@fruga/sdk 1.0.4 → 1.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/README.md +8 -1
- package/dist/connect.d.mts +16 -1
- package/dist/connect.d.ts +16 -1
- package/dist/connect.js +1 -1
- package/dist/connect.mjs +1 -1
- package/dist/index.d.mts +324 -21
- package/dist/index.d.ts +324 -21
- package/dist/index.js +356 -216
- package/dist/index.mjs +337 -210
- package/dist/loader-react.d.mts +140 -25
- package/dist/loader-react.d.ts +140 -25
- package/dist/loader-react.js +1 -1
- package/dist/loader-react.mjs +1 -1
- package/dist/loader.d.mts +168 -6
- package/dist/loader.d.ts +168 -6
- package/dist/loader.global.js +3 -42
- package/dist/loader.js +1 -1
- package/dist/loader.mjs +1 -1
- package/dist/relay.css +1 -1
- package/dist/relay.d.mts +20 -2
- package/dist/relay.d.ts +20 -2
- package/dist/relay.js +1 -1
- package/dist/relay.mjs +1 -1
- package/package.json +21 -10
package/dist/loader.global.js
CHANGED
|
@@ -1,34 +1,6 @@
|
|
|
1
|
-
"use strict";var FrugaLoader=(()=>{var Wt=Object.create;var me=Object.defineProperty;var Ht=Object.getOwnPropertyDescriptor;var Yt=Object.getOwnPropertyNames;var zt=Object.getPrototypeOf,Gt=Object.prototype.hasOwnProperty;var qt=(t,r,o)=>r in t?me(t,r,{enumerable:!0,configurable:!0,writable:!0,value:o}):t[r]=o;var ne=(t,r)=>()=>(r||t((r={exports:{}}).exports,r),r.exports),Kt=(t,r)=>{for(var o in r)me(t,o,{get:r[o],enumerable:!0})},ut=(t,r,o,a)=>{if(r&&typeof r=="object"||typeof r=="function")for(let c of Yt(r))!Gt.call(t,c)&&c!==o&&me(t,c,{get:()=>r[c],enumerable:!(a=Ht(r,c))||a.enumerable});return t};var F=(t,r,o)=>(o=t!=null?Wt(zt(t)):{},ut(r||!t||!t.__esModule?me(o,"default",{value:t,enumerable:!0}):o,t)),Qt=t=>ut(me({},"__esModule",{value:!0}),t);var Re=(t,r,o)=>qt(t,typeof r!="symbol"?r+"":r,o);var lt=ne(Se=>{"use strict";var Xt=Symbol.for("react.transitional.element"),Zt=Symbol.for("react.fragment");function ct(t,r,o){var a=null;if(o!==void 0&&(a=""+o),r.key!==void 0&&(a=""+r.key),"key"in r){o={};for(var c in r)c!=="key"&&(o[c]=r[c])}else o=r;return r=o.ref,{$$typeof:Xt,type:t,key:a,ref:r!==void 0?r:null,props:o}}Se.Fragment=Zt;Se.jsx=ct;Se.jsxs=ct});var Tt=ne(p=>{"use strict";var De=Symbol.for("react.transitional.element"),Jt=Symbol.for("react.portal"),er=Symbol.for("react.fragment"),tr=Symbol.for("react.strict_mode"),rr=Symbol.for("react.profiler"),nr=Symbol.for("react.consumer"),or=Symbol.for("react.context"),sr=Symbol.for("react.forward_ref"),ar=Symbol.for("react.suspense"),ir=Symbol.for("react.memo"),mt=Symbol.for("react.lazy"),ur=Symbol.for("react.activity"),ft=Symbol.iterator;function cr(t){return t===null||typeof t!="object"?null:(t=ft&&t[ft]||t["@@iterator"],typeof t=="function"?t:null)}var ht={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},yt=Object.assign,Et={};function se(t,r,o){this.props=t,this.context=r,this.refs=Et,this.updater=o||ht}se.prototype.isReactComponent={};se.prototype.setState=function(t,r){if(typeof t!="object"&&typeof t!="function"&&t!=null)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,t,r,"setState")};se.prototype.forceUpdate=function(t){this.updater.enqueueForceUpdate(this,t,"forceUpdate")};function vt(){}vt.prototype=se.prototype;function je(t,r,o){this.props=t,this.context=r,this.refs=Et,this.updater=o||ht}var Ue=je.prototype=new vt;Ue.constructor=je;yt(Ue,se.prototype);Ue.isPureReactComponent=!0;var dt=Array.isArray;function Fe(){}var R={H:null,A:null,T:null,S:null},wt=Object.prototype.hasOwnProperty;function Be(t,r,o){var a=o.ref;return{$$typeof:De,type:t,key:r,ref:a!==void 0?a:null,props:o}}function lr(t,r){return Be(t.type,r,t.props)}function $e(t){return typeof t=="object"&&t!==null&&t.$$typeof===De}function fr(t){var r={"=":"=0",":":"=2"};return"$"+t.replace(/[=:]/g,function(o){return r[o]})}var pt=/\/+/g;function Ne(t,r){return typeof t=="object"&&t!==null&&t.key!=null?fr(""+t.key):r.toString(36)}function dr(t){switch(t.status){case"fulfilled":return t.value;case"rejected":throw t.reason;default:switch(typeof t.status=="string"?t.then(Fe,Fe):(t.status="pending",t.then(function(r){t.status==="pending"&&(t.status="fulfilled",t.value=r)},function(r){t.status==="pending"&&(t.status="rejected",t.reason=r)})),t.status){case"fulfilled":return t.value;case"rejected":throw t.reason}}throw t}function oe(t,r,o,a,c){var l=typeof t;(l==="undefined"||l==="boolean")&&(t=null);var m=!1;if(t===null)m=!0;else switch(l){case"bigint":case"string":case"number":m=!0;break;case"object":switch(t.$$typeof){case De:case Jt:m=!0;break;case mt:return m=t._init,oe(m(t._payload),r,o,a,c)}}if(m)return c=c(t),m=a===""?"."+Ne(t,0):a,dt(c)?(o="",m!=null&&(o=m.replace(pt,"$&/")+"/"),oe(c,r,o,"",function(w){return w})):c!=null&&($e(c)&&(c=lr(c,o+(c.key==null||t&&t.key===c.key?"":(""+c.key).replace(pt,"$&/")+"/")+m)),r.push(c)),1;m=0;var k=a===""?".":a+":";if(dt(t))for(var _=0;_<t.length;_++)a=t[_],l=k+Ne(a,_),m+=oe(a,r,o,l,c);else if(_=cr(t),typeof _=="function")for(t=_.call(t),_=0;!(a=t.next()).done;)a=a.value,l=k+Ne(a,_++),m+=oe(a,r,o,l,c);else if(l==="object"){if(typeof t.then=="function")return oe(dr(t),r,o,a,c);throw r=String(t),Error("Objects are not valid as a React child (found: "+(r==="[object Object]"?"object with keys {"+Object.keys(t).join(", ")+"}":r)+"). If you meant to render a collection of children, use an array instead.")}return m}function Ae(t,r,o){if(t==null)return t;var a=[],c=0;return oe(t,a,"","",function(l){return r.call(o,l,c++)}),a}function pr(t){if(t._status===-1){var r=t._result;r=r(),r.then(function(o){(t._status===0||t._status===-1)&&(t._status=1,t._result=o)},function(o){(t._status===0||t._status===-1)&&(t._status=2,t._result=o)}),t._status===-1&&(t._status=0,t._result=r)}if(t._status===1)return t._result.default;throw t._result}var gt=typeof reportError=="function"?reportError:function(t){if(typeof window=="object"&&typeof window.ErrorEvent=="function"){var r=new window.ErrorEvent("error",{bubbles:!0,cancelable:!0,message:typeof t=="object"&&t!==null&&typeof t.message=="string"?String(t.message):String(t),error:t});if(!window.dispatchEvent(r))return}else if(typeof process=="object"&&typeof process.emit=="function"){process.emit("uncaughtException",t);return}console.error(t)},gr={map:Ae,forEach:function(t,r,o){Ae(t,function(){r.apply(this,arguments)},o)},count:function(t){var r=0;return Ae(t,function(){r++}),r},toArray:function(t){return Ae(t,function(r){return r})||[]},only:function(t){if(!$e(t))throw Error("React.Children.only expected to receive a single React element child.");return t}};p.Activity=ur;p.Children=gr;p.Component=se;p.Fragment=er;p.Profiler=rr;p.PureComponent=je;p.StrictMode=tr;p.Suspense=ar;p.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=R;p.__COMPILER_RUNTIME={__proto__:null,c:function(t){return R.H.useMemoCache(t)}};p.cache=function(t){return function(){return t.apply(null,arguments)}};p.cacheSignal=function(){return null};p.cloneElement=function(t,r,o){if(t==null)throw Error("The argument must be a React element, but you passed "+t+".");var a=yt({},t.props),c=t.key;if(r!=null)for(l in r.key!==void 0&&(c=""+r.key),r)!wt.call(r,l)||l==="key"||l==="__self"||l==="__source"||l==="ref"&&r.ref===void 0||(a[l]=r[l]);var l=arguments.length-2;if(l===1)a.children=o;else if(1<l){for(var m=Array(l),k=0;k<l;k++)m[k]=arguments[k+2];a.children=m}return Be(t.type,c,a)};p.createContext=function(t){return t={$$typeof:or,_currentValue:t,_currentValue2:t,_threadCount:0,Provider:null,Consumer:null},t.Provider=t,t.Consumer={$$typeof:nr,_context:t},t};p.createElement=function(t,r,o){var a,c={},l=null;if(r!=null)for(a in r.key!==void 0&&(l=""+r.key),r)wt.call(r,a)&&a!=="key"&&a!=="__self"&&a!=="__source"&&(c[a]=r[a]);var m=arguments.length-2;if(m===1)c.children=o;else if(1<m){for(var k=Array(m),_=0;_<m;_++)k[_]=arguments[_+2];c.children=k}if(t&&t.defaultProps)for(a in m=t.defaultProps,m)c[a]===void 0&&(c[a]=m[a]);return Be(t,l,c)};p.createRef=function(){return{current:null}};p.forwardRef=function(t){return{$$typeof:sr,render:t}};p.isValidElement=$e;p.lazy=function(t){return{$$typeof:mt,_payload:{_status:-1,_result:t},_init:pr}};p.memo=function(t,r){return{$$typeof:ir,type:t,compare:r===void 0?null:r}};p.startTransition=function(t){var r=R.T,o={};R.T=o;try{var a=t(),c=R.S;c!==null&&c(o,a),typeof a=="object"&&a!==null&&typeof a.then=="function"&&a.then(Fe,gt)}catch(l){gt(l)}finally{r!==null&&o.types!==null&&(r.types=o.types),R.T=r}};p.unstable_useCacheRefresh=function(){return R.H.useCacheRefresh()};p.use=function(t){return R.H.use(t)};p.useActionState=function(t,r,o){return R.H.useActionState(t,r,o)};p.useCallback=function(t,r){return R.H.useCallback(t,r)};p.useContext=function(t){return R.H.useContext(t)};p.useDebugValue=function(){};p.useDeferredValue=function(t,r){return R.H.useDeferredValue(t,r)};p.useEffect=function(t,r){return R.H.useEffect(t,r)};p.useEffectEvent=function(t){return R.H.useEffectEvent(t)};p.useId=function(){return R.H.useId()};p.useImperativeHandle=function(t,r,o){return R.H.useImperativeHandle(t,r,o)};p.useInsertionEffect=function(t,r){return R.H.useInsertionEffect(t,r)};p.useLayoutEffect=function(t,r){return R.H.useLayoutEffect(t,r)};p.useMemo=function(t,r){return R.H.useMemo(t,r)};p.useOptimistic=function(t,r){return R.H.useOptimistic(t,r)};p.useReducer=function(t,r,o){return R.H.useReducer(t,r,o)};p.useRef=function(t){return R.H.useRef(t)};p.useState=function(t){return R.H.useState(t)};p.useSyncExternalStore=function(t,r,o){return R.H.useSyncExternalStore(t,r,o)};p.useTransition=function(){return R.H.useTransition()};p.version="19.2.4"});var _t=ne((d,ke)=>{"use strict";process.env.NODE_ENV!=="production"&&(function(){function t(e,n){Object.defineProperty(a.prototype,e,{get:function(){console.warn("%s(...) is deprecated in plain JavaScript React classes. %s",n[0],n[1])}})}function r(e){return e===null||typeof e!="object"?null:(e=ve&&e[ve]||e["@@iterator"],typeof e=="function"?e:null)}function o(e,n){e=(e=e.constructor)&&(e.displayName||e.name)||"ReactClass";var i=e+"."+n;Qe[i]||(console.error("Can't call %s on a component that is not yet mounted. This is a no-op, but it might indicate a bug in your application. Instead, assign to `this.state` directly or define a `state = {};` class property with the desired state in the %s component.",n,e),Qe[i]=!0)}function a(e,n,i){this.props=e,this.context=n,this.refs=Me,this.updater=i||Ve}function c(){}function l(e,n,i){this.props=e,this.context=n,this.refs=Me,this.updater=i||Ve}function m(){}function k(e){return""+e}function _(e){try{k(e);var n=!1}catch{n=!0}if(n){n=console;var i=n.error,u=typeof Symbol=="function"&&Symbol.toStringTag&&e[Symbol.toStringTag]||e.constructor.name||"Object";return i.call(n,"The provided key is an unsupported type %s. This value must be coerced to a string before using it here.",u),k(e)}}function w(e){if(e==null)return null;if(typeof e=="function")return e.$$typeof===Dt?null:e.displayName||e.name||null;if(typeof e=="string")return e;switch(e){case ee:return"Fragment";case s:return"Profiler";case de:return"StrictMode";case q:return"Suspense";case pe:return"SuspenseList";case te:return"Activity"}if(typeof e=="object")switch(typeof e.tag=="number"&&console.error("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."),e.$$typeof){case fe:return"Portal";case b:return e.displayName||"Context";case g:return(e._context.displayName||"Context")+".Consumer";case O:var n=e.render;return e=e.displayName,e||(e=n.displayName||n.name||"",e=e!==""?"ForwardRef("+e+")":"ForwardRef"),e;case A:return n=e.displayName||null,n!==null?n:w(e.type)||"Memo";case L:n=e._payload,e=e._init;try{return w(e(n))}catch{}}return null}function M(e){if(e===ee)return"<>";if(typeof e=="object"&&e!==null&&e.$$typeof===L)return"<...>";try{var n=w(e);return n?"<"+n+">":"<...>"}catch{return"<...>"}}function C(){var e=y.A;return e===null?null:e.getOwner()}function D(){return Error("react-stack-top-frame")}function P(e){if(we.call(e,"key")){var n=Object.getOwnPropertyDescriptor(e,"key").get;if(n&&n.isReactWarning)return!1}return e.key!==void 0}function x(e,n){function i(){et||(et=!0,console.error("%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://react.dev/link/special-props)",n))}i.isReactWarning=!0,Object.defineProperty(e,"key",{get:i,configurable:!0})}function ue(){var e=w(this.type);return rt[e]||(rt[e]=!0,console.error("Accessing element.ref was removed in React 19. ref is now a regular prop. It will be removed from the JSX Element type in a future release.")),e=this.props.ref,e!==void 0?e:null}function j(e,n,i,u,f,E){var h=i.ref;return e={$$typeof:J,type:e,key:n,props:i,_owner:u},(h!==void 0?h:null)!==null?Object.defineProperty(e,"ref",{enumerable:!1,get:ue}):Object.defineProperty(e,"ref",{enumerable:!1,value:null}),e._store={},Object.defineProperty(e._store,"validated",{configurable:!1,enumerable:!1,writable:!0,value:0}),Object.defineProperty(e,"_debugInfo",{configurable:!1,enumerable:!1,writable:!0,value:null}),Object.defineProperty(e,"_debugStack",{configurable:!1,enumerable:!1,writable:!0,value:f}),Object.defineProperty(e,"_debugTask",{configurable:!1,enumerable:!1,writable:!0,value:E}),Object.freeze&&(Object.freeze(e.props),Object.freeze(e)),e}function Q(e,n){return n=j(e.type,n,e.props,e._owner,e._debugStack,e._debugTask),e._store&&(n._store.validated=e._store.validated),n}function I(e){U(e)?e._store&&(e._store.validated=1):typeof e=="object"&&e!==null&&e.$$typeof===L&&(e._payload.status==="fulfilled"?U(e._payload.value)&&e._payload.value._store&&(e._payload.value._store.validated=1):e._store&&(e._store.validated=1))}function U(e){return typeof e=="object"&&e!==null&&e.$$typeof===J}function ce(e){var n={"=":"=0",":":"=2"};return"$"+e.replace(/[=:]/g,function(i){return n[i]})}function z(e,n){return typeof e=="object"&&e!==null&&e.key!=null?(_(e.key),ce(""+e.key)):n.toString(36)}function Ie(e){switch(e.status){case"fulfilled":return e.value;case"rejected":throw e.reason;default:switch(typeof e.status=="string"?e.then(m,m):(e.status="pending",e.then(function(n){e.status==="pending"&&(e.status="fulfilled",e.value=n)},function(n){e.status==="pending"&&(e.status="rejected",e.reason=n)})),e.status){case"fulfilled":return e.value;case"rejected":throw e.reason}}throw e}function $(e,n,i,u,f){var E=typeof e;(E==="undefined"||E==="boolean")&&(e=null);var h=!1;if(e===null)h=!0;else switch(E){case"bigint":case"string":case"number":h=!0;break;case"object":switch(e.$$typeof){case J:case fe:h=!0;break;case L:return h=e._init,$(h(e._payload),n,i,u,f)}}if(h){h=e,f=f(h);var T=u===""?"."+z(h,0):u;return Ze(f)?(i="",T!=null&&(i=T.replace(ot,"$&/")+"/"),$(f,n,i,"",function(Y){return Y})):f!=null&&(U(f)&&(f.key!=null&&(h&&h.key===f.key||_(f.key)),i=Q(f,i+(f.key==null||h&&h.key===f.key?"":(""+f.key).replace(ot,"$&/")+"/")+T),u!==""&&h!=null&&U(h)&&h.key==null&&h._store&&!h._store.validated&&(i._store.validated=2),f=i),n.push(f)),1}if(h=0,T=u===""?".":u+":",Ze(e))for(var v=0;v<e.length;v++)u=e[v],E=T+z(u,v),h+=$(u,n,i,E,f);else if(v=r(e),typeof v=="function")for(v===e.entries&&(nt||console.warn("Using Maps as children is not supported. Use an array of keyed ReactElements instead."),nt=!0),e=v.call(e),v=0;!(u=e.next()).done;)u=u.value,E=T+z(u,v++),h+=$(u,n,i,E,f);else if(E==="object"){if(typeof e.then=="function")return $(Ie(e),n,i,u,f);throw n=String(e),Error("Objects are not valid as a React child (found: "+(n==="[object Object]"?"object with keys {"+Object.keys(e).join(", ")+"}":n)+"). If you meant to render a collection of children, use an array instead.")}return h}function V(e,n,i){if(e==null)return e;var u=[],f=0;return $(e,u,"","",function(E){return n.call(i,E,f++)}),u}function le(e){if(e._status===-1){var n=e._ioInfo;n!=null&&(n.start=n.end=performance.now()),n=e._result;var i=n();if(i.then(function(f){if(e._status===0||e._status===-1){e._status=1,e._result=f;var E=e._ioInfo;E!=null&&(E.end=performance.now()),i.status===void 0&&(i.status="fulfilled",i.value=f)}},function(f){if(e._status===0||e._status===-1){e._status=2,e._result=f;var E=e._ioInfo;E!=null&&(E.end=performance.now()),i.status===void 0&&(i.status="rejected",i.reason=f)}}),n=e._ioInfo,n!=null){n.value=i;var u=i.displayName;typeof u=="string"&&(n.name=u)}e._status===-1&&(e._status=0,e._result=i)}if(e._status===1)return n=e._result,n===void 0&&console.error(`lazy: Expected the result of a dynamic import() call. Instead received: %s
|
|
2
|
-
|
|
3
|
-
Your code should look like:
|
|
4
|
-
const MyComponent = lazy(() => import('./MyComponent'))
|
|
5
|
-
|
|
6
|
-
Did you accidentally put curly braces around the import?`,n),"default"in n||console.error(`lazy: Expected the result of a dynamic import() call. Instead received: %s
|
|
7
|
-
|
|
8
|
-
Your code should look like:
|
|
9
|
-
const MyComponent = lazy(() => import('./MyComponent'))`,n),n.default;throw e._result}function S(){var e=y.H;return e===null&&console.error(`Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
|
|
10
|
-
1. You might have mismatching versions of React and the renderer (such as React DOM)
|
|
11
|
-
2. You might be breaking the Rules of Hooks
|
|
12
|
-
3. You might have more than one copy of React in the same app
|
|
13
|
-
See https://react.dev/link/invalid-hook-call for tips about how to debug and fix this problem.`),e}function Ee(){y.asyncTransitions--}function W(e){if(Te===null)try{var n=("require"+Math.random()).slice(0,7);Te=(ke&&ke[n]).call(ke,"timers").setImmediate}catch{Te=function(u){at===!1&&(at=!0,typeof MessageChannel>"u"&&console.error("This browser does not have a MessageChannel implementation, so enqueuing tasks via await act(async () => ...) will fail. Please file an issue at https://github.com/facebook/react/issues if you encounter this warning."));var f=new MessageChannel;f.port1.onmessage=u,f.port2.postMessage(void 0)}}return Te(e)}function H(e){return 1<e.length&&typeof AggregateError=="function"?new AggregateError(e):e[0]}function X(e,n){n!==_e-1&&console.error("You seem to have overlapping act() calls, this is not supported. Be sure to await previous act() calls before making a new one. "),_e=n}function G(e,n,i){var u=y.actQueue;if(u!==null)if(u.length!==0)try{Z(u),W(function(){return G(e,n,i)});return}catch(f){y.thrownErrors.push(f)}else y.actQueue=null;0<y.thrownErrors.length?(u=H(y.thrownErrors),y.thrownErrors.length=0,i(u)):n(e)}function Z(e){if(!Le){Le=!0;var n=0;try{for(;n<e.length;n++){var i=e[n];do{y.didUsePromise=!1;var u=i(!1);if(u!==null){if(y.didUsePromise){e[n]=i,e.splice(0,n);return}i=u}else break}while(!0)}e.length=0}catch(f){e.splice(0,n+1),y.thrownErrors.push(f)}finally{Le=!1}}}typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<"u"&&typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart=="function"&&__REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(Error());var J=Symbol.for("react.transitional.element"),fe=Symbol.for("react.portal"),ee=Symbol.for("react.fragment"),de=Symbol.for("react.strict_mode"),s=Symbol.for("react.profiler"),g=Symbol.for("react.consumer"),b=Symbol.for("react.context"),O=Symbol.for("react.forward_ref"),q=Symbol.for("react.suspense"),pe=Symbol.for("react.suspense_list"),A=Symbol.for("react.memo"),L=Symbol.for("react.lazy"),te=Symbol.for("react.activity"),ve=Symbol.iterator,Qe={},Ve={isMounted:function(){return!1},enqueueForceUpdate:function(e){o(e,"forceUpdate")},enqueueReplaceState:function(e){o(e,"replaceState")},enqueueSetState:function(e){o(e,"setState")}},Xe=Object.assign,Me={};Object.freeze(Me),a.prototype.isReactComponent={},a.prototype.setState=function(e,n){if(typeof e!="object"&&typeof e!="function"&&e!=null)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,e,n,"setState")},a.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,"forceUpdate")};var N={isMounted:["isMounted","Instead, make sure to clean up subscriptions and pending requests in componentWillUnmount to prevent memory leaks."],replaceState:["replaceState","Refactor your code to use setState instead (see https://github.com/facebook/react/issues/3236)."]};for(ge in N)N.hasOwnProperty(ge)&&t(ge,N[ge]);c.prototype=a.prototype,N=l.prototype=new c,N.constructor=l,Xe(N,a.prototype),N.isPureReactComponent=!0;var Ze=Array.isArray,Dt=Symbol.for("react.client.reference"),y={H:null,A:null,T:null,S:null,actQueue:null,asyncTransitions:0,isBatchingLegacy:!1,didScheduleLegacyUpdate:!1,didUsePromise:!1,thrownErrors:[],getCurrentStack:null,recentlyCreatedOwnerStacks:0},we=Object.prototype.hasOwnProperty,Je=console.createTask?console.createTask:function(){return null};N={react_stack_bottom_frame:function(e){return e()}};var et,tt,rt={},jt=N.react_stack_bottom_frame.bind(N,D)(),Ut=Je(M(D)),nt=!1,ot=/\/+/g,st=typeof reportError=="function"?reportError:function(e){if(typeof window=="object"&&typeof window.ErrorEvent=="function"){var n=new window.ErrorEvent("error",{bubbles:!0,cancelable:!0,message:typeof e=="object"&&e!==null&&typeof e.message=="string"?String(e.message):String(e),error:e});if(!window.dispatchEvent(n))return}else if(typeof process=="object"&&typeof process.emit=="function"){process.emit("uncaughtException",e);return}console.error(e)},at=!1,Te=null,_e=0,be=!1,Le=!1,it=typeof queueMicrotask=="function"?function(e){queueMicrotask(function(){return queueMicrotask(e)})}:W;N=Object.freeze({__proto__:null,c:function(e){return S().useMemoCache(e)}});var ge={map:V,forEach:function(e,n,i){V(e,function(){n.apply(this,arguments)},i)},count:function(e){var n=0;return V(e,function(){n++}),n},toArray:function(e){return V(e,function(n){return n})||[]},only:function(e){if(!U(e))throw Error("React.Children.only expected to receive a single React element child.");return e}};d.Activity=te,d.Children=ge,d.Component=a,d.Fragment=ee,d.Profiler=s,d.PureComponent=l,d.StrictMode=de,d.Suspense=q,d.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=y,d.__COMPILER_RUNTIME=N,d.act=function(e){var n=y.actQueue,i=_e;_e++;var u=y.actQueue=n!==null?n:[],f=!1;try{var E=e()}catch(v){y.thrownErrors.push(v)}if(0<y.thrownErrors.length)throw X(n,i),e=H(y.thrownErrors),y.thrownErrors.length=0,e;if(E!==null&&typeof E=="object"&&typeof E.then=="function"){var h=E;return it(function(){f||be||(be=!0,console.error("You called act(async () => ...) without await. This could lead to unexpected testing behaviour, interleaving multiple act calls and mixing their scopes. You should - await act(async () => ...);"))}),{then:function(v,Y){f=!0,h.then(function(re){if(X(n,i),i===0){try{Z(u),W(function(){return G(re,v,Y)})}catch($t){y.thrownErrors.push($t)}if(0<y.thrownErrors.length){var Bt=H(y.thrownErrors);y.thrownErrors.length=0,Y(Bt)}}else v(re)},function(re){X(n,i),0<y.thrownErrors.length&&(re=H(y.thrownErrors),y.thrownErrors.length=0),Y(re)})}}}var T=E;if(X(n,i),i===0&&(Z(u),u.length!==0&&it(function(){f||be||(be=!0,console.error("A component suspended inside an `act` scope, but the `act` call was not awaited. When testing React components that depend on asynchronous data, you must await the result:\n\nawait act(() => ...)"))}),y.actQueue=null),0<y.thrownErrors.length)throw e=H(y.thrownErrors),y.thrownErrors.length=0,e;return{then:function(v,Y){f=!0,i===0?(y.actQueue=u,W(function(){return G(T,v,Y)})):v(T)}}},d.cache=function(e){return function(){return e.apply(null,arguments)}},d.cacheSignal=function(){return null},d.captureOwnerStack=function(){var e=y.getCurrentStack;return e===null?null:e()},d.cloneElement=function(e,n,i){if(e==null)throw Error("The argument must be a React element, but you passed "+e+".");var u=Xe({},e.props),f=e.key,E=e._owner;if(n!=null){var h;e:{if(we.call(n,"ref")&&(h=Object.getOwnPropertyDescriptor(n,"ref").get)&&h.isReactWarning){h=!1;break e}h=n.ref!==void 0}h&&(E=C()),P(n)&&(_(n.key),f=""+n.key);for(T in n)!we.call(n,T)||T==="key"||T==="__self"||T==="__source"||T==="ref"&&n.ref===void 0||(u[T]=n[T])}var T=arguments.length-2;if(T===1)u.children=i;else if(1<T){h=Array(T);for(var v=0;v<T;v++)h[v]=arguments[v+2];u.children=h}for(u=j(e.type,f,u,E,e._debugStack,e._debugTask),f=2;f<arguments.length;f++)I(arguments[f]);return u},d.createContext=function(e){return e={$$typeof:b,_currentValue:e,_currentValue2:e,_threadCount:0,Provider:null,Consumer:null},e.Provider=e,e.Consumer={$$typeof:g,_context:e},e._currentRenderer=null,e._currentRenderer2=null,e},d.createElement=function(e,n,i){for(var u=2;u<arguments.length;u++)I(arguments[u]);u={};var f=null;if(n!=null)for(v in tt||!("__self"in n)||"key"in n||(tt=!0,console.warn("Your app (or one of its dependencies) is using an outdated JSX transform. Update to the modern JSX transform for faster performance: https://react.dev/link/new-jsx-transform")),P(n)&&(_(n.key),f=""+n.key),n)we.call(n,v)&&v!=="key"&&v!=="__self"&&v!=="__source"&&(u[v]=n[v]);var E=arguments.length-2;if(E===1)u.children=i;else if(1<E){for(var h=Array(E),T=0;T<E;T++)h[T]=arguments[T+2];Object.freeze&&Object.freeze(h),u.children=h}if(e&&e.defaultProps)for(v in E=e.defaultProps,E)u[v]===void 0&&(u[v]=E[v]);f&&x(u,typeof e=="function"?e.displayName||e.name||"Unknown":e);var v=1e4>y.recentlyCreatedOwnerStacks++;return j(e,f,u,C(),v?Error("react-stack-top-frame"):jt,v?Je(M(e)):Ut)},d.createRef=function(){var e={current:null};return Object.seal(e),e},d.forwardRef=function(e){e!=null&&e.$$typeof===A?console.error("forwardRef requires a render function but received a `memo` component. Instead of forwardRef(memo(...)), use memo(forwardRef(...))."):typeof e!="function"?console.error("forwardRef requires a render function but was given %s.",e===null?"null":typeof e):e.length!==0&&e.length!==2&&console.error("forwardRef render functions accept exactly two parameters: props and ref. %s",e.length===1?"Did you forget to use the ref parameter?":"Any additional parameter will be undefined."),e!=null&&e.defaultProps!=null&&console.error("forwardRef render functions do not support defaultProps. Did you accidentally pass a React component?");var n={$$typeof:O,render:e},i;return Object.defineProperty(n,"displayName",{enumerable:!1,configurable:!0,get:function(){return i},set:function(u){i=u,e.name||e.displayName||(Object.defineProperty(e,"name",{value:u}),e.displayName=u)}}),n},d.isValidElement=U,d.lazy=function(e){e={_status:-1,_result:e};var n={$$typeof:L,_payload:e,_init:le},i={name:"lazy",start:-1,end:-1,value:null,owner:null,debugStack:Error("react-stack-top-frame"),debugTask:console.createTask?console.createTask("lazy()"):null};return e._ioInfo=i,n._debugInfo=[{awaited:i}],n},d.memo=function(e,n){e==null&&console.error("memo: The first argument must be a component. Instead received: %s",e===null?"null":typeof e),n={$$typeof:A,type:e,compare:n===void 0?null:n};var i;return Object.defineProperty(n,"displayName",{enumerable:!1,configurable:!0,get:function(){return i},set:function(u){i=u,e.name||e.displayName||(Object.defineProperty(e,"name",{value:u}),e.displayName=u)}}),n},d.startTransition=function(e){var n=y.T,i={};i._updatedFibers=new Set,y.T=i;try{var u=e(),f=y.S;f!==null&&f(i,u),typeof u=="object"&&u!==null&&typeof u.then=="function"&&(y.asyncTransitions++,u.then(Ee,Ee),u.then(m,st))}catch(E){st(E)}finally{n===null&&i._updatedFibers&&(e=i._updatedFibers.size,i._updatedFibers.clear(),10<e&&console.warn("Detected a large number of updates inside startTransition. If this is due to a subscription please re-write it to use React provided hooks. Otherwise concurrent mode guarantees are off the table.")),n!==null&&i.types!==null&&(n.types!==null&&n.types!==i.types&&console.error("We expected inner Transitions to have transferred the outer types set and that you cannot add to the outer Transition while inside the inner.This is a bug in React."),n.types=i.types),y.T=n}},d.unstable_useCacheRefresh=function(){return S().useCacheRefresh()},d.use=function(e){return S().use(e)},d.useActionState=function(e,n,i){return S().useActionState(e,n,i)},d.useCallback=function(e,n){return S().useCallback(e,n)},d.useContext=function(e){var n=S();return e.$$typeof===g&&console.error("Calling useContext(Context.Consumer) is not supported and will cause bugs. Did you mean to call useContext(Context) instead?"),n.useContext(e)},d.useDebugValue=function(e,n){return S().useDebugValue(e,n)},d.useDeferredValue=function(e,n){return S().useDeferredValue(e,n)},d.useEffect=function(e,n){return e==null&&console.warn("React Hook useEffect requires an effect callback. Did you forget to pass a callback to the hook?"),S().useEffect(e,n)},d.useEffectEvent=function(e){return S().useEffectEvent(e)},d.useId=function(){return S().useId()},d.useImperativeHandle=function(e,n,i){return S().useImperativeHandle(e,n,i)},d.useInsertionEffect=function(e,n){return e==null&&console.warn("React Hook useInsertionEffect requires an effect callback. Did you forget to pass a callback to the hook?"),S().useInsertionEffect(e,n)},d.useLayoutEffect=function(e,n){return e==null&&console.warn("React Hook useLayoutEffect requires an effect callback. Did you forget to pass a callback to the hook?"),S().useLayoutEffect(e,n)},d.useMemo=function(e,n){return S().useMemo(e,n)},d.useOptimistic=function(e,n){return S().useOptimistic(e,n)},d.useReducer=function(e,n,i){return S().useReducer(e,n,i)},d.useRef=function(e){return S().useRef(e)},d.useState=function(e){return S().useState(e)},d.useSyncExternalStore=function(e,n,i){return S().useSyncExternalStore(e,n,i)},d.useTransition=function(){return S().useTransition()},d.version="19.2.4",typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<"u"&&typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop=="function"&&__REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(Error())})()});var ae=ne((Hr,We)=>{"use strict";process.env.NODE_ENV==="production"?We.exports=Tt():We.exports=_t()});var bt=ne(Oe=>{"use strict";process.env.NODE_ENV!=="production"&&(function(){function t(s){if(s==null)return null;if(typeof s=="function")return s.$$typeof===Ee?null:s.displayName||s.name||null;if(typeof s=="string")return s;switch(s){case j:return"Fragment";case I:return"Profiler";case Q:return"StrictMode";case Ie:return"Suspense";case $:return"SuspenseList";case S:return"Activity"}if(typeof s=="object")switch(typeof s.tag=="number"&&console.error("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."),s.$$typeof){case ue:return"Portal";case ce:return s.displayName||"Context";case U:return(s._context.displayName||"Context")+".Consumer";case z:var g=s.render;return s=s.displayName,s||(s=g.displayName||g.name||"",s=s!==""?"ForwardRef("+s+")":"ForwardRef"),s;case V:return g=s.displayName||null,g!==null?g:t(s.type)||"Memo";case le:g=s._payload,s=s._init;try{return t(s(g))}catch{}}return null}function r(s){return""+s}function o(s){try{r(s);var g=!1}catch{g=!0}if(g){g=console;var b=g.error,O=typeof Symbol=="function"&&Symbol.toStringTag&&s[Symbol.toStringTag]||s.constructor.name||"Object";return b.call(g,"The provided key is an unsupported type %s. This value must be coerced to a string before using it here.",O),r(s)}}function a(s){if(s===j)return"<>";if(typeof s=="object"&&s!==null&&s.$$typeof===le)return"<...>";try{var g=t(s);return g?"<"+g+">":"<...>"}catch{return"<...>"}}function c(){var s=W.A;return s===null?null:s.getOwner()}function l(){return Error("react-stack-top-frame")}function m(s){if(H.call(s,"key")){var g=Object.getOwnPropertyDescriptor(s,"key").get;if(g&&g.isReactWarning)return!1}return s.key!==void 0}function k(s,g){function b(){Z||(Z=!0,console.error("%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://react.dev/link/special-props)",g))}b.isReactWarning=!0,Object.defineProperty(s,"key",{get:b,configurable:!0})}function _(){var s=t(this.type);return J[s]||(J[s]=!0,console.error("Accessing element.ref was removed in React 19. ref is now a regular prop. It will be removed from the JSX Element type in a future release.")),s=this.props.ref,s!==void 0?s:null}function w(s,g,b,O,q,pe){var A=b.ref;return s={$$typeof:x,type:s,key:g,props:b,_owner:O},(A!==void 0?A:null)!==null?Object.defineProperty(s,"ref",{enumerable:!1,get:_}):Object.defineProperty(s,"ref",{enumerable:!1,value:null}),s._store={},Object.defineProperty(s._store,"validated",{configurable:!1,enumerable:!1,writable:!0,value:0}),Object.defineProperty(s,"_debugInfo",{configurable:!1,enumerable:!1,writable:!0,value:null}),Object.defineProperty(s,"_debugStack",{configurable:!1,enumerable:!1,writable:!0,value:q}),Object.defineProperty(s,"_debugTask",{configurable:!1,enumerable:!1,writable:!0,value:pe}),Object.freeze&&(Object.freeze(s.props),Object.freeze(s)),s}function M(s,g,b,O,q,pe){var A=g.children;if(A!==void 0)if(O)if(X(A)){for(O=0;O<A.length;O++)C(A[O]);Object.freeze&&Object.freeze(A)}else console.error("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 C(A);if(H.call(g,"key")){A=t(s);var L=Object.keys(g).filter(function(ve){return ve!=="key"});O=0<L.length?"{key: someKey, "+L.join(": ..., ")+": ...}":"{key: someKey}",de[A+O]||(L=0<L.length?"{"+L.join(": ..., ")+": ...}":"{}",console.error(`A props object containing a "key" prop is being spread into JSX:
|
|
14
|
-
let props = %s;
|
|
15
|
-
<%s {...props} />
|
|
16
|
-
React keys must be passed directly to JSX without using spread:
|
|
17
|
-
let props = %s;
|
|
18
|
-
<%s key={someKey} {...props} />`,O,A,L,A),de[A+O]=!0)}if(A=null,b!==void 0&&(o(b),A=""+b),m(g)&&(o(g.key),A=""+g.key),"key"in g){b={};for(var te in g)te!=="key"&&(b[te]=g[te])}else b=g;return A&&k(b,typeof s=="function"?s.displayName||s.name||"Unknown":s),w(s,A,b,c(),q,pe)}function C(s){D(s)?s._store&&(s._store.validated=1):typeof s=="object"&&s!==null&&s.$$typeof===le&&(s._payload.status==="fulfilled"?D(s._payload.value)&&s._payload.value._store&&(s._payload.value._store.validated=1):s._store&&(s._store.validated=1))}function D(s){return typeof s=="object"&&s!==null&&s.$$typeof===x}var P=ae(),x=Symbol.for("react.transitional.element"),ue=Symbol.for("react.portal"),j=Symbol.for("react.fragment"),Q=Symbol.for("react.strict_mode"),I=Symbol.for("react.profiler"),U=Symbol.for("react.consumer"),ce=Symbol.for("react.context"),z=Symbol.for("react.forward_ref"),Ie=Symbol.for("react.suspense"),$=Symbol.for("react.suspense_list"),V=Symbol.for("react.memo"),le=Symbol.for("react.lazy"),S=Symbol.for("react.activity"),Ee=Symbol.for("react.client.reference"),W=P.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,H=Object.prototype.hasOwnProperty,X=Array.isArray,G=console.createTask?console.createTask:function(){return null};P={react_stack_bottom_frame:function(s){return s()}};var Z,J={},fe=P.react_stack_bottom_frame.bind(P,l)(),ee=G(a(l)),de={};Oe.Fragment=j,Oe.jsx=function(s,g,b){var O=1e4>W.recentlyCreatedOwnerStacks++;return M(s,g,b,!1,O?Error("react-stack-top-frame"):fe,O?G(a(s)):ee)},Oe.jsxs=function(s,g,b){var O=1e4>W.recentlyCreatedOwnerStacks++;return M(s,g,b,!0,O?Error("react-stack-top-frame"):fe,O?G(a(s)):ee)}})()});var B=ne((zr,He)=>{"use strict";process.env.NODE_ENV==="production"?He.exports=lt():He.exports=bt()});var _r={};Kt(_r,{getBalance:()=>Ft,init:()=>Ke,mount:()=>It,requestBalance:()=>Nt,setOptions:()=>Lt,unmount:()=>Mt});var mr=F(B());var ze=F(ae());var hr=F(B());var Ot=F(ae());var Rt=t=>{let r,o=new Set,a=(w,M)=>{let C=typeof w=="function"?w(r):w;if(!Object.is(C,r)){let D=r;r=M??(typeof C!="object"||C===null)?C:Object.assign({},r,C),o.forEach(P=>P(r,D))}},c=()=>r,k={setState:a,getState:c,getInitialState:()=>_,subscribe:w=>(o.add(w),()=>o.delete(w))},_=r=t(a,c,k);return k},St=(t=>t?Rt(t):Rt);var he=F(ae(),1);var yr=t=>t;function Er(t,r=yr){let o=he.default.useSyncExternalStore(t.subscribe,he.default.useCallback(()=>r(t.getState()),[t,r]),he.default.useCallback(()=>r(t.getInitialState()),[t,r]));return he.default.useDebugValue(o),o}var At=t=>{let r=St(t),o=a=>Er(r,a);return Object.assign(o,r),o},kt=(t=>t?At(t):At);var Ye=kt(t=>({isOpen:!1,isFocused:!0,isIdle:!1,available:0,pending:0,mode:"light",token:null,partnerPayout:null,isAddingPayoutFromAlert:!1,showPayoutSuccess:!1,toggle:()=>t(r=>({isOpen:!r.isOpen})),setOpen:r=>t({isOpen:r}),setFocused:r=>t({isFocused:r}),setIdle:r=>t({isIdle:r}),setBalances:(r,o)=>t({available:r,pending:o}),setMode:r=>t({mode:r}),setToken:r=>t({token:r}),setPartnerPayout:r=>t({partnerPayout:r}),setIsAddingPayoutFromAlert:r=>t({isAddingPayoutFromAlert:r}),setShowPayoutSuccess:r=>t({showPayoutSuccess:r})}));var Ge=F(B());var xt=F(B());var Ct=F(ae());var ye={BOOTSTRAP_DATA:"fruga_bootstrap",BOOTSTRAP_CONFIG:"fruga_active_config"},K=class{static set(r,o){if(!(typeof window>"u"))try{window.localStorage.setItem(r,JSON.stringify(o))}catch(a){console.warn(`[FrugaStorage] Failed to save key "${r}":`,a)}}static get(r){if(typeof window>"u")return null;try{let o=window.localStorage.getItem(r);return o?JSON.parse(o):null}catch(o){return console.warn(`[FrugaStorage] Failed to load key "${r}":`,o),null}}static remove(r){typeof window>"u"||window.localStorage.removeItem(r)}static clear(){typeof window>"u"||window.localStorage.clear()}};var vr=typeof process<"u"&&process.env.VITE_FRUGA_API_URL||"https://api-dev.fruga.co.uk",Pt=t=>t||vr;var qe={partnerEnvId:"env_dev_123",partnerId:"partner_abc_456",partnerType:"EXTERNAL_TENANT",partnerPayout:"USER",auth:{mode:"JWT",audience:"https://api.fruga.io",issuer:"https://auth.fruga.io",tokenTtlSeconds:70},config:{ui:{accent:"#F97316",defaultTheme:"light",launcherIcon:"arrow",showLauncher:!0,launcherLabel:"Help",accentTextDark:"#832424",accentTextLight:"#d81414",allowUserThemeControl:!0},validValues:{defaultTheme:["light","dark"],launcherIcon:["none","gift","sparkles","credit","arrow"]}}};var xe=class{async bootstrap(r,o){let a=Pt(o);if(typeof process<"u"&&process.env.VITE_FRUGA_MODE==="test")return console.log("Fruga SDK: Using bootstrap mocks (VITE_FRUGA_MODE=test)"),qe;try{let l=await fetch(`${a}/widget/bootstrap?partnerKey=${r}`,{method:"GET",headers:{Accept:"application/json","Content-Type":"application/json"}});if(!l.ok)throw new Error(`Bootstrap failed with status: ${l.status}`);return await l.json()}catch(l){return console.error("Fruga SDK: Bootstrap failed, falling back to mocks",l),qe}}};var Ce=class{mount(r,o,a){let{partnerKey:c,theme:l,primaryColor:m,appUrl:k,userId:_}=a,w=document.createElement("iframe"),M=o.partnerType==="EXTERNAL_TENANT"?"relay":"connect",C=typeof document<"u"?document.currentScript:null,D=C?.src||(typeof window<"u"?window.location.href:""),P=`./${M}/index.html`;if(!C)P=`https://frugainsurance.github.io/sdk/${M}/index.html`;else try{new URL(D).pathname.includes("/dist/")&&(P=`./${M}/index.html`)}catch{}let x=new URL(k||o.appUrl||P,D);x.searchParams.set("partnerKey",c),x.searchParams.set("partnerId",o.partnerId);let ue=typeof window<"u"?window.innerWidth<768:!1;if(x.searchParams.set("isHostMobile",String(ue)),typeof window<"u"&&(x.searchParams.set("hostHeight",String(window.innerHeight)),x.searchParams.set("hostWidth",String(window.innerWidth))),l&&x.searchParams.set("theme",l),m&&x.searchParams.set("primaryColor",m),_&&x.searchParams.set("userId",_),o.token&&x.searchParams.set("token",o.token),a.baseUrl&&x.searchParams.set("baseUrl",a.baseUrl),o.bootstrapConfig)try{let I=btoa(JSON.stringify(o.bootstrapConfig));x.searchParams.set("bootstrapConfig",I)}catch(I){console.warn("FrugaLoader: Failed to encode bootstrapConfig for iframe URL",I)}w.src=x.toString(),w.style.border="none",w.style.width="410px",w.style.height="600px",w.style.backgroundColor="transparent";let j=I=>{if(I.source===w.contentWindow&&I.data?.type==="FRUGA_RESIZE"){let{width:U,height:ce,isFullscreen:z}=I.data;z?(w.style.position="fixed",w.style.inset="0",w.style.width="100vw",w.style.height="100vh",w.style.zIndex="99999"):(w.style.position="static",w.style.width=`${U}px`,w.style.height=`${ce}px`,w.style.zIndex="auto")}},Q=()=>{w.contentWindow?.postMessage({type:"FRUGA_HOST_RESIZE",isHostMobile:window.innerWidth<768,hostHeight:window.innerHeight,hostWidth:window.innerWidth},"*")};return window.addEventListener("message",j),window.addEventListener("resize",Q),r.appendChild(w),{iframe:w,cleanup:()=>{window.removeEventListener("message",j),window.removeEventListener("resize",Q)}}}unmount(r){r.remove()}};var Pe=class{constructor(r,o){this.bootstrapService=r;this.widgetMounter=o;Re(this,"state",{container:null,iframe:null,options:null,currentToken:null});Re(this,"pendingRequests",new Map);Re(this,"handleIframeMessage",async r=>{if(!(this.state.iframe&&r.source!==this.state.iframe.contentWindow)){if(r.data?.type==="NEED_TOKEN"&&this.state.options?.onTokenRequired)try{let o=await this.state.options.onTokenRequired();this.state.currentToken=o,this.state.iframe?.contentWindow?.postMessage({type:"FRUGA_TOKEN_UPDATE",token:o},"*")}catch(o){console.error("FrugaLoader: Failed to refresh token:",o)}if(r.data?.type==="FRUGA_BALANCE_RESPONSE"){let{requestId:o,available:a,pending:c}=r.data;if(o&&this.pendingRequests.has(o)){let{resolve:l,timeout:m}=this.pendingRequests.get(o);clearTimeout(m),this.pendingRequests.delete(o),l({available:a,pending:c})}}}})}async init(r){if(this.state.options=r,r.autoMount!==!1){if(r.token&&(this.state.currentToken=r.token),r.onTokenRequired)try{this.state.currentToken=await r.onTokenRequired()}catch(a){console.error("FrugaLoader: Failed to fetch initial token:",a)}await this.mount()}}setOptions(r){this.state.options=r}async mount(){if(!this.state.options||this.state.container&&this.state.iframe&&document.body.contains(this.state.container))return;let r=K.get(ye.BOOTSTRAP_DATA);if(r)this.doMount(r);else{let o=K.get(ye.BOOTSTRAP_CONFIG);if(o){let a={partnerEnvId:"cached",partnerId:"cached",partnerType:"EXTERNAL_TENANT",partnerPayout:"USER",auth:{mode:"none",audience:"",issuer:"",tokenTtlSeconds:0},config:o};this.doMount(a)}}try{let o=await this.bootstrapService.bootstrap(this.state.options.partnerKey,this.state.options.baseUrl);K.set(ye.BOOTSTRAP_DATA,o),K.set(ye.BOOTSTRAP_CONFIG,o.config),this.doMount(o)}catch{}}doMount(r){if(!this.state.options)return;let{containerId:o="fruga-widget-root"}=this.state.options,a=document.getElementById(o);a?a.innerHTML="":(a=document.createElement("div"),a.id=o,document.body.appendChild(a)),a.style.position="fixed",a.style.bottom="0px",a.style.right="0px",a.style.zIndex="9999";let l={...{...this.state.options,containerId:this.state.options.containerId||"fruga-widget-root",bootstrapConfig:r,token:this.state.currentToken||void 0},partnerId:r.partnerId,partnerType:r.partnerType},{iframe:m,cleanup:k}=this.widgetMounter.mount(a,l,this.state.options);this.state.container=a,this.state.iframe=m,a._frugaCleanup=k,window.addEventListener("message",this.handleIframeMessage)}unmount(){if(this.state.container&&document.body.contains(this.state.container)){let r=this.state.container._frugaCleanup;r?.(),this.widgetMounter.unmount(this.state.container)}this.state.container=null,this.state.iframe=null,window.removeEventListener("message",this.handleIframeMessage)}requestBalance(){this.state.iframe&&this.state.iframe.contentWindow?.postMessage({type:"FRUGA_GET_BALANCE"},"*")}async getBalance(){if(!this.state.iframe)throw new Error("FrugaLoader: Cannot get balance - widget not mounted");let r=Math.random().toString(36).substring(2,15);return new Promise((o,a)=>{let c=setTimeout(()=>{this.pendingRequests.has(r)&&(this.pendingRequests.delete(r),a(new Error("FrugaLoader: Get balance request timed out")))},5e3);this.pendingRequests.set(r,{resolve:o,reject:a,timeout:c}),this.state.iframe?.contentWindow?.postMessage({type:"FRUGA_GET_BALANCE",requestId:r},"*")})}};var wr=new xe,Tr=new Ce,ie=new Pe(wr,Tr),It=async()=>{await ie.mount()},Mt=()=>{ie.unmount()},Ke=async t=>{await ie.init(t)},Lt=t=>{ie.setOptions(t)},Nt=()=>{ie.requestBalance()},Ft=async()=>ie.getBalance();if(typeof window<"u"){let t=document.currentScript;if(t){let r=t.getAttribute("data-partner-key"),o=t.getAttribute("data-container-id")||void 0,a=t.getAttribute("data-app-url")||void 0,c=t.getAttribute("data-base-url")||void 0,l=window.frugaConfig||{};(r||l.partnerKey)&&Ke({partnerKey:r||l.partnerKey||"demo-key",containerId:o||l.containerId,appUrl:a||l.appUrl,baseUrl:c||l.baseUrl,theme:l.theme,primaryColor:l.primaryColor})}window.FrugaLoader={init:Ke,setOptions:Lt,mount:It,unmount:Mt,requestBalance:Nt,getBalance:Ft}}return Qt(_r);})();
|
|
1
|
+
"use strict";var FrugaLoader=(()=>{var qe=Object.create;var x=Object.defineProperty;var je=Object.getOwnPropertyDescriptor;var Ge=Object.getOwnPropertyNames;var $e=Object.getPrototypeOf,Ve=Object.prototype.hasOwnProperty;var ze=(t,e,r)=>e in t?x(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r;var S=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Ye=(t,e)=>{for(var r in e)x(t,r,{get:e[r],enumerable:!0})},oe=(t,e,r,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of Ge(e))!Ve.call(t,n)&&n!==r&&x(t,n,{get:()=>e[n],enumerable:!(o=je(e,n))||o.enumerable});return t};var g=(t,e,r)=>(r=t!=null?qe($e(t)):{},oe(e||!t||!t.__esModule?x(r,"default",{value:t,enumerable:!0}):r,t)),Ke=t=>oe(x({},"__esModule",{value:!0}),t);var u=(t,e,r)=>ze(t,typeof e!="symbol"?e+"":e,r);var he=S(a=>{"use strict";var H=Symbol.for("react.transitional.element"),ot=Symbol.for("react.portal"),nt=Symbol.for("react.fragment"),st=Symbol.for("react.strict_mode"),it=Symbol.for("react.profiler"),at=Symbol.for("react.consumer"),ut=Symbol.for("react.context"),ct=Symbol.for("react.forward_ref"),dt=Symbol.for("react.suspense"),pt=Symbol.for("react.memo"),de=Symbol.for("react.lazy"),lt=Symbol.for("react.activity"),ie=Symbol.iterator;function gt(t){return t===null||typeof t!="object"?null:(t=ie&&t[ie]||t["@@iterator"],typeof t=="function"?t:null)}var pe={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},le=Object.assign,ge={};function b(t,e,r){this.props=t,this.context=e,this.refs=ge,this.updater=r||pe}b.prototype.isReactComponent={};b.prototype.setState=function(t,e){if(typeof t!="object"&&typeof t!="function"&&t!=null)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,t,e,"setState")};b.prototype.forceUpdate=function(t){this.updater.enqueueForceUpdate(this,t,"forceUpdate")};function fe(){}fe.prototype=b.prototype;function q(t,e,r){this.props=t,this.context=e,this.refs=ge,this.updater=r||pe}var j=q.prototype=new fe;j.constructor=q;le(j,b.prototype);j.isPureReactComponent=!0;var ae=Array.isArray;function W(){}var c={H:null,A:null,T:null,S:null},me=Object.prototype.hasOwnProperty;function G(t,e,r){var o=r.ref;return{$$typeof:H,type:t,key:e,ref:o!==void 0?o:null,props:r}}function ft(t,e){return G(t.type,e,t.props)}function $(t){return typeof t=="object"&&t!==null&&t.$$typeof===H}function mt(t){var e={"=":"=0",":":"=2"};return"$"+t.replace(/[=:]/g,function(r){return e[r]})}var ue=/\/+/g;function D(t,e){return typeof t=="object"&&t!==null&&t.key!=null?mt(""+t.key):e.toString(36)}function ht(t){switch(t.status){case"fulfilled":return t.value;case"rejected":throw t.reason;default:switch(typeof t.status=="string"?t.then(W,W):(t.status="pending",t.then(function(e){t.status==="pending"&&(t.status="fulfilled",t.value=e)},function(e){t.status==="pending"&&(t.status="rejected",t.reason=e)})),t.status){case"fulfilled":return t.value;case"rejected":throw t.reason}}throw t}function _(t,e,r,o,n){var s=typeof t;(s==="undefined"||s==="boolean")&&(t=null);var i=!1;if(t===null)i=!0;else switch(s){case"bigint":case"string":case"number":i=!0;break;case"object":switch(t.$$typeof){case H:case ot:i=!0;break;case de:return i=t._init,_(i(t._payload),e,r,o,n)}}if(i)return n=n(t),i=o===""?"."+D(t,0):o,ae(n)?(r="",i!=null&&(r=i.replace(ue,"$&/")+"/"),_(n,e,r,"",function(l){return l})):n!=null&&($(n)&&(n=ft(n,r+(n.key==null||t&&t.key===n.key?"":(""+n.key).replace(ue,"$&/")+"/")+i)),e.push(n)),1;i=0;var d=o===""?".":o+":";if(ae(t))for(var p=0;p<t.length;p++)o=t[p],s=d+D(o,p),i+=_(o,e,r,s,n);else if(p=gt(t),typeof p=="function")for(t=p.call(t),p=0;!(o=t.next()).done;)o=o.value,s=d+D(o,p++),i+=_(o,e,r,s,n);else if(s==="object"){if(typeof t.then=="function")return _(ht(t),e,r,o,n);throw e=String(t),Error("Objects are not valid as a React child (found: "+(e==="[object Object]"?"object with keys {"+Object.keys(t).join(", ")+"}":e)+"). If you meant to render a collection of children, use an array instead.")}return i}function A(t,e,r){if(t==null)return t;var o=[],n=0;return _(t,o,"","",function(s){return e.call(r,s,n++)}),o}function yt(t){if(t._status===-1){var e=t._result;e=e(),e.then(function(r){(t._status===0||t._status===-1)&&(t._status=1,t._result=r)},function(r){(t._status===0||t._status===-1)&&(t._status=2,t._result=r)}),t._status===-1&&(t._status=0,t._result=e)}if(t._status===1)return t._result.default;throw t._result}var ce=typeof reportError=="function"?reportError:function(t){if(typeof window=="object"&&typeof window.ErrorEvent=="function"){var e=new window.ErrorEvent("error",{bubbles:!0,cancelable:!0,message:typeof t=="object"&&t!==null&&typeof t.message=="string"?String(t.message):String(t),error:t});if(!window.dispatchEvent(e))return}else if(typeof process=="object"&&typeof process.emit=="function"){process.emit("uncaughtException",t);return}console.error(t)},Tt={map:A,forEach:function(t,e,r){A(t,function(){e.apply(this,arguments)},r)},count:function(t){var e=0;return A(t,function(){e++}),e},toArray:function(t){return A(t,function(e){return e})||[]},only:function(t){if(!$(t))throw Error("React.Children.only expected to receive a single React element child.");return t}};a.Activity=lt;a.Children=Tt;a.Component=b;a.Fragment=nt;a.Profiler=it;a.PureComponent=q;a.StrictMode=st;a.Suspense=dt;a.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=c;a.__COMPILER_RUNTIME={__proto__:null,c:function(t){return c.H.useMemoCache(t)}};a.cache=function(t){return function(){return t.apply(null,arguments)}};a.cacheSignal=function(){return null};a.cloneElement=function(t,e,r){if(t==null)throw Error("The argument must be a React element, but you passed "+t+".");var o=le({},t.props),n=t.key;if(e!=null)for(s in e.key!==void 0&&(n=""+e.key),e)!me.call(e,s)||s==="key"||s==="__self"||s==="__source"||s==="ref"&&e.ref===void 0||(o[s]=e[s]);var s=arguments.length-2;if(s===1)o.children=r;else if(1<s){for(var i=Array(s),d=0;d<s;d++)i[d]=arguments[d+2];o.children=i}return G(t.type,n,o)};a.createContext=function(t){return t={$$typeof:ut,_currentValue:t,_currentValue2:t,_threadCount:0,Provider:null,Consumer:null},t.Provider=t,t.Consumer={$$typeof:at,_context:t},t};a.createElement=function(t,e,r){var o,n={},s=null;if(e!=null)for(o in e.key!==void 0&&(s=""+e.key),e)me.call(e,o)&&o!=="key"&&o!=="__self"&&o!=="__source"&&(n[o]=e[o]);var i=arguments.length-2;if(i===1)n.children=r;else if(1<i){for(var d=Array(i),p=0;p<i;p++)d[p]=arguments[p+2];n.children=d}if(t&&t.defaultProps)for(o in i=t.defaultProps,i)n[o]===void 0&&(n[o]=i[o]);return G(t,s,n)};a.createRef=function(){return{current:null}};a.forwardRef=function(t){return{$$typeof:ct,render:t}};a.isValidElement=$;a.lazy=function(t){return{$$typeof:de,_payload:{_status:-1,_result:t},_init:yt}};a.memo=function(t,e){return{$$typeof:pt,type:t,compare:e===void 0?null:e}};a.startTransition=function(t){var e=c.T,r={};c.T=r;try{var o=t(),n=c.S;n!==null&&n(r,o),typeof o=="object"&&o!==null&&typeof o.then=="function"&&o.then(W,ce)}catch(s){ce(s)}finally{e!==null&&r.types!==null&&(e.types=r.types),c.T=e}};a.unstable_useCacheRefresh=function(){return c.H.useCacheRefresh()};a.use=function(t){return c.H.use(t)};a.useActionState=function(t,e,r){return c.H.useActionState(t,e,r)};a.useCallback=function(t,e){return c.H.useCallback(t,e)};a.useContext=function(t){return c.H.useContext(t)};a.useDebugValue=function(){};a.useDeferredValue=function(t,e){return c.H.useDeferredValue(t,e)};a.useEffect=function(t,e){return c.H.useEffect(t,e)};a.useEffectEvent=function(t){return c.H.useEffectEvent(t)};a.useId=function(){return c.H.useId()};a.useImperativeHandle=function(t,e,r){return c.H.useImperativeHandle(t,e,r)};a.useInsertionEffect=function(t,e){return c.H.useInsertionEffect(t,e)};a.useLayoutEffect=function(t,e){return c.H.useLayoutEffect(t,e)};a.useMemo=function(t,e){return c.H.useMemo(t,e)};a.useOptimistic=function(t,e){return c.H.useOptimistic(t,e)};a.useReducer=function(t,e,r){return c.H.useReducer(t,e,r)};a.useRef=function(t){return c.H.useRef(t)};a.useState=function(t){return c.H.useState(t)};a.useSyncExternalStore=function(t,e,r){return c.H.useSyncExternalStore(t,e,r)};a.useTransition=function(){return c.H.useTransition()};a.version="19.2.4"});var v=S((hr,ye)=>{"use strict";ye.exports=he()});var Ee=S(I=>{"use strict";var Et=Symbol.for("react.transitional.element"),vt=Symbol.for("react.fragment");function Te(t,e,r){var o=null;if(r!==void 0&&(o=""+r),e.key!==void 0&&(o=""+e.key),"key"in e){r={};for(var n in e)n!=="key"&&(r[n]=e[n])}else r=e;return e=r.ref,{$$typeof:Et,type:t,key:o,ref:e!==void 0?e:null,props:r}}I.Fragment=vt;I.jsx=Te;I.jsxs=Te});var y=S((Tr,ve)=>{"use strict";ve.exports=Ee()});var kt={};Ye(kt,{FrugaLoadError:()=>h,getBalance:()=>re,init:()=>X,mount:()=>We,requestBalance:()=>te,retry:()=>ee,setOptions:()=>He,unmount:()=>J});var Qe=["loader.global.js","native.global.js"],Ze=()=>{if(typeof document>"u")return null;let e=document.currentScript?.src;if(!e)return null;try{let r=new URL(e,document.baseURI),o=r.pathname.split("/").pop()??"";return Qe.includes(o)?r.toString():null}catch{return null}},B=Ze();var Xe=["NEED_TOKEN","FRUGA_TOKEN_UPDATE","FRUGA_GET_BALANCE","FRUGA_BALANCE_RESPONSE","FRUGA_RESIZE","FRUGA_HOST_RESIZE","FRUGA_READY","FRUGA_INIT"],Je=t=>typeof t=="string"&&Xe.includes(t),et=["ttl","unauthorized"],ne=t=>{if(typeof t!="object"||t===null)return!1;let e=t;if(!Je(e.type)||e.version!==void 0&&typeof e.version!="string")return!1;if(e.type==="NEED_TOKEN"){let{reason:r}=t;return typeof r=="string"&&et.includes(r)}return!0},N=t=>Number.parseInt(t.split(".")[0]??"",10);var se=t=>t==="PARTNER"||t==="USER"?t:null;var rt="*",M=class{constructor(e){u(this,"target");u(this,"acceptSource");u(this,"listenOn");u(this,"handlers",new Set);u(this,"pinOriginFrom");u(this,"targetOrigin");u(this,"acceptOrigin");u(this,"pinned",null);u(this,"disposed",!1);u(this,"onMessage",e=>{if(this.disposed||this.acceptSource&&e.source!==this.acceptSource||this.acceptOrigin&&e.origin!==this.acceptOrigin||!ne(e.data)||!this.admitWhileUnpinned(e.data.type,e.origin))return;let r=typeof e.data.version=="string"&&e.data.version.length>0?e.data:{...e.data,version:"1.0"};for(let o of[...this.handlers])o(r)});let r=e.listenOn??(typeof window<"u"?window:void 0);if(!r)throw new Error("PostMessageTransport: no window to listen on; pass options.listenOn");this.target=e.target,this.targetOrigin=e.targetOrigin,this.acceptSource=e.acceptSource,this.acceptOrigin=e.acceptOrigin,this.pinOriginFrom=e.pinOriginFrom,this.listenOn=r,this.listenOn.addEventListener("message",this.onMessage)}get pinnedOrigin(){return this.pinned}pinOrigin(e){this.targetOrigin=e,this.acceptOrigin=e,this.pinned=e}send(e){if(this.disposed)return;let r=typeof e.version=="string"&&e.version.length>0?e:{...e,version:"1.0"};this.target.postMessage(r,this.targetOrigin)}subscribe(e){if(this.disposed)throw new Error("PostMessageTransport: cannot subscribe after dispose()");return this.handlers.add(e),()=>{this.handlers.delete(e)}}dispose(){this.disposed||(this.disposed=!0,this.handlers.clear(),this.listenOn.removeEventListener("message",this.onMessage))}admitWhileUnpinned(e,r){return!this.pinOriginFrom||this.pinned!==null?!0:e!==this.pinOriginFrom?!1:r&&r!=="null"?(this.pinOrigin(r),!0):(this.pinned=rt,!0)}};var Y=g(v());var wt=g(y());var Fe=g(v());var we=t=>{let e,r=new Set,o=(l,T)=>{let m=typeof l=="function"?l(e):l;if(!Object.is(m,e)){let R=e;e=T??(typeof m!="object"||m===null)?m:Object.assign({},e,m),r.forEach(E=>E(e,R))}},n=()=>e,d={setState:o,getState:n,getInitialState:()=>p,subscribe:l=>(r.add(l),()=>r.delete(l))},p=e=t(o,n,d);return d},Re=(t=>t?we(t):we);var O=g(v(),1);var Rt=t=>t;function _t(t,e=Rt){let r=O.default.useSyncExternalStore(t.subscribe,O.default.useCallback(()=>e(t.getState()),[t,e]),O.default.useCallback(()=>e(t.getInitialState()),[t,e]));return O.default.useDebugValue(r),r}var _e=t=>{let e=Re(t),r=o=>_t(e,o);return Object.assign(r,e),r},be=(t=>t?_e(t):_e);var V=be(t=>({isOpen:!1,isFocused:!0,isIdle:!1,available:0,pending:0,mode:"light",token:null,tokenEpoch:0,authStatus:"pending",partnerPayout:null,isAddingPayoutFromAlert:!1,showPayoutSuccess:!1,toggle:()=>t(e=>({isOpen:!e.isOpen})),setOpen:e=>t({isOpen:e}),setFocused:e=>t({isFocused:e}),setIdle:e=>t({isIdle:e}),setBalances:(e,r)=>t({available:e,pending:r}),setMode:e=>t({mode:e}),setToken:e=>t(r=>({token:e,tokenEpoch:r.token===e?r.tokenEpoch:r.tokenEpoch+1,authStatus:e?"authenticated":"pending"})),setPartnerPayout:e=>t({partnerPayout:se(e)}),setIsAddingPayoutFromAlert:e=>t({isAddingPayoutFromAlert:e}),setShowPayoutSuccess:e=>t({showPayoutSuccess:e})}));var z=g(v());var xe=g(v()),Ft=g(y()),bt=(0,xe.createContext)(null);var K=g(y());var Me=g(y());var Oe=g(v());var Se="fruga_bootstrap",Ae=(t,e)=>`fruga:${t}:${e}`,F=class{static set(e,r){if(!(typeof window>"u"))try{window.localStorage.setItem(e,JSON.stringify(r))}catch(o){console.warn(`[FrugaStorage] Failed to save key "${e}":`,o)}}static get(e){if(typeof window>"u")return null;try{let r=window.localStorage.getItem(e);return r?JSON.parse(r):null}catch(r){return console.warn(`[FrugaStorage] Failed to load key "${e}":`,r),null}}static remove(e){if(!(typeof window>"u"))try{window.localStorage.removeItem(e)}catch(r){console.warn(`[FrugaStorage] Failed to remove key "${e}":`,r)}}};var xt="https://api.fruga.co.uk",Ie=t=>t||xt;var Le="1.3.0";var L=class{async bootstrap(e,r){let o=Ie(r),n=`${o}/widget/bootstrap?partnerKey=${encodeURIComponent(e)}`,s;try{s=await fetch(n,{method:"GET",headers:{Accept:"application/json"}})}catch(i){throw new Error(`FrugaLoader: bootstrap request to ${o} failed`,{cause:i})}if(!s.ok)throw new Error(`FrugaLoader: bootstrap request to ${o} failed with status ${s.status}`);try{return await s.json()}catch(i){throw new Error(`FrugaLoader: bootstrap response from ${o} was not valid JSON`,{cause:i})}}};var Pe="*",ke=`https://cdn.fruga.co.uk/v/${Le}/`,P=class{mount(e,r,o,n){let s=document.createElement("iframe"),i=this.resolveWidgetUrl(r,o,n),d=this.originOf(i);s.src=i,s.style.border="none",s.style.width="410px",s.style.height="600px",s.style.backgroundColor="transparent",e.appendChild(s);let p=s.contentWindow;if(!p)throw new Error("FrugaLoader: iframe has no contentWindow after being appended");let l=new M({target:p,targetOrigin:d,acceptSource:p,...d===Pe?{}:{acceptOrigin:d}}),T=!1,m=l.subscribe(E=>{if(E.type==="FRUGA_READY"){T=!0;return}E.type==="FRUGA_RESIZE"&&this.applySize(s,E.width,E.height,E.isFullscreen)}),R=()=>{T&&l.send({type:"FRUGA_HOST_RESIZE",version:"1.0",isHostMobile:window.innerWidth<768,hostHeight:window.innerHeight,hostWidth:window.innerWidth})};return window.addEventListener("resize",R),{iframe:s,transport:l,widgetOrigin:d,cleanup:()=>{window.removeEventListener("resize",R),m(),l.dispose()}}}unmount(e){e.remove()}originOf(e){let r;try{r=new URL(e).origin}catch{r="null"}return r&&r!=="null"?r:(console.warn(`FrugaLoader: widget URL has an opaque origin (${e}); falling back to postMessage targetOrigin '*'`),Pe)}applySize(e,r,o,n){if(n){e.style.position="fixed",e.style.inset="0",e.style.width="100vw",e.style.height="100vh",e.style.zIndex="99999";return}e.style.position="static",e.style.inset="",e.style.width=`${r}px`,e.style.height=`${o}px`,e.style.zIndex="auto"}resolveWidgetUrl(e,r,o){let n=B??(typeof window<"u"?window.location.href:ke),s=e.appUrl||o||(B?`./${r}/index.html`:`${ke}${r}/index.html`),i=new URL(s,n);return i.searchParams.set("partnerKey",e.partnerKey),i.toString()}};var Ce=1e4,Q=t=>t==="EXTERNAL_TENANT"?"relay":"connect";var Be="1.3.0";var Ne=Be;var h=class extends Error{constructor(r,o,n={}){super(o);u(this,"code");u(this,"loaderVersion");u(this,"widgetVersion");u(this,"protocolVersion");this.name="FrugaLoadError",this.code=r,this.loaderVersion=n.loaderVersion??Ne,this.widgetVersion=n.widgetVersion,this.protocolVersion=n.protocolVersion}};var Ue="fruga-widget-root",Z=5e3,Ot="Fruga widget failed to load.",De="data-fruga-owned",St=1440*60*1e3,At={get:t=>F.get(t),set:(t,e)=>F.set(t,e),remove:t=>F.remove(t)},C=class{constructor(e,r,o={}){this.bootstrapService=e;this.widgetMounter=r;this.env=o;u(this,"options",null);u(this,"currentToken",null);u(this,"session",null);u(this,"mountGeneration",0);u(this,"inFlightBootstrap",null);u(this,"pendingRequests",new Map);u(this,"loadFailed",!1);u(this,"errorElement",null);u(this,"initialTokenRequested",!1)}async init(e){this.options&&this.options.partnerKey!==e.partnerKey&&(this.currentToken=null,this.initialTokenRequested=!1),this.options=e,e.token&&(this.currentToken=e.token),this.emit("lifecycle","init",{partnerKey:e.partnerKey,autoMount:e.autoMount!==!1}),e.autoMount!==!1&&await this.mount()}setOptions(e){this.options=e,e.token&&e.token!==this.currentToken&&this.setToken(e.token)}async mount(){let e=this.options;if(!e){this.report("error","not_initialised","FrugaLoader: Cannot mount - init() must be called first");return}if(!this.initialTokenRequested&&e.onTokenRequired&&(this.initialTokenRequested=!0,await this.requestToken(e.onTokenRequired,"initial")),this.session&&this.session.container.isConnected)return;let r=++this.mountGeneration;this.loadFailed=!1,this.storage.remove(Se);let o=Ae(e.partnerKey,"bootstrap"),n=this.readFreshCache(o);n&&this.startSession(n);try{let s=await this.fetchBootstrap(e.partnerKey,e.baseUrl);if(r!==this.mountGeneration)return;this.storage.set(o,{fetchedAt:Date.now(),bootstrap:s}),this.applyBootstrap(s)}catch(s){if(r!==this.mountGeneration)return;if(n&&this.session){this.report("warn","bootstrap_refresh_failed","FrugaLoader: bootstrap refresh failed, keeping cached config:",s);return}this.failMount(new h("BOOTSTRAP_FAILED",`FrugaLoader: failed to load partner configuration: ${s instanceof Error?s.message:String(s)}`))}}readFreshCache(e){let r=this.storage.get(e);return!r||typeof r.fetchedAt!="number"||!r.bootstrap?null:Date.now()-r.fetchedAt>=St?(this.storage.remove(e),null):r.bootstrap}fetchBootstrap(e,r){let o=`${e}::${r??""}`,n=this.inFlightBootstrap;if(n&&n.key===o)return n.promise;let s=this.bootstrapService.bootstrap(e,r),i=()=>{this.inFlightBootstrap?.promise===s&&(this.inFlightBootstrap=null)};return s.then(i,i),this.inFlightBootstrap={key:o,promise:s},s}unmount(){this.mountGeneration+=1;let e=this.session;this.session=null,e&&(this.disposeSession(e),e.ownsContainer&&this.widgetMounter.unmount(e.container),this.emit("lifecycle","unmount",{widgetType:e.widgetType})),this.clearErrorElement(),this.rejectPendingRequests(new Error("FrugaLoader: widget unmounted")),this.initialTokenRequested=!1,this.currentToken=this.options?.token??null}async retry(){this.clearErrorElement(),await this.mount()}requestBalance(){let e=this.session;if(!e){this.report("warn","balance_not_mounted","FrugaLoader: Cannot request balance - widget not mounted");return}let r=this.options?.onBalance;if(!r){this.report("warn","balance_no_callback","FrugaLoader: requestBalance() needs an onBalance option; use getBalance() instead");return}let o=this.nextRequestId(),n=setTimeout(()=>{this.pendingRequests.delete(o)&&this.report("warn","balance_timeout",this.balanceTimeoutMessage(e))},Z);this.pendingRequests.set(o,{resolve:s=>r(s),reject:()=>{},timeout:n}),this.sendBalanceRequest(e,o)}async getBalance(){let e=this.session;if(!e)throw new h("NOT_READY","FrugaLoader: Cannot get balance - widget not mounted");let r=this.nextRequestId();return new Promise((o,n)=>{let s=setTimeout(()=>{this.pendingRequests.delete(r)&&n(e.ready?new Error(this.balanceTimeoutMessage(e)):new h("NOT_READY",this.balanceTimeoutMessage(e)))},Z);this.pendingRequests.set(r,{resolve:o,reject:n,timeout:s}),this.sendBalanceRequest(e,r)})}sendBalanceRequest(e,r){if(!e.ready){e.queuedBalanceRequests.push(r);return}this.send(e,{type:"FRUGA_GET_BALANCE",version:"1.0",requestId:r})}flushBalanceRequests(e){for(let r of e.queuedBalanceRequests.splice(0))this.pendingRequests.has(r)&&this.sendBalanceRequest(e,r)}balanceTimeoutMessage(e){return e.ready?"FrugaLoader: Get balance request timed out":`FrugaLoader: widget did not report FRUGA_READY within ${Z}ms; balance request was never sent`}applyBootstrap(e){let r=this.session,o=Q(e.partnerType);if(!r||r.widgetType!==o){this.startSession(e);return}r.bootstrap=e,r.ready&&this.sendInit(r)}startSession(e){let r=this.options,o=this.documentRef;if(!r||!o||this.loadFailed)return;this.clearErrorElement();let n=this.session;this.session=null,n&&this.disposeSession(n);let{container:s,owned:i}=this.ensureContainer(o,r.containerId||Ue),d=Q(e.partnerType),{iframe:p,transport:l,cleanup:T}=this.widgetMounter.mount(s,r,d,e.widgetUrl),m={container:s,iframe:p,transport:l,cleanup:T,bootstrap:e,widgetType:d,ready:!1,ownsContainer:i,queuedBalanceRequests:[],loadTimer:null,unsubscribe:()=>{}};m.unsubscribe=l.subscribe(R=>{this.handleMessage(m,R)}),this.session=m,this.startLoadTimer(m,r),this.emit("lifecycle","mount",{widgetType:d})}disposeSession(e){this.clearLoadTimer(e),e.unsubscribe(),e.cleanup(),e.iframe.remove()}ensureContainer(e,r){let o=e.getElementById(r);if(o)return o.innerHTML="",{container:o,owned:o.hasAttribute(De)};let n=e.createElement("div");return n.id=r,n.setAttribute(De,""),n.style.position="fixed",n.style.bottom="0px",n.style.right="0px",n.style.zIndex="9999",e.body.appendChild(n),{container:n,owned:!0}}async handleMessage(e,r){if(this.session===e)switch(this.emit("protocol",r.type,{direction:"in"}),r.type){case"FRUGA_READY":{if(N(r.protocolVersion)!==N("1.0")){this.report("error","protocol_mismatch","FrugaLoader: protocol mismatch",{loader:"1.0",widget:r.protocolVersion}),this.failSession(e,new h("VERSION_MISMATCH",`FrugaLoader: widget protocol ${r.protocolVersion} is incompatible with loader protocol ${"1.0"}`,{widgetVersion:r.widgetVersion,protocolVersion:r.protocolVersion}));return}this.clearLoadTimer(e),this.clearErrorElement(),e.ready=!0,this.emit("lifecycle","ready",{widgetVersion:r.widgetVersion,protocolVersion:r.protocolVersion}),this.sendInit(e),this.flushBalanceRequests(e);return}case"NEED_TOKEN":{await this.refreshToken();return}case"FRUGA_BALANCE_RESPONSE":{this.resolveBalance(r.requestId,r.available,r.pending);return}default:return}}sendInit(e){let r=this.windowRef,o=r?.innerWidth??0,n=r?.innerHeight??0,s=this.buildOverrides();this.send(e,{type:"FRUGA_INIT",version:"1.0",protocolVersion:"1.0",token:this.currentToken??void 0,bootstrap:e.bootstrap,apiBaseUrl:this.options?.baseUrl,host:{origin:r?.location.origin??"",width:o,height:n,isMobile:o<768},...s?{overrides:s}:{}})}buildOverrides(){let e=this.options;if(!e)return;let r={...e.theme?{theme:e.theme}:{},...e.primaryColor?{primaryColor:e.primaryColor}:{},...e.userId?{userId:e.userId}:{},...e.panelOpen?{panelOpen:!0}:{}};return Object.keys(r).length>0?r:void 0}async refreshToken(){let e=this.options?.onTokenRequired;e&&await this.requestToken(e,"ttl")}async requestToken(e,r){this.emit("lifecycle","token_requested",{reason:r});try{this.setToken(await e())}catch(o){this.report("error","token_failed",`FrugaLoader: Failed to fetch ${r} token:`,o)}}setToken(e){this.currentToken=e,this.emit("lifecycle","token_updated",{});let r=this.session;r&&r.ready&&this.send(r,{type:"FRUGA_TOKEN_UPDATE",version:"1.0",token:e})}resolveBalance(e,r,o){if(!e){this.report("warn","balance_response_without_id","FrugaLoader: FRUGA_BALANCE_RESPONSE without requestId ignored");return}let n=this.pendingRequests.get(e);n&&(clearTimeout(n.timeout),this.pendingRequests.delete(e),n.resolve({available:r,pending:o}))}rejectPendingRequests(e){for(let[r,o]of this.pendingRequests)clearTimeout(o.timeout),this.pendingRequests.delete(r),o.reject(e)}nextRequestId(){return Math.random().toString(36).substring(2,15)}startLoadTimer(e,r){let o=r.loadTimeoutMs??Ce;o<=0||(e.loadTimer=this.setTimer(()=>{e.loadTimer=null,this.failSession(e,new h("TIMEOUT",`FrugaLoader: widget did not report FRUGA_READY within ${o}ms`))},o))}clearLoadTimer(e){e.loadTimer!==null&&(this.clearTimer(e.loadTimer),e.loadTimer=null)}failSession(e,r){this.session===e&&(this.session=null,this.loadFailed=!0,this.disposeSession(e),this.renderErrorElement(e.container),this.rejectPendingRequests(r),this.notifyError(r))}failMount(e){this.loadFailed=!0;let r=this.session;r&&(this.session=null,this.disposeSession(r));let o=this.documentRef,n=this.options?.containerId||Ue;o&&this.renderErrorElement(this.ensureContainer(o,n).container),this.rejectPendingRequests(e),this.notifyError(e)}notifyError(e){this.emit("error",e.code,{message:e.message});let r=this.options?.onError;if(r)try{r(e)}catch(o){console.error("FrugaLoader: onError callback threw:",o)}}renderErrorElement(e){let r=this.documentRef;if(!r)return;this.clearErrorElement();let o=r.createElement("div");o.setAttribute("role","alert"),o.setAttribute("data-fruga-error",""),o.style.padding="12px",o.textContent=Ot,e.appendChild(o),this.errorElement=o}clearErrorElement(){this.errorElement?.remove(),this.errorElement=null}send(e,r){this.emit("protocol",r.type,{direction:"out"}),e.transport.send(r)}emit(e,r,o,n=e==="error"?"error":"info"){let s=this.options?.onEvent;if(s)try{s({type:e,level:n,name:r,data:o,ts:Date.now()})}catch(i){console.error("FrugaLoader: onEvent callback threw:",i)}}report(e,r,o,n){if(this.options?.onEvent){this.emit("log",r,n===void 0?{message:o}:{message:o,data:n},e);return}let s=e==="error"?console.error:console.warn;if(n===void 0){s(o);return}s(o,n)}setTimer(e,r){let o=this.windowRef;return o?o.setTimeout(e,r):setTimeout(e,r)}clearTimer(e){let r=this.windowRef;if(r){r.clearTimeout(e);return}clearTimeout(e)}get windowRef(){return this.env.windowRef??(typeof window<"u"?window:void 0)}get documentRef(){return this.env.documentRef??(typeof document<"u"?document:void 0)}get storage(){return this.env.storage??At}};var It=new L,Lt=new P,w=new C(It,Lt);var We=async()=>{await w.mount()},J=()=>{w.unmount()},ee=async()=>{await w.retry()},X=async t=>(await w.init(t),Pt),He=t=>{w.setOptions(t)},te=()=>{w.requestBalance()},re=async()=>w.getBalance(),Pt={unmount:J,retry:ee,getBalance:re,requestBalance:te};if(typeof window<"u"){let t=document.currentScript;if(t){let e=t.getAttribute("data-partner-key"),r=t.getAttribute("data-container-id")||void 0,o=t.getAttribute("data-app-url")||void 0,n=t.getAttribute("data-base-url")||void 0,s=window.frugaConfig||{};(e||s.partnerKey)&&X({partnerKey:e||s.partnerKey||"demo-key",containerId:r||s.containerId,appUrl:o||s.appUrl,baseUrl:n||s.baseUrl,theme:s.theme,primaryColor:s.primaryColor})}window.FrugaLoader={init:X,setOptions:He,mount:We,unmount:J,retry:ee,requestBalance:te,getBalance:re}}return Ke(kt);})();
|
|
19
2
|
/*! Bundled license information:
|
|
20
3
|
|
|
21
|
-
react/cjs/react-jsx-runtime.production.js:
|
|
22
|
-
(**
|
|
23
|
-
* @license React
|
|
24
|
-
* react-jsx-runtime.production.js
|
|
25
|
-
*
|
|
26
|
-
* Copyright (c) Meta Platforms, Inc. and affiliates.
|
|
27
|
-
*
|
|
28
|
-
* This source code is licensed under the MIT license found in the
|
|
29
|
-
* LICENSE file in the root directory of this source tree.
|
|
30
|
-
*)
|
|
31
|
-
|
|
32
4
|
react/cjs/react.production.js:
|
|
33
5
|
(**
|
|
34
6
|
* @license React
|
|
@@ -40,21 +12,10 @@ react/cjs/react.production.js:
|
|
|
40
12
|
* LICENSE file in the root directory of this source tree.
|
|
41
13
|
*)
|
|
42
14
|
|
|
43
|
-
react/cjs/react.
|
|
44
|
-
(**
|
|
45
|
-
* @license React
|
|
46
|
-
* react.development.js
|
|
47
|
-
*
|
|
48
|
-
* Copyright (c) Meta Platforms, Inc. and affiliates.
|
|
49
|
-
*
|
|
50
|
-
* This source code is licensed under the MIT license found in the
|
|
51
|
-
* LICENSE file in the root directory of this source tree.
|
|
52
|
-
*)
|
|
53
|
-
|
|
54
|
-
react/cjs/react-jsx-runtime.development.js:
|
|
15
|
+
react/cjs/react-jsx-runtime.production.js:
|
|
55
16
|
(**
|
|
56
17
|
* @license React
|
|
57
|
-
* react-jsx-runtime.
|
|
18
|
+
* react-jsx-runtime.production.js
|
|
58
19
|
*
|
|
59
20
|
* Copyright (c) Meta Platforms, Inc. and affiliates.
|
|
60
21
|
*
|
package/dist/loader.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var Y=Object.create;var h=Object.defineProperty;var J=Object.getOwnPropertyDescriptor;var X=Object.getOwnPropertyNames;var Z=Object.getPrototypeOf,ee=Object.prototype.hasOwnProperty;var te=(r,e,t)=>e in r?h(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var re=(r,e)=>{for(var t in e)h(r,t,{get:e[t],enumerable:!0})},L=(r,e,t,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of X(e))!ee.call(r,i)&&i!==t&&h(r,i,{get:()=>e[i],enumerable:!(o=J(e,i))||o.enumerable});return r};var oe=(r,e,t)=>(t=r!=null?Y(Z(r)):{},L(e||!r||!r.__esModule?h(t,"default",{value:r,enumerable:!0}):t,r)),ne=r=>L(h({},"__esModule",{value:!0}),r);var x=(r,e,t)=>te(r,typeof e!="symbol"?e+"":e,t);var ge={};re(ge,{getBalance:()=>K,init:()=>P,mount:()=>H,requestBalance:()=>z,setOptions:()=>G,unmount:()=>$});module.exports=ne(ge);var ie=require("react/jsx-runtime");var A=require("react");var se=require("react/jsx-runtime");var U=require("react");var C=r=>{let e,t=new Set,o=(n,g)=>{let d=typeof n=="function"?n(e):n;if(!Object.is(d,e)){let T=e;e=g??(typeof d!="object"||d===null)?d:Object.assign({},e,d),t.forEach(f=>f(e,T))}},i=()=>e,u={setState:o,getState:i,getInitialState:()=>b,subscribe:n=>(t.add(n),()=>t.delete(n))},b=e=r(o,i,u);return u},M=(r=>r?C(r):C);var y=oe(require("react"),1);var ce=r=>r;function de(r,e=ce){let t=y.default.useSyncExternalStore(r.subscribe,y.default.useCallback(()=>e(r.getState()),[r,e]),y.default.useCallback(()=>e(r.getInitialState()),[r,e]));return y.default.useDebugValue(t),t}var O=r=>{let e=M(r),t=o=>de(e,o);return Object.assign(t,e),t},D=(r=>r?O(r):O);var S=D(r=>({isOpen:!1,isFocused:!0,isIdle:!1,available:0,pending:0,mode:"light",token:null,partnerPayout:null,isAddingPayoutFromAlert:!1,showPayoutSuccess:!1,toggle:()=>r(e=>({isOpen:!e.isOpen})),setOpen:e=>r({isOpen:e}),setFocused:e=>r({isFocused:e}),setIdle:e=>r({isIdle:e}),setBalances:(e,t)=>r({available:e,pending:t}),setMode:e=>r({mode:e}),setToken:e=>r({token:e}),setPartnerPayout:e=>r({partnerPayout:e}),setIsAddingPayoutFromAlert:e=>r({isAddingPayoutFromAlert:e}),setShowPayoutSuccess:e=>r({showPayoutSuccess:e})}));var F=require("react/jsx-runtime");var _=require("react/jsx-runtime");var W=require("react");var w={BOOTSTRAP_DATA:"fruga_bootstrap",BOOTSTRAP_CONFIG:"fruga_active_config"},p=class{static set(e,t){if(!(typeof window>"u"))try{window.localStorage.setItem(e,JSON.stringify(t))}catch(o){console.warn(`[FrugaStorage] Failed to save key "${e}":`,o)}}static get(e){if(typeof window>"u")return null;try{let t=window.localStorage.getItem(e);return t?JSON.parse(t):null}catch(t){return console.warn(`[FrugaStorage] Failed to load key "${e}":`,t),null}}static remove(e){typeof window>"u"||window.localStorage.removeItem(e)}static clear(){typeof window>"u"||window.localStorage.clear()}};var le=typeof process<"u"&&process.env.VITE_FRUGA_API_URL||"https://api-dev.fruga.co.uk",N=r=>r||le;var I={partnerEnvId:"env_dev_123",partnerId:"partner_abc_456",partnerType:"EXTERNAL_TENANT",partnerPayout:"USER",auth:{mode:"JWT",audience:"https://api.fruga.io",issuer:"https://auth.fruga.io",tokenTtlSeconds:70},config:{ui:{accent:"#F97316",defaultTheme:"light",launcherIcon:"arrow",showLauncher:!0,launcherLabel:"Help",accentTextDark:"#832424",accentTextLight:"#d81414",allowUserThemeControl:!0},validValues:{defaultTheme:["light","dark"],launcherIcon:["none","gift","sparkles","credit","arrow"]}}};var v=class{async bootstrap(e,t){let o=N(t);if(typeof process<"u"&&process.env.VITE_FRUGA_MODE==="test")return console.log("Fruga SDK: Using bootstrap mocks (VITE_FRUGA_MODE=test)"),I;try{let a=await fetch(`${o}/widget/bootstrap?partnerKey=${e}`,{method:"GET",headers:{Accept:"application/json","Content-Type":"application/json"}});if(!a.ok)throw new Error(`Bootstrap failed with status: ${a.status}`);return await a.json()}catch(a){return console.error("Fruga SDK: Bootstrap failed, falling back to mocks",a),I}}};var E=class{mount(e,t,o){let{partnerKey:i,theme:a,primaryColor:c,appUrl:u,userId:b}=o,n=document.createElement("iframe"),g=t.partnerType==="EXTERNAL_TENANT"?"relay":"connect",d=typeof document<"u"?document.currentScript:null,T=d?.src||(typeof window<"u"?window.location.href:""),f=`./${g}/index.html`;if(!d)f=`https://frugainsurance.github.io/sdk/${g}/index.html`;else try{new URL(T).pathname.includes("/dist/")&&(f=`./${g}/index.html`)}catch{}let s=new URL(u||t.appUrl||f,T);s.searchParams.set("partnerKey",i),s.searchParams.set("partnerId",t.partnerId);let j=typeof window<"u"?window.innerWidth<768:!1;if(s.searchParams.set("isHostMobile",String(j)),typeof window<"u"&&(s.searchParams.set("hostHeight",String(window.innerHeight)),s.searchParams.set("hostWidth",String(window.innerWidth))),a&&s.searchParams.set("theme",a),c&&s.searchParams.set("primaryColor",c),b&&s.searchParams.set("userId",b),t.token&&s.searchParams.set("token",t.token),o.baseUrl&&s.searchParams.set("baseUrl",o.baseUrl),t.bootstrapConfig)try{let l=btoa(JSON.stringify(t.bootstrapConfig));s.searchParams.set("bootstrapConfig",l)}catch(l){console.warn("FrugaLoader: Failed to encode bootstrapConfig for iframe URL",l)}n.src=s.toString(),n.style.border="none",n.style.width="410px",n.style.height="600px",n.style.backgroundColor="transparent";let k=l=>{if(l.source===n.contentWindow&&l.data?.type==="FRUGA_RESIZE"){let{width:q,height:V,isFullscreen:Q}=l.data;Q?(n.style.position="fixed",n.style.inset="0",n.style.width="100vw",n.style.height="100vh",n.style.zIndex="99999"):(n.style.position="static",n.style.width=`${q}px`,n.style.height=`${V}px`,n.style.zIndex="auto")}},B=()=>{n.contentWindow?.postMessage({type:"FRUGA_HOST_RESIZE",isHostMobile:window.innerWidth<768,hostHeight:window.innerHeight,hostWidth:window.innerWidth},"*")};return window.addEventListener("message",k),window.addEventListener("resize",B),e.appendChild(n),{iframe:n,cleanup:()=>{window.removeEventListener("message",k),window.removeEventListener("resize",B)}}}unmount(e){e.remove()}};var R=class{constructor(e,t){this.bootstrapService=e;this.widgetMounter=t;x(this,"state",{container:null,iframe:null,options:null,currentToken:null});x(this,"pendingRequests",new Map);x(this,"handleIframeMessage",async e=>{if(!(this.state.iframe&&e.source!==this.state.iframe.contentWindow)){if(e.data?.type==="NEED_TOKEN"&&this.state.options?.onTokenRequired)try{let t=await this.state.options.onTokenRequired();this.state.currentToken=t,this.state.iframe?.contentWindow?.postMessage({type:"FRUGA_TOKEN_UPDATE",token:t},"*")}catch(t){console.error("FrugaLoader: Failed to refresh token:",t)}if(e.data?.type==="FRUGA_BALANCE_RESPONSE"){let{requestId:t,available:o,pending:i}=e.data;if(t&&this.pendingRequests.has(t)){let{resolve:a,timeout:c}=this.pendingRequests.get(t);clearTimeout(c),this.pendingRequests.delete(t),a({available:o,pending:i})}}}})}async init(e){if(this.state.options=e,e.autoMount!==!1){if(e.token&&(this.state.currentToken=e.token),e.onTokenRequired)try{this.state.currentToken=await e.onTokenRequired()}catch(o){console.error("FrugaLoader: Failed to fetch initial token:",o)}await this.mount()}}setOptions(e){this.state.options=e}async mount(){if(!this.state.options||this.state.container&&this.state.iframe&&document.body.contains(this.state.container))return;let e=p.get(w.BOOTSTRAP_DATA);if(e)this.doMount(e);else{let t=p.get(w.BOOTSTRAP_CONFIG);if(t){let o={partnerEnvId:"cached",partnerId:"cached",partnerType:"EXTERNAL_TENANT",partnerPayout:"USER",auth:{mode:"none",audience:"",issuer:"",tokenTtlSeconds:0},config:t};this.doMount(o)}}try{let t=await this.bootstrapService.bootstrap(this.state.options.partnerKey,this.state.options.baseUrl);p.set(w.BOOTSTRAP_DATA,t),p.set(w.BOOTSTRAP_CONFIG,t.config),this.doMount(t)}catch{}}doMount(e){if(!this.state.options)return;let{containerId:t="fruga-widget-root"}=this.state.options,o=document.getElementById(t);o?o.innerHTML="":(o=document.createElement("div"),o.id=t,document.body.appendChild(o)),o.style.position="fixed",o.style.bottom="0px",o.style.right="0px",o.style.zIndex="9999";let a={...{...this.state.options,containerId:this.state.options.containerId||"fruga-widget-root",bootstrapConfig:e,token:this.state.currentToken||void 0},partnerId:e.partnerId,partnerType:e.partnerType},{iframe:c,cleanup:u}=this.widgetMounter.mount(o,a,this.state.options);this.state.container=o,this.state.iframe=c,o._frugaCleanup=u,window.addEventListener("message",this.handleIframeMessage)}unmount(){if(this.state.container&&document.body.contains(this.state.container)){let e=this.state.container._frugaCleanup;e?.(),this.widgetMounter.unmount(this.state.container)}this.state.container=null,this.state.iframe=null,window.removeEventListener("message",this.handleIframeMessage)}requestBalance(){this.state.iframe&&this.state.iframe.contentWindow?.postMessage({type:"FRUGA_GET_BALANCE"},"*")}async getBalance(){if(!this.state.iframe)throw new Error("FrugaLoader: Cannot get balance - widget not mounted");let e=Math.random().toString(36).substring(2,15);return new Promise((t,o)=>{let i=setTimeout(()=>{this.pendingRequests.has(e)&&(this.pendingRequests.delete(e),o(new Error("FrugaLoader: Get balance request timed out")))},5e3);this.pendingRequests.set(e,{resolve:t,reject:o,timeout:i}),this.state.iframe?.contentWindow?.postMessage({type:"FRUGA_GET_BALANCE",requestId:e},"*")})}};var pe=new v,ue=new E,m=new R(pe,ue),H=async()=>{await m.mount()},$=()=>{m.unmount()},P=async r=>{await m.init(r)},G=r=>{m.setOptions(r)},z=()=>{m.requestBalance()},K=async()=>m.getBalance();if(typeof window<"u"){let r=document.currentScript;if(r){let e=r.getAttribute("data-partner-key"),t=r.getAttribute("data-container-id")||void 0,o=r.getAttribute("data-app-url")||void 0,i=r.getAttribute("data-base-url")||void 0,a=window.frugaConfig||{};(e||a.partnerKey)&&P({partnerKey:e||a.partnerKey||"demo-key",containerId:t||a.containerId,appUrl:o||a.appUrl,baseUrl:i||a.baseUrl,theme:a.theme,primaryColor:a.primaryColor})}window.FrugaLoader={init:P,setOptions:G,mount:H,unmount:$,requestBalance:z,getBalance:K}}0&&(module.exports={getBalance,init,mount,requestBalance,setOptions,unmount});
|
|
1
|
+
"use strict";var le=Object.create;var v=Object.defineProperty;var pe=Object.getOwnPropertyDescriptor;var ce=Object.getOwnPropertyNames;var ge=Object.getPrototypeOf,me=Object.prototype.hasOwnProperty;var fe=(r,e,t)=>e in r?v(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var he=(r,e)=>{for(var t in e)v(r,t,{get:e[t],enumerable:!0})},W=(r,e,t,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of ce(e))!me.call(r,n)&&n!==t&&v(r,n,{get:()=>e[n],enumerable:!(o=pe(e,n))||o.enumerable});return r};var ye=(r,e,t)=>(t=r!=null?le(ge(r)):{},W(e||!r||!r.__esModule?v(t,"default",{value:r,enumerable:!0}):t,r)),Te=r=>W(v({},"__esModule",{value:!0}),r);var s=(r,e,t)=>fe(r,typeof e!="symbol"?e+"":e,t);var De={};he(De,{FrugaLoadError:()=>c,getBalance:()=>D,init:()=>P,mount:()=>de,requestBalance:()=>N,retry:()=>U,setOptions:()=>ue,unmount:()=>C});module.exports=Te(De);var ve=["loader.global.js","native.global.js"],Ee=()=>{if(typeof document>"u")return null;let e=document.currentScript?.src;if(!e)return null;try{let t=new URL(e,document.baseURI),o=t.pathname.split("/").pop()??"";return ve.includes(o)?t.toString():null}catch{return null}},M=Ee();var we=["NEED_TOKEN","FRUGA_TOKEN_UPDATE","FRUGA_GET_BALANCE","FRUGA_BALANCE_RESPONSE","FRUGA_RESIZE","FRUGA_HOST_RESIZE","FRUGA_READY","FRUGA_INIT"],Fe=r=>typeof r=="string"&&we.includes(r),be=["ttl","unauthorized"],q=r=>{if(typeof r!="object"||r===null)return!1;let e=r;if(!Fe(e.type)||e.version!==void 0&&typeof e.version!="string")return!1;if(e.type==="NEED_TOKEN"){let{reason:t}=r;return typeof t=="string"&&be.includes(t)}return!0},O=r=>Number.parseInt(r.split(".")[0]??"",10);var G=r=>r==="PARTNER"||r==="USER"?r:null;var Re="*",E=class{constructor(e){s(this,"target");s(this,"acceptSource");s(this,"listenOn");s(this,"handlers",new Set);s(this,"pinOriginFrom");s(this,"targetOrigin");s(this,"acceptOrigin");s(this,"pinned",null);s(this,"disposed",!1);s(this,"onMessage",e=>{if(this.disposed||this.acceptSource&&e.source!==this.acceptSource||this.acceptOrigin&&e.origin!==this.acceptOrigin||!q(e.data)||!this.admitWhileUnpinned(e.data.type,e.origin))return;let t=typeof e.data.version=="string"&&e.data.version.length>0?e.data:{...e.data,version:"1.0"};for(let o of[...this.handlers])o(t)});let t=e.listenOn??(typeof window<"u"?window:void 0);if(!t)throw new Error("PostMessageTransport: no window to listen on; pass options.listenOn");this.target=e.target,this.targetOrigin=e.targetOrigin,this.acceptSource=e.acceptSource,this.acceptOrigin=e.acceptOrigin,this.pinOriginFrom=e.pinOriginFrom,this.listenOn=t,this.listenOn.addEventListener("message",this.onMessage)}get pinnedOrigin(){return this.pinned}pinOrigin(e){this.targetOrigin=e,this.acceptOrigin=e,this.pinned=e}send(e){if(this.disposed)return;let t=typeof e.version=="string"&&e.version.length>0?e:{...e,version:"1.0"};this.target.postMessage(t,this.targetOrigin)}subscribe(e){if(this.disposed)throw new Error("PostMessageTransport: cannot subscribe after dispose()");return this.handlers.add(e),()=>{this.handlers.delete(e)}}dispose(){this.disposed||(this.disposed=!0,this.handlers.clear(),this.listenOn.removeEventListener("message",this.onMessage))}admitWhileUnpinned(e,t){return!this.pinOriginFrom||this.pinned!==null?!0:e!==this.pinOriginFrom?!1:t&&t!=="null"?(this.pinOrigin(t),!0):(this.pinned=Re,!0)}};var L=require("react");var Me=require("react/jsx-runtime");var K=require("react");var H=r=>{let e,t=new Set,o=(d,m)=>{let l=typeof d=="function"?d(e):d;if(!Object.is(l,e)){let y=e;e=m??(typeof l!="object"||l===null)?l:Object.assign({},e,l),t.forEach(f=>f(e,y))}},n=()=>e,p={setState:o,getState:n,getInitialState:()=>g,subscribe:d=>(t.add(d),()=>t.delete(d))},g=e=r(o,n,p);return p},V=(r=>r?H(r):H);var w=ye(require("react"),1);var Oe=r=>r;function Se(r,e=Oe){let t=w.default.useSyncExternalStore(r.subscribe,w.default.useCallback(()=>e(r.getState()),[r,e]),w.default.useCallback(()=>e(r.getInitialState()),[r,e]));return w.default.useDebugValue(t),t}var $=r=>{let e=V(r),t=o=>Se(e,o);return Object.assign(t,e),t},j=(r=>r?$(r):$);var I=j(r=>({isOpen:!1,isFocused:!0,isIdle:!1,available:0,pending:0,mode:"light",token:null,tokenEpoch:0,authStatus:"pending",partnerPayout:null,isAddingPayoutFromAlert:!1,showPayoutSuccess:!1,toggle:()=>r(e=>({isOpen:!e.isOpen})),setOpen:e=>r({isOpen:e}),setFocused:e=>r({isFocused:e}),setIdle:e=>r({isIdle:e}),setBalances:(e,t)=>r({available:e,pending:t}),setMode:e=>r({mode:e}),setToken:e=>r(t=>({token:e,tokenEpoch:t.token===e?t.tokenEpoch:t.tokenEpoch+1,authStatus:e?"authenticated":"pending"})),setPartnerPayout:e=>r({partnerPayout:G(e)}),setIsAddingPayoutFromAlert:e=>r({isAddingPayoutFromAlert:e}),setShowPayoutSuccess:e=>r({showPayoutSuccess:e})}));var _=require("react");var z=require("react"),_e=require("react/jsx-runtime"),Ie=(0,z.createContext)(null);var A=require("react/jsx-runtime");var Y=require("react/jsx-runtime");var Q=require("react");var Z="fruga_bootstrap",X=(r,e)=>`fruga:${r}:${e}`,T=class{static set(e,t){if(!(typeof window>"u"))try{window.localStorage.setItem(e,JSON.stringify(t))}catch(o){console.warn(`[FrugaStorage] Failed to save key "${e}":`,o)}}static get(e){if(typeof window>"u")return null;try{let t=window.localStorage.getItem(e);return t?JSON.parse(t):null}catch(t){return console.warn(`[FrugaStorage] Failed to load key "${e}":`,t),null}}static remove(e){if(!(typeof window>"u"))try{window.localStorage.removeItem(e)}catch(t){console.warn(`[FrugaStorage] Failed to remove key "${e}":`,t)}}};var Le="https://api.fruga.co.uk",J=r=>r||Le;var ee="1.3.0";var F=class{async bootstrap(e,t){let o=J(t),n=`${o}/widget/bootstrap?partnerKey=${encodeURIComponent(e)}`,i;try{i=await fetch(n,{method:"GET",headers:{Accept:"application/json"}})}catch(a){throw new Error(`FrugaLoader: bootstrap request to ${o} failed`,{cause:a})}if(!i.ok)throw new Error(`FrugaLoader: bootstrap request to ${o} failed with status ${i.status}`);try{return await i.json()}catch(a){throw new Error(`FrugaLoader: bootstrap response from ${o} was not valid JSON`,{cause:a})}}};var te="*",re=`https://cdn.fruga.co.uk/v/${ee}/`,b=class{mount(e,t,o,n){let i=document.createElement("iframe"),a=this.resolveWidgetUrl(t,o,n),p=this.originOf(a);i.src=a,i.style.border="none",i.style.width="410px",i.style.height="600px",i.style.backgroundColor="transparent",e.appendChild(i);let g=i.contentWindow;if(!g)throw new Error("FrugaLoader: iframe has no contentWindow after being appended");let d=new E({target:g,targetOrigin:p,acceptSource:g,...p===te?{}:{acceptOrigin:p}}),m=!1,l=d.subscribe(f=>{if(f.type==="FRUGA_READY"){m=!0;return}f.type==="FRUGA_RESIZE"&&this.applySize(i,f.width,f.height,f.isFullscreen)}),y=()=>{m&&d.send({type:"FRUGA_HOST_RESIZE",version:"1.0",isHostMobile:window.innerWidth<768,hostHeight:window.innerHeight,hostWidth:window.innerWidth})};return window.addEventListener("resize",y),{iframe:i,transport:d,widgetOrigin:p,cleanup:()=>{window.removeEventListener("resize",y),l(),d.dispose()}}}unmount(e){e.remove()}originOf(e){let t;try{t=new URL(e).origin}catch{t="null"}return t&&t!=="null"?t:(console.warn(`FrugaLoader: widget URL has an opaque origin (${e}); falling back to postMessage targetOrigin '*'`),te)}applySize(e,t,o,n){if(n){e.style.position="fixed",e.style.inset="0",e.style.width="100vw",e.style.height="100vh",e.style.zIndex="99999";return}e.style.position="static",e.style.inset="",e.style.width=`${t}px`,e.style.height=`${o}px`,e.style.zIndex="auto"}resolveWidgetUrl(e,t,o){let n=M??(typeof window<"u"?window.location.href:re),i=e.appUrl||o||(M?`./${t}/index.html`:`${re}${t}/index.html`),a=new URL(i,n);return a.searchParams.set("partnerKey",e.partnerKey),a.toString()}};var oe=1e4,B=r=>r==="EXTERNAL_TENANT"?"relay":"connect";var ne="1.3.0";var ie=ne;var c=class extends Error{constructor(t,o,n={}){super(o);s(this,"code");s(this,"loaderVersion");s(this,"widgetVersion");s(this,"protocolVersion");this.name="FrugaLoadError",this.code=t,this.loaderVersion=n.loaderVersion??ie,this.widgetVersion=n.widgetVersion,this.protocolVersion=n.protocolVersion}};var se="fruga-widget-root",k=5e3,Be="Fruga widget failed to load.",ae="data-fruga-owned",ke=1440*60*1e3,Pe={get:r=>T.get(r),set:(r,e)=>T.set(r,e),remove:r=>T.remove(r)},R=class{constructor(e,t,o={}){this.bootstrapService=e;this.widgetMounter=t;this.env=o;s(this,"options",null);s(this,"currentToken",null);s(this,"session",null);s(this,"mountGeneration",0);s(this,"inFlightBootstrap",null);s(this,"pendingRequests",new Map);s(this,"loadFailed",!1);s(this,"errorElement",null);s(this,"initialTokenRequested",!1)}async init(e){this.options&&this.options.partnerKey!==e.partnerKey&&(this.currentToken=null,this.initialTokenRequested=!1),this.options=e,e.token&&(this.currentToken=e.token),this.emit("lifecycle","init",{partnerKey:e.partnerKey,autoMount:e.autoMount!==!1}),e.autoMount!==!1&&await this.mount()}setOptions(e){this.options=e,e.token&&e.token!==this.currentToken&&this.setToken(e.token)}async mount(){let e=this.options;if(!e){this.report("error","not_initialised","FrugaLoader: Cannot mount - init() must be called first");return}if(!this.initialTokenRequested&&e.onTokenRequired&&(this.initialTokenRequested=!0,await this.requestToken(e.onTokenRequired,"initial")),this.session&&this.session.container.isConnected)return;let t=++this.mountGeneration;this.loadFailed=!1,this.storage.remove(Z);let o=X(e.partnerKey,"bootstrap"),n=this.readFreshCache(o);n&&this.startSession(n);try{let i=await this.fetchBootstrap(e.partnerKey,e.baseUrl);if(t!==this.mountGeneration)return;this.storage.set(o,{fetchedAt:Date.now(),bootstrap:i}),this.applyBootstrap(i)}catch(i){if(t!==this.mountGeneration)return;if(n&&this.session){this.report("warn","bootstrap_refresh_failed","FrugaLoader: bootstrap refresh failed, keeping cached config:",i);return}this.failMount(new c("BOOTSTRAP_FAILED",`FrugaLoader: failed to load partner configuration: ${i instanceof Error?i.message:String(i)}`))}}readFreshCache(e){let t=this.storage.get(e);return!t||typeof t.fetchedAt!="number"||!t.bootstrap?null:Date.now()-t.fetchedAt>=ke?(this.storage.remove(e),null):t.bootstrap}fetchBootstrap(e,t){let o=`${e}::${t??""}`,n=this.inFlightBootstrap;if(n&&n.key===o)return n.promise;let i=this.bootstrapService.bootstrap(e,t),a=()=>{this.inFlightBootstrap?.promise===i&&(this.inFlightBootstrap=null)};return i.then(a,a),this.inFlightBootstrap={key:o,promise:i},i}unmount(){this.mountGeneration+=1;let e=this.session;this.session=null,e&&(this.disposeSession(e),e.ownsContainer&&this.widgetMounter.unmount(e.container),this.emit("lifecycle","unmount",{widgetType:e.widgetType})),this.clearErrorElement(),this.rejectPendingRequests(new Error("FrugaLoader: widget unmounted")),this.initialTokenRequested=!1,this.currentToken=this.options?.token??null}async retry(){this.clearErrorElement(),await this.mount()}requestBalance(){let e=this.session;if(!e){this.report("warn","balance_not_mounted","FrugaLoader: Cannot request balance - widget not mounted");return}let t=this.options?.onBalance;if(!t){this.report("warn","balance_no_callback","FrugaLoader: requestBalance() needs an onBalance option; use getBalance() instead");return}let o=this.nextRequestId(),n=setTimeout(()=>{this.pendingRequests.delete(o)&&this.report("warn","balance_timeout",this.balanceTimeoutMessage(e))},k);this.pendingRequests.set(o,{resolve:i=>t(i),reject:()=>{},timeout:n}),this.sendBalanceRequest(e,o)}async getBalance(){let e=this.session;if(!e)throw new c("NOT_READY","FrugaLoader: Cannot get balance - widget not mounted");let t=this.nextRequestId();return new Promise((o,n)=>{let i=setTimeout(()=>{this.pendingRequests.delete(t)&&n(e.ready?new Error(this.balanceTimeoutMessage(e)):new c("NOT_READY",this.balanceTimeoutMessage(e)))},k);this.pendingRequests.set(t,{resolve:o,reject:n,timeout:i}),this.sendBalanceRequest(e,t)})}sendBalanceRequest(e,t){if(!e.ready){e.queuedBalanceRequests.push(t);return}this.send(e,{type:"FRUGA_GET_BALANCE",version:"1.0",requestId:t})}flushBalanceRequests(e){for(let t of e.queuedBalanceRequests.splice(0))this.pendingRequests.has(t)&&this.sendBalanceRequest(e,t)}balanceTimeoutMessage(e){return e.ready?"FrugaLoader: Get balance request timed out":`FrugaLoader: widget did not report FRUGA_READY within ${k}ms; balance request was never sent`}applyBootstrap(e){let t=this.session,o=B(e.partnerType);if(!t||t.widgetType!==o){this.startSession(e);return}t.bootstrap=e,t.ready&&this.sendInit(t)}startSession(e){let t=this.options,o=this.documentRef;if(!t||!o||this.loadFailed)return;this.clearErrorElement();let n=this.session;this.session=null,n&&this.disposeSession(n);let{container:i,owned:a}=this.ensureContainer(o,t.containerId||se),p=B(e.partnerType),{iframe:g,transport:d,cleanup:m}=this.widgetMounter.mount(i,t,p,e.widgetUrl),l={container:i,iframe:g,transport:d,cleanup:m,bootstrap:e,widgetType:p,ready:!1,ownsContainer:a,queuedBalanceRequests:[],loadTimer:null,unsubscribe:()=>{}};l.unsubscribe=d.subscribe(y=>{this.handleMessage(l,y)}),this.session=l,this.startLoadTimer(l,t),this.emit("lifecycle","mount",{widgetType:p})}disposeSession(e){this.clearLoadTimer(e),e.unsubscribe(),e.cleanup(),e.iframe.remove()}ensureContainer(e,t){let o=e.getElementById(t);if(o)return o.innerHTML="",{container:o,owned:o.hasAttribute(ae)};let n=e.createElement("div");return n.id=t,n.setAttribute(ae,""),n.style.position="fixed",n.style.bottom="0px",n.style.right="0px",n.style.zIndex="9999",e.body.appendChild(n),{container:n,owned:!0}}async handleMessage(e,t){if(this.session===e)switch(this.emit("protocol",t.type,{direction:"in"}),t.type){case"FRUGA_READY":{if(O(t.protocolVersion)!==O("1.0")){this.report("error","protocol_mismatch","FrugaLoader: protocol mismatch",{loader:"1.0",widget:t.protocolVersion}),this.failSession(e,new c("VERSION_MISMATCH",`FrugaLoader: widget protocol ${t.protocolVersion} is incompatible with loader protocol ${"1.0"}`,{widgetVersion:t.widgetVersion,protocolVersion:t.protocolVersion}));return}this.clearLoadTimer(e),this.clearErrorElement(),e.ready=!0,this.emit("lifecycle","ready",{widgetVersion:t.widgetVersion,protocolVersion:t.protocolVersion}),this.sendInit(e),this.flushBalanceRequests(e);return}case"NEED_TOKEN":{await this.refreshToken();return}case"FRUGA_BALANCE_RESPONSE":{this.resolveBalance(t.requestId,t.available,t.pending);return}default:return}}sendInit(e){let t=this.windowRef,o=t?.innerWidth??0,n=t?.innerHeight??0,i=this.buildOverrides();this.send(e,{type:"FRUGA_INIT",version:"1.0",protocolVersion:"1.0",token:this.currentToken??void 0,bootstrap:e.bootstrap,apiBaseUrl:this.options?.baseUrl,host:{origin:t?.location.origin??"",width:o,height:n,isMobile:o<768},...i?{overrides:i}:{}})}buildOverrides(){let e=this.options;if(!e)return;let t={...e.theme?{theme:e.theme}:{},...e.primaryColor?{primaryColor:e.primaryColor}:{},...e.userId?{userId:e.userId}:{},...e.panelOpen?{panelOpen:!0}:{}};return Object.keys(t).length>0?t:void 0}async refreshToken(){let e=this.options?.onTokenRequired;e&&await this.requestToken(e,"ttl")}async requestToken(e,t){this.emit("lifecycle","token_requested",{reason:t});try{this.setToken(await e())}catch(o){this.report("error","token_failed",`FrugaLoader: Failed to fetch ${t} token:`,o)}}setToken(e){this.currentToken=e,this.emit("lifecycle","token_updated",{});let t=this.session;t&&t.ready&&this.send(t,{type:"FRUGA_TOKEN_UPDATE",version:"1.0",token:e})}resolveBalance(e,t,o){if(!e){this.report("warn","balance_response_without_id","FrugaLoader: FRUGA_BALANCE_RESPONSE without requestId ignored");return}let n=this.pendingRequests.get(e);n&&(clearTimeout(n.timeout),this.pendingRequests.delete(e),n.resolve({available:t,pending:o}))}rejectPendingRequests(e){for(let[t,o]of this.pendingRequests)clearTimeout(o.timeout),this.pendingRequests.delete(t),o.reject(e)}nextRequestId(){return Math.random().toString(36).substring(2,15)}startLoadTimer(e,t){let o=t.loadTimeoutMs??oe;o<=0||(e.loadTimer=this.setTimer(()=>{e.loadTimer=null,this.failSession(e,new c("TIMEOUT",`FrugaLoader: widget did not report FRUGA_READY within ${o}ms`))},o))}clearLoadTimer(e){e.loadTimer!==null&&(this.clearTimer(e.loadTimer),e.loadTimer=null)}failSession(e,t){this.session===e&&(this.session=null,this.loadFailed=!0,this.disposeSession(e),this.renderErrorElement(e.container),this.rejectPendingRequests(t),this.notifyError(t))}failMount(e){this.loadFailed=!0;let t=this.session;t&&(this.session=null,this.disposeSession(t));let o=this.documentRef,n=this.options?.containerId||se;o&&this.renderErrorElement(this.ensureContainer(o,n).container),this.rejectPendingRequests(e),this.notifyError(e)}notifyError(e){this.emit("error",e.code,{message:e.message});let t=this.options?.onError;if(t)try{t(e)}catch(o){console.error("FrugaLoader: onError callback threw:",o)}}renderErrorElement(e){let t=this.documentRef;if(!t)return;this.clearErrorElement();let o=t.createElement("div");o.setAttribute("role","alert"),o.setAttribute("data-fruga-error",""),o.style.padding="12px",o.textContent=Be,e.appendChild(o),this.errorElement=o}clearErrorElement(){this.errorElement?.remove(),this.errorElement=null}send(e,t){this.emit("protocol",t.type,{direction:"out"}),e.transport.send(t)}emit(e,t,o,n=e==="error"?"error":"info"){let i=this.options?.onEvent;if(i)try{i({type:e,level:n,name:t,data:o,ts:Date.now()})}catch(a){console.error("FrugaLoader: onEvent callback threw:",a)}}report(e,t,o,n){if(this.options?.onEvent){this.emit("log",t,n===void 0?{message:o}:{message:o,data:n},e);return}let i=e==="error"?console.error:console.warn;if(n===void 0){i(o);return}i(o,n)}setTimer(e,t){let o=this.windowRef;return o?o.setTimeout(e,t):setTimeout(e,t)}clearTimer(e){let t=this.windowRef;if(t){t.clearTimeout(e);return}clearTimeout(e)}get windowRef(){return this.env.windowRef??(typeof window<"u"?window:void 0)}get documentRef(){return this.env.documentRef??(typeof document<"u"?document:void 0)}get storage(){return this.env.storage??Pe}};var Ce=new F,Ue=new b,h=new R(Ce,Ue);var de=async()=>{await h.mount()},C=()=>{h.unmount()},U=async()=>{await h.retry()},P=async r=>(await h.init(r),Ne),ue=r=>{h.setOptions(r)},N=()=>{h.requestBalance()},D=async()=>h.getBalance(),Ne={unmount:C,retry:U,getBalance:D,requestBalance:N};if(typeof window<"u"){let r=document.currentScript;if(r){let e=r.getAttribute("data-partner-key"),t=r.getAttribute("data-container-id")||void 0,o=r.getAttribute("data-app-url")||void 0,n=r.getAttribute("data-base-url")||void 0,i=window.frugaConfig||{};(e||i.partnerKey)&&P({partnerKey:e||i.partnerKey||"demo-key",containerId:t||i.containerId,appUrl:o||i.appUrl,baseUrl:n||i.baseUrl,theme:i.theme,primaryColor:i.primaryColor})}window.FrugaLoader={init:P,setOptions:ue,mount:de,unmount:C,retry:U,requestBalance:N,getBalance:D}}0&&(module.exports={FrugaLoadError,getBalance,init,mount,requestBalance,retry,setOptions,unmount});
|
|
2
2
|
//# sourceMappingURL=loader.js.map
|
package/dist/loader.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var _=Object.defineProperty;var W=(r,e,t)=>e in r?_(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var b=(r,e,t)=>W(r,typeof e!="symbol"?e+"":e,t);import{jsx as he}from"react/jsx-runtime";import{useState as $e,useEffect as Ge,useRef as ze}from"react";import{jsx as be}from"react/jsx-runtime";import{useEffect as ke,useRef as Be}from"react";var I=r=>{let e,t=new Set,o=(n,g)=>{let d=typeof n=="function"?n(e):n;if(!Object.is(d,e)){let w=e;e=g??(typeof d!="object"||d===null)?d:Object.assign({},e,d),t.forEach(f=>f(e,w))}},i=()=>e,u={setState:o,getState:i,getInitialState:()=>y,subscribe:n=>(t.add(n),()=>t.delete(n))},y=e=r(o,i,u);return u},P=(r=>r?I(r):I);import T from"react";var H=r=>r;function $(r,e=H){let t=T.useSyncExternalStore(r.subscribe,T.useCallback(()=>e(r.getState()),[r,e]),T.useCallback(()=>e(r.getInitialState()),[r,e]));return T.useDebugValue(t),t}var k=r=>{let e=P(r),t=o=>$(e,o);return Object.assign(t,e),t},B=(r=>r?k(r):k);var R=B(r=>({isOpen:!1,isFocused:!0,isIdle:!1,available:0,pending:0,mode:"light",token:null,partnerPayout:null,isAddingPayoutFromAlert:!1,showPayoutSuccess:!1,toggle:()=>r(e=>({isOpen:!e.isOpen})),setOpen:e=>r({isOpen:e}),setFocused:e=>r({isFocused:e}),setIdle:e=>r({isIdle:e}),setBalances:(e,t)=>r({available:e,pending:t}),setMode:e=>r({mode:e}),setToken:e=>r({token:e}),setPartnerPayout:e=>r({partnerPayout:e}),setIsAddingPayoutFromAlert:e=>r({isAddingPayoutFromAlert:e}),setShowPayoutSuccess:e=>r({showPayoutSuccess:e})}));import{Fragment as Xe,jsx as Je,jsxs as Ze}from"react/jsx-runtime";import{Fragment as ot,jsx as nt}from"react/jsx-runtime";import{useEffect as st,useState as ct}from"react";var h={BOOTSTRAP_DATA:"fruga_bootstrap",BOOTSTRAP_CONFIG:"fruga_active_config"},p=class{static set(e,t){if(!(typeof window>"u"))try{window.localStorage.setItem(e,JSON.stringify(t))}catch(o){console.warn(`[FrugaStorage] Failed to save key "${e}":`,o)}}static get(e){if(typeof window>"u")return null;try{let t=window.localStorage.getItem(e);return t?JSON.parse(t):null}catch(t){return console.warn(`[FrugaStorage] Failed to load key "${e}":`,t),null}}static remove(e){typeof window>"u"||window.localStorage.removeItem(e)}static clear(){typeof window>"u"||window.localStorage.clear()}};var G=typeof process<"u"&&process.env.VITE_FRUGA_API_URL||"https://api-dev.fruga.co.uk",L=r=>r||G;var S={partnerEnvId:"env_dev_123",partnerId:"partner_abc_456",partnerType:"EXTERNAL_TENANT",partnerPayout:"USER",auth:{mode:"JWT",audience:"https://api.fruga.io",issuer:"https://auth.fruga.io",tokenTtlSeconds:70},config:{ui:{accent:"#F97316",defaultTheme:"light",launcherIcon:"arrow",showLauncher:!0,launcherLabel:"Help",accentTextDark:"#832424",accentTextLight:"#d81414",allowUserThemeControl:!0},validValues:{defaultTheme:["light","dark"],launcherIcon:["none","gift","sparkles","credit","arrow"]}}};var x=class{async bootstrap(e,t){let o=L(t);if(typeof process<"u"&&process.env.VITE_FRUGA_MODE==="test")return console.log("Fruga SDK: Using bootstrap mocks (VITE_FRUGA_MODE=test)"),S;try{let a=await fetch(`${o}/widget/bootstrap?partnerKey=${e}`,{method:"GET",headers:{Accept:"application/json","Content-Type":"application/json"}});if(!a.ok)throw new Error(`Bootstrap failed with status: ${a.status}`);return await a.json()}catch(a){return console.error("Fruga SDK: Bootstrap failed, falling back to mocks",a),S}}};var v=class{mount(e,t,o){let{partnerKey:i,theme:a,primaryColor:c,appUrl:u,userId:y}=o,n=document.createElement("iframe"),g=t.partnerType==="EXTERNAL_TENANT"?"relay":"connect",d=typeof document<"u"?document.currentScript:null,w=d?.src||(typeof window<"u"?window.location.href:""),f=`./${g}/index.html`;if(!d)f=`https://frugainsurance.github.io/sdk/${g}/index.html`;else try{new URL(w).pathname.includes("/dist/")&&(f=`./${g}/index.html`)}catch{}let s=new URL(u||t.appUrl||f,w);s.searchParams.set("partnerKey",i),s.searchParams.set("partnerId",t.partnerId);let M=typeof window<"u"?window.innerWidth<768:!1;if(s.searchParams.set("isHostMobile",String(M)),typeof window<"u"&&(s.searchParams.set("hostHeight",String(window.innerHeight)),s.searchParams.set("hostWidth",String(window.innerWidth))),a&&s.searchParams.set("theme",a),c&&s.searchParams.set("primaryColor",c),y&&s.searchParams.set("userId",y),t.token&&s.searchParams.set("token",t.token),o.baseUrl&&s.searchParams.set("baseUrl",o.baseUrl),t.bootstrapConfig)try{let l=btoa(JSON.stringify(t.bootstrapConfig));s.searchParams.set("bootstrapConfig",l)}catch(l){console.warn("FrugaLoader: Failed to encode bootstrapConfig for iframe URL",l)}n.src=s.toString(),n.style.border="none",n.style.width="410px",n.style.height="600px",n.style.backgroundColor="transparent";let A=l=>{if(l.source===n.contentWindow&&l.data?.type==="FRUGA_RESIZE"){let{width:O,height:D,isFullscreen:U}=l.data;U?(n.style.position="fixed",n.style.inset="0",n.style.width="100vw",n.style.height="100vh",n.style.zIndex="99999"):(n.style.position="static",n.style.width=`${O}px`,n.style.height=`${D}px`,n.style.zIndex="auto")}},F=()=>{n.contentWindow?.postMessage({type:"FRUGA_HOST_RESIZE",isHostMobile:window.innerWidth<768,hostHeight:window.innerHeight,hostWidth:window.innerWidth},"*")};return window.addEventListener("message",A),window.addEventListener("resize",F),e.appendChild(n),{iframe:n,cleanup:()=>{window.removeEventListener("message",A),window.removeEventListener("resize",F)}}}unmount(e){e.remove()}};var E=class{constructor(e,t){this.bootstrapService=e;this.widgetMounter=t;b(this,"state",{container:null,iframe:null,options:null,currentToken:null});b(this,"pendingRequests",new Map);b(this,"handleIframeMessage",async e=>{if(!(this.state.iframe&&e.source!==this.state.iframe.contentWindow)){if(e.data?.type==="NEED_TOKEN"&&this.state.options?.onTokenRequired)try{let t=await this.state.options.onTokenRequired();this.state.currentToken=t,this.state.iframe?.contentWindow?.postMessage({type:"FRUGA_TOKEN_UPDATE",token:t},"*")}catch(t){console.error("FrugaLoader: Failed to refresh token:",t)}if(e.data?.type==="FRUGA_BALANCE_RESPONSE"){let{requestId:t,available:o,pending:i}=e.data;if(t&&this.pendingRequests.has(t)){let{resolve:a,timeout:c}=this.pendingRequests.get(t);clearTimeout(c),this.pendingRequests.delete(t),a({available:o,pending:i})}}}})}async init(e){if(this.state.options=e,e.autoMount!==!1){if(e.token&&(this.state.currentToken=e.token),e.onTokenRequired)try{this.state.currentToken=await e.onTokenRequired()}catch(o){console.error("FrugaLoader: Failed to fetch initial token:",o)}await this.mount()}}setOptions(e){this.state.options=e}async mount(){if(!this.state.options||this.state.container&&this.state.iframe&&document.body.contains(this.state.container))return;let e=p.get(h.BOOTSTRAP_DATA);if(e)this.doMount(e);else{let t=p.get(h.BOOTSTRAP_CONFIG);if(t){let o={partnerEnvId:"cached",partnerId:"cached",partnerType:"EXTERNAL_TENANT",partnerPayout:"USER",auth:{mode:"none",audience:"",issuer:"",tokenTtlSeconds:0},config:t};this.doMount(o)}}try{let t=await this.bootstrapService.bootstrap(this.state.options.partnerKey,this.state.options.baseUrl);p.set(h.BOOTSTRAP_DATA,t),p.set(h.BOOTSTRAP_CONFIG,t.config),this.doMount(t)}catch{}}doMount(e){if(!this.state.options)return;let{containerId:t="fruga-widget-root"}=this.state.options,o=document.getElementById(t);o?o.innerHTML="":(o=document.createElement("div"),o.id=t,document.body.appendChild(o)),o.style.position="fixed",o.style.bottom="0px",o.style.right="0px",o.style.zIndex="9999";let a={...{...this.state.options,containerId:this.state.options.containerId||"fruga-widget-root",bootstrapConfig:e,token:this.state.currentToken||void 0},partnerId:e.partnerId,partnerType:e.partnerType},{iframe:c,cleanup:u}=this.widgetMounter.mount(o,a,this.state.options);this.state.container=o,this.state.iframe=c,o._frugaCleanup=u,window.addEventListener("message",this.handleIframeMessage)}unmount(){if(this.state.container&&document.body.contains(this.state.container)){let e=this.state.container._frugaCleanup;e?.(),this.widgetMounter.unmount(this.state.container)}this.state.container=null,this.state.iframe=null,window.removeEventListener("message",this.handleIframeMessage)}requestBalance(){this.state.iframe&&this.state.iframe.contentWindow?.postMessage({type:"FRUGA_GET_BALANCE"},"*")}async getBalance(){if(!this.state.iframe)throw new Error("FrugaLoader: Cannot get balance - widget not mounted");let e=Math.random().toString(36).substring(2,15);return new Promise((t,o)=>{let i=setTimeout(()=>{this.pendingRequests.has(e)&&(this.pendingRequests.delete(e),o(new Error("FrugaLoader: Get balance request timed out")))},5e3);this.pendingRequests.set(e,{resolve:t,reject:o,timeout:i}),this.state.iframe?.contentWindow?.postMessage({type:"FRUGA_GET_BALANCE",requestId:e},"*")})}};var z=new x,K=new v,m=new E(z,K),j=async()=>{await m.mount()},q=()=>{m.unmount()},C=async r=>{await m.init(r)},V=r=>{m.setOptions(r)},Q=()=>{m.requestBalance()},Y=async()=>m.getBalance();if(typeof window<"u"){let r=document.currentScript;if(r){let e=r.getAttribute("data-partner-key"),t=r.getAttribute("data-container-id")||void 0,o=r.getAttribute("data-app-url")||void 0,i=r.getAttribute("data-base-url")||void 0,a=window.frugaConfig||{};(e||a.partnerKey)&&C({partnerKey:e||a.partnerKey||"demo-key",containerId:t||a.containerId,appUrl:o||a.appUrl,baseUrl:i||a.baseUrl,theme:a.theme,primaryColor:a.primaryColor})}window.FrugaLoader={init:C,setOptions:V,mount:j,unmount:q,requestBalance:Q,getBalance:Y}}export{Y as getBalance,C as init,j as mount,Q as requestBalance,V as setOptions,q as unmount};
|
|
1
|
+
var J=Object.defineProperty;var ee=(o,e,t)=>e in o?J(o,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):o[e]=t;var s=(o,e,t)=>ee(o,typeof e!="symbol"?e+"":e,t);var te=["loader.global.js","native.global.js"],re=()=>{if(typeof document>"u")return null;let e=document.currentScript?.src;if(!e)return null;try{let t=new URL(e,document.baseURI),r=t.pathname.split("/").pop()??"";return te.includes(r)?t.toString():null}catch{return null}},R=re();var oe=["NEED_TOKEN","FRUGA_TOKEN_UPDATE","FRUGA_GET_BALANCE","FRUGA_BALANCE_RESPONSE","FRUGA_RESIZE","FRUGA_HOST_RESIZE","FRUGA_READY","FRUGA_INIT"],ne=o=>typeof o=="string"&&oe.includes(o),ie=["ttl","unauthorized"],L=o=>{if(typeof o!="object"||o===null)return!1;let e=o;if(!ne(e.type)||e.version!==void 0&&typeof e.version!="string")return!1;if(e.type==="NEED_TOKEN"){let{reason:t}=o;return typeof t=="string"&&ie.includes(t)}return!0},M=o=>Number.parseInt(o.split(".")[0]??"",10);var A=o=>o==="PARTNER"||o==="USER"?o:null;var ae="*",v=class{constructor(e){s(this,"target");s(this,"acceptSource");s(this,"listenOn");s(this,"handlers",new Set);s(this,"pinOriginFrom");s(this,"targetOrigin");s(this,"acceptOrigin");s(this,"pinned",null);s(this,"disposed",!1);s(this,"onMessage",e=>{if(this.disposed||this.acceptSource&&e.source!==this.acceptSource||this.acceptOrigin&&e.origin!==this.acceptOrigin||!L(e.data)||!this.admitWhileUnpinned(e.data.type,e.origin))return;let t=typeof e.data.version=="string"&&e.data.version.length>0?e.data:{...e.data,version:"1.0"};for(let r of[...this.handlers])r(t)});let t=e.listenOn??(typeof window<"u"?window:void 0);if(!t)throw new Error("PostMessageTransport: no window to listen on; pass options.listenOn");this.target=e.target,this.targetOrigin=e.targetOrigin,this.acceptSource=e.acceptSource,this.acceptOrigin=e.acceptOrigin,this.pinOriginFrom=e.pinOriginFrom,this.listenOn=t,this.listenOn.addEventListener("message",this.onMessage)}get pinnedOrigin(){return this.pinned}pinOrigin(e){this.targetOrigin=e,this.acceptOrigin=e,this.pinned=e}send(e){if(this.disposed)return;let t=typeof e.version=="string"&&e.version.length>0?e:{...e,version:"1.0"};this.target.postMessage(t,this.targetOrigin)}subscribe(e){if(this.disposed)throw new Error("PostMessageTransport: cannot subscribe after dispose()");return this.handlers.add(e),()=>{this.handlers.delete(e)}}dispose(){this.disposed||(this.disposed=!0,this.handlers.clear(),this.listenOn.removeEventListener("message",this.onMessage))}admitWhileUnpinned(e,t){return!this.pinOriginFrom||this.pinned!==null?!0:e!==this.pinOriginFrom?!1:t&&t!=="null"?(this.pinOrigin(t),!0):(this.pinned=ae,!0)}};import{useState as Wt,useEffect as qt,useRef as Gt}from"react";import{jsx as ot}from"react/jsx-runtime";import{useEffect as ft,useRef as ht}from"react";var B=o=>{let e,t=new Set,r=(d,m)=>{let l=typeof d=="function"?d(e):d;if(!Object.is(l,e)){let y=e;e=m??(typeof l!="object"||l===null)?l:Object.assign({},e,l),t.forEach(f=>f(e,y))}},n=()=>e,p={setState:r,getState:n,getInitialState:()=>g,subscribe:d=>(t.add(d),()=>t.delete(d))},g=e=o(r,n,p);return p},k=(o=>o?B(o):B);import E from"react";var de=o=>o;function ue(o,e=de){let t=E.useSyncExternalStore(o.subscribe,E.useCallback(()=>e(o.getState()),[o,e]),E.useCallback(()=>e(o.getInitialState()),[o,e]));return E.useDebugValue(t),t}var P=o=>{let e=k(o),t=r=>ue(e,r);return Object.assign(t,e),t},C=(o=>o?P(o):P);var S=C(o=>({isOpen:!1,isFocused:!0,isIdle:!1,available:0,pending:0,mode:"light",token:null,tokenEpoch:0,authStatus:"pending",partnerPayout:null,isAddingPayoutFromAlert:!1,showPayoutSuccess:!1,toggle:()=>o(e=>({isOpen:!e.isOpen})),setOpen:e=>o({isOpen:e}),setFocused:e=>o({isFocused:e}),setIdle:e=>o({isIdle:e}),setBalances:(e,t)=>o({available:e,pending:t}),setMode:e=>o({mode:e}),setToken:e=>o(t=>({token:e,tokenEpoch:t.token===e?t.tokenEpoch:t.tokenEpoch+1,authStatus:e?"authenticated":"pending"})),setPartnerPayout:e=>o({partnerPayout:A(e)}),setIsAddingPayoutFromAlert:e=>o({isAddingPayoutFromAlert:e}),setShowPayoutSuccess:e=>o({showPayoutSuccess:e})}));import{useContext as Mt,useEffect as Ot,useRef as St}from"react";import{createContext as le}from"react";import{jsx as bt}from"react/jsx-runtime";var pe=le(null);import{Fragment as Xt,jsx as Zt,jsxs as Jt}from"react/jsx-runtime";import{Fragment as or,jsx as nr}from"react/jsx-runtime";import{useEffect as ar,useState as dr}from"react";var U="fruga_bootstrap",N=(o,e)=>`fruga:${o}:${e}`,T=class{static set(e,t){if(!(typeof window>"u"))try{window.localStorage.setItem(e,JSON.stringify(t))}catch(r){console.warn(`[FrugaStorage] Failed to save key "${e}":`,r)}}static get(e){if(typeof window>"u")return null;try{let t=window.localStorage.getItem(e);return t?JSON.parse(t):null}catch(t){return console.warn(`[FrugaStorage] Failed to load key "${e}":`,t),null}}static remove(e){if(!(typeof window>"u"))try{window.localStorage.removeItem(e)}catch(t){console.warn(`[FrugaStorage] Failed to remove key "${e}":`,t)}}};var ce="https://api.fruga.co.uk",D=o=>o||ce;var W="1.3.0";var w=class{async bootstrap(e,t){let r=D(t),n=`${r}/widget/bootstrap?partnerKey=${encodeURIComponent(e)}`,i;try{i=await fetch(n,{method:"GET",headers:{Accept:"application/json"}})}catch(a){throw new Error(`FrugaLoader: bootstrap request to ${r} failed`,{cause:a})}if(!i.ok)throw new Error(`FrugaLoader: bootstrap request to ${r} failed with status ${i.status}`);try{return await i.json()}catch(a){throw new Error(`FrugaLoader: bootstrap response from ${r} was not valid JSON`,{cause:a})}}};var q="*",G=`https://cdn.fruga.co.uk/v/${W}/`,F=class{mount(e,t,r,n){let i=document.createElement("iframe"),a=this.resolveWidgetUrl(t,r,n),p=this.originOf(a);i.src=a,i.style.border="none",i.style.width="410px",i.style.height="600px",i.style.backgroundColor="transparent",e.appendChild(i);let g=i.contentWindow;if(!g)throw new Error("FrugaLoader: iframe has no contentWindow after being appended");let d=new v({target:g,targetOrigin:p,acceptSource:g,...p===q?{}:{acceptOrigin:p}}),m=!1,l=d.subscribe(f=>{if(f.type==="FRUGA_READY"){m=!0;return}f.type==="FRUGA_RESIZE"&&this.applySize(i,f.width,f.height,f.isFullscreen)}),y=()=>{m&&d.send({type:"FRUGA_HOST_RESIZE",version:"1.0",isHostMobile:window.innerWidth<768,hostHeight:window.innerHeight,hostWidth:window.innerWidth})};return window.addEventListener("resize",y),{iframe:i,transport:d,widgetOrigin:p,cleanup:()=>{window.removeEventListener("resize",y),l(),d.dispose()}}}unmount(e){e.remove()}originOf(e){let t;try{t=new URL(e).origin}catch{t="null"}return t&&t!=="null"?t:(console.warn(`FrugaLoader: widget URL has an opaque origin (${e}); falling back to postMessage targetOrigin '*'`),q)}applySize(e,t,r,n){if(n){e.style.position="fixed",e.style.inset="0",e.style.width="100vw",e.style.height="100vh",e.style.zIndex="99999";return}e.style.position="static",e.style.inset="",e.style.width=`${t}px`,e.style.height=`${r}px`,e.style.zIndex="auto"}resolveWidgetUrl(e,t,r){let n=R??(typeof window<"u"?window.location.href:G),i=e.appUrl||r||(R?`./${t}/index.html`:`${G}${t}/index.html`),a=new URL(i,n);return a.searchParams.set("partnerKey",e.partnerKey),a.toString()}};var H=1e4,I=o=>o==="EXTERNAL_TENANT"?"relay":"connect";var V="1.3.0";var $=V;var c=class extends Error{constructor(t,r,n={}){super(r);s(this,"code");s(this,"loaderVersion");s(this,"widgetVersion");s(this,"protocolVersion");this.name="FrugaLoadError",this.code=t,this.loaderVersion=n.loaderVersion??$,this.widgetVersion=n.widgetVersion,this.protocolVersion=n.protocolVersion}};var j="fruga-widget-root",_=5e3,me="Fruga widget failed to load.",K="data-fruga-owned",fe=1440*60*1e3,he={get:o=>T.get(o),set:(o,e)=>T.set(o,e),remove:o=>T.remove(o)},x=class{constructor(e,t,r={}){this.bootstrapService=e;this.widgetMounter=t;this.env=r;s(this,"options",null);s(this,"currentToken",null);s(this,"session",null);s(this,"mountGeneration",0);s(this,"inFlightBootstrap",null);s(this,"pendingRequests",new Map);s(this,"loadFailed",!1);s(this,"errorElement",null);s(this,"initialTokenRequested",!1)}async init(e){this.options&&this.options.partnerKey!==e.partnerKey&&(this.currentToken=null,this.initialTokenRequested=!1),this.options=e,e.token&&(this.currentToken=e.token),this.emit("lifecycle","init",{partnerKey:e.partnerKey,autoMount:e.autoMount!==!1}),e.autoMount!==!1&&await this.mount()}setOptions(e){this.options=e,e.token&&e.token!==this.currentToken&&this.setToken(e.token)}async mount(){let e=this.options;if(!e){this.report("error","not_initialised","FrugaLoader: Cannot mount - init() must be called first");return}if(!this.initialTokenRequested&&e.onTokenRequired&&(this.initialTokenRequested=!0,await this.requestToken(e.onTokenRequired,"initial")),this.session&&this.session.container.isConnected)return;let t=++this.mountGeneration;this.loadFailed=!1,this.storage.remove(U);let r=N(e.partnerKey,"bootstrap"),n=this.readFreshCache(r);n&&this.startSession(n);try{let i=await this.fetchBootstrap(e.partnerKey,e.baseUrl);if(t!==this.mountGeneration)return;this.storage.set(r,{fetchedAt:Date.now(),bootstrap:i}),this.applyBootstrap(i)}catch(i){if(t!==this.mountGeneration)return;if(n&&this.session){this.report("warn","bootstrap_refresh_failed","FrugaLoader: bootstrap refresh failed, keeping cached config:",i);return}this.failMount(new c("BOOTSTRAP_FAILED",`FrugaLoader: failed to load partner configuration: ${i instanceof Error?i.message:String(i)}`))}}readFreshCache(e){let t=this.storage.get(e);return!t||typeof t.fetchedAt!="number"||!t.bootstrap?null:Date.now()-t.fetchedAt>=fe?(this.storage.remove(e),null):t.bootstrap}fetchBootstrap(e,t){let r=`${e}::${t??""}`,n=this.inFlightBootstrap;if(n&&n.key===r)return n.promise;let i=this.bootstrapService.bootstrap(e,t),a=()=>{this.inFlightBootstrap?.promise===i&&(this.inFlightBootstrap=null)};return i.then(a,a),this.inFlightBootstrap={key:r,promise:i},i}unmount(){this.mountGeneration+=1;let e=this.session;this.session=null,e&&(this.disposeSession(e),e.ownsContainer&&this.widgetMounter.unmount(e.container),this.emit("lifecycle","unmount",{widgetType:e.widgetType})),this.clearErrorElement(),this.rejectPendingRequests(new Error("FrugaLoader: widget unmounted")),this.initialTokenRequested=!1,this.currentToken=this.options?.token??null}async retry(){this.clearErrorElement(),await this.mount()}requestBalance(){let e=this.session;if(!e){this.report("warn","balance_not_mounted","FrugaLoader: Cannot request balance - widget not mounted");return}let t=this.options?.onBalance;if(!t){this.report("warn","balance_no_callback","FrugaLoader: requestBalance() needs an onBalance option; use getBalance() instead");return}let r=this.nextRequestId(),n=setTimeout(()=>{this.pendingRequests.delete(r)&&this.report("warn","balance_timeout",this.balanceTimeoutMessage(e))},_);this.pendingRequests.set(r,{resolve:i=>t(i),reject:()=>{},timeout:n}),this.sendBalanceRequest(e,r)}async getBalance(){let e=this.session;if(!e)throw new c("NOT_READY","FrugaLoader: Cannot get balance - widget not mounted");let t=this.nextRequestId();return new Promise((r,n)=>{let i=setTimeout(()=>{this.pendingRequests.delete(t)&&n(e.ready?new Error(this.balanceTimeoutMessage(e)):new c("NOT_READY",this.balanceTimeoutMessage(e)))},_);this.pendingRequests.set(t,{resolve:r,reject:n,timeout:i}),this.sendBalanceRequest(e,t)})}sendBalanceRequest(e,t){if(!e.ready){e.queuedBalanceRequests.push(t);return}this.send(e,{type:"FRUGA_GET_BALANCE",version:"1.0",requestId:t})}flushBalanceRequests(e){for(let t of e.queuedBalanceRequests.splice(0))this.pendingRequests.has(t)&&this.sendBalanceRequest(e,t)}balanceTimeoutMessage(e){return e.ready?"FrugaLoader: Get balance request timed out":`FrugaLoader: widget did not report FRUGA_READY within ${_}ms; balance request was never sent`}applyBootstrap(e){let t=this.session,r=I(e.partnerType);if(!t||t.widgetType!==r){this.startSession(e);return}t.bootstrap=e,t.ready&&this.sendInit(t)}startSession(e){let t=this.options,r=this.documentRef;if(!t||!r||this.loadFailed)return;this.clearErrorElement();let n=this.session;this.session=null,n&&this.disposeSession(n);let{container:i,owned:a}=this.ensureContainer(r,t.containerId||j),p=I(e.partnerType),{iframe:g,transport:d,cleanup:m}=this.widgetMounter.mount(i,t,p,e.widgetUrl),l={container:i,iframe:g,transport:d,cleanup:m,bootstrap:e,widgetType:p,ready:!1,ownsContainer:a,queuedBalanceRequests:[],loadTimer:null,unsubscribe:()=>{}};l.unsubscribe=d.subscribe(y=>{this.handleMessage(l,y)}),this.session=l,this.startLoadTimer(l,t),this.emit("lifecycle","mount",{widgetType:p})}disposeSession(e){this.clearLoadTimer(e),e.unsubscribe(),e.cleanup(),e.iframe.remove()}ensureContainer(e,t){let r=e.getElementById(t);if(r)return r.innerHTML="",{container:r,owned:r.hasAttribute(K)};let n=e.createElement("div");return n.id=t,n.setAttribute(K,""),n.style.position="fixed",n.style.bottom="0px",n.style.right="0px",n.style.zIndex="9999",e.body.appendChild(n),{container:n,owned:!0}}async handleMessage(e,t){if(this.session===e)switch(this.emit("protocol",t.type,{direction:"in"}),t.type){case"FRUGA_READY":{if(M(t.protocolVersion)!==M("1.0")){this.report("error","protocol_mismatch","FrugaLoader: protocol mismatch",{loader:"1.0",widget:t.protocolVersion}),this.failSession(e,new c("VERSION_MISMATCH",`FrugaLoader: widget protocol ${t.protocolVersion} is incompatible with loader protocol ${"1.0"}`,{widgetVersion:t.widgetVersion,protocolVersion:t.protocolVersion}));return}this.clearLoadTimer(e),this.clearErrorElement(),e.ready=!0,this.emit("lifecycle","ready",{widgetVersion:t.widgetVersion,protocolVersion:t.protocolVersion}),this.sendInit(e),this.flushBalanceRequests(e);return}case"NEED_TOKEN":{await this.refreshToken();return}case"FRUGA_BALANCE_RESPONSE":{this.resolveBalance(t.requestId,t.available,t.pending);return}default:return}}sendInit(e){let t=this.windowRef,r=t?.innerWidth??0,n=t?.innerHeight??0,i=this.buildOverrides();this.send(e,{type:"FRUGA_INIT",version:"1.0",protocolVersion:"1.0",token:this.currentToken??void 0,bootstrap:e.bootstrap,apiBaseUrl:this.options?.baseUrl,host:{origin:t?.location.origin??"",width:r,height:n,isMobile:r<768},...i?{overrides:i}:{}})}buildOverrides(){let e=this.options;if(!e)return;let t={...e.theme?{theme:e.theme}:{},...e.primaryColor?{primaryColor:e.primaryColor}:{},...e.userId?{userId:e.userId}:{},...e.panelOpen?{panelOpen:!0}:{}};return Object.keys(t).length>0?t:void 0}async refreshToken(){let e=this.options?.onTokenRequired;e&&await this.requestToken(e,"ttl")}async requestToken(e,t){this.emit("lifecycle","token_requested",{reason:t});try{this.setToken(await e())}catch(r){this.report("error","token_failed",`FrugaLoader: Failed to fetch ${t} token:`,r)}}setToken(e){this.currentToken=e,this.emit("lifecycle","token_updated",{});let t=this.session;t&&t.ready&&this.send(t,{type:"FRUGA_TOKEN_UPDATE",version:"1.0",token:e})}resolveBalance(e,t,r){if(!e){this.report("warn","balance_response_without_id","FrugaLoader: FRUGA_BALANCE_RESPONSE without requestId ignored");return}let n=this.pendingRequests.get(e);n&&(clearTimeout(n.timeout),this.pendingRequests.delete(e),n.resolve({available:t,pending:r}))}rejectPendingRequests(e){for(let[t,r]of this.pendingRequests)clearTimeout(r.timeout),this.pendingRequests.delete(t),r.reject(e)}nextRequestId(){return Math.random().toString(36).substring(2,15)}startLoadTimer(e,t){let r=t.loadTimeoutMs??H;r<=0||(e.loadTimer=this.setTimer(()=>{e.loadTimer=null,this.failSession(e,new c("TIMEOUT",`FrugaLoader: widget did not report FRUGA_READY within ${r}ms`))},r))}clearLoadTimer(e){e.loadTimer!==null&&(this.clearTimer(e.loadTimer),e.loadTimer=null)}failSession(e,t){this.session===e&&(this.session=null,this.loadFailed=!0,this.disposeSession(e),this.renderErrorElement(e.container),this.rejectPendingRequests(t),this.notifyError(t))}failMount(e){this.loadFailed=!0;let t=this.session;t&&(this.session=null,this.disposeSession(t));let r=this.documentRef,n=this.options?.containerId||j;r&&this.renderErrorElement(this.ensureContainer(r,n).container),this.rejectPendingRequests(e),this.notifyError(e)}notifyError(e){this.emit("error",e.code,{message:e.message});let t=this.options?.onError;if(t)try{t(e)}catch(r){console.error("FrugaLoader: onError callback threw:",r)}}renderErrorElement(e){let t=this.documentRef;if(!t)return;this.clearErrorElement();let r=t.createElement("div");r.setAttribute("role","alert"),r.setAttribute("data-fruga-error",""),r.style.padding="12px",r.textContent=me,e.appendChild(r),this.errorElement=r}clearErrorElement(){this.errorElement?.remove(),this.errorElement=null}send(e,t){this.emit("protocol",t.type,{direction:"out"}),e.transport.send(t)}emit(e,t,r,n=e==="error"?"error":"info"){let i=this.options?.onEvent;if(i)try{i({type:e,level:n,name:t,data:r,ts:Date.now()})}catch(a){console.error("FrugaLoader: onEvent callback threw:",a)}}report(e,t,r,n){if(this.options?.onEvent){this.emit("log",t,n===void 0?{message:r}:{message:r,data:n},e);return}let i=e==="error"?console.error:console.warn;if(n===void 0){i(r);return}i(r,n)}setTimer(e,t){let r=this.windowRef;return r?r.setTimeout(e,t):setTimeout(e,t)}clearTimer(e){let t=this.windowRef;if(t){t.clearTimeout(e);return}clearTimeout(e)}get windowRef(){return this.env.windowRef??(typeof window<"u"?window:void 0)}get documentRef(){return this.env.documentRef??(typeof document<"u"?document:void 0)}get storage(){return this.env.storage??he}};var ye=new w,Te=new F,h=new x(ye,Te);var ve=async()=>{await h.mount()},Y=()=>{h.unmount()},Q=async()=>{await h.retry()},z=async o=>(await h.init(o),we),Ee=o=>{h.setOptions(o)},Z=()=>{h.requestBalance()},X=async()=>h.getBalance(),we={unmount:Y,retry:Q,getBalance:X,requestBalance:Z};if(typeof window<"u"){let o=document.currentScript;if(o){let e=o.getAttribute("data-partner-key"),t=o.getAttribute("data-container-id")||void 0,r=o.getAttribute("data-app-url")||void 0,n=o.getAttribute("data-base-url")||void 0,i=window.frugaConfig||{};(e||i.partnerKey)&&z({partnerKey:e||i.partnerKey||"demo-key",containerId:t||i.containerId,appUrl:r||i.appUrl,baseUrl:n||i.baseUrl,theme:i.theme,primaryColor:i.primaryColor})}window.FrugaLoader={init:z,setOptions:Ee,mount:ve,unmount:Y,retry:Q,requestBalance:Z,getBalance:X}}export{c as FrugaLoadError,X as getBalance,z as init,ve as mount,Z as requestBalance,Q as retry,Ee as setOptions,Y as unmount};
|
|
2
2
|
//# sourceMappingURL=loader.mjs.map
|