forked from clerk/javascript
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patherror.ts
More file actions
327 lines (263 loc) · 9.47 KB
/
Copy patherror.ts
File metadata and controls
327 lines (263 loc) · 9.47 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
import type { ClerkAPIError, ClerkAPIErrorJSON } from '@clerk/types';
export function isUnauthorizedError(e: any): boolean {
const status = e?.status;
const code = e?.errors?.[0]?.code;
return code === 'authentication_invalid' && status === 401;
}
export function isCaptchaError(e: ClerkAPIResponseError): boolean {
return ['captcha_invalid', 'captcha_not_enabled', 'captcha_missing_token'].includes(e.errors[0].code);
}
export function is4xxError(e: any): boolean {
const status = e?.status;
return !!status && status >= 400 && status < 500;
}
export function isNetworkError(e: any): boolean {
// TODO: revise during error handling epic
const message = (`${e.message}${e.name}` || '').toLowerCase().replace(/\s+/g, '');
return message.includes('networkerror');
}
interface ClerkAPIResponseOptions {
data: ClerkAPIErrorJSON[];
status: number;
clerkTraceId?: string;
}
// For a comprehensive Metamask error list, please see
// https://docs.metamask.io/guide/ethereum-provider.html#errors
export interface MetamaskError extends Error {
code: 4001 | 32602 | 32603;
message: string;
data?: unknown;
}
export function isKnownError(error: any): error is ClerkAPIResponseError | ClerkRuntimeError | MetamaskError {
return isClerkAPIResponseError(error) || isMetamaskError(error) || isClerkRuntimeError(error);
}
export function isClerkAPIResponseError(err: any): err is ClerkAPIResponseError {
return 'clerkError' in err;
}
/**
* Checks if the provided error object is an instance of ClerkRuntimeError.
*
* @param {any} err - The error object to check.
* @returns {boolean} True if the error is a ClerkRuntimeError, false otherwise.
*
* @example
* const error = new ClerkRuntimeError('An error occurred');
* if (isClerkRuntimeError(error)) {
* // Handle ClerkRuntimeError
* console.error('ClerkRuntimeError:', error.message);
* } else {
* // Handle other errors
* console.error('Other error:', error.message);
* }
*/
export function isClerkRuntimeError(err: any): err is ClerkRuntimeError {
return 'clerkRuntimeError' in err;
}
export function isMetamaskError(err: any): err is MetamaskError {
return 'code' in err && [4001, 32602, 32603].includes(err.code) && 'message' in err;
}
export function isUserLockedError(err: any) {
return isClerkAPIResponseError(err) && err.errors?.[0]?.code === 'user_locked';
}
export function isPasswordPwnedError(err: any) {
return isClerkAPIResponseError(err) && err.errors?.[0]?.code === 'form_password_pwned';
}
export function parseErrors(data: ClerkAPIErrorJSON[] = []): ClerkAPIError[] {
return data.length > 0 ? data.map(parseError) : [];
}
export function parseError(error: ClerkAPIErrorJSON): ClerkAPIError {
return {
code: error.code,
message: error.message,
longMessage: error.long_message,
meta: {
paramName: error?.meta?.param_name,
sessionId: error?.meta?.session_id,
emailAddresses: error?.meta?.email_addresses,
identifiers: error?.meta?.identifiers,
zxcvbn: error?.meta?.zxcvbn,
},
};
}
export class ClerkAPIResponseError extends Error {
clerkError: true;
status: number;
message: string;
clerkTraceId?: string;
errors: ClerkAPIError[];
constructor(message: string, { data, status, clerkTraceId }: ClerkAPIResponseOptions) {
super(message);
Object.setPrototypeOf(this, ClerkAPIResponseError.prototype);
this.status = status;
this.message = message;
this.clerkTraceId = clerkTraceId;
this.clerkError = true;
this.errors = parseErrors(data);
}
public toString = () => {
let message = `[${this.name}]\nMessage:${this.message}\nStatus:${this.status}\nSerialized errors: ${this.errors.map(
e => JSON.stringify(e),
)}`;
if (this.clerkTraceId) {
message += `\nClerk Trace ID: ${this.clerkTraceId}`;
}
return message;
};
}
/**
* Custom error class for representing Clerk runtime errors.
*
* @class ClerkRuntimeError
* @example
* throw new ClerkRuntimeError('An error occurred', { code: 'password_invalid' });
*/
export class ClerkRuntimeError extends Error {
clerkRuntimeError: true;
/**
* The error message.
*
* @type {string}
* @memberof ClerkRuntimeError
*/
message: string;
/**
* A unique code identifying the error, can be used for localization.
*
* @type {string}
* @memberof ClerkRuntimeError
*/
code: string;
constructor(message: string, { code }: { code: string }) {
const prefix = '🔒 Clerk:';
const regex = new RegExp(prefix.replace(' ', '\\s*'), 'i');
const sanitized = message.replace(regex, '');
const _message = `${prefix} ${sanitized.trim()}\n\n(code="${code}")\n`;
super(_message);
Object.setPrototypeOf(this, ClerkRuntimeError.prototype);
this.code = code;
this.message = _message;
this.clerkRuntimeError = true;
this.name = 'ClerkRuntimeError';
}
/**
* Returns a string representation of the error.
*
* @returns {string} A formatted string with the error name and message.
* @memberof ClerkRuntimeError
*/
public toString = () => {
return `[${this.name}]\nMessage:${this.message}`;
};
}
export class EmailLinkError extends Error {
code: string;
constructor(code: string) {
super(code);
this.code = code;
Object.setPrototypeOf(this, EmailLinkError.prototype);
}
}
export function isEmailLinkError(err: Error): err is EmailLinkError {
return err instanceof EmailLinkError;
}
export const EmailLinkErrorCode = {
Expired: 'expired',
Failed: 'failed',
ClientMismatch: 'client_mismatch',
};
const DefaultMessages = Object.freeze({
InvalidProxyUrlErrorMessage: `The proxyUrl passed to Clerk is invalid. The expected value for proxyUrl is an absolute URL or a relative path with a leading '/'. (key={{url}})`,
InvalidPublishableKeyErrorMessage: `The publishableKey passed to Clerk is invalid. You can get your Publishable key at https://dashboard.clerk.com/last-active?path=api-keys. (key={{key}})`,
MissingPublishableKeyErrorMessage: `Missing publishableKey. You can get your key at https://dashboard.clerk.com/last-active?path=api-keys.`,
MissingSecretKeyErrorMessage: `Missing secretKey. You can get your key at https://dashboard.clerk.com/last-active?path=api-keys.`,
MissingClerkProvider: `{{source}} can only be used within the <ClerkProvider /> component. Learn more: https://clerk.com/docs/components/clerk-provider`,
});
type MessageKeys = keyof typeof DefaultMessages;
type Messages = Record<MessageKeys, string>;
type CustomMessages = Partial<Messages>;
export type ErrorThrowerOptions = {
packageName: string;
customMessages?: CustomMessages;
};
export interface ErrorThrower {
setPackageName(options: ErrorThrowerOptions): ErrorThrower;
setMessages(options: ErrorThrowerOptions): ErrorThrower;
throwInvalidPublishableKeyError(params: { key?: string }): never;
throwInvalidProxyUrl(params: { url?: string }): never;
throwMissingPublishableKeyError(): never;
throwMissingSecretKeyError(): never;
throwMissingClerkProviderError(params: { source?: string }): never;
throw(message: string): never;
}
export function buildErrorThrower({ packageName, customMessages }: ErrorThrowerOptions): ErrorThrower {
let pkg = packageName;
const messages = {
...DefaultMessages,
...customMessages,
};
function buildMessage(rawMessage: string, replacements?: Record<string, string | number>) {
if (!replacements) {
return `${pkg}: ${rawMessage}`;
}
let msg = rawMessage;
const matches = rawMessage.matchAll(/{{([a-zA-Z0-9-_]+)}}/g);
for (const match of matches) {
const replacement = (replacements[match[1]] || '').toString();
msg = msg.replace(`{{${match[1]}}}`, replacement);
}
return `${pkg}: ${msg}`;
}
return {
setPackageName({ packageName }: ErrorThrowerOptions): ErrorThrower {
if (typeof packageName === 'string') {
pkg = packageName;
}
return this;
},
setMessages({ customMessages }: ErrorThrowerOptions): ErrorThrower {
Object.assign(messages, customMessages || {});
return this;
},
throwInvalidPublishableKeyError(params: { key?: string }): never {
throw new Error(buildMessage(messages.InvalidPublishableKeyErrorMessage, params));
},
throwInvalidProxyUrl(params: { url?: string }): never {
throw new Error(buildMessage(messages.InvalidProxyUrlErrorMessage, params));
},
throwMissingPublishableKeyError(): never {
throw new Error(buildMessage(messages.MissingPublishableKeyErrorMessage));
},
throwMissingSecretKeyError(): never {
throw new Error(buildMessage(messages.MissingSecretKeyErrorMessage));
},
throwMissingClerkProviderError(params: { source?: string }): never {
throw new Error(buildMessage(messages.MissingClerkProvider, params));
},
throw(message: string): never {
throw new Error(buildMessage(message));
},
};
}
type ClerkWebAuthnErrorCode =
// Generic
| 'passkey_not_supported'
| 'passkey_pa_not_supported'
| 'passkey_invalid_rpID_or_domain'
| 'passkey_already_exists'
| 'passkey_operation_aborted'
// Retrieval
| 'passkey_retrieval_cancelled'
| 'passkey_retrieval_failed'
// Registration
| 'passkey_registration_cancelled'
| 'passkey_registration_failed';
export class ClerkWebAuthnError extends ClerkRuntimeError {
/**
* A unique code identifying the error, can be used for localization.
*/
code: ClerkWebAuthnErrorCode;
constructor(message: string, { code }: { code: ClerkWebAuthnErrorCode }) {
super(message, { code });
this.code = code;
}
}