@zerohash-sdk/fiat-deposits-js 1.4.1 → 1.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -185,21 +185,22 @@ declare abstract class BaseJsSdk<Config extends BaseConfig<never> = BaseConfig>
185
185
  return customElements.get(this.webComponentTag);
186
186
  }
187
187
 
188
- private getScriptUrl() {
189
- // Support local development with Vite
188
+ private getEffectiveScriptUrls(): Record<string, string> {
189
+ // Support local development with Vite: an internal build pins the script
190
+ // URL for the configured env, bypassing the CDN maps entirely.
190
191
  if (typeof import.meta !== 'undefined' && import.meta.env?.['VITE_INTERNAL_BUILD'] === 'true') {
191
- return import.meta.env['VITE_SCRIPT_URL'] || this.scriptUrls[this.getEnvironment()];
192
+ const override = import.meta.env['VITE_SCRIPT_URL'];
193
+ if (override) return { [this.getEnvironment()]: override };
192
194
  }
193
195
 
194
- // Route EU partners (region claim in JWT) to EU-hosted assets without
195
- // changing the public `env` contract — falls back to the configured env
196
- // when no EU URL is registered for that environment.
197
- const effectiveEnv = resolveEnvByRegion(this.getEnvironment(), this.config.jwt);
198
- return this.scriptUrls[effectiveEnv] ?? this.scriptUrls[this.getEnvironment()];
196
+ return this.scriptUrls;
199
197
  }
200
198
 
201
199
  private async loadScript() {
202
- if (this.isScriptLoaded()) {
200
+ // When the element is already defined or another instance's script tag is
201
+ // in flight, defer to waitForWebComponent — the shared loader would no-op
202
+ // for those cases and never settle this promise.
203
+ if (this.getWebComponent() || this.isScriptLoaded()) {
203
204
  return;
204
205
  }
205
206
 
@@ -207,29 +208,28 @@ declare abstract class BaseJsSdk<Config extends BaseConfig<never> = BaseConfig>
207
208
  return this.scriptLoadingPromise;
208
209
  }
209
210
 
211
+ // The shared loader also reports failures to Faro (with JWT claims for
212
+ // partner/participant context) and removes a failed tag so a later
213
+ // render() call can retry cleanly.
210
214
  this.scriptLoadingPromise = new Promise<void>((resolve, reject) => {
211
- const script = document.createElement('script');
212
- script.id = this.getScriptId();
213
- script.src = this.getScriptUrl();
214
- script.type = 'module';
215
- script.async = true;
216
-
217
- script.onload = () => {
218
- setTimeout(() => {
219
- if (this.getWebComponent()) {
220
- resolve();
221
- } else {
222
- reject(new Error(this.errorMessages.WEB_COMPONENT_NOT_DEFINED));
223
- }
224
- }, 0);
225
- };
226
-
227
- script.onerror = () => {
228
- this.scriptLoadingPromise = undefined;
229
- reject(new Error(`${this.errorMessages.SCRIPT_LOAD_FAILED} (${this.getEnvironment()})`));
230
- };
231
-
232
- document.head.appendChild(script);
215
+ loadWebComponentScript({
216
+ webComponentTag: this.webComponentTag,
217
+ appName: this.webComponentTag,
218
+ scriptUrls: this.getEffectiveScriptUrls(),
219
+ collectorUrls: FARO_COLLECTOR_URLS,
220
+ env: this.getEnvironment(),
221
+ jwt: this.config.jwt,
222
+ onLoad: resolve,
223
+ onError: (info) => {
224
+ reject(
225
+ new Error(
226
+ info.reason === 'not-defined'
227
+ ? this.errorMessages.WEB_COMPONENT_NOT_DEFINED
228
+ : `${this.errorMessages.SCRIPT_LOAD_FAILED} (${this.getEnvironment()})`
229
+ )
230
+ );
231
+ },
232
+ });
233
233
  });
234
234
 
235
235
  try {
package/dist/index.js CHANGED
@@ -1,30 +1,148 @@
1
- const d = "production", h = "JWT token is required and must be a string.", p = (r) => {
2
- if (!r || typeof r != "string")
1
+ const C = "production", z = "JWT token is required and must be a string.", x = {
2
+ dev: "https://grafana-faro-collector.dev.0hash.com/collect",
3
+ cert: "https://grafana-faro-collector.cert.zerohash.com/collect",
4
+ prod: "https://grafana-faro-collector.zerohash.com/collect",
5
+ "eu-cert": "https://grafana-faro-collector.cert.zerohash.eu/collect",
6
+ "eu-prod": "https://grafana-faro-collector.zerohash.eu/collect",
7
+ sandbox: "https://grafana-faro-collector.cert.zerohash.com/collect",
8
+ production: "https://grafana-faro-collector.zerohash.com/collect"
9
+ }, F = (e) => {
10
+ if (!e || typeof e != "string")
3
11
  return null;
4
- const e = r.split(".");
5
- if (e.length < 2)
12
+ const t = e.split(".");
13
+ if (t.length < 2)
6
14
  return null;
7
15
  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")
16
+ const r = t[1].replace(/-/g, "+").replace(/_/g, "/"), n = r + "===".slice(0, (4 - r.length % 4) % 4), o = typeof atob < "u" ? atob(n) : Buffer.from(n, "base64").toString("utf-8"), c = JSON.parse(o)?.payload?.region;
17
+ if (typeof c != "string")
10
18
  return null;
11
- const s = a.toLowerCase();
19
+ const s = c.toLowerCase();
12
20
  return s === "us" || s === "eu" ? s : null;
13
21
  } catch {
14
22
  return null;
15
23
  }
16
- }, l = (r, e) => p(e) !== "eu" ? r : r === "cert" ? "eu-cert" : r === "prod" ? "eu-prod" : r;
17
- class u {
24
+ }, O = (e, t) => F(t) !== "eu" ? e : e === "cert" ? "eu-cert" : e === "prod" ? "eu-prod" : e, M = (e) => {
25
+ if (!e || typeof e != "string")
26
+ return {};
27
+ const t = e.split(".");
28
+ if (t.length < 2)
29
+ return {};
30
+ try {
31
+ const r = t[1].replace(/-/g, "+").replace(/_/g, "/"), n = r + "===".slice(0, (4 - r.length % 4) % 4), o = typeof atob < "u" ? atob(n) : Buffer.from(n, "base64").toString("utf-8"), a = JSON.parse(o), c = a?.payload ?? {}, s = (d) => typeof d == "string" && d.length > 0 ? d : void 0;
32
+ return {
33
+ participantCode: s(c.participant_code),
34
+ platformName: s(c.platform_name),
35
+ platformCode: s(a.platform_code),
36
+ region: s(c.region)
37
+ };
38
+ } catch {
39
+ return {};
40
+ }
41
+ }, T = (e, t, r) => {
42
+ const n = O(t, r);
43
+ return e[n] ?? e[t] ?? e.prod;
44
+ }, W = (e, t, r) => {
45
+ const n = O(t, r);
46
+ return e[n] ?? e[t];
47
+ }, w = () => {
48
+ }, P = () => {
49
+ const e = new Uint8Array(8);
50
+ return globalThis.crypto.getRandomValues(e), Array.from(e, (t) => t.toString(16).padStart(2, "0")).join("");
51
+ }, j = (e, t) => {
52
+ const r = P(), n = globalThis.__ZH_WEB_SDK_VERSION__, o = {};
53
+ e.claims.participantCode && (o.participant_code = e.claims.participantCode), e.claims.platformName && (o.platform_name = e.claims.platformName), e.claims.platformCode && (o.platform_code = e.claims.platformCode), e.claims.region && (o.region = e.claims.region), n && (o.zh_web_sdk_version = n);
54
+ const a = {
55
+ meta: {
56
+ app: { name: e.appName, version: t ?? "unknown", environment: e.env },
57
+ session: { id: r, attributes: o },
58
+ browser: typeof navigator < "u" ? { userAgent: navigator.userAgent } : void 0,
59
+ page: typeof window < "u" ? { url: window.location.origin } : void 0
60
+ },
61
+ logs: [
62
+ {
63
+ message: `Failed to load the script for ${e.webComponentTag} from ${e.env} environment.`,
64
+ level: "error",
65
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
66
+ context: {
67
+ web_component: e.webComponentTag,
68
+ script_url: e.scriptUrl,
69
+ reason: e.reason,
70
+ tried_fallback: String(e.triedFallback),
71
+ elapsed_ms: String(e.elapsedMs)
72
+ }
73
+ }
74
+ ]
75
+ };
76
+ return { sessionId: r, payload: a };
77
+ }, k = (e, t, r) => {
78
+ if (!e || typeof fetch > "u")
79
+ return;
80
+ const { sessionId: n, payload: o } = j(t, r);
81
+ try {
82
+ fetch(e, {
83
+ method: "POST",
84
+ headers: { "Content-Type": "application/json", "x-faro-session-id": n },
85
+ body: JSON.stringify(o),
86
+ keepalive: !0
87
+ }).catch(() => {
88
+ });
89
+ } catch {
90
+ }
91
+ }, U = (e) => {
92
+ const { webComponentTag: t, appName: r, appVersion: n, scriptUrls: o, fallbackScriptUrls: a, collectorUrls: c, env: s, jwt: d, timeoutMs: S = 15e3, onLoad: L, onError: I } = e;
93
+ if (typeof document > "u")
94
+ return w;
95
+ const u = `${t}-script-${s}`;
96
+ if (customElements.get(t) || document.getElementById(u))
97
+ return w;
98
+ const v = M(d), D = e.report ?? ((l) => k(c && W(c, s, d), l, n));
99
+ let m = !1, _ = 0, h;
100
+ const f = () => {
101
+ h !== void 0 && clearTimeout(h);
102
+ }, g = (l, p, i) => {
103
+ if (m)
104
+ return;
105
+ const A = Math.round(performance.now() - _), y = {
106
+ webComponentTag: t,
107
+ appName: r,
108
+ env: s,
109
+ scriptUrl: p,
110
+ reason: l,
111
+ triedFallback: i,
112
+ elapsedMs: A,
113
+ claims: v
114
+ };
115
+ D(y);
116
+ const E = i ? void 0 : T(a ?? {}, s, d);
117
+ if (E && E !== p) {
118
+ b(E, !0);
119
+ return;
120
+ }
121
+ m = !0, f(), document.getElementById(u)?.remove(), I?.(y);
122
+ }, b = (l, p) => {
123
+ f(), _ = performance.now();
124
+ const i = document.createElement("script");
125
+ i.id = u, i.src = l, i.type = "module", i.async = !0, i.onload = () => {
126
+ setTimeout(() => {
127
+ m || (customElements.get(t) ? (m = !0, f(), L?.()) : g("not-defined", l, p));
128
+ }, 0);
129
+ }, i.onerror = () => g("network", l, p), h = setTimeout(() => g("timeout", l, p), S), document.getElementById(u)?.remove(), document.head.appendChild(i);
130
+ }, R = T(o, s, d);
131
+ return R ? (b(R, !1), () => {
132
+ m = !0, f();
133
+ }) : w;
134
+ };
135
+ class B {
18
136
  config;
19
137
  state;
20
138
  scriptLoadingPromise;
21
- constructor(e) {
22
- if (!e.jwt || typeof e.jwt != "string")
23
- throw new Error(h);
139
+ constructor(t) {
140
+ if (!t.jwt || typeof t.jwt != "string")
141
+ throw new Error(z);
24
142
  this.config = {
25
- ...e,
26
- env: e.env || d,
27
- theme: e.theme
143
+ ...t,
144
+ env: t.env || C,
145
+ theme: t.theme
28
146
  }, this.state = {
29
147
  initialized: !1,
30
148
  scriptLoaded: !1,
@@ -37,17 +155,17 @@ class u {
37
155
  * @param container - The container element to render the widget into
38
156
  * @returns Promise that resolves when the widget is rendered
39
157
  */
40
- async render(e) {
41
- if (!e || !(e instanceof HTMLElement))
158
+ async render(t) {
159
+ if (!t || !(t instanceof HTMLElement))
42
160
  throw new Error(this.errorMessages.INVALID_CONTAINER);
43
161
  if (this.state.initialized)
44
162
  throw new Error(this.errorMessages.ALREADY_RENDERED);
45
163
  try {
46
164
  await this.ensureScriptLoaded();
47
- const i = this.createWebComponent();
48
- e.innerHTML = "", e.appendChild(i), this.state.container = e, this.state.element = i, this.state.initialized = !0;
49
- } catch (i) {
50
- throw console.error("Failed to render widget:", i), i;
165
+ const r = this.createWebComponent();
166
+ t.innerHTML = "", t.appendChild(r), this.state.container = t, this.state.element = r, this.state.initialized = !0;
167
+ } catch (r) {
168
+ throw console.error("Failed to render widget:", r), r;
51
169
  }
52
170
  }
53
171
  /**
@@ -55,12 +173,12 @@ class u {
55
173
  * @param config - Partial configuration to update
56
174
  * @returns void
57
175
  */
58
- updateConfig(e) {
176
+ updateConfig(t) {
59
177
  if (!this.state.initialized || !this.state.element)
60
178
  throw new Error(this.errorMessages.NOT_RENDERED);
61
- const i = this.state.element;
62
- Object.entries(e).forEach(([t, n]) => {
63
- n && (this.config[t] = n, i[t] = n);
179
+ const r = this.state.element;
180
+ Object.entries(t).forEach(([n, o]) => {
181
+ o && (this.config[n] = o, r[n] = o);
64
182
  });
65
183
  }
66
184
  /**
@@ -84,7 +202,7 @@ class u {
84
202
  return { ...this.config };
85
203
  }
86
204
  getEnvironment() {
87
- return this.config.env || d;
205
+ return this.config.env || C;
88
206
  }
89
207
  getScriptId() {
90
208
  return `${this.webComponentTag}-script-${this.getEnvironment()}`;
@@ -95,42 +213,45 @@ class u {
95
213
  getWebComponent() {
96
214
  return customElements.get(this.webComponentTag);
97
215
  }
98
- getScriptUrl() {
99
- const e = l(this.getEnvironment(), this.config.jwt);
100
- return this.scriptUrls[e] ?? this.scriptUrls[this.getEnvironment()];
216
+ getEffectiveScriptUrls() {
217
+ return this.scriptUrls;
101
218
  }
102
219
  async loadScript() {
103
- if (!this.isScriptLoaded()) {
220
+ if (!(this.getWebComponent() || this.isScriptLoaded())) {
104
221
  if (this.scriptLoadingPromise)
105
222
  return this.scriptLoadingPromise;
106
- this.scriptLoadingPromise = new Promise((e, i) => {
107
- const t = document.createElement("script");
108
- t.id = this.getScriptId(), t.src = this.getScriptUrl(), t.type = "module", t.async = !0, t.onload = () => {
109
- setTimeout(() => {
110
- this.getWebComponent() ? e() : i(new Error(this.errorMessages.WEB_COMPONENT_NOT_DEFINED));
111
- }, 0);
112
- }, t.onerror = () => {
113
- this.scriptLoadingPromise = void 0, i(new Error(`${this.errorMessages.SCRIPT_LOAD_FAILED} (${this.getEnvironment()})`));
114
- }, document.head.appendChild(t);
223
+ this.scriptLoadingPromise = new Promise((t, r) => {
224
+ U({
225
+ webComponentTag: this.webComponentTag,
226
+ appName: this.webComponentTag,
227
+ scriptUrls: this.getEffectiveScriptUrls(),
228
+ collectorUrls: x,
229
+ env: this.getEnvironment(),
230
+ jwt: this.config.jwt,
231
+ onLoad: t,
232
+ onError: (n) => {
233
+ r(new Error(n.reason === "not-defined" ? this.errorMessages.WEB_COMPONENT_NOT_DEFINED : `${this.errorMessages.SCRIPT_LOAD_FAILED} (${this.getEnvironment()})`));
234
+ }
235
+ });
115
236
  });
116
237
  try {
117
238
  await this.scriptLoadingPromise;
118
- } catch (e) {
119
- throw this.scriptLoadingPromise = void 0, e;
239
+ } catch (t) {
240
+ throw this.scriptLoadingPromise = void 0, t;
120
241
  }
121
242
  return this.scriptLoadingPromise;
122
243
  }
123
244
  }
124
- async waitForWebComponent(e = 5e3) {
245
+ async waitForWebComponent(t = 5e3) {
125
246
  if (!this.getWebComponent())
126
- return new Promise((i, t) => {
127
- const n = setTimeout(() => {
128
- t(new Error(`Timeout waiting for ${this.webComponentTag} to be defined`));
129
- }, e);
247
+ return new Promise((r, n) => {
248
+ const o = setTimeout(() => {
249
+ n(new Error(`Timeout waiting for ${this.webComponentTag} to be defined`));
250
+ }, t);
130
251
  customElements.whenDefined(this.webComponentTag).then(() => {
131
- clearTimeout(n), i();
132
- }).catch((o) => {
133
- clearTimeout(n), t(o);
252
+ clearTimeout(o), r();
253
+ }).catch((a) => {
254
+ clearTimeout(o), n(a);
134
255
  });
135
256
  });
136
257
  }
@@ -141,22 +262,22 @@ class u {
141
262
  if (!this.state.scriptLoaded)
142
263
  try {
143
264
  await this.loadScript(), await this.waitForWebComponent(), this.state.scriptLoaded = !0;
144
- } catch (e) {
145
- throw console.error("Failed to load Connect script:", e), e;
265
+ } catch (t) {
266
+ throw console.error("Failed to load Connect script:", t), t;
146
267
  }
147
268
  }
148
269
  createWebComponent() {
149
- const e = document.createElement(this.webComponentTag);
150
- return Object.entries(this.config).forEach(([i, t]) => {
151
- t && (e[i] = t);
152
- }), e;
270
+ const t = document.createElement(this.webComponentTag);
271
+ return Object.entries(this.config).forEach(([r, n]) => {
272
+ n && (t[r] = n);
273
+ }), t;
153
274
  }
154
275
  }
155
- var c;
156
- (function(r) {
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";
158
- })(c || (c = {}));
159
- class m extends u {
276
+ var N;
277
+ (function(e) {
278
+ e.NETWORK_ERROR = "network_error", e.AUTH_ERROR = "auth_error", e.NOT_FOUND_ERROR = "not_found_error", e.VALIDATION_ERROR = "validation_error", e.SERVER_ERROR = "server_error", e.CLIENT_ERROR = "client_error", e.UNKNOWN_ERROR = "unknown_error";
279
+ })(N || (N = {}));
280
+ class V extends B {
160
281
  errorMessages = {
161
282
  ALREADY_RENDERED: "FiatDeposits widget is already rendered. Call destroy() before rendering again.",
162
283
  NOT_RENDERED: "FiatDeposits widget is not rendered. Call render() first.",
@@ -178,15 +299,15 @@ class m extends u {
178
299
  * @param container - The container element to render the widget into
179
300
  * @returns Promise that resolves when the widget is rendered
180
301
  */
181
- render(e) {
182
- return super.render(e);
302
+ render(t) {
303
+ return super.render(t);
183
304
  }
184
305
  /**
185
306
  * Update the configuration of the FiatDeposits widget
186
307
  * @param config - Partial configuration to update
187
308
  */
188
- updateConfig(e) {
189
- return super.updateConfig(e);
309
+ updateConfig(t) {
310
+ return super.updateConfig(t);
190
311
  }
191
312
  /**
192
313
  * Get the current configuration
@@ -210,5 +331,5 @@ class m extends u {
210
331
  }
211
332
  }
212
333
  export {
213
- m as FiatDeposits
334
+ V as FiatDeposits
214
335
  };
@@ -1 +1 @@
1
- (function(s,o){typeof exports=="object"&&typeof module<"u"?o(exports):typeof define=="function"&&define.amd?define(["exports"],o):(s=typeof globalThis<"u"?globalThis:s||self,o(s.FiatDeposits={}))})(this,(function(s){"use strict";const o="production",h="JWT token is required and must be a string.",l=i=>{if(!i||typeof i!="string")return null;const e=i.split(".");if(e.length<2)return null;try{const r=e[1].replace(/-/g,"+").replace(/_/g,"/"),t=r+"===".slice(0,(4-r.length%4)%4),n=typeof atob<"u"?atob(t):Buffer.from(t,"base64").toString("utf-8"),p=JSON.parse(n)?.payload?.region;if(typeof p!="string")return null;const a=p.toLowerCase();return a==="us"||a==="eu"?a:null}catch{return null}},u=(i,e)=>l(e)!=="eu"?i:i==="cert"?"eu-cert":i==="prod"?"eu-prod":i;class f{config;state;scriptLoadingPromise;constructor(e){if(!e.jwt||typeof e.jwt!="string")throw new Error(h);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 r=this.createWebComponent();e.innerHTML="",e.appendChild(r),this.state.container=e,this.state.element=r,this.state.initialized=!0}catch(r){throw console.error("Failed to render widget:",r),r}}updateConfig(e){if(!this.state.initialized||!this.state.element)throw new Error(this.errorMessages.NOT_RENDERED);const r=this.state.element;Object.entries(e).forEach(([t,n])=>{n&&(this.config[t]=n,r[t]=n)})}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,r)=>{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():r(new Error(this.errorMessages.WEB_COMPONENT_NOT_DEFINED))},0)},t.onerror=()=>{this.scriptLoadingPromise=void 0,r(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((r,t)=>{const n=setTimeout(()=>{t(new Error(`Timeout waiting for ${this.webComponentTag} to be defined`))},e);customElements.whenDefined(this.webComponentTag).then(()=>{clearTimeout(n),r()}).catch(c=>{clearTimeout(n),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(([r,t])=>{t&&(e[r]=t)}),e}}var d;(function(i){i.NETWORK_ERROR="network_error",i.AUTH_ERROR="auth_error",i.NOT_FOUND_ERROR="not_found_error",i.VALIDATION_ERROR="validation_error",i.SERVER_ERROR="server_error",i.CLIENT_ERROR="client_error",i.UNKNOWN_ERROR="unknown_error"})(d||(d={}));class m extends f{errorMessages={ALREADY_RENDERED:"FiatDeposits widget is already rendered. Call destroy() before rendering again.",NOT_RENDERED:"FiatDeposits widget is not rendered. Call render() first.",INVALID_CONTAINER:"Invalid container element provided.",SCRIPT_LOAD_FAILED:"Failed to load the Connect FiatDeposits script.",WEB_COMPONENT_NOT_DEFINED:"Web component is not defined. Script may not be loaded."};scriptUrls={local:"http://localhost:5173/fiat-deposits-web/index.js",dev:"https://connect-sdk.dev.0hash.com/fiat-deposits-web/index.js",cert:"https://sdk.sandbox.connect.xyz/fiat-deposits-web/index.js",prod:"https://sdk.connect.xyz/fiat-deposits-web/index.js",sandbox:"https://sdk.sandbox.connect.xyz/fiat-deposits-web/index.js",production:"https://sdk.connect.xyz/fiat-deposits-web/index.js"};webComponentTag="zerohash-fiat-deposits";render(e){return super.render(e)}updateConfig(e){return super.updateConfig(e)}getConfig(){return super.getConfig()}isRendered(){return super.isRendered()}destroy(){return super.destroy()}}s.FiatDeposits=m,Object.defineProperty(s,Symbol.toStringTag,{value:"Module"})}));
1
+ (function(p,m){typeof exports=="object"&&typeof module<"u"?m(exports):typeof define=="function"&&define.amd?define(["exports"],m):(p=typeof globalThis<"u"?globalThis:p||self,m(p.FiatDeposits={}))})(this,(function(p){"use strict";const m="production",L="JWT token is required and must be a string.",D={dev:"https://grafana-faro-collector.dev.0hash.com/collect",cert:"https://grafana-faro-collector.cert.zerohash.com/collect",prod:"https://grafana-faro-collector.zerohash.com/collect","eu-cert":"https://grafana-faro-collector.cert.zerohash.eu/collect","eu-prod":"https://grafana-faro-collector.zerohash.eu/collect",sandbox:"https://grafana-faro-collector.cert.zerohash.com/collect",production:"https://grafana-faro-collector.zerohash.com/collect"},v=e=>{if(!e||typeof e!="string")return null;const t=e.split(".");if(t.length<2)return null;try{const r=t[1].replace(/-/g,"+").replace(/_/g,"/"),n=r+"===".slice(0,(4-r.length%4)%4),o=typeof atob<"u"?atob(n):Buffer.from(n,"base64").toString("utf-8"),c=JSON.parse(o)?.payload?.region;if(typeof c!="string")return null;const s=c.toLowerCase();return s==="us"||s==="eu"?s:null}catch{return null}},y=(e,t)=>v(t)!=="eu"?e:e==="cert"?"eu-cert":e==="prod"?"eu-prod":e,I=e=>{if(!e||typeof e!="string")return{};const t=e.split(".");if(t.length<2)return{};try{const r=t[1].replace(/-/g,"+").replace(/_/g,"/"),n=r+"===".slice(0,(4-r.length%4)%4),o=typeof atob<"u"?atob(n):Buffer.from(n,"base64").toString("utf-8"),a=JSON.parse(o),c=a?.payload??{},s=d=>typeof d=="string"&&d.length>0?d:void 0;return{participantCode:s(c.participant_code),platformName:s(c.platform_name),platformCode:s(a.platform_code),region:s(c.region)}}catch{return{}}},R=(e,t,r)=>{const n=y(t,r);return e[n]??e[t]??e.prod},A=(e,t,r)=>{const n=y(t,r);return e[n]??e[t]},E=()=>{},z=()=>{const e=new Uint8Array(8);return globalThis.crypto.getRandomValues(e),Array.from(e,t=>t.toString(16).padStart(2,"0")).join("")},x=(e,t)=>{const r=z(),n=globalThis.__ZH_WEB_SDK_VERSION__,o={};e.claims.participantCode&&(o.participant_code=e.claims.participantCode),e.claims.platformName&&(o.platform_name=e.claims.platformName),e.claims.platformCode&&(o.platform_code=e.claims.platformCode),e.claims.region&&(o.region=e.claims.region),n&&(o.zh_web_sdk_version=n);const a={meta:{app:{name:e.appName,version:t??"unknown",environment:e.env},session:{id:r,attributes:o},browser:typeof navigator<"u"?{userAgent:navigator.userAgent}:void 0,page:typeof window<"u"?{url:window.location.origin}:void 0},logs:[{message:`Failed to load the script for ${e.webComponentTag} from ${e.env} environment.`,level:"error",timestamp:new Date().toISOString(),context:{web_component:e.webComponentTag,script_url:e.scriptUrl,reason:e.reason,tried_fallback:String(e.triedFallback),elapsed_ms:String(e.elapsedMs)}}]};return{sessionId:r,payload:a}},F=(e,t,r)=>{if(!e||typeof fetch>"u")return;const{sessionId:n,payload:o}=x(t,r);try{fetch(e,{method:"POST",headers:{"Content-Type":"application/json","x-faro-session-id":n},body:JSON.stringify(o),keepalive:!0}).catch(()=>{})}catch{}},M=e=>{const{webComponentTag:t,appName:r,appVersion:n,scriptUrls:o,fallbackScriptUrls:a,collectorUrls:c,env:s,jwt:d,timeoutMs:P=15e3,onLoad:k,onError:U}=e;if(typeof document>"u")return E;const h=`${t}-script-${s}`;if(customElements.get(t)||document.getElementById(h))return E;const B=I(d),V=e.report??(l=>F(c&&A(c,s,d),l,n));let f=!1,C=0,w;const g=()=>{w!==void 0&&clearTimeout(w)},_=(l,u,i)=>{if(f)return;const $=Math.round(performance.now()-C),O={webComponentTag:t,appName:r,env:s,scriptUrl:u,reason:l,triedFallback:i,elapsedMs:$,claims:B};V(O);const b=i?void 0:R(a??{},s,d);if(b&&b!==u){N(b,!0);return}f=!0,g(),document.getElementById(h)?.remove(),U?.(O)},N=(l,u)=>{g(),C=performance.now();const i=document.createElement("script");i.id=h,i.src=l,i.type="module",i.async=!0,i.onload=()=>{setTimeout(()=>{f||(customElements.get(t)?(f=!0,g(),k?.()):_("not-defined",l,u))},0)},i.onerror=()=>_("network",l,u),w=setTimeout(()=>_("timeout",l,u),P),document.getElementById(h)?.remove(),document.head.appendChild(i)},S=R(o,s,d);return S?(N(S,!1),()=>{f=!0,g()}):E};class W{config;state;scriptLoadingPromise;constructor(t){if(!t.jwt||typeof t.jwt!="string")throw new Error(L);this.config={...t,env:t.env||m,theme:t.theme},this.state={initialized:!1,scriptLoaded:!1,container:null,element:null}}async render(t){if(!t||!(t 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 r=this.createWebComponent();t.innerHTML="",t.appendChild(r),this.state.container=t,this.state.element=r,this.state.initialized=!0}catch(r){throw console.error("Failed to render widget:",r),r}}updateConfig(t){if(!this.state.initialized||!this.state.element)throw new Error(this.errorMessages.NOT_RENDERED);const r=this.state.element;Object.entries(t).forEach(([n,o])=>{o&&(this.config[n]=o,r[n]=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||m}getScriptId(){return`${this.webComponentTag}-script-${this.getEnvironment()}`}isScriptLoaded(){return!!document.getElementById(this.getScriptId())}getWebComponent(){return customElements.get(this.webComponentTag)}getEffectiveScriptUrls(){return this.scriptUrls}async loadScript(){if(!(this.getWebComponent()||this.isScriptLoaded())){if(this.scriptLoadingPromise)return this.scriptLoadingPromise;this.scriptLoadingPromise=new Promise((t,r)=>{M({webComponentTag:this.webComponentTag,appName:this.webComponentTag,scriptUrls:this.getEffectiveScriptUrls(),collectorUrls:D,env:this.getEnvironment(),jwt:this.config.jwt,onLoad:t,onError:n=>{r(new Error(n.reason==="not-defined"?this.errorMessages.WEB_COMPONENT_NOT_DEFINED:`${this.errorMessages.SCRIPT_LOAD_FAILED} (${this.getEnvironment()})`))}})});try{await this.scriptLoadingPromise}catch(t){throw this.scriptLoadingPromise=void 0,t}return this.scriptLoadingPromise}}async waitForWebComponent(t=5e3){if(!this.getWebComponent())return new Promise((r,n)=>{const o=setTimeout(()=>{n(new Error(`Timeout waiting for ${this.webComponentTag} to be defined`))},t);customElements.whenDefined(this.webComponentTag).then(()=>{clearTimeout(o),r()}).catch(a=>{clearTimeout(o),n(a)})})}async ensureScriptLoaded(){if(!this.state.scriptLoaded)try{await this.loadScript(),await this.waitForWebComponent(),this.state.scriptLoaded=!0}catch(t){throw console.error("Failed to load Connect script:",t),t}}createWebComponent(){const t=document.createElement(this.webComponentTag);return Object.entries(this.config).forEach(([r,n])=>{n&&(t[r]=n)}),t}}var T;(function(e){e.NETWORK_ERROR="network_error",e.AUTH_ERROR="auth_error",e.NOT_FOUND_ERROR="not_found_error",e.VALIDATION_ERROR="validation_error",e.SERVER_ERROR="server_error",e.CLIENT_ERROR="client_error",e.UNKNOWN_ERROR="unknown_error"})(T||(T={}));class j extends W{errorMessages={ALREADY_RENDERED:"FiatDeposits widget is already rendered. Call destroy() before rendering again.",NOT_RENDERED:"FiatDeposits widget is not rendered. Call render() first.",INVALID_CONTAINER:"Invalid container element provided.",SCRIPT_LOAD_FAILED:"Failed to load the Connect FiatDeposits script.",WEB_COMPONENT_NOT_DEFINED:"Web component is not defined. Script may not be loaded."};scriptUrls={local:"http://localhost:5173/fiat-deposits-web/index.js",dev:"https://connect-sdk.dev.0hash.com/fiat-deposits-web/index.js",cert:"https://sdk.sandbox.connect.xyz/fiat-deposits-web/index.js",prod:"https://sdk.connect.xyz/fiat-deposits-web/index.js",sandbox:"https://sdk.sandbox.connect.xyz/fiat-deposits-web/index.js",production:"https://sdk.connect.xyz/fiat-deposits-web/index.js"};webComponentTag="zerohash-fiat-deposits";render(t){return super.render(t)}updateConfig(t){return super.updateConfig(t)}getConfig(){return super.getConfig()}isRendered(){return super.isRendered()}destroy(){return super.destroy()}}p.FiatDeposits=j,Object.defineProperty(p,Symbol.toStringTag,{value:"Module"})}));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zerohash-sdk/fiat-deposits-js",
3
- "version": "1.4.1",
3
+ "version": "1.5.0",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",