@zerohash-sdk/fiat-account-link-js 1.4.2 → 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,29 +1,147 @@
1
- const c = "production", h = "JWT token is required and must be a string.", l = (n) => {
2
- if (!n || typeof n != "string")
1
+ const C = "production", k = "JWT token is required and must be a string.", z = {
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
+ }, x = (t) => {
10
+ if (!t || typeof t != "string")
3
11
  return null;
4
- const e = n.split(".");
12
+ const e = t.split(".");
5
13
  if (e.length < 2)
6
14
  return null;
7
15
  try {
8
- const r = e[1].replace(/-/g, "+").replace(/_/g, "/"), t = r + "===".slice(0, (4 - r.length % 4) % 4), i = typeof atob < "u" ? atob(t) : Buffer.from(t, "base64").toString("utf-8"), a = JSON.parse(i)?.payload?.region;
9
- if (typeof a != "string")
16
+ const n = e[1].replace(/-/g, "+").replace(/_/g, "/"), r = n + "===".slice(0, (4 - n.length % 4) % 4), o = typeof atob < "u" ? atob(r) : Buffer.from(r, "base64").toString("utf-8"), c = JSON.parse(o)?.payload?.region;
17
+ if (typeof c != "string")
10
18
  return null;
11
- const s = a.toLowerCase();
12
- return s === "us" || s === "eu" ? s : null;
19
+ const i = c.toLowerCase();
20
+ return i === "us" || i === "eu" ? i : null;
13
21
  } catch {
14
22
  return null;
15
23
  }
16
- }, u = (n, e) => l(e) !== "eu" ? n : n === "cert" ? "eu-cert" : n === "prod" ? "eu-prod" : n, p = {};
17
- class m {
24
+ }, L = (t, e) => x(e) !== "eu" ? t : t === "cert" ? "eu-cert" : t === "prod" ? "eu-prod" : t, F = (t) => {
25
+ if (!t || typeof t != "string")
26
+ return {};
27
+ const e = t.split(".");
28
+ if (e.length < 2)
29
+ return {};
30
+ try {
31
+ const n = e[1].replace(/-/g, "+").replace(/_/g, "/"), r = n + "===".slice(0, (4 - n.length % 4) % 4), o = typeof atob < "u" ? atob(r) : Buffer.from(r, "base64").toString("utf-8"), a = JSON.parse(o), c = a?.payload ?? {}, i = (d) => typeof d == "string" && d.length > 0 ? d : void 0;
32
+ return {
33
+ participantCode: i(c.participant_code),
34
+ platformName: i(c.platform_name),
35
+ platformCode: i(a.platform_code),
36
+ region: i(c.region)
37
+ };
38
+ } catch {
39
+ return {};
40
+ }
41
+ }, T = (t, e, n) => {
42
+ const r = L(e, n);
43
+ return t[r] ?? t[e] ?? t.prod;
44
+ }, M = (t, e, n) => {
45
+ const r = L(e, n);
46
+ return t[r] ?? t[e];
47
+ }, _ = () => {
48
+ }, W = () => {
49
+ const t = new Uint8Array(8);
50
+ return globalThis.crypto.getRandomValues(t), Array.from(t, (e) => e.toString(16).padStart(2, "0")).join("");
51
+ }, P = (t, e) => {
52
+ const n = W(), r = globalThis.__ZH_WEB_SDK_VERSION__, o = {};
53
+ t.claims.participantCode && (o.participant_code = t.claims.participantCode), t.claims.platformName && (o.platform_name = t.claims.platformName), t.claims.platformCode && (o.platform_code = t.claims.platformCode), t.claims.region && (o.region = t.claims.region), r && (o.zh_web_sdk_version = r);
54
+ const a = {
55
+ meta: {
56
+ app: { name: t.appName, version: e ?? "unknown", environment: t.env },
57
+ session: { id: n, 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 ${t.webComponentTag} from ${t.env} environment.`,
64
+ level: "error",
65
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
66
+ context: {
67
+ web_component: t.webComponentTag,
68
+ script_url: t.scriptUrl,
69
+ reason: t.reason,
70
+ tried_fallback: String(t.triedFallback),
71
+ elapsed_ms: String(t.elapsedMs)
72
+ }
73
+ }
74
+ ]
75
+ };
76
+ return { sessionId: n, payload: a };
77
+ }, U = (t, e, n) => {
78
+ if (!t || typeof fetch > "u")
79
+ return;
80
+ const { sessionId: r, payload: o } = P(e, n);
81
+ try {
82
+ fetch(t, {
83
+ method: "POST",
84
+ headers: { "Content-Type": "application/json", "x-faro-session-id": r },
85
+ body: JSON.stringify(o),
86
+ keepalive: !0
87
+ }).catch(() => {
88
+ });
89
+ } catch {
90
+ }
91
+ }, j = (t) => {
92
+ const { webComponentTag: e, appName: n, appVersion: r, scriptUrls: o, fallbackScriptUrls: a, collectorUrls: c, env: i, jwt: d, timeoutMs: S = 15e3, onLoad: O, onError: v } = t;
93
+ if (typeof document > "u")
94
+ return _;
95
+ const m = `${e}-script-${i}`;
96
+ if (customElements.get(e) || document.getElementById(m))
97
+ return _;
98
+ const I = F(d), A = t.report ?? ((l) => U(c && M(c, i, d), l, r));
99
+ let u = !1, w = 0, h;
100
+ const f = () => {
101
+ h !== void 0 && clearTimeout(h);
102
+ }, g = (l, p, s) => {
103
+ if (u)
104
+ return;
105
+ const D = Math.round(performance.now() - w), y = {
106
+ webComponentTag: e,
107
+ appName: n,
108
+ env: i,
109
+ scriptUrl: p,
110
+ reason: l,
111
+ triedFallback: s,
112
+ elapsedMs: D,
113
+ claims: I
114
+ };
115
+ A(y);
116
+ const E = s ? void 0 : T(a ?? {}, i, d);
117
+ if (E && E !== p) {
118
+ b(E, !0);
119
+ return;
120
+ }
121
+ u = !0, f(), document.getElementById(m)?.remove(), v?.(y);
122
+ }, b = (l, p) => {
123
+ f(), w = performance.now();
124
+ const s = document.createElement("script");
125
+ s.id = m, s.src = l, s.type = "module", s.async = !0, s.onload = () => {
126
+ setTimeout(() => {
127
+ u || (customElements.get(e) ? (u = !0, f(), O?.()) : g("not-defined", l, p));
128
+ }, 0);
129
+ }, s.onerror = () => g("network", l, p), h = setTimeout(() => g("timeout", l, p), S), document.getElementById(m)?.remove(), document.head.appendChild(s);
130
+ }, R = T(o, i, d);
131
+ return R ? (b(R, !1), () => {
132
+ u = !0, f();
133
+ }) : _;
134
+ }, B = {};
135
+ class V {
18
136
  config;
19
137
  state;
20
138
  scriptLoadingPromise;
21
139
  constructor(e) {
22
140
  if (!e.jwt || typeof e.jwt != "string")
23
- throw new Error(h);
141
+ throw new Error(k);
24
142
  this.config = {
25
143
  ...e,
26
- env: e.env || c,
144
+ env: e.env || C,
27
145
  theme: e.theme
28
146
  }, this.state = {
29
147
  initialized: !1,
@@ -44,10 +162,10 @@ class m {
44
162
  throw new Error(this.errorMessages.ALREADY_RENDERED);
45
163
  try {
46
164
  await this.ensureScriptLoaded();
47
- const r = this.createWebComponent();
48
- e.innerHTML = "", e.appendChild(r), this.state.container = e, this.state.element = r, this.state.initialized = !0;
49
- } catch (r) {
50
- throw console.error("Failed to render widget:", r), r;
165
+ const n = this.createWebComponent();
166
+ e.innerHTML = "", e.appendChild(n), this.state.container = e, this.state.element = n, this.state.initialized = !0;
167
+ } catch (n) {
168
+ throw console.error("Failed to render widget:", n), n;
51
169
  }
52
170
  }
53
171
  /**
@@ -58,9 +176,9 @@ class m {
58
176
  updateConfig(e) {
59
177
  if (!this.state.initialized || !this.state.element)
60
178
  throw new Error(this.errorMessages.NOT_RENDERED);
61
- const r = this.state.element;
62
- Object.entries(e).forEach(([t, i]) => {
63
- i && (this.config[t] = i, r[t] = i);
179
+ const n = this.state.element;
180
+ Object.entries(e).forEach(([r, o]) => {
181
+ o && (this.config[r] = o, n[r] = o);
64
182
  });
65
183
  }
66
184
  /**
@@ -84,7 +202,7 @@ class m {
84
202
  return { ...this.config };
85
203
  }
86
204
  getEnvironment() {
87
- return this.config.env || c;
205
+ return this.config.env || C;
88
206
  }
89
207
  getScriptId() {
90
208
  return `${this.webComponentTag}-script-${this.getEnvironment()}`;
@@ -95,25 +213,31 @@ class m {
95
213
  getWebComponent() {
96
214
  return customElements.get(this.webComponentTag);
97
215
  }
98
- getScriptUrl() {
99
- if (typeof import.meta < "u")
100
- return p.VITE_SCRIPT_URL || this.scriptUrls[this.getEnvironment()];
101
- const e = u(this.getEnvironment(), this.config.jwt);
102
- return this.scriptUrls[e] ?? this.scriptUrls[this.getEnvironment()];
216
+ getEffectiveScriptUrls() {
217
+ if (typeof import.meta < "u") {
218
+ const e = B.VITE_SCRIPT_URL;
219
+ if (e)
220
+ return { [this.getEnvironment()]: e };
221
+ }
222
+ return this.scriptUrls;
103
223
  }
104
224
  async loadScript() {
105
- if (!this.isScriptLoaded()) {
225
+ if (!(this.getWebComponent() || this.isScriptLoaded())) {
106
226
  if (this.scriptLoadingPromise)
107
227
  return this.scriptLoadingPromise;
108
- this.scriptLoadingPromise = new Promise((e, r) => {
109
- const t = document.createElement("script");
110
- t.id = this.getScriptId(), t.src = this.getScriptUrl(), t.type = "module", t.async = !0, t.onload = () => {
111
- setTimeout(() => {
112
- this.getWebComponent() ? e() : r(new Error(this.errorMessages.WEB_COMPONENT_NOT_DEFINED));
113
- }, 0);
114
- }, t.onerror = () => {
115
- this.scriptLoadingPromise = void 0, r(new Error(`${this.errorMessages.SCRIPT_LOAD_FAILED} (${this.getEnvironment()})`));
116
- }, document.head.appendChild(t);
228
+ this.scriptLoadingPromise = new Promise((e, n) => {
229
+ j({
230
+ webComponentTag: this.webComponentTag,
231
+ appName: this.webComponentTag,
232
+ scriptUrls: this.getEffectiveScriptUrls(),
233
+ collectorUrls: z,
234
+ env: this.getEnvironment(),
235
+ jwt: this.config.jwt,
236
+ onLoad: e,
237
+ onError: (r) => {
238
+ n(new Error(r.reason === "not-defined" ? this.errorMessages.WEB_COMPONENT_NOT_DEFINED : `${this.errorMessages.SCRIPT_LOAD_FAILED} (${this.getEnvironment()})`));
239
+ }
240
+ });
117
241
  });
118
242
  try {
119
243
  await this.scriptLoadingPromise;
@@ -125,14 +249,14 @@ class m {
125
249
  }
126
250
  async waitForWebComponent(e = 5e3) {
127
251
  if (!this.getWebComponent())
128
- return new Promise((r, t) => {
129
- const i = setTimeout(() => {
130
- t(new Error(`Timeout waiting for ${this.webComponentTag} to be defined`));
252
+ return new Promise((n, r) => {
253
+ const o = setTimeout(() => {
254
+ r(new Error(`Timeout waiting for ${this.webComponentTag} to be defined`));
131
255
  }, e);
132
256
  customElements.whenDefined(this.webComponentTag).then(() => {
133
- clearTimeout(i), r();
134
- }).catch((o) => {
135
- clearTimeout(i), t(o);
257
+ clearTimeout(o), n();
258
+ }).catch((a) => {
259
+ clearTimeout(o), r(a);
136
260
  });
137
261
  });
138
262
  }
@@ -149,16 +273,16 @@ class m {
149
273
  }
150
274
  createWebComponent() {
151
275
  const e = document.createElement(this.webComponentTag);
152
- return Object.entries(this.config).forEach(([r, t]) => {
153
- t && (e[r] = t);
276
+ return Object.entries(this.config).forEach(([n, r]) => {
277
+ r && (e[n] = r);
154
278
  }), e;
155
279
  }
156
280
  }
157
- var d;
158
- (function(n) {
159
- n.NETWORK_ERROR = "network_error", n.AUTH_ERROR = "auth_error", n.NOT_FOUND_ERROR = "not_found_error", n.VALIDATION_ERROR = "validation_error", n.SERVER_ERROR = "server_error", n.CLIENT_ERROR = "client_error", n.UNKNOWN_ERROR = "unknown_error";
160
- })(d || (d = {}));
161
- class g extends m {
281
+ var N;
282
+ (function(t) {
283
+ t.NETWORK_ERROR = "network_error", t.AUTH_ERROR = "auth_error", t.NOT_FOUND_ERROR = "not_found_error", t.VALIDATION_ERROR = "validation_error", t.SERVER_ERROR = "server_error", t.CLIENT_ERROR = "client_error", t.UNKNOWN_ERROR = "unknown_error";
284
+ })(N || (N = {}));
285
+ class $ extends V {
162
286
  errorMessages = {
163
287
  ALREADY_RENDERED: "FiatAccountLink widget is already rendered. Call destroy() before rendering again.",
164
288
  NOT_RENDERED: "FiatAccountLink widget is not rendered. Call render() first.",
@@ -192,7 +316,7 @@ class g extends m {
192
316
  }
193
317
  }
194
318
  export {
195
- d as ErrorCode,
196
- g as FiatAccountLink,
197
- g as default
319
+ N as ErrorCode,
320
+ $ as FiatAccountLink,
321
+ $ as default
198
322
  };
@@ -1 +1 @@
1
- (function(r,s){typeof exports=="object"&&typeof module<"u"?s(exports):typeof define=="function"&&define.amd?define(["exports"],s):(r=typeof globalThis<"u"?globalThis:r||self,s(r.FiatAccountLink={}))})(this,(function(r){"use strict";var s=typeof document<"u"?document.currentScript:null;const c="production",h="JWT token is required and must be a string.",p=n=>{if(!n||typeof n!="string")return null;const e=n.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),o=typeof atob<"u"?atob(t):Buffer.from(t,"base64").toString("utf-8"),l=JSON.parse(o)?.payload?.region;if(typeof l!="string")return null;const a=l.toLowerCase();return a==="us"||a==="eu"?a:null}catch{return null}},f=(n,e)=>p(e)!=="eu"?n:n==="cert"?"eu-cert":n==="prod"?"eu-prod":n,m={};class g{config;state;scriptLoadingPromise;constructor(e){if(!e.jwt||typeof e.jwt!="string")throw new Error(h);this.config={...e,env:e.env||c,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||c}getScriptId(){return`${this.webComponentTag}-script-${this.getEnvironment()}`}isScriptLoaded(){return!!document.getElementById(this.getScriptId())}getWebComponent(){return customElements.get(this.webComponentTag)}getScriptUrl(){if(typeof{url:typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__filename).href:typeof document>"u"?location.href:s&&s.tagName.toUpperCase()==="SCRIPT"&&s.src||new URL("index.umd.cjs",document.baseURI).href}<"u")return m.VITE_SCRIPT_URL||this.scriptUrls[this.getEnvironment()];const e=f(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 o=setTimeout(()=>{t(new Error(`Timeout waiting for ${this.webComponentTag} to be defined`))},e);customElements.whenDefined(this.webComponentTag).then(()=>{clearTimeout(o),i()}).catch(u=>{clearTimeout(o),t(u)})})}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(n){n.NETWORK_ERROR="network_error",n.AUTH_ERROR="auth_error",n.NOT_FOUND_ERROR="not_found_error",n.VALIDATION_ERROR="validation_error",n.SERVER_ERROR="server_error",n.CLIENT_ERROR="client_error",n.UNKNOWN_ERROR="unknown_error"})(r.ErrorCode||(r.ErrorCode={}));class d extends g{errorMessages={ALREADY_RENDERED:"FiatAccountLink widget is already rendered. Call destroy() before rendering again.",NOT_RENDERED:"FiatAccountLink widget is not rendered. Call render() first.",INVALID_CONTAINER:"Invalid container element provided.",SCRIPT_LOAD_FAILED:"Failed to load the Connect FiatAccountLink script.",WEB_COMPONENT_NOT_DEFINED:"Web component is not defined. Script may not be loaded."};scriptUrls={local:"http://localhost:4208/fiat-account-link-web/index.js",dev:"https://connect-sdk.dev.0hash.com/fiat-account-link-web/index.js",cert:"https://sdk.sandbox.connect.xyz/fiat-account-link-web/index.js",prod:"https://sdk.connect.xyz/fiat-account-link-web/index.js",sandbox:"https://sdk.sandbox.connect.xyz/fiat-account-link-web/index.js",production:"https://sdk.connect.xyz/fiat-account-link-web/index.js"};webComponentTag="zerohash-fiat-account-link";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.FiatAccountLink=d,r.default=d,Object.defineProperties(r,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})}));
1
+ (function(s,u){typeof exports=="object"&&typeof module<"u"?u(exports):typeof define=="function"&&define.amd?define(["exports"],u):(s=typeof globalThis<"u"?globalThis:s||self,u(s.FiatAccountLink={}))})(this,(function(s){"use strict";var u=typeof document<"u"?document.currentScript:null;const R="production",O="JWT token is required and must be a string.",I={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"},A=t=>{if(!t||typeof t!="string")return null;const e=t.split(".");if(e.length<2)return null;try{const n=e[1].replace(/-/g,"+").replace(/_/g,"/"),r=n+"===".slice(0,(4-n.length%4)%4),o=typeof atob<"u"?atob(r):Buffer.from(r,"base64").toString("utf-8"),d=JSON.parse(o)?.payload?.region;if(typeof d!="string")return null;const i=d.toLowerCase();return i==="us"||i==="eu"?i:null}catch{return null}},y=(t,e)=>A(e)!=="eu"?t:t==="cert"?"eu-cert":t==="prod"?"eu-prod":t,k=t=>{if(!t||typeof t!="string")return{};const e=t.split(".");if(e.length<2)return{};try{const n=e[1].replace(/-/g,"+").replace(/_/g,"/"),r=n+"===".slice(0,(4-n.length%4)%4),o=typeof atob<"u"?atob(r):Buffer.from(r,"base64").toString("utf-8"),c=JSON.parse(o),d=c?.payload??{},i=l=>typeof l=="string"&&l.length>0?l:void 0;return{participantCode:i(d.participant_code),platformName:i(d.platform_name),platformCode:i(c.platform_code),region:i(d.region)}}catch{return{}}},C=(t,e,n)=>{const r=y(e,n);return t[r]??t[e]??t.prod},D=(t,e,n)=>{const r=y(e,n);return t[r]??t[e]},_=()=>{},z=()=>{const t=new Uint8Array(8);return globalThis.crypto.getRandomValues(t),Array.from(t,e=>e.toString(16).padStart(2,"0")).join("")},F=(t,e)=>{const n=z(),r=globalThis.__ZH_WEB_SDK_VERSION__,o={};t.claims.participantCode&&(o.participant_code=t.claims.participantCode),t.claims.platformName&&(o.platform_name=t.claims.platformName),t.claims.platformCode&&(o.platform_code=t.claims.platformCode),t.claims.region&&(o.region=t.claims.region),r&&(o.zh_web_sdk_version=r);const c={meta:{app:{name:t.appName,version:e??"unknown",environment:t.env},session:{id:n,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 ${t.webComponentTag} from ${t.env} environment.`,level:"error",timestamp:new Date().toISOString(),context:{web_component:t.webComponentTag,script_url:t.scriptUrl,reason:t.reason,tried_fallback:String(t.triedFallback),elapsed_ms:String(t.elapsedMs)}}]};return{sessionId:n,payload:c}},M=(t,e,n)=>{if(!t||typeof fetch>"u")return;const{sessionId:r,payload:o}=F(e,n);try{fetch(t,{method:"POST",headers:{"Content-Type":"application/json","x-faro-session-id":r},body:JSON.stringify(o),keepalive:!0}).catch(()=>{})}catch{}},U=t=>{const{webComponentTag:e,appName:n,appVersion:r,scriptUrls:o,fallbackScriptUrls:c,collectorUrls:d,env:i,jwt:l,timeoutMs:W=15e3,onLoad:x,onError:B}=t;if(typeof document>"u")return _;const h=`${e}-script-${i}`;if(customElements.get(e)||document.getElementById(h))return _;const V=k(l),$=t.report??(p=>M(d&&D(d,i,l),p,r));let m=!1,L=0,E;const g=()=>{E!==void 0&&clearTimeout(E)},w=(p,f,a)=>{if(m)return;const J=Math.round(performance.now()-L),v={webComponentTag:e,appName:n,env:i,scriptUrl:f,reason:p,triedFallback:a,elapsedMs:J,claims:V};$(v);const b=a?void 0:C(c??{},i,l);if(b&&b!==f){N(b,!0);return}m=!0,g(),document.getElementById(h)?.remove(),B?.(v)},N=(p,f)=>{g(),L=performance.now();const a=document.createElement("script");a.id=h,a.src=p,a.type="module",a.async=!0,a.onload=()=>{setTimeout(()=>{m||(customElements.get(e)?(m=!0,g(),x?.()):w("not-defined",p,f))},0)},a.onerror=()=>w("network",p,f),E=setTimeout(()=>w("timeout",p,f),W),document.getElementById(h)?.remove(),document.head.appendChild(a)},S=C(o,i,l);return S?(N(S,!1),()=>{m=!0,g()}):_},P={};class j{config;state;scriptLoadingPromise;constructor(e){if(!e.jwt||typeof e.jwt!="string")throw new Error(O);this.config={...e,env:e.env||R,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 n=this.createWebComponent();e.innerHTML="",e.appendChild(n),this.state.container=e,this.state.element=n,this.state.initialized=!0}catch(n){throw console.error("Failed to render widget:",n),n}}updateConfig(e){if(!this.state.initialized||!this.state.element)throw new Error(this.errorMessages.NOT_RENDERED);const n=this.state.element;Object.entries(e).forEach(([r,o])=>{o&&(this.config[r]=o,n[r]=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||R}getScriptId(){return`${this.webComponentTag}-script-${this.getEnvironment()}`}isScriptLoaded(){return!!document.getElementById(this.getScriptId())}getWebComponent(){return customElements.get(this.webComponentTag)}getEffectiveScriptUrls(){if(typeof{url:typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__filename).href:typeof document>"u"?location.href:u&&u.tagName.toUpperCase()==="SCRIPT"&&u.src||new URL("index.umd.cjs",document.baseURI).href}<"u"){const e=P.VITE_SCRIPT_URL;if(e)return{[this.getEnvironment()]:e}}return this.scriptUrls}async loadScript(){if(!(this.getWebComponent()||this.isScriptLoaded())){if(this.scriptLoadingPromise)return this.scriptLoadingPromise;this.scriptLoadingPromise=new Promise((e,n)=>{U({webComponentTag:this.webComponentTag,appName:this.webComponentTag,scriptUrls:this.getEffectiveScriptUrls(),collectorUrls:I,env:this.getEnvironment(),jwt:this.config.jwt,onLoad:e,onError:r=>{n(new Error(r.reason==="not-defined"?this.errorMessages.WEB_COMPONENT_NOT_DEFINED:`${this.errorMessages.SCRIPT_LOAD_FAILED} (${this.getEnvironment()})`))}})});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((n,r)=>{const o=setTimeout(()=>{r(new Error(`Timeout waiting for ${this.webComponentTag} to be defined`))},e);customElements.whenDefined(this.webComponentTag).then(()=>{clearTimeout(o),n()}).catch(c=>{clearTimeout(o),r(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(([n,r])=>{r&&(e[n]=r)}),e}}s.ErrorCode=void 0,(function(t){t.NETWORK_ERROR="network_error",t.AUTH_ERROR="auth_error",t.NOT_FOUND_ERROR="not_found_error",t.VALIDATION_ERROR="validation_error",t.SERVER_ERROR="server_error",t.CLIENT_ERROR="client_error",t.UNKNOWN_ERROR="unknown_error"})(s.ErrorCode||(s.ErrorCode={}));class T extends j{errorMessages={ALREADY_RENDERED:"FiatAccountLink widget is already rendered. Call destroy() before rendering again.",NOT_RENDERED:"FiatAccountLink widget is not rendered. Call render() first.",INVALID_CONTAINER:"Invalid container element provided.",SCRIPT_LOAD_FAILED:"Failed to load the Connect FiatAccountLink script.",WEB_COMPONENT_NOT_DEFINED:"Web component is not defined. Script may not be loaded."};scriptUrls={local:"http://localhost:4208/fiat-account-link-web/index.js",dev:"https://connect-sdk.dev.0hash.com/fiat-account-link-web/index.js",cert:"https://sdk.sandbox.connect.xyz/fiat-account-link-web/index.js",prod:"https://sdk.connect.xyz/fiat-account-link-web/index.js",sandbox:"https://sdk.sandbox.connect.xyz/fiat-account-link-web/index.js",production:"https://sdk.connect.xyz/fiat-account-link-web/index.js"};webComponentTag="zerohash-fiat-account-link";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.FiatAccountLink=T,s.default=T,Object.defineProperties(s,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})}));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zerohash-sdk/fiat-account-link-js",
3
- "version": "1.4.2",
3
+ "version": "1.5.0",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",