-
Notifications
You must be signed in to change notification settings - Fork 453
Expand file tree
/
Copy pathloadClerkJsScript.ts
More file actions
359 lines (302 loc) · 10.7 KB
/
loadClerkJsScript.ts
File metadata and controls
359 lines (302 loc) · 10.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
import { buildErrorThrower, ClerkRuntimeError } from './error';
import { createDevOrStagingUrlCache, parsePublishableKey } from './keys';
import { loadScript } from './loadScript';
import { isValidProxyUrl, proxyUrlToAbsoluteURL } from './proxy';
import type { SDKMetadata } from './types';
import { addClerkPrefix } from './url';
import { versionSelector } from './versionSelector';
const { isDevOrStagingUrl } = createDevOrStagingUrlCache();
const errorThrower = buildErrorThrower({ packageName: '@clerk/shared' });
export type LoadClerkJsScriptOptions = {
publishableKey: string;
clerkJSUrl?: string;
clerkJSVariant?: 'headless' | '';
clerkJSVersion?: string;
/**
* Branded object for pinning @clerk/clerk-js version.
* Takes precedence over clerkJSVersion if both are provided.
*/
clerkJs?: { version: string };
sdkMetadata?: SDKMetadata;
proxyUrl?: string;
domain?: string;
nonce?: string;
/**
* Timeout in milliseconds to wait for clerk-js to load before considering it failed.
*
* @default 15000 (15 seconds)
*/
scriptLoadTimeout?: number;
};
export type LoadClerkUiScriptOptions = {
publishableKey: string;
clerkUiUrl?: string;
clerkUIVariant?: 'shared' | '';
clerkUiVersion?: string;
proxyUrl?: string;
domain?: string;
nonce?: string;
scriptLoadTimeout?: number;
};
/**
* Validates that window.Clerk exists and is properly initialized.
* This ensures we don't have false positives where the script loads but Clerk is malformed.
*
* @returns `true` if window.Clerk exists and has the expected structure with a load method.
*/
function isClerkGlobalProperlyLoaded(prop: 'Clerk' | '__internal_ClerkUiCtor'): boolean {
if (typeof window === 'undefined' || !(window as any)[prop]) {
return false;
}
// Basic validation that window.Clerk has the expected structure
const val = (window as any)[prop];
return !!val;
}
const isClerkProperlyLoaded = () => isClerkGlobalProperlyLoaded('Clerk');
const isClerkUiProperlyLoaded = () => isClerkGlobalProperlyLoaded('__internal_ClerkUiCtor');
/**
* Checks if an existing script has a request error using Performance API.
*
* @param scriptUrl - The URL of the script to check.
* @returns True if the script has failed to load due to a network/HTTP error.
*/
function hasScriptRequestError(scriptUrl: string): boolean {
if (typeof window === 'undefined' || !window.performance) {
return false;
}
const entries = performance.getEntriesByName(scriptUrl, 'resource') as PerformanceResourceTiming[];
if (entries.length === 0) {
return false;
}
const scriptEntry = entries[entries.length - 1];
// transferSize === 0 with responseEnd === 0 indicates network failure
// transferSize === 0 with responseEnd > 0 might be a 4xx/5xx error or blocked request
if (scriptEntry.transferSize === 0 && scriptEntry.decodedBodySize === 0) {
// If there was no response at all, it's definitely an error
if (scriptEntry.responseEnd === 0) {
return true;
}
// If we got a response but no content, likely an HTTP error (4xx/5xx)
if (scriptEntry.responseEnd > 0 && scriptEntry.responseStart > 0) {
return true;
}
if ('responseStatus' in scriptEntry) {
const status = (scriptEntry as any).responseStatus;
if (status >= 400) {
return true;
}
if (scriptEntry.responseStatus === 0) {
return true;
}
}
}
return false;
}
/**
* Hotloads the Clerk JS script with robust failure detection.
*
* Uses a timeout-based approach to ensure absolute certainty about load success/failure.
* If the script fails to load within the timeout period, or loads but doesn't create
* a proper Clerk instance, the promise rejects with an error.
*
* @param opts - The options used to build the Clerk JS script URL and load the script.
* Must include a `publishableKey` if no existing script is found.
* @returns Promise that resolves with null if Clerk loads successfully, or rejects with an error.
*
* @example
* ```typescript
* try {
* await loadClerkJsScript({ publishableKey: 'pk_test_...' });
* console.log('Clerk loaded successfully');
* } catch (error) {
* console.error('Failed to load Clerk:', error.message);
* }
* ```
*/
export const loadClerkJsScript = async (opts?: LoadClerkJsScriptOptions): Promise<HTMLScriptElement | null> => {
const timeout = opts?.scriptLoadTimeout ?? 15000;
const rejectWith = (error?: Error) =>
new ClerkRuntimeError('Failed to load Clerk JS' + (error?.message ? `, ${error.message}` : ''), {
code: 'failed_to_load_clerk_js',
cause: error,
});
if (isClerkProperlyLoaded()) {
return null;
}
if (!opts?.publishableKey) {
errorThrower.throwMissingPublishableKeyError();
return null;
}
const scriptUrl = clerkJsScriptUrl(opts);
const existingScript = document.querySelector<HTMLScriptElement>('script[data-clerk-js-script]');
if (existingScript) {
if (hasScriptRequestError(scriptUrl)) {
existingScript.remove();
} else {
try {
await waitForPredicateWithTimeout(timeout, isClerkProperlyLoaded, rejectWith(), existingScript);
return null;
} catch {
existingScript.remove();
}
}
}
const loadPromise = waitForPredicateWithTimeout(timeout, isClerkProperlyLoaded, rejectWith());
loadScript(scriptUrl, {
async: true,
crossOrigin: 'anonymous',
nonce: opts.nonce,
beforeLoad: applyAttributesToScript(buildClerkJsScriptAttributes(opts)),
}).catch(error => {
throw rejectWith(error);
});
return loadPromise;
};
export const loadClerkUiScript = async (opts?: LoadClerkUiScriptOptions): Promise<HTMLScriptElement | null> => {
const timeout = opts?.scriptLoadTimeout ?? 15000;
const rejectWith = (error?: Error) =>
new ClerkRuntimeError('Failed to load Clerk UI' + (error?.message ? `, ${error.message}` : ''), {
code: 'failed_to_load_clerk_ui',
cause: error,
});
if (isClerkUiProperlyLoaded()) {
return null;
}
if (!opts?.publishableKey) {
errorThrower.throwMissingPublishableKeyError();
return null;
}
const scriptUrl = clerkUiScriptUrl(opts);
const existingScript = document.querySelector<HTMLScriptElement>('script[data-clerk-ui-script]');
if (existingScript) {
if (hasScriptRequestError(scriptUrl)) {
existingScript.remove();
} else {
try {
await waitForPredicateWithTimeout(timeout, isClerkUiProperlyLoaded, rejectWith(), existingScript);
return null;
} catch {
existingScript.remove();
}
}
}
const loadPromise = waitForPredicateWithTimeout(timeout, isClerkUiProperlyLoaded, rejectWith());
loadScript(scriptUrl, {
async: true,
crossOrigin: 'anonymous',
nonce: opts.nonce,
beforeLoad: applyAttributesToScript(buildClerkUiScriptAttributes(opts)),
}).catch(error => {
throw rejectWith(error);
});
return loadPromise;
};
export const clerkJsScriptUrl = (opts: LoadClerkJsScriptOptions) => {
const { clerkJSUrl, clerkJSVariant, clerkJSVersion, clerkJs, proxyUrl, domain, publishableKey } = opts;
if (clerkJSUrl) {
return clerkJSUrl;
}
const scriptHost = buildScriptHost({ publishableKey, proxyUrl, domain });
const variant = clerkJSVariant ? `${clerkJSVariant.replace(/\.+$/, '')}.` : '';
// clerkJs object takes precedence over clerkJSVersion string
const version = versionSelector(clerkJs?.version ?? clerkJSVersion);
return `https://${scriptHost}/npm/@clerk/clerk-js@${version}/dist/clerk.${variant}browser.js`;
};
export const clerkUiScriptUrl = (opts: LoadClerkUiScriptOptions) => {
const { clerkUiUrl, clerkUIVariant, clerkUiVersion, proxyUrl, domain, publishableKey } = opts;
if (clerkUiUrl) {
return clerkUiUrl;
}
const scriptHost = buildScriptHost({ publishableKey, proxyUrl, domain });
const variant = clerkUIVariant ? `${clerkUIVariant}.` : '';
const version = versionSelector(clerkUiVersion, UI_PACKAGE_VERSION);
return `https://${scriptHost}/npm/@clerk/ui@${version}/dist/ui.${variant}browser.js`;
};
export const buildClerkJsScriptAttributes = (options: LoadClerkJsScriptOptions) => {
const obj: Record<string, string> = {};
if (options.publishableKey) {
obj['data-clerk-publishable-key'] = options.publishableKey;
}
if (options.proxyUrl) {
obj['data-clerk-proxy-url'] = options.proxyUrl;
}
if (options.domain) {
obj['data-clerk-domain'] = options.domain;
}
if (options.nonce) {
obj.nonce = options.nonce;
}
return obj;
};
export const buildClerkUiScriptAttributes = (options: LoadClerkUiScriptOptions) => {
// TODO @nikos do we need this?
return buildClerkJsScriptAttributes(options);
};
const applyAttributesToScript = (attributes: Record<string, string>) => (script: HTMLScriptElement) => {
for (const attribute in attributes) {
script.setAttribute(attribute, attributes[attribute]);
}
};
export const buildScriptHost = (opts: { publishableKey: string; proxyUrl?: string; domain?: string }) => {
const { proxyUrl, domain, publishableKey } = opts;
if (!!proxyUrl && isValidProxyUrl(proxyUrl)) {
return proxyUrlToAbsoluteURL(proxyUrl).replace(/http(s)?:\/\//, '');
} else if (domain && !isDevOrStagingUrl(parsePublishableKey(publishableKey)?.frontendApi || '')) {
return addClerkPrefix(domain);
} else {
return parsePublishableKey(publishableKey)?.frontendApi || '';
}
};
function waitForPredicateWithTimeout(
timeoutMs: number,
predicate: () => boolean,
rejectWith: Error,
existingScript?: HTMLScriptElement,
): Promise<HTMLScriptElement | null> {
return new Promise((resolve, reject) => {
let resolved = false;
const cleanup = (timeoutId: ReturnType<typeof setTimeout>, pollInterval: ReturnType<typeof setInterval>) => {
clearTimeout(timeoutId);
clearInterval(pollInterval);
};
// Bail out early if the script fails to load, instead of waiting for the entire timeout
existingScript?.addEventListener('error', () => {
cleanup(timeoutId, pollInterval);
reject(rejectWith);
});
const checkAndResolve = () => {
if (resolved) {
return;
}
if (predicate()) {
resolved = true;
cleanup(timeoutId, pollInterval);
resolve(null);
}
};
const handleTimeout = () => {
if (resolved) {
return;
}
resolved = true;
cleanup(timeoutId, pollInterval);
if (!predicate()) {
reject(rejectWith);
} else {
resolve(null);
}
};
const timeoutId = setTimeout(handleTimeout, timeoutMs);
checkAndResolve();
const pollInterval = setInterval(() => {
if (resolved) {
clearInterval(pollInterval);
return;
}
checkAndResolve();
}, 100);
});
}
export function setClerkJsLoadingErrorPackageName(packageName: string) {
errorThrower.setPackageName({ packageName });
}