@zerohash-sdk/crypto-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
@@ -194,21 +194,22 @@ declare abstract class BaseJsSdk<Config extends BaseConfig<never> = BaseConfig>
194
194
  return customElements.get(this.webComponentTag);
195
195
  }
196
196
 
197
- private getScriptUrl() {
198
- // Support local development with Vite
197
+ private getEffectiveScriptUrls(): Record<string, string> {
198
+ // Support local development with Vite: an internal build pins the script
199
+ // URL for the configured env, bypassing the CDN maps entirely.
199
200
  if (typeof import.meta !== 'undefined' && import.meta.env?.['VITE_INTERNAL_BUILD'] === 'true') {
200
- return import.meta.env['VITE_SCRIPT_URL'] || this.scriptUrls[this.getEnvironment()];
201
+ const override = import.meta.env['VITE_SCRIPT_URL'];
202
+ if (override) return { [this.getEnvironment()]: override };
201
203
  }
202
204
 
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()];
205
+ return this.scriptUrls;
208
206
  }
209
207
 
210
208
  private async loadScript() {
211
- if (this.isScriptLoaded()) {
209
+ // When the element is already defined or another instance's script tag is
210
+ // in flight, defer to waitForWebComponent — the shared loader would no-op
211
+ // for those cases and never settle this promise.
212
+ if (this.getWebComponent() || this.isScriptLoaded()) {
212
213
  return;
213
214
  }
214
215
 
@@ -216,29 +217,28 @@ declare abstract class BaseJsSdk<Config extends BaseConfig<never> = BaseConfig>
216
217
  return this.scriptLoadingPromise;
217
218
  }
218
219
 
220
+ // The shared loader also reports failures to Faro (with JWT claims for
221
+ // partner/participant context) and removes a failed tag so a later
222
+ // render() call can retry cleanly.
219
223
  this.scriptLoadingPromise = new Promise<void>((resolve, reject) => {
220
- const script = document.createElement('script');
221
- script.id = this.getScriptId();
222
- script.src = this.getScriptUrl();
223
- script.type = 'module';
224
- script.async = true;
225
-
226
- script.onload = () => {
227
- setTimeout(() => {
228
- if (this.getWebComponent()) {
229
- resolve();
230
- } else {
231
- reject(new Error(this.errorMessages.WEB_COMPONENT_NOT_DEFINED));
232
- }
233
- }, 0);
234
- };
235
-
236
- script.onerror = () => {
237
- this.scriptLoadingPromise = undefined;
238
- reject(new Error(`${this.errorMessages.SCRIPT_LOAD_FAILED} (${this.getEnvironment()})`));
239
- };
240
-
241
- document.head.appendChild(script);
224
+ loadWebComponentScript({
225
+ webComponentTag: this.webComponentTag,
226
+ appName: this.webComponentTag,
227
+ scriptUrls: this.getEffectiveScriptUrls(),
228
+ collectorUrls: FARO_COLLECTOR_URLS,
229
+ env: this.getEnvironment(),
230
+ jwt: this.config.jwt,
231
+ onLoad: resolve,
232
+ onError: (info) => {
233
+ reject(
234
+ new Error(
235
+ info.reason === 'not-defined'
236
+ ? this.errorMessages.WEB_COMPONENT_NOT_DEFINED
237
+ : `${this.errorMessages.SCRIPT_LOAD_FAILED} (${this.getEnvironment()})`
238
+ )
239
+ );
240
+ },
241
+ });
242
242
  });
243
243
 
244
244
  try {
package/dist/index.js CHANGED
@@ -1,11 +1,19 @@
1
- const a = "production", h = "JWT token is required and must be a string.", l = (r) => {
2
- if (!r || typeof r != "string")
1
+ const C = "production", D = "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 = (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 n = e[1].replace(/-/g, "+").replace(/_/g, "/"), t = n + "===".slice(0, (4 - n.length % 4) % 4), i = typeof atob < "u" ? atob(t) : Buffer.from(t, "base64").toString("utf-8"), c = JSON.parse(i)?.payload?.region;
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;
9
17
  if (typeof c != "string")
10
18
  return null;
11
19
  const s = c.toLowerCase();
@@ -13,18 +21,128 @@ const a = "production", h = "JWT token is required and must be a string.", l = (
13
21
  } catch {
14
22
  return null;
15
23
  }
16
- }, p = (r, e) => l(e) !== "eu" ? r : r === "cert" ? "eu-cert" : r === "prod" ? "eu-prod" : r;
17
- class u {
24
+ }, L = (e, t) => x(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 = L(t, r);
43
+ return e[n] ?? e[t] ?? e.prod;
44
+ }, W = (e, t, r) => {
45
+ const n = L(t, r);
46
+ return e[n] ?? e[t];
47
+ }, w = () => {
48
+ }, j = () => {
49
+ const e = new Uint8Array(8);
50
+ return globalThis.crypto.getRandomValues(e), Array.from(e, (t) => t.toString(16).padStart(2, "0")).join("");
51
+ }, P = (e, t) => {
52
+ const r = j(), 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
+ }, U = (e, t, r) => {
78
+ if (!e || typeof fetch > "u")
79
+ return;
80
+ const { sessionId: n, payload: o } = P(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
+ }, F = (e) => {
92
+ const { webComponentTag: t, appName: r, appVersion: n, scriptUrls: o, fallbackScriptUrls: a, collectorUrls: c, env: s, jwt: d, timeoutMs: O = 15e3, onLoad: S, onError: I } = e;
93
+ if (typeof document > "u")
94
+ return w;
95
+ const m = `${t}-script-${s}`;
96
+ if (customElements.get(t) || document.getElementById(m))
97
+ return w;
98
+ const v = M(d), k = e.report ?? ((l) => U(c && W(c, s, d), l, n));
99
+ let u = !1, y = 0, f;
100
+ const h = () => {
101
+ f !== void 0 && clearTimeout(f);
102
+ }, g = (l, p, i) => {
103
+ if (u)
104
+ return;
105
+ const A = Math.round(performance.now() - y), R = {
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
+ k(R);
116
+ const E = i ? void 0 : T(a ?? {}, s, d);
117
+ if (E && E !== p) {
118
+ _(E, !0);
119
+ return;
120
+ }
121
+ u = !0, h(), document.getElementById(m)?.remove(), I?.(R);
122
+ }, _ = (l, p) => {
123
+ h(), y = performance.now();
124
+ const i = document.createElement("script");
125
+ i.id = m, i.src = l, i.type = "module", i.async = !0, i.onload = () => {
126
+ setTimeout(() => {
127
+ u || (customElements.get(t) ? (u = !0, h(), S?.()) : g("not-defined", l, p));
128
+ }, 0);
129
+ }, i.onerror = () => g("network", l, p), f = setTimeout(() => g("timeout", l, p), O), document.getElementById(m)?.remove(), document.head.appendChild(i);
130
+ }, b = T(o, s, d);
131
+ return b ? (_(b, !1), () => {
132
+ u = !0, h();
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(D);
24
142
  this.config = {
25
- ...e,
26
- env: e.env || a,
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 n = this.createWebComponent();
48
- e.innerHTML = "", e.appendChild(n), this.state.container = e, this.state.element = n, this.state.initialized = !0;
49
- } catch (n) {
50
- throw console.error("Failed to render widget:", n), n;
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 n = this.state.element;
62
- Object.entries(e).forEach(([t, i]) => {
63
- i && (this.config[t] = i, n[t] = i);
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 || a;
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 = p(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, n) => {
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() : n(new Error(this.errorMessages.WEB_COMPONENT_NOT_DEFINED));
111
- }, 0);
112
- }, t.onerror = () => {
113
- this.scriptLoadingPromise = void 0, n(new Error(`${this.errorMessages.SCRIPT_LOAD_FAILED} (${this.getEnvironment()})`));
114
- }, document.head.appendChild(t);
223
+ this.scriptLoadingPromise = new Promise((t, r) => {
224
+ F({
225
+ webComponentTag: this.webComponentTag,
226
+ appName: this.webComponentTag,
227
+ scriptUrls: this.getEffectiveScriptUrls(),
228
+ collectorUrls: z,
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((n, t) => {
127
- const i = 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(i), n();
132
- }).catch((o) => {
133
- clearTimeout(i), 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(([n, t]) => {
151
- t && (e[n] = 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 d;
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
- })(d || (d = {}));
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: "CryptoAccountLink widget is already rendered. Call destroy() before rendering again.",
162
283
  NOT_RENDERED: "CryptoAccountLink widget is not rendered. Call render() first.",
@@ -182,15 +303,15 @@ class m extends u {
182
303
  * @param container - The container element to render the widget into
183
304
  * @returns Promise that resolves when the widget is rendered
184
305
  */
185
- render(e) {
186
- return super.render(e);
306
+ render(t) {
307
+ return super.render(t);
187
308
  }
188
309
  /**
189
310
  * Update the configuration of the CryptoAccountLink widget
190
311
  * @param config - Partial configuration to update
191
312
  */
192
- updateConfig(e) {
193
- return super.updateConfig(e);
313
+ updateConfig(t) {
314
+ return super.updateConfig(t);
194
315
  }
195
316
  /**
196
317
  * Get the current configuration
@@ -214,7 +335,7 @@ class m extends u {
214
335
  }
215
336
  }
216
337
  export {
217
- m as CryptoAccountLink,
218
- d as ErrorCode,
219
- m as default
338
+ V as CryptoAccountLink,
339
+ N as ErrorCode,
340
+ V as default
220
341
  };
@@ -1 +1 @@
1
- (function(i,s){typeof exports=="object"&&typeof module<"u"?s(exports):typeof define=="function"&&define.amd?define(["exports"],s):(i=typeof globalThis<"u"?globalThis:i||self,s(i.CryptoAccountLink={}))})(this,(function(i){"use strict";const s="production",l="JWT token is required and must be a string.",h=n=>{if(!n||typeof n!="string")return null;const e=n.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),o=typeof atob<"u"?atob(t):Buffer.from(t,"base64").toString("utf-8"),u=JSON.parse(o)?.payload?.region;if(typeof u!="string")return null;const c=u.toLowerCase();return c==="us"||c==="eu"?c:null}catch{return null}},p=(n,e)=>h(e)!=="eu"?n:n==="cert"?"eu-cert":n==="prod"?"eu-prod":n;class m{config;state;scriptLoadingPromise;constructor(e){if(!e.jwt||typeof e.jwt!="string")throw new Error(l);this.config={...e,env:e.env||s,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,o])=>{o&&(this.config[t]=o,r[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||s}getScriptId(){return`${this.webComponentTag}-script-${this.getEnvironment()}`}isScriptLoaded(){return!!document.getElementById(this.getScriptId())}getWebComponent(){return customElements.get(this.webComponentTag)}getScriptUrl(){const e=p(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 o=setTimeout(()=>{t(new Error(`Timeout waiting for ${this.webComponentTag} to be defined`))},e);customElements.whenDefined(this.webComponentTag).then(()=>{clearTimeout(o),r()}).catch(d=>{clearTimeout(o),t(d)})})}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}}i.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"})(i.ErrorCode||(i.ErrorCode={}));class a extends m{errorMessages={ALREADY_RENDERED:"CryptoAccountLink widget is already rendered. Call destroy() before rendering again.",NOT_RENDERED:"CryptoAccountLink widget is not rendered. Call render() first.",INVALID_CONTAINER:"Invalid container element provided.",SCRIPT_LOAD_FAILED:"Failed to load the Connect CryptoAccountLink script.",WEB_COMPONENT_NOT_DEFINED:"Web component is not defined. Script may not be loaded."};scriptUrls={local:"http://localhost:5173/crypto-account-link-web/index.js",dev:"https://connect-sdk.dev.0hash.com/crypto-account-link-web/index.js",cert:"https://sdk.sandbox.connect.xyz/crypto-account-link-web/index.js",prod:"https://sdk.connect.xyz/crypto-account-link-web/index.js",sandbox:"https://sdk.sandbox.connect.xyz/crypto-account-link-web/index.js",production:"https://sdk.connect.xyz/crypto-account-link-web/index.js","eu-cert":"https://sdk-cdn.cert.zerohash.eu/crypto-account-link-web/index.js","eu-prod":"https://sdk-cdn.zerohash.eu/crypto-account-link-web/index.js"};webComponentTag="zerohash-crypto-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()}}i.CryptoAccountLink=a,i.default=a,Object.defineProperties(i,{__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.CryptoAccountLink={}))})(this,(function(s){"use strict";const u="production",O="JWT token is required and must be a string.",v={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"},I=e=>{if(!e||typeof e!="string")return null;const t=e.split(".");if(t.length<2)return null;try{const n=t[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}},b=(e,t)=>I(t)!=="eu"?e:e==="cert"?"eu-cert":e==="prod"?"eu-prod":e,k=e=>{if(!e||typeof e!="string")return{};const t=e.split(".");if(t.length<2)return{};try{const n=t[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=(e,t,n)=>{const r=b(t,n);return e[r]??e[t]??e.prod},A=(e,t,n)=>{const r=b(t,n);return e[r]??e[t]},E=()=>{},D=()=>{const e=new Uint8Array(8);return globalThis.crypto.getRandomValues(e),Array.from(e,t=>t.toString(16).padStart(2,"0")).join("")},z=(e,t)=>{const n=D(),r=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),r&&(o.zh_web_sdk_version=r);const c={meta:{app:{name:e.appName,version:t??"unknown",environment:e.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 ${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:n,payload:c}},M=(e,t,n)=>{if(!e||typeof fetch>"u")return;const{sessionId:r,payload:o}=z(t,n);try{fetch(e,{method:"POST",headers:{"Content-Type":"application/json","x-faro-session-id":r},body:JSON.stringify(o),keepalive:!0}).catch(()=>{})}catch{}},j=e=>{const{webComponentTag:t,appName:n,appVersion:r,scriptUrls:o,fallbackScriptUrls:c,collectorUrls:d,env:i,jwt:l,timeoutMs:W=15e3,onLoad:P,onError:U}=e;if(typeof document>"u")return E;const f=`${t}-script-${i}`;if(customElements.get(t)||document.getElementById(f))return E;const F=k(l),B=e.report??(p=>M(d&&A(d,i,l),p,r));let h=!1,T=0,y;const g=()=>{y!==void 0&&clearTimeout(y)},w=(p,m,a)=>{if(h)return;const V=Math.round(performance.now()-T),S={webComponentTag:t,appName:n,env:i,scriptUrl:m,reason:p,triedFallback:a,elapsedMs:V,claims:F};B(S);const _=a?void 0:C(c??{},i,l);if(_&&_!==m){N(_,!0);return}h=!0,g(),document.getElementById(f)?.remove(),U?.(S)},N=(p,m)=>{g(),T=performance.now();const a=document.createElement("script");a.id=f,a.src=p,a.type="module",a.async=!0,a.onload=()=>{setTimeout(()=>{h||(customElements.get(t)?(h=!0,g(),P?.()):w("not-defined",p,m))},0)},a.onerror=()=>w("network",p,m),y=setTimeout(()=>w("timeout",p,m),W),document.getElementById(f)?.remove(),document.head.appendChild(a)},L=C(o,i,l);return L?(N(L,!1),()=>{h=!0,g()}):E};class x{config;state;scriptLoadingPromise;constructor(t){if(!t.jwt||typeof t.jwt!="string")throw new Error(O);this.config={...t,env:t.env||u,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 n=this.createWebComponent();t.innerHTML="",t.appendChild(n),this.state.container=t,this.state.element=n,this.state.initialized=!0}catch(n){throw console.error("Failed to render widget:",n),n}}updateConfig(t){if(!this.state.initialized||!this.state.element)throw new Error(this.errorMessages.NOT_RENDERED);const n=this.state.element;Object.entries(t).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||u}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,n)=>{j({webComponentTag:this.webComponentTag,appName:this.webComponentTag,scriptUrls:this.getEffectiveScriptUrls(),collectorUrls:v,env:this.getEnvironment(),jwt:this.config.jwt,onLoad:t,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(t){throw this.scriptLoadingPromise=void 0,t}return this.scriptLoadingPromise}}async waitForWebComponent(t=5e3){if(!this.getWebComponent())return new Promise((n,r)=>{const o=setTimeout(()=>{r(new Error(`Timeout waiting for ${this.webComponentTag} to be defined`))},t);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(t){throw console.error("Failed to load Connect script:",t),t}}createWebComponent(){const t=document.createElement(this.webComponentTag);return Object.entries(this.config).forEach(([n,r])=>{r&&(t[n]=r)}),t}}s.ErrorCode=void 0,(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"})(s.ErrorCode||(s.ErrorCode={}));class R extends x{errorMessages={ALREADY_RENDERED:"CryptoAccountLink widget is already rendered. Call destroy() before rendering again.",NOT_RENDERED:"CryptoAccountLink widget is not rendered. Call render() first.",INVALID_CONTAINER:"Invalid container element provided.",SCRIPT_LOAD_FAILED:"Failed to load the Connect CryptoAccountLink script.",WEB_COMPONENT_NOT_DEFINED:"Web component is not defined. Script may not be loaded."};scriptUrls={local:"http://localhost:5173/crypto-account-link-web/index.js",dev:"https://connect-sdk.dev.0hash.com/crypto-account-link-web/index.js",cert:"https://sdk.sandbox.connect.xyz/crypto-account-link-web/index.js",prod:"https://sdk.connect.xyz/crypto-account-link-web/index.js",sandbox:"https://sdk.sandbox.connect.xyz/crypto-account-link-web/index.js",production:"https://sdk.connect.xyz/crypto-account-link-web/index.js","eu-cert":"https://sdk-cdn.cert.zerohash.eu/crypto-account-link-web/index.js","eu-prod":"https://sdk-cdn.zerohash.eu/crypto-account-link-web/index.js"};webComponentTag="zerohash-crypto-account-link";render(t){return super.render(t)}updateConfig(t){return super.updateConfig(t)}getConfig(){return super.getConfig()}isRendered(){return super.isRendered()}destroy(){return super.destroy()}}s.CryptoAccountLink=R,s.default=R,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/crypto-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",