@faable/auth-js 1.9.2 → 2.0.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
@@ -144,9 +144,71 @@ await auth.changePassword({ email: 'user@example.com' })
144
144
 
145
145
  ### Sign out
146
146
 
147
+ By default `signOut()` (global scope, in a browser) **navigates the page to the
148
+ auth server's `/logout`** to clear the SSO cookie, then returns to `returnTo` if
149
+ you pass one. This matters: the SSO cookie lives on the auth domain, so a
150
+ cross-origin `fetch` from your app can neither send nor clear it. Without the
151
+ navigation the SSO session survives and the next `signInWith…` silently re-logs
152
+ the previous user, ignoring the requested connection.
153
+
154
+ ```ts
155
+ await auth.signOut() // clears local + redirects to /logout to clear the SSO cookie
156
+ await auth.signOut({ returnTo: 'https://app.example.com/bye' }) // + landing page
157
+ await auth.signOut({ scope: 'local' }) // only this device's storage, no redirect
158
+ await auth.signOut({ redirect: false }) // legacy: local + best-effort fetch, no nav
159
+ ```
160
+
161
+ `returnTo` maps to the OIDC `post_logout_redirect_uri` and **must be registered
162
+ as a logout URL on the client**, or the server responds `400`.
163
+
164
+ On the redirect path the returned promise does not resolve (the browser is
165
+ navigating away) — do not re-enable UI after the `await`. To drive the
166
+ navigation yourself, build the URL with `getLogoutUrl`:
167
+
168
+ ```ts
169
+ window.location.assign(
170
+ auth.getLogoutUrl({ returnTo: 'https://app.example.com' })
171
+ )
172
+ ```
173
+
174
+ ## Error handling
175
+
176
+ The client has **one error contract, applied uniformly**: every asynchronous
177
+ method resolves with `{ data, error }` and **never throws for an expected
178
+ failure** (bad credentials, wrong OTP, missing session, network error…). On
179
+ success `error` is `null`; on failure `data` is `null` and `error` is an
180
+ `AuthError`. Always check `error` before reading `data`:
181
+
182
+ ```ts
183
+ const { data, error } = await auth.signInWithOtp({ username, otp })
184
+ if (error) {
185
+ showError(error.message)
186
+ return
187
+ }
188
+ useSession(data.session)
189
+ ```
190
+
191
+ The only thing that throws is `createClient` itself, and only for a
192
+ misconfiguration (missing `domain` / `clientId`) — a programming error you fix
193
+ once, not a runtime condition to catch.
194
+
195
+ This applies to `signInWithOauthConnection`, `signInWithUsernamePassword`,
196
+ `signUp`, `signInWithOtp`, `signInWithPasswordless`, `changePassword`,
197
+ `changeEmail`, `signOut`, `getSession`, `setSession`, `refreshSession`,
198
+ `initialize` and `handleRedirectCallback`. Their return types (`AuthResult<T>`,
199
+ `AuthResponse`, `OAuthResponse`) are all variants of the same shape.
200
+
201
+ ### Prefer throw-style? Use `unwrap`
202
+
203
+ If your code path would rather let errors propagate (a server handler, a
204
+ `try/catch`, a wrapper that normalizes everything to throws), wrap the call in
205
+ `unwrap` instead of hand-writing `if (error) throw error`:
206
+
147
207
  ```ts
148
- await auth.signOut() // global all sessions for this user
149
- await auth.signOut({ scope: 'local' }) // only this device
208
+ import { unwrap } from '@faable/auth-js'
209
+
210
+ // returns data on success, throws the AuthError on failure
211
+ const { session } = unwrap(await auth.signInWithOtp({ username, otp }))
150
212
  ```
151
213
 
152
214
  ## Sessions and state changes
@@ -4,9 +4,10 @@ export default class FaableAuthApi extends BaseLog {
4
4
  base_url: string;
5
5
  constructor(base_url: string, config: BaseLogOptions);
6
6
  protected extraPrint(): string;
7
- signOut(params: {
7
+ signOut({ credentials, ...params }: {
8
8
  client_id: string;
9
9
  returnTo?: string;
10
+ credentials?: RequestCredentials;
10
11
  }): Promise<{
11
12
  data: null;
12
13
  error: AuthError | null;
@@ -5,7 +5,7 @@ import { AuthError } from './lib/errors';
5
5
  import { Deferred } from './lib/helpers';
6
6
  import { getSessionFromCookies } from './lib/nextjs';
7
7
  import { cookieStorageAdapter } from './lib/storage/cookie-storage';
8
- import { AuthFlowType, CallRefreshTokenResult, InitializeResult, OAuthResponse, SignInWithOAuthConnection, Subscription, SupportedStorage } from './lib/types';
8
+ import { AuthFlowType, AuthResult, CallRefreshTokenResult, InitializeResult, OAuthResponse, SignInWithOAuthConnection, Subscription, SupportedStorage } from './lib/types';
9
9
  import { AuthChangeEvent, AuthResponse, FaableAuthClientConfig } from './lib/types';
10
10
  import { Session, SignOut } from './lib/types';
11
11
  import { Lock } from './lock/Lock';
@@ -295,10 +295,7 @@ export declare class FaableAuthClient extends Base {
295
295
  redirectTo?: string;
296
296
  state?: string;
297
297
  audience?: string;
298
- }): Promise<{
299
- data: null;
300
- error: AuthError | null;
301
- }>;
298
+ }): Promise<AuthResult<null>>;
302
299
  /**
303
300
  * Registers a new user against the tenant's database connection with an
304
301
  * email + password, then signs them in — so an email/password signup form
@@ -347,10 +344,7 @@ export declare class FaableAuthClient extends Base {
347
344
  redirectTo?: string;
348
345
  state?: string;
349
346
  audience?: string;
350
- }): Promise<{
351
- data: null;
352
- error: AuthError | null;
353
- }>;
347
+ }): Promise<AuthResult<null>>;
354
348
  /**
355
349
  * Completes a passwordless login by exchanging an OTP code for a session.
356
350
  *
@@ -399,10 +393,7 @@ export declare class FaableAuthClient extends Base {
399
393
  email: string;
400
394
  type: 'code' | 'link';
401
395
  audience?: string;
402
- }): Promise<{
403
- data: any;
404
- error: AuthError | null;
405
- }>;
396
+ }): Promise<AuthResult<any>>;
406
397
  /**
407
398
  * Triggers a "change your password" email for a database-connection user.
408
399
  *
@@ -420,10 +411,7 @@ export declare class FaableAuthClient extends Base {
420
411
  */
421
412
  changePassword(params: {
422
413
  email: string;
423
- }): Promise<{
424
- data: unknown;
425
- error: AuthError | null;
426
- }>;
414
+ }): Promise<AuthResult<unknown>>;
427
415
  /**
428
416
  * Resolves the signed-in user's id from a session. Prefers the userinfo
429
417
  * shape (`user.id`) returned by `/me`, falls back to a `sub` claim on the
@@ -461,10 +449,7 @@ export declare class FaableAuthClient extends Base {
461
449
  new_email: string;
462
450
  verification_mode?: 'new_only' | 'old_and_new';
463
451
  redirect_uri?: string;
464
- }): Promise<{
465
- data: unknown;
466
- error: AuthError | null;
467
- }>;
452
+ }): Promise<AuthResult<unknown>>;
468
453
  /**
469
454
  * Builds the tenant's `/authorize` URL without redirecting the browser.
470
455
  *
@@ -494,6 +479,36 @@ export declare class FaableAuthClient extends Base {
494
479
  scope?: string;
495
480
  response_type?: string;
496
481
  audience?: string;
482
+ /**
483
+ * Extra `/authorize` params merged in as-is — e.g.
484
+ * `{ prompt: 'select_account' }` or `{ prompt: 'login' }` to force
485
+ * account selection / re-authentication even when an SSO session exists.
486
+ */
487
+ queryParams?: {
488
+ [key: string]: string;
489
+ };
490
+ }): string;
491
+ /**
492
+ * Builds the tenant's RP-initiated logout URL
493
+ * (`{domain}/logout?client_id=…`).
494
+ *
495
+ * Navigate the browser to it (top-level, not `fetch`) to end the session and
496
+ * clear the auth server's SSO cookie — the only reliable way to do that from
497
+ * another origin. {@link FaableAuthClient.signOut} does this for you by
498
+ * default; use this helper when you want to drive the navigation yourself.
499
+ *
500
+ * @param options.returnTo Where to send the browser after logout, mapped to
501
+ * the OIDC `post_logout_redirect_uri`. Must be registered as a logout URL
502
+ * on the client or the server responds `400`.
503
+ * @example
504
+ * ```ts
505
+ * window.location.assign(auth.getLogoutUrl({ returnTo: 'https://app.example.com' }))
506
+ * ```
507
+ * @see {@link https://faable.com/docs/auth/oidc/logout | Logout}
508
+ * @category Authorize URLs
509
+ */
510
+ getLogoutUrl(options?: {
511
+ returnTo?: string;
497
512
  }): string;
498
513
  /**
499
514
  * Redirects the current window to the tenant's `/authorize` endpoint.
@@ -618,16 +633,28 @@ export declare class FaableAuthClient extends Base {
618
633
  * access token JWT itself remains valid until its `exp` — keep that
619
634
  * expiry short.
620
635
  *
636
+ * **By default (global scope, in a browser) this navigates the page to the
637
+ * auth server's `/logout` to also clear the SSO cookie**, then returns to
638
+ * `returnTo` if given. Without that navigation the SSO session survives on
639
+ * the auth domain and the next `/authorize` silently re-logs the previous
640
+ * user — a cross-origin `fetch` cannot clear that cookie. On this path the
641
+ * returned promise does not resolve (the browser is unloading). Pass
642
+ * `{ redirect: false }` to keep the legacy fetch-only behaviour, or use
643
+ * {@link FaableAuthClient.getLogoutUrl} to drive the navigation yourself.
644
+ *
621
645
  * Scopes:
622
- * - `'global'` (default) — invalidate all refresh tokens for the user
623
- * - `'local'` only clear this client's storage
646
+ * - `'global'` (default) — invalidate all refresh tokens for the user and,
647
+ * in a browser, redirect to `/logout` to clear the SSO cookie
648
+ * - `'local'` — only clear this client's storage (no redirect)
624
649
  * - `'others'` — invalidate every refresh token except this device's; no
625
- * `SIGNED_OUT` event is fired locally
650
+ * `SIGNED_OUT` event is fired locally (no redirect)
626
651
  *
627
652
  * @example
628
653
  * ```ts
629
- * await auth.signOut() // global — all sessions for this user
630
- * await auth.signOut({ scope: 'local' }) // only this device
654
+ * await auth.signOut() // global — clears local + auth SSO cookie via redirect
655
+ * await auth.signOut({ returnTo: 'https://app.example.com/bye' }) // + landing
656
+ * await auth.signOut({ redirect: false }) // legacy: local + best-effort fetch
657
+ * await auth.signOut({ scope: 'local' }) // only this device, no redirect
631
658
  * ```
632
659
  * @see {@link https://faable.com/docs/auth/oidc/logout | Logout}
633
660
  * @category Sign out
@@ -635,7 +662,7 @@ export declare class FaableAuthClient extends Base {
635
662
  signOut(options?: SignOut): Promise<{
636
663
  error: AuthError | null;
637
664
  }>;
638
- protected _signOut({ scope }?: SignOut): Promise<{
665
+ protected _signOut({ scope, redirect, returnTo }?: SignOut): Promise<{
639
666
  error: AuthError | null;
640
667
  }>;
641
668
  /**
@@ -2,6 +2,7 @@ import { FaableAuthClient, cookieStorageAdapter, getSessionFromCookies } from '.
2
2
  import { createClient } from './createClient';
3
3
  import { AuthError } from './lib/errors';
4
4
  import { Session, User } from './lib/types';
5
- import type { AuthChangeEvent, AuthFlowType, AuthResponse, CookieOptions, FaableAuthClientConfig, OAuthResponse, Provider, SignInWithOAuthConnection, SignOut, Subscription, SupportedStorage } from './lib/types';
6
- export { Session, User, FaableAuthClient, AuthError, createClient, cookieStorageAdapter, getSessionFromCookies };
7
- export type { FaableAuthClientConfig, SignInWithOAuthConnection, AuthResponse, AuthChangeEvent, Subscription, SignOut, SupportedStorage, CookieOptions, OAuthResponse, AuthFlowType, Provider };
5
+ import type { AuthChangeEvent, AuthFlowType, AuthResponse, AuthResult, CookieOptions, FaableAuthClientConfig, OAuthResponse, Provider, SignInWithOAuthConnection, SignOut, Subscription, SupportedStorage } from './lib/types';
6
+ import { unwrap } from './lib/unwrap';
7
+ export { Session, User, FaableAuthClient, AuthError, createClient, cookieStorageAdapter, getSessionFromCookies, unwrap };
8
+ export type { FaableAuthClientConfig, SignInWithOAuthConnection, AuthResponse, AuthResult, AuthChangeEvent, Subscription, SignOut, SupportedStorage, CookieOptions, OAuthResponse, AuthFlowType, Provider };
@@ -396,6 +396,14 @@ export type SignInWithOAuthConnection = {
396
396
  * authorize URL on success (useful when `skipBrowserRedirect: true` so you
397
397
  * can drive the navigation yourself) or an {@link AuthError} on failure.
398
398
  */
399
+ /**
400
+ * Result of {@link FaableAuthClient.signInWithOauthConnection}. A precise
401
+ * variant of {@link AuthResult} — the same never-throw contract applies.
402
+ *
403
+ * Note: on the browser redirect success path the method's promise does not
404
+ * resolve at all (the page is navigating away), so this value is only observed
405
+ * when `skipBrowserRedirect: true` or in non-navigating runtimes.
406
+ */
399
407
  export type OAuthResponse = {
400
408
  data: {
401
409
  url: string;
@@ -444,9 +452,32 @@ export interface Session {
444
452
  token_type: string;
445
453
  user: User;
446
454
  }
455
+ /**
456
+ * The uniform result shape every asynchronous method on
457
+ * {@link FaableAuthClient} resolves to.
458
+ *
459
+ * **The whole client follows one error contract: methods never throw for
460
+ * expected failures — they resolve with the error in `error`.** On success
461
+ * `error` is `null` and `data` holds the payload; on failure `data` is `null`
462
+ * and `error` is an {@link AuthError}. Always check `error` before reading
463
+ * `data`. The only thing that throws is `createClient` itself (missing
464
+ * `domain`/`clientId` — a programming error, not a runtime one).
465
+ *
466
+ * If you prefer throw-style control flow, wrap a call in {@link unwrap} instead
467
+ * of hand-writing `if (error) throw error`.
468
+ *
469
+ * `AuthResponse` and `OAuthResponse` are the two richer, discriminated variants
470
+ * of this same contract.
471
+ */
472
+ export type AuthResult<Data = unknown> = {
473
+ data: Data | null;
474
+ error: AuthError | null;
475
+ };
447
476
  /**
448
477
  * Discriminated union returned by every sign-in / set-session / refresh
449
478
  * method. Always check `error` first — `data` fields are `null` on failure.
479
+ * A precise variant of {@link AuthResult}; the same never-throw contract
480
+ * applies.
450
481
  */
451
482
  export type AuthResponse = {
452
483
  data: {
@@ -505,6 +536,31 @@ export type SignOut = {
505
536
  * `SIGNED_OUT` event is fired locally
506
537
  */
507
538
  scope?: 'global' | 'local' | 'others';
539
+ /**
540
+ * Whether to end the session with a top-level navigation to the auth
541
+ * server's `/logout` (RP-initiated logout). **Defaults to `true`** for the
542
+ * `global` scope in a browser.
543
+ *
544
+ * This is required to clear the auth server's SSO cookie: it lives on the
545
+ * auth domain, so a cross-origin `fetch` from your app can neither send nor
546
+ * clear it. Without the navigation the SSO session survives and the next
547
+ * `/authorize` silently re-logs the previous user, ignoring the requested
548
+ * connection.
549
+ *
550
+ * Set to `false` to keep the legacy behaviour (clear local storage + a
551
+ * best-effort cross-origin `fetch` to `/logout`) — e.g. when your app and
552
+ * the auth server share a site, or you drive the navigation yourself with
553
+ * {@link FaableAuthClient.getLogoutUrl}. Ignored for the `local`/`others`
554
+ * scopes and outside the browser.
555
+ */
556
+ redirect?: boolean;
557
+ /**
558
+ * Where the auth server should send the browser back to after logging out,
559
+ * mapped to the OIDC `post_logout_redirect_uri`. **Must be registered as a
560
+ * logout URL on the client** or the server responds `400`. Only used on the
561
+ * redirect path.
562
+ */
563
+ returnTo?: string;
508
564
  };
509
565
  export type InitializeResult = {
510
566
  error: AuthError | null;
@@ -0,0 +1,28 @@
1
+ import { AuthError } from './errors';
2
+ /**
3
+ * Converts a `{ data, error }` result from any {@link FaableAuthClient} method
4
+ * into throw-style control flow: returns `data` on success, throws the
5
+ * {@link AuthError} on failure.
6
+ *
7
+ * Every async method on the client follows the never-throw contract — expected
8
+ * failures resolve in `error` rather than rejecting. That is the right default
9
+ * for most UIs, but when you'd rather let an error propagate (a server handler,
10
+ * a `try/catch`, a wrapper that normalizes everything to throws), `unwrap`
11
+ * saves you from hand-writing `if (error) throw error` at every call site.
12
+ *
13
+ * @example
14
+ * ```ts
15
+ * import { unwrap } from '@faable/auth-js'
16
+ *
17
+ * // throws AuthError on a wrong OTP instead of returning { error }
18
+ * const { session } = unwrap(await auth.signInWithOtp({ username, otp }))
19
+ * ```
20
+ *
21
+ * @param result Any `{ data, error }` result returned by the client.
22
+ * @returns The `data` payload when `error` is `null`.
23
+ * @throws {AuthError} The `error` from the result when it is non-null.
24
+ */
25
+ export declare function unwrap<Data>(result: {
26
+ data: Data;
27
+ error: AuthError | null;
28
+ }): Data;
@@ -1,7 +1,7 @@
1
1
  /*!
2
- * @faable/auth-js v1.9.2
2
+ * @faable/auth-js v2.0.0
3
3
  * (c) 2026
4
4
  * @license SEE LICENSE.md
5
5
  */
6
- !function(e){"use strict";var t=function(e,r){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r])},t(e,r)};function r(e,r){if("function"!=typeof r&&null!==r)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");function n(){this.constructor=e}t(e,r),e.prototype=null===r?Object.create(r):(n.prototype=r.prototype,new n)}var n=function(){return n=Object.assign||function(e){for(var t,r=1,n=arguments.length;r<n;r++)for(var i in t=arguments[r])Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i]);return e},n.apply(this,arguments)};function i(e,t,r,n){return new(r||(r=Promise))(function(i,s){function o(e){try{u(n.next(e))}catch(e){s(e)}}function a(e){try{u(n.throw(e))}catch(e){s(e)}}function u(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(o,a)}u((n=n.apply(e,t||[])).next())})}function s(e,t){var r,n,i,s={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]},o=Object.create(("function"==typeof Iterator?Iterator:Object).prototype);return o.next=a(0),o.throw=a(1),o.return=a(2),"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function a(a){return function(u){return function(a){if(r)throw new TypeError("Generator is already executing.");for(;o&&(o=0,a[0]&&(s=0)),s;)try{if(r=1,n&&(i=2&a[0]?n.return:a[0]?n.throw||((i=n.return)&&i.call(n),0):n.next)&&!(i=i.call(n,a[1])).done)return i;switch(n=0,i&&(a=[2&a[0],i.value]),a[0]){case 0:case 1:i=a;break;case 4:return s.label++,{value:a[1],done:!1};case 5:s.label++,n=a[1],a=[0];continue;case 7:a=s.ops.pop(),s.trys.pop();continue;default:if(!(i=s.trys,(i=i.length>0&&i[i.length-1])||6!==a[0]&&2!==a[0])){s=0;continue}if(3===a[0]&&(!i||a[1]>i[0]&&a[1]<i[3])){s.label=a[1];break}if(6===a[0]&&s.label<i[1]){s.label=i[1],i=a;break}if(i&&s.label<i[2]){s.label=i[2],s.ops.push(a);break}i[2]&&s.ops.pop(),s.trys.pop();continue}a=t.call(e,s)}catch(e){a=[6,e],n=0}finally{r=i=0}if(5&a[0])throw a[1];return{value:a[0]?a[1]:void 0,done:!0}}([a,u])}}}function o(e,t,r){if(r||2===arguments.length)for(var n,i=0,s=t.length;i<s;i++)!n&&i in t||(n||(n=Array.prototype.slice.call(t,0,i)),n[i]=t[i]);return e.concat(n||Array.prototype.slice.call(t))}"function"==typeof SuppressedError&&SuppressedError;var a="0.0.0",u=function(){function e(e){void 0===e&&(e={}),this.logger=console.log,this.logDebugMessages=!!e.debug,"function"==typeof e.debug&&(this.logger=e.debug)}return e.prototype._debug=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];if(this.logDebugMessages){var r=this.extraPrint?this.extraPrint():"";this.logger.apply(this,o(["FaableAuth@".concat(r," (").concat(a,") ").concat((new Date).toISOString())],e,!1))}return this},e}(),c=function(e){function t(r){void 0===r&&(r={});var n=e.call(this,r)||this;return n.instanceID=t.nextInstanceID,t.nextInstanceID+=1,n}return r(t,e),t.prototype.extraPrint=function(){return this.instanceID.toString()},t.nextInstanceID=0,t}(u),l="undefined"!=typeof window?window:void 0,h="undefined"!=typeof globalThis?globalThis:l,d=null==h?void 0:h.document,f=h.fetch,v=function(e){void 0===e&&(e={});var t={"x-faable-client":"auth-js/".concat(a)};return(null==e?void 0:e.token)&&(t=n(n({},t),{Authorization:"Bearer ".concat(null==e?void 0:e.token)})),n(n({},null==e?void 0:e.headers),t)},p=function(e){for(var t=[],r=1;r<arguments.length;r++)t[r-1]=arguments[r];return i(void 0,o([e],t,!0),void 0,function(e,t){var r,n,i;return void 0===t&&(t={}),s(this,function(s){switch(s.label){case 0:return t.raw?[4,e.text()]:[3,2];case 1:return n=s.sent(),[3,4];case 2:return[4,e.json()];case 3:n=s.sent(),s.label=4;case 4:return r=n,e.status>=300?[2,{data:r,error:t.raw?null===(i=JSON.parse(r))||void 0===i?void 0:i.message:null==r?void 0:r.message}]:[2,{data:r,error:null}]}})})},b=function(e,t){for(var r=[],a=2;a<arguments.length;a++)r[a-2]=arguments[a];return i(void 0,o([e,t],r,!0),void 0,function(e,t,r){var i;return void 0===r&&(r={}),s(this,function(s){switch(s.label){case 0:return s.trys.push([0,3,,4]),[4,f(e,{method:"POST",body:JSON.stringify(t),headers:n(n({},v(r)),{"Content-Type":"application/json"})})];case 1:return i=s.sent(),[4,p(i,r)];case 2:return[2,s.sent()];case 3:return[2,{data:null,error:s.sent()}];case 4:return[2]}})})},_=function(e){for(var t=[],r=1;r<arguments.length;r++)t[r-1]=arguments[r];return i(void 0,o([e],t,!0),void 0,function(e,t){var r;return void 0===t&&(t={}),s(this,function(i){switch(i.label){case 0:return i.trys.push([0,3,,4]),[4,f(e,n(n({},t),{method:"GET",headers:v(t)}))];case 1:return r=i.sent(),[4,p(r,t)];case 2:return[2,i.sent()];case 3:return[2,{data:null,error:i.sent()}];case 4:return[2]}})})},g=function(e){function t(t,r){var n=e.call(this,r)||this;return n.base_url=t,n}return r(t,e),t.prototype.extraPrint=function(){return"api"},t.prototype.signOut=function(e){return i(this,void 0,void 0,function(){var t,r;return s(this,function(n){switch(n.label){case 0:return t="".concat(this.base_url,"/logout?").concat(new URLSearchParams(e)),this._debug("requesting ".concat(t)),[4,_(t)];case 1:return r=n.sent(),this._debug(r),r.error?[2,{error:r.error,data:null}]:[2,{error:null,data:null}]}})})},t}(u),y=function(e,t){return e.response_type||(t?"code":"token")},w=function(e,t,r){return i(void 0,void 0,void 0,function(){return s(this,function(n){switch(n.label){case 0:return[4,e.setItem(t,JSON.stringify(r))];case 1:return n.sent(),[2]}})})},m=function(e,t){return i(void 0,void 0,void 0,function(){var r;return s(this,function(n){switch(n.label){case 0:return[4,e.getItem(t)];case 1:if(!(r=n.sent()))return[2,null];try{return[2,JSON.parse(r)]}catch(e){return[2,r]}return[2]}})})},k=function(e,t,r){return i(void 0,[e,t,r],void 0,function(e,t,r){var n,i=r.verifier,o=r.redirectType,a=r.returnTo,u=r.now,c=void 0===u?Date.now():u;return s(this,function(r){switch(r.label){case 0:return n={verifier:i,createdAt:c},o&&(n.redirectType=o),a&&(n.returnTo=a),[4,w(e,t,n)];case 1:return r.sent(),[2]}})})},S=function(e,t){for(var r=[],n=2;n<arguments.length;n++)r[n-2]=arguments[n];return i(void 0,o([e,t],r,!0),void 0,function(e,t,r){var n,i,o=(void 0===r?{}:r).now,a=void 0===o?Date.now():o;return s(this,function(r){switch(r.label){case 0:return[4,m(e,t)];case 1:return n=r.sent(),"object"!=typeof(s=n)||null===s||"string"!=typeof s.verifier||"number"!=typeof s.createdAt?[2,null]:a-n.createdAt>6e5?[4,e.removeItem(t)]:[3,3];case 2:return r.sent(),[2,null];case 3:return i={verifier:n.verifier},n.redirectType&&(i.redirectType=n.redirectType),n.returnTo&&(i.returnTo=n.returnTo),[2,i]}var s})})};function T(e){return("0"+e.toString(16)).substr(-2)}function I(e){return i(this,void 0,void 0,function(){var t,r,n,i;return s(this,function(s){switch(s.label){case 0:return t=new TextEncoder,r=t.encode(e),[4,crypto.subtle.digest("SHA-256",r)];case 1:return n=s.sent(),i=new Uint8Array(n),[2,Array.from(i).map(function(e){return String.fromCharCode(e)}).join("")]}})})}function x(e){return i(this,void 0,void 0,function(){var t;return s(this,function(r){switch(r.label){case 0:return"undefined"!=typeof crypto&&void 0!==crypto.subtle&&"undefined"!=typeof TextEncoder?[4,I(e)]:(console.warn("WebCrypto API is not supported. Code challenge method will default to use plain instead of sha256."),[2,e]);case 1:return t=r.sent(),[2,(n=t,btoa(n).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,""))]}var n})})}function A(e,t){return i(this,arguments,void 0,function(e,t,r,n){var i,o;return void 0===r&&(r=!1),s(this,function(s){switch(s.label){case 0:return i=function(){if("undefined"==typeof crypto||"function"!=typeof crypto.getRandomValues)throw new Error("Web Crypto API is required to generate a PKCE code verifier");var e=new Uint32Array(56);return crypto.getRandomValues(e),Array.from(e,T).join("")}(),[4,k(e,"".concat(t,"-code-verifier"),{verifier:i,redirectType:r?"PASSWORD_RECOVERY":void 0,returnTo:n})];case 1:return s.sent(),[4,x(i)];case 2:return[2,[o=s.sent(),i===o?"plain":"S256"]]}})})}var R=function(){return"undefined"!=typeof document},C={tested:!1,writable:!1},E=function(){if(!R())return!1;try{if("object"!=typeof globalThis.localStorage)return!1}catch(e){return!1}if(C.tested)return C.writable;var e="lswt-".concat(Math.random()).concat(Math.random());try{globalThis.localStorage.setItem(e,e),globalThis.localStorage.removeItem(e),C.tested=!0,C.writable=!0}catch(e){C.tested=!0,C.writable=!1}return C.writable};function U(e){var t,r,i=e.data,s=null;if(!i)throw new Error("Bad session response");return function(e){return!!e.access_token&&!!e.refresh_token&&!!e.expires_in}(i)&&(s=n({},i),!i.expires_at&&i.expires_in&&(s.expires_at=(r=i.expires_in,Math.round(Date.now()/1e3)+r))),{data:{session:s,user:null!==(t=i.user)&&void 0!==t?t:i},error:null}}var P=function(){function e(){var t=this;this.promise=new e.promiseConstructor(function(e,r){t.resolve=e,t.reject=r})}return e.promiseConstructor=Promise,e}();function L(e,t){var r=this;return new Promise(function(n,o){i(r,void 0,void 0,function(){var r,i,a;return s(this,function(s){switch(s.label){case 0:r=0,s.label=1;case 1:if(!(r<1/0))return[3,6];s.label=2;case 2:return s.trys.push([2,4,,5]),[4,e(r)];case 3:return i=s.sent(),t(r,null,i)?[3,5]:(n(i),[2]);case 4:return a=s.sent(),t(r,a)?[3,5]:(o(a),[2]);case 5:return r++,[3,1];case 6:return[2]}})})})}function O(e){return i(this,void 0,void 0,function(){return s(this,function(t){return[2,new Promise(function(t){setTimeout(function(){return t(null)},e)})]})})}var D=function(){function e(e,t){var r=this;if(this.debug=t,this.channel=null,this.subscribers=new Map,"undefined"!=typeof globalThis&&"function"==typeof globalThis.BroadcastChannel&&e)try{this.channel=new globalThis.BroadcastChannel(e),this.channel.addEventListener("message",function(e){return i(r,void 0,void 0,function(){return s(this,function(t){switch(t.label){case 0:return this.debug("broadcast_sync: received notification from another tab",e),[4,this.dispatch(e.data.event,e.data.session,!1)];case 1:return t.sent(),[2]}})})})}catch(e){console.error("Failed to create BroadcastChannel; cross-tab sync disabled",e)}}return e.prototype.subscribe=function(e){var t=this,r="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(e){var t=16*Math.random()|0;return("x"==e?t:3&t|8).toString(16)}),n={id:r,callback:e,unsubscribe:function(){t.subscribers.delete(r)}};return this.subscribers.set(r,n),{subscription:n}},e.prototype.notify=function(e,t){return i(this,arguments,void 0,function(e,t,r){return void 0===r&&(r=!0),s(this,function(n){switch(n.label){case 0:return r&&this.channel&&this.channel.postMessage({event:e,session:t}),[4,this.dispatch(e,t,r)];case 1:return n.sent(),[2]}})})},e.prototype.dispatch=function(e,t,r){return i(this,void 0,void 0,function(){var r,n,o,a=this;return s(this,function(u){switch(u.label){case 0:return r=[],n=Array.from(this.subscribers.values()).map(function(n){return i(a,void 0,void 0,function(){var i;return s(this,function(s){switch(s.label){case 0:return s.trys.push([0,2,,3]),[4,n.callback(e,t)];case 1:return s.sent(),[3,3];case 2:return i=s.sent(),r.push(i),[3,3];case 3:return[2]}})})}),[4,Promise.all(n)];case 1:if(u.sent(),r.length>0){for(o=0;o<r.length;o+=1)console.error(r[o]);throw r[0]}return[2]}})})},e.prototype.close=function(){var e;this.subscribers.clear();try{null===(e=this.channel)||void 0===e||e.close()}catch(e){}this.channel=null},e}(),z="faableauth",N=function(e){function t(t,r,n){var i=e.call(this,t)||this;return i.__isAuthError=!0,i.name="AuthError",i.status=r,i.code=n,i}return r(t,e),t}(Error),q=function(e){function t(t,r,n,i){var s=e.call(this,t,n,i)||this;return s.name=r,s.status=n,s}return r(t,e),t}(N),j=function(e){function t(){return e.call(this,"Auth session missing!","AuthSessionMissingError",400,void 0)||this}return r(t,e),t}(q);function K(e){return"object"==typeof e&&null!==e&&"__isAuthError"in e}var M=function(e){function t(t,r,n){var i=e.call(this,t,r,n)||this;return i.name="AuthApiError",i.status=r,i.code=n,i}return r(t,e),t}(N);var F=function(e){function t(t,r){void 0===r&&(r=null);var n=e.call(this,t,"AuthImplicitGrantRedirectError",500,void 0)||this;return n.details=null,n.details=r,n}return r(t,e),t.prototype.toJSON=function(){return{name:this.name,message:this.message,status:this.status,details:this.details}},t}(q),V=function(e){function t(t,r){void 0===r&&(r=null);var n=e.call(this,t,"AuthPKCEGrantCodeExchangeError",500,void 0)||this;return n.details=null,n.details=r,n}return r(t,e),t.prototype.toJSON=function(){return{name:this.name,message:this.message,status:this.status,details:this.details}},t}(q),W=function(e){function t(t,r){var n=e.call(this,t)||this;return n.name="AuthUnknownError",n.originalError=r,n}return r(t,e),t}(N),G=function(e){function t(){return e.call(this,"Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)||this}return r(t,e),t}(q);function J(e){return K(e)&&"AuthRetryableFetchError"===e.name}function B(){if(!l)throw new Error("No window in environment");return l}!function(e){function t(t,r){return e.call(this,t,"AuthRetryableFetchError",r,void 0)||this}r(t,e)}(q);var $={redirect:function(e){B().location=e},getDocument:function(){return B().document},getWindow:B};function H(e){var t=e.split(".");if(3!==t.length)throw new Error("JWT is not valid: not a JWT structure");if(!/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}=?$|[a-z0-9_-]{2}(==)?$)$/i.test(t[1]))throw new Error("JWT is not valid: payload is not in base64url format");var r=t[1];return JSON.parse(function(e){var t,r,n,i,s,o,a="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",u="",c=0;for(e=e.replace("-","+").replace("_","/");c<e.length;)t=a.indexOf(e.charAt(c++))<<2|(i=a.indexOf(e.charAt(c++)))>>4,r=(15&i)<<4|(s=a.indexOf(e.charAt(c++)))>>2,n=(3&s)<<6|(o=a.indexOf(e.charAt(c++))),u+=String.fromCharCode(t),64!=s&&0!=r&&(u+=String.fromCharCode(r)),64!=o&&0!=n&&(u+=String.fromCharCode(n));return u}(r))}var Y=function(e,t){if(!e)return null;var r="function"==typeof e.get?function(t){var r;return null===(r=e.get(t))||void 0===r?void 0:r.value}:function(t){return e[t]},n=r(t);if(n)return n;for(var i=[],s=0;;s++){var o=r("".concat(t,".").concat(s));if(!o)break;i.push(o)}return i.length?i.join(""):null},Q=function(e){return"object"==typeof e&&null!==e&&"access_token"in e&&"refresh_token"in e&&"expires_at"in e},X=function(e){var t=new Map;if(!e)return t;for(var r=0,n=e.split(";");r<n.length;r++){var i=n[r].trim();if(i){var s=i.indexOf("=");if(!(s<0)){var o=Z(i.slice(0,s).trim()),a=Z(i.slice(s+1).trim());o&&t.set(o,a)}}}return t},Z=function(e){try{return decodeURIComponent(e)}catch(t){return e}},ee=function(e,t,r){var n="".concat(encodeURIComponent(e),"=").concat(encodeURIComponent(t));return void 0!==r.maxAge&&(n+="; Max-Age=".concat(r.maxAge)),r.domain&&(n+="; Domain=".concat(r.domain)),r.path&&(n+="; Path=".concat(r.path)),r.sameSite&&(n+="; SameSite=".concat(r.sameSite)),(!0===r.secure||"None"===r.sameSite)&&(n+="; Secure"),n},te=function(e,t){return ee(e,"",{domain:t.domain,path:t.path,sameSite:t.sameSite,secure:t.secure,maxAge:0})},re=3200,ne=function(e,t){return"".concat(e,".").concat(t)},ie=function(e,t){var r="".concat(t,"."),n=[];return e.forEach(function(e,t){if(t.startsWith(r)){var i=t.slice(r.length);/^\d+$/.test(i)&&n.push({name:t,idx:Number(i)})}}),n.sort(function(e,t){return e.idx-t.idx}),n.map(function(e){return e.name})},se=function(e,t){void 0===e&&(e={}),void 0===t&&(t=R()?document:null);var r=n({path:"/",sameSite:"Lax",secure:R()&&"https:"===window.location.protocol,maxAge:2592e3},e);return{getItem:function(e){return t?function(e,t){var r=e.get(t);if(void 0!==r)return r;var n=ie(e,t);return 0===n.length?null:n.map(function(t){return e.get(t)}).join("")}(X(t.cookie),e):null},setItem:function(e,n){if(t){var i=X(t.cookie);if(n.length<=re){for(var s=0,o=ie(i,e);s<o.length;s++){var a=o[s];t.cookie=te(a,r)}t.cookie=ee(e,n,r)}else{i.has(e)&&(t.cookie=te(e,r));for(var u=Math.ceil(n.length/re),c=0,l=ie(i,e);c<l.length;c++){var h=l[c];Number(h.slice(e.length+1))>=u&&(t.cookie=te(h,r))}for(var d=0,f=0;d<n.length;d+=re,f++){var v=n.slice(d,d+re);t.cookie=ee(ne(e,f),v,r)}}}},removeItem:function(e){if(t){var n=X(t.cookie);t.cookie=te(e,r);for(var i=0,s=ie(n,e);i<s.length;i++){var o=s[i];t.cookie=te(o,r)}}}}},oe={getItem:function(e){return E()?globalThis.localStorage.getItem(e):null},setItem:function(e,t){E()&&globalThis.localStorage.setItem(e,t)},removeItem:function(e){E()&&globalThis.localStorage.removeItem(e)}};function ae(e){void 0===e&&(e="");var t={},r=new URL(e);if(r.hash&&"#"===r.hash[0])try{new URLSearchParams(r.hash.substring(1)).forEach(function(e,r){t[r]=e})}catch(e){}return r.searchParams.forEach(function(e,r){t[r]=e}),t}var ue=function(e){void 0===e&&(e=[]);var t=new URL(window.location.href);e.forEach(function(e){t.searchParams.delete(e)}),t.hash="",window.history.replaceState(window.history.state,"",t.toString())};globalThis&&E()&&globalThis.localStorage&&globalThis.localStorage.getItem("faable.auth.locks.debug");var ce=function(e){function t(t){var r=e.call(this,t)||this;return r.isAcquireTimeout=!0,r}return r(t,e),t}(Error);function le(e,t,r){return i(this,void 0,void 0,function(){return s(this,function(e){switch(e.label){case 0:return[4,r()];case 1:return[2,e.sent()]}})})}!function(e){function t(){return null!==e&&e.apply(this,arguments)||this}r(t,e)}(ce);var he=function(e){function t(t){var r=e.call(this,{debug:t.debug})||this;return r.lockAcquired=!1,r.pendingInLock=[],r.lock=t.lock||le,r.storageKey=t.storageKey,r}return r(t,e),t.prototype._acquireLock=function(e,t){return i(this,void 0,void 0,function(){var r,n,a=this;return s(this,function(u){switch(u.label){case 0:this._debug("#_acquireLock","begin",e),u.label=1;case 1:return u.trys.push([1,,3,4]),this.lockAcquired?(r=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),n=i(a,void 0,void 0,function(){return s(this,function(e){switch(e.label){case 0:return[4,r];case 1:return e.sent(),[4,t()];case 2:return[2,e.sent()]}})}),this.pendingInLock.push(i(a,void 0,void 0,function(){return s(this,function(e){switch(e.label){case 0:return e.trys.push([0,2,,3]),[4,n];case 1:case 2:return e.sent(),[3,3];case 3:return[2]}})})),[2,n]):[4,this.lock("lock:".concat(this.storageKey),e,function(){return i(a,void 0,void 0,function(){var e,r,n=this;return s(this,function(a){switch(a.label){case 0:this._debug("#_acquireLock","lock acquired for storage key",this.storageKey),a.label=1;case 1:return a.trys.push([1,,7,8]),this.lockAcquired=!0,e=t(),this.pendingInLock.push(i(n,void 0,void 0,function(){return s(this,function(t){switch(t.label){case 0:return t.trys.push([0,2,,3]),[4,e];case 1:case 2:return t.sent(),[3,3];case 3:return[2]}})})),[4,e];case 2:a.sent(),a.label=3;case 3:return this.pendingInLock.length?(r=o([],this.pendingInLock,!0),[4,Promise.all(r)]):[3,5];case 4:return a.sent(),this.pendingInLock.splice(0,r.length),[3,3];case 5:return[4,e];case 6:return[2,a.sent()];case 7:return this._debug("#_acquireLock","lock released for storage key",this.storageKey),this.lockAcquired=!1,[7];case 8:return[2]}})})})];case 2:return[2,u.sent()];case 3:return this._debug("#_acquireLock","end"),[7];case 4:return[2]}})})},t}(c),de=3e4,fe=function(e){function t(t){var r,n,i=this,s=(null==t?void 0:t.debug)||!1;if((i=e.call(this,{debug:s})||this).initializePromise=null,i._lastInitializeResult=null,i.detectSessionInUrl=!0,i.autoRefreshTicker=null,i.visibilityChangedCallback=null,i.refreshingDeferred=null,i._session=null,i.sessionCheckExpiryDays=1,i.redirectUri=(null==t?void 0:t.redirectUri)||"",!(null==t?void 0:t.domain))throw new Error("Missing domain");if(i.domainUrl=function(e){var t=(null!=e?e:"").trim().replace(/\/+$/,""),r=t.match(/^(https?):\/\/(.*)$/i);if(r){var n=r[2].replace(/^(https?:\/\/)+/i,"");return"".concat(r[1].toLowerCase(),"://").concat(n)}var i="undefined"!=typeof location&&(null===location||void 0===location?void 0:location.protocol)?location.protocol.replace(/:$/,""):"https";return"".concat(i,"://").concat(t)}(t.domain),i.tokenIssuer=(n=i.domainUrl,"".concat(n)),!t.clientId)throw new Error("Missing clientId");i.clientId=t.clientId,i.audience=t.audience,i.api=new g(i.domainUrl,{debug:s});var a=(null==t?void 0:t.storageKey)||z;return i.storageKey="".concat(a,"-").concat(i.clientId),i.storage=function(e){var t=e.storage,r=e.cookieOptions;return"cookie"===t||r?se(r):"localStorage"===t||void 0===t?oe:t}(t),i.lock=new he({lock:t.lock,storageKey:i.storageKey,debug:t.debug}),i.broadcastSync=new D(R()?i.storageKey:"",function(e){for(var t=[],r=1;r<arguments.length;r++)t[r-1]=arguments[r];return i._debug.apply(i,o([e],t,!1))}),i.flowType=null!==(r=t.flowType)&&void 0!==r?r:R()?"pkce":"implicit",i.autoRefreshToken=!0,i.initialize(),i}return r(t,e),Object.defineProperty(t.prototype,"session",{get:function(){return this._session},enumerable:!1,configurable:!0}),t.prototype.initialize=function(){return i(this,void 0,void 0,function(){var e,t=this;return s(this,function(r){switch(r.label){case 0:return this.initializePromise?[4,this.initializePromise]:[3,2];case 1:return[2,r.sent()];case 2:return this.initializePromise=i(t,void 0,void 0,function(){var e=this;return s(this,function(t){switch(t.label){case 0:return[4,this.lock._acquireLock(-1,function(){return i(e,void 0,void 0,function(){return s(this,function(e){switch(e.label){case 0:return[4,this._initialize()];case 1:return[2,e.sent()]}})})})];case 1:return[2,t.sent()]}})}),[4,this.initializePromise];case 3:return e=r.sent(),this._lastInitializeResult=e,[2,e]}})})},Object.defineProperty(t.prototype,"lastInitializeResult",{get:function(){return this._lastInitializeResult},enumerable:!1,configurable:!0}),t.prototype.handleRedirectCallback=function(){return i(this,void 0,void 0,function(){return s(this,function(e){switch(e.label){case 0:return[4,this.initialize()];case 1:return[2,e.sent()]}})})},t.prototype._initialize=function(){return i(this,void 0,void 0,function(){var e,t,r,n,o,a,u,c,l,h=this;return s(this,function(d){switch(d.label){case 0:return d.trys.push([0,8,9,11]),[4,this._detectFlowType()];case 1:return e=d.sent(),this._debug("#_initialize()","begin","flow_type",e),e?[4,this._getSessionFromURL(e)]:[3,6];case 2:return t=d.sent(),r=t.data,(n=t.error)?(this._debug("#_initialize()","error detecting session from URL",n),"Identity is already linked"===(null==n?void 0:n.message)||"Identity is already linked to another user"===(null==n?void 0:n.message)?[2,{error:n}]:[4,this._removeSession()]):[3,4];case 3:return d.sent(),[2,{error:n}];case 4:return o=r.session,a=r.redirectType,u=r.returnTo,c=r.is_new_user,this._debug("#_initialize()","detected session in URL",o,"redirect type",a),[4,this._saveSession(o)];case 5:return d.sent(),setTimeout(function(){return i(h,void 0,void 0,function(){return s(this,function(e){switch(e.label){case 0:return"recovery"!==a?[3,2]:[4,this._notifyAllSubscribers("PASSWORD_RECOVERY",o)];case 1:return e.sent(),[3,4];case 2:return[4,this._notifyAllSubscribers("SIGNED_IN",o)];case 3:e.sent(),e.label=4;case 4:return[2]}})})},0),[2,{error:null,redirectType:a,returnTo:u,is_new_user:c}];case 6:return[4,this._recoverAndRefresh()];case 7:return d.sent(),[2,{error:null}];case 8:return K(l=d.sent())?[2,{error:l}]:[2,{error:new W("Unexpected error during initialization",l)}];case 9:return[4,this._handleVisibilityChange()];case 10:return d.sent(),this._debug("#_initialize()","end"),[7];case 11:return[2]}})})},t.prototype._getSessionFromURL=function(e){return i(this,void 0,void 0,function(){var t,r,n,i,o,a,u,c,h,d,f,v,p,b,_,g,y,w,m,k,S;return s(this,function(s){switch(s.label){case 0:if(s.trys.push([0,4,,5]),t=ae(null==l?void 0:l.location.href),r="true"===t.signup,"pkce"!=e)return[3,2];if(!t.code)throw new V("No code detected.");return[4,this._exchangeCodeForSession(t.code)];case 1:if(n=s.sent(),i=n.data,o=n.error)throw o;return ue(["code","signup"]),[2,{data:{session:i.session,redirectType:i.redirectType,returnTo:i.returnTo,is_new_user:r},error:null}];case 2:if(t.error||t.error_description||t.error_code)throw new F(t.error_description||"Error in URL with unspecified error_description",{error:t.error||"unspecified_error",code:t.error_code||"unspecified_code"});if(a=t.provider_token,u=t.provider_refresh_token,c=t.access_token,h=t.refresh_token,d=t.expires_in,f=t.expires_at,v=t.token_type,!c||!h)throw new F("No session defined in URL");return p=void 0,b=void 0,d?(k=function(e){var t=e.expires_in,r=e.expires_at,n=e.refreshTick,i=Math.round(Date.now()/1e3),s=parseInt(t),o=i+s;r&&(o=parseInt(r));var a=o-i;1e3*a<=n&&console.warn("@faable/auth-js: Session as retrieved from URL expires in ".concat(a,"s, should have been closer to ").concat(s,"s"));var u=o-s;return i-u>=120?console.warn("@faable/auth-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",u,o,i):i-u<0&&console.warn("@faable/auth-js: Session as retrieved from URL was issued in the future? Check the device clok for skew",u,o,i),{expiresIn:s,expiresAt:o}}({expires_in:d,expires_at:f,refreshTick:de}),p=k.expiresAt,b=k.expiresIn):(S=function(e,t,r){var n;void 0===r&&(r=Date.now()/1e3);var i=H(e),s=null!=t&&""!==t?Number(t):null!==(n=i.exp)&&void 0!==n?n:r;return{expiresAt:s,expiresIn:s-r}}(c,f),p=S.expiresAt,b=S.expiresIn),[4,this._getUser(c)];case 3:if(_=s.sent(),g=_.data,(y=_.error)||!g)throw y;return w={provider_token:a,provider_refresh_token:u,access_token:c,expires_in:b,expires_at:p,refresh_token:h,token_type:v||"bearer",user:g},ue(["access_token","expires_in","refresh_token","token_type","scope","signup"]),this._debug("#_getSessionFromURL()","clearing window.location.hash"),[2,{data:{session:w,redirectType:t.type,returnTo:null,is_new_user:r},error:null}];case 4:if(m=s.sent(),this._debug(m),K(m))return[2,{data:{session:null,redirectType:null,returnTo:null,is_new_user:!1},error:m}];throw m;case 5:return[2]}})})},t.prototype._exchangeCodeForSession=function(e){return i(this,void 0,void 0,function(){var t,r,i,o,a,u,c,l,h,d,f,v,p,_;return s(this,function(s){switch(s.label){case 0:return[4,S(this.storage,"".concat(this.storageKey,"-code-verifier"))];case 1:return(t=s.sent())?(r=t.verifier,i=t.redirectType,o=void 0===i?null:i,a=t.returnTo,u=void 0===a?null:a,[4,b("".concat(this.domainUrl,"/oauth/token"),n({client_id:this.clientId,grant_type:"authorization_code",code:e,code_verifier:r},this.audience?{audience:this.audience}:{}))]):[2,{data:{user:null,session:null,redirectType:null,returnTo:null},error:new V("No active PKCE code verifier — the authorization flow has expired or was not started")}];case 2:if(c=s.sent(),l=U(c),h=l.data,d=l.error,!h)throw new Error("Missing data");return[4,this.storage.removeItem("".concat(this.storageKey,"-code-verifier"))];case 3:return s.sent(),d?[2,{data:{user:null,session:null,redirectType:null,returnTo:null},error:d}]:h&&h.session&&h.user?(f=h.session)?[4,this._getUser(f.access_token)]:[3,7]:[2,{data:{user:null,session:null,redirectType:null,returnTo:null},error:new G}];case 4:if(v=s.sent(),p=v.data,(_=v.error)||!p)throw _;return f=n(n({},f),{user:p}),h.session=f,[4,this._saveSession(f)];case 5:return s.sent(),[4,this._notifyAllSubscribers("SIGNED_IN",f)];case 6:s.sent(),s.label=7;case 7:return[2,{data:n(n({},h),{redirectType:null!=o?o:null,returnTo:null!=u?u:null}),error:d}]}})})},t.prototype._handleVisibilityChange=function(){return i(this,void 0,void 0,function(){var e,t=this;return s(this,function(r){switch(r.label){case 0:if(this._debug("#_handleVisibilityChange()"),!R()||!(null==l?void 0:l.addEventListener))return this.autoRefreshToken&&this.startAutoRefresh(),[2,!1];r.label=1;case 1:return r.trys.push([1,3,,4]),this.visibilityChangedCallback=function(){return i(t,void 0,void 0,function(){return s(this,function(e){switch(e.label){case 0:return[4,this._onVisibilityChanged(!1)];case 1:return[2,e.sent()]}})})},null==l||l.addEventListener("visibilitychange",this.visibilityChangedCallback),[4,this._onVisibilityChanged(!0)];case 2:return r.sent(),[3,4];case 3:return e=r.sent(),console.error("_handleVisibilityChange",e),[3,4];case 4:return[2]}})})},t.prototype._onVisibilityChanged=function(e){return i(this,void 0,void 0,function(){var t,r=this;return s(this,function(n){switch(n.label){case 0:return t="#_onVisibilityChanged(".concat(e,")"),this._debug(t,"visibilityState",d.visibilityState),"visible"!==d.visibilityState?[3,4]:(this.autoRefreshToken&&this._startAutoRefresh(),e?[3,3]:[4,this.initializePromise]);case 1:return n.sent(),[4,this.lock._acquireLock(-1,function(){return i(r,void 0,void 0,function(){return s(this,function(e){switch(e.label){case 0:return"visible"!==d.visibilityState?(this._debug(t,"acquired the lock to recover the session, but the browser visibilityState is no longer visible, aborting"),[2]):[4,this._recoverAndRefresh()];case 1:return e.sent(),[2]}})})})];case 2:n.sent(),n.label=3;case 3:return[3,5];case 4:"hidden"===d.visibilityState&&this.autoRefreshToken&&this._stopAutoRefresh(),n.label=5;case 5:return[2]}})})},t.prototype._recoverAndRefresh=function(){return i(this,void 0,void 0,function(){var e,t,r,n,i,o,a;return s(this,function(s){switch(s.label){case 0:e="#_recoverAndRefresh()",this._debug(e,"begin"),s.label=1;case 1:return s.trys.push([1,12,13,14]),[4,m(this.storage,this.storageKey)];case 2:return t=s.sent(),this._debug(e,"session from storage",t),Q(t)?[3,5]:(this._debug(e,"session is not valid"),null===t?[3,4]:[4,this._removeSession()]);case 3:s.sent(),s.label=4;case 4:return[2];case 5:return r=Math.round(Date.now()/1e3),n=(null!==(a=t.expires_at)&&void 0!==a?a:1/0)<r+10,this._debug(e,"session has".concat(n?"":" not"," expired with margin of ").concat(10,"s")),n?this.autoRefreshToken&&t.refresh_token?[4,this._callRefreshToken(t.refresh_token)]:[3,8]:[3,9];case 6:return(i=s.sent().error)?(console.error(i),J(i)?[3,8]:(this._debug(e,"refresh failed with a non-retryable error, removing the session",i),[4,this._removeSession()])):[3,8];case 7:s.sent(),s.label=8;case 8:return[3,11];case 9:return this._session=t,[4,this._notifyAllSubscribers("SIGNED_IN",t)];case 10:s.sent(),s.label=11;case 11:return[3,14];case 12:return o=s.sent(),this._debug(e,"error",o),console.error(o),[2];case 13:return this._debug(e,"end"),[7];case 14:return[2]}})})},t.prototype._removeVisibilityChangedCallback=function(){this._debug("#_removeVisibilityChangedCallback()");var e=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{e&&R()&&(null==l?void 0:l.removeEventListener)&&l.removeEventListener("visibilitychange",e)}catch(e){console.error("removing visibilitychange callback failed",e)}},t.prototype.startAutoRefresh=function(){return i(this,void 0,void 0,function(){return s(this,function(e){switch(e.label){case 0:return this._removeVisibilityChangedCallback(),[4,this._startAutoRefresh()];case 1:return e.sent(),[2]}})})},t.prototype._startAutoRefresh=function(){return i(this,void 0,void 0,function(){var e,t=this;return s(this,function(r){switch(r.label){case 0:return[4,this._stopAutoRefresh()];case 1:return r.sent(),this._debug("#_startAutoRefresh()"),e=setInterval(function(){return t._autoRefreshTokenTick()},de),this.autoRefreshTicker=e,e&&"object"==typeof e&&"function"==typeof e.unref?e.unref():void 0!==globalThis.Deno&&"function"==typeof globalThis.Deno.unrefTimer&&globalThis.Deno.unrefTimer(e),setTimeout(function(){return i(t,void 0,void 0,function(){return s(this,function(e){switch(e.label){case 0:return[4,this.initializePromise];case 1:return e.sent(),[4,this._autoRefreshTokenTick()];case 2:return e.sent(),[2]}})})},0),[2]}})})},t.prototype._stopAutoRefresh=function(){return i(this,void 0,void 0,function(){var e;return s(this,function(t){return this._debug("#_stopAutoRefresh()"),e=this.autoRefreshTicker,this.autoRefreshTicker=null,e&&clearInterval(e),[2]})})},t.prototype._autoRefreshTokenTick=function(){return i(this,void 0,void 0,function(){var e,t=this;return s(this,function(r){switch(r.label){case 0:this._debug("#_autoRefreshTokenTick()","begin"),r.label=1;case 1:return r.trys.push([1,3,,4]),[4,this.lock._acquireLock(0,function(){return i(t,void 0,void 0,function(){var e,t,r=this;return s(this,function(n){switch(n.label){case 0:n.trys.push([0,,5,6]),e=Date.now(),n.label=1;case 1:return n.trys.push([1,3,,4]),[4,this._useSession(function(t){return i(r,void 0,void 0,function(){var r,n;return s(this,function(i){switch(i.label){case 0:return(r=t.data.session)&&r.refresh_token&&r.expires_at?(n=Math.floor((1e3*r.expires_at-e)/de),this._debug("#_autoRefreshTokenTick()","access token expires in ".concat(n," ticks, a tick lasts ").concat(de,"ms, refresh threshold is ").concat(3," ticks")),n<=3?[4,this._callRefreshToken(r.refresh_token)]:[3,2]):(this._debug("#_autoRefreshTokenTick()","no session"),[2]);case 1:i.sent(),i.label=2;case 2:return[2]}})})})];case 2:return[2,n.sent()];case 3:return t=n.sent(),console.error("Auto refresh tick failed with error. This is likely a transient error.",t),[3,4];case 4:return[3,6];case 5:return this._debug("#_autoRefreshTokenTick()","end"),[7];case 6:return[2]}})})})];case 2:return r.sent(),[3,4];case 3:if(!((e=r.sent()).isAcquireTimeout||e instanceof ce))throw e;return this._debug("auto refresh token tick lock not available"),[3,4];case 4:return[2]}})})},t.prototype._detectFlowType=function(){return i(this,void 0,void 0,function(){var e,t;return s(this,function(r){return e=ae(null==l?void 0:l.location.href),(t=R())&&e.code?[2,"pkce"]:t&&(e.access_token||e.error_description)?[2,"implicit"]:[2,null]})})},t.prototype._scope=function(){return this.scope||"openid profile email"},t.prototype._getUrlForConnection=function(e,t){return i(this,void 0,void 0,function(){var r,i,o,a,u,c,h;return s(this,function(s){switch(s.label){case 0:return r=t.queryParams||{},i={client_id:this.clientId,response_type:t.response_type,redirect_uri:t.redirectTo||this.redirectUri||(null==l?void 0:l.location.origin),scope:t.scopes||this._scope()},"pkce"!==this.flowType?[3,2]:[4,A(this.storage,this.storageKey,!1,t.returnTo)];case 1:o=s.sent(),a=o[0],u=o[1],r=n(n({},r),{code_challenge:a,code_challenge_method:u}),s.label=2;case 2:return t.connection_id?i.connection_id=t.connection_id:t.connection&&(i.connection=t.connection),(c=null!==(h=t.audience)&&void 0!==h?h:this.audience)&&(i.audience=c),[2,"".concat(e,"?").concat(new URLSearchParams(n(n({},r),i)))]}})})},t.prototype.signInWithOauthConnection=function(e){return i(this,void 0,void 0,function(){return s(this,function(t){switch(t.label){case 0:return[4,this._handleConnectionSignIn({connection:e.connection,connection_id:e.connection_id,redirectTo:null==e?void 0:e.redirectTo,returnTo:null==e?void 0:e.returnTo,scopes:null==e?void 0:e.scopes,queryParams:e.queryParams,skipBrowserRedirect:e.skipBrowserRedirect,audience:e.audience})];case 1:return[2,t.sent()]}})})},t.prototype.signInWithUsernamePassword=function(e){return i(this,void 0,void 0,function(){var t,r,i;return s(this,function(s){switch(s.label){case 0:return t=null!==(i=e.audience)&&void 0!==i?i:this.audience,[4,b("".concat(this.domainUrl,"/usernamepassword/login"),n({username:e.username,password:e.password,redirect_uri:e.redirectTo||this.redirectUri||(null==l?void 0:l.location.origin),client_id:this.clientId,state:e.state},t?{audience:t}:{}),{raw:!0})];case 1:return!(r=s.sent()).data||r.error?[2,{data:null,error:new W(r.error||"Error in username password login",r.error)}]:(function(e,t){var r=t.createElement("div");r.innerHTML=e;var n=t.body.appendChild(r).children[0];if(!n)throw new Error("Auth response did not contain a submittable form");n.submit()}(r.data,d),[2,{data:null,error:null}])}})})},t.prototype.signUp=function(e){return i(this,void 0,void 0,function(){var t,r,i,o,a;return s(this,function(s){switch(s.label){case 0:return(null==e?void 0:e.email)&&(null==e?void 0:e.password)?[4,b("".concat(this.domainUrl,"/dbconnections/signup"),n(n(n(n(n({client_id:this.clientId,email:e.email,password:e.password},e.name?{name:e.name}:{}),e.given_name?{given_name:e.given_name}:{}),e.family_name?{family_name:e.family_name}:{}),e.user_metadata?{user_metadata:e.user_metadata}:{}),e.connection?{connection:e.connection}:{}))]:[2,{data:null,error:new W("email and password are required",null)}];case 1:return t=s.sent(),r=t.data,(i=t.error)?(o=null==r?void 0:r.status,a=403===o?"signup_disabled":409===o?"email_exists":void 0,[2,{data:null,error:new M(String(i),null!=o?o:500,a)}]):[2,this.signInWithUsernamePassword({username:e.email,password:e.password,redirectTo:e.redirectTo,state:e.state,audience:e.audience})]}})})},t.prototype.signInWithOtp=function(e){return i(this,void 0,void 0,function(){var t,r,i,o,a,u,c,l,h,d;return s(this,function(s){switch(s.label){case 0:return t=null!==(d=e.audience)&&void 0!==d?d:this.audience,[4,b("".concat(this.domainUrl,"/oauth/token"),n({client_id:this.clientId,grant_type:"http://auth0.com/oauth/grant-type/passwordless/otp",username:e.username,otp:e.otp},t?{audience:t}:{}))];case 1:return r=s.sent(),i=U(r),o=i.data,(a=i.error)?[2,{data:{user:null,session:null},error:a}]:o&&o.session?(u=o.session,[4,this._getUser(u.access_token)]):[2,{data:{user:null,session:null},error:new G}];case 2:return c=s.sent(),l=c.data,(h=c.error)||!l?[2,{data:{user:null,session:null},error:h||new W("Could not fetch user info",null)}]:(u.user=l,[4,this._saveSession(u)]);case 3:return s.sent(),[4,this._notifyAllSubscribers("SIGNED_IN",u)];case 4:return s.sent(),[2,{data:{user:u.user,session:u},error:null}]}})})},t.prototype.signInWithPasswordless=function(e){return i(this,void 0,void 0,function(){var t,r,i;return s(this,function(s){switch(s.label){case 0:return t=null!==(i=e.audience)&&void 0!==i?i:this.audience,[4,b("".concat(this.domainUrl,"/passwordless/start"),n({client_id:this.clientId,email:e.email,send:e.type},t?{audience:t}:{}))];case 1:return[2,{data:(r=s.sent()).data,error:r.error}]}})})},t.prototype.changePassword=function(e){return i(this,void 0,void 0,function(){var t,r,n;return s(this,function(i){switch(i.label){case 0:return(null==e?void 0:e.email)?[4,b("".concat(this.domainUrl,"/dbconnections/change_password"),{email:e.email})]:[2,{data:null,error:new W("email is required",null)}];case 1:return t=i.sent(),r=t.data,n=t.error,[2,{data:null!=r?r:null,error:n?new W(String(n),n):null}]}})})},t.prototype._resolveUserId=function(e){var t,r,n,i=null!==(r=null===(t=e.user)||void 0===t?void 0:t.id)&&void 0!==r?r:null===(n=e.user)||void 0===n?void 0:n.sub;if(i)return i;try{var s=H(e.access_token);return null==s?void 0:s.sub}catch(e){return}},t.prototype.changeEmail=function(e){return i(this,void 0,void 0,function(){var t,r,i,o,a,u,c,l;return s(this,function(s){switch(s.label){case 0:return(null==e?void 0:e.new_email)?[4,this.getSession()]:[2,{data:null,error:new W("new_email is required",null)}];case 1:return t=s.sent(),r=t.data,i=t.error,o=null==r?void 0:r.session,i||!o?[2,{data:null,error:i||new j}]:(a=this._resolveUserId(o))?[4,b("".concat(this.domainUrl,"/user/").concat(a,"/change-email"),n(n({new_email:e.new_email},e.verification_mode?{verification_mode:e.verification_mode}:{}),e.redirect_uri?{redirect_uri:e.redirect_uri}:{}),{token:o.access_token})]:[2,{data:null,error:new j}];case 2:return u=s.sent(),c=u.data,l=u.error,[2,{data:null!=c?c:null,error:l?new W(String(l),l):null}]}})})},t.prototype.buildAuthorizeUrl=function(e){var t;void 0===e&&(e={});var r={client_id:this.clientId,redirect_uri:e.redirectTo||this.redirectUri||(null==l?void 0:l.location.origin),response_type:y(e,R()),audience:null!==(t=e.audience)&&void 0!==t?t:this.audience,scope:e.scope,connection:e.connection},n=Object.fromEntries(Object.entries(r).filter(function(e){return!!e[1]}));return"".concat(this.domainUrl,"/authorize?").concat(new URLSearchParams(n).toString())},t.prototype.authorize=function(e){var t=this.buildAuthorizeUrl(e);$.redirect(t)},t.prototype._handleConnectionSignIn=function(e){return i(this,void 0,void 0,function(){var t;return s(this,function(r){switch(r.label){case 0:return[4,this._getUrlForConnection("".concat(this.domainUrl,"/authorize"),{response_type:R()?"code":"token",connection:e.connection,connection_id:e.connection_id,redirectTo:e.redirectTo,returnTo:e.returnTo,scopes:e.scopes,queryParams:e.queryParams,audience:e.audience})];case 1:return t=r.sent(),this._debug("#_handleConnectionSignIn()","options",e,"url",t),!R()||e.skipBrowserRedirect?[3,3]:(null==l||l.location.assign(t),[4,new Promise(function(){})]);case 2:r.sent(),r.label=3;case 3:return[2,{data:{url:t},error:null}]}})})},t.prototype.setSession=function(e){return i(this,void 0,void 0,function(){var t=this;return s(this,function(r){switch(r.label){case 0:return[4,this.initializePromise];case 1:return r.sent(),[4,this.lock._acquireLock(-1,function(){return i(t,void 0,void 0,function(){return s(this,function(t){switch(t.label){case 0:return[4,this._setSession(e)];case 1:return[2,t.sent()]}})})})];case 2:return[2,r.sent()]}})})},t.prototype.getSession=function(){return i(this,void 0,void 0,function(){var e=this;return s(this,function(t){switch(t.label){case 0:return[4,this.initializePromise];case 1:return t.sent(),[4,this.lock._acquireLock(-1,function(){return i(e,void 0,void 0,function(){var e=this;return s(this,function(t){return[2,this._useSession(function(t){return i(e,void 0,void 0,function(){return s(this,function(e){return[2,t]})})})]})})})];case 2:return[2,t.sent()]}})})},t.prototype._useSession=function(e){return i(this,void 0,void 0,function(){var t;return s(this,function(r){switch(r.label){case 0:this._debug("#_useSession","begin"),r.label=1;case 1:return r.trys.push([1,,4,5]),[4,this.__loadSession()];case 2:return t=r.sent(),[4,e(t)];case 3:return[2,r.sent()];case 4:return this._debug("#_useSession","end"),[7];case 5:return[2]}})})},t.prototype.__loadSession=function(){return i(this,void 0,void 0,function(){var e,t,r,n,i,o,a;return s(this,function(s){switch(s.label){case 0:this._debug("#__loadSession()","begin"),this.lock.lockAcquired||this._debug("#__loadSession()","used outside of an acquired lock!",(new Error).stack),s.label=1;case 1:return s.trys.push([1,,7,8]),e=null,[4,m(this.storage,this.storageKey)];case 2:return t=s.sent(),this._debug("#getSession()","session from storage",t),null===t?[3,5]:Q(t)?(e=t,[3,5]):[3,3];case 3:return this._debug("#getSession()","session from storage is not valid"),[4,this._removeSession()];case 4:s.sent(),s.label=5;case 5:return e?(r=!!e.expires_at&&e.expires_at<=Date.now()/1e3,this._debug("#__loadSession()","session has".concat(r?"":" not"," expired"),"expires_at",e.expires_at),r?[4,this._callRefreshToken(e.refresh_token)]:(this.storage.isServer&&(n=new Proxy(e,{get:function(e,t,r){return"user"===t&&console.warn("Reading `session.user` from a server-side cookie store can be insecure: the value is whatever the cookie contains and has not been verified against Faable Auth. Re-fetch the user with `auth.getUser()` (or verify the access token yourself) before trusting it on the server."),Reflect.get(e,t,r)}}),e=n),[2,{data:{session:e},error:null}])):[2,{data:{session:null},error:null}];case 6:return i=s.sent(),o=i.session,(a=i.error)?[2,{data:{session:null},error:a}]:[2,{data:{session:o},error:null}];case 7:return this._debug("#__loadSession()","end"),[7];case 8:return[2]}})})},t.prototype._removeSession=function(){return i(this,void 0,void 0,function(){return s(this,function(e){switch(e.label){case 0:return this._debug("#_removeSession()"),this._session=null,[4,this.storage.removeItem(this.storageKey)];case 1:return e.sent(),[2]}})})},t.prototype._setSession=function(e){return i(this,void 0,void 0,function(){var t,r,n,i,o,a,u,c,l,h,d;return s(this,function(s){switch(s.label){case 0:if(s.trys.push([0,7,,8]),!e.access_token||!e.refresh_token)throw new j;return t=Date.now()/1e3,r=t,n=!0,i=null,(o=H(e.access_token)).exp&&(r=o.exp,n=r<=t),n?[4,this._callRefreshToken(e.refresh_token)]:[3,2];case 1:return a=s.sent(),u=a.session,(h=a.error)?[2,{data:{user:null,session:null},error:h}]:u?(i=u,[3,6]):[2,{data:{user:null,session:null},error:null}];case 2:return[4,this._getUser(e.access_token)];case 3:if(c=s.sent(),l=c.data,(h=c.error)||!l)throw h;return i={access_token:e.access_token,refresh_token:e.refresh_token,user:l,token_type:"bearer",expires_in:r-t,expires_at:r},[4,this._saveSession(i)];case 4:return s.sent(),[4,this._notifyAllSubscribers("SIGNED_IN",i)];case 5:s.sent(),s.label=6;case 6:return[2,{data:{user:i.user,session:i},error:null}];case 7:if(K(d=s.sent()))return[2,{data:{session:null,user:null},error:d}];throw d;case 8:return[2]}})})},t.prototype._saveSession=function(e){return i(this,void 0,void 0,function(){return s(this,function(t){switch(t.label){case 0:return this._debug("#_saveSession()",e),this._session=e,[4,w(this.storage,this.storageKey,e)];case 1:return t.sent(),[2]}})})},t.prototype._getUser=function(e){return i(this,void 0,void 0,function(){var t;return s(this,function(r){switch(r.label){case 0:if(!e)throw new Error("Cannot fetch user without token");return this._debug("#_getUser() begin"),[4,_("".concat(this.domainUrl,"/me"),{token:e})];case 1:return t=r.sent(),this._debug("#_getUser() end"),[2,{data:t.data,error:t.error}]}})})},t.prototype._callRefreshToken=function(e){return i(this,void 0,void 0,function(){var t,r,n,i,o,a,u,c;return s(this,function(s){switch(s.label){case 0:if(!e)throw new j;if(this.refreshingDeferred)return[2,this.refreshingDeferred.promise];t="#_callRefreshToken(".concat(e.substring(0,5),"...)"),this._debug(t,"begin"),s.label=1;case 1:return s.trys.push([1,5,10,11]),this.refreshingDeferred=new P,[4,(l=this._refreshAccessToken(e),h=3e4,d="Token refresh timed out",v=new Promise(function(e,t){f=setTimeout(function(){return t(new Error(d))},h)}),Promise.race([l.finally(function(){void 0!==f&&clearTimeout(f)}),v]))];case 2:if(r=s.sent(),n=r.data,i=r.error)throw i;if(!n.session)throw new j;return[4,this._saveSession(n.session)];case 3:return s.sent(),[4,this._notifyAllSubscribers("TOKEN_REFRESHED",n.session)];case 4:return s.sent(),a={session:n.session,error:null},this.refreshingDeferred.resolve(a),[2,a];case 5:return o=s.sent(),this._debug(t,"error",o),K(o)?(a={session:null,error:o},J(o)?[3,8]:[4,this._removeSession()]):[3,9];case 6:return s.sent(),[4,this._notifyAllSubscribers("SIGNED_OUT",null)];case 7:s.sent(),s.label=8;case 8:return null===(u=this.refreshingDeferred)||void 0===u||u.resolve(a),[2,a];case 9:throw null===(c=this.refreshingDeferred)||void 0===c||c.reject(o),o;case 10:return this.refreshingDeferred=null,this._debug(t,"end"),[7];case 11:return[2]}var l,h,d,f,v})})},t.prototype._refreshAccessToken=function(e){return i(this,void 0,void 0,function(){var t,r,o,a=this;return s(this,function(u){switch(u.label){case 0:t="#_refreshAccessToken(".concat(e.substring(0,5),"...)"),this._debug(t,"begin"),u.label=1;case 1:return u.trys.push([1,3,4,5]),r=Date.now(),[4,L(function(r){return i(a,void 0,void 0,function(){var i,o,a,u,c,l,h;return s(this,function(s){switch(s.label){case 0:return r>0?[4,O(200*Math.pow(2,r-1))]:[3,2];case 1:s.sent(),s.label=2;case 2:return this._debug(t,"refreshing attempt",r),[4,b("".concat(this.domainUrl,"/oauth/token"),n({client_id:this.clientId,grant_type:"refresh_token",refresh_token:e},this.audience?{audience:this.audience}:{}))];case 3:if((i=s.sent()).error)throw new W("Refresh token request failed: ".concat(i.error),i.error);if(o=U(i),!(null===(l=o.data.session)||void 0===l?void 0:l.access_token))throw new G;return[4,this._getUser(null===(h=o.data.session)||void 0===h?void 0:h.access_token)];case 4:if(a=s.sent(),u=a.data,c=a.error)throw new W("Could not fetch user info",c);if(!u)throw new W("Refresh response missing user",null);return[2,{data:{session:n(n({},o.data.session),{user:u}),user:u},error:null}]}})})},function(e,t){var n=200*Math.pow(2,e);return t&&J(t)&&Date.now()+n-r<de})];case 2:return[2,u.sent()];case 3:if(o=u.sent(),this._debug(t,"error",o),K(o))return[2,{data:{session:null,user:null},error:o}];throw o;case 4:return this._debug(t,"end"),[7];case 5:return[2]}})})},t.prototype._notifyAllSubscribers=function(e,t){return i(this,arguments,void 0,function(e,t,r){var n;return void 0===r&&(r=!0),s(this,function(i){switch(i.label){case 0:n="#_notifyAllSubscribers(".concat(e,")"),this._debug(n,"begin",t,"broadcast = ".concat(r)),i.label=1;case 1:return i.trys.push([1,,3,4]),[4,this.broadcastSync.notify(e,t,r)];case 2:return i.sent(),[3,4];case 3:return this._debug(n,"end"),[7];case 4:return[2]}})})},t.prototype.signOut=function(){return i(this,arguments,void 0,function(e){var t=this;return void 0===e&&(e={scope:"global"}),s(this,function(r){switch(r.label){case 0:return[4,this.initializePromise];case 1:return r.sent(),[4,this.lock._acquireLock(-1,function(){return i(t,void 0,void 0,function(){return s(this,function(t){switch(t.label){case 0:return[4,this._signOut(e)];case 1:return[2,t.sent()]}})})})];case 2:return[2,r.sent()]}})})},t.prototype._signOut=function(){return i(this,arguments,void 0,function(e){var t=this,r=(void 0===e?{scope:"global"}:e).scope;return s(this,function(e){switch(e.label){case 0:return[4,this._useSession(function(e){return i(t,void 0,void 0,function(){var t,n,i,o;return s(this,function(s){switch(s.label){case 0:return t=e.data,(n=e.error)?[2,{error:n}]:(null===(o=t.session)||void 0===o?void 0:o.access_token)?[4,this.api.signOut({client_id:this.clientId})]:[3,2];case 1:if((i=s.sent().error)&&(!function(e){return K(e)&&"AuthApiError"===e.name}(i)||404!==i.status&&401!==i.status))return[2,{error:i}];s.label=2;case 2:return"others"===r?[3,6]:[4,this._removeSession()];case 3:return s.sent(),[4,this.storage.removeItem("".concat(this.storageKey,"-code-verifier"))];case 4:return s.sent(),[4,this._notifyAllSubscribers("SIGNED_OUT",null)];case 5:s.sent(),s.label=6;case 6:return[2,{error:null}]}})})})];case 1:return[2,e.sent()]}})})},t.prototype.onAuthStateChange=function(e){var t=this,r=this.broadcastSync.subscribe(e).subscription;return this._debug("#onAuthStateChange()","registered callback with id",r.id),i(t,void 0,void 0,function(){var e=this;return s(this,function(t){switch(t.label){case 0:return[4,this.initializePromise];case 1:return t.sent(),[4,this.lock._acquireLock(-1,function(){return i(e,void 0,void 0,function(){return s(this,function(e){return this._emitInitialSession(r),[2]})})})];case 2:return t.sent(),[2]}})}),{data:{subscription:r}}},t.prototype._emitInitialSession=function(e){return i(this,void 0,void 0,function(){var t=this;return s(this,function(r){switch(r.label){case 0:return[4,this._useSession(function(r){return i(t,void 0,void 0,function(){var t,n,i;return s(this,function(s){switch(s.label){case 0:if(s.trys.push([0,2,,4]),t=r.data.session,n=r.error)throw n;return[4,e.callback("INITIAL_SESSION",t)];case 1:return s.sent(),this._debug("INITIAL_SESSION","callback id",e.id,"session",t),[3,4];case 2:return i=s.sent(),[4,e.callback("INITIAL_SESSION",null)];case 3:return s.sent(),this._debug("INITIAL_SESSION","callback id",e.id,"error",i),console.error(i),[3,4];case 4:return[2]}})})})];case 1:return[2,r.sent()]}})})},t.prototype.refreshSession=function(e){return i(this,void 0,void 0,function(){var t=this;return s(this,function(r){switch(r.label){case 0:return[4,this.initializePromise];case 1:return r.sent(),[4,this.lock._acquireLock(-1,function(){return i(t,void 0,void 0,function(){return s(this,function(t){switch(t.label){case 0:return[4,this._refreshSession(e)];case 1:return[2,t.sent()]}})})})];case 2:return[2,r.sent()]}})})},t.prototype._refreshSession=function(e){return i(this,void 0,void 0,function(){var t,r=this;return s(this,function(n){switch(n.label){case 0:return n.trys.push([0,2,,3]),[4,this._useSession(function(t){return i(r,void 0,void 0,function(){var r,n,i,o,a,u;return s(this,function(s){switch(s.label){case 0:if(!e){if(r=t.data,n=t.error)throw n;e=null!==(u=r.session)&&void 0!==u?u:void 0}if(!(null==e?void 0:e.refresh_token))throw new j;return[4,this._callRefreshToken(e.refresh_token)];case 1:return i=s.sent(),o=i.session,(a=i.error)?[2,{data:{user:null,session:null},error:a}]:o?[2,{data:{user:o.user,session:o},error:null}]:[2,{data:{user:null,session:null},error:null}]}})})})];case 1:return[2,n.sent()];case 2:if(K(t=n.sent()))return[2,{data:{user:null,session:null},error:t}];throw t;case 3:return[2]}})})},t}(c),ve=function(){};e.AuthError=N,e.FaableAuthClient=fe,e.User=ve,e.cookieStorageAdapter=se,e.createClient=function(e){return new fe(e)},e.getSessionFromCookies=function(e,t){var r,n="".concat(null!==(r=t.storageKey)&&void 0!==r?r:z,"-").concat(t.clientId),i=Y(e,n);if(!i)return null;try{return JSON.parse(decodeURIComponent(i))}catch(e){return console.error("Failed to parse session from cookie",e),null}}}({});
6
+ !function(e){"use strict";var t=function(e,r){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r])},t(e,r)};function r(e,r){if("function"!=typeof r&&null!==r)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");function n(){this.constructor=e}t(e,r),e.prototype=null===r?Object.create(r):(n.prototype=r.prototype,new n)}var n=function(){return n=Object.assign||function(e){for(var t,r=1,n=arguments.length;r<n;r++)for(var i in t=arguments[r])Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i]);return e},n.apply(this,arguments)};function i(e,t,r,n){return new(r||(r=Promise))(function(i,s){function o(e){try{u(n.next(e))}catch(e){s(e)}}function a(e){try{u(n.throw(e))}catch(e){s(e)}}function u(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(o,a)}u((n=n.apply(e,t||[])).next())})}function s(e,t){var r,n,i,s={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]},o=Object.create(("function"==typeof Iterator?Iterator:Object).prototype);return o.next=a(0),o.throw=a(1),o.return=a(2),"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function a(a){return function(u){return function(a){if(r)throw new TypeError("Generator is already executing.");for(;o&&(o=0,a[0]&&(s=0)),s;)try{if(r=1,n&&(i=2&a[0]?n.return:a[0]?n.throw||((i=n.return)&&i.call(n),0):n.next)&&!(i=i.call(n,a[1])).done)return i;switch(n=0,i&&(a=[2&a[0],i.value]),a[0]){case 0:case 1:i=a;break;case 4:return s.label++,{value:a[1],done:!1};case 5:s.label++,n=a[1],a=[0];continue;case 7:a=s.ops.pop(),s.trys.pop();continue;default:if(!(i=s.trys,(i=i.length>0&&i[i.length-1])||6!==a[0]&&2!==a[0])){s=0;continue}if(3===a[0]&&(!i||a[1]>i[0]&&a[1]<i[3])){s.label=a[1];break}if(6===a[0]&&s.label<i[1]){s.label=i[1],i=a;break}if(i&&s.label<i[2]){s.label=i[2],s.ops.push(a);break}i[2]&&s.ops.pop(),s.trys.pop();continue}a=t.call(e,s)}catch(e){a=[6,e],n=0}finally{r=i=0}if(5&a[0])throw a[1];return{value:a[0]?a[1]:void 0,done:!0}}([a,u])}}}function o(e,t,r){if(r||2===arguments.length)for(var n,i=0,s=t.length;i<s;i++)!n&&i in t||(n||(n=Array.prototype.slice.call(t,0,i)),n[i]=t[i]);return e.concat(n||Array.prototype.slice.call(t))}"function"==typeof SuppressedError&&SuppressedError;var a="0.0.0",u=function(){function e(e){void 0===e&&(e={}),this.logger=console.log,this.logDebugMessages=!!e.debug,"function"==typeof e.debug&&(this.logger=e.debug)}return e.prototype._debug=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];if(this.logDebugMessages){var r=this.extraPrint?this.extraPrint():"";this.logger.apply(this,o(["FaableAuth@".concat(r," (").concat(a,") ").concat((new Date).toISOString())],e,!1))}return this},e}(),c=function(e){function t(r){void 0===r&&(r={});var n=e.call(this,r)||this;return n.instanceID=t.nextInstanceID,t.nextInstanceID+=1,n}return r(t,e),t.prototype.extraPrint=function(){return this.instanceID.toString()},t.nextInstanceID=0,t}(u),l="undefined"!=typeof window?window:void 0,h="undefined"!=typeof globalThis?globalThis:l,d=null==h?void 0:h.document,f=h.fetch,v=function(e){void 0===e&&(e={});var t={"x-faable-client":"auth-js/".concat(a)};return(null==e?void 0:e.token)&&(t=n(n({},t),{Authorization:"Bearer ".concat(null==e?void 0:e.token)})),n(n({},null==e?void 0:e.headers),t)},p=function(e){for(var t=[],r=1;r<arguments.length;r++)t[r-1]=arguments[r];return i(void 0,o([e],t,!0),void 0,function(e,t){var r,n,i;return void 0===t&&(t={}),s(this,function(s){switch(s.label){case 0:return t.raw?[4,e.text()]:[3,2];case 1:return n=s.sent(),[3,4];case 2:return[4,e.json()];case 3:n=s.sent(),s.label=4;case 4:return r=n,e.status>=300?[2,{data:r,error:t.raw?null===(i=JSON.parse(r))||void 0===i?void 0:i.message:null==r?void 0:r.message}]:[2,{data:r,error:null}]}})})},b=function(e,t){for(var r=[],a=2;a<arguments.length;a++)r[a-2]=arguments[a];return i(void 0,o([e,t],r,!0),void 0,function(e,t,r){var i;return void 0===r&&(r={}),s(this,function(s){switch(s.label){case 0:return s.trys.push([0,3,,4]),[4,f(e,{method:"POST",body:JSON.stringify(t),headers:n(n({},v(r)),{"Content-Type":"application/json"})})];case 1:return i=s.sent(),[4,p(i,r)];case 2:return[2,s.sent()];case 3:return[2,{data:null,error:s.sent()}];case 4:return[2]}})})},g=function(e){for(var t=[],r=1;r<arguments.length;r++)t[r-1]=arguments[r];return i(void 0,o([e],t,!0),void 0,function(e,t){var r;return void 0===t&&(t={}),s(this,function(i){switch(i.label){case 0:return i.trys.push([0,3,,4]),[4,f(e,n(n({},t),{method:"GET",headers:v(t)}))];case 1:return r=i.sent(),[4,p(r,t)];case 2:return[2,i.sent()];case 3:return[2,{data:null,error:i.sent()}];case 4:return[2]}})})},_=function(e){function t(t,r){var n=e.call(this,r)||this;return n.base_url=t,n}return r(t,e),t.prototype.extraPrint=function(){return"api"},t.prototype.signOut=function(e){return i(this,void 0,void 0,function(){var t,r,n=e.credentials,i=function(e,t){var r={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(r[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var i=0;for(n=Object.getOwnPropertySymbols(e);i<n.length;i++)t.indexOf(n[i])<0&&Object.prototype.propertyIsEnumerable.call(e,n[i])&&(r[n[i]]=e[n[i]])}return r}(e,["credentials"]);return s(this,function(e){switch(e.label){case 0:return t="".concat(this.base_url,"/logout?").concat(new URLSearchParams(i)),this._debug("requesting ".concat(t)),[4,g(t,n?{credentials:n}:{})];case 1:return r=e.sent(),this._debug(r),r.error?[2,{error:r.error,data:null}]:[2,{error:null,data:null}]}})})},t}(u),y=function(e,t){return e.response_type||(t?"code":"token")},w=function(e,t,r){return i(void 0,void 0,void 0,function(){return s(this,function(n){switch(n.label){case 0:return[4,e.setItem(t,JSON.stringify(r))];case 1:return n.sent(),[2]}})})},m=function(e,t){return i(void 0,void 0,void 0,function(){var r;return s(this,function(n){switch(n.label){case 0:return[4,e.getItem(t)];case 1:if(!(r=n.sent()))return[2,null];try{return[2,JSON.parse(r)]}catch(e){return[2,r]}return[2]}})})},k=function(e,t,r){return i(void 0,[e,t,r],void 0,function(e,t,r){var n,i=r.verifier,o=r.redirectType,a=r.returnTo,u=r.now,c=void 0===u?Date.now():u;return s(this,function(r){switch(r.label){case 0:return n={verifier:i,createdAt:c},o&&(n.redirectType=o),a&&(n.returnTo=a),[4,w(e,t,n)];case 1:return r.sent(),[2]}})})},S=function(e,t){for(var r=[],n=2;n<arguments.length;n++)r[n-2]=arguments[n];return i(void 0,o([e,t],r,!0),void 0,function(e,t,r){var n,i,o=(void 0===r?{}:r).now,a=void 0===o?Date.now():o;return s(this,function(r){switch(r.label){case 0:return[4,m(e,t)];case 1:return n=r.sent(),"object"!=typeof(s=n)||null===s||"string"!=typeof s.verifier||"number"!=typeof s.createdAt?[2,null]:a-n.createdAt>6e5?[4,e.removeItem(t)]:[3,3];case 2:return r.sent(),[2,null];case 3:return i={verifier:n.verifier},n.redirectType&&(i.redirectType=n.redirectType),n.returnTo&&(i.returnTo=n.returnTo),[2,i]}var s})})};function T(e){return("0"+e.toString(16)).substr(-2)}function I(e){return i(this,void 0,void 0,function(){var t,r,n,i;return s(this,function(s){switch(s.label){case 0:return t=new TextEncoder,r=t.encode(e),[4,crypto.subtle.digest("SHA-256",r)];case 1:return n=s.sent(),i=new Uint8Array(n),[2,Array.from(i).map(function(e){return String.fromCharCode(e)}).join("")]}})})}function x(e){return i(this,void 0,void 0,function(){var t;return s(this,function(r){switch(r.label){case 0:return"undefined"!=typeof crypto&&void 0!==crypto.subtle&&"undefined"!=typeof TextEncoder?[4,I(e)]:(console.warn("WebCrypto API is not supported. Code challenge method will default to use plain instead of sha256."),[2,e]);case 1:return t=r.sent(),[2,(n=t,btoa(n).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,""))]}var n})})}function A(e,t){return i(this,arguments,void 0,function(e,t,r,n){var i,o;return void 0===r&&(r=!1),s(this,function(s){switch(s.label){case 0:return i=function(){if("undefined"==typeof crypto||"function"!=typeof crypto.getRandomValues)throw new Error("Web Crypto API is required to generate a PKCE code verifier");var e=new Uint32Array(56);return crypto.getRandomValues(e),Array.from(e,T).join("")}(),[4,k(e,"".concat(t,"-code-verifier"),{verifier:i,redirectType:r?"PASSWORD_RECOVERY":void 0,returnTo:n})];case 1:return s.sent(),[4,x(i)];case 2:return[2,[o=s.sent(),i===o?"plain":"S256"]]}})})}var R=function(){return"undefined"!=typeof document},E={tested:!1,writable:!1},C=function(){if(!R())return!1;try{if("object"!=typeof globalThis.localStorage)return!1}catch(e){return!1}if(E.tested)return E.writable;var e="lswt-".concat(Math.random()).concat(Math.random());try{globalThis.localStorage.setItem(e,e),globalThis.localStorage.removeItem(e),E.tested=!0,E.writable=!0}catch(e){E.tested=!0,E.writable=!1}return E.writable};function U(e){var t,r,i=e.data,s=null;if(!i)throw new Error("Bad session response");return function(e){return!!e.access_token&&!!e.refresh_token&&!!e.expires_in}(i)&&(s=n({},i),!i.expires_at&&i.expires_in&&(s.expires_at=(r=i.expires_in,Math.round(Date.now()/1e3)+r))),{data:{session:s,user:null!==(t=i.user)&&void 0!==t?t:i},error:null}}var P=function(){function e(){var t=this;this.promise=new e.promiseConstructor(function(e,r){t.resolve=e,t.reject=r})}return e.promiseConstructor=Promise,e}();function O(e,t){var r=this;return new Promise(function(n,o){i(r,void 0,void 0,function(){var r,i,a;return s(this,function(s){switch(s.label){case 0:r=0,s.label=1;case 1:if(!(r<1/0))return[3,6];s.label=2;case 2:return s.trys.push([2,4,,5]),[4,e(r)];case 3:return i=s.sent(),t(r,null,i)?[3,5]:(n(i),[2]);case 4:return a=s.sent(),t(r,a)?[3,5]:(o(a),[2]);case 5:return r++,[3,1];case 6:return[2]}})})})}function L(e){return i(this,void 0,void 0,function(){return s(this,function(t){return[2,new Promise(function(t){setTimeout(function(){return t(null)},e)})]})})}var D=function(){function e(e,t){var r=this;if(this.debug=t,this.channel=null,this.subscribers=new Map,"undefined"!=typeof globalThis&&"function"==typeof globalThis.BroadcastChannel&&e)try{this.channel=new globalThis.BroadcastChannel(e),this.channel.addEventListener("message",function(e){return i(r,void 0,void 0,function(){return s(this,function(t){switch(t.label){case 0:return this.debug("broadcast_sync: received notification from another tab",e),[4,this.dispatch(e.data.event,e.data.session,!1)];case 1:return t.sent(),[2]}})})})}catch(e){console.error("Failed to create BroadcastChannel; cross-tab sync disabled",e)}}return e.prototype.subscribe=function(e){var t=this,r="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(e){var t=16*Math.random()|0;return("x"==e?t:3&t|8).toString(16)}),n={id:r,callback:e,unsubscribe:function(){t.subscribers.delete(r)}};return this.subscribers.set(r,n),{subscription:n}},e.prototype.notify=function(e,t){return i(this,arguments,void 0,function(e,t,r){return void 0===r&&(r=!0),s(this,function(n){switch(n.label){case 0:return r&&this.channel&&this.channel.postMessage({event:e,session:t}),[4,this.dispatch(e,t,r)];case 1:return n.sent(),[2]}})})},e.prototype.dispatch=function(e,t,r){return i(this,void 0,void 0,function(){var r,n,o,a=this;return s(this,function(u){switch(u.label){case 0:return r=[],n=Array.from(this.subscribers.values()).map(function(n){return i(a,void 0,void 0,function(){var i;return s(this,function(s){switch(s.label){case 0:return s.trys.push([0,2,,3]),[4,n.callback(e,t)];case 1:return s.sent(),[3,3];case 2:return i=s.sent(),r.push(i),[3,3];case 3:return[2]}})})}),[4,Promise.all(n)];case 1:if(u.sent(),r.length>0){for(o=0;o<r.length;o+=1)console.error(r[o]);throw r[0]}return[2]}})})},e.prototype.close=function(){var e;this.subscribers.clear();try{null===(e=this.channel)||void 0===e||e.close()}catch(e){}this.channel=null},e}(),N="faableauth",z=function(e){function t(t,r,n){var i=e.call(this,t)||this;return i.__isAuthError=!0,i.name="AuthError",i.status=r,i.code=n,i}return r(t,e),t}(Error),q=function(e){function t(t,r,n,i){var s=e.call(this,t,n,i)||this;return s.name=r,s.status=n,s}return r(t,e),t}(z),j=function(e){function t(){return e.call(this,"Auth session missing!","AuthSessionMissingError",400,void 0)||this}return r(t,e),t}(q);function K(e){return"object"==typeof e&&null!==e&&"__isAuthError"in e}var M=function(e){function t(t,r,n){var i=e.call(this,t,r,n)||this;return i.name="AuthApiError",i.status=r,i.code=n,i}return r(t,e),t}(z);var F=function(e){function t(t,r){void 0===r&&(r=null);var n=e.call(this,t,"AuthImplicitGrantRedirectError",500,void 0)||this;return n.details=null,n.details=r,n}return r(t,e),t.prototype.toJSON=function(){return{name:this.name,message:this.message,status:this.status,details:this.details}},t}(q),V=function(e){function t(t,r){void 0===r&&(r=null);var n=e.call(this,t,"AuthPKCEGrantCodeExchangeError",500,void 0)||this;return n.details=null,n.details=r,n}return r(t,e),t.prototype.toJSON=function(){return{name:this.name,message:this.message,status:this.status,details:this.details}},t}(q),W=function(e){function t(t,r){var n=e.call(this,t)||this;return n.name="AuthUnknownError",n.originalError=r,n}return r(t,e),t}(z),G=function(e){function t(){return e.call(this,"Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)||this}return r(t,e),t}(q);function J(e){return K(e)&&"AuthRetryableFetchError"===e.name}function B(){if(!l)throw new Error("No window in environment");return l}!function(e){function t(t,r){return e.call(this,t,"AuthRetryableFetchError",r,void 0)||this}r(t,e)}(q);var $={redirect:function(e){B().location=e},getDocument:function(){return B().document},getWindow:B};function H(e){var t=e.split(".");if(3!==t.length)throw new Error("JWT is not valid: not a JWT structure");if(!/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}=?$|[a-z0-9_-]{2}(==)?$)$/i.test(t[1]))throw new Error("JWT is not valid: payload is not in base64url format");var r=t[1];return JSON.parse(function(e){var t,r,n,i,s,o,a="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",u="",c=0;for(e=e.replace("-","+").replace("_","/");c<e.length;)t=a.indexOf(e.charAt(c++))<<2|(i=a.indexOf(e.charAt(c++)))>>4,r=(15&i)<<4|(s=a.indexOf(e.charAt(c++)))>>2,n=(3&s)<<6|(o=a.indexOf(e.charAt(c++))),u+=String.fromCharCode(t),64!=s&&0!=r&&(u+=String.fromCharCode(r)),64!=o&&0!=n&&(u+=String.fromCharCode(n));return u}(r))}var Y=function(e,t){if(!e)return null;var r="function"==typeof e.get?function(t){var r;return null===(r=e.get(t))||void 0===r?void 0:r.value}:function(t){return e[t]},n=r(t);if(n)return n;for(var i=[],s=0;;s++){var o=r("".concat(t,".").concat(s));if(!o)break;i.push(o)}return i.length?i.join(""):null},Q=function(e){return"object"==typeof e&&null!==e&&"access_token"in e&&"refresh_token"in e&&"expires_at"in e},X=function(e){var t=new Map;if(!e)return t;for(var r=0,n=e.split(";");r<n.length;r++){var i=n[r].trim();if(i){var s=i.indexOf("=");if(!(s<0)){var o=Z(i.slice(0,s).trim()),a=Z(i.slice(s+1).trim());o&&t.set(o,a)}}}return t},Z=function(e){try{return decodeURIComponent(e)}catch(t){return e}},ee=function(e,t,r){var n="".concat(encodeURIComponent(e),"=").concat(encodeURIComponent(t));return void 0!==r.maxAge&&(n+="; Max-Age=".concat(r.maxAge)),r.domain&&(n+="; Domain=".concat(r.domain)),r.path&&(n+="; Path=".concat(r.path)),r.sameSite&&(n+="; SameSite=".concat(r.sameSite)),(!0===r.secure||"None"===r.sameSite)&&(n+="; Secure"),n},te=function(e,t){return ee(e,"",{domain:t.domain,path:t.path,sameSite:t.sameSite,secure:t.secure,maxAge:0})},re=3200,ne=function(e,t){return"".concat(e,".").concat(t)},ie=function(e,t){var r="".concat(t,"."),n=[];return e.forEach(function(e,t){if(t.startsWith(r)){var i=t.slice(r.length);/^\d+$/.test(i)&&n.push({name:t,idx:Number(i)})}}),n.sort(function(e,t){return e.idx-t.idx}),n.map(function(e){return e.name})},se=function(e,t){void 0===e&&(e={}),void 0===t&&(t=R()?document:null);var r=n({path:"/",sameSite:"Lax",secure:R()&&"https:"===window.location.protocol,maxAge:2592e3},e);return{getItem:function(e){return t?function(e,t){var r=e.get(t);if(void 0!==r)return r;var n=ie(e,t);return 0===n.length?null:n.map(function(t){return e.get(t)}).join("")}(X(t.cookie),e):null},setItem:function(e,n){if(t){var i=X(t.cookie);if(n.length<=re){for(var s=0,o=ie(i,e);s<o.length;s++){var a=o[s];t.cookie=te(a,r)}t.cookie=ee(e,n,r)}else{i.has(e)&&(t.cookie=te(e,r));for(var u=Math.ceil(n.length/re),c=0,l=ie(i,e);c<l.length;c++){var h=l[c];Number(h.slice(e.length+1))>=u&&(t.cookie=te(h,r))}for(var d=0,f=0;d<n.length;d+=re,f++){var v=n.slice(d,d+re);t.cookie=ee(ne(e,f),v,r)}}}},removeItem:function(e){if(t){var n=X(t.cookie);t.cookie=te(e,r);for(var i=0,s=ie(n,e);i<s.length;i++){var o=s[i];t.cookie=te(o,r)}}}}},oe={getItem:function(e){return C()?globalThis.localStorage.getItem(e):null},setItem:function(e,t){C()&&globalThis.localStorage.setItem(e,t)},removeItem:function(e){C()&&globalThis.localStorage.removeItem(e)}};function ae(e){void 0===e&&(e="");var t={},r=new URL(e);if(r.hash&&"#"===r.hash[0])try{new URLSearchParams(r.hash.substring(1)).forEach(function(e,r){t[r]=e})}catch(e){}return r.searchParams.forEach(function(e,r){t[r]=e}),t}var ue=function(e){void 0===e&&(e=[]);var t=new URL(window.location.href);e.forEach(function(e){t.searchParams.delete(e)}),t.hash="",window.history.replaceState(window.history.state,"",t.toString())};globalThis&&C()&&globalThis.localStorage&&globalThis.localStorage.getItem("faable.auth.locks.debug");var ce=function(e){function t(t){var r=e.call(this,t)||this;return r.isAcquireTimeout=!0,r}return r(t,e),t}(Error);function le(e,t,r){return i(this,void 0,void 0,function(){return s(this,function(e){switch(e.label){case 0:return[4,r()];case 1:return[2,e.sent()]}})})}!function(e){function t(){return null!==e&&e.apply(this,arguments)||this}r(t,e)}(ce);var he=function(e){function t(t){var r=e.call(this,{debug:t.debug})||this;return r.lockAcquired=!1,r.pendingInLock=[],r.lock=t.lock||le,r.storageKey=t.storageKey,r}return r(t,e),t.prototype._acquireLock=function(e,t){return i(this,void 0,void 0,function(){var r,n,a=this;return s(this,function(u){switch(u.label){case 0:this._debug("#_acquireLock","begin",e),u.label=1;case 1:return u.trys.push([1,,3,4]),this.lockAcquired?(r=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),n=i(a,void 0,void 0,function(){return s(this,function(e){switch(e.label){case 0:return[4,r];case 1:return e.sent(),[4,t()];case 2:return[2,e.sent()]}})}),this.pendingInLock.push(i(a,void 0,void 0,function(){return s(this,function(e){switch(e.label){case 0:return e.trys.push([0,2,,3]),[4,n];case 1:case 2:return e.sent(),[3,3];case 3:return[2]}})})),[2,n]):[4,this.lock("lock:".concat(this.storageKey),e,function(){return i(a,void 0,void 0,function(){var e,r,n=this;return s(this,function(a){switch(a.label){case 0:this._debug("#_acquireLock","lock acquired for storage key",this.storageKey),a.label=1;case 1:return a.trys.push([1,,7,8]),this.lockAcquired=!0,e=t(),this.pendingInLock.push(i(n,void 0,void 0,function(){return s(this,function(t){switch(t.label){case 0:return t.trys.push([0,2,,3]),[4,e];case 1:case 2:return t.sent(),[3,3];case 3:return[2]}})})),[4,e];case 2:a.sent(),a.label=3;case 3:return this.pendingInLock.length?(r=o([],this.pendingInLock,!0),[4,Promise.all(r)]):[3,5];case 4:return a.sent(),this.pendingInLock.splice(0,r.length),[3,3];case 5:return[4,e];case 6:return[2,a.sent()];case 7:return this._debug("#_acquireLock","lock released for storage key",this.storageKey),this.lockAcquired=!1,[7];case 8:return[2]}})})})];case 2:return[2,u.sent()];case 3:return this._debug("#_acquireLock","end"),[7];case 4:return[2]}})})},t}(c),de=3e4,fe=function(e){function t(t){var r,n,i=this,s=(null==t?void 0:t.debug)||!1;if((i=e.call(this,{debug:s})||this).initializePromise=null,i._lastInitializeResult=null,i.detectSessionInUrl=!0,i.autoRefreshTicker=null,i.visibilityChangedCallback=null,i.refreshingDeferred=null,i._session=null,i.sessionCheckExpiryDays=1,i.redirectUri=(null==t?void 0:t.redirectUri)||"",!(null==t?void 0:t.domain))throw new Error("Missing domain");if(i.domainUrl=function(e){var t=(null!=e?e:"").trim().replace(/\/+$/,""),r=t.match(/^(https?):\/\/(.*)$/i);if(r){var n=r[2].replace(/^(https?:\/\/)+/i,"");return"".concat(r[1].toLowerCase(),"://").concat(n)}var i="undefined"!=typeof location&&(null===location||void 0===location?void 0:location.protocol)?location.protocol.replace(/:$/,""):"https";return"".concat(i,"://").concat(t)}(t.domain),i.tokenIssuer=(n=i.domainUrl,"".concat(n)),!t.clientId)throw new Error("Missing clientId");i.clientId=t.clientId,i.audience=t.audience,i.api=new _(i.domainUrl,{debug:s});var a=(null==t?void 0:t.storageKey)||N;return i.storageKey="".concat(a,"-").concat(i.clientId),i.storage=function(e){var t=e.storage,r=e.cookieOptions;return"cookie"===t||r?se(r):"localStorage"===t||void 0===t?oe:t}(t),i.lock=new he({lock:t.lock,storageKey:i.storageKey,debug:t.debug}),i.broadcastSync=new D(R()?i.storageKey:"",function(e){for(var t=[],r=1;r<arguments.length;r++)t[r-1]=arguments[r];return i._debug.apply(i,o([e],t,!1))}),i.flowType=null!==(r=t.flowType)&&void 0!==r?r:R()?"pkce":"implicit",i.autoRefreshToken=!0,i.initialize(),i}return r(t,e),Object.defineProperty(t.prototype,"session",{get:function(){return this._session},enumerable:!1,configurable:!0}),t.prototype.initialize=function(){return i(this,void 0,void 0,function(){var e,t=this;return s(this,function(r){switch(r.label){case 0:return this.initializePromise?[4,this.initializePromise]:[3,2];case 1:return[2,r.sent()];case 2:return this.initializePromise=i(t,void 0,void 0,function(){var e=this;return s(this,function(t){switch(t.label){case 0:return[4,this.lock._acquireLock(-1,function(){return i(e,void 0,void 0,function(){return s(this,function(e){switch(e.label){case 0:return[4,this._initialize()];case 1:return[2,e.sent()]}})})})];case 1:return[2,t.sent()]}})}),[4,this.initializePromise];case 3:return e=r.sent(),this._lastInitializeResult=e,[2,e]}})})},Object.defineProperty(t.prototype,"lastInitializeResult",{get:function(){return this._lastInitializeResult},enumerable:!1,configurable:!0}),t.prototype.handleRedirectCallback=function(){return i(this,void 0,void 0,function(){return s(this,function(e){switch(e.label){case 0:return[4,this.initialize()];case 1:return[2,e.sent()]}})})},t.prototype._initialize=function(){return i(this,void 0,void 0,function(){var e,t,r,n,o,a,u,c,l,h=this;return s(this,function(d){switch(d.label){case 0:return d.trys.push([0,8,9,11]),[4,this._detectFlowType()];case 1:return e=d.sent(),this._debug("#_initialize()","begin","flow_type",e),e?[4,this._getSessionFromURL(e)]:[3,6];case 2:return t=d.sent(),r=t.data,(n=t.error)?(this._debug("#_initialize()","error detecting session from URL",n),"Identity is already linked"===(null==n?void 0:n.message)||"Identity is already linked to another user"===(null==n?void 0:n.message)?[2,{error:n}]:[4,this._removeSession()]):[3,4];case 3:return d.sent(),[2,{error:n}];case 4:return o=r.session,a=r.redirectType,u=r.returnTo,c=r.is_new_user,this._debug("#_initialize()","detected session in URL",o,"redirect type",a),[4,this._saveSession(o)];case 5:return d.sent(),setTimeout(function(){return i(h,void 0,void 0,function(){return s(this,function(e){switch(e.label){case 0:return"recovery"!==a?[3,2]:[4,this._notifyAllSubscribers("PASSWORD_RECOVERY",o)];case 1:return e.sent(),[3,4];case 2:return[4,this._notifyAllSubscribers("SIGNED_IN",o)];case 3:e.sent(),e.label=4;case 4:return[2]}})})},0),[2,{error:null,redirectType:a,returnTo:u,is_new_user:c}];case 6:return[4,this._recoverAndRefresh()];case 7:return d.sent(),[2,{error:null}];case 8:return K(l=d.sent())?[2,{error:l}]:[2,{error:new W("Unexpected error during initialization",l)}];case 9:return[4,this._handleVisibilityChange()];case 10:return d.sent(),this._debug("#_initialize()","end"),[7];case 11:return[2]}})})},t.prototype._getSessionFromURL=function(e){return i(this,void 0,void 0,function(){var t,r,n,i,o,a,u,c,h,d,f,v,p,b,g,_,y,w,m,k,S;return s(this,function(s){switch(s.label){case 0:if(s.trys.push([0,4,,5]),t=ae(null==l?void 0:l.location.href),r="true"===t.signup,"pkce"!=e)return[3,2];if(!t.code)throw new V("No code detected.");return[4,this._exchangeCodeForSession(t.code)];case 1:if(n=s.sent(),i=n.data,o=n.error)throw o;return ue(["code","signup"]),[2,{data:{session:i.session,redirectType:i.redirectType,returnTo:i.returnTo,is_new_user:r},error:null}];case 2:if(t.error||t.error_description||t.error_code)throw new F(t.error_description||"Error in URL with unspecified error_description",{error:t.error||"unspecified_error",code:t.error_code||"unspecified_code"});if(a=t.provider_token,u=t.provider_refresh_token,c=t.access_token,h=t.refresh_token,d=t.expires_in,f=t.expires_at,v=t.token_type,!c||!h)throw new F("No session defined in URL");return p=void 0,b=void 0,d?(k=function(e){var t=e.expires_in,r=e.expires_at,n=e.refreshTick,i=Math.round(Date.now()/1e3),s=parseInt(t),o=i+s;r&&(o=parseInt(r));var a=o-i;1e3*a<=n&&console.warn("@faable/auth-js: Session as retrieved from URL expires in ".concat(a,"s, should have been closer to ").concat(s,"s"));var u=o-s;return i-u>=120?console.warn("@faable/auth-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",u,o,i):i-u<0&&console.warn("@faable/auth-js: Session as retrieved from URL was issued in the future? Check the device clok for skew",u,o,i),{expiresIn:s,expiresAt:o}}({expires_in:d,expires_at:f,refreshTick:de}),p=k.expiresAt,b=k.expiresIn):(S=function(e,t,r){var n;void 0===r&&(r=Date.now()/1e3);var i=H(e),s=null!=t&&""!==t?Number(t):null!==(n=i.exp)&&void 0!==n?n:r;return{expiresAt:s,expiresIn:s-r}}(c,f),p=S.expiresAt,b=S.expiresIn),[4,this._getUser(c)];case 3:if(g=s.sent(),_=g.data,(y=g.error)||!_)throw y;return w={provider_token:a,provider_refresh_token:u,access_token:c,expires_in:b,expires_at:p,refresh_token:h,token_type:v||"bearer",user:_},ue(["access_token","expires_in","refresh_token","token_type","scope","signup"]),this._debug("#_getSessionFromURL()","clearing window.location.hash"),[2,{data:{session:w,redirectType:t.type,returnTo:null,is_new_user:r},error:null}];case 4:if(m=s.sent(),this._debug(m),K(m))return[2,{data:{session:null,redirectType:null,returnTo:null,is_new_user:!1},error:m}];throw m;case 5:return[2]}})})},t.prototype._exchangeCodeForSession=function(e){return i(this,void 0,void 0,function(){var t,r,i,o,a,u,c,l,h,d,f,v,p,g;return s(this,function(s){switch(s.label){case 0:return[4,S(this.storage,"".concat(this.storageKey,"-code-verifier"))];case 1:return(t=s.sent())?(r=t.verifier,i=t.redirectType,o=void 0===i?null:i,a=t.returnTo,u=void 0===a?null:a,[4,b("".concat(this.domainUrl,"/oauth/token"),n({client_id:this.clientId,grant_type:"authorization_code",code:e,code_verifier:r},this.audience?{audience:this.audience}:{}))]):[2,{data:{user:null,session:null,redirectType:null,returnTo:null},error:new V("No active PKCE code verifier — the authorization flow has expired or was not started")}];case 2:if(c=s.sent(),l=U(c),h=l.data,d=l.error,!h)throw new Error("Missing data");return[4,this.storage.removeItem("".concat(this.storageKey,"-code-verifier"))];case 3:return s.sent(),d?[2,{data:{user:null,session:null,redirectType:null,returnTo:null},error:d}]:h&&h.session&&h.user?(f=h.session)?[4,this._getUser(f.access_token)]:[3,7]:[2,{data:{user:null,session:null,redirectType:null,returnTo:null},error:new G}];case 4:if(v=s.sent(),p=v.data,(g=v.error)||!p)throw g;return f=n(n({},f),{user:p}),h.session=f,[4,this._saveSession(f)];case 5:return s.sent(),[4,this._notifyAllSubscribers("SIGNED_IN",f)];case 6:s.sent(),s.label=7;case 7:return[2,{data:n(n({},h),{redirectType:null!=o?o:null,returnTo:null!=u?u:null}),error:d}]}})})},t.prototype._handleVisibilityChange=function(){return i(this,void 0,void 0,function(){var e,t=this;return s(this,function(r){switch(r.label){case 0:if(this._debug("#_handleVisibilityChange()"),!R()||!(null==l?void 0:l.addEventListener))return this.autoRefreshToken&&this.startAutoRefresh(),[2,!1];r.label=1;case 1:return r.trys.push([1,3,,4]),this.visibilityChangedCallback=function(){return i(t,void 0,void 0,function(){return s(this,function(e){switch(e.label){case 0:return[4,this._onVisibilityChanged(!1)];case 1:return[2,e.sent()]}})})},null==l||l.addEventListener("visibilitychange",this.visibilityChangedCallback),[4,this._onVisibilityChanged(!0)];case 2:return r.sent(),[3,4];case 3:return e=r.sent(),console.error("_handleVisibilityChange",e),[3,4];case 4:return[2]}})})},t.prototype._onVisibilityChanged=function(e){return i(this,void 0,void 0,function(){var t,r=this;return s(this,function(n){switch(n.label){case 0:return t="#_onVisibilityChanged(".concat(e,")"),this._debug(t,"visibilityState",d.visibilityState),"visible"!==d.visibilityState?[3,4]:(this.autoRefreshToken&&this._startAutoRefresh(),e?[3,3]:[4,this.initializePromise]);case 1:return n.sent(),[4,this.lock._acquireLock(-1,function(){return i(r,void 0,void 0,function(){return s(this,function(e){switch(e.label){case 0:return"visible"!==d.visibilityState?(this._debug(t,"acquired the lock to recover the session, but the browser visibilityState is no longer visible, aborting"),[2]):[4,this._recoverAndRefresh()];case 1:return e.sent(),[2]}})})})];case 2:n.sent(),n.label=3;case 3:return[3,5];case 4:"hidden"===d.visibilityState&&this.autoRefreshToken&&this._stopAutoRefresh(),n.label=5;case 5:return[2]}})})},t.prototype._recoverAndRefresh=function(){return i(this,void 0,void 0,function(){var e,t,r,n,i,o,a;return s(this,function(s){switch(s.label){case 0:e="#_recoverAndRefresh()",this._debug(e,"begin"),s.label=1;case 1:return s.trys.push([1,12,13,14]),[4,m(this.storage,this.storageKey)];case 2:return t=s.sent(),this._debug(e,"session from storage",t),Q(t)?[3,5]:(this._debug(e,"session is not valid"),null===t?[3,4]:[4,this._removeSession()]);case 3:s.sent(),s.label=4;case 4:return[2];case 5:return r=Math.round(Date.now()/1e3),n=(null!==(a=t.expires_at)&&void 0!==a?a:1/0)<r+10,this._debug(e,"session has".concat(n?"":" not"," expired with margin of ").concat(10,"s")),n?this.autoRefreshToken&&t.refresh_token?[4,this._callRefreshToken(t.refresh_token)]:[3,8]:[3,9];case 6:return(i=s.sent().error)?(console.error(i),J(i)?[3,8]:(this._debug(e,"refresh failed with a non-retryable error, removing the session",i),[4,this._removeSession()])):[3,8];case 7:s.sent(),s.label=8;case 8:return[3,11];case 9:return this._session=t,[4,this._notifyAllSubscribers("SIGNED_IN",t)];case 10:s.sent(),s.label=11;case 11:return[3,14];case 12:return o=s.sent(),this._debug(e,"error",o),console.error(o),[2];case 13:return this._debug(e,"end"),[7];case 14:return[2]}})})},t.prototype._removeVisibilityChangedCallback=function(){this._debug("#_removeVisibilityChangedCallback()");var e=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{e&&R()&&(null==l?void 0:l.removeEventListener)&&l.removeEventListener("visibilitychange",e)}catch(e){console.error("removing visibilitychange callback failed",e)}},t.prototype.startAutoRefresh=function(){return i(this,void 0,void 0,function(){return s(this,function(e){switch(e.label){case 0:return this._removeVisibilityChangedCallback(),[4,this._startAutoRefresh()];case 1:return e.sent(),[2]}})})},t.prototype._startAutoRefresh=function(){return i(this,void 0,void 0,function(){var e,t=this;return s(this,function(r){switch(r.label){case 0:return[4,this._stopAutoRefresh()];case 1:return r.sent(),this._debug("#_startAutoRefresh()"),e=setInterval(function(){return t._autoRefreshTokenTick()},de),this.autoRefreshTicker=e,e&&"object"==typeof e&&"function"==typeof e.unref?e.unref():void 0!==globalThis.Deno&&"function"==typeof globalThis.Deno.unrefTimer&&globalThis.Deno.unrefTimer(e),setTimeout(function(){return i(t,void 0,void 0,function(){return s(this,function(e){switch(e.label){case 0:return[4,this.initializePromise];case 1:return e.sent(),[4,this._autoRefreshTokenTick()];case 2:return e.sent(),[2]}})})},0),[2]}})})},t.prototype._stopAutoRefresh=function(){return i(this,void 0,void 0,function(){var e;return s(this,function(t){return this._debug("#_stopAutoRefresh()"),e=this.autoRefreshTicker,this.autoRefreshTicker=null,e&&clearInterval(e),[2]})})},t.prototype._autoRefreshTokenTick=function(){return i(this,void 0,void 0,function(){var e,t=this;return s(this,function(r){switch(r.label){case 0:this._debug("#_autoRefreshTokenTick()","begin"),r.label=1;case 1:return r.trys.push([1,3,,4]),[4,this.lock._acquireLock(0,function(){return i(t,void 0,void 0,function(){var e,t,r=this;return s(this,function(n){switch(n.label){case 0:n.trys.push([0,,5,6]),e=Date.now(),n.label=1;case 1:return n.trys.push([1,3,,4]),[4,this._useSession(function(t){return i(r,void 0,void 0,function(){var r,n;return s(this,function(i){switch(i.label){case 0:return(r=t.data.session)&&r.refresh_token&&r.expires_at?(n=Math.floor((1e3*r.expires_at-e)/de),this._debug("#_autoRefreshTokenTick()","access token expires in ".concat(n," ticks, a tick lasts ").concat(de,"ms, refresh threshold is ").concat(3," ticks")),n<=3?[4,this._callRefreshToken(r.refresh_token)]:[3,2]):(this._debug("#_autoRefreshTokenTick()","no session"),[2]);case 1:i.sent(),i.label=2;case 2:return[2]}})})})];case 2:return[2,n.sent()];case 3:return t=n.sent(),console.error("Auto refresh tick failed with error. This is likely a transient error.",t),[3,4];case 4:return[3,6];case 5:return this._debug("#_autoRefreshTokenTick()","end"),[7];case 6:return[2]}})})})];case 2:return r.sent(),[3,4];case 3:if(!((e=r.sent()).isAcquireTimeout||e instanceof ce))throw e;return this._debug("auto refresh token tick lock not available"),[3,4];case 4:return[2]}})})},t.prototype._detectFlowType=function(){return i(this,void 0,void 0,function(){var e,t;return s(this,function(r){return e=ae(null==l?void 0:l.location.href),(t=R())&&e.code?[2,"pkce"]:t&&(e.access_token||e.error_description)?[2,"implicit"]:[2,null]})})},t.prototype._scope=function(){return this.scope||"openid profile email"},t.prototype._getUrlForConnection=function(e,t){return i(this,void 0,void 0,function(){var r,i,o,a,u,c,h;return s(this,function(s){switch(s.label){case 0:return r=t.queryParams||{},i={client_id:this.clientId,response_type:t.response_type,redirect_uri:t.redirectTo||this.redirectUri||(null==l?void 0:l.location.origin),scope:t.scopes||this._scope()},"pkce"!==this.flowType?[3,2]:[4,A(this.storage,this.storageKey,!1,t.returnTo)];case 1:o=s.sent(),a=o[0],u=o[1],r=n(n({},r),{code_challenge:a,code_challenge_method:u}),s.label=2;case 2:return t.connection_id?i.connection_id=t.connection_id:t.connection&&(i.connection=t.connection),(c=null!==(h=t.audience)&&void 0!==h?h:this.audience)&&(i.audience=c),[2,"".concat(e,"?").concat(new URLSearchParams(n(n({},r),i)))]}})})},t.prototype.signInWithOauthConnection=function(e){return i(this,void 0,void 0,function(){return s(this,function(t){switch(t.label){case 0:return[4,this._handleConnectionSignIn({connection:e.connection,connection_id:e.connection_id,redirectTo:null==e?void 0:e.redirectTo,returnTo:null==e?void 0:e.returnTo,scopes:null==e?void 0:e.scopes,queryParams:e.queryParams,skipBrowserRedirect:e.skipBrowserRedirect,audience:e.audience})];case 1:return[2,t.sent()]}})})},t.prototype.signInWithUsernamePassword=function(e){return i(this,void 0,void 0,function(){var t,r,i;return s(this,function(s){switch(s.label){case 0:return t=null!==(i=e.audience)&&void 0!==i?i:this.audience,[4,b("".concat(this.domainUrl,"/usernamepassword/login"),n({username:e.username,password:e.password,redirect_uri:e.redirectTo||this.redirectUri||(null==l?void 0:l.location.origin),client_id:this.clientId,state:e.state},t?{audience:t}:{}),{raw:!0})];case 1:return!(r=s.sent()).data||r.error?[2,{data:null,error:new W(r.error||"Error in username password login",r.error)}]:(function(e,t){var r=t.createElement("div");r.innerHTML=e;var n=t.body.appendChild(r).children[0];if(!n)throw new Error("Auth response did not contain a submittable form");n.submit()}(r.data,d),[2,{data:null,error:null}])}})})},t.prototype.signUp=function(e){return i(this,void 0,void 0,function(){var t,r,i,o,a;return s(this,function(s){switch(s.label){case 0:return(null==e?void 0:e.email)&&(null==e?void 0:e.password)?[4,b("".concat(this.domainUrl,"/dbconnections/signup"),n(n(n(n(n({client_id:this.clientId,email:e.email,password:e.password},e.name?{name:e.name}:{}),e.given_name?{given_name:e.given_name}:{}),e.family_name?{family_name:e.family_name}:{}),e.user_metadata?{user_metadata:e.user_metadata}:{}),e.connection?{connection:e.connection}:{}))]:[2,{data:null,error:new W("email and password are required",null)}];case 1:return t=s.sent(),r=t.data,(i=t.error)?(o=null==r?void 0:r.status,a=403===o?"signup_disabled":409===o?"email_exists":void 0,[2,{data:null,error:new M(String(i),null!=o?o:500,a)}]):[2,this.signInWithUsernamePassword({username:e.email,password:e.password,redirectTo:e.redirectTo,state:e.state,audience:e.audience})]}})})},t.prototype.signInWithOtp=function(e){return i(this,void 0,void 0,function(){var t,r,i,o,a,u,c,l,h,d;return s(this,function(s){switch(s.label){case 0:return t=null!==(d=e.audience)&&void 0!==d?d:this.audience,[4,b("".concat(this.domainUrl,"/oauth/token"),n({client_id:this.clientId,grant_type:"http://auth0.com/oauth/grant-type/passwordless/otp",username:e.username,otp:e.otp},t?{audience:t}:{}))];case 1:return r=s.sent(),i=U(r),o=i.data,(a=i.error)?[2,{data:{user:null,session:null},error:a}]:o&&o.session?(u=o.session,[4,this._getUser(u.access_token)]):[2,{data:{user:null,session:null},error:new G}];case 2:return c=s.sent(),l=c.data,(h=c.error)||!l?[2,{data:{user:null,session:null},error:h||new W("Could not fetch user info",null)}]:(u.user=l,[4,this._saveSession(u)]);case 3:return s.sent(),[4,this._notifyAllSubscribers("SIGNED_IN",u)];case 4:return s.sent(),[2,{data:{user:u.user,session:u},error:null}]}})})},t.prototype.signInWithPasswordless=function(e){return i(this,void 0,void 0,function(){var t,r,i;return s(this,function(s){switch(s.label){case 0:return t=null!==(i=e.audience)&&void 0!==i?i:this.audience,[4,b("".concat(this.domainUrl,"/passwordless/start"),n({client_id:this.clientId,email:e.email,send:e.type},t?{audience:t}:{}))];case 1:return[2,{data:(r=s.sent()).data,error:r.error}]}})})},t.prototype.changePassword=function(e){return i(this,void 0,void 0,function(){var t,r,n;return s(this,function(i){switch(i.label){case 0:return(null==e?void 0:e.email)?[4,b("".concat(this.domainUrl,"/dbconnections/change_password"),{email:e.email})]:[2,{data:null,error:new W("email is required",null)}];case 1:return t=i.sent(),r=t.data,n=t.error,[2,{data:null!=r?r:null,error:n?new W(String(n),n):null}]}})})},t.prototype._resolveUserId=function(e){var t,r,n,i=null!==(r=null===(t=e.user)||void 0===t?void 0:t.id)&&void 0!==r?r:null===(n=e.user)||void 0===n?void 0:n.sub;if(i)return i;try{var s=H(e.access_token);return null==s?void 0:s.sub}catch(e){return}},t.prototype.changeEmail=function(e){return i(this,void 0,void 0,function(){var t,r,i,o,a,u,c,l;return s(this,function(s){switch(s.label){case 0:return(null==e?void 0:e.new_email)?[4,this.getSession()]:[2,{data:null,error:new W("new_email is required",null)}];case 1:return t=s.sent(),r=t.data,i=t.error,o=null==r?void 0:r.session,i||!o?[2,{data:null,error:i||new j}]:(a=this._resolveUserId(o))?[4,b("".concat(this.domainUrl,"/user/").concat(a,"/change-email"),n(n({new_email:e.new_email},e.verification_mode?{verification_mode:e.verification_mode}:{}),e.redirect_uri?{redirect_uri:e.redirect_uri}:{}),{token:o.access_token})]:[2,{data:null,error:new j}];case 2:return u=s.sent(),c=u.data,l=u.error,[2,{data:null!=c?c:null,error:l?new W(String(l),l):null}]}})})},t.prototype.buildAuthorizeUrl=function(e){var t;void 0===e&&(e={});var r=n(n({},e.queryParams),{client_id:this.clientId,redirect_uri:e.redirectTo||this.redirectUri||(null==l?void 0:l.location.origin),response_type:y(e,R()),audience:null!==(t=e.audience)&&void 0!==t?t:this.audience,scope:e.scope,connection:e.connection}),i=Object.fromEntries(Object.entries(r).filter(function(e){return!!e[1]}));return"".concat(this.domainUrl,"/authorize?").concat(new URLSearchParams(i).toString())},t.prototype.getLogoutUrl=function(e){void 0===e&&(e={});var t={client_id:this.clientId};return e.returnTo&&(t.post_logout_redirect_uri=e.returnTo),"".concat(this.domainUrl,"/logout?").concat(new URLSearchParams(t).toString())},t.prototype.authorize=function(e){var t=this.buildAuthorizeUrl(e);$.redirect(t)},t.prototype._handleConnectionSignIn=function(e){return i(this,void 0,void 0,function(){var t;return s(this,function(r){switch(r.label){case 0:return[4,this._getUrlForConnection("".concat(this.domainUrl,"/authorize"),{response_type:R()?"code":"token",connection:e.connection,connection_id:e.connection_id,redirectTo:e.redirectTo,returnTo:e.returnTo,scopes:e.scopes,queryParams:e.queryParams,audience:e.audience})];case 1:return t=r.sent(),this._debug("#_handleConnectionSignIn()","options",e,"url",t),!R()||e.skipBrowserRedirect?[3,3]:(null==l||l.location.assign(t),[4,new Promise(function(){})]);case 2:r.sent(),r.label=3;case 3:return[2,{data:{url:t},error:null}]}})})},t.prototype.setSession=function(e){return i(this,void 0,void 0,function(){var t=this;return s(this,function(r){switch(r.label){case 0:return[4,this.initializePromise];case 1:return r.sent(),[4,this.lock._acquireLock(-1,function(){return i(t,void 0,void 0,function(){return s(this,function(t){switch(t.label){case 0:return[4,this._setSession(e)];case 1:return[2,t.sent()]}})})})];case 2:return[2,r.sent()]}})})},t.prototype.getSession=function(){return i(this,void 0,void 0,function(){var e=this;return s(this,function(t){switch(t.label){case 0:return[4,this.initializePromise];case 1:return t.sent(),[4,this.lock._acquireLock(-1,function(){return i(e,void 0,void 0,function(){var e=this;return s(this,function(t){return[2,this._useSession(function(t){return i(e,void 0,void 0,function(){return s(this,function(e){return[2,t]})})})]})})})];case 2:return[2,t.sent()]}})})},t.prototype._useSession=function(e){return i(this,void 0,void 0,function(){var t;return s(this,function(r){switch(r.label){case 0:this._debug("#_useSession","begin"),r.label=1;case 1:return r.trys.push([1,,4,5]),[4,this.__loadSession()];case 2:return t=r.sent(),[4,e(t)];case 3:return[2,r.sent()];case 4:return this._debug("#_useSession","end"),[7];case 5:return[2]}})})},t.prototype.__loadSession=function(){return i(this,void 0,void 0,function(){var e,t,r,n,i,o,a;return s(this,function(s){switch(s.label){case 0:this._debug("#__loadSession()","begin"),this.lock.lockAcquired||this._debug("#__loadSession()","used outside of an acquired lock!",(new Error).stack),s.label=1;case 1:return s.trys.push([1,,7,8]),e=null,[4,m(this.storage,this.storageKey)];case 2:return t=s.sent(),this._debug("#getSession()","session from storage",t),null===t?[3,5]:Q(t)?(e=t,[3,5]):[3,3];case 3:return this._debug("#getSession()","session from storage is not valid"),[4,this._removeSession()];case 4:s.sent(),s.label=5;case 5:return e?(r=!!e.expires_at&&e.expires_at<=Date.now()/1e3,this._debug("#__loadSession()","session has".concat(r?"":" not"," expired"),"expires_at",e.expires_at),r?[4,this._callRefreshToken(e.refresh_token)]:(this.storage.isServer&&(n=new Proxy(e,{get:function(e,t,r){return"user"===t&&console.warn("Reading `session.user` from a server-side cookie store can be insecure: the value is whatever the cookie contains and has not been verified against Faable Auth. Re-fetch the user with `auth.getUser()` (or verify the access token yourself) before trusting it on the server."),Reflect.get(e,t,r)}}),e=n),[2,{data:{session:e},error:null}])):[2,{data:{session:null},error:null}];case 6:return i=s.sent(),o=i.session,(a=i.error)?[2,{data:{session:null},error:a}]:[2,{data:{session:o},error:null}];case 7:return this._debug("#__loadSession()","end"),[7];case 8:return[2]}})})},t.prototype._removeSession=function(){return i(this,void 0,void 0,function(){return s(this,function(e){switch(e.label){case 0:return this._debug("#_removeSession()"),this._session=null,[4,this.storage.removeItem(this.storageKey)];case 1:return e.sent(),[2]}})})},t.prototype._setSession=function(e){return i(this,void 0,void 0,function(){var t,r,n,i,o,a,u,c,l,h,d;return s(this,function(s){switch(s.label){case 0:if(s.trys.push([0,7,,8]),!e.access_token||!e.refresh_token)throw new j;return t=Date.now()/1e3,r=t,n=!0,i=null,(o=H(e.access_token)).exp&&(r=o.exp,n=r<=t),n?[4,this._callRefreshToken(e.refresh_token)]:[3,2];case 1:return a=s.sent(),u=a.session,(h=a.error)?[2,{data:{user:null,session:null},error:h}]:u?(i=u,[3,6]):[2,{data:{user:null,session:null},error:null}];case 2:return[4,this._getUser(e.access_token)];case 3:if(c=s.sent(),l=c.data,(h=c.error)||!l)throw h;return i={access_token:e.access_token,refresh_token:e.refresh_token,user:l,token_type:"bearer",expires_in:r-t,expires_at:r},[4,this._saveSession(i)];case 4:return s.sent(),[4,this._notifyAllSubscribers("SIGNED_IN",i)];case 5:s.sent(),s.label=6;case 6:return[2,{data:{user:i.user,session:i},error:null}];case 7:if(K(d=s.sent()))return[2,{data:{session:null,user:null},error:d}];throw d;case 8:return[2]}})})},t.prototype._saveSession=function(e){return i(this,void 0,void 0,function(){return s(this,function(t){switch(t.label){case 0:return this._debug("#_saveSession()",e),this._session=e,[4,w(this.storage,this.storageKey,e)];case 1:return t.sent(),[2]}})})},t.prototype._getUser=function(e){return i(this,void 0,void 0,function(){var t;return s(this,function(r){switch(r.label){case 0:if(!e)throw new Error("Cannot fetch user without token");return this._debug("#_getUser() begin"),[4,g("".concat(this.domainUrl,"/me"),{token:e})];case 1:return t=r.sent(),this._debug("#_getUser() end"),[2,{data:t.data,error:t.error}]}})})},t.prototype._callRefreshToken=function(e){return i(this,void 0,void 0,function(){var t,r,n,i,o,a,u,c;return s(this,function(s){switch(s.label){case 0:if(!e)throw new j;if(this.refreshingDeferred)return[2,this.refreshingDeferred.promise];t="#_callRefreshToken(".concat(e.substring(0,5),"...)"),this._debug(t,"begin"),s.label=1;case 1:return s.trys.push([1,5,10,11]),this.refreshingDeferred=new P,[4,(l=this._refreshAccessToken(e),h=3e4,d="Token refresh timed out",v=new Promise(function(e,t){f=setTimeout(function(){return t(new Error(d))},h)}),Promise.race([l.finally(function(){void 0!==f&&clearTimeout(f)}),v]))];case 2:if(r=s.sent(),n=r.data,i=r.error)throw i;if(!n.session)throw new j;return[4,this._saveSession(n.session)];case 3:return s.sent(),[4,this._notifyAllSubscribers("TOKEN_REFRESHED",n.session)];case 4:return s.sent(),a={session:n.session,error:null},this.refreshingDeferred.resolve(a),[2,a];case 5:return o=s.sent(),this._debug(t,"error",o),K(o)?(a={session:null,error:o},J(o)?[3,8]:[4,this._removeSession()]):[3,9];case 6:return s.sent(),[4,this._notifyAllSubscribers("SIGNED_OUT",null)];case 7:s.sent(),s.label=8;case 8:return null===(u=this.refreshingDeferred)||void 0===u||u.resolve(a),[2,a];case 9:throw null===(c=this.refreshingDeferred)||void 0===c||c.reject(o),o;case 10:return this.refreshingDeferred=null,this._debug(t,"end"),[7];case 11:return[2]}var l,h,d,f,v})})},t.prototype._refreshAccessToken=function(e){return i(this,void 0,void 0,function(){var t,r,o,a=this;return s(this,function(u){switch(u.label){case 0:t="#_refreshAccessToken(".concat(e.substring(0,5),"...)"),this._debug(t,"begin"),u.label=1;case 1:return u.trys.push([1,3,4,5]),r=Date.now(),[4,O(function(r){return i(a,void 0,void 0,function(){var i,o,a,u,c,l,h;return s(this,function(s){switch(s.label){case 0:return r>0?[4,L(200*Math.pow(2,r-1))]:[3,2];case 1:s.sent(),s.label=2;case 2:return this._debug(t,"refreshing attempt",r),[4,b("".concat(this.domainUrl,"/oauth/token"),n({client_id:this.clientId,grant_type:"refresh_token",refresh_token:e},this.audience?{audience:this.audience}:{}))];case 3:if((i=s.sent()).error)throw new W("Refresh token request failed: ".concat(i.error),i.error);if(o=U(i),!(null===(l=o.data.session)||void 0===l?void 0:l.access_token))throw new G;return[4,this._getUser(null===(h=o.data.session)||void 0===h?void 0:h.access_token)];case 4:if(a=s.sent(),u=a.data,c=a.error)throw new W("Could not fetch user info",c);if(!u)throw new W("Refresh response missing user",null);return[2,{data:{session:n(n({},o.data.session),{user:u}),user:u},error:null}]}})})},function(e,t){var n=200*Math.pow(2,e);return t&&J(t)&&Date.now()+n-r<de})];case 2:return[2,u.sent()];case 3:if(o=u.sent(),this._debug(t,"error",o),K(o))return[2,{data:{session:null,user:null},error:o}];throw o;case 4:return this._debug(t,"end"),[7];case 5:return[2]}})})},t.prototype._notifyAllSubscribers=function(e,t){return i(this,arguments,void 0,function(e,t,r){var n;return void 0===r&&(r=!0),s(this,function(i){switch(i.label){case 0:n="#_notifyAllSubscribers(".concat(e,")"),this._debug(n,"begin",t,"broadcast = ".concat(r)),i.label=1;case 1:return i.trys.push([1,,3,4]),[4,this.broadcastSync.notify(e,t,r)];case 2:return i.sent(),[3,4];case 3:return this._debug(n,"end"),[7];case 4:return[2]}})})},t.prototype.signOut=function(){return i(this,arguments,void 0,function(e){var t=this;return void 0===e&&(e={scope:"global"}),s(this,function(r){switch(r.label){case 0:return[4,this.initializePromise];case 1:return r.sent(),[4,this.lock._acquireLock(-1,function(){return i(t,void 0,void 0,function(){return s(this,function(t){switch(t.label){case 0:return[4,this._signOut(e)];case 1:return[2,t.sent()]}})})})];case 2:return[2,r.sent()]}})})},t.prototype._signOut=function(){return i(this,arguments,void 0,function(e){var t=this,r=void 0===e?{scope:"global"}:e,n=r.scope,o=void 0===n?"global":n,a=r.redirect,u=r.returnTo;return s(this,function(e){switch(e.label){case 0:return[4,this._useSession(function(e){return i(t,void 0,void 0,function(){var t,r,n,i;return s(this,function(s){switch(s.label){case 0:return t=e.data,(r=e.error)?[2,{error:r}]:"global"===o&&!1!==a&&R()?[4,this._removeSession()]:[3,5];case 1:return s.sent(),[4,this.storage.removeItem("".concat(this.storageKey,"-code-verifier"))];case 2:return s.sent(),[4,this._notifyAllSubscribers("SIGNED_OUT",null)];case 3:return s.sent(),$.redirect(this.getLogoutUrl({returnTo:u})),[4,new Promise(function(){})];case 4:s.sent(),s.label=5;case 5:return(null===(i=t.session)||void 0===i?void 0:i.access_token)?[4,this.api.signOut({client_id:this.clientId,credentials:"include"})]:[3,7];case 6:if((n=s.sent().error)&&(!function(e){return K(e)&&"AuthApiError"===e.name}(n)||404!==n.status&&401!==n.status))return[2,{error:n}];s.label=7;case 7:return"others"===o?[3,11]:[4,this._removeSession()];case 8:return s.sent(),[4,this.storage.removeItem("".concat(this.storageKey,"-code-verifier"))];case 9:return s.sent(),[4,this._notifyAllSubscribers("SIGNED_OUT",null)];case 10:s.sent(),s.label=11;case 11:return[2,{error:null}]}})})})];case 1:return[2,e.sent()]}})})},t.prototype.onAuthStateChange=function(e){var t=this,r=this.broadcastSync.subscribe(e).subscription;return this._debug("#onAuthStateChange()","registered callback with id",r.id),i(t,void 0,void 0,function(){var e=this;return s(this,function(t){switch(t.label){case 0:return[4,this.initializePromise];case 1:return t.sent(),[4,this.lock._acquireLock(-1,function(){return i(e,void 0,void 0,function(){return s(this,function(e){return this._emitInitialSession(r),[2]})})})];case 2:return t.sent(),[2]}})}),{data:{subscription:r}}},t.prototype._emitInitialSession=function(e){return i(this,void 0,void 0,function(){var t=this;return s(this,function(r){switch(r.label){case 0:return[4,this._useSession(function(r){return i(t,void 0,void 0,function(){var t,n,i;return s(this,function(s){switch(s.label){case 0:if(s.trys.push([0,2,,4]),t=r.data.session,n=r.error)throw n;return[4,e.callback("INITIAL_SESSION",t)];case 1:return s.sent(),this._debug("INITIAL_SESSION","callback id",e.id,"session",t),[3,4];case 2:return i=s.sent(),[4,e.callback("INITIAL_SESSION",null)];case 3:return s.sent(),this._debug("INITIAL_SESSION","callback id",e.id,"error",i),console.error(i),[3,4];case 4:return[2]}})})})];case 1:return[2,r.sent()]}})})},t.prototype.refreshSession=function(e){return i(this,void 0,void 0,function(){var t=this;return s(this,function(r){switch(r.label){case 0:return[4,this.initializePromise];case 1:return r.sent(),[4,this.lock._acquireLock(-1,function(){return i(t,void 0,void 0,function(){return s(this,function(t){switch(t.label){case 0:return[4,this._refreshSession(e)];case 1:return[2,t.sent()]}})})})];case 2:return[2,r.sent()]}})})},t.prototype._refreshSession=function(e){return i(this,void 0,void 0,function(){var t,r=this;return s(this,function(n){switch(n.label){case 0:return n.trys.push([0,2,,3]),[4,this._useSession(function(t){return i(r,void 0,void 0,function(){var r,n,i,o,a,u;return s(this,function(s){switch(s.label){case 0:if(!e){if(r=t.data,n=t.error)throw n;e=null!==(u=r.session)&&void 0!==u?u:void 0}if(!(null==e?void 0:e.refresh_token))throw new j;return[4,this._callRefreshToken(e.refresh_token)];case 1:return i=s.sent(),o=i.session,(a=i.error)?[2,{data:{user:null,session:null},error:a}]:o?[2,{data:{user:o.user,session:o},error:null}]:[2,{data:{user:null,session:null},error:null}]}})})})];case 1:return[2,n.sent()];case 2:if(K(t=n.sent()))return[2,{data:{user:null,session:null},error:t}];throw t;case 3:return[2]}})})},t}(c),ve=function(){};e.AuthError=z,e.FaableAuthClient=fe,e.User=ve,e.cookieStorageAdapter=se,e.createClient=function(e){return new fe(e)},e.getSessionFromCookies=function(e,t){var r,n="".concat(null!==(r=t.storageKey)&&void 0!==r?r:N,"-").concat(t.clientId),i=Y(e,n);if(!i)return null;try{return JSON.parse(decodeURIComponent(i))}catch(e){return console.error("Failed to parse session from cookie",e),null}},e.unwrap=function(e){if(e.error)throw e.error;return e.data}}({});
7
7
  //# sourceMappingURL=faableauth.js.map