-
Notifications
You must be signed in to change notification settings - Fork 2.3k
Expand file tree
/
Copy pathindex.js
More file actions
179 lines (148 loc) · 6.01 KB
/
index.js
File metadata and controls
179 lines (148 loc) · 6.01 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
const addBruShimToContext = require('./shims/bru');
const addBrunoRequestShimToContext = require('./shims/bruno-request');
const addConsoleShimToContext = require('./shims/console');
const addBrunoResponseShimToContext = require('./shims/bruno-response');
const addTestShimToContext = require('./shims/test');
const addLibraryShimsToContext = require('./shims/lib');
const addLocalModuleLoaderShimToContext = require('./shims/local-module');
const { newQuickJSWASMModule, memoizePromiseFactory } = require('quickjs-emscripten');
// execute `npm run sandbox:bundle-libraries` if the below file doesn't exist
const getBundledCode = require('../bundle-browser-rollup');
const addPathShimToContext = require('./shims/lib/path');
const { marshallToVm } = require('./utils');
const addCryptoUtilsShimToContext = require('./shims/lib/crypto-utils');
const { wrapScriptInClosure, SANDBOX } = require('../../utils/sandbox');
let QuickJSModule;
const loader = memoizePromiseFactory(() => newQuickJSWASMModule());
loader().then((mod) => (QuickJSModule = mod));
const toNumber = (value) => {
const num = Number(value);
return Number.isInteger(num) ? parseInt(value, 10) : parseFloat(value);
};
const removeQuotes = (str) => {
if ((str.startsWith('"') && str.endsWith('"')) || (str.startsWith('\'') && str.endsWith('\''))) {
return str.slice(1, -1);
}
return str;
};
const executeQuickJsVm = ({ script: externalScript, context: externalContext, scriptType = 'template-literal' }) => {
if (!externalScript?.length || typeof externalScript !== 'string') {
return externalScript;
}
externalScript = externalScript?.trim();
if (scriptType === 'template-literal') {
if (!isNaN(Number(externalScript))) {
const number = Number(externalScript);
// Check if the number is too high. Too high number might get altered, see #1000
if (number > Number.MAX_SAFE_INTEGER) {
return externalScript;
}
return toNumber(externalScript);
}
if (externalScript === 'true') return true;
if (externalScript === 'false') return false;
if (externalScript === 'null') return null;
if (externalScript === 'undefined') return undefined;
externalScript = removeQuotes(externalScript);
}
const vm = QuickJSModule.newContext();
try {
const { bru, req, res, ...variables } = externalContext;
bru && addBruShimToContext(vm, bru);
req && addBrunoRequestShimToContext(vm, req);
res && addBrunoResponseShimToContext(vm, res);
Object.entries(variables)?.forEach(([key, value]) => {
vm.setProp(vm.global, key, marshallToVm(value, vm));
});
const templateLiteralText = `\`${externalScript}\``;
const jsExpressionText = `${externalScript}`;
let scriptText = scriptType === 'template-literal' ? templateLiteralText : jsExpressionText;
const result = vm.evalCode(scriptText);
if (result.error) {
let e = vm.dump(result.error);
result.error.dispose();
return e;
} else {
let v = vm.dump(result.value);
result.value.dispose();
return v;
}
} catch (error) {
console.error('Error executing the script!', error);
}
};
const executeQuickJsVmAsync = async ({ script: externalScript, context: externalContext, collectionPath, scriptPath }) => {
if (!externalScript?.length || typeof externalScript !== 'string') {
return externalScript;
}
externalScript = externalScript?.trim();
try {
const module = await loader();
const vm = module.newContext();
// add crypto utilities required by the crypto-js library in bundledCode
await addCryptoUtilsShimToContext(vm);
const bundledCode = getBundledCode?.toString() || '';
const moduleLoaderCode = function () {
return `
globalThis.require = (mod) => {
let lib = globalThis.requireObject[mod];
let isModuleAPath = (module) => (module?.startsWith('.') || module?.startsWith?.(bru.cwd()))
if (lib) {
return lib;
}
else if (isModuleAPath(mod)) {
// fetch local module
let localModuleCode = globalThis.__brunoLoadLocalModule(mod);
// compile local module as iife
(function (){
const initModuleExportsCode = "const module = { exports: {} };"
const copyModuleExportsCode = "\\n;globalThis.requireObject[mod] = module.exports;";
const patchedRequire = ${`
"\\n;" +
"let require = (subModule) => isModuleAPath(subModule) ? globalThis.require(path.resolve(bru.cwd(), mod, '..', subModule)) : globalThis.require(subModule)" +
"\\n;"
`}
eval(initModuleExportsCode + patchedRequire + localModuleCode + copyModuleExportsCode);
})();
// resolve module
return globalThis.requireObject[mod];
}
else {
throw new Error("Cannot find module " + mod);
}
}
`;
};
vm.evalCode(
`
(${bundledCode})()
${moduleLoaderCode()}
`
);
const { bru, req, res, test, __brunoTestResults, console: consoleFn } = externalContext;
consoleFn && addConsoleShimToContext(vm, consoleFn);
bru && addBruShimToContext(vm, bru);
req && addBrunoRequestShimToContext(vm, req);
res && addBrunoResponseShimToContext(vm, res);
addLocalModuleLoaderShimToContext(vm, collectionPath);
addPathShimToContext(vm);
await addLibraryShimsToContext(vm);
test && __brunoTestResults && addTestShimToContext(vm, __brunoTestResults);
const script = wrapScriptInClosure(externalScript, SANDBOX.QUICKJS);
const result = vm.evalCode(script, scriptPath);
const promiseHandle = vm.unwrapResult(result);
const resolvedResult = await vm.resolvePromise(promiseHandle);
promiseHandle.dispose();
const resolvedHandle = vm.unwrapResult(resolvedResult);
resolvedHandle.dispose();
// vm.dispose();
return;
} catch (error) {
error.__isQuickJS = true;
throw error;
}
};
module.exports = {
executeQuickJsVm,
executeQuickJsVmAsync
};