Repository navigation
Expand file tree
/
Copy pathsetup.ts
More file actions
103 lines (88 loc) · 3.66 KB
/
Copy pathsetup.ts
File metadata and controls
103 lines (88 loc) · 3.66 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
import { createClerkClient } from '@clerk/backend';
import { isClerkAPIResponseError } from '@clerk/shared/error';
import { parsePublishableKey } from '@clerk/shared/keys';
import dotenv from 'dotenv';
import type { ClerkSetupOptions, ClerkSetupReturn } from './types';
const MAX_RETRIES = 5;
const BASE_DELAY_MS = 1000;
const JITTER_MAX_MS = 500;
const MAX_RETRY_DELAY_MS = 30_000;
const RETRYABLE_STATUS_CODES = new Set([408, 429, 500, 502, 503, 504]);
const RETRYABLE_NETWORK_ERRORS = new Set(['ECONNREFUSED', 'ECONNRESET', 'ENOTFOUND', 'ETIMEDOUT', 'EAI_AGAIN']);
function isNetworkError(error: unknown): boolean {
return (
error instanceof Error &&
'code' in error &&
RETRYABLE_NETWORK_ERRORS.has((error as NodeJS.ErrnoException).code ?? '')
);
}
async function fetchWithRetry<T>(fn: () => Promise<T>, label: string): Promise<T> {
for (let attempt = 0; attempt <= MAX_RETRIES; attempt++) {
try {
return await fn();
} catch (error) {
const isRetryableApi = isClerkAPIResponseError(error) && RETRYABLE_STATUS_CODES.has(error.status);
const isRetryableNetwork = isNetworkError(error);
if ((!isRetryableApi && !isRetryableNetwork) || attempt === MAX_RETRIES) {
throw error;
}
const status = isClerkAPIResponseError(error) ? error.status : (error as NodeJS.ErrnoException).code;
const exponentialDelay = BASE_DELAY_MS * Math.pow(2, attempt) + Math.random() * JITTER_MAX_MS;
const delay =
isClerkAPIResponseError(error) && typeof error.retryAfter === 'number'
? Math.min(Math.max(error.retryAfter * 1000, exponentialDelay), MAX_RETRY_DELAY_MS)
: Math.min(exponentialDelay, MAX_RETRY_DELAY_MS);
console.warn(
`[Retry] ${status} for ${label}, attempt ${attempt + 1}/${MAX_RETRIES}, waiting ${Math.round(delay)}ms`,
);
await new Promise(resolve => setTimeout(resolve, delay));
}
}
throw new Error('Unreachable');
}
export const fetchEnvVars = async (options?: ClerkSetupOptions): Promise<ClerkSetupReturn> => {
const { debug = false, dotenv: loadDotEnv = true, ...rest } = options || {};
const log = (msg: string) => {
if (debug) {
console.log(`Clerk: ${msg}`);
}
};
log('Setting up Clerk...');
if (loadDotEnv) {
dotenv.config({ path: ['.env.local', '.env'] });
}
const publishableKey =
rest.publishableKey ||
process.env.NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY ||
process.env.VITE_CLERK_PUBLISHABLE_KEY ||
process.env.CLERK_PUBLISHABLE_KEY ||
process.env.REACT_APP_CLERK_PUBLISHABLE_KEY ||
process.env.EXPO_PUBLIC_CLERK_PUBLISHABLE_KEY;
const secretKey = rest.secretKey || process.env.CLERK_SECRET_KEY;
let testingToken = process.env.CLERK_TESTING_TOKEN;
if (!publishableKey) {
throw new Error('You need to set the CLERK_PUBLISHABLE_KEY environment variable.');
}
if (!secretKey && !testingToken) {
throw new Error('You need to set the CLERK_SECRET_KEY or the CLERK_TESTING_TOKEN environment variable.');
}
if (secretKey && !testingToken) {
log('Fetching testing token from Clerk Backend API...');
try {
const apiUrl = (rest as any)?.apiUrl || process.env.CLERK_API_URL;
const clerkClient = createClerkClient({ secretKey, apiUrl });
const tokenData = await fetchWithRetry(
() => clerkClient.testingTokens.createTestingToken(),
'testingTokens.createTestingToken',
);
testingToken = tokenData.token;
} catch (err) {
console.error('Failed to fetch testing token from Clerk API.');
throw err;
}
}
return {
CLERK_FAPI: options?.frontendApiUrl || parsePublishableKey(publishableKey)?.frontendApi,
CLERK_TESTING_TOKEN: testingToken,
};
};