@zerohash-sdk/crypto-deposits-js 0.1.0 → 0.2.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/README.md +2 -0
- package/dist/index.d.ts +497 -0
- package/dist/index.js +334 -0
- package/dist/index.umd.cjs +1 -0
- package/package.json +1 -1
package/README.md
CHANGED
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,497 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Zerohash Crypto Deposits JavaScript SDK
|
|
3
|
+
*
|
|
4
|
+
* A programmatic JavaScript SDK for integrating the Crypto Deposits widget
|
|
5
|
+
* into web applications without requiring HTML custom elements.
|
|
6
|
+
*
|
|
7
|
+
* @packageDocumentation
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* Generic app event structure
|
|
12
|
+
* @template TType - Event type string
|
|
13
|
+
* @template TData - Event data payload
|
|
14
|
+
*/
|
|
15
|
+
declare type AppEvent<TType extends string = string, TData = Record<string, unknown>> = {
|
|
16
|
+
/** The type of event that occurred */
|
|
17
|
+
type: TType;
|
|
18
|
+
/** Data associated with the event */
|
|
19
|
+
data: TData;
|
|
20
|
+
};
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Configuration options for the SDK
|
|
24
|
+
*/
|
|
25
|
+
declare interface BaseConfig<TEvent = AppEvent> extends CommonCallbacks<TEvent> {
|
|
26
|
+
/**
|
|
27
|
+
* JWT token used for authentication. Provide/update it via `setJWT`
|
|
28
|
+
* (`updateConfig({ jwt })`).
|
|
29
|
+
*/
|
|
30
|
+
jwt: string;
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* Target environment
|
|
34
|
+
* @default 'production'
|
|
35
|
+
*/
|
|
36
|
+
env?: Environment;
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Theme mode
|
|
40
|
+
* @default 'light'
|
|
41
|
+
*
|
|
42
|
+
* Available themes:
|
|
43
|
+
* - `'auto'` - Automatically detect system preference (light/dark mode)
|
|
44
|
+
* - `'light'` - Force light theme
|
|
45
|
+
* - `'dark'` - Force dark theme
|
|
46
|
+
*/
|
|
47
|
+
theme?: Theme;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
declare type BaseErrorMessageKeys =
|
|
51
|
+
| 'ALREADY_RENDERED'
|
|
52
|
+
| 'NOT_RENDERED'
|
|
53
|
+
| 'INVALID_CONTAINER'
|
|
54
|
+
| 'SCRIPT_LOAD_FAILED'
|
|
55
|
+
| 'WEB_COMPONENT_NOT_DEFINED';
|
|
56
|
+
|
|
57
|
+
declare abstract class BaseJsSdk<Config extends BaseConfig<never> = BaseConfig> {
|
|
58
|
+
private config: Config;
|
|
59
|
+
private state: SdkState;
|
|
60
|
+
private scriptLoadingPromise?: Promise<void>;
|
|
61
|
+
|
|
62
|
+
protected abstract errorMessages: Record<BaseErrorMessageKeys, string>;
|
|
63
|
+
protected abstract scriptUrls: Record<string, string>;
|
|
64
|
+
protected abstract webComponentTag: string;
|
|
65
|
+
|
|
66
|
+
constructor(config: Config) {
|
|
67
|
+
if (!config.jwt || typeof config.jwt !== 'string') {
|
|
68
|
+
throw new Error(INVALID_JWT_ERROR_MESSAGE);
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
this.config = {
|
|
72
|
+
...config,
|
|
73
|
+
env: config.env || DEFAULT_ENVIRONMENT,
|
|
74
|
+
theme: config.theme,
|
|
75
|
+
};
|
|
76
|
+
|
|
77
|
+
this.state = {
|
|
78
|
+
initialized: false,
|
|
79
|
+
scriptLoaded: false,
|
|
80
|
+
container: null,
|
|
81
|
+
element: null,
|
|
82
|
+
};
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* Render the widget to a container element
|
|
87
|
+
* @param container - The container element to render the widget into
|
|
88
|
+
* @returns Promise that resolves when the widget is rendered
|
|
89
|
+
*/
|
|
90
|
+
async render(container: HTMLElement): Promise<void> {
|
|
91
|
+
// Validate container
|
|
92
|
+
if (!container || !(container instanceof HTMLElement)) {
|
|
93
|
+
throw new Error(this.errorMessages.INVALID_CONTAINER);
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
// Check if already rendered
|
|
97
|
+
if (this.state.initialized) {
|
|
98
|
+
throw new Error(this.errorMessages.ALREADY_RENDERED);
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
try {
|
|
102
|
+
// Ensure script is loaded
|
|
103
|
+
await this.ensureScriptLoaded();
|
|
104
|
+
|
|
105
|
+
// Create and append the web component
|
|
106
|
+
const element = this.createWebComponent();
|
|
107
|
+
|
|
108
|
+
// Clear the container and append the element
|
|
109
|
+
container.innerHTML = '';
|
|
110
|
+
container.appendChild(element);
|
|
111
|
+
|
|
112
|
+
// Update state
|
|
113
|
+
this.state.container = container;
|
|
114
|
+
this.state.element = element;
|
|
115
|
+
this.state.initialized = true;
|
|
116
|
+
} catch (error) {
|
|
117
|
+
console.error('Failed to render widget:', error);
|
|
118
|
+
throw error;
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/**
|
|
123
|
+
* Update the configuration of the widget (e.g. `theme`, or the `jwt`).
|
|
124
|
+
*
|
|
125
|
+
* Passing a `jwt` is the JS-SDK equivalent of `setJWT` — it provides the JWT
|
|
126
|
+
* used to authenticate.
|
|
127
|
+
*
|
|
128
|
+
* @param config - Partial configuration to update
|
|
129
|
+
* @returns void
|
|
130
|
+
*/
|
|
131
|
+
updateConfig(config: Partial<Config>): void {
|
|
132
|
+
if (!this.state.initialized || !this.state.element) {
|
|
133
|
+
throw new Error(this.errorMessages.NOT_RENDERED);
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
const element = this.state.element as SdkElement<Config>;
|
|
137
|
+
|
|
138
|
+
Object.entries(config).forEach(([key, value]) => {
|
|
139
|
+
if (value) {
|
|
140
|
+
this.config[key as keyof Config] = value;
|
|
141
|
+
element[key as keyof Config] = value;
|
|
142
|
+
}
|
|
143
|
+
});
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/**
|
|
147
|
+
* Destroy the widget and clean up resources
|
|
148
|
+
*/
|
|
149
|
+
destroy(): void {
|
|
150
|
+
if (!this.state.initialized) {
|
|
151
|
+
return; // Nothing to destroy
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
// Remove the element from the container
|
|
155
|
+
if (this.state.element && this.state.element.parentNode) {
|
|
156
|
+
this.state.element.parentNode.removeChild(this.state.element);
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
// Clear the container
|
|
160
|
+
if (this.state.container) {
|
|
161
|
+
this.state.container.innerHTML = '';
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
// Reset state
|
|
165
|
+
this.state.container = null;
|
|
166
|
+
this.state.element = null;
|
|
167
|
+
this.state.initialized = false;
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/**
|
|
171
|
+
* Check if the widget is currently rendered
|
|
172
|
+
* @returns True if the widget is rendered, false otherwise
|
|
173
|
+
*/
|
|
174
|
+
isRendered(): boolean {
|
|
175
|
+
return this.state.initialized;
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/**
|
|
179
|
+
* Get the current configuration
|
|
180
|
+
* @returns The current configuration object
|
|
181
|
+
*/
|
|
182
|
+
getConfig(): Readonly<Config> {
|
|
183
|
+
return { ...this.config };
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
private getEnvironment(): Environment {
|
|
187
|
+
return this.config.env || DEFAULT_ENVIRONMENT;
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
private getScriptId() {
|
|
191
|
+
return `${this.webComponentTag}-script-${this.getEnvironment()}`;
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
private isScriptLoaded() {
|
|
195
|
+
return !!document.getElementById(this.getScriptId());
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
private getWebComponent() {
|
|
199
|
+
return customElements.get(this.webComponentTag);
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
private getEffectiveScriptUrls(): Record<string, string> {
|
|
203
|
+
// Support local development with Vite: an internal build pins the script
|
|
204
|
+
// URL for the configured env, bypassing the CDN maps entirely.
|
|
205
|
+
if (typeof import.meta !== 'undefined' && import.meta.env?.['VITE_INTERNAL_BUILD'] === 'true') {
|
|
206
|
+
const override = import.meta.env['VITE_SCRIPT_URL'];
|
|
207
|
+
if (override) return { [this.getEnvironment()]: override };
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
return this.scriptUrls;
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
private async loadScript() {
|
|
214
|
+
// When the element is already defined or another instance's script tag is
|
|
215
|
+
// in flight, defer to waitForWebComponent — the shared loader would no-op
|
|
216
|
+
// for those cases and never settle this promise.
|
|
217
|
+
if (this.getWebComponent() || this.isScriptLoaded()) {
|
|
218
|
+
return;
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
if (this.scriptLoadingPromise) {
|
|
222
|
+
return this.scriptLoadingPromise;
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
// The shared loader also reports failures to Faro (with JWT claims for
|
|
226
|
+
// partner/participant context) and removes a failed tag so a later
|
|
227
|
+
// render() call can retry cleanly.
|
|
228
|
+
this.scriptLoadingPromise = new Promise<void>((resolve, reject) => {
|
|
229
|
+
loadWebComponentScript({
|
|
230
|
+
webComponentTag: this.webComponentTag,
|
|
231
|
+
appName: this.webComponentTag,
|
|
232
|
+
scriptUrls: this.getEffectiveScriptUrls(),
|
|
233
|
+
collectorUrls: FARO_COLLECTOR_URLS,
|
|
234
|
+
env: this.getEnvironment(),
|
|
235
|
+
jwt: this.config.jwt,
|
|
236
|
+
onLoad: resolve,
|
|
237
|
+
onError: (info) => {
|
|
238
|
+
reject(
|
|
239
|
+
new Error(
|
|
240
|
+
info.reason === 'not-defined'
|
|
241
|
+
? this.errorMessages.WEB_COMPONENT_NOT_DEFINED
|
|
242
|
+
: `${this.errorMessages.SCRIPT_LOAD_FAILED} (${this.getEnvironment()})`
|
|
243
|
+
)
|
|
244
|
+
);
|
|
245
|
+
},
|
|
246
|
+
});
|
|
247
|
+
});
|
|
248
|
+
|
|
249
|
+
try {
|
|
250
|
+
await this.scriptLoadingPromise;
|
|
251
|
+
} catch (error) {
|
|
252
|
+
this.scriptLoadingPromise = undefined;
|
|
253
|
+
throw error;
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
return this.scriptLoadingPromise;
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
private async waitForWebComponent(timeout = 5000) {
|
|
260
|
+
if (this.getWebComponent()) {
|
|
261
|
+
return;
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
return new Promise<void>((resolve, reject) => {
|
|
265
|
+
const timeoutId = setTimeout(() => {
|
|
266
|
+
reject(new Error(`Timeout waiting for ${this.webComponentTag} to be defined`));
|
|
267
|
+
}, timeout);
|
|
268
|
+
|
|
269
|
+
customElements
|
|
270
|
+
.whenDefined(this.webComponentTag)
|
|
271
|
+
.then(() => {
|
|
272
|
+
clearTimeout(timeoutId);
|
|
273
|
+
resolve();
|
|
274
|
+
})
|
|
275
|
+
.catch((error) => {
|
|
276
|
+
clearTimeout(timeoutId);
|
|
277
|
+
reject(error);
|
|
278
|
+
});
|
|
279
|
+
});
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
/**
|
|
283
|
+
* Load the web component script if not already loaded
|
|
284
|
+
*/
|
|
285
|
+
protected async ensureScriptLoaded(): Promise<void> {
|
|
286
|
+
if (this.state.scriptLoaded) {
|
|
287
|
+
return;
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
try {
|
|
291
|
+
await this.loadScript();
|
|
292
|
+
await this.waitForWebComponent();
|
|
293
|
+
this.state.scriptLoaded = true;
|
|
294
|
+
} catch (error) {
|
|
295
|
+
console.error('Failed to load Connect script:', error);
|
|
296
|
+
throw error;
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
private createWebComponent() {
|
|
301
|
+
const element = document.createElement(this.webComponentTag) as SdkElement<Config>;
|
|
302
|
+
|
|
303
|
+
Object.entries(this.config).forEach(([key, value]) => {
|
|
304
|
+
if (value) {
|
|
305
|
+
element[key as keyof Config] = value;
|
|
306
|
+
}
|
|
307
|
+
});
|
|
308
|
+
|
|
309
|
+
return element;
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
/**
|
|
314
|
+
* Common callback function types shared across all Connect apps
|
|
315
|
+
* @template TEvent - The event type for onEvent callback
|
|
316
|
+
*/
|
|
317
|
+
declare type CommonCallbacks<TEvent = AppEvent> = {
|
|
318
|
+
/** Called when an error occurs */
|
|
319
|
+
onError?: (error: ErrorPayload) => void;
|
|
320
|
+
/** Called when the component is closed */
|
|
321
|
+
onClose?: () => void;
|
|
322
|
+
/** Called when a general event occurs */
|
|
323
|
+
onEvent?: (event: TEvent) => void;
|
|
324
|
+
/** Called when the widget has loaded and is ready */
|
|
325
|
+
onLoaded?: () => void;
|
|
326
|
+
/**
|
|
327
|
+
* Called when a deposit reaches a terminal state (success/failure/verifying).
|
|
328
|
+
* Optional — only SDKs that drive the integrations deposit flow emit it.
|
|
329
|
+
*/
|
|
330
|
+
onDeposit?: (deposit: DepositCompletedPayload) => void;
|
|
331
|
+
};
|
|
332
|
+
|
|
333
|
+
/**
|
|
334
|
+
* CryptoDeposits SDK class for programmatic control of the Connect Crypto Deposits widget.
|
|
335
|
+
*
|
|
336
|
+
* Renders the `zerohash-crypto-deposits` web component, which handles the iframe
|
|
337
|
+
* and postMessage communication internally.
|
|
338
|
+
*
|
|
339
|
+
* @example
|
|
340
|
+
* ```javascript
|
|
341
|
+
* const cryptoDeposits = new CryptoDeposits({
|
|
342
|
+
* jwt: 'your-jwt-token',
|
|
343
|
+
* env: 'prod',
|
|
344
|
+
* theme: 'light',
|
|
345
|
+
* onCompleted: ({ depositId, assetSymbol }) => console.log('Deposit', depositId, assetSymbol),
|
|
346
|
+
* onFailed: ({ depositId, assetSymbol }) => console.log('Deposit failed', depositId, assetSymbol),
|
|
347
|
+
* onDeposit: ({ data }) => console.log('Deposit status', data.status.value),
|
|
348
|
+
* onClose: () => console.log('Closed'),
|
|
349
|
+
* onError: ({ errorCode, reason }) => console.error(errorCode, reason),
|
|
350
|
+
* });
|
|
351
|
+
*
|
|
352
|
+
* // Render to a container
|
|
353
|
+
* await cryptoDeposits.render(document.getElementById('crypto-deposits-container'));
|
|
354
|
+
*
|
|
355
|
+
* // Clean up
|
|
356
|
+
* cryptoDeposits.destroy();
|
|
357
|
+
* ```
|
|
358
|
+
*/
|
|
359
|
+
declare class CryptoDeposits extends BaseJsSdk<CryptoDepositsConfig> {
|
|
360
|
+
protected errorMessages: {
|
|
361
|
+
ALREADY_RENDERED: string;
|
|
362
|
+
NOT_RENDERED: string;
|
|
363
|
+
INVALID_CONTAINER: string;
|
|
364
|
+
SCRIPT_LOAD_FAILED: string;
|
|
365
|
+
WEB_COMPONENT_NOT_DEFINED: string;
|
|
366
|
+
};
|
|
367
|
+
protected scriptUrls: Record<string, string>;
|
|
368
|
+
protected webComponentTag: string;
|
|
369
|
+
render(container: HTMLElement): Promise<void>;
|
|
370
|
+
updateConfig(config: Partial<CryptoDepositsConfig>): void;
|
|
371
|
+
getConfig(): Readonly<CryptoDepositsConfig>;
|
|
372
|
+
isRendered(): boolean;
|
|
373
|
+
destroy(): void;
|
|
374
|
+
}
|
|
375
|
+
export { CryptoDeposits }
|
|
376
|
+
export default CryptoDeposits;
|
|
377
|
+
|
|
378
|
+
declare type CryptoDepositsCallbacks = CommonCallbacks<CryptoDepositsEvent> & {
|
|
379
|
+
/** Called when the flow is successfully completed */
|
|
380
|
+
onCompleted?: (data: CryptoDepositsCompletedData) => void;
|
|
381
|
+
/**
|
|
382
|
+
* Called when a deposit transaction reaches a terminal **failed** state (the
|
|
383
|
+
* "Transaction failed" page). Distinct from `onError`, which signals an SDK/
|
|
384
|
+
* request error — `onFailed` carries the failed transaction's details.
|
|
385
|
+
*/
|
|
386
|
+
onFailed?: (data: CryptoDepositsCompletedData) => void;
|
|
387
|
+
};
|
|
388
|
+
|
|
389
|
+
declare type CryptoDepositsCompletedData = {
|
|
390
|
+
depositId: string;
|
|
391
|
+
assetSymbol: string;
|
|
392
|
+
network: string;
|
|
393
|
+
amount: string;
|
|
394
|
+
};
|
|
395
|
+
|
|
396
|
+
export declare interface CryptoDepositsConfig extends BaseConfig<CryptoDepositsEvent>, CryptoDepositsCallbacks {
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
declare type CryptoDepositsEvent = AppEvent<CryptoDepositsEventType>;
|
|
400
|
+
|
|
401
|
+
declare type CryptoDepositsEventType = string;
|
|
402
|
+
|
|
403
|
+
/**
|
|
404
|
+
* Deposit completed payload — emitted by SDKs that drive a deposit through
|
|
405
|
+
* the integrations flow. Lives on `CommonCallbacks` because both Auth and
|
|
406
|
+
* any SDK embedding `@zerohash/integrations-flow` (e.g. fund with `useAuth`)
|
|
407
|
+
* resolve through the same deposit-status hook.
|
|
408
|
+
*/
|
|
409
|
+
declare type DepositCompletedPayload = {
|
|
410
|
+
data: {
|
|
411
|
+
depositId: string;
|
|
412
|
+
status: DepositStatus;
|
|
413
|
+
assetId: string;
|
|
414
|
+
networkId: string;
|
|
415
|
+
amount?: string;
|
|
416
|
+
accountMatchingValidation?: {
|
|
417
|
+
status: 'PENDING' | 'VALID' | 'INVALID' | 'ERROR';
|
|
418
|
+
reason?: string;
|
|
419
|
+
};
|
|
420
|
+
};
|
|
421
|
+
};
|
|
422
|
+
|
|
423
|
+
/**
|
|
424
|
+
* Deposit status object — shared across SDKs that surface deposit completion.
|
|
425
|
+
*/
|
|
426
|
+
declare type DepositStatus = {
|
|
427
|
+
value: string;
|
|
428
|
+
details: string;
|
|
429
|
+
occurredAt: string;
|
|
430
|
+
};
|
|
431
|
+
|
|
432
|
+
/**
|
|
433
|
+
* Environment configuration for the SDK
|
|
434
|
+
*/
|
|
435
|
+
export declare type Environment = 'local' | 'dev' | 'cert' | 'prod' | 'sandbox' | 'production';
|
|
436
|
+
|
|
437
|
+
/**
|
|
438
|
+
* Generic error codes for all Connect applications
|
|
439
|
+
*/
|
|
440
|
+
export declare enum ErrorCode {
|
|
441
|
+
/** Network connectivity error */
|
|
442
|
+
NETWORK_ERROR = 'network_error',
|
|
443
|
+
/** Authentication or session expired error */
|
|
444
|
+
AUTH_ERROR = 'auth_error',
|
|
445
|
+
/** Resource not found error */
|
|
446
|
+
NOT_FOUND_ERROR = 'not_found_error',
|
|
447
|
+
/** Validation error from user input */
|
|
448
|
+
VALIDATION_ERROR = 'validation_error',
|
|
449
|
+
/** Server error (5xx) */
|
|
450
|
+
SERVER_ERROR = 'server_error',
|
|
451
|
+
/** Client error (4xx) */
|
|
452
|
+
CLIENT_ERROR = 'client_error',
|
|
453
|
+
/** Unknown or unexpected error */
|
|
454
|
+
UNKNOWN_ERROR = 'unknown_error',
|
|
455
|
+
}
|
|
456
|
+
|
|
457
|
+
/**
|
|
458
|
+
* Generic error payload structure for error callbacks
|
|
459
|
+
*/
|
|
460
|
+
declare type ErrorPayload = {
|
|
461
|
+
/** Error code indicating the type of error */
|
|
462
|
+
errorCode: ErrorCode;
|
|
463
|
+
/** Human-readable reason for the error */
|
|
464
|
+
reason: string;
|
|
465
|
+
};
|
|
466
|
+
|
|
467
|
+
/**
|
|
468
|
+
* Generic HTMLElement representing a web component with custom config
|
|
469
|
+
*/
|
|
470
|
+
declare type SdkElement<Config extends BaseConfig<never>> = HTMLElement & Config;
|
|
471
|
+
|
|
472
|
+
/**
|
|
473
|
+
* Internal state of the SDK
|
|
474
|
+
*/
|
|
475
|
+
declare interface SdkState {
|
|
476
|
+
/** Whether the SDK is initialized */
|
|
477
|
+
initialized: boolean;
|
|
478
|
+
/** Whether the web component script is loaded */
|
|
479
|
+
scriptLoaded: boolean;
|
|
480
|
+
/** The container element where the widget is rendered */
|
|
481
|
+
container: HTMLElement | null;
|
|
482
|
+
/** The web component element */
|
|
483
|
+
element: HTMLElement | null;
|
|
484
|
+
}
|
|
485
|
+
|
|
486
|
+
/**
|
|
487
|
+
* Theme configuration for the SDK
|
|
488
|
+
*
|
|
489
|
+
* - `"auto"` - Automatically detect system preference (light/dark mode)
|
|
490
|
+
* - `"light"` - Force light theme
|
|
491
|
+
* - `"dark"` - Force dark theme
|
|
492
|
+
*/
|
|
493
|
+
declare type Theme = 'auto' | 'light' | 'dark';
|
|
494
|
+
|
|
495
|
+
export declare type ZerohashCryptoDepositsElement = SdkElement<CryptoDepositsConfig>;
|
|
496
|
+
|
|
497
|
+
export { }
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,334 @@
|
|
|
1
|
+
const T = "production", M = "JWT token is required and must be a string.", W = {
|
|
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
|
+
}, k = (e) => {
|
|
10
|
+
if (!e || typeof e != "string")
|
|
11
|
+
return null;
|
|
12
|
+
const t = e.split(".");
|
|
13
|
+
if (t.length < 2)
|
|
14
|
+
return null;
|
|
15
|
+
try {
|
|
16
|
+
const r = t[1].replace(/-/g, "+").replace(/_/g, "/"), o = r + "===".slice(0, (4 - r.length % 4) % 4), n = typeof atob < "u" ? atob(o) : Buffer.from(o, "base64").toString("utf-8"), i = JSON.parse(n)?.payload?.region;
|
|
17
|
+
if (typeof i != "string")
|
|
18
|
+
return null;
|
|
19
|
+
const s = i.toLowerCase();
|
|
20
|
+
return s === "us" || s === "eu" ? s : null;
|
|
21
|
+
} catch {
|
|
22
|
+
return null;
|
|
23
|
+
}
|
|
24
|
+
}, O = (e, t) => k(t) !== "eu" ? e : e === "cert" ? "eu-cert" : e === "prod" ? "eu-prod" : e, P = (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, "/"), o = r + "===".slice(0, (4 - r.length % 4) % 4), n = typeof atob < "u" ? atob(o) : Buffer.from(o, "base64").toString("utf-8"), a = JSON.parse(n), i = a?.payload ?? {}, s = (c) => typeof c == "string" && c.length > 0 ? c : void 0;
|
|
32
|
+
return {
|
|
33
|
+
participantCode: s(i.participant_code),
|
|
34
|
+
platformName: s(i.platform_name),
|
|
35
|
+
platformCode: s(a.platform_code),
|
|
36
|
+
region: s(i.region)
|
|
37
|
+
};
|
|
38
|
+
} catch {
|
|
39
|
+
return {};
|
|
40
|
+
}
|
|
41
|
+
}, N = (e, t, r) => {
|
|
42
|
+
const o = O(t, r);
|
|
43
|
+
return e[o] ?? e[t] ?? e.prod;
|
|
44
|
+
}, U = (e, t, r) => {
|
|
45
|
+
const o = O(t, r);
|
|
46
|
+
return e[o] ?? e[t];
|
|
47
|
+
}, w = () => {
|
|
48
|
+
}, F = () => {
|
|
49
|
+
const e = new Uint8Array(8);
|
|
50
|
+
return globalThis.crypto.getRandomValues(e), Array.from(e, (t) => t.toString(16).padStart(2, "0")).join("");
|
|
51
|
+
}, $ = (e, t) => {
|
|
52
|
+
const r = F(), o = globalThis.__ZH_WEB_SDK_VERSION__, n = {};
|
|
53
|
+
e.claims.participantCode && (n.participant_code = e.claims.participantCode), e.claims.platformName && (n.platform_name = e.claims.platformName), e.claims.platformCode && (n.platform_code = e.claims.platformCode), e.claims.region && (n.region = e.claims.region), o && (n.zh_web_sdk_version = o);
|
|
54
|
+
const a = {
|
|
55
|
+
meta: {
|
|
56
|
+
app: { name: e.appName, version: t ?? "unknown", environment: e.env },
|
|
57
|
+
session: { id: r, attributes: n },
|
|
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
|
+
}, B = (e, t, r) => {
|
|
78
|
+
if (!e || typeof fetch > "u")
|
|
79
|
+
return;
|
|
80
|
+
const { sessionId: o, payload: n } = $(t, r);
|
|
81
|
+
try {
|
|
82
|
+
fetch(e, {
|
|
83
|
+
method: "POST",
|
|
84
|
+
headers: { "Content-Type": "application/json", "x-faro-session-id": o },
|
|
85
|
+
body: JSON.stringify(n),
|
|
86
|
+
keepalive: !0
|
|
87
|
+
}).catch(() => {
|
|
88
|
+
});
|
|
89
|
+
} catch {
|
|
90
|
+
}
|
|
91
|
+
}, V = (e) => {
|
|
92
|
+
const { webComponentTag: t, appName: r, appVersion: o, scriptUrls: n, fallbackScriptUrls: a, collectorUrls: i, env: s, jwt: c, timeoutMs: L = 15e3, onLoad: v, onError: D } = e;
|
|
93
|
+
if (typeof document > "u")
|
|
94
|
+
return w;
|
|
95
|
+
const h = `${t}-script-${s}`;
|
|
96
|
+
if (customElements.get(t) || document.getElementById(h))
|
|
97
|
+
return w;
|
|
98
|
+
const I = P(c), A = e.report ?? ((l) => B(i && U(i, s, c), l, o));
|
|
99
|
+
let m = !1, y = 0, g;
|
|
100
|
+
const f = () => {
|
|
101
|
+
g !== void 0 && clearTimeout(g);
|
|
102
|
+
}, E = (l, u, d) => {
|
|
103
|
+
if (m)
|
|
104
|
+
return;
|
|
105
|
+
const z = Math.round(performance.now() - y), b = {
|
|
106
|
+
webComponentTag: t,
|
|
107
|
+
appName: r,
|
|
108
|
+
env: s,
|
|
109
|
+
scriptUrl: u,
|
|
110
|
+
reason: l,
|
|
111
|
+
triedFallback: d,
|
|
112
|
+
elapsedMs: z,
|
|
113
|
+
claims: I
|
|
114
|
+
};
|
|
115
|
+
A(b);
|
|
116
|
+
const _ = d ? void 0 : N(a ?? {}, s, c);
|
|
117
|
+
if (_ && _ !== u) {
|
|
118
|
+
C(_, !0);
|
|
119
|
+
return;
|
|
120
|
+
}
|
|
121
|
+
m = !0, f(), document.getElementById(h)?.remove(), D?.(b);
|
|
122
|
+
}, C = (l, u) => {
|
|
123
|
+
f(), y = performance.now();
|
|
124
|
+
const d = document.createElement("script");
|
|
125
|
+
d.id = h, d.src = l, d.type = "module", d.async = !0, d.onload = () => {
|
|
126
|
+
setTimeout(() => {
|
|
127
|
+
m || (customElements.get(t) ? (m = !0, f(), v?.()) : E("not-defined", l, u));
|
|
128
|
+
}, 0);
|
|
129
|
+
}, d.onerror = () => E("network", l, u), g = setTimeout(() => E("timeout", l, u), L), document.getElementById(h)?.remove(), document.head.appendChild(d);
|
|
130
|
+
}, R = N(n, s, c);
|
|
131
|
+
return R ? (C(R, !1), () => {
|
|
132
|
+
m = !0, f();
|
|
133
|
+
}) : w;
|
|
134
|
+
};
|
|
135
|
+
class j {
|
|
136
|
+
config;
|
|
137
|
+
state;
|
|
138
|
+
scriptLoadingPromise;
|
|
139
|
+
constructor(t) {
|
|
140
|
+
if (!t.jwt || typeof t.jwt != "string")
|
|
141
|
+
throw new Error(M);
|
|
142
|
+
this.config = {
|
|
143
|
+
...t,
|
|
144
|
+
env: t.env || T,
|
|
145
|
+
theme: t.theme
|
|
146
|
+
}, this.state = {
|
|
147
|
+
initialized: !1,
|
|
148
|
+
scriptLoaded: !1,
|
|
149
|
+
container: null,
|
|
150
|
+
element: null
|
|
151
|
+
};
|
|
152
|
+
}
|
|
153
|
+
/**
|
|
154
|
+
* Render the widget to a container element
|
|
155
|
+
* @param container - The container element to render the widget into
|
|
156
|
+
* @returns Promise that resolves when the widget is rendered
|
|
157
|
+
*/
|
|
158
|
+
async render(t) {
|
|
159
|
+
if (!t || !(t instanceof HTMLElement))
|
|
160
|
+
throw new Error(this.errorMessages.INVALID_CONTAINER);
|
|
161
|
+
if (this.state.initialized)
|
|
162
|
+
throw new Error(this.errorMessages.ALREADY_RENDERED);
|
|
163
|
+
try {
|
|
164
|
+
await this.ensureScriptLoaded();
|
|
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;
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
/**
|
|
172
|
+
* Update the configuration of the widget (e.g. `theme`, or the `jwt`).
|
|
173
|
+
*
|
|
174
|
+
* Passing a `jwt` is the JS-SDK equivalent of `setJWT` — it provides the JWT
|
|
175
|
+
* used to authenticate.
|
|
176
|
+
*
|
|
177
|
+
* @param config - Partial configuration to update
|
|
178
|
+
* @returns void
|
|
179
|
+
*/
|
|
180
|
+
updateConfig(t) {
|
|
181
|
+
if (!this.state.initialized || !this.state.element)
|
|
182
|
+
throw new Error(this.errorMessages.NOT_RENDERED);
|
|
183
|
+
const r = this.state.element;
|
|
184
|
+
Object.entries(t).forEach(([o, n]) => {
|
|
185
|
+
n && (this.config[o] = n, r[o] = n);
|
|
186
|
+
});
|
|
187
|
+
}
|
|
188
|
+
/**
|
|
189
|
+
* Destroy the widget and clean up resources
|
|
190
|
+
*/
|
|
191
|
+
destroy() {
|
|
192
|
+
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);
|
|
193
|
+
}
|
|
194
|
+
/**
|
|
195
|
+
* Check if the widget is currently rendered
|
|
196
|
+
* @returns True if the widget is rendered, false otherwise
|
|
197
|
+
*/
|
|
198
|
+
isRendered() {
|
|
199
|
+
return this.state.initialized;
|
|
200
|
+
}
|
|
201
|
+
/**
|
|
202
|
+
* Get the current configuration
|
|
203
|
+
* @returns The current configuration object
|
|
204
|
+
*/
|
|
205
|
+
getConfig() {
|
|
206
|
+
return { ...this.config };
|
|
207
|
+
}
|
|
208
|
+
getEnvironment() {
|
|
209
|
+
return this.config.env || T;
|
|
210
|
+
}
|
|
211
|
+
getScriptId() {
|
|
212
|
+
return `${this.webComponentTag}-script-${this.getEnvironment()}`;
|
|
213
|
+
}
|
|
214
|
+
isScriptLoaded() {
|
|
215
|
+
return !!document.getElementById(this.getScriptId());
|
|
216
|
+
}
|
|
217
|
+
getWebComponent() {
|
|
218
|
+
return customElements.get(this.webComponentTag);
|
|
219
|
+
}
|
|
220
|
+
getEffectiveScriptUrls() {
|
|
221
|
+
return this.scriptUrls;
|
|
222
|
+
}
|
|
223
|
+
async loadScript() {
|
|
224
|
+
if (!(this.getWebComponent() || this.isScriptLoaded())) {
|
|
225
|
+
if (this.scriptLoadingPromise)
|
|
226
|
+
return this.scriptLoadingPromise;
|
|
227
|
+
this.scriptLoadingPromise = new Promise((t, r) => {
|
|
228
|
+
V({
|
|
229
|
+
webComponentTag: this.webComponentTag,
|
|
230
|
+
appName: this.webComponentTag,
|
|
231
|
+
scriptUrls: this.getEffectiveScriptUrls(),
|
|
232
|
+
collectorUrls: W,
|
|
233
|
+
env: this.getEnvironment(),
|
|
234
|
+
jwt: this.config.jwt,
|
|
235
|
+
onLoad: t,
|
|
236
|
+
onError: (o) => {
|
|
237
|
+
r(new Error(o.reason === "not-defined" ? this.errorMessages.WEB_COMPONENT_NOT_DEFINED : `${this.errorMessages.SCRIPT_LOAD_FAILED} (${this.getEnvironment()})`));
|
|
238
|
+
}
|
|
239
|
+
});
|
|
240
|
+
});
|
|
241
|
+
try {
|
|
242
|
+
await this.scriptLoadingPromise;
|
|
243
|
+
} catch (t) {
|
|
244
|
+
throw this.scriptLoadingPromise = void 0, t;
|
|
245
|
+
}
|
|
246
|
+
return this.scriptLoadingPromise;
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
async waitForWebComponent(t = 5e3) {
|
|
250
|
+
if (!this.getWebComponent())
|
|
251
|
+
return new Promise((r, o) => {
|
|
252
|
+
const n = setTimeout(() => {
|
|
253
|
+
o(new Error(`Timeout waiting for ${this.webComponentTag} to be defined`));
|
|
254
|
+
}, t);
|
|
255
|
+
customElements.whenDefined(this.webComponentTag).then(() => {
|
|
256
|
+
clearTimeout(n), r();
|
|
257
|
+
}).catch((a) => {
|
|
258
|
+
clearTimeout(n), o(a);
|
|
259
|
+
});
|
|
260
|
+
});
|
|
261
|
+
}
|
|
262
|
+
/**
|
|
263
|
+
* Load the web component script if not already loaded
|
|
264
|
+
*/
|
|
265
|
+
async ensureScriptLoaded() {
|
|
266
|
+
if (!this.state.scriptLoaded)
|
|
267
|
+
try {
|
|
268
|
+
await this.loadScript(), await this.waitForWebComponent(), this.state.scriptLoaded = !0;
|
|
269
|
+
} catch (t) {
|
|
270
|
+
throw console.error("Failed to load Connect script:", t), t;
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
createWebComponent() {
|
|
274
|
+
const t = document.createElement(this.webComponentTag);
|
|
275
|
+
return Object.entries(this.config).forEach(([r, o]) => {
|
|
276
|
+
o && (t[r] = o);
|
|
277
|
+
}), t;
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
const p = {
|
|
281
|
+
local: "http://localhost:5173",
|
|
282
|
+
dev: "https://sdk-cdn.dev.0hash.com",
|
|
283
|
+
cert: "https://sdk-cdn.cert.zerohash.com",
|
|
284
|
+
prod: "https://sdk-cdn.zerohash.com",
|
|
285
|
+
"eu-cert": "https://sdk-cdn.cert.zerohash.eu",
|
|
286
|
+
"eu-prod": "https://sdk-cdn.zerohash.eu"
|
|
287
|
+
}, J = "https://sdk-cdn.gating.0hash.com", x = (e, t, r = {}) => {
|
|
288
|
+
const { eu: o = !1, legacyAliases: n = !1, local: a = p.local } = r, i = (c) => `${c}/${e}/${t}`, s = {
|
|
289
|
+
local: i(a),
|
|
290
|
+
dev: i(p.dev),
|
|
291
|
+
gating: i(J),
|
|
292
|
+
cert: i(p.cert),
|
|
293
|
+
prod: i(p.prod)
|
|
294
|
+
};
|
|
295
|
+
return n && (s.sandbox = i(p.cert), s.production = i(p.prod)), o && (s["eu-cert"] = i(p["eu-cert"]), s["eu-prod"] = i(p["eu-prod"])), s;
|
|
296
|
+
};
|
|
297
|
+
var S;
|
|
298
|
+
(function(e) {
|
|
299
|
+
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";
|
|
300
|
+
})(S || (S = {}));
|
|
301
|
+
class H extends j {
|
|
302
|
+
errorMessages = {
|
|
303
|
+
ALREADY_RENDERED: "CryptoDeposits widget is already rendered. Call destroy() before rendering again.",
|
|
304
|
+
NOT_RENDERED: "CryptoDeposits widget is not rendered. Call render() first.",
|
|
305
|
+
INVALID_CONTAINER: "Invalid container element provided.",
|
|
306
|
+
SCRIPT_LOAD_FAILED: "Failed to load the Connect CryptoDeposits script.",
|
|
307
|
+
WEB_COMPONENT_NOT_DEFINED: "Web component is not defined. Script may not be loaded."
|
|
308
|
+
};
|
|
309
|
+
scriptUrls = x("crypto-deposits-web", "index.js", {
|
|
310
|
+
legacyAliases: !0,
|
|
311
|
+
eu: !0
|
|
312
|
+
});
|
|
313
|
+
webComponentTag = "zerohash-crypto-deposits";
|
|
314
|
+
render(t) {
|
|
315
|
+
return super.render(t);
|
|
316
|
+
}
|
|
317
|
+
updateConfig(t) {
|
|
318
|
+
return super.updateConfig(t);
|
|
319
|
+
}
|
|
320
|
+
getConfig() {
|
|
321
|
+
return super.getConfig();
|
|
322
|
+
}
|
|
323
|
+
isRendered() {
|
|
324
|
+
return super.isRendered();
|
|
325
|
+
}
|
|
326
|
+
destroy() {
|
|
327
|
+
return super.destroy();
|
|
328
|
+
}
|
|
329
|
+
}
|
|
330
|
+
export {
|
|
331
|
+
H as CryptoDeposits,
|
|
332
|
+
S as ErrorCode,
|
|
333
|
+
H as default
|
|
334
|
+
};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
(function(c,m){typeof exports=="object"&&typeof module<"u"?m(exports):typeof define=="function"&&define.amd?define(["exports"],m):(c=typeof globalThis<"u"?globalThis:c||self,m(c.CryptoDeposits={}))})(this,(function(c){"use strict";const m="production",v="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"},I=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,"/"),o=r+"===".slice(0,(4-r.length%4)%4),n=typeof atob<"u"?atob(o):Buffer.from(o,"base64").toString("utf-8"),i=JSON.parse(n)?.payload?.region;if(typeof i!="string")return null;const s=i.toLowerCase();return s==="us"||s==="eu"?s:null}catch{return null}},b=(e,t)=>I(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,"/"),o=r+"===".slice(0,(4-r.length%4)%4),n=typeof atob<"u"?atob(o):Buffer.from(o,"base64").toString("utf-8"),a=JSON.parse(n),i=a?.payload??{},s=d=>typeof d=="string"&&d.length>0?d:void 0;return{participantCode:s(i.participant_code),platformName:s(i.platform_name),platformCode:s(a.platform_code),region:s(i.region)}}catch{return{}}},R=(e,t,r)=>{const o=b(t,r);return e[o]??e[t]??e.prod},z=(e,t,r)=>{const o=b(t,r);return e[o]??e[t]},_=()=>{},M=()=>{const e=new Uint8Array(8);return globalThis.crypto.getRandomValues(e),Array.from(e,t=>t.toString(16).padStart(2,"0")).join("")},W=(e,t)=>{const r=M(),o=globalThis.__ZH_WEB_SDK_VERSION__,n={};e.claims.participantCode&&(n.participant_code=e.claims.participantCode),e.claims.platformName&&(n.platform_name=e.claims.platformName),e.claims.platformCode&&(n.platform_code=e.claims.platformCode),e.claims.region&&(n.region=e.claims.region),o&&(n.zh_web_sdk_version=o);const a={meta:{app:{name:e.appName,version:t??"unknown",environment:e.env},session:{id:r,attributes:n},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}},P=(e,t,r)=>{if(!e||typeof fetch>"u")return;const{sessionId:o,payload:n}=W(t,r);try{fetch(e,{method:"POST",headers:{"Content-Type":"application/json","x-faro-session-id":o},body:JSON.stringify(n),keepalive:!0}).catch(()=>{})}catch{}},k=e=>{const{webComponentTag:t,appName:r,appVersion:o,scriptUrls:n,fallbackScriptUrls:a,collectorUrls:i,env:s,jwt:d,timeoutMs:j=15e3,onLoad:B,onError:V}=e;if(typeof document>"u")return _;const g=`${t}-script-${s}`;if(customElements.get(t)||document.getElementById(g))return _;const J=A(d),H=e.report??(u=>P(i&&z(i,s,d),u,o));let f=!1,N=0,y;const E=()=>{y!==void 0&&clearTimeout(y)},w=(u,h,l)=>{if(f)return;const x=Math.round(performance.now()-N),L={webComponentTag:t,appName:r,env:s,scriptUrl:h,reason:u,triedFallback:l,elapsedMs:x,claims:J};H(L);const C=l?void 0:R(a??{},s,d);if(C&&C!==h){S(C,!0);return}f=!0,E(),document.getElementById(g)?.remove(),V?.(L)},S=(u,h)=>{E(),N=performance.now();const l=document.createElement("script");l.id=g,l.src=u,l.type="module",l.async=!0,l.onload=()=>{setTimeout(()=>{f||(customElements.get(t)?(f=!0,E(),B?.()):w("not-defined",u,h))},0)},l.onerror=()=>w("network",u,h),y=setTimeout(()=>w("timeout",u,h),j),document.getElementById(g)?.remove(),document.head.appendChild(l)},O=R(n,s,d);return O?(S(O,!1),()=>{f=!0,E()}):_};class U{config;state;scriptLoadingPromise;constructor(t){if(!t.jwt||typeof t.jwt!="string")throw new Error(v);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(([o,n])=>{n&&(this.config[o]=n,r[o]=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||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)=>{k({webComponentTag:this.webComponentTag,appName:this.webComponentTag,scriptUrls:this.getEffectiveScriptUrls(),collectorUrls:D,env:this.getEnvironment(),jwt:this.config.jwt,onLoad:t,onError:o=>{r(new Error(o.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,o)=>{const n=setTimeout(()=>{o(new Error(`Timeout waiting for ${this.webComponentTag} to be defined`))},t);customElements.whenDefined(this.webComponentTag).then(()=>{clearTimeout(n),r()}).catch(a=>{clearTimeout(n),o(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,o])=>{o&&(t[r]=o)}),t}}const p={local:"http://localhost:5173",dev:"https://sdk-cdn.dev.0hash.com",cert:"https://sdk-cdn.cert.zerohash.com",prod:"https://sdk-cdn.zerohash.com","eu-cert":"https://sdk-cdn.cert.zerohash.eu","eu-prod":"https://sdk-cdn.zerohash.eu"},F="https://sdk-cdn.gating.0hash.com",$=(e,t,r={})=>{const{eu:o=!1,legacyAliases:n=!1,local:a=p.local}=r,i=d=>`${d}/${e}/${t}`,s={local:i(a),dev:i(p.dev),gating:i(F),cert:i(p.cert),prod:i(p.prod)};return n&&(s.sandbox=i(p.cert),s.production=i(p.prod)),o&&(s["eu-cert"]=i(p["eu-cert"]),s["eu-prod"]=i(p["eu-prod"])),s};c.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"})(c.ErrorCode||(c.ErrorCode={}));class T extends U{errorMessages={ALREADY_RENDERED:"CryptoDeposits widget is already rendered. Call destroy() before rendering again.",NOT_RENDERED:"CryptoDeposits widget is not rendered. Call render() first.",INVALID_CONTAINER:"Invalid container element provided.",SCRIPT_LOAD_FAILED:"Failed to load the Connect CryptoDeposits script.",WEB_COMPONENT_NOT_DEFINED:"Web component is not defined. Script may not be loaded."};scriptUrls=$("crypto-deposits-web","index.js",{legacyAliases:!0,eu:!0});webComponentTag="zerohash-crypto-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()}}c.CryptoDeposits=T,c.default=T,Object.defineProperties(c,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})}));
|