@movmo/express-checkout-button 1.11.0 → 1.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.cjs.js","sources":["../src/api.ts","../src/tracking.ts","../src/MovmoCheckoutOverlay.tsx","../src/MovmoCheckoutButton.tsx"],"sourcesContent":["/**\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 = process.env.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 = process.env.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.\n if (!response.ok) {\n throw new Error(\n `Movmo API request failed: ${response.status} ${response.statusText} (${path})`,\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\nexport const saveProviderOffer = async (\n providerID: string,\n rawOffer: object,\n client: ApiClient,\n): Promise<string | null> => {\n try {\n const data = await client.post<{ offer_id?: string }>(\n `/v1/flights/providers/${providerID}/offers`,\n rawOffer,\n );\n return data?.offer_id ?? null;\n } catch (err) {\n // MOVMO-464 contract: never throw into the click handler. Returning null\n // is what makes the button emit OFFER_SAVE_FAILED instead of dying silently.\n console.error(err);\n return null;\n }\n};\n","import { EVENTS, Movmo } from '@movmo_app/analytics';\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 process.env.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';\n\n/** Passed to the airline's onExit callback when the checkout hands control back. */\nexport interface MovmoCheckoutExitInfo {\n reason: MovmoExitReason;\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 * 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 overlayReturnTo: MovmoCheckoutOverlayOptions['returnTo'];\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/**\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\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 = [process.env.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 const initMessage: MovmoInitMessage = {\n type: MovmoFrameMessageType.INIT,\n parentOrigin: window.location.origin,\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 window.history.replaceState(\n { checkoutOpen: true, bookingComplete: true, bookingId, providerId },\n '',\n `/movmo/checkout/booking/${bookingId}?airlineRef=${airlineRef || ''}&providerId=${providerId || ''}`,\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 process.env.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\n window.history.replaceState(\n { 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\"`.\n iframe.setAttribute('allow', 'storage-access');\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 overlayOnExit = options?.onExit;\n overlayReturnTo = options?.returnTo;\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\nwindow.addEventListener('popstate', () => {\n const container = document.getElementById('movmo-checkout');\n if (!window.history.state?.checkoutOpen && container) {\n trackOverlayTeardown();\n container.remove();\n }\n});\n\n/**\n * Determine if the current environment is production based on hostname\n * - Production: hostname contains neither 'e2e' nor 'localhost'\n * - Development/Testing: hostname contains 'e2e' or 'localhost'\n */\nfunction isProductionEnvironment(): boolean {\n const hostname = window.location.hostname;\n // Check if we're on production (neither e2e nor localhost)\n return !hostname.includes('e2e') && !hostname.includes('localhost');\n}\n\n// Handle page refresh or direct navigation to a booking confirmation URL\nfunction rehydrateCheckoutOverlay(): void {\n const isBookingConfirmation = window.location.pathname.includes('/movmo/checkout/booking/');\n const isCheckoutPath = window.location.pathname.startsWith('/movmo/checkout');\n\n if (isBookingConfirmation || isCheckoutPath) {\n const queryParams = window.location.search.substring(1);\n const isProd = isProductionEnvironment();\n showMovmoOverlay(queryParams, isProd);\n }\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 { MovmoCheckoutExitInfo, showMovmoOverlay } from './MovmoCheckoutOverlay';\nimport {\n EVENTS,\n initScopedTracker,\n trackSafe,\n trackerIsInternal,\n trackerSessionId,\n} from './tracking';\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\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}) => {\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 savedOfferId = await saveProviderOffer(providerID, flightOffer, client);\n const latency = Date.now() - startedAt;\n if (!savedOfferId) {\n // Previously a silent return — a lost booking with zero trace (MOVMO-464).\n trackSafe(EVENTS.OFFER_SAVE_FAILED, { latency_ms: latency });\n return;\n }\n trackSafe(EVENTS.OFFER_SAVE_SUCCEEDED, { latency_ms: latency });\n offerId = savedOfferId;\n }\n\n if (!offerId) {\n // TODO: handle error - neither flightOfferID nor flightOffer provided\n console.error('Neither flightOfferID nor flightOffer provided');\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 window.history.pushState({ checkoutOpen: true }, '', `/movmo/checkout?${qs}`);\n showMovmoOverlay(qs, isProd, { onExit, 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":["buildHeaders","apiKey","airlineRef","headers","Accept","window","location","host","proxyAuth","process","env","REACT_APP_CLOUD_FRONT_PROXY_SECRET_HEADER","hostname","csrf","name","document","cookies","cookie","split","i","length","trim","startsWith","decodeURIComponent","substring","getCookie","trackSafe","event","props","Movmo","track","overlayOnExit","overlayReturnTo","messageListenerAttached","overlayIsProd","overlayOpenedAt","iframeReadySeen","CLOSE_POLL_MS","CLOSE_POLL_MAX_ATTEMPTS","trackOverlayTeardown","EVENTS","OVERLAY_ABANDONED_PRE_IFRAME","ms_since_open","Date","now","handleIframeMessage","extraOrigins","REACT_APP_MOVMO_CHECKOUT_URL","isTrustedOrigin","origin","MOVMO_FLIGHTS_ORIGINS","isProd","data","type","MovmoFrameMessageType","READY","IFRAME_READY","initMessage","INIT","parentOrigin","source","postMessage","BOOKING_COMPLETE","getElementById","bookingId","providerId","history","replaceState","checkoutOpen","bookingComplete","BOOKING_FAILED","reason","exit","onClosed","remove","state","url","settled","attempts","settle","removeEventListener","addEventListener","once","poll","setTimeout","back","closeOverlay","e","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","onExit","returnTo","rehydrateCheckoutOverlay","isBookingConfirmation","isCheckoutPath","isProductionEnvironment","readyState","iataCode","providerID","flightOffer","flightOfferID","className","isHovered","setIsHovered","useState","buttonRef","useRef","hoverStartRef","client","proxyBaseUrl","REACT_APP_MOVMO_CHECKOUT_API_URL","post","path","replace","controller","AbortController","timer","abort","response","fetch","method","JSON","stringify","credentials","signal","ok","Error","status","statusText","json","clearTimeout","createApiClient","useEffect","isInitialized","endpoint","REACT_APP_MOVMO_ANALYTICS_URL","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","savedOfferId","rawOffer","offer_id","err","saveProviderOffer","latency","OFFER_SAVE_FAILED","latency_ms","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":";;;;;;mIAWA,MAmCMA,EAAe,CAACC,EAAgBC,KACpC,MAAMC,EAAkC,CACtCC,OAAQ,mBACR,eAAgB,mBAChB,YAAaH,EACb,mBAAsC,oBAAXI,OAAyBA,OAAOC,SAASC,KAAO,GAC3E,oBAAqBL,GAKjBM,EAAYC,QAAQC,IAAIC,0CA7BZ,oBAAXN,QACuB,cAA7BA,OAAOC,SAASM,UAAyD,cAA7BP,OAAOC,SAASM,WA6BxCJ,IACnBL,EAAQ,sBAAwBK,GAGlC,MAAMK,EAhDU,CAACC,IACjB,GAAwB,oBAAbC,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,WAAWR,EAAO,KAE3B,OAAOS,mBAAmBN,EAAOO,UAAUV,EAAKM,OAAS,GAE7D,CACA,OAAO,IAAI,EAsCEK,CAAU,oBAKvB,OAJIZ,IACFV,EAA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