@alter-ai/connect 0.10.0 → 0.11.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/README.md CHANGED
@@ -1,8 +1,8 @@
1
1
  # Alter Connect SDK
2
2
 
3
- A lightweight JavaScript SDK for embedding OAuth integrations into your application. The SDK opens a backend-served Connect UI in a popup — the backend handles auth, provider selection, branding, and OAuth, then sends results back via postMessage.
3
+ A lightweight JavaScript SDK for embedding OAuth integrations into an application. The SDK opens Alter Connect in a popup and reports the completed grants through typed callbacks.
4
4
 
5
- **~10KB minified | Zero dependencies | TypeScript included**
5
+ **Typed OAuth callbacks | Zod-validated payloads | TypeScript included**
6
6
 
7
7
  ## Quick Start
8
8
 
@@ -18,12 +18,12 @@ Or use via CDN:
18
18
  <script src="https://cdn.jsdelivr.net/npm/@alter-ai/connect@latest/dist/alter-connect.umd.js"></script>
19
19
  ```
20
20
 
21
- ### 2. Get a Session Token from Your Backend
21
+ ### 2. Get a Session Token from the Application Backend
22
22
 
23
- Your backend creates a short-lived session token using the [Alter SDK](https://www.npmjs.com/package/@alter-ai/alter-sdk):
23
+ The application backend creates a short-lived session token using the [Alter SDK](https://www.npmjs.com/package/@alter-ai/alter-sdk):
24
24
 
25
25
  ```typescript
26
- // YOUR backend (Node.js example using @alter-ai/alter-sdk)
26
+ // Application backend (Node.js example using @alter-ai/alter-sdk)
27
27
  import { App, CallerType } from "@alter-ai/alter-sdk";
28
28
 
29
29
  const alterApp = new App({
@@ -35,6 +35,14 @@ const alterApp = new App({
35
35
  const session = await alterApp.createConnectSession({
36
36
  allowedProviders: ["google", "slack", "github"],
37
37
  returnUrl: "https://yourapp.com/callback",
38
+ // Optional. When the user approves access, the Connect UI also lets them set
39
+ // their own usage limits on the connection being created — deny rules,
40
+ // human approval, time windows, request quotas, and operation/parameter
41
+ // rules. They can only narrow what they are granting, never widen it, and
42
+ // they can change or remove the limits later in their wallet.
43
+ //
44
+ // This step is enabled by default. To hide it, pass:
45
+ // allowUserPolicyRules: false,
38
46
  });
39
47
 
40
48
  const session_token = session.sessionToken;
@@ -48,27 +56,47 @@ import AlterConnect from '@alter-ai/connect';
48
56
  // Initialize SDK (no API key needed!)
49
57
  const alterConnect = AlterConnect.create();
50
58
 
51
- // Get session token from YOUR backend
52
- const { session_token } = await fetch('/api/alter/session').then(r => r.json());
59
+ const connectButton = document.querySelector('#connect-button');
60
+ if (!(connectButton instanceof HTMLButtonElement)) {
61
+ throw new Error('Connect button is missing');
62
+ }
63
+ connectButton.disabled = true;
64
+
65
+ // Prefetch before the user interacts. Browsers may block a popup opened only
66
+ // after an awaited network request has detached it from the click gesture.
67
+ let sessionToken = null;
68
+ fetch('/api/alter/session')
69
+ .then(response => response.json())
70
+ .then(({ session_token }) => {
71
+ sessionToken = session_token;
72
+ connectButton.disabled = false;
73
+ })
74
+ .catch(() => {
75
+ console.error('Unable to prepare the Connect session');
76
+ });
53
77
 
54
- // Open Connect UI
55
- await alterConnect.open({
56
- token: session_token,
57
- onSuccess: (connections) => {
58
- console.log('Connected!', connections);
59
- // Save each connection.grant_id to your database
60
- connections.forEach(conn => console.log(conn.provider, conn.grant_id));
61
- },
62
- onError: (error) => {
63
- console.error('Failed:', error);
64
- },
65
- onExit: () => {
66
- console.log('User closed the window');
67
- }
78
+ connectButton.addEventListener('click', () => {
79
+ if (!sessionToken) return;
80
+ void alterConnect.open({
81
+ token: sessionToken,
82
+ onSuccess: (connections, completion) => {
83
+ console.log('Connected!', connections);
84
+ connections.forEach(conn => console.log(conn.provider, conn.grant_id));
85
+ completion.failedGrants.forEach(failure => {
86
+ console.warn(failure.providerId, failure.reason, failure.message);
87
+ });
88
+ },
89
+ onError: (error) => {
90
+ console.error('Failed:', error);
91
+ },
92
+ onExit: () => {
93
+ console.log('User closed the window');
94
+ }
95
+ });
68
96
  });
69
97
  ```
70
98
 
71
- That's it! The SDK handles the OAuth flow, popup windows, mobile redirects, and all security.
99
+ The SDK handles the OAuth flow, popup windows, mobile redirects, and security checks.
72
100
 
73
101
  ## Framework Examples
74
102
 
@@ -163,7 +191,7 @@ const alterConnect = AlterConnect.create({
163
191
  |--------|------|-------------|---------|
164
192
  | `debug` | `boolean` | Enable debug logging | `false` |
165
193
 
166
- **Note:** Visual customization (colors, fonts, logo) is configured via the Developer Portal branding settings. The backend-served Connect UI applies your branding automatically.
194
+ **Note:** Visual customization (colors, fonts, logo) is configured via the Developer Portal branding settings. Alter Connect applies the configured branding automatically.
167
195
 
168
196
  ---
169
197
 
@@ -174,7 +202,7 @@ Opens the Connect UI. On desktop, opens a centered popup window (500x700px). On
174
202
  ```javascript
175
203
  await alterConnect.open({
176
204
  token: 'sess_abc123...',
177
- onSuccess: (connections) => { /* ... */ },
205
+ onSuccess: (connections, completion) => { /* ... */ },
178
206
  onError: (error) => { /* ... */ },
179
207
  onExit: () => { /* ... */ },
180
208
  onEvent: (eventName, metadata) => { /* ... */ }
@@ -183,46 +211,53 @@ await alterConnect.open({
183
211
 
184
212
  | Parameter | Type | Required | Description |
185
213
  |-----------|------|----------|-------------|
186
- | `token` | `string` | Yes | Session token from your backend |
187
- | `onSuccess` | `function` | Yes | Called with array of connections on success |
188
- | `onError` | `function` | No | Called when connection fails |
214
+ | `token` | `string` | Yes | Short-lived session token created by the application backend with an Alter SDK |
215
+ | `onSuccess` | `(grants, completion) => void` | Yes | Called with the legacy grants array and a typed completion object. `completion.failedGrants` identifies partial failures. |
216
+ | `onError` | `(error) => void` | No | Called when connection fails. A total usage-limit application failure has code `grant_policy_application_failed` and typed `failedGrants`. |
189
217
  | `onExit` | `function` | No | Called when user closes popup |
190
218
  | `onEvent` | `function` | No | Called for analytics events |
191
219
 
192
220
  **Upgrading from 0.8.x:** `open()` no longer accepts a `baseURL` option — the widget always opens against the production Alter host. A `baseURL` override is reserved for a future release but not currently supported; contact support if you need to target a non-production deployment.
193
221
 
194
- **Grants Array (onSuccess):**
222
+ **Completion data (`onSuccess`):**
195
223
 
196
- `onSuccess` receives an array of `Grant` objects (multi-provider flow):
224
+ For compatibility, the first argument remains an array of `Grant` objects. The
225
+ second argument makes partial completion explicit:
197
226
 
198
227
  ```typescript
199
- // Each connection in the array:
200
- {
201
- grant_id: string; // Unique ID - store this!
202
- provider: string; // e.g., 'google', 'slack'
203
- provider_name: string; // e.g., 'Google', 'Slack'
204
- account_identifier: string; // e.g., 'user@gmail.com'
205
- timestamp: string; // ISO 8601 timestamp
206
- operation: 'creation' | 'reauth';
207
- scopes: string[]; // Granted OAuth scopes
208
- status: 'active' | 'pending' | 'error';
209
- metadata?: {
210
- account_display_name?: string;
211
- account_email?: string;
212
- };
228
+ interface ConnectCompletion {
229
+ grants: Grant[];
230
+ failedGrants: Array<{
231
+ providerId: string;
232
+ reason: string;
233
+ message: string;
234
+ }>;
213
235
  }
214
236
  ```
215
237
 
238
+ `failedGrants` is empty for full success. When at least one provider succeeds,
239
+ it identifies any providers whose grants were revoked because the selected
240
+ usage limits could not be applied. Unknown `reason` strings are preserved.
241
+
216
242
  **Error Object (onError):**
217
243
 
218
244
  ```typescript
219
245
  {
220
- code: string; // e.g., 'invalid_token', 'popup_blocked'
221
- message: string; // Human-readable message
222
- details?: object; // Additional error context
246
+ code: string;
247
+ message: string;
248
+ details?: Record<string, unknown>;
249
+ failedGrants?: Array<{
250
+ providerId: string;
251
+ reason: string;
252
+ message: string;
253
+ }>;
223
254
  }
224
255
  ```
225
256
 
257
+ A completion with no successful grants and one or more failed grants invokes
258
+ `onError` with `code: "grant_policy_application_failed"` instead of reporting
259
+ bare success.
260
+
226
261
  ---
227
262
 
228
263
  ### `alterConnect.close()`
@@ -250,8 +285,9 @@ alterConnect.destroy();
250
285
  Register an event listener. Returns an unsubscribe function.
251
286
 
252
287
  ```javascript
253
- const unsubscribe = alterConnect.on('success', (connection) => {
254
- console.log('Connected:', connection);
288
+ const unsubscribe = alterConnect.on('success', (grants, completion) => {
289
+ console.log('Connected:', grants);
290
+ console.log('Providers not kept:', completion.failedGrants);
255
291
  });
256
292
 
257
293
  // Later: unsubscribe();
@@ -287,22 +323,21 @@ The SDK automatically detects mobile devices and switches to an optimized flow:
287
323
 
288
324
  | Device | Flow | How It Works |
289
325
  |--------|------|-------------|
290
- | Desktop | Popup | Opens centered popup (500x700px), communicates via postMessage |
326
+ | Desktop | Popup | Opens a centered popup (500x700px) and reports completion through callbacks |
291
327
  | Phone (<=480px) | Redirect | Full-page redirect, returns via URL params |
292
328
  | Tablet (portrait) | Redirect | Full-page redirect for better UX |
293
329
  | Tablet (landscape) | Popup | Uses popup flow like desktop |
294
330
 
295
331
  No code changes needed — the SDK handles device detection automatically.
296
332
 
297
- For mobile redirect flow, include a `return_url` when creating the session:
333
+ For mobile redirect flow, include a return URL when creating the session:
298
334
 
299
- ```javascript
300
- // Backend session creation with mobile support
301
- body: JSON.stringify({
302
- allowed_providers: ['google', 'slack'],
303
- allowed_origin: 'https://yourapp.com', // For desktop popup (postMessage)
304
- return_url: 'https://yourapp.com/' // For mobile redirect (return destination)
305
- })
335
+ ```typescript
336
+ const session = await alterApp.createConnectSession({
337
+ allowedProviders: ["google", "slack"],
338
+ allowedOrigin: "https://app.example.com",
339
+ returnUrl: "https://app.example.com/",
340
+ });
306
341
  ```
307
342
 
308
343
  ## Security
@@ -321,6 +356,7 @@ Full TypeScript definitions included:
321
356
  ```typescript
322
357
  import AlterConnect, {
323
358
  AlterConnectConfig,
359
+ ConnectCompletion,
324
360
  Grant,
325
361
  AlterError
326
362
  } from '@alter-ai/connect';
@@ -329,12 +365,15 @@ const alterConnect = AlterConnect.create({ debug: true });
329
365
 
330
366
  await alterConnect.open({
331
367
  token: sessionToken,
332
- onSuccess: (grants: Grant[]) => {
368
+ onSuccess: (grants: Grant[], completion: ConnectCompletion) => {
333
369
  for (const grant of grants) {
334
- console.log(grant.grant_id); // Store this in your DB!
370
+ console.log(grant.grant_id); // Store this in the application database
335
371
  console.log(grant.provider);
336
372
  console.log(grant.scopes);
337
373
  }
374
+ for (const failure of completion.failedGrants) {
375
+ console.warn(failure.providerId, failure.message);
376
+ }
338
377
  },
339
378
  onError: (error: AlterError) => {
340
379
  console.error(error.code, error.message);
@@ -344,13 +383,14 @@ await alterConnect.open({
344
383
 
345
384
  ## Bundle Size
346
385
 
347
- | Format | Size | Gzipped |
348
- |--------|------|---------|
349
- | **CJS** | ~10KB | ~3.5KB |
350
- | **ESM** | ~10KB | ~3.4KB |
351
- | **UMD** | ~11KB | ~3.5KB |
386
+ | Format | Minified size |
387
+ |--------|---------------|
388
+ | **CJS** | ~74KB |
389
+ | **ESM** | ~74KB |
390
+ | **UMD** | ~74KB |
352
391
 
353
- Zero runtime dependencies.
392
+ The package has one runtime dependency: Zod 4 validates complete OAuth
393
+ `postMessage` payloads before callback data is consumed.
354
394
 
355
395
  ## Browser Support
356
396
 
@@ -392,7 +432,7 @@ button.addEventListener('click', () => {
392
432
 
393
433
  **Problem:** CORS error when calling Alter API
394
434
 
395
- **Solution:** Session tokens should be created from your **backend**, not frontend. The SDK handles all frontend API calls.
435
+ **Solution:** Session tokens must be created by the application backend, not the frontend. The SDK handles the frontend flow.
396
436
 
397
437
  ## Support
398
438
 
@@ -1,2 +1,2 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});const e="https://backend.alterauth.com";function t(e,...t){e.debug&&console.log("[Alter Connect]",...t)}class s{constructor(){this.events=new Map}on(e,t){return this.events.has(e)||this.events.set(e,new Set),this.events.get(e).add(t),()=>this.off(e,t)}off(e,t){const s=this.events.get(e);s&&s.delete(t)}emit(e,...t){const s=this.events.get(e);s&&s.forEach(s=>{try{s(...t)}catch(t){console.error(`[Alter Connect] Error in event handler for '${e}':`,t)}})}removeAllListeners(e){e?this.events.delete(e):this.events.clear()}}class i{constructor(){this.state={isOpen:!1,sessionToken:null,error:null},this.listeners=new Set}getState(){return{...this.state}}get(e){return this.state[e]}setState(e){this.state={...this.state,...e},this.notifyListeners()}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}clearListeners(){this.listeners.clear()}notifyListeners(){const e=this.getState();this.listeners.forEach(t=>{try{t(e)}catch(e){console.error("[Alter Connect] Error in state listener:",e)}})}}function n(){const e=navigator.userAgent||navigator.vendor||window.opera||"",t=/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(e),s="ontouchstart"in window||navigator.maxTouchPoints>0||(navigator.msMaxTouchPoints??0)>0,i=window.innerWidth<=768;return t||s&&i}function r(){return n()&&window.innerWidth<=480?"phone":n()&&window.innerWidth>480&&window.innerWidth<=1024?"tablet":"desktop"}function o(e){return"reauth"===e?"reauth":"creation"}function a(e){return"pending"===e?"pending":"error"===e?"error":"active"}function h(e){sessionStorage.removeItem("alter_oauth_state");try{const t=new URL(e);window.history.replaceState({},document.title,t.pathname+t.search+t.hash)}catch{window.history.replaceState({},document.title,window.location.pathname)}}class c{constructor(t){this.popup=null,this.pollInterval=null,this.messageListener=null,this.settled=!1,this.options={baseURL:t.baseURL,onSuccess:t.onSuccess,onError:t.onError,onCancel:t.onCancel,popupWidth:t.popupWidth||500,popupHeight:t.popupHeight||700,debug:t.debug||!1,expectedOrigin:t.expectedOrigin||""};try{this.expectedOrigin=new URL(t.baseURL).origin}catch{throw new Error(`Invalid baseURL: "${t.baseURL}". Must be a full URL with protocol (e.g., "${e}").`)}}startOAuth(e){if(!this.options.expectedOrigin)try{const t=new URL(e);this.options.expectedOrigin=t.origin,this.log("Derived expected origin:",this.options.expectedOrigin)}catch{return this.log("Failed to parse OAuth URL for origin validation:",e),void this.options.onError({code:"invalid_oauth_url",message:"Failed to determine origin from OAuth URL. Cannot proceed securely."})}!function(){const e=r();return"phone"===e||"tablet"===e&&window.innerHeight>window.innerWidth}()?(this.log("Using popup flow for desktop"),this.openPopup(e)):(this.log("Using redirect flow for mobile device"),this.startRedirectFlow(e))}startRedirectFlow(e){this.log("Starting redirect flow:",e);const t={timestamp:Date.now(),returnUrl:window.location.href};try{sessionStorage.setItem("alter_oauth_state",JSON.stringify(t))}catch(e){return this.log("Failed to save state:",e),void this.options.onError({code:"redirect_error",message:"Failed to start OAuth flow: could not save session state",details:{error:e}})}window.location.href=e}static checkOAuthReturn(e,t){const s=sessionStorage.getItem("alter_oauth_state");if(!s)return!1;try{const i=JSON.parse(s);if(Date.now()-i.timestamp>3e5)return sessionStorage.removeItem("alter_oauth_state"),!1;const n=new URLSearchParams(window.location.search),r=n.get("alter_connect_success"),c=n.get("alter_connect_error");if("true"===r){const s=n.get("grant_id"),r=n.get("provider"),c=n.get("account_identifier");if(!s||!r||!c)return h(i.returnUrl),t({code:"invalid_response",message:"OAuth redirect returned incomplete grant data"}),!0;const l={grant_id:s,provider:r,provider_name:n.get("provider_name")||r,account_identifier:c,timestamp:n.get("timestamp")||(new Date).toISOString(),operation:o(n.get("operation")),scopes:n.get("scopes")?.split(",")||[],status:a(n.get("status"))};return h(i.returnUrl),e([l]),!0}if(c){const e={code:n.get("error_code")||"oauth_error",message:n.get("error_description")||"OAuth authorization failed"};return h(i.returnUrl),t(e),!0}return!1}catch(e){return console.error("[OAuth Handler] Failed to check OAuth return:",e),sessionStorage.removeItem("alter_oauth_state"),!1}}openPopup(e){const t=window.screenX+(window.outerWidth-this.options.popupWidth)/2,s=window.screenY+(window.outerHeight-this.options.popupHeight)/2,i=[`width=${this.options.popupWidth}`,`height=${this.options.popupHeight}`,`left=${t}`,`top=${s}`,"resizable=yes","scrollbars=yes","status=yes"].join(",");this.log("Opening OAuth popup:",e),this.popup=window.open(e,"alter_oauth_popup",i),this.popup?(this.startPolling(),this.setupMessageListener()):this.options.onError({code:"popup_blocked",message:"Popup was blocked by browser. Please allow popups for this site."})}close(){this.log("Closing OAuth handler"),this.popup&&!this.popup.closed&&this.popup.close(),this.popup=null,null!==this.pollInterval&&(clearInterval(this.pollInterval),this.pollInterval=null),this.messageListener&&(window.removeEventListener("message",this.messageListener),this.messageListener=null)}startPolling(){this.pollInterval=window.setInterval(()=>{this.settled||this.popup&&!this.popup.closed||(this.log("Popup closed by user"),this.settled=!0,this.close(),this.options.onCancel())},500)}setupMessageListener(){this.messageListener=e=>{if(this.settled)return;if(e.origin!==this.expectedOrigin)return void this.log("Rejected message from unexpected origin:",e.origin,"(expected:",this.expectedOrigin+")");this.log("Received message from",e.origin);const t=e.data;if(t&&"object"==typeof t)if("alter_connect_success"===t.type){this.log("OAuth success");const e=Array.isArray(t.grants)?t.grants:null;if(e){this.log("Multi-provider success:",e.length,"grants");const t=[];for(const s of e){const e=s.grant_id;e&&s.provider?t.push({grant_id:e,provider:s.provider,provider_name:s.provider_name||s.provider,account_identifier:s.account_identifier||"",timestamp:s.timestamp||(new Date).toISOString(),operation:o(s.operation),scopes:Array.isArray(s.scopes)?s.scopes:[],status:a(s.status),metadata:s.metadata}):this.log("Skipping invalid grant item:",s)}return 0===t.length?(this.settled=!0,this.close(),void this.options.onError({code:"invalid_response",message:"Server returned empty grants array"})):(this.settled=!0,this.close(),void this.options.onSuccess(t))}this.settled=!0,this.close(),this.options.onError({code:"invalid_response",message:"Server returned success without grants array"})}else if("alter_connect_error"===t.type){this.log("OAuth error");const e={code:t.error||"oauth_error",message:t.error_description||"OAuth authorization failed",details:t};this.settled=!0,this.close(),this.options.onError(e)}},window.addEventListener("message",this.messageListener)}log(...e){this.options.debug&&console.log("[OAuth Handler]",...e)}}const l="0.2.0";let d=!1;class u{constructor(n={}){if(this._oauthHandler=null,this._perOpenCleanups=[],function(e){if(void 0!==e.baseURL)throw e.baseURL,new Error("AlterConnectConfig.baseURL is reserved and not yet supported. Omit the field to use the production Alter host.")}(n),this.config=function(e){return{debug:e.debug??!1}}(n),this._baseURL=(n.baseURL??e).replace(/\/+$/,""),this._baseURL!==e&&!d){d=!0;const e=new URL(this._baseURL).origin;console.warn(`[alter-connect] Using non-default Alter host: ${e}. Unset baseURL in AlterConnect.create() for production.`)}this.eventEmitter=new s,this.stateManager=new i,this._isInitialized=!0,t(this.config,"Alter Connect SDK initialized",{version:l,baseURL:this._baseURL}),this.checkRedirectReturn()}checkRedirectReturn(){c.checkOAuthReturn(e=>{t(this.config,"OAuth redirect return - success:",e),this.eventEmitter.emit("success",e)},e=>{t(this.config,"OAuth redirect return - error:",e),this.eventEmitter.emit("error",e)})&&t(this.config,"OAuth redirect return detected and handled")}static create(e){return new u(e)}async open(e){if(!this._isInitialized)throw this.createError("sdk_destroyed","Cannot call open() - SDK instance has been destroyed");if(t(this.config,"Opening Connect UI"),!e.token||"string"!=typeof e.token)throw this.createError("invalid_options","Session token is required. Create one from your backend using POST /sdk/oauth/connect/session");if(!e.onSuccess||"function"!=typeof e.onSuccess)throw this.createError("invalid_options","onSuccess callback is required");if(this.isOpen())return void t(this.config,"Connect UI is already open");this._oauthHandler=new c({baseURL:this._baseURL,onSuccess:e=>{t(this.config,"OAuth success:",e),this.handleOAuthSuccess(e)},onError:e=>{t(this.config,"OAuth error:",e),this.handleOAuthError(e)},onCancel:()=>{t(this.config,"OAuth cancelled (popup closed)"),this.handleOAuthCancel()},popupWidth:500,popupHeight:700,debug:this.config.debug}),this.stateManager.setState({isOpen:!0,error:null,sessionToken:e.token}),this.registerEventHandlers(e);const s=`${this._baseURL}/sdk/oauth/connect#session=${encodeURIComponent(e.token)}`;t(this.config,"Connect URL:",s),this._oauthHandler.startOAuth(s),e.onEvent&&e.onEvent("connect_opened",{timestamp:(new Date).toISOString()}),t(this.config,"Connect UI opened successfully")}close(){if(!this._isInitialized)throw this.createError("sdk_destroyed","Cannot call close() - SDK instance has been destroyed");t(this.config,"Closing Connect UI"),this._oauthHandler&&(this._oauthHandler.close(),this._oauthHandler=null),this._perOpenCleanups.forEach(e=>e()),this._perOpenCleanups=[],this.stateManager.setState({isOpen:!1}),this.eventEmitter.emit("close")}destroy(){this._isInitialized&&(t(this.config,"Destroying SDK instance"),this._oauthHandler&&(this._oauthHandler.close(),this._oauthHandler=null),this.stateManager.get("isOpen")&&this.stateManager.setState({isOpen:!1}),this.eventEmitter.removeAllListeners(),this.stateManager.clearListeners(),this._isInitialized=!1)}on(e,t){if(!this._isInitialized)throw this.createError("sdk_destroyed","Cannot call on() - SDK instance has been destroyed");return this.eventEmitter.on(e,t)}off(e,t){if(!this._isInitialized)throw this.createError("sdk_destroyed","Cannot call off() - SDK instance has been destroyed");this.eventEmitter.off(e,t)}isOpen(){if(!this._isInitialized)throw this.createError("sdk_destroyed","Cannot call isOpen() - SDK instance has been destroyed");return this.stateManager.get("isOpen")}getVersion(){return l}cleanupHandler(){this._oauthHandler=null}handleOAuthSuccess(e){this.cleanupHandler(),this.eventEmitter.emit("success",e)}handleOAuthError(e){this.cleanupHandler(),this.stateManager.setState({error:e}),this.eventEmitter.emit("error",e)}handleOAuthCancel(){this.cleanupHandler(),this.eventEmitter.emit("exit")}registerEventHandlers(e){e.onSuccess&&this._perOpenCleanups.push(this.eventEmitter.on("success",t=>{e.onSuccess(t),this.close()})),e.onExit&&this._perOpenCleanups.push(this.eventEmitter.on("exit",()=>{e.onExit(),this.close()})),this._perOpenCleanups.push(this.eventEmitter.on("error",t=>{e.onError&&e.onError(t),this.close()})),e.onEvent&&this._perOpenCleanups.push(this.eventEmitter.on("event",(t,s)=>{e.onEvent(t,s)}))}createError(e,t,s){const i=new Error(t);return i.code=e,i.details=s,i}}exports.default=u;
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});const e="https://backend.alterauth.com";function t(e,...t){e.debug&&console.log("[Alter Connect]",...t)}class n{constructor(){this.events=new Map}on(e,t){return this.events.has(e)||this.events.set(e,new Set),this.events.get(e).add(t),()=>this.off(e,t)}off(e,t){const n=this.events.get(e);n&&n.delete(t)}emit(e,...t){const n=this.events.get(e);n&&n.forEach(n=>{try{n(...t)}catch(t){console.error(`[Alter Connect] Error in event handler for '${e}':`,t)}})}removeAllListeners(e){e?this.events.delete(e):this.events.clear()}}class r{constructor(){this.state={isOpen:!1,sessionToken:null,error:null},this.listeners=new Set}getState(){return{...this.state}}get(e){return this.state[e]}setState(e){this.state={...this.state,...e},this.notifyListeners()}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}clearListeners(){this.listeners.clear()}notifyListeners(){const e=this.getState();this.listeners.forEach(t=>{try{t(e)}catch(e){console.error("[Alter Connect] Error in state listener:",e)}})}}var o;function i(e,t,n){function r(n,r){if(n._zod||Object.defineProperty(n,"_zod",{value:{def:r,constr:s,traits:new Set},enumerable:!1}),n._zod.traits.has(e))return;n._zod.traits.add(e),t(n,r);const o=s.prototype,i=Object.keys(o);for(let e=0;e<i.length;e++){const t=i[e];t in n||(n[t]=o[t].bind(n))}}const o=n?.Parent??Object;class i extends o{}function s(e){var t;const o=n?.Parent?new i:this;r(o,e),(t=o._zod).deferred??(t.deferred=[]);for(const e of o._zod.deferred)e();return o}return Object.defineProperty(i,"name",{value:e}),Object.defineProperty(s,"init",{value:r}),Object.defineProperty(s,Symbol.hasInstance,{value:t=>!!(n?.Parent&&t instanceof n.Parent)||t?._zod?.traits?.has(e)}),Object.defineProperty(s,"name",{value:e}),s}class s extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class a extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name="ZodEncodeError"}}(o=globalThis).__zod_globalConfig??(o.__zod_globalConfig={});const c=globalThis.__zod_globalConfig;function u(e){return c}function d(e){const t=Object.values(e).filter(e=>"number"==typeof e);return Object.entries(e).filter(([e,n])=>-1===t.indexOf(+e)).map(([e,t])=>t)}function p(e,t){return"bigint"==typeof t?t.toString():t}function l(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function h(e){return null==e}function f(e){const t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}const m=Symbol("evaluating");function g(e,t,n){let r;Object.defineProperty(e,t,{get(){if(r!==m)return void 0===r&&(r=m,r=n()),r},set(n){Object.defineProperty(e,t,{value:n})},configurable:!0})}function _(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function v(...e){const t={};for(const n of e){const e=Object.getOwnPropertyDescriptors(n);Object.assign(t,e)}return Object.defineProperties({},t)}function y(e){return JSON.stringify(e)}const w="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function z(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}const b=l(()=>{if(c.jitless)return!1;if("undefined"!=typeof navigator&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(e){return!1}});function k(e){if(!1===z(e))return!1;const t=e.constructor;if(void 0===t)return!0;if("function"!=typeof t)return!0;const n=t.prototype;return!1!==z(n)&&!1!==Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")}function O(e){return k(e)?{...e}:Array.isArray(e)?[...e]:e instanceof Map?new Map(e):e instanceof Set?new Set(e):e}const $=new Set(["string","number","symbol"]);function S(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function E(e,t,n){const r=new e._zod.constr(t??e._zod.def);return t&&!n?.parent||(r._zod.parent=e),r}function Z(e){const t=e;if(!t)return{};if("string"==typeof t)return{error:()=>t};if(void 0!==t?.message){if(void 0!==t?.error)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,"string"==typeof t.error?{...t,error:()=>t.error}:t}function A(e,t=0){if(!0===e.aborted)return!0;for(let n=t;n<e.issues.length;n++)if(!0!==e.issues[n]?.continue)return!0;return!1}function x(e,t=0){if(!0===e.aborted)return!0;for(let n=t;n<e.issues.length;n++)if(!1===e.issues[n]?.continue)return!0;return!1}function P(e,t){return t.map(t=>{var n;return(n=t).path??(n.path=[]),t.path.unshift(e),t})}function T(e){return"string"==typeof e?e:e?.message}function I(e,t,n){const r=e.message?e.message:T(e.inst?._zod.def?.error?.(e))??T(t?.error?.(e))??T(n.customError?.(e))??T(n.localeError?.(e))??"Invalid input",{inst:o,continue:i,input:s,...a}=e;return a.path??(a.path=[]),a.message=r,t?.reportInput&&(a.input=s),a}function j(e){return Array.isArray(e)?"array":"string"==typeof e?"string":"unknown"}function R(...e){const[t,n,r]=e;return"string"==typeof t?{message:t,code:"custom",input:n,inst:r}:{...t}}const C=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,p,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},U=i("$ZodError",C),N=i("$ZodError",C,{Parent:Error});const L=e=>(t,n,r,o)=>{const i=r?{...r,async:!1}:{async:!1},a=t._zod.run({value:n,issues:[]},i);if(a instanceof Promise)throw new s;if(a.issues.length){const t=new(o?.Err??e)(a.issues.map(e=>I(e,i,u())));throw w(t,o?.callee),t}return a.value},D=e=>async(t,n,r,o)=>{const i=r?{...r,async:!0}:{async:!0};let s=t._zod.run({value:n,issues:[]},i);if(s instanceof Promise&&(s=await s),s.issues.length){const t=new(o?.Err??e)(s.issues.map(e=>I(e,i,u())));throw w(t,o?.callee),t}return s.value},J=e=>(t,n,r)=>{const o=r?{...r,async:!1}:{async:!1},i=t._zod.run({value:n,issues:[]},o);if(i instanceof Promise)throw new s;return i.issues.length?{success:!1,error:new(e??U)(i.issues.map(e=>I(e,o,u())))}:{success:!0,data:i.value}},F=J(N),M=e=>async(t,n,r)=>{const o=r?{...r,async:!0}:{async:!0};let i=t._zod.run({value:n,issues:[]},o);return i instanceof Promise&&(i=await i),i.issues.length?{success:!1,error:new e(i.issues.map(e=>I(e,o,u())))}:{success:!0,data:i.value}},W=M(N),H=e=>(t,n,r)=>{const o=r?{...r,direction:"backward"}:{direction:"backward"};return L(e)(t,n,o)},V=e=>(t,n,r)=>L(e)(t,n,r),K=e=>async(t,n,r)=>{const o=r?{...r,direction:"backward"}:{direction:"backward"};return D(e)(t,n,o)},B=e=>async(t,n,r)=>D(e)(t,n,r),q=e=>(t,n,r)=>{const o=r?{...r,direction:"backward"}:{direction:"backward"};return J(e)(t,n,o)},G=e=>(t,n,r)=>J(e)(t,n,r),Y=e=>async(t,n,r)=>{const o=r?{...r,direction:"backward"}:{direction:"backward"};return M(e)(t,n,o)},X=e=>async(t,n,r)=>M(e)(t,n,r),Q=/^[cC][0-9a-z]{6,}$/,ee=/^[0-9a-z]+$/,te=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,ne=/^[0-9a-vA-V]{20}$/,re=/^[A-Za-z0-9]{27}$/,oe=/^[a-zA-Z0-9_-]{21}$/,ie=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,se=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,ae=e=>e?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,ce=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;const ue=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,de=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,pe=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,le=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,he=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,fe=/^[A-Za-z0-9_-]*$/,me=/^https?$/,ge=/^\+[1-9]\d{6,14}$/,_e="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",ve=new RegExp(`^${_e}$`);function ye(e){const t="(?:[01]\\d|2[0-3]):[0-5]\\d";return"number"==typeof e.precision?-1===e.precision?`${t}`:0===e.precision?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}const we=/^[^A-Z]*$/,ze=/^[^a-z]*$/,be=i("$ZodCheck",(e,t)=>{var n;e._zod??(e._zod={}),e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),ke=i("$ZodCheckMaxLength",(e,t)=>{var n;be.init(e,t),(n=e._zod.def).when??(n.when=e=>{const t=e.value;return!h(t)&&void 0!==t.length}),e._zod.onattach.push(e=>{const n=e._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<n&&(e._zod.bag.maximum=t.maximum)}),e._zod.check=n=>{const r=n.value;if(r.length<=t.maximum)return;const o=j(r);n.issues.push({origin:o,code:"too_big",maximum:t.maximum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),Oe=i("$ZodCheckMinLength",(e,t)=>{var n;be.init(e,t),(n=e._zod.def).when??(n.when=e=>{const t=e.value;return!h(t)&&void 0!==t.length}),e._zod.onattach.push(e=>{const n=e._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>n&&(e._zod.bag.minimum=t.minimum)}),e._zod.check=n=>{const r=n.value;if(r.length>=t.minimum)return;const o=j(r);n.issues.push({origin:o,code:"too_small",minimum:t.minimum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),$e=i("$ZodCheckLengthEquals",(e,t)=>{var n;be.init(e,t),(n=e._zod.def).when??(n.when=e=>{const t=e.value;return!h(t)&&void 0!==t.length}),e._zod.onattach.push(e=>{const n=e._zod.bag;n.minimum=t.length,n.maximum=t.length,n.length=t.length}),e._zod.check=n=>{const r=n.value,o=r.length;if(o===t.length)return;const i=j(r),s=o>t.length;n.issues.push({origin:i,...s?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),Se=i("$ZodCheckStringFormat",(e,t)=>{var n,r;be.init(e,t),e._zod.onattach.push(e=>{const n=e._zod.bag;n.format=t.format,t.pattern&&(n.patterns??(n.patterns=new Set),n.patterns.add(t.pattern))}),t.pattern?(n=e._zod).check??(n.check=n=>{t.pattern.lastIndex=0,t.pattern.test(n.value)||n.issues.push({origin:"string",code:"invalid_format",format:t.format,input:n.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(r=e._zod).check??(r.check=()=>{})}),Ee=i("$ZodCheckRegex",(e,t)=>{Se.init(e,t),e._zod.check=n=>{t.pattern.lastIndex=0,t.pattern.test(n.value)||n.issues.push({origin:"string",code:"invalid_format",format:"regex",input:n.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),Ze=i("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=we),Se.init(e,t)}),Ae=i("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=ze),Se.init(e,t)}),xe=i("$ZodCheckIncludes",(e,t)=>{be.init(e,t);const n=S(t.includes),r=new RegExp("number"==typeof t.position?`^.{${t.position}}${n}`:n);t.pattern=r,e._zod.onattach.push(e=>{const t=e._zod.bag;t.patterns??(t.patterns=new Set),t.patterns.add(r)}),e._zod.check=n=>{n.value.includes(t.includes,t.position)||n.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:n.value,inst:e,continue:!t.abort})}}),Pe=i("$ZodCheckStartsWith",(e,t)=>{be.init(e,t);const n=new RegExp(`^${S(t.prefix)}.*`);t.pattern??(t.pattern=n),e._zod.onattach.push(e=>{const t=e._zod.bag;t.patterns??(t.patterns=new Set),t.patterns.add(n)}),e._zod.check=n=>{n.value.startsWith(t.prefix)||n.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:n.value,inst:e,continue:!t.abort})}}),Te=i("$ZodCheckEndsWith",(e,t)=>{be.init(e,t);const n=new RegExp(`.*${S(t.suffix)}$`);t.pattern??(t.pattern=n),e._zod.onattach.push(e=>{const t=e._zod.bag;t.patterns??(t.patterns=new Set),t.patterns.add(n)}),e._zod.check=n=>{n.value.endsWith(t.suffix)||n.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:n.value,inst:e,continue:!t.abort})}}),Ie=i("$ZodCheckOverwrite",(e,t)=>{be.init(e,t),e._zod.check=e=>{e.value=t.tx(e.value)}});class je{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if("function"==typeof e)return e(this,{execution:"sync"}),void e(this,{execution:"async"});const t=e.split("\n").filter(e=>e),n=Math.min(...t.map(e=>e.length-e.trimStart().length)),r=t.map(e=>e.slice(n)).map(e=>" ".repeat(2*this.indent)+e);for(const e of r)this.content.push(e)}compile(){const e=Function,t=this?.args;return new e(...t,[...(this?.content??[""]).map(e=>` ${e}`)].join("\n"))}}const Re={major:4,minor:4,patch:3},Ce=i("$ZodType",(e,t)=>{var n;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=Re;const r=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&r.unshift(e);for(const t of r)for(const n of t._zod.onattach)n(e);if(0===r.length)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{const t=(e,t,n)=>{let r,o=A(e);for(const i of t){if(i._zod.def.when){if(x(e))continue;if(!i._zod.def.when(e))continue}else if(o)continue;const t=e.issues.length,a=i._zod.check(e);if(a instanceof Promise&&!1===n?.async)throw new s;if(r||a instanceof Promise)r=(r??Promise.resolve()).then(async()=>{await a;e.issues.length!==t&&(o||(o=A(e,t)))});else{if(e.issues.length===t)continue;o||(o=A(e,t))}}return r?r.then(()=>e):e},n=(n,o,i)=>{if(A(n))return n.aborted=!0,n;const a=t(o,r,i);if(a instanceof Promise){if(!1===i.async)throw new s;return a.then(t=>e._zod.parse(t,i))}return e._zod.parse(a,i)};e._zod.run=(o,i)=>{if(i.skipChecks)return e._zod.parse(o,i);if("backward"===i.direction){const t=e._zod.parse({value:o.value,issues:[]},{...i,skipChecks:!0});return t instanceof Promise?t.then(e=>n(e,o,i)):n(t,o,i)}const a=e._zod.parse(o,i);if(a instanceof Promise){if(!1===i.async)throw new s;return a.then(e=>t(e,r,i))}return t(a,r,i)}}g(e,"~standard",()=>({validate:t=>{try{const n=F(e,t);return n.success?{value:n.data}:{issues:n.error?.issues}}catch(n){return W(e,t).then(e=>e.success?{value:e.data}:{issues:e.error?.issues})}},vendor:"zod",version:1}))}),Ue=i("$ZodString",(e,t)=>{var n;Ce.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??(n=e._zod.bag,new RegExp(`^${n?`[\\s\\S]{${n?.minimum??0},${n?.maximum??""}}`:"[\\s\\S]*"}$`)),e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=String(n.value)}catch(r){}return"string"==typeof n.value||n.issues.push({expected:"string",code:"invalid_type",input:n.value,inst:e}),n}}),Ne=i("$ZodStringFormat",(e,t)=>{Se.init(e,t),Ue.init(e,t)}),Le=i("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=se),Ne.init(e,t)}),De=i("$ZodUUID",(e,t)=>{if(t.version){const e={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(void 0===e)throw new Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=ae(e))}else t.pattern??(t.pattern=ae());Ne.init(e,t)}),Je=i("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=ce),Ne.init(e,t)}),Fe=i("$ZodURL",(e,t)=>{Ne.init(e,t),e._zod.check=n=>{try{const r=n.value.trim();if(!t.normalize&&t.protocol?.source===me.source&&!/^https?:\/\//i.test(r))return void n.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:n.value,inst:e,continue:!t.abort});const o=new URL(r);return t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(o.hostname)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:t.hostname.source,input:n.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(o.protocol.endsWith(":")?o.protocol.slice(0,-1):o.protocol)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:n.value,inst:e,continue:!t.abort})),void(t.normalize?n.value=o.href:n.value=r)}catch(r){n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:e,continue:!t.abort})}}}),Me=i("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Ne.init(e,t)}),We=i("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=oe),Ne.init(e,t)}),He=i("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=Q),Ne.init(e,t)}),Ve=i("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=ee),Ne.init(e,t)}),Ke=i("$ZodULID",(e,t)=>{t.pattern??(t.pattern=te),Ne.init(e,t)}),Be=i("$ZodXID",(e,t)=>{t.pattern??(t.pattern=ne),Ne.init(e,t)}),qe=i("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=re),Ne.init(e,t)}),Ge=i("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=function(e){const t=ye({precision:e.precision}),n=["Z"];e.local&&n.push(""),e.offset&&n.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");const r=`${t}(?:${n.join("|")})`;return new RegExp(`^${_e}T(?:${r})$`)}(t)),Ne.init(e,t)}),Ye=i("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=ve),Ne.init(e,t)}),Xe=i("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=new RegExp(`^${ye(t)}$`)),Ne.init(e,t)}),Qe=i("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=ie),Ne.init(e,t)}),et=i("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=ue),Ne.init(e,t),e._zod.bag.format="ipv4"}),tt=i("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=de),Ne.init(e,t),e._zod.bag.format="ipv6",e._zod.check=n=>{try{new URL(`http://[${n.value}]`)}catch{n.issues.push({code:"invalid_format",format:"ipv6",input:n.value,inst:e,continue:!t.abort})}}}),nt=i("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=pe),Ne.init(e,t)}),rt=i("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=le),Ne.init(e,t),e._zod.check=n=>{const r=n.value.split("/");try{if(2!==r.length)throw new Error;const[e,t]=r;if(!t)throw new Error;const n=Number(t);if(`${n}`!==t)throw new Error;if(n<0||n>128)throw new Error;new URL(`http://[${e}]`)}catch{n.issues.push({code:"invalid_format",format:"cidrv6",input:n.value,inst:e,continue:!t.abort})}}});function ot(e){if(""===e)return!0;if(/\s/.test(e))return!1;if(e.length%4!=0)return!1;try{return atob(e),!0}catch{return!1}}const it=i("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=he),Ne.init(e,t),e._zod.bag.contentEncoding="base64",e._zod.check=n=>{ot(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:e,continue:!t.abort})}});const st=i("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=fe),Ne.init(e,t),e._zod.bag.contentEncoding="base64url",e._zod.check=n=>{(function(e){if(!fe.test(e))return!1;const t=e.replace(/[-_]/g,e=>"-"===e?"+":"/");return ot(t.padEnd(4*Math.ceil(t.length/4),"="))})(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:e,continue:!t.abort})}}),at=i("$ZodE164",(e,t)=>{t.pattern??(t.pattern=ge),Ne.init(e,t)});const ct=i("$ZodJWT",(e,t)=>{Ne.init(e,t),e._zod.check=n=>{(function(e,t=null){try{const n=e.split(".");if(3!==n.length)return!1;const[r]=n;if(!r)return!1;const o=JSON.parse(atob(r));return!("typ"in o&&"JWT"!==o?.typ||!o.alg||t&&(!("alg"in o)||o.alg!==t))}catch{return!1}})(n.value,t.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:e,continue:!t.abort})}}),ut=i("$ZodUnknown",(e,t)=>{Ce.init(e,t),e._zod.parse=e=>e}),dt=i("$ZodNever",(e,t)=>{Ce.init(e,t),e._zod.parse=(t,n)=>(t.issues.push({expected:"never",code:"invalid_type",input:t.value,inst:e}),t)});function pt(e,t,n){e.issues.length&&t.issues.push(...P(n,e.issues)),t.value[n]=e.value}const lt=i("$ZodArray",(e,t)=>{Ce.init(e,t),e._zod.parse=(n,r)=>{const o=n.value;if(!Array.isArray(o))return n.issues.push({expected:"array",code:"invalid_type",input:o,inst:e}),n;n.value=Array(o.length);const i=[];for(let e=0;e<o.length;e++){const s=o[e],a=t.element._zod.run({value:s,issues:[]},r);a instanceof Promise?i.push(a.then(t=>pt(t,n,e))):pt(a,n,e)}return i.length?Promise.all(i).then(()=>n):n}});function ht(e,t,n,r,o,i){const s=n in r;if(e.issues.length){if(o&&i&&!s)return;t.issues.push(...P(n,e.issues))}s||o?void 0===e.value?s&&(t.value[n]=void 0):t.value[n]=e.value:e.issues.length||t.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[n]})}function ft(e){const t=Object.keys(e.shape);for(const n of t)if(!e.shape?.[n]?._zod?.traits?.has("$ZodType"))throw new Error(`Invalid element at key "${n}": expected a Zod schema`);const n=(r=e.shape,Object.keys(r).filter(e=>"optional"===r[e]._zod.optin&&"optional"===r[e]._zod.optout));var r;return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(n)}}function mt(e,t,n,r,o,i){const s=[],a=o.keySet,c=o.catchall._zod,u=c.def.type,d="optional"===c.optin,p="optional"===c.optout;for(const o in t){if("__proto__"===o)continue;if(a.has(o))continue;if("never"===u){s.push(o);continue}const i=c.run({value:t[o],issues:[]},r);i instanceof Promise?e.push(i.then(e=>ht(e,n,o,t,d,p))):ht(i,n,o,t,d,p)}return s.length&&n.issues.push({code:"unrecognized_keys",keys:s,input:t,inst:i}),e.length?Promise.all(e).then(()=>n):n}const gt=i("$ZodObject",(e,t)=>{Ce.init(e,t);const n=Object.getOwnPropertyDescriptor(t,"shape");if(!n?.get){const e=t.shape;Object.defineProperty(t,"shape",{get:()=>{const n={...e};return Object.defineProperty(t,"shape",{value:n}),n}})}const r=l(()=>ft(t));g(e._zod,"propValues",()=>{const e=t.shape,n={};for(const t in e){const r=e[t]._zod;if(r.values){n[t]??(n[t]=new Set);for(const e of r.values)n[t].add(e)}}return n});const o=z,i=t.catchall;let s;e._zod.parse=(t,n)=>{s??(s=r.value);const a=t.value;if(!o(a))return t.issues.push({expected:"object",code:"invalid_type",input:a,inst:e}),t;t.value={};const c=[],u=s.shape;for(const e of s.keys){const r=u[e],o="optional"===r._zod.optin,i="optional"===r._zod.optout,s=r._zod.run({value:a[e],issues:[]},n);s instanceof Promise?c.push(s.then(n=>ht(n,t,e,a,o,i))):ht(s,t,e,a,o,i)}return i?mt(c,a,t,n,r.value,e):c.length?Promise.all(c).then(()=>t):t}}),_t=i("$ZodObjectJIT",(e,t)=>{gt.init(e,t);const n=e._zod.parse,r=l(()=>ft(t));let o;const i=z,s=!c.jitless,a=s&&b.value,u=t.catchall;let d;e._zod.parse=(c,p)=>{d??(d=r.value);const l=c.value;return i(l)?s&&a&&!1===p?.async&&!0!==p.jitless?(o||(o=(e=>{const t=new je(["shape","payload","ctx"]),n=r.value,o=e=>{const t=y(e);return`shape[${t}]._zod.run({ value: input[${t}], issues: [] }, ctx)`};t.write("const input = payload.value;");const i=Object.create(null);let s=0;for(const e of n.keys)i[e]="key_"+s++;t.write("const newResult = {};");for(const r of n.keys){const n=i[r],s=y(r),a=e[r],c="optional"===a?._zod?.optin,u="optional"===a?._zod?.optout;t.write(`const ${n} = ${o(r)};`),c&&u?t.write(`\n if (${n}.issues.length) {\n if (${s} in input) {\n payload.issues = payload.issues.concat(${n}.issues.map(iss => ({\n ...iss,\n path: iss.path ? [${s}, ...iss.path] : [${s}]\n })));\n }\n }\n \n if (${n}.value === undefined) {\n if (${s} in input) {\n newResult[${s}] = undefined;\n }\n } else {\n newResult[${s}] = ${n}.value;\n }\n \n `):c?t.write(`\n if (${n}.issues.length) {\n payload.issues = payload.issues.concat(${n}.issues.map(iss => ({\n ...iss,\n path: iss.path ? [${s}, ...iss.path] : [${s}]\n })));\n }\n \n if (${n}.value === undefined) {\n if (${s} in input) {\n newResult[${s}] = undefined;\n }\n } else {\n newResult[${s}] = ${n}.value;\n }\n \n `):t.write(`\n const ${n}_present = ${s} in input;\n if (${n}.issues.length) {\n payload.issues = payload.issues.concat(${n}.issues.map(iss => ({\n ...iss,\n path: iss.path ? [${s}, ...iss.path] : [${s}]\n })));\n }\n if (!${n}_present && !${n}.issues.length) {\n payload.issues.push({\n code: "invalid_type",\n expected: "nonoptional",\n input: undefined,\n path: [${s}]\n });\n }\n\n if (${n}_present) {\n if (${n}.value === undefined) {\n newResult[${s}] = undefined;\n } else {\n newResult[${s}] = ${n}.value;\n }\n }\n\n `)}t.write("payload.value = newResult;"),t.write("return payload;");const a=t.compile();return(t,n)=>a(e,t,n)})(t.shape)),c=o(c,p),u?mt([],l,c,p,d,e):c):n(c,p):(c.issues.push({expected:"object",code:"invalid_type",input:l,inst:e}),c)}});function vt(e,t,n,r){for(const n of e)if(0===n.issues.length)return t.value=n.value,t;const o=e.filter(e=>!A(e));return 1===o.length?(t.value=o[0].value,o[0]):(t.issues.push({code:"invalid_union",input:t.value,inst:n,errors:e.map(e=>e.issues.map(e=>I(e,r,u())))}),t)}const yt=i("$ZodUnion",(e,t)=>{Ce.init(e,t),g(e._zod,"optin",()=>t.options.some(e=>"optional"===e._zod.optin)?"optional":void 0),g(e._zod,"optout",()=>t.options.some(e=>"optional"===e._zod.optout)?"optional":void 0),g(e._zod,"values",()=>{if(t.options.every(e=>e._zod.values))return new Set(t.options.flatMap(e=>Array.from(e._zod.values)))}),g(e._zod,"pattern",()=>{if(t.options.every(e=>e._zod.pattern)){const e=t.options.map(e=>e._zod.pattern);return new RegExp(`^(${e.map(e=>f(e.source)).join("|")})$`)}});const n=1===t.options.length?t.options[0]._zod.run:null;e._zod.parse=(r,o)=>{if(n)return n(r,o);let i=!1;const s=[];for(const e of t.options){const t=e._zod.run({value:r.value,issues:[]},o);if(t instanceof Promise)s.push(t),i=!0;else{if(0===t.issues.length)return t;s.push(t)}}return i?Promise.all(s).then(t=>vt(t,r,e,o)):vt(s,r,e,o)}}),wt=i("$ZodIntersection",(e,t)=>{Ce.init(e,t),e._zod.parse=(e,n)=>{const r=e.value,o=t.left._zod.run({value:r,issues:[]},n),i=t.right._zod.run({value:r,issues:[]},n);return o instanceof Promise||i instanceof Promise?Promise.all([o,i]).then(([t,n])=>bt(e,t,n)):bt(e,o,i)}});function zt(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e===+t)return{valid:!0,data:e};if(k(e)&&k(t)){const n=Object.keys(t),r=Object.keys(e).filter(e=>-1!==n.indexOf(e)),o={...e,...t};for(const n of r){const r=zt(e[n],t[n]);if(!r.valid)return{valid:!1,mergeErrorPath:[n,...r.mergeErrorPath]};o[n]=r.data}return{valid:!0,data:o}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};const n=[];for(let r=0;r<e.length;r++){const o=zt(e[r],t[r]);if(!o.valid)return{valid:!1,mergeErrorPath:[r,...o.mergeErrorPath]};n.push(o.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function bt(e,t,n){const r=new Map;let o;for(const n of t.issues)if("unrecognized_keys"===n.code){o??(o=n);for(const e of n.keys)r.has(e)||r.set(e,{}),r.get(e).l=!0}else e.issues.push(n);for(const t of n.issues)if("unrecognized_keys"===t.code)for(const e of t.keys)r.has(e)||r.set(e,{}),r.get(e).r=!0;else e.issues.push(t);const i=[...r].filter(([,e])=>e.l&&e.r).map(([e])=>e);if(i.length&&o&&e.issues.push({...o,keys:i}),A(e))return e;const s=zt(t.value,n.value);if(!s.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(s.mergeErrorPath)}`);return e.value=s.data,e}const kt=i("$ZodEnum",(e,t)=>{Ce.init(e,t);const n=d(t.entries),r=new Set(n);e._zod.values=r,e._zod.pattern=new RegExp(`^(${n.filter(e=>$.has(typeof e)).map(e=>"string"==typeof e?S(e):e.toString()).join("|")})$`),e._zod.parse=(t,o)=>{const i=t.value;return r.has(i)||t.issues.push({code:"invalid_value",values:n,input:i,inst:e}),t}}),Ot=i("$ZodLiteral",(e,t)=>{if(Ce.init(e,t),0===t.values.length)throw new Error("Cannot create literal schema with no valid values");const n=new Set(t.values);e._zod.values=n,e._zod.pattern=new RegExp(`^(${t.values.map(e=>"string"==typeof e?S(e):e?S(e.toString()):String(e)).join("|")})$`),e._zod.parse=(r,o)=>{const i=r.value;return n.has(i)||r.issues.push({code:"invalid_value",values:t.values,input:i,inst:e}),r}}),$t=i("$ZodTransform",(e,t)=>{Ce.init(e,t),e._zod.optin="optional",e._zod.parse=(n,r)=>{if("backward"===r.direction)throw new a(e.constructor.name);const o=t.transform(n.value,n);if(r.async){return(o instanceof Promise?o:Promise.resolve(o)).then(e=>(n.value=e,n.fallback=!0,n))}if(o instanceof Promise)throw new s;return n.value=o,n.fallback=!0,n}});function St(e,t){return void 0===t&&(e.issues.length||e.fallback)?{issues:[],value:void 0}:e}const Et=i("$ZodOptional",(e,t)=>{Ce.init(e,t),e._zod.optin="optional",e._zod.optout="optional",g(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),g(e._zod,"pattern",()=>{const e=t.innerType._zod.pattern;return e?new RegExp(`^(${f(e.source)})?$`):void 0}),e._zod.parse=(e,n)=>{if("optional"===t.innerType._zod.optin){const r=e.value,o=t.innerType._zod.run(e,n);return o instanceof Promise?o.then(e=>St(e,r)):St(o,r)}return void 0===e.value?e:t.innerType._zod.run(e,n)}}),Zt=i("$ZodExactOptional",(e,t)=>{Et.init(e,t),g(e._zod,"values",()=>t.innerType._zod.values),g(e._zod,"pattern",()=>t.innerType._zod.pattern),e._zod.parse=(e,n)=>t.innerType._zod.run(e,n)}),At=i("$ZodNullable",(e,t)=>{Ce.init(e,t),g(e._zod,"optin",()=>t.innerType._zod.optin),g(e._zod,"optout",()=>t.innerType._zod.optout),g(e._zod,"pattern",()=>{const e=t.innerType._zod.pattern;return e?new RegExp(`^(${f(e.source)}|null)$`):void 0}),g(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(e,n)=>null===e.value?e:t.innerType._zod.run(e,n)}),xt=i("$ZodDefault",(e,t)=>{Ce.init(e,t),e._zod.optin="optional",g(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(e,n)=>{if("backward"===n.direction)return t.innerType._zod.run(e,n);if(void 0===e.value)return e.value=t.defaultValue,e;const r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(e=>Pt(e,t)):Pt(r,t)}});function Pt(e,t){return void 0===e.value&&(e.value=t.defaultValue),e}const Tt=i("$ZodPrefault",(e,t)=>{Ce.init(e,t),e._zod.optin="optional",g(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(e,n)=>("backward"===n.direction||void 0===e.value&&(e.value=t.defaultValue),t.innerType._zod.run(e,n))}),It=i("$ZodNonOptional",(e,t)=>{Ce.init(e,t),g(e._zod,"values",()=>{const e=t.innerType._zod.values;return e?new Set([...e].filter(e=>void 0!==e)):void 0}),e._zod.parse=(n,r)=>{const o=t.innerType._zod.run(n,r);return o instanceof Promise?o.then(t=>jt(t,e)):jt(o,e)}});function jt(e,t){return e.issues.length||void 0!==e.value||e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t}),e}const Rt=i("$ZodCatch",(e,t)=>{Ce.init(e,t),e._zod.optin="optional",g(e._zod,"optout",()=>t.innerType._zod.optout),g(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(e,n)=>{if("backward"===n.direction)return t.innerType._zod.run(e,n);const r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(r=>(e.value=r.value,r.issues.length&&(e.value=t.catchValue({...e,error:{issues:r.issues.map(e=>I(e,n,u()))},input:e.value}),e.issues=[],e.fallback=!0),e)):(e.value=r.value,r.issues.length&&(e.value=t.catchValue({...e,error:{issues:r.issues.map(e=>I(e,n,u()))},input:e.value}),e.issues=[],e.fallback=!0),e)}}),Ct=i("$ZodPipe",(e,t)=>{Ce.init(e,t),g(e._zod,"values",()=>t.in._zod.values),g(e._zod,"optin",()=>t.in._zod.optin),g(e._zod,"optout",()=>t.out._zod.optout),g(e._zod,"propValues",()=>t.in._zod.propValues),e._zod.parse=(e,n)=>{if("backward"===n.direction){const r=t.out._zod.run(e,n);return r instanceof Promise?r.then(e=>Ut(e,t.in,n)):Ut(r,t.in,n)}const r=t.in._zod.run(e,n);return r instanceof Promise?r.then(e=>Ut(e,t.out,n)):Ut(r,t.out,n)}});function Ut(e,t,n){return e.issues.length?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues,fallback:e.fallback},n)}const Nt=i("$ZodReadonly",(e,t)=>{Ce.init(e,t),g(e._zod,"propValues",()=>t.innerType._zod.propValues),g(e._zod,"values",()=>t.innerType._zod.values),g(e._zod,"optin",()=>t.innerType?._zod?.optin),g(e._zod,"optout",()=>t.innerType?._zod?.optout),e._zod.parse=(e,n)=>{if("backward"===n.direction)return t.innerType._zod.run(e,n);const r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(Lt):Lt(r)}});function Lt(e){return e.value=Object.freeze(e.value),e}const Dt=i("$ZodCustom",(e,t)=>{be.init(e,t),Ce.init(e,t),e._zod.parse=(e,t)=>e,e._zod.check=n=>{const r=n.value,o=t.fn(r);if(o instanceof Promise)return o.then(t=>Jt(t,n,r,e));Jt(o,n,r,e)}});function Jt(e,t,n,r){if(!e){const e={code:"custom",input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(e.params=r._zod.def.params),t.issues.push(R(e))}}var Ft;class Mt{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...t){const n=t[0];return this._map.set(e,n),n&&"object"==typeof n&&"id"in n&&this._idmap.set(n.id,e),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(e){const t=this._map.get(e);return t&&"object"==typeof t&&"id"in t&&this._idmap.delete(t.id),this._map.delete(e),this}get(e){const t=e._zod.parent;if(t){const n={...this.get(t)??{}};delete n.id;const r={...n,...this._map.get(e)};return Object.keys(r).length?r:void 0}return this._map.get(e)}has(e){return this._map.has(e)}}(Ft=globalThis).__zod_globalRegistry??(Ft.__zod_globalRegistry=new Mt);const Wt=globalThis.__zod_globalRegistry;function Ht(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...Z(t)})}function Vt(e,t){return new ke({check:"max_length",...Z(t),maximum:e})}function Kt(e,t){return new Oe({check:"min_length",...Z(t),minimum:e})}function Bt(e,t){return new $e({check:"length_equals",...Z(t),length:e})}function qt(e){return new Ie({check:"overwrite",tx:e})}function Gt(e,t){const n=function(e,t){const n=new be({check:"custom",...Z(t)});return n._zod.check=e,n}(t=>(t.addIssue=e=>{if("string"==typeof e)t.issues.push(R(e,t.value,n._zod.def));else{const r=e;r.fatal&&(r.continue=!1),r.code??(r.code="custom"),r.input??(r.input=t.value),r.inst??(r.inst=n),r.continue??(r.continue=!n._zod.def.abort),t.issues.push(R(r))}},e(t.value,t)),t);return n}function Yt(e){let t=e?.target??"draft-2020-12";return"draft-4"===t&&(t="draft-04"),"draft-7"===t&&(t="draft-07"),{processors:e.processors??{},metadataRegistry:e?.metadata??Wt,target:t,unrepresentable:e?.unrepresentable??"throw",override:e?.override??(()=>{}),io:e?.io??"output",counter:0,seen:new Map,cycles:e?.cycles??"ref",reused:e?.reused??"inline",external:e?.external??void 0}}function Xt(e,t,n={path:[],schemaPath:[]}){var r;const o=e._zod.def,i=t.seen.get(e);if(i){i.count++;return n.schemaPath.includes(e)&&(i.cycle=n.path),i.schema}const s={schema:{},count:1,cycle:void 0,path:n.path};t.seen.set(e,s);const a=e._zod.toJSONSchema?.();if(a)s.schema=a;else{const r={...n,schemaPath:[...n.schemaPath,e],path:n.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,s.schema,r);else{const n=s.schema,i=t.processors[o.type];if(!i)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${o.type}`);i(e,t,n,r)}const i=e._zod.parent;i&&(s.ref||(s.ref=i),Xt(i,t,r),t.seen.get(i).isParent=!0)}const c=t.metadataRegistry.get(e);c&&Object.assign(s.schema,c),"input"===t.io&&tn(e)&&(delete s.schema.examples,delete s.schema.default),"input"===t.io&&"_prefault"in s.schema&&((r=s.schema).default??(r.default=s.schema._prefault)),delete s.schema._prefault;return t.seen.get(e).schema}function Qt(e,t){const n=e.seen.get(t);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");const r=new Map;for(const t of e.seen.entries()){const n=e.metadataRegistry.get(t[0])?.id;if(n){const e=r.get(n);if(e&&e!==t[0])throw new Error(`Duplicate schema id "${n}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);r.set(n,t[0])}}const o=t=>{if(t[1].schema.$ref)return;const r=t[1],{ref:o,defId:i}=(t=>{const r="draft-2020-12"===e.target?"$defs":"definitions";if(e.external){const n=e.external.registry.get(t[0])?.id,o=e.external.uri??(e=>e);if(n)return{ref:o(n)};const i=t[1].defId??t[1].schema.id??"schema"+e.counter++;return t[1].defId=i,{defId:i,ref:`${o("__shared")}#/${r}/${i}`}}if(t[1]===n)return{ref:"#"};const o=`#/${r}/`,i=t[1].schema.id??"__schema"+e.counter++;return{defId:i,ref:o+i}})(t);r.def={...r.schema},i&&(r.defId=i);const s=r.schema;for(const e in s)delete s[e];s.$ref=o};if("throw"===e.cycles)for(const t of e.seen.entries()){const e=t[1];if(e.cycle)throw new Error(`Cycle detected: #/${e.cycle?.join("/")}/<root>\n\nSet the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const n of e.seen.entries()){const r=n[1];if(t===n[0]){o(n);continue}if(e.external){const r=e.external.registry.get(n[0])?.id;if(t!==n[0]&&r){o(n);continue}}const i=e.metadataRegistry.get(n[0])?.id;i?o(n):(r.cycle||r.count>1&&"ref"===e.reused)&&o(n)}}function en(e,t){const n=e.seen.get(t);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");const r=t=>{const n=e.seen.get(t);if(null===n.ref)return;const o=n.def??n.schema,i={...o},s=n.ref;if(n.ref=null,s){r(s);const n=e.seen.get(s),a=n.schema;!a.$ref||"draft-07"!==e.target&&"draft-04"!==e.target&&"openapi-3.0"!==e.target?Object.assign(o,a):(o.allOf=o.allOf??[],o.allOf.push(a)),Object.assign(o,i);if(t._zod.parent===s)for(const e in o)"$ref"!==e&&"allOf"!==e&&(e in i||delete o[e]);if(a.$ref&&n.def)for(const e in o)"$ref"!==e&&"allOf"!==e&&e in n.def&&JSON.stringify(o[e])===JSON.stringify(n.def[e])&&delete o[e]}const a=t._zod.parent;if(a&&a!==s){r(a);const t=e.seen.get(a);if(t?.schema.$ref&&(o.$ref=t.schema.$ref,t.def))for(const e in o)"$ref"!==e&&"allOf"!==e&&e in t.def&&JSON.stringify(o[e])===JSON.stringify(t.def[e])&&delete o[e]}e.override({zodSchema:t,jsonSchema:o,path:n.path??[]})};for(const t of[...e.seen.entries()].reverse())r(t[0]);const o={};if("draft-2020-12"===e.target?o.$schema="https://json-schema.org/draft/2020-12/schema":"draft-07"===e.target?o.$schema="http://json-schema.org/draft-07/schema#":"draft-04"===e.target?o.$schema="http://json-schema.org/draft-04/schema#":e.target,e.external?.uri){const n=e.external.registry.get(t)?.id;if(!n)throw new Error("Schema is missing an `id` property");o.$id=e.external.uri(n)}Object.assign(o,n.def??n.schema);const i=e.metadataRegistry.get(t)?.id;void 0!==i&&o.id===i&&delete o.id;const s=e.external?.defs??{};for(const t of e.seen.entries()){const e=t[1];e.def&&e.defId&&(e.def.id===e.defId&&delete e.def.id,s[e.defId]=e.def)}e.external||Object.keys(s).length>0&&("draft-2020-12"===e.target?o.$defs=s:o.definitions=s);try{const n=JSON.parse(JSON.stringify(o));return Object.defineProperty(n,"~standard",{value:{...t["~standard"],jsonSchema:{input:nn(t,"input",e.processors),output:nn(t,"output",e.processors)}},enumerable:!1,writable:!1}),n}catch(e){throw new Error("Error converting schema to JSON.")}}function tn(e,t){const n=t??{seen:new Set};if(n.seen.has(e))return!1;n.seen.add(e);const r=e._zod.def;if("transform"===r.type)return!0;if("array"===r.type)return tn(r.element,n);if("set"===r.type)return tn(r.valueType,n);if("lazy"===r.type)return tn(r.getter(),n);if("promise"===r.type||"optional"===r.type||"nonoptional"===r.type||"nullable"===r.type||"readonly"===r.type||"default"===r.type||"prefault"===r.type)return tn(r.innerType,n);if("intersection"===r.type)return tn(r.left,n)||tn(r.right,n);if("record"===r.type||"map"===r.type)return tn(r.keyType,n)||tn(r.valueType,n);if("pipe"===r.type)return!!e._zod.traits.has("$ZodCodec")||(tn(r.in,n)||tn(r.out,n));if("object"===r.type){for(const e in r.shape)if(tn(r.shape[e],n))return!0;return!1}if("union"===r.type){for(const e of r.options)if(tn(e,n))return!0;return!1}if("tuple"===r.type){for(const e of r.items)if(tn(e,n))return!0;return!(!r.rest||!tn(r.rest,n))}return!1}const nn=(e,t,n={})=>r=>{const{libraryOptions:o,target:i}=r??{},s=Yt({...o??{},target:i,io:t,processors:n});return Xt(e,s),Qt(s,e),en(s,e)},rn={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},on=(e,t,n,r)=>{const o=e._zod.def;Xt(o.innerType,t,r);t.seen.get(e).ref=o.innerType},sn=i("ZodISODateTime",(e,t)=>{Ge.init(e,t),jn.init(e,t)});function an(e){return function(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...Z(t)})}(sn,e)}const cn=i("ZodISODate",(e,t)=>{Ye.init(e,t),jn.init(e,t)});function un(e){return function(e,t){return new e({type:"string",format:"date",check:"string_format",...Z(t)})}(cn,e)}const dn=i("ZodISOTime",(e,t)=>{Xe.init(e,t),jn.init(e,t)});function pn(e){return function(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...Z(t)})}(dn,e)}const ln=i("ZodISODuration",(e,t)=>{Qe.init(e,t),jn.init(e,t)});function hn(e){return function(e,t){return new e({type:"string",format:"duration",check:"string_format",...Z(t)})}(ln,e)}const fn=(e,t)=>{U.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:t=>function(e,t=e=>e.message){const n={_errors:[]},r=(e,o=[])=>{for(const i of e.issues)if("invalid_union"===i.code&&i.errors.length)i.errors.map(e=>r({issues:e},[...o,...i.path]));else if("invalid_key"===i.code)r({issues:i.issues},[...o,...i.path]);else if("invalid_element"===i.code)r({issues:i.issues},[...o,...i.path]);else{const e=[...o,...i.path];if(0===e.length)n._errors.push(t(i));else{let r=n,o=0;for(;o<e.length;){const n=e[o];o===e.length-1?(r[n]=r[n]||{_errors:[]},r[n]._errors.push(t(i))):r[n]=r[n]||{_errors:[]},r=r[n],o++}}}};return r(e),n}(e,t)},flatten:{value:t=>function(e,t=e=>e.message){const n={},r=[];for(const o of e.issues)o.path.length>0?(n[o.path[0]]=n[o.path[0]]||[],n[o.path[0]].push(t(o))):r.push(t(o));return{formErrors:r,fieldErrors:n}}(e,t)},addIssue:{value:t=>{e.issues.push(t),e.message=JSON.stringify(e.issues,p,2)}},addIssues:{value:t=>{e.issues.push(...t),e.message=JSON.stringify(e.issues,p,2)}},isEmpty:{get:()=>0===e.issues.length}})},mn=i("ZodError",fn,{Parent:Error}),gn=L(mn),_n=D(mn),vn=J(mn),yn=M(mn),wn=H(mn),zn=V(mn),bn=K(mn),kn=B(mn),On=q(mn),$n=G(mn),Sn=Y(mn),En=X(mn),Zn=new WeakMap;function An(e,t,n){const r=Object.getPrototypeOf(e);let o=Zn.get(r);if(o||(o=new Set,Zn.set(r,o)),!o.has(t)){o.add(t);for(const e in n){const t=n[e];Object.defineProperty(r,e,{configurable:!0,enumerable:!1,get(){const n=t.bind(this);return Object.defineProperty(this,e,{configurable:!0,writable:!0,enumerable:!0,value:n}),n},set(t){Object.defineProperty(this,e,{configurable:!0,writable:!0,enumerable:!0,value:t})}})}}}const xn=i("ZodType",(e,t)=>(Ce.init(e,t),Object.assign(e["~standard"],{jsonSchema:{input:nn(e,"input"),output:nn(e,"output")}}),e.toJSONSchema=((e,t={})=>n=>{const r=Yt({...n,processors:t});return Xt(e,r),Qt(r,e),en(r,e)})(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.parse=(t,n)=>gn(e,t,n,{callee:e.parse}),e.safeParse=(t,n)=>vn(e,t,n),e.parseAsync=async(t,n)=>_n(e,t,n,{callee:e.parseAsync}),e.safeParseAsync=async(t,n)=>yn(e,t,n),e.spa=e.safeParseAsync,e.encode=(t,n)=>wn(e,t,n),e.decode=(t,n)=>zn(e,t,n),e.encodeAsync=async(t,n)=>bn(e,t,n),e.decodeAsync=async(t,n)=>kn(e,t,n),e.safeEncode=(t,n)=>On(e,t,n),e.safeDecode=(t,n)=>$n(e,t,n),e.safeEncodeAsync=async(t,n)=>Sn(e,t,n),e.safeDecodeAsync=async(t,n)=>En(e,t,n),An(e,"ZodType",{check(...e){const t=this.def;return this.clone(v(t,{checks:[...t.checks??[],...e.map(e=>"function"==typeof e?{_zod:{check:e,def:{check:"custom"},onattach:[]}}:e)]}),{parent:!0})},with(...e){return this.check(...e)},clone(e,t){return E(this,e,t)},brand(){return this},register(e,t){return e.add(this,t),this},refine(e,t){return this.check(function(e,t={}){return function(e,t,n){return new e({type:"custom",check:"custom",fn:t,...Z(n)})}(Er,e,t)}(e,t))},superRefine(e,t){return this.check(function(e,t){return Gt(e,t)}(e,t))},overwrite(e){return this.check(qt(e))},optional(){return gr(this)},exactOptional(){return new _r({type:"optional",innerType:this})},nullable(){return yr(this)},nullish(){return gr(yr(this))},nonoptional(e){return function(e,t){return new br({type:"nonoptional",innerType:e,...Z(t)})}(this,e)},array(){return ir(this)},or(e){return new cr({type:"union",options:[this,e],...Z(t)});var t},and(e){return new ur({type:"intersection",left:this,right:e})},transform(e){return $r(this,new fr({type:"transform",transform:e}))},default(e){return t=e,new wr({type:"default",innerType:this,get defaultValue(){return"function"==typeof t?t():O(t)}});var t},prefault(e){return t=e,new zr({type:"prefault",innerType:this,get defaultValue(){return"function"==typeof t?t():O(t)}});var t},catch(e){return new kr({type:"catch",innerType:this,catchValue:"function"==typeof(t=e)?t:()=>t});var t},pipe(e){return $r(this,e)},readonly(){return new Sr({type:"readonly",innerType:this})},describe(e){const t=this.clone();return Wt.add(t,{description:e}),t},meta(...e){if(0===e.length)return Wt.get(this);const t=this.clone();return Wt.add(t,e[0]),t},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(e){return e(this)}}),Object.defineProperty(e,"description",{get:()=>Wt.get(e)?.description,configurable:!0}),e)),Pn=i("_ZodString",(e,t)=>{Ue.init(e,t),xn.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n)=>{const r=n;r.type="string";const{minimum:o,maximum:i,format:s,patterns:a,contentEncoding:c}=e._zod.bag;if("number"==typeof o&&(r.minLength=o),"number"==typeof i&&(r.maxLength=i),s&&(r.format=rn[s]??s,""===r.format&&delete r.format,"time"===s&&delete r.format),c&&(r.contentEncoding=c),a&&a.size>0){const e=[...a];1===e.length?r.pattern=e[0].source:e.length>1&&(r.allOf=[...e.map(e=>({..."draft-07"===t.target||"draft-04"===t.target||"openapi-3.0"===t.target?{type:"string"}:{},pattern:e.source}))])}})(e,t,n);const n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null,An(e,"_ZodString",{regex(...e){return this.check(function(e,t){return new Ee({check:"string_format",format:"regex",...Z(t),pattern:e})}(...e))},includes(...e){return this.check(function(e,t){return new xe({check:"string_format",format:"includes",...Z(t),includes:e})}(...e))},startsWith(...e){return this.check(function(e,t){return new Pe({check:"string_format",format:"starts_with",...Z(t),prefix:e})}(...e))},endsWith(...e){return this.check(function(e,t){return new Te({check:"string_format",format:"ends_with",...Z(t),suffix:e})}(...e))},min(...e){return this.check(Kt(...e))},max(...e){return this.check(Vt(...e))},length(...e){return this.check(Bt(...e))},nonempty(...e){return this.check(Kt(1,...e))},lowercase(e){return this.check(function(e){return new Ze({check:"string_format",format:"lowercase",...Z(e)})}(e))},uppercase(e){return this.check(function(e){return new Ae({check:"string_format",format:"uppercase",...Z(e)})}(e))},trim(){return this.check(qt(e=>e.trim()))},normalize(...e){return this.check(function(e){return qt(t=>t.normalize(e))}(...e))},toLowerCase(){return this.check(qt(e=>e.toLowerCase()))},toUpperCase(){return this.check(qt(e=>e.toUpperCase()))},slugify(){return this.check(qt(e=>function(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}(e)))}})}),Tn=i("ZodString",(e,t)=>{Ue.init(e,t),Pn.init(e,t),e.email=t=>e.check(function(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...Z(t)})}(Rn,t)),e.url=t=>e.check(function(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...Z(t)})}(Nn,t)),e.jwt=t=>e.check(function(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...Z(t)})}(Qn,t)),e.emoji=t=>e.check(function(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...Z(t)})}(Ln,t)),e.guid=t=>e.check(Ht(Cn,t)),e.uuid=t=>e.check(function(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...Z(t)})}(Un,t)),e.uuidv4=t=>e.check(function(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...Z(t)})}(Un,t)),e.uuidv6=t=>e.check(function(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...Z(t)})}(Un,t)),e.uuidv7=t=>e.check(function(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...Z(t)})}(Un,t)),e.nanoid=t=>e.check(function(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...Z(t)})}(Dn,t)),e.guid=t=>e.check(Ht(Cn,t)),e.cuid=t=>e.check(function(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...Z(t)})}(Jn,t)),e.cuid2=t=>e.check(function(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...Z(t)})}(Fn,t)),e.ulid=t=>e.check(function(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...Z(t)})}(Mn,t)),e.base64=t=>e.check(function(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...Z(t)})}(Gn,t)),e.base64url=t=>e.check(function(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...Z(t)})}(Yn,t)),e.xid=t=>e.check(function(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...Z(t)})}(Wn,t)),e.ksuid=t=>e.check(function(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...Z(t)})}(Hn,t)),e.ipv4=t=>e.check(function(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...Z(t)})}(Vn,t)),e.ipv6=t=>e.check(function(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...Z(t)})}(Kn,t)),e.cidrv4=t=>e.check(function(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...Z(t)})}(Bn,t)),e.cidrv6=t=>e.check(function(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...Z(t)})}(qn,t)),e.e164=t=>e.check(function(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...Z(t)})}(Xn,t)),e.datetime=t=>e.check(an(t)),e.date=t=>e.check(un(t)),e.time=t=>e.check(pn(t)),e.duration=t=>e.check(hn(t))});function In(e){return function(e,t){return new e({type:"string",...Z(t)})}(Tn,e)}const jn=i("ZodStringFormat",(e,t)=>{Ne.init(e,t),Pn.init(e,t)}),Rn=i("ZodEmail",(e,t)=>{Je.init(e,t),jn.init(e,t)}),Cn=i("ZodGUID",(e,t)=>{Le.init(e,t),jn.init(e,t)}),Un=i("ZodUUID",(e,t)=>{De.init(e,t),jn.init(e,t)}),Nn=i("ZodURL",(e,t)=>{Fe.init(e,t),jn.init(e,t)}),Ln=i("ZodEmoji",(e,t)=>{Me.init(e,t),jn.init(e,t)}),Dn=i("ZodNanoID",(e,t)=>{We.init(e,t),jn.init(e,t)}),Jn=i("ZodCUID",(e,t)=>{He.init(e,t),jn.init(e,t)}),Fn=i("ZodCUID2",(e,t)=>{Ve.init(e,t),jn.init(e,t)}),Mn=i("ZodULID",(e,t)=>{Ke.init(e,t),jn.init(e,t)}),Wn=i("ZodXID",(e,t)=>{Be.init(e,t),jn.init(e,t)}),Hn=i("ZodKSUID",(e,t)=>{qe.init(e,t),jn.init(e,t)}),Vn=i("ZodIPv4",(e,t)=>{et.init(e,t),jn.init(e,t)}),Kn=i("ZodIPv6",(e,t)=>{tt.init(e,t),jn.init(e,t)}),Bn=i("ZodCIDRv4",(e,t)=>{nt.init(e,t),jn.init(e,t)}),qn=i("ZodCIDRv6",(e,t)=>{rt.init(e,t),jn.init(e,t)}),Gn=i("ZodBase64",(e,t)=>{it.init(e,t),jn.init(e,t)}),Yn=i("ZodBase64URL",(e,t)=>{st.init(e,t),jn.init(e,t)}),Xn=i("ZodE164",(e,t)=>{at.init(e,t),jn.init(e,t)}),Qn=i("ZodJWT",(e,t)=>{ct.init(e,t),jn.init(e,t)}),er=i("ZodUnknown",(e,t)=>{ut.init(e,t),xn.init(e,t),e._zod.processJSONSchema=(e,t,n)=>{}});function tr(){return new er({type:"unknown"})}const nr=i("ZodNever",(e,t)=>{dt.init(e,t),xn.init(e,t),e._zod.processJSONSchema=(e,t,n)=>((e,t,n)=>{n.not={}})(0,0,t)});function rr(e){return function(e,t){return new e({type:"never",...Z(t)})}(nr,e)}const or=i("ZodArray",(e,t)=>{lt.init(e,t),xn.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const o=n,i=e._zod.def,{minimum:s,maximum:a}=e._zod.bag;"number"==typeof s&&(o.minItems=s),"number"==typeof a&&(o.maxItems=a),o.type="array",o.items=Xt(i.element,t,{...r,path:[...r.path,"items"]})})(e,t,n,r),e.element=t.element,An(e,"ZodArray",{min(e,t){return this.check(Kt(e,t))},nonempty(e){return this.check(Kt(1,e))},max(e,t){return this.check(Vt(e,t))},length(e,t){return this.check(Bt(e,t))},unwrap(){return this.element}})});function ir(e,t){return function(e,t,n){return new e({type:"array",element:t,...Z(n)})}(or,e,t)}const sr=i("ZodObject",(e,t)=>{_t.init(e,t),xn.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const o=n,i=e._zod.def;o.type="object",o.properties={};const s=i.shape;for(const e in s)o.properties[e]=Xt(s[e],t,{...r,path:[...r.path,"properties",e]});const a=new Set(Object.keys(s)),c=new Set([...a].filter(e=>{const n=i.shape[e]._zod;return"input"===t.io?void 0===n.optin:void 0===n.optout}));c.size>0&&(o.required=Array.from(c)),"never"===i.catchall?._zod.def.type?o.additionalProperties=!1:i.catchall?i.catchall&&(o.additionalProperties=Xt(i.catchall,t,{...r,path:[...r.path,"additionalProperties"]})):"output"===t.io&&(o.additionalProperties=!1)})(e,t,n,r),g(e,"shape",()=>t.shape),An(e,"ZodObject",{keyof(){return pr(Object.keys(this._zod.def.shape))},catchall(e){return this.clone({...this._zod.def,catchall:e})},passthrough(){return this.clone({...this._zod.def,catchall:tr()})},loose(){return this.clone({...this._zod.def,catchall:tr()})},strict(){return this.clone({...this._zod.def,catchall:rr()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(e){return function(e,t){if(!k(t))throw new Error("Invalid input to extend: expected a plain object");const n=e._zod.def.checks;if(n&&n.length>0){const n=e._zod.def.shape;for(const e in t)if(void 0!==Object.getOwnPropertyDescriptor(n,e))throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}const r=v(e._zod.def,{get shape(){const n={...e._zod.def.shape,...t};return _(this,"shape",n),n}});return E(e,r)}(this,e)},safeExtend(e){return function(e,t){if(!k(t))throw new Error("Invalid input to safeExtend: expected a plain object");const n=v(e._zod.def,{get shape(){const n={...e._zod.def.shape,...t};return _(this,"shape",n),n}});return E(e,n)}(this,e)},merge(e){return function(e,t){if(e._zod.def.checks?.length)throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");const n=v(e._zod.def,{get shape(){const n={...e._zod.def.shape,...t._zod.def.shape};return _(this,"shape",n),n},get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]});return E(e,n)}(this,e)},pick(e){return function(e,t){const n=e._zod.def,r=n.checks;if(r&&r.length>0)throw new Error(".pick() cannot be used on object schemas containing refinements");return E(e,v(e._zod.def,{get shape(){const e={};for(const r in t){if(!(r in n.shape))throw new Error(`Unrecognized key: "${r}"`);t[r]&&(e[r]=n.shape[r])}return _(this,"shape",e),e},checks:[]}))}(this,e)},omit(e){return function(e,t){const n=e._zod.def,r=n.checks;if(r&&r.length>0)throw new Error(".omit() cannot be used on object schemas containing refinements");const o=v(e._zod.def,{get shape(){const r={...e._zod.def.shape};for(const e in t){if(!(e in n.shape))throw new Error(`Unrecognized key: "${e}"`);t[e]&&delete r[e]}return _(this,"shape",r),r},checks:[]});return E(e,o)}(this,e)},partial(...e){return function(e,t,n){const r=t._zod.def.checks;if(r&&r.length>0)throw new Error(".partial() cannot be used on object schemas containing refinements");const o=v(t._zod.def,{get shape(){const r=t._zod.def.shape,o={...r};if(n)for(const t in n){if(!(t in r))throw new Error(`Unrecognized key: "${t}"`);n[t]&&(o[t]=e?new e({type:"optional",innerType:r[t]}):r[t])}else for(const t in r)o[t]=e?new e({type:"optional",innerType:r[t]}):r[t];return _(this,"shape",o),o},checks:[]});return E(t,o)}(mr,this,e[0])},required(...e){return function(e,t,n){const r=v(t._zod.def,{get shape(){const r=t._zod.def.shape,o={...r};if(n)for(const t in n){if(!(t in o))throw new Error(`Unrecognized key: "${t}"`);n[t]&&(o[t]=new e({type:"nonoptional",innerType:r[t]}))}else for(const t in r)o[t]=new e({type:"nonoptional",innerType:r[t]});return _(this,"shape",o),o}});return E(t,r)}(br,this,e[0])}})});function ar(e,t){const n={type:"object",shape:e??{},...Z(t)};return new sr(n)}const cr=i("ZodUnion",(e,t)=>{yt.init(e,t),xn.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const o=e._zod.def,i=!1===o.inclusive,s=o.options.map((e,n)=>Xt(e,t,{...r,path:[...r.path,i?"oneOf":"anyOf",n]}));i?n.oneOf=s:n.anyOf=s})(e,t,n,r),e.options=t.options});const ur=i("ZodIntersection",(e,t)=>{wt.init(e,t),xn.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const o=e._zod.def,i=Xt(o.left,t,{...r,path:[...r.path,"allOf",0]}),s=Xt(o.right,t,{...r,path:[...r.path,"allOf",1]}),a=e=>"allOf"in e&&1===Object.keys(e).length,c=[...a(i)?i.allOf:[i],...a(s)?s.allOf:[s]];n.allOf=c})(e,t,n,r)});const dr=i("ZodEnum",(e,t)=>{kt.init(e,t),xn.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n)=>{const r=d(e._zod.def.entries);r.every(e=>"number"==typeof e)&&(n.type="number"),r.every(e=>"string"==typeof e)&&(n.type="string"),n.enum=r})(e,0,n),e.enum=t.entries,e.options=Object.values(t.entries);const n=new Set(Object.keys(t.entries));e.extract=(e,r)=>{const o={};for(const r of e){if(!n.has(r))throw new Error(`Key ${r} not found in enum`);o[r]=t.entries[r]}return new dr({...t,checks:[],...Z(r),entries:o})},e.exclude=(e,r)=>{const o={...t.entries};for(const t of e){if(!n.has(t))throw new Error(`Key ${t} not found in enum`);delete o[t]}return new dr({...t,checks:[],...Z(r),entries:o})}});function pr(e,t){const n=Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e;return new dr({type:"enum",entries:n,...Z(t)})}const lr=i("ZodLiteral",(e,t)=>{Ot.init(e,t),xn.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n)=>{const r=e._zod.def,o=[];for(const e of r.values)if(void 0===e){if("throw"===t.unrepresentable)throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if("bigint"==typeof e){if("throw"===t.unrepresentable)throw new Error("BigInt literals cannot be represented in JSON Schema");o.push(Number(e))}else o.push(e);if(0===o.length);else if(1===o.length){const e=o[0];n.type=null===e?"null":typeof e,"draft-04"===t.target||"openapi-3.0"===t.target?n.enum=[e]:n.const=e}else o.every(e=>"number"==typeof e)&&(n.type="number"),o.every(e=>"string"==typeof e)&&(n.type="string"),o.every(e=>"boolean"==typeof e)&&(n.type="boolean"),o.every(e=>null===e)&&(n.type="null"),n.enum=o})(e,t,n),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function hr(e,t){return new lr({type:"literal",values:Array.isArray(e)?e:[e],...Z(t)})}const fr=i("ZodTransform",(e,t)=>{$t.init(e,t),xn.init(e,t),e._zod.processJSONSchema=(e,t,n)=>((e,t)=>{if("throw"===t.unrepresentable)throw new Error("Transforms cannot be represented in JSON Schema")})(0,e),e._zod.parse=(n,r)=>{if("backward"===r.direction)throw new a(e.constructor.name);n.addIssue=r=>{if("string"==typeof r)n.issues.push(R(r,n.value,t));else{const t=r;t.fatal&&(t.continue=!1),t.code??(t.code="custom"),t.input??(t.input=n.value),t.inst??(t.inst=e),n.issues.push(R(t))}};const o=t.transform(n.value,n);return o instanceof Promise?o.then(e=>(n.value=e,n.fallback=!0,n)):(n.value=o,n.fallback=!0,n)}});const mr=i("ZodOptional",(e,t)=>{Et.init(e,t),xn.init(e,t),e._zod.processJSONSchema=(t,n,r)=>on(e,t,0,r),e.unwrap=()=>e._zod.def.innerType});function gr(e){return new mr({type:"optional",innerType:e})}const _r=i("ZodExactOptional",(e,t)=>{Zt.init(e,t),xn.init(e,t),e._zod.processJSONSchema=(t,n,r)=>on(e,t,0,r),e.unwrap=()=>e._zod.def.innerType});const vr=i("ZodNullable",(e,t)=>{At.init(e,t),xn.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const o=e._zod.def,i=Xt(o.innerType,t,r),s=t.seen.get(e);"openapi-3.0"===t.target?(s.ref=o.innerType,n.nullable=!0):n.anyOf=[i,{type:"null"}]})(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function yr(e){return new vr({type:"nullable",innerType:e})}const wr=i("ZodDefault",(e,t)=>{xt.init(e,t),xn.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const o=e._zod.def;Xt(o.innerType,t,r),t.seen.get(e).ref=o.innerType,n.default=JSON.parse(JSON.stringify(o.defaultValue))})(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});const zr=i("ZodPrefault",(e,t)=>{Tt.init(e,t),xn.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const o=e._zod.def;Xt(o.innerType,t,r),t.seen.get(e).ref=o.innerType,"input"===t.io&&(n._prefault=JSON.parse(JSON.stringify(o.defaultValue)))})(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});const br=i("ZodNonOptional",(e,t)=>{It.init(e,t),xn.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const o=e._zod.def;Xt(o.innerType,t,r),t.seen.get(e).ref=o.innerType})(e,t,0,r),e.unwrap=()=>e._zod.def.innerType});const kr=i("ZodCatch",(e,t)=>{Rt.init(e,t),xn.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const o=e._zod.def;let i;Xt(o.innerType,t,r),t.seen.get(e).ref=o.innerType;try{i=o.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}n.default=i})(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});const Or=i("ZodPipe",(e,t)=>{Ct.init(e,t),xn.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const o=e._zod.def,i=o.in._zod.traits.has("$ZodTransform"),s="input"===t.io?i?o.out:o.in:o.out;Xt(s,t,r),t.seen.get(e).ref=s})(e,t,0,r),e.in=t.in,e.out=t.out});function $r(e,t){return new Or({type:"pipe",in:e,out:t})}const Sr=i("ZodReadonly",(e,t)=>{Nt.init(e,t),xn.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const o=e._zod.def;Xt(o.innerType,t,r),t.seen.get(e).ref=o.innerType,n.readOnly=!0})(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});const Er=i("ZodCustom",(e,t)=>{Dt.init(e,t),xn.init(e,t),e._zod.processJSONSchema=(e,t,n)=>((e,t)=>{if("throw"===t.unrepresentable)throw new Error("Custom types cannot be represented in JSON Schema")})(0,e)});function Zr(){const e=navigator.userAgent||navigator.vendor||window.opera||"",t=/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(e),n="ontouchstart"in window||navigator.maxTouchPoints>0||(navigator.msMaxTouchPoints??0)>0,r=window.innerWidth<=768;return t||n&&r}function Ar(){return Zr()&&window.innerWidth<=480?"phone":Zr()&&window.innerWidth>480&&window.innerWidth<=1024?"tablet":"desktop"}function xr(e){return"pending"===e?"pending":"error"===e?"error":"active"}const Pr=In().min(1),Tr=ar({account_display_name:In().optional(),account_email:In().optional()}).catchall(tr()),Ir=ar({grant_id:Pr,provider:Pr,provider_name:In().optional(),account_identifier:In().optional(),timestamp:In().optional(),operation:pr(["creation","reauth"]).optional().default("creation"),scopes:ir(In()).optional().default([]),status:pr(["active","pending","error"]).optional().default("active"),metadata:Tr.optional()}).transform(e=>{const t={grant_id:e.grant_id,provider:e.provider,provider_name:e.provider_name??e.provider,account_identifier:e.account_identifier??"",timestamp:e.timestamp??(new Date).toISOString(),operation:e.operation,scopes:e.scopes,status:e.status};return void 0!==e.metadata&&(t.metadata=e.metadata),t}),jr=ar({provider_id:Pr,reason:Pr,message:Pr}).transform(e=>({providerId:e.provider_id,reason:e.reason,message:e.message})),Rr=ar({type:pr(["alter_connect_success","alter_connect_error"])}),Cr=ar({type:hr("alter_connect_success"),grants:ir(Ir),failed_grants:ir(jr).optional().default([])}),Ur=ar({type:hr("alter_connect_error"),error:In().catch("oauth_error"),error_description:In().catch("OAuth authorization failed")}).loose();function Nr(e){const t=e.issues[0]?.path[0];return"failed_grants"===t?"Server returned malformed failed_grants data":"grants"===t&&1===e.issues[0]?.path.length?"Server returned success without grants array":"Server returned malformed grant data"}function Lr(e){sessionStorage.removeItem("alter_oauth_state");try{const t=new URL(e);window.history.replaceState({},document.title,t.pathname+t.search+t.hash)}catch{window.history.replaceState({},document.title,window.location.pathname)}}class Dr{constructor(t){this.popup=null,this.pollInterval=null,this.messageListener=null,this.settled=!1,this.options={baseURL:t.baseURL,onSuccess:t.onSuccess,onError:t.onError,onCancel:t.onCancel,popupWidth:t.popupWidth||500,popupHeight:t.popupHeight||700,debug:t.debug||!1,expectedOrigin:t.expectedOrigin||""};try{this.expectedOrigin=new URL(t.baseURL).origin}catch{throw new Error(`Invalid baseURL: "${t.baseURL}". Must be a full URL with protocol (e.g., "${e}").`)}}startOAuth(e){if(!this.options.expectedOrigin)try{const t=new URL(e);this.options.expectedOrigin=t.origin,this.log("Derived expected origin:",this.options.expectedOrigin)}catch{return this.log("Failed to parse OAuth URL for origin validation:",e),void this.options.onError({code:"invalid_oauth_url",message:"Failed to determine origin from OAuth URL. Cannot proceed securely."})}!function(){const e=Ar();return"phone"===e||"tablet"===e&&window.innerHeight>window.innerWidth}()?(this.log("Using popup flow for desktop"),this.openPopup(e)):(this.log("Using redirect flow for mobile device"),this.startRedirectFlow(e))}startRedirectFlow(e){this.log("Starting redirect flow:",e);const t={timestamp:Date.now(),returnUrl:window.location.href};try{sessionStorage.setItem("alter_oauth_state",JSON.stringify(t))}catch(e){return this.log("Failed to save state:",e),void this.options.onError({code:"redirect_error",message:"Failed to start OAuth flow: could not save session state",details:{error:e}})}window.location.href=e}static checkOAuthReturn(e,t){const n=sessionStorage.getItem("alter_oauth_state");if(!n)return!1;try{const o=JSON.parse(n);if(Date.now()-o.timestamp>3e5)return sessionStorage.removeItem("alter_oauth_state"),!1;const i=new URLSearchParams(window.location.search),s=i.get("alter_connect_success"),a=i.get("alter_connect_error");if("true"===s){const n=i.get("grant_id"),s=i.get("provider"),a=i.get("account_identifier");if(!n||!s||!a)return Lr(o.returnUrl),t({code:"invalid_response",message:"OAuth redirect returned incomplete grant data"}),!0;const c={grant_id:n,provider:s,provider_name:i.get("provider_name")||s,account_identifier:a,timestamp:i.get("timestamp")||(new Date).toISOString(),operation:(r=i.get("operation"),"reauth"===r?"reauth":"creation"),scopes:i.get("scopes")?.split(",")||[],status:xr(i.get("status"))};Lr(o.returnUrl);const u=[c];return e(u,{grants:u,failedGrants:[]}),!0}if(a){const e={code:i.get("error_code")||"oauth_error",message:i.get("error_description")||"OAuth authorization failed"};return Lr(o.returnUrl),t(e),!0}return!1}catch(e){return console.error("[OAuth Handler] Failed to check OAuth return:",e),sessionStorage.removeItem("alter_oauth_state"),!1}var r}openPopup(e){const t=window.screenX+(window.outerWidth-this.options.popupWidth)/2,n=window.screenY+(window.outerHeight-this.options.popupHeight)/2,r=[`width=${this.options.popupWidth}`,`height=${this.options.popupHeight}`,`left=${t}`,`top=${n}`,"resizable=yes","scrollbars=yes","status=yes"].join(",");this.log("Opening OAuth popup:",e),this.popup=window.open(e,"alter_oauth_popup",r),this.popup?(this.startPolling(),this.setupMessageListener()):this.options.onError({code:"popup_blocked",message:"Popup was blocked by browser. Please allow popups for this site."})}close(){this.log("Closing OAuth handler"),this.popup&&!this.popup.closed&&this.popup.close(),this.popup=null,null!==this.pollInterval&&(clearInterval(this.pollInterval),this.pollInterval=null),this.messageListener&&(window.removeEventListener("message",this.messageListener),this.messageListener=null)}startPolling(){this.pollInterval=window.setInterval(()=>{this.settled||this.popup&&!this.popup.closed||(this.log("Popup closed by user"),this.settled=!0,this.close(),this.options.onCancel())},500)}setupMessageListener(){this.messageListener=e=>{if(this.settled)return;if(e.origin!==this.expectedOrigin)return void this.log("Rejected message from unexpected origin:",e.origin,"(expected:",this.expectedOrigin+")");this.log("Received message from",e.origin);const t=Rr.safeParse(e.data);if(!t.success)return;if("alter_connect_success"===t.data.type){this.log("OAuth success");const t=Cr.safeParse(e.data);if(!t.success)return this.settled=!0,this.close(),void this.options.onError({code:"invalid_response",message:Nr(t.error)});const{grants:n,failed_grants:r}=t.data;if(this.log("Connect completion:",n.length,"grants"),0===n.length)return this.settled=!0,this.close(),void(r.length>0?this.options.onError({code:"grant_policy_application_failed",message:"The connection was not completed because the selected usage limits could not be applied.",failedGrants:r}):this.options.onError({code:"invalid_response",message:"Server returned empty grants array"}));const o={grants:n,failedGrants:r};return this.settled=!0,this.close(),void this.options.onSuccess(n,o)}const n=Ur.safeParse(e.data);if(n.success){this.log("OAuth error");const e={code:n.data.error,message:n.data.error_description,details:n.data};this.settled=!0,this.close(),this.options.onError(e)}},window.addEventListener("message",this.messageListener)}log(...e){this.options.debug&&console.log("[OAuth Handler]",...e)}}const Jr="0.2.0";let Fr=!1;class Mr{constructor(o={}){if(this._oauthHandler=null,this._perOpenCleanups=[],function(e){if(void 0!==e.baseURL)throw e.baseURL,new Error("AlterConnectConfig.baseURL is reserved and not yet supported. Omit the field to use the production Alter host.")}(o),this.config=function(e){return{debug:e.debug??!1}}(o),this._baseURL=(o.baseURL??e).replace(/\/+$/,""),this._baseURL!==e&&!Fr){Fr=!0;const e=new URL(this._baseURL).origin;console.warn(`[alter-connect] Using non-default Alter host: ${e}. Unset baseURL in AlterConnect.create() for production.`)}this.eventEmitter=new n,this.stateManager=new r,this._isInitialized=!0,t(this.config,"Alter Connect SDK initialized",{version:Jr,baseURL:this._baseURL}),this.checkRedirectReturn()}checkRedirectReturn(){Dr.checkOAuthReturn((e,n)=>{t(this.config,"OAuth redirect return - success:",e),this.eventEmitter.emit("success",e,n)},e=>{t(this.config,"OAuth redirect return - error:",e),this.eventEmitter.emit("error",e)})&&t(this.config,"OAuth redirect return detected and handled")}static create(e){return new Mr(e)}async open(e){if(!this._isInitialized)throw this.createError("sdk_destroyed","Cannot call open() - SDK instance has been destroyed");if(t(this.config,"Opening Connect UI"),!e.token||"string"!=typeof e.token)throw this.createError("invalid_options","Session token is required. Create one from the application backend with an Alter SDK.");if(!e.onSuccess||"function"!=typeof e.onSuccess)throw this.createError("invalid_options","onSuccess callback is required");if(this.isOpen())return void t(this.config,"Connect UI is already open");this._oauthHandler=new Dr({baseURL:this._baseURL,onSuccess:(e,n)=>{t(this.config,"OAuth success:",e),this.handleOAuthSuccess(e,n)},onError:e=>{t(this.config,"OAuth error:",e),this.handleOAuthError(e)},onCancel:()=>{t(this.config,"OAuth cancelled (popup closed)"),this.handleOAuthCancel()},popupWidth:500,popupHeight:700,debug:this.config.debug}),this.stateManager.setState({isOpen:!0,error:null,sessionToken:e.token}),this.registerEventHandlers(e);const n=`${this._baseURL}/sdk/oauth/connect#session=${encodeURIComponent(e.token)}`;t(this.config,"Connect URL:",n),this._oauthHandler.startOAuth(n),e.onEvent&&e.onEvent("connect_opened",{timestamp:(new Date).toISOString()}),t(this.config,"Connect UI opened successfully")}close(){if(!this._isInitialized)throw this.createError("sdk_destroyed","Cannot call close() - SDK instance has been destroyed");t(this.config,"Closing Connect UI"),this._oauthHandler&&(this._oauthHandler.close(),this._oauthHandler=null),this._perOpenCleanups.forEach(e=>e()),this._perOpenCleanups=[],this.stateManager.setState({isOpen:!1}),this.eventEmitter.emit("close")}destroy(){this._isInitialized&&(t(this.config,"Destroying SDK instance"),this._oauthHandler&&(this._oauthHandler.close(),this._oauthHandler=null),this.stateManager.get("isOpen")&&this.stateManager.setState({isOpen:!1}),this.eventEmitter.removeAllListeners(),this.stateManager.clearListeners(),this._isInitialized=!1)}on(e,t){if(!this._isInitialized)throw this.createError("sdk_destroyed","Cannot call on() - SDK instance has been destroyed");return this.eventEmitter.on(e,t)}off(e,t){if(!this._isInitialized)throw this.createError("sdk_destroyed","Cannot call off() - SDK instance has been destroyed");this.eventEmitter.off(e,t)}isOpen(){if(!this._isInitialized)throw this.createError("sdk_destroyed","Cannot call isOpen() - SDK instance has been destroyed");return this.stateManager.get("isOpen")}getVersion(){return Jr}cleanupHandler(){this._oauthHandler=null}handleOAuthSuccess(e,t){this.cleanupHandler(),this.eventEmitter.emit("success",e,t)}handleOAuthError(e){this.cleanupHandler(),this.stateManager.setState({error:e}),this.eventEmitter.emit("error",e)}handleOAuthCancel(){this.cleanupHandler(),this.eventEmitter.emit("exit")}registerEventHandlers(e){e.onSuccess&&this._perOpenCleanups.push(this.eventEmitter.on("success",(t,n)=>{e.onSuccess(t,n),this.close()})),e.onExit&&this._perOpenCleanups.push(this.eventEmitter.on("exit",()=>{e.onExit(),this.close()})),this._perOpenCleanups.push(this.eventEmitter.on("error",t=>{e.onError&&e.onError(t),this.close()})),e.onEvent&&this._perOpenCleanups.push(this.eventEmitter.on("event",(t,n)=>{e.onEvent(t,n)}))}createError(e,t,n){const r=new Error(t);return r.code=e,r.details=n,r}}exports.default=Mr;
2
2
  //# sourceMappingURL=alter-connect.cjs.js.map