@nvwa-app/sdk-uniapp 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.js CHANGED
@@ -1,7 +1,7 @@
1
- "use strict";var U=Object.defineProperty;var he=Object.getOwnPropertyDescriptor;var ce=Object.getOwnPropertyNames;var ue=Object.prototype.hasOwnProperty;var pe=(t,e)=>{for(var r in e)U(t,r,{get:e[r],enumerable:!0})},de=(t,e,r,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of ce(e))!ue.call(t,a)&&a!==r&&U(t,a,{get:()=>e[a],enumerable:!(i=he(e,a))||i.enumerable});return t};var me=t=>de(U({},"__esModule",{value:!0}),t);var Ze={};pe(Ze,{createSocialLoginComponent:()=>Xe,default:()=>$,disableIframeHoverInspector:()=>Je,enableIframeHoverInspector:()=>Be,getIframeSourceLocation:()=>ze,localStorage:()=>j,setupIframeHoverInspector:()=>Ge,setupIframeSourceLocationListener:()=>Ke});module.exports=me(Ze);var w=class D{constructor(e){if(this.headerMap=new Map,e){if(e instanceof D)e.forEach((r,i)=>this.set(i,r));else if(Array.isArray(e))for(let[r,i]of e)this.set(r,String(i));else if(typeof e=="object")for(let r of Object.keys(e))this.set(r,String(e[r]))}}append(e,r){let i=e.toLowerCase(),a=this.headerMap.get(i);this.headerMap.set(i,a?`${a}, ${r}`:r)}set(e,r){this.headerMap.set(e.toLowerCase(),String(r))}get(e){return this.headerMap.get(e.toLowerCase())??null}has(e){return this.headerMap.has(e.toLowerCase())}delete(e){this.headerMap.delete(e.toLowerCase())}forEach(e){for(let[r,i]of this.headerMap.entries())e(i,r,this)}entries(){return this.headerMap.entries()}keys(){return this.headerMap.keys()}values(){return this.headerMap.values()}[Symbol.iterator](){return this.entries()}},ge=class G{constructor(e){if(this.params=new Map,e){if(typeof e=="string")this.parseString(e);else if(e instanceof G)this.params=new Map(e.params);else if(Array.isArray(e))for(let[r,i]of e)this.append(r,i);else if(e&&typeof e=="object")for(let[r,i]of Object.entries(e))this.set(r,i)}}parseString(e){e.startsWith("?")&&(e=e.slice(1));let r=e.split("&");for(let i of r)if(i){let[a,n]=i.split("=");a&&this.append(decodeURIComponent(a),n?decodeURIComponent(n):"")}}append(e,r){let i=this.params.get(e)||[];i.push(r),this.params.set(e,i)}delete(e){this.params.delete(e)}get(e){let r=this.params.get(e);return r?r[0]:null}getAll(e){return this.params.get(e)||[]}has(e){return this.params.has(e)}set(e,r){this.params.set(e,[r])}sort(){let e=Array.from(this.params.entries()).sort(([r],[i])=>r.localeCompare(i));this.params=new Map(e)}toString(){let e=[];for(let[r,i]of this.params.entries())for(let a of i)e.push(`${encodeURIComponent(r)}=${encodeURIComponent(a)}`);return e.join("&")}forEach(e){for(let[r,i]of this.params.entries())for(let a of i)e(a,r,this)}keys(){return this.params.keys()}values(){let e=[];for(let r of this.params.values())e.push(...r);return e[Symbol.iterator]()}entries(){let e=[];for(let[r,i]of this.params.entries())for(let a of i)e.push([r,a]);return e[Symbol.iterator]()}[Symbol.iterator](){return this.entries()}get size(){return this.params.size}},k=class x{constructor(e,r){let i;if(e instanceof x)i=e.href;else if(r){let n=r instanceof x?r.href:r;i=this.resolve(n,e)}else i=e;let a=this.parseUrl(i);this.href=i,this.origin=`${a.protocol}//${a.host}`,this.protocol=a.protocol,this.username=a.username,this.password=a.password,this.host=a.host,this.hostname=a.hostname,this.port=a.port,this.pathname=a.pathname,this.search=a.search,this.searchParams=new ge(a.search),this.hash=a.hash}resolve(e,r){if(r.startsWith("http://")||r.startsWith("https://"))return r;if(r.startsWith("//"))return`${this.parseUrl(e).protocol}${r}`;if(r.startsWith("/")){let n=this.parseUrl(e);return`${n.protocol}//${n.host}${r}`}let i=this.parseUrl(e),a=i.pathname.endsWith("/")?i.pathname:i.pathname+"/";return`${i.protocol}//${i.host}${a}${r}`}parseUrl(e){let r=e.match(/^(([^:\/?#]+):)?(\/\/([^\/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?$/);if(!r)throw new TypeError("Invalid URL");let i=r[2]||"",a=r[4]||"",n=r[5]||"/",h=r[7]?`?${r[7]}`:"",o=r[9]?`#${r[9]}`:"";if(!i&&!a&&!n.startsWith("/")&&!n.includes("/")&&!n.includes("."))throw new TypeError("Invalid URL");let c=a.match(/^([^@]*)@(.+)$/),s="",l="",u=a;if(c){let f=c[1];u=c[2];let y=f.match(/^([^:]*):?(.*)$/);y&&(s=y[1]||"",l=y[2]||"")}let m=u.match(/^([^:]+):?(\d*)$/),p=m?m[1]:u,d=m&&m[2]?m[2]:"";return{protocol:i?`${i}:`:"",username:s,password:l,host:u,hostname:p,port:d,pathname:n,search:h,hash:o}}toString(){let e=this.searchParams.toString(),r=e?`?${e}`:"";return`${this.protocol}//${this.host}${this.pathname}${r}${this.hash}`}toJSON(){return this.toString()}};var B=class{constructor(t,e){this.bodyData=t,this.status=e?.status??200,this.statusText=e?.statusText??"",this.headers=fe(e?.headers),this.ok=this.status>=200&&this.status<300}async text(){return typeof this.bodyData=="string"?this.bodyData:this.bodyData==null?"":typeof this.bodyData=="object"?JSON.stringify(this.bodyData):String(this.bodyData)}async json(){if(typeof this.bodyData=="string")try{return JSON.parse(this.bodyData)}catch{}return this.bodyData}async arrayBuffer(){let t=await this.text();return new TextEncoder().encode(t).buffer}};function fe(t){return t?new w(t):new w}var ye=class{constructor(){this._aborted=!1,this.listeners=new Set,this.onabort=null}get aborted(){return this._aborted}_trigger(){if(!this._aborted){if(this._aborted=!0,typeof this.onabort=="function")try{this.onabort()}catch{}for(let t of Array.from(this.listeners))try{t()}catch{}this.listeners.clear()}}addEventListener(t,e){if(this._aborted){try{e()}catch{}return}this.listeners.add(e)}removeEventListener(t,e){this.listeners.delete(e)}toString(){return"[object AbortSignal]"}},we=class{constructor(){this._signal=new ye}get signal(){return this._signal}abort(){this._signal._trigger()}toString(){return"[object AbortController]"}};function ve(t){if(t!==void 0)return typeof t=="string"||t instanceof FormData||t instanceof Blob||t instanceof File||t instanceof ArrayBuffer||ArrayBuffer.isView(t)||typeof ReadableStream<"u"&&t instanceof ReadableStream?t:typeof t=="object"&&t!==null?JSON.stringify(t):t}var J=class{constructor(t,e=""){this.http=t,this.baseUrl=e.replace(/\/$/,"")}async invoke(t,e){let r=this.baseUrl?`${this.baseUrl}/functions/${t}`:`/functions/${t}`;return await(await this.http.fetchWithAuth(r,{method:e.method||"POST",body:ve(e.body),headers:e.headers})).json()}},g="nvwa_current_jwt",v="nvwa_login_token",b="nvwa_user_profile",be="set-auth-token",Pe=typeof fetch<"u"?(t,e)=>fetch(t,e):()=>{throw new Error("AuthClient requires fetch")},z={google:{id:"google",name:"Google Login",description:"Sign in with Google account."},github:{id:"github",name:"GitHub Login",description:"Sign in with GitHub account."},"wechat-website":{id:"wechat-website",name:"WeChat QR Login",description:"Sign in with WeChat website QR code."},"wechat-miniprogram":{id:"wechat-miniprogram",name:"WeChat Mini Program Login",description:"Sign in with WeChat mini program code."},"alipay-miniprogram":{id:"alipay-miniprogram",name:"Alipay Mini Program Login",description:"Sign in with Alipay mini program code."},"douyin-miniprogram":{id:"douyin-miniprogram",name:"Douyin Mini Program Login",description:"Sign in with Douyin mini program code."}};function M(t){let e=z[t]??{id:t,name:t,description:""},r="unsupported";switch(t){case"google":r="google_openplatform";break;case"github":r="github_openplatform";break;case"wechat-website":r="wechat_website_openplatform";break;case"wechat-miniprogram":r="wechat_miniprogram_code";break;case"alipay-miniprogram":r="alipay_miniprogram_code";break;case"douyin-miniprogram":r="douyin_miniprogram_code";break;default:break}return{id:e.id,type:e.id,name:e.name,description:e.description,loginKind:r}}function H(t,e){let r=t.socialLogin?.providers?.[e];return r?.enabled?r.oauthCredentialSource==="custom"?"custom":"nvwa_default":null}var K=class{constructor(t,e={}){this.baseUrl=t.replace(/\/$/,""),this.authPath=(e.authPath??"/auth").replace(/^\//,""),this.fetchImpl=e.fetchImpl??Pe,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])=>M(r))}async getAvailableProviders(t){return this.getSocialProviders(t)}async startSocialLogin(t,e){let r=M(t),i=e?.applicationCode?.trim()||this.defaultApplicationCode||void 0,a=e?.returnUrl??(typeof globalThis<"u"&&"location"in globalThis?globalThis.location.href:"");switch(r.loginKind){case"google_openplatform":if(!a)throw new Error("startSocialLogin requires returnUrl for google");this.startGoogleOpenPlatformLogin(a,{applicationCode:i,platformCode:e?.platformCode});return;case"github_openplatform":if(!a)throw new Error("startSocialLogin requires returnUrl for github");this.startGithubOpenPlatformLogin(a,{applicationCode:i,platformCode:e?.platformCode});return;case"wechat_website_openplatform":if(!a)throw new Error("startSocialLogin requires returnUrl for wechat-website");this.startWechatWebsiteOpenPlatformLogin(a);return;case"wechat_miniprogram_code":if(!e?.miniProgramCode?.trim()||!i)throw new Error("startSocialLogin requires miniProgramCode and applicationCode for wechat-miniprogram");await this.loginWithWeChatCode(e.miniProgramCode.trim(),i);return;case"alipay_miniprogram_code":if(!e?.miniProgramCode?.trim()||!i)throw new Error("startSocialLogin requires miniProgramCode and applicationCode for alipay-miniprogram");await this.loginWithAlipayCode(e.miniProgramCode.trim(),i);return;case"douyin_miniprogram_code":throw new Error("startSocialLogin does not support douyin-miniprogram yet");default:throw new Error(`startSocialLogin unsupported provider: ${t}`)}}async currentUser(){if(this.storage){let r=await this.storage.get(b);if(r!=null)return r}let{data:t}=await this.getSession(),e=t?.user??null;return e&&this.storage&&await this.storage.set(b,e),e}async getCurrentJwt(){if(this.storage){let e=await this.storage.get(g);if(e!=null)return e;let r=await this.storage.get(v),{data:i}=await this.getToken(r??void 0);return i?.token?(await this.storage.set(g,i.token),i.token):null}let{data:t}=await this.getToken();return t?.token??null}async persistLogin(t,e){if(!this.storage)return;let r=e?.headers.get(be)?.trim()||t.token||t.session?.token;r&&await this.storage.set(v,r),t.user&&await this.storage.set(b,t.user);let i=r??await this.storage.get(v),{data:a}=await this.getToken(i??void 0);a?.token&&await this.storage.set(g,a.token)}async clearLogin(){this.storage&&(await this.storage.remove(v),await this.storage.remove(b),await this.storage.remove(g))}getGoogleOpenPlatformLoginUrl(t,e){let r=new URLSearchParams({return_url:t}),i=e?.applicationCode?.trim()||this.defaultApplicationCode||"";i&&r.set("application_code",i);let a=e?.platformCode?.trim()??"";a&&r.set("platform_code",a);let n=H(this.integrationProviders,"google");return n&&r.set("oauth_credential_source",n),`${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 n=await this.storage.get(g);n!=null&&(e.Authorization=`Bearer ${n}`)}let r=await this.fetchImpl(this.url("google/openplatform/sign-in"),{method:"POST",headers:e,credentials:this.credentials,body:JSON.stringify({exchangeCode:t})}),i=await r.text();if(!r.ok)return{error:{message:i||r.statusText,status:r.status}};let a=i?JSON.parse(i):null;return!a?.token||!a.user?{error:{message:"invalid_google_login_response",status:502}}:(this.storage&&(await this.storage.set(g,a.token),await this.storage.set(v,a.token),await this.storage.set(b,a.user)),{data:a})}catch(e){return{error:{message:e instanceof Error?e.message:String(e),status:0}}}}async getGoogleOpenPlatformIdentity(){try{let t={};if(this.storage){let a=await this.storage.get(g);a!=null&&(t.Authorization=`Bearer ${a}`)}let e=await this.fetchImpl(this.url("google/openplatform/identity"),{method:"GET",credentials:this.credentials,...Object.keys(t).length?{headers:t}:{}}),r=await e.text();if(!e.ok)return{error:{message:r||e.statusText,status:e.status}};let i=r?JSON.parse(r):null;return i?.sub?{data:i}:{error:{message:"invalid_google_identity_response",status:502}}}catch(t){return{error:{message:t instanceof Error?t.message:String(t),status:0}}}}getGithubOpenPlatformLoginUrl(t,e){let r=new URLSearchParams({return_url:t}),i=e?.applicationCode?.trim()||this.defaultApplicationCode||"";i&&r.set("application_code",i);let a=e?.platformCode?.trim()??"";a&&r.set("platform_code",a);let n=H(this.integrationProviders,"github");return n&&r.set("oauth_credential_source",n),`${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 n=await this.storage.get(g);n!=null&&(e.Authorization=`Bearer ${n}`)}let r=await this.fetchImpl(this.url("github/openplatform/sign-in"),{method:"POST",headers:e,credentials:this.credentials,body:JSON.stringify({exchangeCode:t})}),i=await r.text();if(!r.ok)return{error:{message:i||r.statusText,status:r.status}};let a=i?JSON.parse(i):null;return!a?.token||!a.user?{error:{message:"invalid_github_login_response",status:502}}:(this.storage&&(await this.storage.set(g,a.token),await this.storage.set(v,a.token),await this.storage.set(b,a.user)),{data:a})}catch(e){return{error:{message:e instanceof Error?e.message:String(e),status:0}}}}async getGithubOpenPlatformIdentity(){try{let t={};if(this.storage){let a=await this.storage.get(g);a!=null&&(t.Authorization=`Bearer ${a}`)}let e=await this.fetchImpl(this.url("github/openplatform/identity"),{method:"GET",credentials:this.credentials,...Object.keys(t).length?{headers:t}:{}}),r=await e.text();if(!e.ok)return{error:{message:r||e.statusText,status:e.status}};let i=r?JSON.parse(r):null;return i?.sub?{data:i}:{error:{message:"invalid_github_identity_response",status:502}}}catch(t){return{error:{message:t instanceof Error?t.message:String(t),status:0}}}}getWechatWebsiteOpenPlatformLoginUrl(t){let e=new URLSearchParams({return_url:t});return`${this.url("wechat-website/openplatform/login")}?${e.toString()}`}startWechatWebsiteOpenPlatformLogin(t){let e=this.getWechatWebsiteOpenPlatformLoginUrl(t);if(typeof globalThis<"u"&&"location"in globalThis){globalThis.location.href=e;return}throw new Error("startWechatWebsiteOpenPlatformLogin requires a browser environment with location")}async completeWechatWebsiteOpenPlatformLoginFromCurrentUrl(t){let e;if(t!=null&&t!=="")e=t;else if(typeof globalThis<"u"&&"location"in globalThis)e=globalThis.location.href;else return{error:{message:"completeWechatWebsiteOpenPlatformLoginFromCurrentUrl requires url or browser location",status:0}};let r;try{r=new URL(e).searchParams.get("exchange_code")}catch{return{error:{message:"invalid_callback_url",status:400}}}return r?.trim()?await this.loginWithWechatWebsiteExchangeCode(r.trim()):{error:{message:"missing_exchange_code",status:400}}}async loginWithWechatWebsiteExchangeCode(t){try{let e={"Content-Type":"application/json"};if(this.storage){let n=await this.storage.get(g);n!=null&&(e.Authorization=`Bearer ${n}`)}let r=await this.fetchImpl(this.url("wechat-website/openplatform/sign-in"),{method:"POST",headers:e,credentials:this.credentials,body:JSON.stringify({exchangeCode:t})}),i=await r.text();if(!r.ok)return{error:{message:i||r.statusText,status:r.status}};let a=i?JSON.parse(i):null;return!a?.token||!a.user?{error:{message:"invalid_wechat_website_login_response",status:502}}:(this.storage&&(await this.storage.set(g,a.token),await this.storage.set(v,a.token),await this.storage.set(b,a.user)),{data:a})}catch(e){return{error:{message:e instanceof Error?e.message:String(e),status:0}}}}async getWechatWebsiteOpenPlatformIdentity(){try{let t={};if(this.storage){let a=await this.storage.get(g);a!=null&&(t.Authorization=`Bearer ${a}`)}let e=await this.fetchImpl(this.url("wechat-website/openplatform/identity"),{method:"GET",credentials:this.credentials,...Object.keys(t).length?{headers:t}:{}}),r=await e.text();if(!e.ok)return{error:{message:r||e.statusText,status:e.status}};let i=r?JSON.parse(r):null;return i?.sub?{data:i}:{error:{message:"invalid_wechat_website_identity_response",status:502}}}catch(t){return{error:{message:t instanceof Error?t.message:String(t),status:0}}}}url(t){let e=`${`${this.baseUrl.replace(/\/+$/,"")}/${this.authPath.replace(/^\/+/,"")}`}/${t.replace(/^\/+/,"")}`;return typeof console<"u"&&(console.warn("[NvwaAuth] request URL:",e),!e.startsWith("http://")&&!e.startsWith("https://")&&console.warn("[NvwaAuth] URL \u975E\u5B8C\u6574\u5730\u5740\uFF0C\u5C0F\u7A0B\u5E8F\u4F1A\u62A5 invalid url\uFF0C\u8BF7\u68C0\u67E5 Nvwa \u6784\u9020\u65F6\u4F20\u5165\u7684 baseUrl")),e}async getSession(){try{let t={};if(this.storage){let r=await this.storage.get(v)??await this.storage.get(g);r!=null&&(t.Authorization=`Bearer ${r}`)}let e=await this.fetchImpl(this.url("session"),{method:"GET",credentials:this.credentials,...Object.keys(t).length?{headers:t}:{}});return e.ok?{data:await e.json()}:{data:null,error:{message:await e.text()||e.statusText,status:e.status}}}catch(t){return{data:null,error:{message:t instanceof Error?t.message:String(t),status:0}}}}async signInWithEmail(t,e){try{let r=await this.fetchImpl(this.url("sign-in/email"),{method:"POST",headers:{"Content-Type":"application/json"},credentials:this.credentials,body:JSON.stringify({email:t,password:e})}),i=await r.text();if(!r.ok)return{error:{message:i||r.statusText,status:r.status}};let a=i?JSON.parse(i):void 0;return a&&await this.persistLogin({user:a.user,session:a.session},r),{data:a}}catch(r){return{error:{message:r instanceof Error?r.message:String(r),status:0}}}}async signOut(){try{let t={"Content-Type":"application/json"};if(this.storage){let r=await this.storage.get(v)??await this.storage.get(g);r!=null&&(t.Authorization=`Bearer ${r}`)}await this.clearLogin();let e=await this.fetchImpl(this.url("sign-out"),{method:"POST",credentials:this.credentials,headers:t,body:"{}"});return e.ok?{}:{error:{message:await e.text()||e.statusText,status:e.status}}}catch(t){return{error:{message:t instanceof Error?t.message:String(t),status:0}}}}async signUp(t){let e=await this.postJson("sign-up/email",t);return e.data&&await this.persistLogin(e.data,e.response),e}async getToken(t){try{let e={};if(t)e.Authorization=`Bearer ${t}`;else if(this.storage){let n=await this.storage.get(v)??await this.storage.get(g);n!=null&&(e.Authorization=`Bearer ${n}`)}let r=await this.fetchImpl(this.url("token"),{method:"GET",credentials:this.credentials,...Object.keys(e).length?{headers:e}:{}}),i=await r.text();if(!r.ok)return{error:{message:i||r.statusText,status:r.status}};let a=i?JSON.parse(i):void 0;return{data:a?.token!=null?{token:a.token}:void 0}}catch(e){return{error:{message:e instanceof Error?e.message:String(e),status:0}}}}async signInWithUsername(t,e){let r=await this.postJson("sign-in/username",{username:t,password:e});return r.data&&await this.persistLogin(r.data,r.response),r}async signInWithPhoneNumber(t,e,r){let i=await this.postJson("sign-in/phone-number",{phoneNumber:t,password:e,rememberMe:r});return i.data&&await this.persistLogin(i.data,i.response),i}async sendPhoneNumberOtp(t){let e=await this.postJson("phone-number/send-otp",{phoneNumber:t});return e.error?{error:e.error}:{}}async verifyPhoneNumber(t,e){let r=await this.postJson("phone-number/verify",{phoneNumber:t,code:e});return r.data&&await this.persistLogin(r.data,r.response),r}async loginWithWeChatCode(t,e){try{let r={"Content-Type":"application/json"};if(this.storage){let h=await this.storage.get(g);h!=null&&(r.Authorization=`Bearer ${h}`)}let i=await this.fetchImpl(this.url("wechat/openplatform/sign-in"),{method:"POST",headers:r,credentials:this.credentials,body:JSON.stringify({code:t,applicationCode:e})}),a=await i.text();if(!i.ok)return{error:{message:a||i.statusText,status:i.status}};let n=a?JSON.parse(a):null;return!n?.token||!n.user?{error:{message:"invalid_wechat_login_response",status:502}}:(this.storage&&(await this.storage.set(g,n.token),await this.storage.set(v,n.token),await this.storage.set(b,n.user)),{data:n})}catch(r){return{error:{message:r instanceof Error?r.message:String(r),status:0}}}}async loginWithAlipayCode(t,e){try{let r={"Content-Type":"application/json"};if(this.storage){let h=await this.storage.get(g);h!=null&&(r.Authorization=`Bearer ${h}`)}let i=await this.fetchImpl(this.url("alipay/openplatform/sign-in"),{method:"POST",headers:r,credentials:this.credentials,body:JSON.stringify({code:t,applicationCode:e})}),a=await i.text();if(!i.ok)return{error:{message:a||i.statusText,status:i.status}};let n=a?JSON.parse(a):null;return!n?.token||!n.user?{error:{message:"invalid_alipay_login_response",status:502}}:(this.storage&&(await this.storage.set(g,n.token),await this.storage.set(v,n.token),await this.storage.set(b,n.user)),{data:n})}catch(r){return{error:{message:r instanceof Error?r.message:String(r),status:0}}}}async getWeChatOpenPlatformIdentity(t){try{let e={};if(this.storage){let h=await this.storage.get(g);h!=null&&(e.Authorization=`Bearer ${h}`)}let r=t?.trim()?`?applicationCode=${encodeURIComponent(t.trim())}`:"",i=await this.fetchImpl(this.url(`wechat/openplatform/identity${r}`),{method:"GET",credentials:this.credentials,...Object.keys(e).length?{headers:e}:{}}),a=await i.text();if(!i.ok)return{error:{message:a||i.statusText,status:i.status}};let n=a?JSON.parse(a):null;return!n?.openid||!n.appId?{error:{message:"invalid_wechat_identity_response",status:502}}:{data:n}}catch(e){return{error:{message:e instanceof Error?e.message:String(e),status:0}}}}async getAlipayOpenPlatformIdentity(t){try{let e={};if(this.storage){let h=await this.storage.get(g);h!=null&&(e.Authorization=`Bearer ${h}`)}let r=t?.trim()?`?applicationCode=${encodeURIComponent(t.trim())}`:"",i=await this.fetchImpl(this.url(`alipay/openplatform/identity${r}`),{method:"GET",credentials:this.credentials,...Object.keys(e).length?{headers:e}:{}}),a=await i.text();if(!i.ok)return{error:{message:a||i.statusText,status:i.status}};let n=a?JSON.parse(a):null;return!n?.openid||!n.appId?{error:{message:"invalid_alipay_identity_response",status:502}}:{data:n}}catch(e){return{error:{message:e instanceof Error?e.message:String(e),status:0}}}}async getMiniProgramIdentity(t){let e=t?.applicationCode?.trim()||this.defaultApplicationCode||void 0;if(this.platformType==="WechatMiniProgram"){let r=await this.getWeChatOpenPlatformIdentity(e);if(!r.data)throw new Error(r.error?.message||"failed to get wechat open platform identity");return{platformType:this.platformType,appId:r.data.appId,platformUserId:r.data.openid,unionid:r.data.unionid}}else if(this.platformType==="AlipayMiniProgram"){let r=await this.getAlipayOpenPlatformIdentity(e);if(!r.data)throw new Error(r.error?.message||"failed to get wechat open platform identity");return{platformType:this.platformType,appId:r.data.appId,platformUserId:r.data.openid,unionid:r.data.unionid}}return null}async postJson(t,e){try{let r=await this.fetchImpl(this.url(t),{method:"POST",headers:{"Content-Type":"application/json"},credentials:this.credentials,body:JSON.stringify(e)}),i=await r.text();if(!r.ok)return{error:{message:i||r.statusText,status:r.status}};let a=i?JSON.parse(i):void 0;return{data:a?.data??a??void 0,response:r}}catch(r){return{error:{message:r instanceof Error?r.message:String(r),status:0}}}}},V=class{constructor(t,e,r){this.storage=t,this.customFetch=e,this.handleUnauthorized=r}async fetch(t,e){return await this.customFetch(t,e)}async fetchWithAuth(t,e){let r=await this.storage.get(g),i=new w(e?.headers);r&&i.set("Authorization",`Bearer ${r}`);let a=e?.method||"GET";if((a==="POST"||a==="PUT"||a==="PATCH")&&e?.body){let h=i.get("Content-Type");(!h||h.includes("text/plain"))&&i.set("Content-Type","application/json")}let n=await this.customFetch(t,{...e,headers:i});if(n.status===401)throw this.handleUnauthorized(),new Error("\u672A\u767B\u5F55");return n}},Ee="/storage",Se=Ee+"/generateUploadUrl",Y=class{constructor(t,e){this.baseUrl=t,this.http=e}async uploadFile(t){let e=await this.http.fetch(this.baseUrl+Se,{method:"POST",body:{fileName:t.name||t.fileName,fileSize:t.size||t.fileSize,fileType:t.type||t.fileType}}),{url:r}=await e.json();if(!r)throw new Error("\u83B7\u53D6\u4E0A\u4F20URL\u5931\u8D25");let i=await this.http.fetch(r,{method:"PUT",body:t,headers:new w({"Content-Type":t.type||t.fileType||"application/octet-stream"})}),{url:a}=await i.json();return{url:a.split("?")[0]}}},Ce=class extends Error{constructor(t){super(t.message),this.name="PostgrestError",this.details=t.details,this.hint=t.hint,this.code=t.code}},Te=class{constructor(t){var e,r,i;this.shouldThrowOnError=!1,this.method=t.method,this.url=t.url,this.headers=new w(t.headers),this.schema=t.schema,this.body=t.body,this.shouldThrowOnError=(e=t.shouldThrowOnError)!==null&&e!==void 0?e:!1,this.signal=t.signal,this.isMaybeSingle=(r=t.isMaybeSingle)!==null&&r!==void 0?r:!1,this.urlLengthLimit=(i=t.urlLengthLimit)!==null&&i!==void 0?i:8e3,t.fetch?this.fetch=t.fetch:this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(t,e){return this.headers=new w(this.headers),this.headers.set(t,e),this}then(t,e){var r=this;this.schema===void 0||(["GET","HEAD"].includes(this.method)?this.headers.set("Accept-Profile",this.schema):this.headers.set("Content-Profile",this.schema)),this.method!=="GET"&&this.method!=="HEAD"&&this.headers.set("Content-Type","application/json");let i=this.fetch,a=i(this.url.toString(),{method:this.method,headers:this.headers,body:JSON.stringify(this.body),signal:this.signal}).then(async n=>{let h=null,o=null,c=null,s=n.status,l=n.statusText;if(n.ok){var u,m;if(r.method!=="HEAD"){var p;let y=await n.text();y===""||(r.headers.get("Accept")==="text/csv"||r.headers.get("Accept")&&!((p=r.headers.get("Accept"))===null||p===void 0)&&p.includes("application/vnd.pgrst.plan+text")?o=y:o=JSON.parse(y))}let d=(u=r.headers.get("Prefer"))===null||u===void 0?void 0:u.match(/count=(exact|planned|estimated)/),f=(m=n.headers.get("content-range"))===null||m===void 0?void 0:m.split("/");d&&f&&f.length>1&&(c=parseInt(f[1])),r.isMaybeSingle&&Array.isArray(o)&&(o.length>1?(h={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,s=406,l="Not Acceptable"):o.length===1?o=o[0]:o=null)}else{let d=await n.text();try{h=JSON.parse(d),Array.isArray(h)&&n.status===404&&(o=[],h=null,s=200,l="OK")}catch{n.status===404&&d===""?(s=204,l="No Content"):h={message:d}}if(h&&r.shouldThrowOnError)throw new Ce(h)}return{error:h,data:o,count:c,status:s,statusText:l}});return this.shouldThrowOnError||(a=a.catch(n=>{var h;let o="",c="",s="",l=n?.cause;if(l){var u,m,p,d;let T=(u=l?.message)!==null&&u!==void 0?u:"",S=(m=l?.code)!==null&&m!==void 0?m:"";o=`${(p=n?.name)!==null&&p!==void 0?p:"FetchError"}: ${n?.message}`,o+=`
1
+ "use strict";var k=Object.defineProperty;var ce=Object.getOwnPropertyDescriptor;var ue=Object.getOwnPropertyNames;var pe=Object.prototype.hasOwnProperty;var de=(t,e)=>{for(var r in e)k(t,r,{get:e[r],enumerable:!0})},me=(t,e,r,a)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of ue(e))!pe.call(t,i)&&i!==r&&k(t,i,{get:()=>e[i],enumerable:!(a=ce(e,i))||a.enumerable});return t};var ge=t=>me(k({},"__esModule",{value:!0}),t);var rt={};de(rt,{createSocialLoginComponent:()=>tt,default:()=>$,disableIframeHoverInspector:()=>Ve,enableIframeHoverInspector:()=>Ke,getIframeSourceLocation:()=>Ye,localStorage:()=>j,setupIframeHoverInspector:()=>ze,setupIframeSourceLocationListener:()=>Qe});module.exports=ge(rt);var w=class G{constructor(e){if(this.headerMap=new Map,e){if(e instanceof G)e.forEach((r,a)=>this.set(a,r));else if(Array.isArray(e))for(let[r,a]of e)this.set(r,String(a));else if(typeof e=="object")for(let r of Object.keys(e))this.set(r,String(e[r]))}}append(e,r){let a=e.toLowerCase(),i=this.headerMap.get(a);this.headerMap.set(a,i?`${i}, ${r}`:r)}set(e,r){this.headerMap.set(e.toLowerCase(),String(r))}get(e){return this.headerMap.get(e.toLowerCase())??null}has(e){return this.headerMap.has(e.toLowerCase())}delete(e){this.headerMap.delete(e.toLowerCase())}forEach(e){for(let[r,a]of this.headerMap.entries())e(a,r,this)}entries(){return this.headerMap.entries()}keys(){return this.headerMap.keys()}values(){return this.headerMap.values()}[Symbol.iterator](){return this.entries()}},fe=class B{constructor(e){if(this.params=new Map,e){if(typeof e=="string")this.parseString(e);else if(e instanceof B)this.params=new Map(e.params);else if(Array.isArray(e))for(let[r,a]of e)this.append(r,a);else if(e&&typeof e=="object")for(let[r,a]of Object.entries(e))this.set(r,a)}}parseString(e){e.startsWith("?")&&(e=e.slice(1));let r=e.split("&");for(let a of r)if(a){let[i,n]=a.split("=");i&&this.append(decodeURIComponent(i),n?decodeURIComponent(n):"")}}append(e,r){let a=this.params.get(e)||[];a.push(r),this.params.set(e,a)}delete(e){this.params.delete(e)}get(e){let r=this.params.get(e);return r?r[0]:null}getAll(e){return this.params.get(e)||[]}has(e){return this.params.has(e)}set(e,r){this.params.set(e,[r])}sort(){let e=Array.from(this.params.entries()).sort(([r],[a])=>r.localeCompare(a));this.params=new Map(e)}toString(){let e=[];for(let[r,a]of this.params.entries())for(let i of a)e.push(`${encodeURIComponent(r)}=${encodeURIComponent(i)}`);return e.join("&")}forEach(e){for(let[r,a]of this.params.entries())for(let i of a)e(i,r,this)}keys(){return this.params.keys()}values(){let e=[];for(let r of this.params.values())e.push(...r);return e[Symbol.iterator]()}entries(){let e=[];for(let[r,a]of this.params.entries())for(let i of a)e.push([r,i]);return e[Symbol.iterator]()}[Symbol.iterator](){return this.entries()}get size(){return this.params.size}},U=class x{constructor(e,r){let a;if(e instanceof x)a=e.href;else if(r){let n=r instanceof x?r.href:r;a=this.resolve(n,e)}else a=e;let i=this.parseUrl(a);this.href=a,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 fe(i.search),this.hash=i.hash}resolve(e,r){if(r.startsWith("http://")||r.startsWith("https://"))return r;if(r.startsWith("//"))return`${this.parseUrl(e).protocol}${r}`;if(r.startsWith("/")){let n=this.parseUrl(e);return`${n.protocol}//${n.host}${r}`}let a=this.parseUrl(e),i=a.pathname.endsWith("/")?a.pathname:a.pathname+"/";return`${a.protocol}//${a.host}${i}${r}`}parseUrl(e){let r=e.match(/^(([^:\/?#]+):)?(\/\/([^\/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?$/);if(!r)throw new TypeError("Invalid URL");let a=r[2]||"",i=r[4]||"",n=r[5]||"/",h=r[7]?`?${r[7]}`:"",o=r[9]?`#${r[9]}`:"";if(!a&&!i&&!n.startsWith("/")&&!n.includes("/")&&!n.includes("."))throw new TypeError("Invalid URL");let c=i.match(/^([^@]*)@(.+)$/),s="",l="",u=i;if(c){let f=c[1];u=c[2];let y=f.match(/^([^:]*):?(.*)$/);y&&(s=y[1]||"",l=y[2]||"")}let m=u.match(/^([^:]+):?(\d*)$/),p=m?m[1]:u,d=m&&m[2]?m[2]:"";return{protocol:a?`${a}:`:"",username:s,password:l,host:u,hostname:p,port:d,pathname:n,search:h,hash:o}}toString(){let e=this.searchParams.toString(),r=e?`?${e}`:"";return`${this.protocol}//${this.host}${this.pathname}${r}${this.hash}`}toJSON(){return this.toString()}};var J=class{constructor(t,e){this.bodyData=t,this.status=e?.status??200,this.statusText=e?.statusText??"",this.headers=ye(e?.headers),this.ok=this.status>=200&&this.status<300}async text(){return typeof this.bodyData=="string"?this.bodyData:this.bodyData==null?"":typeof this.bodyData=="object"?JSON.stringify(this.bodyData):String(this.bodyData)}async json(){if(typeof this.bodyData=="string")try{return JSON.parse(this.bodyData)}catch{}return this.bodyData}async arrayBuffer(){let t=await this.text();return new TextEncoder().encode(t).buffer}};function ye(t){return t?new w(t):new w}var we=class{constructor(){this._aborted=!1,this.listeners=new Set,this.onabort=null}get aborted(){return this._aborted}_trigger(){if(!this._aborted){if(this._aborted=!0,typeof this.onabort=="function")try{this.onabort()}catch{}for(let t of Array.from(this.listeners))try{t()}catch{}this.listeners.clear()}}addEventListener(t,e){if(this._aborted){try{e()}catch{}return}this.listeners.add(e)}removeEventListener(t,e){this.listeners.delete(e)}toString(){return"[object AbortSignal]"}},ve=class{constructor(){this._signal=new we}get signal(){return this._signal}abort(){this._signal._trigger()}toString(){return"[object AbortController]"}},M=class extends Error{constructor(t,e,r){super(t),this.name="NvwaFunctionInvokeError",this.status=e,this.bodyText=r}};function be(t){if(!t||typeof t!="object")return null;let e=t;return typeof e.error=="string"&&e.error.length>0?e.error:typeof e.message=="string"&&e.message.length>0?e.message:null}function Pe(t,e){let r=e.trim();if(!r)return`Request failed with status ${t}`;try{let a=JSON.parse(r);return be(a)??r}catch{return r}}function Ee(t){if(t!==void 0)return typeof t=="string"||t instanceof FormData||t instanceof Blob||t instanceof File||t instanceof ArrayBuffer||ArrayBuffer.isView(t)||typeof ReadableStream<"u"&&t instanceof ReadableStream?t:typeof t=="object"&&t!==null?JSON.stringify(t):t}var z=class{constructor(t,e=""){this.http=t,this.baseUrl=e.replace(/\/$/,"")}async invoke(t,e){let r=this.baseUrl?`${this.baseUrl}/functions/${t}`:`/functions/${t}`,a=await this.http.fetchWithAuth(r,{method:e.method||"POST",body:Ee(e.body),headers:e.headers});if(!a.ok){let i=await a.text();throw new M(Pe(a.status,i),a.status,i)}try{return await a.json()}catch(i){let n=i instanceof Error?i.message:String(i);throw new M(`Invalid JSON in function response: ${n}`,a.status)}}},g="nvwa_current_jwt",v="nvwa_login_token",b="nvwa_user_profile",Se="set-auth-token",Ce=typeof fetch<"u"?(t,e)=>fetch(t,e):()=>{throw new Error("AuthClient requires fetch")},K={google:{id:"google",name:"Google Login",description:"Sign in with Google account."},github:{id:"github",name:"GitHub Login",description:"Sign in with GitHub account."},"wechat-website":{id:"wechat-website",name:"WeChat QR Login",description:"Sign in with WeChat website QR code."},"wechat-miniprogram":{id:"wechat-miniprogram",name:"WeChat Mini Program Login",description:"Sign in with WeChat mini program code."},"alipay-miniprogram":{id:"alipay-miniprogram",name:"Alipay Mini Program Login",description:"Sign in with Alipay mini program code."},"douyin-miniprogram":{id:"douyin-miniprogram",name:"Douyin Mini Program Login",description:"Sign in with Douyin mini program code."}};function H(t){let e=K[t]??{id:t,name:t,description:""},r="unsupported";switch(t){case"google":r="google_openplatform";break;case"github":r="github_openplatform";break;case"wechat-website":r="wechat_website_openplatform";break;case"wechat-miniprogram":r="wechat_miniprogram_code";break;case"alipay-miniprogram":r="alipay_miniprogram_code";break;case"douyin-miniprogram":r="douyin_miniprogram_code";break;default:break}return{id:e.id,type:e.id,name:e.name,description:e.description,loginKind:r}}function q(t,e){let r=t.socialLogin?.providers?.[e];return r?.enabled?r.oauthCredentialSource==="custom"?"custom":"nvwa_default":null}var V=class{constructor(t,e={}){this.baseUrl=t.replace(/\/$/,""),this.authPath=(e.authPath??"/auth").replace(/^\//,""),this.fetchImpl=e.fetchImpl??Ce,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 a=K[r]??{id:r,name:r,description:""};return{...a,type:a.id}})}async getSocialProviderDescriptors(t){let e=this.integrationProviders.socialLogin?.providers??{};return Object.entries(e).filter(([,r])=>!!r?.enabled).map(([r])=>H(r))}async getAvailableProviders(t){return this.getSocialProviders(t)}async startSocialLogin(t,e){let r=H(t),a=e?.applicationCode?.trim()||this.defaultApplicationCode||void 0,i=e?.returnUrl??(typeof globalThis<"u"&&"location"in globalThis?globalThis.location.href:"");switch(r.loginKind){case"google_openplatform":if(!i)throw new Error("startSocialLogin requires returnUrl for google");this.startGoogleOpenPlatformLogin(i,{applicationCode:a,platformCode:e?.platformCode});return;case"github_openplatform":if(!i)throw new Error("startSocialLogin requires returnUrl for github");this.startGithubOpenPlatformLogin(i,{applicationCode:a,platformCode:e?.platformCode});return;case"wechat_website_openplatform":if(!i)throw new Error("startSocialLogin requires returnUrl for wechat-website");this.startWechatWebsiteOpenPlatformLogin(i);return;case"wechat_miniprogram_code":if(!e?.miniProgramCode?.trim()||!a)throw new Error("startSocialLogin requires miniProgramCode and applicationCode for wechat-miniprogram");await this.loginWithWeChatCode(e.miniProgramCode.trim(),a);return;case"alipay_miniprogram_code":if(!e?.miniProgramCode?.trim()||!a)throw new Error("startSocialLogin requires miniProgramCode and applicationCode for alipay-miniprogram");await this.loginWithAlipayCode(e.miniProgramCode.trim(),a);return;case"douyin_miniprogram_code":throw new Error("startSocialLogin does not support douyin-miniprogram yet");default:throw new Error(`startSocialLogin unsupported provider: ${t}`)}}async currentUser(){if(this.storage){let r=await this.storage.get(b);if(r!=null)return r}let{data:t}=await this.getSession(),e=t?.user??null;return e&&this.storage&&await this.storage.set(b,e),e}async getCurrentJwt(){if(this.storage){let e=await this.storage.get(g);if(e!=null)return e;let r=await this.storage.get(v),{data:a}=await this.getToken(r??void 0);return a?.token?(await this.storage.set(g,a.token),a.token):null}let{data:t}=await this.getToken();return t?.token??null}async persistLogin(t,e){if(!this.storage)return;let r=e?.headers.get(Se)?.trim()||t.token||t.session?.token;r&&await this.storage.set(v,r),t.user&&await this.storage.set(b,t.user);let a=r??await this.storage.get(v),{data:i}=await this.getToken(a??void 0);i?.token&&await this.storage.set(g,i.token)}async clearLogin(){this.storage&&(await this.storage.remove(v),await this.storage.remove(b),await this.storage.remove(g))}getGoogleOpenPlatformLoginUrl(t,e){let r=new URLSearchParams({return_url:t}),a=e?.applicationCode?.trim()||this.defaultApplicationCode||"";a&&r.set("application_code",a);let i=e?.platformCode?.trim()??"";i&&r.set("platform_code",i);let n=q(this.integrationProviders,"google");return n&&r.set("oauth_credential_source",n),`${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 n=await this.storage.get(g);n!=null&&(e.Authorization=`Bearer ${n}`)}let r=await this.fetchImpl(this.url("google/openplatform/sign-in"),{method:"POST",headers:e,credentials:this.credentials,body:JSON.stringify({exchangeCode:t})}),a=await r.text();if(!r.ok)return{error:{message:a||r.statusText,status:r.status}};let i=a?JSON.parse(a):null;return!i?.token||!i.user?{error:{message:"invalid_google_login_response",status:502}}:(this.storage&&(await this.storage.set(g,i.token),await this.storage.set(v,i.token),await this.storage.set(b,i.user)),{data:i})}catch(e){return{error:{message:e instanceof Error?e.message:String(e),status:0}}}}async getGoogleOpenPlatformIdentity(){try{let t={};if(this.storage){let i=await this.storage.get(g);i!=null&&(t.Authorization=`Bearer ${i}`)}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 a=r?JSON.parse(r):null;return a?.sub?{data:a}:{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}),a=e?.applicationCode?.trim()||this.defaultApplicationCode||"";a&&r.set("application_code",a);let i=e?.platformCode?.trim()??"";i&&r.set("platform_code",i);let n=q(this.integrationProviders,"github");return n&&r.set("oauth_credential_source",n),`${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 n=await this.storage.get(g);n!=null&&(e.Authorization=`Bearer ${n}`)}let r=await this.fetchImpl(this.url("github/openplatform/sign-in"),{method:"POST",headers:e,credentials:this.credentials,body:JSON.stringify({exchangeCode:t})}),a=await r.text();if(!r.ok)return{error:{message:a||r.statusText,status:r.status}};let i=a?JSON.parse(a):null;return!i?.token||!i.user?{error:{message:"invalid_github_login_response",status:502}}:(this.storage&&(await this.storage.set(g,i.token),await this.storage.set(v,i.token),await this.storage.set(b,i.user)),{data:i})}catch(e){return{error:{message:e instanceof Error?e.message:String(e),status:0}}}}async getGithubOpenPlatformIdentity(){try{let t={};if(this.storage){let i=await this.storage.get(g);i!=null&&(t.Authorization=`Bearer ${i}`)}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 a=r?JSON.parse(r):null;return a?.sub?{data:a}:{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 n=await this.storage.get(g);n!=null&&(e.Authorization=`Bearer ${n}`)}let r=await this.fetchImpl(this.url("wechat-website/openplatform/sign-in"),{method:"POST",headers:e,credentials:this.credentials,body:JSON.stringify({exchangeCode:t})}),a=await r.text();if(!r.ok)return{error:{message:a||r.statusText,status:r.status}};let i=a?JSON.parse(a):null;return!i?.token||!i.user?{error:{message:"invalid_wechat_website_login_response",status:502}}:(this.storage&&(await this.storage.set(g,i.token),await this.storage.set(v,i.token),await this.storage.set(b,i.user)),{data:i})}catch(e){return{error:{message:e instanceof Error?e.message:String(e),status:0}}}}async getWechatWebsiteOpenPlatformIdentity(){try{let t={};if(this.storage){let i=await this.storage.get(g);i!=null&&(t.Authorization=`Bearer ${i}`)}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 a=r?JSON.parse(r):null;return a?.sub?{data:a}:{error:{message:"invalid_wechat_website_identity_response",status:502}}}catch(t){return{error:{message:t instanceof Error?t.message:String(t),status:0}}}}url(t){let e=`${`${this.baseUrl.replace(/\/+$/,"")}/${this.authPath.replace(/^\/+/,"")}`}/${t.replace(/^\/+/,"")}`;return typeof console<"u"&&(console.warn("[NvwaAuth] request URL:",e),!e.startsWith("http://")&&!e.startsWith("https://")&&console.warn("[NvwaAuth] URL \u975E\u5B8C\u6574\u5730\u5740\uFF0C\u5C0F\u7A0B\u5E8F\u4F1A\u62A5 invalid url\uFF0C\u8BF7\u68C0\u67E5 Nvwa \u6784\u9020\u65F6\u4F20\u5165\u7684 baseUrl")),e}async getSession(){try{let t={};if(this.storage){let r=await this.storage.get(v)??await this.storage.get(g);r!=null&&(t.Authorization=`Bearer ${r}`)}let e=await this.fetchImpl(this.url("session"),{method:"GET",credentials:this.credentials,...Object.keys(t).length?{headers:t}:{}});return e.ok?{data:await e.json()}:{data:null,error:{message:await e.text()||e.statusText,status:e.status}}}catch(t){return{data:null,error:{message:t instanceof Error?t.message:String(t),status:0}}}}async signInWithEmail(t,e){try{let r=await this.fetchImpl(this.url("sign-in/email"),{method:"POST",headers:{"Content-Type":"application/json"},credentials:this.credentials,body:JSON.stringify({email:t,password:e})}),a=await r.text();if(!r.ok)return{error:{message:a||r.statusText,status:r.status}};let i=a?JSON.parse(a):void 0;return i&&await this.persistLogin({user:i.user,session:i.session},r),{data:i}}catch(r){return{error:{message:r instanceof Error?r.message:String(r),status:0}}}}async signOut(){try{let t={"Content-Type":"application/json"};if(this.storage){let r=await this.storage.get(v)??await this.storage.get(g);r!=null&&(t.Authorization=`Bearer ${r}`)}await this.clearLogin();let e=await this.fetchImpl(this.url("sign-out"),{method:"POST",credentials:this.credentials,headers:t,body:"{}"});return e.ok?{}:{error:{message:await e.text()||e.statusText,status:e.status}}}catch(t){return{error:{message:t instanceof Error?t.message:String(t),status:0}}}}async signUp(t){let e=await this.postJson("sign-up/email",t);return e.data&&await this.persistLogin(e.data,e.response),e}async getToken(t){try{let e={};if(t)e.Authorization=`Bearer ${t}`;else if(this.storage){let n=await this.storage.get(v)??await this.storage.get(g);n!=null&&(e.Authorization=`Bearer ${n}`)}let r=await this.fetchImpl(this.url("token"),{method:"GET",credentials:this.credentials,...Object.keys(e).length?{headers:e}:{}}),a=await r.text();if(!r.ok)return{error:{message:a||r.statusText,status:r.status}};let i=a?JSON.parse(a):void 0;return{data:i?.token!=null?{token:i.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 a=await this.postJson("sign-in/phone-number",{phoneNumber:t,password:e,rememberMe:r});return a.data&&await this.persistLogin(a.data,a.response),a}async sendPhoneNumberOtp(t){let e=await this.postJson("phone-number/send-otp",{phoneNumber:t});return e.error?{error:e.error}:{}}async verifyPhoneNumber(t,e){let r=await this.postJson("phone-number/verify",{phoneNumber:t,code:e});return r.data&&await this.persistLogin(r.data,r.response),r}async loginWithWeChatCode(t,e){try{let r={"Content-Type":"application/json"};if(this.storage){let h=await this.storage.get(g);h!=null&&(r.Authorization=`Bearer ${h}`)}let a=await this.fetchImpl(this.url("wechat/openplatform/sign-in"),{method:"POST",headers:r,credentials:this.credentials,body:JSON.stringify({code:t,applicationCode:e})}),i=await a.text();if(!a.ok)return{error:{message:i||a.statusText,status:a.status}};let n=i?JSON.parse(i):null;return!n?.token||!n.user?{error:{message:"invalid_wechat_login_response",status:502}}:(this.storage&&(await this.storage.set(g,n.token),await this.storage.set(v,n.token),await this.storage.set(b,n.user)),{data:n})}catch(r){return{error:{message:r instanceof Error?r.message:String(r),status:0}}}}async loginWithAlipayCode(t,e){try{let r={"Content-Type":"application/json"};if(this.storage){let h=await this.storage.get(g);h!=null&&(r.Authorization=`Bearer ${h}`)}let a=await this.fetchImpl(this.url("alipay/openplatform/sign-in"),{method:"POST",headers:r,credentials:this.credentials,body:JSON.stringify({code:t,applicationCode:e})}),i=await a.text();if(!a.ok)return{error:{message:i||a.statusText,status:a.status}};let n=i?JSON.parse(i):null;return!n?.token||!n.user?{error:{message:"invalid_alipay_login_response",status:502}}:(this.storage&&(await this.storage.set(g,n.token),await this.storage.set(v,n.token),await this.storage.set(b,n.user)),{data:n})}catch(r){return{error:{message:r instanceof Error?r.message:String(r),status:0}}}}async getWeChatOpenPlatformIdentity(t){try{let e={};if(this.storage){let h=await this.storage.get(g);h!=null&&(e.Authorization=`Bearer ${h}`)}let r=t?.trim()?`?applicationCode=${encodeURIComponent(t.trim())}`:"",a=await this.fetchImpl(this.url(`wechat/openplatform/identity${r}`),{method:"GET",credentials:this.credentials,...Object.keys(e).length?{headers:e}:{}}),i=await a.text();if(!a.ok)return{error:{message:i||a.statusText,status:a.status}};let n=i?JSON.parse(i):null;return!n?.openid||!n.appId?{error:{message:"invalid_wechat_identity_response",status:502}}:{data:n}}catch(e){return{error:{message:e instanceof Error?e.message:String(e),status:0}}}}async getAlipayOpenPlatformIdentity(t){try{let e={};if(this.storage){let h=await this.storage.get(g);h!=null&&(e.Authorization=`Bearer ${h}`)}let r=t?.trim()?`?applicationCode=${encodeURIComponent(t.trim())}`:"",a=await this.fetchImpl(this.url(`alipay/openplatform/identity${r}`),{method:"GET",credentials:this.credentials,...Object.keys(e).length?{headers:e}:{}}),i=await a.text();if(!a.ok)return{error:{message:i||a.statusText,status:a.status}};let n=i?JSON.parse(i):null;return!n?.openid||!n.appId?{error:{message:"invalid_alipay_identity_response",status:502}}:{data:n}}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)}),a=await r.text();if(!r.ok)return{error:{message:a||r.statusText,status:r.status}};let i=a?JSON.parse(a):void 0;return{data:i?.data??i??void 0,response:r}}catch(r){return{error:{message:r instanceof Error?r.message:String(r),status:0}}}}},Y=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),a=new w(e?.headers);r&&a.set("Authorization",`Bearer ${r}`);let i=e?.method||"GET";if((i==="POST"||i==="PUT"||i==="PATCH")&&e?.body){let h=a.get("Content-Type");(!h||h.includes("text/plain"))&&a.set("Content-Type","application/json")}let n=await this.customFetch(t,{...e,headers:a});if(n.status===401)throw this.handleUnauthorized(),new Error("\u672A\u767B\u5F55");return n}},Te="/storage",Oe=Te+"/generateUploadUrl",Q=class{constructor(t,e){this.baseUrl=t,this.http=e}async uploadFile(t){let e=await this.http.fetch(this.baseUrl+Oe,{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 a=await this.http.fetch(r,{method:"PUT",body:t,headers:new w({"Content-Type":t.type||t.fileType||"application/octet-stream"})}),{url:i}=await a.json();return{url:i.split("?")[0]}}},Le=class extends Error{constructor(t){super(t.message),this.name="PostgrestError",this.details=t.details,this.hint=t.hint,this.code=t.code}},_e=class{constructor(t){var e,r,a;this.shouldThrowOnError=!1,this.method=t.method,this.url=t.url,this.headers=new w(t.headers),this.schema=t.schema,this.body=t.body,this.shouldThrowOnError=(e=t.shouldThrowOnError)!==null&&e!==void 0?e:!1,this.signal=t.signal,this.isMaybeSingle=(r=t.isMaybeSingle)!==null&&r!==void 0?r:!1,this.urlLengthLimit=(a=t.urlLengthLimit)!==null&&a!==void 0?a:8e3,t.fetch?this.fetch=t.fetch:this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(t,e){return this.headers=new w(this.headers),this.headers.set(t,e),this}then(t,e){var r=this;this.schema===void 0||(["GET","HEAD"].includes(this.method)?this.headers.set("Accept-Profile",this.schema):this.headers.set("Content-Profile",this.schema)),this.method!=="GET"&&this.method!=="HEAD"&&this.headers.set("Content-Type","application/json");let a=this.fetch,i=a(this.url.toString(),{method:this.method,headers:this.headers,body:JSON.stringify(this.body),signal:this.signal}).then(async n=>{let h=null,o=null,c=null,s=n.status,l=n.statusText;if(n.ok){var u,m;if(r.method!=="HEAD"){var p;let y=await n.text();y===""||(r.headers.get("Accept")==="text/csv"||r.headers.get("Accept")&&!((p=r.headers.get("Accept"))===null||p===void 0)&&p.includes("application/vnd.pgrst.plan+text")?o=y:o=JSON.parse(y))}let d=(u=r.headers.get("Prefer"))===null||u===void 0?void 0:u.match(/count=(exact|planned|estimated)/),f=(m=n.headers.get("content-range"))===null||m===void 0?void 0:m.split("/");d&&f&&f.length>1&&(c=parseInt(f[1])),r.isMaybeSingle&&Array.isArray(o)&&(o.length>1?(h={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,s=406,l="Not Acceptable"):o.length===1?o=o[0]:o=null)}else{let d=await n.text();try{h=JSON.parse(d),Array.isArray(h)&&n.status===404&&(o=[],h=null,s=200,l="OK")}catch{n.status===404&&d===""?(s=204,l="No Content"):h={message:d}}if(h&&r.shouldThrowOnError)throw new Le(h)}return{error:h,data:o,count:c,status:s,statusText:l}});return this.shouldThrowOnError||(i=i.catch(n=>{var h;let o="",c="",s="",l=n?.cause;if(l){var u,m,p,d;let T=(u=l?.message)!==null&&u!==void 0?u:"",S=(m=l?.code)!==null&&m!==void 0?m:"";o=`${(p=n?.name)!==null&&p!==void 0?p:"FetchError"}: ${n?.message}`,o+=`
2
2
 
3
3
  Caused by: ${(d=l?.name)!==null&&d!==void 0?d:"Error"}: ${T}`,S&&(o+=` (${S})`),l?.stack&&(o+=`
4
- ${l.stack}`)}else{var f;o=(f=n?.stack)!==null&&f!==void 0?f:""}let y=this.url.toString().length;return n?.name==="AbortError"||n?.code==="ABORT_ERR"?(s="",c="Request was aborted (timeout or manual cancellation)",y>this.urlLengthLimit&&(c+=`. Note: Your request URL is ${y} characters, which may exceed server limits. If selecting many fields, consider using views. If filtering with large arrays (e.g., .in('id', [many IDs])), consider using an RPC function to pass values server-side.`)):(l?.name==="HeadersOverflowError"||l?.code==="UND_ERR_HEADERS_OVERFLOW")&&(s="",c="HTTP headers exceeded server limits (typically 16KB)",y>this.urlLengthLimit&&(c+=`. Your request URL is ${y} characters. If selecting many fields, consider using views. If filtering with large arrays (e.g., .in('id', [200+ IDs])), consider using an RPC function instead.`)),{error:{message:`${(h=n?.name)!==null&&h!==void 0?h:"FetchError"}: ${n?.message}`,details:o,hint:c,code:s},data:null,count:null,status:0,statusText:""}})),a.then(t,e)}returns(){return this}overrideTypes(){return this}},Le=class extends Te{select(t){let e=!1,r=(t??"*").split("").map(i=>/\s/.test(i)&&!e?"":(i==='"'&&(e=!e),i)).join("");return this.url.searchParams.set("select",r),this.headers.append("Prefer","return=representation"),this}order(t,{ascending:e=!0,nullsFirst:r,foreignTable:i,referencedTable:a=i}={}){let n=a?`${a}.order`:"order",h=this.url.searchParams.get(n);return this.url.searchParams.set(n,`${h?`${h},`:""}${t}.${e?"asc":"desc"}${r===void 0?"":r?".nullsfirst":".nullslast"}`),this}limit(t,{foreignTable:e,referencedTable:r=e}={}){let i=typeof r>"u"?"limit":`${r}.limit`;return this.url.searchParams.set(i,`${t}`),this}range(t,e,{foreignTable:r,referencedTable:i=r}={}){let a=typeof i>"u"?"offset":`${i}.offset`,n=typeof i>"u"?"limit":`${i}.limit`;return this.url.searchParams.set(a,`${t}`),this.url.searchParams.set(n,`${e-t+1}`),this}abortSignal(t){return this.signal=t,this}single(){return this.headers.set("Accept","application/vnd.pgrst.object+json"),this}maybeSingle(){return this.isMaybeSingle=!0,this}csv(){return this.headers.set("Accept","text/csv"),this}geojson(){return this.headers.set("Accept","application/geo+json"),this}explain({analyze:t=!1,verbose:e=!1,settings:r=!1,buffers:i=!1,wal:a=!1,format:n="text"}={}){var h;let o=[t?"analyze":null,e?"verbose":null,r?"settings":null,i?"buffers":null,a?"wal":null].filter(Boolean).join("|"),c=(h=this.headers.get("Accept"))!==null&&h!==void 0?h:"application/json";return this.headers.set("Accept",`application/vnd.pgrst.plan+${n}; for="${c}"; options=${o};`),n==="json"?this:this}rollback(){return this.headers.append("Prefer","tx=rollback"),this}returns(){return this}maxAffected(t){return this.headers.append("Prefer","handling=strict"),this.headers.append("Prefer",`max-affected=${t}`),this}},q=new RegExp("[,()]"),P=class extends Le{eq(t,e){return this.url.searchParams.append(t,`eq.${e}`),this}neq(t,e){return this.url.searchParams.append(t,`neq.${e}`),this}gt(t,e){return this.url.searchParams.append(t,`gt.${e}`),this}gte(t,e){return this.url.searchParams.append(t,`gte.${e}`),this}lt(t,e){return this.url.searchParams.append(t,`lt.${e}`),this}lte(t,e){return this.url.searchParams.append(t,`lte.${e}`),this}like(t,e){return this.url.searchParams.append(t,`like.${e}`),this}likeAllOf(t,e){return this.url.searchParams.append(t,`like(all).{${e.join(",")}}`),this}likeAnyOf(t,e){return this.url.searchParams.append(t,`like(any).{${e.join(",")}}`),this}ilike(t,e){return this.url.searchParams.append(t,`ilike.${e}`),this}ilikeAllOf(t,e){return this.url.searchParams.append(t,`ilike(all).{${e.join(",")}}`),this}ilikeAnyOf(t,e){return this.url.searchParams.append(t,`ilike(any).{${e.join(",")}}`),this}regexMatch(t,e){return this.url.searchParams.append(t,`match.${e}`),this}regexIMatch(t,e){return this.url.searchParams.append(t,`imatch.${e}`),this}is(t,e){return this.url.searchParams.append(t,`is.${e}`),this}isDistinct(t,e){return this.url.searchParams.append(t,`isdistinct.${e}`),this}in(t,e){let r=Array.from(new Set(e)).map(i=>typeof i=="string"&&q.test(i)?`"${i}"`:`${i}`).join(",");return this.url.searchParams.append(t,`in.(${r})`),this}notIn(t,e){let r=Array.from(new Set(e)).map(i=>typeof i=="string"&&q.test(i)?`"${i}"`:`${i}`).join(",");return this.url.searchParams.append(t,`not.in.(${r})`),this}contains(t,e){return typeof e=="string"?this.url.searchParams.append(t,`cs.${e}`):Array.isArray(e)?this.url.searchParams.append(t,`cs.{${e.join(",")}}`):this.url.searchParams.append(t,`cs.${JSON.stringify(e)}`),this}containedBy(t,e){return typeof e=="string"?this.url.searchParams.append(t,`cd.${e}`):Array.isArray(e)?this.url.searchParams.append(t,`cd.{${e.join(",")}}`):this.url.searchParams.append(t,`cd.${JSON.stringify(e)}`),this}rangeGt(t,e){return this.url.searchParams.append(t,`sr.${e}`),this}rangeGte(t,e){return this.url.searchParams.append(t,`nxl.${e}`),this}rangeLt(t,e){return this.url.searchParams.append(t,`sl.${e}`),this}rangeLte(t,e){return this.url.searchParams.append(t,`nxr.${e}`),this}rangeAdjacent(t,e){return this.url.searchParams.append(t,`adj.${e}`),this}overlaps(t,e){return typeof e=="string"?this.url.searchParams.append(t,`ov.${e}`):this.url.searchParams.append(t,`ov.{${e.join(",")}}`),this}textSearch(t,e,{config:r,type:i}={}){let a="";i==="plain"?a="pl":i==="phrase"?a="ph":i==="websearch"&&(a="w");let n=r===void 0?"":`(${r})`;return this.url.searchParams.append(t,`${a}fts${n}.${e}`),this}match(t){return Object.entries(t).filter(([e,r])=>r!==void 0).forEach(([e,r])=>{this.url.searchParams.append(e,`eq.${r}`)}),this}not(t,e,r){return this.url.searchParams.append(t,`not.${e}.${r}`),this}or(t,{foreignTable:e,referencedTable:r=e}={}){let i=r?`${r}.or`:"or";return this.url.searchParams.append(i,`(${t})`),this}filter(t,e,r){return this.url.searchParams.append(t,`${e}.${r}`),this}},Oe=class{constructor(t,{headers:e={},schema:r,fetch:i,urlLengthLimit:a=8e3}){this.url=t,this.headers=new w(e),this.schema=r,this.fetch=i,this.urlLengthLimit=a}cloneRequestState(){return{url:new k(this.url.toString()),headers:new w(this.headers)}}select(t,e){let{head:r=!1,count:i}=e??{},a=r?"HEAD":"GET",n=!1,h=(t??"*").split("").map(s=>/\s/.test(s)&&!n?"":(s==='"'&&(n=!n),s)).join(""),{url:o,headers:c}=this.cloneRequestState();return o.searchParams.set("select",h),i&&c.append("Prefer",`count=${i}`),new P({method:a,url:o,headers:c,schema:this.schema,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}insert(t,{count:e,defaultToNull:r=!0}={}){var i;let a="POST",{url:n,headers:h}=this.cloneRequestState();if(e&&h.append("Prefer",`count=${e}`),r||h.append("Prefer","missing=default"),Array.isArray(t)){let o=t.reduce((c,s)=>c.concat(Object.keys(s)),[]);if(o.length>0){let c=[...new Set(o)].map(s=>`"${s}"`);n.searchParams.set("columns",c.join(","))}}return new P({method:a,url:n,headers:h,schema:this.schema,body:t,fetch:(i=this.fetch)!==null&&i!==void 0?i:fetch,urlLengthLimit:this.urlLengthLimit})}upsert(t,{onConflict:e,ignoreDuplicates:r=!1,count:i,defaultToNull:a=!0}={}){var n;let h="POST",{url:o,headers:c}=this.cloneRequestState();if(c.append("Prefer",`resolution=${r?"ignore":"merge"}-duplicates`),e!==void 0&&o.searchParams.set("on_conflict",e),i&&c.append("Prefer",`count=${i}`),a||c.append("Prefer","missing=default"),Array.isArray(t)){let s=t.reduce((l,u)=>l.concat(Object.keys(u)),[]);if(s.length>0){let l=[...new Set(s)].map(u=>`"${u}"`);o.searchParams.set("columns",l.join(","))}}return new P({method:h,url:o,headers:c,schema:this.schema,body:t,fetch:(n=this.fetch)!==null&&n!==void 0?n:fetch,urlLengthLimit:this.urlLengthLimit})}update(t,{count:e}={}){var r;let i="PATCH",{url:a,headers:n}=this.cloneRequestState();return e&&n.append("Prefer",`count=${e}`),new P({method:i,url:a,headers:n,schema:this.schema,body:t,fetch:(r=this.fetch)!==null&&r!==void 0?r:fetch,urlLengthLimit:this.urlLengthLimit})}delete({count:t}={}){var e;let r="DELETE",{url:i,headers:a}=this.cloneRequestState();return t&&a.append("Prefer",`count=${t}`),new P({method:r,url:i,headers:a,schema:this.schema,fetch:(e=this.fetch)!==null&&e!==void 0?e:fetch,urlLengthLimit:this.urlLengthLimit})}};function C(t){"@babel/helpers - typeof";return C=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},C(t)}function _e(t,e){if(C(t)!="object"||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var i=r.call(t,e||"default");if(C(i)!="object")return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function Ae(t){var e=_e(t,"string");return C(e)=="symbol"?e:e+""}function $e(t,e,r){return(e=Ae(e))in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function W(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(t);e&&(i=i.filter(function(a){return Object.getOwnPropertyDescriptor(t,a).enumerable})),r.push.apply(r,i)}return r}function L(t){for(var e=1;e<arguments.length;e++){var r=arguments[e]!=null?arguments[e]:{};e%2?W(Object(r),!0).forEach(function(i){$e(t,i,r[i])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):W(Object(r)).forEach(function(i){Object.defineProperty(t,i,Object.getOwnPropertyDescriptor(r,i))})}return t}var Ie=class Q{constructor(e,{headers:r={},schema:i,fetch:a,timeout:n,urlLengthLimit:h=8e3}={}){this.url=e,this.headers=new w(r),this.schemaName=i,this.urlLengthLimit=h;let o=a??globalThis.fetch;n!==void 0&&n>0?this.fetch=(c,s)=>{let l=new we,u=setTimeout(()=>l.abort(),n),m=s?.signal;if(m){if(m.aborted)return clearTimeout(u),o(c,s);let p=()=>{clearTimeout(u),l.abort()};return m.addEventListener("abort",p,{once:!0}),o(c,L(L({},s),{},{signal:l.signal})).finally(()=>{clearTimeout(u),m.removeEventListener("abort",p)})}return o(c,L(L({},s),{},{signal:l.signal})).finally(()=>clearTimeout(u))}:this.fetch=o}from(e){if(!e||typeof e!="string"||e.trim()==="")throw new Error("Invalid relation name: relation must be a non-empty string.");return new Oe(new k(`${this.url}/${e}`),{headers:new w(this.headers),schema:this.schemaName,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}schema(e){return new Q(this.url,{headers:this.headers,schema:e,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}rpc(e,r={},{head:i=!1,get:a=!1,count:n}={}){var h;let o,c=new k(`${this.url}/rpc/${e}`),s,l=p=>p!==null&&typeof p=="object"&&(!Array.isArray(p)||p.some(l)),u=i&&Object.values(r).some(l);u?(o="POST",s=r):i||a?(o=i?"HEAD":"GET",Object.entries(r).filter(([p,d])=>d!==void 0).map(([p,d])=>[p,Array.isArray(d)?`{${d.join(",")}}`:`${d}`]).forEach(([p,d])=>{c.searchParams.append(p,d)})):(o="POST",s=r);let m=new w(this.headers);return u?m.set("Prefer",n?`count=${n},return=minimal`:"return=minimal"):n&&m.set("Prefer",`count=${n}`),new P({method:o,url:c,headers:m,schema:this.schemaName,body:s,fetch:(h=this.fetch)!==null&&h!==void 0?h:fetch,urlLengthLimit:this.urlLengthLimit})}},Ue="/entities",X=(t,e)=>new Ie(t+Ue,{fetch:e.fetchWithAuth.bind(e)}),Z=class{constructor(){this.hoverOverlay=null,this.selectedOverlay=null,this.tooltip=null,this.hoverElement=null,this.selectedElement=null,this.hoverUpdateHandler=null,this.selectedUpdateHandler=null,this.createStyles()}createStyles(){if(document.getElementById("__nvwa-inspector-overlay-style"))return;let t=document.createElement("style");t.id="__nvwa-inspector-overlay-style",t.textContent=`
4
+ ${l.stack}`)}else{var f;o=(f=n?.stack)!==null&&f!==void 0?f:""}let y=this.url.toString().length;return n?.name==="AbortError"||n?.code==="ABORT_ERR"?(s="",c="Request was aborted (timeout or manual cancellation)",y>this.urlLengthLimit&&(c+=`. Note: Your request URL is ${y} characters, which may exceed server limits. If selecting many fields, consider using views. If filtering with large arrays (e.g., .in('id', [many IDs])), consider using an RPC function to pass values server-side.`)):(l?.name==="HeadersOverflowError"||l?.code==="UND_ERR_HEADERS_OVERFLOW")&&(s="",c="HTTP headers exceeded server limits (typically 16KB)",y>this.urlLengthLimit&&(c+=`. Your request URL is ${y} characters. If selecting many fields, consider using views. If filtering with large arrays (e.g., .in('id', [200+ IDs])), consider using an RPC function instead.`)),{error:{message:`${(h=n?.name)!==null&&h!==void 0?h:"FetchError"}: ${n?.message}`,details:o,hint:c,code:s},data:null,count:null,status:0,statusText:""}})),i.then(t,e)}returns(){return this}overrideTypes(){return this}},Ae=class extends _e{select(t){let e=!1,r=(t??"*").split("").map(a=>/\s/.test(a)&&!e?"":(a==='"'&&(e=!e),a)).join("");return this.url.searchParams.set("select",r),this.headers.append("Prefer","return=representation"),this}order(t,{ascending:e=!0,nullsFirst:r,foreignTable:a,referencedTable:i=a}={}){let n=i?`${i}.order`:"order",h=this.url.searchParams.get(n);return this.url.searchParams.set(n,`${h?`${h},`:""}${t}.${e?"asc":"desc"}${r===void 0?"":r?".nullsfirst":".nullslast"}`),this}limit(t,{foreignTable:e,referencedTable:r=e}={}){let a=typeof r>"u"?"limit":`${r}.limit`;return this.url.searchParams.set(a,`${t}`),this}range(t,e,{foreignTable:r,referencedTable:a=r}={}){let i=typeof a>"u"?"offset":`${a}.offset`,n=typeof a>"u"?"limit":`${a}.limit`;return this.url.searchParams.set(i,`${t}`),this.url.searchParams.set(n,`${e-t+1}`),this}abortSignal(t){return this.signal=t,this}single(){return this.headers.set("Accept","application/vnd.pgrst.object+json"),this}maybeSingle(){return this.isMaybeSingle=!0,this}csv(){return this.headers.set("Accept","text/csv"),this}geojson(){return this.headers.set("Accept","application/geo+json"),this}explain({analyze:t=!1,verbose:e=!1,settings:r=!1,buffers:a=!1,wal:i=!1,format:n="text"}={}){var h;let o=[t?"analyze":null,e?"verbose":null,r?"settings":null,a?"buffers":null,i?"wal":null].filter(Boolean).join("|"),c=(h=this.headers.get("Accept"))!==null&&h!==void 0?h:"application/json";return this.headers.set("Accept",`application/vnd.pgrst.plan+${n}; for="${c}"; options=${o};`),n==="json"?this:this}rollback(){return this.headers.append("Prefer","tx=rollback"),this}returns(){return this}maxAffected(t){return this.headers.append("Prefer","handling=strict"),this.headers.append("Prefer",`max-affected=${t}`),this}},W=new RegExp("[,()]"),P=class extends Ae{eq(t,e){return this.url.searchParams.append(t,`eq.${e}`),this}neq(t,e){return this.url.searchParams.append(t,`neq.${e}`),this}gt(t,e){return this.url.searchParams.append(t,`gt.${e}`),this}gte(t,e){return this.url.searchParams.append(t,`gte.${e}`),this}lt(t,e){return this.url.searchParams.append(t,`lt.${e}`),this}lte(t,e){return this.url.searchParams.append(t,`lte.${e}`),this}like(t,e){return this.url.searchParams.append(t,`like.${e}`),this}likeAllOf(t,e){return this.url.searchParams.append(t,`like(all).{${e.join(",")}}`),this}likeAnyOf(t,e){return this.url.searchParams.append(t,`like(any).{${e.join(",")}}`),this}ilike(t,e){return this.url.searchParams.append(t,`ilike.${e}`),this}ilikeAllOf(t,e){return this.url.searchParams.append(t,`ilike(all).{${e.join(",")}}`),this}ilikeAnyOf(t,e){return this.url.searchParams.append(t,`ilike(any).{${e.join(",")}}`),this}regexMatch(t,e){return this.url.searchParams.append(t,`match.${e}`),this}regexIMatch(t,e){return this.url.searchParams.append(t,`imatch.${e}`),this}is(t,e){return this.url.searchParams.append(t,`is.${e}`),this}isDistinct(t,e){return this.url.searchParams.append(t,`isdistinct.${e}`),this}in(t,e){let r=Array.from(new Set(e)).map(a=>typeof a=="string"&&W.test(a)?`"${a}"`:`${a}`).join(",");return this.url.searchParams.append(t,`in.(${r})`),this}notIn(t,e){let r=Array.from(new Set(e)).map(a=>typeof a=="string"&&W.test(a)?`"${a}"`:`${a}`).join(",");return this.url.searchParams.append(t,`not.in.(${r})`),this}contains(t,e){return typeof e=="string"?this.url.searchParams.append(t,`cs.${e}`):Array.isArray(e)?this.url.searchParams.append(t,`cs.{${e.join(",")}}`):this.url.searchParams.append(t,`cs.${JSON.stringify(e)}`),this}containedBy(t,e){return typeof e=="string"?this.url.searchParams.append(t,`cd.${e}`):Array.isArray(e)?this.url.searchParams.append(t,`cd.{${e.join(",")}}`):this.url.searchParams.append(t,`cd.${JSON.stringify(e)}`),this}rangeGt(t,e){return this.url.searchParams.append(t,`sr.${e}`),this}rangeGte(t,e){return this.url.searchParams.append(t,`nxl.${e}`),this}rangeLt(t,e){return this.url.searchParams.append(t,`sl.${e}`),this}rangeLte(t,e){return this.url.searchParams.append(t,`nxr.${e}`),this}rangeAdjacent(t,e){return this.url.searchParams.append(t,`adj.${e}`),this}overlaps(t,e){return typeof e=="string"?this.url.searchParams.append(t,`ov.${e}`):this.url.searchParams.append(t,`ov.{${e.join(",")}}`),this}textSearch(t,e,{config:r,type:a}={}){let i="";a==="plain"?i="pl":a==="phrase"?i="ph":a==="websearch"&&(i="w");let n=r===void 0?"":`(${r})`;return this.url.searchParams.append(t,`${i}fts${n}.${e}`),this}match(t){return Object.entries(t).filter(([e,r])=>r!==void 0).forEach(([e,r])=>{this.url.searchParams.append(e,`eq.${r}`)}),this}not(t,e,r){return this.url.searchParams.append(t,`not.${e}.${r}`),this}or(t,{foreignTable:e,referencedTable:r=e}={}){let a=r?`${r}.or`:"or";return this.url.searchParams.append(a,`(${t})`),this}filter(t,e,r){return this.url.searchParams.append(t,`${e}.${r}`),this}},$e=class{constructor(t,{headers:e={},schema:r,fetch:a,urlLengthLimit:i=8e3}){this.url=t,this.headers=new w(e),this.schema=r,this.fetch=a,this.urlLengthLimit=i}cloneRequestState(){return{url:new U(this.url.toString()),headers:new w(this.headers)}}select(t,e){let{head:r=!1,count:a}=e??{},i=r?"HEAD":"GET",n=!1,h=(t??"*").split("").map(s=>/\s/.test(s)&&!n?"":(s==='"'&&(n=!n),s)).join(""),{url:o,headers:c}=this.cloneRequestState();return o.searchParams.set("select",h),a&&c.append("Prefer",`count=${a}`),new P({method:i,url:o,headers:c,schema:this.schema,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}insert(t,{count:e,defaultToNull:r=!0}={}){var a;let i="POST",{url:n,headers:h}=this.cloneRequestState();if(e&&h.append("Prefer",`count=${e}`),r||h.append("Prefer","missing=default"),Array.isArray(t)){let o=t.reduce((c,s)=>c.concat(Object.keys(s)),[]);if(o.length>0){let c=[...new Set(o)].map(s=>`"${s}"`);n.searchParams.set("columns",c.join(","))}}return new P({method:i,url:n,headers:h,schema:this.schema,body:t,fetch:(a=this.fetch)!==null&&a!==void 0?a:fetch,urlLengthLimit:this.urlLengthLimit})}upsert(t,{onConflict:e,ignoreDuplicates:r=!1,count:a,defaultToNull:i=!0}={}){var n;let h="POST",{url:o,headers:c}=this.cloneRequestState();if(c.append("Prefer",`resolution=${r?"ignore":"merge"}-duplicates`),e!==void 0&&o.searchParams.set("on_conflict",e),a&&c.append("Prefer",`count=${a}`),i||c.append("Prefer","missing=default"),Array.isArray(t)){let s=t.reduce((l,u)=>l.concat(Object.keys(u)),[]);if(s.length>0){let l=[...new Set(s)].map(u=>`"${u}"`);o.searchParams.set("columns",l.join(","))}}return new P({method:h,url:o,headers:c,schema:this.schema,body:t,fetch:(n=this.fetch)!==null&&n!==void 0?n:fetch,urlLengthLimit:this.urlLengthLimit})}update(t,{count:e}={}){var r;let a="PATCH",{url:i,headers:n}=this.cloneRequestState();return e&&n.append("Prefer",`count=${e}`),new P({method:a,url:i,headers:n,schema:this.schema,body:t,fetch:(r=this.fetch)!==null&&r!==void 0?r:fetch,urlLengthLimit:this.urlLengthLimit})}delete({count:t}={}){var e;let r="DELETE",{url:a,headers:i}=this.cloneRequestState();return t&&i.append("Prefer",`count=${t}`),new P({method:r,url:a,headers:i,schema:this.schema,fetch:(e=this.fetch)!==null&&e!==void 0?e:fetch,urlLengthLimit:this.urlLengthLimit})}};function C(t){"@babel/helpers - typeof";return C=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},C(t)}function Ie(t,e){if(C(t)!="object"||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var a=r.call(t,e||"default");if(C(a)!="object")return a;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function ke(t){var e=Ie(t,"string");return C(e)=="symbol"?e:e+""}function Ue(t,e,r){return(e=ke(e))in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function F(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(t);e&&(a=a.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),r.push.apply(r,a)}return r}function O(t){for(var e=1;e<arguments.length;e++){var r=arguments[e]!=null?arguments[e]:{};e%2?F(Object(r),!0).forEach(function(a){Ue(t,a,r[a])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):F(Object(r)).forEach(function(a){Object.defineProperty(t,a,Object.getOwnPropertyDescriptor(r,a))})}return t}var xe=class X{constructor(e,{headers:r={},schema:a,fetch:i,timeout:n,urlLengthLimit:h=8e3}={}){this.url=e,this.headers=new w(r),this.schemaName=a,this.urlLengthLimit=h;let o=i??globalThis.fetch;n!==void 0&&n>0?this.fetch=(c,s)=>{let l=new ve,u=setTimeout(()=>l.abort(),n),m=s?.signal;if(m){if(m.aborted)return clearTimeout(u),o(c,s);let p=()=>{clearTimeout(u),l.abort()};return m.addEventListener("abort",p,{once:!0}),o(c,O(O({},s),{},{signal:l.signal})).finally(()=>{clearTimeout(u),m.removeEventListener("abort",p)})}return o(c,O(O({},s),{},{signal:l.signal})).finally(()=>clearTimeout(u))}:this.fetch=o}from(e){if(!e||typeof e!="string"||e.trim()==="")throw new Error("Invalid relation name: relation must be a non-empty string.");return new $e(new U(`${this.url}/${e}`),{headers:new w(this.headers),schema:this.schemaName,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}schema(e){return new X(this.url,{headers:this.headers,schema:e,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}rpc(e,r={},{head:a=!1,get:i=!1,count:n}={}){var h;let o,c=new U(`${this.url}/rpc/${e}`),s,l=p=>p!==null&&typeof p=="object"&&(!Array.isArray(p)||p.some(l)),u=a&&Object.values(r).some(l);u?(o="POST",s=r):a||i?(o=a?"HEAD":"GET",Object.entries(r).filter(([p,d])=>d!==void 0).map(([p,d])=>[p,Array.isArray(d)?`{${d.join(",")}}`:`${d}`]).forEach(([p,d])=>{c.searchParams.append(p,d)})):(o="POST",s=r);let m=new w(this.headers);return u?m.set("Prefer",n?`count=${n},return=minimal`:"return=minimal"):n&&m.set("Prefer",`count=${n}`),new P({method:o,url:c,headers:m,schema:this.schemaName,body:s,fetch:(h=this.fetch)!==null&&h!==void 0?h:fetch,urlLengthLimit:this.urlLengthLimit})}},Ne="/entities",Z=(t,e)=>new xe(t+Ne,{fetch:e.fetchWithAuth.bind(e)}),ee=class{constructor(){this.hoverOverlay=null,this.selectedOverlay=null,this.tooltip=null,this.hoverElement=null,this.selectedElement=null,this.hoverUpdateHandler=null,this.selectedUpdateHandler=null,this.createStyles()}createStyles(){if(document.getElementById("__nvwa-inspector-overlay-style"))return;let t=document.createElement("style");t.id="__nvwa-inspector-overlay-style",t.textContent=`
5
5
  .__nvwa-inspector-overlay {
6
6
  position: absolute;
7
7
  pointer-events: none;
@@ -33,4 +33,4 @@ ${l.stack}`)}else{var f;o=(f=n?.stack)!==null&&f!==void 0?f:""}let y=this.url.to
33
33
  max-width: 400px;
34
34
  word-break: break-all;
35
35
  }
36
- `,document.head.appendChild(t)}createTooltip(){return this.tooltip?this.tooltip:(this.tooltip=document.createElement("div"),this.tooltip.id="__nvwa-inspector-tooltip",document.body.appendChild(this.tooltip),this.tooltip)}createOverlay(t){let e=document.createElement("div");return e.className=`__nvwa-inspector-overlay __nvwa-inspector-overlay-${t}`,document.body.appendChild(e),e}updateOverlayPosition(t,e){if(!e.isConnected)return;let r=e.getBoundingClientRect(),i=window.scrollX||window.pageXOffset,a=window.scrollY||window.pageYOffset;r.width>0&&r.height>0?(t.style.left=`${r.left+i}px`,t.style.top=`${r.top+a}px`,t.style.width=`${r.width}px`,t.style.height=`${r.height}px`,t.style.display="block"):t.style.display="none"}removeOverlay(t){t&&t.parentNode&&t.parentNode.removeChild(t)}highlightElement(t,e){if(!t.isConnected)return;if(this.hoverElement===t&&this.hoverOverlay){this.updateOverlayPosition(this.hoverOverlay,t);let h=this.createTooltip();e?h.textContent=e:h.textContent=`<${t.tagName.toLowerCase()}> (\u65E0 source location)`,h.style.display="block";let o=t.getBoundingClientRect();h.style.left=`${o.left+window.scrollX}px`,h.style.top=`${o.top+window.scrollY-h.offsetHeight-8}px`,o.top<h.offsetHeight+8&&(h.style.top=`${o.bottom+window.scrollY+8}px`);return}this.hoverOverlay&&(this.removeOverlay(this.hoverOverlay),this.hoverOverlay=null);let r=this.createOverlay("hover");this.updateOverlayPosition(r,t),this.hoverOverlay=r,this.hoverElement=t;let i=()=>{this.hoverOverlay&&this.hoverElement&&this.hoverElement.isConnected&&this.updateOverlayPosition(this.hoverOverlay,this.hoverElement)};this.hoverUpdateHandler&&(window.removeEventListener("scroll",this.hoverUpdateHandler,!0),window.removeEventListener("resize",this.hoverUpdateHandler)),this.hoverUpdateHandler=i,window.addEventListener("scroll",i,!0),window.addEventListener("resize",i);let a=this.createTooltip();e?a.textContent=e:a.textContent=`<${t.tagName.toLowerCase()}> (\u65E0 source location)`,a.style.display="block";let n=t.getBoundingClientRect();a.style.left=`${n.left+window.scrollX}px`,a.style.top=`${n.top+window.scrollY-a.offsetHeight-8}px`,n.top<a.offsetHeight+8&&(a.style.top=`${n.bottom+window.scrollY+8}px`)}selectElement(t,e){if(!t.isConnected)return;if(this.selectedElement===t&&this.selectedOverlay){this.updateOverlayPosition(this.selectedOverlay,t);return}this.selectedOverlay&&(this.removeOverlay(this.selectedOverlay),this.selectedOverlay=null);let r=this.createOverlay("selected");this.updateOverlayPosition(r,t),this.selectedOverlay=r,this.selectedElement=t;let i=()=>{this.selectedOverlay&&this.selectedElement&&this.selectedElement.isConnected&&this.updateOverlayPosition(this.selectedOverlay,this.selectedElement)};this.selectedUpdateHandler&&(window.removeEventListener("scroll",this.selectedUpdateHandler,!0),window.removeEventListener("resize",this.selectedUpdateHandler)),this.selectedUpdateHandler=i,window.addEventListener("scroll",i,!0),window.addEventListener("resize",i)}removeHighlight(){this.hoverOverlay&&(this.removeOverlay(this.hoverOverlay),this.hoverOverlay=null),this.hoverElement&&(this.hoverElement=null),this.tooltip&&(this.tooltip.style.display="none"),this.hoverUpdateHandler&&(window.removeEventListener("scroll",this.hoverUpdateHandler,!0),window.removeEventListener("resize",this.hoverUpdateHandler),this.hoverUpdateHandler=null)}clearSelection(){this.selectedOverlay&&(this.removeOverlay(this.selectedOverlay),this.selectedOverlay=null),this.selectedElement&&(this.selectedElement=null),this.selectedUpdateHandler&&(window.removeEventListener("scroll",this.selectedUpdateHandler,!0),window.removeEventListener("resize",this.selectedUpdateHandler),this.selectedUpdateHandler=null)}cleanup(){this.removeHighlight(),this.clearSelection(),this.tooltip&&this.tooltip.parentNode&&(this.tooltip.parentNode.removeChild(this.tooltip),this.tooltip=null);let t=document.getElementById("__nvwa-inspector-overlay-style");t&&t.parentNode&&t.parentNode.removeChild(t)}};function ee(t="root"){if(typeof document>"u")return null;let e=document.getElementById(t)||document.body;if(!e)return null;let r=e.querySelector("[data-source-location]");if(r){let i=r.getAttribute("data-source-location");if(i)return i}if(e.firstElementChild){let i=e.firstElementChild.getAttribute("data-source-location");if(i)return i}return null}var ke={"wechat-pay":{id:"wechat-pay",name:"WeChat Pay",description:"WeChat payment for web and miniapp."},"wechat-platform":{id:"wechat-platform",name:"WeChat Partner",description:"WeChat partner merchant onboarding."},"alipay-web":{id:"alipay-web",name:"Alipay Web",description:"Alipay page pay (ISV)."},"alipay-mobile-web":{id:"alipay-mobile-web",name:"Alipay Mobile Web",description:"Alipay WAP pay (ISV)."},"alipay-miniprogram":{id:"alipay-miniprogram",name:"Alipay Mini Program",description:"Alipay mini program payment."},stripe:{id:"stripe",name:"Stripe",description:"Stripe payment."}};function te(t){let e=t;if(typeof e.kind=="string")return e;if(typeof e.tradeNO=="string")return{kind:"alipay_miniprogram",tradeNO:e.tradeNO};if(typeof e.clientSecret=="string")return{kind:"stripe_client_secret",clientSecret:e.clientSecret};if(typeof e.redirectUrl=="string")return{kind:"redirect_url",redirectUrl:e.redirectUrl};if(typeof e.formHtml=="string")return{kind:"alipay_page",formHtml:e.formHtml};if(typeof e.codeUrl=="string")return{kind:"wechat_native_qr",codeUrl:e.codeUrl};let r=e.jsapiPayParams??e;return typeof r.timeStamp=="string"&&typeof r.nonceStr=="string"&&typeof r.package=="string"&&typeof r.paySign=="string"&&typeof r.appId=="string"?{kind:"wechat_jsapi",mode:"jsapi",jsapiPayParams:{appId:r.appId,timeStamp:r.timeStamp,nonceStr:r.nonceStr,package:r.package,signType:r.signType??"RSA",paySign:r.paySign}}:null}async function re(t,e){let r=t.payment?.providers??{};return Object.entries(r).filter(([,i])=>i.enabled).map(([i])=>{let a=ke[i]??{id:i,name:i,description:""};return{...a,type:a.id}})}function O(t){return t&&typeof t=="object"?t:{}}function xe(t){let e=O(t),r=e.enabled===!0,i=String(e.oauthCredentialSource??"").toLowerCase();return i?{enabled:r,oauthCredentialSource:i==="custom"?"custom":"nvwa_default"}:{enabled:r}}function F(t){let e=O(t),r=O(e.providers),i={};for(let[a,n]of Object.entries(r))i[a]=xe(n);return{providers:i}}function N(t){let e=O(t);return{socialLogin:F(e.socialLogin),payment:F(e.payment)}}var Ne=["DesktopWeb","MobileWeb","AndroidApp","IosApp","HarmonyApp","WechatMiniProgram","AlipayMiniProgram","DouyinMiniProgram"];function Re(t){return Ne.includes(t)}async function ie(t){let{platformType:e,getMiniProgramIdentity:r}=t;if(e!=="WechatMiniProgram"&&e!=="AlipayMiniProgram")return{platformType:e};if(!r)return{platformType:e};let i=await r();return i?{platformType:i.platformType,platformUserId:i.platformUserId,appId:i.appId,unionid:i.unionid}:{platformType:e}}function ae(t){return N(t.integrationProviders??{})}function ne(t){let e=t.baseUrl?.trim()??"";if(!e)throw new Error("Nvwa: appConfig.baseUrl is required");let r=t.applicationCode?.trim()??"";if(!r)throw new Error("Nvwa: appConfig.applicationCode is required");let i=t.platformType?.trim()??"";if(!i)throw new Error("Nvwa: appConfig.platformType is required");if(!Re(i))throw new Error("Nvwa: appConfig.platformType is invalid");return{baseUrl:e,applicationCode:r,platformType:i}}var _=class{constructor(){this.prefix="nvwa_"}getKey(e){return`${this.prefix}${e}`}async get(e){try{let r=this.getKey(e),i=uni.getStorageSync(r);return i?i.expires&&Date.now()>i.expires?(await this.remove(e),null):i.value:null}catch(r){return console.error("UniAppStorageService get error:",r),null}}async set(e,r,i){try{let a=this.getKey(e),n={value:r,expires:i?Date.now()+i*1e3:null,timestamp:Date.now()};uni.setStorageSync(a,n)}catch(a){throw console.error("UniAppStorageService set error:",a),a}}async remove(e){try{let r=this.getKey(e);uni.removeStorageSync(r)}catch(r){throw console.error("UniAppStorageService remove error:",r),r}}async clear(){try{uni.clearStorageSync()}catch(e){throw console.error("UniAppStorageService clear error:",e),e}}};var A=(t,e)=>{let r;if(typeof t=="string")r=t;else if(t&&typeof t.toString=="function")r=t.toString();else if(t?.url)r=t.url;else throw new Error("Invalid input for uniappFetch");typeof console<"u"&&(console.warn("[NvwaUni] request url:",r,"method:",(e?.method||"GET").toUpperCase()),!r.startsWith("http://")&&!r.startsWith("https://")&&console.warn("[NvwaUni] url \u975E\u5B8C\u6574\u5730\u5740\uFF0C\u5C0F\u7A0B\u5E8F uni.request \u4F1A\u62A5 invalid url\uFF0C\u8BF7\u68C0\u67E5 baseUrl \u662F\u5426\u4F20\u5165\u5B8C\u6574\u57DF\u540D"));let i=(e?.method||"GET").toUpperCase(),a={};if(e?.headers){let o=e.headers;if(typeof o?.forEach=="function")o.forEach((c,s)=>{a[s]=c});else if(Array.isArray(o))for(let[c,s]of o)a[c]=s;else Object.assign(a,o)}let n;if(e?.body!==void 0){let o=e.body;if(typeof o=="string")n=o;else if(o&&typeof o=="object"&&typeof o.forEach=="function"){let c={};o.forEach((s,l)=>{c[l]=s}),n=c}else n=o}let h=e?.timeout||3e4;return new Promise((o,c)=>{let s=e?.signal;if(s?.aborted){let p=new Error("The operation was aborted");p.name="AbortError",c(p);return}let l=!1,u=[],m=uni.request({url:r,method:i,data:n,header:a,timeout:h,success:p=>{if(l)return;l=!0;let d=p.statusCode,f="",y=new w,T=p.header||p.headers||{};Object.keys(T).forEach(S=>{let I=T[S];y.set(S,typeof I=="string"?I:String(I))}),o(new B(p.data,{status:d,statusText:f,headers:y}))},fail:p=>{if(l)return;l=!0;let d=p?.errMsg||p?.message||"Network Error",f=new Error(d);/(abort|aborted|canceled|cancelled)/i.test(String(d))&&(f.name="AbortError"),c(f)}});if(s&&typeof s.addEventListener=="function"){let p=()=>{if(l)return;try{m?.abort?.()}catch{}let d=new Error("The operation was aborted");d.name="AbortError",l=!0,c(d)};s.addEventListener("abort",p),u.push(()=>{try{s.removeEventListener?.("abort",p)}catch{}})}})};globalThis&&typeof globalThis.fetch!="function"&&(globalThis.fetch=A);function je(t){return`https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=${encodeURIComponent(t)}`}function se(t){if(typeof window<"u"){window.open(t,"_blank");return}globalThis.plus?.runtime?.openURL?.(t)}async function Me(t){if(t.kind!=="alipay_miniprogram")throw new Error("requestPayment: invalid payParams for alipay miniprogram");await new Promise((e,r)=>{let i=globalThis.my;if(!i?.tradePay){r(new Error("requestPayment: my.tradePay is unavailable"));return}i.tradePay({tradeNO:t.tradeNO,success:()=>e(),fail:a=>r(a)})})}async function He(t){if(t.kind!=="wechat_jsapi")throw new Error("requestPayment: invalid payParams for wechat jsapi");let e=t.jsapiPayParams;await new Promise((r,i)=>{uni.requestPayment({provider:"wxpay",timeStamp:e.timeStamp,nonceStr:e.nonceStr,package:e.package,signType:e.signType??"RSA",paySign:e.paySign,success:()=>r(),fail:a=>i(a)})})}function qe(t){if(t.kind!=="redirect_url")throw new Error("requestPayment: invalid payParams for redirect");typeof window<"u"?window.location.href=t.redirectUrl:se(t.redirectUrl)}function We(t){if(t.kind!=="wechat_native_qr")throw new Error("requestPayment: invalid payParams for wechat qr");let e=je(t.codeUrl);se(e)}function Fe(t){if(t.kind!=="alipay_page")throw new Error("requestPayment: invalid payParams for alipay page");if(typeof document>"u"||!document.body)throw new Error("requestPayment: alipay_page (formHtml) requires a browser/WebView environment (e.g. H5 or App webview)");let e=t.formHtml,a=new DOMParser().parseFromString(e,"text/html").querySelector("form");if(!a)throw new Error("requestPayment: alipay_page formHtml does not contain a form element");let n=document.importNode(a,!0);n.setAttribute("style","display:none"),document.body.appendChild(n),n.submit()}async function De(t){if(!t)return!1;switch(t.kind){case"alipay_miniprogram":return await Me(t),!0;case"alipay_page":return Fe(t),!0;case"wechat_jsapi":return await He(t),!0;case"redirect_url":return qe(t),!0;case"wechat_native_qr":return We(t),!0;default:return!1}}var R={async requestPayment(t,e){try{let r=te(t);if(!await De(r))throw new Error("requestPayment: unsupported payParams for current endpoint");e?.onSuccess?.()}catch(r){throw e?.onFailure?.(r),r}}};function oe(t){let e=async r=>await re(t,r);return{...R,getAvailableProviders:e,getProviders:e}}function Ge(){if(typeof window>"u"||window===window.parent)return;let t=!1,e=new Z;function r(s){if(!s)return!1;let l=s.toLowerCase();return l.includes("/components/")||l.includes("\\components\\")}function i(s){let l=s,u=null;for(;l;){let m=l.getAttribute("data-source-location");if(m)if(r(m)){u||(u=m),l=l.parentElement;continue}else return m;l=l.parentElement}return u}let a=null;function n(s){t&&(a!==null&&cancelAnimationFrame(a),a=requestAnimationFrame(()=>{let l=s.target;if(!l||l===document.body||l===document.documentElement){e.removeHighlight();return}if(l.tagName.toLowerCase()==="img"){let d=i(l);e.highlightElement(l,d);let f={type:"HOVER_INSPECTOR_ELEMENT_HOVER",sourceLocation:d,elementInfo:{tagName:l.tagName.toLowerCase(),className:l.className||"",id:l.id||""}};window.parent.postMessage(f,"*");return}let u=l,m=i(l);if(!m){let d=l.parentElement;for(;d&&d!==document.body&&d!==document.documentElement;){let f=i(d);if(f){u=d,m=f;break}d=d.parentElement}}e.highlightElement(u,m);let p={type:"HOVER_INSPECTOR_ELEMENT_HOVER",sourceLocation:m,elementInfo:{tagName:u.tagName.toLowerCase(),className:u.className||"",id:u.id||""}};window.parent.postMessage(p,"*")}))}function h(){if(!t)return;e.removeHighlight();let s={type:"HOVER_INSPECTOR_ELEMENT_LEAVE"};window.parent.postMessage(s,"*")}function o(s){if(!t)return;s.preventDefault(),s.stopPropagation();let l=s.target;if(!l||l===document.body||l===document.documentElement)return;let u=i(l);e.selectElement(l,u);let m={type:"HOVER_INSPECTOR_ELEMENT_SELECT",sourceLocation:u,elementInfo:{tagName:l.tagName.toLowerCase(),className:l.className||"",id:l.id||""}};window.parent.postMessage(m,"*")}function c(s){s.data?.type==="HOVER_INSPECTOR_ENABLE"?(t=!0,document.addEventListener("mousemove",n),document.addEventListener("mouseleave",h),document.addEventListener("click",o,!0)):s.data?.type==="HOVER_INSPECTOR_DISABLE"&&(t=!1,document.removeEventListener("mousemove",n),document.removeEventListener("mouseleave",h),document.removeEventListener("click",o,!0),e.removeHighlight(),e.clearSelection())}return window.addEventListener("message",c),()=>{window.removeEventListener("message",c),document.removeEventListener("mousemove",n),document.removeEventListener("mouseleave",h),document.removeEventListener("click",o,!0),e.cleanup()}}function Be(t,e){if(!t||!t.contentWindow)throw new Error("Invalid iframe element");let r={type:"HOVER_INSPECTOR_ENABLE"};t.contentWindow.postMessage(r,e)}function Je(t,e){if(!t||!t.contentWindow)return;let r={type:"HOVER_INSPECTOR_DISABLE"};t.contentWindow.postMessage(r,e)}function ze(t,e,r=5e3){return new Promise((i,a)=>{if(!t||!t.contentWindow){a(new Error("Invalid iframe element"));return}let n=`source-location-${Date.now()}-${Math.random()}`,h=setTimeout(()=>{window.removeEventListener("message",o),a(new Error("Request timeout"))},r),o=s=>{s.origin===e&&s.data?.type==="GET_SOURCE_LOCATION_RESPONSE"&&s.data?.requestId===n&&(clearTimeout(h),window.removeEventListener("message",o),s.data.error?a(new Error(s.data.error)):i(s.data.sourceLocation||null))};window.addEventListener("message",o);let c={type:"GET_SOURCE_LOCATION_REQUEST",requestId:n};try{t.contentWindow.postMessage(c,e)}catch(s){clearTimeout(h),window.removeEventListener("message",o),a(s)}})}function Ke(){if(typeof window>"u"||window===window.parent)return;let t=e=>{if(e.data?.type==="GET_SOURCE_LOCATION_REQUEST")try{let i={type:"GET_SOURCE_LOCATION_RESPONSE",sourceLocation:Ve(),requestId:e.data.requestId};window.parent.postMessage(i,e.origin)}catch(r){let i={type:"GET_SOURCE_LOCATION_RESPONSE",sourceLocation:null,error:r instanceof Error?r.message:"Unknown error",requestId:e.data.requestId};window.parent.postMessage(i,e.origin)}};return window.addEventListener("message",t),()=>{window.removeEventListener("message",t)}}function Ve(){return ee("app")}function Ye(t){let e=t==="wechat-miniprogram"?"weixin":t==="alipay-miniprogram"?"alipay":t==="douyin-miniprogram"?"toutiao":void 0;return e?new Promise((r,i)=>{uni.login({provider:e,success:a=>{if(!a.code?.trim()){i(new Error(`login code missing for ${t}`));return}r(a.code.trim())},fail:a=>{i(a instanceof Error?a:new Error(`uni.login failed: ${String(a)}`))}})}):Promise.reject(new Error(`unsupported miniprogram provider: ${t}`))}async function Qe(t,e){return e??await t.getSocialProviderDescriptors()}function le(t){return t?.trim()?t.trim():typeof globalThis<"u"&&"location"in globalThis?globalThis.location.href:""}function Xe(t){let{name:e="NvwaSocialLoginButtons",auth:r,applicationCode:i,providers:a,containerClass:n="nvwa-social-login-list",providerClass:h="nvwa-social-login-button"}=t,o=t.resolveMiniProgramCode??Ye;return{name:e,data(){return{providers:[],loading:!0}},async created(){try{this.providers=await Qe(r,a)}catch(c){t.onError?.(c instanceof Error?c:new Error(String(c)))}finally{this.loading=!1}},methods:{async handleProviderTap(c){try{if(t.onBeforeLogin?.(c),c.loginKind==="wechat_miniprogram_code"||c.loginKind==="alipay_miniprogram_code"){let s=await o(c.id);await r.startSocialLogin(c.id,{miniProgramCode:s,applicationCode:i,returnUrl:le(t.returnUrl)});return}await r.startSocialLogin(c.id,{returnUrl:le(t.returnUrl),applicationCode:i})}catch(s){t.onError?.(s instanceof Error?s:new Error(String(s)))}}},render(){if(this.loading||this.providers.length===0)return null;let c=this.$createElement,s=this.providers.filter(l=>l.loginKind!=="unsupported").map(l=>c("button",{key:l.id,class:h,attrs:{type:"button"},on:{click:()=>this.handleProviderTap(l)}},l.name));return c("view",{class:n},s)}}}var j=new _,$=class{constructor(e){this.payment=R;let{handleUnauthorized:r,appConfig:i,integrationProviders:a}=e,n=ne(i);typeof console<"u"&&console.warn("[Nvwa] uniapp init baseUrl:",n.baseUrl||"(empty)"),this.applicationCode=n.applicationCode,this.platformType=n.platformType,this.integrationProviders=N(a??ae(i)),this.auth=new K(n.baseUrl,{fetchImpl:A,storage:j,integrationProviders:this.integrationProviders,applicationCode:this.applicationCode,platformType:n.platformType}),this.httpClient=new V(j,A,r),this.fileStorage=new Y(n.baseUrl,this.httpClient),this.entities=X(n.baseUrl,this.httpClient),this.functions=new J(this.httpClient,n.baseUrl);let h=oe(this.integrationProviders);this.payment={...h,collectPaymentClientContext:()=>ie({platformType:this.platformType,getMiniProgramIdentity:()=>this.auth.getMiniProgramIdentity()})}}};0&&(module.exports={createSocialLoginComponent,disableIframeHoverInspector,enableIframeHoverInspector,getIframeSourceLocation,localStorage,setupIframeHoverInspector,setupIframeSourceLocationListener});
36
+ `,document.head.appendChild(t)}createTooltip(){return this.tooltip?this.tooltip:(this.tooltip=document.createElement("div"),this.tooltip.id="__nvwa-inspector-tooltip",document.body.appendChild(this.tooltip),this.tooltip)}createOverlay(t){let e=document.createElement("div");return e.className=`__nvwa-inspector-overlay __nvwa-inspector-overlay-${t}`,document.body.appendChild(e),e}updateOverlayPosition(t,e){if(!e.isConnected)return;let r=e.getBoundingClientRect(),a=window.scrollX||window.pageXOffset,i=window.scrollY||window.pageYOffset;r.width>0&&r.height>0?(t.style.left=`${r.left+a}px`,t.style.top=`${r.top+i}px`,t.style.width=`${r.width}px`,t.style.height=`${r.height}px`,t.style.display="block"):t.style.display="none"}removeOverlay(t){t&&t.parentNode&&t.parentNode.removeChild(t)}highlightElement(t,e){if(!t.isConnected)return;if(this.hoverElement===t&&this.hoverOverlay){this.updateOverlayPosition(this.hoverOverlay,t);let h=this.createTooltip();e?h.textContent=e:h.textContent=`<${t.tagName.toLowerCase()}> (\u65E0 source location)`,h.style.display="block";let o=t.getBoundingClientRect();h.style.left=`${o.left+window.scrollX}px`,h.style.top=`${o.top+window.scrollY-h.offsetHeight-8}px`,o.top<h.offsetHeight+8&&(h.style.top=`${o.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 a=()=>{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=a,window.addEventListener("scroll",a,!0),window.addEventListener("resize",a);let i=this.createTooltip();e?i.textContent=e:i.textContent=`<${t.tagName.toLowerCase()}> (\u65E0 source location)`,i.style.display="block";let n=t.getBoundingClientRect();i.style.left=`${n.left+window.scrollX}px`,i.style.top=`${n.top+window.scrollY-i.offsetHeight-8}px`,n.top<i.offsetHeight+8&&(i.style.top=`${n.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 a=()=>{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=a,window.addEventListener("scroll",a,!0),window.addEventListener("resize",a)}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 te(t="root"){if(typeof document>"u")return null;let e=document.getElementById(t)||document.body;if(!e)return null;let r=e.querySelector("[data-source-location]");if(r){let a=r.getAttribute("data-source-location");if(a)return a}if(e.firstElementChild){let a=e.firstElementChild.getAttribute("data-source-location");if(a)return a}return null}var Re={"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 re(t){let e=t;if(typeof e.kind=="string")return e;if(typeof e.tradeNO=="string")return{kind:"alipay_miniprogram",tradeNO:e.tradeNO};if(typeof e.clientSecret=="string")return{kind:"stripe_client_secret",clientSecret:e.clientSecret};if(typeof e.redirectUrl=="string")return{kind:"redirect_url",redirectUrl:e.redirectUrl};if(typeof e.formHtml=="string")return{kind:"alipay_page",formHtml:e.formHtml};if(typeof e.codeUrl=="string")return{kind:"wechat_native_qr",codeUrl:e.codeUrl};let r=e.jsapiPayParams??e;return typeof r.timeStamp=="string"&&typeof r.nonceStr=="string"&&typeof r.package=="string"&&typeof r.paySign=="string"&&typeof r.appId=="string"?{kind:"wechat_jsapi",mode:"jsapi",jsapiPayParams:{appId:r.appId,timeStamp:r.timeStamp,nonceStr:r.nonceStr,package:r.package,signType:r.signType??"RSA",paySign:r.paySign}}:null}async function ae(t,e){let r=t.payment?.providers??{};return Object.entries(r).filter(([,a])=>a.enabled).map(([a])=>{let i=Re[a]??{id:a,name:a,description:""};return{...i,type:i.id}})}function L(t){return t&&typeof t=="object"?t:{}}function je(t){let e=L(t),r=e.enabled===!0,a=String(e.oauthCredentialSource??"").toLowerCase();return a?{enabled:r,oauthCredentialSource:a==="custom"?"custom":"nvwa_default"}:{enabled:r}}function D(t){let e=L(t),r=L(e.providers),a={};for(let[i,n]of Object.entries(r))a[i]=je(n);return{providers:a}}function N(t){let e=L(t);return{socialLogin:D(e.socialLogin),payment:D(e.payment)}}var Me=["DesktopWeb","MobileWeb","AndroidApp","IosApp","HarmonyApp","WechatMiniProgram","AlipayMiniProgram","DouyinMiniProgram"];function He(t){return Me.includes(t)}async function ie(t){let{platformType:e,getMiniProgramIdentity:r}=t;if(e!=="WechatMiniProgram"&&e!=="AlipayMiniProgram")return{platformType:e};if(!r)return{platformType:e};let a=await r();return a?{platformType:a.platformType,platformUserId:a.platformUserId,appId:a.appId,unionid:a.unionid}:{platformType:e}}function ne(t){return N(t.integrationProviders??{})}function se(t){let e=t.baseUrl?.trim()??"";if(!e)throw new Error("Nvwa: appConfig.baseUrl is required");let r=t.applicationCode?.trim()??"";if(!r)throw new Error("Nvwa: appConfig.applicationCode is required");let a=t.platformType?.trim()??"";if(!a)throw new Error("Nvwa: appConfig.platformType is required");if(!He(a))throw new Error("Nvwa: appConfig.platformType is invalid");return{baseUrl:e,applicationCode:r,platformType:a}}var _=class{constructor(){this.prefix="nvwa_"}getKey(e){return`${this.prefix}${e}`}async get(e){try{let r=this.getKey(e),a=uni.getStorageSync(r);return a?a.expires&&Date.now()>a.expires?(await this.remove(e),null):a.value:null}catch(r){return console.error("UniAppStorageService get error:",r),null}}async set(e,r,a){try{let i=this.getKey(e),n={value:r,expires:a?Date.now()+a*1e3:null,timestamp:Date.now()};uni.setStorageSync(i,n)}catch(i){throw console.error("UniAppStorageService set error:",i),i}}async remove(e){try{let r=this.getKey(e);uni.removeStorageSync(r)}catch(r){throw console.error("UniAppStorageService remove error:",r),r}}async clear(){try{uni.clearStorageSync()}catch(e){throw console.error("UniAppStorageService clear error:",e),e}}};var A=(t,e)=>{let r;if(typeof t=="string")r=t;else if(t&&typeof t.toString=="function")r=t.toString();else if(t?.url)r=t.url;else throw new Error("Invalid input for uniappFetch");typeof console<"u"&&(console.warn("[NvwaUni] request url:",r,"method:",(e?.method||"GET").toUpperCase()),!r.startsWith("http://")&&!r.startsWith("https://")&&console.warn("[NvwaUni] url \u975E\u5B8C\u6574\u5730\u5740\uFF0C\u5C0F\u7A0B\u5E8F uni.request \u4F1A\u62A5 invalid url\uFF0C\u8BF7\u68C0\u67E5 baseUrl \u662F\u5426\u4F20\u5165\u5B8C\u6574\u57DF\u540D"));let a=(e?.method||"GET").toUpperCase(),i={};if(e?.headers){let o=e.headers;if(typeof o?.forEach=="function")o.forEach((c,s)=>{i[s]=c});else if(Array.isArray(o))for(let[c,s]of o)i[c]=s;else Object.assign(i,o)}let n;if(e?.body!==void 0){let o=e.body;if(typeof o=="string")n=o;else if(o&&typeof o=="object"&&typeof o.forEach=="function"){let c={};o.forEach((s,l)=>{c[l]=s}),n=c}else n=o}let h=e?.timeout||3e4;return new Promise((o,c)=>{let s=e?.signal;if(s?.aborted){let p=new Error("The operation was aborted");p.name="AbortError",c(p);return}let l=!1,u=[],m=uni.request({url:r,method:a,data:n,header:i,timeout:h,success:p=>{if(l)return;l=!0;let d=p.statusCode,f="",y=new w,T=p.header||p.headers||{};Object.keys(T).forEach(S=>{let I=T[S];y.set(S,typeof I=="string"?I:String(I))}),o(new J(p.data,{status:d,statusText:f,headers:y}))},fail:p=>{if(l)return;l=!0;let d=p?.errMsg||p?.message||"Network Error",f=new Error(d);/(abort|aborted|canceled|cancelled)/i.test(String(d))&&(f.name="AbortError"),c(f)}});if(s&&typeof s.addEventListener=="function"){let p=()=>{if(l)return;try{m?.abort?.()}catch{}let d=new Error("The operation was aborted");d.name="AbortError",l=!0,c(d)};s.addEventListener("abort",p),u.push(()=>{try{s.removeEventListener?.("abort",p)}catch{}})}})};globalThis&&typeof globalThis.fetch!="function"&&(globalThis.fetch=A);function qe(t){return`https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=${encodeURIComponent(t)}`}function oe(t){if(typeof window<"u"){window.open(t,"_blank");return}globalThis.plus?.runtime?.openURL?.(t)}async function We(t){if(t.kind!=="alipay_miniprogram")throw new Error("requestPayment: invalid payParams for alipay miniprogram");await new Promise((e,r)=>{let a=globalThis.my;if(!a?.tradePay){r(new Error("requestPayment: my.tradePay is unavailable"));return}a.tradePay({tradeNO:t.tradeNO,success:()=>e(),fail:i=>r(i)})})}async function Fe(t){if(t.kind!=="wechat_jsapi")throw new Error("requestPayment: invalid payParams for wechat jsapi");let e=t.jsapiPayParams;await new Promise((r,a)=>{uni.requestPayment({provider:"wxpay",timeStamp:e.timeStamp,nonceStr:e.nonceStr,package:e.package,signType:e.signType??"RSA",paySign:e.paySign,success:()=>r(),fail:i=>a(i)})})}function De(t){if(t.kind!=="redirect_url")throw new Error("requestPayment: invalid payParams for redirect");typeof window<"u"?window.location.href=t.redirectUrl:oe(t.redirectUrl)}function Ge(t){if(t.kind!=="wechat_native_qr")throw new Error("requestPayment: invalid payParams for wechat qr");let e=qe(t.codeUrl);oe(e)}function Be(t){if(t.kind!=="alipay_page")throw new Error("requestPayment: invalid payParams for alipay page");if(typeof document>"u"||!document.body)throw new Error("requestPayment: alipay_page (formHtml) requires a browser/WebView environment (e.g. H5 or App webview)");let e=t.formHtml,i=new DOMParser().parseFromString(e,"text/html").querySelector("form");if(!i)throw new Error("requestPayment: alipay_page formHtml does not contain a form element");let n=document.importNode(i,!0);n.setAttribute("style","display:none"),document.body.appendChild(n),n.submit()}async function Je(t){if(!t)return!1;switch(t.kind){case"alipay_miniprogram":return await We(t),!0;case"alipay_page":return Be(t),!0;case"wechat_jsapi":return await Fe(t),!0;case"redirect_url":return De(t),!0;case"wechat_native_qr":return Ge(t),!0;default:return!1}}var R={async requestPayment(t,e){try{let r=re(t);if(!await Je(r))throw new Error("requestPayment: unsupported payParams for current endpoint");e?.onSuccess?.()}catch(r){throw e?.onFailure?.(r),r}}};function le(t){let e=async r=>await ae(t,r);return{...R,getAvailableProviders:e,getProviders:e}}function ze(){if(typeof window>"u"||window===window.parent)return;let t=!1,e=new ee;function r(s){if(!s)return!1;let l=s.toLowerCase();return l.includes("/components/")||l.includes("\\components\\")}function a(s){let l=s,u=null;for(;l;){let m=l.getAttribute("data-source-location");if(m)if(r(m)){u||(u=m),l=l.parentElement;continue}else return m;l=l.parentElement}return u}let i=null;function n(s){t&&(i!==null&&cancelAnimationFrame(i),i=requestAnimationFrame(()=>{let l=s.target;if(!l||l===document.body||l===document.documentElement){e.removeHighlight();return}if(l.tagName.toLowerCase()==="img"){let d=a(l);e.highlightElement(l,d);let f={type:"HOVER_INSPECTOR_ELEMENT_HOVER",sourceLocation:d,elementInfo:{tagName:l.tagName.toLowerCase(),className:l.className||"",id:l.id||""}};window.parent.postMessage(f,"*");return}let u=l,m=a(l);if(!m){let d=l.parentElement;for(;d&&d!==document.body&&d!==document.documentElement;){let f=a(d);if(f){u=d,m=f;break}d=d.parentElement}}e.highlightElement(u,m);let p={type:"HOVER_INSPECTOR_ELEMENT_HOVER",sourceLocation:m,elementInfo:{tagName:u.tagName.toLowerCase(),className:u.className||"",id:u.id||""}};window.parent.postMessage(p,"*")}))}function h(){if(!t)return;e.removeHighlight();let s={type:"HOVER_INSPECTOR_ELEMENT_LEAVE"};window.parent.postMessage(s,"*")}function o(s){if(!t)return;s.preventDefault(),s.stopPropagation();let l=s.target;if(!l||l===document.body||l===document.documentElement)return;let u=a(l);e.selectElement(l,u);let m={type:"HOVER_INSPECTOR_ELEMENT_SELECT",sourceLocation:u,elementInfo:{tagName:l.tagName.toLowerCase(),className:l.className||"",id:l.id||""}};window.parent.postMessage(m,"*")}function c(s){s.data?.type==="HOVER_INSPECTOR_ENABLE"?(t=!0,document.addEventListener("mousemove",n),document.addEventListener("mouseleave",h),document.addEventListener("click",o,!0)):s.data?.type==="HOVER_INSPECTOR_DISABLE"&&(t=!1,document.removeEventListener("mousemove",n),document.removeEventListener("mouseleave",h),document.removeEventListener("click",o,!0),e.removeHighlight(),e.clearSelection())}return window.addEventListener("message",c),()=>{window.removeEventListener("message",c),document.removeEventListener("mousemove",n),document.removeEventListener("mouseleave",h),document.removeEventListener("click",o,!0),e.cleanup()}}function Ke(t,e){if(!t||!t.contentWindow)throw new Error("Invalid iframe element");let r={type:"HOVER_INSPECTOR_ENABLE"};t.contentWindow.postMessage(r,e)}function Ve(t,e){if(!t||!t.contentWindow)return;let r={type:"HOVER_INSPECTOR_DISABLE"};t.contentWindow.postMessage(r,e)}function Ye(t,e,r=5e3){return new Promise((a,i)=>{if(!t||!t.contentWindow){i(new Error("Invalid iframe element"));return}let n=`source-location-${Date.now()}-${Math.random()}`,h=setTimeout(()=>{window.removeEventListener("message",o),i(new Error("Request timeout"))},r),o=s=>{s.origin===e&&s.data?.type==="GET_SOURCE_LOCATION_RESPONSE"&&s.data?.requestId===n&&(clearTimeout(h),window.removeEventListener("message",o),s.data.error?i(new Error(s.data.error)):a(s.data.sourceLocation||null))};window.addEventListener("message",o);let c={type:"GET_SOURCE_LOCATION_REQUEST",requestId:n};try{t.contentWindow.postMessage(c,e)}catch(s){clearTimeout(h),window.removeEventListener("message",o),i(s)}})}function Qe(){if(typeof window>"u"||window===window.parent)return;let t=e=>{if(e.data?.type==="GET_SOURCE_LOCATION_REQUEST")try{let a={type:"GET_SOURCE_LOCATION_RESPONSE",sourceLocation:Xe(),requestId:e.data.requestId};window.parent.postMessage(a,e.origin)}catch(r){let a={type:"GET_SOURCE_LOCATION_RESPONSE",sourceLocation:null,error:r instanceof Error?r.message:"Unknown error",requestId:e.data.requestId};window.parent.postMessage(a,e.origin)}};return window.addEventListener("message",t),()=>{window.removeEventListener("message",t)}}function Xe(){return te("app")}function Ze(t){let e=t==="wechat-miniprogram"?"weixin":t==="alipay-miniprogram"?"alipay":t==="douyin-miniprogram"?"toutiao":void 0;return e?new Promise((r,a)=>{uni.login({provider:e,success:i=>{if(!i.code?.trim()){a(new Error(`login code missing for ${t}`));return}r(i.code.trim())},fail:i=>{a(i instanceof Error?i:new Error(`uni.login failed: ${String(i)}`))}})}):Promise.reject(new Error(`unsupported miniprogram provider: ${t}`))}async function et(t,e){return e??await t.getSocialProviderDescriptors()}function he(t){return t?.trim()?t.trim():typeof globalThis<"u"&&"location"in globalThis?globalThis.location.href:""}function tt(t){let{name:e="NvwaSocialLoginButtons",auth:r,applicationCode:a,providers:i,containerClass:n="nvwa-social-login-list",providerClass:h="nvwa-social-login-button"}=t,o=t.resolveMiniProgramCode??Ze;return{name:e,data(){return{providers:[],loading:!0}},async created(){try{this.providers=await et(r,i)}catch(c){t.onError?.(c instanceof Error?c:new Error(String(c)))}finally{this.loading=!1}},methods:{async handleProviderTap(c){try{if(t.onBeforeLogin?.(c),c.loginKind==="wechat_miniprogram_code"||c.loginKind==="alipay_miniprogram_code"){let s=await o(c.id);await r.startSocialLogin(c.id,{miniProgramCode:s,applicationCode:a,returnUrl:he(t.returnUrl)});return}await r.startSocialLogin(c.id,{returnUrl:he(t.returnUrl),applicationCode:a})}catch(s){t.onError?.(s instanceof Error?s:new Error(String(s)))}}},render(){if(this.loading||this.providers.length===0)return null;let c=this.$createElement,s=this.providers.filter(l=>l.loginKind!=="unsupported").map(l=>c("button",{key:l.id,class:h,attrs:{type:"button"},on:{click:()=>this.handleProviderTap(l)}},l.name));return c("view",{class:n},s)}}}var j=new _,$=class{constructor(e){this.payment=R;let{handleUnauthorized:r,appConfig:a,integrationProviders:i}=e,n=se(a);typeof console<"u"&&console.warn("[Nvwa] uniapp init baseUrl:",n.baseUrl||"(empty)"),this.applicationCode=n.applicationCode,this.platformType=n.platformType,this.integrationProviders=N(i??ne(a)),this.auth=new V(n.baseUrl,{fetchImpl:A,storage:j,integrationProviders:this.integrationProviders,applicationCode:this.applicationCode,platformType:n.platformType}),this.httpClient=new Y(j,A,r),this.fileStorage=new Q(n.baseUrl,this.httpClient),this.entities=Z(n.baseUrl,this.httpClient),this.functions=new z(this.httpClient,n.baseUrl);let h=le(this.integrationProviders);this.payment={...h,collectPaymentClientContext:()=>ie({platformType:this.platformType,getMiniProgramIdentity:()=>this.auth.getMiniProgramIdentity()})}}};0&&(module.exports={createSocialLoginComponent,disableIframeHoverInspector,enableIframeHoverInspector,getIframeSourceLocation,localStorage,setupIframeHoverInspector,setupIframeSourceLocationListener});
package/dist/index.mjs CHANGED
@@ -1,7 +1,7 @@
1
- var w=class F{constructor(e){if(this.headerMap=new Map,e){if(e instanceof F)e.forEach((r,i)=>this.set(i,r));else if(Array.isArray(e))for(let[r,i]of e)this.set(r,String(i));else if(typeof e=="object")for(let r of Object.keys(e))this.set(r,String(e[r]))}}append(e,r){let i=e.toLowerCase(),a=this.headerMap.get(i);this.headerMap.set(i,a?`${a}, ${r}`:r)}set(e,r){this.headerMap.set(e.toLowerCase(),String(r))}get(e){return this.headerMap.get(e.toLowerCase())??null}has(e){return this.headerMap.has(e.toLowerCase())}delete(e){this.headerMap.delete(e.toLowerCase())}forEach(e){for(let[r,i]of this.headerMap.entries())e(i,r,this)}entries(){return this.headerMap.entries()}keys(){return this.headerMap.keys()}values(){return this.headerMap.values()}[Symbol.iterator](){return this.entries()}},he=class D{constructor(e){if(this.params=new Map,e){if(typeof e=="string")this.parseString(e);else if(e instanceof D)this.params=new Map(e.params);else if(Array.isArray(e))for(let[r,i]of e)this.append(r,i);else if(e&&typeof e=="object")for(let[r,i]of Object.entries(e))this.set(r,i)}}parseString(e){e.startsWith("?")&&(e=e.slice(1));let r=e.split("&");for(let i of r)if(i){let[a,n]=i.split("=");a&&this.append(decodeURIComponent(a),n?decodeURIComponent(n):"")}}append(e,r){let i=this.params.get(e)||[];i.push(r),this.params.set(e,i)}delete(e){this.params.delete(e)}get(e){let r=this.params.get(e);return r?r[0]:null}getAll(e){return this.params.get(e)||[]}has(e){return this.params.has(e)}set(e,r){this.params.set(e,[r])}sort(){let e=Array.from(this.params.entries()).sort(([r],[i])=>r.localeCompare(i));this.params=new Map(e)}toString(){let e=[];for(let[r,i]of this.params.entries())for(let a of i)e.push(`${encodeURIComponent(r)}=${encodeURIComponent(a)}`);return e.join("&")}forEach(e){for(let[r,i]of this.params.entries())for(let a of i)e(a,r,this)}keys(){return this.params.keys()}values(){let e=[];for(let r of this.params.values())e.push(...r);return e[Symbol.iterator]()}entries(){let e=[];for(let[r,i]of this.params.entries())for(let a of i)e.push([r,a]);return e[Symbol.iterator]()}[Symbol.iterator](){return this.entries()}get size(){return this.params.size}},U=class k{constructor(e,r){let i;if(e instanceof k)i=e.href;else if(r){let n=r instanceof k?r.href:r;i=this.resolve(n,e)}else i=e;let a=this.parseUrl(i);this.href=i,this.origin=`${a.protocol}//${a.host}`,this.protocol=a.protocol,this.username=a.username,this.password=a.password,this.host=a.host,this.hostname=a.hostname,this.port=a.port,this.pathname=a.pathname,this.search=a.search,this.searchParams=new he(a.search),this.hash=a.hash}resolve(e,r){if(r.startsWith("http://")||r.startsWith("https://"))return r;if(r.startsWith("//"))return`${this.parseUrl(e).protocol}${r}`;if(r.startsWith("/")){let n=this.parseUrl(e);return`${n.protocol}//${n.host}${r}`}let i=this.parseUrl(e),a=i.pathname.endsWith("/")?i.pathname:i.pathname+"/";return`${i.protocol}//${i.host}${a}${r}`}parseUrl(e){let r=e.match(/^(([^:\/?#]+):)?(\/\/([^\/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?$/);if(!r)throw new TypeError("Invalid URL");let i=r[2]||"",a=r[4]||"",n=r[5]||"/",h=r[7]?`?${r[7]}`:"",o=r[9]?`#${r[9]}`:"";if(!i&&!a&&!n.startsWith("/")&&!n.includes("/")&&!n.includes("."))throw new TypeError("Invalid URL");let c=a.match(/^([^@]*)@(.+)$/),s="",l="",u=a;if(c){let f=c[1];u=c[2];let y=f.match(/^([^:]*):?(.*)$/);y&&(s=y[1]||"",l=y[2]||"")}let m=u.match(/^([^:]+):?(\d*)$/),p=m?m[1]:u,d=m&&m[2]?m[2]:"";return{protocol:i?`${i}:`:"",username:s,password:l,host:u,hostname:p,port:d,pathname:n,search:h,hash:o}}toString(){let e=this.searchParams.toString(),r=e?`?${e}`:"";return`${this.protocol}//${this.host}${this.pathname}${r}${this.hash}`}toJSON(){return this.toString()}};var G=class{constructor(t,e){this.bodyData=t,this.status=e?.status??200,this.statusText=e?.statusText??"",this.headers=ce(e?.headers),this.ok=this.status>=200&&this.status<300}async text(){return typeof this.bodyData=="string"?this.bodyData:this.bodyData==null?"":typeof this.bodyData=="object"?JSON.stringify(this.bodyData):String(this.bodyData)}async json(){if(typeof this.bodyData=="string")try{return JSON.parse(this.bodyData)}catch{}return this.bodyData}async arrayBuffer(){let t=await this.text();return new TextEncoder().encode(t).buffer}};function ce(t){return t?new w(t):new w}var ue=class{constructor(){this._aborted=!1,this.listeners=new Set,this.onabort=null}get aborted(){return this._aborted}_trigger(){if(!this._aborted){if(this._aborted=!0,typeof this.onabort=="function")try{this.onabort()}catch{}for(let t of Array.from(this.listeners))try{t()}catch{}this.listeners.clear()}}addEventListener(t,e){if(this._aborted){try{e()}catch{}return}this.listeners.add(e)}removeEventListener(t,e){this.listeners.delete(e)}toString(){return"[object AbortSignal]"}},pe=class{constructor(){this._signal=new ue}get signal(){return this._signal}abort(){this._signal._trigger()}toString(){return"[object AbortController]"}};function de(t){if(t!==void 0)return typeof t=="string"||t instanceof FormData||t instanceof Blob||t instanceof File||t instanceof ArrayBuffer||ArrayBuffer.isView(t)||typeof ReadableStream<"u"&&t instanceof ReadableStream?t:typeof t=="object"&&t!==null?JSON.stringify(t):t}var B=class{constructor(t,e=""){this.http=t,this.baseUrl=e.replace(/\/$/,"")}async invoke(t,e){let r=this.baseUrl?`${this.baseUrl}/functions/${t}`:`/functions/${t}`;return await(await this.http.fetchWithAuth(r,{method:e.method||"POST",body:de(e.body),headers:e.headers})).json()}},g="nvwa_current_jwt",v="nvwa_login_token",b="nvwa_user_profile",me="set-auth-token",ge=typeof fetch<"u"?(t,e)=>fetch(t,e):()=>{throw new Error("AuthClient requires fetch")},J={google:{id:"google",name:"Google Login",description:"Sign in with Google account."},github:{id:"github",name:"GitHub Login",description:"Sign in with GitHub account."},"wechat-website":{id:"wechat-website",name:"WeChat QR Login",description:"Sign in with WeChat website QR code."},"wechat-miniprogram":{id:"wechat-miniprogram",name:"WeChat Mini Program Login",description:"Sign in with WeChat mini program code."},"alipay-miniprogram":{id:"alipay-miniprogram",name:"Alipay Mini Program Login",description:"Sign in with Alipay mini program code."},"douyin-miniprogram":{id:"douyin-miniprogram",name:"Douyin Mini Program Login",description:"Sign in with Douyin mini program code."}};function j(t){let e=J[t]??{id:t,name:t,description:""},r="unsupported";switch(t){case"google":r="google_openplatform";break;case"github":r="github_openplatform";break;case"wechat-website":r="wechat_website_openplatform";break;case"wechat-miniprogram":r="wechat_miniprogram_code";break;case"alipay-miniprogram":r="alipay_miniprogram_code";break;case"douyin-miniprogram":r="douyin_miniprogram_code";break;default:break}return{id:e.id,type:e.id,name:e.name,description:e.description,loginKind:r}}function M(t,e){let r=t.socialLogin?.providers?.[e];return r?.enabled?r.oauthCredentialSource==="custom"?"custom":"nvwa_default":null}var z=class{constructor(t,e={}){this.baseUrl=t.replace(/\/$/,""),this.authPath=(e.authPath??"/auth").replace(/^\//,""),this.fetchImpl=e.fetchImpl??ge,this.storage=e.storage??null,this.credentials=e.credentials??"omit",this.integrationProviders=e.integrationProviders??{},this.defaultApplicationCode=e.applicationCode?.trim()||null,this.platformType=e.platformType,typeof console<"u"&&(console.warn("[NvwaAuth] init baseUrl:",this.baseUrl||"(empty)"),(!this.baseUrl||!this.baseUrl.startsWith("http://")&&!this.baseUrl.startsWith("https://"))&&console.warn("[NvwaAuth] baseUrl \u5E94\u4E3A\u5B8C\u6574\u5730\u5740\uFF08\u5982 https://xxx.nvwa.app\uFF09\uFF0C\u5426\u5219\u5C0F\u7A0B\u5E8F request \u4F1A\u62A5 invalid url"))}async getSocialProviders(t){let e=this.integrationProviders.socialLogin?.providers??{};return Object.entries(e).filter(([,r])=>r.enabled).map(([r])=>{let i=J[r]??{id:r,name:r,description:""};return{...i,type:i.id}})}async getSocialProviderDescriptors(t){let e=this.integrationProviders.socialLogin?.providers??{};return Object.entries(e).filter(([,r])=>!!r?.enabled).map(([r])=>j(r))}async getAvailableProviders(t){return this.getSocialProviders(t)}async startSocialLogin(t,e){let r=j(t),i=e?.applicationCode?.trim()||this.defaultApplicationCode||void 0,a=e?.returnUrl??(typeof globalThis<"u"&&"location"in globalThis?globalThis.location.href:"");switch(r.loginKind){case"google_openplatform":if(!a)throw new Error("startSocialLogin requires returnUrl for google");this.startGoogleOpenPlatformLogin(a,{applicationCode:i,platformCode:e?.platformCode});return;case"github_openplatform":if(!a)throw new Error("startSocialLogin requires returnUrl for github");this.startGithubOpenPlatformLogin(a,{applicationCode:i,platformCode:e?.platformCode});return;case"wechat_website_openplatform":if(!a)throw new Error("startSocialLogin requires returnUrl for wechat-website");this.startWechatWebsiteOpenPlatformLogin(a);return;case"wechat_miniprogram_code":if(!e?.miniProgramCode?.trim()||!i)throw new Error("startSocialLogin requires miniProgramCode and applicationCode for wechat-miniprogram");await this.loginWithWeChatCode(e.miniProgramCode.trim(),i);return;case"alipay_miniprogram_code":if(!e?.miniProgramCode?.trim()||!i)throw new Error("startSocialLogin requires miniProgramCode and applicationCode for alipay-miniprogram");await this.loginWithAlipayCode(e.miniProgramCode.trim(),i);return;case"douyin_miniprogram_code":throw new Error("startSocialLogin does not support douyin-miniprogram yet");default:throw new Error(`startSocialLogin unsupported provider: ${t}`)}}async currentUser(){if(this.storage){let r=await this.storage.get(b);if(r!=null)return r}let{data:t}=await this.getSession(),e=t?.user??null;return e&&this.storage&&await this.storage.set(b,e),e}async getCurrentJwt(){if(this.storage){let e=await this.storage.get(g);if(e!=null)return e;let r=await this.storage.get(v),{data:i}=await this.getToken(r??void 0);return i?.token?(await this.storage.set(g,i.token),i.token):null}let{data:t}=await this.getToken();return t?.token??null}async persistLogin(t,e){if(!this.storage)return;let r=e?.headers.get(me)?.trim()||t.token||t.session?.token;r&&await this.storage.set(v,r),t.user&&await this.storage.set(b,t.user);let i=r??await this.storage.get(v),{data:a}=await this.getToken(i??void 0);a?.token&&await this.storage.set(g,a.token)}async clearLogin(){this.storage&&(await this.storage.remove(v),await this.storage.remove(b),await this.storage.remove(g))}getGoogleOpenPlatformLoginUrl(t,e){let r=new URLSearchParams({return_url:t}),i=e?.applicationCode?.trim()||this.defaultApplicationCode||"";i&&r.set("application_code",i);let a=e?.platformCode?.trim()??"";a&&r.set("platform_code",a);let n=M(this.integrationProviders,"google");return n&&r.set("oauth_credential_source",n),`${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 n=await this.storage.get(g);n!=null&&(e.Authorization=`Bearer ${n}`)}let r=await this.fetchImpl(this.url("google/openplatform/sign-in"),{method:"POST",headers:e,credentials:this.credentials,body:JSON.stringify({exchangeCode:t})}),i=await r.text();if(!r.ok)return{error:{message:i||r.statusText,status:r.status}};let a=i?JSON.parse(i):null;return!a?.token||!a.user?{error:{message:"invalid_google_login_response",status:502}}:(this.storage&&(await this.storage.set(g,a.token),await this.storage.set(v,a.token),await this.storage.set(b,a.user)),{data:a})}catch(e){return{error:{message:e instanceof Error?e.message:String(e),status:0}}}}async getGoogleOpenPlatformIdentity(){try{let t={};if(this.storage){let a=await this.storage.get(g);a!=null&&(t.Authorization=`Bearer ${a}`)}let e=await this.fetchImpl(this.url("google/openplatform/identity"),{method:"GET",credentials:this.credentials,...Object.keys(t).length?{headers:t}:{}}),r=await e.text();if(!e.ok)return{error:{message:r||e.statusText,status:e.status}};let i=r?JSON.parse(r):null;return i?.sub?{data:i}:{error:{message:"invalid_google_identity_response",status:502}}}catch(t){return{error:{message:t instanceof Error?t.message:String(t),status:0}}}}getGithubOpenPlatformLoginUrl(t,e){let r=new URLSearchParams({return_url:t}),i=e?.applicationCode?.trim()||this.defaultApplicationCode||"";i&&r.set("application_code",i);let a=e?.platformCode?.trim()??"";a&&r.set("platform_code",a);let n=M(this.integrationProviders,"github");return n&&r.set("oauth_credential_source",n),`${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 n=await this.storage.get(g);n!=null&&(e.Authorization=`Bearer ${n}`)}let r=await this.fetchImpl(this.url("github/openplatform/sign-in"),{method:"POST",headers:e,credentials:this.credentials,body:JSON.stringify({exchangeCode:t})}),i=await r.text();if(!r.ok)return{error:{message:i||r.statusText,status:r.status}};let a=i?JSON.parse(i):null;return!a?.token||!a.user?{error:{message:"invalid_github_login_response",status:502}}:(this.storage&&(await this.storage.set(g,a.token),await this.storage.set(v,a.token),await this.storage.set(b,a.user)),{data:a})}catch(e){return{error:{message:e instanceof Error?e.message:String(e),status:0}}}}async getGithubOpenPlatformIdentity(){try{let t={};if(this.storage){let a=await this.storage.get(g);a!=null&&(t.Authorization=`Bearer ${a}`)}let e=await this.fetchImpl(this.url("github/openplatform/identity"),{method:"GET",credentials:this.credentials,...Object.keys(t).length?{headers:t}:{}}),r=await e.text();if(!e.ok)return{error:{message:r||e.statusText,status:e.status}};let i=r?JSON.parse(r):null;return i?.sub?{data:i}:{error:{message:"invalid_github_identity_response",status:502}}}catch(t){return{error:{message:t instanceof Error?t.message:String(t),status:0}}}}getWechatWebsiteOpenPlatformLoginUrl(t){let e=new URLSearchParams({return_url:t});return`${this.url("wechat-website/openplatform/login")}?${e.toString()}`}startWechatWebsiteOpenPlatformLogin(t){let e=this.getWechatWebsiteOpenPlatformLoginUrl(t);if(typeof globalThis<"u"&&"location"in globalThis){globalThis.location.href=e;return}throw new Error("startWechatWebsiteOpenPlatformLogin requires a browser environment with location")}async completeWechatWebsiteOpenPlatformLoginFromCurrentUrl(t){let e;if(t!=null&&t!=="")e=t;else if(typeof globalThis<"u"&&"location"in globalThis)e=globalThis.location.href;else return{error:{message:"completeWechatWebsiteOpenPlatformLoginFromCurrentUrl requires url or browser location",status:0}};let r;try{r=new URL(e).searchParams.get("exchange_code")}catch{return{error:{message:"invalid_callback_url",status:400}}}return r?.trim()?await this.loginWithWechatWebsiteExchangeCode(r.trim()):{error:{message:"missing_exchange_code",status:400}}}async loginWithWechatWebsiteExchangeCode(t){try{let e={"Content-Type":"application/json"};if(this.storage){let n=await this.storage.get(g);n!=null&&(e.Authorization=`Bearer ${n}`)}let r=await this.fetchImpl(this.url("wechat-website/openplatform/sign-in"),{method:"POST",headers:e,credentials:this.credentials,body:JSON.stringify({exchangeCode:t})}),i=await r.text();if(!r.ok)return{error:{message:i||r.statusText,status:r.status}};let a=i?JSON.parse(i):null;return!a?.token||!a.user?{error:{message:"invalid_wechat_website_login_response",status:502}}:(this.storage&&(await this.storage.set(g,a.token),await this.storage.set(v,a.token),await this.storage.set(b,a.user)),{data:a})}catch(e){return{error:{message:e instanceof Error?e.message:String(e),status:0}}}}async getWechatWebsiteOpenPlatformIdentity(){try{let t={};if(this.storage){let a=await this.storage.get(g);a!=null&&(t.Authorization=`Bearer ${a}`)}let e=await this.fetchImpl(this.url("wechat-website/openplatform/identity"),{method:"GET",credentials:this.credentials,...Object.keys(t).length?{headers:t}:{}}),r=await e.text();if(!e.ok)return{error:{message:r||e.statusText,status:e.status}};let i=r?JSON.parse(r):null;return i?.sub?{data:i}:{error:{message:"invalid_wechat_website_identity_response",status:502}}}catch(t){return{error:{message:t instanceof Error?t.message:String(t),status:0}}}}url(t){let e=`${`${this.baseUrl.replace(/\/+$/,"")}/${this.authPath.replace(/^\/+/,"")}`}/${t.replace(/^\/+/,"")}`;return typeof console<"u"&&(console.warn("[NvwaAuth] request URL:",e),!e.startsWith("http://")&&!e.startsWith("https://")&&console.warn("[NvwaAuth] URL \u975E\u5B8C\u6574\u5730\u5740\uFF0C\u5C0F\u7A0B\u5E8F\u4F1A\u62A5 invalid url\uFF0C\u8BF7\u68C0\u67E5 Nvwa \u6784\u9020\u65F6\u4F20\u5165\u7684 baseUrl")),e}async getSession(){try{let t={};if(this.storage){let r=await this.storage.get(v)??await this.storage.get(g);r!=null&&(t.Authorization=`Bearer ${r}`)}let e=await this.fetchImpl(this.url("session"),{method:"GET",credentials:this.credentials,...Object.keys(t).length?{headers:t}:{}});return e.ok?{data:await e.json()}:{data:null,error:{message:await e.text()||e.statusText,status:e.status}}}catch(t){return{data:null,error:{message:t instanceof Error?t.message:String(t),status:0}}}}async signInWithEmail(t,e){try{let r=await this.fetchImpl(this.url("sign-in/email"),{method:"POST",headers:{"Content-Type":"application/json"},credentials:this.credentials,body:JSON.stringify({email:t,password:e})}),i=await r.text();if(!r.ok)return{error:{message:i||r.statusText,status:r.status}};let a=i?JSON.parse(i):void 0;return a&&await this.persistLogin({user:a.user,session:a.session},r),{data:a}}catch(r){return{error:{message:r instanceof Error?r.message:String(r),status:0}}}}async signOut(){try{let t={"Content-Type":"application/json"};if(this.storage){let r=await this.storage.get(v)??await this.storage.get(g);r!=null&&(t.Authorization=`Bearer ${r}`)}await this.clearLogin();let e=await this.fetchImpl(this.url("sign-out"),{method:"POST",credentials:this.credentials,headers:t,body:"{}"});return e.ok?{}:{error:{message:await e.text()||e.statusText,status:e.status}}}catch(t){return{error:{message:t instanceof Error?t.message:String(t),status:0}}}}async signUp(t){let e=await this.postJson("sign-up/email",t);return e.data&&await this.persistLogin(e.data,e.response),e}async getToken(t){try{let e={};if(t)e.Authorization=`Bearer ${t}`;else if(this.storage){let n=await this.storage.get(v)??await this.storage.get(g);n!=null&&(e.Authorization=`Bearer ${n}`)}let r=await this.fetchImpl(this.url("token"),{method:"GET",credentials:this.credentials,...Object.keys(e).length?{headers:e}:{}}),i=await r.text();if(!r.ok)return{error:{message:i||r.statusText,status:r.status}};let a=i?JSON.parse(i):void 0;return{data:a?.token!=null?{token:a.token}:void 0}}catch(e){return{error:{message:e instanceof Error?e.message:String(e),status:0}}}}async signInWithUsername(t,e){let r=await this.postJson("sign-in/username",{username:t,password:e});return r.data&&await this.persistLogin(r.data,r.response),r}async signInWithPhoneNumber(t,e,r){let i=await this.postJson("sign-in/phone-number",{phoneNumber:t,password:e,rememberMe:r});return i.data&&await this.persistLogin(i.data,i.response),i}async sendPhoneNumberOtp(t){let e=await this.postJson("phone-number/send-otp",{phoneNumber:t});return e.error?{error:e.error}:{}}async verifyPhoneNumber(t,e){let r=await this.postJson("phone-number/verify",{phoneNumber:t,code:e});return r.data&&await this.persistLogin(r.data,r.response),r}async loginWithWeChatCode(t,e){try{let r={"Content-Type":"application/json"};if(this.storage){let h=await this.storage.get(g);h!=null&&(r.Authorization=`Bearer ${h}`)}let i=await this.fetchImpl(this.url("wechat/openplatform/sign-in"),{method:"POST",headers:r,credentials:this.credentials,body:JSON.stringify({code:t,applicationCode:e})}),a=await i.text();if(!i.ok)return{error:{message:a||i.statusText,status:i.status}};let n=a?JSON.parse(a):null;return!n?.token||!n.user?{error:{message:"invalid_wechat_login_response",status:502}}:(this.storage&&(await this.storage.set(g,n.token),await this.storage.set(v,n.token),await this.storage.set(b,n.user)),{data:n})}catch(r){return{error:{message:r instanceof Error?r.message:String(r),status:0}}}}async loginWithAlipayCode(t,e){try{let r={"Content-Type":"application/json"};if(this.storage){let h=await this.storage.get(g);h!=null&&(r.Authorization=`Bearer ${h}`)}let i=await this.fetchImpl(this.url("alipay/openplatform/sign-in"),{method:"POST",headers:r,credentials:this.credentials,body:JSON.stringify({code:t,applicationCode:e})}),a=await i.text();if(!i.ok)return{error:{message:a||i.statusText,status:i.status}};let n=a?JSON.parse(a):null;return!n?.token||!n.user?{error:{message:"invalid_alipay_login_response",status:502}}:(this.storage&&(await this.storage.set(g,n.token),await this.storage.set(v,n.token),await this.storage.set(b,n.user)),{data:n})}catch(r){return{error:{message:r instanceof Error?r.message:String(r),status:0}}}}async getWeChatOpenPlatformIdentity(t){try{let e={};if(this.storage){let h=await this.storage.get(g);h!=null&&(e.Authorization=`Bearer ${h}`)}let r=t?.trim()?`?applicationCode=${encodeURIComponent(t.trim())}`:"",i=await this.fetchImpl(this.url(`wechat/openplatform/identity${r}`),{method:"GET",credentials:this.credentials,...Object.keys(e).length?{headers:e}:{}}),a=await i.text();if(!i.ok)return{error:{message:a||i.statusText,status:i.status}};let n=a?JSON.parse(a):null;return!n?.openid||!n.appId?{error:{message:"invalid_wechat_identity_response",status:502}}:{data:n}}catch(e){return{error:{message:e instanceof Error?e.message:String(e),status:0}}}}async getAlipayOpenPlatformIdentity(t){try{let e={};if(this.storage){let h=await this.storage.get(g);h!=null&&(e.Authorization=`Bearer ${h}`)}let r=t?.trim()?`?applicationCode=${encodeURIComponent(t.trim())}`:"",i=await this.fetchImpl(this.url(`alipay/openplatform/identity${r}`),{method:"GET",credentials:this.credentials,...Object.keys(e).length?{headers:e}:{}}),a=await i.text();if(!i.ok)return{error:{message:a||i.statusText,status:i.status}};let n=a?JSON.parse(a):null;return!n?.openid||!n.appId?{error:{message:"invalid_alipay_identity_response",status:502}}:{data:n}}catch(e){return{error:{message:e instanceof Error?e.message:String(e),status:0}}}}async getMiniProgramIdentity(t){let e=t?.applicationCode?.trim()||this.defaultApplicationCode||void 0;if(this.platformType==="WechatMiniProgram"){let r=await this.getWeChatOpenPlatformIdentity(e);if(!r.data)throw new Error(r.error?.message||"failed to get wechat open platform identity");return{platformType:this.platformType,appId:r.data.appId,platformUserId:r.data.openid,unionid:r.data.unionid}}else if(this.platformType==="AlipayMiniProgram"){let r=await this.getAlipayOpenPlatformIdentity(e);if(!r.data)throw new Error(r.error?.message||"failed to get wechat open platform identity");return{platformType:this.platformType,appId:r.data.appId,platformUserId:r.data.openid,unionid:r.data.unionid}}return null}async postJson(t,e){try{let r=await this.fetchImpl(this.url(t),{method:"POST",headers:{"Content-Type":"application/json"},credentials:this.credentials,body:JSON.stringify(e)}),i=await r.text();if(!r.ok)return{error:{message:i||r.statusText,status:r.status}};let a=i?JSON.parse(i):void 0;return{data:a?.data??a??void 0,response:r}}catch(r){return{error:{message:r instanceof Error?r.message:String(r),status:0}}}}},K=class{constructor(t,e,r){this.storage=t,this.customFetch=e,this.handleUnauthorized=r}async fetch(t,e){return await this.customFetch(t,e)}async fetchWithAuth(t,e){let r=await this.storage.get(g),i=new w(e?.headers);r&&i.set("Authorization",`Bearer ${r}`);let a=e?.method||"GET";if((a==="POST"||a==="PUT"||a==="PATCH")&&e?.body){let h=i.get("Content-Type");(!h||h.includes("text/plain"))&&i.set("Content-Type","application/json")}let n=await this.customFetch(t,{...e,headers:i});if(n.status===401)throw this.handleUnauthorized(),new Error("\u672A\u767B\u5F55");return n}},fe="/storage",ye=fe+"/generateUploadUrl",V=class{constructor(t,e){this.baseUrl=t,this.http=e}async uploadFile(t){let e=await this.http.fetch(this.baseUrl+ye,{method:"POST",body:{fileName:t.name||t.fileName,fileSize:t.size||t.fileSize,fileType:t.type||t.fileType}}),{url:r}=await e.json();if(!r)throw new Error("\u83B7\u53D6\u4E0A\u4F20URL\u5931\u8D25");let i=await this.http.fetch(r,{method:"PUT",body:t,headers:new w({"Content-Type":t.type||t.fileType||"application/octet-stream"})}),{url:a}=await i.json();return{url:a.split("?")[0]}}},we=class extends Error{constructor(t){super(t.message),this.name="PostgrestError",this.details=t.details,this.hint=t.hint,this.code=t.code}},ve=class{constructor(t){var e,r,i;this.shouldThrowOnError=!1,this.method=t.method,this.url=t.url,this.headers=new w(t.headers),this.schema=t.schema,this.body=t.body,this.shouldThrowOnError=(e=t.shouldThrowOnError)!==null&&e!==void 0?e:!1,this.signal=t.signal,this.isMaybeSingle=(r=t.isMaybeSingle)!==null&&r!==void 0?r:!1,this.urlLengthLimit=(i=t.urlLengthLimit)!==null&&i!==void 0?i:8e3,t.fetch?this.fetch=t.fetch:this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(t,e){return this.headers=new w(this.headers),this.headers.set(t,e),this}then(t,e){var r=this;this.schema===void 0||(["GET","HEAD"].includes(this.method)?this.headers.set("Accept-Profile",this.schema):this.headers.set("Content-Profile",this.schema)),this.method!=="GET"&&this.method!=="HEAD"&&this.headers.set("Content-Type","application/json");let i=this.fetch,a=i(this.url.toString(),{method:this.method,headers:this.headers,body:JSON.stringify(this.body),signal:this.signal}).then(async n=>{let h=null,o=null,c=null,s=n.status,l=n.statusText;if(n.ok){var u,m;if(r.method!=="HEAD"){var p;let y=await n.text();y===""||(r.headers.get("Accept")==="text/csv"||r.headers.get("Accept")&&!((p=r.headers.get("Accept"))===null||p===void 0)&&p.includes("application/vnd.pgrst.plan+text")?o=y:o=JSON.parse(y))}let d=(u=r.headers.get("Prefer"))===null||u===void 0?void 0:u.match(/count=(exact|planned|estimated)/),f=(m=n.headers.get("content-range"))===null||m===void 0?void 0:m.split("/");d&&f&&f.length>1&&(c=parseInt(f[1])),r.isMaybeSingle&&Array.isArray(o)&&(o.length>1?(h={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,s=406,l="Not Acceptable"):o.length===1?o=o[0]:o=null)}else{let d=await n.text();try{h=JSON.parse(d),Array.isArray(h)&&n.status===404&&(o=[],h=null,s=200,l="OK")}catch{n.status===404&&d===""?(s=204,l="No Content"):h={message:d}}if(h&&r.shouldThrowOnError)throw new we(h)}return{error:h,data:o,count:c,status:s,statusText:l}});return this.shouldThrowOnError||(a=a.catch(n=>{var h;let o="",c="",s="",l=n?.cause;if(l){var u,m,p,d;let L=(u=l?.message)!==null&&u!==void 0?u:"",C=(m=l?.code)!==null&&m!==void 0?m:"";o=`${(p=n?.name)!==null&&p!==void 0?p:"FetchError"}: ${n?.message}`,o+=`
1
+ var w=class D{constructor(e){if(this.headerMap=new Map,e){if(e instanceof D)e.forEach((r,a)=>this.set(a,r));else if(Array.isArray(e))for(let[r,a]of e)this.set(r,String(a));else if(typeof e=="object")for(let r of Object.keys(e))this.set(r,String(e[r]))}}append(e,r){let a=e.toLowerCase(),i=this.headerMap.get(a);this.headerMap.set(a,i?`${i}, ${r}`:r)}set(e,r){this.headerMap.set(e.toLowerCase(),String(r))}get(e){return this.headerMap.get(e.toLowerCase())??null}has(e){return this.headerMap.has(e.toLowerCase())}delete(e){this.headerMap.delete(e.toLowerCase())}forEach(e){for(let[r,a]of this.headerMap.entries())e(a,r,this)}entries(){return this.headerMap.entries()}keys(){return this.headerMap.keys()}values(){return this.headerMap.values()}[Symbol.iterator](){return this.entries()}},ce=class G{constructor(e){if(this.params=new Map,e){if(typeof e=="string")this.parseString(e);else if(e instanceof G)this.params=new Map(e.params);else if(Array.isArray(e))for(let[r,a]of e)this.append(r,a);else if(e&&typeof e=="object")for(let[r,a]of Object.entries(e))this.set(r,a)}}parseString(e){e.startsWith("?")&&(e=e.slice(1));let r=e.split("&");for(let a of r)if(a){let[i,n]=a.split("=");i&&this.append(decodeURIComponent(i),n?decodeURIComponent(n):"")}}append(e,r){let a=this.params.get(e)||[];a.push(r),this.params.set(e,a)}delete(e){this.params.delete(e)}get(e){let r=this.params.get(e);return r?r[0]:null}getAll(e){return this.params.get(e)||[]}has(e){return this.params.has(e)}set(e,r){this.params.set(e,[r])}sort(){let e=Array.from(this.params.entries()).sort(([r],[a])=>r.localeCompare(a));this.params=new Map(e)}toString(){let e=[];for(let[r,a]of this.params.entries())for(let i of a)e.push(`${encodeURIComponent(r)}=${encodeURIComponent(i)}`);return e.join("&")}forEach(e){for(let[r,a]of this.params.entries())for(let i of a)e(i,r,this)}keys(){return this.params.keys()}values(){let e=[];for(let r of this.params.values())e.push(...r);return e[Symbol.iterator]()}entries(){let e=[];for(let[r,a]of this.params.entries())for(let i of a)e.push([r,i]);return e[Symbol.iterator]()}[Symbol.iterator](){return this.entries()}get size(){return this.params.size}},k=class U{constructor(e,r){let a;if(e instanceof U)a=e.href;else if(r){let n=r instanceof U?r.href:r;a=this.resolve(n,e)}else a=e;let i=this.parseUrl(a);this.href=a,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 ce(i.search),this.hash=i.hash}resolve(e,r){if(r.startsWith("http://")||r.startsWith("https://"))return r;if(r.startsWith("//"))return`${this.parseUrl(e).protocol}${r}`;if(r.startsWith("/")){let n=this.parseUrl(e);return`${n.protocol}//${n.host}${r}`}let a=this.parseUrl(e),i=a.pathname.endsWith("/")?a.pathname:a.pathname+"/";return`${a.protocol}//${a.host}${i}${r}`}parseUrl(e){let r=e.match(/^(([^:\/?#]+):)?(\/\/([^\/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?$/);if(!r)throw new TypeError("Invalid URL");let a=r[2]||"",i=r[4]||"",n=r[5]||"/",h=r[7]?`?${r[7]}`:"",o=r[9]?`#${r[9]}`:"";if(!a&&!i&&!n.startsWith("/")&&!n.includes("/")&&!n.includes("."))throw new TypeError("Invalid URL");let c=i.match(/^([^@]*)@(.+)$/),s="",l="",u=i;if(c){let f=c[1];u=c[2];let y=f.match(/^([^:]*):?(.*)$/);y&&(s=y[1]||"",l=y[2]||"")}let m=u.match(/^([^:]+):?(\d*)$/),p=m?m[1]:u,d=m&&m[2]?m[2]:"";return{protocol:a?`${a}:`:"",username:s,password:l,host:u,hostname:p,port:d,pathname:n,search:h,hash:o}}toString(){let e=this.searchParams.toString(),r=e?`?${e}`:"";return`${this.protocol}//${this.host}${this.pathname}${r}${this.hash}`}toJSON(){return this.toString()}};var B=class{constructor(t,e){this.bodyData=t,this.status=e?.status??200,this.statusText=e?.statusText??"",this.headers=ue(e?.headers),this.ok=this.status>=200&&this.status<300}async text(){return typeof this.bodyData=="string"?this.bodyData:this.bodyData==null?"":typeof this.bodyData=="object"?JSON.stringify(this.bodyData):String(this.bodyData)}async json(){if(typeof this.bodyData=="string")try{return JSON.parse(this.bodyData)}catch{}return this.bodyData}async arrayBuffer(){let t=await this.text();return new TextEncoder().encode(t).buffer}};function ue(t){return t?new w(t):new w}var pe=class{constructor(){this._aborted=!1,this.listeners=new Set,this.onabort=null}get aborted(){return this._aborted}_trigger(){if(!this._aborted){if(this._aborted=!0,typeof this.onabort=="function")try{this.onabort()}catch{}for(let t of Array.from(this.listeners))try{t()}catch{}this.listeners.clear()}}addEventListener(t,e){if(this._aborted){try{e()}catch{}return}this.listeners.add(e)}removeEventListener(t,e){this.listeners.delete(e)}toString(){return"[object AbortSignal]"}},de=class{constructor(){this._signal=new pe}get signal(){return this._signal}abort(){this._signal._trigger()}toString(){return"[object AbortController]"}},j=class extends Error{constructor(t,e,r){super(t),this.name="NvwaFunctionInvokeError",this.status=e,this.bodyText=r}};function me(t){if(!t||typeof t!="object")return null;let e=t;return typeof e.error=="string"&&e.error.length>0?e.error:typeof e.message=="string"&&e.message.length>0?e.message:null}function ge(t,e){let r=e.trim();if(!r)return`Request failed with status ${t}`;try{let a=JSON.parse(r);return me(a)??r}catch{return r}}function fe(t){if(t!==void 0)return typeof t=="string"||t instanceof FormData||t instanceof Blob||t instanceof File||t instanceof ArrayBuffer||ArrayBuffer.isView(t)||typeof ReadableStream<"u"&&t instanceof ReadableStream?t:typeof t=="object"&&t!==null?JSON.stringify(t):t}var J=class{constructor(t,e=""){this.http=t,this.baseUrl=e.replace(/\/$/,"")}async invoke(t,e){let r=this.baseUrl?`${this.baseUrl}/functions/${t}`:`/functions/${t}`,a=await this.http.fetchWithAuth(r,{method:e.method||"POST",body:fe(e.body),headers:e.headers});if(!a.ok){let i=await a.text();throw new j(ge(a.status,i),a.status,i)}try{return await a.json()}catch(i){let n=i instanceof Error?i.message:String(i);throw new j(`Invalid JSON in function response: ${n}`,a.status)}}},g="nvwa_current_jwt",v="nvwa_login_token",b="nvwa_user_profile",ye="set-auth-token",we=typeof fetch<"u"?(t,e)=>fetch(t,e):()=>{throw new Error("AuthClient requires fetch")},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 M(t){let e=z[t]??{id:t,name:t,description:""},r="unsupported";switch(t){case"google":r="google_openplatform";break;case"github":r="github_openplatform";break;case"wechat-website":r="wechat_website_openplatform";break;case"wechat-miniprogram":r="wechat_miniprogram_code";break;case"alipay-miniprogram":r="alipay_miniprogram_code";break;case"douyin-miniprogram":r="douyin_miniprogram_code";break;default:break}return{id:e.id,type:e.id,name:e.name,description:e.description,loginKind:r}}function H(t,e){let r=t.socialLogin?.providers?.[e];return r?.enabled?r.oauthCredentialSource==="custom"?"custom":"nvwa_default":null}var K=class{constructor(t,e={}){this.baseUrl=t.replace(/\/$/,""),this.authPath=(e.authPath??"/auth").replace(/^\//,""),this.fetchImpl=e.fetchImpl??we,this.storage=e.storage??null,this.credentials=e.credentials??"omit",this.integrationProviders=e.integrationProviders??{},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 a=z[r]??{id:r,name:r,description:""};return{...a,type:a.id}})}async getSocialProviderDescriptors(t){let e=this.integrationProviders.socialLogin?.providers??{};return Object.entries(e).filter(([,r])=>!!r?.enabled).map(([r])=>M(r))}async getAvailableProviders(t){return this.getSocialProviders(t)}async startSocialLogin(t,e){let r=M(t),a=e?.applicationCode?.trim()||this.defaultApplicationCode||void 0,i=e?.returnUrl??(typeof globalThis<"u"&&"location"in globalThis?globalThis.location.href:"");switch(r.loginKind){case"google_openplatform":if(!i)throw new Error("startSocialLogin requires returnUrl for google");this.startGoogleOpenPlatformLogin(i,{applicationCode:a,platformCode:e?.platformCode});return;case"github_openplatform":if(!i)throw new Error("startSocialLogin requires returnUrl for github");this.startGithubOpenPlatformLogin(i,{applicationCode:a,platformCode:e?.platformCode});return;case"wechat_website_openplatform":if(!i)throw new Error("startSocialLogin requires returnUrl for wechat-website");this.startWechatWebsiteOpenPlatformLogin(i);return;case"wechat_miniprogram_code":if(!e?.miniProgramCode?.trim()||!a)throw new Error("startSocialLogin requires miniProgramCode and applicationCode for wechat-miniprogram");await this.loginWithWeChatCode(e.miniProgramCode.trim(),a);return;case"alipay_miniprogram_code":if(!e?.miniProgramCode?.trim()||!a)throw new Error("startSocialLogin requires miniProgramCode and applicationCode for alipay-miniprogram");await this.loginWithAlipayCode(e.miniProgramCode.trim(),a);return;case"douyin_miniprogram_code":throw new Error("startSocialLogin does not support douyin-miniprogram yet");default:throw new Error(`startSocialLogin unsupported provider: ${t}`)}}async currentUser(){if(this.storage){let r=await this.storage.get(b);if(r!=null)return r}let{data:t}=await this.getSession(),e=t?.user??null;return e&&this.storage&&await this.storage.set(b,e),e}async getCurrentJwt(){if(this.storage){let e=await this.storage.get(g);if(e!=null)return e;let r=await this.storage.get(v),{data:a}=await this.getToken(r??void 0);return a?.token?(await this.storage.set(g,a.token),a.token):null}let{data:t}=await this.getToken();return t?.token??null}async persistLogin(t,e){if(!this.storage)return;let r=e?.headers.get(ye)?.trim()||t.token||t.session?.token;r&&await this.storage.set(v,r),t.user&&await this.storage.set(b,t.user);let a=r??await this.storage.get(v),{data:i}=await this.getToken(a??void 0);i?.token&&await this.storage.set(g,i.token)}async clearLogin(){this.storage&&(await this.storage.remove(v),await this.storage.remove(b),await this.storage.remove(g))}getGoogleOpenPlatformLoginUrl(t,e){let r=new URLSearchParams({return_url:t}),a=e?.applicationCode?.trim()||this.defaultApplicationCode||"";a&&r.set("application_code",a);let i=e?.platformCode?.trim()??"";i&&r.set("platform_code",i);let n=H(this.integrationProviders,"google");return n&&r.set("oauth_credential_source",n),`${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 n=await this.storage.get(g);n!=null&&(e.Authorization=`Bearer ${n}`)}let r=await this.fetchImpl(this.url("google/openplatform/sign-in"),{method:"POST",headers:e,credentials:this.credentials,body:JSON.stringify({exchangeCode:t})}),a=await r.text();if(!r.ok)return{error:{message:a||r.statusText,status:r.status}};let i=a?JSON.parse(a):null;return!i?.token||!i.user?{error:{message:"invalid_google_login_response",status:502}}:(this.storage&&(await this.storage.set(g,i.token),await this.storage.set(v,i.token),await this.storage.set(b,i.user)),{data:i})}catch(e){return{error:{message:e instanceof Error?e.message:String(e),status:0}}}}async getGoogleOpenPlatformIdentity(){try{let t={};if(this.storage){let i=await this.storage.get(g);i!=null&&(t.Authorization=`Bearer ${i}`)}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 a=r?JSON.parse(r):null;return a?.sub?{data:a}:{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}),a=e?.applicationCode?.trim()||this.defaultApplicationCode||"";a&&r.set("application_code",a);let i=e?.platformCode?.trim()??"";i&&r.set("platform_code",i);let n=H(this.integrationProviders,"github");return n&&r.set("oauth_credential_source",n),`${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 n=await this.storage.get(g);n!=null&&(e.Authorization=`Bearer ${n}`)}let r=await this.fetchImpl(this.url("github/openplatform/sign-in"),{method:"POST",headers:e,credentials:this.credentials,body:JSON.stringify({exchangeCode:t})}),a=await r.text();if(!r.ok)return{error:{message:a||r.statusText,status:r.status}};let i=a?JSON.parse(a):null;return!i?.token||!i.user?{error:{message:"invalid_github_login_response",status:502}}:(this.storage&&(await this.storage.set(g,i.token),await this.storage.set(v,i.token),await this.storage.set(b,i.user)),{data:i})}catch(e){return{error:{message:e instanceof Error?e.message:String(e),status:0}}}}async getGithubOpenPlatformIdentity(){try{let t={};if(this.storage){let i=await this.storage.get(g);i!=null&&(t.Authorization=`Bearer ${i}`)}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 a=r?JSON.parse(r):null;return a?.sub?{data:a}:{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 n=await this.storage.get(g);n!=null&&(e.Authorization=`Bearer ${n}`)}let r=await this.fetchImpl(this.url("wechat-website/openplatform/sign-in"),{method:"POST",headers:e,credentials:this.credentials,body:JSON.stringify({exchangeCode:t})}),a=await r.text();if(!r.ok)return{error:{message:a||r.statusText,status:r.status}};let i=a?JSON.parse(a):null;return!i?.token||!i.user?{error:{message:"invalid_wechat_website_login_response",status:502}}:(this.storage&&(await this.storage.set(g,i.token),await this.storage.set(v,i.token),await this.storage.set(b,i.user)),{data:i})}catch(e){return{error:{message:e instanceof Error?e.message:String(e),status:0}}}}async getWechatWebsiteOpenPlatformIdentity(){try{let t={};if(this.storage){let i=await this.storage.get(g);i!=null&&(t.Authorization=`Bearer ${i}`)}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 a=r?JSON.parse(r):null;return a?.sub?{data:a}:{error:{message:"invalid_wechat_website_identity_response",status:502}}}catch(t){return{error:{message:t instanceof Error?t.message:String(t),status:0}}}}url(t){let e=`${`${this.baseUrl.replace(/\/+$/,"")}/${this.authPath.replace(/^\/+/,"")}`}/${t.replace(/^\/+/,"")}`;return typeof console<"u"&&(console.warn("[NvwaAuth] request URL:",e),!e.startsWith("http://")&&!e.startsWith("https://")&&console.warn("[NvwaAuth] URL \u975E\u5B8C\u6574\u5730\u5740\uFF0C\u5C0F\u7A0B\u5E8F\u4F1A\u62A5 invalid url\uFF0C\u8BF7\u68C0\u67E5 Nvwa \u6784\u9020\u65F6\u4F20\u5165\u7684 baseUrl")),e}async getSession(){try{let t={};if(this.storage){let r=await this.storage.get(v)??await this.storage.get(g);r!=null&&(t.Authorization=`Bearer ${r}`)}let e=await this.fetchImpl(this.url("session"),{method:"GET",credentials:this.credentials,...Object.keys(t).length?{headers:t}:{}});return e.ok?{data:await e.json()}:{data:null,error:{message:await e.text()||e.statusText,status:e.status}}}catch(t){return{data:null,error:{message:t instanceof Error?t.message:String(t),status:0}}}}async signInWithEmail(t,e){try{let r=await this.fetchImpl(this.url("sign-in/email"),{method:"POST",headers:{"Content-Type":"application/json"},credentials:this.credentials,body:JSON.stringify({email:t,password:e})}),a=await r.text();if(!r.ok)return{error:{message:a||r.statusText,status:r.status}};let i=a?JSON.parse(a):void 0;return i&&await this.persistLogin({user:i.user,session:i.session},r),{data:i}}catch(r){return{error:{message:r instanceof Error?r.message:String(r),status:0}}}}async signOut(){try{let t={"Content-Type":"application/json"};if(this.storage){let r=await this.storage.get(v)??await this.storage.get(g);r!=null&&(t.Authorization=`Bearer ${r}`)}await this.clearLogin();let e=await this.fetchImpl(this.url("sign-out"),{method:"POST",credentials:this.credentials,headers:t,body:"{}"});return e.ok?{}:{error:{message:await e.text()||e.statusText,status:e.status}}}catch(t){return{error:{message:t instanceof Error?t.message:String(t),status:0}}}}async signUp(t){let e=await this.postJson("sign-up/email",t);return e.data&&await this.persistLogin(e.data,e.response),e}async getToken(t){try{let e={};if(t)e.Authorization=`Bearer ${t}`;else if(this.storage){let n=await this.storage.get(v)??await this.storage.get(g);n!=null&&(e.Authorization=`Bearer ${n}`)}let r=await this.fetchImpl(this.url("token"),{method:"GET",credentials:this.credentials,...Object.keys(e).length?{headers:e}:{}}),a=await r.text();if(!r.ok)return{error:{message:a||r.statusText,status:r.status}};let i=a?JSON.parse(a):void 0;return{data:i?.token!=null?{token:i.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 a=await this.postJson("sign-in/phone-number",{phoneNumber:t,password:e,rememberMe:r});return a.data&&await this.persistLogin(a.data,a.response),a}async sendPhoneNumberOtp(t){let e=await this.postJson("phone-number/send-otp",{phoneNumber:t});return e.error?{error:e.error}:{}}async verifyPhoneNumber(t,e){let r=await this.postJson("phone-number/verify",{phoneNumber:t,code:e});return r.data&&await this.persistLogin(r.data,r.response),r}async loginWithWeChatCode(t,e){try{let r={"Content-Type":"application/json"};if(this.storage){let h=await this.storage.get(g);h!=null&&(r.Authorization=`Bearer ${h}`)}let a=await this.fetchImpl(this.url("wechat/openplatform/sign-in"),{method:"POST",headers:r,credentials:this.credentials,body:JSON.stringify({code:t,applicationCode:e})}),i=await a.text();if(!a.ok)return{error:{message:i||a.statusText,status:a.status}};let n=i?JSON.parse(i):null;return!n?.token||!n.user?{error:{message:"invalid_wechat_login_response",status:502}}:(this.storage&&(await this.storage.set(g,n.token),await this.storage.set(v,n.token),await this.storage.set(b,n.user)),{data:n})}catch(r){return{error:{message:r instanceof Error?r.message:String(r),status:0}}}}async loginWithAlipayCode(t,e){try{let r={"Content-Type":"application/json"};if(this.storage){let h=await this.storage.get(g);h!=null&&(r.Authorization=`Bearer ${h}`)}let a=await this.fetchImpl(this.url("alipay/openplatform/sign-in"),{method:"POST",headers:r,credentials:this.credentials,body:JSON.stringify({code:t,applicationCode:e})}),i=await a.text();if(!a.ok)return{error:{message:i||a.statusText,status:a.status}};let n=i?JSON.parse(i):null;return!n?.token||!n.user?{error:{message:"invalid_alipay_login_response",status:502}}:(this.storage&&(await this.storage.set(g,n.token),await this.storage.set(v,n.token),await this.storage.set(b,n.user)),{data:n})}catch(r){return{error:{message:r instanceof Error?r.message:String(r),status:0}}}}async getWeChatOpenPlatformIdentity(t){try{let e={};if(this.storage){let h=await this.storage.get(g);h!=null&&(e.Authorization=`Bearer ${h}`)}let r=t?.trim()?`?applicationCode=${encodeURIComponent(t.trim())}`:"",a=await this.fetchImpl(this.url(`wechat/openplatform/identity${r}`),{method:"GET",credentials:this.credentials,...Object.keys(e).length?{headers:e}:{}}),i=await a.text();if(!a.ok)return{error:{message:i||a.statusText,status:a.status}};let n=i?JSON.parse(i):null;return!n?.openid||!n.appId?{error:{message:"invalid_wechat_identity_response",status:502}}:{data:n}}catch(e){return{error:{message:e instanceof Error?e.message:String(e),status:0}}}}async getAlipayOpenPlatformIdentity(t){try{let e={};if(this.storage){let h=await this.storage.get(g);h!=null&&(e.Authorization=`Bearer ${h}`)}let r=t?.trim()?`?applicationCode=${encodeURIComponent(t.trim())}`:"",a=await this.fetchImpl(this.url(`alipay/openplatform/identity${r}`),{method:"GET",credentials:this.credentials,...Object.keys(e).length?{headers:e}:{}}),i=await a.text();if(!a.ok)return{error:{message:i||a.statusText,status:a.status}};let n=i?JSON.parse(i):null;return!n?.openid||!n.appId?{error:{message:"invalid_alipay_identity_response",status:502}}:{data:n}}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)}),a=await r.text();if(!r.ok)return{error:{message:a||r.statusText,status:r.status}};let i=a?JSON.parse(a):void 0;return{data:i?.data??i??void 0,response:r}}catch(r){return{error:{message:r instanceof Error?r.message:String(r),status:0}}}}},V=class{constructor(t,e,r){this.storage=t,this.customFetch=e,this.handleUnauthorized=r}async fetch(t,e){return await this.customFetch(t,e)}async fetchWithAuth(t,e){let r=await this.storage.get(g),a=new w(e?.headers);r&&a.set("Authorization",`Bearer ${r}`);let i=e?.method||"GET";if((i==="POST"||i==="PUT"||i==="PATCH")&&e?.body){let h=a.get("Content-Type");(!h||h.includes("text/plain"))&&a.set("Content-Type","application/json")}let n=await this.customFetch(t,{...e,headers:a});if(n.status===401)throw this.handleUnauthorized(),new Error("\u672A\u767B\u5F55");return n}},ve="/storage",be=ve+"/generateUploadUrl",Y=class{constructor(t,e){this.baseUrl=t,this.http=e}async uploadFile(t){let e=await this.http.fetch(this.baseUrl+be,{method:"POST",body:{fileName:t.name||t.fileName,fileSize:t.size||t.fileSize,fileType:t.type||t.fileType}}),{url:r}=await e.json();if(!r)throw new Error("\u83B7\u53D6\u4E0A\u4F20URL\u5931\u8D25");let a=await this.http.fetch(r,{method:"PUT",body:t,headers:new w({"Content-Type":t.type||t.fileType||"application/octet-stream"})}),{url:i}=await a.json();return{url:i.split("?")[0]}}},Pe=class extends Error{constructor(t){super(t.message),this.name="PostgrestError",this.details=t.details,this.hint=t.hint,this.code=t.code}},Ee=class{constructor(t){var e,r,a;this.shouldThrowOnError=!1,this.method=t.method,this.url=t.url,this.headers=new w(t.headers),this.schema=t.schema,this.body=t.body,this.shouldThrowOnError=(e=t.shouldThrowOnError)!==null&&e!==void 0?e:!1,this.signal=t.signal,this.isMaybeSingle=(r=t.isMaybeSingle)!==null&&r!==void 0?r:!1,this.urlLengthLimit=(a=t.urlLengthLimit)!==null&&a!==void 0?a:8e3,t.fetch?this.fetch=t.fetch:this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(t,e){return this.headers=new w(this.headers),this.headers.set(t,e),this}then(t,e){var r=this;this.schema===void 0||(["GET","HEAD"].includes(this.method)?this.headers.set("Accept-Profile",this.schema):this.headers.set("Content-Profile",this.schema)),this.method!=="GET"&&this.method!=="HEAD"&&this.headers.set("Content-Type","application/json");let a=this.fetch,i=a(this.url.toString(),{method:this.method,headers:this.headers,body:JSON.stringify(this.body),signal:this.signal}).then(async n=>{let h=null,o=null,c=null,s=n.status,l=n.statusText;if(n.ok){var u,m;if(r.method!=="HEAD"){var p;let y=await n.text();y===""||(r.headers.get("Accept")==="text/csv"||r.headers.get("Accept")&&!((p=r.headers.get("Accept"))===null||p===void 0)&&p.includes("application/vnd.pgrst.plan+text")?o=y:o=JSON.parse(y))}let d=(u=r.headers.get("Prefer"))===null||u===void 0?void 0:u.match(/count=(exact|planned|estimated)/),f=(m=n.headers.get("content-range"))===null||m===void 0?void 0:m.split("/");d&&f&&f.length>1&&(c=parseInt(f[1])),r.isMaybeSingle&&Array.isArray(o)&&(o.length>1?(h={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,s=406,l="Not Acceptable"):o.length===1?o=o[0]:o=null)}else{let d=await n.text();try{h=JSON.parse(d),Array.isArray(h)&&n.status===404&&(o=[],h=null,s=200,l="OK")}catch{n.status===404&&d===""?(s=204,l="No Content"):h={message:d}}if(h&&r.shouldThrowOnError)throw new Pe(h)}return{error:h,data:o,count:c,status:s,statusText:l}});return this.shouldThrowOnError||(i=i.catch(n=>{var h;let o="",c="",s="",l=n?.cause;if(l){var u,m,p,d;let O=(u=l?.message)!==null&&u!==void 0?u:"",C=(m=l?.code)!==null&&m!==void 0?m:"";o=`${(p=n?.name)!==null&&p!==void 0?p:"FetchError"}: ${n?.message}`,o+=`
2
2
 
3
- Caused by: ${(d=l?.name)!==null&&d!==void 0?d:"Error"}: ${L}`,C&&(o+=` (${C})`),l?.stack&&(o+=`
4
- ${l.stack}`)}else{var f;o=(f=n?.stack)!==null&&f!==void 0?f:""}let y=this.url.toString().length;return n?.name==="AbortError"||n?.code==="ABORT_ERR"?(s="",c="Request was aborted (timeout or manual cancellation)",y>this.urlLengthLimit&&(c+=`. Note: Your request URL is ${y} characters, which may exceed server limits. If selecting many fields, consider using views. If filtering with large arrays (e.g., .in('id', [many IDs])), consider using an RPC function to pass values server-side.`)):(l?.name==="HeadersOverflowError"||l?.code==="UND_ERR_HEADERS_OVERFLOW")&&(s="",c="HTTP headers exceeded server limits (typically 16KB)",y>this.urlLengthLimit&&(c+=`. Your request URL is ${y} characters. If selecting many fields, consider using views. If filtering with large arrays (e.g., .in('id', [200+ IDs])), consider using an RPC function instead.`)),{error:{message:`${(h=n?.name)!==null&&h!==void 0?h:"FetchError"}: ${n?.message}`,details:o,hint:c,code:s},data:null,count:null,status:0,statusText:""}})),a.then(t,e)}returns(){return this}overrideTypes(){return this}},be=class extends ve{select(t){let e=!1,r=(t??"*").split("").map(i=>/\s/.test(i)&&!e?"":(i==='"'&&(e=!e),i)).join("");return this.url.searchParams.set("select",r),this.headers.append("Prefer","return=representation"),this}order(t,{ascending:e=!0,nullsFirst:r,foreignTable:i,referencedTable:a=i}={}){let n=a?`${a}.order`:"order",h=this.url.searchParams.get(n);return this.url.searchParams.set(n,`${h?`${h},`:""}${t}.${e?"asc":"desc"}${r===void 0?"":r?".nullsfirst":".nullslast"}`),this}limit(t,{foreignTable:e,referencedTable:r=e}={}){let i=typeof r>"u"?"limit":`${r}.limit`;return this.url.searchParams.set(i,`${t}`),this}range(t,e,{foreignTable:r,referencedTable:i=r}={}){let a=typeof i>"u"?"offset":`${i}.offset`,n=typeof i>"u"?"limit":`${i}.limit`;return this.url.searchParams.set(a,`${t}`),this.url.searchParams.set(n,`${e-t+1}`),this}abortSignal(t){return this.signal=t,this}single(){return this.headers.set("Accept","application/vnd.pgrst.object+json"),this}maybeSingle(){return this.isMaybeSingle=!0,this}csv(){return this.headers.set("Accept","text/csv"),this}geojson(){return this.headers.set("Accept","application/geo+json"),this}explain({analyze:t=!1,verbose:e=!1,settings:r=!1,buffers:i=!1,wal:a=!1,format:n="text"}={}){var h;let o=[t?"analyze":null,e?"verbose":null,r?"settings":null,i?"buffers":null,a?"wal":null].filter(Boolean).join("|"),c=(h=this.headers.get("Accept"))!==null&&h!==void 0?h:"application/json";return this.headers.set("Accept",`application/vnd.pgrst.plan+${n}; for="${c}"; options=${o};`),n==="json"?this:this}rollback(){return this.headers.append("Prefer","tx=rollback"),this}returns(){return this}maxAffected(t){return this.headers.append("Prefer","handling=strict"),this.headers.append("Prefer",`max-affected=${t}`),this}},H=new RegExp("[,()]"),P=class extends be{eq(t,e){return this.url.searchParams.append(t,`eq.${e}`),this}neq(t,e){return this.url.searchParams.append(t,`neq.${e}`),this}gt(t,e){return this.url.searchParams.append(t,`gt.${e}`),this}gte(t,e){return this.url.searchParams.append(t,`gte.${e}`),this}lt(t,e){return this.url.searchParams.append(t,`lt.${e}`),this}lte(t,e){return this.url.searchParams.append(t,`lte.${e}`),this}like(t,e){return this.url.searchParams.append(t,`like.${e}`),this}likeAllOf(t,e){return this.url.searchParams.append(t,`like(all).{${e.join(",")}}`),this}likeAnyOf(t,e){return this.url.searchParams.append(t,`like(any).{${e.join(",")}}`),this}ilike(t,e){return this.url.searchParams.append(t,`ilike.${e}`),this}ilikeAllOf(t,e){return this.url.searchParams.append(t,`ilike(all).{${e.join(",")}}`),this}ilikeAnyOf(t,e){return this.url.searchParams.append(t,`ilike(any).{${e.join(",")}}`),this}regexMatch(t,e){return this.url.searchParams.append(t,`match.${e}`),this}regexIMatch(t,e){return this.url.searchParams.append(t,`imatch.${e}`),this}is(t,e){return this.url.searchParams.append(t,`is.${e}`),this}isDistinct(t,e){return this.url.searchParams.append(t,`isdistinct.${e}`),this}in(t,e){let r=Array.from(new Set(e)).map(i=>typeof i=="string"&&H.test(i)?`"${i}"`:`${i}`).join(",");return this.url.searchParams.append(t,`in.(${r})`),this}notIn(t,e){let r=Array.from(new Set(e)).map(i=>typeof i=="string"&&H.test(i)?`"${i}"`:`${i}`).join(",");return this.url.searchParams.append(t,`not.in.(${r})`),this}contains(t,e){return typeof e=="string"?this.url.searchParams.append(t,`cs.${e}`):Array.isArray(e)?this.url.searchParams.append(t,`cs.{${e.join(",")}}`):this.url.searchParams.append(t,`cs.${JSON.stringify(e)}`),this}containedBy(t,e){return typeof e=="string"?this.url.searchParams.append(t,`cd.${e}`):Array.isArray(e)?this.url.searchParams.append(t,`cd.{${e.join(",")}}`):this.url.searchParams.append(t,`cd.${JSON.stringify(e)}`),this}rangeGt(t,e){return this.url.searchParams.append(t,`sr.${e}`),this}rangeGte(t,e){return this.url.searchParams.append(t,`nxl.${e}`),this}rangeLt(t,e){return this.url.searchParams.append(t,`sl.${e}`),this}rangeLte(t,e){return this.url.searchParams.append(t,`nxr.${e}`),this}rangeAdjacent(t,e){return this.url.searchParams.append(t,`adj.${e}`),this}overlaps(t,e){return typeof e=="string"?this.url.searchParams.append(t,`ov.${e}`):this.url.searchParams.append(t,`ov.{${e.join(",")}}`),this}textSearch(t,e,{config:r,type:i}={}){let a="";i==="plain"?a="pl":i==="phrase"?a="ph":i==="websearch"&&(a="w");let n=r===void 0?"":`(${r})`;return this.url.searchParams.append(t,`${a}fts${n}.${e}`),this}match(t){return Object.entries(t).filter(([e,r])=>r!==void 0).forEach(([e,r])=>{this.url.searchParams.append(e,`eq.${r}`)}),this}not(t,e,r){return this.url.searchParams.append(t,`not.${e}.${r}`),this}or(t,{foreignTable:e,referencedTable:r=e}={}){let i=r?`${r}.or`:"or";return this.url.searchParams.append(i,`(${t})`),this}filter(t,e,r){return this.url.searchParams.append(t,`${e}.${r}`),this}},Pe=class{constructor(t,{headers:e={},schema:r,fetch:i,urlLengthLimit:a=8e3}){this.url=t,this.headers=new w(e),this.schema=r,this.fetch=i,this.urlLengthLimit=a}cloneRequestState(){return{url:new U(this.url.toString()),headers:new w(this.headers)}}select(t,e){let{head:r=!1,count:i}=e??{},a=r?"HEAD":"GET",n=!1,h=(t??"*").split("").map(s=>/\s/.test(s)&&!n?"":(s==='"'&&(n=!n),s)).join(""),{url:o,headers:c}=this.cloneRequestState();return o.searchParams.set("select",h),i&&c.append("Prefer",`count=${i}`),new P({method:a,url:o,headers:c,schema:this.schema,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}insert(t,{count:e,defaultToNull:r=!0}={}){var i;let a="POST",{url:n,headers:h}=this.cloneRequestState();if(e&&h.append("Prefer",`count=${e}`),r||h.append("Prefer","missing=default"),Array.isArray(t)){let o=t.reduce((c,s)=>c.concat(Object.keys(s)),[]);if(o.length>0){let c=[...new Set(o)].map(s=>`"${s}"`);n.searchParams.set("columns",c.join(","))}}return new P({method:a,url:n,headers:h,schema:this.schema,body:t,fetch:(i=this.fetch)!==null&&i!==void 0?i:fetch,urlLengthLimit:this.urlLengthLimit})}upsert(t,{onConflict:e,ignoreDuplicates:r=!1,count:i,defaultToNull:a=!0}={}){var n;let h="POST",{url:o,headers:c}=this.cloneRequestState();if(c.append("Prefer",`resolution=${r?"ignore":"merge"}-duplicates`),e!==void 0&&o.searchParams.set("on_conflict",e),i&&c.append("Prefer",`count=${i}`),a||c.append("Prefer","missing=default"),Array.isArray(t)){let s=t.reduce((l,u)=>l.concat(Object.keys(u)),[]);if(s.length>0){let l=[...new Set(s)].map(u=>`"${u}"`);o.searchParams.set("columns",l.join(","))}}return new P({method:h,url:o,headers:c,schema:this.schema,body:t,fetch:(n=this.fetch)!==null&&n!==void 0?n:fetch,urlLengthLimit:this.urlLengthLimit})}update(t,{count:e}={}){var r;let i="PATCH",{url:a,headers:n}=this.cloneRequestState();return e&&n.append("Prefer",`count=${e}`),new P({method:i,url:a,headers:n,schema:this.schema,body:t,fetch:(r=this.fetch)!==null&&r!==void 0?r:fetch,urlLengthLimit:this.urlLengthLimit})}delete({count:t}={}){var e;let r="DELETE",{url:i,headers:a}=this.cloneRequestState();return t&&a.append("Prefer",`count=${t}`),new P({method:r,url:i,headers:a,schema:this.schema,fetch:(e=this.fetch)!==null&&e!==void 0?e:fetch,urlLengthLimit:this.urlLengthLimit})}};function T(t){"@babel/helpers - typeof";return T=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},T(t)}function Ee(t,e){if(T(t)!="object"||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var i=r.call(t,e||"default");if(T(i)!="object")return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function Se(t){var e=Ee(t,"string");return T(e)=="symbol"?e:e+""}function Ce(t,e,r){return(e=Se(e))in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function q(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(t);e&&(i=i.filter(function(a){return Object.getOwnPropertyDescriptor(t,a).enumerable})),r.push.apply(r,i)}return r}function O(t){for(var e=1;e<arguments.length;e++){var r=arguments[e]!=null?arguments[e]:{};e%2?q(Object(r),!0).forEach(function(i){Ce(t,i,r[i])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):q(Object(r)).forEach(function(i){Object.defineProperty(t,i,Object.getOwnPropertyDescriptor(r,i))})}return t}var Te=class Y{constructor(e,{headers:r={},schema:i,fetch:a,timeout:n,urlLengthLimit:h=8e3}={}){this.url=e,this.headers=new w(r),this.schemaName=i,this.urlLengthLimit=h;let o=a??globalThis.fetch;n!==void 0&&n>0?this.fetch=(c,s)=>{let l=new pe,u=setTimeout(()=>l.abort(),n),m=s?.signal;if(m){if(m.aborted)return clearTimeout(u),o(c,s);let p=()=>{clearTimeout(u),l.abort()};return m.addEventListener("abort",p,{once:!0}),o(c,O(O({},s),{},{signal:l.signal})).finally(()=>{clearTimeout(u),m.removeEventListener("abort",p)})}return o(c,O(O({},s),{},{signal:l.signal})).finally(()=>clearTimeout(u))}:this.fetch=o}from(e){if(!e||typeof e!="string"||e.trim()==="")throw new Error("Invalid relation name: relation must be a non-empty string.");return new Pe(new U(`${this.url}/${e}`),{headers:new w(this.headers),schema:this.schemaName,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}schema(e){return new Y(this.url,{headers:this.headers,schema:e,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}rpc(e,r={},{head:i=!1,get:a=!1,count:n}={}){var h;let o,c=new U(`${this.url}/rpc/${e}`),s,l=p=>p!==null&&typeof p=="object"&&(!Array.isArray(p)||p.some(l)),u=i&&Object.values(r).some(l);u?(o="POST",s=r):i||a?(o=i?"HEAD":"GET",Object.entries(r).filter(([p,d])=>d!==void 0).map(([p,d])=>[p,Array.isArray(d)?`{${d.join(",")}}`:`${d}`]).forEach(([p,d])=>{c.searchParams.append(p,d)})):(o="POST",s=r);let m=new w(this.headers);return u?m.set("Prefer",n?`count=${n},return=minimal`:"return=minimal"):n&&m.set("Prefer",`count=${n}`),new P({method:o,url:c,headers:m,schema:this.schemaName,body:s,fetch:(h=this.fetch)!==null&&h!==void 0?h:fetch,urlLengthLimit:this.urlLengthLimit})}},Le="/entities",Q=(t,e)=>new Te(t+Le,{fetch:e.fetchWithAuth.bind(e)}),X=class{constructor(){this.hoverOverlay=null,this.selectedOverlay=null,this.tooltip=null,this.hoverElement=null,this.selectedElement=null,this.hoverUpdateHandler=null,this.selectedUpdateHandler=null,this.createStyles()}createStyles(){if(document.getElementById("__nvwa-inspector-overlay-style"))return;let t=document.createElement("style");t.id="__nvwa-inspector-overlay-style",t.textContent=`
3
+ Caused by: ${(d=l?.name)!==null&&d!==void 0?d:"Error"}: ${O}`,C&&(o+=` (${C})`),l?.stack&&(o+=`
4
+ ${l.stack}`)}else{var f;o=(f=n?.stack)!==null&&f!==void 0?f:""}let y=this.url.toString().length;return n?.name==="AbortError"||n?.code==="ABORT_ERR"?(s="",c="Request was aborted (timeout or manual cancellation)",y>this.urlLengthLimit&&(c+=`. Note: Your request URL is ${y} characters, which may exceed server limits. If selecting many fields, consider using views. If filtering with large arrays (e.g., .in('id', [many IDs])), consider using an RPC function to pass values server-side.`)):(l?.name==="HeadersOverflowError"||l?.code==="UND_ERR_HEADERS_OVERFLOW")&&(s="",c="HTTP headers exceeded server limits (typically 16KB)",y>this.urlLengthLimit&&(c+=`. Your request URL is ${y} characters. If selecting many fields, consider using views. If filtering with large arrays (e.g., .in('id', [200+ IDs])), consider using an RPC function instead.`)),{error:{message:`${(h=n?.name)!==null&&h!==void 0?h:"FetchError"}: ${n?.message}`,details:o,hint:c,code:s},data:null,count:null,status:0,statusText:""}})),i.then(t,e)}returns(){return this}overrideTypes(){return this}},Se=class extends Ee{select(t){let e=!1,r=(t??"*").split("").map(a=>/\s/.test(a)&&!e?"":(a==='"'&&(e=!e),a)).join("");return this.url.searchParams.set("select",r),this.headers.append("Prefer","return=representation"),this}order(t,{ascending:e=!0,nullsFirst:r,foreignTable:a,referencedTable:i=a}={}){let n=i?`${i}.order`:"order",h=this.url.searchParams.get(n);return this.url.searchParams.set(n,`${h?`${h},`:""}${t}.${e?"asc":"desc"}${r===void 0?"":r?".nullsfirst":".nullslast"}`),this}limit(t,{foreignTable:e,referencedTable:r=e}={}){let a=typeof r>"u"?"limit":`${r}.limit`;return this.url.searchParams.set(a,`${t}`),this}range(t,e,{foreignTable:r,referencedTable:a=r}={}){let i=typeof a>"u"?"offset":`${a}.offset`,n=typeof a>"u"?"limit":`${a}.limit`;return this.url.searchParams.set(i,`${t}`),this.url.searchParams.set(n,`${e-t+1}`),this}abortSignal(t){return this.signal=t,this}single(){return this.headers.set("Accept","application/vnd.pgrst.object+json"),this}maybeSingle(){return this.isMaybeSingle=!0,this}csv(){return this.headers.set("Accept","text/csv"),this}geojson(){return this.headers.set("Accept","application/geo+json"),this}explain({analyze:t=!1,verbose:e=!1,settings:r=!1,buffers:a=!1,wal:i=!1,format:n="text"}={}){var h;let o=[t?"analyze":null,e?"verbose":null,r?"settings":null,a?"buffers":null,i?"wal":null].filter(Boolean).join("|"),c=(h=this.headers.get("Accept"))!==null&&h!==void 0?h:"application/json";return this.headers.set("Accept",`application/vnd.pgrst.plan+${n}; for="${c}"; options=${o};`),n==="json"?this:this}rollback(){return this.headers.append("Prefer","tx=rollback"),this}returns(){return this}maxAffected(t){return this.headers.append("Prefer","handling=strict"),this.headers.append("Prefer",`max-affected=${t}`),this}},q=new RegExp("[,()]"),P=class extends Se{eq(t,e){return this.url.searchParams.append(t,`eq.${e}`),this}neq(t,e){return this.url.searchParams.append(t,`neq.${e}`),this}gt(t,e){return this.url.searchParams.append(t,`gt.${e}`),this}gte(t,e){return this.url.searchParams.append(t,`gte.${e}`),this}lt(t,e){return this.url.searchParams.append(t,`lt.${e}`),this}lte(t,e){return this.url.searchParams.append(t,`lte.${e}`),this}like(t,e){return this.url.searchParams.append(t,`like.${e}`),this}likeAllOf(t,e){return this.url.searchParams.append(t,`like(all).{${e.join(",")}}`),this}likeAnyOf(t,e){return this.url.searchParams.append(t,`like(any).{${e.join(",")}}`),this}ilike(t,e){return this.url.searchParams.append(t,`ilike.${e}`),this}ilikeAllOf(t,e){return this.url.searchParams.append(t,`ilike(all).{${e.join(",")}}`),this}ilikeAnyOf(t,e){return this.url.searchParams.append(t,`ilike(any).{${e.join(",")}}`),this}regexMatch(t,e){return this.url.searchParams.append(t,`match.${e}`),this}regexIMatch(t,e){return this.url.searchParams.append(t,`imatch.${e}`),this}is(t,e){return this.url.searchParams.append(t,`is.${e}`),this}isDistinct(t,e){return this.url.searchParams.append(t,`isdistinct.${e}`),this}in(t,e){let r=Array.from(new Set(e)).map(a=>typeof a=="string"&&q.test(a)?`"${a}"`:`${a}`).join(",");return this.url.searchParams.append(t,`in.(${r})`),this}notIn(t,e){let r=Array.from(new Set(e)).map(a=>typeof a=="string"&&q.test(a)?`"${a}"`:`${a}`).join(",");return this.url.searchParams.append(t,`not.in.(${r})`),this}contains(t,e){return typeof e=="string"?this.url.searchParams.append(t,`cs.${e}`):Array.isArray(e)?this.url.searchParams.append(t,`cs.{${e.join(",")}}`):this.url.searchParams.append(t,`cs.${JSON.stringify(e)}`),this}containedBy(t,e){return typeof e=="string"?this.url.searchParams.append(t,`cd.${e}`):Array.isArray(e)?this.url.searchParams.append(t,`cd.{${e.join(",")}}`):this.url.searchParams.append(t,`cd.${JSON.stringify(e)}`),this}rangeGt(t,e){return this.url.searchParams.append(t,`sr.${e}`),this}rangeGte(t,e){return this.url.searchParams.append(t,`nxl.${e}`),this}rangeLt(t,e){return this.url.searchParams.append(t,`sl.${e}`),this}rangeLte(t,e){return this.url.searchParams.append(t,`nxr.${e}`),this}rangeAdjacent(t,e){return this.url.searchParams.append(t,`adj.${e}`),this}overlaps(t,e){return typeof e=="string"?this.url.searchParams.append(t,`ov.${e}`):this.url.searchParams.append(t,`ov.{${e.join(",")}}`),this}textSearch(t,e,{config:r,type:a}={}){let i="";a==="plain"?i="pl":a==="phrase"?i="ph":a==="websearch"&&(i="w");let n=r===void 0?"":`(${r})`;return this.url.searchParams.append(t,`${i}fts${n}.${e}`),this}match(t){return Object.entries(t).filter(([e,r])=>r!==void 0).forEach(([e,r])=>{this.url.searchParams.append(e,`eq.${r}`)}),this}not(t,e,r){return this.url.searchParams.append(t,`not.${e}.${r}`),this}or(t,{foreignTable:e,referencedTable:r=e}={}){let a=r?`${r}.or`:"or";return this.url.searchParams.append(a,`(${t})`),this}filter(t,e,r){return this.url.searchParams.append(t,`${e}.${r}`),this}},Ce=class{constructor(t,{headers:e={},schema:r,fetch:a,urlLengthLimit:i=8e3}){this.url=t,this.headers=new w(e),this.schema=r,this.fetch=a,this.urlLengthLimit=i}cloneRequestState(){return{url:new k(this.url.toString()),headers:new w(this.headers)}}select(t,e){let{head:r=!1,count:a}=e??{},i=r?"HEAD":"GET",n=!1,h=(t??"*").split("").map(s=>/\s/.test(s)&&!n?"":(s==='"'&&(n=!n),s)).join(""),{url:o,headers:c}=this.cloneRequestState();return o.searchParams.set("select",h),a&&c.append("Prefer",`count=${a}`),new P({method:i,url:o,headers:c,schema:this.schema,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}insert(t,{count:e,defaultToNull:r=!0}={}){var a;let i="POST",{url:n,headers:h}=this.cloneRequestState();if(e&&h.append("Prefer",`count=${e}`),r||h.append("Prefer","missing=default"),Array.isArray(t)){let o=t.reduce((c,s)=>c.concat(Object.keys(s)),[]);if(o.length>0){let c=[...new Set(o)].map(s=>`"${s}"`);n.searchParams.set("columns",c.join(","))}}return new P({method:i,url:n,headers:h,schema:this.schema,body:t,fetch:(a=this.fetch)!==null&&a!==void 0?a:fetch,urlLengthLimit:this.urlLengthLimit})}upsert(t,{onConflict:e,ignoreDuplicates:r=!1,count:a,defaultToNull:i=!0}={}){var n;let h="POST",{url:o,headers:c}=this.cloneRequestState();if(c.append("Prefer",`resolution=${r?"ignore":"merge"}-duplicates`),e!==void 0&&o.searchParams.set("on_conflict",e),a&&c.append("Prefer",`count=${a}`),i||c.append("Prefer","missing=default"),Array.isArray(t)){let s=t.reduce((l,u)=>l.concat(Object.keys(u)),[]);if(s.length>0){let l=[...new Set(s)].map(u=>`"${u}"`);o.searchParams.set("columns",l.join(","))}}return new P({method:h,url:o,headers:c,schema:this.schema,body:t,fetch:(n=this.fetch)!==null&&n!==void 0?n:fetch,urlLengthLimit:this.urlLengthLimit})}update(t,{count:e}={}){var r;let a="PATCH",{url:i,headers:n}=this.cloneRequestState();return e&&n.append("Prefer",`count=${e}`),new P({method:a,url:i,headers:n,schema:this.schema,body:t,fetch:(r=this.fetch)!==null&&r!==void 0?r:fetch,urlLengthLimit:this.urlLengthLimit})}delete({count:t}={}){var e;let r="DELETE",{url:a,headers:i}=this.cloneRequestState();return t&&i.append("Prefer",`count=${t}`),new P({method:r,url:a,headers:i,schema:this.schema,fetch:(e=this.fetch)!==null&&e!==void 0?e:fetch,urlLengthLimit:this.urlLengthLimit})}};function T(t){"@babel/helpers - typeof";return T=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},T(t)}function Te(t,e){if(T(t)!="object"||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var a=r.call(t,e||"default");if(T(a)!="object")return a;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function Oe(t){var e=Te(t,"string");return T(e)=="symbol"?e:e+""}function Le(t,e,r){return(e=Oe(e))in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function W(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(t);e&&(a=a.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),r.push.apply(r,a)}return r}function L(t){for(var e=1;e<arguments.length;e++){var r=arguments[e]!=null?arguments[e]:{};e%2?W(Object(r),!0).forEach(function(a){Le(t,a,r[a])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):W(Object(r)).forEach(function(a){Object.defineProperty(t,a,Object.getOwnPropertyDescriptor(r,a))})}return t}var _e=class Q{constructor(e,{headers:r={},schema:a,fetch:i,timeout:n,urlLengthLimit:h=8e3}={}){this.url=e,this.headers=new w(r),this.schemaName=a,this.urlLengthLimit=h;let o=i??globalThis.fetch;n!==void 0&&n>0?this.fetch=(c,s)=>{let l=new de,u=setTimeout(()=>l.abort(),n),m=s?.signal;if(m){if(m.aborted)return clearTimeout(u),o(c,s);let p=()=>{clearTimeout(u),l.abort()};return m.addEventListener("abort",p,{once:!0}),o(c,L(L({},s),{},{signal:l.signal})).finally(()=>{clearTimeout(u),m.removeEventListener("abort",p)})}return o(c,L(L({},s),{},{signal:l.signal})).finally(()=>clearTimeout(u))}:this.fetch=o}from(e){if(!e||typeof e!="string"||e.trim()==="")throw new Error("Invalid relation name: relation must be a non-empty string.");return new Ce(new k(`${this.url}/${e}`),{headers:new w(this.headers),schema:this.schemaName,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}schema(e){return new Q(this.url,{headers:this.headers,schema:e,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}rpc(e,r={},{head:a=!1,get:i=!1,count:n}={}){var h;let o,c=new k(`${this.url}/rpc/${e}`),s,l=p=>p!==null&&typeof p=="object"&&(!Array.isArray(p)||p.some(l)),u=a&&Object.values(r).some(l);u?(o="POST",s=r):a||i?(o=a?"HEAD":"GET",Object.entries(r).filter(([p,d])=>d!==void 0).map(([p,d])=>[p,Array.isArray(d)?`{${d.join(",")}}`:`${d}`]).forEach(([p,d])=>{c.searchParams.append(p,d)})):(o="POST",s=r);let m=new w(this.headers);return u?m.set("Prefer",n?`count=${n},return=minimal`:"return=minimal"):n&&m.set("Prefer",`count=${n}`),new P({method:o,url:c,headers:m,schema:this.schemaName,body:s,fetch:(h=this.fetch)!==null&&h!==void 0?h:fetch,urlLengthLimit:this.urlLengthLimit})}},Ae="/entities",X=(t,e)=>new _e(t+Ae,{fetch:e.fetchWithAuth.bind(e)}),Z=class{constructor(){this.hoverOverlay=null,this.selectedOverlay=null,this.tooltip=null,this.hoverElement=null,this.selectedElement=null,this.hoverUpdateHandler=null,this.selectedUpdateHandler=null,this.createStyles()}createStyles(){if(document.getElementById("__nvwa-inspector-overlay-style"))return;let t=document.createElement("style");t.id="__nvwa-inspector-overlay-style",t.textContent=`
5
5
  .__nvwa-inspector-overlay {
6
6
  position: absolute;
7
7
  pointer-events: none;
@@ -33,4 +33,4 @@ ${l.stack}`)}else{var f;o=(f=n?.stack)!==null&&f!==void 0?f:""}let y=this.url.to
33
33
  max-width: 400px;
34
34
  word-break: break-all;
35
35
  }
36
- `,document.head.appendChild(t)}createTooltip(){return this.tooltip?this.tooltip:(this.tooltip=document.createElement("div"),this.tooltip.id="__nvwa-inspector-tooltip",document.body.appendChild(this.tooltip),this.tooltip)}createOverlay(t){let e=document.createElement("div");return e.className=`__nvwa-inspector-overlay __nvwa-inspector-overlay-${t}`,document.body.appendChild(e),e}updateOverlayPosition(t,e){if(!e.isConnected)return;let r=e.getBoundingClientRect(),i=window.scrollX||window.pageXOffset,a=window.scrollY||window.pageYOffset;r.width>0&&r.height>0?(t.style.left=`${r.left+i}px`,t.style.top=`${r.top+a}px`,t.style.width=`${r.width}px`,t.style.height=`${r.height}px`,t.style.display="block"):t.style.display="none"}removeOverlay(t){t&&t.parentNode&&t.parentNode.removeChild(t)}highlightElement(t,e){if(!t.isConnected)return;if(this.hoverElement===t&&this.hoverOverlay){this.updateOverlayPosition(this.hoverOverlay,t);let h=this.createTooltip();e?h.textContent=e:h.textContent=`<${t.tagName.toLowerCase()}> (\u65E0 source location)`,h.style.display="block";let o=t.getBoundingClientRect();h.style.left=`${o.left+window.scrollX}px`,h.style.top=`${o.top+window.scrollY-h.offsetHeight-8}px`,o.top<h.offsetHeight+8&&(h.style.top=`${o.bottom+window.scrollY+8}px`);return}this.hoverOverlay&&(this.removeOverlay(this.hoverOverlay),this.hoverOverlay=null);let r=this.createOverlay("hover");this.updateOverlayPosition(r,t),this.hoverOverlay=r,this.hoverElement=t;let i=()=>{this.hoverOverlay&&this.hoverElement&&this.hoverElement.isConnected&&this.updateOverlayPosition(this.hoverOverlay,this.hoverElement)};this.hoverUpdateHandler&&(window.removeEventListener("scroll",this.hoverUpdateHandler,!0),window.removeEventListener("resize",this.hoverUpdateHandler)),this.hoverUpdateHandler=i,window.addEventListener("scroll",i,!0),window.addEventListener("resize",i);let a=this.createTooltip();e?a.textContent=e:a.textContent=`<${t.tagName.toLowerCase()}> (\u65E0 source location)`,a.style.display="block";let n=t.getBoundingClientRect();a.style.left=`${n.left+window.scrollX}px`,a.style.top=`${n.top+window.scrollY-a.offsetHeight-8}px`,n.top<a.offsetHeight+8&&(a.style.top=`${n.bottom+window.scrollY+8}px`)}selectElement(t,e){if(!t.isConnected)return;if(this.selectedElement===t&&this.selectedOverlay){this.updateOverlayPosition(this.selectedOverlay,t);return}this.selectedOverlay&&(this.removeOverlay(this.selectedOverlay),this.selectedOverlay=null);let r=this.createOverlay("selected");this.updateOverlayPosition(r,t),this.selectedOverlay=r,this.selectedElement=t;let i=()=>{this.selectedOverlay&&this.selectedElement&&this.selectedElement.isConnected&&this.updateOverlayPosition(this.selectedOverlay,this.selectedElement)};this.selectedUpdateHandler&&(window.removeEventListener("scroll",this.selectedUpdateHandler,!0),window.removeEventListener("resize",this.selectedUpdateHandler)),this.selectedUpdateHandler=i,window.addEventListener("scroll",i,!0),window.addEventListener("resize",i)}removeHighlight(){this.hoverOverlay&&(this.removeOverlay(this.hoverOverlay),this.hoverOverlay=null),this.hoverElement&&(this.hoverElement=null),this.tooltip&&(this.tooltip.style.display="none"),this.hoverUpdateHandler&&(window.removeEventListener("scroll",this.hoverUpdateHandler,!0),window.removeEventListener("resize",this.hoverUpdateHandler),this.hoverUpdateHandler=null)}clearSelection(){this.selectedOverlay&&(this.removeOverlay(this.selectedOverlay),this.selectedOverlay=null),this.selectedElement&&(this.selectedElement=null),this.selectedUpdateHandler&&(window.removeEventListener("scroll",this.selectedUpdateHandler,!0),window.removeEventListener("resize",this.selectedUpdateHandler),this.selectedUpdateHandler=null)}cleanup(){this.removeHighlight(),this.clearSelection(),this.tooltip&&this.tooltip.parentNode&&(this.tooltip.parentNode.removeChild(this.tooltip),this.tooltip=null);let t=document.getElementById("__nvwa-inspector-overlay-style");t&&t.parentNode&&t.parentNode.removeChild(t)}};function Z(t="root"){if(typeof document>"u")return null;let e=document.getElementById(t)||document.body;if(!e)return null;let r=e.querySelector("[data-source-location]");if(r){let i=r.getAttribute("data-source-location");if(i)return i}if(e.firstElementChild){let i=e.firstElementChild.getAttribute("data-source-location");if(i)return i}return null}var Oe={"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 ee(t){let e=t;if(typeof e.kind=="string")return e;if(typeof e.tradeNO=="string")return{kind:"alipay_miniprogram",tradeNO:e.tradeNO};if(typeof e.clientSecret=="string")return{kind:"stripe_client_secret",clientSecret:e.clientSecret};if(typeof e.redirectUrl=="string")return{kind:"redirect_url",redirectUrl:e.redirectUrl};if(typeof e.formHtml=="string")return{kind:"alipay_page",formHtml:e.formHtml};if(typeof e.codeUrl=="string")return{kind:"wechat_native_qr",codeUrl:e.codeUrl};let r=e.jsapiPayParams??e;return typeof r.timeStamp=="string"&&typeof r.nonceStr=="string"&&typeof r.package=="string"&&typeof r.paySign=="string"&&typeof r.appId=="string"?{kind:"wechat_jsapi",mode:"jsapi",jsapiPayParams:{appId:r.appId,timeStamp:r.timeStamp,nonceStr:r.nonceStr,package:r.package,signType:r.signType??"RSA",paySign:r.paySign}}:null}async function te(t,e){let r=t.payment?.providers??{};return Object.entries(r).filter(([,i])=>i.enabled).map(([i])=>{let a=Oe[i]??{id:i,name:i,description:""};return{...a,type:a.id}})}function _(t){return t&&typeof t=="object"?t:{}}function _e(t){let e=_(t),r=e.enabled===!0,i=String(e.oauthCredentialSource??"").toLowerCase();return i?{enabled:r,oauthCredentialSource:i==="custom"?"custom":"nvwa_default"}:{enabled:r}}function W(t){let e=_(t),r=_(e.providers),i={};for(let[a,n]of Object.entries(r))i[a]=_e(n);return{providers:i}}function x(t){let e=_(t);return{socialLogin:W(e.socialLogin),payment:W(e.payment)}}var Ae=["DesktopWeb","MobileWeb","AndroidApp","IosApp","HarmonyApp","WechatMiniProgram","AlipayMiniProgram","DouyinMiniProgram"];function $e(t){return Ae.includes(t)}async function re(t){let{platformType:e,getMiniProgramIdentity:r}=t;if(e!=="WechatMiniProgram"&&e!=="AlipayMiniProgram")return{platformType:e};if(!r)return{platformType:e};let i=await r();return i?{platformType:i.platformType,platformUserId:i.platformUserId,appId:i.appId,unionid:i.unionid}:{platformType:e}}function ie(t){return x(t.integrationProviders??{})}function ae(t){let e=t.baseUrl?.trim()??"";if(!e)throw new Error("Nvwa: appConfig.baseUrl is required");let r=t.applicationCode?.trim()??"";if(!r)throw new Error("Nvwa: appConfig.applicationCode is required");let i=t.platformType?.trim()??"";if(!i)throw new Error("Nvwa: appConfig.platformType is required");if(!$e(i))throw new Error("Nvwa: appConfig.platformType is invalid");return{baseUrl:e,applicationCode:r,platformType:i}}var A=class{constructor(){this.prefix="nvwa_"}getKey(e){return`${this.prefix}${e}`}async get(e){try{let r=this.getKey(e),i=uni.getStorageSync(r);return i?i.expires&&Date.now()>i.expires?(await this.remove(e),null):i.value:null}catch(r){return console.error("UniAppStorageService get error:",r),null}}async set(e,r,i){try{let a=this.getKey(e),n={value:r,expires:i?Date.now()+i*1e3:null,timestamp:Date.now()};uni.setStorageSync(a,n)}catch(a){throw console.error("UniAppStorageService set error:",a),a}}async remove(e){try{let r=this.getKey(e);uni.removeStorageSync(r)}catch(r){throw console.error("UniAppStorageService remove error:",r),r}}async clear(){try{uni.clearStorageSync()}catch(e){throw console.error("UniAppStorageService clear error:",e),e}}};var $=(t,e)=>{let r;if(typeof t=="string")r=t;else if(t&&typeof t.toString=="function")r=t.toString();else if(t?.url)r=t.url;else throw new Error("Invalid input for uniappFetch");typeof console<"u"&&(console.warn("[NvwaUni] request url:",r,"method:",(e?.method||"GET").toUpperCase()),!r.startsWith("http://")&&!r.startsWith("https://")&&console.warn("[NvwaUni] url \u975E\u5B8C\u6574\u5730\u5740\uFF0C\u5C0F\u7A0B\u5E8F uni.request \u4F1A\u62A5 invalid url\uFF0C\u8BF7\u68C0\u67E5 baseUrl \u662F\u5426\u4F20\u5165\u5B8C\u6574\u57DF\u540D"));let i=(e?.method||"GET").toUpperCase(),a={};if(e?.headers){let o=e.headers;if(typeof o?.forEach=="function")o.forEach((c,s)=>{a[s]=c});else if(Array.isArray(o))for(let[c,s]of o)a[c]=s;else Object.assign(a,o)}let n;if(e?.body!==void 0){let o=e.body;if(typeof o=="string")n=o;else if(o&&typeof o=="object"&&typeof o.forEach=="function"){let c={};o.forEach((s,l)=>{c[l]=s}),n=c}else n=o}let h=e?.timeout||3e4;return new Promise((o,c)=>{let s=e?.signal;if(s?.aborted){let p=new Error("The operation was aborted");p.name="AbortError",c(p);return}let l=!1,u=[],m=uni.request({url:r,method:i,data:n,header:a,timeout:h,success:p=>{if(l)return;l=!0;let d=p.statusCode,f="",y=new w,L=p.header||p.headers||{};Object.keys(L).forEach(C=>{let I=L[C];y.set(C,typeof I=="string"?I:String(I))}),o(new G(p.data,{status:d,statusText:f,headers:y}))},fail:p=>{if(l)return;l=!0;let d=p?.errMsg||p?.message||"Network Error",f=new Error(d);/(abort|aborted|canceled|cancelled)/i.test(String(d))&&(f.name="AbortError"),c(f)}});if(s&&typeof s.addEventListener=="function"){let p=()=>{if(l)return;try{m?.abort?.()}catch{}let d=new Error("The operation was aborted");d.name="AbortError",l=!0,c(d)};s.addEventListener("abort",p),u.push(()=>{try{s.removeEventListener?.("abort",p)}catch{}})}})};globalThis&&typeof globalThis.fetch!="function"&&(globalThis.fetch=$);function Ie(t){return`https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=${encodeURIComponent(t)}`}function ne(t){if(typeof window<"u"){window.open(t,"_blank");return}globalThis.plus?.runtime?.openURL?.(t)}async function Ue(t){if(t.kind!=="alipay_miniprogram")throw new Error("requestPayment: invalid payParams for alipay miniprogram");await new Promise((e,r)=>{let i=globalThis.my;if(!i?.tradePay){r(new Error("requestPayment: my.tradePay is unavailable"));return}i.tradePay({tradeNO:t.tradeNO,success:()=>e(),fail:a=>r(a)})})}async function ke(t){if(t.kind!=="wechat_jsapi")throw new Error("requestPayment: invalid payParams for wechat jsapi");let e=t.jsapiPayParams;await new Promise((r,i)=>{uni.requestPayment({provider:"wxpay",timeStamp:e.timeStamp,nonceStr:e.nonceStr,package:e.package,signType:e.signType??"RSA",paySign:e.paySign,success:()=>r(),fail:a=>i(a)})})}function xe(t){if(t.kind!=="redirect_url")throw new Error("requestPayment: invalid payParams for redirect");typeof window<"u"?window.location.href=t.redirectUrl:ne(t.redirectUrl)}function Ne(t){if(t.kind!=="wechat_native_qr")throw new Error("requestPayment: invalid payParams for wechat qr");let e=Ie(t.codeUrl);ne(e)}function Re(t){if(t.kind!=="alipay_page")throw new Error("requestPayment: invalid payParams for alipay page");if(typeof document>"u"||!document.body)throw new Error("requestPayment: alipay_page (formHtml) requires a browser/WebView environment (e.g. H5 or App webview)");let e=t.formHtml,a=new DOMParser().parseFromString(e,"text/html").querySelector("form");if(!a)throw new Error("requestPayment: alipay_page formHtml does not contain a form element");let n=document.importNode(a,!0);n.setAttribute("style","display:none"),document.body.appendChild(n),n.submit()}async function je(t){if(!t)return!1;switch(t.kind){case"alipay_miniprogram":return await Ue(t),!0;case"alipay_page":return Re(t),!0;case"wechat_jsapi":return await ke(t),!0;case"redirect_url":return xe(t),!0;case"wechat_native_qr":return Ne(t),!0;default:return!1}}var N={async requestPayment(t,e){try{let r=ee(t);if(!await je(r))throw new Error("requestPayment: unsupported payParams for current endpoint");e?.onSuccess?.()}catch(r){throw e?.onFailure?.(r),r}}};function se(t){let e=async r=>await te(t,r);return{...N,getAvailableProviders:e,getProviders:e}}function ft(){if(typeof window>"u"||window===window.parent)return;let t=!1,e=new X;function r(s){if(!s)return!1;let l=s.toLowerCase();return l.includes("/components/")||l.includes("\\components\\")}function i(s){let l=s,u=null;for(;l;){let m=l.getAttribute("data-source-location");if(m)if(r(m)){u||(u=m),l=l.parentElement;continue}else return m;l=l.parentElement}return u}let a=null;function n(s){t&&(a!==null&&cancelAnimationFrame(a),a=requestAnimationFrame(()=>{let l=s.target;if(!l||l===document.body||l===document.documentElement){e.removeHighlight();return}if(l.tagName.toLowerCase()==="img"){let d=i(l);e.highlightElement(l,d);let f={type:"HOVER_INSPECTOR_ELEMENT_HOVER",sourceLocation:d,elementInfo:{tagName:l.tagName.toLowerCase(),className:l.className||"",id:l.id||""}};window.parent.postMessage(f,"*");return}let u=l,m=i(l);if(!m){let d=l.parentElement;for(;d&&d!==document.body&&d!==document.documentElement;){let f=i(d);if(f){u=d,m=f;break}d=d.parentElement}}e.highlightElement(u,m);let p={type:"HOVER_INSPECTOR_ELEMENT_HOVER",sourceLocation:m,elementInfo:{tagName:u.tagName.toLowerCase(),className:u.className||"",id:u.id||""}};window.parent.postMessage(p,"*")}))}function h(){if(!t)return;e.removeHighlight();let s={type:"HOVER_INSPECTOR_ELEMENT_LEAVE"};window.parent.postMessage(s,"*")}function o(s){if(!t)return;s.preventDefault(),s.stopPropagation();let l=s.target;if(!l||l===document.body||l===document.documentElement)return;let u=i(l);e.selectElement(l,u);let m={type:"HOVER_INSPECTOR_ELEMENT_SELECT",sourceLocation:u,elementInfo:{tagName:l.tagName.toLowerCase(),className:l.className||"",id:l.id||""}};window.parent.postMessage(m,"*")}function c(s){s.data?.type==="HOVER_INSPECTOR_ENABLE"?(t=!0,document.addEventListener("mousemove",n),document.addEventListener("mouseleave",h),document.addEventListener("click",o,!0)):s.data?.type==="HOVER_INSPECTOR_DISABLE"&&(t=!1,document.removeEventListener("mousemove",n),document.removeEventListener("mouseleave",h),document.removeEventListener("click",o,!0),e.removeHighlight(),e.clearSelection())}return window.addEventListener("message",c),()=>{window.removeEventListener("message",c),document.removeEventListener("mousemove",n),document.removeEventListener("mouseleave",h),document.removeEventListener("click",o,!0),e.cleanup()}}function yt(t,e){if(!t||!t.contentWindow)throw new Error("Invalid iframe element");let r={type:"HOVER_INSPECTOR_ENABLE"};t.contentWindow.postMessage(r,e)}function wt(t,e){if(!t||!t.contentWindow)return;let r={type:"HOVER_INSPECTOR_DISABLE"};t.contentWindow.postMessage(r,e)}function vt(t,e,r=5e3){return new Promise((i,a)=>{if(!t||!t.contentWindow){a(new Error("Invalid iframe element"));return}let n=`source-location-${Date.now()}-${Math.random()}`,h=setTimeout(()=>{window.removeEventListener("message",o),a(new Error("Request timeout"))},r),o=s=>{s.origin===e&&s.data?.type==="GET_SOURCE_LOCATION_RESPONSE"&&s.data?.requestId===n&&(clearTimeout(h),window.removeEventListener("message",o),s.data.error?a(new Error(s.data.error)):i(s.data.sourceLocation||null))};window.addEventListener("message",o);let c={type:"GET_SOURCE_LOCATION_REQUEST",requestId:n};try{t.contentWindow.postMessage(c,e)}catch(s){clearTimeout(h),window.removeEventListener("message",o),a(s)}})}function bt(){if(typeof window>"u"||window===window.parent)return;let t=e=>{if(e.data?.type==="GET_SOURCE_LOCATION_REQUEST")try{let i={type:"GET_SOURCE_LOCATION_RESPONSE",sourceLocation:Me(),requestId:e.data.requestId};window.parent.postMessage(i,e.origin)}catch(r){let i={type:"GET_SOURCE_LOCATION_RESPONSE",sourceLocation:null,error:r instanceof Error?r.message:"Unknown error",requestId:e.data.requestId};window.parent.postMessage(i,e.origin)}};return window.addEventListener("message",t),()=>{window.removeEventListener("message",t)}}function Me(){return Z("app")}function He(t){let e=t==="wechat-miniprogram"?"weixin":t==="alipay-miniprogram"?"alipay":t==="douyin-miniprogram"?"toutiao":void 0;return e?new Promise((r,i)=>{uni.login({provider:e,success:a=>{if(!a.code?.trim()){i(new Error(`login code missing for ${t}`));return}r(a.code.trim())},fail:a=>{i(a instanceof Error?a:new Error(`uni.login failed: ${String(a)}`))}})}):Promise.reject(new Error(`unsupported miniprogram provider: ${t}`))}async function qe(t,e){return e??await t.getSocialProviderDescriptors()}function oe(t){return t?.trim()?t.trim():typeof globalThis<"u"&&"location"in globalThis?globalThis.location.href:""}function St(t){let{name:e="NvwaSocialLoginButtons",auth:r,applicationCode:i,providers:a,containerClass:n="nvwa-social-login-list",providerClass:h="nvwa-social-login-button"}=t,o=t.resolveMiniProgramCode??He;return{name:e,data(){return{providers:[],loading:!0}},async created(){try{this.providers=await qe(r,a)}catch(c){t.onError?.(c instanceof Error?c:new Error(String(c)))}finally{this.loading=!1}},methods:{async handleProviderTap(c){try{if(t.onBeforeLogin?.(c),c.loginKind==="wechat_miniprogram_code"||c.loginKind==="alipay_miniprogram_code"){let s=await o(c.id);await r.startSocialLogin(c.id,{miniProgramCode:s,applicationCode:i,returnUrl:oe(t.returnUrl)});return}await r.startSocialLogin(c.id,{returnUrl:oe(t.returnUrl),applicationCode:i})}catch(s){t.onError?.(s instanceof Error?s:new Error(String(s)))}}},render(){if(this.loading||this.providers.length===0)return null;let c=this.$createElement,s=this.providers.filter(l=>l.loginKind!=="unsupported").map(l=>c("button",{key:l.id,class:h,attrs:{type:"button"},on:{click:()=>this.handleProviderTap(l)}},l.name));return c("view",{class:n},s)}}}var le=new A,R=class{constructor(e){this.payment=N;let{handleUnauthorized:r,appConfig:i,integrationProviders:a}=e,n=ae(i);typeof console<"u"&&console.warn("[Nvwa] uniapp init baseUrl:",n.baseUrl||"(empty)"),this.applicationCode=n.applicationCode,this.platformType=n.platformType,this.integrationProviders=x(a??ie(i)),this.auth=new z(n.baseUrl,{fetchImpl:$,storage:le,integrationProviders:this.integrationProviders,applicationCode:this.applicationCode,platformType:n.platformType}),this.httpClient=new K(le,$,r),this.fileStorage=new V(n.baseUrl,this.httpClient),this.entities=Q(n.baseUrl,this.httpClient),this.functions=new B(this.httpClient,n.baseUrl);let h=se(this.integrationProviders);this.payment={...h,collectPaymentClientContext:()=>re({platformType:this.platformType,getMiniProgramIdentity:()=>this.auth.getMiniProgramIdentity()})}}};export{St as createSocialLoginComponent,R as default,wt as disableIframeHoverInspector,yt as enableIframeHoverInspector,vt as getIframeSourceLocation,le as localStorage,ft as setupIframeHoverInspector,bt as setupIframeSourceLocationListener};
36
+ `,document.head.appendChild(t)}createTooltip(){return this.tooltip?this.tooltip:(this.tooltip=document.createElement("div"),this.tooltip.id="__nvwa-inspector-tooltip",document.body.appendChild(this.tooltip),this.tooltip)}createOverlay(t){let e=document.createElement("div");return e.className=`__nvwa-inspector-overlay __nvwa-inspector-overlay-${t}`,document.body.appendChild(e),e}updateOverlayPosition(t,e){if(!e.isConnected)return;let r=e.getBoundingClientRect(),a=window.scrollX||window.pageXOffset,i=window.scrollY||window.pageYOffset;r.width>0&&r.height>0?(t.style.left=`${r.left+a}px`,t.style.top=`${r.top+i}px`,t.style.width=`${r.width}px`,t.style.height=`${r.height}px`,t.style.display="block"):t.style.display="none"}removeOverlay(t){t&&t.parentNode&&t.parentNode.removeChild(t)}highlightElement(t,e){if(!t.isConnected)return;if(this.hoverElement===t&&this.hoverOverlay){this.updateOverlayPosition(this.hoverOverlay,t);let h=this.createTooltip();e?h.textContent=e:h.textContent=`<${t.tagName.toLowerCase()}> (\u65E0 source location)`,h.style.display="block";let o=t.getBoundingClientRect();h.style.left=`${o.left+window.scrollX}px`,h.style.top=`${o.top+window.scrollY-h.offsetHeight-8}px`,o.top<h.offsetHeight+8&&(h.style.top=`${o.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 a=()=>{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=a,window.addEventListener("scroll",a,!0),window.addEventListener("resize",a);let i=this.createTooltip();e?i.textContent=e:i.textContent=`<${t.tagName.toLowerCase()}> (\u65E0 source location)`,i.style.display="block";let n=t.getBoundingClientRect();i.style.left=`${n.left+window.scrollX}px`,i.style.top=`${n.top+window.scrollY-i.offsetHeight-8}px`,n.top<i.offsetHeight+8&&(i.style.top=`${n.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 a=()=>{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=a,window.addEventListener("scroll",a,!0),window.addEventListener("resize",a)}removeHighlight(){this.hoverOverlay&&(this.removeOverlay(this.hoverOverlay),this.hoverOverlay=null),this.hoverElement&&(this.hoverElement=null),this.tooltip&&(this.tooltip.style.display="none"),this.hoverUpdateHandler&&(window.removeEventListener("scroll",this.hoverUpdateHandler,!0),window.removeEventListener("resize",this.hoverUpdateHandler),this.hoverUpdateHandler=null)}clearSelection(){this.selectedOverlay&&(this.removeOverlay(this.selectedOverlay),this.selectedOverlay=null),this.selectedElement&&(this.selectedElement=null),this.selectedUpdateHandler&&(window.removeEventListener("scroll",this.selectedUpdateHandler,!0),window.removeEventListener("resize",this.selectedUpdateHandler),this.selectedUpdateHandler=null)}cleanup(){this.removeHighlight(),this.clearSelection(),this.tooltip&&this.tooltip.parentNode&&(this.tooltip.parentNode.removeChild(this.tooltip),this.tooltip=null);let t=document.getElementById("__nvwa-inspector-overlay-style");t&&t.parentNode&&t.parentNode.removeChild(t)}};function ee(t="root"){if(typeof document>"u")return null;let e=document.getElementById(t)||document.body;if(!e)return null;let r=e.querySelector("[data-source-location]");if(r){let a=r.getAttribute("data-source-location");if(a)return a}if(e.firstElementChild){let a=e.firstElementChild.getAttribute("data-source-location");if(a)return a}return null}var $e={"wechat-pay":{id:"wechat-pay",name:"WeChat Pay",description:"WeChat payment for web and miniapp."},"wechat-platform":{id:"wechat-platform",name:"WeChat Partner",description:"WeChat partner merchant onboarding."},"alipay-web":{id:"alipay-web",name:"Alipay Web",description:"Alipay page pay (ISV)."},"alipay-mobile-web":{id:"alipay-mobile-web",name:"Alipay Mobile Web",description:"Alipay WAP pay (ISV)."},"alipay-miniprogram":{id:"alipay-miniprogram",name:"Alipay Mini Program",description:"Alipay mini program payment."},stripe:{id:"stripe",name:"Stripe",description:"Stripe payment."}};function te(t){let e=t;if(typeof e.kind=="string")return e;if(typeof e.tradeNO=="string")return{kind:"alipay_miniprogram",tradeNO:e.tradeNO};if(typeof e.clientSecret=="string")return{kind:"stripe_client_secret",clientSecret:e.clientSecret};if(typeof e.redirectUrl=="string")return{kind:"redirect_url",redirectUrl:e.redirectUrl};if(typeof e.formHtml=="string")return{kind:"alipay_page",formHtml:e.formHtml};if(typeof e.codeUrl=="string")return{kind:"wechat_native_qr",codeUrl:e.codeUrl};let r=e.jsapiPayParams??e;return typeof r.timeStamp=="string"&&typeof r.nonceStr=="string"&&typeof r.package=="string"&&typeof r.paySign=="string"&&typeof r.appId=="string"?{kind:"wechat_jsapi",mode:"jsapi",jsapiPayParams:{appId:r.appId,timeStamp:r.timeStamp,nonceStr:r.nonceStr,package:r.package,signType:r.signType??"RSA",paySign:r.paySign}}:null}async function re(t,e){let r=t.payment?.providers??{};return Object.entries(r).filter(([,a])=>a.enabled).map(([a])=>{let i=$e[a]??{id:a,name:a,description:""};return{...i,type:i.id}})}function _(t){return t&&typeof t=="object"?t:{}}function Ie(t){let e=_(t),r=e.enabled===!0,a=String(e.oauthCredentialSource??"").toLowerCase();return a?{enabled:r,oauthCredentialSource:a==="custom"?"custom":"nvwa_default"}:{enabled:r}}function F(t){let e=_(t),r=_(e.providers),a={};for(let[i,n]of Object.entries(r))a[i]=Ie(n);return{providers:a}}function x(t){let e=_(t);return{socialLogin:F(e.socialLogin),payment:F(e.payment)}}var ke=["DesktopWeb","MobileWeb","AndroidApp","IosApp","HarmonyApp","WechatMiniProgram","AlipayMiniProgram","DouyinMiniProgram"];function Ue(t){return ke.includes(t)}async function ae(t){let{platformType:e,getMiniProgramIdentity:r}=t;if(e!=="WechatMiniProgram"&&e!=="AlipayMiniProgram")return{platformType:e};if(!r)return{platformType:e};let a=await r();return a?{platformType:a.platformType,platformUserId:a.platformUserId,appId:a.appId,unionid:a.unionid}:{platformType:e}}function ie(t){return x(t.integrationProviders??{})}function ne(t){let e=t.baseUrl?.trim()??"";if(!e)throw new Error("Nvwa: appConfig.baseUrl is required");let r=t.applicationCode?.trim()??"";if(!r)throw new Error("Nvwa: appConfig.applicationCode is required");let a=t.platformType?.trim()??"";if(!a)throw new Error("Nvwa: appConfig.platformType is required");if(!Ue(a))throw new Error("Nvwa: appConfig.platformType is invalid");return{baseUrl:e,applicationCode:r,platformType:a}}var A=class{constructor(){this.prefix="nvwa_"}getKey(e){return`${this.prefix}${e}`}async get(e){try{let r=this.getKey(e),a=uni.getStorageSync(r);return a?a.expires&&Date.now()>a.expires?(await this.remove(e),null):a.value:null}catch(r){return console.error("UniAppStorageService get error:",r),null}}async set(e,r,a){try{let i=this.getKey(e),n={value:r,expires:a?Date.now()+a*1e3:null,timestamp:Date.now()};uni.setStorageSync(i,n)}catch(i){throw console.error("UniAppStorageService set error:",i),i}}async remove(e){try{let r=this.getKey(e);uni.removeStorageSync(r)}catch(r){throw console.error("UniAppStorageService remove error:",r),r}}async clear(){try{uni.clearStorageSync()}catch(e){throw console.error("UniAppStorageService clear error:",e),e}}};var $=(t,e)=>{let r;if(typeof t=="string")r=t;else if(t&&typeof t.toString=="function")r=t.toString();else if(t?.url)r=t.url;else throw new Error("Invalid input for uniappFetch");typeof console<"u"&&(console.warn("[NvwaUni] request url:",r,"method:",(e?.method||"GET").toUpperCase()),!r.startsWith("http://")&&!r.startsWith("https://")&&console.warn("[NvwaUni] url \u975E\u5B8C\u6574\u5730\u5740\uFF0C\u5C0F\u7A0B\u5E8F uni.request \u4F1A\u62A5 invalid url\uFF0C\u8BF7\u68C0\u67E5 baseUrl \u662F\u5426\u4F20\u5165\u5B8C\u6574\u57DF\u540D"));let a=(e?.method||"GET").toUpperCase(),i={};if(e?.headers){let o=e.headers;if(typeof o?.forEach=="function")o.forEach((c,s)=>{i[s]=c});else if(Array.isArray(o))for(let[c,s]of o)i[c]=s;else Object.assign(i,o)}let n;if(e?.body!==void 0){let o=e.body;if(typeof o=="string")n=o;else if(o&&typeof o=="object"&&typeof o.forEach=="function"){let c={};o.forEach((s,l)=>{c[l]=s}),n=c}else n=o}let h=e?.timeout||3e4;return new Promise((o,c)=>{let s=e?.signal;if(s?.aborted){let p=new Error("The operation was aborted");p.name="AbortError",c(p);return}let l=!1,u=[],m=uni.request({url:r,method:a,data:n,header:i,timeout:h,success:p=>{if(l)return;l=!0;let d=p.statusCode,f="",y=new w,O=p.header||p.headers||{};Object.keys(O).forEach(C=>{let I=O[C];y.set(C,typeof I=="string"?I:String(I))}),o(new B(p.data,{status:d,statusText:f,headers:y}))},fail:p=>{if(l)return;l=!0;let d=p?.errMsg||p?.message||"Network Error",f=new Error(d);/(abort|aborted|canceled|cancelled)/i.test(String(d))&&(f.name="AbortError"),c(f)}});if(s&&typeof s.addEventListener=="function"){let p=()=>{if(l)return;try{m?.abort?.()}catch{}let d=new Error("The operation was aborted");d.name="AbortError",l=!0,c(d)};s.addEventListener("abort",p),u.push(()=>{try{s.removeEventListener?.("abort",p)}catch{}})}})};globalThis&&typeof globalThis.fetch!="function"&&(globalThis.fetch=$);function xe(t){return`https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=${encodeURIComponent(t)}`}function se(t){if(typeof window<"u"){window.open(t,"_blank");return}globalThis.plus?.runtime?.openURL?.(t)}async function Ne(t){if(t.kind!=="alipay_miniprogram")throw new Error("requestPayment: invalid payParams for alipay miniprogram");await new Promise((e,r)=>{let a=globalThis.my;if(!a?.tradePay){r(new Error("requestPayment: my.tradePay is unavailable"));return}a.tradePay({tradeNO:t.tradeNO,success:()=>e(),fail:i=>r(i)})})}async function Re(t){if(t.kind!=="wechat_jsapi")throw new Error("requestPayment: invalid payParams for wechat jsapi");let e=t.jsapiPayParams;await new Promise((r,a)=>{uni.requestPayment({provider:"wxpay",timeStamp:e.timeStamp,nonceStr:e.nonceStr,package:e.package,signType:e.signType??"RSA",paySign:e.paySign,success:()=>r(),fail:i=>a(i)})})}function je(t){if(t.kind!=="redirect_url")throw new Error("requestPayment: invalid payParams for redirect");typeof window<"u"?window.location.href=t.redirectUrl:se(t.redirectUrl)}function Me(t){if(t.kind!=="wechat_native_qr")throw new Error("requestPayment: invalid payParams for wechat qr");let e=xe(t.codeUrl);se(e)}function He(t){if(t.kind!=="alipay_page")throw new Error("requestPayment: invalid payParams for alipay page");if(typeof document>"u"||!document.body)throw new Error("requestPayment: alipay_page (formHtml) requires a browser/WebView environment (e.g. H5 or App webview)");let e=t.formHtml,i=new DOMParser().parseFromString(e,"text/html").querySelector("form");if(!i)throw new Error("requestPayment: alipay_page formHtml does not contain a form element");let n=document.importNode(i,!0);n.setAttribute("style","display:none"),document.body.appendChild(n),n.submit()}async function qe(t){if(!t)return!1;switch(t.kind){case"alipay_miniprogram":return await Ne(t),!0;case"alipay_page":return He(t),!0;case"wechat_jsapi":return await Re(t),!0;case"redirect_url":return je(t),!0;case"wechat_native_qr":return Me(t),!0;default:return!1}}var N={async requestPayment(t,e){try{let r=te(t);if(!await qe(r))throw new Error("requestPayment: unsupported payParams for current endpoint");e?.onSuccess?.()}catch(r){throw e?.onFailure?.(r),r}}};function oe(t){let e=async r=>await re(t,r);return{...N,getAvailableProviders:e,getProviders:e}}function bt(){if(typeof window>"u"||window===window.parent)return;let t=!1,e=new Z;function r(s){if(!s)return!1;let l=s.toLowerCase();return l.includes("/components/")||l.includes("\\components\\")}function a(s){let l=s,u=null;for(;l;){let m=l.getAttribute("data-source-location");if(m)if(r(m)){u||(u=m),l=l.parentElement;continue}else return m;l=l.parentElement}return u}let i=null;function n(s){t&&(i!==null&&cancelAnimationFrame(i),i=requestAnimationFrame(()=>{let l=s.target;if(!l||l===document.body||l===document.documentElement){e.removeHighlight();return}if(l.tagName.toLowerCase()==="img"){let d=a(l);e.highlightElement(l,d);let f={type:"HOVER_INSPECTOR_ELEMENT_HOVER",sourceLocation:d,elementInfo:{tagName:l.tagName.toLowerCase(),className:l.className||"",id:l.id||""}};window.parent.postMessage(f,"*");return}let u=l,m=a(l);if(!m){let d=l.parentElement;for(;d&&d!==document.body&&d!==document.documentElement;){let f=a(d);if(f){u=d,m=f;break}d=d.parentElement}}e.highlightElement(u,m);let p={type:"HOVER_INSPECTOR_ELEMENT_HOVER",sourceLocation:m,elementInfo:{tagName:u.tagName.toLowerCase(),className:u.className||"",id:u.id||""}};window.parent.postMessage(p,"*")}))}function h(){if(!t)return;e.removeHighlight();let s={type:"HOVER_INSPECTOR_ELEMENT_LEAVE"};window.parent.postMessage(s,"*")}function o(s){if(!t)return;s.preventDefault(),s.stopPropagation();let l=s.target;if(!l||l===document.body||l===document.documentElement)return;let u=a(l);e.selectElement(l,u);let m={type:"HOVER_INSPECTOR_ELEMENT_SELECT",sourceLocation:u,elementInfo:{tagName:l.tagName.toLowerCase(),className:l.className||"",id:l.id||""}};window.parent.postMessage(m,"*")}function c(s){s.data?.type==="HOVER_INSPECTOR_ENABLE"?(t=!0,document.addEventListener("mousemove",n),document.addEventListener("mouseleave",h),document.addEventListener("click",o,!0)):s.data?.type==="HOVER_INSPECTOR_DISABLE"&&(t=!1,document.removeEventListener("mousemove",n),document.removeEventListener("mouseleave",h),document.removeEventListener("click",o,!0),e.removeHighlight(),e.clearSelection())}return window.addEventListener("message",c),()=>{window.removeEventListener("message",c),document.removeEventListener("mousemove",n),document.removeEventListener("mouseleave",h),document.removeEventListener("click",o,!0),e.cleanup()}}function Pt(t,e){if(!t||!t.contentWindow)throw new Error("Invalid iframe element");let r={type:"HOVER_INSPECTOR_ENABLE"};t.contentWindow.postMessage(r,e)}function Et(t,e){if(!t||!t.contentWindow)return;let r={type:"HOVER_INSPECTOR_DISABLE"};t.contentWindow.postMessage(r,e)}function St(t,e,r=5e3){return new Promise((a,i)=>{if(!t||!t.contentWindow){i(new Error("Invalid iframe element"));return}let n=`source-location-${Date.now()}-${Math.random()}`,h=setTimeout(()=>{window.removeEventListener("message",o),i(new Error("Request timeout"))},r),o=s=>{s.origin===e&&s.data?.type==="GET_SOURCE_LOCATION_RESPONSE"&&s.data?.requestId===n&&(clearTimeout(h),window.removeEventListener("message",o),s.data.error?i(new Error(s.data.error)):a(s.data.sourceLocation||null))};window.addEventListener("message",o);let c={type:"GET_SOURCE_LOCATION_REQUEST",requestId:n};try{t.contentWindow.postMessage(c,e)}catch(s){clearTimeout(h),window.removeEventListener("message",o),i(s)}})}function Ct(){if(typeof window>"u"||window===window.parent)return;let t=e=>{if(e.data?.type==="GET_SOURCE_LOCATION_REQUEST")try{let a={type:"GET_SOURCE_LOCATION_RESPONSE",sourceLocation:We(),requestId:e.data.requestId};window.parent.postMessage(a,e.origin)}catch(r){let a={type:"GET_SOURCE_LOCATION_RESPONSE",sourceLocation:null,error:r instanceof Error?r.message:"Unknown error",requestId:e.data.requestId};window.parent.postMessage(a,e.origin)}};return window.addEventListener("message",t),()=>{window.removeEventListener("message",t)}}function We(){return ee("app")}function Fe(t){let e=t==="wechat-miniprogram"?"weixin":t==="alipay-miniprogram"?"alipay":t==="douyin-miniprogram"?"toutiao":void 0;return e?new Promise((r,a)=>{uni.login({provider:e,success:i=>{if(!i.code?.trim()){a(new Error(`login code missing for ${t}`));return}r(i.code.trim())},fail:i=>{a(i instanceof Error?i:new Error(`uni.login failed: ${String(i)}`))}})}):Promise.reject(new Error(`unsupported miniprogram provider: ${t}`))}async function De(t,e){return e??await t.getSocialProviderDescriptors()}function le(t){return t?.trim()?t.trim():typeof globalThis<"u"&&"location"in globalThis?globalThis.location.href:""}function Lt(t){let{name:e="NvwaSocialLoginButtons",auth:r,applicationCode:a,providers:i,containerClass:n="nvwa-social-login-list",providerClass:h="nvwa-social-login-button"}=t,o=t.resolveMiniProgramCode??Fe;return{name:e,data(){return{providers:[],loading:!0}},async created(){try{this.providers=await De(r,i)}catch(c){t.onError?.(c instanceof Error?c:new Error(String(c)))}finally{this.loading=!1}},methods:{async handleProviderTap(c){try{if(t.onBeforeLogin?.(c),c.loginKind==="wechat_miniprogram_code"||c.loginKind==="alipay_miniprogram_code"){let s=await o(c.id);await r.startSocialLogin(c.id,{miniProgramCode:s,applicationCode:a,returnUrl:le(t.returnUrl)});return}await r.startSocialLogin(c.id,{returnUrl:le(t.returnUrl),applicationCode:a})}catch(s){t.onError?.(s instanceof Error?s:new Error(String(s)))}}},render(){if(this.loading||this.providers.length===0)return null;let c=this.$createElement,s=this.providers.filter(l=>l.loginKind!=="unsupported").map(l=>c("button",{key:l.id,class:h,attrs:{type:"button"},on:{click:()=>this.handleProviderTap(l)}},l.name));return c("view",{class:n},s)}}}var he=new A,R=class{constructor(e){this.payment=N;let{handleUnauthorized:r,appConfig:a,integrationProviders:i}=e,n=ne(a);typeof console<"u"&&console.warn("[Nvwa] uniapp init baseUrl:",n.baseUrl||"(empty)"),this.applicationCode=n.applicationCode,this.platformType=n.platformType,this.integrationProviders=x(i??ie(a)),this.auth=new K(n.baseUrl,{fetchImpl:$,storage:he,integrationProviders:this.integrationProviders,applicationCode:this.applicationCode,platformType:n.platformType}),this.httpClient=new V(he,$,r),this.fileStorage=new Y(n.baseUrl,this.httpClient),this.entities=X(n.baseUrl,this.httpClient),this.functions=new J(this.httpClient,n.baseUrl);let h=oe(this.integrationProviders);this.payment={...h,collectPaymentClientContext:()=>ae({platformType:this.platformType,getMiniProgramIdentity:()=>this.auth.getMiniProgramIdentity()})}}};export{Lt as createSocialLoginComponent,R as default,Et as disableIframeHoverInspector,Pt as enableIframeHoverInspector,St as getIframeSourceLocation,he as localStorage,bt as setupIframeHoverInspector,Ct as setupIframeSourceLocationListener};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nvwa-app/sdk-uniapp",
3
- "version": "6.47.0",
3
+ "version": "6.48.0",
4
4
  "description": "NVWA跨端通用工具类UniApp端实现",
5
5
  "main": "dist/index.js",
6
6
  "module": "dist/index.mjs",