build-monaco-editor.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426
  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. import path = require('path');
  6. import fs = require('fs');
  7. import { REPO_ROOT, readFiles, writeFiles, IFile } from '../build/utils';
  8. import { removeDir } from '../build/fs';
  9. import ts = require('typescript');
  10. import { generateMetadata } from './releaseMetadata';
  11. removeDir(`out/monaco-editor`);
  12. // dev folder
  13. AMD_releaseOne('dev');
  14. // min folder
  15. AMD_releaseOne('min');
  16. // esm folder
  17. ESM_release();
  18. // monaco.d.ts, editor.api.d.ts
  19. releaseDTS();
  20. // ThirdPartyNotices.txt
  21. releaseThirdPartyNotices();
  22. // esm/metadata.d.ts, esm/metadata.js
  23. generateMetadata();
  24. // package.json
  25. (() => {
  26. const packageJSON = readFiles('package.json', { base: '' })[0];
  27. const json = JSON.parse(packageJSON.contents.toString());
  28. json.private = false;
  29. delete json.scripts['postinstall'];
  30. packageJSON.contents = Buffer.from(JSON.stringify(json, null, ' '));
  31. writeFiles([packageJSON], `out/monaco-editor`);
  32. })();
  33. (() => {
  34. /** @type {IFile[]} */
  35. let otherFiles = [];
  36. otherFiles = otherFiles.concat(readFiles('README.md', { base: '' }));
  37. otherFiles = otherFiles.concat(readFiles('CHANGELOG.md', { base: '' }));
  38. otherFiles = otherFiles.concat(
  39. readFiles('node_modules/monaco-editor-core/min-maps/**/*', {
  40. base: 'node_modules/monaco-editor-core/'
  41. })
  42. );
  43. otherFiles = otherFiles.concat(
  44. readFiles('node_modules/monaco-editor-core/LICENSE', {
  45. base: 'node_modules/monaco-editor-core/'
  46. })
  47. );
  48. writeFiles(otherFiles, `out/monaco-editor`);
  49. })();
  50. /**
  51. * Release to `dev` or `min`.
  52. */
  53. function AMD_releaseOne(type: 'dev' | 'min') {
  54. const coreFiles = readFiles(`node_modules/monaco-editor-core/${type}/**/*`, {
  55. base: `node_modules/monaco-editor-core/${type}`
  56. });
  57. AMD_addPluginContribs(type, coreFiles);
  58. writeFiles(coreFiles, `out/monaco-editor/${type}`);
  59. const pluginFiles = readFiles(`out/languages/bundled/amd-${type}/**/*`, {
  60. base: `out/languages/bundled/amd-${type}`,
  61. ignore: ['**/monaco.contribution.js']
  62. });
  63. writeFiles(pluginFiles, `out/monaco-editor/${type}`);
  64. }
  65. /**
  66. * Edit editor.main.js:
  67. * - rename the AMD module 'vs/editor/editor.main' to 'vs/editor/edcore.main'
  68. * - append monaco.contribution modules from plugins
  69. * - append new AMD module 'vs/editor/editor.main' that stiches things together
  70. */
  71. function AMD_addPluginContribs(type: 'dev' | 'min', files: IFile[]) {
  72. for (const file of files) {
  73. if (!/editor\.main\.js$/.test(file.path)) {
  74. continue;
  75. }
  76. let contents = file.contents.toString();
  77. // Rename the AMD module 'vs/editor/editor.main' to 'vs/editor/edcore.main'
  78. contents = contents.replace(/"vs\/editor\/editor\.main\"/, '"vs/editor/edcore.main"');
  79. const pluginFiles = readFiles(`out/languages/bundled/amd-${type}/**/monaco.contribution.js`, {
  80. base: `out/languages/bundled/amd-${type}`
  81. });
  82. const extraContent = pluginFiles.map((file) => {
  83. return file.contents
  84. .toString()
  85. .replace(
  86. /define\((['"][a-z\/\-]+\/fillers\/monaco-editor-core['"]),\[\],/,
  87. "define($1,['vs/editor/editor.api'],"
  88. );
  89. });
  90. const allPluginsModuleIds = pluginFiles.map((file) => {
  91. return file.path.replace(/\.js$/, '');
  92. });
  93. extraContent.push(
  94. `define("vs/editor/editor.main", ["vs/editor/edcore.main","${allPluginsModuleIds.join(
  95. '","'
  96. )}"], function(api) { return api; });`
  97. );
  98. let insertIndex = contents.lastIndexOf('//# sourceMappingURL=');
  99. if (insertIndex === -1) {
  100. insertIndex = contents.length;
  101. }
  102. contents =
  103. contents.substring(0, insertIndex) +
  104. '\n' +
  105. extraContent.join('\n') +
  106. '\n' +
  107. contents.substring(insertIndex);
  108. file.contents = Buffer.from(contents);
  109. }
  110. }
  111. function ESM_release() {
  112. const coreFiles = readFiles(`node_modules/monaco-editor-core/esm/**/*`, {
  113. base: 'node_modules/monaco-editor-core/esm',
  114. // we will create our own editor.api.d.ts which also contains the plugins API
  115. ignore: ['node_modules/monaco-editor-core/esm/vs/editor/editor.api.d.ts']
  116. });
  117. ESM_addImportSuffix(coreFiles);
  118. ESM_addPluginContribs(coreFiles);
  119. writeFiles(coreFiles, `out/monaco-editor/esm`);
  120. ESM_releasePlugins();
  121. }
  122. /**
  123. * Release a plugin to `esm`.
  124. * Adds a dependency to 'vs/editor/editor.api' in contrib files in order for `monaco` to be defined.
  125. * Rewrites imports for 'monaco-editor-core/**'
  126. */
  127. function ESM_releasePlugins() {
  128. const files = readFiles(`out/languages/bundled/esm/**/*`, { base: 'out/languages/bundled/esm/' });
  129. for (const file of files) {
  130. if (!/(\.js$)|(\.ts$)/.test(file.path)) {
  131. continue;
  132. }
  133. let contents = file.contents.toString();
  134. const info = ts.preProcessFile(contents);
  135. for (let i = info.importedFiles.length - 1; i >= 0; i--) {
  136. let importText = info.importedFiles[i].fileName;
  137. const pos = info.importedFiles[i].pos;
  138. const end = info.importedFiles[i].end;
  139. if (!/(^\.\/)|(^\.\.\/)/.test(importText)) {
  140. // non-relative import
  141. if (!/^monaco-editor-core/.test(importText)) {
  142. console.error(`Non-relative import for unknown module: ${importText} in ${file.path}`);
  143. process.exit(1);
  144. }
  145. if (importText === 'monaco-editor-core') {
  146. importText = 'monaco-editor-core/esm/vs/editor/editor.api';
  147. }
  148. const importFilePath = importText.substring('monaco-editor-core/esm/'.length);
  149. let relativePath = path
  150. .relative(path.dirname(file.path), importFilePath)
  151. .replace(/\\/g, '/');
  152. if (!/(^\.\/)|(^\.\.\/)/.test(relativePath)) {
  153. relativePath = './' + relativePath;
  154. }
  155. contents = contents.substring(0, pos + 1) + relativePath + contents.substring(end + 1);
  156. }
  157. }
  158. file.contents = Buffer.from(contents);
  159. }
  160. for (const file of files) {
  161. if (!/monaco\.contribution\.js$/.test(file.path)) {
  162. continue;
  163. }
  164. const apiFilePath = 'vs/editor/editor.api';
  165. let relativePath = path.relative(path.dirname(file.path), apiFilePath).replace(/\\/g, '/');
  166. if (!/(^\.\/)|(^\.\.\/)/.test(relativePath)) {
  167. relativePath = './' + relativePath;
  168. }
  169. let contents = file.contents.toString();
  170. contents = `import '${relativePath}';\n` + contents;
  171. file.contents = Buffer.from(contents);
  172. }
  173. ESM_addImportSuffix(files);
  174. writeFiles(files, `out/monaco-editor/esm`);
  175. }
  176. /**
  177. * Adds `.js` to all import statements.
  178. */
  179. function ESM_addImportSuffix(files: IFile[]) {
  180. for (const file of files) {
  181. if (!/\.js$/.test(file.path)) {
  182. continue;
  183. }
  184. let contents = file.contents.toString();
  185. const info = ts.preProcessFile(contents);
  186. for (let i = info.importedFiles.length - 1; i >= 0; i--) {
  187. const importText = info.importedFiles[i].fileName;
  188. const pos = info.importedFiles[i].pos;
  189. const end = info.importedFiles[i].end;
  190. if (/(\.css)|(\.js)$/.test(importText)) {
  191. // A CSS import or an import already using .js
  192. continue;
  193. }
  194. contents = contents.substring(0, pos + 1) + importText + '.js' + contents.substring(end + 1);
  195. }
  196. file.contents = Buffer.from(contents);
  197. }
  198. }
  199. /**
  200. * - Rename esm/vs/editor/editor.main.js to esm/vs/editor/edcore.main.js
  201. * - Create esm/vs/editor/editor.main.js that that stiches things together
  202. */
  203. function ESM_addPluginContribs(files: IFile[]) {
  204. for (const file of files) {
  205. if (!/editor\.main\.js$/.test(file.path)) {
  206. continue;
  207. }
  208. file.path = file.path.replace(/editor\.main/, 'edcore.main');
  209. }
  210. const mainFileDestPath = 'vs/editor/editor.main.js';
  211. const mainFileImports = readFiles(`out/languages/bundled/esm/**/monaco.contribution.js`, {
  212. base: `out/languages/bundled/esm`
  213. }).map((file) => {
  214. let relativePath = path
  215. .relative(path.dirname(mainFileDestPath), file.path)
  216. .replace(/\\/g, '/')
  217. .replace(/\.js$/, '');
  218. if (!/(^\.\/)|(^\.\.\/)/.test(relativePath)) {
  219. relativePath = './' + relativePath;
  220. }
  221. return relativePath;
  222. });
  223. const mainFileContents =
  224. mainFileImports.map((name) => `import '${name}';`).join('\n') +
  225. `\n\nexport * from './edcore.main';`;
  226. files.push({
  227. path: mainFileDestPath,
  228. contents: Buffer.from(mainFileContents)
  229. });
  230. }
  231. /**
  232. * Edit monaco.d.ts:
  233. * - append monaco.d.ts from plugins
  234. */
  235. function releaseDTS() {
  236. const monacodts = readFiles('node_modules/monaco-editor-core/monaco.d.ts', {
  237. base: 'node_modules/monaco-editor-core'
  238. })[0];
  239. let contents = monacodts.contents.toString();
  240. const extraContent = readFiles('out/languages/bundled/*.d.ts', {
  241. base: 'out/languages/bundled/'
  242. }).map((file) => {
  243. return file.contents.toString().replace(/\/\/\/ <reference.*\n/m, '');
  244. });
  245. contents =
  246. [
  247. '/*!-----------------------------------------------------------',
  248. ' * Copyright (c) Microsoft Corporation. All rights reserved.',
  249. ' * Type definitions for monaco-editor',
  250. ' * Released under the MIT license',
  251. '*-----------------------------------------------------------*/'
  252. ].join('\n') +
  253. '\n' +
  254. contents +
  255. '\n' +
  256. extraContent.join('\n');
  257. // Ensure consistent indentation and line endings
  258. contents = cleanFile(contents);
  259. monacodts.contents = Buffer.from(contents);
  260. const editorapidts = {
  261. path: 'esm/vs/editor/editor.api.d.ts',
  262. contents: Buffer.from(toExternalDTS(contents))
  263. };
  264. writeFiles([monacodts, editorapidts], `out/monaco-editor`);
  265. // fs.writeFileSync('website/typedoc/monaco.d.ts', contents);
  266. }
  267. /**
  268. * Transforms a .d.ts which uses internal modules (namespaces) to one which is usable with external modules
  269. * This function is duplicated in the `vscode` repo.
  270. */
  271. function toExternalDTS(contents: string): string {
  272. let lines = contents.split(/\r\n|\r|\n/);
  273. let killNextCloseCurlyBrace = false;
  274. for (let i = 0; i < lines.length; i++) {
  275. let line = lines[i];
  276. if (killNextCloseCurlyBrace) {
  277. if ('}' === line) {
  278. lines[i] = '';
  279. killNextCloseCurlyBrace = false;
  280. continue;
  281. }
  282. if (line.indexOf(' ') === 0) {
  283. lines[i] = line.substr(4);
  284. } else if (line.charAt(0) === '\t') {
  285. lines[i] = line.substr(1);
  286. }
  287. continue;
  288. }
  289. if ('declare namespace monaco {' === line) {
  290. lines[i] = '';
  291. killNextCloseCurlyBrace = true;
  292. continue;
  293. }
  294. if (line.indexOf('declare namespace monaco.') === 0) {
  295. lines[i] = line.replace('declare namespace monaco.', 'export namespace ');
  296. }
  297. if (line.indexOf('declare let MonacoEnvironment') === 0) {
  298. lines[i] = [
  299. 'declare global {',
  300. ' let MonacoEnvironment: Environment | undefined;',
  301. '',
  302. ' interface Window {',
  303. ' MonacoEnvironment?: Environment | undefined;',
  304. ' }',
  305. '}',
  306. ''
  307. ].join('\n');
  308. }
  309. if (line.indexOf(' MonacoEnvironment?') === 0) {
  310. lines[i] = ` MonacoEnvironment?: Environment | undefined;`;
  311. }
  312. }
  313. return lines.join('\n').replace(/\n\n\n+/g, '\n\n');
  314. }
  315. /**
  316. * Normalize line endings and ensure consistent 4 spaces indentation
  317. */
  318. function cleanFile(contents: string): string {
  319. return contents
  320. .split(/\r\n|\r|\n/)
  321. .map(function (line) {
  322. const m = line.match(/^(\t+)/);
  323. if (!m) {
  324. return line;
  325. }
  326. const tabsCount = m[1].length;
  327. let newIndent = '';
  328. for (let i = 0; i < 4 * tabsCount; i++) {
  329. newIndent += ' ';
  330. }
  331. return newIndent + line.substring(tabsCount);
  332. })
  333. .join('\n');
  334. }
  335. /**
  336. * Edit ThirdPartyNotices.txt:
  337. * - append ThirdPartyNotices.txt from plugins
  338. */
  339. function releaseThirdPartyNotices() {
  340. const tpn = readFiles('node_modules/monaco-editor-core/ThirdPartyNotices.txt', {
  341. base: 'node_modules/monaco-editor-core'
  342. })[0];
  343. let contents = tpn.contents.toString();
  344. console.log('ADDING ThirdPartyNotices from ./ThirdPartyNotices.txt');
  345. let thirdPartyNoticeContent = fs
  346. .readFileSync(path.join(REPO_ROOT, 'ThirdPartyNotices.txt'))
  347. .toString();
  348. thirdPartyNoticeContent = thirdPartyNoticeContent.split('\n').slice(8).join('\n');
  349. contents += '\n' + thirdPartyNoticeContent;
  350. tpn.contents = Buffer.from(contents);
  351. writeFiles([tpn], `out/monaco-editor`);
  352. }