Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

esm - reduce diff #224919

Merged
merged 7 commits into from
Aug 6, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .eslintrc.json
Original file line number Diff line number Diff line change
Expand Up @@ -1033,7 +1033,7 @@
"restrictions": []
},
{
"target": "src/{bootstrap-amd.js,bootstrap-fork.js,bootstrap-node.js,bootstrap-window.js,bootstrap.js,cli.js,main.js,server-cli.js,server-main.js}",
"target": "src/{bootstrap-amd.js,bootstrap-fork.js,bootstrap-node.js,bootstrap-window.js,cli.js,main.js,server-cli.js,server-main.js}",
"restrictions": []
}
]
Expand Down
1 change: 0 additions & 1 deletion build/gulpfile.vscode.js
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,6 @@ const vscodeResources = [
// be inlined into the target window file in this order
// and they depend on each other in this way.
const windowBootstrapFiles = [
'out-build/bootstrap.js',
'out-build/vs/loader.js',
'out-build/bootstrap-window.js'
];
Expand Down
31 changes: 22 additions & 9 deletions src/bootstrap-amd.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,17 +19,33 @@ const isESM = false;
// import * as fs from 'fs';
// import { fileURLToPath } from 'url';
// import { createRequire, register } from 'node:module';
// if (process.env['ELECTRON_RUN_AS_NODE'] || process.versions['electron']) {
// register('./loader-original-fs.mjs', import.meta.url);
// }
// import { product, pkg } from './bootstrap-meta.js';
// import * as bootstrap from './bootstrap.js';
// import * as bootstrapNode from './bootstrap-node.js';
// import * as performance from './vs/base/common/performance.js';
//
// const require = createRequire(import.meta.url);
// const isESM = true;
// const module = { exports: {} };
// const __dirname = path.dirname(fileURLToPath(import.meta.url));
//
// // Install a hook to module resolution to map 'fs' to 'original-fs'
// if (process.env['ELECTRON_RUN_AS_NODE'] || process.versions['electron']) {
// const jsCode = `
// export async function resolve(specifier, context, nextResolve) {
// if (specifier === 'fs') {
// return {
// format: 'builtin',
// shortCircuit: true,
// url: 'node:original-fs'
// };
// }

// // Defer to the next hook in the chain, which would be the
// // Node.js default resolve if this is the last user-specified loader.
// return nextResolve(specifier, context);
// }`;
// register(`data:text/javascript;base64,${Buffer.from(jsCode).toString('base64')}`, import.meta.url);
// }
// ESM-uncomment-end

// Store the node.js require function in a variable
Expand Down Expand Up @@ -67,7 +83,7 @@ globalThis._VSCODE_PACKAGE_JSON = require('./bootstrap-meta').pkg;
globalThis._VSCODE_FILE_ROOT = __dirname;

// ESM-comment-begin
const bootstrap = require('./bootstrap');
const bootstrapNode = require('./bootstrap-node');
const performance = require(`./vs/base/common/performance`);
const fs = require('fs');
// ESM-comment-end
Expand Down Expand Up @@ -109,7 +125,6 @@ async function doSetupNLS() {
messagesFile = nlsConfig.defaultMessagesFile;
}

// VSCODE_GLOBALS: NLS
globalThis._VSCODE_NLS_LANGUAGE = nlsConfig?.resolvedLanguage;
} catch (e) {
console.error(`Error reading VSCODE_NLS_CONFIG from environment: ${e}`);
Expand All @@ -124,7 +139,6 @@ async function doSetupNLS() {
}

try {
// VSCODE_GLOBALS: NLS
globalThis._VSCODE_NLS_MESSAGES = JSON.parse((await fs.promises.readFile(messagesFile)).toString());
} catch (error) {
console.error(`Error reading NLS messages file ${messagesFile}: ${error}`);
Expand All @@ -141,7 +155,6 @@ async function doSetupNLS() {
// Fallback to the default message file to ensure english translation at least
if (nlsConfig?.defaultMessagesFile && nlsConfig.defaultMessagesFile !== messagesFile) {
try {
// VSCODE_GLOBALS: NLS
globalThis._VSCODE_NLS_MESSAGES = JSON.parse((await fs.promises.readFile(nlsConfig.defaultMessagesFile)).toString());
} catch (error) {
console.error(`Error reading default NLS messages file ${nlsConfig.defaultMessagesFile}: ${error}`);
Expand Down Expand Up @@ -186,7 +199,7 @@ if (isESM) {
const loader = require('./vs/loader');

loader.config({
baseUrl: bootstrap.fileUriFromPath(__dirname, { isWindows: process.platform === 'win32' }),
baseUrl: bootstrapNode.fileUriFromPath(__dirname, { isWindows: process.platform === 'win32' }),
catchError: true,
nodeRequire,
amdModulesPattern: /^vs\//,
Expand Down
4 changes: 1 addition & 3 deletions src/bootstrap-fork.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,11 @@

// ESM-comment-begin
const performance = require('./vs/base/common/performance');
const bootstrap = require('./bootstrap');
const bootstrapNode = require('./bootstrap-node');
const bootstrapAmd = require('./bootstrap-amd');
// ESM-comment-end
// ESM-uncomment-begin
// import * as performance from './vs/base/common/performance.js';
// import * as bootstrap from './bootstrap.js';
// import * as bootstrapNode from './bootstrap-node.js';
// import * as bootstrapAmd from './bootstrap-amd.js';
// ESM-uncomment-end
Expand All @@ -28,7 +26,7 @@ configureCrashReporter();
bootstrapNode.removeGlobalNodeModuleLookupPaths();

// Enable ASAR in our forked processes
bootstrap.enableASARSupport();
bootstrapNode.enableASARSupport();

if (process.env['VSCODE_INJECT_NODE_MODULE_LOOKUP_PATH']) {
bootstrapNode.injectNodeModuleLookupPath(process.env['VSCODE_INJECT_NODE_MODULE_LOOKUP_PATH']);
Expand Down
86 changes: 86 additions & 0 deletions src/bootstrap-node.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
// ESM-comment-begin
const path = require('path');
const fs = require('fs');
const Module = require('module');

const isESM = false;
// ESM-comment-end
Expand All @@ -19,11 +20,30 @@ const isESM = false;
// import { createRequire } from 'node:module';
//
// const require = createRequire(import.meta.url);
// const Module = require('module');
// const isESM = true;
// const module = { exports: {} };
// const __dirname = path.dirname(fileURLToPath(import.meta.url));
// ESM-uncomment-end

// increase number of stack frames(from 10, https://github.com/v8/v8/wiki/Stack-Trace-API)
Error.stackTraceLimit = 100;

if (!process.env['VSCODE_HANDLES_SIGPIPE']) {
// Workaround for Electron not installing a handler to ignore SIGPIPE
// (https://github.com/electron/electron/issues/13254)
let didLogAboutSIGPIPE = false;
process.on('SIGPIPE', () => {
// See https://github.com/microsoft/vscode-remote-release/issues/6543
// In certain situations, the console itself can be in a broken pipe state
// so logging SIGPIPE to the console will cause an infinite async loop
if (!didLogAboutSIGPIPE) {
didLogAboutSIGPIPE = true;
console.error(new Error(`Unexpected SIGPIPE`));
}
});
}

// Setup current working directory in all our node & electron processes
// - Windows: call `process.chdir()` to always set application folder as cwd
// - all OS: store the `process.cwd()` inside `VSCODE_CWD` for consistent lookups
Expand Down Expand Up @@ -177,8 +197,74 @@ module.exports.configurePortable = function (product) {
};
};

/**
* Helper to enable ASAR support.
*/
module.exports.enableASARSupport = function () {
const NODE_MODULES_PATH = path.join(__dirname, '../node_modules');
const NODE_MODULES_ASAR_PATH = `${NODE_MODULES_PATH}.asar`;

// @ts-ignore
const originalResolveLookupPaths = Module._resolveLookupPaths;

// @ts-ignore
Module._resolveLookupPaths = function (request, parent) {
const paths = originalResolveLookupPaths(request, parent);
if (Array.isArray(paths)) {
for (let i = 0, len = paths.length; i < len; i++) {
if (paths[i] === NODE_MODULES_PATH) {
paths.splice(i, 0, NODE_MODULES_ASAR_PATH);
break;
}
}
}

return paths;
};
};

/**
* Helper to convert a file path to a URI.
*
* TODO@bpasero check for removal once ESM has landed.
*
* @param {string} path
* @param {{ isWindows?: boolean, scheme?: string, fallbackAuthority?: string }} config
* @returns {string}
*/
module.exports.fileUriFromPath = function (path, config) {

// Since we are building a URI, we normalize any backslash
// to slashes and we ensure that the path begins with a '/'.
let pathName = path.replace(/\\/g, '/');
if (pathName.length > 0 && pathName.charAt(0) !== '/') {
pathName = `/${pathName}`;
}

/** @type {string} */
let uri;

// Windows: in order to support UNC paths (which start with '//')
// that have their own authority, we do not use the provided authority
// but rather preserve it.
if (config.isWindows && pathName.startsWith('//')) {
uri = encodeURI(`${config.scheme || 'file'}:${pathName}`);
}

// Otherwise we optionally add the provided authority if specified
else {
uri = encodeURI(`${config.scheme || 'file'}://${config.fallbackAuthority || ''}${pathName}`);
}

return uri.replace(/#/g, '%23');
};

//#endregion

// ESM-uncomment-begin
// export const injectNodeModuleLookupPath = module.exports.injectNodeModuleLookupPath;
// export const removeGlobalNodeModuleLookupPaths = module.exports.removeGlobalNodeModuleLookupPaths;
// export const configurePortable = module.exports.configurePortable;
// export const enableASARSupport = module.exports.enableASARSupport;
// export const fileUriFromPath = module.exports.fileUriFromPath;
// ESM-uncomment-end
55 changes: 35 additions & 20 deletions src/bootstrap-window.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
* @typedef {any} LoaderConfig
*/

/* eslint-disable no-restricted-globals, */
/* eslint-disable no-restricted-globals */

// ESM-comment-begin
const isESM = false;
Expand All @@ -22,24 +22,16 @@ const isESM = false;
// const isESM = true;
// ESM-uncomment-end

// Simple module style to support node.js and browser environments
(function (factory) {

// Node.js
if (typeof exports === 'object') {
module.exports = factory();
}

// Browser
else {
// @ts-ignore
globalThis.MonacoBootstrapWindow = factory();
}
// @ts-ignore
globalThis.MonacoBootstrapWindow = factory();
}(function () {
const bootstrapLib = bootstrap();
const preloadGlobals = sandboxGlobals();
const safeProcess = preloadGlobals.process;

// increase number of stack frames(from 10, https://github.com/v8/v8/wiki/Stack-Trace-API)
Error.stackTraceLimit = 100;
alexdima marked this conversation as resolved.
Show resolved Hide resolved

/**
* @param {string[]} modulePaths
* @param {(result: unknown, configuration: ISandboxConfiguration) => Promise<unknown> | undefined} resultCallback
Expand Down Expand Up @@ -90,7 +82,6 @@ const isESM = false;
developerDeveloperKeybindingsDisposable = registerDeveloperKeybindings(disallowReloadKeybinding);
}

// VSCODE_GLOBALS: NLS
globalThis._VSCODE_NLS_MESSAGES = configuration.nls.messages;
globalThis._VSCODE_NLS_LANGUAGE = configuration.nls.language;
let language = configuration.nls.language || 'en';
Expand Down Expand Up @@ -178,7 +169,7 @@ const isESM = false;

/** @type {LoaderConfig} */
const loaderConfig = {
baseUrl: `${bootstrapLib.fileUriFromPath(configuration.appRoot, { isWindows: safeProcess.platform === 'win32', scheme: 'vscode-file', fallbackAuthority: 'vscode-app' })}/out`,
baseUrl: `${fileUriFromPath(configuration.appRoot, { isWindows: safeProcess.platform === 'win32', scheme: 'vscode-file', fallbackAuthority: 'vscode-app' })}/out`,
preferScriptTags: true
};

Expand Down Expand Up @@ -317,11 +308,35 @@ const isESM = false;
}

/**
* @return {{ fileUriFromPath: (path: string, config: { isWindows?: boolean, scheme?: string, fallbackAuthority?: string }) => string; }}
* @param {string} path
* @param {{ isWindows?: boolean, scheme?: string, fallbackAuthority?: string }} config
* @returns {string}
*/
function bootstrap() {
// @ts-ignore (defined in bootstrap.js)
return window.MonacoBootstrap;
function fileUriFromPath(path, config) {

// Since we are building a URI, we normalize any backslash
// to slashes and we ensure that the path begins with a '/'.
let pathName = path.replace(/\\/g, '/');
if (pathName.length > 0 && pathName.charAt(0) !== '/') {
pathName = `/${pathName}`;
}

/** @type {string} */
let uri;

// Windows: in order to support UNC paths (which start with '//')
// that have their own authority, we do not use the provided authority
// but rather preserve it.
if (config.isWindows && pathName.startsWith('//')) {
uri = encodeURI(`${config.scheme || 'file'}:${pathName}`);
}

// Otherwise we optionally add the provided authority if specified
else {
uri = encodeURI(`${config.scheme || 'file'}://${config.fallbackAuthority || ''}${pathName}`);
}

return uri.replace(/#/g, '%23');
}

/**
Expand Down
Loading
Loading