@cowprotocol/widget-react 0.14.6 → 1.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -6,10 +6,6 @@ React component that creates a CoW Swap widget. It is based on [https://npmjs.co
6
6
 
7
7
  Install dependency
8
8
 
9
- ```bash
10
- yarn add @cowprotocol/widget-react
11
- ```
12
-
13
9
  ```bash
14
10
  npm install @cowprotocol/widget-react
15
11
  ```
package/jest.config.ts ADDED
@@ -0,0 +1,11 @@
1
+ export default {
2
+ displayName: 'widget-react',
3
+ preset: '../../jest.preset.js',
4
+ transform: {
5
+ '^(?!.*\\.(js|jsx|ts|tsx|css|json)$)': '@nx/react/plugins/jest',
6
+ '^.+\\.[tj]sx?$': ['babel-jest', { presets: ['@nx/react/babel'] }],
7
+ },
8
+ setupFilesAfterEnv: ['../../jest.setup.ts'],
9
+ moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx'],
10
+ coverageDirectory: '../../../coverage/libs/widget-react',
11
+ }
package/package.json CHANGED
@@ -1,27 +1,21 @@
1
1
  {
2
2
  "name": "@cowprotocol/widget-react",
3
- "version": "0.14.6",
4
- "type": "commonjs",
3
+ "version": "1.0.4",
5
4
  "description": "CoW Swap Widget Library. Allows you to easily embed a CoW Swap widget on your React application.",
6
- "main": "index.js",
7
- "exports": {
8
- "import": "./index.js",
9
- "require": "./index.mjs"
10
- },
5
+ "type": "commonjs",
6
+ "main": "./src/index.ts",
7
+ "types": "./src/index.d.ts",
11
8
  "license": "ISC",
12
- "repository": {
13
- "type": "git",
14
- "url": "https://github.com/cowprotocol/cowswap"
9
+ "publishConfig": {
10
+ "access": "public"
15
11
  },
16
- "keywords": [
17
- "cowprotocol",
18
- "widget",
19
- "cowswap",
20
- "dex",
21
- "widget-lib",
22
- "react"
23
- ],
24
12
  "dependencies": {
25
- "@cowprotocol/widget-lib": "^0.22.3"
13
+ "react": "19.1.2",
14
+ "@cowprotocol/events": "3.1.0",
15
+ "@cowprotocol/types": "3.1.0",
16
+ "@cowprotocol/widget-lib": "1.1.1"
17
+ },
18
+ "devDependencies": {
19
+ "@types/react": "19.1.3"
26
20
  }
27
- }
21
+ }
package/project.json ADDED
@@ -0,0 +1,42 @@
1
+ {
2
+ "name": "widget-react",
3
+ "$schema": "../../node_modules/nx/schemas/project-schema.json",
4
+ "sourceRoot": "libs/widget-react/src",
5
+ "projectType": "library",
6
+ "tags": [],
7
+ "targets": {
8
+ "lint": {
9
+ "executor": "@nx/eslint:lint",
10
+ "outputs": ["{options.outputFile}"],
11
+ "options": {
12
+ "lintFilePatterns": ["libs/widget-react/**/*.{ts,tsx,js,jsx}"]
13
+ }
14
+ },
15
+ "build": {
16
+ "executor": "@nx/js:tsc",
17
+ "outputs": ["{options.outputPath}"],
18
+ "options": {
19
+ "outputPath": "dist/libs/widget-react",
20
+ "main": "libs/widget-react/src/index.ts",
21
+ "tsConfig": "libs/widget-react/tsconfig.lib.json",
22
+ "assets": ["libs/widget-react/*.md"],
23
+ "updateBuildableProjectDepsInPackageJson": true,
24
+ "buildableProjectDepsInPackageJsonType": "dependencies"
25
+ }
26
+ },
27
+ "test": {
28
+ "executor": "@nx/jest:jest",
29
+ "outputs": ["{workspaceRoot}/coverage/{projectRoot}"],
30
+ "options": {
31
+ "jestConfig": "libs/widget-react/jest.config.ts",
32
+ "passWithNoTests": true
33
+ },
34
+ "configurations": {
35
+ "ci": {
36
+ "ci": true,
37
+ "codeCoverage": true
38
+ }
39
+ }
40
+ }
41
+ }
42
+ }
package/src/index.ts ADDED
@@ -0,0 +1,2 @@
1
+ export * from './lib/CowSwapWidget'
2
+ export * from '@cowprotocol/widget-lib'
@@ -0,0 +1,7 @@
1
+ import { CowSwapWidget } from './CowSwapWidget'
2
+
3
+ describe('CowSwapWidget', () => {
4
+ it('should render successfully', () => {
5
+ expect(CowSwapWidget).toBeTruthy()
6
+ })
7
+ })
@@ -0,0 +1,125 @@
1
+ import { ReactNode, useCallback, useEffect, useRef, useState } from 'react'
2
+
3
+ import type { CowWidgetEventListeners } from '@cowprotocol/events'
4
+ import type { Command } from '@cowprotocol/types'
5
+ import {
6
+ CowSwapWidgetHandler,
7
+ CowSwapWidgetParams,
8
+ CowSwapWidgetProps,
9
+ EthereumProvider,
10
+ createCowSwapWidget,
11
+ } from '@cowprotocol/widget-lib'
12
+
13
+ export function CowSwapWidget(props: CowSwapWidgetProps): ReactNode {
14
+ const { params, provider, listeners } = props
15
+ const [error, setError] = useState<{ error: Error; message: string } | null>(null)
16
+ const paramsRef = useRef<CowSwapWidgetParams | null>(null)
17
+ const providerRef = useRef<EthereumProvider | undefined>(provider)
18
+ const listenersRef = useRef<CowWidgetEventListeners | undefined>(listeners)
19
+ const containerRef = useRef<HTMLDivElement | null>(null)
20
+ const widgetHandlerRef = useRef<CowSwapWidgetHandler | null>(null)
21
+
22
+ // Error handling
23
+ const tryOrHandleError = useCallback((action: string, actionThatMightFail: Command) => {
24
+ try {
25
+ console.log(`[WIDGET] ${action}`)
26
+ actionThatMightFail()
27
+ } catch (error) {
28
+ const errorMessage = `Error ${action.toLowerCase()}`
29
+ console.error(`[WIDGET] ${errorMessage}`, error)
30
+ setError({ message: errorMessage, error })
31
+ }
32
+ }, [])
33
+
34
+ // Cleanup widget on mount
35
+ useEffect(() => {
36
+ return () => {
37
+ // Cleanup references
38
+ paramsRef.current = null
39
+ providerRef.current = undefined
40
+ listenersRef.current = undefined
41
+
42
+ // Destroy widget
43
+ const handler = widgetHandlerRef.current
44
+ if (handler) {
45
+ tryOrHandleError('💥 Destroy widget', () => handler.destroy())
46
+ widgetHandlerRef.current = null
47
+ }
48
+ }
49
+ // eslint-disable-next-line react-hooks/exhaustive-deps
50
+ }, [])
51
+
52
+ // Create/Update the widget if the parameters change
53
+ useEffect(() => {
54
+ if (!containerRef.current || JSON.stringify(paramsRef.current) === JSON.stringify(params)) {
55
+ return
56
+ }
57
+
58
+ const container = containerRef.current
59
+ const handler = widgetHandlerRef.current
60
+ paramsRef.current = params
61
+
62
+ if (handler === null) {
63
+ tryOrHandleError('Creating a new widget', () => {
64
+ widgetHandlerRef.current = createCowSwapWidget(container, { params, provider: providerRef.current, listeners })
65
+ listenersRef.current = listeners
66
+ })
67
+ } else {
68
+ tryOrHandleError('Updating the widget', () => handler.updateParams(params))
69
+ }
70
+ // Trigger only on params changes
71
+ // eslint-disable-next-line react-hooks/exhaustive-deps
72
+ }, [params, tryOrHandleError])
73
+
74
+ // Update widget provider (if it changes)
75
+ useEffect(() => {
76
+ if (!widgetHandlerRef.current || providerRef.current === provider) {
77
+ return
78
+ }
79
+
80
+ // Update provider
81
+ providerRef.current = provider
82
+
83
+ // TODO: Fix this https://github.com/cowprotocol/cowswap/issues/3810#issue-2127257473 (in meantime forcing full refresh as before)
84
+ // const handler = widgetHandlerRef.current
85
+ // tryOrHandleError('Updating the provider', () => {
86
+ // handler.updateProvider(provider)
87
+ // if (paramsRef.current) {
88
+ // handler.updateWidget(paramsRef.current)
89
+ // }
90
+ // })
91
+ const container = containerRef.current
92
+ if (container) {
93
+ tryOrHandleError('Updating the provider', () => {
94
+ // Destroy the old widget (if it exists)
95
+ widgetHandlerRef.current?.destroy()
96
+
97
+ // Re-create the widget
98
+ widgetHandlerRef.current = createCowSwapWidget(container, { params, provider: providerRef.current, listeners })
99
+ })
100
+ }
101
+ // Trigger only on provider changes
102
+ // eslint-disable-next-line react-hooks/exhaustive-deps
103
+ }, [provider, tryOrHandleError])
104
+
105
+ // Update widget listeners (if they change)
106
+ useEffect(() => {
107
+ if (!widgetHandlerRef.current || listenersRef.current === listeners) return
108
+
109
+ const handler = widgetHandlerRef.current
110
+ tryOrHandleError('Updating the listeners', () => handler.updateListeners(listeners))
111
+ }, [listeners, tryOrHandleError])
112
+
113
+ // Handle errors
114
+ if (error) {
115
+ return (
116
+ <div style={{ color: '#ff3a3a' }}>
117
+ {error.message}
118
+ {error.error.message && <pre style={{ whiteSpace: 'pre-wrap', fontSize: '0.75em' }}>{error.error.message}</pre>}
119
+ </div>
120
+ )
121
+ }
122
+
123
+ // Render widget container
124
+ return <div ref={containerRef} style={{ width: '100%' }}></div>
125
+ }
package/tsconfig.json ADDED
@@ -0,0 +1,21 @@
1
+ {
2
+ "extends": "../../tsconfig.base.json",
3
+ "compilerOptions": {
4
+ "jsx": "react-jsx",
5
+ "allowJs": false,
6
+ "esModuleInterop": false,
7
+ "allowSyntheticDefaultImports": true,
8
+ "strict": true,
9
+ "types": ["vite/client"]
10
+ },
11
+ "files": [],
12
+ "include": [],
13
+ "references": [
14
+ {
15
+ "path": "./tsconfig.lib.json"
16
+ },
17
+ {
18
+ "path": "./tsconfig.spec.json"
19
+ }
20
+ ]
21
+ }
@@ -0,0 +1,10 @@
1
+ {
2
+ "extends": "./tsconfig.json",
3
+ "compilerOptions": {
4
+ "outDir": "../../dist/out-tsc",
5
+ "declaration": true,
6
+ "types": ["node"]
7
+ },
8
+ "include": ["src/**/*.ts", "src/**/*.tsx"],
9
+ "exclude": ["src/**/*.spec.ts", "src/**/*.test.ts", "src/**/*.spec.tsx", "src/**/*.test.tsx"]
10
+ }
@@ -0,0 +1,20 @@
1
+ {
2
+ "extends": "./tsconfig.json",
3
+ "compilerOptions": {
4
+ "outDir": "../../../dist/out-tsc",
5
+ "module": "commonjs",
6
+ "types": ["jest", "node"]
7
+ },
8
+ "include": [
9
+ "jest.config.ts",
10
+ "src/**/*.test.ts",
11
+ "src/**/*.spec.ts",
12
+ "src/**/*.test.tsx",
13
+ "src/**/*.spec.tsx",
14
+ "src/**/*.test.js",
15
+ "src/**/*.spec.js",
16
+ "src/**/*.test.jsx",
17
+ "src/**/*.spec.jsx",
18
+ "src/**/*.d.ts"
19
+ ]
20
+ }
package/index.d.ts DELETED
@@ -1,2 +0,0 @@
1
- export * from './lib/CowSwapWidget';
2
- export * from '@cowprotocol/widget-lib';
package/index.js DELETED
@@ -1 +0,0 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const A=require("react/jsx-runtime"),v=require("react");class F{constructor(t){this.key=t}postMessageToWindow(t,n,r){const p=typeof r=="object"?r:{},h={key:this.key,method:n,...p};t.postMessage(h,"*")}listenToMessageFromWindow(t,n,r){const p=h=>{!G(h.data)||h.data.key!==this.key||h.data.method!==n||r(h.data)};return t.addEventListener("message",p),p}stopListeningToMessageFromWindow(t,n,r){t.removeEventListener("message",r)}stopListeningWindowListener(t,n){t.removeEventListener("message",n)}}function G(e){return typeof e=="object"&&e!==null&&"key"in e&&"method"in e&&typeof e.key=="string"&&typeof e.method=="string"}var g=(e=>(e.PROVIDER_RPC_REQUEST="PROVIDER_RPC_REQUEST",e.PROVIDER_RPC_RESPONSE="PROVIDER_RPC_RESPONSE",e.PROVIDER_ON_EVENT="PROVIDER_ON_EVENT",e.SEND_PROVIDER_META_INFO="SEND_PROVIDER_META_INFO",e.REQUEST_PROVIDER_META_INFO="REQUEST_PROVIDER_META_INFO",e))(g||{});const P=new F("cowSwapIframeRpcProviderTransport");function q(e){if(e.isWalletConnect)return e?.session?.peer?.metadata}function $(e,t){return t.find(n=>n.provider===e)?.info}const B=["connect","disconnect","close","chainChanged","accountsChanged"],U=[];typeof window<"u"&&window.addEventListener("eip6963:announceProvider",e=>{const t=e;U.push(t.detail)});class J{constructor(t){this.iframeWidow=t}ethereumProvider=null;requestWaitingForConnection={};disconnect(){typeof window>"u"||(this.ethereumProvider=null,P.stopListeningToMessageFromWindow(window,g.PROVIDER_RPC_REQUEST,this.processRpcCallFromWindow),P.stopListeningToMessageFromWindow(window,g.REQUEST_PROVIDER_META_INFO,this.processProviderMetaInfoRequest))}onConnect(t){typeof window>"u"||(this.ethereumProvider?this.disconnect():P.listenToMessageFromWindow(window,g.PROVIDER_RPC_REQUEST,this.processRpcCallFromWindow),this.ethereumProvider=t,this.processPendingRequests(),B.forEach(n=>{t.on(n,r=>this.onProviderEvent(n,r))}),P.listenToMessageFromWindow(window,g.REQUEST_PROVIDER_META_INFO,this.processProviderMetaInfoRequest))}processPendingRequests(){Object.keys(this.requestWaitingForConnection).forEach(t=>{this.processRpcRequest(this.requestWaitingForConnection[t])}),this.requestWaitingForConnection={}}processRpcRequest(t){const{id:n,jsonrpc:r,method:p}=t;if(!this.ethereumProvider||!n)return;(p==="enable"?this.ethereumProvider.request({method:"eth_requestAccounts",id:n}):this.ethereumProvider.request({...t,id:n})).then(w=>this.forwardRpcResponseToIframe({rpcResponse:{jsonrpc:r,id:n,result:w}})).catch(w=>this.forwardRpcResponseToIframe({rpcResponse:{jsonrpc:r,id:n,error:w}}))}processRpcCallFromWindow=({rpcRequest:t})=>{if(!this.ethereumProvider){t.id&&(this.requestWaitingForConnection[t.id]=t);return}this.processRpcRequest(t)};processProviderMetaInfoRequest=()=>{if(!this.ethereumProvider)return;const t=$(this.ethereumProvider,U),n=q(this.ethereumProvider);P.postMessageToWindow(this.iframeWidow,g.SEND_PROVIDER_META_INFO,{providerEip6963Info:t,providerWcMetadata:n})};onProviderEvent(t,n){P.postMessageToWindow(this.iframeWidow,g.PROVIDER_ON_EVENT,{event:t,params:n})}forwardRpcResponseToIframe(t){P.postMessageToWindow(this.iframeWidow,g.PROVIDER_RPC_RESPONSE,t)}}var D={exports:{}},b;function z(){return b||(b=1,function(e){var t=Object.prototype.hasOwnProperty,n="~";function r(){}Object.create&&(r.prototype=Object.create(null),new r().__proto__||(n=!1));function p(c,i,s){this.fn=c,this.context=i,this.once=s||!1}function h(c,i,s,o,f){if(typeof s!="function")throw new TypeError("The listener must be a function");var d=new p(s,o||c,f),l=n?n+i:i;return c._events[l]?c._events[l].fn?c._events[l]=[c._events[l],d]:c._events[l].push(d):(c._events[l]=d,c._eventsCount++),c}function w(c,i){--c._eventsCount===0?c._events=new r:delete c._events[i]}function u(){this._events=new r,this._eventsCount=0}u.prototype.eventNames=function(){var i=[],s,o;if(this._eventsCount===0)return i;for(o in s=this._events)t.call(s,o)&&i.push(n?o.slice(1):o);return Object.getOwnPropertySymbols?i.concat(Object.getOwnPropertySymbols(s)):i},u.prototype.listeners=function(i){var s=n?n+i:i,o=this._events[s];if(!o)return[];if(o.fn)return[o.fn];for(var f=0,d=o.length,l=new Array(d);f<d;f++)l[f]=o[f].fn;return l},u.prototype.listenerCount=function(i){var s=n?n+i:i,o=this._events[s];return o?o.fn?1:o.length:0},u.prototype.emit=function(i,s,o,f,d,l){var _=n?n+i:i;if(!this._events[_])return!1;var a=this._events[_],R=arguments.length,m,E;if(a.fn){switch(a.once&&this.removeListener(i,a.fn,void 0,!0),R){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,o),!0;case 4:return a.fn.call(a.context,s,o,f),!0;case 5:return a.fn.call(a.context,s,o,f,d),!0;case 6:return a.fn.call(a.context,s,o,f,d,l),!0}for(E=1,m=new Array(R-1);E<R;E++)m[E-1]=arguments[E];a.fn.apply(a.context,m)}else{var Q=a.length,O;for(E=0;E<Q;E++)switch(a[E].once&&this.removeListener(i,a[E].fn,void 0,!0),R){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,o);break;case 4:a[E].fn.call(a[E].context,s,o,f);break;default:if(!m)for(O=1,m=new Array(R-1);O<R;O++)m[O-1]=arguments[O];a[E].fn.apply(a[E].context,m)}}return!0},u.prototype.on=function(i,s,o){return h(this,i,s,o,!1)},u.prototype.once=function(i,s,o){return h(this,i,s,o,!0)},u.prototype.removeListener=function(i,s,o,f){var d=n?n+i:i;if(!this._events[d])return this;if(!s)return w(this,d),this;var l=this._events[d];if(l.fn)l.fn===s&&(!f||l.once)&&(!o||l.context===o)&&w(this,d);else{for(var _=0,a=[],R=l.length;_<R;_++)(l[_].fn!==s||f&&!l[_].once||o&&l[_].context!==o)&&a.push(l[_]);a.length?this._events[d]=a.length===1?a[0]:a:w(this,d)}return this},u.prototype.removeAllListeners=function(i){var s;return i?(s=n?n+i:i,this._events[s]&&w(this,s)):(this._events=new r,this._eventsCount=0),this},u.prototype.off=u.prototype.removeListener,u.prototype.addListener=u.prototype.on,u.prefixed=n,u.EventEmitter=u,e.exports=u}(D)),D.exports}z();class Y{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(p=>p!==r)),t}emit(t,n){this.subscriptions[t]&&this.subscriptions[t].forEach(r=>r(n))}}var I=(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))(I||{}),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.YIELD="yield",e))(W||{});const K=["primary","background","paper","text","danger","warning","alert","info","success"],T=new F("cowSwapWidget");class X{constructor(t,n=[]){this.contentWindow=t,this.updateListeners(n),this.widgetListener=T.listenToMessageFromWindow(this.contentWindow,I.EMIT_COW_EVENT,r=>this.eventEmitter.emit(r.event,r.payload))}eventEmitter=new Y;listeners=[];widgetListener;stopListeningIframe(){T.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=r=>{ee(r.data)&&(typeof window<"u"&&r.origin===window.location.origin||(te(r.data)?this.appWindow.parent.postMessage(r.data,"*"):ne(r.data)&&this.iframeWidow.postMessage(r.data,"*")))},this.startListening()}forwardSdkMessage;startListening(){this.appWindow.addEventListener("message",this.forwardSdkMessage)}stopListening(){this.appWindow.removeEventListener("message",this.forwardSdkMessage)}}function ee(e){return typeof e=="object"&&e!==null&&"id"in e&&typeof e.id=="string"}function te(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 ne(e){return"success"in e&&typeof e.success=="boolean"&&"version"in e&&typeof e.version=="string"}function x(e){return!!(e&&typeof e=="object")}const M="_";function re(e){const t=typeof e.baseUrl=="string"?e.baseUrl:"https://swap.cow.fi",n=k(e);return t+"/#"+n+"?"+H(e)}function k(e){const{chainId:t=1,sell:n,buy:r,tradeType:p=W.SWAP}=e,h=[n?.asset||M,r?.asset||M].map(encodeURIComponent).join("/");return`/${t}/widget/${p}/${h}`}function H(e){const t=new URLSearchParams;return ie(oe(se(t,e),e),e)}function se(e,t){const{sell:n,buy:r}=t;return n?.amount&&e.append("sellAmount",n.amount),r?.amount&&e.append("buyAmount",r.amount),e}function oe(e,t){const n=t.theme;return n?(x(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 ie(e,t){return t.targetChainId&&e.append("targetChainId",t.targetChainId.toString()),e}const j="640px",ae="450px",ce=20,ue={updateParams:()=>{},updateListeners:()=>{},updateProvider:()=>{},destroy:()=>{}};function L(e,t){const{params:n,provider:r,listeners:p}=t;let h=r,w=n;if(typeof window>"u")return ue;const u=de(n);e.innerHTML="",e.appendChild(u);const{contentWindow:c}=u;if(!c)throw console.error("Iframe does not contain a window",u),new Error("Iframe does not contain a window!");const i=[];i.push(fe(c,n.appCode)),i.push(...le(u,n.height,n.maxHeight)),i.push(pe());const s=new X(window,p);let o=N(c,null,h);u.addEventListener("load",()=>V(c,w,h));const f=new Z(window,c);return{updateParams:d=>{w=d,V(c,w,h)},updateListeners:d=>s.updateListeners(d),updateProvider:d=>{h=d,o=N(c,o,d)},destroy:()=>{o.disconnect(),s.stopListeningIframe(),i.forEach(d=>window.removeEventListener("message",d)),f.stopListening(),e.removeChild(u)}}}function N(e,t,n){t&&t.disconnect();const r=t||new J(e);return n&&r.onConnect(n),r}function de(e){const{width:t=ae,height:n=j}=e,r=document.createElement("iframe");return r.src=re(e),r.width=t,r.height=n,r.style.border="0",r.allow="clipboard-read; clipboard-write",r}function V(e,t,n){const r=!!n,p=k(t),h=H(t).toString(),{theme:w,...u}=t;T.postMessageToWindow(e,S.UPDATE_PARAMS,{urlParams:{pathname:p,search:h},appParams:u,hasProvider:r})}function fe(e,t){return T.listenToMessageFromWindow(window,I.ACTIVATE,()=>{T.postMessageToWindow(e,S.UPDATE_APP_DATA,{metaData:t?{appCode:t}:void 0})})}function pe(){return T.listenToMessageFromWindow(window,I.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 le(e,t=j,n){return[T.listenToMessageFromWindow(window,I.UPDATE_HEIGHT,r=>{const p=r.height?r.height+ce:void 0;e.style.height=p?`${n?Math.min(p,n):p}px`:t}),T.listenToMessageFromWindow(window,I.SET_FULL_HEIGHT,({isUpToSmall:r})=>{e.style.height=r?t:`${n||document.body.offsetHeight}px`})]}const he=Object.values(W);function Ee(e,t,n){if(y(e)){const r=e[n];return C(r)?r[t]:r}if(C(e)){const r=e[t];return y(r)?r[n]:r}return e}function y(e){return typeof e!="object"?!1:Object.keys(e).every(t=>he.includes(t))}const we=/^\d+$/;function C(e){return typeof e!="object"?!1:Object.keys(e).every(t=>we.test(t))}function _e(e){return y(e)?Object.values(e).flatMap(t=>C(t)?Object.values(t):[t]):C(e)?Object.values(e).flatMap(t=>y(t)?Object.values(t):[t]):[e]}function ve(e){const{params:t,provider:n,listeners:r}=e,[p,h]=v.useState(null),w=v.useRef(null),u=v.useRef(n),c=v.useRef(r),i=v.useRef(null),s=v.useRef(null),o=v.useCallback((f,d)=>{try{console.log(`[WIDGET] ${f}`),d()}catch(l){const _=`Error ${f.toLowerCase()}`;console.error(`[WIDGET] ${_}`,l),h({message:_,error:l})}},[]);return v.useEffect(()=>()=>{w.current=null,u.current=void 0,c.current=void 0;const f=s.current;f&&(o("💥 Destroy widget",()=>f.destroy()),s.current=null)},[]),v.useEffect(()=>{if(!i.current||JSON.stringify(w.current)===JSON.stringify(t))return;const f=i.current,d=s.current;w.current=t,d===null?o("Creating a new widget",()=>{s.current=L(f,{params:t,provider:u.current,listeners:r}),c.current=r}):o("Updating the widget",()=>d.updateParams(t))},[t,o]),v.useEffect(()=>{if(!s.current||u.current===n)return;u.current=n;const f=i.current;f&&o("Updating the provider",()=>{s.current?.destroy(),s.current=L(f,{params:t,provider:u.current,listeners:r})})},[n,o]),v.useEffect(()=>{if(!s.current||c.current===r)return;const f=s.current;o("Updating the listeners",()=>f.updateListeners(r))},[r,o]),p?A.jsxs("div",{style:{color:"#ff3a3a"},children:[p.message,p.error.message&&A.jsx("pre",{style:{whiteSpace:"pre-wrap",fontSize:"0.75em"},children:p.error.message})]}):A.jsx("div",{ref:i,style:{width:"100%"}})}exports.CowSwapWidget=ve;exports.TradeType=W;exports.WIDGET_PALETTE_COLORS=K;exports.WidgetMethodsEmit=I;exports.WidgetMethodsListen=S;exports.createCowSwapWidget=L;exports.isCowSwapWidgetPalette=x;exports.isPerNetworkConfig=C;exports.isPerTradeTypeConfig=y;exports.resolveFlexibleConfig=Ee;exports.resolveFlexibleConfigValues=_e;exports.widgetIframeTransport=T;