@connect-xyz/auth-js 1.71.3 → 1.71.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -343,15 +343,20 @@ declare abstract class BaseJsSdk<Config extends BaseConfig<never> = BaseConfig>
343
343
  return this.scriptLoadingPromise;
344
344
  }
345
345
 
346
- private async waitForWebComponent(timeout = 5000) {
346
+ private async waitForWebComponent() {
347
347
  if (this.getWebComponent()) {
348
348
  return;
349
349
  }
350
350
 
351
+ // The script has already loaded (loadScript awaited its onLoad); this only
352
+ // covers the window until the custom element registers. Under load (CI, slow
353
+ // devices) that can take longer than a few seconds, so the grace period is
354
+ // generous — a genuine load failure still fails fast via loadScript's
355
+ // onError, not this timer.
351
356
  return new Promise<void>((resolve, reject) => {
352
357
  const timeoutId = setTimeout(() => {
353
358
  reject(new Error(`Timeout waiting for ${this.webComponentTag} to be defined`));
354
- }, timeout);
359
+ }, DEFAULT_WEB_COMPONENT_TIMEOUT_MS);
355
360
 
356
361
  customElements
357
362
  .whenDefined(this.webComponentTag)
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- const C = "production", z = "JWT token is required and must be a string.", M = {
1
+ const y = "production", M = "JWT token is required and must be a string.", z = {
2
2
  dev: "https://grafana-faro-collector.dev.0hash.com/collect",
3
3
  cert: "https://grafana-faro-collector.cert.zerohash.com/collect",
4
4
  prod: "https://grafana-faro-collector.zerohash.com/collect",
@@ -13,45 +13,45 @@ const C = "production", z = "JWT token is required and must be a string.", M = {
13
13
  if (t.length < 2)
14
14
  return null;
15
15
  try {
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")
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"), a = JSON.parse(o)?.payload?.region;
17
+ if (typeof a != "string")
18
18
  return null;
19
- const s = c.toLowerCase();
19
+ const s = a.toLowerCase();
20
20
  return s === "us" || s === "eu" ? s : null;
21
21
  } catch {
22
22
  return null;
23
23
  }
24
- }, S = (e, t) => W(t) !== "eu" ? e : e === "cert" ? "eu-cert" : e === "prod" ? "eu-prod" : e, P = (e) => {
24
+ }, O = (e, t) => W(t) !== "eu" ? e : e === "cert" ? "eu-cert" : e === "prod" ? "eu-prod" : e, P = (e) => {
25
25
  if (!e || typeof e != "string")
26
26
  return {};
27
27
  const t = e.split(".");
28
28
  if (t.length < 2)
29
29
  return {};
30
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;
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"), l = JSON.parse(o), a = l?.payload ?? {}, s = (c) => typeof c == "string" && c.length > 0 ? c : void 0;
32
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)
33
+ participantCode: s(a.participant_code),
34
+ platformName: s(a.platform_name),
35
+ platformCode: s(l.platform_code),
36
+ region: s(a.region)
37
37
  };
38
38
  } catch {
39
39
  return {};
40
40
  }
41
- }, T = (e, t, r) => {
42
- const n = S(t, r);
41
+ }, C = (e, t, r) => {
42
+ const n = O(t, r);
43
43
  return e[n] ?? e[t] ?? e.prod;
44
44
  }, U = (e, t, r) => {
45
- const n = S(t, r);
45
+ const n = O(t, r);
46
46
  return e[n] ?? e[t];
47
47
  }, _ = () => {
48
48
  }, F = () => {
49
49
  const e = new Uint8Array(8);
50
50
  return globalThis.crypto.getRandomValues(e), Array.from(e, (t) => t.toString(16).padStart(2, "0")).join("");
51
- }, k = (e, t) => {
51
+ }, B = (e, t) => {
52
52
  const r = F(), n = globalThis.__ZH_WEB_SDK_VERSION__, o = {};
53
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 = {
54
+ const l = {
55
55
  meta: {
56
56
  app: { name: e.appName, version: t ?? "unknown", environment: e.env },
57
57
  session: { id: r, attributes: o },
@@ -73,11 +73,11 @@ const C = "production", z = "JWT token is required and must be a string.", M = {
73
73
  }
74
74
  ]
75
75
  };
76
- return { sessionId: r, payload: a };
77
- }, x = (e, t, r) => {
76
+ return { sessionId: r, payload: l };
77
+ }, k = (e, t, r) => {
78
78
  if (!e || typeof fetch > "u")
79
79
  return;
80
- const { sessionId: n, payload: o } = k(t, r);
80
+ const { sessionId: n, payload: o } = B(t, r);
81
81
  try {
82
82
  fetch(e, {
83
83
  method: "POST",
@@ -88,60 +88,60 @@ const C = "production", z = "JWT token is required and must be a string.", M = {
88
88
  });
89
89
  } catch {
90
90
  }
91
- }, B = (e) => {
92
- const { webComponentTag: t, appName: r, appVersion: n, scriptUrls: o, fallbackScriptUrls: a, collectorUrls: c, env: s, jwt: d, timeoutMs: L = 15e3, onLoad: O, onError: I } = e;
91
+ }, x = (e) => {
92
+ const { webComponentTag: t, appName: r, appVersion: n, scriptUrls: o, fallbackScriptUrls: l, collectorUrls: a, env: s, jwt: c, timeoutMs: S = 15e3, onLoad: L, onError: I } = e;
93
93
  if (typeof document > "u")
94
94
  return _;
95
95
  const m = `${t}-script-${s}`;
96
96
  if (customElements.get(t) || document.getElementById(m))
97
97
  return _;
98
- const v = P(d), A = e.report ?? ((l) => x(c && U(c, s, d), l, n));
98
+ const A = P(c), v = e.report ?? ((d) => k(a && U(a, s, c), d, n));
99
99
  let u = !1, w = 0, f;
100
100
  const h = () => {
101
101
  f !== void 0 && clearTimeout(f);
102
- }, g = (l, p, i) => {
102
+ }, g = (d, p, i) => {
103
103
  if (u)
104
104
  return;
105
- const D = Math.round(performance.now() - w), y = {
105
+ const D = Math.round(performance.now() - w), T = {
106
106
  webComponentTag: t,
107
107
  appName: r,
108
108
  env: s,
109
109
  scriptUrl: p,
110
- reason: l,
110
+ reason: d,
111
111
  triedFallback: i,
112
112
  elapsedMs: D,
113
- claims: v
113
+ claims: A
114
114
  };
115
- A(y);
116
- const E = i ? void 0 : T(a ?? {}, s, d);
115
+ v(T);
116
+ const E = i ? void 0 : C(l ?? {}, s, c);
117
117
  if (E && E !== p) {
118
118
  R(E, !0);
119
119
  return;
120
120
  }
121
- u = !0, h(), document.getElementById(m)?.remove(), I?.(y);
122
- }, R = (l, p) => {
121
+ u = !0, h(), document.getElementById(m)?.remove(), I?.(T);
122
+ }, R = (d, p) => {
123
123
  h(), w = performance.now();
124
124
  const i = document.createElement("script");
125
- i.id = m, i.src = l, i.type = "module", i.async = !0, i.onload = () => {
125
+ i.id = m, i.src = d, i.type = "module", i.async = !0, i.onload = () => {
126
126
  setTimeout(() => {
127
- u || (customElements.get(t) ? (u = !0, h(), O?.()) : g("not-defined", l, p));
127
+ u || (customElements.get(t) ? (u = !0, h(), L?.()) : g("not-defined", d, p));
128
128
  }, 0);
129
- }, i.onerror = () => g("network", l, p), f = setTimeout(() => g("timeout", l, p), L), document.getElementById(m)?.remove(), document.head.appendChild(i);
130
- }, b = T(o, s, d);
129
+ }, i.onerror = () => g("network", d, p), f = setTimeout(() => g("timeout", d, p), S), document.getElementById(m)?.remove(), document.head.appendChild(i);
130
+ }, b = C(o, s, c);
131
131
  return b ? (R(b, !1), () => {
132
132
  u = !0, h();
133
133
  }) : _;
134
- };
135
- class j {
134
+ }, j = 1e4;
135
+ class V {
136
136
  config;
137
137
  state;
138
138
  scriptLoadingPromise;
139
139
  constructor(t) {
140
140
  if (!t.jwt || typeof t.jwt != "string")
141
- throw new Error(z);
141
+ throw new Error(M);
142
142
  this.config = {
143
143
  ...t,
144
- env: t.env || C,
144
+ env: t.env || y,
145
145
  theme: t.theme
146
146
  }, this.state = {
147
147
  initialized: !1,
@@ -206,7 +206,7 @@ class j {
206
206
  return { ...this.config };
207
207
  }
208
208
  getEnvironment() {
209
- return this.config.env || C;
209
+ return this.config.env || y;
210
210
  }
211
211
  getScriptId() {
212
212
  return `${this.webComponentTag}-script-${this.getEnvironment()}`;
@@ -225,11 +225,11 @@ class j {
225
225
  if (this.scriptLoadingPromise)
226
226
  return this.scriptLoadingPromise;
227
227
  this.scriptLoadingPromise = new Promise((t, r) => {
228
- B({
228
+ x({
229
229
  webComponentTag: this.webComponentTag,
230
230
  appName: this.webComponentTag,
231
231
  scriptUrls: this.getEffectiveScriptUrls(),
232
- collectorUrls: M,
232
+ collectorUrls: z,
233
233
  env: this.getEnvironment(),
234
234
  jwt: this.config.jwt,
235
235
  onLoad: t,
@@ -246,16 +246,16 @@ class j {
246
246
  return this.scriptLoadingPromise;
247
247
  }
248
248
  }
249
- async waitForWebComponent(t = 5e3) {
249
+ async waitForWebComponent() {
250
250
  if (!this.getWebComponent())
251
- return new Promise((r, n) => {
252
- const o = setTimeout(() => {
253
- n(new Error(`Timeout waiting for ${this.webComponentTag} to be defined`));
254
- }, t);
251
+ return new Promise((t, r) => {
252
+ const n = setTimeout(() => {
253
+ r(new Error(`Timeout waiting for ${this.webComponentTag} to be defined`));
254
+ }, j);
255
255
  customElements.whenDefined(this.webComponentTag).then(() => {
256
- clearTimeout(o), r();
257
- }).catch((a) => {
258
- clearTimeout(o), n(a);
256
+ clearTimeout(n), t();
257
+ }).catch((o) => {
258
+ clearTimeout(n), r(o);
259
259
  });
260
260
  });
261
261
  }
@@ -281,11 +281,11 @@ var N;
281
281
  (function(e) {
282
282
  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";
283
283
  })(N || (N = {}));
284
- const V = {
284
+ const $ = {
285
285
  sandbox: "https://sdk.sandbox.connect.xyz/auth-web/index.js",
286
286
  production: "https://sdk.connect.xyz/auth-web/index.js"
287
287
  };
288
- class $ extends j {
288
+ class J extends V {
289
289
  errorMessages = {
290
290
  ALREADY_RENDERED: "Auth widget is already rendered. Call destroy() before rendering again.",
291
291
  NOT_RENDERED: "Auth widget is not rendered. Call render() first.",
@@ -294,7 +294,7 @@ class $ extends j {
294
294
  WEB_COMPONENT_NOT_DEFINED: "Web component is not defined. Script may not be loaded."
295
295
  };
296
296
  // protected override scriptUrls = EFFECTIVE_SCRIPT_URLS;
297
- scriptUrls = V;
297
+ scriptUrls = $;
298
298
  webComponentTag = "connect-auth";
299
299
  /**
300
300
  * Render the Auth widget to a container element
@@ -333,7 +333,7 @@ class $ extends j {
333
333
  }
334
334
  }
335
335
  export {
336
- $ as Auth,
336
+ J as Auth,
337
337
  N as ErrorCode,
338
- $ as default
338
+ J as default
339
339
  };
@@ -1 +1 @@
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.Auth={}))})(this,(function(s){"use strict";const u="production",L="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"},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"),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)=>v(t)!=="eu"?e:e==="cert"?"eu-cert":e==="prod"?"eu-prod":e,A=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"),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{}}},y=(e,t,r)=>{const n=b(t,r);return e[n]??e[t]??e.prod},D=(e,t,r)=>{const n=b(t,r);return e[n]??e[t]},E=()=>{},M=()=>{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 r=M(),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 c={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:c}},P=(e,t,r)=>{if(!e||typeof fetch>"u")return;const{sessionId:n,payload:o}=z(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{}},W=e=>{const{webComponentTag:t,appName:r,appVersion:n,scriptUrls:o,fallbackScriptUrls:c,collectorUrls:d,env:i,jwt:l,timeoutMs:j=15e3,onLoad:k,onError:B}=e;if(typeof document>"u")return E;const h=`${t}-script-${i}`;if(customElements.get(t)||document.getElementById(h))return E;const V=A(l),$=e.report??(p=>P(d&&D(d,i,l),p,n));let f=!1,T=0,_;const g=()=>{_!==void 0&&clearTimeout(_)},w=(p,m,a)=>{if(f)return;const x=Math.round(performance.now()-T),O={webComponentTag:t,appName:r,env:i,scriptUrl:m,reason:p,triedFallback:a,elapsedMs:x,claims:V};$(O);const R=a?void 0:y(c??{},i,l);if(R&&R!==m){N(R,!0);return}f=!0,g(),document.getElementById(h)?.remove(),B?.(O)},N=(p,m)=>{g(),T=performance.now();const a=document.createElement("script");a.id=h,a.src=p,a.type="module",a.async=!0,a.onload=()=>{setTimeout(()=>{f||(customElements.get(t)?(f=!0,g(),k?.()):w("not-defined",p,m))},0)},a.onerror=()=>w("network",p,m),_=setTimeout(()=>w("timeout",p,m),j),document.getElementById(h)?.remove(),document.head.appendChild(a)},S=y(o,i,l);return S?(N(S,!1),()=>{f=!0,g()}):E};class U{config;state;scriptLoadingPromise;constructor(t){if(!t.jwt||typeof t.jwt!="string")throw new Error(L);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 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||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,r)=>{W({webComponentTag:this.webComponentTag,appName:this.webComponentTag,scriptUrls:this.getEffectiveScriptUrls(),collectorUrls:I,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(c=>{clearTimeout(o),n(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(([r,n])=>{n&&(t[r]=n)}),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={}));const F={sandbox:"https://sdk.sandbox.connect.xyz/auth-web/index.js",production:"https://sdk.connect.xyz/auth-web/index.js"};class C extends U{errorMessages={ALREADY_RENDERED:"Auth widget is already rendered. Call destroy() before rendering again.",NOT_RENDERED:"Auth widget is not rendered. Call render() first.",INVALID_CONTAINER:"Invalid container element provided.",SCRIPT_LOAD_FAILED:"Failed to load the Connect Auth script.",WEB_COMPONENT_NOT_DEFINED:"Web component is not defined. Script may not be loaded."};scriptUrls=F;webComponentTag="connect-auth";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.Auth=C,s.default=C,Object.defineProperties(s,{__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.Auth={}))})(this,(function(s){"use strict";const u="production",L="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=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 i=c.toLowerCase();return i==="us"||i==="eu"?i:null}catch{return null}},b=(e,t)=>A(t)!=="eu"?e:e==="cert"?"eu-cert":e==="prod"?"eu-prod":e,v=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"),p=JSON.parse(o),c=p?.payload??{},i=d=>typeof d=="string"&&d.length>0?d:void 0;return{participantCode:i(c.participant_code),platformName:i(c.platform_name),platformCode:i(p.platform_code),region:i(c.region)}}catch{return{}}},T=(e,t,r)=>{const n=b(t,r);return e[n]??e[t]??e.prod},D=(e,t,r)=>{const n=b(t,r);return e[n]??e[t]},E=()=>{},M=()=>{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 r=M(),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 p={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:p}},P=(e,t,r)=>{if(!e||typeof fetch>"u")return;const{sessionId:n,payload:o}=z(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{}},W=e=>{const{webComponentTag:t,appName:r,appVersion:n,scriptUrls:o,fallbackScriptUrls:p,collectorUrls:c,env:i,jwt:d,timeoutMs:B=15e3,onLoad:k,onError:V}=e;if(typeof document>"u")return E;const h=`${t}-script-${i}`;if(customElements.get(t)||document.getElementById(h))return E;const $=v(d),x=e.report??(l=>P(c&&D(c,i,d),l,n));let f=!1,C=0,_;const g=()=>{_!==void 0&&clearTimeout(_)},w=(l,m,a)=>{if(f)return;const J=Math.round(performance.now()-C),O={webComponentTag:t,appName:r,env:i,scriptUrl:m,reason:l,triedFallback:a,elapsedMs:J,claims:$};x(O);const R=a?void 0:T(p??{},i,d);if(R&&R!==m){N(R,!0);return}f=!0,g(),document.getElementById(h)?.remove(),V?.(O)},N=(l,m)=>{g(),C=performance.now();const a=document.createElement("script");a.id=h,a.src=l,a.type="module",a.async=!0,a.onload=()=>{setTimeout(()=>{f||(customElements.get(t)?(f=!0,g(),k?.()):w("not-defined",l,m))},0)},a.onerror=()=>w("network",l,m),_=setTimeout(()=>w("timeout",l,m),B),document.getElementById(h)?.remove(),document.head.appendChild(a)},S=T(o,i,d);return S?(N(S,!1),()=>{f=!0,g()}):E},U=1e4;class F{config;state;scriptLoadingPromise;constructor(t){if(!t.jwt||typeof t.jwt!="string")throw new Error(L);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 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||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,r)=>{W({webComponentTag:this.webComponentTag,appName:this.webComponentTag,scriptUrls:this.getEffectiveScriptUrls(),collectorUrls:I,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(){if(!this.getWebComponent())return new Promise((t,r)=>{const n=setTimeout(()=>{r(new Error(`Timeout waiting for ${this.webComponentTag} to be defined`))},U);customElements.whenDefined(this.webComponentTag).then(()=>{clearTimeout(n),t()}).catch(o=>{clearTimeout(n),r(o)})})}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}}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={}));const j={sandbox:"https://sdk.sandbox.connect.xyz/auth-web/index.js",production:"https://sdk.connect.xyz/auth-web/index.js"};class y extends F{errorMessages={ALREADY_RENDERED:"Auth widget is already rendered. Call destroy() before rendering again.",NOT_RENDERED:"Auth widget is not rendered. Call render() first.",INVALID_CONTAINER:"Invalid container element provided.",SCRIPT_LOAD_FAILED:"Failed to load the Connect Auth script.",WEB_COMPONENT_NOT_DEFINED:"Web component is not defined. Script may not be loaded."};scriptUrls=j;webComponentTag="connect-auth";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.Auth=y,s.default=y,Object.defineProperties(s,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})}));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@connect-xyz/auth-js",
3
- "version": "1.71.3",
3
+ "version": "1.71.4",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",