@movmo/express-checkout-button 1.14.0 → 2.0.1

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.
@@ -1 +1 @@
1
- {"version":3,"file":"index.es.js","sources":["../src/env.ts","../src/api.ts","../src/tracking.ts","../src/MovmoCheckoutOverlay.tsx","../src/MovmoCheckoutButton.tsx"],"sourcesContent":["/**\n * Reads a build-time environment override without assuming a `process` global.\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 */\nexport function readEnv(name: string): string | undefined {\n try {\n const proc = (globalThis as { process?: { env?: Record<string, string | undefined> } }).process;\n const value = proc?.env?.[name];\n return value ? String(value) : undefined;\n } catch {\n return undefined;\n }\n}\n","import { readEnv } 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 // Folded to `undefined` by @rollup/plugin-replace in the UMD build, so this\n // branch is statically eliminated there (a browser IIFE has no `process`).\n const proxyAuth = readEnv('REACT_APP_CLOUD_FRONT_PROXY_SECRET_HEADER');\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). Defaults are unchanged when the env var is unset.\n const proxyBaseUrl = readEnv('REACT_APP_MOVMO_CHECKOUT_API_URL') || `${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","import { EVENTS, Movmo } from '@movmo_app/analytics';\nimport { readEnv } 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 override mechanism as REACT_APP_MOVMO_CHECKOUT_URL (inlined by the consumer's CRA build).\n const endpoint =\n readEnv('REACT_APP_MOVMO_ANALYTICS_URL') ||\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 {\n MOVMO_FLIGHTS_ORIGINS,\n MovmoExitReason,\n MovmoFrameMessage,\n MovmoFrameMessageType,\n MovmoInitMessage,\n isTrustedOrigin,\n} from '@movmo_app/types';\n\nimport { EVENTS, trackSafe } from './tracking';\nimport { readEnv } from './env';\n\n/**\n * `MovmoInitMessage.capabilities` (`@movmo_app/types` >= 1.25.0, MOVMO-686), declared here\n * so this package builds against the published range it pins. Drop once the range is >= 1.25.0.\n */\ninterface InitCapabilities {\n capabilities?: { passkeys?: boolean };\n}\n\n/** Passed to the airline's onExit callback when the checkout hands control back. */\nexport interface MovmoCheckoutExitInfo {\n reason: MovmoExitReason;\n}\n\n/** Passed to onBookingComplete when a booking is confirmed inside the checkout. */\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 MovmoCheckoutOverlayOptions {\n /**\n * Fires after an iframe-initiated exit (e.g. the traveler clicked\n * \"Return to airline\" on a dead-end screen) once the overlay is removed and\n * the page URL has been restored to where the checkout was opened. Use it to\n * route the traveler onward or record analytics. It does NOT fire when the\n * user closes the checkout with the browser back button (they are already\n * back where they were), and it cannot survive a page refresh — a\n * re-hydrated overlay falls back to the default close behavior.\n */\n onExit?: (info: MovmoCheckoutExitInfo) => void;\n /**\n * Fires once per booking, while the traveler is still on Movmo's\n * confirmation screen and before any `onExit({ reason: 'booking_confirmed' })`\n * — that exit only fires later, if the traveler clicks \"Return to airline\".\n * Like `onExit`, it does not re-fire after a page refresh: a re-hydrated\n * overlay has no way to know whether this already ran before the reload.\n */\n onBookingComplete?: (info: MovmoBookingCompleteInfo) => void;\n /**\n * The partner page's URL + history.state captured by the button IMMEDIATELY\n * before it pushed the /movmo/checkout entry. An iframe-initiated exit\n * restores the page by replaceState-ing back to this entry instead of\n * traversing — see closeOverlay for why history.back() can't be trusted.\n * Absent on refresh-rehydrated overlays (nothing was captured), which fall\n * back to a back() traversal.\n */\n returnTo?: { url: string; state: unknown };\n}\n\n// A single message listener for the page lifetime, attached on the first overlay open and\n// never re-added. Re-adding per call would stack orphaned listeners every time the overlay\n// is torn down and reopened — each would reply to READY (duplicate INIT handshakes the\n// iframe can't disambiguate) and push duplicate history entries on BOOKING_COMPLETE.\nlet messageListenerAttached = false;\nlet overlayIsProd = false;\nlet overlayOnExit: MovmoCheckoutOverlayOptions['onExit'];\nlet overlayOnBookingComplete: MovmoCheckoutOverlayOptions['onBookingComplete'];\nlet overlayReturnTo: MovmoCheckoutOverlayOptions['returnTo'];\n// Dedupe guard for onBookingComplete: the MOVMO-676 queued-message flush can replay a\n// BOOKING_COMPLETE for a bookingId already delivered (e.g. a slow handshake queues the\n// message, then a duplicate arrives after flush). Reset alongside overlayOnExit/\n// overlayReturnTo on every showMovmoOverlay call so a reopen for a NEW booking fires again.\nlet lastCompletedBookingId: string | null = null;\n\n// Pre-iframe funnel analytics (MOVMO-464). Module-level for the same reason as\n// overlayOnExit/overlayIsProd above — the overlay outlives React, so this state must\n// survive teardown/reopen outside any component lifecycle.\nlet overlayOpenedAt: number | null = null;\nlet iframeReadySeen = false;\n\n// sessionStorage mirror of the environment persisted in the /movmo/checkout history\n// entry's state (see showMovmoOverlay/rehydrateCheckoutOverlay below). history.state\n// is the primary carrier; this is only a fallback for when it's unavailable at\n// reload (e.g. a host script replaced history.state without spreading the existing\n// value). Cleared on a normal close so a stale value can't leak into a later,\n// unrelated session — but MUST survive a reload, so it's never cleared on open.\nconst CHECKOUT_ENV_STORAGE_KEY = 'movmo:checkout:isProd';\n\nfunction persistCheckoutEnv(isProd: boolean): void {\n try {\n sessionStorage.setItem(CHECKOUT_ENV_STORAGE_KEY, String(isProd));\n } catch {\n // sessionStorage can throw (private browsing, disabled, quota) — best effort only.\n }\n}\n\nfunction clearPersistedCheckoutEnv(): void {\n try {\n sessionStorage.removeItem(CHECKOUT_ENV_STORAGE_KEY);\n } catch {\n // best effort\n }\n}\n\n/**\n * Tear down the overlay and restore the page to where the checkout was opened.\n *\n * Primary path (MOVMO-521): the button captured the partner page's URL +\n * history.state right before pushing the /movmo/checkout entry, so the close\n * restores it with a synchronous replaceState on the checkout entry — no\n * history traversal at all, and onClosed fires immediately with the URL\n * already restored. history.back() is NOT trustworthy here: once the iframe\n * has performed internal navigations (it always has by the confirmation page —\n * /booking → /booking/{id}), its session entries join the joint history, and a\n * script-initiated back() issued after the iframe's removal is silently\n * dropped by Chrome (the -1 target was one of the just-pruned iframe entries;\n * deferring the back() a task does not help — verified empirically). The cost\n * is a benign ghost entry: the real pre-checkout entry still sits behind the\n * restored one with the same URL and state, so a subsequent browser-back is a\n * visual no-op.\n *\n * Fallback path (refresh-rehydrated overlay — nothing captured): the original\n * MOVMO-474 behavior. Remove the iframe FIRST (pruning its joint-history\n * entries), issue history.back(), and defer onClosed until the traversal\n * settles (one-shot popstate, bounded poll). When there is no checkoutOpen\n * state at all (direct navigation to a /movmo/checkout URL), no restore is\n * attempted and onClosed fires immediately; the airline's onExit is the remedy\n * for the lingering URL in that case.\n */\n// Poll interval and cap for the popstate fallback below.\nconst CLOSE_POLL_MS = 50;\nconst CLOSE_POLL_MAX_ATTEMPTS = 20; // ~1s ceiling\n\n/**\n * Fires `overlay_abandoned_pre_iframe` at most once per open, only when the overlay is\n * torn down before flights-ui ever sent MOVMO_READY (a traveler who bounced before the\n * checkout even loaded). Once READY has been seen, teardown is unremarkable and this is\n * a no-op. Call from EVERY teardown path — closeOverlay and the popstate\n * container-removal listener both count as \"the overlay went away\".\n */\nfunction trackOverlayTeardown(): void {\n if (overlayOpenedAt !== null && !iframeReadySeen) {\n trackSafe(EVENTS.OVERLAY_ABANDONED_PRE_IFRAME, {\n ms_since_open: Date.now() - overlayOpenedAt,\n });\n }\n overlayOpenedAt = null; // fire at most once per open\n}\n\nfunction closeOverlay(onClosed?: () => void) {\n trackOverlayTeardown();\n document.getElementById('movmo-checkout')?.remove();\n // A normal close ends this checkout attempt — clear the persisted environment so\n // it can't leak into a later, unrelated session. (A reload while still IN the\n // overlay never reaches this function, so the value still survives reloads.)\n clearPersistedCheckoutEnv();\n\n if (!window.history.state?.checkoutOpen) {\n onClosed?.();\n return;\n }\n\n if (overlayReturnTo) {\n // Traversal-free restore onto the captured pre-checkout entry (see the\n // function comment for why back() can't be used here).\n window.history.replaceState(overlayReturnTo.state ?? null, '', overlayReturnTo.url);\n onClosed?.();\n return;\n }\n\n if (onClosed) {\n let settled = false;\n let attempts = 0;\n const settle = () => {\n if (settled) return;\n settled = true;\n window.removeEventListener('popstate', settle);\n onClosed();\n };\n // popstate = the back() traversal completed and the pre-checkout URL is\n // restored: notify immediately. This is the path real browsers take.\n window.addEventListener('popstate', settle, { once: true });\n // Fallback for environments where popstate never fires (jsdom mocks\n // history.back). Only settle once the checkoutOpen entry is actually gone,\n // so onExit never runs against a still-current /movmo/checkout URL — an\n // airline callback that navigates would otherwise be undone when the\n // pending back() finally lands. Bounded so a genuinely stuck traversal\n // can't hang the callback forever; if we exhaust the budget we settle\n // anyway and warn, since the URL guarantee can't be met.\n const poll = () => {\n if (settled) return;\n if (!window.history.state?.checkoutOpen) {\n settle();\n return;\n }\n if (attempts >= CLOSE_POLL_MAX_ATTEMPTS) {\n console.warn(\n '[movmo] overlay close: history did not settle; onExit may see an unrestored URL',\n );\n settle();\n return;\n }\n attempts += 1;\n setTimeout(poll, CLOSE_POLL_MS);\n };\n setTimeout(poll, CLOSE_POLL_MS);\n }\n window.history.back();\n}\n\nfunction handleIframeMessage(event: MessageEvent) {\n // Only ever trust messages from a Movmo flights-ui origin. REACT_APP_MOVMO_CHECKOUT_URL\n // widens the non-prod allowlist for the offline demo; prod keeps its hardcoded list.\n const extraOrigins = [readEnv('REACT_APP_MOVMO_CHECKOUT_URL')];\n if (\n !isTrustedOrigin(event.origin, MOVMO_FLIGHTS_ORIGINS, { isProd: overlayIsProd, extraOrigins })\n ) {\n return;\n }\n\n const data = event.data as MovmoFrameMessage | undefined;\n if (!data?.type) return;\n\n switch (data.type) {\n case MovmoFrameMessageType.READY: {\n // Fire the pre-iframe funnel's terminal \"success\" event exactly once per open,\n // before anything else — a duplicate READY (or a slow reopen) must not double-count.\n if (!iframeReadySeen) {\n iframeReadySeen = true;\n if (overlayOpenedAt !== null) {\n trackSafe(EVENTS.IFRAME_READY, { ms_since_open: Date.now() - overlayOpenedAt });\n }\n }\n // Handshake: reply with our origin so the iframe can target us directly on\n // subsequent messages instead of broadcasting to \"*\".\n // `capabilities.passkeys` (MOVMO-686): this SDK grants `publickey-credentials-get` on the iframe.\n const initMessage: MovmoInitMessage & InitCapabilities = {\n type: MovmoFrameMessageType.INIT,\n parentOrigin: window.location.origin,\n capabilities: { passkeys: true },\n };\n (event.source as Window | null)?.postMessage(initMessage, event.origin);\n break;\n }\n case MovmoFrameMessageType.BOOKING_COMPLETE: {\n // Stale message after teardown (the user browser-backed while a\n // BOOKING_COMPLETE was in flight): the partner entry is current now,\n // and replaceState would clobber the partner's own URL irrecoverably.\n if (!document.getElementById('movmo-checkout')) break;\n const { bookingId, airlineRef, providerId } = data;\n if (bookingId) {\n // Update the parent URL to reflect booking completion. replaceState, not\n // pushState: only one checkoutOpen entry may ever exist, so the success-path\n // exit's single history.back() in closeOverlay lands on the partner's real\n // pre-checkout URL (pushState would strand it at /movmo/checkout), and\n // browser-back from the confirmation closes the overlay in one press.\n // The PNR must NEVER enter the URL — history, analytics/tag managers, session\n // replay, and (on a refresh) the server log/Referer for this request all see it.\n // Spread the existing state so the environment persisted at open (isProd,\n // MOVMO-678) survives this rewrite instead of being dropped.\n window.history.replaceState(\n {\n ...window.history.state,\n checkoutOpen: true,\n bookingComplete: true,\n bookingId,\n providerId,\n },\n '',\n `/movmo/checkout/booking/${bookingId}?airlineRef=${airlineRef || ''}&providerId=${providerId || ''}`,\n );\n const airlinePnr =\n typeof data.airlinePnr === 'string' && data.airlinePnr.trim()\n ? data.airlinePnr.trim()\n : undefined;\n const info: MovmoBookingCompleteInfo = {\n bookingId,\n ...(airlinePnr !== undefined ? { airlinePnr } : {}),\n ...(airlineRef !== undefined ? { airlineRef } : {}),\n ...(providerId !== undefined ? { providerId } : {}),\n };\n // Dedupe against a replayed message for a booking already reported (MOVMO-676\n // queued-message flush) — a reopen resets lastCompletedBookingId, so a genuinely\n // new booking always fires.\n if (bookingId !== lastCompletedBookingId) {\n lastCompletedBookingId = bookingId;\n try {\n overlayOnBookingComplete?.(info);\n } catch (e) {\n console.error('[movmo] onBookingComplete callback threw', e);\n }\n }\n } else {\n console.warn(\n '[movmo] BOOKING_COMPLETE received without a bookingId; leaving the overlay in place',\n );\n }\n break;\n }\n case MovmoFrameMessageType.BOOKING_FAILED: {\n // The iframe is handing control back to the airline page: a booking\n // failed non-retryably, a dead-end screen's exit was clicked\n // (reason: 'offer_unavailable', MOVMO-474), or the traveler clicked\n // \"Return to {airline}\" on the booking confirmation\n // (reason: 'booking_confirmed', MOVMO-521 — the booking succeeded;\n // the exit only rides on this message type for back-compat). Older\n // flights-ui builds send no reason — treat as 'search_again'.\n const reason: MovmoExitReason = data.reason ?? 'search_again';\n // Capture the callback before the async close: a reopen during the\n // pending history traversal must not swap callbacks mid-flight.\n const exit = overlayOnExit;\n closeOverlay(() => {\n if (!exit) return;\n try {\n exit({ reason });\n } catch (e) {\n console.error('[movmo] onExit callback threw', e);\n }\n });\n break;\n }\n default: {\n console.warn('[movmo] ignoring unexpected message type from a trusted origin:', data.type);\n }\n }\n}\n\nexport function showMovmoOverlay(\n queryParams: string,\n isProd: boolean = false,\n options?: MovmoCheckoutOverlayOptions,\n) {\n if (document.getElementById('movmo-checkout')) return;\n\n const container = document.createElement('div');\n container.id = 'movmo-checkout';\n container.style.cssText = `\n position: fixed;\n top: 0;\n left: 0;\n width: 100vw;\n height: 100vh;\n background: white;\n z-index: 9999;\n `;\n\n // Use production or development URL based on isProd flag. REACT_APP_MOVMO_CHECKOUT_URL\n // overrides both (e.g. the offline demo points the overlay at http://localhost:3000);\n // defaults are unchanged when the env var is unset.\n const baseUrl =\n readEnv('REACT_APP_MOVMO_CHECKOUT_URL') ||\n (isProd ? 'https://flights.movmo.io' : 'https://flights.e2e.movmo.io');\n\n // Load index.html explicitly and use hash routing to avoid CloudFront error response issues\n // This ensures we load a file that actually exists in S3, then let React Router handle navigation\n let iframeUrl = `${baseUrl}/index.html#/booking?${queryParams}`;\n\n // If the URL indicates we're on a booking confirmation page, load that instead\n if (window.location.pathname.includes('/movmo/checkout/booking/')) {\n const bookingId = window.location.pathname.split('/').pop();\n const urlParams = new URLSearchParams(window.location.search);\n const airlineRef = urlParams.get('airlineRef') || '';\n const providerId = urlParams.get('providerId') || '';\n\n // Direct the iframe to the booking confirmation page using hash routing\n iframeUrl = `${baseUrl}/index.html#/booking/${bookingId}?airlineRef=${airlineRef}&providerId=${providerId}`;\n\n // Ensure we maintain the checkout state — spread the existing state so a\n // persisted isProd (MOVMO-678) survives this rewrite too.\n window.history.replaceState(\n { ...window.history.state, checkoutOpen: true, bookingComplete: true },\n '',\n window.location.href,\n );\n }\n\n // Create iframe element imperatively to prevent XSS (APP-XSS-001 fix)\n const iframe = document.createElement('iframe');\n iframe.src = iframeUrl;\n iframe.width = '100%';\n iframe.height = '100%';\n iframe.style.border = 'none';\n iframe.id = 'movmo-checkout-iframe';\n // Permit the embedded flights-ui document to call document.requestStorageAccess()\n // for cross-site Movmo recognition (MOVMO-427/429; the in-iframe request this\n // enables is MOVMO-428). WebKit rejects the request outright unless the\n // embedding iframe carries `allow=\"storage-access\"`. `publickey-credentials-get`\n // lets the iframe run a passkey sign-in `get()` cross-origin (MOVMO-686); the\n // INIT handshake advertises it so the iframe knows it may try.\n iframe.setAttribute('allow', 'storage-access; publickey-credentials-get');\n\n container.appendChild(iframe);\n\n document.body.appendChild(container);\n\n // Keep the (single, page-lifetime) message listener's environment current, then attach\n // it exactly once. See handleIframeMessage above for why it's not re-added per call.\n // overlayOnExit/overlayReturnTo are set UNCONDITIONALLY on every successful\n // open: the DOMContentLoaded re-hydration path calls showMovmoOverlay with\n // no options, and this assignment resets any stale callback (a closure over\n // a React tree from before the refresh) and any stale captured return entry\n // (a pre-refresh URL that may no longer be the right restore target).\n overlayIsProd = isProd;\n // Mirror to sessionStorage (MOVMO-678) on every open — both the button-click path\n // and the refresh-rehydration path (which calls showMovmoOverlay with no options)\n // funnel through here, so this is the single place that needs to do it.\n persistCheckoutEnv(isProd);\n overlayOnExit = options?.onExit;\n overlayOnBookingComplete = options?.onBookingComplete;\n overlayReturnTo = options?.returnTo;\n lastCompletedBookingId = null;\n overlayOpenedAt = Date.now();\n iframeReadySeen = false;\n if (!messageListenerAttached) {\n window.addEventListener('message', handleIframeMessage);\n messageListenerAttached = true;\n }\n}\n\n// Clean up when back button is used.\n// Guarded the same way as the `DOMContentLoaded` listener further down this\n// file: this runs at module top level, so an unguarded `window` reference\n// crashes any non-browser import of this module (Node/Vitest/SSR frameworks\n// — exactly the environments MOVMO-673's exports-map fix makes `import()`\n// of this package reachable from for the first time).\nif (typeof window !== 'undefined') {\n window.addEventListener('popstate', () => {\n const container = document.getElementById('movmo-checkout');\n if (!window.history.state?.checkoutOpen && container) {\n trackOverlayTeardown();\n container.remove();\n // Browser-back is a teardown too: drop the persisted environment like closeOverlay does.\n clearPersistedCheckoutEnv();\n }\n });\n}\n\n// Handle page refresh or direct navigation to a booking confirmation URL.\n//\n// The environment must NEVER be re-derived from window.location.hostname — a\n// partner hosts the checkout entry under ITS OWN domain, which the SDK has no\n// reliable way to classify as prod/e2e by pattern-matching (MOVMO-678 pilot-kit\n// run 4: a partner hostname containing neither \"e2e\" nor \"localhost\" was silently\n// treated as production even though the button had been mounted with\n// isProd={false}). The button's own isProd prop is the only source of truth for\n// which flights-ui environment a reload should reopen against, so it's persisted\n// at open — in the history.state pushed for the /movmo/checkout entry, mirrored to\n// sessionStorage as a fallback — and read back here, never sniffed from the URL.\nfunction rehydrateCheckoutOverlay(): void {\n const isBookingConfirmation = window.location.pathname.includes('/movmo/checkout/booking/');\n const isCheckoutPath = window.location.pathname.startsWith('/movmo/checkout');\n if (!isBookingConfirmation && !isCheckoutPath) return;\n\n const stateIsProd = (window.history.state as { isProd?: unknown } | null)?.isProd;\n let isProd: boolean;\n if (typeof stateIsProd === 'boolean') {\n isProd = stateIsProd;\n } else {\n let stored: string | null = null;\n try {\n stored = sessionStorage.getItem(CHECKOUT_ENV_STORAGE_KEY);\n } catch {\n stored = null;\n }\n if (stored !== 'true' && stored !== 'false') {\n console.warn('[movmo] checkout URL without a persisted environment; not reopening');\n return;\n }\n isProd = stored === 'true';\n }\n\n const queryParams = window.location.search.substring(1);\n showMovmoOverlay(queryParams, isProd);\n}\n\nif (typeof window !== 'undefined') {\n // 'interactive' is ambiguous: it's also the readyState while a `defer`\n // script is executing, which happens BEFORE DOMContentLoaded fires (e.g.\n // flights-ui's CRA production bundle is defer-loaded). Taking the\n // immediate path there would race a setTimeout(0) against the\n // DOMContentLoaded task instead of deterministically listening for it.\n // 'complete' is unambiguous — it's only reached after DOMContentLoaded has\n // already fired, so the event will never come and we must run the check\n // ourselves. That leaves a script dynamically injected between\n // DOMContentLoaded and `load` (readyState is 'complete' but our own\n // 'DOMContentLoaded' listener registered on 'loading'/'interactive' would\n // have already missed it too) as an accepted pre-existing gap.\n if (document.readyState === 'complete') {\n // Defer to a macrotask so it lands after the rest of synchronous module\n // init, preserving the original ordering.\n setTimeout(rehydrateCheckoutOverlay, 0);\n } else {\n window.addEventListener('DOMContentLoaded', rehydrateCheckoutOverlay);\n }\n}\n","import React, { useEffect, useRef, useState } from 'react';\n\nimport { createApiClient, saveProviderOffer } from './api';\nimport {\n MovmoBookingCompleteInfo,\n MovmoCheckoutExitInfo,\n showMovmoOverlay,\n} from './MovmoCheckoutOverlay';\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 * Fires when the traveler exits the Movmo checkout from inside the overlay,\n * after the overlay is removed and the page URL is restored to where the\n * checkout was opened. `info.reason` says why: 'booking_confirmed' — the\n * traveler booked successfully and clicked \"Return to {airline}\" on the\n * confirmation; 'offer_unavailable' — a dead-end screen's exit;\n * 'search_again' — a non-retryable booking failure. Use it to route the\n * traveler onward (e.g. a post-booking landing for 'booking_confirmed',\n * search results otherwise) or record analytics; without it the traveler\n * is simply returned to the page they clicked the button on. Not invoked\n * for browser-back closes, and it does not survive a page refresh inside\n * the checkout.\n */\n onExit?: (info: MovmoCheckoutExitInfo) => void;\n /**\n * Fires once per booking, while the traveler is still on Movmo's confirmation\n * screen and before any `onExit({ reason: 'booking_confirmed' })` — that exit\n * only fires later, if the traveler clicks \"Return to airline\". `info.airlinePnr`\n * is the airline's own record locator (absent if the provider returned none);\n * `info.airlineRef` is the airline IATA/company code, not the PNR. Like `onExit`,\n * it does not re-fire after a page refresh inside the checkout.\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 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\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 // eslint-disable-next-line react-hooks/exhaustive-deps\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 (e.g. after minutes on the checkout overlay) would then report a\n // 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 const queryParams = new URLSearchParams({\n offerId,\n providerId: providerID,\n airlineRef: iataCode,\n });\n // Session stitching (MOVMO-464): the iframe-side SDK adopts this id so\n // button_viewed -> booking_confirmed joins as one session.\n const sid = trackerSessionId();\n if (sid) queryParams.set('mvs', sid);\n // Traffic hygiene (MOVMO-478): forward the internal/QA/demo flag so the whole embedded\n // session stays flagged across the iframe boundary, not just the partner-page events.\n if (trackerIsInternal()) queryParams.set('mv_internal', '1');\n const qs = queryParams.toString();\n\n // Capture the partner page's entry BEFORE pushing ours: an iframe-initiated\n // exit restores it via replaceState (closeOverlay explains why not back()).\n // Snapshot the state so partner JS mutating its live history.state object\n // while the overlay is open can't corrupt the restore.\n let capturedState: unknown = null;\n try {\n capturedState = structuredClone(window.history.state);\n } catch {\n capturedState = window.history.state as unknown;\n }\n const returnTo = { url: window.location.href, state: capturedState };\n // isProd rides in the pushed state (MOVMO-678) so a reload reopens against the\n // environment the button was actually mounted with — never sniffed from the\n // partner's hostname. showMovmoOverlay mirrors it to sessionStorage as a fallback.\n window.history.pushState({ checkoutOpen: true, isProd }, '', `/movmo/checkout?${qs}`);\n showMovmoOverlay(qs, isProd, { onExit, onBookingComplete, returnTo });\n trackSafe(EVENTS.OVERLAY_OPENED);\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":["readEnv","name","proc","globalThis","process","value","env","String","undefined","buildHeaders","apiKey","airlineRef","headers","Accept","window","location","host","proxyAuth","hostname","csrf","document","cookies","cookie","split","i","length","trim","startsWith","decodeURIComponent","substring","getCookie","trackSafe","event","props","Movmo","track","overlayOnExit","overlayOnBookingComplete","overlayReturnTo","messageListenerAttached","overlayIsProd","lastCompletedBookingId","overlayOpenedAt","iframeReadySeen","CHECKOUT_ENV_STORAGE_KEY","clearPersistedCheckoutEnv","sessionStorage","removeItem","CLOSE_POLL_MS","CLOSE_POLL_MAX_ATTEMPTS","trackOverlayTeardown","EVENTS","OVERLAY_ABANDONED_PRE_IFRAME","ms_since_open","Date","now","handleIframeMessage","extraOrigins","isTrustedOrigin","origin","MOVMO_FLIGHTS_ORIGINS","isProd","data","type","MovmoFrameMessageType","READY","IFRAME_READY","initMessage","INIT","parentOrigin","capabilities","passkeys","source","postMessage","BOOKING_COMPLETE","getElementById","bookingId","providerId","history","replaceState","state","checkoutOpen","bookingComplete","airlinePnr","info","e","BOOKING_FAILED","reason","exit","onClosed","remove","url","settled","attempts","settle","removeEventListener","addEventListener","once","poll","setTimeout","back","closeOverlay","showMovmoOverlay","queryParams","options","container","createElement","id","style","cssText","baseUrl","iframeUrl","pathname","includes","pop","urlParams","URLSearchParams","search","get","href","iframe","src","width","height","border","setAttribute","appendChild","body","setItem","persistCheckoutEnv","onExit","onBookingComplete","returnTo","rehydrateCheckoutOverlay","isBookingConfirmation","isCheckoutPath","stateIsProd","stored","getItem","readyState","MovmoCheckoutButton","iataCode","providerID","flightOffer","flightOfferID","className","onError","isHovered","setIsHovered","useState","buttonRef","useRef","hoverStartRef","client","proxyBaseUrl","post","path","replace","controller","AbortController","timer","abort","response","fetch","method","JSON","stringify","credentials","signal","ok","errorBody","json","Object","assign","Error","status","statusText","clearTimeout","createApiClient","useEffect","isInitialized","endpoint","init","app","partnerId","scoped","PLUGIN_LOADED","initScopedTracker","IntersectionObserver","current","observer","entries","some","isIntersecting","BUTTON_VIEWED","disconnect","threshold","observe","buttonClasses","badgeClasses","_jsxs","ref","onClick","async","BUTTON_CLICKED","offerId","OFFER_SAVE_STARTED","startedAt","result","rawOffer","offer_id","message","err","error","nestedMessage","messageFromBody","cause","saveProviderOffer","latency","OFFER_SAVE_FAILED","latency_ms","stage","OFFER_SAVE_SUCCEEDED","sid","getSessionId","trackerSessionId","set","isInternal","trackerIsInternal","qs","toString","capturedState","structuredClone","pushState","OVERLAY_OPENED","onMouseEnter","onMouseLeave","dwell","BUTTON_HOVERED","dwell_ms","children","_jsx"],"mappings":";;;;;;gRAQM,SAAUA,EAAQC,GACtB,IACE,MAAMC,EAAQC,WAA0EC,QAClFC,EAAQH,GAAMI,MAAML,GAC1B,OAAOI,EAAQE,OAAOF,QAASG,CACjC,CAAE,MACA,MACF,CACF,CCJA,MAmCMC,EAAe,CAACC,EAAgBC,KACpC,MAAMC,EAAkC,CACtCC,OAAQ,mBACR,eAAgB,mBAChB,YAAaH,EACb,mBAAsC,oBAAXI,OAAyBA,OAAOC,SAASC,KAAO,GAC3E,oBAAqBL,GAKjBM,EAAYjB,EAAQ,6CA7BR,oBAAXc,QACuB,cAA7BA,OAAOC,SAASG,UAAyD,cAA7BJ,OAAOC,SAASG,WA6BxCD,IACnBL,EAAQ,sBAAwBK,GAGlC,MAAME,EAhDU,CAAClB,IACjB,GAAwB,oBAAbmB,SAA0B,OAAO,KAC5C,MAAMC,EAAUD,SAASE,OAAOC,MAAM,KACtC,IAAK,IAAIC,EAAI,EAAGA,EAAIH,EAAQI,OAAQD,IAAK,CACvC,MAAMF,EAASD,EAAQG,GAAGE,OAC1B,GAAIJ,EAAOK,WAAW1B,EAAO,KAE3B,OAAO2B,mBAAmBN,EAAOO,UAAU5B,EAAKwB,OAAS,GAE7D,CACA,OAAO,IAAI,EAsCEK,CAAU,oBAKvB,OAJIX,IACFP,EAAQ,gBAAkBO,GAGrBP,CAAO,WCrCAmB,EAAUC,EAAeC,EAAiC,IACxE,IACEC,EAAMC,MAAMH,EAAOC,EACrB,CAAE,MAEF,CACF,CCgCA,IAEIG,EACAC,EACAC,EAJAC,GAA0B,EAC1BC,GAAgB,EAQhBC,EAAwC,KAKxCC,EAAiC,KACjCC,GAAkB,EAQtB,MAAMC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QE,MACjD,CAAE,MACAuJ,EAAgBzN,OAAOgE,QAAQE,KACjC,CACA,MAAMoD,EAAW,CAAEzC,IAAK7E,OAAOC,SAASwG,KAAMvC,MAAOuJ,GAIrDzN,OAAOgE,QAAQ2J,UAAU,CAAExJ,cAAc,EAAMpB,UAAU,GAAI,mBAAmBwK,KAChF/H,EAAiB+H,EAAIxK,EAAQ,CAAEqE,SAAQC,oBAAmBC,aAC1DrG,EAAUoB,EAAOuL,eAAe,EAoC9BC,aAzHqB,KACvBvF,GAAa,GACbI,EAAcqC,QAAUvI,KAAKC,KAAK,EAwHhCqL,aArHqB,KAEvB,GADAxF,GAAa,GACiB,OAA1BI,EAAcqC,QAAkB,CAClC,MAAMgD,EAAQvL,KAAKC,MAAQiG,EAAcqC,QACzCrC,EAAcqC,QAAU,KACpBgD,GA9CiB,KA8CY9M,EAAUoB,EAAO2L,eAAgB,CAAEC,SAAUF,GAChF,GAgHE5F,UAAWqD,EAAa0C,SAAA,CAAA,mBAGxBC,EAAA,OAAA,CAAMhG,UAAWsD,EAAYyC,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 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","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","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,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,GAAwB,oBAAb4B,SAA0B,OAAO,KAC5C,MAAMC,EAAUD,SAASE,OAAOC,MAAM,KACtC,IAAK,IAAIC,EAAI,EAAGA,EAAIH,EAAQI,OAAQD,IAAK,CACvC,MAAMF,EAASD,EAAQG,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AAKpO,WAAmCqO,OAC9C,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,EAAErK,SAAS,IAAIsK,SAAS,EAAG,OAAM5J,KAAK,GACxE,CACF,CAAE,MAEF,CACA,OAAO,IACT,CG8FkB6J,GACV5K,GH7FF,SAAuBoE,GAC3B,IACElD,eAAe2J,QAAQ3L,EAAaqF,KAAKwC,UAAU3C,GACrD,CAAE,MAEF,CACF,CGwFM0G,CAAa,CACX9K,QACAN,UACA+E,UAAWC,KAAKC,MAChBhF,WAAYkF,EACZ5H,WAAYoE,EACZpB,WAGJ,MAAM5D,EAAMiD,EAAiB,CAC3BI,UACAC,WAAYkF,EACZ5H,WAAYoE,EACZzB,IAAKuC,IACLrC,SAAUuC,IACVtC,UAAWA,GAAaO,EAAiBlD,OAAOC,SAASkD,MACzDP,QACAC,WAEF+B,EAAUF,EAAOiJ,2BACjB3N,OAAOC,SAASiK,OAAOjL,EAAI,EAoCzB2O,aAlHqB,KACvBpF,GAAa,GACbI,EAAc8B,QAAUpD,KAAKC,KAAK,EAiHhCsG,aA9GqB,KAEvB,GADArF,GAAa,GACiB,OAA1BI,EAAc8B,QAAkB,CAClC,MAAMoD,EAAQxG,KAAKC,MAAQqB,EAAc8B,QACzC9B,EAAc8B,QAAU,KACpBoD,GA/DiB,KA+DYlJ,EAAUF,EAAOqJ,eAAgB,CAAEC,SAAUF,GAChF,GAyGEzF,UAAWiD,EAAa2C,SAAA,CAAA,mBAGxBC,EAAA,OAAA,CAAM7F,UAAWkD,EAAY0C,SAAA,YACtB"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@movmo/express-checkout-button",
3
- "version": "1.14.0",
3
+ "version": "2.0.1",
4
4
  "description": "React component plugin for embedding Movmo Express Checkout on airline websites.",
5
5
  "type": "module",
6
6
  "main": "dist/index.cjs",
@@ -41,10 +41,10 @@
41
41
  "airline",
42
42
  "flights",
43
43
  "react",
44
- "iframe"
44
+ "redirect"
45
45
  ],
46
46
  "dependencies": {
47
- "@movmo_app/analytics": "^0.5.1",
47
+ "@movmo_app/analytics": "^0.7.0",
48
48
  "@movmo_app/types": "^1.20.0"
49
49
  },
50
50
  "devDependencies": {
@@ -1,47 +0,0 @@
1
- import { MovmoExitReason } from '@movmo_app/types';
2
- /** Passed to the airline's onExit callback when the checkout hands control back. */
3
- export interface MovmoCheckoutExitInfo {
4
- reason: MovmoExitReason;
5
- }
6
- /** Passed to onBookingComplete when a booking is confirmed inside the checkout. */
7
- export interface MovmoBookingCompleteInfo {
8
- bookingId: string;
9
- /** Record locator (PNR) in the airline's own reservation system. Absent if the provider returned none. */
10
- airlinePnr?: string;
11
- /** Airline IATA / company code — not the PNR. */
12
- airlineRef?: string;
13
- providerId?: string;
14
- }
15
- export interface MovmoCheckoutOverlayOptions {
16
- /**
17
- * Fires after an iframe-initiated exit (e.g. the traveler clicked
18
- * "Return to airline" on a dead-end screen) once the overlay is removed and
19
- * the page URL has been restored to where the checkout was opened. Use it to
20
- * route the traveler onward or record analytics. It does NOT fire when the
21
- * user closes the checkout with the browser back button (they are already
22
- * back where they were), and it cannot survive a page refresh — a
23
- * re-hydrated overlay falls back to the default close behavior.
24
- */
25
- onExit?: (info: MovmoCheckoutExitInfo) => void;
26
- /**
27
- * Fires once per booking, while the traveler is still on Movmo's
28
- * confirmation screen and before any `onExit({ reason: 'booking_confirmed' })`
29
- * — that exit only fires later, if the traveler clicks "Return to airline".
30
- * Like `onExit`, it does not re-fire after a page refresh: a re-hydrated
31
- * overlay has no way to know whether this already ran before the reload.
32
- */
33
- onBookingComplete?: (info: MovmoBookingCompleteInfo) => void;
34
- /**
35
- * The partner page's URL + history.state captured by the button IMMEDIATELY
36
- * before it pushed the /movmo/checkout entry. An iframe-initiated exit
37
- * restores the page by replaceState-ing back to this entry instead of
38
- * traversing — see closeOverlay for why history.back() can't be trusted.
39
- * Absent on refresh-rehydrated overlays (nothing was captured), which fall
40
- * back to a back() traversal.
41
- */
42
- returnTo?: {
43
- url: string;
44
- state: unknown;
45
- };
46
- }
47
- export declare function showMovmoOverlay(queryParams: string, isProd?: boolean, options?: MovmoCheckoutOverlayOptions): void;