@cowprotocol/widget-react 0.10.2-RC.0 → 0.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.js CHANGED
@@ -1 +1 @@
1
- "use strict";var V=Object.defineProperty;var F=(e,t,n)=>t in e?V(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var E=(e,t,n)=>(F(e,typeof t!="symbol"?t+"":t,n),n);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const R=require("react/jsx-runtime"),f=require("react");class M{constructor(){E(this,"subscriptions",{})}on(t){const{event:n,handler:r}=t;return this.subscriptions[n]||(this.subscriptions[n]=[]),this.subscriptions[n].push(r),t}off(t){const{event:n,handler:r}=t;return this.subscriptions[n]&&(this.subscriptions[n]=this.subscriptions[n].filter(s=>s!==r)),t}emit(t,n){this.subscriptions[t]&&this.subscriptions[t].forEach(r=>r(n))}}const L="cowSwapWidget";function g(e,t,n){const s={key:L,method:t,...typeof n=="object"?n:{}};e.postMessage(s,"*")}function m(e,t,n){const r=s=>{!k(s.data)||s.data.key!==L||s.data.method!==t||n(s.data)};return e.addEventListener("message",r),r}function k(e){return typeof e=="object"&&e!==null&&"key"in e&&"method"in e&&typeof e.key=="string"&&typeof e.method=="string"}function D(e,t,n){e.removeEventListener("message",n)}function y(e,t){e.removeEventListener("message",t)}var w=(e=>(e.ACTIVATE="ACTIVATE",e.UPDATE_HEIGHT="UPDATE_HEIGHT",e.SET_FULL_HEIGHT="SET_FULL_HEIGHT",e.EMIT_COW_EVENT="EMIT_COW_EVENT",e.PROVIDER_RPC_REQUEST="PROVIDER_RPC_REQUEST",e.INTERCEPT_WINDOW_OPEN="INTERCEPT_WINDOW_OPEN",e))(w||{}),T=(e=>(e.UPDATE_PARAMS="UPDATE_PARAMS",e.UPDATE_APP_DATA="UPDATE_APP_DATA",e.PROVIDER_RPC_RESPONSE="PROVIDER_RPC_RESPONSE",e.PROVIDER_ON_EVENT="PROVIDER_ON_EVENT",e))(T||{}),P=(e=>(e.SWAP="swap",e.LIMIT="limit",e.ADVANCED="advanced",e))(P||{});const G=["primary","background","paper","text","danger","warning","alert","info","success"];class x{constructor(t,n=[]){E(this,"eventEmitter",new M);E(this,"listeners",[]);E(this,"widgetListener");this.contentWindow=t,this.updateListeners(n),this.widgetListener=m(this.contentWindow,w.EMIT_COW_EVENT,r=>this.eventEmitter.emit(r.event,r.payload))}stopListeningIframe(){y(this.contentWindow,this.widgetListener)}updateListeners(t){for(const n of this.listeners)this.eventEmitter.off(n);this.listeners=t||[];for(const n of this.listeners)this.eventEmitter.on(n)}}const j=["connect","disconnect","close","chainChanged","accountsChanged"];class ${constructor(t){E(this,"ethereumProvider",null);E(this,"requestWaitingForConnection",{});E(this,"processRpcCallFromWindow",({rpcRequest:t})=>{if(!this.ethereumProvider){t.id&&(this.requestWaitingForConnection[t.id]=t);return}this.processRpcRequest(t)});this.iframeWidow=t}disconnect(){this.ethereumProvider=null,D(window,w.PROVIDER_RPC_REQUEST,this.processRpcCallFromWindow)}onConnect(t){this.ethereumProvider?this.disconnect():m(window,w.PROVIDER_RPC_REQUEST,this.processRpcCallFromWindow),this.ethereumProvider=t,this.processPendingRequests(),j.forEach(n=>{t.on(n,r=>this.onProviderEvent(n,r))})}processPendingRequests(){Object.keys(this.requestWaitingForConnection).forEach(t=>{this.processRpcRequest(this.requestWaitingForConnection[t])}),this.requestWaitingForConnection={}}processRpcRequest(t){const{id:n,jsonrpc:r,method:s}=t;if(!this.ethereumProvider||!n)return;(s==="enable"?this.ethereumProvider.enable():this.ethereumProvider.request({...t,id:n})).then(d=>this.forwardRpcResponseToIframe({rpcResponse:{jsonrpc:r,id:n,result:d}})).catch(d=>this.forwardRpcResponseToIframe({rpcResponse:{jsonrpc:r,id:n,error:d}}))}onProviderEvent(t,n){g(this.iframeWidow,T.PROVIDER_ON_EVENT,{event:t,params:n})}forwardRpcResponseToIframe(t){g(this.iframeWidow,T.PROVIDER_RPC_RESPONSE,t)}}class Q{constructor(t,n){E(this,"forwardSdkMessage");this.appWindow=t,this.iframeWidow=n,this.forwardSdkMessage=r=>{q(r.data)&&r.origin!==window.location.origin&&(B(r.data)?this.appWindow.parent.postMessage(r.data,"*"):J(r.data)&&this.iframeWidow.postMessage(r.data,"*"))},this.startListening()}startListening(){this.appWindow.addEventListener("message",this.forwardSdkMessage)}stopListening(){this.appWindow.removeEventListener("message",this.forwardSdkMessage)}}function q(e){return typeof e=="object"&&e!==null&&"id"in e&&typeof e.id=="string"}function B(e){return"method"in e&&typeof e.method=="string"&&"params"in e&&"env"in e&&typeof e.env=="object"&&e.env!==null&&"sdkVersion"in e.env}function J(e){return"success"in e&&typeof e.success=="boolean"&&"version"in e&&typeof e.version=="string"}function b(e){return!!(e&&typeof e=="object")}const I="_";function z(e){const t=typeof e.baseUrl=="string"?e.baseUrl:"https://swap.cow.fi",n=N(e);return t+"/#"+n+"?"+U(e)}function N(e){const{chainId:t=1,sell:n,buy:r,tradeType:s=P.SWAP}=e,c=[(n==null?void 0:n.asset)||I,(r==null?void 0:r.asset)||I].map(encodeURIComponent).join("/");return`/${t}/widget/${s}/${c}`}function U(e){const t=new URLSearchParams;return Y(K(t,e),e)}function K(e,t){const{sell:n,buy:r}=t;return n!=null&&n.amount&&e.append("sellAmount",n.amount),r!=null&&r.amount&&e.append("buyAmount",r.amount),e}function Y(e,t){const n=t.theme;return n?(b(n)?(e.append("palette",encodeURIComponent(JSON.stringify(n))),e.append("theme",n.baseTheme)):(e.append("palette","null"),e.append("theme",n)),e):(e.append("palette","null"),e)}const H="640px",X="450px",Z=20;function _(e,t){const{params:n,provider:r,listeners:s}=t;let c=r,d=n;const o=ee(n);e.innerHTML="",e.appendChild(o);const{contentWindow:p}=o;if(!p)throw console.error("Iframe does not contain a window",o),new Error("Iframe does not contain a window!");const h=[];h.push(te(p,n.appCode)),h.push(...re(o,n.height)),h.push(ne());const u=new x(window,s);let l=A(p,null,c);o.addEventListener("load",()=>O(p,d,c));const a=new Q(window,p);return{updateParams:i=>{d=i,O(p,d,c)},updateListeners:i=>u.updateListeners(i),updateProvider:i=>{c=i,l=A(p,l,i)},destroy:()=>{l.disconnect(),u.stopListeningIframe(),h.forEach(i=>window.removeEventListener("message",i)),a.stopListening(),e.removeChild(o)}}}function A(e,t,n){t&&t.disconnect();const r=t||new $(e);return n&&r.onConnect(n),r}function ee(e){const{width:t=X,height:n=H}=e,r=document.createElement("iframe");return r.src=z(e),r.width=t,r.height=n,r.style.border="0",r.allow="clipboard-read; clipboard-write",r}function O(e,t,n){const r=!!n,s=N(t),c=U(t).toString(),{theme:d,...o}=t;g(e,T.UPDATE_PARAMS,{urlParams:{pathname:s,search:c},appParams:o,hasProvider:r})}function te(e,t){return m(window,w.ACTIVATE,()=>{g(e,T.UPDATE_APP_DATA,{metaData:t?{appCode:t}:void 0})})}function ne(){return m(window,w.INTERCEPT_WINDOW_OPEN,({href:e,rel:t,target:n})=>{const r=e.toString();if(!r.startsWith("http")&&r.match(/^[a-zA-Z0-9]+:\/\//)){window.open(r,n,t);return}})}function re(e,t=H){return[m(window,w.UPDATE_HEIGHT,n=>{e.style.height=n.height?`${n.height+Z}px`:t}),m(window,w.SET_FULL_HEIGHT,({isUpToSmall:n})=>{e.style.height=n?t:`${document.body.offsetHeight}px`})]}const se=Object.values(P);function ie(e,t,n){if(v(e)){const r=e[n];return C(r)?r[t]:r}if(C(e)){const r=e[t];return v(r)?r[n]:r}return e}function v(e){return typeof e!="object"?!1:Object.keys(e).every(t=>se.includes(t))}const oe=/^\d+$/;function C(e){return typeof e!="object"?!1:Object.keys(e).every(t=>typeof t=="number"||oe.test(t))}function ae(e){const{params:t,provider:n,listeners:r}=e,[s,c]=f.useState(null),d=f.useRef(null),o=f.useRef(n),p=f.useRef(r),h=f.useRef(null),u=f.useRef(null),l=f.useCallback((a,i)=>{try{console.log(`[WIDGET] ${a}`),i()}catch(W){const S=`Error ${a.toLowerCase()}`;console.error(`[WIDGET] ${S}`,W),c({message:S,error:W})}},[c]);return f.useEffect(()=>()=>{d.current=null,o.current=void 0,p.current=void 0;const a=u.current;a&&(l("💥 Destroy widget",()=>a.destroy()),u.current=null)},[]),f.useEffect(()=>{if(!h.current||JSON.stringify(d.current)===JSON.stringify(t))return;const a=h.current,i=u.current;d.current=t,i===null?l("Creating a new widget",()=>{u.current=_(a,{params:t,provider:o.current,listeners:r}),p.current=r}):l("Updating the widget",()=>i.updateParams(t))},[t]),f.useEffect(()=>{if(!u.current||o.current===n)return;o.current=n;const a=h.current;a&&l("Updating the provider",()=>{var i;(i=u.current)==null||i.destroy(),u.current=_(a,{params:t,provider:o.current,listeners:r})})},[n]),f.useEffect(()=>{if(!u.current||p.current===r)return;const a=u.current;l("Updating the listeners",()=>a.updateListeners(r))},[r]),s?R.jsxs("div",{style:{color:"#ff3a3a"},children:[s.message,s.error.message&&R.jsx("pre",{style:{whiteSpace:"pre-wrap",fontSize:"0.75em"},children:s.error.message})]}):R.jsx("div",{ref:h,style:{width:"100%"}})}exports.CowSwapWidget=ae;exports.TradeType=P;exports.WIDGET_PALETTE_COLORS=G;exports.WidgetMethodsEmit=w;exports.WidgetMethodsListen=T;exports.createCowSwapWidget=_;exports.isCowSwapWidgetPalette=b;exports.isPerNetworkConfig=C;exports.isPerTradeTypeConfig=v;exports.listenToMessageFromWindow=m;exports.postMessageToWindow=g;exports.resolveFlexibleConfig=ie;exports.stopListeningToMessageFromWindow=D;exports.stopListeningWindowListener=y;
1
+ "use strict";var G=Object.defineProperty;var j=(e,n,t)=>n in e?G(e,n,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[n]=t;var T=(e,n,t)=>(j(e,typeof n!="symbol"?n+"":n,t),t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const I=require("react/jsx-runtime"),g=require("react");class U{constructor(n){this.key=n}postMessageToWindow(n,t,r){const h=typeof r=="object"?r:{},l={key:this.key,method:t,...h};n.postMessage(l,"*")}listenToMessageFromWindow(n,t,r){const h=l=>{!Q(l.data)||l.data.key!==this.key||l.data.method!==t||r(l.data)};return n.addEventListener("message",h),h}stopListeningToMessageFromWindow(n,t,r){n.removeEventListener("message",r)}stopListeningWindowListener(n,t){n.removeEventListener("message",t)}}function Q(e){return typeof e=="object"&&e!==null&&"key"in e&&"method"in e&&typeof e.key=="string"&&typeof e.method=="string"}var C=(e=>(e.PROVIDER_RPC_REQUEST="PROVIDER_RPC_REQUEST",e.PROVIDER_RPC_RESPONSE="PROVIDER_RPC_RESPONSE",e.PROVIDER_ON_EVENT="PROVIDER_ON_EVENT",e))(C||{});const O=new U("cowSwapIframeRpcProviderTransport"),$=["connect","disconnect","close","chainChanged","accountsChanged"];class q{constructor(n){T(this,"ethereumProvider",null);T(this,"requestWaitingForConnection",{});T(this,"processRpcCallFromWindow",({rpcRequest:n})=>{if(!this.ethereumProvider){n.id&&(this.requestWaitingForConnection[n.id]=n);return}this.processRpcRequest(n)});this.iframeWidow=n}disconnect(){this.ethereumProvider=null,O.stopListeningToMessageFromWindow(window,C.PROVIDER_RPC_REQUEST,this.processRpcCallFromWindow)}onConnect(n){this.ethereumProvider?this.disconnect():O.listenToMessageFromWindow(window,C.PROVIDER_RPC_REQUEST,this.processRpcCallFromWindow),this.ethereumProvider=n,this.processPendingRequests(),$.forEach(t=>{n.on(t,r=>this.onProviderEvent(t,r))})}processPendingRequests(){Object.keys(this.requestWaitingForConnection).forEach(n=>{this.processRpcRequest(this.requestWaitingForConnection[n])}),this.requestWaitingForConnection={}}processRpcRequest(n){const{id:t,jsonrpc:r,method:h}=n;if(!this.ethereumProvider||!t)return;(h==="enable"?this.ethereumProvider.enable():this.ethereumProvider.request({...n,id:t})).then(w=>this.forwardRpcResponseToIframe({rpcResponse:{jsonrpc:r,id:t,result:w}})).catch(w=>this.forwardRpcResponseToIframe({rpcResponse:{jsonrpc:r,id:t,error:w}}))}onProviderEvent(n,t){O.postMessageToWindow(this.iframeWidow,C.PROVIDER_ON_EVENT,{event:n,params:t})}forwardRpcResponseToIframe(n){O.postMessageToWindow(this.iframeWidow,C.PROVIDER_RPC_RESPONSE,n)}}var B={exports:{}};(function(e){var n=Object.prototype.hasOwnProperty,t="~";function r(){}Object.create&&(r.prototype=Object.create(null),new r().__proto__||(t=!1));function h(c,o,s){this.fn=c,this.context=o,this.once=s||!1}function l(c,o,s,i,d){if(typeof s!="function")throw new TypeError("The listener must be a function");var u=new h(s,i||c,d),p=t?t+o:o;return c._events[p]?c._events[p].fn?c._events[p]=[c._events[p],u]:c._events[p].push(u):(c._events[p]=u,c._eventsCount++),c}function w(c,o){--c._eventsCount===0?c._events=new r:delete c._events[o]}function f(){this._events=new r,this._eventsCount=0}f.prototype.eventNames=function(){var o=[],s,i;if(this._eventsCount===0)return o;for(i in s=this._events)n.call(s,i)&&o.push(t?i.slice(1):i);return Object.getOwnPropertySymbols?o.concat(Object.getOwnPropertySymbols(s)):o},f.prototype.listeners=function(o){var s=t?t+o:o,i=this._events[s];if(!i)return[];if(i.fn)return[i.fn];for(var d=0,u=i.length,p=new Array(u);d<u;d++)p[d]=i[d].fn;return p},f.prototype.listenerCount=function(o){var s=t?t+o:o,i=this._events[s];return i?i.fn?1:i.length:0},f.prototype.emit=function(o,s,i,d,u,p){var m=t?t+o:o;if(!this._events[m])return!1;var a=this._events[m],v=arguments.length,R,E;if(a.fn){switch(a.once&&this.removeListener(o,a.fn,void 0,!0),v){case 1:return a.fn.call(a.context),!0;case 2:return a.fn.call(a.context,s),!0;case 3:return a.fn.call(a.context,s,i),!0;case 4:return a.fn.call(a.context,s,i,d),!0;case 5:return a.fn.call(a.context,s,i,d,u),!0;case 6:return a.fn.call(a.context,s,i,d,u,p),!0}for(E=1,R=new Array(v-1);E<v;E++)R[E-1]=arguments[E];a.fn.apply(a.context,R)}else{var H=a.length,y;for(E=0;E<H;E++)switch(a[E].once&&this.removeListener(o,a[E].fn,void 0,!0),v){case 1:a[E].fn.call(a[E].context);break;case 2:a[E].fn.call(a[E].context,s);break;case 3:a[E].fn.call(a[E].context,s,i);break;case 4:a[E].fn.call(a[E].context,s,i,d);break;default:if(!R)for(y=1,R=new Array(v-1);y<v;y++)R[y-1]=arguments[y];a[E].fn.apply(a[E].context,R)}}return!0},f.prototype.on=function(o,s,i){return l(this,o,s,i,!1)},f.prototype.once=function(o,s,i){return l(this,o,s,i,!0)},f.prototype.removeListener=function(o,s,i,d){var u=t?t+o:o;if(!this._events[u])return this;if(!s)return w(this,u),this;var p=this._events[u];if(p.fn)p.fn===s&&(!d||p.once)&&(!i||p.context===i)&&w(this,u);else{for(var m=0,a=[],v=p.length;m<v;m++)(p[m].fn!==s||d&&!p[m].once||i&&p[m].context!==i)&&a.push(p[m]);a.length?this._events[u]=a.length===1?a[0]:a:w(this,u)}return this},f.prototype.removeAllListeners=function(o){var s;return o?(s=t?t+o:o,this._events[s]&&w(this,s)):(this._events=new r,this._eventsCount=0),this},f.prototype.off=f.prototype.removeListener,f.prototype.addListener=f.prototype.on,f.prefixed=t,f.EventEmitter=f,e.exports=f})(B);class J{constructor(){T(this,"subscriptions",{})}on(n){const{event:t,handler:r}=n;return this.subscriptions[t]||(this.subscriptions[t]=[]),this.subscriptions[t].push(r),n}off(n){const{event:t,handler:r}=n;return this.subscriptions[t]&&(this.subscriptions[t]=this.subscriptions[t].filter(h=>h!==r)),n}emit(n,t){this.subscriptions[n]&&this.subscriptions[n].forEach(r=>r(t))}}var P=(e=>(e.ACTIVATE="ACTIVATE",e.UPDATE_HEIGHT="UPDATE_HEIGHT",e.SET_FULL_HEIGHT="SET_FULL_HEIGHT",e.EMIT_COW_EVENT="EMIT_COW_EVENT",e.PROVIDER_RPC_REQUEST="PROVIDER_RPC_REQUEST",e.INTERCEPT_WINDOW_OPEN="INTERCEPT_WINDOW_OPEN",e))(P||{}),S=(e=>(e.UPDATE_PARAMS="UPDATE_PARAMS",e.UPDATE_APP_DATA="UPDATE_APP_DATA",e.PROVIDER_RPC_RESPONSE="PROVIDER_RPC_RESPONSE",e.PROVIDER_ON_EVENT="PROVIDER_ON_EVENT",e))(S||{}),W=(e=>(e.SWAP="swap",e.LIMIT="limit",e.ADVANCED="advanced",e))(W||{});const z=["primary","background","paper","text","danger","warning","alert","info","success"],_=new U("cowSwapWidget");class K{constructor(n,t=[]){T(this,"eventEmitter",new J);T(this,"listeners",[]);T(this,"widgetListener");this.contentWindow=n,this.updateListeners(t),this.widgetListener=_.listenToMessageFromWindow(this.contentWindow,P.EMIT_COW_EVENT,r=>this.eventEmitter.emit(r.event,r.payload))}stopListeningIframe(){_.stopListeningWindowListener(this.contentWindow,this.widgetListener)}updateListeners(n){for(const t of this.listeners)this.eventEmitter.off(t);this.listeners=n||[];for(const t of this.listeners)this.eventEmitter.on(t)}}class X{constructor(n,t){T(this,"forwardSdkMessage");this.appWindow=n,this.iframeWidow=t,this.forwardSdkMessage=r=>{Y(r.data)&&r.origin!==window.location.origin&&(Z(r.data)?this.appWindow.parent.postMessage(r.data,"*"):ee(r.data)&&this.iframeWidow.postMessage(r.data,"*"))},this.startListening()}startListening(){this.appWindow.addEventListener("message",this.forwardSdkMessage)}stopListening(){this.appWindow.removeEventListener("message",this.forwardSdkMessage)}}function Y(e){return typeof e=="object"&&e!==null&&"id"in e&&typeof e.id=="string"}function Z(e){return"method"in e&&typeof e.method=="string"&&"params"in e&&"env"in e&&typeof e.env=="object"&&e.env!==null&&"sdkVersion"in e.env}function ee(e){return"success"in e&&typeof e.success=="boolean"&&"version"in e&&typeof e.version=="string"}function V(e){return!!(e&&typeof e=="object")}const b="_";function te(e){const n=typeof e.baseUrl=="string"?e.baseUrl:"https://swap.cow.fi",t=x(e);return n+"/#"+t+"?"+F(e)}function x(e){const{chainId:n=1,sell:t,buy:r,tradeType:h=W.SWAP}=e,l=[(t==null?void 0:t.asset)||b,(r==null?void 0:r.asset)||b].map(encodeURIComponent).join("/");return`/${n}/widget/${h}/${l}`}function F(e){const n=new URLSearchParams;return re(ne(n,e),e)}function ne(e,n){const{sell:t,buy:r}=n;return t!=null&&t.amount&&e.append("sellAmount",t.amount),r!=null&&r.amount&&e.append("buyAmount",r.amount),e}function re(e,n){const t=n.theme;return t?(V(t)?(e.append("palette",encodeURIComponent(JSON.stringify(t))),e.append("theme",t.baseTheme)):(e.append("palette","null"),e.append("theme",t)),e):(e.append("palette","null"),e)}const k="640px",se="450px",oe=20;function L(e,n){const{params:t,provider:r,listeners:h}=n;let l=r,w=t;const f=ie(t);e.innerHTML="",e.appendChild(f);const{contentWindow:c}=f;if(!c)throw console.error("Iframe does not contain a window",f),new Error("Iframe does not contain a window!");const o=[];o.push(ae(c,t.appCode)),o.push(...ue(f,t.height)),o.push(ce());const s=new K(window,h);let i=N(c,null,l);f.addEventListener("load",()=>M(c,w,l));const d=new X(window,c);return{updateParams:u=>{w=u,M(c,w,l)},updateListeners:u=>s.updateListeners(u),updateProvider:u=>{l=u,i=N(c,i,u)},destroy:()=>{i.disconnect(),s.stopListeningIframe(),o.forEach(u=>window.removeEventListener("message",u)),d.stopListening(),e.removeChild(f)}}}function N(e,n,t){n&&n.disconnect();const r=n||new q(e);return t&&r.onConnect(t),r}function ie(e){const{width:n=se,height:t=k}=e,r=document.createElement("iframe");return r.src=te(e),r.width=n,r.height=t,r.style.border="0",r.allow="clipboard-read; clipboard-write",r}function M(e,n,t){const r=!!t,h=x(n),l=F(n).toString(),{theme:w,...f}=n;_.postMessageToWindow(e,S.UPDATE_PARAMS,{urlParams:{pathname:h,search:l},appParams:f,hasProvider:r})}function ae(e,n){return _.listenToMessageFromWindow(window,P.ACTIVATE,()=>{_.postMessageToWindow(e,S.UPDATE_APP_DATA,{metaData:n?{appCode:n}:void 0})})}function ce(){return _.listenToMessageFromWindow(window,P.INTERCEPT_WINDOW_OPEN,({href:e,rel:n,target:t})=>{const r=e.toString();if(!r.startsWith("http")&&r.match(/^[a-zA-Z0-9]+:\/\//)){window.open(r,t,n);return}})}function ue(e,n=k){return[_.listenToMessageFromWindow(window,P.UPDATE_HEIGHT,t=>{e.style.height=t.height?`${t.height+oe}px`:n}),_.listenToMessageFromWindow(window,P.SET_FULL_HEIGHT,({isUpToSmall:t})=>{e.style.height=t?n:`${document.body.offsetHeight}px`})]}const fe=Object.values(W);function de(e,n,t){if(A(e)){const r=e[t];return D(r)?r[n]:r}if(D(e)){const r=e[n];return A(r)?r[t]:r}return e}function A(e){return typeof e!="object"?!1:Object.keys(e).every(n=>fe.includes(n))}const pe=/^\d+$/;function D(e){return typeof e!="object"?!1:Object.keys(e).every(n=>typeof n=="number"||pe.test(n))}function le(e){const{params:n,provider:t,listeners:r}=e,[h,l]=g.useState(null),w=g.useRef(null),f=g.useRef(t),c=g.useRef(r),o=g.useRef(null),s=g.useRef(null),i=g.useCallback((d,u)=>{try{console.log(`[WIDGET] ${d}`),u()}catch(p){const m=`Error ${d.toLowerCase()}`;console.error(`[WIDGET] ${m}`,p),l({message:m,error:p})}},[l]);return g.useEffect(()=>()=>{w.current=null,f.current=void 0,c.current=void 0;const d=s.current;d&&(i("💥 Destroy widget",()=>d.destroy()),s.current=null)},[]),g.useEffect(()=>{if(!o.current||JSON.stringify(w.current)===JSON.stringify(n))return;const d=o.current,u=s.current;w.current=n,u===null?i("Creating a new widget",()=>{s.current=L(d,{params:n,provider:f.current,listeners:r}),c.current=r}):i("Updating the widget",()=>u.updateParams(n))},[n]),g.useEffect(()=>{if(!s.current||f.current===t)return;f.current=t;const d=o.current;d&&i("Updating the provider",()=>{var u;(u=s.current)==null||u.destroy(),s.current=L(d,{params:n,provider:f.current,listeners:r})})},[t]),g.useEffect(()=>{if(!s.current||c.current===r)return;const d=s.current;i("Updating the listeners",()=>d.updateListeners(r))},[r]),h?I.jsxs("div",{style:{color:"#ff3a3a"},children:[h.message,h.error.message&&I.jsx("pre",{style:{whiteSpace:"pre-wrap",fontSize:"0.75em"},children:h.error.message})]}):I.jsx("div",{ref:o,style:{width:"100%"}})}exports.CowSwapWidget=le;exports.TradeType=W;exports.WIDGET_PALETTE_COLORS=z;exports.WidgetMethodsEmit=P;exports.WidgetMethodsListen=S;exports.createCowSwapWidget=L;exports.isCowSwapWidgetPalette=V;exports.isPerNetworkConfig=D;exports.isPerTradeTypeConfig=A;exports.resolveFlexibleConfig=de;exports.widgetIframeTransport=_;
package/index.mjs CHANGED
@@ -1,166 +1,296 @@
1
- var U = Object.defineProperty;
2
- var H = (e, t, n) => t in e ? U(e, t, { enumerable: !0, configurable: !0, writable: !0, value: n }) : e[t] = n;
3
- var l = (e, t, n) => (H(e, typeof t != "symbol" ? t + "" : t, n), n);
4
- import { jsxs as V, jsx as I } from "react/jsx-runtime";
5
- import { useState as F, useRef as m, useCallback as k, useEffect as P } from "react";
1
+ var G = Object.defineProperty;
2
+ var Q = (e, n, t) => n in e ? G(e, n, { enumerable: !0, configurable: !0, writable: !0, value: t }) : e[n] = t;
3
+ var _ = (e, n, t) => (Q(e, typeof n != "symbol" ? n + "" : n, t), t);
4
+ import { jsxs as $, jsx as A } from "react/jsx-runtime";
5
+ import { useState as j, useRef as y, useCallback as B, useEffect as O } from "react";
6
6
  class M {
7
- constructor() {
8
- l(this, "subscriptions", {});
7
+ constructor(n) {
8
+ this.key = n;
9
9
  }
10
- on(t) {
11
- const { event: n, handler: r } = t;
12
- return this.subscriptions[n] || (this.subscriptions[n] = []), this.subscriptions[n].push(r), t;
10
+ postMessageToWindow(n, t, r) {
11
+ const h = typeof r == "object" ? r : {}, l = {
12
+ key: this.key,
13
+ method: t,
14
+ ...h
15
+ };
16
+ n.postMessage(
17
+ l,
18
+ "*"
19
+ // TODO: Change to CoW specific origin in production. https://github.com/cowprotocol/cowswap/issues/3828
20
+ );
13
21
  }
14
- off(t) {
15
- const { event: n, handler: r } = t;
16
- return this.subscriptions[n] && (this.subscriptions[n] = this.subscriptions[n].filter((s) => s !== r)), t;
22
+ listenToMessageFromWindow(n, t, r) {
23
+ const h = (l) => {
24
+ !q(l.data) || l.data.key !== this.key || l.data.method !== t || r(l.data);
25
+ };
26
+ return n.addEventListener("message", h), h;
17
27
  }
18
- emit(t, n) {
19
- this.subscriptions[t] && this.subscriptions[t].forEach((r) => r(n));
28
+ stopListeningToMessageFromWindow(n, t, r) {
29
+ n.removeEventListener("message", r);
30
+ }
31
+ stopListeningWindowListener(n, t) {
32
+ n.removeEventListener("message", t);
20
33
  }
21
34
  }
22
- const L = "cowSwapWidget";
23
- function R(e, t, n) {
24
- const s = {
25
- key: L,
26
- method: t,
27
- ...typeof n == "object" ? n : {}
28
- };
29
- e.postMessage(
30
- s,
31
- "*"
32
- // TODO: Change to CoW specific origin in production. https://github.com/cowprotocol/cowswap/issues/3828
33
- );
34
- }
35
- function w(e, t, n) {
36
- const r = (s) => {
37
- !G(s.data) || s.data.key !== L || s.data.method !== t || n(s.data);
38
- };
39
- return e.addEventListener("message", r), r;
40
- }
41
- function G(e) {
35
+ function q(e) {
42
36
  return typeof e == "object" && e !== null && "key" in e && "method" in e && typeof e.key == "string" && typeof e.method == "string";
43
37
  }
44
- function x(e, t, n) {
45
- e.removeEventListener("message", n);
46
- }
47
- function $(e, t) {
48
- e.removeEventListener("message", t);
49
- }
50
- var E = /* @__PURE__ */ ((e) => (e.ACTIVATE = "ACTIVATE", e.UPDATE_HEIGHT = "UPDATE_HEIGHT", e.SET_FULL_HEIGHT = "SET_FULL_HEIGHT", e.EMIT_COW_EVENT = "EMIT_COW_EVENT", e.PROVIDER_RPC_REQUEST = "PROVIDER_RPC_REQUEST", e.INTERCEPT_WINDOW_OPEN = "INTERCEPT_WINDOW_OPEN", e))(E || {}), T = /* @__PURE__ */ ((e) => (e.UPDATE_PARAMS = "UPDATE_PARAMS", e.UPDATE_APP_DATA = "UPDATE_APP_DATA", e.PROVIDER_RPC_RESPONSE = "PROVIDER_RPC_RESPONSE", e.PROVIDER_ON_EVENT = "PROVIDER_ON_EVENT", e))(T || {}), g = /* @__PURE__ */ ((e) => (e.SWAP = "swap", e.LIMIT = "limit", e.ADVANCED = "advanced", e))(g || {});
51
- const fe = [
52
- "primary",
53
- "background",
54
- "paper",
55
- "text",
56
- "danger",
57
- "warning",
58
- "alert",
59
- "info",
60
- "success"
61
- ];
62
- class j {
63
- constructor(t, n = []) {
64
- l(this, "eventEmitter", new M());
65
- l(this, "listeners", []);
66
- l(this, "widgetListener");
67
- this.contentWindow = t, this.updateListeners(n), this.widgetListener = w(
68
- this.contentWindow,
69
- E.EMIT_COW_EVENT,
70
- (r) => this.eventEmitter.emit(r.event, r.payload)
71
- );
72
- }
73
- stopListeningIframe() {
74
- $(this.contentWindow, this.widgetListener);
75
- }
76
- updateListeners(t) {
77
- for (const n of this.listeners)
78
- this.eventEmitter.off(n);
79
- this.listeners = t || [];
80
- for (const n of this.listeners)
81
- this.eventEmitter.on(n);
82
- }
83
- }
84
- const Q = ["connect", "disconnect", "close", "chainChanged", "accountsChanged"];
85
- class B {
38
+ var C = /* @__PURE__ */ ((e) => (e.PROVIDER_RPC_REQUEST = "PROVIDER_RPC_REQUEST", e.PROVIDER_RPC_RESPONSE = "PROVIDER_RPC_RESPONSE", e.PROVIDER_ON_EVENT = "PROVIDER_ON_EVENT", e))(C || {});
39
+ const I = new M(
40
+ "cowSwapIframeRpcProviderTransport"
41
+ ), J = ["connect", "disconnect", "close", "chainChanged", "accountsChanged"];
42
+ class z {
86
43
  /**
87
44
  * Creates an instance of IframeRpcProviderBridge.
88
45
  * @param iframeWidow - The iFrame window that will post up general RPC messages and to which the IframeRpcProviderBridge will forward the RPC result.
89
46
  * Also it will receive some special RPC events coming from the wallet, like connect/chainChanged,accountChanged
90
47
  */
91
- constructor(t) {
48
+ constructor(n) {
92
49
  /**
93
50
  * The Ethereum provider instance.
94
51
  * When is null the JSON-RPC bridge is disconnected from the Ethereum provider.
95
52
  * */
96
- l(this, "ethereumProvider", null);
53
+ _(this, "ethereumProvider", null);
97
54
  /** Stored JSON-RPC requests, to queue them when disconnected. */
98
- l(this, "requestWaitingForConnection", {});
99
- l(this, "processRpcCallFromWindow", ({ rpcRequest: t }) => {
55
+ _(this, "requestWaitingForConnection", {});
56
+ _(this, "processRpcCallFromWindow", ({ rpcRequest: n }) => {
100
57
  if (!this.ethereumProvider) {
101
- t.id && (this.requestWaitingForConnection[t.id] = t);
58
+ n.id && (this.requestWaitingForConnection[n.id] = n);
102
59
  return;
103
60
  }
104
- this.processRpcRequest(t);
61
+ this.processRpcRequest(n);
105
62
  });
106
- this.iframeWidow = t;
63
+ this.iframeWidow = n;
107
64
  }
108
65
  /**
109
66
  * Disconnects the JSON-RPC bridge from the Ethereum provider.
110
67
  */
111
68
  disconnect() {
112
- this.ethereumProvider = null, x(window, E.PROVIDER_RPC_REQUEST, this.processRpcCallFromWindow);
69
+ this.ethereumProvider = null, I.stopListeningToMessageFromWindow(
70
+ window,
71
+ C.PROVIDER_RPC_REQUEST,
72
+ this.processRpcCallFromWindow
73
+ );
113
74
  }
114
75
  /**
115
76
  * Handles the 'connect' event and sets up event listeners for Ethereum provider events.
116
77
  * @param newProvider - The Ethereum provider to connect.
117
78
  */
118
- onConnect(t) {
119
- this.ethereumProvider ? this.disconnect() : w(window, E.PROVIDER_RPC_REQUEST, this.processRpcCallFromWindow), this.ethereumProvider = t, this.processPendingRequests(), Q.forEach((n) => {
120
- t.on(n, (r) => this.onProviderEvent(n, r));
79
+ onConnect(n) {
80
+ this.ethereumProvider ? this.disconnect() : I.listenToMessageFromWindow(
81
+ window,
82
+ C.PROVIDER_RPC_REQUEST,
83
+ this.processRpcCallFromWindow
84
+ ), this.ethereumProvider = n, this.processPendingRequests(), J.forEach((t) => {
85
+ n.on(t, (r) => this.onProviderEvent(t, r));
121
86
  });
122
87
  }
123
88
  processPendingRequests() {
124
- Object.keys(this.requestWaitingForConnection).forEach((t) => {
125
- this.processRpcRequest(this.requestWaitingForConnection[t]);
89
+ Object.keys(this.requestWaitingForConnection).forEach((n) => {
90
+ this.processRpcRequest(this.requestWaitingForConnection[n]);
126
91
  }), this.requestWaitingForConnection = {};
127
92
  }
128
93
  /**
129
94
  * Processes a JSON-RPC request and sends appropriate response or error via the content window.
130
95
  * @param request - The JSON-RPC request to be processed.
131
96
  */
132
- processRpcRequest(t) {
133
- const { id: n, jsonrpc: r, method: s } = t;
134
- if (!this.ethereumProvider || !n)
97
+ processRpcRequest(n) {
98
+ const { id: t, jsonrpc: r, method: h } = n;
99
+ if (!this.ethereumProvider || !t)
135
100
  return;
136
- (s === "enable" ? this.ethereumProvider.enable() : this.ethereumProvider.request({ ...t, id: n })).then(
137
- (d) => this.forwardRpcResponseToIframe({
138
- rpcResponse: { jsonrpc: r, id: n, result: d }
101
+ (h === "enable" ? this.ethereumProvider.enable() : this.ethereumProvider.request({ ...n, id: t })).then(
102
+ (w) => this.forwardRpcResponseToIframe({
103
+ rpcResponse: { jsonrpc: r, id: t, result: w }
139
104
  })
140
105
  ).catch(
141
- (d) => this.forwardRpcResponseToIframe({
142
- rpcResponse: { jsonrpc: r, id: n, error: d }
106
+ (w) => this.forwardRpcResponseToIframe({
107
+ rpcResponse: { jsonrpc: r, id: t, error: w }
143
108
  })
144
109
  );
145
110
  }
146
- onProviderEvent(t, n) {
147
- R(this.iframeWidow, T.PROVIDER_ON_EVENT, {
148
- event: t,
149
- params: n
111
+ onProviderEvent(n, t) {
112
+ I.postMessageToWindow(this.iframeWidow, C.PROVIDER_ON_EVENT, {
113
+ event: n,
114
+ params: t
150
115
  });
151
116
  }
152
117
  /**
153
118
  * Forward a JSON-RPC message to the content window.
154
119
  */
155
- forwardRpcResponseToIframe(t) {
156
- R(this.iframeWidow, T.PROVIDER_RPC_RESPONSE, t);
120
+ forwardRpcResponseToIframe(n) {
121
+ I.postMessageToWindow(
122
+ this.iframeWidow,
123
+ C.PROVIDER_RPC_RESPONSE,
124
+ n
125
+ );
157
126
  }
158
127
  }
159
- class q {
160
- constructor(t, n) {
161
- l(this, "forwardSdkMessage");
162
- this.appWindow = t, this.iframeWidow = n, this.forwardSdkMessage = (r) => {
163
- J(r.data) && r.origin !== window.location.origin && (z(r.data) ? this.appWindow.parent.postMessage(r.data, "*") : K(r.data) && this.iframeWidow.postMessage(r.data, "*"));
128
+ var K = { exports: {} };
129
+ (function(e) {
130
+ var n = Object.prototype.hasOwnProperty, t = "~";
131
+ function r() {
132
+ }
133
+ Object.create && (r.prototype = /* @__PURE__ */ Object.create(null), new r().__proto__ || (t = !1));
134
+ function h(c, o, s) {
135
+ this.fn = c, this.context = o, this.once = s || !1;
136
+ }
137
+ function l(c, o, s, i, d) {
138
+ if (typeof s != "function")
139
+ throw new TypeError("The listener must be a function");
140
+ var u = new h(s, i || c, d), p = t ? t + o : o;
141
+ return c._events[p] ? c._events[p].fn ? c._events[p] = [c._events[p], u] : c._events[p].push(u) : (c._events[p] = u, c._eventsCount++), c;
142
+ }
143
+ function w(c, o) {
144
+ --c._eventsCount === 0 ? c._events = new r() : delete c._events[o];
145
+ }
146
+ function f() {
147
+ this._events = new r(), this._eventsCount = 0;
148
+ }
149
+ f.prototype.eventNames = function() {
150
+ var o = [], s, i;
151
+ if (this._eventsCount === 0)
152
+ return o;
153
+ for (i in s = this._events)
154
+ n.call(s, i) && o.push(t ? i.slice(1) : i);
155
+ return Object.getOwnPropertySymbols ? o.concat(Object.getOwnPropertySymbols(s)) : o;
156
+ }, f.prototype.listeners = function(o) {
157
+ var s = t ? t + o : o, i = this._events[s];
158
+ if (!i)
159
+ return [];
160
+ if (i.fn)
161
+ return [i.fn];
162
+ for (var d = 0, u = i.length, p = new Array(u); d < u; d++)
163
+ p[d] = i[d].fn;
164
+ return p;
165
+ }, f.prototype.listenerCount = function(o) {
166
+ var s = t ? t + o : o, i = this._events[s];
167
+ return i ? i.fn ? 1 : i.length : 0;
168
+ }, f.prototype.emit = function(o, s, i, d, u, p) {
169
+ var m = t ? t + o : o;
170
+ if (!this._events[m])
171
+ return !1;
172
+ var a = this._events[m], v = arguments.length, g, E;
173
+ if (a.fn) {
174
+ switch (a.once && this.removeListener(o, a.fn, void 0, !0), v) {
175
+ case 1:
176
+ return a.fn.call(a.context), !0;
177
+ case 2:
178
+ return a.fn.call(a.context, s), !0;
179
+ case 3:
180
+ return a.fn.call(a.context, s, i), !0;
181
+ case 4:
182
+ return a.fn.call(a.context, s, i, d), !0;
183
+ case 5:
184
+ return a.fn.call(a.context, s, i, d, u), !0;
185
+ case 6:
186
+ return a.fn.call(a.context, s, i, d, u, p), !0;
187
+ }
188
+ for (E = 1, g = new Array(v - 1); E < v; E++)
189
+ g[E - 1] = arguments[E];
190
+ a.fn.apply(a.context, g);
191
+ } else {
192
+ var H = a.length, P;
193
+ for (E = 0; E < H; E++)
194
+ switch (a[E].once && this.removeListener(o, a[E].fn, void 0, !0), v) {
195
+ case 1:
196
+ a[E].fn.call(a[E].context);
197
+ break;
198
+ case 2:
199
+ a[E].fn.call(a[E].context, s);
200
+ break;
201
+ case 3:
202
+ a[E].fn.call(a[E].context, s, i);
203
+ break;
204
+ case 4:
205
+ a[E].fn.call(a[E].context, s, i, d);
206
+ break;
207
+ default:
208
+ if (!g)
209
+ for (P = 1, g = new Array(v - 1); P < v; P++)
210
+ g[P - 1] = arguments[P];
211
+ a[E].fn.apply(a[E].context, g);
212
+ }
213
+ }
214
+ return !0;
215
+ }, f.prototype.on = function(o, s, i) {
216
+ return l(this, o, s, i, !1);
217
+ }, f.prototype.once = function(o, s, i) {
218
+ return l(this, o, s, i, !0);
219
+ }, f.prototype.removeListener = function(o, s, i, d) {
220
+ var u = t ? t + o : o;
221
+ if (!this._events[u])
222
+ return this;
223
+ if (!s)
224
+ return w(this, u), this;
225
+ var p = this._events[u];
226
+ if (p.fn)
227
+ p.fn === s && (!d || p.once) && (!i || p.context === i) && w(this, u);
228
+ else {
229
+ for (var m = 0, a = [], v = p.length; m < v; m++)
230
+ (p[m].fn !== s || d && !p[m].once || i && p[m].context !== i) && a.push(p[m]);
231
+ a.length ? this._events[u] = a.length === 1 ? a[0] : a : w(this, u);
232
+ }
233
+ return this;
234
+ }, f.prototype.removeAllListeners = function(o) {
235
+ var s;
236
+ return o ? (s = t ? t + o : o, this._events[s] && w(this, s)) : (this._events = new r(), this._eventsCount = 0), this;
237
+ }, f.prototype.off = f.prototype.removeListener, f.prototype.addListener = f.prototype.on, f.prefixed = t, f.EventEmitter = f, e.exports = f;
238
+ })(K);
239
+ class X {
240
+ constructor() {
241
+ _(this, "subscriptions", {});
242
+ }
243
+ on(n) {
244
+ const { event: t, handler: r } = n;
245
+ return this.subscriptions[t] || (this.subscriptions[t] = []), this.subscriptions[t].push(r), n;
246
+ }
247
+ off(n) {
248
+ const { event: t, handler: r } = n;
249
+ return this.subscriptions[t] && (this.subscriptions[t] = this.subscriptions[t].filter((h) => h !== r)), n;
250
+ }
251
+ emit(n, t) {
252
+ this.subscriptions[n] && this.subscriptions[n].forEach((r) => r(t));
253
+ }
254
+ }
255
+ var R = /* @__PURE__ */ ((e) => (e.ACTIVATE = "ACTIVATE", e.UPDATE_HEIGHT = "UPDATE_HEIGHT", e.SET_FULL_HEIGHT = "SET_FULL_HEIGHT", e.EMIT_COW_EVENT = "EMIT_COW_EVENT", e.PROVIDER_RPC_REQUEST = "PROVIDER_RPC_REQUEST", e.INTERCEPT_WINDOW_OPEN = "INTERCEPT_WINDOW_OPEN", e))(R || {}), S = /* @__PURE__ */ ((e) => (e.UPDATE_PARAMS = "UPDATE_PARAMS", e.UPDATE_APP_DATA = "UPDATE_APP_DATA", e.PROVIDER_RPC_RESPONSE = "PROVIDER_RPC_RESPONSE", e.PROVIDER_ON_EVENT = "PROVIDER_ON_EVENT", e))(S || {}), W = /* @__PURE__ */ ((e) => (e.SWAP = "swap", e.LIMIT = "limit", e.ADVANCED = "advanced", e))(W || {});
256
+ const _e = [
257
+ "primary",
258
+ "background",
259
+ "paper",
260
+ "text",
261
+ "danger",
262
+ "warning",
263
+ "alert",
264
+ "info",
265
+ "success"
266
+ ], T = new M("cowSwapWidget");
267
+ class Y {
268
+ constructor(n, t = []) {
269
+ _(this, "eventEmitter", new X());
270
+ _(this, "listeners", []);
271
+ _(this, "widgetListener");
272
+ this.contentWindow = n, this.updateListeners(t), this.widgetListener = T.listenToMessageFromWindow(
273
+ this.contentWindow,
274
+ R.EMIT_COW_EVENT,
275
+ (r) => this.eventEmitter.emit(r.event, r.payload)
276
+ );
277
+ }
278
+ stopListeningIframe() {
279
+ T.stopListeningWindowListener(this.contentWindow, this.widgetListener);
280
+ }
281
+ updateListeners(n) {
282
+ for (const t of this.listeners)
283
+ this.eventEmitter.off(t);
284
+ this.listeners = n || [];
285
+ for (const t of this.listeners)
286
+ this.eventEmitter.on(t);
287
+ }
288
+ }
289
+ class Z {
290
+ constructor(n, t) {
291
+ _(this, "forwardSdkMessage");
292
+ this.appWindow = n, this.iframeWidow = t, this.forwardSdkMessage = (r) => {
293
+ ee(r.data) && r.origin !== window.location.origin && (te(r.data) ? this.appWindow.parent.postMessage(r.data, "*") : ne(r.data) && this.iframeWidow.postMessage(r.data, "*"));
164
294
  }, this.startListening();
165
295
  }
166
296
  startListening() {
@@ -170,187 +300,188 @@ class q {
170
300
  this.appWindow.removeEventListener("message", this.forwardSdkMessage);
171
301
  }
172
302
  }
173
- function J(e) {
303
+ function ee(e) {
174
304
  return typeof e == "object" && e !== null && "id" in e && typeof e.id == "string";
175
305
  }
176
- function z(e) {
306
+ function te(e) {
177
307
  return "method" in e && typeof e.method == "string" && "params" in e && "env" in e && typeof e.env == "object" && e.env !== null && "sdkVersion" in e.env;
178
308
  }
179
- function K(e) {
309
+ function ne(e) {
180
310
  return "success" in e && typeof e.success == "boolean" && "version" in e && typeof e.version == "string";
181
311
  }
182
- function Y(e) {
312
+ function re(e) {
183
313
  return !!(e && typeof e == "object");
184
314
  }
185
- const C = "_";
186
- function X(e) {
187
- const t = typeof e.baseUrl == "string" ? e.baseUrl : "https://swap.cow.fi", n = y(e);
188
- return t + "/#" + n + "?" + N(e);
315
+ const L = "_";
316
+ function se(e) {
317
+ const n = typeof e.baseUrl == "string" ? e.baseUrl : "https://swap.cow.fi", t = x(e);
318
+ return n + "/#" + t + "?" + F(e);
189
319
  }
190
- function y(e) {
191
- const { chainId: t = 1, sell: n, buy: r, tradeType: s = g.SWAP } = e, c = [(n == null ? void 0 : n.asset) || C, (r == null ? void 0 : r.asset) || C].map(encodeURIComponent).join("/");
192
- return `/${t}/widget/${s}/${c}`;
320
+ function x(e) {
321
+ const { chainId: n = 1, sell: t, buy: r, tradeType: h = W.SWAP } = e, l = [(t == null ? void 0 : t.asset) || L, (r == null ? void 0 : r.asset) || L].map(encodeURIComponent).join("/");
322
+ return `/${n}/widget/${h}/${l}`;
193
323
  }
194
- function N(e) {
195
- const t = new URLSearchParams();
196
- return ee(Z(t, e), e);
324
+ function F(e) {
325
+ const n = new URLSearchParams();
326
+ return ie(oe(n, e), e);
197
327
  }
198
- function Z(e, t) {
199
- const { sell: n, buy: r } = t;
200
- return n != null && n.amount && e.append("sellAmount", n.amount), r != null && r.amount && e.append("buyAmount", r.amount), e;
328
+ function oe(e, n) {
329
+ const { sell: t, buy: r } = n;
330
+ return t != null && t.amount && e.append("sellAmount", t.amount), r != null && r.amount && e.append("buyAmount", r.amount), e;
201
331
  }
202
- function ee(e, t) {
203
- const n = t.theme;
204
- return n ? (Y(n) ? (e.append("palette", encodeURIComponent(JSON.stringify(n))), e.append("theme", n.baseTheme)) : (e.append("palette", "null"), e.append("theme", n)), e) : (e.append("palette", "null"), e);
332
+ function ie(e, n) {
333
+ const t = n.theme;
334
+ return t ? (re(t) ? (e.append("palette", encodeURIComponent(JSON.stringify(t))), e.append("theme", t.baseTheme)) : (e.append("palette", "null"), e.append("theme", t)), e) : (e.append("palette", "null"), e);
205
335
  }
206
- const b = "640px", te = "450px", ne = 20;
207
- function A(e, t) {
208
- const { params: n, provider: r, listeners: s } = t;
209
- let c = r, d = n;
210
- const o = re(n);
211
- e.innerHTML = "", e.appendChild(o);
212
- const { contentWindow: p } = o;
213
- if (!p)
214
- throw console.error("Iframe does not contain a window", o), new Error("Iframe does not contain a window!");
215
- const f = [];
216
- f.push(se(p, n.appCode)), f.push(...oe(o, n.height)), f.push(ie());
217
- const u = new j(window, s);
218
- let h = S(p, null, c);
219
- o.addEventListener("load", () => W(p, d, c));
220
- const a = new q(window, p);
336
+ const k = "640px", ae = "450px", ce = 20;
337
+ function D(e, n) {
338
+ const { params: t, provider: r, listeners: h } = n;
339
+ let l = r, w = t;
340
+ const f = ue(t);
341
+ e.innerHTML = "", e.appendChild(f);
342
+ const { contentWindow: c } = f;
343
+ if (!c)
344
+ throw console.error("Iframe does not contain a window", f), new Error("Iframe does not contain a window!");
345
+ const o = [];
346
+ o.push(fe(c, t.appCode)), o.push(...pe(f, t.height)), o.push(de());
347
+ const s = new Y(window, h);
348
+ let i = b(c, null, l);
349
+ f.addEventListener("load", () => N(c, w, l));
350
+ const d = new Z(window, c);
221
351
  return {
222
- updateParams: (i) => {
223
- d = i, W(p, d, c);
352
+ updateParams: (u) => {
353
+ w = u, N(c, w, l);
224
354
  },
225
- updateListeners: (i) => u.updateListeners(i),
226
- updateProvider: (i) => {
227
- c = i, h = S(p, h, i);
355
+ updateListeners: (u) => s.updateListeners(u),
356
+ updateProvider: (u) => {
357
+ l = u, i = b(c, i, u);
228
358
  },
229
359
  destroy: () => {
230
- h.disconnect(), u.stopListeningIframe(), f.forEach((i) => window.removeEventListener("message", i)), a.stopListening(), e.removeChild(o);
360
+ i.disconnect(), s.stopListeningIframe(), o.forEach((u) => window.removeEventListener("message", u)), d.stopListening(), e.removeChild(f);
231
361
  }
232
362
  };
233
363
  }
234
- function S(e, t, n) {
235
- t && t.disconnect();
236
- const r = t || new B(e);
237
- return n && r.onConnect(n), r;
364
+ function b(e, n, t) {
365
+ n && n.disconnect();
366
+ const r = n || new z(e);
367
+ return t && r.onConnect(t), r;
238
368
  }
239
- function re(e) {
240
- const { width: t = te, height: n = b } = e, r = document.createElement("iframe");
241
- return r.src = X(e), r.width = t, r.height = n, r.style.border = "0", r.allow = "clipboard-read; clipboard-write", r;
369
+ function ue(e) {
370
+ const { width: n = ae, height: t = k } = e, r = document.createElement("iframe");
371
+ return r.src = se(e), r.width = n, r.height = t, r.style.border = "0", r.allow = "clipboard-read; clipboard-write", r;
242
372
  }
243
- function W(e, t, n) {
244
- const r = !!n, s = y(t), c = N(t).toString(), { theme: d, ...o } = t;
245
- R(e, T.UPDATE_PARAMS, {
373
+ function N(e, n, t) {
374
+ const r = !!t, h = x(n), l = F(n).toString(), { theme: w, ...f } = n;
375
+ T.postMessageToWindow(e, S.UPDATE_PARAMS, {
246
376
  urlParams: {
247
- pathname: s,
248
- search: c
377
+ pathname: h,
378
+ search: l
249
379
  },
250
- appParams: o,
380
+ appParams: f,
251
381
  hasProvider: r
252
382
  });
253
383
  }
254
- function se(e, t) {
255
- return w(window, E.ACTIVATE, () => {
256
- R(e, T.UPDATE_APP_DATA, {
257
- metaData: t ? { appCode: t } : void 0
384
+ function fe(e, n) {
385
+ return T.listenToMessageFromWindow(window, R.ACTIVATE, () => {
386
+ T.postMessageToWindow(e, S.UPDATE_APP_DATA, {
387
+ metaData: n ? { appCode: n } : void 0
258
388
  });
259
389
  });
260
390
  }
261
- function ie() {
262
- return w(window, E.INTERCEPT_WINDOW_OPEN, ({ href: e, rel: t, target: n }) => {
263
- const r = e.toString();
264
- if (!r.startsWith("http") && r.match(/^[a-zA-Z0-9]+:\/\//)) {
265
- window.open(r, n, t);
266
- return;
391
+ function de() {
392
+ return T.listenToMessageFromWindow(
393
+ window,
394
+ R.INTERCEPT_WINDOW_OPEN,
395
+ ({ href: e, rel: n, target: t }) => {
396
+ const r = e.toString();
397
+ if (!r.startsWith("http") && r.match(/^[a-zA-Z0-9]+:\/\//)) {
398
+ window.open(r, t, n);
399
+ return;
400
+ }
267
401
  }
268
- });
402
+ );
269
403
  }
270
- function oe(e, t = b) {
404
+ function pe(e, n = k) {
271
405
  return [
272
- w(window, E.UPDATE_HEIGHT, (n) => {
273
- e.style.height = n.height ? `${n.height + ne}px` : t;
406
+ T.listenToMessageFromWindow(window, R.UPDATE_HEIGHT, (t) => {
407
+ e.style.height = t.height ? `${t.height + ce}px` : n;
274
408
  }),
275
- w(window, E.SET_FULL_HEIGHT, ({ isUpToSmall: n }) => {
276
- e.style.height = n ? t : `${document.body.offsetHeight}px`;
409
+ T.listenToMessageFromWindow(window, R.SET_FULL_HEIGHT, ({ isUpToSmall: t }) => {
410
+ e.style.height = t ? n : `${document.body.offsetHeight}px`;
277
411
  })
278
412
  ];
279
413
  }
280
- const ae = Object.values(g);
281
- function he(e, t, n) {
282
- if (O(e)) {
283
- const r = e[n];
284
- return D(r) ? r[t] : r;
285
- }
286
- if (D(e)) {
414
+ const le = Object.values(W);
415
+ function ve(e, n, t) {
416
+ if (U(e)) {
287
417
  const r = e[t];
288
- return O(r) ? r[n] : r;
418
+ return V(r) ? r[n] : r;
419
+ }
420
+ if (V(e)) {
421
+ const r = e[n];
422
+ return U(r) ? r[t] : r;
289
423
  }
290
424
  return e;
291
425
  }
292
- function O(e) {
293
- return typeof e != "object" ? !1 : Object.keys(e).every((t) => ae.includes(t));
426
+ function U(e) {
427
+ return typeof e != "object" ? !1 : Object.keys(e).every((n) => le.includes(n));
294
428
  }
295
- const ce = /^\d+$/;
296
- function D(e) {
297
- return typeof e != "object" ? !1 : Object.keys(e).every((t) => typeof t == "number" || ce.test(t));
429
+ const he = /^\d+$/;
430
+ function V(e) {
431
+ return typeof e != "object" ? !1 : Object.keys(e).every((n) => typeof n == "number" || he.test(n));
298
432
  }
299
- function le(e) {
300
- const { params: t, provider: n, listeners: r } = e, [s, c] = F(null), d = m(null), o = m(n), p = m(r), f = m(null), u = m(null), h = k(
301
- (a, i) => {
433
+ function Te(e) {
434
+ const { params: n, provider: t, listeners: r } = e, [h, l] = j(null), w = y(null), f = y(t), c = y(r), o = y(null), s = y(null), i = B(
435
+ (d, u) => {
302
436
  try {
303
- console.log(`[WIDGET] ${a}`), i();
304
- } catch (_) {
305
- const v = `Error ${a.toLowerCase()}`;
306
- console.error(`[WIDGET] ${v}`, _), c({ message: v, error: _ });
437
+ console.log(`[WIDGET] ${d}`), u();
438
+ } catch (p) {
439
+ const m = `Error ${d.toLowerCase()}`;
440
+ console.error(`[WIDGET] ${m}`, p), l({ message: m, error: p });
307
441
  }
308
442
  },
309
- [c]
443
+ [l]
310
444
  );
311
- return P(() => () => {
312
- d.current = null, o.current = void 0, p.current = void 0;
313
- const a = u.current;
314
- a && (h("💥 Destroy widget", () => a.destroy()), u.current = null);
315
- }, []), P(() => {
316
- if (!f.current || JSON.stringify(d.current) === JSON.stringify(t))
445
+ return O(() => () => {
446
+ w.current = null, f.current = void 0, c.current = void 0;
447
+ const d = s.current;
448
+ d && (i("💥 Destroy widget", () => d.destroy()), s.current = null);
449
+ }, []), O(() => {
450
+ if (!o.current || JSON.stringify(w.current) === JSON.stringify(n))
317
451
  return;
318
- const a = f.current, i = u.current;
319
- d.current = t, i === null ? h("Creating a new widget", () => {
320
- u.current = A(a, { params: t, provider: o.current, listeners: r }), p.current = r;
321
- }) : h("Updating the widget", () => i.updateParams(t));
322
- }, [t]), P(() => {
323
- if (!u.current || o.current === n)
452
+ const d = o.current, u = s.current;
453
+ w.current = n, u === null ? i("Creating a new widget", () => {
454
+ s.current = D(d, { params: n, provider: f.current, listeners: r }), c.current = r;
455
+ }) : i("Updating the widget", () => u.updateParams(n));
456
+ }, [n]), O(() => {
457
+ if (!s.current || f.current === t)
324
458
  return;
325
- o.current = n;
326
- const a = f.current;
327
- a && h("Updating the provider", () => {
328
- var i;
329
- (i = u.current) == null || i.destroy(), u.current = A(a, { params: t, provider: o.current, listeners: r });
459
+ f.current = t;
460
+ const d = o.current;
461
+ d && i("Updating the provider", () => {
462
+ var u;
463
+ (u = s.current) == null || u.destroy(), s.current = D(d, { params: n, provider: f.current, listeners: r });
330
464
  });
331
- }, [n]), P(() => {
332
- if (!u.current || p.current === r)
465
+ }, [t]), O(() => {
466
+ if (!s.current || c.current === r)
333
467
  return;
334
- const a = u.current;
335
- h("Updating the listeners", () => a.updateListeners(r));
336
- }, [r]), s ? /* @__PURE__ */ V("div", { style: { color: "#ff3a3a" }, children: [
337
- s.message,
338
- s.error.message && /* @__PURE__ */ I("pre", { style: { whiteSpace: "pre-wrap", fontSize: "0.75em" }, children: s.error.message })
339
- ] }) : /* @__PURE__ */ I("div", { ref: f, style: { width: "100%" } });
468
+ const d = s.current;
469
+ i("Updating the listeners", () => d.updateListeners(r));
470
+ }, [r]), h ? /* @__PURE__ */ $("div", { style: { color: "#ff3a3a" }, children: [
471
+ h.message,
472
+ h.error.message && /* @__PURE__ */ A("pre", { style: { whiteSpace: "pre-wrap", fontSize: "0.75em" }, children: h.error.message })
473
+ ] }) : /* @__PURE__ */ A("div", { ref: o, style: { width: "100%" } });
340
474
  }
341
475
  export {
342
- le as CowSwapWidget,
343
- g as TradeType,
344
- fe as WIDGET_PALETTE_COLORS,
345
- E as WidgetMethodsEmit,
346
- T as WidgetMethodsListen,
347
- A as createCowSwapWidget,
348
- Y as isCowSwapWidgetPalette,
349
- D as isPerNetworkConfig,
350
- O as isPerTradeTypeConfig,
351
- w as listenToMessageFromWindow,
352
- R as postMessageToWindow,
353
- he as resolveFlexibleConfig,
354
- x as stopListeningToMessageFromWindow,
355
- $ as stopListeningWindowListener
476
+ Te as CowSwapWidget,
477
+ W as TradeType,
478
+ _e as WIDGET_PALETTE_COLORS,
479
+ R as WidgetMethodsEmit,
480
+ S as WidgetMethodsListen,
481
+ D as createCowSwapWidget,
482
+ re as isCowSwapWidgetPalette,
483
+ V as isPerNetworkConfig,
484
+ U as isPerTradeTypeConfig,
485
+ ve as resolveFlexibleConfig,
486
+ T as widgetIframeTransport
356
487
  };
@@ -1,3 +1,2 @@
1
1
  import { CowSwapWidgetProps } from '@cowprotocol/widget-lib';
2
-
3
2
  export declare function CowSwapWidget(props: CowSwapWidgetProps): import("react/jsx-runtime").JSX.Element;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cowprotocol/widget-react",
3
- "version": "0.10.2-RC.0",
3
+ "version": "0.12.0",
4
4
  "type": "commonjs",
5
5
  "description": "CoW Swap Widget Library. Allows you to easily embed a CoW Swap widget on your React application.",
6
6
  "main": "index.js",
@@ -22,6 +22,6 @@
22
22
  "react"
23
23
  ],
24
24
  "dependencies": {
25
- "@cowprotocol/widget-lib": "^0.14.1-RC.0"
25
+ "@cowprotocol/widget-lib": "^0.16.0"
26
26
  }
27
- }
27
+ }