@movmo/express-checkout-button 2.0.0 → 2.0.2
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 +2 -1
- package/dist/dts/returnHandler.d.ts +2 -1
- package/dist/dts/urlScrub.d.ts +8 -0
- package/dist/express-checkout.umd.js +5 -5
- package/dist/express-checkout.umd.js.map +1 -1
- package/dist/index.cjs +2 -2
- package/dist/index.cjs.map +1 -1
- package/dist/index.css +1 -1
- package/dist/index.css.map +1 -1
- package/dist/index.d.ts +3 -2
- package/dist/index.es.js +2 -2
- package/dist/index.es.js.map +1 -1
- package/package.json +1 -1
package/dist/index.es.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.es.js","sources":["../src/env.ts","../src/api.ts","../src/urlScrub.ts","../src/redirect.ts","../src/tracking.ts","../src/returnHandler.ts","../src/MovmoCheckoutButton.tsx"],"sourcesContent":["// Replaced at build time: `false` in the UMD bundle (a script-tag SDK must not honour\n// page-controllable overrides), `true` in the ESM/CJS builds and under Vitest. The typeof guard\n// keeps an unreplaced source import (tsc, Storybook) working.\ndeclare const __ALLOW_ENV_OVERRIDES__: boolean;\n\n/** Whether build-time environment overrides are honoured at all (false in the UMD build). */\nexport const ALLOW_ENV_OVERRIDES: boolean =\n typeof __ALLOW_ENV_OVERRIDES__ === 'undefined' || __ALLOW_ENV_OVERRIDES__;\n\n/**\n * Reads a build-time environment override without assuming a `process` global. ESM/CJS builds\n * only: the value is read at runtime from `process.env` (the consuming bundler's define), never\n * inlined by this package, and the UMD build compiles overrides out entirely.\n *\n * Create React App inlines `process.env.REACT_APP_*`; Vite, Parcel, esbuild, Remix/Astro\n * on Vite and plain `<script type=\"module\">` pages have no `process` in the browser, and a\n * bare `process.env.X` read throws `ReferenceError: process is not defined` at mount — which\n * unmounts the host page's whole tree. Always read overrides through this helper.\n *\n * Only a non-empty string is returned: markup that clobbers `window.process` (DOM clobbering)\n * can make `process.env.X` an element or object, which must never reach a URL.\n */\nexport function readEnv(name: string): string | undefined {\n if (!ALLOW_ENV_OVERRIDES) return undefined;\n try {\n const proc = (globalThis as { process?: { env?: Record<string, unknown> } }).process;\n const value = proc?.env?.[name];\n return typeof value === 'string' && value !== '' ? value : undefined;\n } catch {\n return undefined;\n }\n}\n\n/**\n * True for `https://movmo.io`, `https://*.movmo.io`, and `http://localhost[:port]` /\n * `http://127.0.0.1[:port]` (local development). No credentials in the URL.\n */\nexport function isTrustedMovmoUrl(raw: string): boolean {\n try {\n const url = new URL(raw);\n if (url.username || url.password) return false;\n const host = url.hostname.toLowerCase();\n if (url.protocol === 'https:') return host === 'movmo.io' || host.endsWith('.movmo.io');\n if (url.protocol === 'http:') return host === 'localhost' || host === '127.0.0.1';\n return false;\n } catch {\n return false;\n }\n}\n\n/** A URL override that passes {@link isTrustedMovmoUrl}; anything else is ignored. */\nexport function readUrlOverride(name: string): string | undefined {\n const value = readEnv(name);\n if (value === undefined) return undefined;\n if (isTrustedMovmoUrl(value)) return value;\n console.warn(`[movmo] express checkout: ignoring untrusted ${name} override`);\n return undefined;\n}\n","import { ALLOW_ENV_OVERRIDES, readEnv, readUrlOverride } from './env';\n/**\n * Minimal JSON POST client for the Movmo checkout proxy.\n *\n * Replaces axios (MOVMO-517) — the package's only runtime HTTP dependency,\n * ~14 KB gzip of the UMD bundle. Deliberately NOT a general-purpose HTTP\n * client: one method, one content type, one caller (`saveProviderOffer`).\n */\nexport interface ApiClient {\n post<T>(path: string, body: unknown): Promise<T>;\n}\n\nconst REQUEST_TIMEOUT_MS = 30_000;\n\n// Helper function to read cookie value from document.cookie\nconst getCookie = (name: string): string | null => {\n if (typeof document === 'undefined') return null;\n const cookies = document.cookie.split(';');\n for (let i = 0; i < cookies.length; i++) {\n const cookie = cookies[i].trim();\n if (cookie.startsWith(name + '=')) {\n // URL-decode the cookie value to match what backend expects\n return decodeURIComponent(cookie.substring(name.length + 1));\n }\n }\n return null;\n};\n\nconst isLocalHost = () =>\n typeof window !== 'undefined' &&\n (window.location.hostname === 'localhost' || window.location.hostname === '127.0.0.1');\n\n/**\n * Built fresh for EVERY request, not once per client:\n * - the CSRF cookie is set by the proxy during the session and can change\n * between the button rendering and the traveler clicking — the old axios\n * request interceptor re-read it per request for exactly this reason;\n * - X-Forwarded-Host now reflects the page's host at send time too (axios\n * baked it in at client creation).\n *\n * The axios interceptor also deleted any inherited `Authorization` header.\n * That mattered because axios was resolved from the PARTNER's node_modules\n * in the React build, so `axios.create()` inherited their global\n * `axios.defaults.headers` — a partner-wide bearer token would otherwise\n * have been forwarded to Movmo's proxy. `fetch` has no shared defaults, so\n * that defence now holds by construction; do not \"restore\" it.\n */\nconst buildHeaders = (apiKey: string, airlineRef: string): Record<string, string> => {\n const headers: Record<string, string> = {\n Accept: 'application/json',\n 'Content-Type': 'application/json',\n 'x-api-key': apiKey,\n 'X-Forwarded-Host': typeof window !== 'undefined' ? window.location.host : '',\n 'movmo-customer-id': airlineRef,\n };\n\n // Overrides are compiled out of the UMD build (ALLOW_ENV_OVERRIDES is false there).\n const proxyAuth = ALLOW_ENV_OVERRIDES\n ? readEnv('REACT_APP_CLOUD_FRONT_PROXY_SECRET_HEADER')\n : undefined;\n if (isLocalHost() && proxyAuth) {\n headers['X-Movmo-Proxy-Auth'] = proxyAuth;\n }\n\n const csrf = getCookie('movmo_csrf_token');\n if (csrf) {\n headers['X-CSRF-Token'] = csrf;\n }\n\n return headers;\n};\n\nexport const createApiClient = (\n apiKey: string,\n airlineRef: string,\n isProd: boolean = false,\n): ApiClient => {\n const baseUrl = isProd ? 'https://flights.movmo.io' : 'https://flights.e2e.movmo.io';\n // REACT_APP_MOVMO_CHECKOUT_API_URL overrides the API base (e.g. the offline demo\n // talks directly to the local monolith-api at http://localhost:8080, bypassing the\n // CloudFront /v1/proxy hop). Only a movmo.io or localhost URL is accepted; anything else falls back to the default.\n const apiOverride = ALLOW_ENV_OVERRIDES\n ? readUrlOverride('REACT_APP_MOVMO_CHECKOUT_API_URL')\n : undefined;\n const proxyBaseUrl = apiOverride || `${baseUrl}/v1/proxy`;\n\n return {\n async post<T>(path: string, body: unknown): Promise<T> {\n // axios `baseURL` semantics: the base PATH is preserved and the request\n // path appended → .../v1/proxy/v1/flights/... . `new URL(path, base)`\n // would resolve the leading slash against the ORIGIN and silently drop\n // /v1/proxy, bypassing the CloudFront hop. Do not \"simplify\" this.\n const url = `${proxyBaseUrl.replace(/\\/+$/, '')}/${path.replace(/^\\/+/, '')}`;\n\n // AbortController + setTimeout rather than AbortSignal.timeout(): the\n // latter is Safari 16+ only, and this ships to partner pages with no\n // control over the traveler's browser.\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS);\n\n try {\n const response = await fetch(url, {\n method: 'POST',\n headers: buildHeaders(apiKey, airlineRef),\n body: JSON.stringify(body),\n // Cross-site call: without this the Movmo session + CSRF cookies are\n // never sent and the proxy rejects the save (axios: withCredentials).\n credentials: 'include',\n signal: controller.signal,\n });\n\n // axios rejected on non-2xx by default; fetch resolves. Keep rejecting, but\n // now carry the status + parsed body along on the thrown Error so callers\n // (saveProviderOffer, MOVMO-673) can surface a status code and a backend\n // message instead of only a generic string.\n if (!response.ok) {\n let errorBody: unknown;\n try {\n errorBody = await response.json();\n } catch {\n // Non-JSON or empty error body — errorBody stays undefined, message\n // falls back to the generic string below.\n }\n throw Object.assign(\n new Error(\n `Movmo API request failed: ${response.status} ${response.statusText} (${path})`,\n ),\n { status: response.status, body: errorBody },\n );\n }\n\n return (await response.json()) as T;\n } finally {\n // Always clear, including on the success path — otherwise every save\n // leaves a 30 s timer behind.\n clearTimeout(timer);\n }\n },\n };\n};\n\n/**\n * Discriminated result of {@link saveProviderOffer} (MOVMO-673). Replaces the earlier\n * `string | null` contract so the button (and, via `onError`, the partner page) can\n * surface WHY a save failed — an HTTP status when the response was non-2xx, and a\n * message that prefers the backend's own JSON `message`/`error` field over a generic\n * fetch/timeout string.\n */\nexport type SaveOfferResult =\n | { ok: true; offerId: string }\n | { ok: false; status?: number; message: string; cause?: unknown };\n\n// Shape of a typical backend error body: a top-level { message: \"...\" }, a string\n// { error: \"...\" }, or go-services-core's nested { error: { message, status_code,\n// is_retryable } } (the shape a rejected-offer 400 actually sends). All three are\n// checked since different endpoints/providers use different conventions.\nconst messageFromBody = (body: unknown): string | undefined => {\n if (!body || typeof body !== 'object') return undefined;\n const { message, error } = body as { message?: unknown; error?: unknown };\n if (typeof message === 'string' && message) return message;\n if (typeof error === 'string' && error) return error;\n if (error && typeof error === 'object') {\n const nestedMessage = (error as { message?: unknown }).message;\n if (typeof nestedMessage === 'string' && nestedMessage) return nestedMessage;\n }\n return undefined;\n};\n\nexport const saveProviderOffer = async (\n providerID: string,\n rawOffer: object,\n client: ApiClient,\n): Promise<SaveOfferResult> => {\n try {\n const data = await client.post<{ offer_id?: string }>(\n `/v1/flights/providers/${providerID}/offers`,\n rawOffer,\n );\n if (!data?.offer_id) {\n const message = 'no offer_id in response';\n console.error(message);\n return { ok: false, message };\n }\n return { ok: true, offerId: data.offer_id };\n } catch (err) {\n // MOVMO-464 contract: never throw into the click handler. Resolving an `ok:\n // false` result is what makes the button emit OFFER_SAVE_FAILED (and, since\n // MOVMO-673, call onError) instead of dying silently.\n console.error(err);\n const status = (err as { status?: number } | undefined)?.status;\n const body = (err as { body?: unknown } | undefined)?.body;\n const message = messageFromBody(body) ?? (err instanceof Error ? err.message : String(err));\n return { ok: false, status, message, cause: err };\n }\n};\n","/**\n * String-level URL surgery (no URLSearchParams round trip), so the partner's own query and\n * hash survive byte for byte: `?q=a%20b&next=/x/y&flag` stays exactly that.\n */\n\nfunction safeDecode(s: string): string {\n try {\n return decodeURIComponent(s);\n } catch {\n return s;\n }\n}\n\n/** Remove every `movmo_*` key from a `?query` string; returns '' when nothing is left. */\nexport function scrubQuery(search: string): string {\n if (search.length <= 1) return search === '?' ? '' : search;\n const kept = search\n .slice(1)\n .split('&')\n .filter((seg) => !safeDecode(seg.split('=')[0]).startsWith('movmo_'));\n return kept.length > 0 ? `?${kept.join('&')}` : '';\n}\n\nconst PNR_TOKEN = /^movmo_pnr(?:=.*)?$/;\n\n/**\n * Remove every `movmo_pnr=` segment from a `#fragment`, whatever delimiter (`?` or `&`)\n * precedes it: `#movmo_pnr=A&movmo_pnr=B`, `#movmo_pnr=OLD?movmo_pnr=NEW`, `#/r?a=1&movmo_pnr=X`.\n * Returns '' (no hash) when nothing is left.\n */\nexport function scrubHashPnr(hash: string): string {\n if (hash.length <= 1) return '';\n const parts = hash.slice(1).split(/([?&])/); // token, delim, token, delim, ...\n let out = '';\n let carry: string | null = null; // leading delimiter of the first removed token in a run\n let removedAny = false;\n for (let i = 0; i < parts.length; i += 2) {\n const delim = i === 0 ? '' : parts[i - 1];\n const token = parts[i];\n if (PNR_TOKEN.test(token)) {\n removedAny = true;\n if (carry === null) carry = delim;\n continue;\n }\n let lead = delim;\n if (carry !== null) {\n // `?` (or nothing) before a removed run is inherited by the next kept token.\n if (carry === '' || carry === '?') lead = out === '' ? '' : carry;\n carry = null;\n }\n out += lead + token;\n }\n if (!removedAny) return hash;\n return out === '' ? '' : `#${out}`;\n}\n\n/** True when the fragment looks like a router route (`#/x`, `#!/x`) rather than an anchor or data. */\nexport function isRouteHash(hash: string): boolean {\n return /^#!?\\//.test(hash);\n}\n","import { ALLOW_ENV_OVERRIDES, readUrlOverride } from './env';\nimport { isRouteHash, scrubHashPnr, scrubQuery } from './urlScrub';\n\n/** sessionStorage key holding the pending-return record on the partner origin. */\nexport const PENDING_KEY = 'movmo:checkout:pending';\n\nconst PROD_CHECKOUT_URL = 'https://flights.movmo.io';\nconst E2E_CHECKOUT_URL = 'https://flights.e2e.movmo.io';\n\n/** What the button remembers across the top-level navigation to Movmo and back. */\nexport interface PendingCheckout {\n state: string;\n offerId: string;\n startedAt: number;\n /** Stored at click so the return is attributed to the button that started it. */\n providerId?: string;\n airlineRef?: string;\n /** Environment the button was mounted with; selects the analytics collector on return. */\n isProd?: boolean;\n}\n\n/** A pending record older than this is ignored (an abandoned checkout, or a stale tab). */\nexport const PENDING_TTL_MS = 24 * 60 * 60 * 1000;\n\nexport interface BuildCheckoutUrlParams {\n offerId: string;\n providerId: string;\n /** Airline IATA code, sent as `airlineRef`. */\n airlineRef: string;\n /** Partner analytics session id (`mvs`), when the tracker has one. */\n mvs?: string | null;\n internal?: boolean;\n returnUrl: string;\n /** Omitted only when the platform has no crypto at all. */\n state?: string | null;\n isProd: boolean;\n}\n\n/** Checkout origin: the build-time override, else prod or e2e. Path routing, not a hash route. */\nexport function checkoutBaseUrl(isProd: boolean): string {\n // Validated: an override must be a movmo.io (or localhost) URL, and UMD compiles it out.\n const override = ALLOW_ENV_OVERRIDES\n ? readUrlOverride('REACT_APP_MOVMO_CHECKOUT_URL')\n : undefined;\n if (override) return override.replace(/\\/+$/, '');\n return isProd ? PROD_CHECKOUT_URL : E2E_CHECKOUT_URL;\n}\n\nexport function buildCheckoutUrl(params: BuildCheckoutUrlParams): string {\n const qs = new URLSearchParams({\n offerId: params.offerId,\n providerId: params.providerId,\n airlineRef: params.airlineRef,\n });\n // Session stitching (MOVMO-464): flights-ui adopts mvs so button_viewed -> booking_confirmed\n // joins as one session. mv_internal keeps QA/demo traffic flagged (MOVMO-478).\n if (params.mvs) qs.set('mvs', params.mvs);\n if (params.internal) qs.set('mv_internal', '1');\n qs.set('returnUrl', params.returnUrl);\n if (params.state) qs.set('state', params.state);\n return `${checkoutBaseUrl(params.isProd)}/booking?${qs.toString()}`;\n}\n\n/**\n * The return URL sent to Movmo (it lands in CloudFront logs): the current page URL with every\n * `movmo_*` query param removed. The other params are kept. The fragment is kept only when it\n * looks like a router route (`#/` or `#!/`), and then without any `movmo_pnr`; any other\n * fragment (anchors, tokens, partner data) is dropped.\n */\nexport function defaultReturnUrl(href: string): string {\n const url = new URL(href);\n const hash = isRouteHash(url.hash) ? scrubHashPnr(url.hash) : '';\n return `${url.origin}${url.pathname}${scrubQuery(url.search)}${hash}`;\n}\n\n/**\n * Random nonce echoed back as `movmo_state`. `crypto.randomUUID()`, else 16 random bytes as\n * hex. With no crypto at all returns null: the redirect still happens without `state`, and the\n * return is then not verifiable, so the SDK ignores it (fails closed on the callback side).\n */\nexport function mintState(): string | null {\n try {\n const c = (globalThis as { crypto?: Crypto }).crypto;\n if (c && typeof c.randomUUID === 'function') return c.randomUUID();\n if (c && typeof c.getRandomValues === 'function') {\n const bytes = c.getRandomValues(new Uint8Array(16));\n return Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('');\n }\n } catch {\n /* fall through */\n }\n return null;\n}\n\nexport function writePending(pending: PendingCheckout): void {\n try {\n sessionStorage.setItem(PENDING_KEY, JSON.stringify(pending));\n } catch {\n /* fail-open: storage blocked or unavailable */\n }\n}\n\nexport function readPending(): PendingCheckout | null {\n try {\n const raw = sessionStorage.getItem(PENDING_KEY);\n if (!raw) return null;\n const v = JSON.parse(raw) as Partial<PendingCheckout> | null;\n if (\n v &&\n typeof v.state === 'string' &&\n v.state !== '' &&\n typeof v.offerId === 'string' &&\n typeof v.startedAt === 'number'\n ) {\n if (Date.now() - v.startedAt > PENDING_TTL_MS) {\n clearPending();\n return null;\n }\n return {\n state: v.state,\n offerId: v.offerId,\n startedAt: v.startedAt,\n ...(typeof v.providerId === 'string' ? { providerId: v.providerId } : {}),\n ...(typeof v.airlineRef === 'string' ? { airlineRef: v.airlineRef } : {}),\n ...(typeof v.isProd === 'boolean' ? { isProd: v.isProd } : {}),\n };\n }\n } catch {\n /* fall through */\n }\n return null;\n}\n\nexport function clearPending(): void {\n try {\n sessionStorage.removeItem(PENDING_KEY);\n } catch {\n /* fail-open */\n }\n}\n","import { EVENTS, Movmo } from '@movmo_app/analytics';\nimport { ALLOW_ENV_OVERRIDES, readUrlOverride } from './env';\n\nexport { EVENTS };\n\n/**\n * Scoped-mode analytics for the partner page (MOVMO-464). Autocapture stays OFF —\n * we never observe the partner's DOM or inputs; listeners attach only to\n * Movmo-rendered elements. Analytics must never break checkout: every entry\n * point here is fail-open.\n */\nexport function initScopedTracker(iataCode: string, isProd: boolean): void {\n try {\n if (Movmo.isInitialized()) return;\n // Same validated, ESM/CJS-only override mechanism as REACT_APP_MOVMO_CHECKOUT_URL.\n const endpoint =\n (ALLOW_ENV_OVERRIDES ? readUrlOverride('REACT_APP_MOVMO_ANALYTICS_URL') : undefined) ||\n (isProd ? 'https://api.movmo.io/v1/t' : 'https://e2e.api.movmo.io/v1/t');\n Movmo.init({\n app: 'express-checkout-button',\n env: isProd ? 'prd' : 'e2e',\n partnerId: iataCode,\n endpoint,\n scoped: true,\n });\n Movmo.track(EVENTS.PLUGIN_LOADED);\n } catch {\n /* fail-open */\n }\n}\n\nexport function trackSafe(event: string, props: Record<string, unknown> = {}): void {\n try {\n Movmo.track(event, props);\n } catch {\n /* fail-open */\n }\n}\n\nexport function trackerSessionId(): string | null {\n try {\n return Movmo.getSessionId();\n } catch {\n return null;\n }\n}\n\n/** Whether the partner-page session is flagged internal/QA/demo traffic (MOVMO-478). */\nexport function trackerIsInternal(): boolean {\n try {\n return Movmo.isInternal();\n } catch {\n return false;\n }\n}\n","import type { MovmoExitReason } from '@movmo_app/types';\n\nimport { clearPending, PendingCheckout, readPending } from './redirect';\nimport { EVENTS, initScopedTracker, trackSafe } from './tracking';\nimport { scrubHashPnr, scrubQuery } from './urlScrub';\n\n/** Passed to the airline's onExit callback when the traveler returns from Movmo. */\nexport interface MovmoCheckoutExitInfo {\n reason: MovmoExitReason;\n}\n\n/** Passed to onBookingComplete when the traveler returns from a confirmed booking. */\nexport interface MovmoBookingCompleteInfo {\n bookingId: string;\n /** Record locator (PNR) in the airline's own reservation system. Absent if the provider returned none. */\n airlinePnr?: string;\n /** Airline IATA / company code, not the PNR. */\n airlineRef?: string;\n providerId?: string;\n}\n\nexport interface MovmoCheckoutReturnOptions {\n /**\n * The button's identity. When given, an instance only claims a return whose pending record\n * (written at click) matches; a page-level `consumeReturn()` omits them and claims whatever\n * is pending, taking the values from the record.\n */\n iataCode?: string;\n providerID?: string;\n /** The pre-saved offer id, when known, to tell two buttons with the same airline apart. */\n offerId?: string;\n /**\n * Analytics environment, used only when the pending record does not carry one. When neither\n * is known the tracker is not initialised here.\n */\n isProd?: boolean;\n onExit?: (info: MovmoCheckoutExitInfo) => void;\n onBookingComplete?: (info: MovmoBookingCompleteInfo) => void;\n}\n\nconst REASONS: readonly MovmoExitReason[] = [\n 'search_again',\n 'offer_unavailable',\n 'booking_confirmed',\n];\n\ninterface ReturnStash {\n exit: string;\n state: string | null;\n bookingId: string | null;\n pnr: string | null;\n}\n\n// The return is parsed and scrubbed from the URL on the FIRST call, then held here until an\n// instance whose identity matches the pending record claims it (two buttons on one page).\nlet stash: ReturnStash | null = null;\nlet parsed = false;\nlet claimed = false;\n\n/** @internal Test hook: forget any parsed or claimed return. Not exported from the package entry. */\nexport function __resetForTests(): void {\n stash = null;\n parsed = false;\n claimed = false;\n}\n\n/** The last `movmo_pnr` in the fragment (hash-router or bare), or null. */\nfunction readHashPnr(hash: string): string | null {\n if (hash.length <= 1) return null;\n const q = hash.lastIndexOf('?');\n const all = new URLSearchParams(hash.slice(q === -1 ? 1 : q + 1)).getAll('movmo_pnr');\n return all.length > 0 ? all[all.length - 1] : null;\n}\n\n/**\n * Remove the movmo_* return params from the address bar without adding a history entry.\n * String surgery keeps the partner's own query and hash byte for byte; no-op when nothing\n * would change.\n */\nfunction scrubUrl(): void {\n try {\n const { pathname, search, hash } = window.location;\n const cleanSearch = scrubQuery(search);\n const cleanHash = scrubHashPnr(hash);\n if (cleanSearch === search && cleanHash === hash) return;\n window.history.replaceState(window.history.state, '', `${pathname}${cleanSearch}${cleanHash}`);\n } catch {\n /* fail-open */\n }\n}\n\nfunction safely(label: string, fn: () => void): void {\n try {\n fn();\n } catch (err) {\n console.error(`[movmo] express checkout: ${label} callback threw`, err);\n }\n}\n\nfunction matchesPending(opts: MovmoCheckoutReturnOptions, pending: PendingCheckout): boolean {\n if (opts.iataCode && pending.airlineRef && opts.iataCode !== pending.airlineRef) return false;\n if (opts.providerID && pending.providerId && opts.providerID !== pending.providerId) return false;\n if (opts.offerId && pending.offerId && opts.offerId !== pending.offerId) return false;\n return true;\n}\n\n/**\n * Consume a return from Movmo checkout (MOVMO-549). Returns true when callbacks fired.\n *\n * Reads `movmo_exit`, `movmo_state`, `movmo_booking_id` from `location.search` and\n * `movmo_pnr` from `location.hash` (the PNR lives in the fragment so it is never sent to a\n * server or Referer). Callbacks run only when `movmo_state` matches the nonce stored at click\n * and this instance matches the button that started the checkout. These are unauthenticated\n * browser signals (the traveler can edit the URL): never fulfil or award anything from them.\n *\n * movmo_* params are scrubbed from the URL on the first call, with or without a return. Call\n * it as early as possible, before analytics or session-replay scripts read the URL.\n */\nexport function consumeMovmoCheckoutReturn(options?: MovmoCheckoutReturnOptions): boolean {\n if (typeof window === 'undefined' || claimed) return false;\n try {\n const opts = options ?? {};\n if (!parsed) {\n const params = new URLSearchParams(window.location.search);\n const exit = params.get('movmo_exit');\n if (exit === null) {\n scrubUrl(); // stale movmo_* leftovers; nothing to stash, so try again on a later call\n return false;\n }\n parsed = true;\n stash = {\n exit,\n state: params.get('movmo_state'),\n bookingId: params.get('movmo_booking_id'),\n pnr: readHashPnr(window.location.hash),\n };\n scrubUrl();\n }\n if (!stash) return false;\n\n const pending = readPending();\n // Two buttons on one page: leave the stash for the instance that started this checkout.\n if (pending && !matchesPending(opts, pending)) return false;\n const { exit, state, bookingId, pnr } = stash;\n stash = null;\n claimed = true;\n\n if (!pending || !state || state !== pending.state) {\n console.warn('[movmo] express checkout: ignoring return with unknown state');\n return false;\n }\n // Single use: clear before any callback runs, so a throwing or re-entrant callback cannot\n // replay the same return.\n clearPending();\n\n const reason: MovmoExitReason = (REASONS as readonly string[]).includes(exit)\n ? (exit as MovmoExitReason)\n : 'search_again';\n const airlineRef = pending.airlineRef ?? opts.iataCode;\n const providerId = pending.providerId ?? opts.providerID;\n\n if (reason === 'booking_confirmed' && bookingId) {\n const airlinePnr = pnr?.trim();\n const info: MovmoBookingCompleteInfo = {\n bookingId,\n ...(airlinePnr ? { airlinePnr } : {}),\n ...(airlineRef !== undefined ? { airlineRef } : {}),\n ...(providerId !== undefined ? { providerId } : {}),\n };\n const { onBookingComplete } = opts;\n if (onBookingComplete) safely('onBookingComplete', () => onBookingComplete(info));\n }\n const { onExit } = opts;\n if (onExit) safely('onExit', () => onExit({ reason }));\n\n // Init first: the tracker is otherwise only initialised by a button's mount effect, and a\n // page-level consumeReturn (no button) would drop the event. The environment comes from\n // the click-time record; without any known environment, do not guess (e2e on a prod page).\n const isProd = pending.isProd ?? opts.isProd;\n if (isProd !== undefined) initScopedTracker(airlineRef ?? '', isProd);\n trackSafe(EVENTS.CHECKOUT_RETURNED, { reason, ms_away: Date.now() - pending.startedAt });\n return true;\n } catch (err) {\n console.warn('[movmo] express checkout: could not process checkout return', err);\n return false;\n }\n}\n","import React, { useEffect, useRef, useState } from 'react';\n\nimport { createApiClient, saveProviderOffer } from './api';\nimport { buildCheckoutUrl, defaultReturnUrl, mintState, writePending } from './redirect';\nimport {\n consumeMovmoCheckoutReturn,\n MovmoBookingCompleteInfo,\n MovmoCheckoutExitInfo,\n} from './returnHandler';\nimport {\n EVENTS,\n initScopedTracker,\n trackSafe,\n trackerIsInternal,\n trackerSessionId,\n} from './tracking';\n\n/**\n * A user-facing failure the button could not recover from on its own (MOVMO-673).\n * `stage` is `'save_offer'` — the click-time raw-offer save failed (CORS from an\n * unregistered origin, a 4xx/5xx from the proxy, or a timeout) — or `'missing_offer'`\n * — neither `flightOfferID` nor `flightOffer` was provided. `status` is the HTTP\n * status when the failure was a non-2xx response; it is omitted for network errors,\n * timeouts, and the `missing_offer` stage. `message` prefers the backend's own JSON\n * `message`/`error` field, falling back to a generic error string.\n */\nexport type MovmoCheckoutError = {\n stage: 'save_offer' | 'missing_offer';\n status?: number;\n message: string;\n};\n\nexport interface MovmoCheckoutButtonProps {\n iataCode: string;\n apiKey: string;\n providerID: string;\n // TODO: support fare splitting\n flightOffer?: object;\n flightOfferID?: string;\n isProd?: boolean;\n className?: string;\n /**\n * Where Movmo sends the traveler back to. Defaults to the current page URL at click\n * with every `movmo_*` query param removed (other params and the hash are kept). Movmo\n * validates it against the airline's registered origins; an unregistered origin gets no\n * return link. The callbacks below fire on whichever page loads this button (or calls\n * `consumeMovmoCheckoutReturn`) at that URL.\n */\n returnUrl?: string;\n /**\n * Fires when the traveler comes back from the Movmo checkout (a full-page return to\n * `returnUrl`, verified against the state nonce minted at click). `info.reason` says\n * why: 'booking_confirmed' - the traveler booked and clicked \"Return to {airline}\";\n * 'offer_unavailable' - a dead-end screen's exit; 'search_again' - a non-retryable\n * failure or the header's \"Back to {airline}\". Use it to route the traveler onward.\n * Not invoked when the traveler never returns (browser back, closed tab).\n */\n onExit?: (info: MovmoCheckoutExitInfo) => void;\n /**\n * Fires once, on return, when the booking was confirmed, immediately BEFORE\n * `onExit({ reason: 'booking_confirmed' })`. `info.airlinePnr` is the airline's own\n * record locator (absent if the provider returned none; it travels only in the URL\n * fragment and is scrubbed on arrival); `info.airlineRef` is the airline IATA/company\n * code, not the PNR.\n */\n onBookingComplete?: (info: MovmoBookingCompleteInfo) => void;\n /**\n * Fires when the button hits a failure it cannot recover from on its own — the\n * click-time offer save failed, or neither `flightOfferID` nor `flightOffer` was\n * provided. The button already logs a `console.warn` and emits the matching\n * analytics event either way; this is for the partner page to react (e.g. show\n * its own error toast, or fall back to its native checkout). Additive — omitting\n * it preserves the console-only behavior.\n */\n onError?: (error: MovmoCheckoutError) => void;\n}\n\nconst HOVER_DWELL_MIN_MS = 200;\n\nexport const MovmoCheckoutButton: React.FC<MovmoCheckoutButtonProps> = ({\n iataCode,\n apiKey,\n providerID,\n flightOffer,\n flightOfferID,\n isProd = false,\n className,\n returnUrl,\n onExit,\n onBookingComplete,\n onError,\n}) => {\n const [isHovered, setIsHovered] = useState(false);\n const buttonRef = useRef<HTMLButtonElement>(null);\n const hoverStartRef = useRef<number | null>(null);\n const client = createApiClient(apiKey, iataCode, isProd);\n // Latest callbacks for the one-shot return consumption on mount.\n const returnOptions = {\n iataCode,\n providerID,\n isProd,\n offerId: flightOfferID,\n onExit,\n onBookingComplete,\n };\n const returnOptionsRef = useRef(returnOptions);\n returnOptionsRef.current = returnOptions;\n\n useEffect(() => {\n initScopedTracker(iataCode, isProd);\n if (typeof IntersectionObserver === 'undefined' || !buttonRef.current) return;\n const observer = new IntersectionObserver(\n (entries) => {\n if (entries.some((e) => e.isIntersecting)) {\n trackSafe(EVENTS.BUTTON_VIEWED);\n observer.disconnect(); // impression fires once per mount\n }\n },\n { threshold: 0.5 },\n );\n observer.observe(buttonRef.current);\n return () => observer.disconnect();\n }, []);\n\n // Declared AFTER the tracker-init effect on purpose: effects run in order, and the return\n // handler tracks checkout_returned through the tracker that effect initialises.\n useEffect(() => {\n consumeMovmoCheckoutReturn(returnOptionsRef.current);\n }, []);\n\n const handleMouseEnter = () => {\n setIsHovered(true);\n hoverStartRef.current = Date.now();\n };\n\n const handleMouseLeave = () => {\n setIsHovered(false);\n if (hoverStartRef.current !== null) {\n const dwell = Date.now() - hoverStartRef.current;\n hoverStartRef.current = null;\n if (dwell >= HOVER_DWELL_MIN_MS) trackSafe(EVENTS.BUTTON_HOVERED, { dwell_ms: dwell });\n }\n };\n\n const handleClick = async () => {\n // A click ends the \"hover consideration\" window. Without this, a user who clicks\n // without ever mousing away leaves hoverStartRef set from the original mouseenter;\n // a LATER mouseleave would then report a wildly inflated dwell_ms instead of being ignored.\n hoverStartRef.current = null;\n trackSafe(EVENTS.BUTTON_CLICKED);\n let offerId = flightOfferID;\n\n // If no pre-saved offer ID, save the raw offer\n if (!offerId && flightOffer) {\n trackSafe(EVENTS.OFFER_SAVE_STARTED);\n const startedAt = Date.now();\n const result = await saveProviderOffer(providerID, flightOffer, client);\n const latency = Date.now() - startedAt;\n if (!result.ok) {\n // Previously a silent return — a lost booking with zero trace (MOVMO-464).\n // MOVMO-673: also surface it to dev tools and, if wired, the partner page.\n trackSafe(EVENTS.OFFER_SAVE_FAILED, { latency_ms: latency });\n console.warn('[movmo] express checkout: offer save failed', {\n status: result.status,\n message: result.message,\n });\n onError?.({ stage: 'save_offer', status: result.status, message: result.message });\n return;\n }\n trackSafe(EVENTS.OFFER_SAVE_SUCCEEDED, { latency_ms: latency });\n offerId = result.offerId;\n }\n\n if (!offerId) {\n // Unconditional (not gated on onError being absent) so this stays visible in\n // dev tools by default, matching the save-failure branch above (MOVMO-673).\n console.warn('[movmo] express checkout: neither flightOfferID nor flightOffer was provided');\n onError?.({\n stage: 'missing_offer',\n message: 'neither flightOfferID nor flightOffer was provided',\n });\n return;\n }\n\n // Top-level redirect (MOVMO-549). The state nonce is echoed back as movmo_state and\n // checked against the pending record before any callback fires.\n const state = mintState();\n if (state) {\n writePending({\n state,\n offerId,\n startedAt: Date.now(),\n providerId: providerID,\n airlineRef: iataCode,\n isProd,\n });\n }\n const url = buildCheckoutUrl({\n offerId,\n providerId: providerID,\n airlineRef: iataCode,\n mvs: trackerSessionId(),\n internal: trackerIsInternal(),\n returnUrl: returnUrl ?? defaultReturnUrl(window.location.href),\n state,\n isProd,\n });\n trackSafe(EVENTS.CHECKOUT_REDIRECT_STARTED);\n window.location.assign(url);\n };\n\n // Every class here carries the package's Tailwind prefix (tailwind.config.js\n // `prefix: 'movmo-'`) so the shipped stylesheet can't collide with the host\n // page's CSS. The consumer-supplied `className` is deliberately NOT prefixed:\n // it is host-page CSS (e.g. the Clic demo passes its own Tailwind classes)\n // and must reach the DOM verbatim.\n // `movmo-checkout-button` is not a Tailwind utility: it carries the\n // hand-written keyboard focus ring in src/index.css (see the note there).\n const buttonClasses = `\n movmo-checkout-button\n movmo-px-7 movmo-py-5\n movmo-font-inter movmo-font-semibold movmo-text-lg\n movmo-rounded-xl\n movmo-text-white\n movmo-border-none\n movmo-cursor-pointer\n movmo-transition-all movmo-duration-200\n movmo-outline-none\n ${isHovered ? 'movmo-bg-gradient-hover' : 'movmo-bg-gradient-normal'}\n ${className ?? ''}\n `.trim();\n\n const badgeClasses = `\n movmo-ml-2 movmo-px-2 movmo-py-1\n movmo-bg-white\n movmo-text-[#171412]\n movmo-rounded-md\n movmo-text-lg\n `.trim();\n\n return (\n <button\n ref={buttonRef}\n onClick={handleClick}\n onMouseEnter={handleMouseEnter}\n onMouseLeave={handleMouseLeave}\n className={buttonClasses}\n >\n Express Checkout\n <span className={badgeClasses}>Movmo</span>\n </button>\n );\n};\n"],"names":["ALLOW_ENV_OVERRIDES","readEnv","name","proc","globalThis","process","value","env","undefined","readUrlOverride","raw","url","URL","username","password","host","hostname","toLowerCase","protocol","endsWith","isTrustedMovmoUrl","buildHeaders","apiKey","airlineRef","headers","Accept","window","location","proxyAuth","csrf","document","cookies","cookie","split","i","length","trim","startsWith","decodeURIComponent","substring","getCookie","scrubQuery","search","kept","slice","filter","seg","s","safeDecode","join","PNR_TOKEN","scrubHashPnr","hash","parts","out","carry","removedAny","delim","token","test","lead","PENDING_KEY","PROD_CHECKOUT_URL","E2E_CHECKOUT_URL","PENDING_TTL_MS","buildCheckoutUrl","params","qs","URLSearchParams","offerId","providerId","mvs","set","internal","returnUrl","state","isProd","override","replace","checkoutBaseUrl","toString","defaultReturnUrl","href","isRouteHash","origin","pathname","clearPending","sessionStorage","removeItem","initScopedTracker","iataCode","Movmo","isInitialized","endpoint","init","app","partnerId","scoped","track","EVENTS","PLUGIN_LOADED","trackSafe","event","props","trackerSessionId","getSessionId","trackerIsInternal","isInternal","REASONS","stash","parsed","claimed","readHashPnr","q","lastIndexOf","all","getAll","scrubUrl","cleanSearch","cleanHash","history","replaceState","safely","label","fn","err","consumeMovmoCheckoutReturn","options","opts","exit","get","bookingId","pnr","pending","getItem","v","JSON","parse","startedAt","Date","now","readPending","providerID","matchesPending","reason","includes","airlinePnr","info","onBookingComplete","onExit","CHECKOUT_RETURNED","ms_away","MovmoCheckoutButton","flightOffer","flightOfferID","className","onError","isHovered","setIsHovered","useState","buttonRef","useRef","hoverStartRef","client","baseUrl","proxyBaseUrl","post","path","body","controller","AbortController","timer","setTimeout","abort","response","fetch","method","stringify","credentials","signal","ok","errorBody","json","Object","assign","Error","status","statusText","clearTimeout","createApiClient","returnOptions","returnOptionsRef","current","useEffect","IntersectionObserver","observer","entries","some","e","isIntersecting","BUTTON_VIEWED","disconnect","threshold","observe","buttonClasses","badgeClasses","_jsxs","ref","onClick","async","BUTTON_CLICKED","OFFER_SAVE_STARTED","result","rawOffer","data","offer_id","message","error","nestedMessage","messageFromBody","String","cause","saveProviderOffer","latency","OFFER_SAVE_FAILED","latency_ms","stage","OFFER_SAVE_SUCCEEDED","c","crypto","randomUUID","getRandomValues","bytes","Uint8Array","Array","from","b","padStart","mintState","setItem","writePending","CHECKOUT_REDIRECT_STARTED","onMouseEnter","onMouseLeave","dwell","BUTTON_HOVERED","dwell_ms","children","_jsx"],"mappings":";;;;;;uKAMO,MAAMA,GACuC,EAe9C,SAAUC,EAAQC,GAEtB,IACE,MAAMC,EAAQC,WAA+DC,QACvEC,EAAQH,GAAMI,MAAML,GAC1B,MAAwB,iBAAVI,GAAgC,KAAVA,EAAeA,OAAQE,CAC7D,CAAE,MACA,MACF,CACF,CAoBM,SAAUC,EAAgBP,GAC9B,MAAMI,EAAQL,EAAQC,GACtB,QAAcM,IAAVF,EACJ,OAjBI,SAA4BI,GAChC,IACE,MAAMC,EAAM,IAAIC,IAAIF,GACpB,GAAIC,EAAIE,UAAYF,EAAIG,SAAU,OAAO,EACzC,MAAMC,EAAOJ,EAAIK,SAASC,cAC1B,MAAqB,WAAjBN,EAAIO,SAAuC,aAATH,GAAuBA,EAAKI,SAAS,aACtD,UAAjBR,EAAIO,WAAsC,cAATH,GAAiC,cAATA,EAE/D,CAAE,MACA,OAAO,CACT,CACF,CAMMK,CAAkBd,GAAeA,OAArC,CAGF,CC7CA,MAmCMe,EAAe,CAACC,EAAgBC,KACpC,MAAMC,EAAkC,CACtCC,OAAQ,mBACR,eAAgB,mBAChB,YAAaH,EACb,mBAAsC,oBAAXI,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,GAAID,GAA6B,mBAAjBA,EAAEE,WAA2B,OAAOF,EAAEE,aACtD,GAAIF,GAAkC,mBAAtBA,EAAEG,gBAAgC,CAChD,MAAMC,EAAQJ,EAAEG,gBAAgB,IAAIE,WAAW,KAC/C,OAAOC,MAAMC,KAAKH,GAAQI,GAAMA,EAAE5J,SAAS,IAAI6J,SAAS,EAAG,OAAM5L,KAAK,GACxE,CACF,CAAE,MAEF,CACA,OAAO,IACT,CG8FkB6L,GACVnK,GH7FF,SAAuB0D,GAC3B,IACE9C,eAAewJ,QAAQlL,EAAa2E,KAAKyC,UAAU5C,GACrD,CAAE,MAEF,CACF,CGwFM2G,CAAa,CACXrK,QACAN,UACAqE,UAAWC,KAAKC,MAChBtE,WAAYwE,EACZvH,WAAYmE,EACZd,WAGJ,MAAMjE,EAAMsD,EAAiB,CAC3BI,UACAC,WAAYwE,EACZvH,WAAYmE,EACZnB,IAAKiC,IACL/B,SAAUiC,IACVhC,UAAWA,GAAaO,EAAiBvD,OAAOC,SAASuD,MACzDP,QACAC,WAEFyB,EAAUF,EAAO8I,2BACjBvN,OAAOC,SAAS6J,OAAO7K,EAAI,EAoCzBuO,aAlHqB,KACvBpF,GAAa,GACbI,EAAc8B,QAAUrD,KAAKC,KAAK,EAiHhCuG,aA9GqB,KAEvB,GADArF,GAAa,GACiB,OAA1BI,EAAc8B,QAAkB,CAClC,MAAMoD,EAAQzG,KAAKC,MAAQsB,EAAc8B,QACzC9B,EAAc8B,QAAU,KACpBoD,GA/DiB,KA+DY/I,EAAUF,EAAOkJ,eAAgB,CAAEC,SAAUF,GAChF,GAyGEzF,UAAWiD,EAAa2C,SAAA,CAAA,mBAGxBC,EAAA,OAAA,CAAM7F,UAAWkD,EAAY0C,SAAA,YACtB"}
|
|
1
|
+
{"version":3,"file":"index.es.js","sources":["../src/env.ts","../src/api.ts","../src/urlScrub.ts","../src/redirect.ts","../src/tracking.ts","../src/returnHandler.ts","../src/MovmoCheckoutButton.tsx"],"sourcesContent":["// Replaced at build time: `false` in the UMD bundle (a script-tag SDK must not honour\n// page-controllable overrides), `true` in the ESM/CJS builds and under Vitest. The typeof guard\n// keeps an unreplaced source import (tsc, Storybook) working.\ndeclare const __ALLOW_ENV_OVERRIDES__: boolean;\n\n/** Whether build-time environment overrides are honoured at all (false in the UMD build). */\nexport const ALLOW_ENV_OVERRIDES: boolean =\n typeof __ALLOW_ENV_OVERRIDES__ === 'undefined' || __ALLOW_ENV_OVERRIDES__;\n\n/**\n * Reads a build-time environment override without assuming a `process` global. ESM/CJS builds\n * only: the value is read at runtime from `process.env` (the consuming bundler's define), never\n * inlined by this package, and the UMD build compiles overrides out entirely.\n *\n * Create React App inlines `process.env.REACT_APP_*`; Vite, Parcel, esbuild, Remix/Astro\n * on Vite and plain `<script type=\"module\">` pages have no `process` in the browser, and a\n * bare `process.env.X` read throws `ReferenceError: process is not defined` at mount — which\n * unmounts the host page's whole tree. Always read overrides through this helper.\n *\n * Only a non-empty string is returned: markup that clobbers `window.process` (DOM clobbering)\n * can make `process.env.X` an element or object, which must never reach a URL.\n */\nexport function readEnv(name: string): string | undefined {\n if (!ALLOW_ENV_OVERRIDES) return undefined;\n try {\n const proc = (globalThis as { process?: { env?: Record<string, unknown> } }).process;\n const value = proc?.env?.[name];\n return typeof value === 'string' && value !== '' ? value : undefined;\n } catch {\n return undefined;\n }\n}\n\n/**\n * True for `https://movmo.io`, `https://*.movmo.io`, and `http://localhost[:port]` /\n * `http://127.0.0.1[:port]` (local development). No credentials in the URL.\n */\nexport function isTrustedMovmoUrl(raw: string): boolean {\n try {\n const url = new URL(raw);\n if (url.username || url.password) return false;\n const host = url.hostname.toLowerCase();\n if (url.protocol === 'https:') return host === 'movmo.io' || host.endsWith('.movmo.io');\n if (url.protocol === 'http:') return host === 'localhost' || host === '127.0.0.1';\n return false;\n } catch {\n return false;\n }\n}\n\n/** A URL override that passes {@link isTrustedMovmoUrl}; anything else is ignored. */\nexport function readUrlOverride(name: string): string | undefined {\n const value = readEnv(name);\n if (value === undefined) return undefined;\n if (isTrustedMovmoUrl(value)) return value;\n console.warn(`[movmo] express checkout: ignoring untrusted ${name} override`);\n return undefined;\n}\n","import { ALLOW_ENV_OVERRIDES, readEnv, readUrlOverride } from './env';\n/**\n * Minimal JSON POST client for the Movmo checkout proxy.\n *\n * Replaces axios (MOVMO-517) — the package's only runtime HTTP dependency,\n * ~14 KB gzip of the UMD bundle. Deliberately NOT a general-purpose HTTP\n * client: one method, one content type, one caller (`saveProviderOffer`).\n */\nexport interface ApiClient {\n post<T>(path: string, body: unknown): Promise<T>;\n}\n\nconst REQUEST_TIMEOUT_MS = 30_000;\n\n// Helper function to read cookie value from document.cookie\nconst getCookie = (name: string): string | null => {\n if (typeof document === 'undefined') return null;\n const cookies = document.cookie.split(';');\n for (let i = 0; i < cookies.length; i++) {\n const cookie = cookies[i].trim();\n if (cookie.startsWith(name + '=')) {\n // URL-decode the cookie value to match what backend expects\n return decodeURIComponent(cookie.substring(name.length + 1));\n }\n }\n return null;\n};\n\nconst isLocalHost = () =>\n typeof window !== 'undefined' &&\n (window.location.hostname === 'localhost' || window.location.hostname === '127.0.0.1');\n\n/**\n * Built fresh for EVERY request, not once per client:\n * - the CSRF cookie is set by the proxy during the session and can change\n * between the button rendering and the traveler clicking — the old axios\n * request interceptor re-read it per request for exactly this reason;\n * - X-Forwarded-Host now reflects the page's host at send time too (axios\n * baked it in at client creation).\n *\n * The axios interceptor also deleted any inherited `Authorization` header.\n * That mattered because axios was resolved from the PARTNER's node_modules\n * in the React build, so `axios.create()` inherited their global\n * `axios.defaults.headers` — a partner-wide bearer token would otherwise\n * have been forwarded to Movmo's proxy. `fetch` has no shared defaults, so\n * that defence now holds by construction; do not \"restore\" it.\n */\nconst buildHeaders = (apiKey: string, airlineRef: string): Record<string, string> => {\n const headers: Record<string, string> = {\n Accept: 'application/json',\n 'Content-Type': 'application/json',\n 'x-api-key': apiKey,\n 'X-Forwarded-Host': typeof window !== 'undefined' ? window.location.host : '',\n 'movmo-customer-id': airlineRef,\n };\n\n // Overrides are compiled out of the UMD build (ALLOW_ENV_OVERRIDES is false there).\n const proxyAuth = ALLOW_ENV_OVERRIDES\n ? readEnv('REACT_APP_CLOUD_FRONT_PROXY_SECRET_HEADER')\n : undefined;\n if (isLocalHost() && proxyAuth) {\n headers['X-Movmo-Proxy-Auth'] = proxyAuth;\n }\n\n const csrf = getCookie('movmo_csrf_token');\n if (csrf) {\n headers['X-CSRF-Token'] = csrf;\n }\n\n return headers;\n};\n\nexport const createApiClient = (\n apiKey: string,\n airlineRef: string,\n isProd: boolean = false,\n): ApiClient => {\n const baseUrl = isProd ? 'https://flights.movmo.io' : 'https://flights.e2e.movmo.io';\n // REACT_APP_MOVMO_CHECKOUT_API_URL overrides the API base (e.g. the offline demo\n // talks directly to the local monolith-api at http://localhost:8080, bypassing the\n // CloudFront /v1/proxy hop). Only a movmo.io or localhost URL is accepted; anything else falls back to the default.\n const apiOverride = ALLOW_ENV_OVERRIDES\n ? readUrlOverride('REACT_APP_MOVMO_CHECKOUT_API_URL')\n : undefined;\n const proxyBaseUrl = apiOverride || `${baseUrl}/v1/proxy`;\n\n return {\n async post<T>(path: string, body: unknown): Promise<T> {\n // axios `baseURL` semantics: the base PATH is preserved and the request\n // path appended → .../v1/proxy/v1/flights/... . `new URL(path, base)`\n // would resolve the leading slash against the ORIGIN and silently drop\n // /v1/proxy, bypassing the CloudFront hop. Do not \"simplify\" this.\n const url = `${proxyBaseUrl.replace(/\\/+$/, '')}/${path.replace(/^\\/+/, '')}`;\n\n // AbortController + setTimeout rather than AbortSignal.timeout(): the\n // latter is Safari 16+ only, and this ships to partner pages with no\n // control over the traveler's browser.\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS);\n\n try {\n const response = await fetch(url, {\n method: 'POST',\n headers: buildHeaders(apiKey, airlineRef),\n body: JSON.stringify(body),\n // Cross-site call: without this the Movmo session + CSRF cookies are\n // never sent and the proxy rejects the save (axios: withCredentials).\n credentials: 'include',\n signal: controller.signal,\n });\n\n // axios rejected on non-2xx by default; fetch resolves. Keep rejecting, but\n // now carry the status + parsed body along on the thrown Error so callers\n // (saveProviderOffer, MOVMO-673) can surface a status code and a backend\n // message instead of only a generic string.\n if (!response.ok) {\n let errorBody: unknown;\n try {\n errorBody = await response.json();\n } catch {\n // Non-JSON or empty error body — errorBody stays undefined, message\n // falls back to the generic string below.\n }\n throw Object.assign(\n new Error(\n `Movmo API request failed: ${response.status} ${response.statusText} (${path})`,\n ),\n { status: response.status, body: errorBody },\n );\n }\n\n return (await response.json()) as T;\n } finally {\n // Always clear, including on the success path — otherwise every save\n // leaves a 30 s timer behind.\n clearTimeout(timer);\n }\n },\n };\n};\n\n/**\n * Discriminated result of {@link saveProviderOffer} (MOVMO-673). Replaces the earlier\n * `string | null` contract so the button (and, via `onError`, the partner page) can\n * surface WHY a save failed — an HTTP status when the response was non-2xx, and a\n * message that prefers the backend's own JSON `message`/`error` field over a generic\n * fetch/timeout string.\n */\nexport type SaveOfferResult =\n | { ok: true; offerId: string }\n | { ok: false; status?: number; message: string; cause?: unknown };\n\n// Shape of a typical backend error body: a top-level { message: \"...\" }, a string\n// { error: \"...\" }, or go-services-core's nested { error: { message, status_code,\n// is_retryable } } (the shape a rejected-offer 400 actually sends). All three are\n// checked since different endpoints/providers use different conventions.\nconst messageFromBody = (body: unknown): string | undefined => {\n if (!body || typeof body !== 'object') return undefined;\n const { message, error } = body as { message?: unknown; error?: unknown };\n if (typeof message === 'string' && message) return message;\n if (typeof error === 'string' && error) return error;\n if (error && typeof error === 'object') {\n const nestedMessage = (error as { message?: unknown }).message;\n if (typeof nestedMessage === 'string' && nestedMessage) return nestedMessage;\n }\n return undefined;\n};\n\nexport const saveProviderOffer = async (\n providerID: string,\n rawOffer: object,\n client: ApiClient,\n): Promise<SaveOfferResult> => {\n try {\n const data = await client.post<{ offer_id?: string }>(\n `/v1/flights/providers/${providerID}/offers`,\n rawOffer,\n );\n if (!data?.offer_id) {\n const message = 'no offer_id in response';\n console.error(message);\n return { ok: false, message };\n }\n return { ok: true, offerId: data.offer_id };\n } catch (err) {\n // MOVMO-464 contract: never throw into the click handler. Resolving an `ok:\n // false` result is what makes the button emit OFFER_SAVE_FAILED (and, since\n // MOVMO-673, call onError) instead of dying silently.\n console.error(err);\n const status = (err as { status?: number } | undefined)?.status;\n const body = (err as { body?: unknown } | undefined)?.body;\n const message = messageFromBody(body) ?? (err instanceof Error ? err.message : String(err));\n return { ok: false, status, message, cause: err };\n }\n};\n","/**\n * String-level URL surgery (no URLSearchParams round trip), so the partner's own query and\n * hash survive byte for byte: `?q=a%20b&next=/x/y&flag` stays exactly that.\n */\n\nfunction safeDecode(s: string): string {\n try {\n return decodeURIComponent(s);\n } catch {\n return s;\n }\n}\n\n/** Remove every `movmo_*` key from a `?query` string; returns '' when nothing is left. */\nexport function scrubQuery(search: string): string {\n if (search.length <= 1) return search === '?' ? '' : search;\n const kept = search\n .slice(1)\n .split('&')\n .filter((seg) => !safeDecode(seg.split('=')[0]).startsWith('movmo_'));\n return kept.length > 0 ? `?${kept.join('&')}` : '';\n}\n\n/** The query params Movmo's checkout return carries; the only ones the return handler removes. */\nexport const RETURN_QUERY_KEYS: readonly string[] = [\n 'movmo_exit',\n 'movmo_state',\n 'movmo_booking_id',\n 'movmo_pnr',\n];\n\n/**\n * Remove ONLY the named keys from a `?query` string (decoded-name match), leaving every other\n * segment, including other `movmo_*` keys such as connect-button's `movmo_signed_out` /\n * `movmo_logout_state`, byte for byte. Returns '' when nothing is left.\n */\nexport function scrubQueryKeys(search: string, keys: readonly string[]): string {\n if (search.length <= 1) return search === '?' ? '' : search;\n const segs = search.slice(1).split('&');\n const kept = segs.filter((seg) => !keys.includes(safeDecode(seg.split('=')[0])));\n if (kept.length === segs.length) return search;\n return kept.length > 0 ? `?${kept.join('&')}` : '';\n}\n\nconst PNR_TOKEN = /^movmo_pnr(?:=.*)?$/;\n\n/**\n * Remove every `movmo_pnr=` segment from a `#fragment`, whatever delimiter (`?` or `&`)\n * precedes it: `#movmo_pnr=A&movmo_pnr=B`, `#movmo_pnr=OLD?movmo_pnr=NEW`, `#/r?a=1&movmo_pnr=X`.\n * Returns '' (no hash) when nothing is left.\n */\nexport function scrubHashPnr(hash: string): string {\n if (hash.length <= 1) return '';\n const parts = hash.slice(1).split(/([?&])/); // token, delim, token, delim, ...\n let out = '';\n let carry: string | null = null; // leading delimiter of the first removed token in a run\n let removedAny = false;\n for (let i = 0; i < parts.length; i += 2) {\n const delim = i === 0 ? '' : parts[i - 1];\n const token = parts[i];\n if (PNR_TOKEN.test(token)) {\n removedAny = true;\n if (carry === null) carry = delim;\n continue;\n }\n let lead = delim;\n if (carry !== null) {\n // `?` (or nothing) before a removed run is inherited by the next kept token.\n if (carry === '' || carry === '?') lead = out === '' ? '' : carry;\n carry = null;\n }\n out += lead + token;\n }\n if (!removedAny) return hash;\n return out === '' ? '' : `#${out}`;\n}\n\n/** True when the fragment looks like a router route (`#/x`, `#!/x`) rather than an anchor or data. */\nexport function isRouteHash(hash: string): boolean {\n return /^#!?\\//.test(hash);\n}\n","import { ALLOW_ENV_OVERRIDES, readUrlOverride } from './env';\nimport { isRouteHash, scrubHashPnr, scrubQuery } from './urlScrub';\n\n/** sessionStorage key holding the pending-return record on the partner origin. */\nexport const PENDING_KEY = 'movmo:checkout:pending';\n\nconst PROD_CHECKOUT_URL = 'https://flights.movmo.io';\nconst E2E_CHECKOUT_URL = 'https://flights.e2e.movmo.io';\n\n/** What the button remembers across the top-level navigation to Movmo and back. */\nexport interface PendingCheckout {\n state: string;\n offerId: string;\n startedAt: number;\n /** Stored at click so the return is attributed to the button that started it. */\n providerId?: string;\n airlineRef?: string;\n /** Environment the button was mounted with; selects the analytics collector on return. */\n isProd?: boolean;\n}\n\n/** A pending record older than this is ignored (an abandoned checkout, or a stale tab). */\nexport const PENDING_TTL_MS = 24 * 60 * 60 * 1000;\n\nexport interface BuildCheckoutUrlParams {\n offerId: string;\n providerId: string;\n /** Airline IATA code, sent as `airlineRef`. */\n airlineRef: string;\n /** Partner analytics session id (`mvs`), when the tracker has one. */\n mvs?: string | null;\n internal?: boolean;\n returnUrl: string;\n /** Omitted only when the platform has no crypto at all. */\n state?: string | null;\n isProd: boolean;\n}\n\n/** Checkout origin: the build-time override, else prod or e2e. Path routing, not a hash route. */\nexport function checkoutBaseUrl(isProd: boolean): string {\n // Validated: an override must be a movmo.io (or localhost) URL, and UMD compiles it out.\n const override = ALLOW_ENV_OVERRIDES\n ? readUrlOverride('REACT_APP_MOVMO_CHECKOUT_URL')\n : undefined;\n if (override) return override.replace(/\\/+$/, '');\n return isProd ? PROD_CHECKOUT_URL : E2E_CHECKOUT_URL;\n}\n\nexport function buildCheckoutUrl(params: BuildCheckoutUrlParams): string {\n const qs = new URLSearchParams({\n offerId: params.offerId,\n providerId: params.providerId,\n airlineRef: params.airlineRef,\n });\n // Session stitching (MOVMO-464): flights-ui adopts mvs so button_viewed -> booking_confirmed\n // joins as one session. mv_internal keeps QA/demo traffic flagged (MOVMO-478).\n if (params.mvs) qs.set('mvs', params.mvs);\n if (params.internal) qs.set('mv_internal', '1');\n qs.set('returnUrl', params.returnUrl);\n if (params.state) qs.set('state', params.state);\n return `${checkoutBaseUrl(params.isProd)}/booking?${qs.toString()}`;\n}\n\n/**\n * The return URL sent to Movmo (it lands in CloudFront logs): the current page URL with every\n * `movmo_*` query param removed. The other params are kept. The fragment is kept only when it\n * looks like a router route (`#/` or `#!/`), and then without any `movmo_pnr`; any other\n * fragment (anchors, tokens, partner data) is dropped.\n */\nexport function defaultReturnUrl(href: string): string {\n const url = new URL(href);\n const hash = isRouteHash(url.hash) ? scrubHashPnr(url.hash) : '';\n return `${url.origin}${url.pathname}${scrubQuery(url.search)}${hash}`;\n}\n\n/**\n * Random nonce echoed back as `movmo_state`. `crypto.randomUUID()`, else 16 random bytes as\n * hex. With no crypto at all returns null: the redirect still happens without `state`, and the\n * return is then not verifiable, so the SDK ignores it (fails closed on the callback side).\n */\nexport function mintState(): string | null {\n try {\n const c = (globalThis as { crypto?: Crypto }).crypto;\n if (c && typeof c.randomUUID === 'function') return c.randomUUID();\n if (c && typeof c.getRandomValues === 'function') {\n const bytes = c.getRandomValues(new Uint8Array(16));\n return Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('');\n }\n } catch {\n /* fall through */\n }\n return null;\n}\n\nexport function writePending(pending: PendingCheckout): void {\n try {\n sessionStorage.setItem(PENDING_KEY, JSON.stringify(pending));\n } catch {\n /* fail-open: storage blocked or unavailable */\n }\n}\n\nexport function readPending(): PendingCheckout | null {\n try {\n const raw = sessionStorage.getItem(PENDING_KEY);\n if (!raw) return null;\n const v = JSON.parse(raw) as Partial<PendingCheckout> | null;\n if (\n v &&\n typeof v.state === 'string' &&\n v.state !== '' &&\n typeof v.offerId === 'string' &&\n typeof v.startedAt === 'number'\n ) {\n if (Date.now() - v.startedAt > PENDING_TTL_MS) {\n clearPending();\n return null;\n }\n return {\n state: v.state,\n offerId: v.offerId,\n startedAt: v.startedAt,\n ...(typeof v.providerId === 'string' ? { providerId: v.providerId } : {}),\n ...(typeof v.airlineRef === 'string' ? { airlineRef: v.airlineRef } : {}),\n ...(typeof v.isProd === 'boolean' ? { isProd: v.isProd } : {}),\n };\n }\n } catch {\n /* fall through */\n }\n return null;\n}\n\nexport function clearPending(): void {\n try {\n sessionStorage.removeItem(PENDING_KEY);\n } catch {\n /* fail-open */\n }\n}\n","import { EVENTS, Movmo } from '@movmo_app/analytics';\nimport { ALLOW_ENV_OVERRIDES, readUrlOverride } from './env';\n\nexport { EVENTS };\n\n/**\n * Scoped-mode analytics for the partner page (MOVMO-464). Autocapture stays OFF —\n * we never observe the partner's DOM or inputs; listeners attach only to\n * Movmo-rendered elements. Analytics must never break checkout: every entry\n * point here is fail-open.\n */\nexport function initScopedTracker(iataCode: string, isProd: boolean): void {\n try {\n if (Movmo.isInitialized()) return;\n // Same validated, ESM/CJS-only override mechanism as REACT_APP_MOVMO_CHECKOUT_URL.\n const endpoint =\n (ALLOW_ENV_OVERRIDES ? readUrlOverride('REACT_APP_MOVMO_ANALYTICS_URL') : undefined) ||\n (isProd ? 'https://api.movmo.io/v1/t' : 'https://e2e.api.movmo.io/v1/t');\n Movmo.init({\n app: 'express-checkout-button',\n env: isProd ? 'prd' : 'e2e',\n partnerId: iataCode,\n endpoint,\n scoped: true,\n });\n Movmo.track(EVENTS.PLUGIN_LOADED);\n } catch {\n /* fail-open */\n }\n}\n\nexport function trackSafe(event: string, props: Record<string, unknown> = {}): void {\n try {\n Movmo.track(event, props);\n } catch {\n /* fail-open */\n }\n}\n\nexport function trackerSessionId(): string | null {\n try {\n return Movmo.getSessionId();\n } catch {\n return null;\n }\n}\n\n/** Whether the partner-page session is flagged internal/QA/demo traffic (MOVMO-478). */\nexport function trackerIsInternal(): boolean {\n try {\n return Movmo.isInternal();\n } catch {\n return false;\n }\n}\n","import type { MovmoExitReason } from '@movmo_app/types';\n\nimport { clearPending, PendingCheckout, readPending } from './redirect';\nimport { EVENTS, initScopedTracker, trackSafe } from './tracking';\nimport { RETURN_QUERY_KEYS, scrubHashPnr, scrubQueryKeys } from './urlScrub';\n\n/** Passed to the airline's onExit callback when the traveler returns from Movmo. */\nexport interface MovmoCheckoutExitInfo {\n reason: MovmoExitReason;\n}\n\n/** Passed to onBookingComplete when the traveler returns from a confirmed booking. */\nexport interface MovmoBookingCompleteInfo {\n bookingId: string;\n /** Record locator (PNR) in the airline's own reservation system. Absent if the provider returned none. */\n airlinePnr?: string;\n /** Airline IATA / company code, not the PNR. */\n airlineRef?: string;\n providerId?: string;\n}\n\nexport interface MovmoCheckoutReturnOptions {\n /**\n * The button's identity. When given, an instance only claims a return whose pending record\n * (written at click) matches; a page-level `consumeReturn()` omits them and claims whatever\n * is pending, taking the values from the record.\n */\n iataCode?: string;\n providerID?: string;\n /** The pre-saved offer id, when known, to tell two buttons with the same airline apart. */\n offerId?: string;\n /**\n * Analytics environment, used only when the pending record does not carry one. When neither\n * is known the tracker is not initialised here.\n */\n isProd?: boolean;\n onExit?: (info: MovmoCheckoutExitInfo) => void;\n onBookingComplete?: (info: MovmoBookingCompleteInfo) => void;\n}\n\nconst REASONS: readonly MovmoExitReason[] = [\n 'search_again',\n 'offer_unavailable',\n 'booking_confirmed',\n];\n\ninterface ReturnStash {\n exit: string;\n state: string | null;\n bookingId: string | null;\n pnr: string | null;\n}\n\n// The return is parsed and scrubbed from the URL on the FIRST call, then held here until an\n// instance whose identity matches the pending record claims it (two buttons on one page).\nlet stash: ReturnStash | null = null;\nlet parsed = false;\nlet claimed = false;\n\n/** @internal Test hook: forget any parsed or claimed return. Not exported from the package entry. */\nexport function __resetForTests(): void {\n stash = null;\n parsed = false;\n claimed = false;\n}\n\n/** The last `movmo_pnr` in the fragment (hash-router or bare), or null. */\nfunction readHashPnr(hash: string): string | null {\n if (hash.length <= 1) return null;\n const q = hash.lastIndexOf('?');\n const all = new URLSearchParams(hash.slice(q === -1 ? 1 : q + 1)).getAll('movmo_pnr');\n return all.length > 0 ? all[all.length - 1] : null;\n}\n\n/**\n * Remove ONLY this SDK's return params (`movmo_exit`, `movmo_state`, `movmo_booking_id`, plus\n * `movmo_pnr` in the hash) from the address bar without adding a history entry.\n * String surgery keeps the partner's own query and hash byte for byte; no-op when nothing\n * would change.\n */\nfunction scrubUrl(): void {\n try {\n const { pathname, search, hash } = window.location;\n const cleanSearch = scrubQueryKeys(search, RETURN_QUERY_KEYS);\n const cleanHash = scrubHashPnr(hash);\n if (cleanSearch === search && cleanHash === hash) return;\n window.history.replaceState(window.history.state, '', `${pathname}${cleanSearch}${cleanHash}`);\n } catch {\n /* fail-open */\n }\n}\n\nfunction safely(label: string, fn: () => void): void {\n try {\n fn();\n } catch (err) {\n console.error(`[movmo] express checkout: ${label} callback threw`, err);\n }\n}\n\nfunction matchesPending(opts: MovmoCheckoutReturnOptions, pending: PendingCheckout): boolean {\n if (opts.iataCode && pending.airlineRef && opts.iataCode !== pending.airlineRef) return false;\n if (opts.providerID && pending.providerId && opts.providerID !== pending.providerId) return false;\n if (opts.offerId && pending.offerId && opts.offerId !== pending.offerId) return false;\n return true;\n}\n\n/**\n * Consume a return from Movmo checkout (MOVMO-549). Returns true when callbacks fired.\n *\n * Reads `movmo_exit`, `movmo_state`, `movmo_booking_id` from `location.search` and\n * `movmo_pnr` from `location.hash` (the PNR lives in the fragment so it is never sent to a\n * server or Referer). Callbacks run only when `movmo_state` matches the nonce stored at click\n * and this instance matches the button that started the checkout. These are unauthenticated\n * browser signals (the traveler can edit the URL): never fulfil or award anything from them.\n *\n * Only this SDK's own params are scrubbed from the URL (never connect-button's\n * `movmo_signed_out` / `movmo_logout_state`), on the first call, with or without a return. Call\n * it as early as possible, before analytics or session-replay scripts read the URL.\n */\nexport function consumeMovmoCheckoutReturn(options?: MovmoCheckoutReturnOptions): boolean {\n if (typeof window === 'undefined' || claimed) return false;\n try {\n const opts = options ?? {};\n if (!parsed) {\n const params = new URLSearchParams(window.location.search);\n const exit = params.get('movmo_exit');\n if (exit === null) {\n scrubUrl(); // stale movmo_* leftovers; nothing to stash, so try again on a later call\n return false;\n }\n parsed = true;\n stash = {\n exit,\n state: params.get('movmo_state'),\n bookingId: params.get('movmo_booking_id'),\n pnr: readHashPnr(window.location.hash),\n };\n scrubUrl();\n }\n if (!stash) return false;\n\n const pending = readPending();\n // Two buttons on one page: leave the stash for the instance that started this checkout.\n if (pending && !matchesPending(opts, pending)) return false;\n const { exit, state, bookingId, pnr } = stash;\n stash = null;\n claimed = true;\n\n if (!pending || !state || state !== pending.state) {\n console.warn('[movmo] express checkout: ignoring return with unknown state');\n return false;\n }\n // Single use: clear before any callback runs, so a throwing or re-entrant callback cannot\n // replay the same return.\n clearPending();\n\n const reason: MovmoExitReason = (REASONS as readonly string[]).includes(exit)\n ? (exit as MovmoExitReason)\n : 'search_again';\n const airlineRef = pending.airlineRef ?? opts.iataCode;\n const providerId = pending.providerId ?? opts.providerID;\n\n if (reason === 'booking_confirmed' && bookingId) {\n const airlinePnr = pnr?.trim();\n const info: MovmoBookingCompleteInfo = {\n bookingId,\n ...(airlinePnr ? { airlinePnr } : {}),\n ...(airlineRef !== undefined ? { airlineRef } : {}),\n ...(providerId !== undefined ? { providerId } : {}),\n };\n const { onBookingComplete } = opts;\n if (onBookingComplete) safely('onBookingComplete', () => onBookingComplete(info));\n }\n const { onExit } = opts;\n if (onExit) safely('onExit', () => onExit({ reason }));\n\n // Init first: the tracker is otherwise only initialised by a button's mount effect, and a\n // page-level consumeReturn (no button) would drop the event. The environment comes from\n // the click-time record; without any known environment, do not guess (e2e on a prod page).\n const isProd = pending.isProd ?? opts.isProd;\n if (isProd !== undefined) initScopedTracker(airlineRef ?? '', isProd);\n trackSafe(EVENTS.CHECKOUT_RETURNED, { reason, ms_away: Date.now() - pending.startedAt });\n return true;\n } catch (err) {\n console.warn('[movmo] express checkout: could not process checkout return', err);\n return false;\n }\n}\n","import React, { useEffect, useRef, useState } from 'react';\n\nimport { createApiClient, saveProviderOffer } from './api';\nimport { buildCheckoutUrl, defaultReturnUrl, mintState, writePending } from './redirect';\nimport {\n consumeMovmoCheckoutReturn,\n MovmoBookingCompleteInfo,\n MovmoCheckoutExitInfo,\n} from './returnHandler';\nimport {\n EVENTS,\n initScopedTracker,\n trackSafe,\n trackerIsInternal,\n trackerSessionId,\n} from './tracking';\n\n/**\n * A user-facing failure the button could not recover from on its own (MOVMO-673).\n * `stage` is `'save_offer'` — the click-time raw-offer save failed (CORS from an\n * unregistered origin, a 4xx/5xx from the proxy, or a timeout) — or `'missing_offer'`\n * — neither `flightOfferID` nor `flightOffer` was provided. `status` is the HTTP\n * status when the failure was a non-2xx response; it is omitted for network errors,\n * timeouts, and the `missing_offer` stage. `message` prefers the backend's own JSON\n * `message`/`error` field, falling back to a generic error string.\n */\nexport type MovmoCheckoutError = {\n stage: 'save_offer' | 'missing_offer';\n status?: number;\n message: string;\n};\n\nexport interface MovmoCheckoutButtonProps {\n iataCode: string;\n apiKey: string;\n providerID: string;\n // TODO: support fare splitting\n flightOffer?: object;\n flightOfferID?: string;\n isProd?: boolean;\n className?: string;\n /**\n * Where Movmo sends the traveler back to. Defaults to the current page URL at click\n * with every `movmo_*` query param removed (other params and the hash are kept). Movmo\n * validates it against the airline's registered origins; an unregistered origin gets no\n * return link. The callbacks below fire on whichever page loads this button (or calls\n * `consumeMovmoCheckoutReturn`) at that URL.\n */\n returnUrl?: string;\n /**\n * Fires when the traveler comes back from the Movmo checkout (a full-page return to\n * `returnUrl`, verified against the state nonce minted at click). `info.reason` says\n * why: 'booking_confirmed' - the traveler booked and clicked \"Return to {airline}\";\n * 'offer_unavailable' - a dead-end screen's exit; 'search_again' - a non-retryable\n * failure or the header's \"Back to {airline}\". Use it to route the traveler onward.\n * Not invoked when the traveler never returns (browser back, closed tab).\n */\n onExit?: (info: MovmoCheckoutExitInfo) => void;\n /**\n * Fires once, on return, when the booking was confirmed, immediately BEFORE\n * `onExit({ reason: 'booking_confirmed' })`. `info.airlinePnr` is the airline's own\n * record locator (absent if the provider returned none; it travels only in the URL\n * fragment and is scrubbed on arrival); `info.airlineRef` is the airline IATA/company\n * code, not the PNR.\n */\n onBookingComplete?: (info: MovmoBookingCompleteInfo) => void;\n /**\n * Fires when the button hits a failure it cannot recover from on its own — the\n * click-time offer save failed, or neither `flightOfferID` nor `flightOffer` was\n * provided. The button already logs a `console.warn` and emits the matching\n * analytics event either way; this is for the partner page to react (e.g. show\n * its own error toast, or fall back to its native checkout). Additive — omitting\n * it preserves the console-only behavior.\n */\n onError?: (error: MovmoCheckoutError) => void;\n}\n\nconst HOVER_DWELL_MIN_MS = 200;\n\nexport const MovmoCheckoutButton: React.FC<MovmoCheckoutButtonProps> = ({\n iataCode,\n apiKey,\n providerID,\n flightOffer,\n flightOfferID,\n isProd = false,\n className,\n returnUrl,\n onExit,\n onBookingComplete,\n onError,\n}) => {\n const [isHovered, setIsHovered] = useState(false);\n // True from the click until the Movmo page replaces this one (or the attempt fails).\n const [isPending, setIsPending] = useState(false);\n const buttonRef = useRef<HTMLButtonElement>(null);\n const hoverStartRef = useRef<number | null>(null);\n const client = createApiClient(apiKey, iataCode, isProd);\n // Latest callbacks for the one-shot return consumption on mount.\n const returnOptions = {\n iataCode,\n providerID,\n isProd,\n offerId: flightOfferID,\n onExit,\n onBookingComplete,\n };\n const returnOptionsRef = useRef(returnOptions);\n returnOptionsRef.current = returnOptions;\n\n useEffect(() => {\n initScopedTracker(iataCode, isProd);\n if (typeof IntersectionObserver === 'undefined' || !buttonRef.current) return;\n const observer = new IntersectionObserver(\n (entries) => {\n if (entries.some((e) => e.isIntersecting)) {\n trackSafe(EVENTS.BUTTON_VIEWED);\n observer.disconnect(); // impression fires once per mount\n }\n },\n { threshold: 0.5 },\n );\n observer.observe(buttonRef.current);\n return () => observer.disconnect();\n }, []);\n\n // Declared AFTER the tracker-init effect on purpose: effects run in order, and the return\n // handler tracks checkout_returned through the tracker that effect initialises.\n useEffect(() => {\n consumeMovmoCheckoutReturn(returnOptionsRef.current);\n }, []);\n\n // bfcache: pressing Back from Movmo can restore this page from the back/forward cache with\n // the old React state, i.e. still pending. `pageshow` with `persisted` marks that restore.\n useEffect(() => {\n if (typeof window === 'undefined') return;\n const onPageShow = (event: PageTransitionEvent) => {\n if (event.persisted) setIsPending(false);\n };\n window.addEventListener('pageshow', onPageShow);\n return () => window.removeEventListener('pageshow', onPageShow);\n }, []);\n\n const handleMouseEnter = () => {\n setIsHovered(true);\n hoverStartRef.current = Date.now();\n };\n\n const handleMouseLeave = () => {\n setIsHovered(false);\n if (hoverStartRef.current !== null) {\n const dwell = Date.now() - hoverStartRef.current;\n hoverStartRef.current = null;\n if (dwell >= HOVER_DWELL_MIN_MS) trackSafe(EVENTS.BUTTON_HOVERED, { dwell_ms: dwell });\n }\n };\n\n const handleClick = async () => {\n if (isPending) return;\n // Before tracking or the offer save: blocks a second click re-running the save.\n setIsPending(true);\n // A click ends the \"hover consideration\" window. Without this, a user who clicks\n // without ever mousing away leaves hoverStartRef set from the original mouseenter;\n // a LATER mouseleave would then report a wildly inflated dwell_ms instead of being ignored.\n hoverStartRef.current = null;\n trackSafe(EVENTS.BUTTON_CLICKED);\n let offerId = flightOfferID;\n\n // If no pre-saved offer ID, save the raw offer\n if (!offerId && flightOffer) {\n trackSafe(EVENTS.OFFER_SAVE_STARTED);\n const startedAt = Date.now();\n const result = await saveProviderOffer(providerID, flightOffer, client);\n const latency = Date.now() - startedAt;\n if (!result.ok) {\n // Previously a silent return — a lost booking with zero trace (MOVMO-464).\n // MOVMO-673: also surface it to dev tools and, if wired, the partner page.\n trackSafe(EVENTS.OFFER_SAVE_FAILED, { latency_ms: latency });\n console.warn('[movmo] express checkout: offer save failed', {\n status: result.status,\n message: result.message,\n });\n onError?.({ stage: 'save_offer', status: result.status, message: result.message });\n setIsPending(false);\n return;\n }\n trackSafe(EVENTS.OFFER_SAVE_SUCCEEDED, { latency_ms: latency });\n offerId = result.offerId;\n }\n\n if (!offerId) {\n // Unconditional (not gated on onError being absent) so this stays visible in\n // dev tools by default, matching the save-failure branch above (MOVMO-673).\n console.warn('[movmo] express checkout: neither flightOfferID nor flightOffer was provided');\n onError?.({\n stage: 'missing_offer',\n message: 'neither flightOfferID nor flightOffer was provided',\n });\n setIsPending(false);\n return;\n }\n\n // Top-level redirect (MOVMO-549). The state nonce is echoed back as movmo_state and\n // checked against the pending record before any callback fires.\n const state = mintState();\n if (state) {\n writePending({\n state,\n offerId,\n startedAt: Date.now(),\n providerId: providerID,\n airlineRef: iataCode,\n isProd,\n });\n }\n const url = buildCheckoutUrl({\n offerId,\n providerId: providerID,\n airlineRef: iataCode,\n mvs: trackerSessionId(),\n internal: trackerIsInternal(),\n returnUrl: returnUrl ?? defaultReturnUrl(window.location.href),\n state,\n isProd,\n });\n trackSafe(EVENTS.CHECKOUT_REDIRECT_STARTED);\n // Pending stays true on success: the page is about to unload.\n try {\n window.location.assign(url);\n } catch (err) {\n console.warn('[movmo] express checkout: redirect failed', err);\n setIsPending(false);\n }\n };\n\n // Every class here carries the package's Tailwind prefix (tailwind.config.js\n // `prefix: 'movmo-'`) so the shipped stylesheet can't collide with the host\n // page's CSS. The consumer-supplied `className` is deliberately NOT prefixed:\n // it is host-page CSS (e.g. the Clic demo passes its own Tailwind classes)\n // and must reach the DOM verbatim.\n // `movmo-checkout-button` is not a Tailwind utility: it carries the\n // hand-written keyboard focus ring in src/index.css (see the note there).\n const buttonClasses = `\n movmo-checkout-button\n movmo-px-7 movmo-py-5\n movmo-font-inter movmo-font-semibold movmo-text-lg\n movmo-rounded-xl\n movmo-text-white\n movmo-border-none\n ${isPending ? 'movmo-cursor-progress' : 'movmo-cursor-pointer'}\n movmo-inline-grid movmo-place-items-center\n movmo-transition-all movmo-duration-200\n movmo-outline-none\n ${isHovered ? 'movmo-bg-gradient-hover' : 'movmo-bg-gradient-normal'}\n ${className ?? ''}\n `.trim();\n\n const badgeClasses = `\n movmo-ml-2 movmo-px-2 movmo-py-1\n movmo-bg-white\n movmo-text-[#171412]\n movmo-rounded-md\n movmo-text-lg\n `.trim();\n\n // Both labels share ONE grid cell, so the button is always as wide and tall as the wider\n // one and does not jump between states; the inactive label is `visibility: hidden`\n // (still laid out, hidden from sight and the accessibility tree).\n const cellClasses = 'movmo-col-start-1 movmo-row-start-1 movmo-inline-flex movmo-items-center';\n\n return (\n <button\n ref={buttonRef}\n onClick={handleClick}\n onMouseEnter={handleMouseEnter}\n onMouseLeave={handleMouseLeave}\n className={buttonClasses}\n disabled={isPending}\n aria-busy={isPending ? 'true' : undefined}\n >\n <span className={`${cellClasses} ${isPending ? 'movmo-invisible' : ''}`.trim()}>\n Express Checkout\n <span className={badgeClasses}>Movmo</span>\n </span>\n <span\n className={`${cellClasses} movmo-gap-2 ${isPending ? '' : 'movmo-invisible'}`.trim()}\n aria-hidden={isPending ? undefined : 'true'}\n >\n <span className=\"movmo-checkout-spinner\" aria-hidden=\"true\" />\n Opening Movmo…\n </span>\n </button>\n );\n};\n"],"names":["ALLOW_ENV_OVERRIDES","readEnv","name","proc","globalThis","process","value","env","undefined","readUrlOverride","raw","url","URL","username","password","host","hostname","toLowerCase","protocol","endsWith","isTrustedMovmoUrl","buildHeaders","apiKey","airlineRef","headers","Accept","window","location","proxyAuth","csrf","document","cookies","cookie","split","i","length","trim","startsWith","decodeURIComponent","substring","getCookie","safeDecode","s","RETURN_QUERY_KEYS","PNR_TOKEN","scrubHashPnr","hash","parts","slice","out","carry","removedAny","delim","token","test","lead","PENDING_KEY","PROD_CHECKOUT_URL","E2E_CHECKOUT_URL","PENDING_TTL_MS","buildCheckoutUrl","params","qs","URLSearchParams","offerId","providerId","mvs","set","internal","returnUrl","state","isProd","override","replace","checkoutBaseUrl","toString","defaultReturnUrl","href","isRouteHash","origin","pathname","search","kept","filter","seg","join","scrubQuery","clearPending","sessionStorage","removeItem","initScopedTracker","iataCode","Movmo","isInitialized","endpoint","init","app","partnerId","scoped","track","EVENTS","PLUGIN_LOADED","trackSafe","event","props","trackerSessionId","getSessionId","trackerIsInternal","isInternal","REASONS","stash","parsed","claimed","readHashPnr","q","lastIndexOf","all","getAll","scrubUrl","cleanSearch","keys","segs","includes","scrubQueryKeys","cleanHash","history","replaceState","safely","label","fn","err","consumeMovmoCheckoutReturn","options","opts","exit","get","bookingId","pnr","pending","getItem","v","JSON","parse","startedAt","Date","now","readPending","providerID","matchesPending","reason","airlinePnr","info","onBookingComplete","onExit","CHECKOUT_RETURNED","ms_away","MovmoCheckoutButton","flightOffer","flightOfferID","className","onError","isHovered","setIsHovered","useState","isPending","setIsPending","buttonRef","useRef","hoverStartRef","client","baseUrl","proxyBaseUrl","post","path","body","controller","AbortController","timer","setTimeout","abort","response","fetch","method","stringify","credentials","signal","ok","errorBody","json","Object","assign","Error","status","statusText","clearTimeout","createApiClient","returnOptions","returnOptionsRef","current","useEffect","IntersectionObserver","observer","entries","some","e","isIntersecting","BUTTON_VIEWED","disconnect","threshold","observe","onPageShow","persisted","addEventListener","removeEventListener","buttonClasses","badgeClasses","cellClasses","_jsxs","ref","onClick","async","BUTTON_CLICKED","OFFER_SAVE_STARTED","result","rawOffer","data","offer_id","message","error","nestedMessage","messageFromBody","String","cause","saveProviderOffer","latency","OFFER_SAVE_FAILED","latency_ms","stage","OFFER_SAVE_SUCCEEDED","c","crypto","randomUUID","getRandomValues","bytes","Uint8Array","Array","from","b","padStart","mintState","setItem","writePending","CHECKOUT_REDIRECT_STARTED","onMouseEnter","onMouseLeave","dwell","BUTTON_HOVERED","dwell_ms","disabled","children","_jsx"],"mappings":";;;;;;uKAMO,MAAMA,GACuC,EAe9C,SAAUC,EAAQC,GAEtB,IACE,MAAMC,EAAQC,WAA+DC,QACvEC,EAAQH,GAAMI,MAAML,GAC1B,MAAwB,iBAAVI,GAAgC,KAAVA,EAAeA,OAAQE,CAC7D,CAAE,MACA,MACF,CACF,CAoBM,SAAUC,EAAgBP,GAC9B,MAAMI,EAAQL,EAAQC,GACtB,QAAcM,IAAVF,EACJ,OAjBI,SAA4BI,GAChC,IACE,MAAMC,EAAM,IAAIC,IAAIF,GACpB,GAAIC,EAAIE,UAAYF,EAAIG,SAAU,OAAO,EACzC,MAAMC,EAAOJ,EAAIK,SAASC,cAC1B,MAAqB,WAAjBN,EAAIO,SAAuC,aAATH,GAAuBA,EAAKI,SAAS,aACtD,UAAjBR,EAAIO,WAAsC,cAATH,GAAiC,cAATA,EAE/D,CAAE,MACA,OAAO,CACT,CACF,CAMMK,CAAkBd,GAAeA,OAArC,CAGF,CC7CA,MAmCMe,EAAe,CAACC,EAAgBC,KACpC,MAAMC,EAAkC,CACtCC,OAAQ,mBACR,eAAgB,mBAChB,YAAaH,EACb,mBAAsC,oBAAXI,OAAyBA,OAAOC,SAASZ,KAAO,GAC3E,oBAAqBQ,GAIjBK,EACF3B,EAAQ,6CA7BM,oBAAXyB,QACuB,cAA7BA,OAAOC,SAASX,UAAyD,cAA7BU,OAAOC,SAASX,WA8BxCY,IACnBJ,EAAQ,sBAAwBI,GAGlC,MAAMC,EAjDU,CAAC3B,IACjB,GA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