importTypescript.js 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269
  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. if (linesWithRequire && linesWithRequire.length) {
  45. console.error('Found new require() calls on the following lines. These should be removed to avoid breaking webpack builds.\n');
  46. console.error(linesWithRequire.join('\n'));
  47. process.exit(1);
  48. }
  49. // Make sure process.args don't get called in the browser, this
  50. // should only happen in TS 2.6.2
  51. const beforeProcess = `ts.perfLogger.logInfoEvent("Starting TypeScript v" + ts.versionMajorMinor + " with command line: " + JSON.stringify(process.argv));`
  52. const afterProcess = `// MONACOCHANGE\n ts.perfLogger.logInfoEvent("Starting TypeScript v" + ts.versionMajorMinor + " with command line: " + JSON.stringify([]));\n// END MONACOCHANGE`
  53. tsServices = tsServices.replace(beforeProcess, afterProcess);
  54. var tsServices_amd = generatedNote + tsServices +
  55. `
  56. // MONACOCHANGE
  57. // Defining the entire module name because r.js has an issue and cannot bundle this file
  58. // correctly with an anonymous define call
  59. define("vs/language/typescript/lib/typescriptServices", [], function() { return ts; });
  60. // END MONACOCHANGE
  61. `;
  62. fs.writeFileSync(path.join(TYPESCRIPT_LIB_DESTINATION, 'typescriptServices-amd.js'), stripSourceMaps(tsServices_amd));
  63. var tsServices_esm = generatedNote + tsServices +
  64. `
  65. // MONACOCHANGE
  66. export var createClassifier = ts.createClassifier;
  67. export var createLanguageService = ts.createLanguageService;
  68. export var displayPartsToString = ts.displayPartsToString;
  69. export var EndOfLineState = ts.EndOfLineState;
  70. export var flattenDiagnosticMessageText = ts.flattenDiagnosticMessageText;
  71. export var IndentStyle = ts.IndentStyle;
  72. export var ScriptKind = ts.ScriptKind;
  73. export var ScriptTarget = ts.ScriptTarget;
  74. export var TokenClass = ts.TokenClass;
  75. // END MONACOCHANGE
  76. `;
  77. fs.writeFileSync(path.join(TYPESCRIPT_LIB_DESTINATION, 'typescriptServices.js'), stripSourceMaps(tsServices_esm));
  78. var dtsServices = fs.readFileSync(path.join(TYPESCRIPT_LIB_SOURCE, 'typescriptServices.d.ts')).toString();
  79. dtsServices +=
  80. `
  81. // MONACOCHANGE
  82. export = ts;
  83. // END MONACOCHANGE
  84. `;
  85. fs.writeFileSync(path.join(TYPESCRIPT_LIB_DESTINATION, 'typescriptServices.d.ts'), generatedNote + dtsServices);
  86. })();
  87. function importLibs() {
  88. function getFileName(name) {
  89. return (name === '' ? 'lib.d.ts' : `lib.${name}.d.ts`);
  90. }
  91. function getVariableName(name) {
  92. return (name === '' ? 'lib_dts' : `lib_${name.replace(/\./g, '_')}_dts`);
  93. }
  94. function readLibFile(name) {
  95. var srcPath = path.join(TYPESCRIPT_LIB_SOURCE, getFileName(name));
  96. return fs.readFileSync(srcPath).toString();
  97. }
  98. var queue = [];
  99. var in_queue = {};
  100. var enqueue = function (name) {
  101. if (in_queue[name]) {
  102. return;
  103. }
  104. in_queue[name] = true;
  105. queue.push(name);
  106. };
  107. enqueue('');
  108. enqueue('es6');
  109. enqueue('es2015');
  110. var result = [];
  111. while (queue.length > 0) {
  112. var name = queue.shift();
  113. var contents = readLibFile(name);
  114. var lines = contents.split(/\r\n|\r|\n/);
  115. var output = '';
  116. var writeOutput = function (text) {
  117. if (output.length === 0) {
  118. output = text;
  119. } else {
  120. output += ` + ${text}`;
  121. }
  122. };
  123. var outputLines = [];
  124. var flushOutputLines = function () {
  125. writeOutput(`"${escapeText(outputLines.join('\n'))}"`);
  126. outputLines = [];
  127. };
  128. var deps = [];
  129. for (let i = 0; i < lines.length; i++) {
  130. let m = lines[i].match(/\/\/\/\s*<reference\s*lib="([^"]+)"/);
  131. if (m) {
  132. deps.push(getVariableName(m[1]));
  133. enqueue(m[1]);
  134. outputLines.push(lines[i]);
  135. continue;
  136. }
  137. outputLines.push(lines[i]);
  138. }
  139. flushOutputLines();
  140. result.push({
  141. name: getVariableName(name),
  142. filepath: getFileName(name),
  143. deps: deps,
  144. output: output
  145. });
  146. }
  147. var strResult = `/*---------------------------------------------------------------------------------------------
  148. * Copyright (c) Microsoft Corporation. All rights reserved.
  149. * Licensed under the MIT License. See License.txt in the project root for license information.
  150. *--------------------------------------------------------------------------------------------*/
  151. ${generatedNote}
  152. /** Contains all the lib files */
  153. export const libFileMap: Record<string, string> = {}
  154. `
  155. ;
  156. // Do a topological sort
  157. while (result.length > 0) {
  158. for (let i = result.length - 1; i >= 0; i--) {
  159. if (result[i].deps.length === 0) {
  160. // emit this node
  161. strResult += `\nexport const ${result[i].name}: string = ${result[i].output};\n`;
  162. strResult += `\libFileMap['${result[i].filepath}'] = ${result[i].name};\n`;
  163. // mark dep as resolved
  164. for (let j = 0; j < result.length; j++) {
  165. for (let k = 0; k < result[j].deps.length; k++) {
  166. if (result[j].deps[k] === result[i].name) {
  167. result[j].deps.splice(k, 1);
  168. break;
  169. }
  170. }
  171. }
  172. // remove from result
  173. result.splice(i, 1);
  174. break;
  175. }
  176. }
  177. }
  178. var dstPath = path.join(TYPESCRIPT_LIB_DESTINATION, 'lib.ts');
  179. fs.writeFileSync(dstPath, strResult);
  180. }
  181. /**
  182. * Escape text such that it can be used in a javascript string enclosed by double quotes (")
  183. */
  184. function escapeText(text) {
  185. // See http://www.javascriptkit.com/jsref/escapesequence.shtml
  186. var _backspace = '\b'.charCodeAt(0);
  187. var _formFeed = '\f'.charCodeAt(0);
  188. var _newLine = '\n'.charCodeAt(0);
  189. var _nullChar = 0;
  190. var _carriageReturn = '\r'.charCodeAt(0);
  191. var _tab = '\t'.charCodeAt(0);
  192. var _verticalTab = '\v'.charCodeAt(0);
  193. var _backslash = '\\'.charCodeAt(0);
  194. var _doubleQuote = '"'.charCodeAt(0);
  195. var startPos = 0, chrCode, replaceWith = null, resultPieces = [];
  196. for (var i = 0, len = text.length; i < len; i++) {
  197. chrCode = text.charCodeAt(i);
  198. switch (chrCode) {
  199. case _backspace:
  200. replaceWith = '\\b';
  201. break;
  202. case _formFeed:
  203. replaceWith = '\\f';
  204. break;
  205. case _newLine:
  206. replaceWith = '\\n';
  207. break;
  208. case _nullChar:
  209. replaceWith = '\\0';
  210. break;
  211. case _carriageReturn:
  212. replaceWith = '\\r';
  213. break;
  214. case _tab:
  215. replaceWith = '\\t';
  216. break;
  217. case _verticalTab:
  218. replaceWith = '\\v';
  219. break;
  220. case _backslash:
  221. replaceWith = '\\\\';
  222. break;
  223. case _doubleQuote:
  224. replaceWith = '\\"';
  225. break;
  226. }
  227. if (replaceWith !== null) {
  228. resultPieces.push(text.substring(startPos, i));
  229. resultPieces.push(replaceWith);
  230. startPos = i + 1;
  231. replaceWith = null;
  232. }
  233. }
  234. resultPieces.push(text.substring(startPos, len));
  235. return resultPieces.join('');
  236. }
  237. function stripSourceMaps(str) {
  238. return str.replace(/\/\/# sourceMappingURL[^\n]+/gm, '');
  239. }