importTypescript.js 7.4 KB

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