directus

Форк
0
57 строк · 1.6 Кб
1
/**
2
 * Call the passed function in a try-catch, and return the output wrapped in a state object.
3
 *
4
 * This is needed as isolated-vm doesn't allow the isolate to catch errors that are thrown in the
5
 * host. Instead, we'll wrap the output in a known shape which allows the isolated sdk context to
6
 * re-throw the error in the correct context.
7
 *
8
 * @see https://github.com/laverdet/isolated-vm/issues/417
9
 */
10
export function wrap(name: string, util: (...args: any[]) => any) {
11
	return async (...args: any[]) => {
12
		try {
13
			return { result: await util(...args), error: false };
14
		} catch (error) {
15
			// isolated-vm expects objects thrown from within the vm to be an instance of `Error`
16
			let result;
17

18
			if (error instanceof Error) {
19
				// Don't expose the stack trace to the vm
20
				delete error.stack;
21

22
				// Serialize the remaining error properties
23
				for (const key of Object.getOwnPropertyNames(error)) {
24
					const value = error[key as keyof typeof error];
25

26
					if (!value || typeof value !== 'object') continue;
27

28
					error[key as keyof typeof error] = JSON.stringify(value, getCircularReplacer());
29
				}
30

31
				result = error;
32
			} else if (error && typeof error !== 'object') {
33
				result = error;
34
			} else {
35
				result = new Error(`Unknown error in "${name}" Sandbox SDK function`);
36
			}
37

38
			return { result, error: true };
39
		}
40
	};
41
}
42

43
function getCircularReplacer() {
44
	const seen = new WeakSet();
45

46
	return (_key: string, value: unknown) => {
47
		if (value !== null && typeof value === 'object') {
48
			if (seen.has(value)) {
49
				return '[Circular]';
50
			}
51

52
			seen.add(value);
53
		}
54

55
		return value;
56
	};
57
}
58

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.