importTypescript.js 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  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. const path = require('path');
  6. const fs = require('fs');
  7. const child_process = require('child_process');
  8. const generatedNote = `//
  9. // **NOTE**: Do not edit directly! This file is generated using \`npm run import-typescript\`
  10. //
  11. `;
  12. const REPO_ROOT = path.join(__dirname, '../');
  13. const TYPESCRIPT_LIB_SOURCE = path.join(REPO_ROOT, 'node_modules/typescript/lib');
  14. const TYPESCRIPT_LIB_DESTINATION = path.join(REPO_ROOT, 'monaco-typescript/src/lib');
  15. (function () {
  16. try {
  17. fs.statSync(TYPESCRIPT_LIB_DESTINATION);
  18. } catch (err) {
  19. fs.mkdirSync(TYPESCRIPT_LIB_DESTINATION);
  20. }
  21. importLibs();
  22. const npmLsOutput = JSON.parse(
  23. child_process.execSync('npm ls typescript --depth=0 --json=true', { cwd: REPO_ROOT }).toString()
  24. );
  25. const typeScriptDependencyVersion = npmLsOutput.dependencies.typescript.version;
  26. fs.writeFileSync(
  27. path.join(TYPESCRIPT_LIB_DESTINATION, 'typescriptServicesMetadata.ts'),
  28. `${generatedNote}
  29. export const typescriptVersion = "${typeScriptDependencyVersion}";\n`
  30. );
  31. let tsServices = fs
  32. .readFileSync(path.join(TYPESCRIPT_LIB_SOURCE, 'typescriptServices.js'))
  33. .toString();
  34. // Ensure we never run into the node system...
  35. // (this also removes require calls that trick webpack into shimming those modules...)
  36. tsServices = tsServices.replace(
  37. /\n ts\.sys =([^]*)\n \}\)\(\);/m,
  38. `\n // MONACOCHANGE\n ts.sys = undefined;\n // END MONACOCHANGE`
  39. );
  40. // Eliminate more require() calls...
  41. tsServices = tsServices.replace(
  42. /^( +)etwModule = require\(.*$/m,
  43. '$1// MONACOCHANGE\n$1etwModule = undefined;\n$1// END MONACOCHANGE'
  44. );
  45. tsServices = tsServices.replace(
  46. /^( +)var result = ts\.sys\.require\(.*$/m,
  47. '$1// MONACOCHANGE\n$1var result = undefined;\n$1// END MONACOCHANGE'
  48. );
  49. tsServices = tsServices.replace(
  50. /^( +)fs = require\("fs"\);$/m,
  51. '$1// MONACOCHANGE\n$1fs = undefined;\n$1// END MONACOCHANGE'
  52. );
  53. tsServices = tsServices.replace(
  54. /^( +)debugger;$/m,
  55. '$1// MONACOCHANGE\n$1// debugger;\n$1// END MONACOCHANGE'
  56. );
  57. tsServices = tsServices.replace(
  58. /= require\("perf_hooks"\)/m,
  59. '/* MONACOCHANGE */= {}/* END MONACOCHANGE */'
  60. );
  61. // Flag any new require calls (outside comments) so they can be corrected preemptively.
  62. // To avoid missing cases (or using an even more complex regex), temporarily remove comments
  63. // about require() and then check for lines actually calling require().
  64. // \/[*/] matches the start of a comment (single or multi-line).
  65. // ^\s+\*[^/] matches (presumably) a later line of a multi-line comment.
  66. const tsServicesNoCommentedRequire = tsServices.replace(
  67. /(\/[*/]|^\s+\*[^/]).*\brequire\(.*/gm,
  68. ''
  69. );
  70. const linesWithRequire = tsServicesNoCommentedRequire.match(/^.*?\brequire\(.*$/gm);
  71. // Allow error messages to include references to require() in their strings
  72. const runtimeRequires =
  73. linesWithRequire &&
  74. linesWithRequire.filter((l) => !l.includes(': diag(') && !l.includes('ts.DiagnosticCategory'));
  75. if (runtimeRequires && runtimeRequires.length && linesWithRequire) {
  76. console.error(
  77. 'Found new require() calls on the following lines. These should be removed to avoid breaking webpack builds.\n'
  78. );
  79. console.error(
  80. runtimeRequires.map((r) => `${r} (${tsServicesNoCommentedRequire.indexOf(r)})`).join('\n')
  81. );
  82. process.exit(1);
  83. }
  84. const tsServices_amd =
  85. generatedNote +
  86. tsServices +
  87. `
  88. // MONACOCHANGE
  89. // Defining the entire module name because r.js has an issue and cannot bundle this file
  90. // correctly with an anonymous define call
  91. define("vs/language/typescript/lib/typescriptServices", [], function() { return ts; });
  92. // END MONACOCHANGE
  93. `;
  94. fs.writeFileSync(
  95. path.join(TYPESCRIPT_LIB_DESTINATION, 'typescriptServices-amd.js'),
  96. stripSourceMaps(tsServices_amd)
  97. );
  98. // Remove pattern that creates warnings with esbuild
  99. // e.g.
  100. // > monaco-typescript/src/lib/typescriptServices.js:20:21: warning: Top-level "this" will be replaced with undefined since this file is an ECMAScript module
  101. // 20 │ var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
  102. // ╵ ~~~~
  103. //
  104. tsServices = tsServices.replace(/\nvar ([^ ]+) = \(this && this\.([^)]+)\) \|\|/gm, '\nvar $1 =');
  105. const tsServices_esm =
  106. generatedNote +
  107. tsServices +
  108. `
  109. // MONACOCHANGE
  110. export var createClassifier = ts.createClassifier;
  111. export var createLanguageService = ts.createLanguageService;
  112. export var displayPartsToString = ts.displayPartsToString;
  113. export var EndOfLineState = ts.EndOfLineState;
  114. export var flattenDiagnosticMessageText = ts.flattenDiagnosticMessageText;
  115. export var IndentStyle = ts.IndentStyle;
  116. export var ScriptKind = ts.ScriptKind;
  117. export var ScriptTarget = ts.ScriptTarget;
  118. export var TokenClass = ts.TokenClass;
  119. // END MONACOCHANGE
  120. `;
  121. fs.writeFileSync(
  122. path.join(TYPESCRIPT_LIB_DESTINATION, 'typescriptServices.js'),
  123. stripSourceMaps(tsServices_esm)
  124. );
  125. let dtsServices = fs
  126. .readFileSync(path.join(TYPESCRIPT_LIB_SOURCE, 'typescriptServices.d.ts'))
  127. .toString();
  128. dtsServices += `
  129. // MONACOCHANGE
  130. export = ts;
  131. // END MONACOCHANGE
  132. `;
  133. fs.writeFileSync(
  134. path.join(TYPESCRIPT_LIB_DESTINATION, 'typescriptServices.d.ts'),
  135. generatedNote + dtsServices
  136. );
  137. })();
  138. function importLibs() {
  139. function readLibFile(name) {
  140. const srcPath = path.join(TYPESCRIPT_LIB_SOURCE, name);
  141. return fs.readFileSync(srcPath).toString();
  142. }
  143. let strLibResult = `/*---------------------------------------------------------------------------------------------
  144. * Copyright (c) Microsoft Corporation. All rights reserved.
  145. * Licensed under the MIT License. See License.txt in the project root for license information.
  146. *--------------------------------------------------------------------------------------------*/
  147. ${generatedNote}
  148. /** Contains all the lib files */
  149. export const libFileMap: Record<string, string> = {}
  150. `;
  151. let strIndexResult = `/*---------------------------------------------------------------------------------------------
  152. * Copyright (c) Microsoft Corporation. All rights reserved.
  153. * Licensed under the MIT License. See License.txt in the project root for license information.
  154. *--------------------------------------------------------------------------------------------*/
  155. ${generatedNote}
  156. /** Contains all the lib files */
  157. export const libFileSet: Record<string, boolean> = {}
  158. `;
  159. const dtsFiles = fs.readdirSync(TYPESCRIPT_LIB_SOURCE).filter((f) => f.includes('lib.'));
  160. while (dtsFiles.length > 0) {
  161. const name = dtsFiles.shift();
  162. const output = readLibFile(name).replace(/\r\n/g, '\n');
  163. strLibResult += `libFileMap['${name}'] = "${escapeText(output)}";\n`;
  164. strIndexResult += `libFileSet['${name}'] = true;\n`;
  165. }
  166. fs.writeFileSync(path.join(TYPESCRIPT_LIB_DESTINATION, 'lib.ts'), strLibResult);
  167. fs.writeFileSync(path.join(TYPESCRIPT_LIB_DESTINATION, 'lib.index.ts'), strIndexResult);
  168. }
  169. /**
  170. * Escape text such that it can be used in a javascript string enclosed by double quotes (")
  171. */
  172. function escapeText(text) {
  173. // See http://www.javascriptkit.com/jsref/escapesequence.shtml
  174. const _backspace = '\b'.charCodeAt(0);
  175. const _formFeed = '\f'.charCodeAt(0);
  176. const _newLine = '\n'.charCodeAt(0);
  177. const _nullChar = 0;
  178. const _carriageReturn = '\r'.charCodeAt(0);
  179. const _tab = '\t'.charCodeAt(0);
  180. const _verticalTab = '\v'.charCodeAt(0);
  181. const _backslash = '\\'.charCodeAt(0);
  182. const _doubleQuote = '"'.charCodeAt(0);
  183. const len = text.length;
  184. let startPos = 0;
  185. let chrCode;
  186. let replaceWith = null;
  187. let resultPieces = [];
  188. for (let i = 0; i < len; i++) {
  189. chrCode = text.charCodeAt(i);
  190. switch (chrCode) {
  191. case _backspace:
  192. replaceWith = '\\b';
  193. break;
  194. case _formFeed:
  195. replaceWith = '\\f';
  196. break;
  197. case _newLine:
  198. replaceWith = '\\n';
  199. break;
  200. case _nullChar:
  201. replaceWith = '\\0';
  202. break;
  203. case _carriageReturn:
  204. replaceWith = '\\r';
  205. break;
  206. case _tab:
  207. replaceWith = '\\t';
  208. break;
  209. case _verticalTab:
  210. replaceWith = '\\v';
  211. break;
  212. case _backslash:
  213. replaceWith = '\\\\';
  214. break;
  215. case _doubleQuote:
  216. replaceWith = '\\"';
  217. break;
  218. }
  219. if (replaceWith !== null) {
  220. resultPieces.push(text.substring(startPos, i));
  221. resultPieces.push(replaceWith);
  222. startPos = i + 1;
  223. replaceWith = null;
  224. }
  225. }
  226. resultPieces.push(text.substring(startPos, len));
  227. return resultPieces.join('');
  228. }
  229. function stripSourceMaps(str) {
  230. return str.replace(/\/\/# sourceMappingURL[^\n]+/gm, '');
  231. }