@cowprotocol/widget-lib 4.3.1 → 4.4.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.
@@ -0,0 +1,6 @@
1
+ import type * as CSS from 'csstype';
2
+ /**
3
+ * Assigns camelCase CSS properties to a DOM element's style.
4
+ * String values are applied as-is; numbers are stringified (e.g. `inset: 0` → `"0"`).
5
+ */
6
+ export declare function assignElementStyles(element: HTMLElement, styles: CSS.Properties | undefined): void;
@@ -1,3 +1,10 @@
1
+ /** `id` of the iframe element created by {@link createCowSwapWidget}. */
2
+ export declare const WIDGET_IFRAME_ID = "cowswap-widget-iframe";
3
+ /** Default `id` of the host container rendered by `@cowprotocol/widget-react`. */
4
+ export declare const WIDGET_CONTAINER_ID = "cowswap-widget";
5
+ export declare const DEFAULT_WIDGET_PARAMS: {
6
+ readonly appCode: "";
7
+ };
1
8
  /**
2
9
  * Iframe sandbox allowlist for the embedded CoW Swap app.
3
10
  * - allow-scripts + allow-same-origin: required for the SPA, storage, and same-origin API calls.
package/index.cjs CHANGED
@@ -1,53 +1,44 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const y=require("@cowprotocol/iframe-transport"),K=require("@cowprotocol/events"),Q=new Set(["wc:","metamask:","imtokenv2:","trustassetapp:","okex:","ledgerlive:","rainbow:","argent:","exodus:","zerion:","okxwallet:","uniswap:","robinhood-wallet:","krakenwallet:","bitpay:","oneinch:","safe:","backpack:","tangem:","mathwallet:","keplrwallet:","coin98:","tpoutside:","bncus:","bnc:"]),Y=new Set(["http:","https:"]);function z(e){try{const t=new URL(e).protocol;return Y.has(t)||Q.has(t)}catch{return!1}}const U="allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox",F="strict-origin-when-cross-origin",B="clipboard-read; clipboard-write";var f=(e=>(e.ACTIVATE="ACTIVATE",e.READY="READY",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.PROCESS_HOOK="PROCESS_HOOK",e))(f||{}),g=(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.HOOK_RESULT="HOOK_RESULT",e))(g||{}),_=(e=>(e.ON_BEFORE_APPROVAL="ON_BEFORE_APPROVAL",e.ON_BEFORE_TRADE="ON_BEFORE_TRADE",e.ON_BEFORE_WRAP_UNWRAP="ON_BEFORE_WRAP_UNWRAP",e.ON_BEFORE_ORDER_CANCEL="ON_BEFORE_ORDER_CANCEL",e.ON_BEFORE_ORDERS_CANCEL="ON_BEFORE_ORDERS_CANCEL",e))(_||{}),P=(e=>(e.SWAP="swap",e.LIMIT="limit",e.ADVANCED="advanced",e.YIELD="yield",e))(P||{});const X=["primary","background","paper","text","danger","warning","alert","info","success"],c=new y.IframeTransport("cowSwapWidget");class J{constructor(t,n,o,r=[]){this.contentWindow=t,this.updateListeners(r),this.widgetListener=c.listenToMessageFromWindow(this.contentWindow,o,f.EMIT_COW_EVENT,i=>this.eventEmitter.emit(i.event,i.payload),n)}eventEmitter=new K.SimpleCowEventEmitter;listeners=[];widgetListener;stopListeningIframe(){c.stopListeningWindowListener(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)}}class Z{constructor(t,n){this.appWindow=t,this.iframeWidow=n,this.forwardSdkMessage=o=>{q(o.data)&&(typeof window<"u"&&o.origin===window.location.origin||(ee(o.data)?this.appWindow.parent.postMessage(o.data,"*"):te(o.data)&&this.iframeWidow.postMessage(o.data,"*")))},this.startListening()}forwardSdkMessage;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 ee(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 te(e){return"success"in e&&typeof e.success=="boolean"&&"version"in e&&typeof e.version=="string"}function ne(e="Default",t="#1c5dbf",...n){console.debug(`%c [COW][${e}]`,`font-weight: bold; color: ${t}`,...n)}function oe(...e){process.env.NODE_ENV!=="test"&&ne("Widget","#47aba8",...e)}const H="https://swap.cow.fi";function k(e){return!!(e&&typeof e=="object")}const v="_",re="CoW Swap widget: invalid baseUrl.",M=!1;function ie(e){return e==="localhost"||e==="127.0.0.1"||e==="::1"||e.endsWith(".localhost")}function C(e,t){const n=`${re} ${e}`;if(t)throw new Error(n);return console.error("[CoW Widget]",n),H}function x(e,t=M){const n=typeof e=="string"?e.trim():"";if(!n)return H;let o;try{o=new URL(n)}catch{return C(`Not a valid URL: ${JSON.stringify(n)}`,t)}if(o.username||o.password)return C("Userinfo (username/password) in URL is not allowed.",t);const r=o.protocol==="https:",i=o.protocol==="http:"&&ie(o.hostname);if(!r&&!i)return C(`Use https, or http only on localhost / 127.0.0.1 / ::1 / *.localhost (got ${o.protocol}//${o.hostname}).`,t);const u=o.pathname==="/"||o.pathname===""?"":o.pathname.replace(/\/+$/,"");return`${o.origin}${u}`}function se(e){const t=x(e.baseUrl),n=V(e);return t+"/#"+n+"?"+$(e)}function V(e){const{chainId:t=1,sell:n,buy:o,tradeType:r=P.SWAP}=e,i=[n?.asset||v,o?.asset||v].map(encodeURIComponent).join("/");return`/${t}/widget/${r}/${i}`}function $(e){const t=new URLSearchParams;return ue(ce(le(de(ae(t,e),e),e),e),e)}function ae(e,t){const{sell:n,buy:o}=t;return n?.amount&&e.append("sellAmount",n.amount),o?.amount&&e.append("buyAmount",o.amount),e}function de(e,t){const n=t.theme;return n?(k(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)}function le(e,t){return t.targetChainId&&e.append("targetChainId",t.targetChainId.toString()),e}function ce(e,t){return t.locale&&e.append("lng",t.locale),e}function ue(e,t){return pe(t.hooks)?e.append("hooksEnabled","true"):e.delete("hooksEnabled"),e}function pe(e){return!!e&&Object.values(e).some(Boolean)}const fe=3e4,m="coWWidgetContentReloadButton";function Ee(e,t,n){const o=e.src;let r=!1,i=!1,u;function E(){e.srcdoc=we,t?.()}function p(){clearTimeout(u),u=setTimeout(()=>{r||i||E()},fe)}function s(){r||i||(e.removeAttribute("srcdoc"),e.src=o,p())}function a(){if(r)return;const d=e.contentDocument,T=d?.querySelector(`.${m}`);if(!(!d||!T)&&(T.addEventListener("click",s),n)){const h=d.createElement("style");h.textContent=n,d.head.appendChild(h)}}return e.addEventListener("error",d=>{r||(console.error("Could not load iframe",d),E())}),e.addEventListener("load",a),p(),{cancelWidgetLoading(){r=!0,clearTimeout(u),e.removeEventListener("load",a)},onWidgetReady(){i=!0,clearTimeout(u)}}}const we=`<!DOCTYPE html>
2
- <html lang="en">
3
- <head>
4
- <style>
5
- html, body { margin: 0; padding: 0; width: 100%; height: 100%; }
6
- .errorContent {
7
- display: flex;
8
- flex-direction: column;
9
- gap: 16px;
10
- align-items: center;
11
- justify-content: center;
12
- text-align: center;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const j=require("@cowprotocol/iframe-transport"),oe=require("@cowprotocol/events"),re=new Set(["wc:","metamask:","imtokenv2:","trustassetapp:","okex:","ledgerlive:","rainbow:","argent:","exodus:","zerion:","okxwallet:","uniswap:","robinhood-wallet:","krakenwallet:","bitpay:","oneinch:","safe:","backpack:","tangem:","mathwallet:","keplrwallet:","coin98:","tpoutside:","bncus:","bnc:"]),ie=new Set(["http:","https:"]);function se(e){try{const t=new URL(e).protocol;return ie.has(t)||re.has(t)}catch{return!1}}function ae(e,t){if(t){e.removeAttribute("style");for(const n of Object.keys(t)){const o=n,r=t[o];if(r==null||typeof r!="string"&&typeof r!="number")continue;const i=`${r}`;e.style[o]=i}}}const K="cowswap-widget-iframe",le="cowswap-widget",de={appCode:""},Y="allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox",Q="strict-origin-when-cross-origin",z="clipboard-read; clipboard-write";var w=(e=>(e.ACTIVATE="ACTIVATE",e.READY="READY",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.PROCESS_HOOK="PROCESS_HOOK",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.HOOK_RESULT="HOOK_RESULT",e))(T||{}),_=(e=>(e.ON_BEFORE_APPROVAL="ON_BEFORE_APPROVAL",e.ON_BEFORE_TRADE="ON_BEFORE_TRADE",e.ON_BEFORE_WRAP_UNWRAP="ON_BEFORE_WRAP_UNWRAP",e.ON_BEFORE_ORDER_CANCEL="ON_BEFORE_ORDER_CANCEL",e.ON_BEFORE_ORDERS_CANCEL="ON_BEFORE_ORDERS_CANCEL",e))(_||{}),L=(e=>(e.SWAP="swap",e.LIMIT="limit",e.ADVANCED="advanced",e.YIELD="yield",e))(L||{});const ce=["primary","background","paper","text","danger","warning","alert","info","success"],p=new j.IframeTransport("cowSwapWidget");class ue{constructor(t,n,o,r=[]){this.contentWindow=t,this.updateListeners(r),this.widgetListener=p.listenToMessageFromWindow(this.contentWindow,o,w.EMIT_COW_EVENT,i=>this.eventEmitter.emit(i.event,i.payload),n)}eventEmitter=new oe.SimpleCowEventEmitter;listeners=[];widgetListener;stopListeningIframe(){p.stopListeningWindowListener(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)}}class pe{constructor(t,n){this.appWindow=t,this.iframeWidow=n,this.forwardSdkMessage=o=>{fe(o.data)&&(typeof window<"u"&&o.origin===window.location.origin||(Ee(o.data)?this.appWindow.parent.postMessage(o.data,"*"):we(o.data)&&this.iframeWidow.postMessage(o.data,"*")))},this.startListening()}forwardSdkMessage;startListening(){this.appWindow.addEventListener("message",this.forwardSdkMessage)}stopListening(){this.appWindow.removeEventListener("message",this.forwardSdkMessage)}}function fe(e){return typeof e=="object"&&e!==null&&"id"in e&&typeof e.id=="string"}function Ee(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 we(e){return"success"in e&&typeof e.success=="boolean"&&"version"in e&&typeof e.version=="string"}function he(e="Default",t="#1c5dbf",...n){console.debug(`%c [COW][${e}]`,`font-weight: bold; color: ${t}`,...n)}function _e(...e){process.env.NODE_ENV!=="test"&&he("Widget","#47aba8",...e)}function D(e){return!!(e&&typeof e=="object")}const X="https://swap.cow.fi",x="_",ge="CoW Swap widget: invalid baseUrl.",J=!1;function Re(e){return e==="localhost"||e==="127.0.0.1"||e==="::1"||e.endsWith(".localhost")}function v(e,t){const n=`${ge} ${e}`;if(t)throw new Error(n);return console.error("[CoW Widget]",n),X}function Z(e,t=J){const n=typeof e=="string"?e.trim():"";if(!n)return X;let o;try{o=new URL(n)}catch{return v(`Not a valid URL: ${JSON.stringify(n)}`,t)}if(o.username||o.password)return v("Userinfo (username/password) in URL is not allowed.",t);const r=o.protocol==="https:",i=o.protocol==="http:"&&Re(o.hostname);if(!r&&!i)return v(`Use https, or http only on localhost / 127.0.0.1 / ::1 / *.localhost (got ${o.protocol}//${o.hostname}).`,t);const f=o.pathname==="/"||o.pathname===""?"":o.pathname.replace(/\/+$/,"");return`${o.origin}${f}`}function me(e){const t=Z(e.baseUrl),n=q(e);return t+"/#"+n+"?"+ee(e)}function q(e){const{chainId:t=1,sell:n,buy:o,tradeType:r=L.SWAP}=e,i=[n?.asset||x,o?.asset||x].map(encodeURIComponent).join("/");return`/${t}/widget/${r}/${i}`}function ee(e){const t=new URLSearchParams;return Ae(ye(Te(Se(Oe(t,e),e),e),e),e)}function Oe(e,t){const{sell:n,buy:o}=t;return n?.amount&&e.append("sellAmount",n.amount),o?.amount&&e.append("buyAmount",o.amount),e}function Se(e,t){const n=t.theme;return n?(D(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)}function Te(e,t){return t.targetChainId&&e.append("targetChainId",t.targetChainId.toString()),e}function ye(e,t){return t.locale&&e.append("lng",t.locale),e}function Ae(e,t){return Le(t.hooks)?e.append("hooksEnabled","true"):e.delete("hooksEnabled"),e}function Le(e){return!!e&&Object.values(e).some(Boolean)}const Ce=3e4,h="cow-widget-loading-error",B=`data-${h}`;function Ie(e,t,n,o,r){const i=t.src;let f=!1,E=null;function c(){r?.(),t.style.display="none",Pe();const l=document.createElement("div"),s=document.createElement("button"),d=document.createElement("p");s.innerText="Reload",s.addEventListener("click",()=>{e.removeChild(l),o(!0),t.src="about:blank",t.style.display="",setTimeout(()=>{t.src=i,n()},100)}),d.innerText="Couldn't load the page. Please, try again later",l.classList.add(h),l.appendChild(d),l.appendChild(s),e.appendChild(l)}return t.addEventListener("error",l=>{f||(console.error("Could not load iframe",l),c())}),E=window.setTimeout(()=>{f||c()},Ce),{onWidgetReady(){E&&clearTimeout(E);const l=document.getElementsByClassName(h)[0];l&&e.removeChild(l)},cancelWidgetLoading(){f=!0}}}let m=null;function Pe(){if(!(typeof document>"u")){if(ve()){m||(m=new CSSStyleSheet,m.replaceSync(k)),document.adoptedStyleSheets.includes(m)||(document.adoptedStyleSheets=[...document.adoptedStyleSheets,m]);return}if(!document.head.querySelector(`style[${B}]`)){const e=document.createElement("style");e.setAttribute(B,""),e.textContent=k,document.head.appendChild(e)}}}function ve(){return typeof document<"u"&&"adoptedStyleSheets"in Document.prototype&&typeof CSSStyleSheet=="function"&&typeof CSSStyleSheet.prototype.replaceSync=="function"}const k=`
2
+ .${h} {
3
+ display: flex;
4
+ flex-direction: column;
5
+ gap: 16px;
6
+ align-items: center;
7
+ justify-content: center;
8
+ text-align: center;
9
+ box-sizing: border-box;
10
+ width: 100%;
11
+ height: 100%;
12
+ min-height: 200px;
13
+ padding: 24px;
14
+ background: #fff5f5;
15
+ color: #d32f2f;
16
+ font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
17
+ font-size: 14px;
18
+ line-height: 1.5;
19
+ font-weight: 500;
20
+ }
13
21
 
14
- width: 100%;
15
- height: 100%;
22
+ .${h} p {
23
+ margin: 0;
24
+ }
16
25
 
17
- padding: 24px;
18
- box-sizing: border-box;
26
+ .${h} button {
27
+ padding: 8px 24px;
28
+ border-radius: 8px;
29
+ font: inherit;
30
+ cursor: pointer;
31
+ border: 1px solid #d32f2f;
32
+ background: transparent;
33
+ color: #d32f2f;
34
+ }
19
35
 
20
- background: #fff5f5;
21
- color: #d32f2f;
36
+ .${h} button:disabled {
37
+ cursor: progress;
38
+ opacity: 0.75;
39
+ }
22
40
 
23
- border: 1px solid #f5c2c7;
24
- border-radius: 12px;
25
-
26
- font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
27
- font-size: 14px;
28
- line-height: 1.5;
29
- font-weight: 500;
30
- }
31
- .${m} {
32
- padding: 8px 24px;
33
- border: 1px solid #d32f2f;
34
- border-radius: 8px;
35
- background: transparent;
36
- color: #d32f2f;
37
- font: inherit;
38
- cursor: pointer;
39
- }
40
- .${m}:hover {
41
- background: #d32f2f;
42
- color: #fff5f5;
43
- }
44
- </style>
45
- </head>
46
- <body>
47
- <div class="errorContent">
48
- <span>Couldn't load the widget. Please try again later.</span>
49
-
50
- <button class="${m}">Retry</button>
51
- </div>
52
- </body>
53
- </html>`,G="640px",_e="450px",Oe=20,Re={iframe:null,updateParams:()=>{},updateListeners:()=>{},updateProvider:()=>{},destroy:()=>{}};function ge(e,t){const{params:n,provider:o,listeners:r,onReady:i,enableSafeSdkBridge:u=!0}=t;let E=o,p=n;if(typeof window>"u")return Re;const s=Te(n),a=he(s);oe("Resolved trusted iframe origin",{iframeOrigin:a});const d=[];e.innerHTML="",e.appendChild(s);const{cancelWidgetLoading:T,onWidgetReady:h}=Ee(s,t.onLoadingError,t.loadingErrorStyles),{contentWindow:l}=s;if(!l)throw console.error("Iframe does not contain a window",s),new Error("Iframe does not contain a window!");d.push(Ae(l,a,()=>{i?.(),h()})),d.push(Le(l,a,n.appCode)),d.push(...Ie(s,a,n.height,n.maxHeight));let L=null;function W(){l&&(L&&window.removeEventListener("message",L),!p.disableWindowOpen&&(L=me(a,l),d.push(L)))}let A=null;function S(){l&&(A&&window.removeEventListener("message",A),A=Se(l,a,p.hooks),d.push(A))}W(),S();const D=new J(window,a,l,r);let I=b(l,a,null,E);s.addEventListener("load",()=>{N(l,a,p,E)});const j=u?new Z(window,l):null;return{iframe:s,updateParams:w=>{p=w,N(l,a,p,E),W(),S()},updateListeners:w=>D.updateListeners(w),updateProvider:w=>{E=w,I=b(l,a,I,w)},destroy:()=>{I.disconnect(),D.stopListeningIframe(),d.forEach(w=>window.removeEventListener("message",w)),j?.stopListening(),s&&s.parentNode===e&&e.removeChild(s),T()}}}function b(e,t,n,o){n&&n.disconnect();const r=n||new y.IframeRpcProviderBridge(e,t);return o&&r.onConnect(o),r}function Te(e){const{width:t=_e,height:n=G}=e,o=document.createElement("iframe");return o.src=se(e),o.width=t,o.height=n,o.style.border="0",o.setAttribute("sandbox",U),o.referrerPolicy=F,o.allow=B,o}function he(e){return new URL(e.src).origin}function N(e,t,n,o){const r=!!o,i=V(n),u=$(n).toString(),{theme:E,hooks:p,...s}=n;c.postMessageToWindow(e,g.UPDATE_PARAMS,{urlParams:{pathname:i,search:u},appParams:s,hasProvider:r},t)}function Le(e,t,n){return c.listenToMessageFromWindow(window,e,f.ACTIVATE,()=>{c.postMessageToWindow(e,g.UPDATE_APP_DATA,{metaData:n?{appCode:n}:void 0},t)},t)}function Ae(e,t,n){let o=!1;return c.listenToMessageFromWindow(window,e,f.READY,()=>{o||(o=!0,n())},t)}function me(e,t){return c.listenToMessageFromWindow(window,t,f.INTERCEPT_WINDOW_OPEN,({href:n,rel:o,target:r})=>{const i=Pe(n.toString(),e);i&&z(i)&&window.open(i,r,o)},e)}function Pe(e,t){const n=e.trim();if(!n)return null;try{return new URL(n,t).toString()}catch{return null}}function Ie(e,t,n=G,o){return e.contentWindow?[c.listenToMessageFromWindow(window,e.contentWindow,f.UPDATE_HEIGHT,r=>{const i=r.height?r.height+Oe:void 0;e.style.height=i?`${o?Math.min(i,o):i}px`:n},t),c.listenToMessageFromWindow(window,e.contentWindow,f.SET_FULL_HEIGHT,({isUpToSmall:r})=>{e.style.height=r?n:`${o||document.body.offsetHeight}px`},t)]:[]}const Ce={[_.ON_BEFORE_APPROVAL]:(e,t)=>t?.onBeforeApproval?t.onBeforeApproval(e):!0,[_.ON_BEFORE_TRADE]:(e,t)=>t?.onBeforeTrade?t.onBeforeTrade(e):!0,[_.ON_BEFORE_WRAP_UNWRAP]:(e,t)=>t?.onBeforeWrapOrUnwrap?t.onBeforeWrapOrUnwrap(e):!0,[_.ON_BEFORE_ORDER_CANCEL]:(e,t)=>t?.onBeforeOrderCancel?t.onBeforeOrderCancel(e):!0,[_.ON_BEFORE_ORDERS_CANCEL]:(e,t)=>t?.onBeforeOrdersCancel?t.onBeforeOrdersCancel(e):!0};function We(e,t){return Ce[e.event](e.payload,t)}function Se(e,t,n){return c.listenToMessageFromWindow(window,e,f.PROCESS_HOOK,async o=>{let r=!1;try{r=await We(o,n)}catch{}c.postMessageToWindow(e,g.HOOK_RESULT,{id:o.id,result:r},t)},t)}const De=Object.values(P);function ve(e,t,n){if(O(e)){const o=e[n];return R(o)?o[t]:o}if(R(e)){const o=e[t];return O(o)?o[n]:o}return e}function O(e){return typeof e!="object"?!1:Object.keys(e).every(t=>De.includes(t))}const be=/^\d+$/;function R(e){return typeof e!="object"?!1:Object.keys(e).every(t=>be.test(t))}function Ne(e){return O(e)?Object.values(e).flatMap(t=>R(t)?Object.values(t):[t]):R(e)?Object.values(e).flatMap(t=>O(t)?Object.values(t):[t]):[e]}exports.SHOULD_THROW_IF_INVALID_URL=M;exports.TradeType=P;exports.WIDGET_IFRAME_ALLOW=B;exports.WIDGET_IFRAME_REFERRER_POLICY=F;exports.WIDGET_IFRAME_SANDBOX=U;exports.WIDGET_PALETTE_COLORS=X;exports.WidgetHookEvents=_;exports.WidgetMethodsEmit=f;exports.WidgetMethodsListen=g;exports.createCowSwapWidget=ge;exports.isCowSwapWidgetPalette=k;exports.isPerNetworkConfig=R;exports.isPerTradeTypeConfig=O;exports.resolveFlexibleConfig=ve;exports.resolveFlexibleConfigValues=Ne;exports.sanitizeWidgetBaseUrl=x;exports.widgetIframeTransport=c;
41
+ .${h} button:not(:disabled):hover {
42
+ background: #d32f2f;
43
+ color: #fff5f5;
44
+ }`,We={iframe:null,updateParams:()=>{},updateListeners:()=>{},updateProvider:()=>{},destroy:()=>{}};function De(e,t){const{params:n,provider:o,listeners:r,onReady:i,enableSafeSdkBridge:f=!0}=t;let E=o,c=M(n),l="";if(typeof window>"u")return We;const s=be(c),d=Ne(s);_e("Resolved trusted iframe origin",{iframeOrigin:d});const y=[];e.innerHTML="",e.appendChild(s),$(e,c);let a=null,C=()=>{},I=()=>{},b=()=>{},P=null,A=null,N=null,U=[],R=null;function H(){if(a=s.contentWindow,!a)throw console.error("Iframe does not contain a window",s),new Error("Iframe does not contain a window!");y.push(He(a,d,()=>{i?.(),te()})),y.push(Ue(a,d,c.appCode)),U=ke(e,s,d,ne=>{l=ne});let u=null;C=()=>{a&&(u&&window.removeEventListener("message",u),!c.disableWindowOpen&&(u=Fe(d,a),y.push(u)))},I=()=>{a&&(R&&window.removeEventListener("message",R),R=$e(a,d,c.hooks))},C(),I(),P=new ue(window,d,a,r),A=V(a,d,null,E),s.addEventListener("load",()=>{a&&G(a,d,c,E)}),N=f?new pe(window,a):null;const g=Ie(e,s,H,F,t.onLoadingError);b=g.cancelWidgetLoading;const te=g.onWidgetReady}function F(u=!1){A?.disconnect(),P?.stopListeningIframe(),U.forEach(g=>window.removeEventListener("message",g)),y.forEach(g=>window.removeEventListener("message",g)),R&&window.removeEventListener("message",R),N?.stopListening(),!u&&s&&s.parentNode===e&&e.removeChild(s),b?.()}return H(),{iframe:s,updateParams:u=>{a&&(c=M(u),$(e,c,l),G(a,d,c,E),C(),I())},updateListeners:u=>P?.updateListeners(u),updateProvider:u=>{a&&(E=u,A=V(a,d,A,u))},destroy:F}}function M(e){const t={...de,...e};if(typeof t.appCode!="string"||t.appCode.trim().length===0)throw new Error("Required param `appCode` is missing");return t}function V(e,t,n,o){n&&n.disconnect();const r=n||new j.IframeRpcProviderBridge(e,t);return o&&r.onConnect(o),r}function be(e){const t=document.createElement("iframe");return t.id=K,t.src=me(e),t.setAttribute("sandbox",Y),t.referrerPolicy=Q,t.allow=z,t.style.width="100%",t.style.height="100%",t.style.border="0",t.style.display="block",t}function $(e,t,n){ae(e,t.rootStyle),[{name:"params.width",value:t.width,replacementName:"rootStyle.width",replacementValue:t.rootStyle?.width,applyDeprecated:()=>t.width?e.style.width=t.width:void 0},{name:"params.height",value:t.height,replacementName:"rootStyle.height",replacementValue:t.rootStyle?.height,applyDeprecated:()=>t.height?e.style.height=t.height:void 0},{name:"params.maxHeight",value:t.maxHeight,replacementName:"rootStyle.maxHeight",replacementValue:t.rootStyle?.maxHeight,applyDeprecated:()=>t.maxHeight?e.style.maxHeight=`${t.maxHeight}px`:void 0},{name:"params.theme.boxShadow",value:D(t.theme)?t.theme.boxShadow:void 0,replacementName:"cardStyle.boxShadow",replacementValue:t.cardStyle?.boxShadow,applyDeprecated:()=>{}}].filter(r=>!!r.value).forEach(r=>{r.replacementValue?console.warn(`Both ${r.name} and ${r.replacementName} have been set. ${r.name} will be ignored.`):(console.warn(`${r.name} is deprecated. Use ${r.replacementName} instead.`),r.applyDeprecated())}),n&&e.style.setProperty(W,n)}function Ne(e){return new URL(e.src).origin}function G(e,t,n,o){const r=!!o,i=q(n),f=ee(n).toString(),{theme:E,hooks:c,rootStyle:l,...s}=n;p.postMessageToWindow(e,T.UPDATE_PARAMS,{urlParams:{pathname:i,search:f},appParams:s,hasProvider:r},t)}function Ue(e,t,n){return p.listenToMessageFromWindow(window,e,w.ACTIVATE,()=>{p.postMessageToWindow(e,T.UPDATE_APP_DATA,{metaData:n?{appCode:n}:void 0},t)},t)}function He(e,t,n){let o=!1;return p.listenToMessageFromWindow(window,e,w.READY,()=>{o||(o=!0,n())},t)}function Fe(e,t){return p.listenToMessageFromWindow(window,t,w.INTERCEPT_WINDOW_OPEN,({href:n,rel:o,target:r})=>{const i=xe(n.toString(),e);i&&se(i)&&window.open(i,r,o)},e)}function xe(e,t){const n=e.trim();if(!n)return null;try{return new URL(n,t).toString()}catch{return null}}const W="--dynamicHeight",Be=0;function ke(e,t,n,o){return t.contentWindow?[p.listenToMessageFromWindow(window,t.contentWindow,w.UPDATE_HEIGHT,r=>{const i=`${(r?.height??0)+Be}px`;e.style.setProperty(W,i),o(i)},n),p.listenToMessageFromWindow(window,t.contentWindow,w.SET_FULL_HEIGHT,()=>{e.style.setProperty(W,"100dvh"),o("100dvh")},n)]:[]}const Me={[_.ON_BEFORE_APPROVAL]:(e,t)=>t?.onBeforeApproval?t.onBeforeApproval(e):!0,[_.ON_BEFORE_TRADE]:(e,t)=>t?.onBeforeTrade?t.onBeforeTrade(e):!0,[_.ON_BEFORE_WRAP_UNWRAP]:(e,t)=>t?.onBeforeWrapOrUnwrap?t.onBeforeWrapOrUnwrap(e):!0,[_.ON_BEFORE_ORDER_CANCEL]:(e,t)=>t?.onBeforeOrderCancel?t.onBeforeOrderCancel(e):!0,[_.ON_BEFORE_ORDERS_CANCEL]:(e,t)=>t?.onBeforeOrdersCancel?t.onBeforeOrdersCancel(e):!0};function Ve(e,t){return Me[e.event](e.payload,t)}function $e(e,t,n){return p.listenToMessageFromWindow(window,e,w.PROCESS_HOOK,async o=>{let r=!1;try{r=await Ve(o,n)}catch{}p.postMessageToWindow(e,T.HOOK_RESULT,{id:o.id,result:r},t)},t)}const Ge=Object.values(L);function je(e,t,n){if(O(e)){const o=e[n];return S(o)?o[t]:o}if(S(e)){const o=e[t];return O(o)?o[n]:o}return e}function O(e){return typeof e!="object"?!1:Object.keys(e).every(t=>Ge.includes(t))}const Ke=/^\d+$/;function S(e){return typeof e!="object"?!1:Object.keys(e).every(t=>Ke.test(t))}function Ye(e){return O(e)?Object.values(e).flatMap(t=>S(t)?Object.values(t):[t]):S(e)?Object.values(e).flatMap(t=>O(t)?Object.values(t):[t]):[e]}exports.SHOULD_THROW_IF_INVALID_URL=J;exports.TradeType=L;exports.WIDGET_CONTAINER_ID=le;exports.WIDGET_IFRAME_ALLOW=z;exports.WIDGET_IFRAME_ID=K;exports.WIDGET_IFRAME_REFERRER_POLICY=Q;exports.WIDGET_IFRAME_SANDBOX=Y;exports.WIDGET_PALETTE_COLORS=ce;exports.WidgetHookEvents=_;exports.WidgetMethodsEmit=w;exports.WidgetMethodsListen=T;exports.createCowSwapWidget=De;exports.isCowSwapWidgetPalette=D;exports.isPerNetworkConfig=S;exports.isPerTradeTypeConfig=O;exports.resolveFlexibleConfig=je;exports.resolveFlexibleConfigValues=Ye;exports.sanitizeWidgetBaseUrl=Z;exports.widgetIframeTransport=p;
package/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  export { createCowSwapWidget } from './cowSwapWidget';
2
- export { WIDGET_IFRAME_ALLOW, WIDGET_IFRAME_REFERRER_POLICY, WIDGET_IFRAME_SANDBOX } from './cowSwapWidget.constants';
2
+ export { WIDGET_CONTAINER_ID, WIDGET_IFRAME_ALLOW, WIDGET_IFRAME_ID, WIDGET_IFRAME_REFERRER_POLICY, WIDGET_IFRAME_SANDBOX, } from './cowSwapWidget.constants';
3
3
  export type { CowSwapWidgetHandler } from './cowSwapWidget';
4
4
  export { resolveFlexibleConfigValues } from './resolveFlexibleConfigValues';
5
5
  export { sanitizeWidgetBaseUrl, SHOULD_THROW_IF_INVALID_URL } from './urlUtils';
package/index.js CHANGED
@@ -1,6 +1,6 @@
1
- import { IframeTransport as k, IframeRpcProviderBridge as x } from "@cowprotocol/iframe-transport";
2
- import { SimpleCowEventEmitter as M } from "@cowprotocol/events";
3
- const V = /* @__PURE__ */ new Set([
1
+ import { IframeTransport as X, IframeRpcProviderBridge as J } from "@cowprotocol/iframe-transport";
2
+ import { SimpleCowEventEmitter as Z } from "@cowprotocol/events";
3
+ const q = /* @__PURE__ */ new Set([
4
4
  "wc:",
5
5
  // default Wallet-connect protocol
6
6
  "metamask:",
@@ -27,27 +27,41 @@ const V = /* @__PURE__ */ new Set([
27
27
  "tpoutside:",
28
28
  "bncus:",
29
29
  "bnc:"
30
- ]), $ = /* @__PURE__ */ new Set(["http:", "https:"]);
31
- function G(e) {
30
+ ]), ee = /* @__PURE__ */ new Set(["http:", "https:"]);
31
+ function te(e) {
32
32
  try {
33
33
  const t = new URL(e).protocol;
34
- return $.has(t) || V.has(t);
34
+ return ee.has(t) || q.has(t);
35
35
  } catch {
36
36
  return !1;
37
37
  }
38
38
  }
39
- const j = "allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox", K = "strict-origin-when-cross-origin", Q = "clipboard-read; clipboard-write";
40
- var w = /* @__PURE__ */ ((e) => (e.ACTIVATE = "ACTIVATE", e.READY = "READY", 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.PROCESS_HOOK = "PROCESS_HOOK", e))(w || {}), A = /* @__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.HOOK_RESULT = "HOOK_RESULT", e))(A || {}), _ = /* @__PURE__ */ ((e) => (e.ON_BEFORE_APPROVAL = "ON_BEFORE_APPROVAL", e.ON_BEFORE_TRADE = "ON_BEFORE_TRADE", e.ON_BEFORE_WRAP_UNWRAP = "ON_BEFORE_WRAP_UNWRAP", e.ON_BEFORE_ORDER_CANCEL = "ON_BEFORE_ORDER_CANCEL", e.ON_BEFORE_ORDERS_CANCEL = "ON_BEFORE_ORDERS_CANCEL", e))(_ || {}), I = /* @__PURE__ */ ((e) => (e.SWAP = "swap", e.LIMIT = "limit", e.ADVANCED = "advanced", e.YIELD = "yield", e))(I || {});
41
- const Ne = ["primary", "background", "paper", "text", "danger", "warning", "alert", "info", "success"], c = new k("cowSwapWidget");
42
- class Y {
39
+ function ne(e, t) {
40
+ if (t) {
41
+ e.removeAttribute("style");
42
+ for (const n of Object.keys(t)) {
43
+ const o = n, r = t[o];
44
+ if (r == null || typeof r != "string" && typeof r != "number")
45
+ continue;
46
+ const i = `${r}`;
47
+ e.style[o] = i;
48
+ }
49
+ }
50
+ }
51
+ const oe = "cowswap-widget-iframe", Ke = "cowswap-widget", re = {
52
+ appCode: ""
53
+ }, ie = "allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox", se = "strict-origin-when-cross-origin", ae = "clipboard-read; clipboard-write";
54
+ var h = /* @__PURE__ */ ((e) => (e.ACTIVATE = "ACTIVATE", e.READY = "READY", 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.PROCESS_HOOK = "PROCESS_HOOK", e))(h || {}), A = /* @__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.HOOK_RESULT = "HOOK_RESULT", e))(A || {}), g = /* @__PURE__ */ ((e) => (e.ON_BEFORE_APPROVAL = "ON_BEFORE_APPROVAL", e.ON_BEFORE_TRADE = "ON_BEFORE_TRADE", e.ON_BEFORE_WRAP_UNWRAP = "ON_BEFORE_WRAP_UNWRAP", e.ON_BEFORE_ORDER_CANCEL = "ON_BEFORE_ORDER_CANCEL", e.ON_BEFORE_ORDERS_CANCEL = "ON_BEFORE_ORDERS_CANCEL", e))(g || {}), b = /* @__PURE__ */ ((e) => (e.SWAP = "swap", e.LIMIT = "limit", e.ADVANCED = "advanced", e.YIELD = "yield", e))(b || {});
55
+ const Ye = ["primary", "background", "paper", "text", "danger", "warning", "alert", "info", "success"], p = new X("cowSwapWidget");
56
+ class le {
43
57
  constructor(t, n, o, r = []) {
44
- this.contentWindow = t, this.updateListeners(r), this.widgetListener = c.listenToMessageFromWindow(this.contentWindow, o, w.EMIT_COW_EVENT, (i) => this.eventEmitter.emit(i.event, i.payload), n);
58
+ this.contentWindow = t, this.updateListeners(r), this.widgetListener = p.listenToMessageFromWindow(this.contentWindow, o, h.EMIT_COW_EVENT, (i) => this.eventEmitter.emit(i.event, i.payload), n);
45
59
  }
46
- eventEmitter = new M();
60
+ eventEmitter = new Z();
47
61
  listeners = [];
48
62
  widgetListener;
49
63
  stopListeningIframe() {
50
- c.stopListeningWindowListener(this.contentWindow, this.widgetListener);
64
+ p.stopListeningWindowListener(this.contentWindow, this.widgetListener);
51
65
  }
52
66
  updateListeners(t) {
53
67
  for (const n of this.listeners)
@@ -57,10 +71,10 @@ class Y {
57
71
  this.eventEmitter.on(n);
58
72
  }
59
73
  }
60
- class z {
74
+ class de {
61
75
  constructor(t, n) {
62
76
  this.appWindow = t, this.iframeWidow = n, this.forwardSdkMessage = (o) => {
63
- X(o.data) && (typeof window < "u" && o.origin === window.location.origin || (J(o.data) ? this.appWindow.parent.postMessage(o.data, "*") : Z(o.data) && this.iframeWidow.postMessage(o.data, "*")));
77
+ ce(o.data) && (typeof window < "u" && o.origin === window.location.origin || (ue(o.data) ? this.appWindow.parent.postMessage(o.data, "*") : pe(o.data) && this.iframeWidow.postMessage(o.data, "*")));
64
78
  }, this.startListening();
65
79
  }
66
80
  forwardSdkMessage;
@@ -71,180 +85,180 @@ class z {
71
85
  this.appWindow.removeEventListener("message", this.forwardSdkMessage);
72
86
  }
73
87
  }
74
- function X(e) {
88
+ function ce(e) {
75
89
  return typeof e == "object" && e !== null && "id" in e && typeof e.id == "string";
76
90
  }
77
- function J(e) {
91
+ function ue(e) {
78
92
  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;
79
93
  }
80
- function Z(e) {
94
+ function pe(e) {
81
95
  return "success" in e && typeof e.success == "boolean" && "version" in e && typeof e.version == "string";
82
96
  }
83
- function q(e = "Default", t = "#1c5dbf", ...n) {
97
+ function fe(e = "Default", t = "#1c5dbf", ...n) {
84
98
  console.debug(`%c [COW][${e}]`, `font-weight: bold; color: ${t}`, ...n);
85
99
  }
86
- function ee(...e) {
87
- process.env.NODE_ENV !== "test" && q("Widget", "#47aba8", ...e);
100
+ function Ee(...e) {
101
+ process.env.NODE_ENV !== "test" && fe("Widget", "#47aba8", ...e);
88
102
  }
89
- const y = "https://swap.cow.fi";
90
- function te(e) {
103
+ function G(e) {
91
104
  return !!(e && typeof e == "object");
92
105
  }
93
- const v = "_", ne = "CoW Swap widget: invalid baseUrl.", oe = !1;
94
- function re(e) {
106
+ const j = "https://swap.cow.fi", x = "_", we = "CoW Swap widget: invalid baseUrl.", he = !1;
107
+ function me(e) {
95
108
  return e === "localhost" || e === "127.0.0.1" || e === "::1" || e.endsWith(".localhost");
96
109
  }
97
- function C(e, t) {
98
- const n = `${ne} ${e}`;
110
+ function v(e, t) {
111
+ const n = `${we} ${e}`;
99
112
  if (t)
100
113
  throw new Error(n);
101
- return console.error("[CoW Widget]", n), y;
114
+ return console.error("[CoW Widget]", n), j;
102
115
  }
103
- function ie(e, t = oe) {
116
+ function ge(e, t = he) {
104
117
  const n = typeof e == "string" ? e.trim() : "";
105
118
  if (!n)
106
- return y;
119
+ return j;
107
120
  let o;
108
121
  try {
109
122
  o = new URL(n);
110
123
  } catch {
111
- return C(`Not a valid URL: ${JSON.stringify(n)}`, t);
124
+ return v(`Not a valid URL: ${JSON.stringify(n)}`, t);
112
125
  }
113
126
  if (o.username || o.password)
114
- return C("Userinfo (username/password) in URL is not allowed.", t);
115
- const r = o.protocol === "https:", i = o.protocol === "http:" && re(o.hostname);
127
+ return v("Userinfo (username/password) in URL is not allowed.", t);
128
+ const r = o.protocol === "https:", i = o.protocol === "http:" && me(o.hostname);
116
129
  if (!r && !i)
117
- return C(`Use https, or http only on localhost / 127.0.0.1 / ::1 / *.localhost (got ${o.protocol}//${o.hostname}).`, t);
118
- const u = o.pathname === "/" || o.pathname === "" ? "" : o.pathname.replace(/\/+$/, "");
119
- return `${o.origin}${u}`;
130
+ return v(`Use https, or http only on localhost / 127.0.0.1 / ::1 / *.localhost (got ${o.protocol}//${o.hostname}).`, t);
131
+ const f = o.pathname === "/" || o.pathname === "" ? "" : o.pathname.replace(/\/+$/, "");
132
+ return `${o.origin}${f}`;
120
133
  }
121
- function se(e) {
122
- const t = ie(e.baseUrl), n = U(e);
123
- return t + "/#" + n + "?" + B(e);
134
+ function _e(e) {
135
+ const t = ge(e.baseUrl), n = K(e);
136
+ return t + "/#" + n + "?" + Y(e);
124
137
  }
125
- function U(e) {
138
+ function K(e) {
126
139
  const {
127
140
  chainId: t = 1,
128
141
  sell: n,
129
142
  buy: o,
130
- tradeType: r = I.SWAP
131
- } = e, i = [n?.asset || v, o?.asset || v].map(encodeURIComponent).join("/");
143
+ tradeType: r = b.SWAP
144
+ } = e, i = [n?.asset || x, o?.asset || x].map(encodeURIComponent).join("/");
132
145
  return `/${t}/widget/${r}/${i}`;
133
146
  }
134
- function B(e) {
147
+ function Y(e) {
135
148
  const t = new URLSearchParams();
136
- return ue(ce(le(de(ae(t, e), e), e), e), e);
149
+ return Te(ye(Se(Oe(Re(t, e), e), e), e), e);
137
150
  }
138
- function ae(e, t) {
151
+ function Re(e, t) {
139
152
  const {
140
153
  sell: n,
141
154
  buy: o
142
155
  } = t;
143
156
  return n?.amount && e.append("sellAmount", n.amount), o?.amount && e.append("buyAmount", o.amount), e;
144
157
  }
145
- function de(e, t) {
158
+ function Oe(e, t) {
146
159
  const n = t.theme;
147
- return n ? (te(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);
160
+ return n ? (G(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);
148
161
  }
149
- function le(e, t) {
162
+ function Se(e, t) {
150
163
  return t.targetChainId && e.append("targetChainId", t.targetChainId.toString()), e;
151
164
  }
152
- function ce(e, t) {
165
+ function ye(e, t) {
153
166
  return t.locale && e.append("lng", t.locale), e;
154
167
  }
155
- function ue(e, t) {
156
- return pe(t.hooks) ? e.append("hooksEnabled", "true") : e.delete("hooksEnabled"), e;
168
+ function Te(e, t) {
169
+ return Ae(t.hooks) ? e.append("hooksEnabled", "true") : e.delete("hooksEnabled"), e;
157
170
  }
158
- function pe(e) {
171
+ function Ae(e) {
159
172
  return !!e && Object.values(e).some(Boolean);
160
173
  }
161
- const fe = 3e4, T = "coWWidgetContentReloadButton";
162
- function Ee(e, t, n) {
163
- const o = e.src;
164
- let r = !1, i = !1, u;
165
- function f() {
166
- e.srcdoc = we, t?.();
174
+ const Le = 3e4, w = "cow-widget-loading-error", B = `data-${w}`;
175
+ function Ce(e, t, n, o, r) {
176
+ const i = t.src;
177
+ let f = !1, E = null;
178
+ function c() {
179
+ r?.(), t.style.display = "none", Pe();
180
+ const l = document.createElement("div"), s = document.createElement("button"), d = document.createElement("p");
181
+ s.innerText = "Reload", s.addEventListener("click", () => {
182
+ e.removeChild(l), o(!0), t.src = "about:blank", t.style.display = "", setTimeout(() => {
183
+ t.src = i, n();
184
+ }, 100);
185
+ }), d.innerText = "Couldn't load the page. Please, try again later", l.classList.add(w), l.appendChild(d), l.appendChild(s), e.appendChild(l);
167
186
  }
168
- function p() {
169
- clearTimeout(u), u = setTimeout(() => {
170
- r || i || f();
171
- }, fe);
172
- }
173
- function s() {
174
- r || i || (e.removeAttribute("srcdoc"), e.src = o, p());
175
- }
176
- function a() {
177
- if (r) return;
178
- const d = e.contentDocument, O = d?.querySelector(`.${T}`);
179
- if (!(!d || !O) && (O.addEventListener("click", s), n)) {
180
- const R = d.createElement("style");
181
- R.textContent = n, d.head.appendChild(R);
182
- }
183
- }
184
- return e.addEventListener("error", (d) => {
185
- r || (console.error("Could not load iframe", d), f());
186
- }), e.addEventListener("load", a), p(), {
187
- cancelWidgetLoading() {
188
- r = !0, clearTimeout(u), e.removeEventListener("load", a);
189
- },
187
+ return t.addEventListener("error", (l) => {
188
+ f || (console.error("Could not load iframe", l), c());
189
+ }), E = window.setTimeout(() => {
190
+ f || c();
191
+ }, Le), {
190
192
  onWidgetReady() {
191
- i = !0, clearTimeout(u);
193
+ E && clearTimeout(E);
194
+ const l = document.getElementsByClassName(w)[0];
195
+ l && e.removeChild(l);
196
+ },
197
+ cancelWidgetLoading() {
198
+ f = !0;
192
199
  }
193
200
  };
194
201
  }
195
- const we = `<!DOCTYPE html>
196
- <html lang="en">
197
- <head>
198
- <style>
199
- html, body { margin: 0; padding: 0; width: 100%; height: 100%; }
200
- .errorContent {
201
- display: flex;
202
- flex-direction: column;
203
- gap: 16px;
204
- align-items: center;
205
- justify-content: center;
206
- text-align: center;
207
-
208
- width: 100%;
209
- height: 100%;
210
-
211
- padding: 24px;
212
- box-sizing: border-box;
202
+ let R = null;
203
+ function Pe() {
204
+ if (!(typeof document > "u")) {
205
+ if (ve()) {
206
+ R || (R = new CSSStyleSheet(), R.replaceSync(k)), document.adoptedStyleSheets.includes(R) || (document.adoptedStyleSheets = [...document.adoptedStyleSheets, R]);
207
+ return;
208
+ }
209
+ if (!document.head.querySelector(`style[${B}]`)) {
210
+ const e = document.createElement("style");
211
+ e.setAttribute(B, ""), e.textContent = k, document.head.appendChild(e);
212
+ }
213
+ }
214
+ }
215
+ function ve() {
216
+ return typeof document < "u" && "adoptedStyleSheets" in Document.prototype && typeof CSSStyleSheet == "function" && typeof CSSStyleSheet.prototype.replaceSync == "function";
217
+ }
218
+ const k = `
219
+ .${w} {
220
+ display: flex;
221
+ flex-direction: column;
222
+ gap: 16px;
223
+ align-items: center;
224
+ justify-content: center;
225
+ text-align: center;
226
+ box-sizing: border-box;
227
+ width: 100%;
228
+ height: 100%;
229
+ min-height: 200px;
230
+ padding: 24px;
231
+ background: #fff5f5;
232
+ color: #d32f2f;
233
+ font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
234
+ font-size: 14px;
235
+ line-height: 1.5;
236
+ font-weight: 500;
237
+ }
213
238
 
214
- background: #fff5f5;
215
- color: #d32f2f;
239
+ .${w} p {
240
+ margin: 0;
241
+ }
216
242
 
217
- border: 1px solid #f5c2c7;
218
- border-radius: 12px;
243
+ .${w} button {
244
+ padding: 8px 24px;
245
+ border-radius: 8px;
246
+ font: inherit;
247
+ cursor: pointer;
248
+ border: 1px solid #d32f2f;
249
+ background: transparent;
250
+ color: #d32f2f;
251
+ }
219
252
 
220
- font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
221
- font-size: 14px;
222
- line-height: 1.5;
223
- font-weight: 500;
224
- }
225
- .${T} {
226
- padding: 8px 24px;
227
- border: 1px solid #d32f2f;
228
- border-radius: 8px;
229
- background: transparent;
230
- color: #d32f2f;
231
- font: inherit;
232
- cursor: pointer;
233
- }
234
- .${T}:hover {
235
- background: #d32f2f;
236
- color: #fff5f5;
237
- }
238
- </style>
239
- </head>
240
- <body>
241
- <div class="errorContent">
242
- <span>Couldn't load the widget. Please try again later.</span>
253
+ .${w} button:disabled {
254
+ cursor: progress;
255
+ opacity: 0.75;
256
+ }
243
257
 
244
- <button class="${T}">Retry</button>
245
- </div>
246
- </body>
247
- </html>`, F = "640px", _e = "450px", Oe = 20, Re = {
258
+ .${w} button:not(:disabled):hover {
259
+ background: #d32f2f;
260
+ color: #fff5f5;
261
+ }`, Ie = {
248
262
  iframe: null,
249
263
  updateParams: () => {
250
264
  },
@@ -255,118 +269,154 @@ const we = `<!DOCTYPE html>
255
269
  destroy: () => {
256
270
  }
257
271
  };
258
- function ye(e, t) {
272
+ function Qe(e, t) {
259
273
  const {
260
274
  params: n,
261
275
  provider: o,
262
276
  listeners: r,
263
277
  onReady: i,
264
- enableSafeSdkBridge: u = !0
278
+ enableSafeSdkBridge: f = !0
265
279
  } = t;
266
- let f = o, p = n;
267
- if (typeof window > "u") return Re;
268
- const s = he(n), a = ge(s);
269
- ee("Resolved trusted iframe origin", {
270
- iframeOrigin: a
280
+ let E = o, c = F(n), l = "";
281
+ if (typeof window > "u") return Ie;
282
+ const s = be(c), d = De(s);
283
+ Ee("Resolved trusted iframe origin", {
284
+ iframeOrigin: d
271
285
  });
272
- const d = [];
273
- e.innerHTML = "", e.appendChild(s);
274
- const {
275
- cancelWidgetLoading: O,
276
- onWidgetReady: R
277
- } = Ee(s, t.onLoadingError, t.loadingErrorStyles), {
278
- contentWindow: l
279
- } = s;
280
- if (!l)
281
- throw console.error("Iframe does not contain a window", s), new Error("Iframe does not contain a window!");
282
- d.push(me(l, a, () => {
283
- i?.(), R();
284
- })), d.push(Te(l, a, n.appCode)), d.push(...Pe(s, a, n.height, n.maxHeight));
285
- let h = null;
286
- function S() {
287
- l && (h && window.removeEventListener("message", h), !p.disableWindowOpen && (h = Le(a, l), d.push(h)));
286
+ const O = [];
287
+ e.innerHTML = "", e.appendChild(s), M(e, c);
288
+ let a = null, L = () => {
289
+ }, C = () => {
290
+ }, D = () => {
291
+ }, P = null, S = null, N = null, W = [], _ = null;
292
+ function U() {
293
+ if (a = s.contentWindow, !a)
294
+ throw console.error("Iframe does not contain a window", s), new Error("Iframe does not contain a window!");
295
+ O.push(We(a, d, () => {
296
+ i?.(), Q();
297
+ })), O.push(Ne(a, d, c.appCode)), W = Be(e, s, d, (z) => {
298
+ l = z;
299
+ });
300
+ let u = null;
301
+ L = () => {
302
+ a && (u && window.removeEventListener("message", u), !c.disableWindowOpen && (u = Ue(d, a), O.push(u)));
303
+ }, C = () => {
304
+ a && (_ && window.removeEventListener("message", _), _ = Ve(a, d, c.hooks));
305
+ }, L(), C(), P = new le(window, d, a, r), S = V(a, d, null, E), s.addEventListener("load", () => {
306
+ a && $(a, d, c, E);
307
+ }), N = f ? new de(window, a) : null;
308
+ const m = Ce(e, s, U, H, t.onLoadingError);
309
+ D = m.cancelWidgetLoading;
310
+ const Q = m.onWidgetReady;
288
311
  }
289
- let g = null;
290
- function W() {
291
- l && (g && window.removeEventListener("message", g), g = Se(l, a, p.hooks), d.push(g));
312
+ function H(u = !1) {
313
+ S?.disconnect(), P?.stopListeningIframe(), W.forEach((m) => window.removeEventListener("message", m)), O.forEach((m) => window.removeEventListener("message", m)), _ && window.removeEventListener("message", _), N?.stopListening(), !u && s && s.parentNode === e && e.removeChild(s), D?.();
292
314
  }
293
- S(), W();
294
- const D = new Y(window, a, l, r);
295
- let P = b(l, a, null, f);
296
- s.addEventListener("load", () => {
297
- N(l, a, p, f);
298
- });
299
- const H = u ? new z(window, l) : null;
300
- return {
315
+ return U(), {
301
316
  iframe: s,
302
- updateParams: (E) => {
303
- p = E, N(l, a, p, f), S(), W();
317
+ updateParams: (u) => {
318
+ a && (c = F(u), M(e, c, l), $(a, d, c, E), L(), C());
304
319
  },
305
- updateListeners: (E) => D.updateListeners(E),
306
- updateProvider: (E) => {
307
- f = E, P = b(l, a, P, E);
320
+ updateListeners: (u) => P?.updateListeners(u),
321
+ updateProvider: (u) => {
322
+ a && (E = u, S = V(a, d, S, u));
308
323
  },
309
- destroy: () => {
310
- P.disconnect(), D.stopListeningIframe(), d.forEach((E) => window.removeEventListener("message", E)), H?.stopListening(), s && s.parentNode === e && e.removeChild(s), O();
311
- }
324
+ destroy: H
312
325
  };
313
326
  }
314
- function b(e, t, n, o) {
327
+ function F(e) {
328
+ const t = {
329
+ ...re,
330
+ ...e
331
+ };
332
+ if (typeof t.appCode != "string" || t.appCode.trim().length === 0)
333
+ throw new Error("Required param `appCode` is missing");
334
+ return t;
335
+ }
336
+ function V(e, t, n, o) {
315
337
  n && n.disconnect();
316
- const r = n || new x(e, t);
338
+ const r = n || new J(e, t);
317
339
  return o && r.onConnect(o), r;
318
340
  }
319
- function he(e) {
320
- const {
321
- width: t = _e,
322
- height: n = F
323
- } = e, o = document.createElement("iframe");
324
- return o.src = se(e), o.width = t, o.height = n, o.style.border = "0", o.setAttribute("sandbox", j), o.referrerPolicy = K, o.allow = Q, o;
341
+ function be(e) {
342
+ const t = document.createElement("iframe");
343
+ return t.id = oe, t.src = _e(e), t.setAttribute("sandbox", ie), t.referrerPolicy = se, t.allow = ae, t.style.width = "100%", t.style.height = "100%", t.style.border = "0", t.style.display = "block", t;
344
+ }
345
+ function M(e, t, n) {
346
+ ne(e, t.rootStyle), [{
347
+ name: "params.width",
348
+ value: t.width,
349
+ replacementName: "rootStyle.width",
350
+ replacementValue: t.rootStyle?.width,
351
+ applyDeprecated: () => t.width ? e.style.width = t.width : void 0
352
+ }, {
353
+ name: "params.height",
354
+ value: t.height,
355
+ replacementName: "rootStyle.height",
356
+ replacementValue: t.rootStyle?.height,
357
+ applyDeprecated: () => t.height ? e.style.height = t.height : void 0
358
+ }, {
359
+ name: "params.maxHeight",
360
+ value: t.maxHeight,
361
+ replacementName: "rootStyle.maxHeight",
362
+ replacementValue: t.rootStyle?.maxHeight,
363
+ applyDeprecated: () => t.maxHeight ? e.style.maxHeight = `${t.maxHeight}px` : void 0
364
+ }, {
365
+ name: "params.theme.boxShadow",
366
+ value: G(t.theme) ? t.theme.boxShadow : void 0,
367
+ replacementName: "cardStyle.boxShadow",
368
+ replacementValue: t.cardStyle?.boxShadow,
369
+ applyDeprecated: () => {
370
+ }
371
+ }].filter((r) => !!r.value).forEach((r) => {
372
+ r.replacementValue ? console.warn(`Both ${r.name} and ${r.replacementName} have been set. ${r.name} will be ignored.`) : (console.warn(`${r.name} is deprecated. Use ${r.replacementName} instead.`), r.applyDeprecated());
373
+ }), n && e.style.setProperty(I, n);
325
374
  }
326
- function ge(e) {
375
+ function De(e) {
327
376
  return new URL(e.src).origin;
328
377
  }
329
- function N(e, t, n, o) {
330
- const r = !!o, i = U(n), u = B(n).toString(), {
331
- theme: f,
332
- hooks: p,
378
+ function $(e, t, n, o) {
379
+ const r = !!o, i = K(n), f = Y(n).toString(), {
380
+ theme: E,
381
+ hooks: c,
382
+ rootStyle: l,
333
383
  ...s
334
384
  } = n;
335
- c.postMessageToWindow(e, A.UPDATE_PARAMS, {
385
+ p.postMessageToWindow(e, A.UPDATE_PARAMS, {
336
386
  urlParams: {
337
387
  pathname: i,
338
- search: u
388
+ search: f
339
389
  },
340
390
  appParams: s,
341
391
  hasProvider: r
342
392
  }, t);
343
393
  }
344
- function Te(e, t, n) {
345
- return c.listenToMessageFromWindow(window, e, w.ACTIVATE, () => {
346
- c.postMessageToWindow(e, A.UPDATE_APP_DATA, {
394
+ function Ne(e, t, n) {
395
+ return p.listenToMessageFromWindow(window, e, h.ACTIVATE, () => {
396
+ p.postMessageToWindow(e, A.UPDATE_APP_DATA, {
347
397
  metaData: n ? {
348
398
  appCode: n
349
399
  } : void 0
350
400
  }, t);
351
401
  }, t);
352
402
  }
353
- function me(e, t, n) {
403
+ function We(e, t, n) {
354
404
  let o = !1;
355
- return c.listenToMessageFromWindow(window, e, w.READY, () => {
405
+ return p.listenToMessageFromWindow(window, e, h.READY, () => {
356
406
  o || (o = !0, n());
357
407
  }, t);
358
408
  }
359
- function Le(e, t) {
360
- return c.listenToMessageFromWindow(window, t, w.INTERCEPT_WINDOW_OPEN, ({
409
+ function Ue(e, t) {
410
+ return p.listenToMessageFromWindow(window, t, h.INTERCEPT_WINDOW_OPEN, ({
361
411
  href: n,
362
412
  rel: o,
363
413
  target: r
364
414
  }) => {
365
- const i = Ae(n.toString(), e);
366
- i && G(i) && window.open(i, r, o);
415
+ const i = He(n.toString(), e);
416
+ i && te(i) && window.open(i, r, o);
367
417
  }, e);
368
418
  }
369
- function Ae(e, t) {
419
+ function He(e, t) {
370
420
  const n = e.trim();
371
421
  if (!n)
372
422
  return null;
@@ -376,77 +426,78 @@ function Ae(e, t) {
376
426
  return null;
377
427
  }
378
428
  }
379
- function Pe(e, t, n = F, o) {
380
- return e.contentWindow ? [c.listenToMessageFromWindow(window, e.contentWindow, w.UPDATE_HEIGHT, (r) => {
381
- const i = r.height ? r.height + Oe : void 0;
382
- e.style.height = i ? `${o ? Math.min(i, o) : i}px` : n;
383
- }, t), c.listenToMessageFromWindow(window, e.contentWindow, w.SET_FULL_HEIGHT, ({
384
- isUpToSmall: r
385
- }) => {
386
- e.style.height = r ? n : `${o || document.body.offsetHeight}px`;
387
- }, t)] : [];
388
- }
389
- const Ce = {
390
- [_.ON_BEFORE_APPROVAL]: (e, t) => t?.onBeforeApproval ? t.onBeforeApproval(e) : !0,
391
- [_.ON_BEFORE_TRADE]: (e, t) => t?.onBeforeTrade ? t.onBeforeTrade(e) : !0,
392
- [_.ON_BEFORE_WRAP_UNWRAP]: (e, t) => t?.onBeforeWrapOrUnwrap ? t.onBeforeWrapOrUnwrap(e) : !0,
393
- [_.ON_BEFORE_ORDER_CANCEL]: (e, t) => t?.onBeforeOrderCancel ? t.onBeforeOrderCancel(e) : !0,
394
- [_.ON_BEFORE_ORDERS_CANCEL]: (e, t) => t?.onBeforeOrdersCancel ? t.onBeforeOrdersCancel(e) : !0
429
+ const I = "--dynamicHeight", xe = 0;
430
+ function Be(e, t, n, o) {
431
+ return t.contentWindow ? [p.listenToMessageFromWindow(window, t.contentWindow, h.UPDATE_HEIGHT, (r) => {
432
+ const i = `${(r?.height ?? 0) + xe}px`;
433
+ e.style.setProperty(I, i), o(i);
434
+ }, n), p.listenToMessageFromWindow(window, t.contentWindow, h.SET_FULL_HEIGHT, () => {
435
+ e.style.setProperty(I, "100dvh"), o("100dvh");
436
+ }, n)] : [];
437
+ }
438
+ const ke = {
439
+ [g.ON_BEFORE_APPROVAL]: (e, t) => t?.onBeforeApproval ? t.onBeforeApproval(e) : !0,
440
+ [g.ON_BEFORE_TRADE]: (e, t) => t?.onBeforeTrade ? t.onBeforeTrade(e) : !0,
441
+ [g.ON_BEFORE_WRAP_UNWRAP]: (e, t) => t?.onBeforeWrapOrUnwrap ? t.onBeforeWrapOrUnwrap(e) : !0,
442
+ [g.ON_BEFORE_ORDER_CANCEL]: (e, t) => t?.onBeforeOrderCancel ? t.onBeforeOrderCancel(e) : !0,
443
+ [g.ON_BEFORE_ORDERS_CANCEL]: (e, t) => t?.onBeforeOrdersCancel ? t.onBeforeOrdersCancel(e) : !0
395
444
  };
396
- function Ie(e, t) {
397
- return Ce[e.event](e.payload, t);
445
+ function Fe(e, t) {
446
+ return ke[e.event](e.payload, t);
398
447
  }
399
- function Se(e, t, n) {
400
- return c.listenToMessageFromWindow(window, e, w.PROCESS_HOOK, async (o) => {
448
+ function Ve(e, t, n) {
449
+ return p.listenToMessageFromWindow(window, e, h.PROCESS_HOOK, async (o) => {
401
450
  let r = !1;
402
451
  try {
403
- r = await Ie(o, n);
452
+ r = await Fe(o, n);
404
453
  } catch {
405
454
  }
406
- c.postMessageToWindow(e, A.HOOK_RESULT, {
455
+ p.postMessageToWindow(e, A.HOOK_RESULT, {
407
456
  id: o.id,
408
457
  result: r
409
458
  }, t);
410
459
  }, t);
411
460
  }
412
- const We = Object.values(I);
413
- function Ue(e, t, n) {
414
- if (m(e)) {
461
+ const Me = Object.values(b);
462
+ function ze(e, t, n) {
463
+ if (y(e)) {
415
464
  const o = e[n];
416
- return L(o) ? o[t] : o;
465
+ return T(o) ? o[t] : o;
417
466
  }
418
- if (L(e)) {
467
+ if (T(e)) {
419
468
  const o = e[t];
420
- return m(o) ? o[n] : o;
469
+ return y(o) ? o[n] : o;
421
470
  }
422
471
  return e;
423
472
  }
424
- function m(e) {
425
- return typeof e != "object" ? !1 : Object.keys(e).every((t) => We.includes(t));
473
+ function y(e) {
474
+ return typeof e != "object" ? !1 : Object.keys(e).every((t) => Me.includes(t));
426
475
  }
427
- const De = /^\d+$/;
428
- function L(e) {
429
- return typeof e != "object" ? !1 : Object.keys(e).every((t) => De.test(t));
476
+ const $e = /^\d+$/;
477
+ function T(e) {
478
+ return typeof e != "object" ? !1 : Object.keys(e).every((t) => $e.test(t));
430
479
  }
431
- function Be(e) {
432
- return m(e) ? Object.values(e).flatMap((t) => L(t) ? Object.values(t) : [t]) : L(e) ? Object.values(e).flatMap((t) => m(t) ? Object.values(t) : [t]) : [e];
480
+ function Xe(e) {
481
+ return y(e) ? Object.values(e).flatMap((t) => T(t) ? Object.values(t) : [t]) : T(e) ? Object.values(e).flatMap((t) => y(t) ? Object.values(t) : [t]) : [e];
433
482
  }
434
483
  export {
435
- oe as SHOULD_THROW_IF_INVALID_URL,
436
- I as TradeType,
437
- Q as WIDGET_IFRAME_ALLOW,
438
- K as WIDGET_IFRAME_REFERRER_POLICY,
439
- j as WIDGET_IFRAME_SANDBOX,
440
- Ne as WIDGET_PALETTE_COLORS,
441
- _ as WidgetHookEvents,
442
- w as WidgetMethodsEmit,
484
+ he as SHOULD_THROW_IF_INVALID_URL,
485
+ b as TradeType,
486
+ Ke as WIDGET_CONTAINER_ID,
487
+ ae as WIDGET_IFRAME_ALLOW,
488
+ oe as WIDGET_IFRAME_ID,
489
+ se as WIDGET_IFRAME_REFERRER_POLICY,
490
+ ie as WIDGET_IFRAME_SANDBOX,
491
+ Ye as WIDGET_PALETTE_COLORS,
492
+ g as WidgetHookEvents,
493
+ h as WidgetMethodsEmit,
443
494
  A as WidgetMethodsListen,
444
- ye as createCowSwapWidget,
445
- te as isCowSwapWidgetPalette,
446
- L as isPerNetworkConfig,
447
- m as isPerTradeTypeConfig,
448
- Ue as resolveFlexibleConfig,
449
- Be as resolveFlexibleConfigValues,
450
- ie as sanitizeWidgetBaseUrl,
451
- c as widgetIframeTransport
495
+ Qe as createCowSwapWidget,
496
+ G as isCowSwapWidgetPalette,
497
+ T as isPerNetworkConfig,
498
+ y as isPerTradeTypeConfig,
499
+ ze as resolveFlexibleConfig,
500
+ Xe as resolveFlexibleConfigValues,
501
+ ge as sanitizeWidgetBaseUrl,
502
+ p as widgetIframeTransport
452
503
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cowprotocol/widget-lib",
3
- "version": "4.3.1",
3
+ "version": "4.4.0",
4
4
  "description": "CoW Swap Widget Library. Allows you to easily embed a CoW Swap widget on your website.",
5
5
  "repository": {
6
6
  "type": "git",
@@ -19,6 +19,9 @@
19
19
  "@cowprotocol/events": "^4.7.1",
20
20
  "@cowprotocol/iframe-transport": "^2.3.2"
21
21
  },
22
+ "devDependencies": {
23
+ "csstype": "3.1.3"
24
+ },
22
25
  "exports": {
23
26
  ".": {
24
27
  "types": "./index.d.ts",
package/types.d.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import { EnrichedOrder, SupportedChainId } from '@cowprotocol/cow-sdk';
2
2
  import { CowWidgetEventListeners, CowWidgetEventPayloadMap, CowWidgetEvents, OnTradeParamsPayload } from '@cowprotocol/events';
3
+ import type * as CSS from 'csstype';
3
4
  export type { SupportedChainId } from '@cowprotocol/cow-sdk';
4
5
  export type { OnTradeParamsPayload } from '@cowprotocol/events';
5
6
  export type PerTradeTypeConfig<T> = Partial<Record<TradeType, T>>;
@@ -76,11 +77,6 @@ export interface CowSwapWidgetProps {
76
77
  listeners?: CowWidgetEventListeners;
77
78
  onReady?(): void;
78
79
  onLoadingError?(): void;
79
- /**
80
- * Custom CSS appended to the error document displayed inside the iframe when the widget fails to load.
81
- * Use it to override the default look (`.errorContent` and `.reloadButton` classes).
82
- */
83
- loadingErrorStyles?: string;
84
80
  enableSafeSdkBridge?: boolean;
85
81
  }
86
82
  export interface JsonRpcRequest {
@@ -163,6 +159,8 @@ export type CowSwapWidgetPalette = {
163
159
  /**
164
160
  * Overrides the main widget card shadow.
165
161
  * Accepts any valid CSS box-shadow value, for example `none` or `0 12px 24px rgba(0, 0, 0, 0.12)`.
162
+ *
163
+ * @deprecated Use cardStyle.boxShadow instead.
166
164
  */
167
165
  boxShadow?: string;
168
166
  } & CowSwapWidgetPaletteParams;
@@ -210,17 +208,39 @@ export interface CowSwapWidgetParams {
210
208
  */
211
209
  appCode: string;
212
210
  /**
213
- * The width of the widget in pixels. Default: 400px
211
+ * The width of the outer iframe element. Accepts CSS width values such as `450px` or `100%`.
212
+ * Default: `450px`
213
+ *
214
+ * @deprecated Use rootStyle.width instead.
214
215
  */
215
216
  width?: string;
216
217
  /**
217
- * The height of the widget in pixels. Default: 600px
218
+ * The height of the outer iframe element. Accepts CSS height values such as `640px`.
219
+ * Default: `640px`
220
+ *
221
+ * @deprecated Use rootStyle.height instead.
218
222
  */
219
223
  height?: string;
220
224
  /**
221
225
  * The maximum height of the widget in pixels. Default: body.offsetHeight
226
+ *
227
+ * @deprecated Use rootStyle.maxHeight instead.
222
228
  */
223
229
  maxHeight?: number;
230
+ /**
231
+ * Extra inline styles for the outer container element (host page only; not sent into the iframe app).
232
+ * Applied after width/height attributes. Use e.g. `backgroundColor`, `borderRadius`, `boxShadow`, `border`.
233
+ * The injected iframe fills this container. Use `height: 'var(--dynamicHeight)'` here for dynamic height.
234
+ */
235
+ rootStyle?: CSS.Properties;
236
+ /**
237
+ * Inline styles for the body wrapper (inside the iframe).
238
+ */
239
+ bodyWrapperStyle?: CSS.Properties;
240
+ /**
241
+ * Inline styles for the main trade widget card (inside the iframe).
242
+ */
243
+ cardStyle?: CSS.Properties;
224
244
  /**
225
245
  * Network ID.
226
246
  */
@@ -351,6 +371,17 @@ export interface CowSwapWidgetParams {
351
371
  * Defaults to false.
352
372
  */
353
373
  disableProgressBar?: boolean;
374
+ /**
375
+ * Disabled switching tokens places by clicking to the arrow between them
376
+ */
377
+ disableSwitchingTokens?: boolean;
378
+ /**
379
+ * Hides scrollbars inside the widget iframe (`overflow: hidden` on the document).
380
+ * Only use when the host iframe height is driven by `var(--dynamicHeight)` and not constrained (e.g. no max-height).
381
+ *
382
+ * Defaults to false.
383
+ */
384
+ disableScrollbars?: boolean;
354
385
  /**
355
386
  * Disables CoW Swap educational tips shown after a trade completes when no surplus message is available.
356
387
  * Defaults to false.
@@ -441,7 +472,7 @@ export interface WidgetMethodsEmitPayloadMap {
441
472
  [WidgetMethodsEmit.READY]: void;
442
473
  [WidgetMethodsEmit.EMIT_COW_EVENT]: EmitCowEventPayload<CowWidgetEvents>;
443
474
  [WidgetMethodsEmit.UPDATE_HEIGHT]: UpdateWidgetHeightPayload;
444
- [WidgetMethodsEmit.SET_FULL_HEIGHT]: SetWidgetFullHeightPayload;
475
+ [WidgetMethodsEmit.SET_FULL_HEIGHT]: void;
445
476
  [WidgetMethodsEmit.PROVIDER_RPC_REQUEST]: ProviderRpcRequestPayload;
446
477
  [WidgetMethodsEmit.INTERCEPT_WINDOW_OPEN]: WindowOpenPayload;
447
478
  [WidgetMethodsEmit.PROCESS_HOOK]: WidgetHookPayload<WidgetHookEvents>;
@@ -456,7 +487,7 @@ export interface WidgetMethodsListenPayloadMap {
456
487
  export type WidgetEventsPayloadMap = WidgetMethodsEmitPayloadMap & WidgetMethodsListenPayloadMap;
457
488
  export type WidgetMethodsEmitPayloads = WidgetMethodsEmitPayloadMap[WidgetMethodsEmit];
458
489
  export type WidgetMethodsListenPayloads = WidgetMethodsListenPayloadMap[WidgetMethodsListen];
459
- export type CowSwapWidgetAppParams = Omit<CowSwapWidgetParams, 'theme' | 'hooks'>;
490
+ export type CowSwapWidgetAppParams = Omit<CowSwapWidgetParams, 'theme' | 'hooks' | 'rootStyle'>;
460
491
  export interface UpdateParamsPayload {
461
492
  urlParams: {
462
493
  pathname: string;
@@ -473,9 +504,6 @@ export interface UpdateAppDataPayload {
473
504
  export interface UpdateWidgetHeightPayload {
474
505
  height?: number;
475
506
  }
476
- export interface SetWidgetFullHeightPayload {
477
- isUpToSmall?: boolean;
478
- }
479
507
  export type WidgetHookId = string;
480
508
  export interface WidgetHookPayload<T extends WidgetHookEvents> {
481
509
  id: WidgetHookId;
@@ -1,6 +1,6 @@
1
- type IframeLoadingState = {
2
- cancelWidgetLoading: () => void;
3
- onWidgetReady: () => void;
4
- };
5
- export declare function widgetIframeLoading(iframe: HTMLIFrameElement, onWidgetLoadingError?: () => void, customErrorStyles?: string): IframeLoadingState;
1
+ interface WidgetIframeLoadingContext {
2
+ cancelWidgetLoading(): void;
3
+ onWidgetReady(): void;
4
+ }
5
+ export declare function widgetIframeLoading(container: HTMLElement, iframe: HTMLIFrameElement, setup: () => void, destroy: (skipIframeDestroy?: boolean) => void, onWidgetLoadingError?: () => void): WidgetIframeLoadingContext;
6
6
  export {};