@nvwa-app/sdk-core 6.16.0 → 6.18.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.mts CHANGED
@@ -3,12 +3,29 @@ import { PostgrestClient } from '@nvwa-app/postgrest-js';
3
3
  import { NvwaFetch, URL, RequestInfo, RequestInit, Response, Headers } from '@nvwa-app/nvwa-http-polyfill';
4
4
  export { Headers, NvwaFetch, Request, RequestInfo, RequestInit, Response, URL } from '@nvwa-app/nvwa-http-polyfill';
5
5
 
6
+ type OAuthCredentialSource = "nvwa_default" | "custom";
7
+ interface IntegrationProviderConfig {
8
+ enabled: boolean;
9
+ oauthCredentialSource?: OAuthCredentialSource;
10
+ }
11
+ interface IntegrationProvidersEntry {
12
+ providers: Record<string, IntegrationProviderConfig>;
13
+ }
14
+ interface IntegrationProvidersConfig {
15
+ socialLogin?: IntegrationProvidersEntry;
16
+ payment?: IntegrationProvidersEntry;
17
+ }
18
+ declare function normalizeIntegrationProvidersConfig(input: unknown): IntegrationProvidersConfig;
19
+ declare function parseIntegrationProvidersJson(jsonInput: string | undefined | null): IntegrationProvidersConfig;
20
+ declare function getEnabledProvidersByIntegration(integrationProviders: IntegrationProvidersConfig, integrationKey: "socialLogin" | "payment"): string[];
21
+
6
22
  /**
7
23
  * Payment 纯前端能力:仅「发起支付」。
8
24
  * 流程:create order(不传端类型)→ 返回 order 标识;再按 orderId + 端类型请求 getPaymentInfo 得到 payParams;
9
25
  * 前端用 nvwa.payment.requestPayment(payParams) 调起。端类型由 INvwa.getEndpointType() 提供。
10
26
  * 与 Workspace 积分充值无关。
11
27
  */
28
+
12
29
  /**
13
30
  * 业务 create order 返回的 payParams 形态,供 launcher 调起支付。
14
31
  * 与 payment-gateway 一致:codeUrl(扫码)、formHtml(跳转/表单)、
@@ -65,6 +82,11 @@ interface PaymentRequestCallbacks {
65
82
  onSuccess?: () => void;
66
83
  onFailure?: (error: unknown) => void;
67
84
  }
85
+ interface PaymentProvider {
86
+ id: string;
87
+ name: string;
88
+ description: string;
89
+ }
68
90
  declare function normalizePayParams(payParams: PayParams): TypedPayParams | null;
69
91
  /**
70
92
  * 发起支付:接收 payParams,按当前端类型与渠道完成调起。
@@ -73,6 +95,14 @@ declare function normalizePayParams(payParams: PayParams): TypedPayParams | null
73
95
  */
74
96
  interface IPaymentLauncher {
75
97
  requestPayment(payParams: PayParams, callbacks?: PaymentRequestCallbacks): Promise<void>;
98
+ /** 获取当前应用/平台下可用支付渠道(基于编译期 integrationProviders)。 */
99
+ getAvailableProviders?(params?: {
100
+ force?: boolean;
101
+ }): Promise<PaymentProvider[]>;
102
+ /** @deprecated 请使用 getAvailableProviders。 */
103
+ getProviders?(params?: {
104
+ force?: boolean;
105
+ }): Promise<PaymentProvider[]>;
76
106
  }
77
107
  /**
78
108
  * 业务层 create order 返回给前端的订单结果(与 examples payment-create-order 对齐)。
@@ -97,59 +127,9 @@ type CreatePaymentResponse = PaymentOrderResult;
97
127
  * 从业务 create order 返回结果发起的纯前端封装:不发起任何后端请求。
98
128
  */
99
129
  declare function requestPaymentFromOrderResult(result: PaymentOrderResult, launcher: IPaymentLauncher, callbacks?: PaymentRequestCallbacks): Promise<void>;
100
-
101
- /** 仅能在构造 `Nvwa` / `NvwaIntegrationSnapshot` 时传入;`load()` 不再接受应用/端或语言覆盖 */
102
- interface IntegrationSnapshotContext {
103
- applicationCode: string;
104
- platformCode: string;
105
- /** 默认 `zh`;非 `en` 则按中文 */
106
- locale?: string;
107
- }
108
- interface IntegrationSnapshotProvider {
109
- id: string;
110
- name: string;
111
- description: string;
112
- enabled: boolean;
113
- oauthCredentialSource?: "nvwa_default" | "custom";
114
- }
115
- interface IntegrationSnapshotItem {
116
- integrationType: string;
117
- enabled: boolean;
118
- providers?: IntegrationSnapshotProvider[];
119
- }
120
- interface IntegrationSnapshot {
121
- projectCode: string;
122
- applicationCode: string;
123
- platformCode: string;
124
- integrations: IntegrationSnapshotItem[];
125
- }
126
- /**
127
- * 经 Runtime `GET /nvwa/integration-snapshot` 拉取快照(Runtime 再 HMAC 调 Server internal)。
128
- * 应用/端与默认语言仅在构造时通过 `IntegrationSnapshotContext` 传入;`load()` 仅支持 `force` 刷新缓存。
129
- */
130
- declare class NvwaIntegrationSnapshot {
131
- private readonly baseUrl;
132
- private readonly fetchImpl;
133
- private readonly context;
134
- private cache;
135
- constructor(baseUrl: string, fetchImpl: NvwaFetch, context: IntegrationSnapshotContext);
136
- /** 当前缓存的快照(未 load 过则为 null) */
137
- get(): IntegrationSnapshot | null;
138
- /**
139
- * 从当前缓存快照中取某一 integration(如 `social-login`),未 load 或不存在则 null。
140
- */
141
- getIntegrationItem(integrationType: string): IntegrationSnapshotItem | null;
142
- /**
143
- * 已启用且出现在快照中的 providers(`enabled === true`)。
144
- * 须先 `load()`;未缓存时返回空数组。
145
- */
146
- getEnabledProviders(integrationType: string): IntegrationSnapshotProvider[];
147
- clear(): void;
148
- /** 拉取快照;`force: true` 时忽略内存缓存重新请求 */
149
- load(params?: {
150
- force?: boolean;
151
- }): Promise<IntegrationSnapshot>;
152
- }
130
+ declare function getPaymentProvidersFromIntegrationProviders(integrationProviders: IntegrationProvidersConfig, params?: {
131
+ force?: boolean;
132
+ }): Promise<PaymentProvider[]>;
153
133
 
154
134
  interface NvwaLocalStorage {
155
135
  get(key: string): Promise<any | null>;
@@ -296,6 +276,11 @@ interface GithubOpenPlatformIdentity {
296
276
  /** 微信开放平台网站应用扫码登录(与 GitHub 网关同构) */
297
277
  type WechatWebsiteOpenPlatformLoginResult = GithubOpenPlatformLoginResult;
298
278
  type WechatWebsiteOpenPlatformIdentity = GithubOpenPlatformIdentity;
279
+ interface SocialProvider {
280
+ id: string;
281
+ name: string;
282
+ description: string;
283
+ }
299
284
  interface AuthClientOptions {
300
285
  /** Auth 路径,默认 "/auth"(与 runtime 的 basePath 一致) */
301
286
  authPath?: string;
@@ -308,6 +293,8 @@ interface AuthClientOptions {
308
293
  * 与 uniapp / 跨子域一致,不依赖 cookie。
309
294
  */
310
295
  credentials?: RequestCredentials;
296
+ /** 编译期注入的 integration providers 配置。 */
297
+ integrationProviders?: IntegrationProvidersConfig;
311
298
  }
312
299
  /**
313
300
  * 项目侧 Auth 客户端:getSession、登录/登出、currentUser、getCurrentJwt。
@@ -322,7 +309,11 @@ declare class AuthClient {
322
309
  private storage;
323
310
  /** 统一 JWT 鉴权,不使用 cookie */
324
311
  private credentials;
312
+ private integrationProviders;
325
313
  constructor(baseUrl: string, options?: AuthClientOptions);
314
+ getSocialProviders(params?: {
315
+ force?: boolean;
316
+ }): Promise<SocialProvider[]>;
326
317
  /**
327
318
  * 获取当前用户。有 storage 时优先从本地缓存读取,否则请求 getSession()。
328
319
  */
@@ -339,7 +330,7 @@ declare class AuthClient {
339
330
  /**
340
331
  * 浏览器跳转 Google 登录(经 runtime `GET .../google/openplatform/login` 再 302 到平台网关)。
341
332
  * `returnUrl` 须为当前项目同源地址(与 runtime 校验一致),OAuth 结束后会带上 `exchange_code`。
342
- * 传入 `applicationCode` `platformCode` 时,Runtime 会按 integration 快照选择默认或自定义 OAuth(须同时传或同时不传)。
333
+ * SDK 会基于编译期 `integrationProviders` 注入 `oauth_credential_source`,Runtime 直接按参数转发到网关。
343
334
  */
344
335
  getGoogleOpenPlatformLoginUrl(returnUrl: string, options?: {
345
336
  applicationCode?: string;
@@ -385,7 +376,7 @@ declare class AuthClient {
385
376
  /**
386
377
  * 浏览器跳转 GitHub 登录(经 runtime `GET .../github/openplatform/login` 再 302 到平台网关)。
387
378
  * `returnUrl` 须为当前项目同源地址(与 runtime 校验一致),OAuth 结束后会带上 `exchange_code`。
388
- * 传入 `applicationCode` `platformCode` 时,Runtime 会按 integration 快照选择默认或自定义 OAuth(须同时传或同时不传)。
379
+ * SDK 会基于编译期 `integrationProviders` 注入 `oauth_credential_source`,Runtime 直接按参数转发到网关。
389
380
  */
390
381
  getGithubOpenPlatformLoginUrl(returnUrl: string, options?: {
391
382
  applicationCode?: string;
@@ -632,15 +623,12 @@ interface INvwa {
632
623
  payment: IPaymentLauncher;
633
624
  /** 与构造 Nvwa 时传入的 `applicationCode` 一致,便于业务侧复用 */
634
625
  readonly applicationCode: string;
635
- /** 与构造 Nvwa 时传入的 `platformCode` 一致 */
636
- readonly platformCode: string;
637
- /**
638
- * 经 Runtime 拉取 integration / provider 开关快照。
639
- * 应用/端在构造 Nvwa 时传入;调用侧使用 `await integrationSnapshot.load()`(可选 `{ force: true }`)。
640
- */
641
- integrationSnapshot: NvwaIntegrationSnapshot;
626
+ /** 构造入参中的平台类型(Server `PlatformType` 枚举值) */
627
+ readonly platformType: string;
628
+ /** 编译期注入的 integration provider 开关配置。 */
629
+ integrationProviders: IntegrationProvidersConfig;
642
630
  /** 发起支付,由 @nvwa-app/sdk-web / @nvwa-app/sdk-uniapp 分别实现 IPaymentLauncher。 */
643
631
  endpointType: string;
644
632
  }
645
633
 
646
- export { type AlipayCodeLoginResult, type AlipayOpenPlatformIdentity, AuthClient, type AuthClientOptions, type AuthResult, type AuthSession, type AuthUser, CURRENT_JWT_KEY, type CreatePaymentResponse, ENTITIES_BASE_PATH, FILE_STORAGE_BASE_PATH, type FunctionInvokeOptions, GENERATE_UPLOAD_URL_PATH, type GithubOpenPlatformIdentity, type GithubOpenPlatformLoginResult, type GoogleOpenPlatformIdentity, type GoogleOpenPlatformLoginResult, type HoverInspectorMessage, type HttpMethod, type HttpUploadFileResponse, type INvwa, type IPaymentLauncher, type IframeSourceLocationMessage, type IntegrationSnapshot, type IntegrationSnapshotContext, type IntegrationSnapshotItem, type IntegrationSnapshotProvider, LOGIN_TOKEN_KEY, LOGIN_USER_PROFILE_KEY, type LegacyPayParams, NvwaEdgeFunctions, NvwaFileStorage, NvwaHttpClient, NvwaIntegrationSnapshot, type NvwaLocalStorage, OverlayManager, type PayParams, type PaymentOrderResult, type PaymentRequestCallbacks, SET_AUTH_TOKEN_HEADER, type SignUpBody, type TypedPayParams, type WeChatCodeLoginResult, type WeChatOpenPlatformIdentity, type WechatJsapiPayParams, type WechatWebsiteOpenPlatformIdentity, type WechatWebsiteOpenPlatformLoginResult, createPostgrestClient, getSourceLocationFromDOM, normalizePayParams, requestPaymentFromOrderResult };
634
+ export { type AlipayCodeLoginResult, type AlipayOpenPlatformIdentity, AuthClient, type AuthClientOptions, type AuthResult, type AuthSession, type AuthUser, CURRENT_JWT_KEY, type CreatePaymentResponse, ENTITIES_BASE_PATH, FILE_STORAGE_BASE_PATH, type FunctionInvokeOptions, GENERATE_UPLOAD_URL_PATH, type GithubOpenPlatformIdentity, type GithubOpenPlatformLoginResult, type GoogleOpenPlatformIdentity, type GoogleOpenPlatformLoginResult, type HoverInspectorMessage, type HttpMethod, type HttpUploadFileResponse, type INvwa, type IPaymentLauncher, type IframeSourceLocationMessage, type IntegrationProviderConfig, type IntegrationProvidersConfig, type IntegrationProvidersEntry, LOGIN_TOKEN_KEY, LOGIN_USER_PROFILE_KEY, type LegacyPayParams, NvwaEdgeFunctions, NvwaFileStorage, NvwaHttpClient, type NvwaLocalStorage, type OAuthCredentialSource, OverlayManager, type PayParams, type PaymentOrderResult, type PaymentProvider, type PaymentRequestCallbacks, SET_AUTH_TOKEN_HEADER, type SignUpBody, type SocialProvider, type TypedPayParams, type WeChatCodeLoginResult, type WeChatOpenPlatformIdentity, type WechatJsapiPayParams, type WechatWebsiteOpenPlatformIdentity, type WechatWebsiteOpenPlatformLoginResult, createPostgrestClient, getEnabledProvidersByIntegration, getPaymentProvidersFromIntegrationProviders, getSourceLocationFromDOM, normalizeIntegrationProvidersConfig, normalizePayParams, parseIntegrationProvidersJson, requestPaymentFromOrderResult };
package/dist/index.d.ts CHANGED
@@ -3,12 +3,29 @@ import { PostgrestClient } from '@nvwa-app/postgrest-js';
3
3
  import { NvwaFetch, URL, RequestInfo, RequestInit, Response, Headers } from '@nvwa-app/nvwa-http-polyfill';
4
4
  export { Headers, NvwaFetch, Request, RequestInfo, RequestInit, Response, URL } from '@nvwa-app/nvwa-http-polyfill';
5
5
 
6
+ type OAuthCredentialSource = "nvwa_default" | "custom";
7
+ interface IntegrationProviderConfig {
8
+ enabled: boolean;
9
+ oauthCredentialSource?: OAuthCredentialSource;
10
+ }
11
+ interface IntegrationProvidersEntry {
12
+ providers: Record<string, IntegrationProviderConfig>;
13
+ }
14
+ interface IntegrationProvidersConfig {
15
+ socialLogin?: IntegrationProvidersEntry;
16
+ payment?: IntegrationProvidersEntry;
17
+ }
18
+ declare function normalizeIntegrationProvidersConfig(input: unknown): IntegrationProvidersConfig;
19
+ declare function parseIntegrationProvidersJson(jsonInput: string | undefined | null): IntegrationProvidersConfig;
20
+ declare function getEnabledProvidersByIntegration(integrationProviders: IntegrationProvidersConfig, integrationKey: "socialLogin" | "payment"): string[];
21
+
6
22
  /**
7
23
  * Payment 纯前端能力:仅「发起支付」。
8
24
  * 流程:create order(不传端类型)→ 返回 order 标识;再按 orderId + 端类型请求 getPaymentInfo 得到 payParams;
9
25
  * 前端用 nvwa.payment.requestPayment(payParams) 调起。端类型由 INvwa.getEndpointType() 提供。
10
26
  * 与 Workspace 积分充值无关。
11
27
  */
28
+
12
29
  /**
13
30
  * 业务 create order 返回的 payParams 形态,供 launcher 调起支付。
14
31
  * 与 payment-gateway 一致:codeUrl(扫码)、formHtml(跳转/表单)、
@@ -65,6 +82,11 @@ interface PaymentRequestCallbacks {
65
82
  onSuccess?: () => void;
66
83
  onFailure?: (error: unknown) => void;
67
84
  }
85
+ interface PaymentProvider {
86
+ id: string;
87
+ name: string;
88
+ description: string;
89
+ }
68
90
  declare function normalizePayParams(payParams: PayParams): TypedPayParams | null;
69
91
  /**
70
92
  * 发起支付:接收 payParams,按当前端类型与渠道完成调起。
@@ -73,6 +95,14 @@ declare function normalizePayParams(payParams: PayParams): TypedPayParams | null
73
95
  */
74
96
  interface IPaymentLauncher {
75
97
  requestPayment(payParams: PayParams, callbacks?: PaymentRequestCallbacks): Promise<void>;
98
+ /** 获取当前应用/平台下可用支付渠道(基于编译期 integrationProviders)。 */
99
+ getAvailableProviders?(params?: {
100
+ force?: boolean;
101
+ }): Promise<PaymentProvider[]>;
102
+ /** @deprecated 请使用 getAvailableProviders。 */
103
+ getProviders?(params?: {
104
+ force?: boolean;
105
+ }): Promise<PaymentProvider[]>;
76
106
  }
77
107
  /**
78
108
  * 业务层 create order 返回给前端的订单结果(与 examples payment-create-order 对齐)。
@@ -97,59 +127,9 @@ type CreatePaymentResponse = PaymentOrderResult;
97
127
  * 从业务 create order 返回结果发起的纯前端封装:不发起任何后端请求。
98
128
  */
99
129
  declare function requestPaymentFromOrderResult(result: PaymentOrderResult, launcher: IPaymentLauncher, callbacks?: PaymentRequestCallbacks): Promise<void>;
100
-
101
- /** 仅能在构造 `Nvwa` / `NvwaIntegrationSnapshot` 时传入;`load()` 不再接受应用/端或语言覆盖 */
102
- interface IntegrationSnapshotContext {
103
- applicationCode: string;
104
- platformCode: string;
105
- /** 默认 `zh`;非 `en` 则按中文 */
106
- locale?: string;
107
- }
108
- interface IntegrationSnapshotProvider {
109
- id: string;
110
- name: string;
111
- description: string;
112
- enabled: boolean;
113
- oauthCredentialSource?: "nvwa_default" | "custom";
114
- }
115
- interface IntegrationSnapshotItem {
116
- integrationType: string;
117
- enabled: boolean;
118
- providers?: IntegrationSnapshotProvider[];
119
- }
120
- interface IntegrationSnapshot {
121
- projectCode: string;
122
- applicationCode: string;
123
- platformCode: string;
124
- integrations: IntegrationSnapshotItem[];
125
- }
126
- /**
127
- * 经 Runtime `GET /nvwa/integration-snapshot` 拉取快照(Runtime 再 HMAC 调 Server internal)。
128
- * 应用/端与默认语言仅在构造时通过 `IntegrationSnapshotContext` 传入;`load()` 仅支持 `force` 刷新缓存。
129
- */
130
- declare class NvwaIntegrationSnapshot {
131
- private readonly baseUrl;
132
- private readonly fetchImpl;
133
- private readonly context;
134
- private cache;
135
- constructor(baseUrl: string, fetchImpl: NvwaFetch, context: IntegrationSnapshotContext);
136
- /** 当前缓存的快照(未 load 过则为 null) */
137
- get(): IntegrationSnapshot | null;
138
- /**
139
- * 从当前缓存快照中取某一 integration(如 `social-login`),未 load 或不存在则 null。
140
- */
141
- getIntegrationItem(integrationType: string): IntegrationSnapshotItem | null;
142
- /**
143
- * 已启用且出现在快照中的 providers(`enabled === true`)。
144
- * 须先 `load()`;未缓存时返回空数组。
145
- */
146
- getEnabledProviders(integrationType: string): IntegrationSnapshotProvider[];
147
- clear(): void;
148
- /** 拉取快照;`force: true` 时忽略内存缓存重新请求 */
149
- load(params?: {
150
- force?: boolean;
151
- }): Promise<IntegrationSnapshot>;
152
- }
130
+ declare function getPaymentProvidersFromIntegrationProviders(integrationProviders: IntegrationProvidersConfig, params?: {
131
+ force?: boolean;
132
+ }): Promise<PaymentProvider[]>;
153
133
 
154
134
  interface NvwaLocalStorage {
155
135
  get(key: string): Promise<any | null>;
@@ -296,6 +276,11 @@ interface GithubOpenPlatformIdentity {
296
276
  /** 微信开放平台网站应用扫码登录(与 GitHub 网关同构) */
297
277
  type WechatWebsiteOpenPlatformLoginResult = GithubOpenPlatformLoginResult;
298
278
  type WechatWebsiteOpenPlatformIdentity = GithubOpenPlatformIdentity;
279
+ interface SocialProvider {
280
+ id: string;
281
+ name: string;
282
+ description: string;
283
+ }
299
284
  interface AuthClientOptions {
300
285
  /** Auth 路径,默认 "/auth"(与 runtime 的 basePath 一致) */
301
286
  authPath?: string;
@@ -308,6 +293,8 @@ interface AuthClientOptions {
308
293
  * 与 uniapp / 跨子域一致,不依赖 cookie。
309
294
  */
310
295
  credentials?: RequestCredentials;
296
+ /** 编译期注入的 integration providers 配置。 */
297
+ integrationProviders?: IntegrationProvidersConfig;
311
298
  }
312
299
  /**
313
300
  * 项目侧 Auth 客户端:getSession、登录/登出、currentUser、getCurrentJwt。
@@ -322,7 +309,11 @@ declare class AuthClient {
322
309
  private storage;
323
310
  /** 统一 JWT 鉴权,不使用 cookie */
324
311
  private credentials;
312
+ private integrationProviders;
325
313
  constructor(baseUrl: string, options?: AuthClientOptions);
314
+ getSocialProviders(params?: {
315
+ force?: boolean;
316
+ }): Promise<SocialProvider[]>;
326
317
  /**
327
318
  * 获取当前用户。有 storage 时优先从本地缓存读取,否则请求 getSession()。
328
319
  */
@@ -339,7 +330,7 @@ declare class AuthClient {
339
330
  /**
340
331
  * 浏览器跳转 Google 登录(经 runtime `GET .../google/openplatform/login` 再 302 到平台网关)。
341
332
  * `returnUrl` 须为当前项目同源地址(与 runtime 校验一致),OAuth 结束后会带上 `exchange_code`。
342
- * 传入 `applicationCode` `platformCode` 时,Runtime 会按 integration 快照选择默认或自定义 OAuth(须同时传或同时不传)。
333
+ * SDK 会基于编译期 `integrationProviders` 注入 `oauth_credential_source`,Runtime 直接按参数转发到网关。
343
334
  */
344
335
  getGoogleOpenPlatformLoginUrl(returnUrl: string, options?: {
345
336
  applicationCode?: string;
@@ -385,7 +376,7 @@ declare class AuthClient {
385
376
  /**
386
377
  * 浏览器跳转 GitHub 登录(经 runtime `GET .../github/openplatform/login` 再 302 到平台网关)。
387
378
  * `returnUrl` 须为当前项目同源地址(与 runtime 校验一致),OAuth 结束后会带上 `exchange_code`。
388
- * 传入 `applicationCode` `platformCode` 时,Runtime 会按 integration 快照选择默认或自定义 OAuth(须同时传或同时不传)。
379
+ * SDK 会基于编译期 `integrationProviders` 注入 `oauth_credential_source`,Runtime 直接按参数转发到网关。
389
380
  */
390
381
  getGithubOpenPlatformLoginUrl(returnUrl: string, options?: {
391
382
  applicationCode?: string;
@@ -632,15 +623,12 @@ interface INvwa {
632
623
  payment: IPaymentLauncher;
633
624
  /** 与构造 Nvwa 时传入的 `applicationCode` 一致,便于业务侧复用 */
634
625
  readonly applicationCode: string;
635
- /** 与构造 Nvwa 时传入的 `platformCode` 一致 */
636
- readonly platformCode: string;
637
- /**
638
- * 经 Runtime 拉取 integration / provider 开关快照。
639
- * 应用/端在构造 Nvwa 时传入;调用侧使用 `await integrationSnapshot.load()`(可选 `{ force: true }`)。
640
- */
641
- integrationSnapshot: NvwaIntegrationSnapshot;
626
+ /** 构造入参中的平台类型(Server `PlatformType` 枚举值) */
627
+ readonly platformType: string;
628
+ /** 编译期注入的 integration provider 开关配置。 */
629
+ integrationProviders: IntegrationProvidersConfig;
642
630
  /** 发起支付,由 @nvwa-app/sdk-web / @nvwa-app/sdk-uniapp 分别实现 IPaymentLauncher。 */
643
631
  endpointType: string;
644
632
  }
645
633
 
646
- export { type AlipayCodeLoginResult, type AlipayOpenPlatformIdentity, AuthClient, type AuthClientOptions, type AuthResult, type AuthSession, type AuthUser, CURRENT_JWT_KEY, type CreatePaymentResponse, ENTITIES_BASE_PATH, FILE_STORAGE_BASE_PATH, type FunctionInvokeOptions, GENERATE_UPLOAD_URL_PATH, type GithubOpenPlatformIdentity, type GithubOpenPlatformLoginResult, type GoogleOpenPlatformIdentity, type GoogleOpenPlatformLoginResult, type HoverInspectorMessage, type HttpMethod, type HttpUploadFileResponse, type INvwa, type IPaymentLauncher, type IframeSourceLocationMessage, type IntegrationSnapshot, type IntegrationSnapshotContext, type IntegrationSnapshotItem, type IntegrationSnapshotProvider, LOGIN_TOKEN_KEY, LOGIN_USER_PROFILE_KEY, type LegacyPayParams, NvwaEdgeFunctions, NvwaFileStorage, NvwaHttpClient, NvwaIntegrationSnapshot, type NvwaLocalStorage, OverlayManager, type PayParams, type PaymentOrderResult, type PaymentRequestCallbacks, SET_AUTH_TOKEN_HEADER, type SignUpBody, type TypedPayParams, type WeChatCodeLoginResult, type WeChatOpenPlatformIdentity, type WechatJsapiPayParams, type WechatWebsiteOpenPlatformIdentity, type WechatWebsiteOpenPlatformLoginResult, createPostgrestClient, getSourceLocationFromDOM, normalizePayParams, requestPaymentFromOrderResult };
634
+ export { type AlipayCodeLoginResult, type AlipayOpenPlatformIdentity, AuthClient, type AuthClientOptions, type AuthResult, type AuthSession, type AuthUser, CURRENT_JWT_KEY, type CreatePaymentResponse, ENTITIES_BASE_PATH, FILE_STORAGE_BASE_PATH, type FunctionInvokeOptions, GENERATE_UPLOAD_URL_PATH, type GithubOpenPlatformIdentity, type GithubOpenPlatformLoginResult, type GoogleOpenPlatformIdentity, type GoogleOpenPlatformLoginResult, type HoverInspectorMessage, type HttpMethod, type HttpUploadFileResponse, type INvwa, type IPaymentLauncher, type IframeSourceLocationMessage, type IntegrationProviderConfig, type IntegrationProvidersConfig, type IntegrationProvidersEntry, LOGIN_TOKEN_KEY, LOGIN_USER_PROFILE_KEY, type LegacyPayParams, NvwaEdgeFunctions, NvwaFileStorage, NvwaHttpClient, type NvwaLocalStorage, type OAuthCredentialSource, OverlayManager, type PayParams, type PaymentOrderResult, type PaymentProvider, type PaymentRequestCallbacks, SET_AUTH_TOKEN_HEADER, type SignUpBody, type SocialProvider, type TypedPayParams, type WeChatCodeLoginResult, type WeChatOpenPlatformIdentity, type WechatJsapiPayParams, type WechatWebsiteOpenPlatformIdentity, type WechatWebsiteOpenPlatformLoginResult, createPostgrestClient, getEnabledProvidersByIntegration, getPaymentProvidersFromIntegrationProviders, getSourceLocationFromDOM, normalizeIntegrationProvidersConfig, normalizePayParams, parseIntegrationProvidersJson, requestPaymentFromOrderResult };
package/dist/index.js CHANGED
@@ -1,7 +1,7 @@
1
- "use strict";var T=Object.defineProperty;var V=Object.getOwnPropertyDescriptor;var X=Object.getOwnPropertyNames;var Q=Object.prototype.hasOwnProperty;var Z=(s,t)=>{for(var e in t)T(s,e,{get:t[e],enumerable:!0})},tt=(s,t,e,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of X(t))!Q.call(s,i)&&i!==e&&T(s,i,{get:()=>t[i],enumerable:!(r=V(t,i))||r.enumerable});return s};var et=s=>tt(T({},"__esModule",{value:!0}),s);var wt={};Z(wt,{AuthClient:()=>L,CURRENT_JWT_KEY:()=>p,ENTITIES_BASE_PATH:()=>Y,FILE_STORAGE_BASE_PATH:()=>F,GENERATE_UPLOAD_URL_PATH:()=>M,Headers:()=>f,LOGIN_TOKEN_KEY:()=>y,LOGIN_USER_PROFILE_KEY:()=>P,NvwaEdgeFunctions:()=>I,NvwaFileStorage:()=>U,NvwaHttpClient:()=>$,NvwaIntegrationSnapshot:()=>R,OverlayManager:()=>N,Request:()=>_,Response:()=>k,SET_AUTH_TOKEN_HEADER:()=>A,URL:()=>O,createPostgrestClient:()=>dt,getSourceLocationFromDOM:()=>gt,normalizePayParams:()=>mt,requestPaymentFromOrderResult:()=>ft});module.exports=et(wt);var f=class H{constructor(t){if(this.headerMap=new Map,t){if(t instanceof H)t.forEach((e,r)=>this.set(r,e));else if(Array.isArray(t))for(let[e,r]of t)this.set(e,String(r));else if(typeof t=="object")for(let e of Object.keys(t))this.set(e,String(t[e]))}}append(t,e){let r=t.toLowerCase(),i=this.headerMap.get(r);this.headerMap.set(r,i?`${i}, ${e}`:e)}set(t,e){this.headerMap.set(t.toLowerCase(),String(e))}get(t){return this.headerMap.get(t.toLowerCase())??null}has(t){return this.headerMap.has(t.toLowerCase())}delete(t){this.headerMap.delete(t.toLowerCase())}forEach(t){for(let[e,r]of this.headerMap.entries())t(r,e,this)}entries(){return this.headerMap.entries()}keys(){return this.headerMap.keys()}values(){return this.headerMap.values()}[Symbol.iterator](){return this.entries()}},rt=class W{constructor(t){if(this.params=new Map,t){if(typeof t=="string")this.parseString(t);else if(t instanceof W)this.params=new Map(t.params);else if(Array.isArray(t))for(let[e,r]of t)this.append(e,r);else if(t&&typeof t=="object")for(let[e,r]of Object.entries(t))this.set(e,r)}}parseString(t){t.startsWith("?")&&(t=t.slice(1));let e=t.split("&");for(let r of e)if(r){let[i,n]=r.split("=");i&&this.append(decodeURIComponent(i),n?decodeURIComponent(n):"")}}append(t,e){let r=this.params.get(t)||[];r.push(e),this.params.set(t,r)}delete(t){this.params.delete(t)}get(t){let e=this.params.get(t);return e?e[0]:null}getAll(t){return this.params.get(t)||[]}has(t){return this.params.has(t)}set(t,e){this.params.set(t,[e])}sort(){let t=Array.from(this.params.entries()).sort(([e],[r])=>e.localeCompare(r));this.params=new Map(t)}toString(){let t=[];for(let[e,r]of this.params.entries())for(let i of r)t.push(`${encodeURIComponent(e)}=${encodeURIComponent(i)}`);return t.join("&")}forEach(t){for(let[e,r]of this.params.entries())for(let i of r)t(i,e,this)}keys(){return this.params.keys()}values(){let t=[];for(let e of this.params.values())t.push(...e);return t[Symbol.iterator]()}entries(){let t=[];for(let[e,r]of this.params.entries())for(let i of r)t.push([e,i]);return t[Symbol.iterator]()}[Symbol.iterator](){return this.entries()}get size(){return this.params.size}},O=class C{constructor(t,e){let r;if(t instanceof C)r=t.href;else if(e){let n=e instanceof C?e.href:e;r=this.resolve(n,t)}else r=t;let i=this.parseUrl(r);this.href=r,this.origin=`${i.protocol}//${i.host}`,this.protocol=i.protocol,this.username=i.username,this.password=i.password,this.host=i.host,this.hostname=i.hostname,this.port=i.port,this.pathname=i.pathname,this.search=i.search,this.searchParams=new rt(i.search),this.hash=i.hash}resolve(t,e){if(e.startsWith("http://")||e.startsWith("https://"))return e;if(e.startsWith("//"))return`${this.parseUrl(t).protocol}${e}`;if(e.startsWith("/")){let n=this.parseUrl(t);return`${n.protocol}//${n.host}${e}`}let r=this.parseUrl(t),i=r.pathname.endsWith("/")?r.pathname:r.pathname+"/";return`${r.protocol}//${r.host}${i}${e}`}parseUrl(t){let e=t.match(/^(([^:\/?#]+):)?(\/\/([^\/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?$/);if(!e)throw new TypeError("Invalid URL");let r=e[2]||"",i=e[4]||"",n=e[5]||"/",a=e[7]?`?${e[7]}`:"",o=e[9]?`#${e[9]}`:"";if(!r&&!i&&!n.startsWith("/")&&!n.includes("/")&&!n.includes("."))throw new TypeError("Invalid URL");let h=i.match(/^([^@]*)@(.+)$/),c="",l="",u=i;if(h){let b=h[1];u=h[2];let w=b.match(/^([^:]*):?(.*)$/);w&&(c=w[1]||"",l=w[2]||"")}let d=u.match(/^([^:]+):?(\d*)$/),g=d?d[1]:u,m=d&&d[2]?d[2]:"";return{protocol:r?`${r}:`:"",username:c,password:l,host:u,hostname:g,port:m,pathname:n,search:a,hash:o}}toString(){let t=this.searchParams.toString(),e=t?`?${t}`:"";return`${this.protocol}//${this.host}${this.pathname}${e}${this.hash}`}toJSON(){return this.toString()}},_=class G{constructor(t,e){if(typeof t=="string")this.url=t;else if(t?.url)this.url=String(t.url);else if(typeof t?.toString=="function")this.url=String(t.toString());else throw new Error("Invalid input for Request");this.method=(e?.method||"GET").toUpperCase(),this.headers=e?.headers instanceof f?e.headers:new f(e?.headers),this.body=e?.body,this.timeout=e?.timeout,this.signal=e?.signal||void 0}clone(){return new G(this.url,{method:this.method,headers:this.headers,body:this.body,timeout:this.timeout})}toString(){return this.url}},k=class{constructor(s,t){this.bodyData=s,this.status=t?.status??200,this.statusText=t?.statusText??"",this.headers=st(t?.headers),this.ok=this.status>=200&&this.status<300}async text(){return typeof this.bodyData=="string"?this.bodyData:this.bodyData==null?"":typeof this.bodyData=="object"?JSON.stringify(this.bodyData):String(this.bodyData)}async json(){if(typeof this.bodyData=="string")try{return JSON.parse(this.bodyData)}catch{}return this.bodyData}async arrayBuffer(){let s=await this.text();return new TextEncoder().encode(s).buffer}};function st(s){return s?new f(s):new f}var it=class{constructor(){this._aborted=!1,this.listeners=new Set,this.onabort=null}get aborted(){return this._aborted}_trigger(){if(!this._aborted){if(this._aborted=!0,typeof this.onabort=="function")try{this.onabort()}catch{}for(let s of Array.from(this.listeners))try{s()}catch{}this.listeners.clear()}}addEventListener(s,t){if(this._aborted){try{t()}catch{}return}this.listeners.add(t)}removeEventListener(s,t){this.listeners.delete(t)}toString(){return"[object AbortSignal]"}},q=class{constructor(){this._signal=new it}get signal(){return this._signal}abort(){this._signal._trigger()}toString(){return"[object AbortController]"}};var I=class{constructor(t,e=""){this.http=t,this.baseUrl=e.replace(/\/$/,"")}async invoke(t,e){let r=this.baseUrl?`${this.baseUrl}/functions/${t}`:`/functions/${t}`;return await(await this.http.fetch(r,{method:e.method||"POST",body:e.body,headers:e.headers})).json()}};var p="nvwa_current_jwt",y="nvwa_login_token",P="nvwa_user_profile",A="set-auth-token",nt=typeof fetch<"u"?(s,t)=>fetch(s,t):()=>{throw new Error("AuthClient requires fetch")},L=class{constructor(t,e={}){this.baseUrl=t.replace(/\/$/,""),this.authPath=(e.authPath??"/auth").replace(/^\//,""),this.fetchImpl=e.fetchImpl??nt,this.storage=e.storage??null,this.credentials=e.credentials??"omit",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 currentUser(){if(this.storage){let r=await this.storage.get(P);if(r!=null)return r}let{data:t}=await this.getSession(),e=t?.user??null;return e&&this.storage&&await this.storage.set(P,e),e}async getCurrentJwt(){if(this.storage){let e=await this.storage.get(p);if(e!=null)return e;let r=await this.storage.get(y),{data:i}=await this.getToken(r??void 0);return i?.token?(await this.storage.set(p,i.token),i.token):null}let{data:t}=await this.getToken();return t?.token??null}async persistLogin(t,e){if(!this.storage)return;let i=e?.headers.get(A)?.trim()||t.token||t.session?.token;i&&await this.storage.set(y,i),t.user&&await this.storage.set(P,t.user);let n=i??await this.storage.get(y),{data:a}=await this.getToken(n??void 0);a?.token&&await this.storage.set(p,a.token)}async clearLogin(){this.storage&&(await this.storage.remove(y),await this.storage.remove(P),await this.storage.remove(p))}getGoogleOpenPlatformLoginUrl(t,e){let r=new URLSearchParams({return_url:t});return e?.applicationCode?.trim()&&r.set("application_code",e.applicationCode.trim()),e?.platformCode?.trim()&&r.set("platform_code",e.platformCode.trim()),`${this.url("google/openplatform/login")}?${r.toString()}`}startGoogleOpenPlatformLogin(t,e){let r=this.getGoogleOpenPlatformLoginUrl(t,e);if(typeof globalThis<"u"&&"location"in globalThis){globalThis.location.href=r;return}throw new Error("startGoogleOpenPlatformLogin requires a browser environment with location")}async completeGoogleOpenPlatformLoginFromCurrentUrl(t){let e;if(t!=null&&t!=="")e=t;else if(typeof globalThis<"u"&&"location"in globalThis)e=globalThis.location.href;else return{error:{message:"completeGoogleOpenPlatformLoginFromCurrentUrl requires url or browser location",status:0}};let r;try{r=new URL(e).searchParams.get("exchange_code")}catch{return{error:{message:"invalid_callback_url",status:400}}}return r?.trim()?await this.loginWithGoogleExchangeCode(r.trim()):{error:{message:"missing_exchange_code",status:400}}}async loginWithGoogleExchangeCode(t){try{let e={"Content-Type":"application/json"};if(this.storage){let a=await this.storage.get(p);a!=null&&(e.Authorization=`Bearer ${a}`)}let r=await this.fetchImpl(this.url("google/openplatform/sign-in"),{method:"POST",headers:e,credentials:this.credentials,body:JSON.stringify({exchangeCode:t})}),i=await r.text();if(!r.ok)return{error:{message:i||r.statusText,status:r.status}};let n=i?JSON.parse(i):null;return!n?.token||!n.user?{error:{message:"invalid_google_login_response",status:502}}:(this.storage&&(await this.storage.set(p,n.token),await this.storage.set(y,n.token),await this.storage.set(P,n.user)),{data:n})}catch(e){return{error:{message:e instanceof Error?e.message:String(e),status:0}}}}async getGoogleOpenPlatformIdentity(){try{let t={};if(this.storage){let n=await this.storage.get(p);n!=null&&(t.Authorization=`Bearer ${n}`)}let e=await this.fetchImpl(this.url("google/openplatform/identity"),{method:"GET",credentials:this.credentials,...Object.keys(t).length?{headers:t}:{}}),r=await e.text();if(!e.ok)return{error:{message:r||e.statusText,status:e.status}};let i=r?JSON.parse(r):null;return i?.sub?{data:i}:{error:{message:"invalid_google_identity_response",status:502}}}catch(t){return{error:{message:t instanceof Error?t.message:String(t),status:0}}}}getGithubOpenPlatformLoginUrl(t,e){let r=new URLSearchParams({return_url:t});return e?.applicationCode?.trim()&&r.set("application_code",e.applicationCode.trim()),e?.platformCode?.trim()&&r.set("platform_code",e.platformCode.trim()),`${this.url("github/openplatform/login")}?${r.toString()}`}startGithubOpenPlatformLogin(t,e){let r=this.getGithubOpenPlatformLoginUrl(t,e);if(typeof globalThis<"u"&&"location"in globalThis){globalThis.location.href=r;return}throw new Error("startGithubOpenPlatformLogin requires a browser environment with location")}async completeGithubOpenPlatformLoginFromCurrentUrl(t){let e;if(t!=null&&t!=="")e=t;else if(typeof globalThis<"u"&&"location"in globalThis)e=globalThis.location.href;else return{error:{message:"completeGithubOpenPlatformLoginFromCurrentUrl requires url or browser location",status:0}};let r;try{r=new URL(e).searchParams.get("exchange_code")}catch{return{error:{message:"invalid_callback_url",status:400}}}return r?.trim()?await this.loginWithGithubExchangeCode(r.trim()):{error:{message:"missing_exchange_code",status:400}}}async loginWithGithubExchangeCode(t){try{let e={"Content-Type":"application/json"};if(this.storage){let a=await this.storage.get(p);a!=null&&(e.Authorization=`Bearer ${a}`)}let r=await this.fetchImpl(this.url("github/openplatform/sign-in"),{method:"POST",headers:e,credentials:this.credentials,body:JSON.stringify({exchangeCode:t})}),i=await r.text();if(!r.ok)return{error:{message:i||r.statusText,status:r.status}};let n=i?JSON.parse(i):null;return!n?.token||!n.user?{error:{message:"invalid_github_login_response",status:502}}:(this.storage&&(await this.storage.set(p,n.token),await this.storage.set(y,n.token),await this.storage.set(P,n.user)),{data:n})}catch(e){return{error:{message:e instanceof Error?e.message:String(e),status:0}}}}async getGithubOpenPlatformIdentity(){try{let t={};if(this.storage){let n=await this.storage.get(p);n!=null&&(t.Authorization=`Bearer ${n}`)}let e=await this.fetchImpl(this.url("github/openplatform/identity"),{method:"GET",credentials:this.credentials,...Object.keys(t).length?{headers:t}:{}}),r=await e.text();if(!e.ok)return{error:{message:r||e.statusText,status:e.status}};let i=r?JSON.parse(r):null;return i?.sub?{data:i}:{error:{message:"invalid_github_identity_response",status:502}}}catch(t){return{error:{message:t instanceof Error?t.message:String(t),status:0}}}}getWechatWebsiteOpenPlatformLoginUrl(t){let e=new URLSearchParams({return_url:t});return`${this.url("wechat-website/openplatform/login")}?${e.toString()}`}startWechatWebsiteOpenPlatformLogin(t){let e=this.getWechatWebsiteOpenPlatformLoginUrl(t);if(typeof globalThis<"u"&&"location"in globalThis){globalThis.location.href=e;return}throw new Error("startWechatWebsiteOpenPlatformLogin requires a browser environment with location")}async completeWechatWebsiteOpenPlatformLoginFromCurrentUrl(t){let e;if(t!=null&&t!=="")e=t;else if(typeof globalThis<"u"&&"location"in globalThis)e=globalThis.location.href;else return{error:{message:"completeWechatWebsiteOpenPlatformLoginFromCurrentUrl requires url or browser location",status:0}};let r;try{r=new URL(e).searchParams.get("exchange_code")}catch{return{error:{message:"invalid_callback_url",status:400}}}return r?.trim()?await this.loginWithWechatWebsiteExchangeCode(r.trim()):{error:{message:"missing_exchange_code",status:400}}}async loginWithWechatWebsiteExchangeCode(t){try{let e={"Content-Type":"application/json"};if(this.storage){let a=await this.storage.get(p);a!=null&&(e.Authorization=`Bearer ${a}`)}let r=await this.fetchImpl(this.url("wechat-website/openplatform/sign-in"),{method:"POST",headers:e,credentials:this.credentials,body:JSON.stringify({exchangeCode:t})}),i=await r.text();if(!r.ok)return{error:{message:i||r.statusText,status:r.status}};let n=i?JSON.parse(i):null;return!n?.token||!n.user?{error:{message:"invalid_wechat_website_login_response",status:502}}:(this.storage&&(await this.storage.set(p,n.token),await this.storage.set(y,n.token),await this.storage.set(P,n.user)),{data:n})}catch(e){return{error:{message:e instanceof Error?e.message:String(e),status:0}}}}async getWechatWebsiteOpenPlatformIdentity(){try{let t={};if(this.storage){let n=await this.storage.get(p);n!=null&&(t.Authorization=`Bearer ${n}`)}let e=await this.fetchImpl(this.url("wechat-website/openplatform/identity"),{method:"GET",credentials:this.credentials,...Object.keys(t).length?{headers:t}:{}}),r=await e.text();if(!e.ok)return{error:{message:r||e.statusText,status:e.status}};let i=r?JSON.parse(r):null;return i?.sub?{data:i}:{error:{message:"invalid_wechat_website_identity_response",status:502}}}catch(t){return{error:{message:t instanceof Error?t.message:String(t),status:0}}}}url(t){let r=`${`${this.baseUrl.replace(/\/+$/,"")}/${this.authPath.replace(/^\/+/,"")}`}/${t.replace(/^\/+/,"")}`;return typeof console<"u"&&(console.warn("[NvwaAuth] request URL:",r),!r.startsWith("http://")&&!r.startsWith("https://")&&console.warn("[NvwaAuth] URL \u975E\u5B8C\u6574\u5730\u5740\uFF0C\u5C0F\u7A0B\u5E8F\u4F1A\u62A5 invalid url\uFF0C\u8BF7\u68C0\u67E5 Nvwa \u6784\u9020\u65F6\u4F20\u5165\u7684 baseUrl")),r}async getSession(){try{let t={};if(this.storage){let i=await this.storage.get(y)??await this.storage.get(p);i!=null&&(t.Authorization=`Bearer ${i}`)}let e=await this.fetchImpl(this.url("session"),{method:"GET",credentials:this.credentials,...Object.keys(t).length?{headers:t}:{}});return e.ok?{data:await e.json()}:{data:null,error:{message:await e.text()||e.statusText,status:e.status}}}catch(t){return{data:null,error:{message:t instanceof Error?t.message:String(t),status:0}}}}async signInWithEmail(t,e){try{let r=await this.fetchImpl(this.url("sign-in/email"),{method:"POST",headers:{"Content-Type":"application/json"},credentials:this.credentials,body:JSON.stringify({email:t,password:e})}),i=await r.text();if(!r.ok)return{error:{message:i||r.statusText,status:r.status}};let n=i?JSON.parse(i):void 0;return n&&await this.persistLogin({user:n.user,session:n.session},r),{data:n}}catch(r){return{error:{message:r instanceof Error?r.message:String(r),status:0}}}}async signOut(){try{let t={};if(this.storage){let r=await this.storage.get(y)??await this.storage.get(p);r!=null&&(t.Authorization=`Bearer ${r}`)}let e=await this.fetchImpl(this.url("sign-out"),{method:"POST",credentials:this.credentials,...Object.keys(t).length?{headers:t}:{}});return await this.clearLogin(),e.ok?{}:{error:{message:await e.text()||e.statusText,status:e.status}}}catch(t){return{error:{message:t instanceof Error?t.message:String(t),status:0}}}}async signUp(t){let e=await this.postJson("sign-up/email",t);return e.data&&await this.persistLogin(e.data,e.response),e}async getToken(t){try{let e={};if(t)e.Authorization=`Bearer ${t}`;else if(this.storage){let a=await this.storage.get(y)??await this.storage.get(p);a!=null&&(e.Authorization=`Bearer ${a}`)}let r=await this.fetchImpl(this.url("token"),{method:"GET",credentials:this.credentials,...Object.keys(e).length?{headers:e}:{}}),i=await r.text();if(!r.ok)return{error:{message:i||r.statusText,status:r.status}};let n=i?JSON.parse(i):void 0;return{data:n?.token!=null?{token:n.token}:void 0}}catch(e){return{error:{message:e instanceof Error?e.message:String(e),status:0}}}}async signInWithUsername(t,e){let r=await this.postJson("sign-in/username",{username:t,password:e});return r.data&&await this.persistLogin(r.data,r.response),r}async signInWithPhoneNumber(t,e,r){let i=await this.postJson("sign-in/phone-number",{phoneNumber:t,password:e,rememberMe:r});return i.data&&await this.persistLogin(i.data,i.response),i}async sendPhoneNumberOtp(t){let e=await this.postJson("phone-number/send-otp",{phoneNumber:t});return e.error?{error:e.error}:{}}async verifyPhoneNumber(t,e){let r=await this.postJson("phone-number/verify",{phoneNumber:t,code:e});return r.data&&await this.persistLogin(r.data,r.response),r}async loginWithWeChatCode(t,e){try{let r={"Content-Type":"application/json"};if(this.storage){let o=await this.storage.get(p);o!=null&&(r.Authorization=`Bearer ${o}`)}let i=await this.fetchImpl(this.url("wechat/openplatform/sign-in"),{method:"POST",headers:r,credentials:this.credentials,body:JSON.stringify({code:t,applicationCode:e})}),n=await i.text();if(!i.ok)return{error:{message:n||i.statusText,status:i.status}};let a=n?JSON.parse(n):null;return!a?.token||!a.user?{error:{message:"invalid_wechat_login_response",status:502}}:(this.storage&&(await this.storage.set(p,a.token),await this.storage.set(y,a.token),await this.storage.set(P,a.user)),{data:a})}catch(r){return{error:{message:r instanceof Error?r.message:String(r),status:0}}}}async loginWithAlipayCode(t,e){try{let r={"Content-Type":"application/json"};if(this.storage){let o=await this.storage.get(p);o!=null&&(r.Authorization=`Bearer ${o}`)}let i=await this.fetchImpl(this.url("alipay/openplatform/sign-in"),{method:"POST",headers:r,credentials:this.credentials,body:JSON.stringify({code:t,applicationCode:e})}),n=await i.text();if(!i.ok)return{error:{message:n||i.statusText,status:i.status}};let a=n?JSON.parse(n):null;return!a?.token||!a.user?{error:{message:"invalid_alipay_login_response",status:502}}:(this.storage&&(await this.storage.set(p,a.token),await this.storage.set(y,a.token),await this.storage.set(P,a.user)),{data:a})}catch(r){return{error:{message:r instanceof Error?r.message:String(r),status:0}}}}async getWeChatOpenPlatformIdentity(t){try{let e={};if(this.storage){let o=await this.storage.get(p);o!=null&&(e.Authorization=`Bearer ${o}`)}let r=t?.trim()?`?applicationCode=${encodeURIComponent(t.trim())}`:"",i=await this.fetchImpl(this.url(`wechat/openplatform/identity${r}`),{method:"GET",credentials:this.credentials,...Object.keys(e).length?{headers:e}:{}}),n=await i.text();if(!i.ok)return{error:{message:n||i.statusText,status:i.status}};let a=n?JSON.parse(n):null;return!a?.openid||!a.appId?{error:{message:"invalid_wechat_identity_response",status:502}}:{data:a}}catch(e){return{error:{message:e instanceof Error?e.message:String(e),status:0}}}}async getAlipayOpenPlatformIdentity(t){try{let e={};if(this.storage){let o=await this.storage.get(p);o!=null&&(e.Authorization=`Bearer ${o}`)}let r=t?.trim()?`?applicationCode=${encodeURIComponent(t.trim())}`:"",i=await this.fetchImpl(this.url(`alipay/openplatform/identity${r}`),{method:"GET",credentials:this.credentials,...Object.keys(e).length?{headers:e}:{}}),n=await i.text();if(!i.ok)return{error:{message:n||i.statusText,status:i.status}};let a=n?JSON.parse(n):null;return!a?.openid||!a.appId?{error:{message:"invalid_alipay_identity_response",status:502}}:{data:a}}catch(e){return{error:{message:e instanceof Error?e.message:String(e),status:0}}}}async postJson(t,e){try{let r=await this.fetchImpl(this.url(t),{method:"POST",headers:{"Content-Type":"application/json"},credentials:this.credentials,body:JSON.stringify(e)}),i=await r.text();if(!r.ok)return{error:{message:i||r.statusText,status:r.status}};let n=i?JSON.parse(i):void 0;return{data:n?.data??n??void 0,response:r}}catch(r){return{error:{message:r instanceof Error?r.message:String(r),status:0}}}}};var $=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(p),i=new f(e?.headers);r&&i.set("Authorization",`Bearer ${r}`);let n=e?.method||"GET";if((n==="POST"||n==="PUT"||n==="PATCH")&&e?.body){let o=i.get("Content-Type");(!o||o.includes("text/plain"))&&i.set("Content-Type","application/json")}let a=await this.customFetch(t,{...e,headers:i});if(a.status===401)throw this.handleUnauthorized(),new Error("\u672A\u767B\u5F55");return a}};var F="/storage",M=F+"/generateUploadUrl",U=class{constructor(t,e){this.baseUrl=t,this.http=e}async uploadFile(t){let e=await this.http.fetch(this.baseUrl+M,{method:"POST",body:{fileName:t.name||t.fileName,fileSize:t.size||t.fileSize,fileType:t.type||t.fileType}}),{url:r}=await e.json();if(!r)throw new Error("\u83B7\u53D6\u4E0A\u4F20URL\u5931\u8D25");let i=await this.http.fetch(r,{method:"PUT",body:t,headers:new f({"Content-Type":t.type||t.fileType||"application/octet-stream"})}),{url:n}=await i.json();return{url:n.split("?")[0]}}};var at=class extends Error{constructor(s){super(s.message),this.name="PostgrestError",this.details=s.details,this.hint=s.hint,this.code=s.code}},ot=class{constructor(s){var t,e,r;this.shouldThrowOnError=!1,this.method=s.method,this.url=s.url,this.headers=new f(s.headers),this.schema=s.schema,this.body=s.body,this.shouldThrowOnError=(t=s.shouldThrowOnError)!==null&&t!==void 0?t:!1,this.signal=s.signal,this.isMaybeSingle=(e=s.isMaybeSingle)!==null&&e!==void 0?e:!1,this.urlLengthLimit=(r=s.urlLengthLimit)!==null&&r!==void 0?r:8e3,s.fetch?this.fetch=s.fetch:this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(s,t){return this.headers=new f(this.headers),this.headers.set(s,t),this}then(s,t){var e=this;this.schema===void 0||(["GET","HEAD"].includes(this.method)?this.headers.set("Accept-Profile",this.schema):this.headers.set("Content-Profile",this.schema)),this.method!=="GET"&&this.method!=="HEAD"&&this.headers.set("Content-Type","application/json");let r=this.fetch,i=r(this.url.toString(),{method:this.method,headers:this.headers,body:JSON.stringify(this.body),signal:this.signal}).then(async n=>{let a=null,o=null,h=null,c=n.status,l=n.statusText;if(n.ok){var u,d;if(e.method!=="HEAD"){var g;let w=await n.text();w===""||(e.headers.get("Accept")==="text/csv"||e.headers.get("Accept")&&(!((g=e.headers.get("Accept"))===null||g===void 0)&&g.includes("application/vnd.pgrst.plan+text"))?o=w:o=JSON.parse(w))}let m=(u=e.headers.get("Prefer"))===null||u===void 0?void 0:u.match(/count=(exact|planned|estimated)/),b=(d=n.headers.get("content-range"))===null||d===void 0?void 0:d.split("/");m&&b&&b.length>1&&(h=parseInt(b[1])),e.isMaybeSingle&&Array.isArray(o)&&(o.length>1?(a={code:"PGRST116",details:`Results contain ${o.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},o=null,h=null,c=406,l="Not Acceptable"):o.length===1?o=o[0]:o=null)}else{let m=await n.text();try{a=JSON.parse(m),Array.isArray(a)&&n.status===404&&(o=[],a=null,c=200,l="OK")}catch{n.status===404&&m===""?(c=204,l="No Content"):a={message:m}}if(a&&e.shouldThrowOnError)throw new at(a)}return{error:a,data:o,count:h,status:c,statusText:l}});return this.shouldThrowOnError||(i=i.catch(n=>{var a;let o="",h="",c="",l=n?.cause;if(l){var u,d,g,m;let K=(u=l?.message)!==null&&u!==void 0?u:"",j=(d=l?.code)!==null&&d!==void 0?d:"";o=`${(g=n?.name)!==null&&g!==void 0?g:"FetchError"}: ${n?.message}`,o+=`
1
+ "use strict";var T=Object.defineProperty;var Z=Object.getOwnPropertyDescriptor;var tt=Object.getOwnPropertyNames;var et=Object.prototype.hasOwnProperty;var rt=(s,t)=>{for(var e in t)T(s,e,{get:t[e],enumerable:!0})},st=(s,t,e,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of tt(t))!et.call(s,i)&&i!==e&&T(s,i,{get:()=>t[i],enumerable:!(r=Z(t,i))||r.enumerable});return s};var it=s=>st(T({},"__esModule",{value:!0}),s);var Et={};rt(Et,{AuthClient:()=>R,CURRENT_JWT_KEY:()=>u,ENTITIES_BASE_PATH:()=>V,FILE_STORAGE_BASE_PATH:()=>J,GENERATE_UPLOAD_URL_PATH:()=>z,Headers:()=>f,LOGIN_TOKEN_KEY:()=>y,LOGIN_USER_PROFILE_KEY:()=>P,NvwaEdgeFunctions:()=>I,NvwaFileStorage:()=>N,NvwaHttpClient:()=>$,OverlayManager:()=>j,Request:()=>k,Response:()=>A,SET_AUTH_TOKEN_HEADER:()=>U,URL:()=>O,createPostgrestClient:()=>yt,getEnabledProvidersByIntegration:()=>Rt,getPaymentProvidersFromIntegrationProviders:()=>Ot,getSourceLocationFromDOM:()=>vt,normalizeIntegrationProvidersConfig:()=>x,normalizePayParams:()=>Pt,parseIntegrationProvidersJson:()=>Lt,requestPaymentFromOrderResult:()=>bt});module.exports=it(Et);var f=class W{constructor(t){if(this.headerMap=new Map,t){if(t instanceof W)t.forEach((e,r)=>this.set(r,e));else if(Array.isArray(t))for(let[e,r]of t)this.set(e,String(r));else if(typeof t=="object")for(let e of Object.keys(t))this.set(e,String(t[e]))}}append(t,e){let r=t.toLowerCase(),i=this.headerMap.get(r);this.headerMap.set(r,i?`${i}, ${e}`:e)}set(t,e){this.headerMap.set(t.toLowerCase(),String(e))}get(t){return this.headerMap.get(t.toLowerCase())??null}has(t){return this.headerMap.has(t.toLowerCase())}delete(t){this.headerMap.delete(t.toLowerCase())}forEach(t){for(let[e,r]of this.headerMap.entries())t(r,e,this)}entries(){return this.headerMap.entries()}keys(){return this.headerMap.keys()}values(){return this.headerMap.values()}[Symbol.iterator](){return this.entries()}},nt=class G{constructor(t){if(this.params=new Map,t){if(typeof t=="string")this.parseString(t);else if(t instanceof G)this.params=new Map(t.params);else if(Array.isArray(t))for(let[e,r]of t)this.append(e,r);else if(t&&typeof t=="object")for(let[e,r]of Object.entries(t))this.set(e,r)}}parseString(t){t.startsWith("?")&&(t=t.slice(1));let e=t.split("&");for(let r of e)if(r){let[i,n]=r.split("=");i&&this.append(decodeURIComponent(i),n?decodeURIComponent(n):"")}}append(t,e){let r=this.params.get(t)||[];r.push(e),this.params.set(t,r)}delete(t){this.params.delete(t)}get(t){let e=this.params.get(t);return e?e[0]:null}getAll(t){return this.params.get(t)||[]}has(t){return this.params.has(t)}set(t,e){this.params.set(t,[e])}sort(){let t=Array.from(this.params.entries()).sort(([e],[r])=>e.localeCompare(r));this.params=new Map(t)}toString(){let t=[];for(let[e,r]of this.params.entries())for(let i of r)t.push(`${encodeURIComponent(e)}=${encodeURIComponent(i)}`);return t.join("&")}forEach(t){for(let[e,r]of this.params.entries())for(let i of r)t(i,e,this)}keys(){return this.params.keys()}values(){let t=[];for(let e of this.params.values())t.push(...e);return t[Symbol.iterator]()}entries(){let t=[];for(let[e,r]of this.params.entries())for(let i of r)t.push([e,i]);return t[Symbol.iterator]()}[Symbol.iterator](){return this.entries()}get size(){return this.params.size}},O=class _{constructor(t,e){let r;if(t instanceof _)r=t.href;else if(e){let n=e instanceof _?e.href:e;r=this.resolve(n,t)}else r=t;let i=this.parseUrl(r);this.href=r,this.origin=`${i.protocol}//${i.host}`,this.protocol=i.protocol,this.username=i.username,this.password=i.password,this.host=i.host,this.hostname=i.hostname,this.port=i.port,this.pathname=i.pathname,this.search=i.search,this.searchParams=new nt(i.search),this.hash=i.hash}resolve(t,e){if(e.startsWith("http://")||e.startsWith("https://"))return e;if(e.startsWith("//"))return`${this.parseUrl(t).protocol}${e}`;if(e.startsWith("/")){let n=this.parseUrl(t);return`${n.protocol}//${n.host}${e}`}let r=this.parseUrl(t),i=r.pathname.endsWith("/")?r.pathname:r.pathname+"/";return`${r.protocol}//${r.host}${i}${e}`}parseUrl(t){let e=t.match(/^(([^:\/?#]+):)?(\/\/([^\/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?$/);if(!e)throw new TypeError("Invalid URL");let r=e[2]||"",i=e[4]||"",n=e[5]||"/",a=e[7]?`?${e[7]}`:"",o=e[9]?`#${e[9]}`:"";if(!r&&!i&&!n.startsWith("/")&&!n.includes("/")&&!n.includes("."))throw new TypeError("Invalid URL");let h=i.match(/^([^@]*)@(.+)$/),c="",l="",d=i;if(h){let b=h[1];d=h[2];let v=b.match(/^([^:]*):?(.*)$/);v&&(c=v[1]||"",l=v[2]||"")}let p=d.match(/^([^:]+):?(\d*)$/),g=p?p[1]:d,m=p&&p[2]?p[2]:"";return{protocol:r?`${r}:`:"",username:c,password:l,host:d,hostname:g,port:m,pathname:n,search:a,hash:o}}toString(){let t=this.searchParams.toString(),e=t?`?${t}`:"";return`${this.protocol}//${this.host}${this.pathname}${e}${this.hash}`}toJSON(){return this.toString()}},k=class q{constructor(t,e){if(typeof t=="string")this.url=t;else if(t?.url)this.url=String(t.url);else if(typeof t?.toString=="function")this.url=String(t.toString());else throw new Error("Invalid input for Request");this.method=(e?.method||"GET").toUpperCase(),this.headers=e?.headers instanceof f?e.headers:new f(e?.headers),this.body=e?.body,this.timeout=e?.timeout,this.signal=e?.signal||void 0}clone(){return new q(this.url,{method:this.method,headers:this.headers,body:this.body,timeout:this.timeout})}toString(){return this.url}},A=class{constructor(s,t){this.bodyData=s,this.status=t?.status??200,this.statusText=t?.statusText??"",this.headers=at(t?.headers),this.ok=this.status>=200&&this.status<300}async text(){return typeof this.bodyData=="string"?this.bodyData:this.bodyData==null?"":typeof this.bodyData=="object"?JSON.stringify(this.bodyData):String(this.bodyData)}async json(){if(typeof this.bodyData=="string")try{return JSON.parse(this.bodyData)}catch{}return this.bodyData}async arrayBuffer(){let s=await this.text();return new TextEncoder().encode(s).buffer}};function at(s){return s?new f(s):new f}var ot=class{constructor(){this._aborted=!1,this.listeners=new Set,this.onabort=null}get aborted(){return this._aborted}_trigger(){if(!this._aborted){if(this._aborted=!0,typeof this.onabort=="function")try{this.onabort()}catch{}for(let s of Array.from(this.listeners))try{s()}catch{}this.listeners.clear()}}addEventListener(s,t){if(this._aborted){try{t()}catch{}return}this.listeners.add(t)}removeEventListener(s,t){this.listeners.delete(t)}toString(){return"[object AbortSignal]"}},F=class{constructor(){this._signal=new ot}get signal(){return this._signal}abort(){this._signal._trigger()}toString(){return"[object AbortController]"}};var I=class{constructor(t,e=""){this.http=t,this.baseUrl=e.replace(/\/$/,"")}async invoke(t,e){let r=this.baseUrl?`${this.baseUrl}/functions/${t}`:`/functions/${t}`;return await(await this.http.fetch(r,{method:e.method||"POST",body:e.body,headers:e.headers})).json()}};var u="nvwa_current_jwt",y="nvwa_login_token",P="nvwa_user_profile",U="set-auth-token",lt=typeof fetch<"u"?(s,t)=>fetch(s,t):()=>{throw new Error("AuthClient requires fetch")},ht={google:{id:"google",name:"Google Login",description:"Sign in with Google account."},github:{id:"github",name:"GitHub Login",description:"Sign in with GitHub account."},"wechat-website":{id:"wechat-website",name:"WeChat QR Login",description:"Sign in with WeChat website QR code."}};function M(s,t){let e=s.socialLogin?.providers?.[t];return e?.enabled?e.oauthCredentialSource==="custom"?"custom":"nvwa_default":null}var R=class{constructor(t,e={}){this.baseUrl=t.replace(/\/$/,""),this.authPath=(e.authPath??"/auth").replace(/^\//,""),this.fetchImpl=e.fetchImpl??lt,this.storage=e.storage??null,this.credentials=e.credentials??"omit",this.integrationProviders=e.integrationProviders??{},typeof console<"u"&&(console.warn("[NvwaAuth] init baseUrl:",this.baseUrl||"(empty)"),(!this.baseUrl||!this.baseUrl.startsWith("http://")&&!this.baseUrl.startsWith("https://"))&&console.warn("[NvwaAuth] baseUrl \u5E94\u4E3A\u5B8C\u6574\u5730\u5740\uFF08\u5982 https://xxx.nvwa.app\uFF09\uFF0C\u5426\u5219\u5C0F\u7A0B\u5E8F request \u4F1A\u62A5 invalid url"))}async getSocialProviders(t){let e=this.integrationProviders.socialLogin?.providers??{};return Object.entries(e).filter(([,r])=>r.enabled).map(([r])=>ht[r]??{id:r,name:r,description:""})}async currentUser(){if(this.storage){let r=await this.storage.get(P);if(r!=null)return r}let{data:t}=await this.getSession(),e=t?.user??null;return e&&this.storage&&await this.storage.set(P,e),e}async getCurrentJwt(){if(this.storage){let e=await this.storage.get(u);if(e!=null)return e;let r=await this.storage.get(y),{data:i}=await this.getToken(r??void 0);return i?.token?(await this.storage.set(u,i.token),i.token):null}let{data:t}=await this.getToken();return t?.token??null}async persistLogin(t,e){if(!this.storage)return;let i=e?.headers.get(U)?.trim()||t.token||t.session?.token;i&&await this.storage.set(y,i),t.user&&await this.storage.set(P,t.user);let n=i??await this.storage.get(y),{data:a}=await this.getToken(n??void 0);a?.token&&await this.storage.set(u,a.token)}async clearLogin(){this.storage&&(await this.storage.remove(y),await this.storage.remove(P),await this.storage.remove(u))}getGoogleOpenPlatformLoginUrl(t,e){let r=new URLSearchParams({return_url:t});e?.applicationCode?.trim()&&r.set("application_code",e.applicationCode.trim()),e?.platformCode?.trim()&&r.set("platform_code",e.platformCode.trim());let i=M(this.integrationProviders,"google");return i&&r.set("oauth_credential_source",i),`${this.url("google/openplatform/login")}?${r.toString()}`}startGoogleOpenPlatformLogin(t,e){let r=this.getGoogleOpenPlatformLoginUrl(t,e);if(typeof globalThis<"u"&&"location"in globalThis){globalThis.location.href=r;return}throw new Error("startGoogleOpenPlatformLogin requires a browser environment with location")}async completeGoogleOpenPlatformLoginFromCurrentUrl(t){let e;if(t!=null&&t!=="")e=t;else if(typeof globalThis<"u"&&"location"in globalThis)e=globalThis.location.href;else return{error:{message:"completeGoogleOpenPlatformLoginFromCurrentUrl requires url or browser location",status:0}};let r;try{r=new URL(e).searchParams.get("exchange_code")}catch{return{error:{message:"invalid_callback_url",status:400}}}return r?.trim()?await this.loginWithGoogleExchangeCode(r.trim()):{error:{message:"missing_exchange_code",status:400}}}async loginWithGoogleExchangeCode(t){try{let e={"Content-Type":"application/json"};if(this.storage){let a=await this.storage.get(u);a!=null&&(e.Authorization=`Bearer ${a}`)}let r=await this.fetchImpl(this.url("google/openplatform/sign-in"),{method:"POST",headers:e,credentials:this.credentials,body:JSON.stringify({exchangeCode:t})}),i=await r.text();if(!r.ok)return{error:{message:i||r.statusText,status:r.status}};let n=i?JSON.parse(i):null;return!n?.token||!n.user?{error:{message:"invalid_google_login_response",status:502}}:(this.storage&&(await this.storage.set(u,n.token),await this.storage.set(y,n.token),await this.storage.set(P,n.user)),{data:n})}catch(e){return{error:{message:e instanceof Error?e.message:String(e),status:0}}}}async getGoogleOpenPlatformIdentity(){try{let t={};if(this.storage){let n=await this.storage.get(u);n!=null&&(t.Authorization=`Bearer ${n}`)}let e=await this.fetchImpl(this.url("google/openplatform/identity"),{method:"GET",credentials:this.credentials,...Object.keys(t).length?{headers:t}:{}}),r=await e.text();if(!e.ok)return{error:{message:r||e.statusText,status:e.status}};let i=r?JSON.parse(r):null;return i?.sub?{data:i}:{error:{message:"invalid_google_identity_response",status:502}}}catch(t){return{error:{message:t instanceof Error?t.message:String(t),status:0}}}}getGithubOpenPlatformLoginUrl(t,e){let r=new URLSearchParams({return_url:t});e?.applicationCode?.trim()&&r.set("application_code",e.applicationCode.trim()),e?.platformCode?.trim()&&r.set("platform_code",e.platformCode.trim());let i=M(this.integrationProviders,"github");return i&&r.set("oauth_credential_source",i),`${this.url("github/openplatform/login")}?${r.toString()}`}startGithubOpenPlatformLogin(t,e){let r=this.getGithubOpenPlatformLoginUrl(t,e);if(typeof globalThis<"u"&&"location"in globalThis){globalThis.location.href=r;return}throw new Error("startGithubOpenPlatformLogin requires a browser environment with location")}async completeGithubOpenPlatformLoginFromCurrentUrl(t){let e;if(t!=null&&t!=="")e=t;else if(typeof globalThis<"u"&&"location"in globalThis)e=globalThis.location.href;else return{error:{message:"completeGithubOpenPlatformLoginFromCurrentUrl requires url or browser location",status:0}};let r;try{r=new URL(e).searchParams.get("exchange_code")}catch{return{error:{message:"invalid_callback_url",status:400}}}return r?.trim()?await this.loginWithGithubExchangeCode(r.trim()):{error:{message:"missing_exchange_code",status:400}}}async loginWithGithubExchangeCode(t){try{let e={"Content-Type":"application/json"};if(this.storage){let a=await this.storage.get(u);a!=null&&(e.Authorization=`Bearer ${a}`)}let r=await this.fetchImpl(this.url("github/openplatform/sign-in"),{method:"POST",headers:e,credentials:this.credentials,body:JSON.stringify({exchangeCode:t})}),i=await r.text();if(!r.ok)return{error:{message:i||r.statusText,status:r.status}};let n=i?JSON.parse(i):null;return!n?.token||!n.user?{error:{message:"invalid_github_login_response",status:502}}:(this.storage&&(await this.storage.set(u,n.token),await this.storage.set(y,n.token),await this.storage.set(P,n.user)),{data:n})}catch(e){return{error:{message:e instanceof Error?e.message:String(e),status:0}}}}async getGithubOpenPlatformIdentity(){try{let t={};if(this.storage){let n=await this.storage.get(u);n!=null&&(t.Authorization=`Bearer ${n}`)}let e=await this.fetchImpl(this.url("github/openplatform/identity"),{method:"GET",credentials:this.credentials,...Object.keys(t).length?{headers:t}:{}}),r=await e.text();if(!e.ok)return{error:{message:r||e.statusText,status:e.status}};let i=r?JSON.parse(r):null;return i?.sub?{data:i}:{error:{message:"invalid_github_identity_response",status:502}}}catch(t){return{error:{message:t instanceof Error?t.message:String(t),status:0}}}}getWechatWebsiteOpenPlatformLoginUrl(t){let e=new URLSearchParams({return_url:t});return`${this.url("wechat-website/openplatform/login")}?${e.toString()}`}startWechatWebsiteOpenPlatformLogin(t){let e=this.getWechatWebsiteOpenPlatformLoginUrl(t);if(typeof globalThis<"u"&&"location"in globalThis){globalThis.location.href=e;return}throw new Error("startWechatWebsiteOpenPlatformLogin requires a browser environment with location")}async completeWechatWebsiteOpenPlatformLoginFromCurrentUrl(t){let e;if(t!=null&&t!=="")e=t;else if(typeof globalThis<"u"&&"location"in globalThis)e=globalThis.location.href;else return{error:{message:"completeWechatWebsiteOpenPlatformLoginFromCurrentUrl requires url or browser location",status:0}};let r;try{r=new URL(e).searchParams.get("exchange_code")}catch{return{error:{message:"invalid_callback_url",status:400}}}return r?.trim()?await this.loginWithWechatWebsiteExchangeCode(r.trim()):{error:{message:"missing_exchange_code",status:400}}}async loginWithWechatWebsiteExchangeCode(t){try{let e={"Content-Type":"application/json"};if(this.storage){let a=await this.storage.get(u);a!=null&&(e.Authorization=`Bearer ${a}`)}let r=await this.fetchImpl(this.url("wechat-website/openplatform/sign-in"),{method:"POST",headers:e,credentials:this.credentials,body:JSON.stringify({exchangeCode:t})}),i=await r.text();if(!r.ok)return{error:{message:i||r.statusText,status:r.status}};let n=i?JSON.parse(i):null;return!n?.token||!n.user?{error:{message:"invalid_wechat_website_login_response",status:502}}:(this.storage&&(await this.storage.set(u,n.token),await this.storage.set(y,n.token),await this.storage.set(P,n.user)),{data:n})}catch(e){return{error:{message:e instanceof Error?e.message:String(e),status:0}}}}async getWechatWebsiteOpenPlatformIdentity(){try{let t={};if(this.storage){let n=await this.storage.get(u);n!=null&&(t.Authorization=`Bearer ${n}`)}let e=await this.fetchImpl(this.url("wechat-website/openplatform/identity"),{method:"GET",credentials:this.credentials,...Object.keys(t).length?{headers:t}:{}}),r=await e.text();if(!e.ok)return{error:{message:r||e.statusText,status:e.status}};let i=r?JSON.parse(r):null;return i?.sub?{data:i}:{error:{message:"invalid_wechat_website_identity_response",status:502}}}catch(t){return{error:{message:t instanceof Error?t.message:String(t),status:0}}}}url(t){let r=`${`${this.baseUrl.replace(/\/+$/,"")}/${this.authPath.replace(/^\/+/,"")}`}/${t.replace(/^\/+/,"")}`;return typeof console<"u"&&(console.warn("[NvwaAuth] request URL:",r),!r.startsWith("http://")&&!r.startsWith("https://")&&console.warn("[NvwaAuth] URL \u975E\u5B8C\u6574\u5730\u5740\uFF0C\u5C0F\u7A0B\u5E8F\u4F1A\u62A5 invalid url\uFF0C\u8BF7\u68C0\u67E5 Nvwa \u6784\u9020\u65F6\u4F20\u5165\u7684 baseUrl")),r}async getSession(){try{let t={};if(this.storage){let i=await this.storage.get(y)??await this.storage.get(u);i!=null&&(t.Authorization=`Bearer ${i}`)}let e=await this.fetchImpl(this.url("session"),{method:"GET",credentials:this.credentials,...Object.keys(t).length?{headers:t}:{}});return e.ok?{data:await e.json()}:{data:null,error:{message:await e.text()||e.statusText,status:e.status}}}catch(t){return{data:null,error:{message:t instanceof Error?t.message:String(t),status:0}}}}async signInWithEmail(t,e){try{let r=await this.fetchImpl(this.url("sign-in/email"),{method:"POST",headers:{"Content-Type":"application/json"},credentials:this.credentials,body:JSON.stringify({email:t,password:e})}),i=await r.text();if(!r.ok)return{error:{message:i||r.statusText,status:r.status}};let n=i?JSON.parse(i):void 0;return n&&await this.persistLogin({user:n.user,session:n.session},r),{data:n}}catch(r){return{error:{message:r instanceof Error?r.message:String(r),status:0}}}}async signOut(){try{let t={};if(this.storage){let r=await this.storage.get(y)??await this.storage.get(u);r!=null&&(t.Authorization=`Bearer ${r}`)}let e=await this.fetchImpl(this.url("sign-out"),{method:"POST",credentials:this.credentials,...Object.keys(t).length?{headers:t}:{}});return await this.clearLogin(),e.ok?{}:{error:{message:await e.text()||e.statusText,status:e.status}}}catch(t){return{error:{message:t instanceof Error?t.message:String(t),status:0}}}}async signUp(t){let e=await this.postJson("sign-up/email",t);return e.data&&await this.persistLogin(e.data,e.response),e}async getToken(t){try{let e={};if(t)e.Authorization=`Bearer ${t}`;else if(this.storage){let a=await this.storage.get(y)??await this.storage.get(u);a!=null&&(e.Authorization=`Bearer ${a}`)}let r=await this.fetchImpl(this.url("token"),{method:"GET",credentials:this.credentials,...Object.keys(e).length?{headers:e}:{}}),i=await r.text();if(!r.ok)return{error:{message:i||r.statusText,status:r.status}};let n=i?JSON.parse(i):void 0;return{data:n?.token!=null?{token:n.token}:void 0}}catch(e){return{error:{message:e instanceof Error?e.message:String(e),status:0}}}}async signInWithUsername(t,e){let r=await this.postJson("sign-in/username",{username:t,password:e});return r.data&&await this.persistLogin(r.data,r.response),r}async signInWithPhoneNumber(t,e,r){let i=await this.postJson("sign-in/phone-number",{phoneNumber:t,password:e,rememberMe:r});return i.data&&await this.persistLogin(i.data,i.response),i}async sendPhoneNumberOtp(t){let e=await this.postJson("phone-number/send-otp",{phoneNumber:t});return e.error?{error:e.error}:{}}async verifyPhoneNumber(t,e){let r=await this.postJson("phone-number/verify",{phoneNumber:t,code:e});return r.data&&await this.persistLogin(r.data,r.response),r}async loginWithWeChatCode(t,e){try{let r={"Content-Type":"application/json"};if(this.storage){let o=await this.storage.get(u);o!=null&&(r.Authorization=`Bearer ${o}`)}let i=await this.fetchImpl(this.url("wechat/openplatform/sign-in"),{method:"POST",headers:r,credentials:this.credentials,body:JSON.stringify({code:t,applicationCode:e})}),n=await i.text();if(!i.ok)return{error:{message:n||i.statusText,status:i.status}};let a=n?JSON.parse(n):null;return!a?.token||!a.user?{error:{message:"invalid_wechat_login_response",status:502}}:(this.storage&&(await this.storage.set(u,a.token),await this.storage.set(y,a.token),await this.storage.set(P,a.user)),{data:a})}catch(r){return{error:{message:r instanceof Error?r.message:String(r),status:0}}}}async loginWithAlipayCode(t,e){try{let r={"Content-Type":"application/json"};if(this.storage){let o=await this.storage.get(u);o!=null&&(r.Authorization=`Bearer ${o}`)}let i=await this.fetchImpl(this.url("alipay/openplatform/sign-in"),{method:"POST",headers:r,credentials:this.credentials,body:JSON.stringify({code:t,applicationCode:e})}),n=await i.text();if(!i.ok)return{error:{message:n||i.statusText,status:i.status}};let a=n?JSON.parse(n):null;return!a?.token||!a.user?{error:{message:"invalid_alipay_login_response",status:502}}:(this.storage&&(await this.storage.set(u,a.token),await this.storage.set(y,a.token),await this.storage.set(P,a.user)),{data:a})}catch(r){return{error:{message:r instanceof Error?r.message:String(r),status:0}}}}async getWeChatOpenPlatformIdentity(t){try{let e={};if(this.storage){let o=await this.storage.get(u);o!=null&&(e.Authorization=`Bearer ${o}`)}let r=t?.trim()?`?applicationCode=${encodeURIComponent(t.trim())}`:"",i=await this.fetchImpl(this.url(`wechat/openplatform/identity${r}`),{method:"GET",credentials:this.credentials,...Object.keys(e).length?{headers:e}:{}}),n=await i.text();if(!i.ok)return{error:{message:n||i.statusText,status:i.status}};let a=n?JSON.parse(n):null;return!a?.openid||!a.appId?{error:{message:"invalid_wechat_identity_response",status:502}}:{data:a}}catch(e){return{error:{message:e instanceof Error?e.message:String(e),status:0}}}}async getAlipayOpenPlatformIdentity(t){try{let e={};if(this.storage){let o=await this.storage.get(u);o!=null&&(e.Authorization=`Bearer ${o}`)}let r=t?.trim()?`?applicationCode=${encodeURIComponent(t.trim())}`:"",i=await this.fetchImpl(this.url(`alipay/openplatform/identity${r}`),{method:"GET",credentials:this.credentials,...Object.keys(e).length?{headers:e}:{}}),n=await i.text();if(!i.ok)return{error:{message:n||i.statusText,status:i.status}};let a=n?JSON.parse(n):null;return!a?.openid||!a.appId?{error:{message:"invalid_alipay_identity_response",status:502}}:{data:a}}catch(e){return{error:{message:e instanceof Error?e.message:String(e),status:0}}}}async postJson(t,e){try{let r=await this.fetchImpl(this.url(t),{method:"POST",headers:{"Content-Type":"application/json"},credentials:this.credentials,body:JSON.stringify(e)}),i=await r.text();if(!r.ok)return{error:{message:i||r.statusText,status:r.status}};let n=i?JSON.parse(i):void 0;return{data:n?.data??n??void 0,response:r}}catch(r){return{error:{message:r instanceof Error?r.message:String(r),status:0}}}}};var $=class{constructor(t,e,r){this.storage=t,this.customFetch=e,this.handleUnauthorized=r}async fetch(t,e){return await this.customFetch(t,e)}async fetchWithAuth(t,e){let r=await this.storage.get(u),i=new f(e?.headers);r&&i.set("Authorization",`Bearer ${r}`);let n=e?.method||"GET";if((n==="POST"||n==="PUT"||n==="PATCH")&&e?.body){let o=i.get("Content-Type");(!o||o.includes("text/plain"))&&i.set("Content-Type","application/json")}let a=await this.customFetch(t,{...e,headers:i});if(a.status===401)throw this.handleUnauthorized(),new Error("\u672A\u767B\u5F55");return a}};var J="/storage",z=J+"/generateUploadUrl",N=class{constructor(t,e){this.baseUrl=t,this.http=e}async uploadFile(t){let e=await this.http.fetch(this.baseUrl+z,{method:"POST",body:{fileName:t.name||t.fileName,fileSize:t.size||t.fileSize,fileType:t.type||t.fileType}}),{url:r}=await e.json();if(!r)throw new Error("\u83B7\u53D6\u4E0A\u4F20URL\u5931\u8D25");let i=await this.http.fetch(r,{method:"PUT",body:t,headers:new f({"Content-Type":t.type||t.fileType||"application/octet-stream"})}),{url:n}=await i.json();return{url:n.split("?")[0]}}};var ct=class extends Error{constructor(s){super(s.message),this.name="PostgrestError",this.details=s.details,this.hint=s.hint,this.code=s.code}},ut=class{constructor(s){var t,e,r;this.shouldThrowOnError=!1,this.method=s.method,this.url=s.url,this.headers=new f(s.headers),this.schema=s.schema,this.body=s.body,this.shouldThrowOnError=(t=s.shouldThrowOnError)!==null&&t!==void 0?t:!1,this.signal=s.signal,this.isMaybeSingle=(e=s.isMaybeSingle)!==null&&e!==void 0?e:!1,this.urlLengthLimit=(r=s.urlLengthLimit)!==null&&r!==void 0?r:8e3,s.fetch?this.fetch=s.fetch:this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(s,t){return this.headers=new f(this.headers),this.headers.set(s,t),this}then(s,t){var e=this;this.schema===void 0||(["GET","HEAD"].includes(this.method)?this.headers.set("Accept-Profile",this.schema):this.headers.set("Content-Profile",this.schema)),this.method!=="GET"&&this.method!=="HEAD"&&this.headers.set("Content-Type","application/json");let r=this.fetch,i=r(this.url.toString(),{method:this.method,headers:this.headers,body:JSON.stringify(this.body),signal:this.signal}).then(async n=>{let a=null,o=null,h=null,c=n.status,l=n.statusText;if(n.ok){var d,p;if(e.method!=="HEAD"){var g;let v=await n.text();v===""||(e.headers.get("Accept")==="text/csv"||e.headers.get("Accept")&&(!((g=e.headers.get("Accept"))===null||g===void 0)&&g.includes("application/vnd.pgrst.plan+text"))?o=v:o=JSON.parse(v))}let m=(d=e.headers.get("Prefer"))===null||d===void 0?void 0:d.match(/count=(exact|planned|estimated)/),b=(p=n.headers.get("content-range"))===null||p===void 0?void 0:p.split("/");m&&b&&b.length>1&&(h=parseInt(b[1])),e.isMaybeSingle&&Array.isArray(o)&&(o.length>1?(a={code:"PGRST116",details:`Results contain ${o.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},o=null,h=null,c=406,l="Not Acceptable"):o.length===1?o=o[0]:o=null)}else{let m=await n.text();try{a=JSON.parse(m),Array.isArray(a)&&n.status===404&&(o=[],a=null,c=200,l="OK")}catch{n.status===404&&m===""?(c=204,l="No Content"):a={message:m}}if(a&&e.shouldThrowOnError)throw new ct(a)}return{error:a,data:o,count:h,status:c,statusText:l}});return this.shouldThrowOnError||(i=i.catch(n=>{var a;let o="",h="",c="",l=n?.cause;if(l){var d,p,g,m;let X=(d=l?.message)!==null&&d!==void 0?d:"",H=(p=l?.code)!==null&&p!==void 0?p:"";o=`${(g=n?.name)!==null&&g!==void 0?g:"FetchError"}: ${n?.message}`,o+=`
2
2
 
3
- Caused by: ${(m=l?.name)!==null&&m!==void 0?m:"Error"}: ${K}`,j&&(o+=` (${j})`),l?.stack&&(o+=`
4
- ${l.stack}`)}else{var b;o=(b=n?.stack)!==null&&b!==void 0?b:""}let w=this.url.toString().length;return n?.name==="AbortError"||n?.code==="ABORT_ERR"?(c="",h="Request was aborted (timeout or manual cancellation)",w>this.urlLengthLimit&&(h+=`. Note: Your request URL is ${w} characters, which may exceed server limits. If selecting many fields, consider using views. If filtering with large arrays (e.g., .in('id', [many IDs])), consider using an RPC function to pass values server-side.`)):(l?.name==="HeadersOverflowError"||l?.code==="UND_ERR_HEADERS_OVERFLOW")&&(c="",h="HTTP headers exceeded server limits (typically 16KB)",w>this.urlLengthLimit&&(h+=`. Your request URL is ${w} characters. If selecting many fields, consider using views. If filtering with large arrays (e.g., .in('id', [200+ IDs])), consider using an RPC function instead.`)),{error:{message:`${(a=n?.name)!==null&&a!==void 0?a:"FetchError"}: ${n?.message}`,details:o,hint:h,code:c},data:null,count:null,status:0,statusText:""}})),i.then(s,t)}returns(){return this}overrideTypes(){return this}},lt=class extends ot{select(s){let t=!1,e=(s??"*").split("").map(r=>/\s/.test(r)&&!t?"":(r==='"'&&(t=!t),r)).join("");return this.url.searchParams.set("select",e),this.headers.append("Prefer","return=representation"),this}order(s,{ascending:t=!0,nullsFirst:e,foreignTable:r,referencedTable:i=r}={}){let n=i?`${i}.order`:"order",a=this.url.searchParams.get(n);return this.url.searchParams.set(n,`${a?`${a},`:""}${s}.${t?"asc":"desc"}${e===void 0?"":e?".nullsfirst":".nullslast"}`),this}limit(s,{foreignTable:t,referencedTable:e=t}={}){let r=typeof e>"u"?"limit":`${e}.limit`;return this.url.searchParams.set(r,`${s}`),this}range(s,t,{foreignTable:e,referencedTable:r=e}={}){let i=typeof r>"u"?"offset":`${r}.offset`,n=typeof r>"u"?"limit":`${r}.limit`;return this.url.searchParams.set(i,`${s}`),this.url.searchParams.set(n,`${t-s+1}`),this}abortSignal(s){return this.signal=s,this}single(){return this.headers.set("Accept","application/vnd.pgrst.object+json"),this}maybeSingle(){return this.isMaybeSingle=!0,this}csv(){return this.headers.set("Accept","text/csv"),this}geojson(){return this.headers.set("Accept","application/geo+json"),this}explain({analyze:s=!1,verbose:t=!1,settings:e=!1,buffers:r=!1,wal:i=!1,format:n="text"}={}){var a;let o=[s?"analyze":null,t?"verbose":null,e?"settings":null,r?"buffers":null,i?"wal":null].filter(Boolean).join("|"),h=(a=this.headers.get("Accept"))!==null&&a!==void 0?a:"application/json";return this.headers.set("Accept",`application/vnd.pgrst.plan+${n}; for="${h}"; options=${o};`),n==="json"?this:this}rollback(){return this.headers.append("Prefer","tx=rollback"),this}returns(){return this}maxAffected(s){return this.headers.append("Prefer","handling=strict"),this.headers.append("Prefer",`max-affected=${s}`),this}},J=new RegExp("[,()]"),S=class extends lt{eq(s,t){return this.url.searchParams.append(s,`eq.${t}`),this}neq(s,t){return this.url.searchParams.append(s,`neq.${t}`),this}gt(s,t){return this.url.searchParams.append(s,`gt.${t}`),this}gte(s,t){return this.url.searchParams.append(s,`gte.${t}`),this}lt(s,t){return this.url.searchParams.append(s,`lt.${t}`),this}lte(s,t){return this.url.searchParams.append(s,`lte.${t}`),this}like(s,t){return this.url.searchParams.append(s,`like.${t}`),this}likeAllOf(s,t){return this.url.searchParams.append(s,`like(all).{${t.join(",")}}`),this}likeAnyOf(s,t){return this.url.searchParams.append(s,`like(any).{${t.join(",")}}`),this}ilike(s,t){return this.url.searchParams.append(s,`ilike.${t}`),this}ilikeAllOf(s,t){return this.url.searchParams.append(s,`ilike(all).{${t.join(",")}}`),this}ilikeAnyOf(s,t){return this.url.searchParams.append(s,`ilike(any).{${t.join(",")}}`),this}regexMatch(s,t){return this.url.searchParams.append(s,`match.${t}`),this}regexIMatch(s,t){return this.url.searchParams.append(s,`imatch.${t}`),this}is(s,t){return this.url.searchParams.append(s,`is.${t}`),this}isDistinct(s,t){return this.url.searchParams.append(s,`isdistinct.${t}`),this}in(s,t){let e=Array.from(new Set(t)).map(r=>typeof r=="string"&&J.test(r)?`"${r}"`:`${r}`).join(",");return this.url.searchParams.append(s,`in.(${e})`),this}notIn(s,t){let e=Array.from(new Set(t)).map(r=>typeof r=="string"&&J.test(r)?`"${r}"`:`${r}`).join(",");return this.url.searchParams.append(s,`not.in.(${e})`),this}contains(s,t){return typeof t=="string"?this.url.searchParams.append(s,`cs.${t}`):Array.isArray(t)?this.url.searchParams.append(s,`cs.{${t.join(",")}}`):this.url.searchParams.append(s,`cs.${JSON.stringify(t)}`),this}containedBy(s,t){return typeof t=="string"?this.url.searchParams.append(s,`cd.${t}`):Array.isArray(t)?this.url.searchParams.append(s,`cd.{${t.join(",")}}`):this.url.searchParams.append(s,`cd.${JSON.stringify(t)}`),this}rangeGt(s,t){return this.url.searchParams.append(s,`sr.${t}`),this}rangeGte(s,t){return this.url.searchParams.append(s,`nxl.${t}`),this}rangeLt(s,t){return this.url.searchParams.append(s,`sl.${t}`),this}rangeLte(s,t){return this.url.searchParams.append(s,`nxr.${t}`),this}rangeAdjacent(s,t){return this.url.searchParams.append(s,`adj.${t}`),this}overlaps(s,t){return typeof t=="string"?this.url.searchParams.append(s,`ov.${t}`):this.url.searchParams.append(s,`ov.{${t.join(",")}}`),this}textSearch(s,t,{config:e,type:r}={}){let i="";r==="plain"?i="pl":r==="phrase"?i="ph":r==="websearch"&&(i="w");let n=e===void 0?"":`(${e})`;return this.url.searchParams.append(s,`${i}fts${n}.${t}`),this}match(s){return Object.entries(s).filter(([t,e])=>e!==void 0).forEach(([t,e])=>{this.url.searchParams.append(t,`eq.${e}`)}),this}not(s,t,e){return this.url.searchParams.append(s,`not.${t}.${e}`),this}or(s,{foreignTable:t,referencedTable:e=t}={}){let r=e?`${e}.or`:"or";return this.url.searchParams.append(r,`(${s})`),this}filter(s,t,e){return this.url.searchParams.append(s,`${t}.${e}`),this}},ht=class{constructor(s,{headers:t={},schema:e,fetch:r,urlLengthLimit:i=8e3}){this.url=s,this.headers=new f(t),this.schema=e,this.fetch=r,this.urlLengthLimit=i}cloneRequestState(){return{url:new O(this.url.toString()),headers:new f(this.headers)}}select(s,t){let{head:e=!1,count:r}=t??{},i=e?"HEAD":"GET",n=!1,a=(s??"*").split("").map(c=>/\s/.test(c)&&!n?"":(c==='"'&&(n=!n),c)).join(""),{url:o,headers:h}=this.cloneRequestState();return o.searchParams.set("select",a),r&&h.append("Prefer",`count=${r}`),new S({method:i,url:o,headers:h,schema:this.schema,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}insert(s,{count:t,defaultToNull:e=!0}={}){var r;let i="POST",{url:n,headers:a}=this.cloneRequestState();if(t&&a.append("Prefer",`count=${t}`),e||a.append("Prefer","missing=default"),Array.isArray(s)){let o=s.reduce((h,c)=>h.concat(Object.keys(c)),[]);if(o.length>0){let h=[...new Set(o)].map(c=>`"${c}"`);n.searchParams.set("columns",h.join(","))}}return new S({method:i,url:n,headers:a,schema:this.schema,body:s,fetch:(r=this.fetch)!==null&&r!==void 0?r:fetch,urlLengthLimit:this.urlLengthLimit})}upsert(s,{onConflict:t,ignoreDuplicates:e=!1,count:r,defaultToNull:i=!0}={}){var n;let a="POST",{url:o,headers:h}=this.cloneRequestState();if(h.append("Prefer",`resolution=${e?"ignore":"merge"}-duplicates`),t!==void 0&&o.searchParams.set("on_conflict",t),r&&h.append("Prefer",`count=${r}`),i||h.append("Prefer","missing=default"),Array.isArray(s)){let c=s.reduce((l,u)=>l.concat(Object.keys(u)),[]);if(c.length>0){let l=[...new Set(c)].map(u=>`"${u}"`);o.searchParams.set("columns",l.join(","))}}return new S({method:a,url:o,headers:h,schema:this.schema,body:s,fetch:(n=this.fetch)!==null&&n!==void 0?n:fetch,urlLengthLimit:this.urlLengthLimit})}update(s,{count:t}={}){var e;let r="PATCH",{url:i,headers:n}=this.cloneRequestState();return t&&n.append("Prefer",`count=${t}`),new S({method:r,url:i,headers:n,schema:this.schema,body:s,fetch:(e=this.fetch)!==null&&e!==void 0?e:fetch,urlLengthLimit:this.urlLengthLimit})}delete({count:s}={}){var t;let e="DELETE",{url:r,headers:i}=this.cloneRequestState();return s&&i.append("Prefer",`count=${s}`),new S({method:e,url:r,headers:i,schema:this.schema,fetch:(t=this.fetch)!==null&&t!==void 0?t:fetch,urlLengthLimit:this.urlLengthLimit})}};function x(s){"@babel/helpers - typeof";return x=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},x(s)}function ct(s,t){if(x(s)!="object"||!s)return s;var e=s[Symbol.toPrimitive];if(e!==void 0){var r=e.call(s,t||"default");if(x(r)!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(s)}function ut(s){var t=ct(s,"string");return x(t)=="symbol"?t:t+""}function pt(s,t,e){return(t=ut(t))in s?Object.defineProperty(s,t,{value:e,enumerable:!0,configurable:!0,writable:!0}):s[t]=e,s}function B(s,t){var e=Object.keys(s);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(s);t&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(s,i).enumerable})),e.push.apply(e,r)}return e}function E(s){for(var t=1;t<arguments.length;t++){var e=arguments[t]!=null?arguments[t]:{};t%2?B(Object(e),!0).forEach(function(r){pt(s,r,e[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(s,Object.getOwnPropertyDescriptors(e)):B(Object(e)).forEach(function(r){Object.defineProperty(s,r,Object.getOwnPropertyDescriptor(e,r))})}return s}var z=class D{constructor(t,{headers:e={},schema:r,fetch:i,timeout:n,urlLengthLimit:a=8e3}={}){this.url=t,this.headers=new f(e),this.schemaName=r,this.urlLengthLimit=a;let o=i??globalThis.fetch;n!==void 0&&n>0?this.fetch=(h,c)=>{let l=new q,u=setTimeout(()=>l.abort(),n),d=c?.signal;if(d){if(d.aborted)return clearTimeout(u),o(h,c);let g=()=>{clearTimeout(u),l.abort()};return d.addEventListener("abort",g,{once:!0}),o(h,E(E({},c),{},{signal:l.signal})).finally(()=>{clearTimeout(u),d.removeEventListener("abort",g)})}return o(h,E(E({},c),{},{signal:l.signal})).finally(()=>clearTimeout(u))}:this.fetch=o}from(t){if(!t||typeof t!="string"||t.trim()==="")throw new Error("Invalid relation name: relation must be a non-empty string.");return new ht(new O(`${this.url}/${t}`),{headers:new f(this.headers),schema:this.schemaName,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}schema(t){return new D(this.url,{headers:this.headers,schema:t,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}rpc(t,e={},{head:r=!1,get:i=!1,count:n}={}){var a;let o,h=new O(`${this.url}/rpc/${t}`),c,l=g=>g!==null&&typeof g=="object"&&(!Array.isArray(g)||g.some(l)),u=r&&Object.values(e).some(l);u?(o="POST",c=e):r||i?(o=r?"HEAD":"GET",Object.entries(e).filter(([g,m])=>m!==void 0).map(([g,m])=>[g,Array.isArray(m)?`{${m.join(",")}}`:`${m}`]).forEach(([g,m])=>{h.searchParams.append(g,m)})):(o="POST",c=e);let d=new f(this.headers);return u?d.set("Prefer",n?`count=${n},return=minimal`:"return=minimal"):n&&d.set("Prefer",`count=${n}`),new S({method:o,url:h,headers:d,schema:this.schemaName,body:c,fetch:(a=this.fetch)!==null&&a!==void 0?a:fetch,urlLengthLimit:this.urlLengthLimit})}};var Y="/entities",dt=(s,t)=>new z(s+Y,{fetch:t.fetchWithAuth.bind(t)});var N=class{constructor(){this.hoverOverlay=null;this.selectedOverlay=null;this.tooltip=null;this.hoverElement=null;this.selectedElement=null;this.hoverUpdateHandler=null;this.selectedUpdateHandler=null;this.createStyles()}createStyles(){if(document.getElementById("__nvwa-inspector-overlay-style"))return;let t=document.createElement("style");t.id="__nvwa-inspector-overlay-style",t.textContent=`
3
+ Caused by: ${(m=l?.name)!==null&&m!==void 0?m:"Error"}: ${X}`,H&&(o+=` (${H})`),l?.stack&&(o+=`
4
+ ${l.stack}`)}else{var b;o=(b=n?.stack)!==null&&b!==void 0?b:""}let v=this.url.toString().length;return n?.name==="AbortError"||n?.code==="ABORT_ERR"?(c="",h="Request was aborted (timeout or manual cancellation)",v>this.urlLengthLimit&&(h+=`. Note: Your request URL is ${v} characters, which may exceed server limits. If selecting many fields, consider using views. If filtering with large arrays (e.g., .in('id', [many IDs])), consider using an RPC function to pass values server-side.`)):(l?.name==="HeadersOverflowError"||l?.code==="UND_ERR_HEADERS_OVERFLOW")&&(c="",h="HTTP headers exceeded server limits (typically 16KB)",v>this.urlLengthLimit&&(h+=`. Your request URL is ${v} characters. If selecting many fields, consider using views. If filtering with large arrays (e.g., .in('id', [200+ IDs])), consider using an RPC function instead.`)),{error:{message:`${(a=n?.name)!==null&&a!==void 0?a:"FetchError"}: ${n?.message}`,details:o,hint:h,code:c},data:null,count:null,status:0,statusText:""}})),i.then(s,t)}returns(){return this}overrideTypes(){return this}},dt=class extends ut{select(s){let t=!1,e=(s??"*").split("").map(r=>/\s/.test(r)&&!t?"":(r==='"'&&(t=!t),r)).join("");return this.url.searchParams.set("select",e),this.headers.append("Prefer","return=representation"),this}order(s,{ascending:t=!0,nullsFirst:e,foreignTable:r,referencedTable:i=r}={}){let n=i?`${i}.order`:"order",a=this.url.searchParams.get(n);return this.url.searchParams.set(n,`${a?`${a},`:""}${s}.${t?"asc":"desc"}${e===void 0?"":e?".nullsfirst":".nullslast"}`),this}limit(s,{foreignTable:t,referencedTable:e=t}={}){let r=typeof e>"u"?"limit":`${e}.limit`;return this.url.searchParams.set(r,`${s}`),this}range(s,t,{foreignTable:e,referencedTable:r=e}={}){let i=typeof r>"u"?"offset":`${r}.offset`,n=typeof r>"u"?"limit":`${r}.limit`;return this.url.searchParams.set(i,`${s}`),this.url.searchParams.set(n,`${t-s+1}`),this}abortSignal(s){return this.signal=s,this}single(){return this.headers.set("Accept","application/vnd.pgrst.object+json"),this}maybeSingle(){return this.isMaybeSingle=!0,this}csv(){return this.headers.set("Accept","text/csv"),this}geojson(){return this.headers.set("Accept","application/geo+json"),this}explain({analyze:s=!1,verbose:t=!1,settings:e=!1,buffers:r=!1,wal:i=!1,format:n="text"}={}){var a;let o=[s?"analyze":null,t?"verbose":null,e?"settings":null,r?"buffers":null,i?"wal":null].filter(Boolean).join("|"),h=(a=this.headers.get("Accept"))!==null&&a!==void 0?a:"application/json";return this.headers.set("Accept",`application/vnd.pgrst.plan+${n}; for="${h}"; options=${o};`),n==="json"?this:this}rollback(){return this.headers.append("Prefer","tx=rollback"),this}returns(){return this}maxAffected(s){return this.headers.append("Prefer","handling=strict"),this.headers.append("Prefer",`max-affected=${s}`),this}},B=new RegExp("[,()]"),S=class extends dt{eq(s,t){return this.url.searchParams.append(s,`eq.${t}`),this}neq(s,t){return this.url.searchParams.append(s,`neq.${t}`),this}gt(s,t){return this.url.searchParams.append(s,`gt.${t}`),this}gte(s,t){return this.url.searchParams.append(s,`gte.${t}`),this}lt(s,t){return this.url.searchParams.append(s,`lt.${t}`),this}lte(s,t){return this.url.searchParams.append(s,`lte.${t}`),this}like(s,t){return this.url.searchParams.append(s,`like.${t}`),this}likeAllOf(s,t){return this.url.searchParams.append(s,`like(all).{${t.join(",")}}`),this}likeAnyOf(s,t){return this.url.searchParams.append(s,`like(any).{${t.join(",")}}`),this}ilike(s,t){return this.url.searchParams.append(s,`ilike.${t}`),this}ilikeAllOf(s,t){return this.url.searchParams.append(s,`ilike(all).{${t.join(",")}}`),this}ilikeAnyOf(s,t){return this.url.searchParams.append(s,`ilike(any).{${t.join(",")}}`),this}regexMatch(s,t){return this.url.searchParams.append(s,`match.${t}`),this}regexIMatch(s,t){return this.url.searchParams.append(s,`imatch.${t}`),this}is(s,t){return this.url.searchParams.append(s,`is.${t}`),this}isDistinct(s,t){return this.url.searchParams.append(s,`isdistinct.${t}`),this}in(s,t){let e=Array.from(new Set(t)).map(r=>typeof r=="string"&&B.test(r)?`"${r}"`:`${r}`).join(",");return this.url.searchParams.append(s,`in.(${e})`),this}notIn(s,t){let e=Array.from(new Set(t)).map(r=>typeof r=="string"&&B.test(r)?`"${r}"`:`${r}`).join(",");return this.url.searchParams.append(s,`not.in.(${e})`),this}contains(s,t){return typeof t=="string"?this.url.searchParams.append(s,`cs.${t}`):Array.isArray(t)?this.url.searchParams.append(s,`cs.{${t.join(",")}}`):this.url.searchParams.append(s,`cs.${JSON.stringify(t)}`),this}containedBy(s,t){return typeof t=="string"?this.url.searchParams.append(s,`cd.${t}`):Array.isArray(t)?this.url.searchParams.append(s,`cd.{${t.join(",")}}`):this.url.searchParams.append(s,`cd.${JSON.stringify(t)}`),this}rangeGt(s,t){return this.url.searchParams.append(s,`sr.${t}`),this}rangeGte(s,t){return this.url.searchParams.append(s,`nxl.${t}`),this}rangeLt(s,t){return this.url.searchParams.append(s,`sl.${t}`),this}rangeLte(s,t){return this.url.searchParams.append(s,`nxr.${t}`),this}rangeAdjacent(s,t){return this.url.searchParams.append(s,`adj.${t}`),this}overlaps(s,t){return typeof t=="string"?this.url.searchParams.append(s,`ov.${t}`):this.url.searchParams.append(s,`ov.{${t.join(",")}}`),this}textSearch(s,t,{config:e,type:r}={}){let i="";r==="plain"?i="pl":r==="phrase"?i="ph":r==="websearch"&&(i="w");let n=e===void 0?"":`(${e})`;return this.url.searchParams.append(s,`${i}fts${n}.${t}`),this}match(s){return Object.entries(s).filter(([t,e])=>e!==void 0).forEach(([t,e])=>{this.url.searchParams.append(t,`eq.${e}`)}),this}not(s,t,e){return this.url.searchParams.append(s,`not.${t}.${e}`),this}or(s,{foreignTable:t,referencedTable:e=t}={}){let r=e?`${e}.or`:"or";return this.url.searchParams.append(r,`(${s})`),this}filter(s,t,e){return this.url.searchParams.append(s,`${t}.${e}`),this}},pt=class{constructor(s,{headers:t={},schema:e,fetch:r,urlLengthLimit:i=8e3}){this.url=s,this.headers=new f(t),this.schema=e,this.fetch=r,this.urlLengthLimit=i}cloneRequestState(){return{url:new O(this.url.toString()),headers:new f(this.headers)}}select(s,t){let{head:e=!1,count:r}=t??{},i=e?"HEAD":"GET",n=!1,a=(s??"*").split("").map(c=>/\s/.test(c)&&!n?"":(c==='"'&&(n=!n),c)).join(""),{url:o,headers:h}=this.cloneRequestState();return o.searchParams.set("select",a),r&&h.append("Prefer",`count=${r}`),new S({method:i,url:o,headers:h,schema:this.schema,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}insert(s,{count:t,defaultToNull:e=!0}={}){var r;let i="POST",{url:n,headers:a}=this.cloneRequestState();if(t&&a.append("Prefer",`count=${t}`),e||a.append("Prefer","missing=default"),Array.isArray(s)){let o=s.reduce((h,c)=>h.concat(Object.keys(c)),[]);if(o.length>0){let h=[...new Set(o)].map(c=>`"${c}"`);n.searchParams.set("columns",h.join(","))}}return new S({method:i,url:n,headers:a,schema:this.schema,body:s,fetch:(r=this.fetch)!==null&&r!==void 0?r:fetch,urlLengthLimit:this.urlLengthLimit})}upsert(s,{onConflict:t,ignoreDuplicates:e=!1,count:r,defaultToNull:i=!0}={}){var n;let a="POST",{url:o,headers:h}=this.cloneRequestState();if(h.append("Prefer",`resolution=${e?"ignore":"merge"}-duplicates`),t!==void 0&&o.searchParams.set("on_conflict",t),r&&h.append("Prefer",`count=${r}`),i||h.append("Prefer","missing=default"),Array.isArray(s)){let c=s.reduce((l,d)=>l.concat(Object.keys(d)),[]);if(c.length>0){let l=[...new Set(c)].map(d=>`"${d}"`);o.searchParams.set("columns",l.join(","))}}return new S({method:a,url:o,headers:h,schema:this.schema,body:s,fetch:(n=this.fetch)!==null&&n!==void 0?n:fetch,urlLengthLimit:this.urlLengthLimit})}update(s,{count:t}={}){var e;let r="PATCH",{url:i,headers:n}=this.cloneRequestState();return t&&n.append("Prefer",`count=${t}`),new S({method:r,url:i,headers:n,schema:this.schema,body:s,fetch:(e=this.fetch)!==null&&e!==void 0?e:fetch,urlLengthLimit:this.urlLengthLimit})}delete({count:s}={}){var t;let e="DELETE",{url:r,headers:i}=this.cloneRequestState();return s&&i.append("Prefer",`count=${s}`),new S({method:e,url:r,headers:i,schema:this.schema,fetch:(t=this.fetch)!==null&&t!==void 0?t:fetch,urlLengthLimit:this.urlLengthLimit})}};function L(s){"@babel/helpers - typeof";return L=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},L(s)}function gt(s,t){if(L(s)!="object"||!s)return s;var e=s[Symbol.toPrimitive];if(e!==void 0){var r=e.call(s,t||"default");if(L(r)!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(s)}function mt(s){var t=gt(s,"string");return L(t)=="symbol"?t:t+""}function ft(s,t,e){return(t=mt(t))in s?Object.defineProperty(s,t,{value:e,enumerable:!0,configurable:!0,writable:!0}):s[t]=e,s}function D(s,t){var e=Object.keys(s);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(s);t&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(s,i).enumerable})),e.push.apply(e,r)}return e}function E(s){for(var t=1;t<arguments.length;t++){var e=arguments[t]!=null?arguments[t]:{};t%2?D(Object(e),!0).forEach(function(r){ft(s,r,e[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(s,Object.getOwnPropertyDescriptors(e)):D(Object(e)).forEach(function(r){Object.defineProperty(s,r,Object.getOwnPropertyDescriptor(e,r))})}return s}var Y=class K{constructor(t,{headers:e={},schema:r,fetch:i,timeout:n,urlLengthLimit:a=8e3}={}){this.url=t,this.headers=new f(e),this.schemaName=r,this.urlLengthLimit=a;let o=i??globalThis.fetch;n!==void 0&&n>0?this.fetch=(h,c)=>{let l=new F,d=setTimeout(()=>l.abort(),n),p=c?.signal;if(p){if(p.aborted)return clearTimeout(d),o(h,c);let g=()=>{clearTimeout(d),l.abort()};return p.addEventListener("abort",g,{once:!0}),o(h,E(E({},c),{},{signal:l.signal})).finally(()=>{clearTimeout(d),p.removeEventListener("abort",g)})}return o(h,E(E({},c),{},{signal:l.signal})).finally(()=>clearTimeout(d))}:this.fetch=o}from(t){if(!t||typeof t!="string"||t.trim()==="")throw new Error("Invalid relation name: relation must be a non-empty string.");return new pt(new O(`${this.url}/${t}`),{headers:new f(this.headers),schema:this.schemaName,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}schema(t){return new K(this.url,{headers:this.headers,schema:t,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}rpc(t,e={},{head:r=!1,get:i=!1,count:n}={}){var a;let o,h=new O(`${this.url}/rpc/${t}`),c,l=g=>g!==null&&typeof g=="object"&&(!Array.isArray(g)||g.some(l)),d=r&&Object.values(e).some(l);d?(o="POST",c=e):r||i?(o=r?"HEAD":"GET",Object.entries(e).filter(([g,m])=>m!==void 0).map(([g,m])=>[g,Array.isArray(m)?`{${m.join(",")}}`:`${m}`]).forEach(([g,m])=>{h.searchParams.append(g,m)})):(o="POST",c=e);let p=new f(this.headers);return d?p.set("Prefer",n?`count=${n},return=minimal`:"return=minimal"):n&&p.set("Prefer",`count=${n}`),new S({method:o,url:h,headers:p,schema:this.schemaName,body:c,fetch:(a=this.fetch)!==null&&a!==void 0?a:fetch,urlLengthLimit:this.urlLengthLimit})}};var V="/entities",yt=(s,t)=>new Y(s+V,{fetch:t.fetchWithAuth.bind(t)});var j=class{constructor(){this.hoverOverlay=null;this.selectedOverlay=null;this.tooltip=null;this.hoverElement=null;this.selectedElement=null;this.hoverUpdateHandler=null;this.selectedUpdateHandler=null;this.createStyles()}createStyles(){if(document.getElementById("__nvwa-inspector-overlay-style"))return;let t=document.createElement("style");t.id="__nvwa-inspector-overlay-style",t.textContent=`
5
5
  .__nvwa-inspector-overlay {
6
6
  position: absolute;
7
7
  pointer-events: none;
@@ -33,4 +33,4 @@ ${l.stack}`)}else{var b;o=(b=n?.stack)!==null&&b!==void 0?b:""}let w=this.url.to
33
33
  max-width: 400px;
34
34
  word-break: break-all;
35
35
  }
36
- `,document.head.appendChild(t)}createTooltip(){return this.tooltip?this.tooltip:(this.tooltip=document.createElement("div"),this.tooltip.id="__nvwa-inspector-tooltip",document.body.appendChild(this.tooltip),this.tooltip)}createOverlay(t){let e=document.createElement("div");return e.className=`__nvwa-inspector-overlay __nvwa-inspector-overlay-${t}`,document.body.appendChild(e),e}updateOverlayPosition(t,e){if(!e.isConnected)return;let r=e.getBoundingClientRect(),i=window.scrollX||window.pageXOffset,n=window.scrollY||window.pageYOffset;r.width>0&&r.height>0?(t.style.left=`${r.left+i}px`,t.style.top=`${r.top+n}px`,t.style.width=`${r.width}px`,t.style.height=`${r.height}px`,t.style.display="block"):t.style.display="none"}removeOverlay(t){t&&t.parentNode&&t.parentNode.removeChild(t)}highlightElement(t,e){if(!t.isConnected)return;if(this.hoverElement===t&&this.hoverOverlay){this.updateOverlayPosition(this.hoverOverlay,t);let o=this.createTooltip();e?o.textContent=e:o.textContent=`<${t.tagName.toLowerCase()}> (\u65E0 source location)`,o.style.display="block";let h=t.getBoundingClientRect();o.style.left=`${h.left+window.scrollX}px`,o.style.top=`${h.top+window.scrollY-o.offsetHeight-8}px`,h.top<o.offsetHeight+8&&(o.style.top=`${h.bottom+window.scrollY+8}px`);return}this.hoverOverlay&&(this.removeOverlay(this.hoverOverlay),this.hoverOverlay=null);let r=this.createOverlay("hover");this.updateOverlayPosition(r,t),this.hoverOverlay=r,this.hoverElement=t;let i=()=>{this.hoverOverlay&&this.hoverElement&&this.hoverElement.isConnected&&this.updateOverlayPosition(this.hoverOverlay,this.hoverElement)};this.hoverUpdateHandler&&(window.removeEventListener("scroll",this.hoverUpdateHandler,!0),window.removeEventListener("resize",this.hoverUpdateHandler)),this.hoverUpdateHandler=i,window.addEventListener("scroll",i,!0),window.addEventListener("resize",i);let n=this.createTooltip();e?n.textContent=e:n.textContent=`<${t.tagName.toLowerCase()}> (\u65E0 source location)`,n.style.display="block";let a=t.getBoundingClientRect();n.style.left=`${a.left+window.scrollX}px`,n.style.top=`${a.top+window.scrollY-n.offsetHeight-8}px`,a.top<n.offsetHeight+8&&(n.style.top=`${a.bottom+window.scrollY+8}px`)}selectElement(t,e){if(!t.isConnected)return;if(this.selectedElement===t&&this.selectedOverlay){this.updateOverlayPosition(this.selectedOverlay,t);return}this.selectedOverlay&&(this.removeOverlay(this.selectedOverlay),this.selectedOverlay=null);let r=this.createOverlay("selected");this.updateOverlayPosition(r,t),this.selectedOverlay=r,this.selectedElement=t;let i=()=>{this.selectedOverlay&&this.selectedElement&&this.selectedElement.isConnected&&this.updateOverlayPosition(this.selectedOverlay,this.selectedElement)};this.selectedUpdateHandler&&(window.removeEventListener("scroll",this.selectedUpdateHandler,!0),window.removeEventListener("resize",this.selectedUpdateHandler)),this.selectedUpdateHandler=i,window.addEventListener("scroll",i,!0),window.addEventListener("resize",i)}removeHighlight(){this.hoverOverlay&&(this.removeOverlay(this.hoverOverlay),this.hoverOverlay=null),this.hoverElement&&(this.hoverElement=null),this.tooltip&&(this.tooltip.style.display="none"),this.hoverUpdateHandler&&(window.removeEventListener("scroll",this.hoverUpdateHandler,!0),window.removeEventListener("resize",this.hoverUpdateHandler),this.hoverUpdateHandler=null)}clearSelection(){this.selectedOverlay&&(this.removeOverlay(this.selectedOverlay),this.selectedOverlay=null),this.selectedElement&&(this.selectedElement=null),this.selectedUpdateHandler&&(window.removeEventListener("scroll",this.selectedUpdateHandler,!0),window.removeEventListener("resize",this.selectedUpdateHandler),this.selectedUpdateHandler=null)}cleanup(){this.removeHighlight(),this.clearSelection(),this.tooltip&&this.tooltip.parentNode&&(this.tooltip.parentNode.removeChild(this.tooltip),this.tooltip=null);let t=document.getElementById("__nvwa-inspector-overlay-style");t&&t.parentNode&&t.parentNode.removeChild(t)}};function gt(s="root"){if(typeof document>"u")return null;let t=document.getElementById(s)||document.body;if(!t)return null;let e=t.querySelector("[data-source-location]");if(e){let r=e.getAttribute("data-source-location");if(r)return r}if(t.firstElementChild){let i=t.firstElementChild.getAttribute("data-source-location");if(i)return i}return null}function mt(s){let t=s;if(typeof t.kind=="string")return t;if(typeof t.tradeNO=="string")return{kind:"alipay_miniprogram",tradeNO:t.tradeNO};if(typeof t.clientSecret=="string")return{kind:"stripe_client_secret",clientSecret:t.clientSecret};if(typeof t.redirectUrl=="string")return{kind:"redirect_url",redirectUrl:t.redirectUrl};if(typeof t.formHtml=="string")return{kind:"alipay_page",formHtml:t.formHtml};if(typeof t.codeUrl=="string")return{kind:"wechat_native_qr",codeUrl:t.codeUrl};let e=t.jsapiPayParams??t;return typeof e.timeStamp=="string"&&typeof e.nonceStr=="string"&&typeof e.package=="string"&&typeof e.paySign=="string"&&typeof e.appId=="string"?{kind:"wechat_jsapi",mode:"jsapi",jsapiPayParams:{appId:e.appId,timeStamp:e.timeStamp,nonceStr:e.nonceStr,package:e.package,signType:e.signType??"RSA",paySign:e.paySign}}:null}function ft(s,t,e){return t.requestPayment(s.payParams,e)}function yt(s,t){let e=s.replace(/\/$/,""),r=t.startsWith("/")?t:`/${t}`;return`${e}${r}`}var R=class{constructor(t,e,r){this.cache=null;this.baseUrl=t.replace(/\/$/,""),this.fetchImpl=e,this.context=r}get(){return this.cache?.snapshot??null}getIntegrationItem(t){let e=this.cache?.snapshot;return e?e.integrations.find(i=>i.integrationType===t)??null:null}getEnabledProviders(t){let e=this.getIntegrationItem(t);return!e?.enabled||!e.providers?.length?[]:e.providers.filter(r=>r.enabled)}clear(){this.cache=null}async load(t){let e=t??{},r=this.context.applicationCode.trim(),i=this.context.platformCode.trim();if(!r||!i)throw new Error("NvwaIntegrationSnapshot: applicationCode \u4E0E platformCode \u5728\u6784\u9020 IntegrationSnapshotContext \u65F6\u4E0D\u80FD\u4E3A\u7A7A");let a=this.context.locale?.trim().toLowerCase()==="en"?"en":"zh",o=`${r} ${i} ${a}`;if(!e.force&&this.cache?.key===o)return this.cache.snapshot;let c=`/nvwa/integration-snapshot?${new URLSearchParams({applicationCode:r,platformCode:i,locale:a}).toString()}`,l=yt(this.baseUrl,c),u=await this.fetchImpl(l,{credentials:"include",headers:{Accept:"application/json"}});if(!u.ok){let g=await u.text();throw new Error(`integration-snapshot: ${u.status} ${g||u.statusText}`)}let d=await u.json();return this.cache={key:o,snapshot:d},d}};0&&(module.exports={AuthClient,CURRENT_JWT_KEY,ENTITIES_BASE_PATH,FILE_STORAGE_BASE_PATH,GENERATE_UPLOAD_URL_PATH,Headers,LOGIN_TOKEN_KEY,LOGIN_USER_PROFILE_KEY,NvwaEdgeFunctions,NvwaFileStorage,NvwaHttpClient,NvwaIntegrationSnapshot,OverlayManager,Request,Response,SET_AUTH_TOKEN_HEADER,URL,createPostgrestClient,getSourceLocationFromDOM,normalizePayParams,requestPaymentFromOrderResult});
36
+ `,document.head.appendChild(t)}createTooltip(){return this.tooltip?this.tooltip:(this.tooltip=document.createElement("div"),this.tooltip.id="__nvwa-inspector-tooltip",document.body.appendChild(this.tooltip),this.tooltip)}createOverlay(t){let e=document.createElement("div");return e.className=`__nvwa-inspector-overlay __nvwa-inspector-overlay-${t}`,document.body.appendChild(e),e}updateOverlayPosition(t,e){if(!e.isConnected)return;let r=e.getBoundingClientRect(),i=window.scrollX||window.pageXOffset,n=window.scrollY||window.pageYOffset;r.width>0&&r.height>0?(t.style.left=`${r.left+i}px`,t.style.top=`${r.top+n}px`,t.style.width=`${r.width}px`,t.style.height=`${r.height}px`,t.style.display="block"):t.style.display="none"}removeOverlay(t){t&&t.parentNode&&t.parentNode.removeChild(t)}highlightElement(t,e){if(!t.isConnected)return;if(this.hoverElement===t&&this.hoverOverlay){this.updateOverlayPosition(this.hoverOverlay,t);let o=this.createTooltip();e?o.textContent=e:o.textContent=`<${t.tagName.toLowerCase()}> (\u65E0 source location)`,o.style.display="block";let h=t.getBoundingClientRect();o.style.left=`${h.left+window.scrollX}px`,o.style.top=`${h.top+window.scrollY-o.offsetHeight-8}px`,h.top<o.offsetHeight+8&&(o.style.top=`${h.bottom+window.scrollY+8}px`);return}this.hoverOverlay&&(this.removeOverlay(this.hoverOverlay),this.hoverOverlay=null);let r=this.createOverlay("hover");this.updateOverlayPosition(r,t),this.hoverOverlay=r,this.hoverElement=t;let i=()=>{this.hoverOverlay&&this.hoverElement&&this.hoverElement.isConnected&&this.updateOverlayPosition(this.hoverOverlay,this.hoverElement)};this.hoverUpdateHandler&&(window.removeEventListener("scroll",this.hoverUpdateHandler,!0),window.removeEventListener("resize",this.hoverUpdateHandler)),this.hoverUpdateHandler=i,window.addEventListener("scroll",i,!0),window.addEventListener("resize",i);let n=this.createTooltip();e?n.textContent=e:n.textContent=`<${t.tagName.toLowerCase()}> (\u65E0 source location)`,n.style.display="block";let a=t.getBoundingClientRect();n.style.left=`${a.left+window.scrollX}px`,n.style.top=`${a.top+window.scrollY-n.offsetHeight-8}px`,a.top<n.offsetHeight+8&&(n.style.top=`${a.bottom+window.scrollY+8}px`)}selectElement(t,e){if(!t.isConnected)return;if(this.selectedElement===t&&this.selectedOverlay){this.updateOverlayPosition(this.selectedOverlay,t);return}this.selectedOverlay&&(this.removeOverlay(this.selectedOverlay),this.selectedOverlay=null);let r=this.createOverlay("selected");this.updateOverlayPosition(r,t),this.selectedOverlay=r,this.selectedElement=t;let i=()=>{this.selectedOverlay&&this.selectedElement&&this.selectedElement.isConnected&&this.updateOverlayPosition(this.selectedOverlay,this.selectedElement)};this.selectedUpdateHandler&&(window.removeEventListener("scroll",this.selectedUpdateHandler,!0),window.removeEventListener("resize",this.selectedUpdateHandler)),this.selectedUpdateHandler=i,window.addEventListener("scroll",i,!0),window.addEventListener("resize",i)}removeHighlight(){this.hoverOverlay&&(this.removeOverlay(this.hoverOverlay),this.hoverOverlay=null),this.hoverElement&&(this.hoverElement=null),this.tooltip&&(this.tooltip.style.display="none"),this.hoverUpdateHandler&&(window.removeEventListener("scroll",this.hoverUpdateHandler,!0),window.removeEventListener("resize",this.hoverUpdateHandler),this.hoverUpdateHandler=null)}clearSelection(){this.selectedOverlay&&(this.removeOverlay(this.selectedOverlay),this.selectedOverlay=null),this.selectedElement&&(this.selectedElement=null),this.selectedUpdateHandler&&(window.removeEventListener("scroll",this.selectedUpdateHandler,!0),window.removeEventListener("resize",this.selectedUpdateHandler),this.selectedUpdateHandler=null)}cleanup(){this.removeHighlight(),this.clearSelection(),this.tooltip&&this.tooltip.parentNode&&(this.tooltip.parentNode.removeChild(this.tooltip),this.tooltip=null);let t=document.getElementById("__nvwa-inspector-overlay-style");t&&t.parentNode&&t.parentNode.removeChild(t)}};function vt(s="root"){if(typeof document>"u")return null;let t=document.getElementById(s)||document.body;if(!t)return null;let e=t.querySelector("[data-source-location]");if(e){let r=e.getAttribute("data-source-location");if(r)return r}if(t.firstElementChild){let i=t.firstElementChild.getAttribute("data-source-location");if(i)return i}return null}var wt={"wechat-pay":{id:"wechat-pay",name:"WeChat Pay",description:"WeChat payment for web and miniapp."},wechat_partner:{id:"wechat_partner",name:"WeChat Partner",description:"WeChat partner merchant onboarding."},alipay:{id:"alipay",name:"Alipay",description:"Alipay payment."},"alipay-miniprogram":{id:"alipay-miniprogram",name:"Alipay Mini Program",description:"Alipay mini program payment."},stripe:{id:"stripe",name:"Stripe",description:"Stripe payment."}};function Pt(s){let t=s;if(typeof t.kind=="string")return t;if(typeof t.tradeNO=="string")return{kind:"alipay_miniprogram",tradeNO:t.tradeNO};if(typeof t.clientSecret=="string")return{kind:"stripe_client_secret",clientSecret:t.clientSecret};if(typeof t.redirectUrl=="string")return{kind:"redirect_url",redirectUrl:t.redirectUrl};if(typeof t.formHtml=="string")return{kind:"alipay_page",formHtml:t.formHtml};if(typeof t.codeUrl=="string")return{kind:"wechat_native_qr",codeUrl:t.codeUrl};let e=t.jsapiPayParams??t;return typeof e.timeStamp=="string"&&typeof e.nonceStr=="string"&&typeof e.package=="string"&&typeof e.paySign=="string"&&typeof e.appId=="string"?{kind:"wechat_jsapi",mode:"jsapi",jsapiPayParams:{appId:e.appId,timeStamp:e.timeStamp,nonceStr:e.nonceStr,package:e.package,signType:e.signType??"RSA",paySign:e.paySign}}:null}function bt(s,t,e){return t.requestPayment(s.payParams,e)}async function Ot(s,t){let e=s.payment?.providers??{};return Object.entries(e).filter(([,r])=>r.enabled).map(([r])=>wt[r]??{id:r,name:r,description:""})}function C(s){return s&&typeof s=="object"?s:{}}function St(s){let t=C(s),e=t.enabled===!0,r=String(t.oauthCredentialSource??"").toLowerCase();return r?{enabled:e,oauthCredentialSource:r==="custom"?"custom":"nvwa_default"}:{enabled:e}}function Q(s){let t=C(s),e=C(t.providers),r={};for(let[i,n]of Object.entries(e))r[i]=St(n);return{providers:r}}function x(s){let t=C(s);return{socialLogin:Q(t.socialLogin),payment:Q(t.payment)}}function Lt(s){if(!s?.trim())return x({});try{return x(JSON.parse(s))}catch{return x({})}}function Rt(s,t){let e=s[t];return e?Object.entries(e.providers).filter(([,r])=>r.enabled).map(([r])=>r):[]}0&&(module.exports={AuthClient,CURRENT_JWT_KEY,ENTITIES_BASE_PATH,FILE_STORAGE_BASE_PATH,GENERATE_UPLOAD_URL_PATH,Headers,LOGIN_TOKEN_KEY,LOGIN_USER_PROFILE_KEY,NvwaEdgeFunctions,NvwaFileStorage,NvwaHttpClient,OverlayManager,Request,Response,SET_AUTH_TOKEN_HEADER,URL,createPostgrestClient,getEnabledProvidersByIntegration,getPaymentProvidersFromIntegrationProviders,getSourceLocationFromDOM,normalizeIntegrationProvidersConfig,normalizePayParams,parseIntegrationProvidersJson,requestPaymentFromOrderResult});
package/dist/index.mjs CHANGED
@@ -1,7 +1,7 @@
1
- var f=class k{constructor(t){if(this.headerMap=new Map,t){if(t instanceof k)t.forEach((e,r)=>this.set(r,e));else if(Array.isArray(t))for(let[e,r]of t)this.set(e,String(r));else if(typeof t=="object")for(let e of Object.keys(t))this.set(e,String(t[e]))}}append(t,e){let r=t.toLowerCase(),i=this.headerMap.get(r);this.headerMap.set(r,i?`${i}, ${e}`:e)}set(t,e){this.headerMap.set(t.toLowerCase(),String(e))}get(t){return this.headerMap.get(t.toLowerCase())??null}has(t){return this.headerMap.has(t.toLowerCase())}delete(t){this.headerMap.delete(t.toLowerCase())}forEach(t){for(let[e,r]of this.headerMap.entries())t(r,e,this)}entries(){return this.headerMap.entries()}keys(){return this.headerMap.keys()}values(){return this.headerMap.values()}[Symbol.iterator](){return this.entries()}},D=class I{constructor(t){if(this.params=new Map,t){if(typeof t=="string")this.parseString(t);else if(t instanceof I)this.params=new Map(t.params);else if(Array.isArray(t))for(let[e,r]of t)this.append(e,r);else if(t&&typeof t=="object")for(let[e,r]of Object.entries(t))this.set(e,r)}}parseString(t){t.startsWith("?")&&(t=t.slice(1));let e=t.split("&");for(let r of e)if(r){let[i,n]=r.split("=");i&&this.append(decodeURIComponent(i),n?decodeURIComponent(n):"")}}append(t,e){let r=this.params.get(t)||[];r.push(e),this.params.set(t,r)}delete(t){this.params.delete(t)}get(t){let e=this.params.get(t);return e?e[0]:null}getAll(t){return this.params.get(t)||[]}has(t){return this.params.has(t)}set(t,e){this.params.set(t,[e])}sort(){let t=Array.from(this.params.entries()).sort(([e],[r])=>e.localeCompare(r));this.params=new Map(t)}toString(){let t=[];for(let[e,r]of this.params.entries())for(let i of r)t.push(`${encodeURIComponent(e)}=${encodeURIComponent(i)}`);return t.join("&")}forEach(t){for(let[e,r]of this.params.entries())for(let i of r)t(i,e,this)}keys(){return this.params.keys()}values(){let t=[];for(let e of this.params.values())t.push(...e);return t[Symbol.iterator]()}entries(){let t=[];for(let[e,r]of this.params.entries())for(let i of r)t.push([e,i]);return t[Symbol.iterator]()}[Symbol.iterator](){return this.entries()}get size(){return this.params.size}},S=class R{constructor(t,e){let r;if(t instanceof R)r=t.href;else if(e){let n=e instanceof R?e.href:e;r=this.resolve(n,t)}else r=t;let i=this.parseUrl(r);this.href=r,this.origin=`${i.protocol}//${i.host}`,this.protocol=i.protocol,this.username=i.username,this.password=i.password,this.host=i.host,this.hostname=i.hostname,this.port=i.port,this.pathname=i.pathname,this.search=i.search,this.searchParams=new D(i.search),this.hash=i.hash}resolve(t,e){if(e.startsWith("http://")||e.startsWith("https://"))return e;if(e.startsWith("//"))return`${this.parseUrl(t).protocol}${e}`;if(e.startsWith("/")){let n=this.parseUrl(t);return`${n.protocol}//${n.host}${e}`}let r=this.parseUrl(t),i=r.pathname.endsWith("/")?r.pathname:r.pathname+"/";return`${r.protocol}//${r.host}${i}${e}`}parseUrl(t){let e=t.match(/^(([^:\/?#]+):)?(\/\/([^\/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?$/);if(!e)throw new TypeError("Invalid URL");let r=e[2]||"",i=e[4]||"",n=e[5]||"/",a=e[7]?`?${e[7]}`:"",o=e[9]?`#${e[9]}`:"";if(!r&&!i&&!n.startsWith("/")&&!n.includes("/")&&!n.includes("."))throw new TypeError("Invalid URL");let h=i.match(/^([^@]*)@(.+)$/),c="",l="",u=i;if(h){let b=h[1];u=h[2];let y=b.match(/^([^:]*):?(.*)$/);y&&(c=y[1]||"",l=y[2]||"")}let p=u.match(/^([^:]+):?(\d*)$/),g=p?p[1]:u,m=p&&p[2]?p[2]:"";return{protocol:r?`${r}:`:"",username:c,password:l,host:u,hostname:g,port:m,pathname:n,search:a,hash:o}}toString(){let t=this.searchParams.toString(),e=t?`?${t}`:"";return`${this.protocol}//${this.host}${this.pathname}${e}${this.hash}`}toJSON(){return this.toString()}},A=class ${constructor(t,e){if(typeof t=="string")this.url=t;else if(t?.url)this.url=String(t.url);else if(typeof t?.toString=="function")this.url=String(t.toString());else throw new Error("Invalid input for Request");this.method=(e?.method||"GET").toUpperCase(),this.headers=e?.headers instanceof f?e.headers:new f(e?.headers),this.body=e?.body,this.timeout=e?.timeout,this.signal=e?.signal||void 0}clone(){return new $(this.url,{method:this.method,headers:this.headers,body:this.body,timeout:this.timeout})}toString(){return this.url}},U=class{constructor(s,t){this.bodyData=s,this.status=t?.status??200,this.statusText=t?.statusText??"",this.headers=Y(t?.headers),this.ok=this.status>=200&&this.status<300}async text(){return typeof this.bodyData=="string"?this.bodyData:this.bodyData==null?"":typeof this.bodyData=="object"?JSON.stringify(this.bodyData):String(this.bodyData)}async json(){if(typeof this.bodyData=="string")try{return JSON.parse(this.bodyData)}catch{}return this.bodyData}async arrayBuffer(){let s=await this.text();return new TextEncoder().encode(s).buffer}};function Y(s){return s?new f(s):new f}var K=class{constructor(){this._aborted=!1,this.listeners=new Set,this.onabort=null}get aborted(){return this._aborted}_trigger(){if(!this._aborted){if(this._aborted=!0,typeof this.onabort=="function")try{this.onabort()}catch{}for(let s of Array.from(this.listeners))try{s()}catch{}this.listeners.clear()}}addEventListener(s,t){if(this._aborted){try{t()}catch{}return}this.listeners.add(t)}removeEventListener(s,t){this.listeners.delete(t)}toString(){return"[object AbortSignal]"}},N=class{constructor(){this._signal=new K}get signal(){return this._signal}abort(){this._signal._trigger()}toString(){return"[object AbortController]"}};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.fetch(r,{method:e.method||"POST",body:e.body,headers:e.headers})).json()}};var d="nvwa_current_jwt",w="nvwa_login_token",O="nvwa_user_profile",H="set-auth-token",V=typeof fetch<"u"?(s,t)=>fetch(s,t):()=>{throw new Error("AuthClient requires fetch")},T=class{constructor(t,e={}){this.baseUrl=t.replace(/\/$/,""),this.authPath=(e.authPath??"/auth").replace(/^\//,""),this.fetchImpl=e.fetchImpl??V,this.storage=e.storage??null,this.credentials=e.credentials??"omit",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 currentUser(){if(this.storage){let r=await this.storage.get(O);if(r!=null)return r}let{data:t}=await this.getSession(),e=t?.user??null;return e&&this.storage&&await this.storage.set(O,e),e}async getCurrentJwt(){if(this.storage){let e=await this.storage.get(d);if(e!=null)return e;let r=await this.storage.get(w),{data:i}=await this.getToken(r??void 0);return i?.token?(await this.storage.set(d,i.token),i.token):null}let{data:t}=await this.getToken();return t?.token??null}async persistLogin(t,e){if(!this.storage)return;let i=e?.headers.get(H)?.trim()||t.token||t.session?.token;i&&await this.storage.set(w,i),t.user&&await this.storage.set(O,t.user);let n=i??await this.storage.get(w),{data:a}=await this.getToken(n??void 0);a?.token&&await this.storage.set(d,a.token)}async clearLogin(){this.storage&&(await this.storage.remove(w),await this.storage.remove(O),await this.storage.remove(d))}getGoogleOpenPlatformLoginUrl(t,e){let r=new URLSearchParams({return_url:t});return e?.applicationCode?.trim()&&r.set("application_code",e.applicationCode.trim()),e?.platformCode?.trim()&&r.set("platform_code",e.platformCode.trim()),`${this.url("google/openplatform/login")}?${r.toString()}`}startGoogleOpenPlatformLogin(t,e){let r=this.getGoogleOpenPlatformLoginUrl(t,e);if(typeof globalThis<"u"&&"location"in globalThis){globalThis.location.href=r;return}throw new Error("startGoogleOpenPlatformLogin requires a browser environment with location")}async completeGoogleOpenPlatformLoginFromCurrentUrl(t){let e;if(t!=null&&t!=="")e=t;else if(typeof globalThis<"u"&&"location"in globalThis)e=globalThis.location.href;else return{error:{message:"completeGoogleOpenPlatformLoginFromCurrentUrl requires url or browser location",status:0}};let r;try{r=new URL(e).searchParams.get("exchange_code")}catch{return{error:{message:"invalid_callback_url",status:400}}}return r?.trim()?await this.loginWithGoogleExchangeCode(r.trim()):{error:{message:"missing_exchange_code",status:400}}}async loginWithGoogleExchangeCode(t){try{let e={"Content-Type":"application/json"};if(this.storage){let a=await this.storage.get(d);a!=null&&(e.Authorization=`Bearer ${a}`)}let r=await this.fetchImpl(this.url("google/openplatform/sign-in"),{method:"POST",headers:e,credentials:this.credentials,body:JSON.stringify({exchangeCode:t})}),i=await r.text();if(!r.ok)return{error:{message:i||r.statusText,status:r.status}};let n=i?JSON.parse(i):null;return!n?.token||!n.user?{error:{message:"invalid_google_login_response",status:502}}:(this.storage&&(await this.storage.set(d,n.token),await this.storage.set(w,n.token),await this.storage.set(O,n.user)),{data:n})}catch(e){return{error:{message:e instanceof Error?e.message:String(e),status:0}}}}async getGoogleOpenPlatformIdentity(){try{let t={};if(this.storage){let n=await this.storage.get(d);n!=null&&(t.Authorization=`Bearer ${n}`)}let e=await this.fetchImpl(this.url("google/openplatform/identity"),{method:"GET",credentials:this.credentials,...Object.keys(t).length?{headers:t}:{}}),r=await e.text();if(!e.ok)return{error:{message:r||e.statusText,status:e.status}};let i=r?JSON.parse(r):null;return i?.sub?{data:i}:{error:{message:"invalid_google_identity_response",status:502}}}catch(t){return{error:{message:t instanceof Error?t.message:String(t),status:0}}}}getGithubOpenPlatformLoginUrl(t,e){let r=new URLSearchParams({return_url:t});return e?.applicationCode?.trim()&&r.set("application_code",e.applicationCode.trim()),e?.platformCode?.trim()&&r.set("platform_code",e.platformCode.trim()),`${this.url("github/openplatform/login")}?${r.toString()}`}startGithubOpenPlatformLogin(t,e){let r=this.getGithubOpenPlatformLoginUrl(t,e);if(typeof globalThis<"u"&&"location"in globalThis){globalThis.location.href=r;return}throw new Error("startGithubOpenPlatformLogin requires a browser environment with location")}async completeGithubOpenPlatformLoginFromCurrentUrl(t){let e;if(t!=null&&t!=="")e=t;else if(typeof globalThis<"u"&&"location"in globalThis)e=globalThis.location.href;else return{error:{message:"completeGithubOpenPlatformLoginFromCurrentUrl requires url or browser location",status:0}};let r;try{r=new URL(e).searchParams.get("exchange_code")}catch{return{error:{message:"invalid_callback_url",status:400}}}return r?.trim()?await this.loginWithGithubExchangeCode(r.trim()):{error:{message:"missing_exchange_code",status:400}}}async loginWithGithubExchangeCode(t){try{let e={"Content-Type":"application/json"};if(this.storage){let a=await this.storage.get(d);a!=null&&(e.Authorization=`Bearer ${a}`)}let r=await this.fetchImpl(this.url("github/openplatform/sign-in"),{method:"POST",headers:e,credentials:this.credentials,body:JSON.stringify({exchangeCode:t})}),i=await r.text();if(!r.ok)return{error:{message:i||r.statusText,status:r.status}};let n=i?JSON.parse(i):null;return!n?.token||!n.user?{error:{message:"invalid_github_login_response",status:502}}:(this.storage&&(await this.storage.set(d,n.token),await this.storage.set(w,n.token),await this.storage.set(O,n.user)),{data:n})}catch(e){return{error:{message:e instanceof Error?e.message:String(e),status:0}}}}async getGithubOpenPlatformIdentity(){try{let t={};if(this.storage){let n=await this.storage.get(d);n!=null&&(t.Authorization=`Bearer ${n}`)}let e=await this.fetchImpl(this.url("github/openplatform/identity"),{method:"GET",credentials:this.credentials,...Object.keys(t).length?{headers:t}:{}}),r=await e.text();if(!e.ok)return{error:{message:r||e.statusText,status:e.status}};let i=r?JSON.parse(r):null;return i?.sub?{data:i}:{error:{message:"invalid_github_identity_response",status:502}}}catch(t){return{error:{message:t instanceof Error?t.message:String(t),status:0}}}}getWechatWebsiteOpenPlatformLoginUrl(t){let e=new URLSearchParams({return_url:t});return`${this.url("wechat-website/openplatform/login")}?${e.toString()}`}startWechatWebsiteOpenPlatformLogin(t){let e=this.getWechatWebsiteOpenPlatformLoginUrl(t);if(typeof globalThis<"u"&&"location"in globalThis){globalThis.location.href=e;return}throw new Error("startWechatWebsiteOpenPlatformLogin requires a browser environment with location")}async completeWechatWebsiteOpenPlatformLoginFromCurrentUrl(t){let e;if(t!=null&&t!=="")e=t;else if(typeof globalThis<"u"&&"location"in globalThis)e=globalThis.location.href;else return{error:{message:"completeWechatWebsiteOpenPlatformLoginFromCurrentUrl requires url or browser location",status:0}};let r;try{r=new URL(e).searchParams.get("exchange_code")}catch{return{error:{message:"invalid_callback_url",status:400}}}return r?.trim()?await this.loginWithWechatWebsiteExchangeCode(r.trim()):{error:{message:"missing_exchange_code",status:400}}}async loginWithWechatWebsiteExchangeCode(t){try{let e={"Content-Type":"application/json"};if(this.storage){let a=await this.storage.get(d);a!=null&&(e.Authorization=`Bearer ${a}`)}let r=await this.fetchImpl(this.url("wechat-website/openplatform/sign-in"),{method:"POST",headers:e,credentials:this.credentials,body:JSON.stringify({exchangeCode:t})}),i=await r.text();if(!r.ok)return{error:{message:i||r.statusText,status:r.status}};let n=i?JSON.parse(i):null;return!n?.token||!n.user?{error:{message:"invalid_wechat_website_login_response",status:502}}:(this.storage&&(await this.storage.set(d,n.token),await this.storage.set(w,n.token),await this.storage.set(O,n.user)),{data:n})}catch(e){return{error:{message:e instanceof Error?e.message:String(e),status:0}}}}async getWechatWebsiteOpenPlatformIdentity(){try{let t={};if(this.storage){let n=await this.storage.get(d);n!=null&&(t.Authorization=`Bearer ${n}`)}let e=await this.fetchImpl(this.url("wechat-website/openplatform/identity"),{method:"GET",credentials:this.credentials,...Object.keys(t).length?{headers:t}:{}}),r=await e.text();if(!e.ok)return{error:{message:r||e.statusText,status:e.status}};let i=r?JSON.parse(r):null;return i?.sub?{data:i}:{error:{message:"invalid_wechat_website_identity_response",status:502}}}catch(t){return{error:{message:t instanceof Error?t.message:String(t),status:0}}}}url(t){let r=`${`${this.baseUrl.replace(/\/+$/,"")}/${this.authPath.replace(/^\/+/,"")}`}/${t.replace(/^\/+/,"")}`;return typeof console<"u"&&(console.warn("[NvwaAuth] request URL:",r),!r.startsWith("http://")&&!r.startsWith("https://")&&console.warn("[NvwaAuth] URL \u975E\u5B8C\u6574\u5730\u5740\uFF0C\u5C0F\u7A0B\u5E8F\u4F1A\u62A5 invalid url\uFF0C\u8BF7\u68C0\u67E5 Nvwa \u6784\u9020\u65F6\u4F20\u5165\u7684 baseUrl")),r}async getSession(){try{let t={};if(this.storage){let i=await this.storage.get(w)??await this.storage.get(d);i!=null&&(t.Authorization=`Bearer ${i}`)}let e=await this.fetchImpl(this.url("session"),{method:"GET",credentials:this.credentials,...Object.keys(t).length?{headers:t}:{}});return e.ok?{data:await e.json()}:{data:null,error:{message:await e.text()||e.statusText,status:e.status}}}catch(t){return{data:null,error:{message:t instanceof Error?t.message:String(t),status:0}}}}async signInWithEmail(t,e){try{let r=await this.fetchImpl(this.url("sign-in/email"),{method:"POST",headers:{"Content-Type":"application/json"},credentials:this.credentials,body:JSON.stringify({email:t,password:e})}),i=await r.text();if(!r.ok)return{error:{message:i||r.statusText,status:r.status}};let n=i?JSON.parse(i):void 0;return n&&await this.persistLogin({user:n.user,session:n.session},r),{data:n}}catch(r){return{error:{message:r instanceof Error?r.message:String(r),status:0}}}}async signOut(){try{let t={};if(this.storage){let r=await this.storage.get(w)??await this.storage.get(d);r!=null&&(t.Authorization=`Bearer ${r}`)}let e=await this.fetchImpl(this.url("sign-out"),{method:"POST",credentials:this.credentials,...Object.keys(t).length?{headers:t}:{}});return await this.clearLogin(),e.ok?{}:{error:{message:await e.text()||e.statusText,status:e.status}}}catch(t){return{error:{message:t instanceof Error?t.message:String(t),status:0}}}}async signUp(t){let e=await this.postJson("sign-up/email",t);return e.data&&await this.persistLogin(e.data,e.response),e}async getToken(t){try{let e={};if(t)e.Authorization=`Bearer ${t}`;else if(this.storage){let a=await this.storage.get(w)??await this.storage.get(d);a!=null&&(e.Authorization=`Bearer ${a}`)}let r=await this.fetchImpl(this.url("token"),{method:"GET",credentials:this.credentials,...Object.keys(e).length?{headers:e}:{}}),i=await r.text();if(!r.ok)return{error:{message:i||r.statusText,status:r.status}};let n=i?JSON.parse(i):void 0;return{data:n?.token!=null?{token:n.token}:void 0}}catch(e){return{error:{message:e instanceof Error?e.message:String(e),status:0}}}}async signInWithUsername(t,e){let r=await this.postJson("sign-in/username",{username:t,password:e});return r.data&&await this.persistLogin(r.data,r.response),r}async signInWithPhoneNumber(t,e,r){let i=await this.postJson("sign-in/phone-number",{phoneNumber:t,password:e,rememberMe:r});return i.data&&await this.persistLogin(i.data,i.response),i}async sendPhoneNumberOtp(t){let e=await this.postJson("phone-number/send-otp",{phoneNumber:t});return e.error?{error:e.error}:{}}async verifyPhoneNumber(t,e){let r=await this.postJson("phone-number/verify",{phoneNumber:t,code:e});return r.data&&await this.persistLogin(r.data,r.response),r}async loginWithWeChatCode(t,e){try{let r={"Content-Type":"application/json"};if(this.storage){let o=await this.storage.get(d);o!=null&&(r.Authorization=`Bearer ${o}`)}let i=await this.fetchImpl(this.url("wechat/openplatform/sign-in"),{method:"POST",headers:r,credentials:this.credentials,body:JSON.stringify({code:t,applicationCode:e})}),n=await i.text();if(!i.ok)return{error:{message:n||i.statusText,status:i.status}};let a=n?JSON.parse(n):null;return!a?.token||!a.user?{error:{message:"invalid_wechat_login_response",status:502}}:(this.storage&&(await this.storage.set(d,a.token),await this.storage.set(w,a.token),await this.storage.set(O,a.user)),{data:a})}catch(r){return{error:{message:r instanceof Error?r.message:String(r),status:0}}}}async loginWithAlipayCode(t,e){try{let r={"Content-Type":"application/json"};if(this.storage){let o=await this.storage.get(d);o!=null&&(r.Authorization=`Bearer ${o}`)}let i=await this.fetchImpl(this.url("alipay/openplatform/sign-in"),{method:"POST",headers:r,credentials:this.credentials,body:JSON.stringify({code:t,applicationCode:e})}),n=await i.text();if(!i.ok)return{error:{message:n||i.statusText,status:i.status}};let a=n?JSON.parse(n):null;return!a?.token||!a.user?{error:{message:"invalid_alipay_login_response",status:502}}:(this.storage&&(await this.storage.set(d,a.token),await this.storage.set(w,a.token),await this.storage.set(O,a.user)),{data:a})}catch(r){return{error:{message:r instanceof Error?r.message:String(r),status:0}}}}async getWeChatOpenPlatformIdentity(t){try{let e={};if(this.storage){let o=await this.storage.get(d);o!=null&&(e.Authorization=`Bearer ${o}`)}let r=t?.trim()?`?applicationCode=${encodeURIComponent(t.trim())}`:"",i=await this.fetchImpl(this.url(`wechat/openplatform/identity${r}`),{method:"GET",credentials:this.credentials,...Object.keys(e).length?{headers:e}:{}}),n=await i.text();if(!i.ok)return{error:{message:n||i.statusText,status:i.status}};let a=n?JSON.parse(n):null;return!a?.openid||!a.appId?{error:{message:"invalid_wechat_identity_response",status:502}}:{data:a}}catch(e){return{error:{message:e instanceof Error?e.message:String(e),status:0}}}}async getAlipayOpenPlatformIdentity(t){try{let e={};if(this.storage){let o=await this.storage.get(d);o!=null&&(e.Authorization=`Bearer ${o}`)}let r=t?.trim()?`?applicationCode=${encodeURIComponent(t.trim())}`:"",i=await this.fetchImpl(this.url(`alipay/openplatform/identity${r}`),{method:"GET",credentials:this.credentials,...Object.keys(e).length?{headers:e}:{}}),n=await i.text();if(!i.ok)return{error:{message:n||i.statusText,status:i.status}};let a=n?JSON.parse(n):null;return!a?.openid||!a.appId?{error:{message:"invalid_alipay_identity_response",status:502}}:{data:a}}catch(e){return{error:{message:e instanceof Error?e.message:String(e),status:0}}}}async postJson(t,e){try{let r=await this.fetchImpl(this.url(t),{method:"POST",headers:{"Content-Type":"application/json"},credentials:this.credentials,body:JSON.stringify(e)}),i=await r.text();if(!r.ok)return{error:{message:i||r.statusText,status:r.status}};let n=i?JSON.parse(i):void 0;return{data:n?.data??n??void 0,response:r}}catch(r){return{error:{message:r instanceof Error?r.message:String(r),status:0}}}}};var W=class{constructor(t,e,r){this.storage=t,this.customFetch=e,this.handleUnauthorized=r}async fetch(t,e){return await this.customFetch(t,e)}async fetchWithAuth(t,e){let r=await this.storage.get(d),i=new f(e?.headers);r&&i.set("Authorization",`Bearer ${r}`);let n=e?.method||"GET";if((n==="POST"||n==="PUT"||n==="PATCH")&&e?.body){let o=i.get("Content-Type");(!o||o.includes("text/plain"))&&i.set("Content-Type","application/json")}let a=await this.customFetch(t,{...e,headers:i});if(a.status===401)throw this.handleUnauthorized(),new Error("\u672A\u767B\u5F55");return a}};var X="/storage",Q=X+"/generateUploadUrl",G=class{constructor(t,e){this.baseUrl=t,this.http=e}async uploadFile(t){let e=await this.http.fetch(this.baseUrl+Q,{method:"POST",body:{fileName:t.name||t.fileName,fileSize:t.size||t.fileSize,fileType:t.type||t.fileType}}),{url:r}=await e.json();if(!r)throw new Error("\u83B7\u53D6\u4E0A\u4F20URL\u5931\u8D25");let i=await this.http.fetch(r,{method:"PUT",body:t,headers:new f({"Content-Type":t.type||t.fileType||"application/octet-stream"})}),{url:n}=await i.json();return{url:n.split("?")[0]}}};var Z=class extends Error{constructor(s){super(s.message),this.name="PostgrestError",this.details=s.details,this.hint=s.hint,this.code=s.code}},tt=class{constructor(s){var t,e,r;this.shouldThrowOnError=!1,this.method=s.method,this.url=s.url,this.headers=new f(s.headers),this.schema=s.schema,this.body=s.body,this.shouldThrowOnError=(t=s.shouldThrowOnError)!==null&&t!==void 0?t:!1,this.signal=s.signal,this.isMaybeSingle=(e=s.isMaybeSingle)!==null&&e!==void 0?e:!1,this.urlLengthLimit=(r=s.urlLengthLimit)!==null&&r!==void 0?r:8e3,s.fetch?this.fetch=s.fetch:this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(s,t){return this.headers=new f(this.headers),this.headers.set(s,t),this}then(s,t){var e=this;this.schema===void 0||(["GET","HEAD"].includes(this.method)?this.headers.set("Accept-Profile",this.schema):this.headers.set("Content-Profile",this.schema)),this.method!=="GET"&&this.method!=="HEAD"&&this.headers.set("Content-Type","application/json");let r=this.fetch,i=r(this.url.toString(),{method:this.method,headers:this.headers,body:JSON.stringify(this.body),signal:this.signal}).then(async n=>{let a=null,o=null,h=null,c=n.status,l=n.statusText;if(n.ok){var u,p;if(e.method!=="HEAD"){var g;let y=await n.text();y===""||(e.headers.get("Accept")==="text/csv"||e.headers.get("Accept")&&(!((g=e.headers.get("Accept"))===null||g===void 0)&&g.includes("application/vnd.pgrst.plan+text"))?o=y:o=JSON.parse(y))}let m=(u=e.headers.get("Prefer"))===null||u===void 0?void 0:u.match(/count=(exact|planned|estimated)/),b=(p=n.headers.get("content-range"))===null||p===void 0?void 0:p.split("/");m&&b&&b.length>1&&(h=parseInt(b[1])),e.isMaybeSingle&&Array.isArray(o)&&(o.length>1?(a={code:"PGRST116",details:`Results contain ${o.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},o=null,h=null,c=406,l="Not Acceptable"):o.length===1?o=o[0]:o=null)}else{let m=await n.text();try{a=JSON.parse(m),Array.isArray(a)&&n.status===404&&(o=[],a=null,c=200,l="OK")}catch{n.status===404&&m===""?(c=204,l="No Content"):a={message:m}}if(a&&e.shouldThrowOnError)throw new Z(a)}return{error:a,data:o,count:h,status:c,statusText:l}});return this.shouldThrowOnError||(i=i.catch(n=>{var a;let o="",h="",c="",l=n?.cause;if(l){var u,p,g,m;let z=(u=l?.message)!==null&&u!==void 0?u:"",_=(p=l?.code)!==null&&p!==void 0?p:"";o=`${(g=n?.name)!==null&&g!==void 0?g:"FetchError"}: ${n?.message}`,o+=`
1
+ var f=class A{constructor(t){if(this.headerMap=new Map,t){if(t instanceof A)t.forEach((e,r)=>this.set(r,e));else if(Array.isArray(t))for(let[e,r]of t)this.set(e,String(r));else if(typeof t=="object")for(let e of Object.keys(t))this.set(e,String(t[e]))}}append(t,e){let r=t.toLowerCase(),i=this.headerMap.get(r);this.headerMap.set(r,i?`${i}, ${e}`:e)}set(t,e){this.headerMap.set(t.toLowerCase(),String(e))}get(t){return this.headerMap.get(t.toLowerCase())??null}has(t){return this.headerMap.has(t.toLowerCase())}delete(t){this.headerMap.delete(t.toLowerCase())}forEach(t){for(let[e,r]of this.headerMap.entries())t(r,e,this)}entries(){return this.headerMap.entries()}keys(){return this.headerMap.keys()}values(){return this.headerMap.values()}[Symbol.iterator](){return this.entries()}},V=class I{constructor(t){if(this.params=new Map,t){if(typeof t=="string")this.parseString(t);else if(t instanceof I)this.params=new Map(t.params);else if(Array.isArray(t))for(let[e,r]of t)this.append(e,r);else if(t&&typeof t=="object")for(let[e,r]of Object.entries(t))this.set(e,r)}}parseString(t){t.startsWith("?")&&(t=t.slice(1));let e=t.split("&");for(let r of e)if(r){let[i,n]=r.split("=");i&&this.append(decodeURIComponent(i),n?decodeURIComponent(n):"")}}append(t,e){let r=this.params.get(t)||[];r.push(e),this.params.set(t,r)}delete(t){this.params.delete(t)}get(t){let e=this.params.get(t);return e?e[0]:null}getAll(t){return this.params.get(t)||[]}has(t){return this.params.has(t)}set(t,e){this.params.set(t,[e])}sort(){let t=Array.from(this.params.entries()).sort(([e],[r])=>e.localeCompare(r));this.params=new Map(t)}toString(){let t=[];for(let[e,r]of this.params.entries())for(let i of r)t.push(`${encodeURIComponent(e)}=${encodeURIComponent(i)}`);return t.join("&")}forEach(t){for(let[e,r]of this.params.entries())for(let i of r)t(i,e,this)}keys(){return this.params.keys()}values(){let t=[];for(let e of this.params.values())t.push(...e);return t[Symbol.iterator]()}entries(){let t=[];for(let[e,r]of this.params.entries())for(let i of r)t.push([e,i]);return t[Symbol.iterator]()}[Symbol.iterator](){return this.entries()}get size(){return this.params.size}},S=class C{constructor(t,e){let r;if(t instanceof C)r=t.href;else if(e){let n=e instanceof C?e.href:e;r=this.resolve(n,t)}else r=t;let i=this.parseUrl(r);this.href=r,this.origin=`${i.protocol}//${i.host}`,this.protocol=i.protocol,this.username=i.username,this.password=i.password,this.host=i.host,this.hostname=i.hostname,this.port=i.port,this.pathname=i.pathname,this.search=i.search,this.searchParams=new V(i.search),this.hash=i.hash}resolve(t,e){if(e.startsWith("http://")||e.startsWith("https://"))return e;if(e.startsWith("//"))return`${this.parseUrl(t).protocol}${e}`;if(e.startsWith("/")){let n=this.parseUrl(t);return`${n.protocol}//${n.host}${e}`}let r=this.parseUrl(t),i=r.pathname.endsWith("/")?r.pathname:r.pathname+"/";return`${r.protocol}//${r.host}${i}${e}`}parseUrl(t){let e=t.match(/^(([^:\/?#]+):)?(\/\/([^\/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?$/);if(!e)throw new TypeError("Invalid URL");let r=e[2]||"",i=e[4]||"",n=e[5]||"/",a=e[7]?`?${e[7]}`:"",o=e[9]?`#${e[9]}`:"";if(!r&&!i&&!n.startsWith("/")&&!n.includes("/")&&!n.includes("."))throw new TypeError("Invalid URL");let h=i.match(/^([^@]*)@(.+)$/),c="",l="",d=i;if(h){let b=h[1];d=h[2];let y=b.match(/^([^:]*):?(.*)$/);y&&(c=y[1]||"",l=y[2]||"")}let p=d.match(/^([^:]+):?(\d*)$/),g=p?p[1]:d,m=p&&p[2]?p[2]:"";return{protocol:r?`${r}:`:"",username:c,password:l,host:d,hostname:g,port:m,pathname:n,search:a,hash:o}}toString(){let t=this.searchParams.toString(),e=t?`?${t}`:"";return`${this.protocol}//${this.host}${this.pathname}${e}${this.hash}`}toJSON(){return this.toString()}},U=class ${constructor(t,e){if(typeof t=="string")this.url=t;else if(t?.url)this.url=String(t.url);else if(typeof t?.toString=="function")this.url=String(t.toString());else throw new Error("Invalid input for Request");this.method=(e?.method||"GET").toUpperCase(),this.headers=e?.headers instanceof f?e.headers:new f(e?.headers),this.body=e?.body,this.timeout=e?.timeout,this.signal=e?.signal||void 0}clone(){return new $(this.url,{method:this.method,headers:this.headers,body:this.body,timeout:this.timeout})}toString(){return this.url}},N=class{constructor(s,t){this.bodyData=s,this.status=t?.status??200,this.statusText=t?.statusText??"",this.headers=Q(t?.headers),this.ok=this.status>=200&&this.status<300}async text(){return typeof this.bodyData=="string"?this.bodyData:this.bodyData==null?"":typeof this.bodyData=="object"?JSON.stringify(this.bodyData):String(this.bodyData)}async json(){if(typeof this.bodyData=="string")try{return JSON.parse(this.bodyData)}catch{}return this.bodyData}async arrayBuffer(){let s=await this.text();return new TextEncoder().encode(s).buffer}};function Q(s){return s?new f(s):new f}var X=class{constructor(){this._aborted=!1,this.listeners=new Set,this.onabort=null}get aborted(){return this._aborted}_trigger(){if(!this._aborted){if(this._aborted=!0,typeof this.onabort=="function")try{this.onabort()}catch{}for(let s of Array.from(this.listeners))try{s()}catch{}this.listeners.clear()}}addEventListener(s,t){if(this._aborted){try{t()}catch{}return}this.listeners.add(t)}removeEventListener(s,t){this.listeners.delete(t)}toString(){return"[object AbortSignal]"}},j=class{constructor(){this._signal=new X}get signal(){return this._signal}abort(){this._signal._trigger()}toString(){return"[object AbortController]"}};var H=class{constructor(t,e=""){this.http=t,this.baseUrl=e.replace(/\/$/,"")}async invoke(t,e){let r=this.baseUrl?`${this.baseUrl}/functions/${t}`:`/functions/${t}`;return await(await this.http.fetch(r,{method:e.method||"POST",body:e.body,headers:e.headers})).json()}};var u="nvwa_current_jwt",v="nvwa_login_token",O="nvwa_user_profile",G="set-auth-token",Z=typeof fetch<"u"?(s,t)=>fetch(s,t):()=>{throw new Error("AuthClient requires fetch")},tt={google:{id:"google",name:"Google Login",description:"Sign in with Google account."},github:{id:"github",name:"GitHub Login",description:"Sign in with GitHub account."},"wechat-website":{id:"wechat-website",name:"WeChat QR Login",description:"Sign in with WeChat website QR code."}};function W(s,t){let e=s.socialLogin?.providers?.[t];return e?.enabled?e.oauthCredentialSource==="custom"?"custom":"nvwa_default":null}var T=class{constructor(t,e={}){this.baseUrl=t.replace(/\/$/,""),this.authPath=(e.authPath??"/auth").replace(/^\//,""),this.fetchImpl=e.fetchImpl??Z,this.storage=e.storage??null,this.credentials=e.credentials??"omit",this.integrationProviders=e.integrationProviders??{},typeof console<"u"&&(console.warn("[NvwaAuth] init baseUrl:",this.baseUrl||"(empty)"),(!this.baseUrl||!this.baseUrl.startsWith("http://")&&!this.baseUrl.startsWith("https://"))&&console.warn("[NvwaAuth] baseUrl \u5E94\u4E3A\u5B8C\u6574\u5730\u5740\uFF08\u5982 https://xxx.nvwa.app\uFF09\uFF0C\u5426\u5219\u5C0F\u7A0B\u5E8F request \u4F1A\u62A5 invalid url"))}async getSocialProviders(t){let e=this.integrationProviders.socialLogin?.providers??{};return Object.entries(e).filter(([,r])=>r.enabled).map(([r])=>tt[r]??{id:r,name:r,description:""})}async currentUser(){if(this.storage){let r=await this.storage.get(O);if(r!=null)return r}let{data:t}=await this.getSession(),e=t?.user??null;return e&&this.storage&&await this.storage.set(O,e),e}async getCurrentJwt(){if(this.storage){let e=await this.storage.get(u);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(u,i.token),i.token):null}let{data:t}=await this.getToken();return t?.token??null}async persistLogin(t,e){if(!this.storage)return;let i=e?.headers.get(G)?.trim()||t.token||t.session?.token;i&&await this.storage.set(v,i),t.user&&await this.storage.set(O,t.user);let n=i??await this.storage.get(v),{data:a}=await this.getToken(n??void 0);a?.token&&await this.storage.set(u,a.token)}async clearLogin(){this.storage&&(await this.storage.remove(v),await this.storage.remove(O),await this.storage.remove(u))}getGoogleOpenPlatformLoginUrl(t,e){let r=new URLSearchParams({return_url:t});e?.applicationCode?.trim()&&r.set("application_code",e.applicationCode.trim()),e?.platformCode?.trim()&&r.set("platform_code",e.platformCode.trim());let i=W(this.integrationProviders,"google");return i&&r.set("oauth_credential_source",i),`${this.url("google/openplatform/login")}?${r.toString()}`}startGoogleOpenPlatformLogin(t,e){let r=this.getGoogleOpenPlatformLoginUrl(t,e);if(typeof globalThis<"u"&&"location"in globalThis){globalThis.location.href=r;return}throw new Error("startGoogleOpenPlatformLogin requires a browser environment with location")}async completeGoogleOpenPlatformLoginFromCurrentUrl(t){let e;if(t!=null&&t!=="")e=t;else if(typeof globalThis<"u"&&"location"in globalThis)e=globalThis.location.href;else return{error:{message:"completeGoogleOpenPlatformLoginFromCurrentUrl requires url or browser location",status:0}};let r;try{r=new URL(e).searchParams.get("exchange_code")}catch{return{error:{message:"invalid_callback_url",status:400}}}return r?.trim()?await this.loginWithGoogleExchangeCode(r.trim()):{error:{message:"missing_exchange_code",status:400}}}async loginWithGoogleExchangeCode(t){try{let e={"Content-Type":"application/json"};if(this.storage){let a=await this.storage.get(u);a!=null&&(e.Authorization=`Bearer ${a}`)}let r=await this.fetchImpl(this.url("google/openplatform/sign-in"),{method:"POST",headers:e,credentials:this.credentials,body:JSON.stringify({exchangeCode:t})}),i=await r.text();if(!r.ok)return{error:{message:i||r.statusText,status:r.status}};let n=i?JSON.parse(i):null;return!n?.token||!n.user?{error:{message:"invalid_google_login_response",status:502}}:(this.storage&&(await this.storage.set(u,n.token),await this.storage.set(v,n.token),await this.storage.set(O,n.user)),{data:n})}catch(e){return{error:{message:e instanceof Error?e.message:String(e),status:0}}}}async getGoogleOpenPlatformIdentity(){try{let t={};if(this.storage){let n=await this.storage.get(u);n!=null&&(t.Authorization=`Bearer ${n}`)}let e=await this.fetchImpl(this.url("google/openplatform/identity"),{method:"GET",credentials:this.credentials,...Object.keys(t).length?{headers:t}:{}}),r=await e.text();if(!e.ok)return{error:{message:r||e.statusText,status:e.status}};let i=r?JSON.parse(r):null;return i?.sub?{data:i}:{error:{message:"invalid_google_identity_response",status:502}}}catch(t){return{error:{message:t instanceof Error?t.message:String(t),status:0}}}}getGithubOpenPlatformLoginUrl(t,e){let r=new URLSearchParams({return_url:t});e?.applicationCode?.trim()&&r.set("application_code",e.applicationCode.trim()),e?.platformCode?.trim()&&r.set("platform_code",e.platformCode.trim());let i=W(this.integrationProviders,"github");return i&&r.set("oauth_credential_source",i),`${this.url("github/openplatform/login")}?${r.toString()}`}startGithubOpenPlatformLogin(t,e){let r=this.getGithubOpenPlatformLoginUrl(t,e);if(typeof globalThis<"u"&&"location"in globalThis){globalThis.location.href=r;return}throw new Error("startGithubOpenPlatformLogin requires a browser environment with location")}async completeGithubOpenPlatformLoginFromCurrentUrl(t){let e;if(t!=null&&t!=="")e=t;else if(typeof globalThis<"u"&&"location"in globalThis)e=globalThis.location.href;else return{error:{message:"completeGithubOpenPlatformLoginFromCurrentUrl requires url or browser location",status:0}};let r;try{r=new URL(e).searchParams.get("exchange_code")}catch{return{error:{message:"invalid_callback_url",status:400}}}return r?.trim()?await this.loginWithGithubExchangeCode(r.trim()):{error:{message:"missing_exchange_code",status:400}}}async loginWithGithubExchangeCode(t){try{let e={"Content-Type":"application/json"};if(this.storage){let a=await this.storage.get(u);a!=null&&(e.Authorization=`Bearer ${a}`)}let r=await this.fetchImpl(this.url("github/openplatform/sign-in"),{method:"POST",headers:e,credentials:this.credentials,body:JSON.stringify({exchangeCode:t})}),i=await r.text();if(!r.ok)return{error:{message:i||r.statusText,status:r.status}};let n=i?JSON.parse(i):null;return!n?.token||!n.user?{error:{message:"invalid_github_login_response",status:502}}:(this.storage&&(await this.storage.set(u,n.token),await this.storage.set(v,n.token),await this.storage.set(O,n.user)),{data:n})}catch(e){return{error:{message:e instanceof Error?e.message:String(e),status:0}}}}async getGithubOpenPlatformIdentity(){try{let t={};if(this.storage){let n=await this.storage.get(u);n!=null&&(t.Authorization=`Bearer ${n}`)}let e=await this.fetchImpl(this.url("github/openplatform/identity"),{method:"GET",credentials:this.credentials,...Object.keys(t).length?{headers:t}:{}}),r=await e.text();if(!e.ok)return{error:{message:r||e.statusText,status:e.status}};let i=r?JSON.parse(r):null;return i?.sub?{data:i}:{error:{message:"invalid_github_identity_response",status:502}}}catch(t){return{error:{message:t instanceof Error?t.message:String(t),status:0}}}}getWechatWebsiteOpenPlatformLoginUrl(t){let e=new URLSearchParams({return_url:t});return`${this.url("wechat-website/openplatform/login")}?${e.toString()}`}startWechatWebsiteOpenPlatformLogin(t){let e=this.getWechatWebsiteOpenPlatformLoginUrl(t);if(typeof globalThis<"u"&&"location"in globalThis){globalThis.location.href=e;return}throw new Error("startWechatWebsiteOpenPlatformLogin requires a browser environment with location")}async completeWechatWebsiteOpenPlatformLoginFromCurrentUrl(t){let e;if(t!=null&&t!=="")e=t;else if(typeof globalThis<"u"&&"location"in globalThis)e=globalThis.location.href;else return{error:{message:"completeWechatWebsiteOpenPlatformLoginFromCurrentUrl requires url or browser location",status:0}};let r;try{r=new URL(e).searchParams.get("exchange_code")}catch{return{error:{message:"invalid_callback_url",status:400}}}return r?.trim()?await this.loginWithWechatWebsiteExchangeCode(r.trim()):{error:{message:"missing_exchange_code",status:400}}}async loginWithWechatWebsiteExchangeCode(t){try{let e={"Content-Type":"application/json"};if(this.storage){let a=await this.storage.get(u);a!=null&&(e.Authorization=`Bearer ${a}`)}let r=await this.fetchImpl(this.url("wechat-website/openplatform/sign-in"),{method:"POST",headers:e,credentials:this.credentials,body:JSON.stringify({exchangeCode:t})}),i=await r.text();if(!r.ok)return{error:{message:i||r.statusText,status:r.status}};let n=i?JSON.parse(i):null;return!n?.token||!n.user?{error:{message:"invalid_wechat_website_login_response",status:502}}:(this.storage&&(await this.storage.set(u,n.token),await this.storage.set(v,n.token),await this.storage.set(O,n.user)),{data:n})}catch(e){return{error:{message:e instanceof Error?e.message:String(e),status:0}}}}async getWechatWebsiteOpenPlatformIdentity(){try{let t={};if(this.storage){let n=await this.storage.get(u);n!=null&&(t.Authorization=`Bearer ${n}`)}let e=await this.fetchImpl(this.url("wechat-website/openplatform/identity"),{method:"GET",credentials:this.credentials,...Object.keys(t).length?{headers:t}:{}}),r=await e.text();if(!e.ok)return{error:{message:r||e.statusText,status:e.status}};let i=r?JSON.parse(r):null;return i?.sub?{data:i}:{error:{message:"invalid_wechat_website_identity_response",status:502}}}catch(t){return{error:{message:t instanceof Error?t.message:String(t),status:0}}}}url(t){let r=`${`${this.baseUrl.replace(/\/+$/,"")}/${this.authPath.replace(/^\/+/,"")}`}/${t.replace(/^\/+/,"")}`;return typeof console<"u"&&(console.warn("[NvwaAuth] request URL:",r),!r.startsWith("http://")&&!r.startsWith("https://")&&console.warn("[NvwaAuth] URL \u975E\u5B8C\u6574\u5730\u5740\uFF0C\u5C0F\u7A0B\u5E8F\u4F1A\u62A5 invalid url\uFF0C\u8BF7\u68C0\u67E5 Nvwa \u6784\u9020\u65F6\u4F20\u5165\u7684 baseUrl")),r}async getSession(){try{let t={};if(this.storage){let i=await this.storage.get(v)??await this.storage.get(u);i!=null&&(t.Authorization=`Bearer ${i}`)}let e=await this.fetchImpl(this.url("session"),{method:"GET",credentials:this.credentials,...Object.keys(t).length?{headers:t}:{}});return e.ok?{data:await e.json()}:{data:null,error:{message:await e.text()||e.statusText,status:e.status}}}catch(t){return{data:null,error:{message:t instanceof Error?t.message:String(t),status:0}}}}async signInWithEmail(t,e){try{let r=await this.fetchImpl(this.url("sign-in/email"),{method:"POST",headers:{"Content-Type":"application/json"},credentials:this.credentials,body:JSON.stringify({email:t,password:e})}),i=await r.text();if(!r.ok)return{error:{message:i||r.statusText,status:r.status}};let n=i?JSON.parse(i):void 0;return n&&await this.persistLogin({user:n.user,session:n.session},r),{data:n}}catch(r){return{error:{message:r instanceof Error?r.message:String(r),status:0}}}}async signOut(){try{let t={};if(this.storage){let r=await this.storage.get(v)??await this.storage.get(u);r!=null&&(t.Authorization=`Bearer ${r}`)}let e=await this.fetchImpl(this.url("sign-out"),{method:"POST",credentials:this.credentials,...Object.keys(t).length?{headers:t}:{}});return await this.clearLogin(),e.ok?{}:{error:{message:await e.text()||e.statusText,status:e.status}}}catch(t){return{error:{message:t instanceof Error?t.message:String(t),status:0}}}}async signUp(t){let e=await this.postJson("sign-up/email",t);return e.data&&await this.persistLogin(e.data,e.response),e}async getToken(t){try{let e={};if(t)e.Authorization=`Bearer ${t}`;else if(this.storage){let a=await this.storage.get(v)??await this.storage.get(u);a!=null&&(e.Authorization=`Bearer ${a}`)}let r=await this.fetchImpl(this.url("token"),{method:"GET",credentials:this.credentials,...Object.keys(e).length?{headers:e}:{}}),i=await r.text();if(!r.ok)return{error:{message:i||r.statusText,status:r.status}};let n=i?JSON.parse(i):void 0;return{data:n?.token!=null?{token:n.token}:void 0}}catch(e){return{error:{message:e instanceof Error?e.message:String(e),status:0}}}}async signInWithUsername(t,e){let r=await this.postJson("sign-in/username",{username:t,password:e});return r.data&&await this.persistLogin(r.data,r.response),r}async signInWithPhoneNumber(t,e,r){let i=await this.postJson("sign-in/phone-number",{phoneNumber:t,password:e,rememberMe:r});return i.data&&await this.persistLogin(i.data,i.response),i}async sendPhoneNumberOtp(t){let e=await this.postJson("phone-number/send-otp",{phoneNumber:t});return e.error?{error:e.error}:{}}async verifyPhoneNumber(t,e){let r=await this.postJson("phone-number/verify",{phoneNumber:t,code:e});return r.data&&await this.persistLogin(r.data,r.response),r}async loginWithWeChatCode(t,e){try{let r={"Content-Type":"application/json"};if(this.storage){let o=await this.storage.get(u);o!=null&&(r.Authorization=`Bearer ${o}`)}let i=await this.fetchImpl(this.url("wechat/openplatform/sign-in"),{method:"POST",headers:r,credentials:this.credentials,body:JSON.stringify({code:t,applicationCode:e})}),n=await i.text();if(!i.ok)return{error:{message:n||i.statusText,status:i.status}};let a=n?JSON.parse(n):null;return!a?.token||!a.user?{error:{message:"invalid_wechat_login_response",status:502}}:(this.storage&&(await this.storage.set(u,a.token),await this.storage.set(v,a.token),await this.storage.set(O,a.user)),{data:a})}catch(r){return{error:{message:r instanceof Error?r.message:String(r),status:0}}}}async loginWithAlipayCode(t,e){try{let r={"Content-Type":"application/json"};if(this.storage){let o=await this.storage.get(u);o!=null&&(r.Authorization=`Bearer ${o}`)}let i=await this.fetchImpl(this.url("alipay/openplatform/sign-in"),{method:"POST",headers:r,credentials:this.credentials,body:JSON.stringify({code:t,applicationCode:e})}),n=await i.text();if(!i.ok)return{error:{message:n||i.statusText,status:i.status}};let a=n?JSON.parse(n):null;return!a?.token||!a.user?{error:{message:"invalid_alipay_login_response",status:502}}:(this.storage&&(await this.storage.set(u,a.token),await this.storage.set(v,a.token),await this.storage.set(O,a.user)),{data:a})}catch(r){return{error:{message:r instanceof Error?r.message:String(r),status:0}}}}async getWeChatOpenPlatformIdentity(t){try{let e={};if(this.storage){let o=await this.storage.get(u);o!=null&&(e.Authorization=`Bearer ${o}`)}let r=t?.trim()?`?applicationCode=${encodeURIComponent(t.trim())}`:"",i=await this.fetchImpl(this.url(`wechat/openplatform/identity${r}`),{method:"GET",credentials:this.credentials,...Object.keys(e).length?{headers:e}:{}}),n=await i.text();if(!i.ok)return{error:{message:n||i.statusText,status:i.status}};let a=n?JSON.parse(n):null;return!a?.openid||!a.appId?{error:{message:"invalid_wechat_identity_response",status:502}}:{data:a}}catch(e){return{error:{message:e instanceof Error?e.message:String(e),status:0}}}}async getAlipayOpenPlatformIdentity(t){try{let e={};if(this.storage){let o=await this.storage.get(u);o!=null&&(e.Authorization=`Bearer ${o}`)}let r=t?.trim()?`?applicationCode=${encodeURIComponent(t.trim())}`:"",i=await this.fetchImpl(this.url(`alipay/openplatform/identity${r}`),{method:"GET",credentials:this.credentials,...Object.keys(e).length?{headers:e}:{}}),n=await i.text();if(!i.ok)return{error:{message:n||i.statusText,status:i.status}};let a=n?JSON.parse(n):null;return!a?.openid||!a.appId?{error:{message:"invalid_alipay_identity_response",status:502}}:{data:a}}catch(e){return{error:{message:e instanceof Error?e.message:String(e),status:0}}}}async postJson(t,e){try{let r=await this.fetchImpl(this.url(t),{method:"POST",headers:{"Content-Type":"application/json"},credentials:this.credentials,body:JSON.stringify(e)}),i=await r.text();if(!r.ok)return{error:{message:i||r.statusText,status:r.status}};let n=i?JSON.parse(i):void 0;return{data:n?.data??n??void 0,response:r}}catch(r){return{error:{message:r instanceof Error?r.message:String(r),status:0}}}}};var q=class{constructor(t,e,r){this.storage=t,this.customFetch=e,this.handleUnauthorized=r}async fetch(t,e){return await this.customFetch(t,e)}async fetchWithAuth(t,e){let r=await this.storage.get(u),i=new f(e?.headers);r&&i.set("Authorization",`Bearer ${r}`);let n=e?.method||"GET";if((n==="POST"||n==="PUT"||n==="PATCH")&&e?.body){let o=i.get("Content-Type");(!o||o.includes("text/plain"))&&i.set("Content-Type","application/json")}let a=await this.customFetch(t,{...e,headers:i});if(a.status===401)throw this.handleUnauthorized(),new Error("\u672A\u767B\u5F55");return a}};var et="/storage",rt=et+"/generateUploadUrl",F=class{constructor(t,e){this.baseUrl=t,this.http=e}async uploadFile(t){let e=await this.http.fetch(this.baseUrl+rt,{method:"POST",body:{fileName:t.name||t.fileName,fileSize:t.size||t.fileSize,fileType:t.type||t.fileType}}),{url:r}=await e.json();if(!r)throw new Error("\u83B7\u53D6\u4E0A\u4F20URL\u5931\u8D25");let i=await this.http.fetch(r,{method:"PUT",body:t,headers:new f({"Content-Type":t.type||t.fileType||"application/octet-stream"})}),{url:n}=await i.json();return{url:n.split("?")[0]}}};var st=class extends Error{constructor(s){super(s.message),this.name="PostgrestError",this.details=s.details,this.hint=s.hint,this.code=s.code}},it=class{constructor(s){var t,e,r;this.shouldThrowOnError=!1,this.method=s.method,this.url=s.url,this.headers=new f(s.headers),this.schema=s.schema,this.body=s.body,this.shouldThrowOnError=(t=s.shouldThrowOnError)!==null&&t!==void 0?t:!1,this.signal=s.signal,this.isMaybeSingle=(e=s.isMaybeSingle)!==null&&e!==void 0?e:!1,this.urlLengthLimit=(r=s.urlLengthLimit)!==null&&r!==void 0?r:8e3,s.fetch?this.fetch=s.fetch:this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(s,t){return this.headers=new f(this.headers),this.headers.set(s,t),this}then(s,t){var e=this;this.schema===void 0||(["GET","HEAD"].includes(this.method)?this.headers.set("Accept-Profile",this.schema):this.headers.set("Content-Profile",this.schema)),this.method!=="GET"&&this.method!=="HEAD"&&this.headers.set("Content-Type","application/json");let r=this.fetch,i=r(this.url.toString(),{method:this.method,headers:this.headers,body:JSON.stringify(this.body),signal:this.signal}).then(async n=>{let a=null,o=null,h=null,c=n.status,l=n.statusText;if(n.ok){var d,p;if(e.method!=="HEAD"){var g;let y=await n.text();y===""||(e.headers.get("Accept")==="text/csv"||e.headers.get("Accept")&&(!((g=e.headers.get("Accept"))===null||g===void 0)&&g.includes("application/vnd.pgrst.plan+text"))?o=y:o=JSON.parse(y))}let m=(d=e.headers.get("Prefer"))===null||d===void 0?void 0:d.match(/count=(exact|planned|estimated)/),b=(p=n.headers.get("content-range"))===null||p===void 0?void 0:p.split("/");m&&b&&b.length>1&&(h=parseInt(b[1])),e.isMaybeSingle&&Array.isArray(o)&&(o.length>1?(a={code:"PGRST116",details:`Results contain ${o.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},o=null,h=null,c=406,l="Not Acceptable"):o.length===1?o=o[0]:o=null)}else{let m=await n.text();try{a=JSON.parse(m),Array.isArray(a)&&n.status===404&&(o=[],a=null,c=200,l="OK")}catch{n.status===404&&m===""?(c=204,l="No Content"):a={message:m}}if(a&&e.shouldThrowOnError)throw new st(a)}return{error:a,data:o,count:h,status:c,statusText:l}});return this.shouldThrowOnError||(i=i.catch(n=>{var a;let o="",h="",c="",l=n?.cause;if(l){var d,p,g,m;let K=(d=l?.message)!==null&&d!==void 0?d:"",k=(p=l?.code)!==null&&p!==void 0?p:"";o=`${(g=n?.name)!==null&&g!==void 0?g:"FetchError"}: ${n?.message}`,o+=`
2
2
 
3
- Caused by: ${(m=l?.name)!==null&&m!==void 0?m:"Error"}: ${z}`,_&&(o+=` (${_})`),l?.stack&&(o+=`
4
- ${l.stack}`)}else{var b;o=(b=n?.stack)!==null&&b!==void 0?b:""}let y=this.url.toString().length;return n?.name==="AbortError"||n?.code==="ABORT_ERR"?(c="",h="Request was aborted (timeout or manual cancellation)",y>this.urlLengthLimit&&(h+=`. 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")&&(c="",h="HTTP headers exceeded server limits (typically 16KB)",y>this.urlLengthLimit&&(h+=`. 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:`${(a=n?.name)!==null&&a!==void 0?a:"FetchError"}: ${n?.message}`,details:o,hint:h,code:c},data:null,count:null,status:0,statusText:""}})),i.then(s,t)}returns(){return this}overrideTypes(){return this}},et=class extends tt{select(s){let t=!1,e=(s??"*").split("").map(r=>/\s/.test(r)&&!t?"":(r==='"'&&(t=!t),r)).join("");return this.url.searchParams.set("select",e),this.headers.append("Prefer","return=representation"),this}order(s,{ascending:t=!0,nullsFirst:e,foreignTable:r,referencedTable:i=r}={}){let n=i?`${i}.order`:"order",a=this.url.searchParams.get(n);return this.url.searchParams.set(n,`${a?`${a},`:""}${s}.${t?"asc":"desc"}${e===void 0?"":e?".nullsfirst":".nullslast"}`),this}limit(s,{foreignTable:t,referencedTable:e=t}={}){let r=typeof e>"u"?"limit":`${e}.limit`;return this.url.searchParams.set(r,`${s}`),this}range(s,t,{foreignTable:e,referencedTable:r=e}={}){let i=typeof r>"u"?"offset":`${r}.offset`,n=typeof r>"u"?"limit":`${r}.limit`;return this.url.searchParams.set(i,`${s}`),this.url.searchParams.set(n,`${t-s+1}`),this}abortSignal(s){return this.signal=s,this}single(){return this.headers.set("Accept","application/vnd.pgrst.object+json"),this}maybeSingle(){return this.isMaybeSingle=!0,this}csv(){return this.headers.set("Accept","text/csv"),this}geojson(){return this.headers.set("Accept","application/geo+json"),this}explain({analyze:s=!1,verbose:t=!1,settings:e=!1,buffers:r=!1,wal:i=!1,format:n="text"}={}){var a;let o=[s?"analyze":null,t?"verbose":null,e?"settings":null,r?"buffers":null,i?"wal":null].filter(Boolean).join("|"),h=(a=this.headers.get("Accept"))!==null&&a!==void 0?a:"application/json";return this.headers.set("Accept",`application/vnd.pgrst.plan+${n}; for="${h}"; options=${o};`),n==="json"?this:this}rollback(){return this.headers.append("Prefer","tx=rollback"),this}returns(){return this}maxAffected(s){return this.headers.append("Prefer","handling=strict"),this.headers.append("Prefer",`max-affected=${s}`),this}},q=new RegExp("[,()]"),x=class extends et{eq(s,t){return this.url.searchParams.append(s,`eq.${t}`),this}neq(s,t){return this.url.searchParams.append(s,`neq.${t}`),this}gt(s,t){return this.url.searchParams.append(s,`gt.${t}`),this}gte(s,t){return this.url.searchParams.append(s,`gte.${t}`),this}lt(s,t){return this.url.searchParams.append(s,`lt.${t}`),this}lte(s,t){return this.url.searchParams.append(s,`lte.${t}`),this}like(s,t){return this.url.searchParams.append(s,`like.${t}`),this}likeAllOf(s,t){return this.url.searchParams.append(s,`like(all).{${t.join(",")}}`),this}likeAnyOf(s,t){return this.url.searchParams.append(s,`like(any).{${t.join(",")}}`),this}ilike(s,t){return this.url.searchParams.append(s,`ilike.${t}`),this}ilikeAllOf(s,t){return this.url.searchParams.append(s,`ilike(all).{${t.join(",")}}`),this}ilikeAnyOf(s,t){return this.url.searchParams.append(s,`ilike(any).{${t.join(",")}}`),this}regexMatch(s,t){return this.url.searchParams.append(s,`match.${t}`),this}regexIMatch(s,t){return this.url.searchParams.append(s,`imatch.${t}`),this}is(s,t){return this.url.searchParams.append(s,`is.${t}`),this}isDistinct(s,t){return this.url.searchParams.append(s,`isdistinct.${t}`),this}in(s,t){let e=Array.from(new Set(t)).map(r=>typeof r=="string"&&q.test(r)?`"${r}"`:`${r}`).join(",");return this.url.searchParams.append(s,`in.(${e})`),this}notIn(s,t){let e=Array.from(new Set(t)).map(r=>typeof r=="string"&&q.test(r)?`"${r}"`:`${r}`).join(",");return this.url.searchParams.append(s,`not.in.(${e})`),this}contains(s,t){return typeof t=="string"?this.url.searchParams.append(s,`cs.${t}`):Array.isArray(t)?this.url.searchParams.append(s,`cs.{${t.join(",")}}`):this.url.searchParams.append(s,`cs.${JSON.stringify(t)}`),this}containedBy(s,t){return typeof t=="string"?this.url.searchParams.append(s,`cd.${t}`):Array.isArray(t)?this.url.searchParams.append(s,`cd.{${t.join(",")}}`):this.url.searchParams.append(s,`cd.${JSON.stringify(t)}`),this}rangeGt(s,t){return this.url.searchParams.append(s,`sr.${t}`),this}rangeGte(s,t){return this.url.searchParams.append(s,`nxl.${t}`),this}rangeLt(s,t){return this.url.searchParams.append(s,`sl.${t}`),this}rangeLte(s,t){return this.url.searchParams.append(s,`nxr.${t}`),this}rangeAdjacent(s,t){return this.url.searchParams.append(s,`adj.${t}`),this}overlaps(s,t){return typeof t=="string"?this.url.searchParams.append(s,`ov.${t}`):this.url.searchParams.append(s,`ov.{${t.join(",")}}`),this}textSearch(s,t,{config:e,type:r}={}){let i="";r==="plain"?i="pl":r==="phrase"?i="ph":r==="websearch"&&(i="w");let n=e===void 0?"":`(${e})`;return this.url.searchParams.append(s,`${i}fts${n}.${t}`),this}match(s){return Object.entries(s).filter(([t,e])=>e!==void 0).forEach(([t,e])=>{this.url.searchParams.append(t,`eq.${e}`)}),this}not(s,t,e){return this.url.searchParams.append(s,`not.${t}.${e}`),this}or(s,{foreignTable:t,referencedTable:e=t}={}){let r=e?`${e}.or`:"or";return this.url.searchParams.append(r,`(${s})`),this}filter(s,t,e){return this.url.searchParams.append(s,`${t}.${e}`),this}},rt=class{constructor(s,{headers:t={},schema:e,fetch:r,urlLengthLimit:i=8e3}){this.url=s,this.headers=new f(t),this.schema=e,this.fetch=r,this.urlLengthLimit=i}cloneRequestState(){return{url:new S(this.url.toString()),headers:new f(this.headers)}}select(s,t){let{head:e=!1,count:r}=t??{},i=e?"HEAD":"GET",n=!1,a=(s??"*").split("").map(c=>/\s/.test(c)&&!n?"":(c==='"'&&(n=!n),c)).join(""),{url:o,headers:h}=this.cloneRequestState();return o.searchParams.set("select",a),r&&h.append("Prefer",`count=${r}`),new x({method:i,url:o,headers:h,schema:this.schema,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}insert(s,{count:t,defaultToNull:e=!0}={}){var r;let i="POST",{url:n,headers:a}=this.cloneRequestState();if(t&&a.append("Prefer",`count=${t}`),e||a.append("Prefer","missing=default"),Array.isArray(s)){let o=s.reduce((h,c)=>h.concat(Object.keys(c)),[]);if(o.length>0){let h=[...new Set(o)].map(c=>`"${c}"`);n.searchParams.set("columns",h.join(","))}}return new x({method:i,url:n,headers:a,schema:this.schema,body:s,fetch:(r=this.fetch)!==null&&r!==void 0?r:fetch,urlLengthLimit:this.urlLengthLimit})}upsert(s,{onConflict:t,ignoreDuplicates:e=!1,count:r,defaultToNull:i=!0}={}){var n;let a="POST",{url:o,headers:h}=this.cloneRequestState();if(h.append("Prefer",`resolution=${e?"ignore":"merge"}-duplicates`),t!==void 0&&o.searchParams.set("on_conflict",t),r&&h.append("Prefer",`count=${r}`),i||h.append("Prefer","missing=default"),Array.isArray(s)){let c=s.reduce((l,u)=>l.concat(Object.keys(u)),[]);if(c.length>0){let l=[...new Set(c)].map(u=>`"${u}"`);o.searchParams.set("columns",l.join(","))}}return new x({method:a,url:o,headers:h,schema:this.schema,body:s,fetch:(n=this.fetch)!==null&&n!==void 0?n:fetch,urlLengthLimit:this.urlLengthLimit})}update(s,{count:t}={}){var e;let r="PATCH",{url:i,headers:n}=this.cloneRequestState();return t&&n.append("Prefer",`count=${t}`),new x({method:r,url:i,headers:n,schema:this.schema,body:s,fetch:(e=this.fetch)!==null&&e!==void 0?e:fetch,urlLengthLimit:this.urlLengthLimit})}delete({count:s}={}){var t;let e="DELETE",{url:r,headers:i}=this.cloneRequestState();return s&&i.append("Prefer",`count=${s}`),new x({method:e,url:r,headers:i,schema:this.schema,fetch:(t=this.fetch)!==null&&t!==void 0?t:fetch,urlLengthLimit:this.urlLengthLimit})}};function L(s){"@babel/helpers - typeof";return L=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},L(s)}function st(s,t){if(L(s)!="object"||!s)return s;var e=s[Symbol.toPrimitive];if(e!==void 0){var r=e.call(s,t||"default");if(L(r)!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(s)}function it(s){var t=st(s,"string");return L(t)=="symbol"?t:t+""}function nt(s,t,e){return(t=it(t))in s?Object.defineProperty(s,t,{value:e,enumerable:!0,configurable:!0,writable:!0}):s[t]=e,s}function F(s,t){var e=Object.keys(s);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(s);t&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(s,i).enumerable})),e.push.apply(e,r)}return e}function E(s){for(var t=1;t<arguments.length;t++){var e=arguments[t]!=null?arguments[t]:{};t%2?F(Object(e),!0).forEach(function(r){nt(s,r,e[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(s,Object.getOwnPropertyDescriptors(e)):F(Object(e)).forEach(function(r){Object.defineProperty(s,r,Object.getOwnPropertyDescriptor(e,r))})}return s}var M=class J{constructor(t,{headers:e={},schema:r,fetch:i,timeout:n,urlLengthLimit:a=8e3}={}){this.url=t,this.headers=new f(e),this.schemaName=r,this.urlLengthLimit=a;let o=i??globalThis.fetch;n!==void 0&&n>0?this.fetch=(h,c)=>{let l=new N,u=setTimeout(()=>l.abort(),n),p=c?.signal;if(p){if(p.aborted)return clearTimeout(u),o(h,c);let g=()=>{clearTimeout(u),l.abort()};return p.addEventListener("abort",g,{once:!0}),o(h,E(E({},c),{},{signal:l.signal})).finally(()=>{clearTimeout(u),p.removeEventListener("abort",g)})}return o(h,E(E({},c),{},{signal:l.signal})).finally(()=>clearTimeout(u))}:this.fetch=o}from(t){if(!t||typeof t!="string"||t.trim()==="")throw new Error("Invalid relation name: relation must be a non-empty string.");return new rt(new S(`${this.url}/${t}`),{headers:new f(this.headers),schema:this.schemaName,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}schema(t){return new J(this.url,{headers:this.headers,schema:t,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}rpc(t,e={},{head:r=!1,get:i=!1,count:n}={}){var a;let o,h=new S(`${this.url}/rpc/${t}`),c,l=g=>g!==null&&typeof g=="object"&&(!Array.isArray(g)||g.some(l)),u=r&&Object.values(e).some(l);u?(o="POST",c=e):r||i?(o=r?"HEAD":"GET",Object.entries(e).filter(([g,m])=>m!==void 0).map(([g,m])=>[g,Array.isArray(m)?`{${m.join(",")}}`:`${m}`]).forEach(([g,m])=>{h.searchParams.append(g,m)})):(o="POST",c=e);let p=new f(this.headers);return u?p.set("Prefer",n?`count=${n},return=minimal`:"return=minimal"):n&&p.set("Prefer",`count=${n}`),new x({method:o,url:h,headers:p,schema:this.schemaName,body:c,fetch:(a=this.fetch)!==null&&a!==void 0?a:fetch,urlLengthLimit:this.urlLengthLimit})}};var at="/entities",Mt=(s,t)=>new M(s+at,{fetch:t.fetchWithAuth.bind(t)});var B=class{constructor(){this.hoverOverlay=null;this.selectedOverlay=null;this.tooltip=null;this.hoverElement=null;this.selectedElement=null;this.hoverUpdateHandler=null;this.selectedUpdateHandler=null;this.createStyles()}createStyles(){if(document.getElementById("__nvwa-inspector-overlay-style"))return;let t=document.createElement("style");t.id="__nvwa-inspector-overlay-style",t.textContent=`
3
+ Caused by: ${(m=l?.name)!==null&&m!==void 0?m:"Error"}: ${K}`,k&&(o+=` (${k})`),l?.stack&&(o+=`
4
+ ${l.stack}`)}else{var b;o=(b=n?.stack)!==null&&b!==void 0?b:""}let y=this.url.toString().length;return n?.name==="AbortError"||n?.code==="ABORT_ERR"?(c="",h="Request was aborted (timeout or manual cancellation)",y>this.urlLengthLimit&&(h+=`. 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")&&(c="",h="HTTP headers exceeded server limits (typically 16KB)",y>this.urlLengthLimit&&(h+=`. 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:`${(a=n?.name)!==null&&a!==void 0?a:"FetchError"}: ${n?.message}`,details:o,hint:h,code:c},data:null,count:null,status:0,statusText:""}})),i.then(s,t)}returns(){return this}overrideTypes(){return this}},nt=class extends it{select(s){let t=!1,e=(s??"*").split("").map(r=>/\s/.test(r)&&!t?"":(r==='"'&&(t=!t),r)).join("");return this.url.searchParams.set("select",e),this.headers.append("Prefer","return=representation"),this}order(s,{ascending:t=!0,nullsFirst:e,foreignTable:r,referencedTable:i=r}={}){let n=i?`${i}.order`:"order",a=this.url.searchParams.get(n);return this.url.searchParams.set(n,`${a?`${a},`:""}${s}.${t?"asc":"desc"}${e===void 0?"":e?".nullsfirst":".nullslast"}`),this}limit(s,{foreignTable:t,referencedTable:e=t}={}){let r=typeof e>"u"?"limit":`${e}.limit`;return this.url.searchParams.set(r,`${s}`),this}range(s,t,{foreignTable:e,referencedTable:r=e}={}){let i=typeof r>"u"?"offset":`${r}.offset`,n=typeof r>"u"?"limit":`${r}.limit`;return this.url.searchParams.set(i,`${s}`),this.url.searchParams.set(n,`${t-s+1}`),this}abortSignal(s){return this.signal=s,this}single(){return this.headers.set("Accept","application/vnd.pgrst.object+json"),this}maybeSingle(){return this.isMaybeSingle=!0,this}csv(){return this.headers.set("Accept","text/csv"),this}geojson(){return this.headers.set("Accept","application/geo+json"),this}explain({analyze:s=!1,verbose:t=!1,settings:e=!1,buffers:r=!1,wal:i=!1,format:n="text"}={}){var a;let o=[s?"analyze":null,t?"verbose":null,e?"settings":null,r?"buffers":null,i?"wal":null].filter(Boolean).join("|"),h=(a=this.headers.get("Accept"))!==null&&a!==void 0?a:"application/json";return this.headers.set("Accept",`application/vnd.pgrst.plan+${n}; for="${h}"; options=${o};`),n==="json"?this:this}rollback(){return this.headers.append("Prefer","tx=rollback"),this}returns(){return this}maxAffected(s){return this.headers.append("Prefer","handling=strict"),this.headers.append("Prefer",`max-affected=${s}`),this}},M=new RegExp("[,()]"),L=class extends nt{eq(s,t){return this.url.searchParams.append(s,`eq.${t}`),this}neq(s,t){return this.url.searchParams.append(s,`neq.${t}`),this}gt(s,t){return this.url.searchParams.append(s,`gt.${t}`),this}gte(s,t){return this.url.searchParams.append(s,`gte.${t}`),this}lt(s,t){return this.url.searchParams.append(s,`lt.${t}`),this}lte(s,t){return this.url.searchParams.append(s,`lte.${t}`),this}like(s,t){return this.url.searchParams.append(s,`like.${t}`),this}likeAllOf(s,t){return this.url.searchParams.append(s,`like(all).{${t.join(",")}}`),this}likeAnyOf(s,t){return this.url.searchParams.append(s,`like(any).{${t.join(",")}}`),this}ilike(s,t){return this.url.searchParams.append(s,`ilike.${t}`),this}ilikeAllOf(s,t){return this.url.searchParams.append(s,`ilike(all).{${t.join(",")}}`),this}ilikeAnyOf(s,t){return this.url.searchParams.append(s,`ilike(any).{${t.join(",")}}`),this}regexMatch(s,t){return this.url.searchParams.append(s,`match.${t}`),this}regexIMatch(s,t){return this.url.searchParams.append(s,`imatch.${t}`),this}is(s,t){return this.url.searchParams.append(s,`is.${t}`),this}isDistinct(s,t){return this.url.searchParams.append(s,`isdistinct.${t}`),this}in(s,t){let e=Array.from(new Set(t)).map(r=>typeof r=="string"&&M.test(r)?`"${r}"`:`${r}`).join(",");return this.url.searchParams.append(s,`in.(${e})`),this}notIn(s,t){let e=Array.from(new Set(t)).map(r=>typeof r=="string"&&M.test(r)?`"${r}"`:`${r}`).join(",");return this.url.searchParams.append(s,`not.in.(${e})`),this}contains(s,t){return typeof t=="string"?this.url.searchParams.append(s,`cs.${t}`):Array.isArray(t)?this.url.searchParams.append(s,`cs.{${t.join(",")}}`):this.url.searchParams.append(s,`cs.${JSON.stringify(t)}`),this}containedBy(s,t){return typeof t=="string"?this.url.searchParams.append(s,`cd.${t}`):Array.isArray(t)?this.url.searchParams.append(s,`cd.{${t.join(",")}}`):this.url.searchParams.append(s,`cd.${JSON.stringify(t)}`),this}rangeGt(s,t){return this.url.searchParams.append(s,`sr.${t}`),this}rangeGte(s,t){return this.url.searchParams.append(s,`nxl.${t}`),this}rangeLt(s,t){return this.url.searchParams.append(s,`sl.${t}`),this}rangeLte(s,t){return this.url.searchParams.append(s,`nxr.${t}`),this}rangeAdjacent(s,t){return this.url.searchParams.append(s,`adj.${t}`),this}overlaps(s,t){return typeof t=="string"?this.url.searchParams.append(s,`ov.${t}`):this.url.searchParams.append(s,`ov.{${t.join(",")}}`),this}textSearch(s,t,{config:e,type:r}={}){let i="";r==="plain"?i="pl":r==="phrase"?i="ph":r==="websearch"&&(i="w");let n=e===void 0?"":`(${e})`;return this.url.searchParams.append(s,`${i}fts${n}.${t}`),this}match(s){return Object.entries(s).filter(([t,e])=>e!==void 0).forEach(([t,e])=>{this.url.searchParams.append(t,`eq.${e}`)}),this}not(s,t,e){return this.url.searchParams.append(s,`not.${t}.${e}`),this}or(s,{foreignTable:t,referencedTable:e=t}={}){let r=e?`${e}.or`:"or";return this.url.searchParams.append(r,`(${s})`),this}filter(s,t,e){return this.url.searchParams.append(s,`${t}.${e}`),this}},at=class{constructor(s,{headers:t={},schema:e,fetch:r,urlLengthLimit:i=8e3}){this.url=s,this.headers=new f(t),this.schema=e,this.fetch=r,this.urlLengthLimit=i}cloneRequestState(){return{url:new S(this.url.toString()),headers:new f(this.headers)}}select(s,t){let{head:e=!1,count:r}=t??{},i=e?"HEAD":"GET",n=!1,a=(s??"*").split("").map(c=>/\s/.test(c)&&!n?"":(c==='"'&&(n=!n),c)).join(""),{url:o,headers:h}=this.cloneRequestState();return o.searchParams.set("select",a),r&&h.append("Prefer",`count=${r}`),new L({method:i,url:o,headers:h,schema:this.schema,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}insert(s,{count:t,defaultToNull:e=!0}={}){var r;let i="POST",{url:n,headers:a}=this.cloneRequestState();if(t&&a.append("Prefer",`count=${t}`),e||a.append("Prefer","missing=default"),Array.isArray(s)){let o=s.reduce((h,c)=>h.concat(Object.keys(c)),[]);if(o.length>0){let h=[...new Set(o)].map(c=>`"${c}"`);n.searchParams.set("columns",h.join(","))}}return new L({method:i,url:n,headers:a,schema:this.schema,body:s,fetch:(r=this.fetch)!==null&&r!==void 0?r:fetch,urlLengthLimit:this.urlLengthLimit})}upsert(s,{onConflict:t,ignoreDuplicates:e=!1,count:r,defaultToNull:i=!0}={}){var n;let a="POST",{url:o,headers:h}=this.cloneRequestState();if(h.append("Prefer",`resolution=${e?"ignore":"merge"}-duplicates`),t!==void 0&&o.searchParams.set("on_conflict",t),r&&h.append("Prefer",`count=${r}`),i||h.append("Prefer","missing=default"),Array.isArray(s)){let c=s.reduce((l,d)=>l.concat(Object.keys(d)),[]);if(c.length>0){let l=[...new Set(c)].map(d=>`"${d}"`);o.searchParams.set("columns",l.join(","))}}return new L({method:a,url:o,headers:h,schema:this.schema,body:s,fetch:(n=this.fetch)!==null&&n!==void 0?n:fetch,urlLengthLimit:this.urlLengthLimit})}update(s,{count:t}={}){var e;let r="PATCH",{url:i,headers:n}=this.cloneRequestState();return t&&n.append("Prefer",`count=${t}`),new L({method:r,url:i,headers:n,schema:this.schema,body:s,fetch:(e=this.fetch)!==null&&e!==void 0?e:fetch,urlLengthLimit:this.urlLengthLimit})}delete({count:s}={}){var t;let e="DELETE",{url:r,headers:i}=this.cloneRequestState();return s&&i.append("Prefer",`count=${s}`),new L({method:e,url:r,headers:i,schema:this.schema,fetch:(t=this.fetch)!==null&&t!==void 0?t:fetch,urlLengthLimit:this.urlLengthLimit})}};function R(s){"@babel/helpers - typeof";return R=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},R(s)}function ot(s,t){if(R(s)!="object"||!s)return s;var e=s[Symbol.toPrimitive];if(e!==void 0){var r=e.call(s,t||"default");if(R(r)!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(s)}function lt(s){var t=ot(s,"string");return R(t)=="symbol"?t:t+""}function ht(s,t,e){return(t=lt(t))in s?Object.defineProperty(s,t,{value:e,enumerable:!0,configurable:!0,writable:!0}):s[t]=e,s}function J(s,t){var e=Object.keys(s);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(s);t&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(s,i).enumerable})),e.push.apply(e,r)}return e}function E(s){for(var t=1;t<arguments.length;t++){var e=arguments[t]!=null?arguments[t]:{};t%2?J(Object(e),!0).forEach(function(r){ht(s,r,e[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(s,Object.getOwnPropertyDescriptors(e)):J(Object(e)).forEach(function(r){Object.defineProperty(s,r,Object.getOwnPropertyDescriptor(e,r))})}return s}var z=class B{constructor(t,{headers:e={},schema:r,fetch:i,timeout:n,urlLengthLimit:a=8e3}={}){this.url=t,this.headers=new f(e),this.schemaName=r,this.urlLengthLimit=a;let o=i??globalThis.fetch;n!==void 0&&n>0?this.fetch=(h,c)=>{let l=new j,d=setTimeout(()=>l.abort(),n),p=c?.signal;if(p){if(p.aborted)return clearTimeout(d),o(h,c);let g=()=>{clearTimeout(d),l.abort()};return p.addEventListener("abort",g,{once:!0}),o(h,E(E({},c),{},{signal:l.signal})).finally(()=>{clearTimeout(d),p.removeEventListener("abort",g)})}return o(h,E(E({},c),{},{signal:l.signal})).finally(()=>clearTimeout(d))}:this.fetch=o}from(t){if(!t||typeof t!="string"||t.trim()==="")throw new Error("Invalid relation name: relation must be a non-empty string.");return new at(new S(`${this.url}/${t}`),{headers:new f(this.headers),schema:this.schemaName,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}schema(t){return new B(this.url,{headers:this.headers,schema:t,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit})}rpc(t,e={},{head:r=!1,get:i=!1,count:n}={}){var a;let o,h=new S(`${this.url}/rpc/${t}`),c,l=g=>g!==null&&typeof g=="object"&&(!Array.isArray(g)||g.some(l)),d=r&&Object.values(e).some(l);d?(o="POST",c=e):r||i?(o=r?"HEAD":"GET",Object.entries(e).filter(([g,m])=>m!==void 0).map(([g,m])=>[g,Array.isArray(m)?`{${m.join(",")}}`:`${m}`]).forEach(([g,m])=>{h.searchParams.append(g,m)})):(o="POST",c=e);let p=new f(this.headers);return d?p.set("Prefer",n?`count=${n},return=minimal`:"return=minimal"):n&&p.set("Prefer",`count=${n}`),new L({method:o,url:h,headers:p,schema:this.schemaName,body:c,fetch:(a=this.fetch)!==null&&a!==void 0?a:fetch,urlLengthLimit:this.urlLengthLimit})}};var ct="/entities",Yt=(s,t)=>new z(s+ct,{fetch:t.fetchWithAuth.bind(t)});var D=class{constructor(){this.hoverOverlay=null;this.selectedOverlay=null;this.tooltip=null;this.hoverElement=null;this.selectedElement=null;this.hoverUpdateHandler=null;this.selectedUpdateHandler=null;this.createStyles()}createStyles(){if(document.getElementById("__nvwa-inspector-overlay-style"))return;let t=document.createElement("style");t.id="__nvwa-inspector-overlay-style",t.textContent=`
5
5
  .__nvwa-inspector-overlay {
6
6
  position: absolute;
7
7
  pointer-events: none;
@@ -33,4 +33,4 @@ ${l.stack}`)}else{var b;o=(b=n?.stack)!==null&&b!==void 0?b:""}let 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,n=window.scrollY||window.pageYOffset;r.width>0&&r.height>0?(t.style.left=`${r.left+i}px`,t.style.top=`${r.top+n}px`,t.style.width=`${r.width}px`,t.style.height=`${r.height}px`,t.style.display="block"):t.style.display="none"}removeOverlay(t){t&&t.parentNode&&t.parentNode.removeChild(t)}highlightElement(t,e){if(!t.isConnected)return;if(this.hoverElement===t&&this.hoverOverlay){this.updateOverlayPosition(this.hoverOverlay,t);let o=this.createTooltip();e?o.textContent=e:o.textContent=`<${t.tagName.toLowerCase()}> (\u65E0 source location)`,o.style.display="block";let h=t.getBoundingClientRect();o.style.left=`${h.left+window.scrollX}px`,o.style.top=`${h.top+window.scrollY-o.offsetHeight-8}px`,h.top<o.offsetHeight+8&&(o.style.top=`${h.bottom+window.scrollY+8}px`);return}this.hoverOverlay&&(this.removeOverlay(this.hoverOverlay),this.hoverOverlay=null);let r=this.createOverlay("hover");this.updateOverlayPosition(r,t),this.hoverOverlay=r,this.hoverElement=t;let i=()=>{this.hoverOverlay&&this.hoverElement&&this.hoverElement.isConnected&&this.updateOverlayPosition(this.hoverOverlay,this.hoverElement)};this.hoverUpdateHandler&&(window.removeEventListener("scroll",this.hoverUpdateHandler,!0),window.removeEventListener("resize",this.hoverUpdateHandler)),this.hoverUpdateHandler=i,window.addEventListener("scroll",i,!0),window.addEventListener("resize",i);let n=this.createTooltip();e?n.textContent=e:n.textContent=`<${t.tagName.toLowerCase()}> (\u65E0 source location)`,n.style.display="block";let a=t.getBoundingClientRect();n.style.left=`${a.left+window.scrollX}px`,n.style.top=`${a.top+window.scrollY-n.offsetHeight-8}px`,a.top<n.offsetHeight+8&&(n.style.top=`${a.bottom+window.scrollY+8}px`)}selectElement(t,e){if(!t.isConnected)return;if(this.selectedElement===t&&this.selectedOverlay){this.updateOverlayPosition(this.selectedOverlay,t);return}this.selectedOverlay&&(this.removeOverlay(this.selectedOverlay),this.selectedOverlay=null);let r=this.createOverlay("selected");this.updateOverlayPosition(r,t),this.selectedOverlay=r,this.selectedElement=t;let i=()=>{this.selectedOverlay&&this.selectedElement&&this.selectedElement.isConnected&&this.updateOverlayPosition(this.selectedOverlay,this.selectedElement)};this.selectedUpdateHandler&&(window.removeEventListener("scroll",this.selectedUpdateHandler,!0),window.removeEventListener("resize",this.selectedUpdateHandler)),this.selectedUpdateHandler=i,window.addEventListener("scroll",i,!0),window.addEventListener("resize",i)}removeHighlight(){this.hoverOverlay&&(this.removeOverlay(this.hoverOverlay),this.hoverOverlay=null),this.hoverElement&&(this.hoverElement=null),this.tooltip&&(this.tooltip.style.display="none"),this.hoverUpdateHandler&&(window.removeEventListener("scroll",this.hoverUpdateHandler,!0),window.removeEventListener("resize",this.hoverUpdateHandler),this.hoverUpdateHandler=null)}clearSelection(){this.selectedOverlay&&(this.removeOverlay(this.selectedOverlay),this.selectedOverlay=null),this.selectedElement&&(this.selectedElement=null),this.selectedUpdateHandler&&(window.removeEventListener("scroll",this.selectedUpdateHandler,!0),window.removeEventListener("resize",this.selectedUpdateHandler),this.selectedUpdateHandler=null)}cleanup(){this.removeHighlight(),this.clearSelection(),this.tooltip&&this.tooltip.parentNode&&(this.tooltip.parentNode.removeChild(this.tooltip),this.tooltip=null);let t=document.getElementById("__nvwa-inspector-overlay-style");t&&t.parentNode&&t.parentNode.removeChild(t)}};function zt(s="root"){if(typeof document>"u")return null;let t=document.getElementById(s)||document.body;if(!t)return null;let e=t.querySelector("[data-source-location]");if(e){let r=e.getAttribute("data-source-location");if(r)return r}if(t.firstElementChild){let i=t.firstElementChild.getAttribute("data-source-location");if(i)return i}return null}function Kt(s){let t=s;if(typeof t.kind=="string")return t;if(typeof t.tradeNO=="string")return{kind:"alipay_miniprogram",tradeNO:t.tradeNO};if(typeof t.clientSecret=="string")return{kind:"stripe_client_secret",clientSecret:t.clientSecret};if(typeof t.redirectUrl=="string")return{kind:"redirect_url",redirectUrl:t.redirectUrl};if(typeof t.formHtml=="string")return{kind:"alipay_page",formHtml:t.formHtml};if(typeof t.codeUrl=="string")return{kind:"wechat_native_qr",codeUrl:t.codeUrl};let e=t.jsapiPayParams??t;return typeof e.timeStamp=="string"&&typeof e.nonceStr=="string"&&typeof e.package=="string"&&typeof e.paySign=="string"&&typeof e.appId=="string"?{kind:"wechat_jsapi",mode:"jsapi",jsapiPayParams:{appId:e.appId,timeStamp:e.timeStamp,nonceStr:e.nonceStr,package:e.package,signType:e.signType??"RSA",paySign:e.paySign}}:null}function Vt(s,t,e){return t.requestPayment(s.payParams,e)}function ot(s,t){let e=s.replace(/\/$/,""),r=t.startsWith("/")?t:`/${t}`;return`${e}${r}`}var C=class{constructor(t,e,r){this.cache=null;this.baseUrl=t.replace(/\/$/,""),this.fetchImpl=e,this.context=r}get(){return this.cache?.snapshot??null}getIntegrationItem(t){let e=this.cache?.snapshot;return e?e.integrations.find(i=>i.integrationType===t)??null:null}getEnabledProviders(t){let e=this.getIntegrationItem(t);return!e?.enabled||!e.providers?.length?[]:e.providers.filter(r=>r.enabled)}clear(){this.cache=null}async load(t){let e=t??{},r=this.context.applicationCode.trim(),i=this.context.platformCode.trim();if(!r||!i)throw new Error("NvwaIntegrationSnapshot: applicationCode \u4E0E platformCode \u5728\u6784\u9020 IntegrationSnapshotContext \u65F6\u4E0D\u80FD\u4E3A\u7A7A");let a=this.context.locale?.trim().toLowerCase()==="en"?"en":"zh",o=`${r} ${i} ${a}`;if(!e.force&&this.cache?.key===o)return this.cache.snapshot;let c=`/nvwa/integration-snapshot?${new URLSearchParams({applicationCode:r,platformCode:i,locale:a}).toString()}`,l=ot(this.baseUrl,c),u=await this.fetchImpl(l,{credentials:"include",headers:{Accept:"application/json"}});if(!u.ok){let g=await u.text();throw new Error(`integration-snapshot: ${u.status} ${g||u.statusText}`)}let p=await u.json();return this.cache={key:o,snapshot:p},p}};export{T as AuthClient,d as CURRENT_JWT_KEY,at as ENTITIES_BASE_PATH,X as FILE_STORAGE_BASE_PATH,Q as GENERATE_UPLOAD_URL_PATH,f as Headers,w as LOGIN_TOKEN_KEY,O as LOGIN_USER_PROFILE_KEY,j as NvwaEdgeFunctions,G as NvwaFileStorage,W as NvwaHttpClient,C as NvwaIntegrationSnapshot,B as OverlayManager,A as Request,U as Response,H as SET_AUTH_TOKEN_HEADER,S as URL,Mt as createPostgrestClient,zt as getSourceLocationFromDOM,Kt as normalizePayParams,Vt as requestPaymentFromOrderResult};
36
+ `,document.head.appendChild(t)}createTooltip(){return this.tooltip?this.tooltip:(this.tooltip=document.createElement("div"),this.tooltip.id="__nvwa-inspector-tooltip",document.body.appendChild(this.tooltip),this.tooltip)}createOverlay(t){let e=document.createElement("div");return e.className=`__nvwa-inspector-overlay __nvwa-inspector-overlay-${t}`,document.body.appendChild(e),e}updateOverlayPosition(t,e){if(!e.isConnected)return;let r=e.getBoundingClientRect(),i=window.scrollX||window.pageXOffset,n=window.scrollY||window.pageYOffset;r.width>0&&r.height>0?(t.style.left=`${r.left+i}px`,t.style.top=`${r.top+n}px`,t.style.width=`${r.width}px`,t.style.height=`${r.height}px`,t.style.display="block"):t.style.display="none"}removeOverlay(t){t&&t.parentNode&&t.parentNode.removeChild(t)}highlightElement(t,e){if(!t.isConnected)return;if(this.hoverElement===t&&this.hoverOverlay){this.updateOverlayPosition(this.hoverOverlay,t);let o=this.createTooltip();e?o.textContent=e:o.textContent=`<${t.tagName.toLowerCase()}> (\u65E0 source location)`,o.style.display="block";let h=t.getBoundingClientRect();o.style.left=`${h.left+window.scrollX}px`,o.style.top=`${h.top+window.scrollY-o.offsetHeight-8}px`,h.top<o.offsetHeight+8&&(o.style.top=`${h.bottom+window.scrollY+8}px`);return}this.hoverOverlay&&(this.removeOverlay(this.hoverOverlay),this.hoverOverlay=null);let r=this.createOverlay("hover");this.updateOverlayPosition(r,t),this.hoverOverlay=r,this.hoverElement=t;let i=()=>{this.hoverOverlay&&this.hoverElement&&this.hoverElement.isConnected&&this.updateOverlayPosition(this.hoverOverlay,this.hoverElement)};this.hoverUpdateHandler&&(window.removeEventListener("scroll",this.hoverUpdateHandler,!0),window.removeEventListener("resize",this.hoverUpdateHandler)),this.hoverUpdateHandler=i,window.addEventListener("scroll",i,!0),window.addEventListener("resize",i);let n=this.createTooltip();e?n.textContent=e:n.textContent=`<${t.tagName.toLowerCase()}> (\u65E0 source location)`,n.style.display="block";let a=t.getBoundingClientRect();n.style.left=`${a.left+window.scrollX}px`,n.style.top=`${a.top+window.scrollY-n.offsetHeight-8}px`,a.top<n.offsetHeight+8&&(n.style.top=`${a.bottom+window.scrollY+8}px`)}selectElement(t,e){if(!t.isConnected)return;if(this.selectedElement===t&&this.selectedOverlay){this.updateOverlayPosition(this.selectedOverlay,t);return}this.selectedOverlay&&(this.removeOverlay(this.selectedOverlay),this.selectedOverlay=null);let r=this.createOverlay("selected");this.updateOverlayPosition(r,t),this.selectedOverlay=r,this.selectedElement=t;let i=()=>{this.selectedOverlay&&this.selectedElement&&this.selectedElement.isConnected&&this.updateOverlayPosition(this.selectedOverlay,this.selectedElement)};this.selectedUpdateHandler&&(window.removeEventListener("scroll",this.selectedUpdateHandler,!0),window.removeEventListener("resize",this.selectedUpdateHandler)),this.selectedUpdateHandler=i,window.addEventListener("scroll",i,!0),window.addEventListener("resize",i)}removeHighlight(){this.hoverOverlay&&(this.removeOverlay(this.hoverOverlay),this.hoverOverlay=null),this.hoverElement&&(this.hoverElement=null),this.tooltip&&(this.tooltip.style.display="none"),this.hoverUpdateHandler&&(window.removeEventListener("scroll",this.hoverUpdateHandler,!0),window.removeEventListener("resize",this.hoverUpdateHandler),this.hoverUpdateHandler=null)}clearSelection(){this.selectedOverlay&&(this.removeOverlay(this.selectedOverlay),this.selectedOverlay=null),this.selectedElement&&(this.selectedElement=null),this.selectedUpdateHandler&&(window.removeEventListener("scroll",this.selectedUpdateHandler,!0),window.removeEventListener("resize",this.selectedUpdateHandler),this.selectedUpdateHandler=null)}cleanup(){this.removeHighlight(),this.clearSelection(),this.tooltip&&this.tooltip.parentNode&&(this.tooltip.parentNode.removeChild(this.tooltip),this.tooltip=null);let t=document.getElementById("__nvwa-inspector-overlay-style");t&&t.parentNode&&t.parentNode.removeChild(t)}};function Qt(s="root"){if(typeof document>"u")return null;let t=document.getElementById(s)||document.body;if(!t)return null;let e=t.querySelector("[data-source-location]");if(e){let r=e.getAttribute("data-source-location");if(r)return r}if(t.firstElementChild){let i=t.firstElementChild.getAttribute("data-source-location");if(i)return i}return null}var ut={"wechat-pay":{id:"wechat-pay",name:"WeChat Pay",description:"WeChat payment for web and miniapp."},wechat_partner:{id:"wechat_partner",name:"WeChat Partner",description:"WeChat partner merchant onboarding."},alipay:{id:"alipay",name:"Alipay",description:"Alipay payment."},"alipay-miniprogram":{id:"alipay-miniprogram",name:"Alipay Mini Program",description:"Alipay mini program payment."},stripe:{id:"stripe",name:"Stripe",description:"Stripe payment."}};function te(s){let t=s;if(typeof t.kind=="string")return t;if(typeof t.tradeNO=="string")return{kind:"alipay_miniprogram",tradeNO:t.tradeNO};if(typeof t.clientSecret=="string")return{kind:"stripe_client_secret",clientSecret:t.clientSecret};if(typeof t.redirectUrl=="string")return{kind:"redirect_url",redirectUrl:t.redirectUrl};if(typeof t.formHtml=="string")return{kind:"alipay_page",formHtml:t.formHtml};if(typeof t.codeUrl=="string")return{kind:"wechat_native_qr",codeUrl:t.codeUrl};let e=t.jsapiPayParams??t;return typeof e.timeStamp=="string"&&typeof e.nonceStr=="string"&&typeof e.package=="string"&&typeof e.paySign=="string"&&typeof e.appId=="string"?{kind:"wechat_jsapi",mode:"jsapi",jsapiPayParams:{appId:e.appId,timeStamp:e.timeStamp,nonceStr:e.nonceStr,package:e.package,signType:e.signType??"RSA",paySign:e.paySign}}:null}function ee(s,t,e){return t.requestPayment(s.payParams,e)}async function re(s,t){let e=s.payment?.providers??{};return Object.entries(e).filter(([,r])=>r.enabled).map(([r])=>ut[r]??{id:r,name:r,description:""})}function x(s){return s&&typeof s=="object"?s:{}}function dt(s){let t=x(s),e=t.enabled===!0,r=String(t.oauthCredentialSource??"").toLowerCase();return r?{enabled:e,oauthCredentialSource:r==="custom"?"custom":"nvwa_default"}:{enabled:e}}function Y(s){let t=x(s),e=x(t.providers),r={};for(let[i,n]of Object.entries(e))r[i]=dt(n);return{providers:r}}function _(s){let t=x(s);return{socialLogin:Y(t.socialLogin),payment:Y(t.payment)}}function ne(s){if(!s?.trim())return _({});try{return _(JSON.parse(s))}catch{return _({})}}function ae(s,t){let e=s[t];return e?Object.entries(e.providers).filter(([,r])=>r.enabled).map(([r])=>r):[]}export{T as AuthClient,u as CURRENT_JWT_KEY,ct as ENTITIES_BASE_PATH,et as FILE_STORAGE_BASE_PATH,rt as GENERATE_UPLOAD_URL_PATH,f as Headers,v as LOGIN_TOKEN_KEY,O as LOGIN_USER_PROFILE_KEY,H as NvwaEdgeFunctions,F as NvwaFileStorage,q as NvwaHttpClient,D as OverlayManager,U as Request,N as Response,G as SET_AUTH_TOKEN_HEADER,S as URL,Yt as createPostgrestClient,ae as getEnabledProvidersByIntegration,re as getPaymentProvidersFromIntegrationProviders,Qt as getSourceLocationFromDOM,_ as normalizeIntegrationProvidersConfig,te as normalizePayParams,ne as parseIntegrationProvidersJson,ee as requestPaymentFromOrderResult};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nvwa-app/sdk-core",
3
- "version": "6.16.0",
3
+ "version": "6.18.0",
4
4
  "description": "NVWA跨端通用工具类核心接口",
5
5
  "main": "dist/index.js",
6
6
  "module": "dist/index.mjs",