-
Notifications
You must be signed in to change notification settings - Fork 345
/
migrate.mjs
364 lines (315 loc) · 9.81 KB
/
migrate.mjs
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
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
//@ts-check
// *****************************************************************
// * *
// * AMD-TO-ESM MIGRATION SCRIPT *
// * *
// *****************************************************************
import { readFileSync, writeFileSync } from 'node:fs';
import { join, extname, dirname, relative } from 'node:path';
import { preProcessFile } from 'typescript';
import { existsSync, mkdirSync, readdirSync, statSync } from 'fs';
import { fileURLToPath } from 'node:url';
// @ts-expect-error
import watch from './build/lib/watch/index.js';
const enableWatching = !process.argv.includes('--disable-watch');
const srcFolder = fileURLToPath(new URL('src', import.meta.url));
const dstFolder = fileURLToPath(new URL('src2', import.meta.url));
const binaryFileExtensions = new Set([
'.svg', '.ttf', '.png', '.sh', '.html', '.json', '.zsh', '.scpt', '.mp3', '.fish', '.ps1', '.psm1', '.md', '.txt', '.zip', '.pdf', '.qwoff', '.jxs', '.tst', '.wuff', '.less', '.utf16le', '.snap', '.tsx'
]);
function migrate() {
console.log(`~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~`);
console.log(`STARTING AMD->ESM MIGRATION of src to src2.`);
// installing watcher quickly to avoid missing early events
const watchSrc = enableWatching ? watch('src/**', { base: 'src', readDelay: 200 }) : undefined;
/** @type {string[]} */
const files = [];
readdir(srcFolder, files);
for (const filePath of files) {
const fileContents = readFileSync(filePath);
migrateOne(filePath, fileContents);
}
writeFileSync(join(dstFolder, 'package.json'), `{"type": "module"}`);
writeFileSync(join(dstFolder, '.gitignore'), `*`);
console.log(`~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~`);
console.log(`COMPLETED AMD->ESM MIGRATION of src to src2. You can now launch yarn watch-esm or yarn watch-client-esm`);
console.log(`Make sure to set the environment variable VSCODE_BUILD_ESM to a string of value 'true' if you want to build VS Code`);
if (watchSrc) {
console.log(`WATCHING src for changes...`);
watchSrc.on('data', (e) => {
migrateOne(e.path, e.contents);
console.log(`Handled change event for ${e.path}.`);
});
}
}
function posixFilePath(filePath) {
return filePath.replace(/\\/g, '/');
}
/**
* @param filePath
* @param fileContents
*/
function migrateOne(filePath, fileContents) {
const fileExtension = extname(filePath);
if (fileExtension === '.ts') {
migrateTS(filePath, fileContents.toString());
} else if (fileExtension === '.js' || fileExtension === '.cjs') {
if (
posixFilePath(filePath).endsWith('vs/loader.js')
) {
// fake loader
writeDestFile(filePath, `(function () {
if (typeof require !== 'undefined') {
return;
}
globalThis.require = function () {
console.trace('[require(...)] this is ESM, no more AMD/CJS require');
};
globalThis.require.config = function () {
console.trace('[require.config(...)] this is ESM, no more AMD/CJS require');
};
})();`);
} else {
writeDestFile(filePath, fileContents);
}
} else if (fileExtension === '.mjs') {
writeDestFile(filePath, fileContents);
} else if (fileExtension === '.css') {
writeDestFile(filePath, fileContents);
} else if (filePath.endsWith('tsconfig.base.json')) {
const opts = JSON.parse(fileContents.toString());
opts.compilerOptions.module = 'es2022';
opts.compilerOptions.allowSyntheticDefaultImports = true;
writeDestFile(filePath, JSON.stringify(opts, null, '\t'));
} else if (binaryFileExtensions.has(fileExtension)) {
writeDestFile(filePath, fileContents);
} else {
console.log(`ignoring ${filePath}`);
}
}
/**
* @param fileContents
* @typedef {{pos:number;end:number;}} Import
* @return
*/
function discoverImports(fileContents) {
const info = preProcessFile(fileContents);
const search = /export .* from ['"]([^'"]+)['"]/g;
/** typedef {Import[]} */
let result = [];
do {
const m = search.exec(fileContents);
if (!m) {
break;
}
const end = m.index + m[0].length - 2;
const pos = end - m[1].length;
result.push({ pos, end });
} while (true);
result = result.concat(info.importedFiles);
result.sort((a, b) => {
return a.pos - b.pos;
});
for (let i = 1; i < result.length; i++) {
const prev = result[i - 1];
const curr = result[i];
if (prev.pos === curr.pos) {
result.splice(i, 1);
i--;
}
}
return result;
}
/**
* @param filePath
* @param fileContents
*/
function migrateTS(filePath, fileContents) {
const filePathPosix = posixFilePath(filePath);
if (filePath.endsWith('.d.ts')) {
return writeDestFile(filePath, fileContents);
}
const imports = discoverImports(fileContents);
/** @type {Replacement[]} */
const replacements = [];
for (let i = imports.length - 1; i >= 0; i--) {
const pos = imports[i].pos + 1;
const end = imports[i].end + 1;
const importedFilename = fileContents.substring(pos, end);
/** @type {string} */
let importedFilepath;
if (/^vs\/css!/.test(importedFilename)) {
importedFilepath = importedFilename.substr('vs/css!'.length) + '.css';
} else {
importedFilepath = importedFilename;
}
/** @type {boolean} */
let isRelativeImport;
if (/(^\.\/)|(^\.\.\/)/.test(importedFilepath)) {
importedFilepath = join(dirname(filePath), importedFilepath);
isRelativeImport = true;
} else if (/^vs\//.test(importedFilepath)) {
importedFilepath = join(srcFolder, importedFilepath);
isRelativeImport = true;
} else {
importedFilepath = importedFilepath;
isRelativeImport = false;
}
/** @type {string} */
let replacementImport;
if (isRelativeImport) {
replacementImport = generateRelativeImport(filePath, importedFilepath);
} else {
replacementImport = importedFilepath;
}
replacements.push({ pos, end, text: replacementImport });
}
// replacements = replacements.concat(rewriteDefaultImports(fileContents));
fileContents = applyReplacements(fileContents, replacements);
fileContents = fileContents.replace(/require\.__\$__nodeRequire/g, 'require');
writeDestFile(filePath, fileContents);
}
/**
* @param filePath
* @param importedFilepath
*/
function generateRelativeImport(filePath, importedFilepath) {
/** @type {string} */
let relativePath;
// See https://github.com/microsoft/TypeScript/issues/16577#issuecomment-754941937
if (!importedFilepath.endsWith('.css') && !importedFilepath.endsWith('.cjs')) {
importedFilepath = `${importedFilepath}.js`;
}
relativePath = relative(dirname(filePath), `${importedFilepath}`);
relativePath = relativePath.replace(/\\/g, '/');
if (!/(^\.\/)|(^\.\.\/)/.test(relativePath)) {
relativePath = './' + relativePath;
}
return relativePath;
}
/** @typedef {{pos:number;end:number;text:string;}} Replacement */
/**
* @param str
* @param replacements
*/
function applyReplacements(str, replacements) {
replacements.sort((a, b) => {
return a.pos - b.pos;
});
/** @type {string[]} */
const result = [];
let lastEnd = 0;
for (const replacement of replacements) {
const { pos, end, text } = replacement;
result.push(str.substring(lastEnd, pos));
result.push(text);
lastEnd = end;
}
result.push(str.substring(lastEnd, str.length));
return result.join('');
}
/**
* @param srcFilePath
* @param fileContents
*/
function writeDestFile(srcFilePath, fileContents) {
const destFilePath = srcFilePath.replace(srcFolder, dstFolder);
ensureDir(dirname(destFilePath));
if (/(\.ts$)|(\.js$)|(\.html$)/.test(destFilePath)) {
fileContents = toggleComments(fileContents);
}
/** @type {Buffer | undefined} */
let existingFileContents = undefined;
try {
existingFileContents = readFileSync(destFilePath);
} catch (err) { }
if (!buffersAreEqual(existingFileContents, fileContents)) {
writeFileSync(destFilePath, fileContents);
}
/**
* @param fileContents
*/
function toggleComments(fileContents) {
const lines = String(fileContents).split(/\r\n|\r|\n/);
let mode = 0;
let didChange = false;
for (let i = 0; i < lines.length; i++) {
const line = lines[i];
if (mode === 0) {
if (/\/\/ ESM-comment-begin/.test(line)) {
mode = 1;
continue;
}
if (/\/\/ ESM-uncomment-begin/.test(line)) {
mode = 2;
continue;
}
continue;
}
if (mode === 1) {
if (/\/\/ ESM-comment-end/.test(line)) {
mode = 0;
continue;
}
didChange = true;
lines[i] = '// ' + line;
continue;
}
if (mode === 2) {
if (/\/\/ ESM-uncomment-end/.test(line)) {
mode = 0;
continue;
}
didChange = true;
lines[i] = line.replace(/^(\s*)\/\/ ?/, function (_, indent) {
return indent;
});
}
}
if (didChange) {
return lines.join('\n');
}
return fileContents;
}
}
/**
* @param existingFileContents
* @param fileContents
*/
function buffersAreEqual(existingFileContents, fileContents) {
if (!existingFileContents) {
return false;
}
if (typeof fileContents === 'string') {
fileContents = Buffer.from(fileContents);
}
return existingFileContents.equals(fileContents);
}
const ensureDirCache = new Set();
function ensureDir(dirPath) {
if (ensureDirCache.has(dirPath)) {
return;
}
ensureDirCache.add(dirPath);
ensureDir(dirname(dirPath));
if (!existsSync(dirPath)) {
mkdirSync(dirPath);
}
}
function readdir(dirPath, result) {
const entries = readdirSync(dirPath);
for (const entry of entries) {
const entryPath = join(dirPath, entry);
const stat = statSync(entryPath);
if (stat.isDirectory()) {
readdir(join(dirPath, entry), result);
} else {
result.push(entryPath);
}
}
}
migrate();