{"version":3,"file":"AuthProvider-eEzQfWaI.mjs","sources":["../../../libs/frontend-modules/state/src/auth/actions/addError.ts","../../../libs/frontend-modules/state/src/auth/actions/clearErrors.ts","../../../libs/frontend-modules/state/src/auth/actions/notifyAuthenticated.ts","../../../libs/frontend-modules/state/src/auth/actions/notifyUnauthenticated.ts","../../../libs/frontend-modules/state/src/auth/refreshSchedule.ts","../../../libs/frontend-modules/state/src/auth/actions/setAccessToken.ts","../../../libs/frontend-modules/state/src/auth/actions/setIgnoreRefreshToken.ts","../../../libs/frontend-modules/state/src/auth/actions/setUserContext.ts","../../../libs/frontend-modules/state/src/auth/actions/unsetRefreshToken.ts","../../../libs/frontend-modules/state/src/auth/actions/unsetUserContext.ts","../../../libs/frontend-modules/state/src/auth/types.ts","../../../libs/frontend-modules/state/src/auth/transport.ts","../../../libs/frontend-modules/state/src/auth/actors/authenticate.ts","../../../libs/frontend-modules/state/src/auth/actors/refreshAccessToken.ts","../../../libs/frontend-modules/state/src/auth/actors/unauthenticate.ts","../../../libs/frontend-modules/state/src/auth/actors/watchTokenFreshness.ts","../../../libs/frontend-modules/state/src/auth/auth.ts","../../../libs/frontend-modules/state/src/auth/authRefresher.ts","../../../libs/frontend-modules/state/src/auth/AuthProvider.tsx"],"sourcesContent":["import { ErrorActorEvent } from 'xstate';\nimport { AuthMachineContext, AuthMachineEvents } from '../types';\n\nexport function addError({\n  context,\n  event,\n}: {\n  context: AuthMachineContext;\n  event: AuthMachineEvents;\n}) {\n  if (!event.type.includes('xstate.error.actor')) return context;\n\n  const e = event as unknown as ErrorActorEvent;\n  return {\n    errors: [...context.errors, String(e.error).replace('Error: ', '')],\n  };\n}\n\nexport default addError;\n","/** @todo should we assertEvent here? */\nexport function clearErrors() {\n  return {\n    errors: [],\n  };\n}\n\nexport default clearErrors;\n","import { DoneActorEvent } from 'xstate';\nimport {\n  AuthenticatedEmittedEvent,\n  AuthMachineContext,\n  AuthMachineEvents,\n  AuthenticateSuccessEvent,\n  RefreshTokenSuccessEvent,\n} from '../types';\n\nexport function notifyAuthenticated({\n  event,\n}: {\n  context: AuthMachineContext;\n  event: AuthMachineEvents;\n}): AuthenticatedEmittedEvent {\n  if (!event.type.includes('xstate.done.actor'))\n    return { type: 'EMIT_AUTHENTICATED', accessToken: '' };\n\n  const e = event as DoneActorEvent<\n    AuthenticateSuccessEvent | RefreshTokenSuccessEvent\n  >;\n  if (\n    e.output.type !== 'AUTHENTICATE_SUCCESS' &&\n    e.output.type !== 'REFRESH_TOKEN_SUCCESS'\n  )\n    return { type: 'EMIT_AUTHENTICATED', accessToken: '' };\n\n  // A token refresh establishes no new identity, so only a login success\n  // carries the email — see AuthenticatedEmittedEvent.\n  if (e.output.type === 'REFRESH_TOKEN_SUCCESS') {\n    return {\n      type: 'EMIT_AUTHENTICATED',\n      accessToken: e.output.accessToken,\n    };\n  }\n\n  return {\n    type: 'EMIT_AUTHENTICATED',\n    accessToken: e.output.accessToken,\n    email: e.output.user?.email as string | undefined,\n  };\n}\n\nexport default notifyAuthenticated;\n","import { AuthMachineContext, UnauthenticatedEmittedEvent } from '../types';\n\n/**\n * Announces the sign-out, with what a deliberate LOGOUT asked for (CTAP-2615): `keepCart` and\n * `returnTo` ride along so the host's sign-out handling can keep the handed-off cart and land on\n * `returnTo` instead of home. An expired session carries neither.\n */\nexport function notifyUnauthenticated({\n  context,\n}: {\n  context: AuthMachineContext;\n}): UnauthenticatedEmittedEvent {\n  const options = context.logoutOptions;\n  return {\n    type: 'EMIT_UNAUTHENTICATED',\n    ...(options?.keepCart ? { keepCart: true } : {}),\n    ...(options?.returnTo ? { returnTo: options.returnTo } : {}),\n  };\n}\n\nexport default notifyUnauthenticated;\n","/**\n * When to refresh an access token, from the token itself (CTAP-2772).\n *\n * The refresh used to run on a flat 14-minute timer from whenever the tab entered `loggedIn`. A tab that slept or\n * froze overshot it, and a document seeded with a token minutes from expiry (the SSR refresh memo serves one until\n * shortly before it expires) started a fresh 14 minutes on a token with one left: its next request 401'd. The\n * schedule now follows the token's `exp`.\n *\n * `exp` is the server's clock. A client clock that is off would make every token look expired (a refresh storm) or\n * fresh for too long, so the skew is measured from `iat` at the moment a token is received, when `iat` is \"now\" on\n * the server, and applied to every later reading.\n */\n\n/** Used when a token has no readable `exp`: the old fixed schedule, for a 15-minute token. */\nexport const FALLBACK_REFRESH_DELAY_MS = 840_000;\n\n/** Refresh this long before `exp`, capped at a quarter of the token's lifetime for a short-lived one. */\nexport const REFRESH_MARGIN_MS = 60_000;\n\n/** A measured skew smaller than this is the request's own latency, not a wrong clock. */\nconst NEGLIGIBLE_SKEW_MS = 5_000;\n\ninterface TokenTimes {\n  exp?: number;\n  iat?: number;\n}\n\n/** The `exp` and `iat` claims of a JWT, or nothing when it is not one. Never throws. */\nexport function tokenTimes(token: string): TokenTimes {\n  const payload = token.split('.')[1];\n  if (!payload) return {};\n  try {\n    const base64 = payload.replace(/-/g, '+').replace(/_/g, '/');\n    const padded = base64 + '='.repeat((4 - (base64.length % 4)) % 4);\n    const json =\n      typeof atob === 'function'\n        ? atob(padded)\n        : Buffer.from(padded, 'base64').toString('binary');\n    const claims = JSON.parse(json) as Record<string, unknown>;\n    return {\n      exp: typeof claims['exp'] === 'number' ? claims['exp'] : undefined,\n      iat: typeof claims['iat'] === 'number' ? claims['iat'] : undefined,\n    };\n  } catch {\n    return {};\n  }\n}\n\n/**\n * The client clock minus the server clock, read from a token received just now (its `iat` is the server's now).\n * 0 when the token has no `iat` or the difference is only latency.\n */\nexport function clockSkewFromFreshToken(token: string, now: number): number {\n  const { iat } = tokenTimes(token);\n  if (iat === undefined) return 0;\n  const skew = now - iat * 1000;\n  return Math.abs(skew) < NEGLIGIBLE_SKEW_MS ? 0 : skew;\n}\n\n/** How long to wait before refreshing `token`: 0 when it is already due. */\nexport function refreshDelayMs(\n  token: string,\n  clockSkewMs: number,\n  now: number,\n): number {\n  const { exp, iat } = tokenTimes(token);\n  if (exp === undefined) return FALLBACK_REFRESH_DELAY_MS;\n\n  const lifetime = iat === undefined ? undefined : (exp - iat) * 1000;\n  const margin =\n    lifetime === undefined || lifetime <= 0\n      ? REFRESH_MARGIN_MS\n      : Math.min(REFRESH_MARGIN_MS, lifetime / 4);\n  const serverNow = now - clockSkewMs;\n\n  return Math.max(0, exp * 1000 - margin - serverNow);\n}\n\n/** Whether `token` is within its refresh margin, or past it. */\nexport function isRefreshDue(\n  token: string,\n  clockSkewMs: number,\n  now: number,\n): boolean {\n  return refreshDelayMs(token, clockSkewMs, now) === 0;\n}\n","import { DoneActorEvent } from 'xstate';\nimport { clockSkewFromFreshToken } from '../refreshSchedule';\nimport {\n  RefreshTokenSuccessEvent,\n  AuthMachineContext,\n  AuthMachineEvents,\n} from '../types';\n\nexport function setAccessToken({\n  context,\n  event,\n}: {\n  context: AuthMachineContext;\n  event: AuthMachineEvents;\n}) {\n  if (!event.type.includes('xstate.done.actor')) return context;\n\n  const e = event as DoneActorEvent<RefreshTokenSuccessEvent>;\n  if (e.output.type !== 'REFRESH_TOKEN_SUCCESS') return context;\n\n  return {\n    accessToken: e.output.accessToken,\n    clockSkewMs: clockSkewFromFreshToken(e.output.accessToken, Date.now()),\n    ignoreRefreshToken: false,\n  };\n}\n\nexport default setAccessToken;\n","// there shouldn't be a problem with not checking event here\n// since we can only hit this action from the refresh actor\n// onDone or onError\nexport function setIgnoreRefreshToken() {\n  return {\n    ignoreRefreshToken: true,\n  };\n}\n\nexport default setIgnoreRefreshToken;\n","import { DoneActorEvent } from 'xstate';\nimport { clockSkewFromFreshToken } from '../refreshSchedule';\nimport {\n  AuthenticateSuccessEvent,\n  AuthMachineContext,\n  AuthMachineEvents,\n} from '../types';\n\nexport function setUserContext({\n  context,\n  event,\n}: {\n  context: AuthMachineContext;\n  event: AuthMachineEvents;\n}) {\n  if (!event.type.includes('xstate.done.actor')) return context;\n\n  const e = event as DoneActorEvent<AuthenticateSuccessEvent>;\n  if (e.output.type !== 'AUTHENTICATE_SUCCESS') return context;\n\n  return {\n    accessToken: e.output.accessToken,\n    clockSkewMs: clockSkewFromFreshToken(e.output.accessToken, Date.now()),\n    ignoreRefreshToken: false,\n    user: e.output.user ?? null,\n  };\n}\n\nexport default setUserContext;\n","// there shouldn't be a problem with not checking event here\n// since we can only hit this action from the refresh actor\n// onDone or onError\nexport function unsetRefreshToken() {\n  return {\n    refreshToken: '',\n  };\n}\n\nexport default unsetRefreshToken;\n","/** @todo should we assertEvent here? */\nexport function unsetUserContext() {\n  return {\n    user: null,\n    accessToken: '',\n    refreshToken: '',\n    ignoreRefreshToken: false,\n  };\n}\n\nexport default unsetUserContext;\n","import { DoneActorEvent } from 'xstate';\nimport { AuthTransport } from './transport';\n\nexport interface AuthMachineContext {\n  /**\n   * Header injection for the auth HTTP calls, supplied by the host when the\n   * actor is created. Injected rather than imported — see `./transport`.\n   * Absent → the hardcoded pre-CTAP-1159 defaults apply.\n   */\n  transport?: AuthTransport;\n  // user: {\n  //   email: string;\n  //   username: string;\n  //   firstName: string;\n  //   lastName: string;\n  //   birthdate?: Date;\n  //   gender?: string /** @todo use enum? */;\n  //   createdAt: Date;\n  //   updatedAt: Date;\n  //   role?: string /** @todo use enum? */;\n  //   locked: boolean;\n  //   affiliateId: string;\n  //   stripeId: string;\n  // } | null;\n  // eslint-disable-next-line @typescript-eslint/no-explicit-any\n  user: Record<string, any> | null;\n  accessToken: string;\n  /**\n   * This client's clock minus the server's, measured from `iat` when a token arrives from login or a refresh, so\n   * the refresh schedule reads `exp` on the server's clock (CTAP-2772). 0 until measured.\n   */\n  clockSkewMs?: number;\n  refreshToken: string;\n  ignoreRefreshToken: boolean;\n  /**\n   * Why the session ended: `deliberate` (a LOGOUT, through `unauthenticating` and the logout endpoint →\n   * `loggedOut.afterLogout`, home) or `expired` (a refresh failure or SESSION_EXPIRED → straight to\n   * `loggedOut.afterRefreshFailure`, return-path redirect, with no logout call). See CTAP-1129, CTAP-2772.\n   */\n  logoutReason: 'deliberate' | 'expired' | null;\n  /**\n   * What a deliberate LOGOUT asked for (CTAP-2615), carried to EMIT_UNAUTHENTICATED: keep the cart\n   * (the host handed it off to a guest cart before signing out) and where to land instead of home.\n   * Null for an expired session.\n   */\n  logoutOptions: { keepCart: boolean; returnTo: string | null } | null;\n  endpoints: {\n    login: string;\n    logout: string;\n    refresh: string;\n    ssrRefresh: string;\n  };\n  errors: Array<string>;\n}\n\nexport interface RefreshTokenEvent {\n  type: 'REFRESH_TOKEN';\n  accessToken: AuthMachineContext['accessToken'];\n}\n\nexport interface LoginEvent {\n  type: 'LOGIN';\n  username: string;\n  password: string;\n}\n\nexport interface LogoutEvent {\n  type: 'LOGOUT';\n  /**\n   * The cart stays (CTAP-2615): the host has already moved it into a guest cart with\n   * `quoteHandOffToGuest`, which must happen BEFORE this event, while the session can still prove it\n   * owns the cart. Carried to EMIT_UNAUTHENTICATED for the host's sign-out handling.\n   */\n  keepCart?: boolean;\n  /** Where to land after signing out instead of the home page, e.g. `/checkout` (CTAP-2615). */\n  returnTo?: string;\n}\n\n/**\n * The SERVER rejected our access token (a 401 from any authenticated request).\n * Distinct from LOGOUT: an expired session is not a chosen sign-out, so it must\n * route to `afterRefreshFailure` — which keeps the return path to wherever the\n * visitor was — rather than `afterLogout`, which deliberately goes home with no\n * return path (CTAP-1120/1129/1425).\n */\nexport interface SessionExpiredEvent {\n  type: 'SESSION_EXPIRED';\n}\n\n/**\n * A credential-change mutation (email/password) minted a fresh session server-side and returned a\n * new access token; the rotated refresh cookie is already set on the response. Swap the in-memory\n * access token in place so the user stays signed in — no login round-trip.\n */\nexport interface SessionReissuedEvent {\n  type: 'SESSION_REISSUED';\n  accessToken: AuthMachineContext['accessToken'];\n}\n\nexport interface ClearErrorsEvent {\n  type: 'CLEAR_ERRORS';\n}\n\nexport interface RestoreEvent {\n  type: 'RESTORE';\n}\n\n// export interface AfterLoggedInEvent {\n//   type: 'AFTER_LOGGED_IN';\n// }\n\n// export interface AfterLoggedOutEvent {\n//   type: 'AFTER_LOGGED_OUT';\n// }\n\nexport interface AuthenticateSuccessEvent {\n  type: 'AUTHENTICATE_SUCCESS';\n  user: Partial<AuthMachineContext['user']>;\n  accessToken: AuthMachineContext['accessToken'];\n}\n\nexport interface RefreshTokenSuccessEvent {\n  type: 'REFRESH_TOKEN_SUCCESS';\n  accessToken: AuthMachineContext['accessToken'];\n}\n\nexport interface UnauthenticateSuccessEvent {\n  type: 'UNAUTHENTICATE_SUCCESS';\n}\n\nexport interface AuthenticatedEmittedEvent {\n  type: 'EMIT_AUTHENTICATED';\n  accessToken: AuthMachineContext['accessToken'];\n  /**\n   * The signed-in identity, present when the emit follows an AUTHENTICATE\n   * (login) success — identity consumers (GA4 signed_in, Klaviyo identify)\n   * need it at exactly this moment. Absent on token refreshes: a refresh\n   * establishes no new identity.\n   */\n  email?: string;\n}\n\nexport interface UnauthenticatedEmittedEvent {\n  type: 'EMIT_UNAUTHENTICATED';\n  /** The LOGOUT kept the cart (CTAP-2615): the next anonymous refresh loads the handed-off guest cart. */\n  keepCart?: boolean;\n  /** The LOGOUT's landing page instead of home (CTAP-2615). */\n  returnTo?: string;\n}\n\n// type AuthEvents = RefreshTokenEvent | AnotherEvent;\nexport type AuthMachineEvents =\n  | RefreshTokenEvent\n  | RestoreEvent\n  | LoginEvent\n  | LogoutEvent\n  | SessionExpiredEvent\n  | SessionReissuedEvent\n  | ClearErrorsEvent\n  // | AfterLoggedInEvent\n  // | AfterLoggedOutEvent\n  | DoneActorEvent<AuthenticateSuccessEvent>\n  | DoneActorEvent<RefreshTokenSuccessEvent>;\n\nexport type AuthMachineEmittedEvents =\n  AuthenticatedEmittedEvent | UnauthenticatedEmittedEvent;\n\nexport enum AuthMachineStatusCode {\n  INCORRECT_LOGIN_CREDENTIALS = 'INCORRECT_LOGIN_CREDENTIALS',\n  /**\n   * The account is TEMPORARILY locked from signing in after repeated failed\n   * password attempts (e.g. Magento's lockout window, surfaced to the user\n   * as \"Sign-in with this account is unavailable\"). It clears on its own —\n   * hosts branch on this to run a recovery flow (an OTP re-verify step, a\n   * \"try again later\" notice) instead of the incorrect-credentials copy.\n   *\n   * Mapped from the login response's structured `code` field\n   * ({@link AuthenticateResponse.code}) — never from the display message,\n   * which belongs to the backend (Magento's copy can change). A backend that\n   * doesn't emit the code keeps collapsing to INCORRECT_LOGIN_CREDENTIALS.\n   */\n  ACCOUNT_LOCKED = 'ACCOUNT_LOCKED',\n  /**\n   * Sign-in could not be attempted: the server failed (5xx) or could not be reached at all\n   * (offline, DNS, CORS, an aborted request). **No credential decision was made** — the password\n   * may well be correct.\n   *\n   * Separate from INCORRECT_LOGIN_CREDENTIALS because collapsing the two told users their password\n   * was wrong during a server outage. A consumer's 500 was triaged as a credentials problem for most of a\n   * day on the strength of that copy, and the account holder was asked to reset a working password\n   * (CTAP-1817).\n   *\n   * A host that does not know this code falls through to its own default branch, which is the right\n   * outcome and needs no coordinated release.\n   */\n  AUTHENTICATION_UNAVAILABLE = 'AUTHENTICATION_UNAVAILABLE',\n}\n","/**\n * Header injection for the auth machine's HTTP calls.\n *\n * The auth actors used to hardcode `clicktap-scope: view` /\n * `clicktap-scope-id: default` — fine for a single-storefront app, fatal for\n * anything else: a wholesale/B2B storefront needs the ACTUAL view id, an\n * `Authorization` header, and a `clicktap-company` header on `/auth/login`,\n * `/auth/refresh` and `/auth/logout`, and those values are only known to the\n * host app (and change over the life of the actor). The quote machines got a\n * `QuoteTransport` input precisely to end this kind of hardcoded coupling —\n * this is the same pattern for auth (CTAP-1159).\n *\n * The provider is a FUNCTION, called immediately before each request, so the\n * headers it returns are current at call time — an `Authorization` built from\n * the token at actor creation would go stale after the first refresh, and\n * `clicktap-company` changes when the visitor picks a company. Its return\n * value is merged OVER the defaults, so a host only overrides what it needs:\n *\n *   createActor(authMachine, {\n *     input: {\n *       transport: {\n *         headers: () => ({\n *           'clicktap-scope-id': viewId,\n *           ...(token ? { Authorization: `Bearer ${token}` } : {}),\n *           ...(company ? { 'clicktap-company': company } : {}),\n *         }),\n *       },\n *       initialContext: { … },\n *     },\n *   });\n *\n * Like `QuoteTransport`, the transport lives in machine context and therefore\n * does not survive snapshot serialization — a consumer restoring a persisted\n * snapshot must recreate the actor with the transport supplied again.\n */\n\n/** Which auth request the headers are being resolved for. */\nexport type AuthCall = 'login' | 'refresh' | 'ssrRefresh' | 'logout';\n\n/**\n * Returns the headers to merge over {@link DEFAULT_AUTH_HEADERS} for one call.\n * Invoked per request — return fresh values, don't capture stale ones.\n */\nexport type AuthHeadersProvider = (call: AuthCall) => Record<string, string>;\n\nexport type AuthTransport = {\n  headers?: AuthHeadersProvider;\n};\n\n/**\n * The pre-CTAP-1159 hardcoded values, kept as the default so hosts that never\n * pass a transport behave exactly as before.\n */\nexport const DEFAULT_AUTH_HEADERS: Record<string, string> = {\n  'clicktap-scope': 'view',\n  'clicktap-scope-id': 'default',\n};\n\nexport function resolveAuthHeaders(\n  transport: AuthTransport | undefined,\n  call: AuthCall,\n): Record<string, string> {\n  return {\n    ...DEFAULT_AUTH_HEADERS,\n    ...(transport?.headers?.(call) ?? {}),\n  };\n}\n","import { fromPromise } from 'xstate';\nimport {\n  AuthenticateSuccessEvent,\n  AuthMachineContext,\n  AuthMachineStatusCode,\n} from '../types';\nimport { AuthTransport, resolveAuthHeaders } from '../transport';\nimport { request } from '../../helpers/request';\nimport { isDevelopment } from '../../helpers/env';\n\nexport type AuthenticateInput = {\n  endpoint: {\n    client: AuthMachineContext['endpoints']['login'];\n  };\n  password: string;\n  /** Host-supplied header injection — see `../transport`. */\n  transport?: AuthTransport;\n  username: string;\n};\n\nexport type AuthenticateResponse = {\n  success: boolean;\n  message?: string;\n  /**\n   * Structured failure code (an {@link AuthMachineStatusCode} value, e.g.\n   * `ACCOUNT_LOCKED` for a temporary bad-password lockout). This — never the\n   * display `message` — is what the actor maps to a status code: messages are\n   * backend/Magento display copy and not a contract (CTAP-1197).\n   */\n  code?: string;\n  access_token?: string;\n  /**\n   * HTTP status, present only on a failed response (see `helpers/request`). This — never the\n   * message — is how the actor tells a server failure from a rejected password (CTAP-1817).\n   */\n  status?: number;\n};\n\n// export type AuthenticateTokenOutput = {\n//   type: string;\n//   accessToken: string;\n// };\n\n/** @todo pass locale for auth server? */\nexport const authenticate = fromPromise<\n  AuthenticateSuccessEvent,\n  AuthenticateInput\n>(async ({ input }) => {\n  if (!input.endpoint.client || input.endpoint.client === '') {\n    throw new Error('No client endpoint provided.');\n  }\n\n  // A known AuthMachineStatusCode, or null. The structured `code` is the contract; the display\n  // message is backend copy and never dispatched on (CTAP-1197).\n  const knownCode = (code?: string): AuthMachineStatusCode | null =>\n    code && (Object.values(AuthMachineStatusCode) as string[]).includes(code)\n      ? (code as AuthMachineStatusCode)\n      : null;\n\n  // The original is CHAINED, never discarded: a host that logs the failure needs the real error,\n  // and before CTAP-1817 it was replaced outright.\n  const fail = (code: AuthMachineStatusCode, cause?: unknown): Error => {\n    const error = new Error(code);\n    if (cause !== undefined) {\n      // Assigned rather than passed to the constructor: the `options` argument needs an ES2022\n      // lib, and this package typechecks below that.\n      (error as Error & { cause?: unknown }).cause = cause;\n    }\n\n    return error;\n  };\n\n  let data: AuthenticateResponse;\n  try {\n    data = await request<AuthenticateResponse>(input.endpoint.client, {\n      method: 'POST',\n      mode: 'cors',\n      credentials: 'include',\n      headers: {\n        'Content-Type': 'application/json',\n        ...resolveAuthHeaders(input.transport, 'login'),\n      },\n      body: JSON.stringify({\n        username: input.username,\n        password: input.password,\n      }).toString(),\n    });\n  } catch (err) {\n    // `fetch` itself rejected — offline, DNS, CORS, abort. There is no response, so the server\n    // never saw the credentials and cannot have rejected them.\n    if (isDevelopment) {\n      console.error('[authenticate] transport failure', err);\n    }\n\n    throw fail(AuthMachineStatusCode.AUTHENTICATION_UNAVAILABLE, err);\n  }\n\n  if (!data.success) {\n    if (isDevelopment) {\n      console.error('[authenticate] sign-in failed', data);\n    }\n\n    // A code the backend emitted deliberately wins, whatever the status.\n    const code = knownCode(data.code);\n    if (code) {\n      throw fail(code);\n    }\n\n    // 5xx: the server broke. It made no credential decision, so saying the password is wrong is\n    // not a hedge, it is a false statement — and it is what sent a consumer's triage down the wrong path.\n    if (typeof data.status === 'number' && data.status >= 500) {\n      throw fail(\n        AuthMachineStatusCode.AUTHENTICATION_UNAVAILABLE,\n        new Error(data.message ?? `Login endpoint returned ${data.status}`),\n      );\n    }\n\n    // Everything else is the server rejecting the credentials: a 401, or a 200 whose body says\n    // `success: false` without a code. This is the collapse ACCOUNT_LOCKED's docblock describes,\n    // and it is correct HERE — a credential decision was genuinely made.\n    throw fail(\n      AuthMachineStatusCode.INCORRECT_LOGIN_CREDENTIALS,\n      new Error(data.message ?? 'Sign in failed.'),\n    );\n  }\n\n  return {\n    type: 'AUTHENTICATE_SUCCESS',\n    // The signed-in identity — the auth endpoint returns no profile, so the\n    // submitted username (an email) is what identity consumers get.\n    user: { email: input.username },\n    accessToken: data.access_token ?? '',\n  };\n});\n\nexport default authenticate;\n","import { fromPromise } from 'xstate';\nimport { isDevelopment } from '../../helpers/env';\nimport { RefreshTokenSuccessEvent, AuthMachineContext } from '../types';\nimport { AuthTransport, resolveAuthHeaders } from '../transport';\nimport { request } from '../../helpers/request';\n\nexport type RefreshTokenInput = {\n  // accessToken: AuthMachineContext['accessToken'];\n  refreshToken: AuthMachineContext['refreshToken'];\n  endpoint: {\n    client: AuthMachineContext['endpoints']['refresh'];\n    server: AuthMachineContext['endpoints']['ssrRefresh'];\n  };\n  /** Host-supplied header injection — see `../transport`. */\n  transport?: AuthTransport;\n};\n\nexport type RefreshTokenResponse = {\n  access_token?: string;\n};\n\nexport type RefreshTokenOutput = {\n  type: string;\n  accessToken: string;\n};\n\nconst IS_SERVER = typeof window === 'undefined';\n\n/** @todo pass locale for auth server? */\nexport const refreshAccessToken = fromPromise<\n  RefreshTokenSuccessEvent,\n  RefreshTokenInput\n>(async ({ input }) => {\n  if (!input.endpoint.client || input.endpoint.client === '') {\n    if (isDevelopment) {\n      console.log('refreshAccessToken: No client endpoint provided.');\n    }\n    throw new Error('No client endpoint provided.');\n  }\n  // The server endpoint is only called on the server; the browser has none to give (CTAP-2026).\n  if (IS_SERVER && !input.endpoint.server) {\n    if (isDevelopment) {\n      console.log('refreshAccessToken: No server endpoint provided.');\n    }\n    throw new Error('No server endpoint provided.');\n  }\n  // if (!input.accessToken) throw new Error('No access token provided.');\n\n  let data: RefreshTokenResponse;\n\n  if (IS_SERVER) {\n    if (input.refreshToken === '') throw new Error('Unauthorized.');\n\n    try {\n      data = await request<RefreshTokenResponse>(input.endpoint.server, {\n        method: 'POST',\n        mode: 'cors',\n        credentials: 'include',\n        headers: {\n          Cookie: `refresh_token=${input.refreshToken}`,\n          'Content-Type': 'application/json',\n          ...resolveAuthHeaders(input.transport, 'ssrRefresh'),\n        },\n      });\n\n      if (typeof data.access_token === 'undefined') {\n        throw new Error('Unauthorized.');\n      }\n\n      return {\n        type: 'REFRESH_TOKEN_SUCCESS',\n        accessToken: data.access_token,\n      } as RefreshTokenSuccessEvent;\n    } catch (err) {\n      if (isDevelopment) {\n        console.log(err);\n      }\n      throw new Error('Could not complete refresh request (server)');\n    }\n  } else {\n    // client\n    data = await request<RefreshTokenResponse>(input.endpoint.client, {\n      method: 'POST',\n      mode: 'cors',\n      credentials: 'include',\n      headers: {\n        'Content-Type': 'application/json',\n        ...resolveAuthHeaders(input.transport, 'refresh'),\n      },\n      /** @todo is this necessary anymore? */\n      body: JSON.stringify({\n        grant_type: 'refresh_token',\n        // client_id: 'default',\n        // client_secret: 'Password123!',\n        // scope: 'default',\n      }).toString(),\n    });\n\n    if (typeof data.access_token === 'undefined') {\n      throw new Error('Unauthorized.');\n    }\n\n    return {\n      type: 'REFRESH_TOKEN_SUCCESS',\n      accessToken: data.access_token,\n    };\n  }\n});\n\nexport default refreshAccessToken;\n","import { fromPromise } from 'xstate';\nimport { UnauthenticateSuccessEvent, AuthMachineContext } from '../types';\nimport { AuthTransport, resolveAuthHeaders } from '../transport';\n\nexport type UnauthenticateInput = {\n  endpoint: {\n    client: AuthMachineContext['endpoints']['logout'];\n  };\n  /** Host-supplied header injection — see `../transport`. */\n  transport?: AuthTransport;\n};\n\nexport type UnauthenticateResponse = {\n  success: boolean;\n  message?: string;\n  accessToken?: string;\n};\n\n// export type UnauthenticateOutput = {\n//   type: string;\n//   accessToken: string;\n// };\n\n/** @todo pass locale for auth server? */\nexport const unauthenticate = fromPromise<\n  UnauthenticateSuccessEvent,\n  UnauthenticateInput\n>(async ({ input }) => {\n  if (!input.endpoint.client || input.endpoint.client === '') {\n    console.log('unauthenticate: No client endpoint provided.');\n    throw new Error('No client endpoint provided.');\n  }\n\n  try {\n    await fetch(input.endpoint.client, {\n      method: 'POST',\n      mode: 'cors',\n      credentials: 'include',\n      headers: resolveAuthHeaders(input.transport, 'logout'),\n      // headers: {\n      //   'Access-Control-Allow-Origin': 'https://pwa-demo.rmgmedia.com',\n      //   'Access-Control-Allow-Credentials': 'true',\n      // },\n    });\n\n    return { type: 'UNAUTHENTICATE_SUCCESS' };\n  } catch (err) {\n    console.log(err);\n    throw new Error('Could not complete unauthenticate request (server)');\n  }\n  /** @todo do we need to handle different status codes here...like what if the service is down? */\n  // const data = await response.json();\n});\n\nexport default unauthenticate;\n","import { fromCallback } from 'xstate';\nimport { isRefreshDue } from '../refreshSchedule';\n\nexport interface WatchTokenFreshnessInput {\n  accessToken: string;\n  clockSkewMs: number;\n}\n\n/**\n * Refreshes as soon as a tab is usable again with a token that is due (CTAP-2772). A hidden or frozen tab's timers\n * are throttled or stopped, so the scheduled refresh can come long after `exp`; the first request after the tab is\n * shown would then 401. Checks on becoming visible and on coming back online, and sends REFRESH_TOKEN when due.\n */\nexport const watchTokenFreshness = fromCallback<\n  { type: 'REFRESH_TOKEN'; accessToken: string },\n  WatchTokenFreshnessInput\n>(({ input, sendBack }) => {\n  if (typeof window === 'undefined' || typeof document === 'undefined') {\n    return undefined;\n  }\n\n  const check = () => {\n    if (document.visibilityState === 'hidden') return;\n    if (isRefreshDue(input.accessToken, input.clockSkewMs, Date.now())) {\n      sendBack({ type: 'REFRESH_TOKEN', accessToken: input.accessToken });\n    }\n  };\n\n  document.addEventListener('visibilitychange', check);\n  window.addEventListener('online', check);\n\n  return () => {\n    document.removeEventListener('visibilitychange', check);\n    window.removeEventListener('online', check);\n  };\n});\n\nexport default watchTokenFreshness;\n","import { assertEvent, assign, emit, setup } from 'xstate';\nimport { AuthTransport } from './transport';\nimport {\n  AuthMachineContext,\n  AuthMachineEmittedEvents,\n  AuthMachineEvents,\n} from './types';\nimport {\n  addError as addErrorAction,\n  clearErrors as clearErrorsAction,\n  notifyAuthenticated as notifyAuthenticatedAction,\n  notifyUnauthenticated as notifyUnauthenticatedAction,\n  setAccessToken as setAccessTokenAction,\n  setIgnoreRefreshToken as setIgnoreRefreshTokenAction,\n  setUserContext as setUserContextAction,\n  unsetRefreshToken as unsetRefreshTokenAction,\n  unsetUserContext as unsetUserContextAction,\n} from './actions';\nimport {\n  authenticate as authenticateActor,\n  refreshAccessToken as refreshAccessTokenActor,\n  unauthenticate as unauthenticateActor,\n  watchTokenFreshness as watchTokenFreshnessActor,\n} from './actors';\nimport { refreshDelayMs } from './refreshSchedule';\n\nexport const authMachine = setup({\n  types: {\n    context: {} as AuthMachineContext,\n    emitted: {} as AuthMachineEmittedEvents,\n    events: {} as AuthMachineEvents,\n    input: {} as {\n      /**\n       * Header injection for the auth HTTP calls — see `./transport`.\n       * Optional: without it the actors send the historical hardcoded\n       * `clicktap-scope: view` / `clicktap-scope-id: default`.\n       */\n      transport?: AuthTransport;\n      initialContext: Partial<AuthMachineContext>;\n      initialState?: string;\n    },\n  },\n  actions: {\n    addError: assign(addErrorAction),\n    clearErrors: assign(clearErrorsAction),\n    notifyAuthenticated: emit(notifyAuthenticatedAction),\n    notifyUnauthenticated: emit(notifyUnauthenticatedAction),\n    setAccessToken: assign(setAccessTokenAction),\n    // A credential-change mutation returned a fresh access token (refresh cookie already rotated\n    // server-side); swap it into context and re-announce authentication with the new token.\n    setReissuedAccessToken: assign(({ event }) => {\n      assertEvent(event, 'SESSION_REISSUED');\n      return { accessToken: event.accessToken, ignoreRefreshToken: false };\n    }),\n    notifyReissued: emit(({ event }) => {\n      assertEvent(event, 'SESSION_REISSUED');\n      return {\n        type: 'EMIT_AUTHENTICATED' as const,\n        accessToken: event.accessToken,\n      };\n    }),\n    setIgnoreRefreshToken: assign(setIgnoreRefreshTokenAction),\n    // Record why the session is ending so `unauthenticating` can route a\n    // deliberate sign-out (→ home) apart from an expired session (→ return-path\n    // redirect), even though both pass through the same state (CTAP-1129).\n    // A deliberate LOGOUT also records what it asked for (CTAP-2615): keep the cart, land elsewhere.\n    markDeliberateLogout: assign(({ event }) => ({\n      logoutReason: 'deliberate' as const,\n      logoutOptions:\n        event.type === 'LOGOUT'\n          ? {\n              keepCart: Boolean(event.keepCart),\n              returnTo: event.returnTo ?? null,\n            }\n          : null,\n    })),\n    markExpiredSession: assign(() => ({\n      logoutReason: 'expired' as const,\n      logoutOptions: null,\n    })),\n    setUserContext: assign(setUserContextAction),\n    unsetRefreshToken: assign(unsetRefreshTokenAction),\n    unsetUserContext: assign(unsetUserContextAction),\n  },\n  actors: {\n    authenticate: authenticateActor,\n    refreshAccessToken: refreshAccessTokenActor,\n    unauthenticate: unauthenticateActor,\n    watchTokenFreshness: watchTokenFreshnessActor,\n  },\n  delays: {\n    // From the token's `exp` on the server's clock, not a flat 14 minutes from entering loggedIn (CTAP-2772): a\n    // seeded token close to expiry refreshes at once, and a token without a readable `exp` keeps the old 840000.\n    refresh: ({ context }) =>\n      refreshDelayMs(context.accessToken, context.clockSkewMs ?? 0, Date.now()),\n  },\n}).createMachine({\n  id: 'auth',\n  context: ({ input }) => ({\n    transport: input?.transport,\n    user: null,\n    accessToken: '',\n    clockSkewMs: 0,\n    refreshToken: '', // will only be on the request from the server side for initial check, does not get passed to the client\n    /**\n     * If unauthenticating fails, we need a way to ignore the refresh token on subsequent access token refresh.\n     * This would be set to true done/error of unauthenticate service, and false on done of authenticate service\n     */\n    ignoreRefreshToken: false,\n    logoutReason: null,\n    logoutOptions: null,\n    endpoints: {\n      login: '',\n      logout: '',\n      refresh: '',\n      ssrRefresh: '',\n    },\n    errors: [],\n    ...input?.initialContext,\n  }),\n  initial: 'initializing',\n  states: {\n    initializing: {\n      always: [\n        {\n          target: 'loggedIn',\n          guard: ({ context }) => !!context.accessToken,\n        },\n        {\n          target: 'loggedOut.initial',\n        },\n      ],\n    },\n    authenticating: {\n      invoke: {\n        src: 'authenticate',\n        input: ({ context, event }) => {\n          assertEvent(event, 'LOGIN');\n\n          return {\n            endpoint: {\n              client: context.endpoints.login,\n            },\n            transport: context.transport,\n            username: event.username,\n            password: event.password,\n          };\n        },\n        onDone: [\n          {\n            actions: ['setUserContext', 'notifyAuthenticated'],\n            target: 'loggedIn',\n          },\n        ],\n        onError: [\n          {\n            actions: 'addError',\n            target: 'loggedOut.afterFailedAuth',\n          },\n        ],\n      },\n    },\n    unauthenticating: {\n      invoke: {\n        src: 'unauthenticate',\n        input: ({ context }) => {\n          return {\n            endpoint: {\n              client: context.endpoints.logout,\n            },\n            transport: context.transport,\n          };\n        },\n        // Since CTAP-2772 only a deliberate LOGOUT reaches `unauthenticating`:\n        // an expired session (a refresh failure, SESSION_EXPIRED) settles in\n        // `afterRefreshFailure` without calling the logout endpoint. The\n        // `expired` routes below stay so an expired reason, however it got\n        // here, still keeps its return path (CTAP-1129).\n        onDone: [\n          {\n            guard: ({ context }) => context.logoutReason === 'expired',\n            actions: ['unsetUserContext', 'notifyUnauthenticated'],\n            target: 'loggedOut.afterRefreshFailure',\n          },\n          {\n            actions: ['unsetUserContext', 'notifyUnauthenticated'],\n            target: 'loggedOut.afterLogout',\n          },\n        ],\n        onError: [\n          {\n            guard: ({ context }) => context.logoutReason === 'expired',\n            actions: [\n              'unsetUserContext',\n              'setIgnoreRefreshToken',\n              'notifyUnauthenticated',\n            ],\n            target: 'loggedOut.afterRefreshFailure',\n          },\n          {\n            actions: [\n              'unsetUserContext',\n              'setIgnoreRefreshToken',\n              'notifyUnauthenticated',\n            ],\n            target: 'loggedOut.afterLogout',\n          },\n        ],\n      },\n    },\n    refreshing: {\n      invoke: {\n        src: 'refreshAccessToken',\n        input: ({ context }) => {\n          return {\n            accessToken: context.accessToken,\n            endpoint: {\n              client: context.endpoints.refresh,\n              server: context.endpoints.ssrRefresh,\n            },\n            refreshToken: context.refreshToken,\n            transport: context.transport,\n          };\n        },\n        onDone: [\n          {\n            actions: [\n              'unsetRefreshToken',\n              'setAccessToken',\n              'notifyAuthenticated',\n            ],\n            guard: () => typeof window !== 'undefined',\n            target: 'loggedIn',\n          },\n          /**\n           * We must transition to transient loggedInReady state from server-side refresh\n           * so the frontend can send RESTORE event. Otherwise actions and timers from\n           * loggedIn state won't fire properly from client (known issue in xstate)\n           */\n          {\n            actions: ['unsetRefreshToken', 'setAccessToken'],\n            target: 'loggedInReady',\n          },\n        ],\n        /**\n         * @todo\n         * confirm this logic, does it make sense to unset refresh token\n         * if the request fails for some reason on server side?\n         */\n        onError: [\n          // logout can only happen on the client side, so we\n          // guard the action to prevent it from happening on the server\n          // and fall back to loggedOut state server-side\n          {\n            // Client-side refresh failure = an EXPIRED session, not a\n            // deliberate sign-out: settle in afterRefreshFailure (return path,\n            // CTAP-1129) WITHOUT calling the logout endpoint. Logout revokes\n            // the shared cookie's whole family, and that cookie may already\n            // belong to a session another tab signed into since: an expiry has\n            // nothing of this tab's left to revoke (CTAP-2772).\n            actions: [\n              'unsetRefreshToken',\n              'markExpiredSession',\n              'unsetUserContext',\n              'notifyUnauthenticated',\n            ],\n            target: 'loggedOut.afterRefreshFailure',\n            guard: () => typeof window !== 'undefined',\n          },\n          {\n            actions: ['unsetRefreshToken', 'notifyUnauthenticated'],\n            target: 'loggedOut.afterRefreshFailure',\n          },\n        ],\n      },\n    },\n    /**\n     * `loggedOut` is a compound state. The substate records *why* we\n     * are logged out so consumers can react appropriately — most\n     * importantly, so a failed login attempt on an inline auth form\n     * (e.g. /checkout step 1) does not trigger the same hard reload\n     * that a real logout does, which would destroy the form's error\n     * state before the user sees it.\n     *\n     * Transition matrix:\n     *   initializing      → loggedOut.initial              (cold load, no token)\n     *   authenticating    → loggedOut.afterFailedAuth      (wrong password)\n     *   unauthenticating  → loggedOut.afterLogout          (DELIBERATE user logout — logoutReason 'deliberate')\n     *   refreshing        → loggedOut.afterRefreshFailure  (refresh failure — logoutReason 'expired', CTAP-1129;\n     *                                                       no logout call, CTAP-2772)\n     *   loggedIn          → loggedOut.afterRefreshFailure  (SESSION_EXPIRED, a server 401 — no logout call)\n     *\n     * Existing consumer code that uses `state.matches('loggedOut')`\n     * still matches every substate (xstate parent matching). Code\n     * that uses `state.value === 'loggedOut'` will need to migrate to\n     * `.matches()` because compound `value` is `{ loggedOut: '<sub>' }`.\n     */\n    loggedOut: {\n      initial: 'initial',\n      on: {\n        LOGIN: {\n          target: 'authenticating',\n        },\n        CLEAR_ERRORS: {\n          actions: 'clearErrors',\n        },\n      },\n      states: {\n        initial: {},\n        afterFailedAuth: {},\n        afterLogout: {},\n        afterRefreshFailure: {},\n      },\n    },\n    /**\n     * loggedInReady transient state is a workaround to restoring the snapshot on client side,\n     * since actions won't run (they are assumed to have run already) and timers are stopped (they\n     * have no clock mechanism to determine at what point to restart)\n     */\n    loggedInReady: {\n      on: {\n        RESTORE: {\n          guard: () => typeof window !== 'undefined',\n          target: 'loggedIn',\n        },\n      },\n    },\n    loggedIn: {\n      // A tab shown again (or back online) with a due token refreshes before its next request (CTAP-2772).\n      invoke: {\n        src: 'watchTokenFreshness',\n        input: ({ context }) => ({\n          accessToken: context.accessToken,\n          clockSkewMs: context.clockSkewMs ?? 0,\n        }),\n      },\n      after: {\n        // From the token's exp (see `delays.refresh`).\n        refresh: {\n          guard: () => typeof window !== 'undefined',\n          target: 'refreshing',\n        },\n      },\n      on: {\n        LOGOUT: {\n          // Deliberate sign-out → mark it so `unauthenticating` routes to\n          // afterLogout (home), distinct from an expired session (CTAP-1129).\n          actions: 'markDeliberateLogout',\n          target: 'unauthenticating',\n        },\n        // A server 401 on an authenticated request: marked EXPIRED so the\n        // visitor is returned to where they were via the login page instead of\n        // being dropped on the home page (CTAP-1425). Torn down locally only,\n        // never through the logout endpoint (CTAP-2772): this tab's request\n        // carries the browser's shared refresh cookie, and logout revokes that\n        // cookie's whole family, which may be the session another tab just\n        // signed into. Only a deliberate LOGOUT ends the session on the server.\n        SESSION_EXPIRED: {\n          actions: [\n            'markExpiredSession',\n            'unsetUserContext',\n            'notifyUnauthenticated',\n          ],\n          target: 'loggedOut.afterRefreshFailure',\n        },\n        CLEAR_ERRORS: {\n          actions: 'clearErrors',\n        },\n        LOGIN: {\n          target: 'authenticating',\n        },\n        REFRESH_TOKEN: {\n          target: 'refreshing',\n        },\n        // Stay signed in after an email/password change: swap in the re-issued access token\n        // (self-transition, no re-auth). The rotated refresh cookie was set on the mutation response.\n        // `reenter` matters: a targetless self-transition keeps the REVOKED\n        // token's `after: refresh` schedule, so the first background refresh\n        // after a credential change fired on the old token's clock. Re-entering\n        // restarts the 14-minute timer for the re-issued token (CTAP-1159).\n        SESSION_REISSUED: {\n          actions: ['setReissuedAccessToken', 'notifyReissued'],\n          target: 'loggedIn',\n          reenter: true,\n        },\n        // AFTER_LOGGED_IN: {\n        //   target: 'afterLoggedIn',\n        // },\n      },\n    },\n    // onLogin: {\n    //   always: {\n    //     target: 'loggedIn',\n    //   },\n    // },\n    // afterLoggedOut: {\n    //   always: {\n    //     target: 'loggedOut',\n    //   },\n    // },\n  },\n});\n\nexport default authMachine;\n","import { Actor, waitFor } from 'xstate';\nimport { authMachine } from './auth';\n\n/**\n * The refresher `@clicktap/ui`'s auth-aware GraphQL client calls on a 401 (CTAP-2773), so a request whose access\n * token aged out is retried with a fresh one instead of signing the user out.\n *\n * Shared with the client through `globalThis[Symbol.for(AUTH_REFRESHER_KEY)]`, so neither package imports the other.\n * The key must stay identical to `AUTH_REFRESHER_KEY` in `@clicktap/ui`'s `createAuthAwareGraphqlClient`.\n */\nexport const AUTH_REFRESHER_KEY = '@clicktap/auth-refresher';\n\n/** How long a request waits for the auth machine's refresh before it gives up and reports the 401. */\nconst REFRESH_WAIT_MS = 15_000;\n\n/**\n * Resolves with an access token to retry with, or null when the session is gone.\n *\n * The machine stays the only owner of the token. A token that already changed since the failed request (another\n * request's refresh finished first) is returned as it is; otherwise the machine refreshes (or is already refreshing)\n * and the new token is returned once it is back in `loggedIn`.\n */\nexport function createAuthRefresher(actor: Actor<typeof authMachine>) {\n  return async (failedToken: string): Promise<string | null> => {\n    const snapshot = actor.getSnapshot();\n    if (\n      snapshot.matches('loggedIn') &&\n      snapshot.context.accessToken &&\n      snapshot.context.accessToken !== failedToken\n    ) {\n      return snapshot.context.accessToken;\n    }\n    if (snapshot.matches('loggedIn')) {\n      actor.send({\n        type: 'REFRESH_TOKEN',\n        accessToken: snapshot.context.accessToken,\n      });\n    } else if (!snapshot.matches('refreshing')) {\n      return null;\n    }\n\n    try {\n      const settled = await waitFor(\n        actor,\n        (s) =>\n          (s.matches('loggedIn') && s.context.accessToken !== failedToken) ||\n          s.matches('loggedOut'),\n        { timeout: REFRESH_WAIT_MS },\n      );\n      return settled.matches('loggedIn') ? settled.context.accessToken : null;\n    } catch {\n      return null;\n    }\n  };\n}\n\n/** Registers the actor's refresher for the GraphQL client; returns the unregister. Browser only. */\nexport function registerAuthRefresher(\n  actor: Actor<typeof authMachine>,\n): () => void {\n  if (typeof window === 'undefined') {\n    return () => undefined;\n  }\n  const key = Symbol.for(AUTH_REFRESHER_KEY);\n  const registry = globalThis as Record<symbol, unknown>;\n  const refresher = createAuthRefresher(actor);\n  registry[key] = refresher;\n\n  return () => {\n    if (registry[key] === refresher) {\n      delete registry[key];\n    }\n  };\n}\n","'use client';\n\nimport {\n  createContext,\n  useContext,\n  useEffect,\n  useMemo,\n  useState,\n  ReactNode,\n} from 'react';\nimport { Actor, InspectionEvent, Observer, createActor } from 'xstate';\nimport { useSessionTransition } from '../session';\nimport { authMachine } from './auth';\nimport { AuthTransport } from './transport';\nimport { registerAuthRefresher } from './authRefresher';\n\nexport interface AuthContextType {\n  authActor: Actor<typeof authMachine>;\n  /**\n   * The visitor's identity. Held steady for the duration of a session\n   * transition — see the `AuthProvider` doc block for the two ordering\n   * constraints that hold depends on (it must be mounted inside\n   * `SessionTransitionProvider`, and the gate is `transitionRef`, not\n   * `isTransitioning`).\n   *\n   * This is the ONLY session value published here. \"Is a session change\n   * happening?\" belongs to `useSessionTransition()`, not to auth state.\n   *\n   * There used to be an `isLoggingOut` flag too, derived from\n   * `unauthenticating || loggedOut.afterLogout`. It is deliberately gone:\n   * `afterLogout` is a TERMINAL state, so the flag stayed true for the life of\n   * the actor and wedged everything gated on it — the header account menu became\n   * permanently unclickable, the logout overlay reappeared on unrelated pages,\n   * and the account-page sign-in redirect stopped firing altogether. Every\n   * consumer invented its own escape hatch and none of them held. Removing it\n   * outright is what stops that being reintroduced (CTAP-1151).\n   */\n  isLoggedIn: boolean;\n}\n\n/**\n * Auth state is derived ONCE, here in the provider, and published whole.\n *\n * It used to be derived inside `useAuth()`, which meant every one of ~60 call\n * sites ran its own `useState` + `authActor.subscribe`. Beyond the waste, that\n * made the identity freeze below unsound: a component mounting mid-transition\n * seeded `isLoggedIn` from the LIVE snapshot while its already-mounted siblings\n * were still holding the pre-transition value, so two parts of the same screen\n * disagreed about whether the visitor was signed in. One shared value cannot\n * diverge.\n */\nconst AuthContext = createContext<AuthContextType>({} as AuthContextType);\n\nexport const useAuth = (): AuthContextType => useContext(AuthContext);\n\n// export const useUser = () => {\n//   return useContext(AuthContext).getSnapshot().context.user;\n// };\n\ntype AuthOptions = {\n  inspect: Observer<InspectionEvent> | undefined;\n  endpoints: {\n    login: string;\n    logout: string;\n    refresh: string;\n    ssrRefresh: string;\n  };\n  /** Header injection for the auth HTTP calls — see `./transport`. */\n  transport?: AuthTransport;\n};\n\n/**\n * runs on server side as part of withAuth HOF\n *\n * @todo should probably update signature to pass Partial<AuthContext> and\n * Options, endpoints should probably be moved into context\n */\nexport const getAuth = async (\n  refreshToken = '',\n  options: AuthOptions = {\n    inspect: undefined,\n    endpoints: { login: '', logout: '', refresh: '', ssrRefresh: '' },\n  },\n) => {\n  return createActor(authMachine, {\n    input: {\n      transport: options.transport,\n      initialContext: {\n        endpoints: options.endpoints,\n        refreshToken,\n      },\n    },\n    inspect: options.inspect,\n  }).start();\n};\n\ntype AuthSnapshot = ReturnType<Actor<typeof authMachine>['getSnapshot']>;\n\n/**\n * Signed-in predicate — `loggedIn` OR `loggedInReady`.\n *\n * `loggedInReady` is the rehydration state: an actor restored from a serialized\n * snapshot on the server, authenticated but waiting for the client `RESTORE`\n * event. The visitor genuinely IS signed in there, so it must count.\n *\n * It is easy to miss because it is unreachable in a consumer that prepends the\n * `initializing` state — that short-circuits straight to `loggedIn` whenever a\n * token is present, so `loggedInReady` never occurs and omitting it does no\n * visible harm. Consumers that restore a snapshot through the `withAuth` HOF do\n * reach it, and for them omitting it renders an authenticated visitor as signed\n * out for the whole of hydration.\n */\nconst isSignedIn = (snapshot: AuthSnapshot): boolean =>\n  snapshot.matches('loggedIn') || snapshot.matches('loggedInReady');\n\ntype Props = {\n  actor: Actor<typeof authMachine>;\n  children: ReactNode;\n};\n\n/**\n * Publishes the auth actor and a single derived `isLoggedIn`.\n *\n * ## Two ordering constraints you can get wrong silently\n *\n * **1. `SessionTransitionProvider` MUST be an ancestor of this provider.**\n * `isLoggedIn` is held steady for the duration of a session transition, and that\n * hold is read from `useSessionTransition()`. Mounted outside the transition\n * provider, this reads the inert default context (`transitionRef: {current:\n * false}`) — which is safe rather than throwing, so nothing warns and nothing\n * breaks in an obvious way. The identity simply flips mid-transition anyway: the\n * overlay covers the screen while the checkout swaps to the guest email form\n * underneath it, and the browser offers autofill for the guest email.\n *\n * **2. The hold is gated on `transitionRef`, not `isTransitioning`** — and any\n * consumer mirroring this identity into its own state must do the same.\n * `isTransitioning` is React state, so it only reflects a transition after a\n * re-render, while actor subscriptions fire synchronously on the machine's own\n * transitions and routinely outrun it: a local sign-out reaches `afterLogout`\n * while `isTransitioning` still reads `false`. If you keep a copy of the\n * identity (feeding a router provider, say), the fix is to **delete the mirror\n * and read the held value here** rather than to reproduce the ref gating.\n *\n * ## Why the identity is held but the actor is not\n *\n * The actor freeze in the app's provider tree covers the quote/checkout\n * subtrees, but the auth actor must stay LIVE — components send LOGIN/LOGOUT\n * through it and several subscribe directly, so a frozen proxy would deadlock\n * sign-in. The identity alone is held; transition progress stays live because the\n * overlay renders from it (CTAP-1150/1151).\n */\nexport function AuthProvider({ actor, children }: Props) {\n  const [isLoggedIn, setIsLoggedIn] = useState(() =>\n    isSignedIn(actor.getSnapshot()),\n  );\n\n  // Hold `isLoggedIn` steady while a session transition is in flight.\n  //\n  // The actor freeze in `Providers` covers the quote/checkout subtrees, but the\n  // auth actor must stay LIVE — components send LOGIN/LOGOUT through it and\n  // several subscribe to it directly, so a frozen proxy would deadlock sign-in\n  // and latch `useAuthTransitioning`. So the identity alone is held: without it\n  // the checkout Information step swaps to the guest email form behind the\n  // overlay, which the browser then offers autofill for. The progress signals\n  // below stay live by design — the overlay depends on them.\n  const { isTransitioning, transitionRef } = useSessionTransition();\n\n  // The GraphQL client's refresh-and-retry on a 401 asks this actor for a fresh token (CTAP-2773).\n  useEffect(() => registerAuthRefresher(actor), [actor]);\n\n  useEffect(() => {\n    const subscription = actor.subscribe((snapshot) => {\n      // Gate on the REF, not the state value. This callback runs synchronously\n      // with the machine's transition, which outruns React: a local sign-out\n      // reaches `afterLogout` while `isTransitioning` still reads false, so the\n      // identity would flip mid-freeze.\n      if (!transitionRef.current) {\n        if (isSignedIn(snapshot)) {\n          setIsLoggedIn(true);\n        } else if (snapshot.matches('loggedOut')) {\n          setIsLoggedIn(false);\n        }\n      }\n    });\n\n    return () => {\n      subscription.unsubscribe();\n    };\n  }, [actor, transitionRef]);\n\n  // Re-sync when the freeze lifts. The machine usually settles DURING the\n  // transition, so there is no later emission to carry the final value — the\n  // held update would otherwise be lost and the identity would stay stale until\n  // some unrelated auth event happened to fire.\n  useEffect(() => {\n    if (isTransitioning) {\n      return;\n    }\n    const snapshot = actor.getSnapshot();\n    if (isSignedIn(snapshot)) {\n      // Freeze-lift re-sync from an external store: the machine settled\n      // DURING the transition, so no later emission carries the final value;\n      // this effect is the only place the held identity can catch up\n      // (CTAP-1150/1151). Hence the set-state-in-effect disables.\n      // eslint-disable-next-line react-hooks/set-state-in-effect\n      setIsLoggedIn(true);\n    } else if (snapshot.matches('loggedOut')) {\n      setIsLoggedIn(false);\n    }\n  }, [isTransitioning, actor]);\n\n  const value = useMemo(\n    () => ({ authActor: actor, isLoggedIn }),\n    [actor, isLoggedIn],\n  );\n\n  return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;\n}\n"],"names":["addError","context","event","e","clearErrors","notifyAuthenticated","notifyUnauthenticated","options","FALLBACK_REFRESH_DELAY_MS","REFRESH_MARGIN_MS","NEGLIGIBLE_SKEW_MS","tokenTimes","token","payload","base64","padded","json","claims","clockSkewFromFreshToken","now","iat","skew","refreshDelayMs","clockSkewMs","exp","lifetime","margin","serverNow","isRefreshDue","setAccessToken","setIgnoreRefreshToken","setUserContext","unsetRefreshToken","unsetUserContext","AuthMachineStatusCode","DEFAULT_AUTH_HEADERS","resolveAuthHeaders","transport","call","authenticate","fromPromise","input","knownCode","code","fail","cause","error","data","request","err","isDevelopment","IS_SERVER","refreshAccessToken","unauthenticate","watchTokenFreshness","fromCallback","sendBack","check","authMachine","setup","assign","addErrorAction","clearErrorsAction","emit","notifyAuthenticatedAction","notifyUnauthenticatedAction","setAccessTokenAction","assertEvent","setIgnoreRefreshTokenAction","setUserContextAction","unsetRefreshTokenAction","unsetUserContextAction","authenticateActor","refreshAccessTokenActor","unauthenticateActor","watchTokenFreshnessActor","AUTH_REFRESHER_KEY","REFRESH_WAIT_MS","createAuthRefresher","actor","failedToken","snapshot","settled","waitFor","s","registerAuthRefresher","key","registry","refresher","AuthContext","createContext","useAuth","useContext","getAuth","refreshToken","createActor","isSignedIn","AuthProvider","children","isLoggedIn","setIsLoggedIn","useState","isTransitioning","transition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