@alter-ai/connect 0.12.1 → 0.13.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,6 +1,6 @@
1
1
  # Alter Connect SDK
2
2
 
3
- A lightweight JavaScript SDK for embedding OAuth integrations into an application. The SDK opens Alter Connect in a desktop popup, uses full-page navigation on mobile-classified devices, and validates completion data before invoking typed callbacks.
3
+ A lightweight JavaScript SDK for embedding OAuth integrations into an application. The SDK opens Alter Connect in a desktop popup, uses full-page navigation on mobile-classified devices, or renders inline inside an element the application provides, and validates completion data before invoking typed callbacks.
4
4
 
5
5
  **Typed OAuth callbacks | Zod-validated payloads | TypeScript included**
6
6
 
@@ -135,7 +135,7 @@ const alterConnect = AlterConnect.create({
135
135
 
136
136
  ### `alterConnect.open(options)`
137
137
 
138
- Attempts to open Connect. Desktop uses a centered popup window (500×700 px). Mobile-classified devices use full-page navigation, with the limitation documented under [Mobile behavior](#mobile-behavior).
138
+ Attempts to open Connect. Desktop uses a centered popup window (500×700 px). Mobile-classified devices use full-page navigation, with the limitation documented under [Mobile behavior](#mobile-behavior). Supplying `container` renders Connect inline inside that element on every device instead (see [Inline mode](#inline-embedded-mode)).
139
139
 
140
140
  ```javascript
141
141
  await alterConnect.open({
@@ -150,12 +150,27 @@ await alterConnect.open({
150
150
  | Parameter | Type | Required | Description |
151
151
  |-----------|------|----------|-------------|
152
152
  | `token` | `string` | Yes | Short-lived session token created by the application backend with an Alter SDK |
153
+ | `container` | `HTMLElement` | No | Render Connect inline inside this attached element instead of a popup window. The widget fills the element (350×300 px minimum recommended). The host page's origin must equal the session's allowed origin. |
154
+ | `direct` | `boolean` | No | Inline mode only: the session's `direct` flag (true for a single-provider session). Called from the user's click, the provider window opens immediately with a plain status line in the container; a blocked window falls back to the inline tile. |
153
155
  | `onSuccess` | `(grants, completion) => void` | Yes | Called with the legacy grants array and a typed completion object. `completion.failedGrants` identifies partial failures. |
154
156
  | `onError` | `(error) => void` | No | Called for failures delivered to the browser SDK, including a terminal provider denial (`code: "connect_denied"`). |
155
- | `onExit` | `function` | No | Called when the user closes the desktop popup; this does not mark the backend session denied |
156
- | `onEvent` | `(eventName, metadata) => void` | No | Called with `connect_opened` after each launch attempt (including a blocked popup), with `provider_declined` when the user refuses a provider in a session that can still continue, and with `provider_error` when the provider itself fails in such a session |
157
+ | `onExit` | `function` | No | Called when the user closes the desktop popup or presses Cancel inside the inline widget; this does not mark the backend session denied |
158
+ | `onEvent` | `(eventName, metadata) => void` | No | Called with `connect_opened` once a flow launches (`metadata.mode` names the flow: `popup`, `redirect`, or `embed`; a blocked popup reports `popup_blocked` through `onError` and no `connect_opened`), with `provider_declined` when the user refuses a provider in a session that can still continue, with `provider_error` when the provider itself fails in such a session, and with `embed_unsupported` when the inline widget had to fall back to a window |
157
159
 
158
- The promise resolves after the launch attempt, not after user authorization. Missing or invalid `token` or `onSuccess` values reject the returned promise with `code: "invalid_options"`. `baseURL` is not an `OpenOptions` field: TypeScript rejects it, while plain JavaScript ignores it.
160
+ The promise resolves after the launch attempt, not after user authorization. Missing or invalid `token` or `onSuccess` values reject the returned promise with `code: "invalid_options"`; a `container` that is not an element attached to the document rejects with `code: "invalid_container"`, and a host page with no `http(s)` origin, or one that is itself inside an iframe, rejects with `code: "embed_unsupported_origin"`. `baseURL` is not an `OpenOptions` field: TypeScript rejects it, while plain JavaScript ignores it.
161
+
162
+ #### Inline (embedded) mode
163
+
164
+ ```javascript
165
+ await alterConnect.open({
166
+ token: 'sess_abc123...',
167
+ container: document.getElementById('alter-connect'),
168
+ onSuccess: (grants, completion) => { /* ... */ },
169
+ onExit: () => { /* user pressed Cancel inside the widget */ },
170
+ });
171
+ ```
172
+
173
+ The hosted Connect UI renders inside `container`, which the application sizes. Provider sign-in cannot run inside a frame, so the widget opens it in a new window: from the application's own click when a single-provider session's `direct` flag is passed (no tile), otherwise from the user's click on the tile inside the widget; the widget updates when the window finishes; `open()` itself need not run inside a click handler in this mode. The widget carries its own Cancel control (`onExit`). Mobile devices use the inline widget too (never the full-page redirect). When the session's `direct` flag is not passed, or the browser blocked the window it tried to open, a session created for exactly one provider shows a single "Continue with" tile naming that provider; either way the connection confirms automatically after the provider returns. Browsers that refuse the widget's storage inside a frame are handled automatically: the widget offers "Continue in a new window" and completes there through the same callbacks (`onEvent` receives `embed_unsupported`).
159
174
 
160
175
  `onSuccess`, `onError`, and `onExit` run through the event emitter's exception
161
176
  guard. If one throws, the SDK logs the exception and still performs that
@@ -208,8 +223,9 @@ bare success.
208
223
  A provider denial is terminal only when the session has nothing left to try.
209
224
  Desktop delivers `code: "connect_denied"` to `onError` and the `error` event; a
210
225
  mobile flow with `returnUrl` delivers the same code to the returning page's
211
- `error` listener. If the session allows another provider, already authorized a
212
- grant, or still has an account the user has connected and can approve, Connect
226
+ `error` listener. If the session still offers a provider the user has not yet
227
+ declined, already authorized a grant, or still has an account the user has
228
+ connected and can approve, Connect
213
229
  returns to the picker and leaves backend polling pending so the user can
214
230
  continue — and reports the refusal as a non-terminal `provider_declined` event
215
231
  (`onEvent` and the `event` bus) rather than an error, because `onError` closes
@@ -224,8 +240,9 @@ browser chrome remains `onExit`; it is not a provider denial.
224
240
 
225
241
  ### `alterConnect.close()`
226
242
 
227
- Closes an active popup if one exists, stops the current flow handler, removes
228
- the current per-open callbacks, resets `isOpen()`, and emits `close`.
243
+ Closes an active popup (or removes the inline widget) if one exists, stops the
244
+ current flow handler, removes the current per-open callbacks, resets
245
+ `isOpen()`, and emits `close`.
229
246
 
230
247
  ```javascript
231
248
  alterConnect.close();
@@ -293,14 +310,14 @@ if (alterConnect.isOpen()) {
293
310
  Gets the SDK version.
294
311
 
295
312
  ```javascript
296
- console.log(alterConnect.getVersion()); // "0.2.0" in package 0.11.0
313
+ console.log(alterConnect.getVersion()); // "0.2.0" in package 0.12.2
297
314
  ```
298
315
 
299
316
  `getVersion()` reads a runtime constant embedded in the bundle. It does not currently match the package metadata version.
300
317
 
301
318
  ## Mobile behavior
302
319
 
303
- The SDK chooses the flow using user-agent, touch, viewport, and orientation checks:
320
+ Without a `container`, the SDK chooses the flow using user-agent, touch, viewport, and orientation checks:
304
321
 
305
322
  | Device | Flow | How It Works |
306
323
  |--------|------|-------------|
@@ -308,6 +325,7 @@ The SDK chooses the flow using user-agent, touch, viewport, and orientation chec
308
325
  | Mobile-classified viewport ≤480 px | Redirect | Navigates the full page to Connect |
309
326
  | Mobile-classified viewport 481–1024 px in portrait | Redirect | Navigates the full page to Connect |
310
327
  | Other devices | Popup | Uses the desktop callback flow |
328
+ | Any device, `container` supplied | Inline | Renders the hosted UI inside the element; provider sign-in opens in a new window (a new tab on phones) and the widget reports completion through callbacks |
311
329
 
312
330
  **Redirect completion:** full-page navigation destroys the callbacks and listeners registered by the original page. Set `returnUrl` on the session and Connect navigates back to it with the outcome, which is delivered to the callbacks registered on the instance constructed by the returning page. Callback parameters that do not carry the per-flow value the SDK minted are ignored. Sessions created without a `returnUrl`, and returns arriving more than five minutes after the flow started, complete through `createConnectSession()` plus `pollConnectSession()` on the application backend.
313
331
 
@@ -325,6 +343,7 @@ from a session that was first observed pending and later expired.
325
343
 
326
344
  - **API keys stay on the backend.** The frontend only receives a short-lived session token minted by the application backend.
327
345
  - **No API keys or provider credentials in the browser.** The frontend receives only the short-lived Connect session token.
346
+ - **The inline widget is isolated from the host page.** It renders on Alter's origin inside a frame the host page cannot read, accepts only the session's allowed origin as its parent, and only hands the outcome to that origin. Provider sign-in always runs in a top-level window.
328
347
 
329
348
  ## Provider selection
330
349
 
@@ -413,6 +432,24 @@ button.addEventListener('click', () => {
413
432
  });
414
433
  ```
415
434
 
435
+ ### Inline Widget Shows An Error
436
+
437
+ **Problem:** `open({ container })` mounts the widget, it renders an error, and `onError` fires with `code: "embed_origin_mismatch"`
438
+
439
+ **Solution:** The host page's origin must equal the session's allowed origin (`allowedOrigin` at session creation, or the origin of the app's Website URL when it is omitted). Pass the exact origin of the page that embeds the widget.
440
+
441
+ ### Inline Widget Never Loads
442
+
443
+ **Problem:** `open({ container })` mounts the widget, it stays empty, and `onError` fires with `code: "embed_load_timeout"` after 15 seconds
444
+
445
+ **Solution:** The frame delivered no message: the browser refused the hosted page, it failed to load, or the Alter host was unreachable. Confirm the page is served over `http(s)` at the session's allowed origin and is not itself inside an iframe (a nested host page rejects `open()` with `code: "embed_unsupported_origin"` up front), then mint a fresh session and retry.
446
+
447
+ ### Provider Window Did Not Open (Inline Mode)
448
+
449
+ **Problem:** Clicking a provider inside the inline widget does nothing
450
+
451
+ **Solution:** The widget opens the provider sign-in in a new window from that click; if the browser blocks it, the widget shows a message asking to allow pop-ups for the site and the click can be retried.
452
+
416
453
  ### Session Token Expired
417
454
 
418
455
  **Problem:** The hosted Connect page reports that the session expired or is invalid
@@ -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 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)}hasListeners(e){const t=this.events.get(e);return void 0!==t&&t.size>0}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 s{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 r;function o(e,t,n){function s(n,s){if(n._zod||Object.defineProperty(n,"_zod",{value:{def:s,constr:i,traits:new Set},enumerable:!1}),n._zod.traits.has(e))return;n._zod.traits.add(e),t(n,s);const r=i.prototype,o=Object.keys(r);for(let e=0;e<o.length;e++){const t=o[e];t in n||(n[t]=r[t].bind(n))}}const r=n?.Parent??Object;class o extends r{}function i(e){var t;const r=n?.Parent?new o:this;s(r,e),(t=r._zod).deferred??(t.deferred=[]);for(const e of r._zod.deferred)e();return r}return Object.defineProperty(o,"name",{value:e}),Object.defineProperty(i,"init",{value:s}),Object.defineProperty(i,Symbol.hasInstance,{value:t=>!!(n?.Parent&&t instanceof n.Parent)||t?._zod?.traits?.has(e)}),Object.defineProperty(i,"name",{value:e}),i}class i 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"}}(r=globalThis).__zod_globalConfig??(r.__zod_globalConfig={});const c=globalThis.__zod_globalConfig;function u(e){return c}function l(e,t){return"bigint"==typeof t?t.toString():t}const d=Symbol("evaluating");function h(e,t,n){let s;Object.defineProperty(e,t,{get(){if(s!==d)return void 0===s&&(s=d,s=n()),s},set(n){Object.defineProperty(e,t,{value:n})},configurable:!0})}const p="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function f(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function g(e){if(!1===f(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!==f(n)&&!1!==Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")}const m=new Set(["string","number","symbol"]);function v(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function _(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 y(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 w(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 b(e,t){return t.map(t=>{var n;return(n=t).path??(n.path=[]),t.path.unshift(e),t})}function z(e){return"string"==typeof e?e:e?.message}function O(e,t,n){const s=e.message?e.message:z(e.inst?._zod.def?.error?.(e))??z(t?.error?.(e))??z(n.customError?.(e))??z(n.localeError?.(e))??"Invalid input",{inst:r,continue:o,input:i,...a}=e;return a.path??(a.path=[]),a.message=s,t?.reportInput&&(a.input=i),a}const k=(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,l,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},E=o("$ZodError",k),S=o("$ZodError",k,{Parent:Error}),A=(e=>(t,n,s,r)=>{const o=s?{...s,async:!1}:{async:!1},a=t._zod.run({value:n,issues:[]},o);if(a instanceof Promise)throw new i;if(a.issues.length){const t=new(r?.Err??e)(a.issues.map(e=>O(e,o,u())));throw p(t,r?.callee),t}return a.value})(S),P=e=>async(t,n,s,r)=>{const o=s?{...s,async:!0}:{async:!0};let i=t._zod.run({value:n,issues:[]},o);if(i instanceof Promise&&(i=await i),i.issues.length){const t=new(r?.Err??e)(i.issues.map(e=>O(e,o,u())));throw p(t,r?.callee),t}return i.value},R=P(S),U=(e=>(t,n,s)=>{const r=s?{...s,async:!1}:{async:!1},o=t._zod.run({value:n,issues:[]},r);if(o instanceof Promise)throw new i;return o.issues.length?{success:!1,error:new(e??E)(o.issues.map(e=>O(e,r,u())))}:{success:!0,data:o.value}})(S),L=(e=>async(t,n,s)=>{const r=s?{...s,async:!0}:{async:!0};let o=t._zod.run({value:n,issues:[]},r);return o instanceof Promise&&(o=await o),o.issues.length?{success:!1,error:new e(o.issues.map(e=>O(e,r,u())))}:{success:!0,data:o.value}})(S),C=/^-?\d+(?:\.\d+)?$/,T=o("$ZodCheck",(e,t)=>{var n;e._zod??(e._zod={}),e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),$=o("$ZodCheckMinLength",(e,t)=>{var n;T.init(e,t),(n=e._zod.def).when??(n.when=e=>{const t=e.value;return!(n=t,null==n||void 0===t.length);var n}),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 s=n.value;if(s.length>=t.minimum)return;const r=function(e){return Array.isArray(e)?"array":"string"==typeof e?"string":"unknown"}(s);n.issues.push({origin:r,code:"too_small",minimum:t.minimum,inclusive:!0,input:s,inst:e,continue:!t.abort})}}),I={major:4,minor:4,patch:3},j=o("$ZodType",(e,t)=>{var n;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=I;const s=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&s.unshift(e);for(const t of s)for(const n of t._zod.onattach)n(e);if(0===s.length)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{const t=(e,t,n)=>{let s,r=y(e);for(const o of t){if(o._zod.def.when){if(w(e))continue;if(!o._zod.def.when(e))continue}else if(r)continue;const t=e.issues.length,a=o._zod.check(e);if(a instanceof Promise&&!1===n?.async)throw new i;if(s||a instanceof Promise)s=(s??Promise.resolve()).then(async()=>{await a;e.issues.length!==t&&(r||(r=y(e,t)))});else{if(e.issues.length===t)continue;r||(r=y(e,t))}}return s?s.then(()=>e):e},n=(n,r,o)=>{if(y(n))return n.aborted=!0,n;const a=t(r,s,o);if(a instanceof Promise){if(!1===o.async)throw new i;return a.then(t=>e._zod.parse(t,o))}return e._zod.parse(a,o)};e._zod.run=(r,o)=>{if(o.skipChecks)return e._zod.parse(r,o);if("backward"===o.direction){const t=e._zod.parse({value:r.value,issues:[]},{...o,skipChecks:!0});return t instanceof Promise?t.then(e=>n(e,r,o)):n(t,r,o)}const a=e._zod.parse(r,o);if(a instanceof Promise){if(!1===o.async)throw new i;return a.then(e=>t(e,s,o))}return t(a,s,o)}}h(e,"~standard",()=>({validate:t=>{try{const n=U(e,t);return n.success?{value:n.data}:{issues:n.error?.issues}}catch(n){return L(e,t).then(e=>e.success?{value:e.data}:{issues:e.error?.issues})}},vendor:"zod",version:1}))}),M=o("$ZodString",(e,t)=>{var n;j.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,s)=>{if(t.coerce)try{n.value=String(n.value)}catch(s){}return"string"==typeof n.value||n.issues.push({expected:"string",code:"invalid_type",input:n.value,inst:e}),n}}),Z=o("$ZodUnknown",(e,t)=>{j.init(e,t),e._zod.parse=e=>e});function x(e,t,n){e.issues.length&&t.issues.push(...b(n,e.issues)),t.value[n]=e.value}const H=o("$ZodArray",(e,t)=>{j.init(e,t),e._zod.parse=(n,s)=>{const r=n.value;if(!Array.isArray(r))return n.issues.push({expected:"array",code:"invalid_type",input:r,inst:e}),n;n.value=Array(r.length);const o=[];for(let e=0;e<r.length;e++){const i=r[e],a=t.element._zod.run({value:i,issues:[]},s);a instanceof Promise?o.push(a.then(t=>x(t,n,e))):x(a,n,e)}return o.length?Promise.all(o).then(()=>n):n}});function D(e,t,n,s,r,o){const i=n in s;if(e.issues.length){if(r&&o&&!i)return;t.issues.push(...b(n,e.issues))}i||r?void 0===e.value?i&&(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 W(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=(s=e.shape,Object.keys(s).filter(e=>"optional"===s[e]._zod.optin&&"optional"===s[e]._zod.optout));var s;return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(n)}}const N=o("$ZodObject",(e,t)=>{j.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 s=(r=()=>W(t),{get value(){{const e=r();return Object.defineProperty(this,"value",{value:e}),e}}});var r;h(e._zod,"propValues",()=>{const e=t.shape,n={};for(const t in e){const s=e[t]._zod;if(s.values){n[t]??(n[t]=new Set);for(const e of s.values)n[t].add(e)}}return n});const o=f,i=t.catchall;let a;e._zod.parse=(t,n)=>{a??(a=s.value);const r=t.value;if(!o(r))return t.issues.push({expected:"object",code:"invalid_type",input:r,inst:e}),t;t.value={};const c=[],u=a.shape;for(const e of a.keys){const s=u[e],o="optional"===s._zod.optin,i="optional"===s._zod.optout,a=s._zod.run({value:r[e],issues:[]},n);a instanceof Promise?c.push(a.then(n=>D(n,t,e,r,o,i))):D(a,t,e,r,o,i)}return i?function(e,t,n,s,r,o){const i=[],a=r.keySet,c=r.catchall._zod,u=c.def.type,l="optional"===c.optin,d="optional"===c.optout;for(const r in t){if("__proto__"===r)continue;if(a.has(r))continue;if("never"===u){i.push(r);continue}const o=c.run({value:t[r],issues:[]},s);o instanceof Promise?e.push(o.then(e=>D(e,n,r,t,l,d))):D(o,n,r,t,l,d)}return i.length&&n.issues.push({code:"unrecognized_keys",keys:i,input:t,inst:o}),e.length?Promise.all(e).then(()=>n):n}(c,r,t,n,s.value,e):c.length?Promise.all(c).then(()=>t):t}}),V=o("$ZodRecord",(e,t)=>{j.init(e,t),e._zod.parse=(n,s)=>{const r=n.value;if(!g(r))return n.issues.push({expected:"record",code:"invalid_type",input:r,inst:e}),n;const o=[],i=t.keyType._zod.values;if(i){n.value={};const a=new Set;for(const c of i)if("string"==typeof c||"number"==typeof c||"symbol"==typeof c){a.add("number"==typeof c?c.toString():c);const i=t.keyType._zod.run({value:c,issues:[]},s);if(i instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(i.issues.length){n.issues.push({code:"invalid_key",origin:"record",issues:i.issues.map(e=>O(e,s,u())),input:c,path:[c],inst:e});continue}const l=i.value,d=t.valueType._zod.run({value:r[c],issues:[]},s);d instanceof Promise?o.push(d.then(e=>{e.issues.length&&n.issues.push(...b(c,e.issues)),n.value[l]=e.value})):(d.issues.length&&n.issues.push(...b(c,d.issues)),n.value[l]=d.value)}let c;for(const e in r)a.has(e)||(c=c??[],c.push(e));c&&c.length>0&&n.issues.push({code:"unrecognized_keys",input:r,inst:e,keys:c})}else{n.value={};for(const i of Reflect.ownKeys(r)){if("__proto__"===i)continue;if(!Object.prototype.propertyIsEnumerable.call(r,i))continue;let a=t.keyType._zod.run({value:i,issues:[]},s);if(a instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if("string"==typeof i&&C.test(i)&&a.issues.length){const e=t.keyType._zod.run({value:Number(i),issues:[]},s);if(e instanceof Promise)throw new Error("Async schemas not supported in object keys currently");0===e.issues.length&&(a=e)}if(a.issues.length){"loose"===t.mode?n.value[i]=r[i]:n.issues.push({code:"invalid_key",origin:"record",issues:a.issues.map(e=>O(e,s,u())),input:i,path:[i],inst:e});continue}const c=t.valueType._zod.run({value:r[i],issues:[]},s);c instanceof Promise?o.push(c.then(e=>{e.issues.length&&n.issues.push(...b(i,e.issues)),n.value[a.value]=e.value})):(c.issues.length&&n.issues.push(...b(i,c.issues)),n.value[a.value]=c.value)}}return o.length?Promise.all(o).then(()=>n):n}}),F=o("$ZodEnum",(e,t)=>{j.init(e,t);const n=function(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)}(t.entries),s=new Set(n);e._zod.values=s,e._zod.pattern=new RegExp(`^(${n.filter(e=>m.has(typeof e)).map(e=>"string"==typeof e?v(e):e.toString()).join("|")})$`),e._zod.parse=(t,r)=>{const o=t.value;return s.has(o)||t.issues.push({code:"invalid_value",values:n,input:o,inst:e}),t}}),K=o("$ZodLiteral",(e,t)=>{if(j.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?v(e):e?v(e.toString()):String(e)).join("|")})$`),e._zod.parse=(s,r)=>{const o=s.value;return n.has(o)||s.issues.push({code:"invalid_value",values:t.values,input:o,inst:e}),s}}),G=o("$ZodTransform",(e,t)=>{j.init(e,t),e._zod.optin="optional",e._zod.parse=(n,s)=>{if("backward"===s.direction)throw new a(e.constructor.name);const r=t.transform(n.value,n);if(s.async){return(r instanceof Promise?r:Promise.resolve(r)).then(e=>(n.value=e,n.fallback=!0,n))}if(r instanceof Promise)throw new i;return n.value=r,n.fallback=!0,n}});function J(e,t){return void 0===t&&(e.issues.length||e.fallback)?{issues:[],value:void 0}:e}const q=o("$ZodOptional",(e,t)=>{j.init(e,t),e._zod.optin="optional",e._zod.optout="optional",h(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),h(e._zod,"pattern",()=>{const e=t.innerType._zod.pattern;return e?new RegExp(`^(${function(e){const t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}(e.source)})?$`):void 0}),e._zod.parse=(e,n)=>{if("optional"===t.innerType._zod.optin){const s=e.value,r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(e=>J(e,s)):J(r,s)}return void 0===e.value?e:t.innerType._zod.run(e,n)}}),B=o("$ZodDefault",(e,t)=>{j.init(e,t),e._zod.optin="optional",h(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 s=t.innerType._zod.run(e,n);return s instanceof Promise?s.then(e=>Y(e,t)):Y(s,t)}});function Y(e,t){return void 0===e.value&&(e.value=t.defaultValue),e}const X=o("$ZodCatch",(e,t)=>{j.init(e,t),e._zod.optin="optional",h(e._zod,"optout",()=>t.innerType._zod.optout),h(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(e,n)=>{if("backward"===n.direction)return t.innerType._zod.run(e,n);const s=t.innerType._zod.run(e,n);return s instanceof Promise?s.then(s=>(e.value=s.value,s.issues.length&&(e.value=t.catchValue({...e,error:{issues:s.issues.map(e=>O(e,n,u()))},input:e.value}),e.issues=[],e.fallback=!0),e)):(e.value=s.value,s.issues.length&&(e.value=t.catchValue({...e,error:{issues:s.issues.map(e=>O(e,n,u()))},input:e.value}),e.issues=[],e.fallback=!0),e)}}),Q=o("$ZodPipe",(e,t)=>{j.init(e,t),h(e._zod,"values",()=>t.in._zod.values),h(e._zod,"optin",()=>t.in._zod.optin),h(e._zod,"optout",()=>t.out._zod.optout),h(e._zod,"propValues",()=>t.in._zod.propValues),e._zod.parse=(e,n)=>{if("backward"===n.direction){const s=t.out._zod.run(e,n);return s instanceof Promise?s.then(e=>ee(e,t.in,n)):ee(s,t.in,n)}const s=t.in._zod.run(e,n);return s instanceof Promise?s.then(e=>ee(e,t.out,n)):ee(s,t.out,n)}});function ee(e,t,n){return e.issues.length?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues,fallback:e.fallback},n)}var te;class ne{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 s={...n,...this._map.get(e)};return Object.keys(s).length?s:void 0}return this._map.get(e)}has(e){return this._map.has(e)}}(te=globalThis).__zod_globalRegistry??(te.__zod_globalRegistry=new ne);const se=o("ZodMiniType",(e,t)=>{if(!e._zod)throw new Error("Uninitialized schema in ZodMiniType.");j.init(e,t),e.def=t,e.type=t.type,e.parse=(t,n)=>A(e,t,n,{callee:e.parse}),e.safeParse=(t,n)=>U(e,t,n),e.parseAsync=async(t,n)=>R(e,t,n,{callee:e.parseAsync}),e.safeParseAsync=async(t,n)=>L(e,t,n),e.check=(...n)=>e.clone({...t,checks:[...t.checks??[],...n.map(e=>"function"==typeof e?{_zod:{check:e,def:{check:"custom"},onattach:[]}}:e)]},{parent:!0}),e.with=e.check,e.clone=(t,n)=>function(e,t,n){const s=new e._zod.constr(t??e._zod.def);return t&&!n?.parent||(s._zod.parent=e),s}(e,t,n),e.brand=()=>e,e.register=(t,n)=>(t.add(e,n),e),e.apply=t=>t(e)}),re=o("ZodMiniString",(e,t)=>{M.init(e,t),se.init(e,t)});function oe(e){return function(e,t){return new e({type:"string",..._(t)})}(re,e)}const ie=o("ZodMiniUnknown",(e,t)=>{Z.init(e,t),se.init(e,t)});function ae(){return new ie({type:"unknown"})}const ce=o("ZodMiniArray",(e,t)=>{H.init(e,t),se.init(e,t)});function ue(e,t){return new ce({type:"array",element:e,..._(t)})}const le=o("ZodMiniObject",(e,t)=>{N.init(e,t),se.init(e,t),h(e,"shape",()=>t.shape)});function de(e,t){const n={type:"object",shape:e??{},..._(t)};return new le(n)}function he(e,t){return new le({type:"object",shape:e,catchall:ae(),..._(t)})}const pe=o("ZodMiniRecord",(e,t)=>{V.init(e,t),se.init(e,t)});const fe=o("ZodMiniEnum",(e,t)=>{F.init(e,t),se.init(e,t),e.options=Object.values(t.entries)});function ge(e,t){const n=Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e;return new fe({type:"enum",entries:n,..._(t)})}const me=o("ZodMiniLiteral",(e,t)=>{K.init(e,t),se.init(e,t)});function ve(e,t){return new me({type:"literal",values:Array.isArray(e)?e:[e],..._(t)})}const _e=o("ZodMiniTransform",(e,t)=>{G.init(e,t),se.init(e,t)});function ye(e){return new _e({type:"transform",transform:e})}const we=o("ZodMiniOptional",(e,t)=>{q.init(e,t),se.init(e,t)});function be(e){return new we({type:"optional",innerType:e})}const ze=o("ZodMiniDefault",(e,t)=>{B.init(e,t),se.init(e,t)});function Oe(e,t){return new ze({type:"default",innerType:e,get defaultValue(){return"function"==typeof t?t():g(e=t)?{...e}:Array.isArray(e)?[...e]:e instanceof Map?new Map(e):e instanceof Set?new Set(e):e;var e}})}const ke=o("ZodMiniCatch",(e,t)=>{X.init(e,t),se.init(e,t)});function Ee(e,t){return new ke({type:"catch",innerType:e,catchValue:"function"==typeof t?t:()=>t})}const Se=o("ZodMiniPipe",(e,t)=>{Q.init(e,t),se.init(e,t)});function Ae(e,t){return new Se({type:"pipe",in:e,out:t})}function Pe(){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,s=window.innerWidth<=768;return t||n&&s}function Re(){return Pe()&&window.innerWidth<=480?"phone":Pe()&&window.innerWidth>480&&window.innerWidth<=1024?"tablet":"desktop"}function Ue(e){return"pending"===e?"pending":"error"===e?"error":"active"}const Le=oe().check((Ce=1,new $({check:"min_length",..._(Te),minimum:Ce})));var Ce,Te;const $e=function(e,t){return e.clone({...e._zod.def,catchall:t})}(de({account_display_name:be(oe()),account_email:be(oe())}),ae()),Ie=Ae(de({grant_id:Le,provider:Le,provider_name:be(oe()),account_identifier:be(oe()),timestamp:be(oe()),operation:Oe(be(ge(["creation","reauth"])),"creation"),scopes:Oe(be(ue(oe())),[]),status:Oe(be(ge(["active","pending","error"])),"active"),metadata:be($e)}),ye(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})),je=Ae(de({provider_id:Le,reason:Le,message:Le}),ye(e=>({providerId:e.provider_id,reason:e.reason,message:e.message}))),Me=de({type:ge(["alter_connect_success","alter_connect_error","alter_connect_event"])}),Ze=de({type:ve("alter_connect_success"),grants:ue(Ie),failed_grants:Oe(be(ue(je)),[])}),xe=he({type:ve("alter_connect_error"),error:Ee(oe(),"oauth_error"),error_description:Ee(oe(),"OAuth authorization failed")}),He=he({type:ve("alter_connect_event"),event:Ee(oe(),"connect_notice"),metadata:Ee(function(e,t,n){return t&&t._zod?new pe({type:"record",keyType:e,valueType:t,..._(n)}):new pe({type:"record",keyType:oe(),valueType:e,..._(t)})}(oe(),ae()),{})});function De(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"}const We="alter_oauth_state",Ne="alter_connect_nonce",Ve=["alter_connect_success","alter_connect_error",Ne,"grant_id","provider","provider_name","account_identifier","timestamp","operation","scopes","status","error_code","error_message"];function Fe(){const e=new URLSearchParams(window.location.search);return null!==e.get("alter_connect_success")||null!==e.get("alter_connect_error")}function Ke(e){sessionStorage.removeItem(We);try{const t=new URL(e);if(t.pathname===window.location.pathname)return void window.history.replaceState({},document.title,t.pathname+t.search+t.hash)}catch{}Ge()}function Ge(){const e=new URL(window.location.href);for(const t of Ve)e.searchParams.delete(t);window.history.replaceState({},document.title,e.pathname+e.search+e.hash)}class Je{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,onNotice:t.onNotice||(()=>{}),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=Re();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=function(){const e=globalThis.crypto;if(!e)return null;if("function"==typeof e.randomUUID)return e.randomUUID();if("function"==typeof e.getRandomValues){const t=e.getRandomValues(new Uint8Array(16));return Array.from(t,e=>e.toString(16).padStart(2,"0")).join("")}return null}();if(null===t)return this.log("No cryptographic randomness available; refusing redirect flow"),void this.options.onError({code:"redirect_error",message:"Failed to start OAuth flow: this browser provides no secure random source, so the OAuth callback could not be bound to this flow"});let n;try{const s=new URL(e);s.searchParams.set(Ne,t),n=s.toString()}catch{return this.log("Failed to parse OAuth URL for redirect flow:",e),void this.options.onError({code:"invalid_oauth_url",message:"Failed to start OAuth flow: the OAuth URL is not a valid absolute URL"})}const s={timestamp:Date.now(),returnUrl:window.location.href,nonce:t};try{sessionStorage.setItem(We,JSON.stringify(s))}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=n}static checkOAuthReturn(e,t){const n=sessionStorage.getItem(We);if(!n)return!!Fe()&&(Ge(),t({code:"redirect_state_missing",message:"Received an Alter Connect redirect callback, but no matching flow state exists on this origin. The return URL must be on the SAME origin (scheme, host and port) as the page that called open() — browsers scope the flow's session storage to one origin, so a callback delivered elsewhere cannot be completed.",details:{origin:window.location.origin}}),!0);try{const r=function(e){let t;try{t=JSON.parse(e)}catch{return null}if("object"!=typeof t||null===t)return null;const{timestamp:n,returnUrl:s,nonce:r}=t;return"number"==typeof n&&Number.isFinite(n)?"string"!=typeof s||0===s.length||"string"!=typeof r||0===r.length?null:{timestamp:n,returnUrl:s,nonce:r}:null}(n);if(null===r)return sessionStorage.removeItem(We),Fe()&&Ge(),!1;const o=Date.now()-r.timestamp;if(o<0||o>3e5)return sessionStorage.removeItem(We),Fe()&&Ge(),!1;const i=new URLSearchParams(window.location.search),a=i.get("alter_connect_success"),c=i.get("alter_connect_error");if(null===a&&null===c)return!1;if(i.get(Ne)!==r.nonce)return console.warn("[OAuth Handler] Ignoring OAuth callback parameters that do not carry this flow's nonce"),Ge(),!1;if("true"===a){const n=i.get("grant_id"),o=i.get("provider"),a=i.get("account_identifier");if(!n||!o||!a)return Ke(r.returnUrl),t({code:"invalid_response",message:"OAuth redirect returned incomplete grant data"}),!0;const c={grant_id:n,provider:o,provider_name:i.get("provider_name")||o,account_identifier:a,timestamp:i.get("timestamp")||(new Date).toISOString(),operation:(s=i.get("operation"),"reauth"===s?"reauth":"creation"),scopes:i.get("scopes")?.split(",")||[],status:Ue(i.get("status"))};Ke(r.returnUrl);const u=[c];return e(u,{grants:u,failedGrants:[]}),!0}if(c){const e={code:i.get("error_code")||"oauth_error",message:i.get("error_description")||"OAuth authorization failed"};return Ke(r.returnUrl),t(e),!0}return Ke(r.returnUrl),!1}catch(e){return console.error("[OAuth Handler] Failed to check OAuth return:",e),sessionStorage.removeItem(We),Fe()&&Ge(),!1}var s}openPopup(e){const t=window.screenX+(window.outerWidth-this.options.popupWidth)/2,n=window.screenY+(window.outerHeight-this.options.popupHeight)/2,s=[`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",s),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=Me.safeParse(e.data);if(!t.success)return;if("alter_connect_event"===t.data.type){const t=He.safeParse(e.data);return void(t.success&&(this.log("Connect notice:",t.data.event),this.options.onNotice(t.data.event,t.data.metadata)))}if("alter_connect_success"===t.data.type){this.log("OAuth success");const t=Ze.safeParse(e.data);if(!t.success)return this.settled=!0,this.close(),void this.options.onError({code:"invalid_response",message:De(t.error)});const{grants:n,failed_grants:s}=t.data;if(this.log("Connect completion:",n.length,"grants"),0===n.length)return this.settled=!0,this.close(),void(s.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:s}):this.options.onError({code:"invalid_response",message:"Server returned empty grants array"}));const r={grants:n,failedGrants:s};return this.settled=!0,this.close(),void this.options.onSuccess(n,r)}const n=xe.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 qe="0.2.0";let Be=!1;class Ye{constructor(r={}){if(this._oauthHandler=null,this._perOpenCleanups=[],this.pendingRedirectOutcome=null,function(e){if(void 0!==e.baseURL)throw new Error("AlterConnectConfig.baseURL is reserved and not yet supported. Omit the field to use the production Alter host.")}(r),this.config=function(e){return{debug:e.debug??!1}}(r),this._baseURL=(r.baseURL??e).replace(/\/+$/,""),this._baseURL!==e&&!Be){Be=!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 s,this._isInitialized=!0,t(this.config,"Alter Connect SDK initialized",{version:qe,baseURL:this._baseURL}),this.checkRedirectReturn()}checkRedirectReturn(){Je.checkOAuthReturn((e,n)=>{t(this.config,"OAuth redirect return - success:",e),this.deliverRedirectOutcome("success",[e,n])},e=>{t(this.config,"OAuth redirect return - error:",e),this.deliverRedirectOutcome("error",[e])})&&t(this.config,"OAuth redirect return detected and handled")}deliverRedirectOutcome(e,t){this.eventEmitter.hasListeners(e)?this.eventEmitter.emit(e,...t):this.pendingRedirectOutcome={event:e,args:t}}flushRedirectOutcome(e){const t=this.pendingRedirectOutcome;null!==t&&t.event===e&&(this.pendingRedirectOutcome=null,this.eventEmitter.emit(t.event,...t.args))}static create(e){return new Ye(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 Je({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()},onNotice:(e,n)=>{t(this.config,"OAuth notice:",e),this.eventEmitter.emit("event",e,n)},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.pendingRedirectOutcome=null,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");const n=this.eventEmitter.on(e,t);return this.flushRedirectOutcome(e),n}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 qe}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")}releaseAfterTerminal(e){try{e()}finally{this._isInitialized&&this.close()}}registerEventHandlers(e){this._perOpenCleanups.push(this.eventEmitter.on("success",(t,n)=>{this.releaseAfterTerminal(()=>e.onSuccess?.(t,n))})),this._perOpenCleanups.push(this.eventEmitter.on("exit",()=>{this.releaseAfterTerminal(()=>e.onExit?.())})),this._perOpenCleanups.push(this.eventEmitter.on("error",t=>{this.releaseAfterTerminal(()=>e.onError?.(t))})),e.onEvent&&this._perOpenCleanups.push(this.eventEmitter.on("event",(t,n)=>{e.onEvent(t,n)}))}createError(e,t,n){const s=new Error(t);return s.code=e,s.details=n,s}}exports.default=Ye;
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)}hasListeners(e){const t=this.events.get(e);return void 0!==t&&t.size>0}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 s{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 r(){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,s=window.innerWidth<=768;return t||n&&s}function o(){return r()&&window.innerWidth<=480?"phone":r()&&window.innerWidth>480&&window.innerWidth<=1024?"tablet":"desktop"}var i;function a(e,t,n){function s(n,s){if(n._zod||Object.defineProperty(n,"_zod",{value:{def:s,constr:i,traits:new Set},enumerable:!1}),n._zod.traits.has(e))return;n._zod.traits.add(e),t(n,s);const r=i.prototype,o=Object.keys(r);for(let e=0;e<o.length;e++){const t=o[e];t in n||(n[t]=r[t].bind(n))}}const r=n?.Parent??Object;class o extends r{}function i(e){var t;const r=n?.Parent?new o:this;s(r,e),(t=r._zod).deferred??(t.deferred=[]);for(const e of r._zod.deferred)e();return r}return Object.defineProperty(o,"name",{value:e}),Object.defineProperty(i,"init",{value:s}),Object.defineProperty(i,Symbol.hasInstance,{value:t=>!!(n?.Parent&&t instanceof n.Parent)||t?._zod?.traits?.has(e)}),Object.defineProperty(i,"name",{value:e}),i}class c extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class u extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name="ZodEncodeError"}}(i=globalThis).__zod_globalConfig??(i.__zod_globalConfig={});const l=globalThis.__zod_globalConfig;function d(e){return l}function h(e,t){return"bigint"==typeof t?t.toString():t}const p=Symbol("evaluating");function f(e,t,n){let s;Object.defineProperty(e,t,{get(){if(s!==p)return void 0===s&&(s=p,s=n()),s},set(n){Object.defineProperty(e,t,{value:n})},configurable:!0})}const g="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function m(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function v(e){if(!1===m(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!==m(n)&&!1!==Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")}const _=new Set(["string","number","symbol"]);function w(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function y(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 b(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 z(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 O(e,t){return t.map(t=>{var n;return(n=t).path??(n.path=[]),t.path.unshift(e),t})}function E(e){return"string"==typeof e?e:e?.message}function k(e,t,n){const s=e.message?e.message:E(e.inst?._zod.def?.error?.(e))??E(t?.error?.(e))??E(n.customError?.(e))??E(n.localeError?.(e))??"Invalid input",{inst:r,continue:o,input:i,...a}=e;return a.path??(a.path=[]),a.message=s,t?.reportInput&&(a.input=i),a}const S=(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,h,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},C=a("$ZodError",S),R=a("$ZodError",S,{Parent:Error}),L=(e=>(t,n,s,r)=>{const o=s?{...s,async:!1}:{async:!1},i=t._zod.run({value:n,issues:[]},o);if(i instanceof Promise)throw new c;if(i.issues.length){const t=new(r?.Err??e)(i.issues.map(e=>k(e,o,d())));throw g(t,r?.callee),t}return i.value})(R),P=e=>async(t,n,s,r)=>{const o=s?{...s,async:!0}:{async:!0};let i=t._zod.run({value:n,issues:[]},o);if(i instanceof Promise&&(i=await i),i.issues.length){const t=new(r?.Err??e)(i.issues.map(e=>k(e,o,d())));throw g(t,r?.callee),t}return i.value},A=P(R),U=(e=>(t,n,s)=>{const r=s?{...s,async:!1}:{async:!1},o=t._zod.run({value:n,issues:[]},r);if(o instanceof Promise)throw new c;return o.issues.length?{success:!1,error:new(e??C)(o.issues.map(e=>k(e,r,d())))}:{success:!0,data:o.value}})(R),T=(e=>async(t,n,s)=>{const r=s?{...s,async:!0}:{async:!0};let o=t._zod.run({value:n,issues:[]},r);return o instanceof Promise&&(o=await o),o.issues.length?{success:!1,error:new e(o.issues.map(e=>k(e,r,d())))}:{success:!0,data:o.value}})(R),x=/^-?\d+(?:\.\d+)?$/,I=a("$ZodCheck",(e,t)=>{var n;e._zod??(e._zod={}),e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),$=a("$ZodCheckMinLength",(e,t)=>{var n;I.init(e,t),(n=e._zod.def).when??(n.when=e=>{const t=e.value;return!(n=t,null==n||void 0===t.length);var n}),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 s=n.value;if(s.length>=t.minimum)return;const r=function(e){return Array.isArray(e)?"array":"string"==typeof e?"string":"unknown"}(s);n.issues.push({origin:r,code:"too_small",minimum:t.minimum,inclusive:!0,input:s,inst:e,continue:!t.abort})}}),j={major:4,minor:4,patch:3},M=a("$ZodType",(e,t)=>{var n;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=j;const s=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&s.unshift(e);for(const t of s)for(const n of t._zod.onattach)n(e);if(0===s.length)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{const t=(e,t,n)=>{let s,r=b(e);for(const o of t){if(o._zod.def.when){if(z(e))continue;if(!o._zod.def.when(e))continue}else if(r)continue;const t=e.issues.length,i=o._zod.check(e);if(i instanceof Promise&&!1===n?.async)throw new c;if(s||i instanceof Promise)s=(s??Promise.resolve()).then(async()=>{await i;e.issues.length!==t&&(r||(r=b(e,t)))});else{if(e.issues.length===t)continue;r||(r=b(e,t))}}return s?s.then(()=>e):e},n=(n,r,o)=>{if(b(n))return n.aborted=!0,n;const i=t(r,s,o);if(i instanceof Promise){if(!1===o.async)throw new c;return i.then(t=>e._zod.parse(t,o))}return e._zod.parse(i,o)};e._zod.run=(r,o)=>{if(o.skipChecks)return e._zod.parse(r,o);if("backward"===o.direction){const t=e._zod.parse({value:r.value,issues:[]},{...o,skipChecks:!0});return t instanceof Promise?t.then(e=>n(e,r,o)):n(t,r,o)}const i=e._zod.parse(r,o);if(i instanceof Promise){if(!1===o.async)throw new c;return i.then(e=>t(e,s,o))}return t(i,s,o)}}f(e,"~standard",()=>({validate:t=>{try{const n=U(e,t);return n.success?{value:n.data}:{issues:n.error?.issues}}catch(n){return T(e,t).then(e=>e.success?{value:e.data}:{issues:e.error?.issues})}},vendor:"zod",version:1}))}),Z=a("$ZodString",(e,t)=>{var n;M.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,s)=>{if(t.coerce)try{n.value=String(n.value)}catch(s){}return"string"==typeof n.value||n.issues.push({expected:"string",code:"invalid_type",input:n.value,inst:e}),n}}),H=a("$ZodUnknown",(e,t)=>{M.init(e,t),e._zod.parse=e=>e});function W(e,t,n){e.issues.length&&t.issues.push(...O(n,e.issues)),t.value[n]=e.value}const D=a("$ZodArray",(e,t)=>{M.init(e,t),e._zod.parse=(n,s)=>{const r=n.value;if(!Array.isArray(r))return n.issues.push({expected:"array",code:"invalid_type",input:r,inst:e}),n;n.value=Array(r.length);const o=[];for(let e=0;e<r.length;e++){const i=r[e],a=t.element._zod.run({value:i,issues:[]},s);a instanceof Promise?o.push(a.then(t=>W(t,n,e))):W(a,n,e)}return o.length?Promise.all(o).then(()=>n):n}});function N(e,t,n,s,r,o){const i=n in s;if(e.issues.length){if(r&&o&&!i)return;t.issues.push(...O(n,e.issues))}i||r?void 0===e.value?i&&(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 F(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=(s=e.shape,Object.keys(s).filter(e=>"optional"===s[e]._zod.optin&&"optional"===s[e]._zod.optout));var s;return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(n)}}const V=a("$ZodObject",(e,t)=>{M.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 s=(r=()=>F(t),{get value(){{const e=r();return Object.defineProperty(this,"value",{value:e}),e}}});var r;f(e._zod,"propValues",()=>{const e=t.shape,n={};for(const t in e){const s=e[t]._zod;if(s.values){n[t]??(n[t]=new Set);for(const e of s.values)n[t].add(e)}}return n});const o=m,i=t.catchall;let a;e._zod.parse=(t,n)=>{a??(a=s.value);const r=t.value;if(!o(r))return t.issues.push({expected:"object",code:"invalid_type",input:r,inst:e}),t;t.value={};const c=[],u=a.shape;for(const e of a.keys){const s=u[e],o="optional"===s._zod.optin,i="optional"===s._zod.optout,a=s._zod.run({value:r[e],issues:[]},n);a instanceof Promise?c.push(a.then(n=>N(n,t,e,r,o,i))):N(a,t,e,r,o,i)}return i?function(e,t,n,s,r,o){const i=[],a=r.keySet,c=r.catchall._zod,u=c.def.type,l="optional"===c.optin,d="optional"===c.optout;for(const r in t){if("__proto__"===r)continue;if(a.has(r))continue;if("never"===u){i.push(r);continue}const o=c.run({value:t[r],issues:[]},s);o instanceof Promise?e.push(o.then(e=>N(e,n,r,t,l,d))):N(o,n,r,t,l,d)}return i.length&&n.issues.push({code:"unrecognized_keys",keys:i,input:t,inst:o}),e.length?Promise.all(e).then(()=>n):n}(c,r,t,n,s.value,e):c.length?Promise.all(c).then(()=>t):t}}),K=a("$ZodRecord",(e,t)=>{M.init(e,t),e._zod.parse=(n,s)=>{const r=n.value;if(!v(r))return n.issues.push({expected:"record",code:"invalid_type",input:r,inst:e}),n;const o=[],i=t.keyType._zod.values;if(i){n.value={};const a=new Set;for(const c of i)if("string"==typeof c||"number"==typeof c||"symbol"==typeof c){a.add("number"==typeof c?c.toString():c);const i=t.keyType._zod.run({value:c,issues:[]},s);if(i instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(i.issues.length){n.issues.push({code:"invalid_key",origin:"record",issues:i.issues.map(e=>k(e,s,d())),input:c,path:[c],inst:e});continue}const u=i.value,l=t.valueType._zod.run({value:r[c],issues:[]},s);l instanceof Promise?o.push(l.then(e=>{e.issues.length&&n.issues.push(...O(c,e.issues)),n.value[u]=e.value})):(l.issues.length&&n.issues.push(...O(c,l.issues)),n.value[u]=l.value)}let c;for(const e in r)a.has(e)||(c=c??[],c.push(e));c&&c.length>0&&n.issues.push({code:"unrecognized_keys",input:r,inst:e,keys:c})}else{n.value={};for(const i of Reflect.ownKeys(r)){if("__proto__"===i)continue;if(!Object.prototype.propertyIsEnumerable.call(r,i))continue;let a=t.keyType._zod.run({value:i,issues:[]},s);if(a instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if("string"==typeof i&&x.test(i)&&a.issues.length){const e=t.keyType._zod.run({value:Number(i),issues:[]},s);if(e instanceof Promise)throw new Error("Async schemas not supported in object keys currently");0===e.issues.length&&(a=e)}if(a.issues.length){"loose"===t.mode?n.value[i]=r[i]:n.issues.push({code:"invalid_key",origin:"record",issues:a.issues.map(e=>k(e,s,d())),input:i,path:[i],inst:e});continue}const c=t.valueType._zod.run({value:r[i],issues:[]},s);c instanceof Promise?o.push(c.then(e=>{e.issues.length&&n.issues.push(...O(i,e.issues)),n.value[a.value]=e.value})):(c.issues.length&&n.issues.push(...O(i,c.issues)),n.value[a.value]=c.value)}}return o.length?Promise.all(o).then(()=>n):n}}),G=a("$ZodEnum",(e,t)=>{M.init(e,t);const n=function(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)}(t.entries),s=new Set(n);e._zod.values=s,e._zod.pattern=new RegExp(`^(${n.filter(e=>_.has(typeof e)).map(e=>"string"==typeof e?w(e):e.toString()).join("|")})$`),e._zod.parse=(t,r)=>{const o=t.value;return s.has(o)||t.issues.push({code:"invalid_value",values:n,input:o,inst:e}),t}}),q=a("$ZodLiteral",(e,t)=>{if(M.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?w(e):e?w(e.toString()):String(e)).join("|")})$`),e._zod.parse=(s,r)=>{const o=s.value;return n.has(o)||s.issues.push({code:"invalid_value",values:t.values,input:o,inst:e}),s}}),J=a("$ZodTransform",(e,t)=>{M.init(e,t),e._zod.optin="optional",e._zod.parse=(n,s)=>{if("backward"===s.direction)throw new u(e.constructor.name);const r=t.transform(n.value,n);if(s.async){return(r instanceof Promise?r:Promise.resolve(r)).then(e=>(n.value=e,n.fallback=!0,n))}if(r instanceof Promise)throw new c;return n.value=r,n.fallback=!0,n}});function B(e,t){return void 0===t&&(e.issues.length||e.fallback)?{issues:[],value:void 0}:e}const Y=a("$ZodOptional",(e,t)=>{M.init(e,t),e._zod.optin="optional",e._zod.optout="optional",f(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),f(e._zod,"pattern",()=>{const e=t.innerType._zod.pattern;return e?new RegExp(`^(${function(e){const t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}(e.source)})?$`):void 0}),e._zod.parse=(e,n)=>{if("optional"===t.innerType._zod.optin){const s=e.value,r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(e=>B(e,s)):B(r,s)}return void 0===e.value?e:t.innerType._zod.run(e,n)}}),X=a("$ZodDefault",(e,t)=>{M.init(e,t),e._zod.optin="optional",f(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 s=t.innerType._zod.run(e,n);return s instanceof Promise?s.then(e=>Q(e,t)):Q(s,t)}});function Q(e,t){return void 0===e.value&&(e.value=t.defaultValue),e}const ee=a("$ZodCatch",(e,t)=>{M.init(e,t),e._zod.optin="optional",f(e._zod,"optout",()=>t.innerType._zod.optout),f(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(e,n)=>{if("backward"===n.direction)return t.innerType._zod.run(e,n);const s=t.innerType._zod.run(e,n);return s instanceof Promise?s.then(s=>(e.value=s.value,s.issues.length&&(e.value=t.catchValue({...e,error:{issues:s.issues.map(e=>k(e,n,d()))},input:e.value}),e.issues=[],e.fallback=!0),e)):(e.value=s.value,s.issues.length&&(e.value=t.catchValue({...e,error:{issues:s.issues.map(e=>k(e,n,d()))},input:e.value}),e.issues=[],e.fallback=!0),e)}}),te=a("$ZodPipe",(e,t)=>{M.init(e,t),f(e._zod,"values",()=>t.in._zod.values),f(e._zod,"optin",()=>t.in._zod.optin),f(e._zod,"optout",()=>t.out._zod.optout),f(e._zod,"propValues",()=>t.in._zod.propValues),e._zod.parse=(e,n)=>{if("backward"===n.direction){const s=t.out._zod.run(e,n);return s instanceof Promise?s.then(e=>ne(e,t.in,n)):ne(s,t.in,n)}const s=t.in._zod.run(e,n);return s instanceof Promise?s.then(e=>ne(e,t.out,n)):ne(s,t.out,n)}});function ne(e,t,n){return e.issues.length?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues,fallback:e.fallback},n)}var se;class re{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 s={...n,...this._map.get(e)};return Object.keys(s).length?s:void 0}return this._map.get(e)}has(e){return this._map.has(e)}}(se=globalThis).__zod_globalRegistry??(se.__zod_globalRegistry=new re);const oe=a("ZodMiniType",(e,t)=>{if(!e._zod)throw new Error("Uninitialized schema in ZodMiniType.");M.init(e,t),e.def=t,e.type=t.type,e.parse=(t,n)=>L(e,t,n,{callee:e.parse}),e.safeParse=(t,n)=>U(e,t,n),e.parseAsync=async(t,n)=>A(e,t,n,{callee:e.parseAsync}),e.safeParseAsync=async(t,n)=>T(e,t,n),e.check=(...n)=>e.clone({...t,checks:[...t.checks??[],...n.map(e=>"function"==typeof e?{_zod:{check:e,def:{check:"custom"},onattach:[]}}:e)]},{parent:!0}),e.with=e.check,e.clone=(t,n)=>function(e,t,n){const s=new e._zod.constr(t??e._zod.def);return t&&!n?.parent||(s._zod.parent=e),s}(e,t,n),e.brand=()=>e,e.register=(t,n)=>(t.add(e,n),e),e.apply=t=>t(e)}),ie=a("ZodMiniString",(e,t)=>{Z.init(e,t),oe.init(e,t)});function ae(e){return function(e,t){return new e({type:"string",...y(t)})}(ie,e)}const ce=a("ZodMiniUnknown",(e,t)=>{H.init(e,t),oe.init(e,t)});function ue(){return new ce({type:"unknown"})}const le=a("ZodMiniArray",(e,t)=>{D.init(e,t),oe.init(e,t)});function de(e,t){return new le({type:"array",element:e,...y(t)})}const he=a("ZodMiniObject",(e,t)=>{V.init(e,t),oe.init(e,t),f(e,"shape",()=>t.shape)});function pe(e,t){const n={type:"object",shape:e??{},...y(t)};return new he(n)}function fe(e,t){return new he({type:"object",shape:e,catchall:ue(),...y(t)})}const ge=a("ZodMiniRecord",(e,t)=>{K.init(e,t),oe.init(e,t)});const me=a("ZodMiniEnum",(e,t)=>{G.init(e,t),oe.init(e,t),e.options=Object.values(t.entries)});function ve(e,t){const n=Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e;return new me({type:"enum",entries:n,...y(t)})}const _e=a("ZodMiniLiteral",(e,t)=>{q.init(e,t),oe.init(e,t)});function we(e,t){return new _e({type:"literal",values:Array.isArray(e)?e:[e],...y(t)})}const ye=a("ZodMiniTransform",(e,t)=>{J.init(e,t),oe.init(e,t)});function be(e){return new ye({type:"transform",transform:e})}const ze=a("ZodMiniOptional",(e,t)=>{Y.init(e,t),oe.init(e,t)});function Oe(e){return new ze({type:"optional",innerType:e})}const Ee=a("ZodMiniDefault",(e,t)=>{X.init(e,t),oe.init(e,t)});function ke(e,t){return new Ee({type:"default",innerType:e,get defaultValue(){return"function"==typeof t?t():v(e=t)?{...e}:Array.isArray(e)?[...e]:e instanceof Map?new Map(e):e instanceof Set?new Set(e):e;var e}})}const Se=a("ZodMiniCatch",(e,t)=>{ee.init(e,t),oe.init(e,t)});function Ce(e,t){return new Se({type:"catch",innerType:e,catchValue:"function"==typeof t?t:()=>t})}const Re=a("ZodMiniPipe",(e,t)=>{te.init(e,t),oe.init(e,t)});function Le(e,t){return new Re({type:"pipe",in:e,out:t})}const Pe=ae().check((Ae=1,new $({check:"min_length",...y(Ue),minimum:Ae})));var Ae,Ue;const Te=function(e,t){return e.clone({...e._zod.def,catchall:t})}(pe({account_display_name:Oe(ae()),account_email:Oe(ae())}),ue()),xe=Le(pe({grant_id:Pe,provider:Pe,provider_name:Oe(ae()),account_identifier:Oe(ae()),timestamp:Oe(ae()),operation:ke(Oe(ve(["creation","reauth"])),"creation"),scopes:ke(Oe(de(ae())),[]),status:ke(Oe(ve(["active","pending","error"])),"active"),metadata:Oe(Te)}),be(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})),Ie=Le(pe({provider_id:Pe,reason:Pe,message:Pe}),be(e=>({providerId:e.provider_id,reason:e.reason,message:e.message}))),$e=pe({type:ve(["alter_connect_success","alter_connect_error","alter_connect_event","alter_connect_exit","alter_connect_embed_unsupported","alter_connect_ready"])}),je=pe({type:we("alter_connect_success"),grants:de(xe),failed_grants:ke(Oe(de(Ie)),[])}),Me=fe({type:we("alter_connect_error"),error:Ce(ae(),"oauth_error"),error_description:Ce(ae(),"OAuth authorization failed")}),Ze=fe({type:we("alter_connect_event"),event:Ce(ae(),"connect_notice"),metadata:Ce(function(e,t,n){return t&&t._zod?new ge({type:"record",keyType:e,valueType:t,...y(n)}):new ge({type:"record",keyType:ae(),valueType:e,...y(t)})}(ae(),ue()),{})}),He=fe({type:we("alter_connect_embed_unsupported"),reason:Oe(ae())});function We(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 De(e){const t=$e.safeParse(e);if(!t.success)return{kind:"ignore"};switch(t.data.type){case"alter_connect_event":{const t=Ze.safeParse(e);return t.success?{kind:"notice",event:t.data.event,metadata:t.data.metadata}:{kind:"ignore"}}case"alter_connect_exit":return{kind:"exit"};case"alter_connect_ready":return{kind:"ready"};case"alter_connect_embed_unsupported":{const t=He.safeParse(e);return{kind:"notice",event:"embed_unsupported",metadata:{reason:t.success?t.data.reason??null:null,timestamp:(new Date).toISOString()}}}case"alter_connect_success":{const t=je.safeParse(e);if(!t.success)return{kind:"error",error:{code:"invalid_response",message:We(t.error)}};const{grants:n,failed_grants:s}=t.data;return 0===n.length?s.length>0?{kind:"error",error:{code:"grant_policy_application_failed",message:"The connection was not completed because the selected usage limits could not be applied.",failedGrants:s}}:{kind:"error",error:{code:"invalid_response",message:"Server returned empty grants array"}}:{kind:"success",grants:n,completion:{grants:n,failedGrants:s}}}case"alter_connect_error":{const t=Me.safeParse(e);return t.success?{kind:"error",error:{code:t.data.error,message:t.data.error_description,details:t.data}}:{kind:"ignore"}}}}function Ne(e){return"pending"===e?"pending":"error"===e?"error":"active"}const Fe="alter_oauth_state",Ve="alter_connect_nonce",Ke=["alter_connect_success","alter_connect_error",Ve,"grant_id","provider","provider_name","account_identifier","timestamp","operation","scopes","status","error_code","error_description"];function Ge(){const e=new URLSearchParams(window.location.search);return null!==e.get("alter_connect_success")||null!==e.get("alter_connect_error")}function qe(e){sessionStorage.removeItem(Fe);try{const t=new URL(e);if(t.pathname===window.location.pathname)return void window.history.replaceState({},document.title,t.pathname+t.search+t.hash)}catch{}Je()}function Je(){const e=new URL(window.location.href);for(const t of Ke)e.searchParams.delete(t);window.history.replaceState({},document.title,e.pathname+e.search+e.hash)}class Be{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,onNotice:t.onNotice||(()=>{}),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){return this.deriveExpectedOrigin(e)?function(){const e=o();return"phone"===e||"tablet"===e&&window.innerHeight>window.innerWidth}()?(this.log("Using redirect flow for mobile device"),this.startRedirectFlow(e)?"redirect":null):(this.log("Using popup flow for desktop"),this.openPopup(e)?"popup":null):null}deriveExpectedOrigin(e){if(this.options.expectedOrigin)return!0;try{return this.options.expectedOrigin=new URL(e).origin,this.log("Derived expected origin:",this.options.expectedOrigin),!0}catch{return this.log("Failed to parse OAuth URL for origin validation:",e),this.options.onError({code:"invalid_oauth_url",message:"Failed to determine origin from OAuth URL. Cannot proceed securely."}),!1}}tryOpenWindow(e){if(!this.deriveExpectedOrigin(e))return!1;const t=this.createPopup(e);return!!t&&(this.popup=t,this.startPolling(),this.setupMessageListener(),!0)}focusWindow(){this.popup&&!this.popup.closed&&this.popup.focus()}startRedirectFlow(e){this.log("Starting redirect flow:",e);const t=function(){const e=globalThis.crypto;if(!e)return null;if("function"==typeof e.randomUUID)return e.randomUUID();if("function"==typeof e.getRandomValues){const t=e.getRandomValues(new Uint8Array(16));return Array.from(t,e=>e.toString(16).padStart(2,"0")).join("")}return null}();if(null===t)return this.log("No cryptographic randomness available; refusing redirect flow"),this.options.onError({code:"redirect_error",message:"Failed to start OAuth flow: this browser provides no secure random source, so the OAuth callback could not be bound to this flow"}),!1;let n;try{const s=new URL(e);s.searchParams.set(Ve,t),n=s.toString()}catch{return this.log("Failed to parse OAuth URL for redirect flow:",e),this.options.onError({code:"invalid_oauth_url",message:"Failed to start OAuth flow: the OAuth URL is not a valid absolute URL"}),!1}const s={timestamp:Date.now(),returnUrl:window.location.href,nonce:t};try{sessionStorage.setItem(Fe,JSON.stringify(s))}catch(e){return this.log("Failed to save state:",e),this.options.onError({code:"redirect_error",message:"Failed to start OAuth flow: could not save session state",details:{error:e}}),!1}return window.location.href=n,!0}static checkOAuthReturn(e,t){const n=sessionStorage.getItem(Fe);if(!n)return!!Ge()&&(Je(),t({code:"redirect_state_missing",message:"Received an Alter Connect redirect callback, but no matching flow state exists on this origin. The return URL must be on the SAME origin (scheme, host and port) as the page that called open() — browsers scope the flow's session storage to one origin, so a callback delivered elsewhere cannot be completed.",details:{origin:window.location.origin}}),!0);try{const r=function(e){let t;try{t=JSON.parse(e)}catch{return null}if("object"!=typeof t||null===t)return null;const{timestamp:n,returnUrl:s,nonce:r}=t;return"number"==typeof n&&Number.isFinite(n)?"string"!=typeof s||0===s.length||"string"!=typeof r||0===r.length?null:{timestamp:n,returnUrl:s,nonce:r}:null}(n);if(null===r)return sessionStorage.removeItem(Fe),Ge()&&Je(),!1;const o=Date.now()-r.timestamp;if(o<0||o>3e5)return sessionStorage.removeItem(Fe),Ge()&&Je(),!1;const i=new URLSearchParams(window.location.search),a=i.get("alter_connect_success"),c=i.get("alter_connect_error");if(null===a&&null===c)return!1;if(i.get(Ve)!==r.nonce)return console.warn("[OAuth Handler] Ignoring OAuth callback parameters that do not carry this flow's nonce"),Je(),!1;if("true"===a){const n=i.get("grant_id"),o=i.get("provider"),a=i.get("account_identifier");if(!n||!o||!a)return qe(r.returnUrl),t({code:"invalid_response",message:"OAuth redirect returned incomplete grant data"}),!0;const c={grant_id:n,provider:o,provider_name:i.get("provider_name")||o,account_identifier:a,timestamp:i.get("timestamp")||(new Date).toISOString(),operation:(s=i.get("operation"),"reauth"===s?"reauth":"creation"),scopes:i.get("scopes")?.split(",")||[],status:Ne(i.get("status"))};qe(r.returnUrl);const u=[c];return e(u,{grants:u,failedGrants:[]}),!0}if(c){const e={code:i.get("error_code")||"oauth_error",message:i.get("error_description")||"OAuth authorization failed"};return qe(r.returnUrl),t(e),!0}return qe(r.returnUrl),!1}catch(e){return console.error("[OAuth Handler] Failed to check OAuth return:",e),sessionStorage.removeItem(Fe),Ge()&&Je(),!1}var s}createPopup(e){const t=window.screenX+(window.outerWidth-this.options.popupWidth)/2,n=window.screenY+(window.outerHeight-this.options.popupHeight)/2,s=[`width=${this.options.popupWidth}`,`height=${this.options.popupHeight}`,`left=${t}`,`top=${n}`,"resizable=yes","scrollbars=yes","status=yes"].join(",");return this.log("Opening OAuth popup:",e),window.open(e,"alter_oauth_popup",s)}openPopup(e){return!!this.deriveExpectedOrigin(e)&&(!!this.tryOpenWindow(e)||(this.options.onError({code:"popup_blocked",message:"Popup was blocked by browser. Please allow popups for this site."}),!1))}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+")");if(!this.popup||e.source!==this.popup)return void this.log("Rejected message from a window this handler did not open");this.log("Received message from",e.origin);const t=De(e.data);switch(t.kind){case"ignore":case"ready":return;case"notice":return this.log("Connect notice:",t.event),void this.options.onNotice(t.event,t.metadata);case"exit":return this.log("Connect exit"),this.settled=!0,this.close(),void this.options.onCancel();case"success":return this.log("Connect completion:",t.grants.length,"grants"),this.settled=!0,this.close(),void this.options.onSuccess(t.grants,t.completion);case"error":return this.log("OAuth error"),this.settled=!0,this.close(),void this.options.onError(t.error)}},window.addEventListener("message",this.messageListener)}log(...e){this.options.debug&&console.log("[OAuth Handler]",...e)}}const Ye="data-alter-connect";class Xe{constructor(t){this.iframe=null,this.messageListener=null,this.loadTimer=null,this.settled=!1,this.options={baseURL:t.baseURL,container:t.container,onSuccess:t.onSuccess,onError:t.onError,onCancel:t.onCancel,onNotice:t.onNotice||(()=>{}),debug:t.debug||!1};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}").`)}}start(e){const t=document.createElement("iframe");return t.title="Connect account",t.setAttribute(Ye,"embed"),t.style.width="100%",t.style.height="100%",t.style.border="0",t.style.display="block",this.iframe=t,this.setupMessageListener(),t.src=e,this.options.container.appendChild(t),this.armLoadTimer(),this.log("Mounted inline Connect UI"),"embed"}close(){this.log("Closing inline Connect UI"),this.clearLoadTimer(),this.messageListener&&(window.removeEventListener("message",this.messageListener),this.messageListener=null),this.iframe&&(this.iframe.isConnected&&this.iframe.remove(),this.iframe=null)}armLoadTimer(){this.loadTimer=window.setTimeout(()=>{this.loadTimer=null,this.settled||(this.log("No message from the frame within the load window"),this.settled=!0,this.close(),this.options.onError({code:"embed_load_timeout",message:"The embedded Connect page did not load. Check that the host page's origin equals the origin the session was created with, that the host page is the top-level window, and that the Alter host is reachable from this browser.",details:{timeoutMs:15e3}}))},15e3)}clearLoadTimer(){null!==this.loadTimer&&(window.clearTimeout(this.loadTimer),this.loadTimer=null)}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+")");if(!this.iframe||e.source!==this.iframe.contentWindow)return void this.log("Rejected message from a window that is not this widget");this.clearLoadTimer();const t=De(e.data);switch(t.kind){case"ignore":return;case"ready":return void this.log("Inline Connect UI reported ready");case"notice":return this.log("Connect notice:",t.event),void this.options.onNotice(t.event,t.metadata);case"exit":return this.log("User cancelled the inline Connect UI"),this.settled=!0,this.close(),void this.options.onCancel();case"success":return this.log("Connect completion:",t.grants.length,"grants"),this.settled=!0,this.close(),void this.options.onSuccess(t.grants,t.completion);case"error":return this.log("Connect error"),this.settled=!0,this.close(),void this.options.onError(t.error)}},window.addEventListener("message",this.messageListener)}log(...e){this.options.debug&&console.log("[Embed Handler]",...e)}}const Qe="min-height:44px;min-width:44px;padding:10px 16px;border-radius:6px;border:1px solid rgba(128,128,128,0.5);background-color:transparent;color:inherit;cursor:pointer;font:inherit;";class et{constructor(e){this.panel=null,this.container=e.container,this.onCancel=e.onCancel,this.oauth=new Be({baseURL:e.baseURL,popupWidth:e.popupWidth,popupHeight:e.popupHeight,onSuccess:(t,n)=>{this.removePanel(),e.onSuccess(t,n)},onError:t=>{this.removePanel(),e.onError(t)},onCancel:()=>{this.removePanel(),e.onCancel()},onNotice:e.onNotice,debug:e.debug})}start(e){return this.oauth.tryOpenWindow(e)?(this.renderPanel(),"embed"):null}close(){this.oauth.close(),this.removePanel()}removePanel(){this.panel&&(this.panel.isConnected&&this.panel.remove(),this.panel=null)}renderPanel(){const e=document.createElement("div");e.setAttribute(Ye,"direct"),e.setAttribute("role","status"),e.style.cssText="display:flex;flex-direction:column;gap:12px;padding:16px;border:1px solid rgba(128,128,128,0.35);border-radius:8px;background-color:transparent;color:inherit;font-size:14px;line-height:1.5;font-family:inherit;";const t=document.createElement("p");t.style.margin="0",t.textContent="Continue in the window that just opened.";const n=document.createElement("div");n.style.cssText="display:flex;gap:8px;flex-wrap:wrap;";const s=document.createElement("button");s.type="button",s.textContent="Show the window",s.setAttribute("data-alter-connect-action","show"),s.style.cssText=Qe,s.addEventListener("click",()=>this.oauth.focusWindow());const r=document.createElement("button");r.type="button",r.textContent="Cancel",r.setAttribute("data-alter-connect-action","cancel"),r.style.cssText=Qe,r.addEventListener("click",()=>{this.close(),this.onCancel()}),n.appendChild(s),n.appendChild(r),e.appendChild(t),e.appendChild(n),this.container.appendChild(e),this.panel=e}}const tt="0.2.0";let nt=!1;function st(e,t,n){const s=`#session=${encodeURIComponent(t)}`;return void 0===n?`${e}/sdk/oauth/connect${s}`:`${e}/sdk/oauth/connect?embed=1&embed_origin=${encodeURIComponent(n)}${s}`}class rt{constructor(r={}){if(this._flowHandler=null,this._perOpenCleanups=[],this._focusReturnTarget=null,this.pendingRedirectOutcome=null,function(e){if(void 0!==e.baseURL)throw new Error("AlterConnectConfig.baseURL is reserved and not yet supported. Omit the field to use the production Alter host.")}(r),this.config=function(e){return{debug:e.debug??!1}}(r),this._baseURL=(r.baseURL??e).replace(/\/+$/,""),this._baseURL!==e&&!nt){nt=!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 s,this._isInitialized=!0,t(this.config,"Alter Connect SDK initialized",{version:tt,baseURL:this._baseURL}),this.checkRedirectReturn()}checkRedirectReturn(){Be.checkOAuthReturn((e,n)=>{t(this.config,"OAuth redirect return - success:",e),this.deliverRedirectOutcome("success",[e,n])},e=>{t(this.config,"OAuth redirect return - error:",e),this.deliverRedirectOutcome("error",[e])})&&t(this.config,"OAuth redirect return detected and handled")}deliverRedirectOutcome(e,t){this.eventEmitter.hasListeners(e)?this.eventEmitter.emit(e,...t):this.pendingRedirectOutcome={event:e,args:t}}flushRedirectOutcome(e){const t=this.pendingRedirectOutcome;null!==t&&t.event===e&&(this.pendingRedirectOutcome=null,this.eventEmitter.emit(t.event,...t.args))}static create(e){return new rt(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");const n=this.resolveContainer(e);if(this.isOpen())return void t(this.config,"Connect UI is already open");this._focusReturnTarget=document.activeElement instanceof HTMLElement?document.activeElement:null;const s={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 or widget dismissed)"),this.handleOAuthCancel()},onNotice:(e,n)=>{t(this.config,"OAuth notice:",e),this.eventEmitter.emit("event",e,n)},debug:this.config.debug},r={popupWidth:500,popupHeight:700},o=null!==n&&!0===e.direct,i=null===n?new Be({baseURL:this._baseURL,...r,...s}):o?new et({baseURL:this._baseURL,container:n,...r,...s}):new Xe({baseURL:this._baseURL,container:n,...s});this._flowHandler=i,this.stateManager.setState({isOpen:!0,error:null,sessionToken:e.token}),this.registerEventHandlers(e);const a=st(this._baseURL,e.token,null!==n?window.location.origin:void 0);let c;t(this.config,"Connect URL:",a);let u=!1;if(i instanceof et)if(c=i.start(st(this._baseURL,e.token)),null!==c)u=!0,t(this.config,"Opened the provider window from the click");else{t(this.config,"Provider window blocked; rendering the inline tile instead");const e=new Xe({baseURL:this._baseURL,container:n,...s});this._flowHandler=e,c=e.start(a)}else c=i instanceof Xe?i.start(a):i.startOAuth(a);if(null!==c){if(e.onEvent)try{e.onEvent("connect_opened",{timestamp:(new Date).toISOString(),mode:c,...u?{direct:!0}:{}})}catch{}t(this.config,"Connect UI opened successfully")}}resolveContainer(e){if(!("container"in e)||void 0===e.container)return null;const t=e.container;if(null===t||"object"!=typeof t||1!==t.nodeType||!t.isConnected)throw this.createError("invalid_container","container must be an Element attached to the document");if(!/^https?:/.test(window.location.origin))throw this.createError("embed_unsupported_origin","Inline mode needs the host page to have an http(s) origin");if(window.self!==window.top)throw this.createError("embed_unsupported_origin","Inline mode needs the host page to be the top-level window. This page is itself inside an iframe, and the embedded Connect page can be framed by exactly one origin, so the browser would refuse it here. Open the popup flow instead (omit container).");return t}close(){if(!this._isInitialized)throw this.createError("sdk_destroyed","Cannot call close() - SDK instance has been destroyed");t(this.config,"Closing Connect UI");const e=this.stateManager.get("isOpen");this._flowHandler&&(this._flowHandler.close(),this._flowHandler=null),this._perOpenCleanups.forEach(e=>e()),this._perOpenCleanups=[],this.stateManager.setState({isOpen:!1}),this.restoreFocus(),e&&this.eventEmitter.emit("close")}restoreFocus(){const e=this._focusReturnTarget;if(this._focusReturnTarget=null,null===e||!e.isConnected)return;const t=document.activeElement;null!==t&&t!==document.body||e.focus()}destroy(){this._isInitialized&&(t(this.config,"Destroying SDK instance"),this._flowHandler&&(this._flowHandler.close(),this._flowHandler=null),this.stateManager.get("isOpen")&&this.stateManager.setState({isOpen:!1}),this.restoreFocus(),this.pendingRedirectOutcome=null,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");const n=this.eventEmitter.on(e,t);return this.flushRedirectOutcome(e),n}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 tt}cleanupHandler(){this._flowHandler=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")}releaseAfterTerminal(e){try{e()}finally{this._isInitialized&&this.close()}}registerEventHandlers(e){this._perOpenCleanups.push(this.eventEmitter.on("success",(t,n)=>{this.releaseAfterTerminal(()=>e.onSuccess?.(t,n))})),this._perOpenCleanups.push(this.eventEmitter.on("exit",()=>{this.releaseAfterTerminal(()=>e.onExit?.())})),this._perOpenCleanups.push(this.eventEmitter.on("error",t=>{this.releaseAfterTerminal(()=>e.onError?.(t))})),e.onEvent&&this._perOpenCleanups.push(this.eventEmitter.on("event",(t,n)=>{e.onEvent(t,n)}))}createError(e,t,n){const s=new Error(t);return s.code=e,s.details=n,s}}exports.default=rt;
2
2
  //# sourceMappingURL=alter-connect.cjs.js.map