@movmo/express-checkout-button 2.0.2 → 2.1.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.
- package/README.md +9 -1
- package/dist/dts/MovmoCheckoutButton.d.ts +32 -6
- package/dist/dts/api.d.ts +17 -1
- package/dist/dts/index.d.ts +2 -3
- package/dist/dts/redirect.d.ts +17 -0
- package/dist/dts/returnHandler.d.ts +11 -1
- package/dist/dts/tracking.d.ts +0 -2
- package/dist/dts/umd.d.ts +2 -1
- package/dist/express-checkout.umd.js +5 -5
- package/dist/express-checkout.umd.js.map +1 -1
- package/dist/index.cjs +2 -2
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts +61 -26
- package/dist/index.es.js +2 -2
- package/dist/index.es.js.map +1 -1
- package/package.json +3 -6
package/dist/index.d.ts
CHANGED
|
@@ -1,12 +1,33 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @movmo/express-checkout-button v2.0
|
|
2
|
+
* @movmo/express-checkout-button v2.1.0
|
|
3
3
|
* React component plugin for embedding Movmo Express Checkout on airline websites.
|
|
4
4
|
* (c) Movmo
|
|
5
5
|
* @license MIT
|
|
6
6
|
*/
|
|
7
7
|
import React from 'react';
|
|
8
|
-
|
|
9
|
-
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Discriminated result of {@link saveProviderOffer} (MOVMO-673). Replaces the earlier
|
|
11
|
+
* `string | null` contract so the button (and, via `onError`, the partner page) can
|
|
12
|
+
* surface WHY a save failed — an HTTP status when the response was non-2xx, and a
|
|
13
|
+
* message that prefers the backend's own JSON `message`/`error` field over a generic
|
|
14
|
+
* fetch/timeout string.
|
|
15
|
+
*/
|
|
16
|
+
type SaveOfferResult = {
|
|
17
|
+
ok: true;
|
|
18
|
+
offerId: string;
|
|
19
|
+
} | {
|
|
20
|
+
ok: false;
|
|
21
|
+
status?: number;
|
|
22
|
+
message: string;
|
|
23
|
+
cause?: unknown;
|
|
24
|
+
};
|
|
25
|
+
/** The ticket choice an events checkout starts from. */
|
|
26
|
+
interface EventTicketSelection {
|
|
27
|
+
eventId: string;
|
|
28
|
+
listingId: string;
|
|
29
|
+
quantity: number;
|
|
30
|
+
}
|
|
10
31
|
|
|
11
32
|
/** Passed to the airline's onExit callback when the traveler returns from Movmo. */
|
|
12
33
|
interface MovmoCheckoutExitInfo {
|
|
@@ -20,6 +41,8 @@ interface MovmoBookingCompleteInfo {
|
|
|
20
41
|
/** Airline IATA / company code, not the PNR. */
|
|
21
42
|
airlineRef?: string;
|
|
22
43
|
providerId?: string;
|
|
44
|
+
/** Events checkouts: the seller ref that started the checkout. */
|
|
45
|
+
sellerRef?: string;
|
|
23
46
|
}
|
|
24
47
|
interface MovmoCheckoutReturnOptions {
|
|
25
48
|
/**
|
|
@@ -28,6 +51,11 @@ interface MovmoCheckoutReturnOptions {
|
|
|
28
51
|
* is pending, taking the values from the record.
|
|
29
52
|
*/
|
|
30
53
|
iataCode?: string;
|
|
54
|
+
/**
|
|
55
|
+
* Events: the seller ref. Giving it makes this an events call, which only claims an events
|
|
56
|
+
* return for that seller; a call with only `iataCode` only claims a flights return.
|
|
57
|
+
*/
|
|
58
|
+
sellerRef?: string;
|
|
31
59
|
providerID?: string;
|
|
32
60
|
/** The pre-saved offer id, when known, to tell two buttons with the same airline apart. */
|
|
33
61
|
offerId?: string;
|
|
@@ -39,6 +67,9 @@ interface MovmoCheckoutReturnOptions {
|
|
|
39
67
|
onExit?: (info: MovmoCheckoutExitInfo) => void;
|
|
40
68
|
onBookingComplete?: (info: MovmoBookingCompleteInfo) => void;
|
|
41
69
|
}
|
|
70
|
+
/** Why the checkout handed control back to the airline page (`onExit`). */
|
|
71
|
+
declare const REASONS: readonly ["search_again", "offer_unavailable", "booking_confirmed"];
|
|
72
|
+
type MovmoExitReason = (typeof REASONS)[number];
|
|
42
73
|
/**
|
|
43
74
|
* Consume a return from Movmo checkout (MOVMO-549). Returns true when callbacks fired.
|
|
44
75
|
*
|
|
@@ -56,7 +87,8 @@ declare function consumeMovmoCheckoutReturn(options?: MovmoCheckoutReturnOptions
|
|
|
56
87
|
|
|
57
88
|
/**
|
|
58
89
|
* A user-facing failure the button could not recover from on its own (MOVMO-673).
|
|
59
|
-
* `stage`
|
|
90
|
+
* `stage` may also be `'invalid_options'` or `'not_available'` (events mode: a bad ticket choice, or
|
|
91
|
+
* production, which is not supported yet). `stage` is `'save_offer'` — the click-time raw-offer save failed (CORS from an
|
|
60
92
|
* unregistered origin, a 4xx/5xx from the proxy, or a timeout) — or `'missing_offer'`
|
|
61
93
|
* — neither `flightOfferID` nor `flightOffer` was provided. `status` is the HTTP
|
|
62
94
|
* status when the failure was a non-2xx response; it is omitted for network errors,
|
|
@@ -64,16 +96,14 @@ declare function consumeMovmoCheckoutReturn(options?: MovmoCheckoutReturnOptions
|
|
|
64
96
|
* `message`/`error` field, falling back to a generic error string.
|
|
65
97
|
*/
|
|
66
98
|
type MovmoCheckoutError = {
|
|
67
|
-
stage: 'save_offer' | 'missing_offer';
|
|
99
|
+
stage: 'save_offer' | 'missing_offer' | 'invalid_options' | 'not_available';
|
|
68
100
|
status?: number;
|
|
69
101
|
message: string;
|
|
70
102
|
};
|
|
71
|
-
|
|
72
|
-
|
|
103
|
+
/** Props shared by the flights and events modes. */
|
|
104
|
+
interface MovmoCheckoutCommonProps {
|
|
73
105
|
apiKey: string;
|
|
74
106
|
providerID: string;
|
|
75
|
-
flightOffer?: object;
|
|
76
|
-
flightOfferID?: string;
|
|
77
107
|
isProd?: boolean;
|
|
78
108
|
className?: string;
|
|
79
109
|
/**
|
|
@@ -111,23 +141,28 @@ interface MovmoCheckoutButtonProps {
|
|
|
111
141
|
*/
|
|
112
142
|
onError?: (error: MovmoCheckoutError) => void;
|
|
113
143
|
}
|
|
114
|
-
|
|
115
|
-
|
|
144
|
+
/** Flights mode: an airline page starts a flight checkout. */
|
|
145
|
+
interface MovmoFlightCheckoutProps extends MovmoCheckoutCommonProps {
|
|
146
|
+
iataCode: string;
|
|
147
|
+
flightOffer?: object;
|
|
148
|
+
flightOfferID?: string;
|
|
149
|
+
sellerRef?: never;
|
|
150
|
+
eventTicket?: never;
|
|
151
|
+
}
|
|
152
|
+
/** The ticket choice an events checkout starts from (quantity is a whole number, 1 to 20). */
|
|
153
|
+
type MovmoEventTicket = EventTicketSelection;
|
|
116
154
|
/**
|
|
117
|
-
*
|
|
118
|
-
*
|
|
119
|
-
* surface WHY a save failed — an HTTP status when the response was non-2xx, and a
|
|
120
|
-
* message that prefers the backend's own JSON `message`/`error` field over a generic
|
|
121
|
-
* fetch/timeout string.
|
|
155
|
+
* Events mode: a ticket seller's page starts an events checkout. `sellerRef` is the seller
|
|
156
|
+
* Movmo registered for `providerID`. Not available in production yet (`onError` fires).
|
|
122
157
|
*/
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
158
|
+
interface MovmoEventCheckoutProps extends MovmoCheckoutCommonProps {
|
|
159
|
+
sellerRef: string;
|
|
160
|
+
eventTicket: MovmoEventTicket;
|
|
161
|
+
iataCode?: never;
|
|
162
|
+
flightOffer?: never;
|
|
163
|
+
flightOfferID?: never;
|
|
164
|
+
}
|
|
165
|
+
type MovmoCheckoutButtonProps = MovmoFlightCheckoutProps | MovmoEventCheckoutProps;
|
|
166
|
+
declare const MovmoCheckoutButton: React.FC<MovmoCheckoutButtonProps>;
|
|
132
167
|
|
|
133
|
-
export { type MovmoBookingCompleteInfo, MovmoCheckoutButton, type MovmoCheckoutButtonProps, type MovmoCheckoutError, type MovmoCheckoutExitInfo, type MovmoCheckoutReturnOptions, type SaveOfferResult, consumeMovmoCheckoutReturn };
|
|
168
|
+
export { type MovmoBookingCompleteInfo, MovmoCheckoutButton, type MovmoCheckoutButtonProps, type MovmoCheckoutCommonProps, type MovmoCheckoutError, type MovmoCheckoutExitInfo, type MovmoCheckoutReturnOptions, type MovmoEventCheckoutProps, type MovmoEventTicket, type MovmoExitReason, type MovmoFlightCheckoutProps, type SaveOfferResult, consumeMovmoCheckoutReturn };
|
package/dist/index.es.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @movmo/express-checkout-button v2.0
|
|
2
|
+
* @movmo/express-checkout-button v2.1.0
|
|
3
3
|
* React component plugin for embedding Movmo Express Checkout on airline websites.
|
|
4
4
|
* (c) Movmo
|
|
5
5
|
* @license MIT
|
|
6
6
|
*/
|
|
7
|
-
import{jsxs as t,jsx as o}from"react/jsx-runtime";import{useState as e,useRef as n,useEffect as r}from"react";import{Movmo as i,EVENTS as s}from"@movmo_app/analytics";const a=!0;function c(t){try{const o=globalThis.process,e=o?.env?.[t];return"string"==typeof e&&""!==e?e:void 0}catch{return}}function m(t){const o=c(t);if(void 0!==o)return function(t){try{const o=new URL(t);if(o.username||o.password)return!1;const e=o.hostname.toLowerCase();return"https:"===o.protocol?"movmo.io"===e||e.endsWith(".movmo.io"):"http:"===o.protocol&&("localhost"===e||"127.0.0.1"===e)}catch{return!1}}(o)?o:void 0}const l=(t,o)=>{const e={Accept:"application/json","Content-Type":"application/json","x-api-key":t,"X-Forwarded-Host":"undefined"!=typeof window?window.location.host:"","movmo-customer-id":o},n=c("REACT_APP_CLOUD_FRONT_PROXY_SECRET_HEADER");"undefined"==typeof window||"localhost"!==window.location.hostname&&"127.0.0.1"!==window.location.hostname||!n||(e["X-Movmo-Proxy-Auth"]=n);const r=(t=>{if("undefined"==typeof document)return null;const o=document.cookie.split(";");for(let e=0;e<o.length;e++){const n=o[e].trim();if(n.startsWith(t+"="))return decodeURIComponent(n.substring(t.length+1))}return null})("movmo_csrf_token");return r&&(e["X-CSRF-Token"]=r),e};function f(t){try{return decodeURIComponent(t)}catch{return t}}const d=["movmo_exit","movmo_state","movmo_booking_id","movmo_pnr"];const u=/^movmo_pnr(?:=.*)?$/;function p(t){if(t.length<=1)return"";const o=t.slice(1).split(/([?&])/);let e="",n=null,r=!1;for(let t=0;t<o.length;t+=2){const i=0===t?"":o[t-1],s=o[t];if(u.test(s)){r=!0,null===n&&(n=i);continue}let a=i;null!==n&&(""!==n&&"?"!==n||(a=""===e?"":n),n=null),e+=a+s}return r?""===e?"":`#${e}`:t}const v="movmo:checkout:pending",h="https://flights.movmo.io",g="https://flights.e2e.movmo.io",w=864e5;function y(t){const o=new URLSearchParams({offerId:t.offerId,providerId:t.providerId,airlineRef:t.airlineRef});return t.mvs&&o.set("mvs",t.mvs),t.internal&&o.set("mv_internal","1"),o.set("returnUrl",t.returnUrl),t.state&&o.set("state",t.state),`${function(t){const o=m("REACT_APP_MOVMO_CHECKOUT_URL");return o?o.replace(/\/+$/,""):t?h:g}(t.isProd)}/booking?${o.toString()}`}function _(t){const o=new URL(t),e=function(t){return/^#!?\//.test(t)}(o.hash)?p(o.hash):"";return`${o.origin}${o.pathname}${function(t){if(t.length<=1)return"?"===t?"":t;const o=t.slice(1).split("&").filter((t=>!f(t.split("=")[0]).startsWith("movmo_")));return o.length>0?`?${o.join("&")}`:""}(o.search)}${e}`}function I(){try{sessionStorage.removeItem(v)}catch{}}function E(t,o){try{if(i.isInitialized())return;const e=(a?m("REACT_APP_MOVMO_ANALYTICS_URL"):void 0)||(o?"https://api.movmo.io/v1/t":"https://e2e.api.movmo.io/v1/t");i.init({app:"express-checkout-button",env:o?"prd":"e2e",partnerId:t,endpoint:e,scoped:!0}),i.track(s.PLUGIN_LOADED)}catch{}}function R(t,o={}){try{i.track(t,o)}catch{}}function b(){try{return i.getSessionId()}catch{return null}}function C(){try{return i.isInternal()}catch{return!1}}const O=["search_again","offer_unavailable","booking_confirmed"];let A=null,T=!1,D=!1;function U(t){if(t.length<=1)return null;const o=t.lastIndexOf("?"),e=new URLSearchParams(t.slice(-1===o?1:o+1)).getAll("movmo_pnr");return e.length>0?e[e.length-1]:null}function $(){try{const{pathname:t,search:o,hash:e}=window.location,n=function(t,o){if(t.length<=1)return"?"===t?"":t;const e=t.slice(1).split("&"),n=e.filter((t=>!o.includes(f(t.split("=")[0]))));return n.length===e.length?t:n.length>0?`?${n.join("&")}`:""}(o,d),r=p(e);if(n===o&&r===e)return;window.history.replaceState(window.history.state,"",`${t}${n}${r}`)}catch{}}function k(t,o){try{o()}catch(t){}}function P(t){if("undefined"==typeof window||D)return!1;try{const o=t??{};if(!T){const t=new URLSearchParams(window.location.search),o=t.get("movmo_exit");if(null===o)return $(),!1;T=!0,A={exit:o,state:t.get("movmo_state"),bookingId:t.get("movmo_booking_id"),pnr:U(window.location.hash)},$()}if(!A)return!1;const e=function(){try{const t=sessionStorage.getItem(v);if(!t)return null;const o=JSON.parse(t);if(o&&"string"==typeof o.state&&""!==o.state&&"string"==typeof o.offerId&&"number"==typeof o.startedAt)return Date.now()-o.startedAt>w?(I(),null):{state:o.state,offerId:o.offerId,startedAt:o.startedAt,..."string"==typeof o.providerId?{providerId:o.providerId}:{},..."string"==typeof o.airlineRef?{airlineRef:o.airlineRef}:{},..."boolean"==typeof o.isProd?{isProd:o.isProd}:{}}}catch{}return null}();if(e&&!function(t,o){return!(t.iataCode&&o.airlineRef&&t.iataCode!==o.airlineRef||t.providerID&&o.providerId&&t.providerID!==o.providerId||t.offerId&&o.offerId&&t.offerId!==o.offerId)}(o,e))return!1;const{exit:n,state:r,bookingId:i,pnr:a}=A;if(A=null,D=!0,!e||!r||r!==e.state)return!1;I();const c=O.includes(n)?n:"search_again",m=e.airlineRef??o.iataCode,l=e.providerId??o.providerID;if("booking_confirmed"===c&&i){const t=a?.trim(),e={bookingId:i,...t?{airlinePnr:t}:{},...void 0!==m?{airlineRef:m}:{},...void 0!==l?{providerId:l}:{}},{onBookingComplete:n}=o;n&&k(0,(()=>n(e)))}const{onExit:f}=o;f&&k(0,(()=>f({reason:c})));const d=e.isProd??o.isProd;return void 0!==d&&E(m??"",d),R(s.CHECKOUT_RETURNED,{reason:c,ms_away:Date.now()-e.startedAt}),!0}catch(t){return!1}}const S=({iataCode:i,apiKey:a,providerID:c,flightOffer:f,flightOfferID:d,isProd:u=!1,className:p,returnUrl:h,onExit:g,onBookingComplete:w,onError:I})=>{const[O,A]=e(!1),[T,D]=e(!1),U=n(null),$=n(null),k=((t,o,e=!1)=>{const n=e?"https://flights.movmo.io":"https://flights.e2e.movmo.io",r=m("REACT_APP_MOVMO_CHECKOUT_API_URL")||`${n}/v1/proxy`;return{async post(e,n){const i=`${r.replace(/\/+$/,"")}/${e.replace(/^\/+/,"")}`,s=new AbortController,a=setTimeout((()=>s.abort()),3e4);try{const r=await fetch(i,{method:"POST",headers:l(t,o),body:JSON.stringify(n),credentials:"include",signal:s.signal});if(!r.ok){let t;try{t=await r.json()}catch{}throw Object.assign(new Error(`Movmo API request failed: ${r.status} ${r.statusText} (${e})`),{status:r.status,body:t})}return await r.json()}finally{clearTimeout(a)}}}})(a,i,u),S={iataCode:i,providerID:c,isProd:u,offerId:d,onExit:g,onBookingComplete:w},x=n(S);x.current=S,r((()=>{if(E(i,u),"undefined"==typeof IntersectionObserver||!U.current)return;const t=new IntersectionObserver((o=>{o.some((t=>t.isIntersecting))&&(R(s.BUTTON_VIEWED),t.disconnect())}),{threshold:.5});return t.observe(U.current),()=>t.disconnect()}),[]),r((()=>{P(x.current)}),[]),r((()=>{if("undefined"==typeof window)return;const t=t=>{t.persisted&&D(!1)};return window.addEventListener("pageshow",t),()=>window.removeEventListener("pageshow",t)}),[]);const L=`\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 ${T?"movmo-cursor-progress":"movmo-cursor-pointer"}\n movmo-inline-grid movmo-place-items-center\n movmo-transition-all movmo-duration-200\n movmo-outline-none\n ${O?"movmo-bg-gradient-hover":"movmo-bg-gradient-normal"}\n ${p??""}\n `.trim(),N="\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(),M="movmo-col-start-1 movmo-row-start-1 movmo-inline-flex movmo-items-center";return t("button",{ref:U,onClick:async()=>{if(T)return;D(!0),$.current=null,R(s.BUTTON_CLICKED);let t=d;if(!t&&f){R(s.OFFER_SAVE_STARTED);const o=Date.now(),e=await(async(t,o,e)=>{try{const n=await e.post(`/v1/flights/providers/${t}/offers`,o);return n?.offer_id?{ok:!0,offerId:n.offer_id}:{ok:!1,message:"no offer_id in response"}}catch(t){const o=t?.status,e=t?.body,n=(t=>{if(!t||"object"!=typeof t)return;const{message:o,error:e}=t;if("string"==typeof o&&o)return o;if("string"==typeof e&&e)return e;if(e&&"object"==typeof e){const t=e.message;if("string"==typeof t&&t)return t}})(e)??(t instanceof Error?t.message:String(t));return{ok:!1,status:o,message:n,cause:t}}})(c,f,k),n=Date.now()-o;if(!e.ok)return R(s.OFFER_SAVE_FAILED,{latency_ms:n}),I?.({stage:"save_offer",status:e.status,message:e.message}),void D(!1);R(s.OFFER_SAVE_SUCCEEDED,{latency_ms:n}),t=e.offerId}if(!t)return I?.({stage:"missing_offer",message:"neither flightOfferID nor flightOffer was provided"}),void D(!1);const o=function(){try{const t=globalThis.crypto;if(t&&"function"==typeof t.randomUUID)return t.randomUUID();if(t&&"function"==typeof t.getRandomValues){const o=t.getRandomValues(new Uint8Array(16));return Array.from(o,(t=>t.toString(16).padStart(2,"0"))).join("")}}catch{}return null}();o&&function(t){try{sessionStorage.setItem(v,JSON.stringify(t))}catch{}}({state:o,offerId:t,startedAt:Date.now(),providerId:c,airlineRef:i,isProd:u});const e=y({offerId:t,providerId:c,airlineRef:i,mvs:b(),internal:C(),returnUrl:h??_(window.location.href),state:o,isProd:u});R(s.CHECKOUT_REDIRECT_STARTED);try{window.location.assign(e)}catch(t){D(!1)}},onMouseEnter:()=>{A(!0),$.current=Date.now()},onMouseLeave:()=>{if(A(!1),null!==$.current){const t=Date.now()-$.current;$.current=null,t>=200&&R(s.BUTTON_HOVERED,{dwell_ms:t})}},className:L,disabled:T,"aria-busy":T?"true":void 0,children:[t("span",{className:`${M} ${T?"movmo-invisible":""}`.trim(),children:["Express Checkout",o("span",{className:N,children:"Movmo"})]}),t("span",{className:`${M} movmo-gap-2 ${T?"":"movmo-invisible"}`.trim(),"aria-hidden":T?void 0:"true",children:[o("span",{className:"movmo-checkout-spinner","aria-hidden":"true"}),"Opening Movmo…"]})]})};export{S as MovmoCheckoutButton,P as consumeMovmoCheckoutReturn};
|
|
7
|
+
import{jsxs as e,jsx as t}from"react/jsx-runtime";import{useState as n,useRef as o,useEffect as r}from"react";let i="granted",s=!1;function a(){return typeof navigator<"u"&&!0===navigator.globalPrivacyControl}function c(){return s?"granted"===i:"granted"===i&&!a()}const l=Object.freeze({SEARCH_PERFORMED:"search_performed",RESULTS_VIEWED:"results_viewed",FARE_COMPARED:"fare_compared",OFFER_SELECTED:"offer_selected",CHECKOUT_STARTED:"checkout_started",CONTACT_INFO_COMPLETED:"contact_info_completed",PASSENGER_INFO_COMPLETED:"passenger_info_completed",PASSENGER_AUTOFILLED:"passenger_autofilled",PASSENGER_FORM_CLEARED:"passenger_form_cleared",PASSENGER_SELECTED:"passenger_selected",SEAT_MAP_OPENED:"seat_map_opened",SEAT_SELECTED:"seat_selected",BAG_ADDED:"bag_added",BAG_REMOVED:"bag_removed",INSURANCE_SELECTED:"insurance_selected",OFFER_EXPIRY_WARNING:"offer_expiry_warning",OFFER_EXPIRED:"offer_expired",EXPIRED_MODAL_ACTION:"expired_modal_action",PAYMENT_STARTED:"payment_started",PAYMENT_SUBMITTED:"payment_submitted",PAYMENT_FAILED:"payment_failed",BOOKING_CONFIRMED:"booking_confirmed",CONFIRMATION_VIEWED:"confirmation_viewed",BOOKING_RATED:"booking_rated",REFERRAL_CLICKED:"referral_clicked",AIRLINE_HELP_CLICKED:"airline_help_clicked",SIGNIN_WALL_SHOWN:"signin_wall_shown",SIGNIN_STARTED:"signin_started",OTP_REQUESTED:"otp_requested",OTP_VERIFIED:"otp_verified",OAUTH_CONSENT_VIEWED:"oauth_consent_viewed",OAUTH_CONSENT_GRANTED:"oauth_consent_granted",OAUTH_CONSENT_DENIED:"oauth_consent_denied",SIGN_IN:"sign_in",SIGN_OUT:"sign_out",PROFILE_UPDATED:"profile_updated",PAYMENT_METHOD_ADDED:"payment_method_added",PASSENGER_SAVED:"passenger_saved",LOYALTY_PROGRAM_ADDED:"loyalty_program_added",PAYMENT_METHOD_AUTOSELECTED:"payment_method_autoselected",PAYMENT_METHOD_SELECTED:"payment_method_selected",PAYMENT_METHOD_EDITED:"payment_method_edited",PAYMENT_METHOD_DELETED:"payment_method_deleted",PAYMENT_METHOD_SET_DEFAULT:"payment_method_set_default",FORM_VALIDATION_ERROR:"form_validation_error",LOCALE_CHANGED:"locale_changed",CURRENCY_CHANGED:"currency_changed",LOYALTY_PROGRAM_OPTED_IN:"loyalty_program_opted_in",LOYALTY_PROGRAM_OPTED_OUT:"loyalty_program_opted_out",LOYALTY_PROGRAM_HOVERED:"loyalty_program_hovered",PLUGIN_LOADED:"plugin_loaded",BUTTON_VIEWED:"button_viewed",BUTTON_HOVERED:"button_hovered",BUTTON_CLICKED:"button_clicked",OFFER_SAVE_STARTED:"offer_save_started",OFFER_SAVE_SUCCEEDED:"offer_save_succeeded",OFFER_SAVE_FAILED:"offer_save_failed",CHECKOUT_REDIRECT_STARTED:"checkout_redirect_started",CHECKOUT_RETURNED:"checkout_returned",PASSKEY_PROMPT_SHOWN:"passkey_prompt_shown",PASSKEY_PROMPT_ACCEPTED:"passkey_prompt_accepted",PASSKEY_PROMPT_DECLINED:"passkey_prompt_declined"}),d=Object.freeze({CLICK:"$click",RAGE_CLICK:"$rage_click",HOVER:"$hover",FIELD_ENGAGED:"$field_engaged",SECTION_VIEWED:"$section_viewed",SCROLL:"$scroll",EXCEPTION:"$exception",PAGE:"$page",VITAL:"$vital",API_TIMING:"$api_timing"});Object.values(l),Object.values(d);class u{constructor(e){this.buf=[],this.retryBatches=[],this.destroyed=!1,this.timer=null,this.pagehideHandler=null,this.endpoint=e.endpoint,this.maxBatch=e.maxBatch??25;const t=e.flushIntervalMs??1e4;this.timer=setInterval((()=>{this.flush()}),t)}enqueue(e){c()&&(this.buf.push(e),this.buf.length>=this.maxBatch&&setTimeout((()=>{this.flush()}),0))}async flush(){if(!c())return this.buf=[],void(this.retryBatches=[]);const e=this.retryBatches.splice(0);this.buf.length>0&&e.push({events:this.buf.splice(0,this.maxBatch),attempts:0});for(const t of e)try{const e=await fetch(this.endpoint,{method:"POST",keepalive:!0,headers:{"Content-Type":"application/json"},body:JSON.stringify({events:t.events})});if(!e.ok)throw new Error("collector http "+e.status)}catch{!this.destroyed&&t.attempts<2&&this.retryBatches.push({events:t.events,attempts:t.attempts+1})}}installPagehideFlush(){this.pagehideHandler=()=>{if(!c())return this.buf=[],void(this.retryBatches=[]);const e=this.retryBatches.splice(0).flatMap((e=>e.events)).concat(this.buf.splice(0,this.buf.length));if(0!==e.length)for(let t=0;t<e.length;t+=this.maxBatch)this.sendOnUnload(e.slice(t,t+this.maxBatch))},window.addEventListener("pagehide",this.pagehideHandler)}sendOnUnload(e){const t=JSON.stringify({events:e});try{if("function"==typeof fetch)return void fetch(this.endpoint,{method:"POST",keepalive:!0,credentials:"omit",headers:{"Content-Type":"text/plain;charset=UTF-8"},body:t}).catch((()=>{}));typeof navigator<"u"&&"function"==typeof navigator.sendBeacon&&navigator.sendBeacon(this.endpoint,t)}catch{}}destroy(){this.destroyed=!0,this.timer&&clearInterval(this.timer),this.pagehideHandler&&window.removeEventListener("pagehide",this.pagehideHandler),this.buf=[],this.retryBatches=[]}}const f="mv_sid",m="mv_seq",_="mv_uid",h="mv_internal",p=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function v(e){try{return sessionStorage.getItem(e)}catch{return null}}function E(e,t){try{sessionStorage.setItem(e,t)}catch{}}let g=null,I=0,y=null,T=!1;function R(){if(g)return;const e=function(){try{const e=new URLSearchParams(window.location.search).get("mvs");if(e)return e;const t=window.location.hash,n=t.indexOf("?");return-1===n?null:new URLSearchParams(t.slice(n+1)).get("mvs")}catch{return null}}();!e||!p.test(e)||(v(f)!==e&&(I=0,E(m,"0")),g=e,E(f,e))}function O(e){return"1"===e||"true"===e}function w(e){(e||O(function(){try{const e=new URLSearchParams(window.location.search).get("mv_internal");if(e)return e;const t=window.location.hash,n=t.indexOf("?");return-1===n?null:new URLSearchParams(t.slice(n+1)).get("mv_internal")}catch{return null}}())||O(v(h)))&&(T=!0,E(h,"1"))}function D(){return!!T||(T=O(v(h)),T)}function A(){if(g)return g;const e=v(f);if(e)return g=e,e;if(R(),g)return g;const t=typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(e=>{const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)}));return g=t,E(f,t),t}function S(){if(0===I){const e=Number(v(m)??0);I=Number.isFinite(e)?e:0}return I+=1,E(m,String(I)),I}function x(e){if(y=e,null===e)try{sessionStorage.removeItem(_)}catch{}else E(_,e)}function C(e){let t=!1;try{t=window.self!==window.top}catch{t=!0}const n=typeof location<"u"?e?location.hostname:location.pathname:"",o=e?"":typeof document<"u"?document.referrer:"";return{page:n.slice(0,512),referrer:o.slice(0,512),viewport:typeof window<"u"?`${window.innerWidth}x${window.innerHeight}`:"0x0",locale:typeof navigator<"u"?navigator.language:"",embedded:t}}const P=new class{constructor(){this.config=null,this.queue=null,this.teardowns=[]}init(e){var t;this.config||(this.config=e,t=e.consent,s||(i=t??"granted",a()&&(i="denied")),R(),w(!0===e.internal),this.queue=new u({endpoint:e.endpoint,flushIntervalMs:e.flushIntervalMs,maxBatch:e.maxBatch}),this.queue.installPagehideFlush())}registerTeardown(e){this.teardowns.push(e)}isScoped(){var e;return!0===(null==(e=this.config)?void 0:e.scoped)}isInitialized(){return null!==this.config}getSessionId(){return this.config?A():null}isInternal(){return!!this.config&&D()}buildEvent(e,t){var n;if(!this.config)throw new Error("@movmo_app/analytics: buildEvent before init");const o=this.config;return{event_id:typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(e=>{const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)})),ts:(new Date).toISOString(),schema_version:1,app:o.app,env:o.env,partner_id:o.partnerId??null,session_id:A(),seq:S(),user_id:y||(y=v(_),y),event_name:e,props:t,context:C(!0===(null==(n=this.config)?void 0:n.scoped)),is_internal:D()}}track(e,t={}){try{if(!this.config||!this.queue)return;this.queue.enqueue(this.buildEvent(e,t))}catch{}}page(e){var t;const n=!0===(null==(t=this.config)?void 0:t.scoped),o=typeof location<"u"?n?location.hostname:location.pathname:"";this.track(d.PAGE,{name:e??o})}identify(e){x(e)}reset(){x(null)}setConsent(e){s=!0,i=e.analytics?"granted":"denied"}shutdown(){var e;for(const e of this.teardowns)try{e()}catch{}this.teardowns=[],null==(e=this.queue)||e.destroy(),this.queue=null,this.config=null,function(){g=null,I=0,y=null,T=!1;try{sessionStorage.removeItem(f),sessionStorage.removeItem(m),sessionStorage.removeItem(_),sessionStorage.removeItem(h)}catch{}}(),s=!1,i="granted"}},N=!0;function b(e){try{const t=globalThis.process,n=t?.env?.[e];return"string"==typeof n&&""!==n?n:void 0}catch{return}}function U(e){const t=b(e);if(void 0!==t)return function(e){try{const t=new URL(e);if(t.username||t.password)return!1;const n=t.hostname.toLowerCase();return"https:"===t.protocol?"movmo.io"===n||n.endsWith(".movmo.io"):"http:"===t.protocol&&("localhost"===n||"127.0.0.1"===n)}catch{return!1}}(t)?t:void 0}const L=(e,t)=>{const n={Accept:"application/json","Content-Type":"application/json","x-api-key":e,"X-Forwarded-Host":"undefined"!=typeof window?window.location.host:"","movmo-customer-id":t},o=b("REACT_APP_CLOUD_FRONT_PROXY_SECRET_HEADER");"undefined"==typeof window||"localhost"!==window.location.hostname&&"127.0.0.1"!==window.location.hostname||!o||(n["X-Movmo-Proxy-Auth"]=o);const r=(e=>{if("undefined"==typeof document)return null;const t=document.cookie.split(";");for(let n=0;n<t.length;n++){const o=t[n].trim();if(o.startsWith(e+"="))return decodeURIComponent(o.substring(e.length+1))}return null})("movmo_csrf_token");return r&&(n["X-CSRF-Token"]=r),n},M=(e,t,n=!1,o="flights")=>{const r=t,i="events"===o,s=i?n?"https://events.movmo.io":"https://events.e2e.movmo.io":n?"https://flights.movmo.io":"https://flights.e2e.movmo.io",a=(i?void 0:U("REACT_APP_MOVMO_CHECKOUT_API_URL"))||`${s}/v1/proxy`;return{async post(t,n){const o=`${a.replace(/\/+$/,"")}/${t.replace(/^\/+/,"")}`,i=new AbortController,s=setTimeout((()=>i.abort()),3e4);try{const s=await fetch(o,{method:"POST",headers:L(e,r),body:JSON.stringify(n),credentials:"include",signal:i.signal});if(!s.ok){let e;try{e=await s.json()}catch{}throw Object.assign(new Error(`Movmo API request failed: ${s.status} ${s.statusText} (${t})`),{status:s.status,body:e})}return await s.json()}finally{clearTimeout(s)}}}},k=async(e,t,n)=>{try{const o=await n.post(e,t);if(!o?.offer_id){return{ok:!1,message:"no offer_id in response"}}return{ok:!0,offerId:o.offer_id}}catch(e){const t=e?.status,n=e?.body,o=(e=>{if(!e||"object"!=typeof e)return;const{message:t,error:n}=e;if("string"==typeof t&&t)return t;if("string"==typeof n&&n)return n;if(n&&"object"==typeof n){const e=n.message;if("string"==typeof e&&e)return e}})(n)??(e instanceof Error?e.message:String(e));return{ok:!1,status:t,message:o,cause:e}}};function F(e){try{return decodeURIComponent(e)}catch{return e}}const $=["movmo_exit","movmo_state","movmo_booking_id","movmo_pnr"];const H=/^movmo_pnr(?:=.*)?$/;function B(e){if(e.length<=1)return"";const t=e.slice(1).split(/([?&])/);let n="",o=null,r=!1;for(let e=0;e<t.length;e+=2){const i=0===e?"":t[e-1],s=t[e];if(H.test(s)){r=!0,null===o&&(o=i);continue}let a=i;null!==o&&(""!==o&&"?"!==o||(a=""===n?"":o),o=null),n+=a+s}return r?""===n?"":`#${n}`:e}const V="movmo:checkout:pending",G="https://flights.movmo.io",Y="https://flights.e2e.movmo.io",K="https://events.movmo.io",j="https://events.e2e.movmo.io",q=864e5;function W(e){const t=new URLSearchParams({offerId:e.offerId,providerId:e.providerId,sellerRef:e.sellerRef});return e.mvs&&t.set("mvs",e.mvs),e.internal&&t.set("mv_internal","1"),t.set("returnUrl",e.returnUrl),e.state&&t.set("state",e.state),`${function(e){const t=U("REACT_APP_MOVMO_EVENTS_CHECKOUT_URL");return t?t.replace(/\/+$/,""):e?K:j}(e.isProd)}/booking?${t.toString()}`}function X(e){const t=new URLSearchParams({offerId:e.offerId,providerId:e.providerId,airlineRef:e.airlineRef});return e.mvs&&t.set("mvs",e.mvs),e.internal&&t.set("mv_internal","1"),t.set("returnUrl",e.returnUrl),e.state&&t.set("state",e.state),`${function(e){const t=U("REACT_APP_MOVMO_CHECKOUT_URL");return t?t.replace(/\/+$/,""):e?G:Y}(e.isProd)}/booking?${t.toString()}`}function J(e){const t=new URL(e),n=function(e){return/^#!?\//.test(e)}(t.hash)?B(t.hash):"";return`${t.origin}${t.pathname}${function(e){if(e.length<=1)return"?"===e?"":e;const t=e.slice(1).split("&").filter((e=>!F(e.split("=")[0]).startsWith("movmo_")));return t.length>0?`?${t.join("&")}`:""}(t.search)}${n}`}function z(){try{const e=globalThis.crypto;if(e&&"function"==typeof e.randomUUID)return e.randomUUID();if(e&&"function"==typeof e.getRandomValues){const t=e.getRandomValues(new Uint8Array(16));return Array.from(t,(e=>e.toString(16).padStart(2,"0"))).join("")}}catch{}return null}function Q(e){try{sessionStorage.setItem(V,JSON.stringify(e))}catch{}}function Z(){try{sessionStorage.removeItem(V)}catch{}}function ee(e,t){try{if(P.isInitialized())return;const n=(N?U("REACT_APP_MOVMO_ANALYTICS_URL"):void 0)||(t?"https://api.movmo.io/v1/t":"https://e2e.api.movmo.io/v1/t");P.init({app:"express-checkout-button",env:t?"prd":"e2e",partnerId:e,endpoint:n,scoped:!0}),P.track(l.PLUGIN_LOADED)}catch{}}function te(e,t={}){try{P.track(e,t)}catch{}}function ne(){try{return P.getSessionId()}catch{return null}}function oe(){try{return P.isInternal()}catch{return!1}}const re=["search_again","offer_unavailable","booking_confirmed"];let ie=null,se=!1,ae=!1;function ce(e){if(e.length<=1)return null;const t=e.lastIndexOf("?"),n=new URLSearchParams(e.slice(-1===t?1:t+1)).getAll("movmo_pnr");return n.length>0?n[n.length-1]:null}function le(){try{const{pathname:e,search:t,hash:n}=window.location,o=function(e,t){if(e.length<=1)return"?"===e?"":e;const n=e.slice(1).split("&"),o=n.filter((e=>!t.includes(F(e.split("=")[0]))));return o.length===n.length?e:o.length>0?`?${o.join("&")}`:""}(t,$),r=B(n);if(o===t&&r===n)return;window.history.replaceState(window.history.state,"",`${e}${o}${r}`)}catch{}}function de(e,t){try{t()}catch(e){}}function ue(e){if("undefined"==typeof window||ae)return!1;try{const t=e??{};if(!se){const e=new URLSearchParams(window.location.search),t=e.get("movmo_exit");if(null===t)return le(),!1;se=!0,ie={exit:t,state:e.get("movmo_state"),bookingId:e.get("movmo_booking_id"),pnr:ce(window.location.hash)},le()}if(!ie)return!1;const n=function(){try{const e=sessionStorage.getItem(V);if(!e)return null;const t=JSON.parse(e);if(t&&"string"==typeof t.state&&""!==t.state&&"string"==typeof t.offerId&&"number"==typeof t.startedAt)return Date.now()-t.startedAt>q?(Z(),null):{state:t.state,offerId:t.offerId,startedAt:t.startedAt,..."string"==typeof t.providerId?{providerId:t.providerId}:{},..."string"==typeof t.airlineRef?{airlineRef:t.airlineRef}:{},..."boolean"==typeof t.isProd?{isProd:t.isProd}:{},..."events"===t.product||"flights"===t.product?{product:t.product}:{},..."string"==typeof t.sellerRef?{sellerRef:t.sellerRef}:{}}}catch{}return null}();if(n&&!function(e,t){const n=t.product??"flights";if(void 0!==e.sellerRef){if("events"!==n)return!1;if(e.sellerRef!==t.sellerRef)return!1}else if("flights"!==n)return!1;return!(e.iataCode&&t.airlineRef&&e.iataCode!==t.airlineRef||e.providerID&&t.providerId&&e.providerID!==t.providerId||e.offerId&&t.offerId&&e.offerId!==t.offerId)}(t,n))return!1;const{exit:o,state:r,bookingId:i,pnr:s}=ie;if(ie=null,ae=!0,!n||!r||r!==n.state)return!1;Z();const a=re.includes(o)?o:"search_again",c="events"===n.product,d=c?void 0:n.airlineRef??t.iataCode,u=c?n.sellerRef??t.sellerRef:void 0,f=n.providerId??t.providerID;if("booking_confirmed"===a&&i){const e=c?void 0:s?.trim(),n={bookingId:i,...e?{airlinePnr:e}:{},...void 0!==d?{airlineRef:d}:{},...void 0!==u?{sellerRef:u}:{},...void 0!==f?{providerId:f}:{}},{onBookingComplete:o}=t;o&&de(0,(()=>o(n)))}const{onExit:m}=t;m&&de(0,(()=>m({reason:a})));const _=n.isProd??t.isProd;return void 0!==_&&ee(d??u??"",_),te(l.CHECKOUT_RETURNED,{reason:a,ms_away:Date.now()-n.startedAt}),!0}catch(e){return!1}}const fe=i=>{const{apiKey:s,providerID:a,isProd:c=!1,className:d,returnUrl:u,onExit:f,onBookingComplete:m,onError:_}=i,h=void 0!==i.sellerRef||void 0!==i.eventTicket,p=i.iataCode??"",v=i.sellerRef??"",E=i.eventTicket,{flightOffer:g,flightOfferID:I}=i,y=h?v:p,T=h&&c,[R,O]=n(!1),[w,D]=n(!1),A=o(null),S=o(null),x=h?M(s,v,c,"events"):M(s,p,c),C={...h?{sellerRef:v}:{iataCode:p},providerID:a,isProd:c,offerId:h?void 0:I,onExit:f,onBookingComplete:m},P=o(C);P.current=C,r((()=>{if(T)return;if(ee(y,c),"undefined"==typeof IntersectionObserver||!A.current)return;const e=new IntersectionObserver((t=>{t.some((e=>e.isIntersecting))&&(te(l.BUTTON_VIEWED),e.disconnect())}),{threshold:.5});return e.observe(A.current),()=>e.disconnect()}),[]),r((()=>{ue(P.current)}),[]),r((()=>{if("undefined"==typeof window)return;const e=e=>{e.persisted&&D(!1)};return window.addEventListener("pageshow",e),()=>window.removeEventListener("pageshow",e)}),[]);const N=async()=>{if(w)return;const e=c?"Movmo events checkout is not available in production yet.":function(e){const t=e;if(!t||"object"!=typeof t)return"eventTicket is required";const n=[];"string"==typeof t.eventId&&""!==t.eventId.trim()||n.push("eventTicket.eventId"),"string"==typeof t.listingId&&""!==t.listingId.trim()||n.push("eventTicket.listingId");const o=t.quantity;return("number"!=typeof o||!Number.isInteger(o)||o<1||o>20)&&n.push("eventTicket.quantity (a whole number from 1 to 20)"),n.length>0?`invalid ${n.join(", ")}`:null}(E);if(null!==e||!E||""===v.trim()||!a||!s){const t=e??"sellerRef, providerID and apiKey are required";return void _?.(Object.assign(new Error(t),{message:t,stage:c?"not_available":"invalid_options"}))}D(!0),S.current=null,te(l.BUTTON_CLICKED),te(l.OFFER_SAVE_STARTED);const t=Date.now(),n=await((e,t,n)=>k(`/v1/events/providers/${encodeURIComponent(e)}/website-offers`,{event_id:t.eventId,listing_id:t.listingId,quantity:t.quantity},n))(a,E,x),o=Date.now()-t;if(!n.ok)return te(l.OFFER_SAVE_FAILED,{latency_ms:o}),_?.({stage:"save_offer",status:n.status,message:n.message}),void D(!1);te(l.OFFER_SAVE_SUCCEEDED,{latency_ms:o});const r=z();r&&Q({state:r,offerId:n.offerId,startedAt:Date.now(),providerId:a,product:"events",sellerRef:v,isProd:c});const i=W({offerId:n.offerId,providerId:a,sellerRef:v,mvs:ne(),internal:oe(),returnUrl:u??J(window.location.href),state:r,isProd:c});te(l.CHECKOUT_REDIRECT_STARTED);try{window.location.assign(i)}catch(e){D(!1)}},b=`\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 ${w?"movmo-cursor-progress":"movmo-cursor-pointer"}\n movmo-inline-grid movmo-place-items-center\n movmo-transition-all movmo-duration-200\n movmo-outline-none\n ${R?"movmo-bg-gradient-hover":"movmo-bg-gradient-normal"}\n ${d??""}\n `.trim(),U="\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(),L="movmo-col-start-1 movmo-row-start-1 movmo-inline-flex movmo-items-center";return e("button",{ref:A,onClick:async()=>{if(h)return N();if(w)return;D(!0),S.current=null,te(l.BUTTON_CLICKED);let e=I;if(!e&&g){te(l.OFFER_SAVE_STARTED);const t=Date.now(),n=await((e,t,n)=>k(`/v1/flights/providers/${e}/offers`,t,n))(a,g,x),o=Date.now()-t;if(!n.ok)return te(l.OFFER_SAVE_FAILED,{latency_ms:o}),_?.({stage:"save_offer",status:n.status,message:n.message}),void D(!1);te(l.OFFER_SAVE_SUCCEEDED,{latency_ms:o}),e=n.offerId}if(!e)return _?.({stage:"missing_offer",message:"neither flightOfferID nor flightOffer was provided"}),void D(!1);const t=z();t&&Q({state:t,offerId:e,startedAt:Date.now(),providerId:a,airlineRef:p,isProd:c});const n=X({offerId:e,providerId:a,airlineRef:p,mvs:ne(),internal:oe(),returnUrl:u??J(window.location.href),state:t,isProd:c});te(l.CHECKOUT_REDIRECT_STARTED);try{window.location.assign(n)}catch(e){D(!1)}},onMouseEnter:()=>{O(!0),T||(S.current=Date.now())},onMouseLeave:()=>{if(O(!1),!T&&null!==S.current){const e=Date.now()-S.current;S.current=null,e>=200&&te(l.BUTTON_HOVERED,{dwell_ms:e})}},className:b,disabled:w,"aria-busy":w?"true":void 0,children:[e("span",{className:`${L} ${w?"movmo-invisible":""}`.trim(),children:["Express Checkout",t("span",{className:U,children:"Movmo"})]}),e("span",{className:`${L} movmo-gap-2 ${w?"":"movmo-invisible"}`.trim(),"aria-hidden":w?void 0:"true",children:[t("span",{className:"movmo-checkout-spinner","aria-hidden":"true"}),"Opening Movmo…"]})]})};export{fe as MovmoCheckoutButton,ue as consumeMovmoCheckoutReturn};
|
|
8
8
|
//# sourceMappingURL=index.es.js.map
|