@movmo/express-checkout-button 1.5.0 → 1.6.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.
- package/dist/dts/MovmoCheckoutButton.d.ts +13 -2
- package/dist/dts/MovmoCheckoutOverlay.d.ts +18 -1
- package/dist/dts/index.d.ts +3 -0
- package/dist/index.cjs.js +2 -2
- package/dist/index.cjs.js.map +1 -1
- package/dist/index.d.ts +32 -2
- package/dist/index.es.js +2 -2
- package/dist/index.es.js.map +1 -1
- package/package.json +2 -2
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import React from 'react';
|
|
2
|
-
|
|
2
|
+
import { MovmoCheckoutExitInfo } from './MovmoCheckoutOverlay';
|
|
3
|
+
export interface MovmoCheckoutButtonProps {
|
|
3
4
|
iataCode: string;
|
|
4
5
|
apiKey: string;
|
|
5
6
|
providerID: string;
|
|
@@ -7,6 +8,16 @@ interface MovmoCheckoutButtonProps {
|
|
|
7
8
|
flightOfferID?: string;
|
|
8
9
|
isProd?: boolean;
|
|
9
10
|
className?: string;
|
|
11
|
+
/**
|
|
12
|
+
* Fires when the traveler exits the Movmo checkout from inside the overlay
|
|
13
|
+
* (e.g. "Return to airline" on a dead-end screen, or a non-retryable
|
|
14
|
+
* booking failure), after the overlay is removed and the page URL is
|
|
15
|
+
* restored to where the checkout was opened. Use it to route the traveler
|
|
16
|
+
* onward (e.g. back to your search results) or record analytics; without
|
|
17
|
+
* it the traveler is simply returned to the page they clicked the button
|
|
18
|
+
* on. Not invoked for browser-back closes, and it does not survive a page
|
|
19
|
+
* refresh inside the checkout.
|
|
20
|
+
*/
|
|
21
|
+
onExit?: (info: MovmoCheckoutExitInfo) => void;
|
|
10
22
|
}
|
|
11
23
|
export declare const MovmoCheckoutButton: React.FC<MovmoCheckoutButtonProps>;
|
|
12
|
-
export {};
|
|
@@ -1 +1,18 @@
|
|
|
1
|
-
|
|
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
|
+
export interface MovmoCheckoutOverlayOptions {
|
|
7
|
+
/**
|
|
8
|
+
* Fires after an iframe-initiated exit (e.g. the traveler clicked
|
|
9
|
+
* "Return to airline" on a dead-end screen) once the overlay is removed and
|
|
10
|
+
* the page URL has been restored to where the checkout was opened. Use it to
|
|
11
|
+
* route the traveler onward or record analytics. It does NOT fire when the
|
|
12
|
+
* user closes the checkout with the browser back button (they are already
|
|
13
|
+
* back where they were), and it cannot survive a page refresh — a
|
|
14
|
+
* re-hydrated overlay falls back to the default close behavior.
|
|
15
|
+
*/
|
|
16
|
+
onExit?: (info: MovmoCheckoutExitInfo) => void;
|
|
17
|
+
}
|
|
18
|
+
export declare function showMovmoOverlay(queryParams: string, isProd?: boolean, options?: MovmoCheckoutOverlayOptions): void;
|
package/dist/dts/index.d.ts
CHANGED
|
@@ -1,2 +1,5 @@
|
|
|
1
1
|
import './index.css';
|
|
2
2
|
export { MovmoCheckoutButton } from './MovmoCheckoutButton';
|
|
3
|
+
export type { MovmoCheckoutButtonProps } from './MovmoCheckoutButton';
|
|
4
|
+
export type { MovmoCheckoutExitInfo, MovmoCheckoutOverlayOptions } from './MovmoCheckoutOverlay';
|
|
5
|
+
export type { MovmoExitReason } from '@movmo_app/types';
|
package/dist/index.cjs.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @movmo/express-checkout-button v1.
|
|
2
|
+
* @movmo/express-checkout-button v1.6.1
|
|
3
3
|
* React component plugin for embedding Movmo Express Checkout on airline websites.
|
|
4
4
|
* (c) 2026 Movmo
|
|
5
5
|
* @license MIT
|
|
6
6
|
*/
|
|
7
|
-
"use strict";var e=require("react/jsx-runtime"),o=require("react"),t=require("axios"),n=require("@movmo_app/types");const i=(e,o,n=!1)=>{const i=n?"https://flights.movmo.io":"https://flights.e2e.movmo.io",
|
|
7
|
+
"use strict";var e=require("react/jsx-runtime"),o=require("react"),t=require("axios"),n=require("@movmo_app/types");const i=(e,o,n=!1)=>{const i=n?"https://flights.movmo.io":"https://flights.e2e.movmo.io",s=process.env.REACT_APP_MOVMO_CHECKOUT_API_URL||`${i}/v1/proxy`,r=t.create({baseURL:s,headers:{Accept:"application/json","Content-Type":"application/json","x-api-key":e,"X-Forwarded-Host":"undefined"!=typeof window?window.location.host:"","movmo-customer-id":o,..."undefined"==typeof window||"localhost"!==window.location.hostname&&"127.0.0.1"!==window.location.hostname||!process.env.REACT_APP_CLOUD_FRONT_PROXY_SECRET_HEADER?{}:{"X-Movmo-Proxy-Auth":process.env.REACT_APP_CLOUD_FRONT_PROXY_SECRET_HEADER}},withCredentials:!0,timeout:3e4});return r.interceptors.request.use((e=>{e.headers?.Authorization&&delete e.headers.Authorization;const o=(e=>{const o=document.cookie.split(";");for(let t=0;t<o.length;t++){const n=o[t].trim();if(n.startsWith(e+"="))return decodeURIComponent(n.substring(e.length+1))}return null})("movmo_csrf_token");return o&&(e.headers["X-CSRF-Token"]=o),e})),r};let s,r=!1,c=!1;const a=50,d=20;function m(e){const o=[process.env.REACT_APP_MOVMO_CHECKOUT_URL];if(!n.isTrustedOrigin(e.origin,n.MOVMO_FLIGHTS_ORIGINS,{isProd:c,extraOrigins:o}))return;const t=e.data;if(t?.type)switch(t.type){case n.MovmoFrameMessageType.READY:{const o={type:n.MovmoFrameMessageType.INIT,parentOrigin:window.location.origin};e.source?.postMessage(o,e.origin);break}case n.MovmoFrameMessageType.BOOKING_COMPLETE:{const{bookingId:e,airlineRef:o,providerId:n}=t;e&&window.history.pushState({checkoutOpen:!0,bookingComplete:!0,bookingId:e,providerId:n},"",`/movmo/checkout/booking/${e}?airlineRef=${o||""}&providerId=${n||""}`);break}case n.MovmoFrameMessageType.BOOKING_FAILED:{const e=t.reason??"search_again",o=s;!function(e){if(document.getElementById("movmo-checkout")?.remove(),window.history.state?.checkoutOpen){if(e){let o=!1,t=0;const n=()=>{o||(o=!0,window.removeEventListener("popstate",n),e())};window.addEventListener("popstate",n,{once:!0});const i=()=>{o||(window.history.state?.checkoutOpen?t>=d?n():(t+=1,setTimeout(i,a)):n())};setTimeout(i,a)}window.history.back()}else e?.()}((()=>{if(o)try{o({reason:e})}catch(e){}}));break}}}function h(e,o=!1,t){if(document.getElementById("movmo-checkout"))return;const n=document.createElement("div");n.id="movmo-checkout",n.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 ";const i=process.env.REACT_APP_MOVMO_CHECKOUT_URL||(o?"https://flights.movmo.io":"https://flights.e2e.movmo.io");let a=`${i}/index.html#/booking?${e}`;if(window.location.pathname.includes("/movmo/checkout/booking/")){const e=window.location.pathname.split("/").pop(),o=new URLSearchParams(window.location.search);a=`${i}/index.html#/booking/${e}?airlineRef=${o.get("airlineRef")||""}&providerId=${o.get("providerId")||""}`,window.history.replaceState({checkoutOpen:!0,bookingComplete:!0},"",window.location.href)}const d=document.createElement("iframe");d.src=a,d.width="100%",d.height="100%",d.style.border="none",d.id="movmo-checkout-iframe",d.setAttribute("allow","storage-access"),n.appendChild(d),document.body.appendChild(n),c=o,s=t?.onExit,r||(window.addEventListener("message",m),r=!0)}window.addEventListener("popstate",(()=>{const e=document.getElementById("movmo-checkout");!window.history.state?.checkoutOpen&&e&&e.remove()})),"undefined"!=typeof window&&window.addEventListener("DOMContentLoaded",(()=>{const e=window.location.pathname.includes("/movmo/checkout/booking/"),o=window.location.pathname.startsWith("/movmo/checkout");if(e||o){h(window.location.search.substring(1),function(){const e=window.location.hostname;return!e.includes("e2e")&&!e.includes("localhost")}())}}));exports.MovmoCheckoutButton=({iataCode:t,apiKey:n,providerID:s,flightOffer:r,flightOfferID:c,isProd:a=!1,className:d,onExit:m})=>{const[p,u]=o.useState(!1),l=i(n,t,a),w=`\n px-7 py-5 \n font-inter font-semibold text-lg \n rounded-xl \n text-white \n border-none\n cursor-pointer\n transition-all duration-200\n outline-none focus:ring-2 focus:ring-[#F63D68] focus:ring-opacity-50\n ${p?"bg-gradient-hover":"bg-gradient-normal"}\n ${d??""}\n `.trim(),f="\n ml-2 px-2 py-1\n bg-white \n text-[#171412] \n rounded-md \n text-lg\n ".trim();return e.jsxs("button",{onClick:async()=>{let e=c;if(!e&&r){const o=await(async(e,o,t)=>await t.post(`/v1/flights/providers/${e}/offers`,o).then((e=>e.data.offer_id)).catch((e=>null)))(s,r,l);if(!o)return;e=o}if(!e)return;const o=new URLSearchParams({offerId:e,providerId:s,airlineRef:t}).toString();window.history.pushState({checkoutOpen:!0},"",`/movmo/checkout?${o}`),h(o,a,{onExit:m})},onMouseEnter:()=>u(!0),onMouseLeave:()=>u(!1),className:w,children:["Express Checkout",e.jsx("span",{className:f,children:"Movmo"})]})};
|
|
8
8
|
//# sourceMappingURL=index.cjs.js.map
|
package/dist/index.cjs.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs.js","sources":["../src/api.ts","../src/MovmoCheckoutOverlay.tsx","../src/MovmoCheckoutButton.tsx"],"sourcesContent":["import axios, { AxiosInstance } from 'axios';\n\n// Helper function to read cookie value from document.cookie\nconst getCookie = (name: string): string | null => {\n const cookieString = document.cookie;\n const cookies = cookieString.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\nexport const createAxiosClient = (apiKey: string, airlineRef: string, isProd: boolean = false) => {\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 =\n process.env.REACT_APP_MOVMO_CHECKOUT_API_URL || `${baseUrl}/v1/proxy`;\n\n const client = axios.create({\n baseURL: proxyBaseUrl,\n headers: {\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 ...(isLocalHost() && process.env.REACT_APP_CLOUD_FRONT_PROXY_SECRET_HEADER\n ? { 'X-Movmo-Proxy-Auth': process.env.REACT_APP_CLOUD_FRONT_PROXY_SECRET_HEADER }\n : {}),\n },\n withCredentials: true,\n timeout: 30000,\n });\n\n client.interceptors.request.use((config) => {\n if (config.headers?.Authorization) {\n delete config.headers.Authorization;\n }\n const token = getCookie('movmo_csrf_token');\n if (token) {\n config.headers['X-CSRF-Token'] = token;\n }\n\n return config;\n });\n\n return client;\n};\n\nexport const saveProviderOffer = async (\n providerID: string,\n rawOffer: object,\n client: AxiosInstance,\n): Promise<string | null> => {\n return await client\n .post(`/v1/flights/providers/${providerID}/offers`, rawOffer)\n .then((res) => res.data.offer_id)\n .catch((err) => {\n console.error(err);\n return null;\n });\n};\n","import {\n MOVMO_FLIGHTS_ORIGINS,\n MovmoFrameMessage,\n MovmoFrameMessageType,\n MovmoInitMessage,\n isTrustedOrigin,\n} from '@movmo_app/types';\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;\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 // 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 const { bookingId, airlineRef, providerId } = data;\n if (bookingId) {\n // Update the parent URL to reflect booking completion\n window.history.pushState(\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 // Dismiss the overlay so the user returns to the airline site to start a new search.\n // history.back() triggers the popstate cleanup below.\n if (window.history.state?.checkoutOpen) {\n window.history.back();\n } else {\n document.getElementById('movmo-checkout')?.remove();\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(queryParams: string, isProd: boolean = false) {\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 overlayIsProd = isProd;\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 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\nif (typeof window !== 'undefined') {\n window.addEventListener('DOMContentLoaded', () => {\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}\n","import React, { useState } from 'react';\n\nimport { createAxiosClient, saveProviderOffer } from './api';\nimport { showMovmoOverlay } from './MovmoCheckoutOverlay';\n\ninterface 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\nexport const MovmoCheckoutButton: React.FC<MovmoCheckoutButtonProps> = ({\n iataCode,\n apiKey,\n providerID,\n flightOffer,\n flightOfferID,\n isProd = false,\n className,\n}) => {\n const [isHovered, setIsHovered] = useState(false);\n const client = createAxiosClient(apiKey, iataCode, isProd);\n\n const handleClick = async () => {\n let offerId = flightOfferID;\n\n // If no pre-saved offer ID, save the raw offer\n if (!offerId && flightOffer) {\n const savedOfferId = await saveProviderOffer(providerID, flightOffer, client);\n if (!savedOfferId) {\n // TODO: handle error by displaying a message to the user\n return;\n }\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 }).toString();\n\n window.history.pushState({ checkoutOpen: true }, '', `/movmo/checkout?${queryParams}`);\n showMovmoOverlay(queryParams, isProd);\n };\n\n const buttonClasses = `\n px-7 py-5 \n font-inter font-semibold text-lg \n rounded-xl \n text-white \n border-none\n cursor-pointer\n transition-all duration-200\n outline-none focus:ring-2 focus:ring-[#F63D68] focus:ring-opacity-50\n ${isHovered ? 'bg-gradient-hover' : 'bg-gradient-normal'}\n ${className ?? ''}\n `.trim();\n\n const badgeClasses = `\n ml-2 px-2 py-1\n bg-white \n text-[#171412] \n rounded-md \n text-lg\n `.trim();\n\n return (\n <button\n onClick={handleClick}\n onMouseEnter={() => setIsHovered(true)}\n onMouseLeave={() => setIsHovered(false)}\n className={buttonClasses}\n >\n Express Checkout\n <span className={badgeClasses}>Movmo</span>\n </button>\n );\n};\n"],"names":["createAxiosClient","apiKey","airlineRef","isProd","baseUrl","proxyBaseUrl","process","env","REACT_APP_MOVMO_CHECKOUT_API_URL","client","axios","create","baseURL","headers","Accept","window","location","host","hostname","REACT_APP_CLOUD_FRONT_PROXY_SECRET_HEADER","withCredentials","timeout","interceptors","request","use","config","Authorization","token","name","cookies","document","cookie","split","i","length","trim","startsWith","decodeURIComponent","substring","getCookie","messageListenerAttached","overlayIsProd","handleIframeMessage","event","extraOrigins","REACT_APP_MOVMO_CHECKOUT_URL","isTrustedOrigin","origin","MOVMO_FLIGHTS_ORIGINS","data","type","MovmoFrameMessageType","READY","initMessage","INIT","parentOrigin","source","postMessage","BOOKING_COMPLETE","bookingId","providerId","history","pushState","checkoutOpen","bookingComplete","BOOKING_FAILED","state","back","getElementById","remove","showMovmoOverlay","queryParams","container","createElement","id","style","cssText","iframeUrl","pathname","includes","pop","urlParams","URLSearchParams","search","get","replaceState","href","iframe","src","width","height","border","setAttribute","appendChild","body","addEventListener","isBookingConfirmation","isCheckoutPath","isProductionEnvironment","iataCode","providerID","flightOffer","flightOfferID","className","isHovered","setIsHovered","useState","buttonClasses","badgeClasses","_jsxs","onClick","async","offerId","savedOfferId","rawOffer","post","then","res","offer_id","catch","err","saveProviderOffer","toString","onMouseEnter","onMouseLeave","children","_js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AKD,EAGH,OAGF,MAAMzC,EAAc,IAAIW,gBAAgB,CACtC8B,UACApD,WAAYwC,EACZlG,WAAYiG,IACXuB,WAEH3G,OAAO8C,QAAQC,UAAU,CAAEC,cAAc,GAAQ,GAAI,mBAAmBQ,KACxED,EAAiBC,EAAapE,EAAO,EA2BnCwH,aAAc,IAAMlB,GAAa,GACjCmB,aAAc,IAAMnB,GAAa,GACjCF,UAAWI,EAAakB,SAAA,CAAA,mBAGxBC,EAAAA,YAAMvB,UAAWK,EAAYiB,SAAA,YACtB"}
|
|
1
|
+
{"version":3,"file":"index.cjs.js","sources":["../src/api.ts","../src/MovmoCheckoutOverlay.tsx","../src/MovmoCheckoutButton.tsx"],"sourcesContent":["import axios, { AxiosInstance } from 'axios';\n\n// Helper function to read cookie value from document.cookie\nconst getCookie = (name: string): string | null => {\n const cookieString = document.cookie;\n const cookies = cookieString.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\nexport const createAxiosClient = (apiKey: string, airlineRef: string, isProd: boolean = false) => {\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 =\n process.env.REACT_APP_MOVMO_CHECKOUT_API_URL || `${baseUrl}/v1/proxy`;\n\n const client = axios.create({\n baseURL: proxyBaseUrl,\n headers: {\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 ...(isLocalHost() && process.env.REACT_APP_CLOUD_FRONT_PROXY_SECRET_HEADER\n ? { 'X-Movmo-Proxy-Auth': process.env.REACT_APP_CLOUD_FRONT_PROXY_SECRET_HEADER }\n : {}),\n },\n withCredentials: true,\n timeout: 30000,\n });\n\n client.interceptors.request.use((config) => {\n if (config.headers?.Authorization) {\n delete config.headers.Authorization;\n }\n const token = getCookie('movmo_csrf_token');\n if (token) {\n config.headers['X-CSRF-Token'] = token;\n }\n\n return config;\n });\n\n return client;\n};\n\nexport const saveProviderOffer = async (\n providerID: string,\n rawOffer: object,\n client: AxiosInstance,\n): Promise<string | null> => {\n return await client\n .post(`/v1/flights/providers/${providerID}/offers`, rawOffer)\n .then((res) => res.data.offer_id)\n .catch((err) => {\n console.error(err);\n return null;\n });\n};\n","import {\n MOVMO_FLIGHTS_ORIGINS,\n MovmoExitReason,\n MovmoFrameMessage,\n MovmoFrameMessageType,\n MovmoInitMessage,\n isTrustedOrigin,\n} from '@movmo_app/types';\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\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'];\n\n/**\n * Tear down the overlay and restore the page to where the checkout was opened.\n *\n * Order matters: the iframe is removed FIRST. Its navigations join the\n * parent's joint session history, so a history.back() issued while the iframe\n * is still attached could pop an iframe entry instead of the parent's — the\n * overlay would never close. Removing the browsing context prunes its entries,\n * making the subsequent back() deterministically land on the airline page the\n * user was on when they clicked the button (handleClick pushes\n * {checkoutOpen:true} synchronously before opening).\n *\n * history.back() is asynchronous, so onClosed is deferred until the traversal\n * settles (one-shot popstate, with a short timeout fallback) — an airline\n * callback that navigates would otherwise race the pending traversal. When\n * there is no checkoutOpen state to pop (direct navigation to a\n * /movmo/checkout URL), no back() is issued and onClosed fires immediately;\n * the airline's onExit is the remedy 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\nfunction closeOverlay(onClosed?: () => void) {\n document.getElementById('movmo-checkout')?.remove();\n\n if (!window.history.state?.checkoutOpen) {\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 // 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 const { bookingId, airlineRef, providerId } = data;\n if (bookingId) {\n // Update the parent URL to reflect booking completion\n window.history.pushState(\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, or a dead-end screen's exit was clicked\n // (reason: 'offer_unavailable', MOVMO-474). Older flights-ui builds\n // 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 is set UNCONDITIONALLY on every successful open: the\n // DOMContentLoaded re-hydration path calls showMovmoOverlay with no options,\n // and this assignment resets any stale callback (a closure over a React\n // tree from before the refresh) rather than invoking dead code later.\n overlayIsProd = isProd;\n overlayOnExit = options?.onExit;\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 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\nif (typeof window !== 'undefined') {\n window.addEventListener('DOMContentLoaded', () => {\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}\n","import React, { useState } from 'react';\n\nimport { createAxiosClient, saveProviderOffer } from './api';\nimport { MovmoCheckoutExitInfo, showMovmoOverlay } from './MovmoCheckoutOverlay';\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 * (e.g. \"Return to airline\" on a dead-end screen, or a non-retryable\n * booking failure), after the overlay is removed and the page URL is\n * restored to where the checkout was opened. Use it to route the traveler\n * onward (e.g. back to your search results) or record analytics; without\n * it the traveler is simply returned to the page they clicked the button\n * on. Not invoked for browser-back closes, and it does not survive a page\n * refresh inside the checkout.\n */\n onExit?: (info: MovmoCheckoutExitInfo) => void;\n}\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 client = createAxiosClient(apiKey, iataCode, isProd);\n\n const handleClick = async () => {\n let offerId = flightOfferID;\n\n // If no pre-saved offer ID, save the raw offer\n if (!offerId && flightOffer) {\n const savedOfferId = await saveProviderOffer(providerID, flightOffer, client);\n if (!savedOfferId) {\n // TODO: handle error by displaying a message to the user\n return;\n }\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 }).toString();\n\n window.history.pushState({ checkoutOpen: true }, '', `/movmo/checkout?${queryParams}`);\n showMovmoOverlay(queryParams, isProd, { onExit });\n };\n\n const buttonClasses = `\n px-7 py-5 \n font-inter font-semibold text-lg \n rounded-xl \n text-white \n border-none\n cursor-pointer\n transition-all duration-200\n outline-none focus:ring-2 focus:ring-[#F63D68] focus:ring-opacity-50\n ${isHovered ? 'bg-gradient-hover' : 'bg-gradient-normal'}\n ${className ?? ''}\n `.trim();\n\n const badgeClasses = `\n ml-2 px-2 py-1\n bg-white \n text-[#171412] \n rounded-md \n text-lg\n `.trim();\n\n return (\n <button\n onClick={handleClick}\n onMouseEnter={() => setIsHovered(true)}\n onMouseLeave={() => setIsHovered(false)}\n className={buttonClasses}\n >\n Express Checkout\n <span className={badgeClasses}>Movmo</span>\n </button>\n );\n};\n"],"names":["createAxiosClient","apiKey","airlineRef","isProd","baseUrl","proxyBaseUrl","process","env","REACT_APP_MOVMO_CHECKOUT_API_URL","client","axios","create","baseURL","headers","Accept","window","location","host","hostname","REACT_APP_CLOUD_FRONT_PROXY_SECRET_HEADER","withCredentials","timeout","interceptors","request","use","config","Authorization","token","name","cookies","document","cookie","split","i","length","trim","startsWith","decodeURIComponent","substring","getCookie","overlayOnExit","messageListenerAttached","overlayIsProd","CLOSE_POLL_MS","CLOSE_POLL_MAX_ATTEMPTS","handleIframeMessage","event","extraOrigins","REACT_APP_MOVMO_CHECKOUT_URL","isTrustedOrigin","origin","MOVMO_FLIGHTS_ORIGINS","data","type","MovmoFrameMessageType","READY","initMessage","INIT","parentOrigin","source","postMessage","BOOKING_COMPLETE","bookingId","providerId","history","pushState","checkoutOpen","bookingComplete","BOOKING_FAILED","reason","exit","onClosed","getElementById","remove","state","settled","attempts","settle","removeEventListener","addEventListener","once","poll","setTimeout","back","closeOverlay","e","showMovmoOverlay","queryParams","options","container","createElement","id","style","cssText","iframeUrl","pathname","includes","pop","urlParams","URLSearchParams","search","get","replaceState","href","iframe","src","width","height","border","setAttribute","appendChild","body","onExit","isBookingConfirmation","isCheckoutPath","isProductionEnvironment","iataCode","providerID","flightOffer","flightOfferID","className","isHovered","setIsHovered","useState","buttonClasses","badgeClasses","_jsxs","onClick","async","offerId","savedOfferId","rawOffer","post","then","res","offer_id","catch","err","saveProviderOffer","toString","onMouseEnter","onMouseLeave","children","_jsx"],"mappings":";;;;;;oHAGA,MAiBaA,EAAoB,CAACC,EAAgBC,EAAoBC,GAAkB,KACtF,MAAMC,EAAUD,EAAS,2BAA6B,+BAIhDE,EACJC,QAAQC,IAAIC,kCAAoC,GAAGJ,aAE/CK,EAASC,EAAMC,OAAO,CAC1BC,QAASP,EACTQ,QAAS,CACPC,OAAQ,mBACR,eAAgB,mBAChB,YAAab,EACb,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gB,sRASdH,EAAY,oBAAsB,iCAClCD,GAAa,WACjBrF,OAEE0F,EAAe,mHAMjB1F,OAEJ,OACE2F,OAAA,SAAA,CACEC,QApDgBC,UAClB,IAAIC,EAAUV,EAGd,IAAKU,GAAWX,EAAa,CAC3B,MAAMY,OFcqBF,OAC/BX,EACAc,EACA1H,UAEaA,EACV2H,KAAK,yBAAyBf,WAAqBc,GACnDE,MAAMC,GAAQA,EAAIlF,KAAKmF,WACvBC,OAAOC,GAEC,OExBoBC,CAAkBrB,EAAYC,EAAa7G,GACtE,IAAKyH,EAEH,OAEFD,EAAUC,CACZ,CAEA,IAAKD,EAGH,OAGF,MAAM1C,EAAc,IAAIY,gBAAgB,CACtC8B,UACAlE,WAAYsD,EACZnH,WAAYkH,IACXuB,WAEH5H,OAAOiD,QAAQC,UAAU,CAAEC,cAAc,GAAQ,GAAI,mBAAmBqB,KACxED,EAAiBC,EAAapF,EAAQ,CAAE6G,UAAS,EA2B/C4B,aAAc,IAAMlB,GAAa,GACjCmB,aAAc,IAAMnB,GAAa,GACjCF,UAAWI,EAAakB,SAAA,CAAA,mBAGxBC,EAAAA,YAAMvB,UAAWK,EAAYiB,SAAA,YACtB"}
|
package/dist/index.d.ts
CHANGED
|
@@ -1,10 +1,29 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @movmo/express-checkout-button v1.
|
|
2
|
+
* @movmo/express-checkout-button v1.6.1
|
|
3
3
|
* React component plugin for embedding Movmo Express Checkout on airline websites.
|
|
4
4
|
* (c) 2026 Movmo
|
|
5
5
|
* @license MIT
|
|
6
6
|
*/
|
|
7
7
|
import React from 'react';
|
|
8
|
+
import { MovmoExitReason } from '@movmo_app/types';
|
|
9
|
+
export { MovmoExitReason } from '@movmo_app/types';
|
|
10
|
+
|
|
11
|
+
/** Passed to the airline's onExit callback when the checkout hands control back. */
|
|
12
|
+
interface MovmoCheckoutExitInfo {
|
|
13
|
+
reason: MovmoExitReason;
|
|
14
|
+
}
|
|
15
|
+
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
|
+
}
|
|
8
27
|
|
|
9
28
|
interface MovmoCheckoutButtonProps {
|
|
10
29
|
iataCode: string;
|
|
@@ -14,7 +33,18 @@ interface MovmoCheckoutButtonProps {
|
|
|
14
33
|
flightOfferID?: string;
|
|
15
34
|
isProd?: boolean;
|
|
16
35
|
className?: string;
|
|
36
|
+
/**
|
|
37
|
+
* Fires when the traveler exits the Movmo checkout from inside the overlay
|
|
38
|
+
* (e.g. "Return to airline" on a dead-end screen, or a non-retryable
|
|
39
|
+
* booking failure), after the overlay is removed and the page URL is
|
|
40
|
+
* restored to where the checkout was opened. Use it to route the traveler
|
|
41
|
+
* onward (e.g. back to your search results) or record analytics; without
|
|
42
|
+
* it the traveler is simply returned to the page they clicked the button
|
|
43
|
+
* on. Not invoked for browser-back closes, and it does not survive a page
|
|
44
|
+
* refresh inside the checkout.
|
|
45
|
+
*/
|
|
46
|
+
onExit?: (info: MovmoCheckoutExitInfo) => void;
|
|
17
47
|
}
|
|
18
48
|
declare const MovmoCheckoutButton: React.FC<MovmoCheckoutButtonProps>;
|
|
19
49
|
|
|
20
|
-
export { MovmoCheckoutButton };
|
|
50
|
+
export { MovmoCheckoutButton, type MovmoCheckoutButtonProps, type MovmoCheckoutExitInfo, type MovmoCheckoutOverlayOptions };
|
package/dist/index.es.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @movmo/express-checkout-button v1.
|
|
2
|
+
* @movmo/express-checkout-button v1.6.1
|
|
3
3
|
* React component plugin for embedding Movmo Express Checkout on airline websites.
|
|
4
4
|
* (c) 2026 Movmo
|
|
5
5
|
* @license MIT
|
|
6
6
|
*/
|
|
7
|
-
import{jsxs as o,jsx as e}from"react/jsx-runtime";import{useState as t}from"react";import n from"axios";import{isTrustedOrigin as i,MOVMO_FLIGHTS_ORIGINS as r,MovmoFrameMessageType as s}from"@movmo_app/types";const c=(o,e,t=!1)=>{const i=t?"https://flights.movmo.io":"https://flights.e2e.movmo.io",r=process.env.REACT_APP_MOVMO_CHECKOUT_API_URL||`${i}/v1/proxy`,s=n.create({baseURL:r,headers:{Accept:"application/json","Content-Type":"application/json","x-api-key":o,"X-Forwarded-Host":"undefined"!=typeof window?window.location.host:"","movmo-customer-id":e,..."undefined"==typeof window||"localhost"!==window.location.hostname&&"127.0.0.1"!==window.location.hostname||!process.env.REACT_APP_CLOUD_FRONT_PROXY_SECRET_HEADER?{}:{"X-Movmo-Proxy-Auth":process.env.REACT_APP_CLOUD_FRONT_PROXY_SECRET_HEADER}},withCredentials:!0,timeout:3e4});return s.interceptors.request.use((o=>{o.headers?.Authorization&&delete o.headers.Authorization;const e=(o=>{const e=document.cookie.split(";");for(let t=0;t<e.length;t++){const n=e[t].trim();if(n.startsWith(o+"="))return decodeURIComponent(n.substring(o.length+1))}return null})("movmo_csrf_token");return e&&(o.headers["X-CSRF-Token"]=e),o})),s};let a=!1,
|
|
7
|
+
import{jsxs as o,jsx as e}from"react/jsx-runtime";import{useState as t}from"react";import n from"axios";import{isTrustedOrigin as i,MOVMO_FLIGHTS_ORIGINS as r,MovmoFrameMessageType as s}from"@movmo_app/types";const c=(o,e,t=!1)=>{const i=t?"https://flights.movmo.io":"https://flights.e2e.movmo.io",r=process.env.REACT_APP_MOVMO_CHECKOUT_API_URL||`${i}/v1/proxy`,s=n.create({baseURL:r,headers:{Accept:"application/json","Content-Type":"application/json","x-api-key":o,"X-Forwarded-Host":"undefined"!=typeof window?window.location.host:"","movmo-customer-id":e,..."undefined"==typeof window||"localhost"!==window.location.hostname&&"127.0.0.1"!==window.location.hostname||!process.env.REACT_APP_CLOUD_FRONT_PROXY_SECRET_HEADER?{}:{"X-Movmo-Proxy-Auth":process.env.REACT_APP_CLOUD_FRONT_PROXY_SECRET_HEADER}},withCredentials:!0,timeout:3e4});return s.interceptors.request.use((o=>{o.headers?.Authorization&&delete o.headers.Authorization;const e=(o=>{const e=document.cookie.split(";");for(let t=0;t<e.length;t++){const n=e[t].trim();if(n.startsWith(o+"="))return decodeURIComponent(n.substring(o.length+1))}return null})("movmo_csrf_token");return e&&(o.headers["X-CSRF-Token"]=e),o})),s};let a,d=!1,m=!1;const h=50,p=20;function l(o){const e=[process.env.REACT_APP_MOVMO_CHECKOUT_URL];if(!i(o.origin,r,{isProd:m,extraOrigins:e}))return;const t=o.data;if(t?.type)switch(t.type){case s.READY:{const e={type:s.INIT,parentOrigin:window.location.origin};o.source?.postMessage(e,o.origin);break}case s.BOOKING_COMPLETE:{const{bookingId:o,airlineRef:e,providerId:n}=t;o&&window.history.pushState({checkoutOpen:!0,bookingComplete:!0,bookingId:o,providerId:n},"",`/movmo/checkout/booking/${o}?airlineRef=${e||""}&providerId=${n||""}`);break}case s.BOOKING_FAILED:{const o=t.reason??"search_again",e=a;!function(o){if(document.getElementById("movmo-checkout")?.remove(),window.history.state?.checkoutOpen){if(o){let e=!1,t=0;const n=()=>{e||(e=!0,window.removeEventListener("popstate",n),o())};window.addEventListener("popstate",n,{once:!0});const i=()=>{e||(window.history.state?.checkoutOpen?t>=p?n():(t+=1,setTimeout(i,h)):n())};setTimeout(i,h)}window.history.back()}else o?.()}((()=>{if(e)try{e({reason:o})}catch(o){}}));break}}}function u(o,e=!1,t){if(document.getElementById("movmo-checkout"))return;const n=document.createElement("div");n.id="movmo-checkout",n.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 ";const i=process.env.REACT_APP_MOVMO_CHECKOUT_URL||(e?"https://flights.movmo.io":"https://flights.e2e.movmo.io");let r=`${i}/index.html#/booking?${o}`;if(window.location.pathname.includes("/movmo/checkout/booking/")){const o=window.location.pathname.split("/").pop(),e=new URLSearchParams(window.location.search);r=`${i}/index.html#/booking/${o}?airlineRef=${e.get("airlineRef")||""}&providerId=${e.get("providerId")||""}`,window.history.replaceState({checkoutOpen:!0,bookingComplete:!0},"",window.location.href)}const s=document.createElement("iframe");s.src=r,s.width="100%",s.height="100%",s.style.border="none",s.id="movmo-checkout-iframe",s.setAttribute("allow","storage-access"),n.appendChild(s),document.body.appendChild(n),m=e,a=t?.onExit,d||(window.addEventListener("message",l),d=!0)}window.addEventListener("popstate",(()=>{const o=document.getElementById("movmo-checkout");!window.history.state?.checkoutOpen&&o&&o.remove()})),"undefined"!=typeof window&&window.addEventListener("DOMContentLoaded",(()=>{const o=window.location.pathname.includes("/movmo/checkout/booking/"),e=window.location.pathname.startsWith("/movmo/checkout");if(o||e){u(window.location.search.substring(1),function(){const o=window.location.hostname;return!o.includes("e2e")&&!o.includes("localhost")}())}}));const w=({iataCode:n,apiKey:i,providerID:r,flightOffer:s,flightOfferID:a,isProd:d=!1,className:m,onExit:h})=>{const[p,l]=t(!1),w=c(i,n,d),f=`\n px-7 py-5 \n font-inter font-semibold text-lg \n rounded-xl \n text-white \n border-none\n cursor-pointer\n transition-all duration-200\n outline-none focus:ring-2 focus:ring-[#F63D68] focus:ring-opacity-50\n ${p?"bg-gradient-hover":"bg-gradient-normal"}\n ${m??""}\n `.trim(),g="\n ml-2 px-2 py-1\n bg-white \n text-[#171412] \n rounded-md \n text-lg\n ".trim();return o("button",{onClick:async()=>{let o=a;if(!o&&s){const e=await(async(o,e,t)=>await t.post(`/v1/flights/providers/${o}/offers`,e).then((o=>o.data.offer_id)).catch((o=>null)))(r,s,w);if(!e)return;o=e}if(!o)return;const e=new URLSearchParams({offerId:o,providerId:r,airlineRef:n}).toString();window.history.pushState({checkoutOpen:!0},"",`/movmo/checkout?${e}`),u(e,d,{onExit:h})},onMouseEnter:()=>l(!0),onMouseLeave:()=>l(!1),className:f,children:["Express Checkout",e("span",{className:g,children:"Movmo"})]})};export{w as MovmoCheckoutButton};
|
|
8
8
|
//# sourceMappingURL=index.es.js.map
|
package/dist/index.es.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.es.js","sources":["../src/api.ts","../src/MovmoCheckoutOverlay.tsx","../src/MovmoCheckoutButton.tsx"],"sourcesContent":["import axios, { AxiosInstance } from 'axios';\n\n// Helper function to read cookie value from document.cookie\nconst getCookie = (name: string): string | null => {\n const cookieString = document.cookie;\n const cookies = cookieString.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\nexport const createAxiosClient = (apiKey: string, airlineRef: string, isProd: boolean = false) => {\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 =\n process.env.REACT_APP_MOVMO_CHECKOUT_API_URL || `${baseUrl}/v1/proxy`;\n\n const client = axios.create({\n baseURL: proxyBaseUrl,\n headers: {\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 ...(isLocalHost() && process.env.REACT_APP_CLOUD_FRONT_PROXY_SECRET_HEADER\n ? { 'X-Movmo-Proxy-Auth': process.env.REACT_APP_CLOUD_FRONT_PROXY_SECRET_HEADER }\n : {}),\n },\n withCredentials: true,\n timeout: 30000,\n });\n\n client.interceptors.request.use((config) => {\n if (config.headers?.Authorization) {\n delete config.headers.Authorization;\n }\n const token = getCookie('movmo_csrf_token');\n if (token) {\n config.headers['X-CSRF-Token'] = token;\n }\n\n return config;\n });\n\n return client;\n};\n\nexport const saveProviderOffer = async (\n providerID: string,\n rawOffer: object,\n client: AxiosInstance,\n): Promise<string | null> => {\n return await client\n .post(`/v1/flights/providers/${providerID}/offers`, rawOffer)\n .then((res) => res.data.offer_id)\n .catch((err) => {\n console.error(err);\n return null;\n });\n};\n","import {\n MOVMO_FLIGHTS_ORIGINS,\n MovmoFrameMessage,\n MovmoFrameMessageType,\n MovmoInitMessage,\n isTrustedOrigin,\n} from '@movmo_app/types';\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;\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 // 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 const { bookingId, airlineRef, providerId } = data;\n if (bookingId) {\n // Update the parent URL to reflect booking completion\n window.history.pushState(\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 // Dismiss the overlay so the user returns to the airline site to start a new search.\n // history.back() triggers the popstate cleanup below.\n if (window.history.state?.checkoutOpen) {\n window.history.back();\n } else {\n document.getElementById('movmo-checkout')?.remove();\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(queryParams: string, isProd: boolean = false) {\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 overlayIsProd = isProd;\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 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\nif (typeof window !== 'undefined') {\n window.addEventListener('DOMContentLoaded', () => {\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}\n","import React, { useState } from 'react';\n\nimport { createAxiosClient, saveProviderOffer } from './api';\nimport { showMovmoOverlay } from './MovmoCheckoutOverlay';\n\ninterface 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\nexport const MovmoCheckoutButton: React.FC<MovmoCheckoutButtonProps> = ({\n iataCode,\n apiKey,\n providerID,\n flightOffer,\n flightOfferID,\n isProd = false,\n className,\n}) => {\n const [isHovered, setIsHovered] = useState(false);\n const client = createAxiosClient(apiKey, iataCode, isProd);\n\n const handleClick = async () => {\n let offerId = flightOfferID;\n\n // If no pre-saved offer ID, save the raw offer\n if (!offerId && flightOffer) {\n const savedOfferId = await saveProviderOffer(providerID, flightOffer, client);\n if (!savedOfferId) {\n // TODO: handle error by displaying a message to the user\n return;\n }\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 }).toString();\n\n window.history.pushState({ checkoutOpen: true }, '', `/movmo/checkout?${queryParams}`);\n showMovmoOverlay(queryParams, isProd);\n };\n\n const buttonClasses = `\n px-7 py-5 \n font-inter font-semibold text-lg \n rounded-xl \n text-white \n border-none\n cursor-pointer\n transition-all duration-200\n outline-none focus:ring-2 focus:ring-[#F63D68] focus:ring-opacity-50\n ${isHovered ? 'bg-gradient-hover' : 'bg-gradient-normal'}\n ${className ?? ''}\n `.trim();\n\n const badgeClasses = `\n ml-2 px-2 py-1\n bg-white \n text-[#171412] \n rounded-md \n text-lg\n `.trim();\n\n return (\n <button\n onClick={handleClick}\n onMouseEnter={() => setIsHovered(true)}\n onMouseLeave={() => setIsHovered(false)}\n className={buttonClasses}\n >\n Express Checkout\n <span className={badgeClasses}>Movmo</span>\n </button>\n );\n};\n"],"names":["createAxiosClient","apiKey","airlineRef","isProd","baseUrl","proxyBaseUrl","process","env","REACT_APP_MOVMO_CHECKOUT_API_URL","client","axios","create","baseURL","headers","Accept","window","location","host","hostname","REACT_APP_CLOUD_FRONT_PROXY_SECRET_HEADER","withCredentials","timeout","interceptors","request","use","config","Authorization","token","name","cookies","document","cookie","split","i","length","trim","startsWith","decodeURIComponent","substring","getCookie","messageListenerAttached","overlayIsProd","handleIframeMessage","event","extraOrigins","REACT_APP_MOVMO_CHECKOUT_URL","isTrustedOrigin","origin","MOVMO_FLIGHTS_ORIGINS","data","type","MovmoFrameMessageType","READY","initMessage","INIT","parentOrigin","source","postMessage","BOOKING_COMPLETE","bookingId","providerId","history","pushState","checkoutOpen","bookingComplete","BOOKING_FAILED","state","back","getElementById","remove","showMovmoOverlay","queryParams","container","createElement","id","style","cssText","iframeUrl","pathname","includes","pop","urlParams","URLSearchParams","search","get","replaceState","href","iframe","src","width","height","border","setAttribute","appendChild","body","addEventListener","isBookingConfirmation","isCheckoutPath","isProductionEnvironment","MovmoCheckoutButton","iataCode","providerID","flightOffer","flightOfferID","className","isHovered","setIsHovered","useState","buttonClasses","badgeClasses","_jsxs","onClick","async","offerId","savedOfferId","rawOffer","post","then","res","offer_id","catch","err","saveProviderOffer","toString","onMouseEnter","onMouseLeave","children","_jsx"],"mappings":";;;;;;iNAGA,MAiBaA,EAAoB,CAACC,EAAgBC,EAAoBC,GAAkB,KACtF,MAAMC,EAAUD,EAAS,2BAA6B,+BAIhDE,EACJC,QAAQC,IAAIC,kCAAoC,GAAGJ,aAE/CK,EAASC,EAAMC,OAAO,CAC1BC,QAASP,EACTQ,QAAS,CACPC,OAAQ,mBACR,eAAgB,mBAChB,YAAab,EACb,mBAAsC,oBAAXc,OAAyBA,OAAOC,SAASC,KAAO,GAC3E,oBAAqBf,KAlBP,oBAAXa,QACuB,cAA7BA,OAAOC,S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MovmoCheckoutButton.tsx"],"sourcesContent":["import axios, { AxiosInstance } from 'axios';\n\n// Helper function to read cookie value from document.cookie\nconst getCookie = (name: string): string | null => {\n const cookieString = document.cookie;\n const cookies = cookieString.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\nexport const createAxiosClient = (apiKey: string, airlineRef: string, isProd: boolean = false) => {\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 =\n process.env.REACT_APP_MOVMO_CHECKOUT_API_URL || `${baseUrl}/v1/proxy`;\n\n const client = axios.create({\n baseURL: proxyBaseUrl,\n headers: {\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 ...(isLocalHost() && process.env.REACT_APP_CLOUD_FRONT_PROXY_SECRET_HEADER\n ? { 'X-Movmo-Proxy-Auth': process.env.REACT_APP_CLOUD_FRONT_PROXY_SECRET_HEADER }\n : {}),\n },\n withCredentials: true,\n timeout: 30000,\n });\n\n client.interceptors.request.use((config) => {\n if (config.headers?.Authorization) {\n delete config.headers.Authorization;\n }\n const token = getCookie('movmo_csrf_token');\n if (token) {\n config.headers['X-CSRF-Token'] = token;\n }\n\n return config;\n });\n\n return client;\n};\n\nexport const saveProviderOffer = async (\n providerID: string,\n rawOffer: object,\n client: AxiosInstance,\n): Promise<string | null> => {\n return await client\n .post(`/v1/flights/providers/${providerID}/offers`, rawOffer)\n .then((res) => res.data.offer_id)\n .catch((err) => {\n console.error(err);\n return null;\n });\n};\n","import {\n MOVMO_FLIGHTS_ORIGINS,\n MovmoExitReason,\n MovmoFrameMessage,\n MovmoFrameMessageType,\n MovmoInitMessage,\n isTrustedOrigin,\n} from '@movmo_app/types';\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\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'];\n\n/**\n * Tear down the overlay and restore the page to where the checkout was opened.\n *\n * Order matters: the iframe is removed FIRST. Its navigations join the\n * parent's joint session history, so a history.back() issued while the iframe\n * is still attached could pop an iframe entry instead of the parent's — the\n * overlay would never close. Removing the browsing context prunes its entries,\n * making the subsequent back() deterministically land on the airline page the\n * user was on when they clicked the button (handleClick pushes\n * {checkoutOpen:true} synchronously before opening).\n *\n * history.back() is asynchronous, so onClosed is deferred until the traversal\n * settles (one-shot popstate, with a short timeout fallback) — an airline\n * callback that navigates would otherwise race the pending traversal. When\n * there is no checkoutOpen state to pop (direct navigation to a\n * /movmo/checkout URL), no back() is issued and onClosed fires immediately;\n * the airline's onExit is the remedy 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\nfunction closeOverlay(onClosed?: () => void) {\n document.getElementById('movmo-checkout')?.remove();\n\n if (!window.history.state?.checkoutOpen) {\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 // 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 const { bookingId, airlineRef, providerId } = data;\n if (bookingId) {\n // Update the parent URL to reflect booking completion\n window.history.pushState(\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, or a dead-end screen's exit was clicked\n // (reason: 'offer_unavailable', MOVMO-474). Older flights-ui builds\n // 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 is set UNCONDITIONALLY on every successful open: the\n // DOMContentLoaded re-hydration path calls showMovmoOverlay with no options,\n // and this assignment resets any stale callback (a closure over a React\n // tree from before the refresh) rather than invoking dead code later.\n overlayIsProd = isProd;\n overlayOnExit = options?.onExit;\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 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\nif (typeof window !== 'undefined') {\n window.addEventListener('DOMContentLoaded', () => {\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}\n","import React, { useState } from 'react';\n\nimport { createAxiosClient, saveProviderOffer } from './api';\nimport { MovmoCheckoutExitInfo, showMovmoOverlay } from './MovmoCheckoutOverlay';\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 * (e.g. \"Return to airline\" on a dead-end screen, or a non-retryable\n * booking failure), after the overlay is removed and the page URL is\n * restored to where the checkout was opened. Use it to route the traveler\n * onward (e.g. back to your search results) or record analytics; without\n * it the traveler is simply returned to the page they clicked the button\n * on. Not invoked for browser-back closes, and it does not survive a page\n * refresh inside the checkout.\n */\n onExit?: (info: MovmoCheckoutExitInfo) => void;\n}\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 client = createAxiosClient(apiKey, iataCode, isProd);\n\n const handleClick = async () => {\n let offerId = flightOfferID;\n\n // If no pre-saved offer ID, save the raw offer\n if (!offerId && flightOffer) {\n const savedOfferId = await saveProviderOffer(providerID, flightOffer, client);\n if (!savedOfferId) {\n // TODO: handle error by displaying a message to the user\n return;\n }\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 }).toString();\n\n window.history.pushState({ checkoutOpen: true }, '', `/movmo/checkout?${queryParams}`);\n showMovmoOverlay(queryParams, isProd, { onExit });\n };\n\n const buttonClasses = `\n px-7 py-5 \n font-inter font-semibold text-lg \n rounded-xl \n text-white \n border-none\n cursor-pointer\n transition-all duration-200\n outline-none focus:ring-2 focus:ring-[#F63D68] focus:ring-opacity-50\n ${isHovered ? 'bg-gradient-hover' : 'bg-gradient-normal'}\n ${className ?? ''}\n `.trim();\n\n const badgeClasses = `\n ml-2 px-2 py-1\n bg-white \n text-[#171412] \n rounded-md \n text-lg\n `.trim();\n\n return (\n <button\n onClick={handleClick}\n onMouseEnter={() => setIsHovered(true)}\n onMouseLeave={() => setIsHovered(false)}\n className={buttonClasses}\n >\n Express Checkout\n <span className={badgeClasses}>Movmo</span>\n </button>\n );\n};\n"],"names":["createAxiosClient","apiKey","airlineRef","isProd","baseUrl","proxyBaseUrl","process","env","REACT_APP_MOVMO_CHECKOUT_API_URL","client","axios","create","baseURL","headers","Accept","window","location","host","hostname","REACT_APP_CLOUD_FRONT_PROXY_SECRET_HEADER","withCredentials","timeout","interceptors","request","use","config","Authorization","token","name","cookies","document","cookie","split","i","length","trim","startsWith","decodeURIComponent","substring","getCookie","overlayOnExit","messageListenerAttached","overlayIsProd","CLOSE_POLL_MS","CLOSE_POLL_MAX_ATTEMPTS","handleIframeMessage","event","extraOrigins","REACT_APP_MOVMO_CHECKOUT_URL","isTrustedOrigin","origin","MOVMO_FLIGHTS_ORIGINS","data","type","MovmoFrameMessageType","READY","initMessage","INIT","parentOrigin","source","postMessage","BOOKING_COMPLETE","bookingId","providerId","history","pushState","checkoutOpen","bookingComplete","BOOKING_FAILED","reason","exit","onClosed","getElementById","remove","state","settled","attempts","settle","removeEventListener","addEventListener","once","poll","setTimeout","back","closeOverlay","e","showMovmoOverlay","queryParams","options","container","createElement","id","style","cssText","iframeUrl","pathname","includes","pop","urlParams","URLSearchParams","search","get","replaceState","href","iframe","src","width","height","border","setAttribute","appendChild","body","onExit","isBookingConfirmation","isCheckoutPath","isProductionEnvironment","MovmoCheckoutButton","iataCode","providerID","flightOffer","flightOfferID","className","isHovered","setIsHovered","useState","buttonClasses","badgeClasses","_jsxs","onClick","async","offerId","savedOfferId","rawOffer","post","then","res","offer_id","catch","err","saveProviderOffer","toString","onMouseEnter","onMouseLeave","children","_jsx"],"mappings":";;;;;;iNAGA,MAiBaA,EAAoB,CAACC,EAAgBC,EAAoBC,GAAkB,KACtF,MAAMC,EAAUD,EAAS,2BAA6B,+BAIhDE,EACJC,QAAQC,IAAIC,kCAAoC,GAAGJ,aAE/CK,EAASC,EAAMC,OAAO,CAC1BC,QAASP,EACTQ,QAAS,CACPC,OAAQ,mBACR,eAAgB,mBAChB,YAAab,EACb,mBAAsC,oBAAXc,OAAyBA,OAAOC,SAASC,KAAO,GAC3E,oBAAqBf,KAlBP,oBAAXa,QACuB,cAA7BA,OAAOC,SAASE,UAAyD,cAA7BH,OAAOC,SAASE,WAkBpCZ,QAAQC,IAAIY,0CAE7B,GADA,CAAE,qBAAsBb,QAAQC,IAAIY,4CAG1CC,iBAAiB,EACjBC,QAAS,MAeX,OAZAZ,EAAOa,aAAaC,QAAQC,KAAKC,IAC3BA,EAAOZ,SAASa,sBACXD,EAAOZ,QAAQa,cAExB,MAAMC,EA7CQ,CAACC,IACjB,MACMC,EADeC,SAASC,OACDC,MAAM,KACnC,IAAK,I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E,WAAYuD,EACZpH,WAAYmH,IACXuB,WAEH7H,OAAOiD,QAAQC,UAAU,CAAEC,cAAc,GAAQ,GAAI,mBAAmBqB,KACxED,EAAiBC,EAAapF,EAAQ,CAAE6G,UAAS,EA2B/C6B,aAAc,IAAMlB,GAAa,GACjCmB,aAAc,IAAMnB,GAAa,GACjCF,UAAWI,EAAakB,SAAA,CAAA,mBAGxBC,UAAMvB,UAAWK,EAAYiB,SAAA,YACtB"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@movmo/express-checkout-button",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.6.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.js",
|
|
@@ -30,7 +30,7 @@
|
|
|
30
30
|
"iframe"
|
|
31
31
|
],
|
|
32
32
|
"dependencies": {
|
|
33
|
-
"@movmo_app/types": "^1.
|
|
33
|
+
"@movmo_app/types": "^1.12.0",
|
|
34
34
|
"axios": "^1.13.5"
|
|
35
35
|
},
|
|
36
36
|
"devDependencies": {
|