@movmo_app/payments 0.2.0 → 0.3.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/dist/index.cjs.js +10 -10
- package/dist/index.cjs.js.map +1 -1
- package/dist/index.d.ts +156 -6
- package/dist/index.es.js +1308 -930
- package/dist/index.es.js.map +1 -1
- package/dist/style.css +1 -1
- package/package.json +1 -1
package/dist/index.cjs.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const o=require("react");var Xe={exports:{}},Oe={};/**
|
|
2
2
|
* @license React
|
|
3
3
|
* react-jsx-runtime.production.min.js
|
|
4
4
|
*
|
|
@@ -6,7 +6,7 @@
|
|
|
6
6
|
*
|
|
7
7
|
* This source code is licensed under the MIT license found in the
|
|
8
8
|
* LICENSE file in the root directory of this source tree.
|
|
9
|
-
*/var
|
|
9
|
+
*/var dr;function Vr(){if(dr)return Oe;dr=1;var r=o,t=Symbol.for("react.element"),n=Symbol.for("react.fragment"),i=Object.prototype.hasOwnProperty,c=r.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,d={key:!0,ref:!0,__self:!0,__source:!0};function p(v,h,D){var C,y={},b=null,_=null;D!==void 0&&(b=""+D),h.key!==void 0&&(b=""+h.key),h.ref!==void 0&&(_=h.ref);for(C in h)i.call(h,C)&&!d.hasOwnProperty(C)&&(y[C]=h[C]);if(v&&v.defaultProps)for(C in h=v.defaultProps,h)y[C]===void 0&&(y[C]=h[C]);return{$$typeof:t,type:v,key:b,ref:_,props:y,_owner:c.current}}return Oe.Fragment=n,Oe.jsx=p,Oe.jsxs=p,Oe}var De={};/**
|
|
10
10
|
* @license React
|
|
11
11
|
* react-jsx-runtime.development.js
|
|
12
12
|
*
|
|
@@ -14,18 +14,18 @@
|
|
|
14
14
|
*
|
|
15
15
|
* This source code is licensed under the MIT license found in the
|
|
16
16
|
* LICENSE file in the root directory of this source tree.
|
|
17
|
-
*/var
|
|
18
|
-
`+
|
|
19
|
-
`),
|
|
20
|
-
`)
|
|
21
|
-
`+
|
|
17
|
+
*/var ur;function qr(){return ur||(ur=1,process.env.NODE_ENV!=="production"&&function(){var r=o,t=Symbol.for("react.element"),n=Symbol.for("react.portal"),i=Symbol.for("react.fragment"),c=Symbol.for("react.strict_mode"),d=Symbol.for("react.profiler"),p=Symbol.for("react.provider"),v=Symbol.for("react.context"),h=Symbol.for("react.forward_ref"),D=Symbol.for("react.suspense"),C=Symbol.for("react.suspense_list"),y=Symbol.for("react.memo"),b=Symbol.for("react.lazy"),_=Symbol.for("react.offscreen"),M=Symbol.iterator,S="@@iterator";function G(e){if(e===null||typeof e!="object")return null;var s=M&&e[M]||e[S];return typeof s=="function"?s:null}var w=r.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;function P(e){{for(var s=arguments.length,l=new Array(s>1?s-1:0),m=1;m<s;m++)l[m-1]=arguments[m];q("error",e,l)}}function q(e,s,l){{var m=w.ReactDebugCurrentFrame,k=m.getStackAddendum();k!==""&&(s+="%s",l=l.concat([k]));var O=l.map(function(E){return String(E)});O.unshift("Warning: "+s),Function.prototype.apply.call(console[e],console,O)}}var le=!1,Q=!1,j=!1,te=!1,fe=!1,I;I=Symbol.for("react.module.reference");function T(e){return!!(typeof e=="string"||typeof e=="function"||e===i||e===d||fe||e===c||e===D||e===C||te||e===_||le||Q||j||typeof e=="object"&&e!==null&&(e.$$typeof===b||e.$$typeof===y||e.$$typeof===p||e.$$typeof===v||e.$$typeof===h||e.$$typeof===I||e.getModuleId!==void 0))}function u(e,s,l){var m=e.displayName;if(m)return m;var k=s.displayName||s.name||"";return k!==""?l+"("+k+")":l}function F(e){return e.displayName||"Context"}function R(e){if(e==null)return null;if(typeof e.tag=="number"&&P("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."),typeof e=="function")return e.displayName||e.name||null;if(typeof e=="string")return e;switch(e){case i:return"Fragment";case n:return"Portal";case d:return"Profiler";case c:return"StrictMode";case D:return"Suspense";case C:return"SuspenseList"}if(typeof e=="object")switch(e.$$typeof){case v:var s=e;return F(s)+".Consumer";case p:var l=e;return F(l._context)+".Provider";case h:return u(e,e.render,"ForwardRef");case y:var m=e.displayName||null;return m!==null?m:R(e.type)||"Memo";case b:{var k=e,O=k._payload,E=k._init;try{return R(E(O))}catch{return null}}}return null}var $=Object.assign,H=0,B,X,Y,N,W,de,me;function ve(){}ve.__reactDisabledLog=!0;function be(){{if(H===0){B=console.log,X=console.info,Y=console.warn,N=console.error,W=console.group,de=console.groupCollapsed,me=console.groupEnd;var e={configurable:!0,enumerable:!0,value:ve,writable:!0};Object.defineProperties(console,{info:e,log:e,warn:e,error:e,group:e,groupCollapsed:e,groupEnd:e})}H++}}function ce(){{if(H--,H===0){var e={configurable:!0,enumerable:!0,writable:!0};Object.defineProperties(console,{log:$({},e,{value:B}),info:$({},e,{value:X}),warn:$({},e,{value:Y}),error:$({},e,{value:N}),group:$({},e,{value:W}),groupCollapsed:$({},e,{value:de}),groupEnd:$({},e,{value:me})})}H<0&&P("disabledDepth fell below zero. This is a bug in React. Please file an issue.")}}var ge=w.ReactCurrentDispatcher,pe;function K(e,s,l){{if(pe===void 0)try{throw Error()}catch(k){var m=k.stack.trim().match(/\n( *(at )?)/);pe=m&&m[1]||""}return`
|
|
18
|
+
`+pe+e}}var ae=!1,ne;{var he=typeof WeakMap=="function"?WeakMap:Map;ne=new he}function xe(e,s){if(!e||ae)return"";{var l=ne.get(e);if(l!==void 0)return l}var m;ae=!0;var k=Error.prepareStackTrace;Error.prepareStackTrace=void 0;var O;O=ge.current,ge.current=null,be();try{if(s){var E=function(){throw Error()};if(Object.defineProperty(E.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(E,[])}catch(re){m=re}Reflect.construct(e,[],E)}else{try{E.call()}catch(re){m=re}e.call(E.prototype)}}else{try{throw Error()}catch(re){m=re}e()}}catch(re){if(re&&m&&typeof re.stack=="string"){for(var x=re.stack.split(`
|
|
19
|
+
`),Z=m.stack.split(`
|
|
20
|
+
`),U=x.length-1,L=Z.length-1;U>=1&&L>=0&&x[U]!==Z[L];)L--;for(;U>=1&&L>=0;U--,L--)if(x[U]!==Z[L]){if(U!==1||L!==1)do if(U--,L--,L<0||x[U]!==Z[L]){var ie=`
|
|
21
|
+
`+x[U].replace(" at new "," at ");return e.displayName&&ie.includes("<anonymous>")&&(ie=ie.replace("<anonymous>",e.displayName)),typeof e=="function"&&ne.set(e,ie),ie}while(U>=1&&L>=0);break}}}finally{ae=!1,ge.current=O,ce(),Error.prepareStackTrace=k}var ke=e?e.displayName||e.name:"",je=ke?K(ke):"";return typeof e=="function"&&ne.set(e,je),je}function Ee(e,s,l){return xe(e,!1)}function we(e){var s=e.prototype;return!!(s&&s.isReactComponent)}function se(e,s,l){if(e==null)return"";if(typeof e=="function")return xe(e,we(e));if(typeof e=="string")return K(e);switch(e){case D:return K("Suspense");case C:return K("SuspenseList")}if(typeof e=="object")switch(e.$$typeof){case h:return Ee(e.render);case y:return se(e.type,s,l);case b:{var m=e,k=m._payload,O=m._init;try{return se(O(k),s,l)}catch{}}}return""}var g=Object.prototype.hasOwnProperty,A={},z=w.ReactDebugCurrentFrame;function ue(e){if(e){var s=e._owner,l=se(e.type,e._source,s?s.type:null);z.setExtraStackFrame(l)}else z.setExtraStackFrame(null)}function Ue(e,s,l,m,k){{var O=Function.call.bind(g);for(var E in e)if(O(e,E)){var x=void 0;try{if(typeof e[E]!="function"){var Z=Error((m||"React class")+": "+l+" type `"+E+"` is invalid; it must be a function, usually from the `prop-types` package, but received `"+typeof e[E]+"`.This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.");throw Z.name="Invariant Violation",Z}x=e[E](s,E,m,l,null,"SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED")}catch(U){x=U}x&&!(x instanceof Error)&&(ue(k),P("%s: type specification of %s `%s` is invalid; the type checker function must return `null` or an `Error` but returned a %s. You may have forgotten to pass an argument to the type checker creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and shape all require an argument).",m||"React class",l,E,typeof x),ue(null)),x instanceof Error&&!(x.message in A)&&(A[x.message]=!0,ue(k),P("Failed %s type: %s",l,x.message),ue(null))}}}var Ie=Array.isArray;function f(e){return Ie(e)}function oe(e){{var s=typeof Symbol=="function"&&Symbol.toStringTag,l=s&&e[Symbol.toStringTag]||e.constructor.name||"Object";return l}}function ee(e){try{return V(e),!1}catch{return!0}}function V(e){return""+e}function Ae(e){if(ee(e))return P("The provided key is an unsupported type %s. This value must be coerced to a string before before using it here.",oe(e)),V(e)}var ye=w.ReactCurrentOwner,Le={key:!0,ref:!0,__self:!0,__source:!0},rr,tr;function Nr(e){if(g.call(e,"ref")){var s=Object.getOwnPropertyDescriptor(e,"ref").get;if(s&&s.isReactWarning)return!1}return e.ref!==void 0}function Sr(e){if(g.call(e,"key")){var s=Object.getOwnPropertyDescriptor(e,"key").get;if(s&&s.isReactWarning)return!1}return e.key!==void 0}function Pr(e,s){typeof e.ref=="string"&&ye.current}function Tr(e,s){{var l=function(){rr||(rr=!0,P("%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)",s))};l.isReactWarning=!0,Object.defineProperty(e,"key",{get:l,configurable:!0})}}function Fr(e,s){{var l=function(){tr||(tr=!0,P("%s: `ref` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)",s))};l.isReactWarning=!0,Object.defineProperty(e,"ref",{get:l,configurable:!0})}}var Or=function(e,s,l,m,k,O,E){var x={$$typeof:t,type:e,key:s,ref:l,props:E,_owner:O};return x._store={},Object.defineProperty(x._store,"validated",{configurable:!1,enumerable:!1,writable:!0,value:!1}),Object.defineProperty(x,"_self",{configurable:!1,enumerable:!1,writable:!1,value:m}),Object.defineProperty(x,"_source",{configurable:!1,enumerable:!1,writable:!1,value:k}),Object.freeze&&(Object.freeze(x.props),Object.freeze(x)),x};function Dr(e,s,l,m,k){{var O,E={},x=null,Z=null;l!==void 0&&(Ae(l),x=""+l),Sr(s)&&(Ae(s.key),x=""+s.key),Nr(s)&&(Z=s.ref,Pr(s,k));for(O in s)g.call(s,O)&&!Le.hasOwnProperty(O)&&(E[O]=s[O]);if(e&&e.defaultProps){var U=e.defaultProps;for(O in U)E[O]===void 0&&(E[O]=U[O])}if(x||Z){var L=typeof e=="function"?e.displayName||e.name||"Unknown":e;x&&Tr(E,L),Z&&Fr(E,L)}return Or(e,x,Z,k,m,ye.current,E)}}var Be=w.ReactCurrentOwner,ar=w.ReactDebugCurrentFrame;function Ce(e){if(e){var s=e._owner,l=se(e.type,e._source,s?s.type:null);ar.setExtraStackFrame(l)}else ar.setExtraStackFrame(null)}var Ye;Ye=!1;function ze(e){return typeof e=="object"&&e!==null&&e.$$typeof===t}function nr(){{if(Be.current){var e=R(Be.current.type);if(e)return`
|
|
22
22
|
|
|
23
|
-
Check the render method of \``+e+"`."}return""}}function
|
|
23
|
+
Check the render method of \``+e+"`."}return""}}function Wr(e){return""}var sr={};function Mr(e){{var s=nr();if(!s){var l=typeof e=="string"?e:e.displayName||e.name;l&&(s=`
|
|
24
24
|
|
|
25
|
-
Check the top-level render call using <`+l+">.")}return
|
|
25
|
+
Check the top-level render call using <`+l+">.")}return s}}function or(e,s){{if(!e._store||e._store.validated||e.key!=null)return;e._store.validated=!0;var l=Mr(s);if(sr[l])return;sr[l]=!0;var m="";e&&e._owner&&e._owner!==Be.current&&(m=" It was passed a child from "+R(e._owner.type)+"."),Ce(e),P('Each child in a list should have a unique "key" prop.%s%s See https://reactjs.org/link/warning-keys for more information.',l,m),Ce(null)}}function ir(e,s){{if(typeof e!="object")return;if(f(e))for(var l=0;l<e.length;l++){var m=e[l];ze(m)&&or(m,s)}else if(ze(e))e._store&&(e._store.validated=!0);else if(e){var k=G(e);if(typeof k=="function"&&k!==e.entries)for(var O=k.call(e),E;!(E=O.next()).done;)ze(E.value)&&or(E.value,s)}}}function Ar(e){{var s=e.type;if(s==null||typeof s=="string")return;var l;if(typeof s=="function")l=s.propTypes;else if(typeof s=="object"&&(s.$$typeof===h||s.$$typeof===y))l=s.propTypes;else return;if(l){var m=R(s);Ue(l,e.props,"prop",m,e)}else if(s.PropTypes!==void 0&&!Ye){Ye=!0;var k=R(s);P("Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?",k||"Unknown")}typeof s.getDefaultProps=="function"&&!s.getDefaultProps.isReactClassApproved&&P("getDefaultProps is only used on classic React.createClass definitions. Use a static property named `defaultProps` instead.")}}function $r(e){{for(var s=Object.keys(e.props),l=0;l<s.length;l++){var m=s[l];if(m!=="children"&&m!=="key"){Ce(e),P("Invalid prop `%s` supplied to `React.Fragment`. React.Fragment can only have `key` and `children` props.",m),Ce(null);break}}e.ref!==null&&(Ce(e),P("Invalid attribute `ref` supplied to `React.Fragment`."),Ce(null))}}var lr={};function cr(e,s,l,m,k,O){{var E=T(e);if(!E){var x="";(e===void 0||typeof e=="object"&&e!==null&&Object.keys(e).length===0)&&(x+=" You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.");var Z=Wr();Z?x+=Z:x+=nr();var U;e===null?U="null":f(e)?U="array":e!==void 0&&e.$$typeof===t?(U="<"+(R(e.type)||"Unknown")+" />",x=" Did you accidentally export a JSX literal instead of a component?"):U=typeof e,P("React.jsx: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: %s.%s",U,x)}var L=Dr(e,s,l,k,O);if(L==null)return L;if(E){var ie=s.children;if(ie!==void 0)if(m)if(f(ie)){for(var ke=0;ke<ie.length;ke++)ir(ie[ke],e);Object.freeze&&Object.freeze(ie)}else P("React.jsx: Static children should always be an array. You are likely explicitly calling React.jsxs or React.jsxDEV. Use the Babel transform instead.");else ir(ie,e)}if(g.call(s,"key")){var je=R(e),re=Object.keys(s).filter(function(zr){return zr!=="key"}),Ve=re.length>0?"{key: someKey, "+re.join(": ..., ")+": ...}":"{key: someKey}";if(!lr[je+Ve]){var Yr=re.length>0?"{"+re.join(": ..., ")+": ...}":"{}";P(`A props object containing a "key" prop is being spread into JSX:
|
|
26
26
|
let props = %s;
|
|
27
27
|
<%s {...props} />
|
|
28
28
|
React keys must be passed directly to JSX without using spread:
|
|
29
29
|
let props = %s;
|
|
30
|
-
<%s key={someKey} {...props} />`,De,ye,Ar,ye),Qe[ye+De]=!0}}return e===o?Or(L):Tr(L),L}}function Fr(e,n,l){return er(e,n,l,!0)}function Dr(e,n,l){return er(e,n,l,!1)}var Mr=Dr,Wr=Fr;Ee.Fragment=o,Ee.jsx=Mr,Ee.jsxs=Wr}()),Ee}process.env.NODE_ENV==="production"?Ue.exports=Ir():Ue.exports=Ur();var a=Ue.exports;function cr(r){var t,s,o="";if(typeof r=="string"||typeof r=="number")o+=r;else if(typeof r=="object")if(Array.isArray(r)){var c=r.length;for(t=0;t<c;t++)r[t]&&(s=cr(r[t]))&&(o&&(o+=" "),o+=s)}else for(s in r)r[s]&&(o&&(o+=" "),o+=s);return o}function re(){for(var r,t,s=0,o="",c=arguments.length;s<c;s++)(r=arguments[s])&&(t=cr(r))&&(o&&(o+=" "),o+=t);return o}const Lr="https://core.spreedly.com/iframe/iframe-v1.min.js",Yr="https://cdn.e2e.movmo.io";let je={};const Vr=r=>{je={...je,...r}},Me=r=>{var s;const t=globalThis.process;return(s=t==null?void 0:t.env)==null?void 0:s[r]},_e=()=>({baseUrl:je.baseUrl??Me("REACT_APP_MOVMO_API_URL")??"",spreedlyScriptUrl:je.spreedlyScriptUrl??Me("REACT_APP_SPREEDLY_SCRIPT_URL")??Lr,iconCdnBaseUrl:je.iconCdnBaseUrl??Me("REACT_APP_MOVMO_ICON_CDN_URL")??Yr}),dr=r=>({id:r.id,last4:r.last4,brand:r.brand,expMonth:r.expMonth,expYear:r.expYear,isDefault:r.isDefault}),Re={Accept:"application/json","Content-Type":"application/json"},Ce=r=>{const{baseUrl:t}=_e();if(!t)throw new Error("@movmo_app/payments: baseUrl is not configured. Call setPaymentsConfig({ baseUrl }) at app boot, or set REACT_APP_MOVMO_API_URL.");return`${t}${r}`},Se=async(r,t)=>{try{return(await r.json()).message||t}catch{return t}},zr=async()=>{const r=await fetch(Ce("/v1/payments/tokenization-session"),{method:"GET",headers:Re,credentials:"include"});if(!r.ok)throw new Error(await Se(r,`Failed to fetch tokenization session (${r.status})`));return await r.json()},Br=async(r,t,s)=>{const o=await fetch(Ce(`/v1/users/${encodeURIComponent(r)}/payment-methods/from-token`),{method:"POST",headers:Re,credentials:"include",body:JSON.stringify({tokenizedPaymentMethodId:t,isDefault:s})});if(!o.ok)throw new Error(await Se(o,`Failed to save payment method (${o.status})`));const c=await o.json();return dr(c)},qr=async r=>{const t=await fetch(Ce(`/v1/users/${encodeURIComponent(r)}/payment-methods`),{method:"GET",headers:Re,credentials:"include"});if(!t.ok)throw new Error(await Se(t,`Failed to fetch payment methods (${t.status})`));return(await t.json()??[]).map(dr)},Kr=async(r,t)=>{const s=await fetch(Ce(`/v1/users/${encodeURIComponent(r)}/payment-methods/${encodeURIComponent(t)}`),{method:"DELETE",headers:Re,credentials:"include"});if(!s.ok)throw new Error(await Se(s,`Failed to delete payment method (${s.status})`))},Gr=async(r,t,s)=>{const o=await fetch(Ce(`/v1/users/${encodeURIComponent(r)}/payment-methods/${encodeURIComponent(t)}`),{method:"PUT",headers:Re,credentials:"include",body:JSON.stringify(s)});if(!o.ok)throw new Error(await Se(o,`Failed to update payment method (${o.status})`))},Jr={visa:"visa",master:"mastercard",mastercard:"mastercard",american_express:"amex",amex:"amex",discover:"discover"},Hr=28,ve=({brand:r,className:t,width:s=46})=>{const o=Jr[r.toLowerCase()]??"credit-card",c=Math.max(s,Hr),m=Math.round(c*24/34),{iconCdnBaseUrl:u}=_e();return a.jsx("img",{src:`${u}/website/assets/icons/payments/${o}.svg`,alt:o==="credit-card"?"card":`${o} card`,"data-testid":`card-brand-${r.toLowerCase()}`,className:t,width:c,height:m,loading:"lazy"})};let we=null;const Zr=()=>{if(typeof window>"u")return Promise.reject(new Error("Spreedly can only be loaded in a browser environment."));if(window.Spreedly)return Promise.resolve(window.Spreedly);if(we)return we;const{spreedlyScriptUrl:r}=_e();return we=new Promise((t,s)=>{const o=document.querySelector(`script[src="${r}"]`),c=()=>{window.Spreedly?t(window.Spreedly):s(new Error("Spreedly script loaded but window.Spreedly is undefined."))};if(o){if(window.Spreedly){c();return}o.addEventListener("load",c,{once:!0}),o.addEventListener("error",()=>{o.remove(),s(new Error("Failed to load Spreedly iframe script."))},{once:!0});return}const m=document.createElement("script");m.src=r,m.async=!0,m.onload=c,m.onerror=()=>{m.remove(),s(new Error("Failed to load Spreedly iframe script."))},document.head.appendChild(m)}).catch(t=>{throw we=null,t}),we},Xr="movmo-card-number",Qr="movmo-card-cvv",et=r=>({first_name:r.firstName,last_name:r.lastName,month:r.month,year:r.year,...r.email?{email:r.email}:{},...r.zip?{zip:r.zip}:{}}),ur=(r={})=>{const{numberEl:t=Xr,cvvEl:s=Qr,onCardTokenized:o,onFieldErrors:c,onValidityChange:m,onBrandChange:u}=r,[h,v]=i.useState("idle"),[T,E]=i.useState(null),[w,F]=i.useState({number:!1,cvv:!1}),[R,D]=i.useState(null),C=i.useRef(null),q=i.useRef(o),O=i.useRef(c),S=i.useRef(m),K=i.useRef(u);i.useEffect(()=>{q.current=o},[o]),i.useEffect(()=>{O.current=c},[c]),i.useEffect(()=>{S.current=m},[m]),i.useEffect(()=>{K.current=u},[u]);const M=i.useRef({number:!1,cvv:!1});i.useEffect(()=>{let W=!1;return v("loading"),E(null),F({number:!1,cvv:!1}),D(null),M.current={number:!1,cvv:!1},(async()=>{try{const[b,g]=await Promise.all([zr(),Zr()]);if(W)return;C.current=g,g.on("ready",()=>{var I;if(!W){v("ready");try{(I=g.setNumberFormat)==null||I.call(g,"prettyFormat")}catch{}}}),g.on("paymentMethod",I=>{var U;(U=q.current)==null||U.call(q,I)}),g.on("errors",I=>{var U;(U=O.current)==null||U.call(O,I)}),g.on("fieldEvent",(I,U,ne,z)=>{var le;if(W||U!=="input")return;const P=z??{};if(I==="number"){if(P.numberLength===0)D(V=>{var k;return V!==null&&((k=K.current)==null||k.call(K,null)),null});else if(P.cardType!==void 0){const V=P.cardType||null;D(k=>{var se;return k!==V&&((se=K.current)==null||se.call(K,V)),V})}}const Y=I==="number"?typeof P.validNumber=="boolean"?P.validNumber:void 0:typeof P.validCvv=="boolean"?P.validCvv:void 0;if(typeof Y=="boolean"){const V=M.current,k=I==="number"?{...V,number:Y}:{...V,cvv:Y};(k.number!==V.number||k.cvv!==V.cvv)&&(M.current=k,F(k),(le=S.current)==null||le.call(S,k))}}),g.on("consoleError",I=>{var ne;const U=I instanceof Error?I.message:"An unexpected error occurred while securing your card.";(ne=O.current)==null||ne.call(O,[{message:U}])}),g.init(b.environmentKey,{numberEl:t,cvvEl:s,nonce:b.nonce,timestamp:String(b.timestamp),certificateToken:b.certificateToken,signature:b.signature})}catch(b){if(W)return;const g=b instanceof Error?b.message:"Failed to initialize card form.";E(g),v("error")}})(),()=>{var b,g;W=!0;try{(g=(b=C.current)==null?void 0:b.removeHandlers)==null||g.call(b)}catch{}C.current=null}},[t,s]);const te=i.useCallback(W=>{var b;(b=C.current)==null||b.tokenizeCreditCard(et(W))},[]),ae=i.useCallback(W=>{var b,g;(g=(b=C.current)==null?void 0:b.transferFocus)==null||g.call(b,W)},[]);return{status:h,error:T,tokenize:te,validity:w,brand:R,focusField:ae}},We="h-11 w-full rounded-md border border-grayWarm-300 bg-white px-3 py-2 text-sm text-grayWarm-900 placeholder:text-grayWarm-400 outline-none focus:border-grayWarm-950 focus:shadow-[0_0_0_1px_#1c1917]",ar="flex h-11 w-full items-center gap-2 rounded-md border border-grayWarm-300 bg-white px-3 py-2 transition-shadow focus-within:border-grayWarm-950 focus-within:shadow-[0_0_0_1px_#1c1917]",rt=r=>{const t=r.trim();if(!t)return{firstName:"",lastName:""};const s=t.lastIndexOf(" ");return s===-1?{firstName:t,lastName:""}:{firstName:t.slice(0,s).trim(),lastName:t.slice(s+1).trim()}},fr=r=>{const t=r.replace(/\D/g,"");if(t.length<4)return{month:"",year:""};const s=t.slice(0,2),o=t.slice(2),c=o.length===2?`20${o}`:o.slice(0,4);return{month:s,year:c}},tt=r=>{const t=r.replace(/\D/g,"").slice(0,4);return t.length<=2?t:`${t.slice(0,2)} / ${t.slice(2)}`},Ae=r=>{const{month:t,year:s}=fr(r);if(!t||!s)return!1;const o=parseInt(t,10),c=parseInt(s,10);if(isNaN(o)||o<1||o>12)return!1;const m=new Date;return!(c<m.getFullYear()||c>m.getFullYear()+20||c===m.getFullYear()&&o<m.getMonth()+1)},$e=r=>/^\d{5}(-\d{4})?$/.test(r.trim()),at=r=>{const t=r.replace(/[^\d]/g,"").slice(0,9);return t.length<=5?t:`${t.slice(0,5)}-${t.slice(5)}`},Le=({userId:r,onSuccess:t,onError:s,isDefault:o=!1,className:c,defaultCardholderName:m,defaultCardholderFirstName:u="",defaultCardholderLastName:h="",autoSave:v=!1,formId:T="movmo-card-form",hideInternalSaveButton:E=!1,onCanSubmitChange:w})=>{const F=m??[u,h].filter(Boolean).join(" "),[R,D]=i.useState(F),[C,q]=i.useState(""),[O,S]=i.useState(""),[K,M]=i.useState("idle"),[te,ae]=i.useState(null),W=i.useRef(!1),b=i.useCallback(async N=>{M("saving");try{const d=await Br(r,N,o);M("ready"),t(d)}catch(d){const j=d instanceof Error?d.message:"Failed to save payment method.";ae(j),M("ready"),W.current=!1,s(j)}},[r,o,t,s]),g=i.useCallback(N=>{const d=N.map(j=>j.message).filter(Boolean).join("; ")||"Card validation failed.";ae(d),M(j=>j==="tokenizing"?"ready":j),W.current=!1,s(d)},[s]),I=i.useMemo(()=>({onCardTokenized:b,onFieldErrors:g}),[b,g]),{status:U,error:ne,tokenize:z,validity:P,brand:Y,focusField:le}=ur(I),V=R.trim().split(/\s+/).length>=2,k=Ae(C),se=$e(O),oe=i.useRef(!1),ce=i.useRef(!1),de=i.useRef(!1),ue=i.useRef(null),pe=i.useRef(null);i.useEffect(()=>{var N;P.cvv?ce.current||(ce.current=!0,(N=ue.current)==null||N.focus()):ce.current=!1},[P.cvv]);const be=!V||!k||!se||!P.number||!P.cvv,ee=K==="tokenizing"||K==="saving",H=U==="ready"&&!ee&&!be,Z=i.useRef(w);i.useEffect(()=>{Z.current=w},[w]),i.useEffect(()=>{var N;(N=Z.current)==null||N.call(Z,H)},[H]);const X=i.useCallback(()=>{const{firstName:N,lastName:d}=rt(R),{month:j,year:A}=fr(C);ae(null),M("tokenizing"),z({firstName:N,lastName:d,month:j,year:A,zip:O.trim()})},[R,C,O,z]);i.useEffect(()=>{if(!v||!H||W.current)return;const N=setTimeout(()=>{W.current=!0,X()},1200);return()=>clearTimeout(N)},[v,H,X]);const ie=N=>{N.preventDefault(),H&&X()},fe=te??ne,me=U!=="ready"||ee;return a.jsxs("form",{id:T,onSubmit:ie,className:re("flex w-full flex-col gap-3",c),"data-testid":"movmo-card-form",children:[a.jsxs("div",{children:[a.jsx("span",{id:"movmo-card-number-label",className:"sr-only",children:"Card number"}),a.jsxs("div",{className:ar,children:[a.jsx(ve,{brand:Y??"",width:32,className:"flex-shrink-0"}),a.jsx("div",{id:"movmo-card-number","aria-labelledby":"movmo-card-number-label",className:"flex-1","data-testid":"movmo-card-number-mount"})]})]}),a.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[a.jsxs("div",{children:[a.jsx("label",{htmlFor:"movmo-card-expiry",className:"sr-only",children:"Expiry MM / YY"}),a.jsx("input",{id:"movmo-card-expiry",type:"text",inputMode:"numeric",autoComplete:"cc-exp",placeholder:"MM / YY",value:C,onChange:N=>{const d=tt(N.target.value);q(d),Ae(d)&&!oe.current?(oe.current=!0,le("cvv")):Ae(d)||(oe.current=!1)},className:re(We,C&&!k&&"border-error-500"),disabled:me,required:!0,"data-testid":"movmo-card-expiry-input"})]}),a.jsxs("div",{className:"relative",children:[a.jsx("span",{id:"movmo-card-cvv-label",className:"sr-only",children:"CVV"}),a.jsxs("div",{className:ar,children:[a.jsx("div",{id:"movmo-card-cvv","aria-labelledby":"movmo-card-cvv-label",className:"flex-1","data-testid":"movmo-card-cvv-mount"}),a.jsx("button",{type:"button","aria-label":"CVV help",tabIndex:-1,className:"flex h-5 w-5 flex-shrink-0 items-center justify-center rounded-full border border-grayWarm-300 text-xs text-grayWarm-500",title:Y==="american_express"?"The 4 numbers on the front of your card.":"The 3 numbers on the back of your card.","data-testid":"movmo-cvv-help",children:"?"})]})]}),a.jsxs("div",{children:[a.jsx("label",{htmlFor:"movmo-card-zip",className:"sr-only",children:"ZIP code"}),a.jsx("input",{id:"movmo-card-zip",ref:ue,type:"text",inputMode:"numeric",autoComplete:"postal-code",placeholder:"ZIP code",value:O,onChange:N=>{var j;const d=at(N.target.value);S(d),$e(d)&&!de.current?(de.current=!0,(j=pe.current)==null||j.focus()):$e(d)||(de.current=!1)},className:re(We,O&&!se&&"border-error-500"),disabled:me,required:!0,"data-testid":"movmo-card-zip-input"})]})]}),a.jsxs("div",{children:[a.jsx("label",{htmlFor:"movmo-card-cardholder-name",className:"sr-only",children:"Cardholder name"}),a.jsx("input",{id:"movmo-card-cardholder-name",ref:pe,type:"text",autoComplete:"cc-name",placeholder:"Cardholder name",value:R,onChange:N=>D(N.target.value),className:We,disabled:me,required:!0,"data-testid":"movmo-card-cardholder-name-input"})]}),fe?a.jsx("p",{role:"alert",className:"rounded-md bg-error-50 px-3 py-2 text-sm text-error-700","data-testid":"movmo-card-error",children:fe}):null,!v&&!E?a.jsx("button",{type:"submit",disabled:!H,className:re("inline-flex h-11 items-center justify-center rounded-md bg-brand-500 px-4 text-sm font-semibold text-white transition-colors hover:bg-brand-600","disabled:cursor-not-allowed disabled:bg-grayWarm-300 disabled:text-grayWarm-500"),"data-testid":"movmo-card-save",children:ee?"Saving…":U==="loading"?"Loading…":"Save card"}):ee?a.jsx("p",{className:"text-center text-sm text-grayWarm-500","data-testid":"movmo-card-autosaving",children:"Saving card…"}):null]})};Le.displayName="MovmoCardForm";const mr=r=>{const[t,s]=i.useState("idle"),[o,c]=i.useState(null);return{deletePaymentMethod:i.useCallback(async u=>{s("pending"),c(null);try{await Kr(r,u),s("idle")}catch(h){const v=h instanceof Error?h.message:"Failed to delete payment method.";throw c(v),s("error"),h}},[r]),status:t,error:o}},pr=r=>{const[t,s]=i.useState("idle"),[o,c]=i.useState(null);return{setDefault:i.useCallback(async u=>{s("pending"),c(null);try{await Gr(r,u,{isDefault:!0}),s("idle")}catch(h){const v=h instanceof Error?h.message:"Failed to set default payment method.";throw c(v),s("error"),h}},[r]),status:t,error:o}},yr=r=>{const[t,s]=i.useState([]),[o,c]=i.useState("idle"),[m,u]=i.useState(null),[h,v]=i.useState(0),T=i.useRef(null);i.useEffect(()=>{var F;(F=T.current)==null||F.abort();const w=new AbortController;return T.current=w,c("loading"),u(null),qr(r).then(R=>{w.signal.aborted||(s(R),c("ready"))}).catch(R=>{if(w.signal.aborted)return;const D=R instanceof Error?R.message:"Failed to fetch payment methods.";u(D),c("error")}),()=>{w.abort()}},[r,h]);const E=i.useCallback(()=>{v(w=>w+1)},[]);return{items:t,status:o,error:m,refetch:E}},nt=({open:r,onClose:t,formId:s,saveDisabled:o,saveLabel:c="Save",children:m})=>(i.useEffect(()=>{if(!r)return;const u=h=>{h.key==="Escape"&&t()};return document.addEventListener("keydown",u),()=>document.removeEventListener("keydown",u)},[r,t]),i.useEffect(()=>{if(!r)return;const u=document.body.style.overflow;return document.body.style.overflow="hidden",()=>{document.body.style.overflow=u}},[r]),r?a.jsx("div",{role:"dialog","aria-modal":"true","aria-labelledby":"movmo-add-payment-title",className:"fixed inset-0 z-50 flex items-center justify-center bg-black/40 p-4",onClick:u=>{u.target===u.currentTarget&&t()},"data-testid":"add-payment-method-modal",children:a.jsxs("div",{className:"flex max-h-full w-full max-w-md flex-col rounded-xl bg-white shadow-2xl",children:[a.jsxs("div",{className:"flex items-center gap-3 border-b border-grayWarm-200 px-4 py-3",children:[a.jsx("button",{type:"button",onClick:t,"aria-label":"Close add-payment dialog",className:"flex h-8 w-8 flex-shrink-0 items-center justify-center rounded-md border border-grayWarm-200 text-grayWarm-700 hover:bg-grayWarm-100","data-testid":"add-payment-method-close",children:a.jsx("svg",{viewBox:"0 0 16 16",width:"14",height:"14","aria-hidden":"true",children:a.jsx("path",{d:"M3 3L13 13M13 3L3 13",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round"})})}),a.jsx("h2",{id:"movmo-add-payment-title",className:"flex-1 text-center text-base font-semibold text-grayWarm-900",children:"Add payment method"}),a.jsx("span",{"aria-hidden":"true",className:"h-8 w-8 flex-shrink-0"})]}),a.jsx("div",{className:"flex-1 overflow-y-auto p-4",children:m}),a.jsxs("div",{className:"flex gap-3 border-t border-grayWarm-200 p-4",children:[a.jsx("button",{type:"button",onClick:t,className:"inline-flex h-11 flex-1 items-center justify-center rounded-lg border border-grayWarm-300 px-4 text-sm font-semibold text-grayWarm-900 transition-colors hover:border-grayWarm-900 hover:shadow-[0_0_0_1px_#1c1917]","data-testid":"add-payment-method-cancel",children:"Cancel"}),a.jsx("button",{type:"submit",form:s,disabled:o,className:re("inline-flex h-11 flex-1 items-center justify-center rounded-lg bg-brand-500 px-4 text-sm font-semibold text-white transition-colors hover:bg-brand-600","disabled:cursor-not-allowed disabled:bg-grayWarm-300 disabled:text-grayWarm-500"),"data-testid":"add-payment-method-save",children:c})]})]})}):null),st=(r,t,s=new Date)=>t<s.getFullYear()||t===s.getFullYear()&&r<s.getMonth()+1,nr=r=>{const t=r.toLowerCase();return t==="amex"?"Amex":t?t.charAt(0).toUpperCase()+t.slice(1):"Card"},ot=(r,t)=>`${String(r).padStart(2,"0")}/${t}`,it=({method:r,selectable:t,selected:s,onSelect:o,onSetDefault:c,onRemove:m,disabled:u,showDefaultBadge:h,hideSetDefaultMenuItem:v})=>{const[T,E]=i.useState(!1),w=i.useRef(null),F=st(r.expMonth,r.expYear);i.useEffect(()=>{if(!T)return;const D=C=>{var q;(q=w.current)!=null&&q.contains(C.target)||E(!1)};return document.addEventListener("mousedown",D),()=>document.removeEventListener("mousedown",D)},[T]);const R=()=>{t&&o&&!u&&o(r)};return a.jsxs("div",{className:re("flex items-center gap-3 rounded-lg border px-3 py-3 transition-colors",t&&!u&&"cursor-pointer",s?"border-grayWarm-950 shadow-[0_0_0_1px_#1c1917]":"border-grayWarm-200 hover:border-grayWarm-300"),onClick:R,"data-testid":`payment-method-row-${r.id}`,children:[t?a.jsx("input",{type:"radio",name:"movmo-payment-method",checked:s,onChange:()=>o==null?void 0:o(r),onClick:D=>D.stopPropagation(),"aria-label":`Select ${nr(r.brand)} ending ${r.last4}`,className:"h-4 w-4 cursor-pointer accent-grayWarm-950",disabled:u}):null,a.jsx(ve,{brand:r.brand,className:"flex-shrink-0"}),a.jsxs("div",{className:"min-w-0 flex-1",children:[a.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[a.jsxs("span",{className:"text-base font-semibold text-grayWarm-900",children:[nr(r.brand)," ••••",r.last4]}),h&&r.isDefault?a.jsx("span",{className:"inline-flex items-center rounded-full bg-success-50 px-2 py-0.5 text-xs font-medium text-success-700","data-testid":`badge-default-${r.id}`,children:"Default"}):null,F?a.jsx("span",{className:"inline-flex items-center rounded-full bg-error-50 px-2 py-0.5 text-xs font-medium text-error-700","data-testid":`badge-expired-${r.id}`,children:"Expired"}):null]}),a.jsxs("div",{className:re("text-sm",F?"text-grayWarm-400":"text-grayWarm-600"),children:["Exp. ",ot(r.expMonth,r.expYear)]})]}),a.jsxs("div",{className:"relative flex-shrink-0",ref:w,children:[a.jsx("button",{type:"button","aria-label":`Open actions for card ending ${r.last4}`,"aria-haspopup":"menu","aria-expanded":T,className:"rounded-lg p-2 text-grayWarm-600 transition-colors hover:bg-grayWarm-100 disabled:cursor-not-allowed disabled:opacity-50",disabled:u,onClick:D=>{D.stopPropagation(),E(C=>!C)},"data-testid":`menu-trigger-${r.id}`,children:a.jsxs("svg",{viewBox:"0 0 16 16",width:"16",height:"16","aria-hidden":"true",children:[a.jsx("circle",{cx:"3",cy:"8",r:"1.5",fill:"currentColor"}),a.jsx("circle",{cx:"8",cy:"8",r:"1.5",fill:"currentColor"}),a.jsx("circle",{cx:"13",cy:"8",r:"1.5",fill:"currentColor"})]})}),T?a.jsxs("div",{role:"menu",className:"absolute right-0 top-full z-10 mt-1 min-w-[160px] rounded-lg border border-grayWarm-200 bg-white py-1 shadow-lg",onClick:D=>D.stopPropagation(),"data-testid":`menu-${r.id}`,children:[!r.isDefault&&!v?a.jsx("button",{type:"button",role:"menuitem",className:"block w-full px-4 py-2 text-left text-sm text-grayWarm-700 hover:bg-grayWarm-100",onClick:()=>{E(!1),c(r)},"data-testid":`menu-set-default-${r.id}`,children:"Set as default"}):null,a.jsx("button",{type:"button",role:"menuitem",className:"block w-full px-4 py-2 text-left text-sm text-error-700 hover:bg-error-50",onClick:()=>{E(!1),m(r)},"data-testid":`menu-remove-${r.id}`,children:"Remove"})]}):null]})]})},lt=r=>`${_e().iconCdnBaseUrl}/website/assets/icons/payments/${r}.svg`,Ie=({slug:r,alt:t})=>a.jsx("img",{src:lt(r),alt:t,height:20,loading:"lazy",style:{height:20,width:"auto"}}),Ne=({type:r,label:t,iconNode:s})=>a.jsxs("label",{className:"flex cursor-pointer items-center gap-3 rounded-lg border border-grayWarm-200 px-4 py-3 transition-colors hover:border-grayWarm-300","data-testid":`payment-type-${r}`,children:[a.jsx("input",{type:"radio",name:"movmo-payment-type",value:r,onChange:()=>{},className:"h-4 w-4 cursor-pointer accent-grayWarm-900","aria-label":t}),a.jsxs("span",{className:"flex flex-1 items-center gap-2 text-sm font-semibold text-grayWarm-900",children:[t,s]})]}),sr=({selected:r,onSelect:t,creditCardBody:s,className:o})=>{const c=r==="credit_card";return a.jsxs("div",{className:re("flex w-full flex-col gap-3",o),children:[a.jsxs("label",{className:re("flex cursor-pointer flex-col gap-3 rounded-lg border px-4 py-3 transition-colors",c?"border-grayWarm-900 shadow-[0_0_0_1px_#1c1917]":"border-grayWarm-200"),"data-testid":"payment-type-credit_card",children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("input",{type:"radio",name:"movmo-payment-type",value:"credit_card",checked:c,onChange:()=>t("credit_card"),className:"h-4 w-4 cursor-pointer accent-grayWarm-900","aria-label":"Credit card"}),a.jsx("span",{className:"flex-1 text-sm font-semibold text-grayWarm-900",children:"Credit card"}),a.jsxs("div",{className:"flex items-center gap-1.5",children:[a.jsx(ve,{brand:"mastercard",width:28}),a.jsx(ve,{brand:"visa",width:28}),a.jsx(ve,{brand:"amex",width:28}),a.jsx(ve,{brand:"discover",width:28})]})]}),c?a.jsx("div",{"data-testid":"payment-type-credit_card-body",children:s}):null]}),c?a.jsx("p",{className:"mt-2 text-sm font-semibold text-grayWarm-900","data-testid":"payment-type-other-options-header",children:"Other options"}):null,a.jsx(Ne,{type:"paypal",label:"PayPal",iconNode:a.jsx(Ie,{slug:"paypal",alt:"PayPal"})}),a.jsx(Ne,{type:"googlepay",label:"GooglePay",iconNode:a.jsx(Ie,{slug:"google-pay",alt:"GooglePay"})}),a.jsx(Ne,{type:"klarna",label:"Klarna",iconNode:a.jsx(Ie,{slug:"klarna",alt:"Klarna"})}),a.jsx(Ne,{type:"ach",label:"Bank account (ACH)",iconNode:a.jsx("span",{className:"text-xs font-medium text-grayWarm-500",children:"Direct debit"})})]})},or="movmo-add-payment-form",ir=r=>{const t=r.filter(o=>o.isDefault),s=r.filter(o=>!o.isDefault);return[...t,...s]},lr=()=>a.jsxs("div",{className:"flex items-center gap-3 rounded-lg border border-grayWarm-200 px-3 py-3","data-testid":"payment-method-skeleton",children:[a.jsx("div",{className:"h-8 w-[46px] flex-shrink-0 animate-pulse rounded bg-grayWarm-200"}),a.jsxs("div",{className:"flex-1 space-y-2",children:[a.jsx("div",{className:"h-4 w-32 animate-pulse rounded bg-grayWarm-200"}),a.jsx("div",{className:"h-3 w-20 animate-pulse rounded bg-grayWarm-200"})]}),a.jsx("div",{className:"h-8 w-8 animate-pulse rounded bg-grayWarm-200"})]}),vr=({userId:r,defaultCardholderName:t,defaultCardholderFirstName:s,defaultCardholderLastName:o,selectedId:c,onSelect:m,onChange:u,paymentTypeSelector:h=!0,autoSaveFirstCard:v=!0,selectionSetsDefault:T=!1,showDefaultBadge:E=!0,className:w})=>{const{items:F,status:R,error:D,refetch:C}=yr(r),{deletePaymentMethod:q,status:O}=mr(r),{setDefault:S,status:K}=pr(r),[M,te]=i.useState([]),[ae,W]=i.useState(null),[b,g]=i.useState(!1),[I,U]=i.useState(null),[ne,z]=i.useState(!1),[P,Y]=i.useState(null),le=i.useCallback(()=>{g(!1),U(null),Y(null)},[]),V=t??([s,o].filter(Boolean).join(" ")||void 0);i.useEffect(()=>{R==="ready"&&te(ir(F))},[F,R]);const k=i.useCallback(d=>{te(j=>{const A=typeof d=="function"?d(j):d,G=ir(A);return u==null||u(G),G})},[u]),se=O==="pending"||K==="pending",oe=i.useCallback(async d=>{const j=M;W(null),k(A=>A.map(G=>({...G,isDefault:G.id===d.id})));try{await S(d.id),C()}catch(A){te(j),u==null||u(j);const G=A instanceof Error?A.message:"Failed to set default payment method.";W(G)}},[M,k,S,C,u]),ce=i.useCallback(d=>{m==null||m(d),T&&(d.isDefault||oe(d))},[m,T,oe]),de=i.useCallback(async d=>{const j=M;W(null),k(A=>A.filter(G=>G.id!==d.id));try{await q(d.id),C()}catch(A){te(j),u==null||u(j);const G=A instanceof Error?A.message:"Failed to delete payment method.";W(G)}},[M,k,q,C,u]),ue=i.useCallback(d=>{U(null),g(!1),Y(null),k(j=>[d,...j.filter(A=>A.id!==d.id)]),C()},[k,C]),pe=i.useCallback(d=>{U(d)},[]),be=R==="ready"&&M.length===0,ee=typeof m=="function",H=M.length===0,Z=v&&M.length===0,X=i.useCallback(d=>a.jsx(Le,{userId:r,isDefault:H,defaultCardholderName:V,autoSave:!d&&Z,hideInternalSaveButton:d,formId:d?or:void 0,onCanSubmitChange:d?z:void 0,onSuccess:ue,onError:pe}),[r,H,V,Z,ue,pe]),ie=i.useMemo(()=>X(!1),[X]),fe=i.useMemo(()=>X(!0),[X]),me=i.useMemo(()=>h?a.jsx(sr,{selected:P,onSelect:d=>Y(d),creditCardBody:ie}):ie,[h,P,ie]),N=i.useMemo(()=>h?a.jsx(sr,{selected:P,onSelect:d=>Y(d),creditCardBody:fe}):fe,[h,P,fe]);return a.jsxs("div",{className:re("flex w-full flex-col gap-4",w),"data-testid":"payment-methods-manager",children:[R==="loading"?a.jsxs("div",{className:"flex flex-col gap-2","data-testid":"payment-methods-loading",children:[a.jsx(lr,{}),a.jsx(lr,{})]}):null,R==="error"?a.jsxs("div",{role:"alert",className:"flex items-center justify-between gap-3 rounded-md bg-error-50 p-3 text-sm text-error-700","data-testid":"payment-methods-list-error",children:[a.jsx("span",{children:D??"Failed to load payment methods."}),a.jsx("button",{type:"button",onClick:C,className:"rounded-md border border-error-700 px-3 py-1 text-xs font-semibold text-error-700 hover:bg-error-50",children:"Retry"})]}):null,ae?a.jsx("div",{role:"alert",className:"rounded-md bg-error-50 p-3 text-sm text-error-700","data-testid":"payment-methods-mutation-error",children:ae}):null,R==="ready"&&M.length>0?a.jsx("div",{className:"flex flex-col gap-2",children:M.map(d=>a.jsx(it,{method:d,selectable:ee,selected:ee&&d.id===c,onSelect:ce,onSetDefault:oe,onRemove:de,disabled:se,showDefaultBadge:E,hideSetDefaultMenuItem:T},d.id))}):null,be?a.jsx("div",{"data-testid":"payment-methods-empty",children:me}):R==="ready"?a.jsx("button",{type:"button",onClick:()=>{U(null),Y(null),z(!1),g(!0)},className:"self-start rounded-lg bg-brand-50 px-6 py-3 text-md font-semibold text-brand-600 transition-colors hover:bg-brand-100","data-testid":"payment-methods-add-trigger",children:"Add payment method"}):null,a.jsxs(nt,{open:b,onClose:le,formId:or,saveDisabled:!ne,children:[N,I?a.jsx("p",{role:"alert",className:"mt-3 rounded-md bg-error-50 px-3 py-2 text-sm text-error-700","data-testid":"payment-methods-modal-error",children:I}):null]})]})};vr.displayName="PaymentMethodsManager";const ct=r=>{const t=r.toLowerCase();return t==="amex"?"Amex":t?t.charAt(0).toUpperCase()+t.slice(1):"Card"},dt=({method:r,trailing:t,onClick:s,className:o})=>a.jsxs("div",{className:re("flex items-center gap-3 py-2",s&&"cursor-pointer",o),onClick:s,role:s?"button":void 0,tabIndex:s?0:void 0,onKeyDown:s?c=>{(c.key==="Enter"||c.key===" ")&&(c.preventDefault(),s())}:void 0,"data-testid":`payment-method-preview-${r.id}`,children:[a.jsx(ve,{brand:r.brand,className:"flex-shrink-0"}),a.jsxs("span",{className:"flex-1 text-base font-semibold text-grayWarm-900",children:[ct(r.brand)," ",r.last4]}),t]});exports.MovmoCardForm=Le;exports.PaymentMethodPreview=dt;exports.PaymentMethodsManager=vr;exports.getPaymentsConfig=_e;exports.setPaymentsConfig=Vr;exports.useDeletePaymentMethod=mr;exports.useMovmoCardFields=ur;exports.useSetDefaultPaymentMethod=pr;exports.useUserPaymentMethods=yr;
|
|
30
|
+
<%s key={someKey} {...props} />`,Ve,je,Yr,je),lr[je+Ve]=!0}}return e===i?$r(L):Ar(L),L}}function Ur(e,s,l){return cr(e,s,l,!0)}function Ir(e,s,l){return cr(e,s,l,!1)}var Lr=Ir,Br=Ur;De.Fragment=i,De.jsx=Lr,De.jsxs=Br}()),De}process.env.NODE_ENV==="production"?Xe.exports=Vr():Xe.exports=qr();var a=Xe.exports;function xr(r){var t,n,i="";if(typeof r=="string"||typeof r=="number")i+=r;else if(typeof r=="object")if(Array.isArray(r)){var c=r.length;for(t=0;t<c;t++)r[t]&&(n=xr(r[t]))&&(i&&(i+=" "),i+=n)}else for(n in r)r[n]&&(i&&(i+=" "),i+=n);return i}function J(){for(var r,t,n=0,i="",c=arguments.length;n<c;n++)(r=arguments[n])&&(t=xr(r))&&(i&&(i+=" "),i+=t);return i}const Kr="https://core.spreedly.com/iframe/iframe-v1.min.js",Gr="https://cdn.e2e.movmo.io";let Ne={};const Hr=r=>{Ne={...Ne,...r}},qe=r=>{var n;const t=globalThis.process;return(n=t==null?void 0:t.env)==null?void 0:n[r]},Re=()=>({baseUrl:Ne.baseUrl??qe("REACT_APP_MOVMO_API_URL")??"",spreedlyScriptUrl:Ne.spreedlyScriptUrl??qe("REACT_APP_SPREEDLY_SCRIPT_URL")??Kr,iconCdnBaseUrl:Ne.iconCdnBaseUrl??qe("REACT_APP_MOVMO_ICON_CDN_URL")??Gr,fetch:Ne.fetch??(typeof globalThis<"u"&&typeof globalThis.fetch=="function"?globalThis.fetch.bind(globalThis):(()=>{throw new Error("@movmo_app/payments: no fetch available")})())}),Ze=r=>({id:r.id,last4:r.last4,brand:r.brand,expMonth:r.expMonth,expYear:r.expYear,isDefault:r.isDefault}),Se={Accept:"application/json","Content-Type":"application/json"},Pe=r=>{const{baseUrl:t}=Re();if(!t)throw new Error("@movmo_app/payments: baseUrl is not configured. Call setPaymentsConfig({ baseUrl }) at app boot, or set REACT_APP_MOVMO_API_URL.");return`${t}${r}`},Te=(r,t)=>{const{fetch:n}=Re();return n(r,t)},Fe=async(r,t)=>{try{return(await r.json()).message||t}catch{return t}};let We=null;const Qe=()=>{if(We)return We;const r=(async()=>{const t=await Te(Pe("/v1/payments/tokenization-session"),{method:"GET",headers:Se,credentials:"include"});if(!t.ok)throw new Error(await Fe(t,`Failed to fetch tokenization session (${t.status})`));return await t.json()})();return We=r,r.finally(()=>{We===r&&(We=null)}).catch(()=>{}),r},Jr=r=>typeof r.brand=="string"&&typeof r.last4=="string"&&typeof r.expMonth=="number"&&typeof r.expYear=="number",Xr=async(r,t,n)=>{const i=await Te(Pe(`/v1/users/${encodeURIComponent(r)}/payment-methods/from-token`),{method:"POST",headers:Se,credentials:"include",body:JSON.stringify({tokenizedPaymentMethodId:t,isDefault:n})});if(!i.ok)throw new Error(await Fe(i,`Failed to save payment method (${i.status})`));const c=await i.json();if(Jr(c))return Ze(c);const d=await Te(Pe(`/v1/users/${encodeURIComponent(r)}/payment-methods/${encodeURIComponent(c.id)}`),{method:"GET",headers:Se,credentials:"include"});if(!d.ok)throw new Error(await Fe(d,`Failed to fetch saved payment method (${d.status})`));const p=await d.json();return Ze(p)},Zr=async(r,t)=>{const n=await Te(Pe(`/v1/users/${encodeURIComponent(r)}/payment-methods`),{method:"GET",headers:Se,credentials:"include",signal:t});if(!n.ok)throw new Error(await Fe(n,`Failed to fetch payment methods (${n.status})`));return(await n.json()??[]).map(Ze)},Qr=async(r,t)=>{const n=await Te(Pe(`/v1/users/${encodeURIComponent(r)}/payment-methods/${encodeURIComponent(t)}`),{method:"DELETE",headers:Se,credentials:"include"});if(!n.ok)throw new Error(await Fe(n,`Failed to delete payment method (${n.status})`))},et=async(r,t,n)=>{const i=await Te(Pe(`/v1/users/${encodeURIComponent(r)}/payment-methods/${encodeURIComponent(t)}`),{method:"PUT",headers:Se,credentials:"include",body:JSON.stringify(n)});if(!i.ok)throw new Error(await Fe(i,`Failed to update payment method (${i.status})`))},rt={visa:"visa",master:"mastercard",mastercard:"mastercard",american_express:"amex",amex:"amex",discover:"discover"},tt=28,_e=({brand:r,className:t,width:n=46})=>{const i=r?rt[r.toLowerCase()]??"credit-card":"credit-card",c=Math.max(n,tt),d=Math.round(c*24/34),{iconCdnBaseUrl:p}=Re();return a.jsx("img",{src:`${p}/website/assets/icons/payments/${i}.svg`,alt:i==="credit-card"?"card":`${i} card`,"data-testid":`card-brand-${r.toLowerCase()}`,className:t,width:c,height:d,loading:"lazy"})};let Me=null;const at=()=>{if(typeof window>"u")return Promise.reject(new Error("Spreedly can only be loaded in a browser environment."));if(window.Spreedly)return Promise.resolve(window.Spreedly);if(Me)return Me;const{spreedlyScriptUrl:r}=Re();return Me=new Promise((t,n)=>{const i=document.querySelector(`script[src="${r}"]`),c=()=>{window.Spreedly?t(window.Spreedly):n(new Error("Spreedly script loaded but window.Spreedly is undefined."))};if(i){if(window.Spreedly){c();return}i.addEventListener("load",c,{once:!0}),i.addEventListener("error",()=>{i.remove(),n(new Error("Failed to load Spreedly iframe script."))},{once:!0});return}const d=document.createElement("script");d.src=r,d.async=!0,d.onload=c,d.onerror=()=>{d.remove(),n(new Error("Failed to load Spreedly iframe script."))},document.head.appendChild(d)}).catch(t=>{throw Me=null,t}),Me},nt="movmo-card-number",st="movmo-card-cvv",ot=r=>({first_name:r.firstName,last_name:r.lastName,month:r.month,year:r.year,...r.email?{email:r.email}:{},...r.zip?{zip:r.zip}:{}}),wr=(r={})=>{const{numberEl:t=nt,cvvEl:n=st,onCardTokenized:i,onFieldErrors:c,onValidityChange:d,onBrandChange:p}=r,[v,h]=o.useState("idle"),[D,C]=o.useState(null),[y,b]=o.useState({number:!1,cvv:!1}),[_,M]=o.useState(null),[S,G]=o.useState({number:!1,cvv:!1}),w=o.useRef(null),P=o.useRef(i),q=o.useRef(c),le=o.useRef(d),Q=o.useRef(p);o.useEffect(()=>{P.current=i},[i]),o.useEffect(()=>{q.current=c},[c]),o.useEffect(()=>{le.current=d},[d]),o.useEffect(()=>{Q.current=p},[p]);const j=o.useRef({number:!1,cvv:!1});o.useEffect(()=>{let I=!1;return h("loading"),C(null),b({number:!1,cvv:!1}),M(null),j.current={number:!1,cvv:!1},(async()=>{try{const[T,u]=await Promise.all([Qe(),at()]);if(I)return;w.current=u,u.on("ready",()=>{var F,R,$,H,B,X;if(!I){h("ready");try{(F=u.setFieldType)==null||F.call(u,"number","tel"),(R=u.setFieldType)==null||R.call(u,"cvv","tel")}catch{}try{typeof u.setNumberFormat=="function"?u.setNumberFormat("prettyFormat"):console.warn("@movmo_app/payments: Spreedly.setNumberFormat is missing — card-number digits will not be space-grouped.")}catch(Y){console.warn("@movmo_app/payments: setNumberFormat failed",Y)}try{($=u.setPlaceholder)==null||$.call(u,"number","Card number"),(H=u.setPlaceholder)==null||H.call(u,"cvv","CVV");const Y='box-sizing: border-box;width: 100%;height: 100%;margin: 0;padding: 0;border: 0;background: transparent;outline: none;font-family: ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;font-size: 14px;font-weight: 400;line-height: 20px;color: rgb(28 25 23);letter-spacing: 0;vertical-align: middle;';(B=u.setStyle)==null||B.call(u,"number",Y),(X=u.setStyle)==null||X.call(u,"cvv",Y)}catch{}}}),u.on("paymentMethod",F=>{var R;(R=P.current)==null||R.call(P,F)}),u.on("errors",F=>{var R;(R=q.current)==null||R.call(q,F)}),u.on("fieldEvent",(F,R,$,H)=>{var Y;if(I)return;if(R==="focus"){G(N=>N[F]?N:{...N,[F]:!0});return}if(R==="blur"){G(N=>N[F]?{...N,[F]:!1}:N);return}if(R!=="input")return;const B=H??{};if(F==="number"){if(B.numberLength===0)M(N=>{var W;return N!==null&&((W=Q.current)==null||W.call(Q,null)),null});else if(B.cardType!==void 0){const N=B.cardType||null;M(W=>{var de;return W!==N&&((de=Q.current)==null||de.call(Q,N)),N})}}const X=F==="number"?typeof B.validNumber=="boolean"?B.validNumber:void 0:typeof B.validCvv=="boolean"?B.validCvv:void 0;if(typeof X=="boolean"){const N=j.current,W=F==="number"?{...N,number:X}:{...N,cvv:X};(W.number!==N.number||W.cvv!==N.cvv)&&(j.current=W,b(W),(Y=le.current)==null||Y.call(le,W))}}),u.on("consoleError",F=>{var $;const R=F instanceof Error?F.message:"An unexpected error occurred while securing your card.";($=q.current)==null||$.call(q,[{message:R}])}),u.init(T.environmentKey,{numberEl:t,cvvEl:n,nonce:T.nonce,timestamp:String(T.timestamp),certificateToken:T.certificateToken,signature:T.signature})}catch(T){if(I)return;const u=T instanceof Error?T.message:"Failed to initialize card form.";C(u),h("error")}})(),()=>{var T,u;I=!0;try{(u=(T=w.current)==null?void 0:T.removeHandlers)==null||u.call(T)}catch{}w.current=null}},[t,n]);const te=o.useCallback(I=>{var T;(T=w.current)==null||T.tokenizeCreditCard(ot(I))},[]),fe=o.useCallback(I=>{var T,u;(u=(T=w.current)==null?void 0:T.transferFocus)==null||u.call(T,I)},[]);return{status:v,error:D,tokenize:te,validity:y,brand:_,focused:S,focusField:fe}},Ke="h-11 w-full rounded-md border border-grayWarm-300 bg-white px-3 py-2 text-sm text-grayWarm-900 placeholder:text-grayWarm-400 outline-none focus:border-grayWarm-950 focus:shadow-[0_0_0_1px_#1c1917]",fr="flex h-11 w-full items-center gap-2 rounded-md border bg-white px-3 py-2 transition-shadow",mr="border-grayWarm-950 shadow-[0_0_0_1px_#1c1917]",pr="border-grayWarm-300",it=r=>{const t=r.trim();if(!t)return{firstName:"",lastName:""};const n=t.lastIndexOf(" ");return n===-1?{firstName:t,lastName:""}:{firstName:t.slice(0,n).trim(),lastName:t.slice(n+1).trim()}},Er=r=>{const t=r.replace(/\D/g,"");if(t.length<4)return{month:"",year:""};const n=t.slice(0,2),i=t.slice(2),c=i.length===2?`20${i}`:i.slice(0,4);return{month:n,year:c}},lt=r=>{const t=r.replace(/\D/g,"").slice(0,4);return t.length<=2?t:`${t.slice(0,2)} / ${t.slice(2)}`},Ge=r=>{const{month:t,year:n}=Er(r);if(!t||!n)return!1;const i=parseInt(t,10),c=parseInt(n,10);if(isNaN(i)||i<1||i>12)return!1;const d=new Date;return!(c<d.getFullYear()||c>d.getFullYear()+20||c===d.getFullYear()&&i<d.getMonth()+1)},He=r=>/^\d{5}(-\d{4})?$/.test(r.trim()),ct=r=>{const t=r.replace(/[^\d]/g,"").slice(0,9);return t.length<=5?t:`${t.slice(0,5)}-${t.slice(5)}`},er=({userId:r,onSuccess:t,onError:n,isDefault:i=!1,className:c,defaultCardholderName:d,defaultCardholderFirstName:p="",defaultCardholderLastName:v="",autoSave:h=!1,formId:D="movmo-card-form",hideInternalSaveButton:C=!1,onCanSubmitChange:y,onSavingChange:b,autoFocus:_})=>{const M=d??[p,v].filter(Boolean).join(" "),[S,G]=o.useState(M),[w,P]=o.useState(""),[q,le]=o.useState(""),[Q,j]=o.useState("idle"),te=o.useRef(!1),fe=o.useCallback(async g=>{j("saving");try{const A=await Xr(r,g,i);j("ready"),t(A)}catch(A){const z=A instanceof Error?A.message:"Failed to save payment method.";j("ready"),te.current=!1,n(z)}},[r,i,t,n]),I=o.useCallback(g=>{const A=g.map(z=>z.message).filter(Boolean).join("; ")||"Card validation failed.";j(z=>z==="tokenizing"?"ready":z),te.current=!1,n(A)},[n]),T=o.useMemo(()=>({onCardTokenized:fe,onFieldErrors:I}),[fe,I]),{status:u,error:F,tokenize:R,validity:$,brand:H,focused:B,focusField:X}=wr(T),Y=o.useRef(!1);o.useEffect(()=>{!_||u!=="ready"||Y.current||(Y.current=!0,X(_))},[_,u,X]);const N=S.trim().split(/\s+/).length>=2,W=Ge(w),de=He(q),me=o.useRef(!1),ve=o.useRef(!1),be=o.useRef(!1),ce=o.useRef(null),ge=o.useRef(null);o.useEffect(()=>{var g;$.cvv?ve.current||(ve.current=!0,(g=ce.current)==null||g.focus()):ve.current=!1},[$.cvv]);const pe=!N||!W||!de||!$.number||!$.cvv,K=Q==="tokenizing"||Q==="saving",ae=u==="ready"&&!K&&!pe,ne=o.useRef(y);o.useEffect(()=>{ne.current=y},[y]),o.useEffect(()=>{var g;(g=ne.current)==null||g.call(ne,ae)},[ae]);const he=o.useRef(b);o.useEffect(()=>{he.current=b},[b]),o.useEffect(()=>{var g;(g=he.current)==null||g.call(he,K)},[K]);const xe=o.useCallback(()=>{const{firstName:g,lastName:A}=it(S),{month:z,year:ue}=Er(w);j("tokenizing"),R({firstName:g,lastName:A,month:z,year:ue,zip:q.trim()})},[S,w,q,R]);o.useEffect(()=>{if(!h||!ae||te.current)return;const g=setTimeout(()=>{te.current=!0,xe()},1200);return()=>clearTimeout(g)},[h,ae,xe]);const Ee=g=>{g.preventDefault(),ae&&xe()},we=u!=="ready"||K,se=o.useRef(n);return o.useEffect(()=>{se.current=n},[n]),o.useEffect(()=>{var g;F&&((g=se.current)==null||g.call(se,F))},[F]),a.jsxs("form",{id:D,onSubmit:Ee,className:J("flex w-full flex-col gap-3",c),"data-testid":"movmo-card-form",children:[a.jsxs("div",{children:[a.jsx("span",{id:"movmo-card-number-label",className:"sr-only",children:"Card number"}),a.jsxs("div",{className:J(fr,B.number?mr:pr),children:[a.jsx(_e,{brand:H??"",width:32,className:"flex-shrink-0"}),a.jsxs("div",{className:"relative h-full flex-1",children:[a.jsx("div",{id:"movmo-card-number","aria-labelledby":"movmo-card-number-label","aria-busy":u!=="ready",className:"absolute inset-0","data-testid":"movmo-card-number-mount"}),u!=="ready"?a.jsx("div",{"aria-hidden":"true",className:"pointer-events-none absolute inset-y-2 left-0 right-2 animate-pulse rounded bg-grayWarm-200"}):null]})]})]}),a.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[a.jsxs("div",{children:[a.jsx("label",{htmlFor:"movmo-card-expiry",className:"sr-only",children:"Expiry MM / YY"}),a.jsx("input",{id:"movmo-card-expiry",type:"text",inputMode:"numeric",autoComplete:"cc-exp",placeholder:"MM / YY",value:w,onChange:g=>{const A=lt(g.target.value);P(A),Ge(A)&&!me.current?(me.current=!0,X("cvv")):Ge(A)||(me.current=!1)},className:J(Ke,w&&!W&&"border-error-500"),disabled:we,required:!0,"data-testid":"movmo-card-expiry-input"})]}),a.jsxs("div",{className:"relative",children:[a.jsx("span",{id:"movmo-card-cvv-label",className:"sr-only",children:"CVV"}),a.jsxs("div",{className:J(fr,B.cvv?mr:pr),children:[a.jsxs("div",{className:"relative h-full flex-1",children:[a.jsx("div",{id:"movmo-card-cvv","aria-labelledby":"movmo-card-cvv-label","aria-busy":u!=="ready",className:"absolute inset-0","data-testid":"movmo-card-cvv-mount"}),u!=="ready"?a.jsx("div",{"aria-hidden":"true",className:"pointer-events-none absolute inset-y-2 left-0 right-2 animate-pulse rounded bg-grayWarm-200"}):null]}),a.jsx("button",{type:"button","aria-label":"CVV help",tabIndex:-1,className:"flex h-5 w-5 flex-shrink-0 items-center justify-center rounded-full border border-grayWarm-300 text-xs text-grayWarm-500",title:H==="american_express"?"The 4 numbers on the front of your card.":"The 3 numbers on the back of your card.","data-testid":"movmo-cvv-help",children:"?"})]})]}),a.jsxs("div",{children:[a.jsx("label",{htmlFor:"movmo-card-zip",className:"sr-only",children:"ZIP code"}),a.jsx("input",{id:"movmo-card-zip",ref:ce,type:"text",inputMode:"numeric",autoComplete:"postal-code",placeholder:"ZIP code",value:q,onChange:g=>{var z;const A=ct(g.target.value);le(A),He(A)&&!be.current?(be.current=!0,(z=ge.current)==null||z.focus()):He(A)||(be.current=!1)},className:J(Ke,q&&!de&&"border-error-500"),disabled:we,required:!0,"data-testid":"movmo-card-zip-input"})]})]}),a.jsxs("div",{children:[a.jsx("label",{htmlFor:"movmo-card-cardholder-name",className:"sr-only",children:"Cardholder name"}),a.jsx("input",{id:"movmo-card-cardholder-name",ref:ge,type:"text",autoComplete:"cc-name",placeholder:"Cardholder name",value:S,onChange:g=>G(g.target.value),className:Ke,disabled:we,required:!0,"data-testid":"movmo-card-cardholder-name-input"})]}),!h&&!C?a.jsx("button",{type:"submit",disabled:!ae,className:J("inline-flex h-11 items-center justify-center rounded-md bg-brand-500 px-4 text-sm font-semibold text-white transition-colors hover:bg-brand-600","disabled:cursor-not-allowed disabled:bg-grayWarm-300 disabled:text-grayWarm-500"),"data-testid":"movmo-card-save",children:K?"Saving…":u==="loading"?"Loading…":"Save card"}):K&&h?a.jsx("p",{className:"text-center text-sm text-grayWarm-500","aria-live":"polite","data-testid":"movmo-card-autosaving",children:"Saving card…"}):null]})};er.displayName="MovmoCardForm";const jr=r=>{const[t,n]=o.useState("idle"),[i,c]=o.useState(null);return{deletePaymentMethod:o.useCallback(async p=>{n("pending"),c(null);try{await Qr(r,p),n("idle")}catch(v){const h=v instanceof Error?v.message:"Failed to delete payment method.";throw c(h),n("error"),v}},[r]),status:t,error:i}},_r=r=>{const[t,n]=o.useState("idle"),[i,c]=o.useState(null);return{setDefault:o.useCallback(async p=>{n("pending"),c(null);try{await et(r,p,{isDefault:!0}),n("idle")}catch(v){const h=v instanceof Error?v.message:"Failed to set default payment method.";throw c(h),n("error"),v}},[r]),status:t,error:i}},Rr=r=>{const[t,n]=o.useState([]),[i,c]=o.useState("idle"),[d,p]=o.useState(null),[v,h]=o.useState(0),D=o.useRef(null);o.useEffect(()=>{var b;(b=D.current)==null||b.abort();const y=new AbortController;return D.current=y,c("loading"),p(null),Zr(r,y.signal).then(_=>{y.signal.aborted||(n(_),c("ready"))}).catch(_=>{if(y.signal.aborted||_ instanceof DOMException&&_.name==="AbortError")return;const M=_ instanceof Error?_.message:"Failed to fetch payment methods.";p(M),c("error")}),()=>{y.abort()}},[r,v]);const C=o.useCallback(()=>{h(y=>y+1)},[]);return{items:t,status:i,error:d,refetch:C}},dt=({open:r,onClose:t,formId:n,saveDisabled:i,saveLabel:c="Save",isSaving:d=!1,children:p})=>(o.useEffect(()=>{if(!r)return;const v=h=>{h.key==="Escape"&&t()};return document.addEventListener("keydown",v),()=>document.removeEventListener("keydown",v)},[r,t]),o.useEffect(()=>{if(!r)return;const v=document.body.style.overflow;return document.body.style.overflow="hidden",()=>{document.body.style.overflow=v}},[r]),r?a.jsx("div",{role:"dialog","aria-modal":"true","aria-labelledby":"movmo-add-payment-title",className:"fixed inset-0 z-50 flex items-center justify-center bg-black/40 p-4",onClick:v=>{v.target===v.currentTarget&&t()},"data-testid":"add-payment-method-modal",children:a.jsxs("div",{className:"flex max-h-full w-full max-w-md flex-col rounded-xl bg-white shadow-2xl",children:[a.jsxs("div",{className:"flex items-center gap-3 border-b border-grayWarm-200 px-4 py-3",children:[a.jsx("button",{type:"button",onClick:t,"aria-label":"Close add-payment dialog",className:"flex h-9 w-9 flex-shrink-0 items-center justify-center rounded-lg bg-grayWarm-100 p-2 text-grayWarm-950 transition-colors hover:bg-grayWarm-200","data-testid":"add-payment-method-close",children:a.jsx("svg",{viewBox:"0 0 20 20",width:"20",height:"20","aria-hidden":"true",children:a.jsx("path",{d:"M5 5L15 15M15 5L5 15",stroke:"currentColor",strokeWidth:"1.67",strokeLinecap:"round",strokeLinejoin:"round"})})}),a.jsx("h2",{id:"movmo-add-payment-title",className:"flex-1 text-center text-base font-semibold text-grayWarm-900",children:"Add payment method"}),a.jsx("span",{"aria-hidden":"true",className:"h-9 w-9 flex-shrink-0"})]}),a.jsx("div",{className:"flex-1 overflow-y-auto p-4",children:p}),a.jsxs("div",{className:"flex gap-3 border-t border-grayWarm-200 p-4",children:[a.jsx("button",{type:"button",onClick:t,className:"inline-flex h-11 flex-1 items-center justify-center rounded-lg border border-grayWarm-300 px-4 text-sm font-semibold text-grayWarm-900 transition-colors hover:border-grayWarm-900 hover:shadow-[0_0_0_1px_#1c1917]","data-testid":"add-payment-method-cancel",children:"Cancel"}),a.jsx("button",{type:"submit",form:n,disabled:d?!1:i,"aria-disabled":d||i,"aria-busy":d,className:J("inline-flex h-11 flex-1 items-center justify-center rounded-lg bg-brand-500 px-4 text-sm font-semibold text-white transition-colors",d?"cursor-not-allowed opacity-90 pointer-events-none":"hover:bg-brand-600 disabled:cursor-not-allowed disabled:bg-grayWarm-300 disabled:text-grayWarm-500"),"data-testid":"add-payment-method-save",children:d?a.jsxs(a.Fragment,{children:[a.jsxs("svg",{className:"h-[18px] w-[18px] animate-spin",viewBox:"0 0 24 24",fill:"none","aria-hidden":"true",children:[a.jsx("circle",{cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"3",strokeOpacity:"0.25"}),a.jsx("path",{d:"M22 12a10 10 0 0 1-10 10",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round"})]}),a.jsx("span",{className:"sr-only",children:"Saving card"})]}):c})]})]})}):null),ut=r=>{if(!r)return"Card";const t=r.toLowerCase();return t==="amex"?"Amex":t.charAt(0).toUpperCase()+t.slice(1)},Cr=({method:r,trailing:t,onClick:n,cardLabelFormat:i="branded",className:c})=>a.jsxs("div",{className:J("flex items-center gap-3",n&&"cursor-pointer",c),onClick:n,role:n?"button":void 0,tabIndex:n?0:void 0,onKeyDown:n?d=>{(d.key==="Enter"||d.key===" ")&&(d.preventDefault(),n())}:void 0,"data-testid":`payment-method-preview-${r.id}`,children:[a.jsx(_e,{brand:r.brand,width:34,className:"flex-shrink-0"}),a.jsx("span",{className:"flex-1 text-lg font-semibold text-grayWarm-950",children:i==="masked"?`•••• ${r.last4}`:`${ut(r.brand)} ${r.last4}`}),t]}),ft=(r,t,n=new Date)=>t<n.getFullYear()||t===n.getFullYear()&&r<n.getMonth()+1,hr=r=>{if(!r)return"Card";const t=r.toLowerCase();return t==="amex"?"Amex":t.charAt(0).toUpperCase()+t.slice(1)},mt=(r,t)=>`${String(r).padStart(2,"0")}/${t}`,pt=({method:r,selectable:t,selected:n,onSelect:i,onSetDefault:c,onRemove:d,disabled:p,showDefaultBadge:v,hideSetDefaultMenuItem:h,cardLabelFormat:D="branded"})=>{const[C,y]=o.useState(!1),b=o.useRef(null),_=ft(r.expMonth,r.expYear);o.useEffect(()=>{if(!C)return;const S=G=>{var w;(w=b.current)!=null&&w.contains(G.target)||y(!1)};return document.addEventListener("mousedown",S),()=>document.removeEventListener("mousedown",S)},[C]);const M=()=>{t&&i&&!p&&i(r)};return a.jsxs("div",{className:J("flex items-start gap-3 transition-colors",t?"rounded-lg border px-3 py-3":"py-4",t&&!p&&"cursor-pointer",t&&(n?"border-grayWarm-950 shadow-[0_0_0_1px_#1c1917]":"border-grayWarm-200 hover:border-grayWarm-300")),onClick:M,"data-testid":`payment-method-row-${r.id}`,children:[t?a.jsx("input",{type:"radio",name:"movmo-payment-method",checked:n,onChange:()=>i==null?void 0:i(r),onClick:S=>S.stopPropagation(),"aria-label":`Select ${hr(r.brand)} ending ${r.last4}`,className:"mr-1 h-4 w-4 mt-2 cursor-pointer appearance-none rounded-full border-2 border-grayWarm-300 checked:border-[5px] checked:border-grayWarm-950 bg-white checked:bg-white focus:ring-0 focus:ring-offset-0",disabled:p}):null,a.jsx(_e,{brand:r.brand,className:"flex-shrink-0"}),a.jsxs("div",{className:"min-w-0 flex-1",children:[a.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[a.jsx("span",{className:"text-lg font-semibold text-grayWarm-950",children:D==="masked"?`•••• ${r.last4}`:`${hr(r.brand)} ${r.last4}`}),v&&r.isDefault?a.jsx("span",{className:"inline-flex items-center rounded-full bg-success-50 px-2 py-0.5 text-xs font-semibold text-success-700","data-testid":`badge-default-${r.id}`,children:"Default"}):null,_?a.jsx("span",{className:"inline-flex items-center rounded-full bg-error-50 px-2 py-0.5 text-xs font-semibold text-error-700","data-testid":`badge-expired-${r.id}`,children:"Expired"}):null]}),a.jsxs("div",{className:J("text-base",_?"text-grayWarm-400":"text-grayWarm-600"),children:["Exp. ",mt(r.expMonth,r.expYear)]})]}),a.jsxs("div",{className:"relative flex-shrink-0",ref:b,children:[a.jsx("button",{type:"button","aria-label":`Open actions for card ending ${r.last4}`,"aria-haspopup":"menu","aria-expanded":C,className:"rounded-lg p-2 text-grayWarm-600 transition-colors hover:bg-grayWarm-100 disabled:cursor-not-allowed disabled:opacity-50",disabled:p,onClick:S=>{S.stopPropagation(),y(G=>!G)},"data-testid":`menu-trigger-${r.id}`,children:a.jsx("svg",{viewBox:"0 0 24 24",width:"20",height:"20",fill:"currentColor","aria-hidden":"true",children:a.jsx("path",{d:"M12 8c1.1 0 2-.9 2-2s-.9-2-2-2-2 .9-2 2 .9 2 2 2zm0 2c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2zm0 6c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2z"})})}),C?a.jsxs("div",{role:"menu",className:J("absolute z-10 whitespace-nowrap rounded-lg border border-grayWarm-200 bg-white py-1 shadow-lg",t?"bottom-full left-1/2 mb-2 -translate-x-1/2":"right-0 top-full mt-1"),onClick:S=>S.stopPropagation(),"data-testid":`menu-${r.id}`,children:[t?a.jsx("span",{"aria-hidden":"true",className:"absolute -bottom-1.5 left-1/2 h-3 w-3 -translate-x-1/2 rotate-45 border-b border-r border-grayWarm-200 bg-white"}):null,!r.isDefault&&!h?a.jsx("button",{type:"button",role:"menuitem",className:"block w-full px-4 py-1 text-left text-md font-semibold text-grayWarm-950 hover:text-grayWarm-700",onClick:()=>{y(!1),c(r)},"data-testid":`menu-set-default-${r.id}`,children:"Set as default"}):null,a.jsx("button",{type:"button",role:"menuitem",className:"block w-full px-4 py-1 text-left text-md font-semibold text-error-700 hover:text-error-500",onClick:()=>{y(!1),d(r)},"data-testid":`menu-remove-${r.id}`,children:"Delete"})]}):null]})]})},ht=r=>`${Re().iconCdnBaseUrl}/website/assets/icons/payments/${r}.svg`,Je=({slug:r,alt:t})=>a.jsx("img",{src:ht(r),alt:t,height:20,loading:"lazy",style:{height:20,width:"auto"}}),$e=({type:r,label:t,iconNode:n})=>a.jsxs("label",{className:"flex cursor-pointer items-center gap-3 rounded-lg border border-grayWarm-200 px-4 py-3 transition-colors hover:border-grayWarm-300","data-testid":`payment-type-${r}`,children:[a.jsx("input",{type:"radio",name:"movmo-payment-type",value:r,onChange:()=>{},className:"h-4 w-4 cursor-pointer accent-grayWarm-900","aria-label":t}),a.jsxs("span",{className:"flex flex-1 items-center gap-2 text-sm font-semibold text-grayWarm-900",children:[t,n]})]}),yr=({selected:r,onSelect:t,creditCardBody:n,className:i})=>{const c=r==="credit_card";return a.jsxs("div",{className:J("flex w-full flex-col gap-3",i),children:[a.jsxs("label",{className:J("flex cursor-pointer flex-col gap-3 rounded-lg border px-4 py-3 transition-colors",c?"border-grayWarm-900 shadow-[0_0_0_1px_#1c1917]":"border-grayWarm-200"),"data-testid":"payment-type-credit_card",children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("input",{type:"radio",name:"movmo-payment-type",value:"credit_card",checked:c,onChange:()=>t("credit_card"),className:"h-4 w-4 cursor-pointer accent-grayWarm-900","aria-label":"Credit card"}),a.jsx("span",{className:"flex-1 text-sm font-semibold text-grayWarm-900",children:"Credit card"}),a.jsxs("div",{className:"flex items-center gap-1.5",children:[a.jsx(_e,{brand:"mastercard",width:28}),a.jsx(_e,{brand:"visa",width:28}),a.jsx(_e,{brand:"amex",width:28}),a.jsx(_e,{brand:"discover",width:28})]})]}),c?a.jsx("div",{"data-testid":"payment-type-credit_card-body",children:n}):null]}),c?a.jsx("p",{className:"mt-2 text-sm font-semibold text-grayWarm-900","data-testid":"payment-type-other-options-header",children:"Other options"}):null,a.jsx($e,{type:"paypal",label:"PayPal",iconNode:a.jsx(Je,{slug:"paypal",alt:"PayPal"})}),a.jsx($e,{type:"googlepay",label:"GooglePay",iconNode:a.jsx(Je,{slug:"google-pay",alt:"GooglePay"})}),a.jsx($e,{type:"klarna",label:"Klarna",iconNode:a.jsx(Je,{slug:"klarna",alt:"Klarna"})}),a.jsx($e,{type:"ach",label:"Bank account (ACH)",iconNode:a.jsx("span",{className:"text-xs font-medium text-grayWarm-500",children:"Direct debit"})})]})},vr="movmo-add-payment-form",br=r=>{const t=r.filter(i=>i.isDefault),n=r.filter(i=>!i.isDefault);return[...t,...n]},gr=({withDefaultBadge:r=!1})=>a.jsxs("div",{className:"flex items-start justify-between py-4","data-testid":"payment-method-skeleton",children:[a.jsxs("div",{className:"flex items-start gap-3",children:[a.jsx("div",{className:"h-8 w-[46px] flex-shrink-0 animate-pulse rounded bg-grayWarm-200"}),a.jsxs("div",{className:"space-y-2",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("div",{className:"h-5 w-[120px] animate-pulse rounded bg-grayWarm-200"}),r?a.jsx("div",{className:"h-5 w-[56px] animate-pulse rounded-full bg-grayWarm-200"}):null]}),a.jsx("div",{className:"h-4 w-[100px] animate-pulse rounded bg-grayWarm-200"})]})]}),a.jsx("div",{className:"h-5 w-5 flex-shrink-0 animate-pulse rounded-full bg-grayWarm-200"})]}),kr=({userId:r,defaultCardholderName:t,defaultCardholderFirstName:n,defaultCardholderLastName:i,selectedId:c,onSelect:d,onChange:p,paymentTypeSelector:v=!0,autoSaveFirstCard:h=!0,selectionSetsDefault:D=!1,showDefaultBadge:C=!0,collapsible:y=!1,cardLabelFormat:b="branded",className:_})=>{const{items:M,status:S,error:G,refetch:w}=Rr(r),{deletePaymentMethod:P,status:q}=jr(r),{setDefault:le,status:Q}=_r(r),[j,te]=o.useState([]),[fe,I]=o.useState(null),[T,u]=o.useState(!1),[F,R]=o.useState(null),[$,H]=o.useState(!1),[B,X]=o.useState(!1),[Y,N]=o.useState(null),[W,de]=o.useState(!1),me=o.useRef(!1),ve=o.useCallback(()=>{u(!1),R(null),N(null)},[]),be=t??([n,i].filter(Boolean).join(" ")||void 0);o.useEffect(()=>{S==="ready"&&te(br(M))},[M,S]),o.useEffect(()=>{if(!d||me.current||S!=="ready"||j.length===0||c)return;me.current=!0;const f=j.find(oe=>oe.isDefault)??j[0];d(f)},[d,S,j,c]);const ce=o.useCallback(f=>{te(oe=>{const ee=typeof f=="function"?f(oe):f,V=br(ee);return queueMicrotask(()=>p==null?void 0:p(V)),V})},[p]),ge=q==="pending"||Q==="pending",pe=o.useCallback(async f=>{const oe=j;I(null),ce(ee=>ee.map(V=>({...V,isDefault:V.id===f.id})));try{await le(f.id),w()}catch(ee){te(oe),p==null||p(oe);const V=ee instanceof Error?ee.message:"Failed to set default payment method.";I(V)}},[j,ce,le,w,p]),K=o.useCallback(f=>{d==null||d(f),D&&(f.isDefault||pe(f))},[d,D,pe]),ae=o.useCallback(async f=>{const oe=j;I(null);const ee=j.filter(ye=>ye.id!==f.id);ce(()=>ee);const V=f.id===c&&d?ee.find(ye=>ye.isDefault)??ee[0]??null:null;V&&K(V);const Ae=!!V&&D&&V!==null&&!V.isDefault;try{await P(f.id),Ae||w()}catch(ye){te(oe),p==null||p(oe);const Le=ye instanceof Error?ye.message:"Failed to delete payment method.";I(Le)}},[j,ce,P,w,p,c,d,K,D]),ne=o.useCallback(f=>{R(null),u(!1),N(null),ce(ee=>[f,...ee.filter(V=>V.id!==f.id)]),K(f),!!d&&D&&!f.isDefault||w()},[ce,w,K,d,D]),he=o.useCallback(f=>{R(f)},[]),xe=S==="ready"&&j.length===0,Ee=typeof d=="function",we=!Ee&&!y,se=j.length===0,g=h&&j.length===0,A=o.useCallback(f=>a.jsx(er,{userId:r,isDefault:se,defaultCardholderName:be,autoSave:!f&&g,hideInternalSaveButton:f,formId:f?vr:void 0,onCanSubmitChange:f?H:void 0,onSavingChange:f?X:void 0,autoFocus:f?"number":void 0,onSuccess:ne,onError:he}),[r,se,be,g,ne,he]),z=o.useMemo(()=>A(!1),[A]),ue=o.useMemo(()=>A(!0),[A]),Ue=o.useMemo(()=>v?a.jsx(yr,{selected:Y,onSelect:f=>N(f),creditCardBody:z}):z,[v,Y,z]),Ie=o.useMemo(()=>v?a.jsx(yr,{selected:Y,onSelect:f=>N(f),creditCardBody:ue}):ue,[v,Y,ue]);return a.jsxs("div",{className:J("flex w-full flex-col gap-4",_),"data-testid":"payment-methods-manager",children:[S==="loading"&&j.length===0?a.jsxs("div",{className:J(we?"flex flex-col divide-y divide-grayWarm-200 rounded-xl border border-grayWarm-200 px-4 md:px-6":"flex flex-col gap-2"),"data-testid":"payment-methods-loading",children:[a.jsx(gr,{withDefaultBadge:!0}),a.jsx(gr,{})]}):null,S==="error"?a.jsxs("div",{role:"alert","aria-live":"polite",className:"flex items-center justify-between gap-3 rounded-md bg-error-50 p-3 text-sm text-error-700","data-testid":"payment-methods-list-error",children:[a.jsx("span",{children:G??"Failed to load payment methods."}),a.jsx("button",{type:"button",onClick:w,className:"rounded-md border border-error-700 px-3 py-1 text-xs font-semibold text-error-700 hover:bg-error-50",children:"Retry"})]}):null,fe?a.jsx("div",{role:"alert","aria-live":"polite",className:"rounded-md bg-error-50 p-3 text-sm text-error-700","data-testid":"payment-methods-mutation-error",children:fe}):null,y&&j.length>0?a.jsx("div",{className:"border-t border-grayWarm-200 pt-4",children:a.jsxs("div",{className:"flex items-center justify-between","data-testid":W?"payment-methods-drawer-header":"payment-methods-collapsed-preview",children:[W?a.jsx("h3",{className:"text-md font-semibold text-grayWarm-950",children:"Payment methods"}):a.jsx(Cr,{method:j.find(f=>f.id===c)??j.find(f=>f.isDefault)??j[0],cardLabelFormat:b,className:"flex-1"}),a.jsx("button",{type:"button","aria-label":W?"Collapse payment methods":"Expand payment methods","aria-expanded":W,className:"bg-grayWarm-100 p-2 rounded-lg hover:bg-grayWarm-200 transition-colors",onClick:()=>de(f=>!f),"data-testid":W?"payment-methods-drawer-close":"payment-methods-drawer-open",children:a.jsx("img",{src:`${Re().iconCdnBaseUrl}/website/assets/icons/chevron-${W?"up":"down"}-double.svg`,alt:"",className:"w-5 h-5"})})]})}):null,j.length>0&&(!y||W)?a.jsx("div",{className:J("flex flex-col",we?"rounded-xl border border-grayWarm-200 px-4 md:px-6 divide-y divide-grayWarm-200":"space-y-3"),children:j.map(f=>a.jsx(pt,{method:f,selectable:Ee,selected:Ee&&f.id===c,onSelect:K,onSetDefault:pe,onRemove:ae,disabled:ge,showDefaultBadge:C,hideSetDefaultMenuItem:D,cardLabelFormat:b},f.id))}):null,xe?a.jsx("div",{"data-testid":"payment-methods-empty",children:Ue}):j.length>0&&(!y||W)?a.jsx("button",{type:"button",onClick:()=>{R(null),N(null),H(!1),u(!0)},onMouseEnter:()=>{Qe().catch(()=>{})},onFocus:()=>{Qe().catch(()=>{})},className:"self-start rounded-lg bg-brand-50 px-6 py-3 text-md font-semibold text-brand-600 transition-colors hover:bg-brand-100","data-testid":"payment-methods-add-trigger",children:"Add payment method"}):null,a.jsxs(dt,{open:T,onClose:ve,formId:vr,saveDisabled:!$,isSaving:B,children:[Ie,F?a.jsx("p",{role:"alert","aria-live":"polite",className:"mt-3 rounded-md bg-error-50 px-3 py-2 text-sm text-error-700","data-testid":"payment-methods-modal-error",children:F}):null]})]})};kr.displayName="PaymentMethodsManager";const yt="/v1/auth/",vt="movmo_csrf_token",bt=r=>{if(typeof document>"u")return null;const t=document.cookie?document.cookie.split(";"):[];for(const n of t){const i=n.trim();if(i.startsWith(r+"="))return decodeURIComponent(i.substring(r.length+1))}return null},gt=r=>typeof r=="string"?r:r instanceof URL?r.href:r.url,xt=()=>{if(typeof globalThis<"u"&&typeof globalThis.fetch=="function")return globalThis.fetch.bind(globalThis);throw new Error("@movmo_app/payments: no global fetch available in this environment")},wt=r=>{const{refreshSession:t,onRefreshFailed:n,csrfCookieName:i=vt,extraHeaders:c,authPathFragment:d=yt,baseFetch:p=xt(),readCookie:v=bt}=r;let h=null;const D=()=>{if(h)return h;const y=(async()=>{await t()})();return h=y,y.finally(()=>{h===y&&(h=null)}).catch(()=>{}),y},C=(y,b)=>{const _=new Headers(b==null?void 0:b.headers),M=v(i);if(M&&!_.has("X-CSRF-Token")&&_.set("X-CSRF-Token",M),c){const S=c(y,b);for(const[G,w]of Object.entries(S))_.has(G)||_.set(G,w)}return{...b,headers:_,credentials:(b==null?void 0:b.credentials)??"include"}};return async function(b,_){const M=await p(b,C(b,_));if(gt(b).includes(d)||M.status!==401&&M.status!==403)return M;try{await D()}catch(w){try{n(w)}catch(P){console.error("@movmo_app/payments: onRefreshFailed callback threw — auth retry path is misconfigured",P)}return M}try{return await p(b,C(b,_))}catch(w){return console.error("@movmo_app/payments: retry after token refresh failed — returning original response",w),M}}};exports.MovmoCardForm=er;exports.PaymentMethodPreview=Cr;exports.PaymentMethodsManager=kr;exports.createMovmoAuthFetch=wt;exports.getPaymentsConfig=Re;exports.setPaymentsConfig=Hr;exports.useDeletePaymentMethod=jr;exports.useMovmoCardFields=wr;exports.useSetDefaultPaymentMethod=_r;exports.useUserPaymentMethods=Rr;
|
|
31
31
|
//# sourceMappingURL=index.cjs.js.map
|