Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
microsoft
GitHub Repository: microsoft/vscode
Path: blob/main/src/bootstrap-import.ts
3285 views
1
/*---------------------------------------------------------------------------------------------
2
* Copyright (c) Microsoft Corporation. All rights reserved.
3
* Licensed under the MIT License. See License.txt in the project root for license information.
4
*--------------------------------------------------------------------------------------------*/
5
6
// *********************************************************************
7
// * *
8
// * We need this to redirect to node_modules from the remote-folder. *
9
// * This ONLY applies when running out of source. *
10
// * *
11
// *********************************************************************
12
13
import { fileURLToPath, pathToFileURL } from 'node:url';
14
import { promises } from 'node:fs';
15
import { join } from 'node:path';
16
17
// SEE https://nodejs.org/docs/latest/api/module.html#initialize
18
19
const _specifierToUrl: Record<string, string> = {};
20
21
export async function initialize(injectPath: string): Promise<void> {
22
// populate mappings
23
24
const injectPackageJSONPath = fileURLToPath(new URL('../package.json', pathToFileURL(injectPath)));
25
const packageJSON = JSON.parse(String(await promises.readFile(injectPackageJSONPath)));
26
27
for (const [name] of Object.entries(packageJSON.dependencies)) {
28
try {
29
const path = join(injectPackageJSONPath, `../node_modules/${name}/package.json`);
30
let { main } = JSON.parse(String(await promises.readFile(path)));
31
32
if (!main) {
33
main = 'index.js';
34
}
35
if (!main.endsWith('.js')) {
36
main += '.js';
37
}
38
const mainPath = join(injectPackageJSONPath, `../node_modules/${name}/${main}`);
39
_specifierToUrl[name] = pathToFileURL(mainPath).href;
40
41
} catch (err) {
42
console.error(name);
43
console.error(err);
44
}
45
}
46
47
console.log(`[bootstrap-import] Initialized node_modules redirector for: ${injectPath}`);
48
}
49
50
export async function resolve(specifier: string | number, context: any, nextResolve: (arg0: any, arg1: any) => any) {
51
52
const newSpecifier = _specifierToUrl[specifier];
53
if (newSpecifier !== undefined) {
54
return {
55
format: 'commonjs',
56
shortCircuit: true,
57
url: newSpecifier
58
};
59
}
60
61
// Defer to the next hook in the chain, which would be the
62
// Node.js default resolve if this is the last user-specified loader.
63
return nextResolve(specifier, context);
64
}
65
66