@zerohash-sdk/csp-fiat-withdrawals-js 0.1.0 → 0.1.3

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
@@ -1,7 +1,134 @@
1
1
  # @zerohash-sdk/csp-fiat-withdrawals-js
2
2
 
3
- This library was generated with [Nx](https://nx.dev).
3
+ A framework-agnostic JavaScript SDK for embedding the Zerohash CSP Fiat Withdrawals flow into web applications. Lets users withdraw fiat (USD) from their account to a linked bank account via ACH.
4
4
 
5
- ## Running unit tests
5
+ ## Installation
6
6
 
7
- Run `nx test @zerohash-sdk/csp-fiat-withdrawals-js` to execute the unit tests via [Vitest](https://vitest.dev/).
7
+ ### Via NPM (recommended)
8
+
9
+ ```bash
10
+ npm install @zerohash-sdk/csp-fiat-withdrawals-js
11
+ ```
12
+
13
+ ```javascript
14
+ import { CspFiatWithdrawals } from '@zerohash-sdk/csp-fiat-withdrawals-js';
15
+ ```
16
+
17
+ ### Via CDN
18
+
19
+ ```html
20
+ <script
21
+ type="module"
22
+ src="https://sdk.connect.xyz/csp-fiat-withdrawals-web/index.js"
23
+ ></script>
24
+ ```
25
+
26
+ Or import directly:
27
+
28
+ ```javascript
29
+ import { CspFiatWithdrawals } from 'https://sdk.connect.xyz/csp-fiat-withdrawals-web/index.js';
30
+ ```
31
+
32
+ ## Getting Started
33
+
34
+ ### 1. Import
35
+
36
+ ```javascript
37
+ import { CspFiatWithdrawals } from '@zerohash-sdk/csp-fiat-withdrawals-js';
38
+ ```
39
+
40
+ ### 2. Initialize and render
41
+
42
+ ```javascript
43
+ const cspFiatWithdrawals = new CspFiatWithdrawals({
44
+ jwt: 'your-jwt-token',
45
+ env: 'prod',
46
+ theme: 'auto',
47
+ onCompleted: ({ amountWithdrawn, assetSymbol }) => {
48
+ console.log(`Withdrew ${amountWithdrawn} ${assetSymbol}`);
49
+ },
50
+ onError: ({ errorCode, reason }) => {
51
+ console.error(errorCode, reason);
52
+ },
53
+ onClose: () => console.log('Closed'),
54
+ onEvent: (event) => console.log('Event:', event),
55
+ onLoaded: () => console.log('Ready'),
56
+ });
57
+
58
+ const container = document.getElementById('csp-fiat-withdrawals-container');
59
+ await cspFiatWithdrawals.render(container);
60
+
61
+ // Update configuration dynamically
62
+ cspFiatWithdrawals.updateConfig({ jwt: 'new-jwt-token', theme: 'dark' });
63
+
64
+ // Clean up when done
65
+ cspFiatWithdrawals.destroy();
66
+ ```
67
+
68
+ ### TypeScript
69
+
70
+ ```typescript
71
+ import { CspFiatWithdrawals, CspFiatWithdrawalsConfig } from '@zerohash-sdk/csp-fiat-withdrawals-js';
72
+
73
+ const config: CspFiatWithdrawalsConfig = {
74
+ jwt: 'your-jwt-token',
75
+ env: 'cert',
76
+ theme: 'dark',
77
+ onCompleted: ({ amountWithdrawn, assetSymbol }) => {
78
+ console.log(`Withdrew ${amountWithdrawn} ${assetSymbol}`);
79
+ },
80
+ };
81
+
82
+ const csp = new CspFiatWithdrawals(config);
83
+ await csp.render(document.getElementById('csp-fiat-withdrawals-container')!);
84
+ ```
85
+
86
+ ## API Reference
87
+
88
+ ### Configuration
89
+
90
+ | Prop | Type | Required | Default | Description |
91
+ | ------------- | -------------------------------------------- | -------- | -------- | -------------------------------------------- |
92
+ | `jwt` | `string` | Yes | - | JWT token for authentication with Connect |
93
+ | `env` | `"prod" \| "cert" \| "dev" \| "local"` | No | `"prod"` | Target environment |
94
+ | `theme` | `"auto" \| "light" \| "dark"` | No | `"auto"` | Theme mode for the interface |
95
+ | `onCompleted` | `({ amountWithdrawn, assetSymbol }) => void` | No | - | Callback when the withdrawal flow completes |
96
+ | `onError` | `({ errorCode, reason }) => void` | No | - | Callback for error events |
97
+ | `onClose` | `() => void` | No | - | Callback when the widget is closed |
98
+ | `onEvent` | `(event) => void` | No | - | Callback for general events |
99
+ | `onLoaded` | `() => void` | No | - | Callback when the widget is loaded and ready |
100
+
101
+ `onCompleted` payload shape: `{ amountWithdrawn: string; assetSymbol: string }` (asset is always `'USD'`).
102
+
103
+ ### Methods
104
+
105
+ #### `render(container: HTMLElement): Promise<void>`
106
+
107
+ Renders the widget into the given container.
108
+
109
+ #### `updateConfig(config: Partial<CspFiatWithdrawalsConfig>): void`
110
+
111
+ Updates the configuration of an already rendered widget.
112
+
113
+ #### `destroy(): void`
114
+
115
+ Removes the widget from the DOM and cleans up resources.
116
+
117
+ #### `isRendered(): boolean`
118
+
119
+ Returns whether the widget is currently rendered.
120
+
121
+ #### `getConfig(): CspFiatWithdrawalsConfig`
122
+
123
+ Returns a copy of the current configuration.
124
+
125
+ ## Browser Support
126
+
127
+ - Chrome / Edge 90+
128
+ - Firefox 88+
129
+ - Safari 14+
130
+ - All modern browsers with Web Components support
131
+
132
+ ## More Information & Support
133
+
134
+ For comprehensive documentation, visit the [Zerohash Documentation Page](https://docs.zerohash.com/).
package/dist/index.d.ts CHANGED
@@ -36,7 +36,7 @@ declare interface BaseConfig<TEvent = AppEvent> extends CommonCallbacks<TEvent>
36
36
 
37
37
  /**
38
38
  * Theme mode
39
- * @default 'auto'
39
+ * @default 'light'
40
40
  *
41
41
  * Available themes:
42
42
  * - `'auto'` - Automatically detect system preference (light/dark mode)
@@ -200,7 +200,11 @@ declare abstract class BaseJsSdk<Config extends BaseConfig<never> = BaseConfig>
200
200
  return import.meta.env['VITE_SCRIPT_URL'] || this.scriptUrls[this.getEnvironment()];
201
201
  }
202
202
 
203
- return this.scriptUrls[this.getEnvironment()];
203
+ // Route EU partners (region claim in JWT) to EU-hosted assets without
204
+ // changing the public `env` contract — falls back to the configured env
205
+ // when no EU URL is registered for that environment.
206
+ const effectiveEnv = resolveEnvByRegion(this.getEnvironment(), this.config.jwt);
207
+ return this.scriptUrls[effectiveEnv] ?? this.scriptUrls[this.getEnvironment()];
204
208
  }
205
209
 
206
210
  private async loadScript() {
@@ -327,7 +331,7 @@ declare type CommonCallbacks<TEvent = AppEvent> = {
327
331
  * const cspFiatWithdrawals = new CspFiatWithdrawals({
328
332
  * jwt: 'your-jwt-token',
329
333
  * env: 'prod',
330
- * theme: 'auto',
334
+ * theme: 'light',
331
335
  * onCompleted: ({ amountWithdrawn, assetSymbol }) =>
332
336
  * console.log('Withdrew', amountWithdrawn, assetSymbol),
333
337
  * onClose: () => console.log('Closed'),
package/dist/index.js CHANGED
@@ -1,14 +1,29 @@
1
- const n = "production", d = "JWT token is required and must be a string.";
2
- class h {
1
+ const d = "production", h = "JWT token is required and must be a string.", l = (r) => {
2
+ if (!r || typeof r != "string")
3
+ return null;
4
+ const e = r.split(".");
5
+ if (e.length < 2)
6
+ return null;
7
+ try {
8
+ const i = e[1].replace(/-/g, "+").replace(/_/g, "/"), t = i + "===".slice(0, (4 - i.length % 4) % 4), n = typeof atob < "u" ? atob(t) : Buffer.from(t, "base64").toString("utf-8"), a = JSON.parse(n)?.payload?.region;
9
+ if (typeof a != "string")
10
+ return null;
11
+ const s = a.toLowerCase();
12
+ return s === "us" || s === "eu" ? s : null;
13
+ } catch {
14
+ return null;
15
+ }
16
+ }, p = (r, e) => l(e) !== "eu" ? r : r === "cert" ? "eu-cert" : r === "prod" ? "eu-prod" : r;
17
+ class u {
3
18
  config;
4
19
  state;
5
20
  scriptLoadingPromise;
6
21
  constructor(e) {
7
22
  if (!e.jwt || typeof e.jwt != "string")
8
- throw new Error(d);
23
+ throw new Error(h);
9
24
  this.config = {
10
25
  ...e,
11
- env: e.env || n,
26
+ env: e.env || d,
12
27
  theme: e.theme
13
28
  }, this.state = {
14
29
  initialized: !1,
@@ -44,8 +59,8 @@ class h {
44
59
  if (!this.state.initialized || !this.state.element)
45
60
  throw new Error(this.errorMessages.NOT_RENDERED);
46
61
  const i = this.state.element;
47
- Object.entries(e).forEach(([t, s]) => {
48
- s && (this.config[t] = s, i[t] = s);
62
+ Object.entries(e).forEach(([t, n]) => {
63
+ n && (this.config[t] = n, i[t] = n);
49
64
  });
50
65
  }
51
66
  /**
@@ -69,7 +84,7 @@ class h {
69
84
  return { ...this.config };
70
85
  }
71
86
  getEnvironment() {
72
- return this.config.env || n;
87
+ return this.config.env || d;
73
88
  }
74
89
  getScriptId() {
75
90
  return `${this.webComponentTag}-script-${this.getEnvironment()}`;
@@ -81,7 +96,8 @@ class h {
81
96
  return customElements.get(this.webComponentTag);
82
97
  }
83
98
  getScriptUrl() {
84
- return this.scriptUrls[this.getEnvironment()];
99
+ const e = p(this.getEnvironment(), this.config.jwt);
100
+ return this.scriptUrls[e] ?? this.scriptUrls[this.getEnvironment()];
85
101
  }
86
102
  async loadScript() {
87
103
  if (!this.isScriptLoaded()) {
@@ -108,13 +124,13 @@ class h {
108
124
  async waitForWebComponent(e = 5e3) {
109
125
  if (!this.getWebComponent())
110
126
  return new Promise((i, t) => {
111
- const s = setTimeout(() => {
127
+ const n = setTimeout(() => {
112
128
  t(new Error(`Timeout waiting for ${this.webComponentTag} to be defined`));
113
129
  }, e);
114
130
  customElements.whenDefined(this.webComponentTag).then(() => {
115
- clearTimeout(s), i();
116
- }).catch((a) => {
117
- clearTimeout(s), t(a);
131
+ clearTimeout(n), i();
132
+ }).catch((o) => {
133
+ clearTimeout(n), t(o);
118
134
  });
119
135
  });
120
136
  }
@@ -136,11 +152,11 @@ class h {
136
152
  }), e;
137
153
  }
138
154
  }
139
- var o;
155
+ var c;
140
156
  (function(r) {
141
157
  r.NETWORK_ERROR = "network_error", r.AUTH_ERROR = "auth_error", r.NOT_FOUND_ERROR = "not_found_error", r.VALIDATION_ERROR = "validation_error", r.SERVER_ERROR = "server_error", r.CLIENT_ERROR = "client_error", r.UNKNOWN_ERROR = "unknown_error";
142
- })(o || (o = {}));
143
- class c extends h {
158
+ })(c || (c = {}));
159
+ class m extends u {
144
160
  errorMessages = {
145
161
  ALREADY_RENDERED: "CspFiatWithdrawals widget is already rendered. Call destroy() before rendering again.",
146
162
  NOT_RENDERED: "CspFiatWithdrawals widget is not rendered. Call render() first.",
@@ -194,7 +210,7 @@ class c extends h {
194
210
  }
195
211
  }
196
212
  export {
197
- c as CspFiatWithdrawals,
198
- o as ErrorCode,
199
- c as default
213
+ m as CspFiatWithdrawals,
214
+ c as ErrorCode,
215
+ m as default
200
216
  };
@@ -1 +1 @@
1
- (function(r,n){typeof exports=="object"&&typeof module<"u"?n(exports):typeof define=="function"&&define.amd?define(["exports"],n):(r=typeof globalThis<"u"?globalThis:r||self,n(r.CspFiatWithdrawals={}))})(this,(function(r){"use strict";const n="production",d="JWT token is required and must be a string.";class h{config;state;scriptLoadingPromise;constructor(e){if(!e.jwt||typeof e.jwt!="string")throw new Error(d);this.config={...e,env:e.env||n,theme:e.theme},this.state={initialized:!1,scriptLoaded:!1,container:null,element:null}}async render(e){if(!e||!(e instanceof HTMLElement))throw new Error(this.errorMessages.INVALID_CONTAINER);if(this.state.initialized)throw new Error(this.errorMessages.ALREADY_RENDERED);try{await this.ensureScriptLoaded();const i=this.createWebComponent();e.innerHTML="",e.appendChild(i),this.state.container=e,this.state.element=i,this.state.initialized=!0}catch(i){throw console.error("Failed to render widget:",i),i}}updateConfig(e){if(!this.state.initialized||!this.state.element)throw new Error(this.errorMessages.NOT_RENDERED);const i=this.state.element;Object.entries(e).forEach(([t,o])=>{o&&(this.config[t]=o,i[t]=o)})}destroy(){this.state.initialized&&(this.state.element&&this.state.element.parentNode&&this.state.element.parentNode.removeChild(this.state.element),this.state.container&&(this.state.container.innerHTML=""),this.state.container=null,this.state.element=null,this.state.initialized=!1)}isRendered(){return this.state.initialized}getConfig(){return{...this.config}}getEnvironment(){return this.config.env||n}getScriptId(){return`${this.webComponentTag}-script-${this.getEnvironment()}`}isScriptLoaded(){return!!document.getElementById(this.getScriptId())}getWebComponent(){return customElements.get(this.webComponentTag)}getScriptUrl(){return this.scriptUrls[this.getEnvironment()]}async loadScript(){if(!this.isScriptLoaded()){if(this.scriptLoadingPromise)return this.scriptLoadingPromise;this.scriptLoadingPromise=new Promise((e,i)=>{const t=document.createElement("script");t.id=this.getScriptId(),t.src=this.getScriptUrl(),t.type="module",t.async=!0,t.onload=()=>{setTimeout(()=>{this.getWebComponent()?e():i(new Error(this.errorMessages.WEB_COMPONENT_NOT_DEFINED))},0)},t.onerror=()=>{this.scriptLoadingPromise=void 0,i(new Error(`${this.errorMessages.SCRIPT_LOAD_FAILED} (${this.getEnvironment()})`))},document.head.appendChild(t)});try{await this.scriptLoadingPromise}catch(e){throw this.scriptLoadingPromise=void 0,e}return this.scriptLoadingPromise}}async waitForWebComponent(e=5e3){if(!this.getWebComponent())return new Promise((i,t)=>{const o=setTimeout(()=>{t(new Error(`Timeout waiting for ${this.webComponentTag} to be defined`))},e);customElements.whenDefined(this.webComponentTag).then(()=>{clearTimeout(o),i()}).catch(c=>{clearTimeout(o),t(c)})})}async ensureScriptLoaded(){if(!this.state.scriptLoaded)try{await this.loadScript(),await this.waitForWebComponent(),this.state.scriptLoaded=!0}catch(e){throw console.error("Failed to load Connect script:",e),e}}createWebComponent(){const e=document.createElement(this.webComponentTag);return Object.entries(this.config).forEach(([i,t])=>{t&&(e[i]=t)}),e}}r.ErrorCode=void 0,(function(s){s.NETWORK_ERROR="network_error",s.AUTH_ERROR="auth_error",s.NOT_FOUND_ERROR="not_found_error",s.VALIDATION_ERROR="validation_error",s.SERVER_ERROR="server_error",s.CLIENT_ERROR="client_error",s.UNKNOWN_ERROR="unknown_error"})(r.ErrorCode||(r.ErrorCode={}));class a extends h{errorMessages={ALREADY_RENDERED:"CspFiatWithdrawals widget is already rendered. Call destroy() before rendering again.",NOT_RENDERED:"CspFiatWithdrawals widget is not rendered. Call render() first.",INVALID_CONTAINER:"Invalid container element provided.",SCRIPT_LOAD_FAILED:"Failed to load the Zerohash CspFiatWithdrawals script.",WEB_COMPONENT_NOT_DEFINED:"Web component is not defined. Script may not be loaded."};scriptUrls={local:"http://localhost:5173/csp-fiat-withdrawals-web/index.js",dev:"https://connect-sdk.dev.0hash.com/csp-fiat-withdrawals-web/index.js",cert:"https://sdk.sandbox.connect.xyz/csp-fiat-withdrawals-web/index.js",prod:"https://sdk.connect.xyz/csp-fiat-withdrawals-web/index.js",sandbox:"https://sdk.sandbox.connect.xyz/csp-fiat-withdrawals-web/index.js",production:"https://sdk.connect.xyz/csp-fiat-withdrawals-web/index.js"};webComponentTag="zerohash-csp-fiat-withdrawals";render(e){return super.render(e)}updateConfig(e){return super.updateConfig(e)}getConfig(){return super.getConfig()}isRendered(){return super.isRendered()}destroy(){return super.destroy()}}r.CspFiatWithdrawals=a,r.default=a,Object.defineProperties(r,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})}));
1
+ (function(n,o){typeof exports=="object"&&typeof module<"u"?o(exports):typeof define=="function"&&define.amd?define(["exports"],o):(n=typeof globalThis<"u"?globalThis:n||self,o(n.CspFiatWithdrawals={}))})(this,(function(n){"use strict";const o="production",l="JWT token is required and must be a string.",p=r=>{if(!r||typeof r!="string")return null;const e=r.split(".");if(e.length<2)return null;try{const i=e[1].replace(/-/g,"+").replace(/_/g,"/"),t=i+"===".slice(0,(4-i.length%4)%4),s=typeof atob<"u"?atob(t):Buffer.from(t,"base64").toString("utf-8"),h=JSON.parse(s)?.payload?.region;if(typeof h!="string")return null;const a=h.toLowerCase();return a==="us"||a==="eu"?a:null}catch{return null}},u=(r,e)=>p(e)!=="eu"?r:r==="cert"?"eu-cert":r==="prod"?"eu-prod":r;class f{config;state;scriptLoadingPromise;constructor(e){if(!e.jwt||typeof e.jwt!="string")throw new Error(l);this.config={...e,env:e.env||o,theme:e.theme},this.state={initialized:!1,scriptLoaded:!1,container:null,element:null}}async render(e){if(!e||!(e instanceof HTMLElement))throw new Error(this.errorMessages.INVALID_CONTAINER);if(this.state.initialized)throw new Error(this.errorMessages.ALREADY_RENDERED);try{await this.ensureScriptLoaded();const i=this.createWebComponent();e.innerHTML="",e.appendChild(i),this.state.container=e,this.state.element=i,this.state.initialized=!0}catch(i){throw console.error("Failed to render widget:",i),i}}updateConfig(e){if(!this.state.initialized||!this.state.element)throw new Error(this.errorMessages.NOT_RENDERED);const i=this.state.element;Object.entries(e).forEach(([t,s])=>{s&&(this.config[t]=s,i[t]=s)})}destroy(){this.state.initialized&&(this.state.element&&this.state.element.parentNode&&this.state.element.parentNode.removeChild(this.state.element),this.state.container&&(this.state.container.innerHTML=""),this.state.container=null,this.state.element=null,this.state.initialized=!1)}isRendered(){return this.state.initialized}getConfig(){return{...this.config}}getEnvironment(){return this.config.env||o}getScriptId(){return`${this.webComponentTag}-script-${this.getEnvironment()}`}isScriptLoaded(){return!!document.getElementById(this.getScriptId())}getWebComponent(){return customElements.get(this.webComponentTag)}getScriptUrl(){const e=u(this.getEnvironment(),this.config.jwt);return this.scriptUrls[e]??this.scriptUrls[this.getEnvironment()]}async loadScript(){if(!this.isScriptLoaded()){if(this.scriptLoadingPromise)return this.scriptLoadingPromise;this.scriptLoadingPromise=new Promise((e,i)=>{const t=document.createElement("script");t.id=this.getScriptId(),t.src=this.getScriptUrl(),t.type="module",t.async=!0,t.onload=()=>{setTimeout(()=>{this.getWebComponent()?e():i(new Error(this.errorMessages.WEB_COMPONENT_NOT_DEFINED))},0)},t.onerror=()=>{this.scriptLoadingPromise=void 0,i(new Error(`${this.errorMessages.SCRIPT_LOAD_FAILED} (${this.getEnvironment()})`))},document.head.appendChild(t)});try{await this.scriptLoadingPromise}catch(e){throw this.scriptLoadingPromise=void 0,e}return this.scriptLoadingPromise}}async waitForWebComponent(e=5e3){if(!this.getWebComponent())return new Promise((i,t)=>{const s=setTimeout(()=>{t(new Error(`Timeout waiting for ${this.webComponentTag} to be defined`))},e);customElements.whenDefined(this.webComponentTag).then(()=>{clearTimeout(s),i()}).catch(c=>{clearTimeout(s),t(c)})})}async ensureScriptLoaded(){if(!this.state.scriptLoaded)try{await this.loadScript(),await this.waitForWebComponent(),this.state.scriptLoaded=!0}catch(e){throw console.error("Failed to load Connect script:",e),e}}createWebComponent(){const e=document.createElement(this.webComponentTag);return Object.entries(this.config).forEach(([i,t])=>{t&&(e[i]=t)}),e}}n.ErrorCode=void 0,(function(r){r.NETWORK_ERROR="network_error",r.AUTH_ERROR="auth_error",r.NOT_FOUND_ERROR="not_found_error",r.VALIDATION_ERROR="validation_error",r.SERVER_ERROR="server_error",r.CLIENT_ERROR="client_error",r.UNKNOWN_ERROR="unknown_error"})(n.ErrorCode||(n.ErrorCode={}));class d extends f{errorMessages={ALREADY_RENDERED:"CspFiatWithdrawals widget is already rendered. Call destroy() before rendering again.",NOT_RENDERED:"CspFiatWithdrawals widget is not rendered. Call render() first.",INVALID_CONTAINER:"Invalid container element provided.",SCRIPT_LOAD_FAILED:"Failed to load the Zerohash CspFiatWithdrawals script.",WEB_COMPONENT_NOT_DEFINED:"Web component is not defined. Script may not be loaded."};scriptUrls={local:"http://localhost:5173/csp-fiat-withdrawals-web/index.js",dev:"https://connect-sdk.dev.0hash.com/csp-fiat-withdrawals-web/index.js",cert:"https://sdk.sandbox.connect.xyz/csp-fiat-withdrawals-web/index.js",prod:"https://sdk.connect.xyz/csp-fiat-withdrawals-web/index.js",sandbox:"https://sdk.sandbox.connect.xyz/csp-fiat-withdrawals-web/index.js",production:"https://sdk.connect.xyz/csp-fiat-withdrawals-web/index.js"};webComponentTag="zerohash-csp-fiat-withdrawals";render(e){return super.render(e)}updateConfig(e){return super.updateConfig(e)}getConfig(){return super.getConfig()}isRendered(){return super.isRendered()}destroy(){return super.destroy()}}n.CspFiatWithdrawals=d,n.default=d,Object.defineProperties(n,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})}));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zerohash-sdk/csp-fiat-withdrawals-js",
3
- "version": "0.1.0",
3
+ "version": "0.1.3",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",