@ms-cloudpack/esm-stub-utilities 0.6.26 → 0.7.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/__fixtures__/loadStubWorker.d.ts +3 -0
- package/lib/__fixtures__/loadStubWorker.d.ts.map +1 -0
- package/lib/__fixtures__/loadStubWorker.js +122 -0
- package/lib/__fixtures__/loadStubWorker.js.map +1 -0
- package/lib/__fixtures__/tryImportStub.d.ts +44 -0
- package/lib/__fixtures__/tryImportStub.d.ts.map +1 -0
- package/lib/__fixtures__/tryImportStub.js +79 -0
- package/lib/__fixtures__/tryImportStub.js.map +1 -0
- package/lib/createESMStub.d.ts +11 -5
- package/lib/createESMStub.d.ts.map +1 -1
- package/lib/createESMStub.js +42 -52
- package/lib/createESMStub.js.map +1 -1
- package/lib/index.d.ts +1 -1
- package/lib/index.d.ts.map +1 -1
- package/lib/index.js +0 -1
- package/lib/index.js.map +1 -1
- package/lib/runInSandbox.d.ts +10 -7
- package/lib/runInSandbox.d.ts.map +1 -1
- package/lib/runInSandbox.js +139 -183
- package/lib/runInSandbox.js.map +1 -1
- package/lib/types/SandboxWorkerResponse.d.ts +21 -0
- package/lib/types/SandboxWorkerResponse.d.ts.map +1 -0
- package/lib/types/SandboxWorkerResponse.js +2 -0
- package/lib/types/SandboxWorkerResponse.js.map +1 -0
- package/lib/types/StubError.d.ts +27 -0
- package/lib/types/StubError.d.ts.map +1 -0
- package/lib/types/StubError.js +2 -0
- package/lib/types/StubError.js.map +1 -0
- package/lib/types/StubExportInfo.d.ts +18 -0
- package/lib/types/StubExportInfo.d.ts.map +1 -0
- package/lib/types/StubExportInfo.js +2 -0
- package/lib/types/StubExportInfo.js.map +1 -0
- package/lib/worker/globals.d.ts +8 -0
- package/lib/worker/globals.d.ts.map +1 -0
- package/lib/worker/globals.js +22 -0
- package/lib/worker/globals.js.map +1 -0
- package/lib/worker/initBrowserEnvironment.d.ts +5 -0
- package/lib/worker/initBrowserEnvironment.d.ts.map +1 -0
- package/lib/worker/initBrowserEnvironment.js +67 -0
- package/lib/worker/initBrowserEnvironment.js.map +1 -0
- package/lib/worker/worker.d.ts +2 -0
- package/lib/worker/worker.d.ts.map +1 -0
- package/lib/worker/worker.js +85 -0
- package/lib/worker/worker.js.map +1 -0
- package/lib/writeESMStub.d.ts +5 -1
- package/lib/writeESMStub.d.ts.map +1 -1
- package/lib/writeESMStub.js +21 -17
- package/lib/writeESMStub.js.map +1 -1
- package/package.json +9 -8
- package/browserEnvironment/index.cjs +0 -81
- package/browserEnvironment/typings.d.ts +0 -5
package/lib/runInSandbox.js
CHANGED
|
@@ -1,119 +1,91 @@
|
|
|
1
1
|
import fs from 'fs';
|
|
2
|
-
import fsPromises from 'fs/promises';
|
|
3
2
|
import path from 'path';
|
|
4
|
-
import { builtinModules, createRequire } from 'module';
|
|
5
3
|
import { fileURLToPath } from 'url';
|
|
6
|
-
import {
|
|
7
|
-
import {
|
|
8
|
-
|
|
9
|
-
const
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
const sandboxRoots = {};
|
|
22
|
-
/** Sandbox root for this file and other cloudpack-related files */
|
|
23
|
-
let cloudpackSandboxRoot = '';
|
|
24
|
-
/** Reset `vms` and `sandboxRoots` for testing */
|
|
25
|
-
export function _clearSandboxCaches() {
|
|
26
|
-
Object.keys(vms).forEach((k) => delete vms[k]);
|
|
27
|
-
Object.keys(sandboxRoots).forEach((k) => delete sandboxRoots[k]);
|
|
4
|
+
import { Worker } from 'worker_threads';
|
|
5
|
+
import { slash } from '@ms-cloudpack/path-string-parsing';
|
|
6
|
+
/** Some known error codes that can occur when running a file in a sandbox. */
|
|
7
|
+
const errorCodes = {
|
|
8
|
+
requireESM: 'ERR_REQUIRE_ESM',
|
|
9
|
+
moduleNotFound: 'MODULE_NOT_FOUND',
|
|
10
|
+
};
|
|
11
|
+
const dirname = path.dirname(fileURLToPath(import.meta.url));
|
|
12
|
+
const workerPath = path.join(dirname, 'worker/worker.js');
|
|
13
|
+
// TODO do we need a pool?
|
|
14
|
+
let worker;
|
|
15
|
+
/** Stop the worker for testing */
|
|
16
|
+
export async function _stopWorker() {
|
|
17
|
+
await worker?.terminate();
|
|
18
|
+
worker = undefined;
|
|
28
19
|
}
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
let dir = path.dirname(filePath);
|
|
42
|
-
if (!sandboxRoots[dir]) {
|
|
43
|
-
// Try to find a git root first
|
|
44
|
-
while (dir !== root && !fs.existsSync(path.join(dir, '.git'))) {
|
|
45
|
-
dir = path.dirname(dir);
|
|
46
|
-
}
|
|
47
|
-
if (dir === root) {
|
|
48
|
-
// If there's a node_modules segment in the path, take the part before that. This covers two cases:
|
|
49
|
-
// - The entry file's sandbox when running cloudpack in a dependency package folder within node_modules
|
|
50
|
-
// - The cloudpack browser environment sandbox when using globally installed cloudpack
|
|
51
|
-
const nodeModulesMatch = filePath.match(/^(.*?)[\\/]node_modules[\\/]/);
|
|
52
|
-
if (nodeModulesMatch) {
|
|
53
|
-
dir = nodeModulesMatch[1];
|
|
54
|
-
}
|
|
55
|
-
else {
|
|
56
|
-
// Try to find a package root, or fall back to parent directory
|
|
57
|
-
dir = findPackageRoot(filePath) || path.dirname(filePath);
|
|
58
|
-
}
|
|
59
|
-
}
|
|
60
|
-
sandboxRoots[dir] = dir;
|
|
20
|
+
function processError(error) {
|
|
21
|
+
const { message, code, name: errorName } = error;
|
|
22
|
+
let newMessage;
|
|
23
|
+
let type;
|
|
24
|
+
if (code === errorCodes.moduleNotFound) {
|
|
25
|
+
// Remove the require stack from MODULE_NOT_FOUND errors (we'll handle it separately).
|
|
26
|
+
// Error: Cannot find module 'foo'
|
|
27
|
+
// Require stack:
|
|
28
|
+
// - [...]/index.js
|
|
29
|
+
// - [.]/worker.js
|
|
30
|
+
newMessage = message.split('\n')[0];
|
|
31
|
+
type = 'module-not-found';
|
|
61
32
|
}
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
const errorName = err.name;
|
|
69
|
-
const newMessage = [`Error ${action}:`, message];
|
|
70
|
-
if (stack.length && err instanceof VMError && err.message.includes('Cannot find module')) {
|
|
71
|
-
newMessage.push('', 'Ensure that this file exists on disk. If it exists, this may be a bug with the choice of `root` ' +
|
|
72
|
-
'(allowed parent directories) settings in @ms-cloudpack/esm-stub-utilities runInSandbox.', `- Root for file being stubbed: ${sandboxRoot}`, `- Root for cloudpack files: ${cloudpackSandboxRoot}`);
|
|
73
|
-
// Find the actual line which caused the error
|
|
74
|
-
const errorLines = stack.filter((line) => line.trim().startsWith('at') && !line.includes('vm2'));
|
|
75
|
-
if (errorLines.length) {
|
|
76
|
-
newMessage.push('', 'Code that may have required this module:', ...errorLines);
|
|
77
|
-
}
|
|
78
|
-
}
|
|
79
|
-
else if (errorName === 'TypeError') {
|
|
80
|
-
newMessage.push('', 'If the code was referencing a built-in global or a property of a Node built-in module, ' +
|
|
81
|
-
'this error may be caused by a missing mock or other issue with the sandbox environment ' +
|
|
82
|
-
'configured in @ms-cloudpack/esm-stub-utilities runInSandbox.');
|
|
33
|
+
else if (code === errorCodes.requireESM) {
|
|
34
|
+
// Remove the instruction to change to a dynamic import, since it's less likely to be applicable here.
|
|
35
|
+
// Error [ERR_REQUIRE_ESM]: require() of ES Module [...]/esm.mjs not supported.
|
|
36
|
+
// Instead change the require of [...]/esm.mjs to a dynamic import() which is available in all CommonJS modules.
|
|
37
|
+
newMessage = message.split('\n')[0];
|
|
38
|
+
type = 'require-esm';
|
|
83
39
|
}
|
|
84
|
-
else if (errorName === 'SyntaxError'
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
newMessage.push('', "It appears you're trying to load an ES module, which is not currently supported in the sandbox. " +
|
|
88
|
-
'If this module is loaded at startup within a CommonJS file, please file an issue with cloudpack. ');
|
|
40
|
+
else if (errorName === 'SyntaxError') {
|
|
41
|
+
newMessage = message;
|
|
42
|
+
type = 'invalid-syntax';
|
|
89
43
|
}
|
|
90
|
-
|
|
91
|
-
newMessage
|
|
92
|
-
|
|
93
|
-
throw new Error(newMessage.join('\n'));
|
|
94
|
-
}
|
|
95
|
-
function logMissingModule(params) {
|
|
96
|
-
const { moduleName, parentDir, error, realParentDir } = params;
|
|
97
|
-
// First determine if moduleName is from an optional peer dependency
|
|
98
|
-
let isOptionalPeerDep = false;
|
|
99
|
-
const depName = moduleName.match(/^(@[\w.-]+\/)?[\w.-]+/)?.[0];
|
|
100
|
-
const parentPkgRoot = depName ? findPackageRoot(parentDir) : undefined;
|
|
101
|
-
if (depName && parentPkgRoot) {
|
|
102
|
-
// eslint-disable-next-line @ms-cloudpack/internal/no-sync-filesystem
|
|
103
|
-
const packageJson = readJsonSync(path.join(parentPkgRoot, 'package.json'));
|
|
104
|
-
isOptionalPeerDep = !!(packageJson?.peerDependencies?.[depName] && packageJson.peerDependenciesMeta?.[depName]?.optional);
|
|
44
|
+
else {
|
|
45
|
+
newMessage = message;
|
|
46
|
+
type = 'other-error';
|
|
105
47
|
}
|
|
106
|
-
|
|
107
|
-
if (
|
|
108
|
-
|
|
109
|
-
|
|
48
|
+
let stack;
|
|
49
|
+
if (error.stack) {
|
|
50
|
+
// Get stack frame lines from the original error stack
|
|
51
|
+
stack = error.stack
|
|
52
|
+
.split('\n')
|
|
53
|
+
.filter((line) => /^\s+at /.test(line))
|
|
54
|
+
.map((line) => line.trim());
|
|
55
|
+
// Remove the worker frame and anything after it
|
|
56
|
+
const workerIndex = stack.findIndex((line) => slash(line).includes('esm-stub-utilities') && line.includes('worker.js'));
|
|
57
|
+
if (workerIndex !== -1) {
|
|
58
|
+
stack = stack.slice(0, workerIndex);
|
|
59
|
+
}
|
|
60
|
+
if (!stack.length) {
|
|
61
|
+
stack = undefined;
|
|
62
|
+
if (code === errorCodes.requireESM) {
|
|
63
|
+
// This error code + no stack outside the worker strongly implies that the file itself
|
|
64
|
+
// If we ended up with no stack besides the worker, this strongly implies that the file
|
|
65
|
+
// itself is an ESM file, not a CommonJS file.
|
|
66
|
+
newMessage =
|
|
67
|
+
"It appears you're trying to create a stub of an ES module, which is not supported. " +
|
|
68
|
+
'You may need to add a cloudpack override to bundle this package with ori.';
|
|
69
|
+
type = 'entry-is-esm';
|
|
70
|
+
}
|
|
71
|
+
}
|
|
110
72
|
}
|
|
73
|
+
// Remove node internals from the stack
|
|
74
|
+
const partialStack = stack?.filter((line) => !line.includes('(node:'));
|
|
75
|
+
return {
|
|
76
|
+
message: newMessage,
|
|
77
|
+
type,
|
|
78
|
+
partialStack: partialStack?.length ? partialStack : undefined,
|
|
79
|
+
};
|
|
111
80
|
}
|
|
112
81
|
/**
|
|
113
82
|
* Run a CommonJS file within a sandboxed environment.
|
|
114
83
|
* @param entryPath - Path to a CommonJS file to run in a sandbox (does not work with ESM files)
|
|
115
|
-
* @returns
|
|
84
|
+
* @returns Info about the file's exports, or error info if there was an issue.
|
|
85
|
+
* Should only throw an error on bad input or other cases that likely indicate either a bug
|
|
86
|
+
* or bad configuration (as opposed to a problem with the file being stubbed).
|
|
116
87
|
*/
|
|
88
|
+
// TODO add mechanism to force one-off worker
|
|
117
89
|
export async function runInSandbox(entryPath) {
|
|
118
90
|
if (!path.isAbsolute(entryPath)) {
|
|
119
91
|
throw new Error('Entry path must be absolute. Received: ' + entryPath);
|
|
@@ -121,92 +93,76 @@ export async function runInSandbox(entryPath) {
|
|
|
121
93
|
if (!fs.existsSync(entryPath)) {
|
|
122
94
|
throw new Error('Entry path does not exist: ' + entryPath);
|
|
123
95
|
}
|
|
124
|
-
|
|
125
|
-
// or under its directory if it's not in a package.
|
|
126
|
-
const sandboxRoot = findSandboxRoot(entryPath);
|
|
127
|
-
if (!vms[sandboxRoot]) {
|
|
128
|
-
if (!cloudpackSandboxRoot) {
|
|
129
|
-
cloudpackSandboxRoot = findSandboxRoot(filename);
|
|
130
|
-
}
|
|
131
|
-
console.debug('esm-stub-utilities: Creating sandbox for ' + sandboxRoot);
|
|
96
|
+
if (!worker) {
|
|
132
97
|
try {
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
console
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
root: [cloudpackSandboxRoot, sandboxRoot],
|
|
143
|
-
// load, compile, and require modules in the sandbox (instead of requiring in the host)
|
|
144
|
-
context: 'sandbox',
|
|
145
|
-
// allowed built-in modules
|
|
146
|
-
builtin: allowedBuiltins,
|
|
147
|
-
// allow loading "external" modules under the given roots
|
|
148
|
-
external: true,
|
|
149
|
-
// simulate the browser at startup (can throw errors)
|
|
150
|
-
import: [browserEnvSetup],
|
|
151
|
-
// fallback resolver if vm2's algorithm fails
|
|
152
|
-
resolve: (moduleName, parentDir) => {
|
|
153
|
-
// eslint-disable-next-line @ms-cloudpack/internal/no-sync-filesystem
|
|
154
|
-
const realParentDir = fs.realpathSync(parentDir);
|
|
155
|
-
if (realParentDir === parentDir) {
|
|
156
|
-
// Log a more informative error if this isn't a realpath issue (explained below).
|
|
157
|
-
// This is clearer than the error message vm2 provides if the file isn't found.
|
|
158
|
-
logMissingModule({ moduleName, parentDir, error: 'module not found' });
|
|
159
|
-
return undefined;
|
|
160
|
-
}
|
|
161
|
-
try {
|
|
162
|
-
// vm2 doesn't get the realpath of the parent directory before resolving,
|
|
163
|
-
// which causes issues with certain install layouts (pnpm, yarn strict).
|
|
164
|
-
// Try again using actual require.resolve with the realpath.
|
|
165
|
-
return require.resolve(moduleName, { paths: [realParentDir] });
|
|
166
|
-
}
|
|
167
|
-
catch (err) {
|
|
168
|
-
logMissingModule({ moduleName, parentDir, error: String(err), realParentDir });
|
|
169
|
-
return undefined;
|
|
170
|
-
}
|
|
171
|
-
},
|
|
172
|
-
// mock these modules so they can be successfully required
|
|
173
|
-
mock: {
|
|
174
|
-
...mockBuiltins,
|
|
175
|
-
// some modules reference these built-ins during their setup
|
|
176
|
-
perf_hooks: {
|
|
177
|
-
performance: { now: () => Date.now() },
|
|
178
|
-
},
|
|
179
|
-
tty: {
|
|
180
|
-
isatty: () => false,
|
|
181
|
-
},
|
|
182
|
-
vm: {
|
|
183
|
-
isContext: () => false,
|
|
184
|
-
},
|
|
185
|
-
},
|
|
186
|
-
},
|
|
187
|
-
env: {
|
|
188
|
-
// prevent debug from accessing process.stderr
|
|
189
|
-
DEBUG_COLORS: 0,
|
|
190
|
-
},
|
|
98
|
+
worker = new Worker(workerPath, { stdout: true, stderr: true, execArgv: [] });
|
|
99
|
+
worker.stdout?.on('data', (data) => {
|
|
100
|
+
console.debug(`[sandbox stdout] ${data}`);
|
|
101
|
+
});
|
|
102
|
+
worker.stderr?.on('data', (data) => {
|
|
103
|
+
console.debug(`[sandbox stderr] ${data}`);
|
|
104
|
+
});
|
|
105
|
+
worker.on('exit', () => {
|
|
106
|
+
worker = undefined;
|
|
191
107
|
});
|
|
108
|
+
// don't hold the process open if only the worker is left
|
|
109
|
+
worker.unref();
|
|
192
110
|
}
|
|
193
111
|
catch (err) {
|
|
194
|
-
|
|
112
|
+
throw new Error(`Error initializing sandbox worker: ${err?.stack || err}`);
|
|
195
113
|
}
|
|
196
114
|
}
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
115
|
+
return new Promise((resolve, reject) => {
|
|
116
|
+
// just for type checking
|
|
117
|
+
if (!worker)
|
|
118
|
+
return;
|
|
119
|
+
worker.on('message', onMessage);
|
|
120
|
+
worker.on('messageerror', onMessageError);
|
|
121
|
+
worker.on('error', onError);
|
|
122
|
+
worker.on('exit', onExit);
|
|
123
|
+
// Send a message requesting the file to be run.
|
|
124
|
+
worker.postMessage(entryPath);
|
|
125
|
+
/** Normally, both success and error results should be sent back as messages. */
|
|
126
|
+
function onMessage(message) {
|
|
127
|
+
if (message.entryPath !== entryPath) {
|
|
128
|
+
return; // message about a different file
|
|
129
|
+
}
|
|
130
|
+
handlersOff();
|
|
131
|
+
if (message.exportInfo) {
|
|
132
|
+
resolve(message.exportInfo);
|
|
133
|
+
}
|
|
134
|
+
else if (message.error) {
|
|
135
|
+
resolve({ error: processError(message.error) });
|
|
136
|
+
}
|
|
137
|
+
else {
|
|
138
|
+
// this indicates a bug in cloudpack
|
|
139
|
+
reject(new Error(`Unexpected sandbox worker message while running ${entryPath}: ${JSON.stringify(message)}`));
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
/** 'messageerror' event: deserializing a message failed. */
|
|
143
|
+
function onMessageError(err) {
|
|
144
|
+
handlersOff();
|
|
145
|
+
reject(new Error(`Error with sandbox worker message serialization while running ${entryPath}: ${err.stack || err}\n`));
|
|
146
|
+
}
|
|
147
|
+
/** 'error' event: unhandled exception in the worker, which shouldn't happen. */
|
|
148
|
+
function onError(err) {
|
|
149
|
+
handlersOff();
|
|
150
|
+
reject(new Error(`Uncaught error in sandbox worker while running ${entryPath}: ${err.stack || err}\n`));
|
|
151
|
+
}
|
|
152
|
+
/**
|
|
153
|
+
* Make sure the promise rejects if the worker exits unexpectedly. (This handler is unlikely
|
|
154
|
+
* to be used because the worker should throw an error if a file calls process.exit().)
|
|
155
|
+
*/
|
|
156
|
+
function onExit() {
|
|
157
|
+
reject(new Error(`Sandbox worker exited unexpectedly while running ${entryPath}`));
|
|
158
|
+
}
|
|
159
|
+
/** Remove all event handlers to avoid interference with future sandbox runs. */
|
|
160
|
+
function handlersOff() {
|
|
161
|
+
worker?.off('message', onMessage);
|
|
162
|
+
worker?.off('messageerror', onMessageError);
|
|
163
|
+
worker?.off('error', onError);
|
|
164
|
+
worker?.off('exit', onExit);
|
|
165
|
+
}
|
|
166
|
+
});
|
|
211
167
|
}
|
|
212
168
|
//# sourceMappingURL=runInSandbox.js.map
|
package/lib/runInSandbox.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"runInSandbox.js","sourceRoot":"","sources":["../src/runInSandbox.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,IAAI,CAAC;AACpB,OAAO,UAAU,MAAM,aAAa,CAAC;AACrC,OAAO,IAAI,MAAM,MAAM,CAAC;AACxB,OAAO,EAAE,cAAc,EAAE,aAAa,EAAE,MAAM,QAAQ,CAAC;AACvD,OAAO,EAAE,aAAa,EAAE,MAAM,KAAK,CAAC;AACpC,OAAO,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,KAAK,CAAC;AAEtC,OAAO,EAAE,eAAe,EAAE,MAAM,8BAA8B,CAAC;AAC/D,OAAO,EAAE,YAAY,EAAE,MAAM,8BAA8B,CAAC;AAE5D,MAAM,OAAO,GAAG,aAAa,CAAC,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;AAC/C,MAAM,QAAQ,GAAG,aAAa,CAAC,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;AAChD,MAAM,OAAO,GAAG,IAAI,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAC;AACvC,MAAM,eAAe,GAAG,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,EAAE,8BAA8B,CAAC,CAAC;AAEzF,uDAAuD;AACvD,wFAAwF;AACxF,MAAM,eAAe,GAAG,CAAC,QAAQ,EAAE,QAAQ,EAAE,MAAM,EAAE,QAAQ,EAAE,KAAK,EAAE,MAAM,CAAC,CAAC;AAC9E,gGAAgG;AAChG,MAAM,YAAY,GAAG,MAAM,CAAC,WAAW,CAAC,cAAc,CAAC,MAAM,CAAC,CAAC,CAAC,EA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BACD,EAAE,EAAE;4BACF,SAAS,EAAE,GAAG,EAAE,CAAC,KAAK;yBACvB;qBACF;iBACF;gBACD,GAAG,EAAE;oBACH,8CAA8C;oBAC9C,YAAY,EAAE,CAAC;iBAChB;aACF,CAAC,CAAC;SACJ;QAAC,OAAO,GAAG,EAAE;YACZ,WAAW,CAAC,4BAA4B,WAAW,uBAAuB,SAAS,GAAG,EAAE,GAAG,EAAE,WAAW,CAAC,CAAC;SAC3G;KACF;IAED,MAAM,OAAO,GAAG,CAAC,GAAY,EAAE,EAAE;QAC/B,WAAW,CAAC,WAAW,SAAS,8BAA8B,EAAE,GAAG,EAAE,WAAW,CAAC,CAAC;IACpF,CAAC,CAAC;IACF,OAAO,CAAC,EAAE,CAAC,mBAAmB,EAAE,OAAO,CAAC,CAAC;IAEzC,IAAI;QACF,MAAM,OAAO,GAAG,MAAM,UAAU,CAAC,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC,CAAC;QAC7D,OAAO,GAAG,CAAC,WAAW,CAAC,CAAC,GAAG,CAAC,OAAO,EAAE,EAAE,QAAQ,EAAE,SAAS,EAAE,CAAY,CAAC;KAC1E;IAAC,OAAO,GAAG,EAAE;QACZ,OAAO,CAAC,GAAG,CAAC,CAAC;KACd;YAAS;QACR,OAAO,CAAC,GAAG,CAAC,mBAAmB,EAAE,OAAO,CAAC,CAAC;KAC3C;AACH,CAAC","sourcesContent":["import fs from 'fs';\nimport fsPromises from 'fs/promises';\nimport path from 'path';\nimport { builtinModules, createRequire } from 'module';\nimport { fileURLToPath } from 'url';\nimport { NodeVM, VMError } from 'vm2';\nimport type { PackageJson } from '@ms-cloudpack/bundler-types';\nimport { findPackageRoot } from '@ms-cloudpack/path-utilities';\nimport { readJsonSync } from '@ms-cloudpack/json-utilities';\n\nconst require = createRequire(import.meta.url);\nconst filename = fileURLToPath(import.meta.url);\nconst dirname = path.dirname(filename);\nconst browserEnvSetup = path.join(path.dirname(dirname), 'browserEnvironment/index.cjs');\n\n/** Allow the sandbox to load these built-in modules */\n// ('events' and 'stream' export classes which other things extend and can't be proxied)\nconst allowedBuiltins = ['buffer', 'events', 'path', 'stream', 'url', 'util'];\n/** Empty mocks of all built-in modules that aren't allowed (to ensure that requires succeed) */\nconst mockBuiltins = Object.fromEntries(builtinModules.filter((m) => !allowedBuiltins.includes(m)).map((m) => [m, {}]));\n\n/** Mapping from sandbox root to VM */\nconst vms: Record<string, NodeVM> = {};\n\n/** Mapping from directory to sandbox root */\nconst sandboxRoots: Record<string, string> = {};\n/** Sandbox root for this file and other cloudpack-related files */\nlet cloudpackSandboxRoot = '';\n\n/** Reset `vms` and `sandboxRoots` for testing */\nexport function _clearSandboxCaches() {\n Object.keys(vms).forEach((k) => delete vms[k]);\n Object.keys(sandboxRoots).forEach((k) => delete sandboxRoots[k]);\n}\n\n/** Get `vms` state for testing */\nexport function _getSandboxVms() {\n return vms;\n}\n\n/**\n * Try to figure out a root directory where the sandbox should be allowed to require files from.\n * This prefers the git root if found, falling back to package root or parent directory.\n *\n * (This is very likely overly permissive and might be good to restrict in the future.)\n */\nfunction findSandboxRoot(filePath: string) {\n const root = path.parse(filePath).root;\n let dir: string | undefined = path.dirname(filePath);\n\n if (!sandboxRoots[dir]) {\n // Try to find a git root first\n while (dir !== root && !fs.existsSync(path.join(dir, '.git'))) {\n dir = path.dirname(dir);\n }\n\n if (dir === root) {\n // If there's a node_modules segment in the path, take the part before that. This covers two cases:\n // - The entry file's sandbox when running cloudpack in a dependency package folder within node_modules\n // - The cloudpack browser environment sandbox when using globally installed cloudpack\n const nodeModulesMatch = filePath.match(/^(.*?)[\\\\/]node_modules[\\\\/]/);\n if (nodeModulesMatch) {\n dir = nodeModulesMatch[1];\n } else {\n // Try to find a package root, or fall back to parent directory\n dir = findPackageRoot(filePath) || path.dirname(filePath);\n }\n }\n\n sandboxRoots[dir] = dir;\n }\n\n return sandboxRoots[dir];\n}\n\nfunction handleError(action: string, err: unknown, sandboxRoot: string) {\n const message = (err as Error).message || String(err);\n const stack = (err as Error).stack?.split(/\\r?\\n/g) || [];\n // instanceof checks don't work with errors from code run within the sandbox, but name is preserved\n const errorName = (err as Error).name;\n\n const newMessage = [`Error ${action}:`, message];\n\n if (stack.length && err instanceof VMError && err.message.includes('Cannot find module')) {\n newMessage.push(\n '',\n 'Ensure that this file exists on disk. If it exists, this may be a bug with the choice of `root` ' +\n '(allowed parent directories) settings in @ms-cloudpack/esm-stub-utilities runInSandbox.',\n `- Root for file being stubbed: ${sandboxRoot}`,\n `- Root for cloudpack files: ${cloudpackSandboxRoot}`,\n );\n\n // Find the actual line which caused the error\n const errorLines = stack.filter((line) => line.trim().startsWith('at') && !line.includes('vm2'));\n if (errorLines.length) {\n newMessage.push('', 'Code that may have required this module:', ...errorLines);\n }\n } else if (errorName === 'TypeError') {\n newMessage.push(\n '',\n 'If the code was referencing a built-in global or a property of a Node built-in module, ' +\n 'this error may be caused by a missing mock or other issue with the sandbox environment ' +\n 'configured in @ms-cloudpack/esm-stub-utilities runInSandbox.',\n );\n } else if (\n errorName === 'SyntaxError' &&\n (/Unexpected token '(import|export)'/.test(message) ||\n message.includes(`'import' and 'export' may appear only with`))\n ) {\n newMessage.push(\n '',\n \"It appears you're trying to load an ES module, which is not currently supported in the sandbox. \" +\n 'If this module is loaded at startup within a CommonJS file, please file an issue with cloudpack. ',\n );\n }\n\n if (stack.length) {\n newMessage.push('', 'Original stack:', ...stack.slice(1));\n }\n\n throw new Error(newMessage.join('\\n'));\n}\n\nfunction logMissingModule(params: { moduleName: string; parentDir: string; error: string; realParentDir?: string }) {\n const { moduleName, parentDir, error, realParentDir } = params;\n\n // First determine if moduleName is from an optional peer dependency\n let isOptionalPeerDep = false;\n const depName = moduleName.match(/^(@[\\w.-]+\\/)?[\\w.-]+/)?.[0];\n const parentPkgRoot = depName ? findPackageRoot(parentDir) : undefined;\n if (depName && parentPkgRoot) {\n // eslint-disable-next-line @ms-cloudpack/internal/no-sync-filesystem\n const packageJson = readJsonSync<PackageJson>(path.join(parentPkgRoot, 'package.json'));\n isOptionalPeerDep = !!(\n packageJson?.peerDependencies?.[depName] && packageJson.peerDependenciesMeta?.[depName]?.optional\n );\n }\n\n // If the module is from an optional dep, it's not useful to warn\n if (!isOptionalPeerDep) {\n const realPathMsg = realParentDir ? ` (real path: ${realParentDir})` : '';\n console.warn(`runInSandbox failed to resolve \"${moduleName}\" from \"${parentDir}\"${realPathMsg}: ${error}`);\n }\n}\n\n/**\n * Run a CommonJS file within a sandboxed environment.\n * @param entryPath - Path to a CommonJS file to run in a sandbox (does not work with ESM files)\n * @returns The module's exports\n */\nexport async function runInSandbox(entryPath: string) {\n if (!path.isAbsolute(entryPath)) {\n throw new Error('Entry path must be absolute. Received: ' + entryPath);\n }\n\n if (!fs.existsSync(entryPath)) {\n throw new Error('Entry path does not exist: ' + entryPath);\n }\n\n // Allow code in the sandbox to require files under the requested file's package root,\n // or under its directory if it's not in a package.\n const sandboxRoot = findSandboxRoot(entryPath);\n\n if (!vms[sandboxRoot]) {\n if (!cloudpackSandboxRoot) {\n cloudpackSandboxRoot = findSandboxRoot(filename);\n }\n\n console.debug('esm-stub-utilities: Creating sandbox for ' + sandboxRoot);\n\n try {\n vms[sandboxRoot] = new NodeVM({\n // disable console logging instead of passing through to the host console\n console: 'off',\n // look for these import extensions (mjs is not included because this doesn't support loading ESM)\n sourceExtensions: ['js', 'cjs'],\n // use a commonjs module wrapper\n wrapper: 'commonjs',\n require: {\n // allow local and dependency modules to be required under here\n root: [cloudpackSandboxRoot, sandboxRoot],\n // load, compile, and require modules in the sandbox (instead of requiring in the host)\n context: 'sandbox',\n // allowed built-in modules\n builtin: allowedBuiltins,\n // allow loading \"external\" modules under the given roots\n external: true,\n // simulate the browser at startup (can throw errors)\n import: [browserEnvSetup],\n // fallback resolver if vm2's algorithm fails\n resolve: (moduleName: string, parentDir: string) => {\n // eslint-disable-next-line @ms-cloudpack/internal/no-sync-filesystem\n const realParentDir = fs.realpathSync(parentDir);\n if (realParentDir === parentDir) {\n // Log a more informative error if this isn't a realpath issue (explained below).\n // This is clearer than the error message vm2 provides if the file isn't found.\n logMissingModule({ moduleName, parentDir, error: 'module not found' });\n return undefined;\n }\n\n try {\n // vm2 doesn't get the realpath of the parent directory before resolving,\n // which causes issues with certain install layouts (pnpm, yarn strict).\n // Try again using actual require.resolve with the realpath.\n return require.resolve(moduleName, { paths: [realParentDir] });\n } catch (err) {\n logMissingModule({ moduleName, parentDir, error: String(err), realParentDir });\n return undefined;\n }\n },\n // mock these modules so they can be successfully required\n mock: {\n ...mockBuiltins,\n // some modules reference these built-ins during their setup\n perf_hooks: {\n performance: { now: () => Date.now() },\n },\n tty: {\n isatty: () => false,\n },\n vm: {\n isContext: () => false,\n },\n },\n },\n env: {\n // prevent debug from accessing process.stderr\n DEBUG_COLORS: 0,\n },\n });\n } catch (err) {\n handleError(`initializing sandbox for ${sandboxRoot} (to create stub of ${entryPath})`, err, sandboxRoot);\n }\n }\n\n const onError = (err: unknown) => {\n handleError(`running ${entryPath} in sandbox (to create stub)`, err, sandboxRoot);\n };\n process.on('uncaughtException', onError);\n\n try {\n const cjsFile = await fsPromises.readFile(entryPath, 'utf8');\n return vms[sandboxRoot].run(cjsFile, { filename: entryPath }) as unknown;\n } catch (err) {\n onError(err);\n } finally {\n process.off('uncaughtException', onError);\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"runInSandbox.js","sourceRoot":"","sources":["../src/runInSandbox.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,IAAI,CAAC;AACpB,OAAO,IAAI,MAAM,MAAM,CAAC;AACxB,OAAO,EAAE,aAAa,EAAE,MAAM,KAAK,CAAC;AACpC,OAAO,EAAE,MAAM,EAAE,MAAM,gBAAgB,CAAC;AAGxC,OAAO,EAAE,KAAK,EAAE,MAAM,mCAAmC,CAAC;AAG1D,8EAA8E;AAC9E,MAAM,UAAU,GAAG;IACjB,UAAU,EAAE,iBAAiB;IAC7B,cAAc,EAAE,kBAAkB;CACnC,CAAC;AAEF,M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AC,CAAC,CAAC;QACrF,CAAC;QAED,gFAAgF;QAChF,SAAS,WAAW;YAClB,MAAM,EAAE,GAAG,CAAC,SAAS,EAAE,SAAS,CAAC,CAAC;YAClC,MAAM,EAAE,GAAG,CAAC,cAAc,EAAE,cAAc,CAAC,CAAC;YAC5C,MAAM,EAAE,GAAG,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;YAC9B,MAAM,EAAE,GAAG,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;QAC9B,CAAC;IACH,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import fs from 'fs';\nimport path from 'path';\nimport { fileURLToPath } from 'url';\nimport { Worker } from 'worker_threads';\nimport type { SandboxWorkerResponse } from './types/SandboxWorkerResponse.js';\nimport type { StubExportInfo } from './types/StubExportInfo.js';\nimport { slash } from '@ms-cloudpack/path-string-parsing';\nimport type { StubError } from './types/StubError.js';\n\n/** Some known error codes that can occur when running a file in a sandbox. */\nconst errorCodes = {\n requireESM: 'ERR_REQUIRE_ESM',\n moduleNotFound: 'MODULE_NOT_FOUND',\n};\n\nconst dirname = path.dirname(fileURLToPath(import.meta.url));\nconst workerPath = path.join(dirname, 'worker/worker.js');\n\n// TODO do we need a pool?\nlet worker: Worker | undefined;\n\n/** Stop the worker for testing */\nexport async function _stopWorker() {\n await worker?.terminate();\n worker = undefined;\n}\n\nfunction processError(error: NonNullable<SandboxWorkerResponse['error']>): StubError {\n const { message, code, name: errorName } = error;\n\n let newMessage: string;\n let type: StubError['type'];\n\n if (code === errorCodes.moduleNotFound) {\n // Remove the require stack from MODULE_NOT_FOUND errors (we'll handle it separately).\n // Error: Cannot find module 'foo'\n // Require stack:\n // - [...]/index.js\n // - [.]/worker.js\n newMessage = message.split('\\n')[0];\n type = 'module-not-found';\n } else if (code === errorCodes.requireESM) {\n // Remove the instruction to change to a dynamic import, since it's less likely to be applicable here.\n // Error [ERR_REQUIRE_ESM]: require() of ES Module [...]/esm.mjs not supported.\n // Instead change the require of [...]/esm.mjs to a dynamic import() which is available in all CommonJS modules.\n newMessage = message.split('\\n')[0];\n type = 'require-esm';\n } else if (errorName === 'SyntaxError') {\n newMessage = message;\n type = 'invalid-syntax';\n } else {\n newMessage = message;\n type = 'other-error';\n }\n\n let stack: string[] | undefined;\n if (error.stack) {\n // Get stack frame lines from the original error stack\n stack = error.stack\n .split('\\n')\n .filter((line) => /^\\s+at /.test(line))\n .map((line) => line.trim());\n\n // Remove the worker frame and anything after it\n const workerIndex = stack.findIndex(\n (line) => slash(line).includes('esm-stub-utilities') && line.includes('worker.js'),\n );\n if (workerIndex !== -1) {\n stack = stack.slice(0, workerIndex);\n }\n\n if (!stack.length) {\n stack = undefined;\n if (code === errorCodes.requireESM) {\n // This error code + no stack outside the worker strongly implies that the file itself\n // If we ended up with no stack besides the worker, this strongly implies that the file\n // itself is an ESM file, not a CommonJS file.\n newMessage =\n \"It appears you're trying to create a stub of an ES module, which is not supported. \" +\n 'You may need to add a cloudpack override to bundle this package with ori.';\n type = 'entry-is-esm';\n }\n }\n }\n\n // Remove node internals from the stack\n const partialStack = stack?.filter((line) => !line.includes('(node:'));\n\n return {\n message: newMessage,\n type,\n partialStack: partialStack?.length ? partialStack : undefined,\n };\n}\n\n/**\n * Run a CommonJS file within a sandboxed environment.\n * @param entryPath - Path to a CommonJS file to run in a sandbox (does not work with ESM files)\n * @returns Info about the file's exports, or error info if there was an issue.\n * Should only throw an error on bad input or other cases that likely indicate either a bug\n * or bad configuration (as opposed to a problem with the file being stubbed).\n */\n// TODO add mechanism to force one-off worker\nexport async function runInSandbox(entryPath: string): Promise<StubExportInfo | { error: StubError }> {\n if (!path.isAbsolute(entryPath)) {\n throw new Error('Entry path must be absolute. Received: ' + entryPath);\n }\n if (!fs.existsSync(entryPath)) {\n throw new Error('Entry path does not exist: ' + entryPath);\n }\n\n if (!worker) {\n try {\n worker = new Worker(workerPath, { stdout: true, stderr: true, execArgv: [] });\n worker.stdout?.on('data', (data) => {\n console.debug(`[sandbox stdout] ${data}`);\n });\n worker.stderr?.on('data', (data) => {\n console.debug(`[sandbox stderr] ${data}`);\n });\n worker.on('exit', () => {\n worker = undefined;\n });\n // don't hold the process open if only the worker is left\n worker.unref();\n } catch (err) {\n throw new Error(`Error initializing sandbox worker: ${(err as Error)?.stack || err}`);\n }\n }\n\n return new Promise((resolve, reject) => {\n // just for type checking\n if (!worker) return;\n\n worker.on('message', onMessage);\n worker.on('messageerror', onMessageError);\n worker.on('error', onError);\n worker.on('exit', onExit);\n\n // Send a message requesting the file to be run.\n worker.postMessage(entryPath);\n\n /** Normally, both success and error results should be sent back as messages. */\n function onMessage(message: SandboxWorkerResponse) {\n if (message.entryPath !== entryPath) {\n return; // message about a different file\n }\n\n handlersOff();\n if (message.exportInfo) {\n resolve(message.exportInfo);\n } else if (message.error) {\n resolve({ error: processError(message.error) });\n } else {\n // this indicates a bug in cloudpack\n reject(new Error(`Unexpected sandbox worker message while running ${entryPath}: ${JSON.stringify(message)}`));\n }\n }\n\n /** 'messageerror' event: deserializing a message failed. */\n function onMessageError(err: Error) {\n handlersOff();\n reject(\n new Error(`Error with sandbox worker message serialization while running ${entryPath}: ${err.stack || err}\\n`),\n );\n }\n\n /** 'error' event: unhandled exception in the worker, which shouldn't happen. */\n function onError(err: Error) {\n handlersOff();\n reject(new Error(`Uncaught error in sandbox worker while running ${entryPath}: ${err.stack || err}\\n`));\n }\n\n /**\n * Make sure the promise rejects if the worker exits unexpectedly. (This handler is unlikely\n * to be used because the worker should throw an error if a file calls process.exit().)\n */\n function onExit() {\n reject(new Error(`Sandbox worker exited unexpectedly while running ${entryPath}`));\n }\n\n /** Remove all event handlers to avoid interference with future sandbox runs. */\n function handlersOff() {\n worker?.off('message', onMessage);\n worker?.off('messageerror', onMessageError);\n worker?.off('error', onError);\n worker?.off('exit', onExit);\n }\n });\n}\n"]}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import type { StubExportInfo } from './StubExportInfo.js';
|
|
2
|
+
/**
|
|
3
|
+
* Success or error IPC message after attempting to run a CJS file in a worker.
|
|
4
|
+
*/
|
|
5
|
+
export interface SandboxWorkerResponse {
|
|
6
|
+
/** Path to the file that was run */
|
|
7
|
+
entryPath: string;
|
|
8
|
+
/** If successful: info about the file's exports */
|
|
9
|
+
exportInfo?: StubExportInfo;
|
|
10
|
+
/** If not successful: info about the error that occurred */
|
|
11
|
+
error?: {
|
|
12
|
+
/** Message describing the error */
|
|
13
|
+
message: string;
|
|
14
|
+
/** If there was an exception: error object name */
|
|
15
|
+
name?: string;
|
|
16
|
+
/** If there was an exception: error code (not always set) */
|
|
17
|
+
code?: string;
|
|
18
|
+
stack?: string;
|
|
19
|
+
};
|
|
20
|
+
}
|
|
21
|
+
//# sourceMappingURL=SandboxWorkerResponse.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"SandboxWorkerResponse.d.ts","sourceRoot":"","sources":["../../src/types/SandboxWorkerResponse.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC;AAE1D;;GAEG;AACH,MAAM,WAAW,qBAAqB;IACpC,oCAAoC;IACpC,SAAS,EAAE,MAAM,CAAC;IAElB,mDAAmD;IACnD,UAAU,CAAC,EAAE,cAAc,CAAC;IAE5B,4DAA4D;IAC5D,KAAK,CAAC,EAAE;QACN,mCAAmC;QACnC,OAAO,EAAE,MAAM,CAAC;QAChB,mDAAmD;QACnD,IAAI,CAAC,EAAE,MAAM,CAAC;QACd,6DAA6D;QAC7D,IAAI,CAAC,EAAE,MAAM,CAAC;QACd,KAAK,CAAC,EAAE,MAAM,CAAC;KAChB,CAAC;CACH"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"SandboxWorkerResponse.js","sourceRoot":"","sources":["../../src/types/SandboxWorkerResponse.ts"],"names":[],"mappings":"","sourcesContent":["import type { StubExportInfo } from './StubExportInfo.js';\n\n/**\n * Success or error IPC message after attempting to run a CJS file in a worker.\n */\nexport interface SandboxWorkerResponse {\n /** Path to the file that was run */\n entryPath: string;\n\n /** If successful: info about the file's exports */\n exportInfo?: StubExportInfo;\n\n /** If not successful: info about the error that occurred */\n error?: {\n /** Message describing the error */\n message: string;\n /** If there was an exception: error object name */\n name?: string;\n /** If there was an exception: error code (not always set) */\n code?: string;\n stack?: string;\n };\n}\n"]}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Error that occurred while attempting to create an ESM stub from a CJS or JSON file.
|
|
3
|
+
*/
|
|
4
|
+
export interface StubError {
|
|
5
|
+
/**
|
|
6
|
+
* Type of error:
|
|
7
|
+
* - `module-not-found`: Some file attempted to load a module that wasn't found.
|
|
8
|
+
* - `require-esm`: Some file attempted to load an ESM module using `require()`.
|
|
9
|
+
* - `entry-is-esm`: The entry file being stubbed is already ESM.
|
|
10
|
+
* - `invalid-syntax`: Some loaded file has invalid syntax.
|
|
11
|
+
* - `other-error`: Anything else.
|
|
12
|
+
*/
|
|
13
|
+
type: 'module-not-found' | 'require-esm' | 'entry-is-esm' | 'invalid-syntax' | 'other-error';
|
|
14
|
+
/**
|
|
15
|
+
* Error message. This will *not* include the path to the file that was being stubbed,
|
|
16
|
+
* since it's assumed the caller already has this context, and it should be reported as the
|
|
17
|
+
* file location in the final BundleMessage error.
|
|
18
|
+
*/
|
|
19
|
+
message: string;
|
|
20
|
+
/**
|
|
21
|
+
* Stack from the location of the error down to the file attempting to be stubbed,
|
|
22
|
+
* omitting frames from Node built-ins. Each line follows the standard stack trace format
|
|
23
|
+
* `at <function> (<file>:<line>:<column>)` (but with whitespace trimmed).
|
|
24
|
+
*/
|
|
25
|
+
partialStack?: string[];
|
|
26
|
+
}
|
|
27
|
+
//# sourceMappingURL=StubError.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"StubError.d.ts","sourceRoot":"","sources":["../../src/types/StubError.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,MAAM,WAAW,SAAS;IACxB;;;;;;;OAOG;IACH,IAAI,EAAE,kBAAkB,GAAG,aAAa,GAAG,cAAc,GAAG,gBAAgB,GAAG,aAAa,CAAC;IAE7F;;;;OAIG;IACH,OAAO,EAAE,MAAM,CAAC;IAEhB;;;;OAIG;IACH,YAAY,CAAC,EAAE,MAAM,EAAE,CAAC;CACzB"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"StubError.js","sourceRoot":"","sources":["../../src/types/StubError.ts"],"names":[],"mappings":"","sourcesContent":["/**\n * Error that occurred while attempting to create an ESM stub from a CJS or JSON file.\n */\nexport interface StubError {\n /**\n * Type of error:\n * - `module-not-found`: Some file attempted to load a module that wasn't found.\n * - `require-esm`: Some file attempted to load an ESM module using `require()`.\n * - `entry-is-esm`: The entry file being stubbed is already ESM.\n * - `invalid-syntax`: Some loaded file has invalid syntax.\n * - `other-error`: Anything else.\n */\n type: 'module-not-found' | 'require-esm' | 'entry-is-esm' | 'invalid-syntax' | 'other-error';\n\n /**\n * Error message. This will *not* include the path to the file that was being stubbed,\n * since it's assumed the caller already has this context, and it should be reported as the\n * file location in the final BundleMessage error.\n */\n message: string;\n\n /**\n * Stack from the location of the error down to the file attempting to be stubbed,\n * omitting frames from Node built-ins. Each line follows the standard stack trace format\n * `at <function> (<file>:<line>:<column>)` (but with whitespace trimmed).\n */\n partialStack?: string[];\n}\n"]}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Information about a CJS module's exports, for purposes of creating a stub.
|
|
3
|
+
*/
|
|
4
|
+
export type StubExportInfo = {
|
|
5
|
+
/**
|
|
6
|
+
* Category describing what this module exports (if anything).
|
|
7
|
+
* - `none`: the module has either set `module.exports = undefined` or deleted `module.exports`
|
|
8
|
+
*/
|
|
9
|
+
type: 'none';
|
|
10
|
+
} | {
|
|
11
|
+
/** - `object` or `function` (potentially with other keys set) */
|
|
12
|
+
type: 'object' | 'function';
|
|
13
|
+
keys: string[];
|
|
14
|
+
} | {
|
|
15
|
+
/** - `other`: primitive or array (should just re-export) */
|
|
16
|
+
type: 'other';
|
|
17
|
+
};
|
|
18
|
+
//# sourceMappingURL=StubExportInfo.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"StubExportInfo.d.ts","sourceRoot":"","sources":["../../src/types/StubExportInfo.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,MAAM,MAAM,cAAc,GACtB;IACE;;;OAGG;IACH,IAAI,EAAE,MAAM,CAAC;CACd,GACD;IACE,iEAAiE;IACjE,IAAI,EAAE,QAAQ,GAAG,UAAU,CAAC;IAC5B,IAAI,EAAE,MAAM,EAAE,CAAC;CAChB,GACD;IACE,4DAA4D;IAC5D,IAAI,EAAE,OAAO,CAAC;CACf,CAAC"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"StubExportInfo.js","sourceRoot":"","sources":["../../src/types/StubExportInfo.ts"],"names":[],"mappings":"","sourcesContent":["/**\n * Information about a CJS module's exports, for purposes of creating a stub.\n */\nexport type StubExportInfo =\n | {\n /**\n * Category describing what this module exports (if anything).\n * - `none`: the module has either set `module.exports = undefined` or deleted `module.exports`\n */\n type: 'none';\n }\n | {\n /** - `object` or `function` (potentially with other keys set) */\n type: 'object' | 'function';\n keys: string[];\n }\n | {\n /** - `other`: primitive or array (should just re-export) */\n type: 'other';\n };\n"]}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
/** Get all property descriptor names from the global object. */
|
|
2
|
+
export function getGlobalProperties(): string[];
|
|
3
|
+
/**
|
|
4
|
+
* Delete any new properties from the global object.
|
|
5
|
+
* @param {string[]} initialGlobalProperties
|
|
6
|
+
*/
|
|
7
|
+
export function cleanUpGlobals(initialGlobalProperties: string[]): void;
|
|
8
|
+
//# sourceMappingURL=globals.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"globals.d.ts","sourceRoot":"","sources":["../../src/worker/globals.js"],"names":[],"mappings":"AAEA,gEAAgE;AAChE,gDAEC;AAED;;;GAGG;AACH,wDAFW,MAAM,EAAE,QAYlB"}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
// See worker.js for why this is a JS file.
|
|
2
|
+
/** Get all property descriptor names from the global object. */
|
|
3
|
+
export function getGlobalProperties() {
|
|
4
|
+
return Object.keys(Object.getOwnPropertyDescriptors(global));
|
|
5
|
+
}
|
|
6
|
+
/**
|
|
7
|
+
* Delete any new properties from the global object.
|
|
8
|
+
* @param {string[]} initialGlobalProperties
|
|
9
|
+
*/
|
|
10
|
+
export function cleanUpGlobals(initialGlobalProperties) {
|
|
11
|
+
Object.entries(Object.getOwnPropertyDescriptors(global)).forEach(([k, desc]) => {
|
|
12
|
+
if (!initialGlobalProperties.includes(k) && desc.configurable) {
|
|
13
|
+
try {
|
|
14
|
+
delete ( /** @type {*} */(global)[k]);
|
|
15
|
+
}
|
|
16
|
+
catch {
|
|
17
|
+
// ignore
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
});
|
|
21
|
+
}
|
|
22
|
+
//# sourceMappingURL=globals.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"globals.js","sourceRoot":"","sources":["../../src/worker/globals.js"],"names":[],"mappings":"AAAA,2CAA2C;AAE3C,gEAAgE;AAChE,MAAM,UAAU,mBAAmB;IACjC,OAAO,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,yBAAyB,CAAC,MAAM,CAAC,CAAC,CAAC;AAC/D,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,cAAc,CAAC,uBAAuB;IACpD,MAAM,CAAC,OAAO,CAAC,MAAM,CAAC,yBAAyB,CAAC,MAAM,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,EAAE,IAAI,CAAC,EAAE,EAAE;QAC7E,IAAI,CAAC,uBAAuB,CAAC,QAAQ,CAAC,CAAC,CAAC,IAAI,IAAI,CAAC,YAAY,EAAE;YAC7D,IAAI;gBACF,OAAO,EAAC,gBAAiB,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;aACvC;YAAC,MAAM;gBACN,SAAS;aACV;SACF;IACH,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["// See worker.js for why this is a JS file.\n\n/** Get all property descriptor names from the global object. */\nexport function getGlobalProperties() {\n return Object.keys(Object.getOwnPropertyDescriptors(global));\n}\n\n/**\n * Delete any new properties from the global object.\n * @param {string[]} initialGlobalProperties\n */\nexport function cleanUpGlobals(initialGlobalProperties) {\n Object.entries(Object.getOwnPropertyDescriptors(global)).forEach(([k, desc]) => {\n if (!initialGlobalProperties.includes(k) && desc.configurable) {\n try {\n delete (/** @type {*} */ (global)[k]);\n } catch {\n // ignore\n }\n }\n });\n}\n"]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"initBrowserEnvironment.d.ts","sourceRoot":"","sources":["../../src/worker/initBrowserEnvironment.js"],"names":[],"mappings":"AAOA;;GAEG;AACH,wDAiEC"}
|