importTypescript.js 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255
  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 TYPESCRIPT_LIB_SOURCE = path.join(__dirname, '../node_modules/typescript/lib');
  9. const TYPESCRIPT_LIB_DESTINATION = path.join(__dirname, '../src/lib');
  10. (function () {
  11. try {
  12. fs.statSync(TYPESCRIPT_LIB_DESTINATION);
  13. } catch (err) {
  14. fs.mkdirSync(TYPESCRIPT_LIB_DESTINATION);
  15. }
  16. importLibs();
  17. const npmLsOutput = JSON.parse(child_process.execSync("npm ls typescript --depth=0 --json=true").toString());
  18. const typeScriptDependencyVersion = npmLsOutput.dependencies.typescript.version;
  19. fs.writeFileSync(
  20. path.join(TYPESCRIPT_LIB_DESTINATION, 'typescriptServicesMetadata.ts'),
  21. `export const typescriptVersion = "${typeScriptDependencyVersion}";\n`
  22. );
  23. var tsServices = fs.readFileSync(path.join(TYPESCRIPT_LIB_SOURCE, 'typescriptServices.js')).toString();
  24. // Ensure we never run into the node system...
  25. // (this also removes require calls that trick webpack into shimming those modules...)
  26. tsServices = (
  27. tsServices.replace(/\n ts\.sys =([^]*)\n \}\)\(\);/m, `\n // MONACOCHANGE\n ts.sys = undefined;\n // END MONACOCHANGE`)
  28. );
  29. // Eliminate more require() calls...
  30. tsServices = (
  31. tsServices.replace(/return require\(fileNameToRequire\);/, `// MONACOCHANGE\n return undefined;\n // END MONACOCHANGE`)
  32. );
  33. tsServices = tsServices.replace(/^( +)etwModule = require\(.*$/m, '$1// MONACOCHANGE\n$1etwModule = undefined;\n$1// END MONACOCHANGE');
  34. // Flag any new require calls (outside comments) so they can be corrected preemptively.
  35. // To avoid missing cases (or using an even more complex regex), temporarily remove comments
  36. // about require() and then check for lines actually calling require().
  37. // \/[*/] matches the start of a comment (single or multi-line).
  38. // ^\s+\*[^/] matches (presumably) a later line of a multi-line comment.
  39. const tsServicesNoCommentedRequire = tsServices.replace(/(\/[*/]|^\s+\*[^/]).*\brequire\(.*/gm, '');
  40. const linesWithRequire = tsServicesNoCommentedRequire.match(/^.*?\brequire\(.*$/gm);
  41. if (linesWithRequire && linesWithRequire.length) {
  42. console.error('Found new require() calls on the following lines. These should be removed to avoid breaking webpack builds.\n');
  43. console.error(linesWithRequire.join('\n'));
  44. process.exit(1);
  45. }
  46. // Make sure process.args don't get called in the browser, this
  47. // should only happen in TS 2.6.2
  48. const beforeProcess = `ts.perfLogger.logInfoEvent("Starting TypeScript v" + ts.versionMajorMinor + " with command line: " + JSON.stringify(process.argv));`
  49. const afterProcess = `// MONACOCHANGE\n ts.perfLogger.logInfoEvent("Starting TypeScript v" + ts.versionMajorMinor + " with command line: " + JSON.stringify([]));\n// END MONACOCHANGE`
  50. tsServices = tsServices.replace(beforeProcess, afterProcess);
  51. var tsServices_amd = 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'), tsServices_amd);
  60. var tsServices_esm = 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'), 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'), dtsServices);
  83. })();
  84. function importLibs() {
  85. function getFileName(name) {
  86. return (name === '' ? 'lib.d.ts' : `lib.${name}.d.ts`);
  87. }
  88. function getVariableName(name) {
  89. return (name === '' ? 'lib_dts' : `lib_${name.replace(/\./g, '_')}_dts`);
  90. }
  91. function readLibFile(name) {
  92. var srcPath = path.join(TYPESCRIPT_LIB_SOURCE, getFileName(name));
  93. return fs.readFileSync(srcPath).toString();
  94. }
  95. var queue = [];
  96. var in_queue = {};
  97. var enqueue = function (name) {
  98. if (in_queue[name]) {
  99. return;
  100. }
  101. in_queue[name] = true;
  102. queue.push(name);
  103. };
  104. enqueue('');
  105. enqueue('es6');
  106. var result = [];
  107. while (queue.length > 0) {
  108. var name = queue.shift();
  109. var contents = readLibFile(name);
  110. var lines = contents.split(/\r\n|\r|\n/);
  111. var output = '';
  112. var writeOutput = function (text) {
  113. if (output.length === 0) {
  114. output = text;
  115. } else {
  116. output += ` + ${text}`;
  117. }
  118. };
  119. var outputLines = [];
  120. var flushOutputLines = function () {
  121. writeOutput(`"${escapeText(outputLines.join('\n'))}"`);
  122. outputLines = [];
  123. };
  124. var deps = [];
  125. for (let i = 0; i < lines.length; i++) {
  126. let m = lines[i].match(/\/\/\/\s*<reference\s*lib="([^"]+)"/);
  127. if (m) {
  128. flushOutputLines();
  129. writeOutput(getVariableName(m[1]));
  130. deps.push(getVariableName(m[1]));
  131. enqueue(m[1]);
  132. continue;
  133. }
  134. outputLines.push(lines[i]);
  135. }
  136. flushOutputLines();
  137. result.push({
  138. name: getVariableName(name),
  139. deps: deps,
  140. output: output
  141. });
  142. }
  143. var strResult = `/*---------------------------------------------------------------------------------------------
  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. `;
  148. // Do a topological sort
  149. while (result.length > 0) {
  150. for (let i = result.length - 1; i >= 0; i--) {
  151. if (result[i].deps.length === 0) {
  152. // emit this node
  153. strResult += `\nexport const ${result[i].name} = ${result[i].output};\n`;
  154. // mark dep as resolved
  155. for (let j = 0; j < result.length; j++) {
  156. for (let k = 0; k < result[j].deps.length; k++) {
  157. if (result[j].deps[k] === result[i].name) {
  158. result[j].deps.splice(k, 1);
  159. break;
  160. }
  161. }
  162. }
  163. // remove from result
  164. result.splice(i, 1);
  165. break;
  166. }
  167. }
  168. }
  169. var dstPath = path.join(TYPESCRIPT_LIB_DESTINATION, 'lib.ts');
  170. fs.writeFileSync(dstPath, strResult);
  171. }
  172. /**
  173. * Escape text such that it can be used in a javascript string enclosed by double quotes (")
  174. */
  175. function escapeText(text) {
  176. // See http://www.javascriptkit.com/jsref/escapesequence.shtml
  177. var _backspace = '\b'.charCodeAt(0);
  178. var _formFeed = '\f'.charCodeAt(0);
  179. var _newLine = '\n'.charCodeAt(0);
  180. var _nullChar = 0;
  181. var _carriageReturn = '\r'.charCodeAt(0);
  182. var _tab = '\t'.charCodeAt(0);
  183. var _verticalTab = '\v'.charCodeAt(0);
  184. var _backslash = '\\'.charCodeAt(0);
  185. var _doubleQuote = '"'.charCodeAt(0);
  186. var startPos = 0, chrCode, replaceWith = null, resultPieces = [];
  187. for (var i = 0, len = text.length; i < len; i++) {
  188. chrCode = text.charCodeAt(i);
  189. switch (chrCode) {
  190. case _backspace:
  191. replaceWith = '\\b';
  192. break;
  193. case _formFeed:
  194. replaceWith = '\\f';
  195. break;
  196. case _newLine:
  197. replaceWith = '\\n';
  198. break;
  199. case _nullChar:
  200. replaceWith = '\\0';
  201. break;
  202. case _carriageReturn:
  203. replaceWith = '\\r';
  204. break;
  205. case _tab:
  206. replaceWith = '\\t';
  207. break;
  208. case _verticalTab:
  209. replaceWith = '\\v';
  210. break;
  211. case _backslash:
  212. replaceWith = '\\\\';
  213. break;
  214. case _doubleQuote:
  215. replaceWith = '\\"';
  216. break;
  217. }
  218. if (replaceWith !== null) {
  219. resultPieces.push(text.substring(startPos, i));
  220. resultPieces.push(replaceWith);
  221. startPos = i + 1;
  222. replaceWith = null;
  223. }
  224. }
  225. resultPieces.push(text.substring(startPos, len));
  226. return resultPieces.join('');
  227. }