gulpfile.js 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797
  1. const gulp = require('gulp');
  2. const metadata = require('./metadata');
  3. const es = require('event-stream');
  4. const path = require('path');
  5. const fs = require('fs');
  6. const rimraf = require('rimraf');
  7. const cp = require('child_process');
  8. const yaserver = require('yaserver');
  9. const http = require('http');
  10. const CleanCSS = require('clean-css');
  11. const uncss = require('uncss');
  12. const File = require('vinyl');
  13. const ts = require('typescript');
  14. const WEBSITE_GENERATED_PATH = path.join(__dirname, 'website/playground/new-samples');
  15. const MONACO_EDITOR_VERSION = (function() {
  16. const packageJsonPath = path.join(__dirname, 'package.json');
  17. const packageJson = JSON.parse(fs.readFileSync(packageJsonPath).toString());
  18. const version = packageJson.version;
  19. if (!/\d+\.\d+\.\d+/.test(version)) {
  20. console.log('unrecognized package.json version: ' + version);
  21. process.exit(0);
  22. }
  23. return version;
  24. })();
  25. async function _execute(task) {
  26. // Always invoke as if it were a callback task
  27. return new Promise((resolve, reject) => {
  28. if (task.length === 1) {
  29. // this is a calback task
  30. task((err) => {
  31. if (err) {
  32. return reject(err);
  33. }
  34. resolve();
  35. });
  36. return;
  37. }
  38. const taskResult = task();
  39. if (typeof taskResult === 'undefined') {
  40. // this is a sync task
  41. resolve();
  42. return;
  43. }
  44. if (typeof taskResult.then === 'function') {
  45. // this is a promise returning task
  46. taskResult.then(resolve, reject);
  47. return;
  48. }
  49. // this is a stream returning task
  50. taskResult.on('end', _ => resolve());
  51. taskResult.on('error', err => reject(err));
  52. });
  53. }
  54. function taskSeries(...tasks) {
  55. return async () => {
  56. for (let i = 0; i < tasks.length; i++) {
  57. await _execute(tasks[i]);
  58. }
  59. };
  60. }
  61. const cleanReleaseTask = function(cb) { rimraf('release', { maxBusyTries: 1 }, cb); };
  62. gulp.task('release', taskSeries(cleanReleaseTask, function() {
  63. return es.merge(
  64. // dev folder
  65. releaseOne('dev'),
  66. // min folder
  67. releaseOne('min'),
  68. // esm folder
  69. ESM_release(),
  70. // package.json
  71. gulp.src('package.json')
  72. .pipe(es.through(function(data) {
  73. var json = JSON.parse(data.contents.toString());
  74. json.private = false;
  75. data.contents = Buffer.from(JSON.stringify(json, null, ' '));
  76. this.emit('data', data);
  77. }))
  78. .pipe(gulp.dest('release')),
  79. gulp.src('CHANGELOG.md')
  80. .pipe(gulp.dest('release')),
  81. // min-maps folder
  82. gulp.src('node_modules/monaco-editor-core/min-maps/**/*')
  83. .pipe(gulp.dest('release/min-maps')),
  84. // other files
  85. gulp.src([
  86. 'node_modules/monaco-editor-core/LICENSE',
  87. 'node_modules/monaco-editor-core/monaco.d.ts',
  88. 'node_modules/monaco-editor-core/ThirdPartyNotices.txt',
  89. 'README.md'
  90. ])
  91. .pipe(addPluginDTS())
  92. .pipe(addPluginThirdPartyNotices())
  93. .pipe(gulp.dest('release'))
  94. )
  95. }));
  96. /**
  97. * Release to `dev` or `min`.
  98. */
  99. function releaseOne(type) {
  100. return es.merge(
  101. gulp.src('node_modules/monaco-editor-core/' + type + '/**/*')
  102. .pipe(addPluginContribs(type))
  103. .pipe(gulp.dest('release/' + type)),
  104. pluginStreams(type, 'release/' + type + '/')
  105. )
  106. }
  107. /**
  108. * Release plugins to `dev` or `min`.
  109. */
  110. function pluginStreams(type, destinationPath) {
  111. return es.merge(
  112. metadata.METADATA.PLUGINS.map(function(plugin) {
  113. return pluginStream(plugin, type, destinationPath);
  114. })
  115. );
  116. }
  117. /**
  118. * Release a plugin to `dev` or `min`.
  119. */
  120. function pluginStream(plugin, type, destinationPath) {
  121. var pluginPath = plugin.paths[`npm/${type}`]; // npm/dev or npm/min
  122. var contribPath = path.join(pluginPath, plugin.contrib.substr(plugin.modulePrefix.length)) + '.js';
  123. return (
  124. gulp.src([
  125. pluginPath + '/**/*',
  126. '!' + contribPath
  127. ])
  128. .pipe(es.through(function(data) {
  129. if (!/_\.contribution/.test(data.path)) {
  130. this.emit('data', data);
  131. return;
  132. }
  133. let contents = data.contents.toString();
  134. contents = contents.replace('define(["require", "exports"],', 'define(["require", "exports", "vs/editor/editor.api"],');
  135. data.contents = Buffer.from(contents);
  136. this.emit('data', data);
  137. }))
  138. .pipe(gulp.dest(destinationPath + plugin.modulePrefix))
  139. );
  140. }
  141. /**
  142. * Edit editor.main.js:
  143. * - rename the AMD module 'vs/editor/editor.main' to 'vs/editor/edcore.main'
  144. * - append monaco.contribution modules from plugins
  145. * - append new AMD module 'vs/editor/editor.main' that stiches things together
  146. */
  147. function addPluginContribs(type) {
  148. return es.through(function(data) {
  149. if (!/editor\.main\.js$/.test(data.path)) {
  150. this.emit('data', data);
  151. return;
  152. }
  153. var contents = data.contents.toString();
  154. // Rename the AMD module 'vs/editor/editor.main' to 'vs/editor/edcore.main'
  155. contents = contents.replace(/"vs\/editor\/editor\.main\"/, '"vs/editor/edcore.main"');
  156. var extraContent = [];
  157. var allPluginsModuleIds = [];
  158. metadata.METADATA.PLUGINS.forEach(function(plugin) {
  159. allPluginsModuleIds.push(plugin.contrib);
  160. var pluginPath = plugin.paths[`npm/${type}`]; // npm/dev or npm/min
  161. var contribPath = path.join(__dirname, pluginPath, plugin.contrib.substr(plugin.modulePrefix.length)) + '.js';
  162. var contribContents = fs.readFileSync(contribPath).toString();
  163. contribContents = contribContents.replace(
  164. /define\((['"][a-z\/\-]+\/fillers\/monaco-editor-core['"]),\[\],/,
  165. 'define($1,[\'vs/editor/editor.api\'],'
  166. );
  167. extraContent.push(contribContents);
  168. });
  169. extraContent.push(`define("vs/editor/editor.main", ["vs/editor/edcore.main","${allPluginsModuleIds.join('","')}"], function(api) { return api; });`);
  170. var insertIndex = contents.lastIndexOf('//# sourceMappingURL=');
  171. if (insertIndex === -1) {
  172. insertIndex = contents.length;
  173. }
  174. contents = contents.substring(0, insertIndex) + '\n' + extraContent.join('\n') + '\n' + contents.substring(insertIndex);
  175. data.contents = Buffer.from(contents);
  176. this.emit('data', data);
  177. });
  178. }
  179. function ESM_release() {
  180. return es.merge(
  181. gulp.src([
  182. 'node_modules/monaco-editor-core/esm/**/*',
  183. // we will create our own editor.api.d.ts which also contains the plugins API
  184. '!node_modules/monaco-editor-core/esm/vs/editor/editor.api.d.ts'
  185. ])
  186. .pipe(ESM_addImportSuffix())
  187. .pipe(ESM_addPluginContribs('release/esm'))
  188. .pipe(gulp.dest('release/esm')),
  189. ESM_pluginStreams('release/esm/')
  190. )
  191. }
  192. /**
  193. * Release plugins to `esm`.
  194. */
  195. function ESM_pluginStreams(destinationPath) {
  196. return es.merge(
  197. metadata.METADATA.PLUGINS.map(function(plugin) {
  198. return ESM_pluginStream(plugin, destinationPath);
  199. })
  200. );
  201. }
  202. /**
  203. * Release a plugin to `esm`.
  204. * Adds a dependency to 'vs/editor/editor.api' in contrib files in order for `monaco` to be defined.
  205. * Rewrites imports for 'monaco-editor-core/**'
  206. */
  207. function ESM_pluginStream(plugin, destinationPath) {
  208. const DESTINATION = path.join(__dirname, destinationPath);
  209. let pluginPath = plugin.paths[`esm`];
  210. return (
  211. gulp.src([
  212. pluginPath + '/**/*'
  213. ])
  214. .pipe(es.through(function(data) {
  215. if (!/(\.js$)|(\.ts$)/.test(data.path)) {
  216. this.emit('data', data);
  217. return;
  218. }
  219. let contents = data.contents.toString();
  220. const info = ts.preProcessFile(contents);
  221. for (let i = info.importedFiles.length - 1; i >= 0; i--) {
  222. let importText = info.importedFiles[i].fileName;
  223. const pos = info.importedFiles[i].pos;
  224. const end = info.importedFiles[i].end;
  225. if (!/(^\.\/)|(^\.\.\/)/.test(importText)) {
  226. // non-relative import
  227. if (!/^monaco-editor-core/.test(importText)) {
  228. console.error(`Non-relative import for unknown module: ${importText} in ${data.path}`);
  229. process.exit(0);
  230. }
  231. if (importText === 'monaco-editor-core') {
  232. importText = 'monaco-editor-core/esm/vs/editor/editor.api';
  233. }
  234. const myFileDestPath = path.join(DESTINATION, plugin.modulePrefix, data.relative);
  235. const importFilePath = path.join(DESTINATION, importText.substr('monaco-editor-core/esm/'.length));
  236. let relativePath = path.relative(path.dirname(myFileDestPath), importFilePath).replace(/\\/g, '/');
  237. if (!/(^\.\/)|(^\.\.\/)/.test(relativePath)) {
  238. relativePath = './' + relativePath;
  239. }
  240. contents = (
  241. contents.substring(0, pos + 1)
  242. + relativePath
  243. + contents.substring(end + 1)
  244. );
  245. }
  246. }
  247. contents = contents.replace(/\/\/# sourceMappingURL=.*((\r?\n)|$)/g, '');
  248. data.contents = Buffer.from(contents);
  249. this.emit('data', data);
  250. }))
  251. .pipe(es.through(function(data) {
  252. if (!/monaco\.contribution\.js$/.test(data.path)) {
  253. this.emit('data', data);
  254. return;
  255. }
  256. const myFileDestPath = path.join(DESTINATION, plugin.modulePrefix, data.relative);
  257. const apiFilePath = path.join(DESTINATION, 'vs/editor/editor.api');
  258. let relativePath = path.relative(path.dirname(myFileDestPath), apiFilePath).replace(/\\/g, '/');
  259. if (!/(^\.\/)|(^\.\.\/)/.test(relativePath)) {
  260. relativePath = './' + relativePath;
  261. }
  262. let contents = data.contents.toString();
  263. contents = (
  264. `import '${relativePath}';\n` +
  265. contents
  266. );
  267. data.contents = Buffer.from(contents);
  268. this.emit('data', data);
  269. }))
  270. .pipe(ESM_addImportSuffix())
  271. .pipe(gulp.dest(destinationPath + plugin.modulePrefix))
  272. );
  273. }
  274. function ESM_addImportSuffix() {
  275. return es.through(function(data) {
  276. if (!/\.js$/.test(data.path)) {
  277. this.emit('data', data);
  278. return;
  279. }
  280. let contents = data.contents.toString();
  281. const info = ts.preProcessFile(contents);
  282. for (let i = info.importedFiles.length - 1; i >= 0; i--) {
  283. const importText = info.importedFiles[i].fileName;
  284. const pos = info.importedFiles[i].pos;
  285. const end = info.importedFiles[i].end;
  286. if (/\.css$/.test(importText)) {
  287. continue;
  288. }
  289. contents = (
  290. contents.substring(0, pos + 1)
  291. + importText + '.js'
  292. + contents.substring(end + 1)
  293. );
  294. }
  295. data.contents = Buffer.from(contents);
  296. this.emit('data', data);
  297. });
  298. }
  299. /**
  300. * - Rename esm/vs/editor/editor.main.js to esm/vs/editor/edcore.main.js
  301. * - Create esm/vs/editor/editor.main.js that that stiches things together
  302. */
  303. function ESM_addPluginContribs(dest) {
  304. const DESTINATION = path.join(__dirname, dest);
  305. return es.through(function(data) {
  306. if (!/editor\.main\.js$/.test(data.path)) {
  307. this.emit('data', data);
  308. return;
  309. }
  310. this.emit('data', new File({
  311. path: data.path.replace(/editor\.main/, 'edcore.main'),
  312. base: data.base,
  313. contents: data.contents
  314. }));
  315. const mainFileDestPath = path.join(DESTINATION, 'vs/editor/editor.main.js');
  316. let mainFileImports = [];
  317. metadata.METADATA.PLUGINS.forEach(function(plugin) {
  318. const contribDestPath = path.join(DESTINATION, plugin.contrib);
  319. let relativePath = path.relative(path.dirname(mainFileDestPath), contribDestPath).replace(/\\/g, '/');
  320. if (!/(^\.\/)|(^\.\.\/)/.test(relativePath)) {
  321. relativePath = './' + relativePath;
  322. }
  323. mainFileImports.push(relativePath);
  324. });
  325. let mainFileContents = (
  326. mainFileImports.map((name) => `import '${name}';`).join('\n')
  327. + `\n\nexport * from './edcore.main';`
  328. );
  329. this.emit('data', new File({
  330. path: data.path,
  331. base: data.base,
  332. contents: Buffer.from(mainFileContents)
  333. }));
  334. });
  335. }
  336. /**
  337. * Edit monaco.d.ts:
  338. * - append monaco.d.ts from plugins
  339. */
  340. function addPluginDTS() {
  341. return es.through(function(data) {
  342. if (!/monaco\.d\.ts$/.test(data.path)) {
  343. this.emit('data', data);
  344. return;
  345. }
  346. var contents = data.contents.toString();
  347. var extraContent = [];
  348. metadata.METADATA.PLUGINS.forEach(function(plugin) {
  349. var pluginPath = plugin.paths[`npm/min`]; // npm/dev or npm/min
  350. var dtsPath = path.join(pluginPath, '../monaco.d.ts');
  351. try {
  352. let plugindts = fs.readFileSync(dtsPath).toString();
  353. plugindts = plugindts.replace(/\/\/\/ <reference.*\n/m, '');
  354. extraContent.push(plugindts);
  355. } catch (err) {
  356. return;
  357. }
  358. });
  359. contents = [
  360. '/*!-----------------------------------------------------------',
  361. ' * Copyright (c) Microsoft Corporation. All rights reserved.',
  362. ' * Type definitions for monaco-editor',
  363. ' * Released under the MIT license',
  364. '*-----------------------------------------------------------*/',
  365. ].join('\n') + '\n' + contents + '\n' + extraContent.join('\n');
  366. // Ensure consistent indentation and line endings
  367. contents = cleanFile(contents);
  368. data.contents = Buffer.from(contents);
  369. this.emit('data', new File({
  370. path: path.join(path.dirname(data.path), 'esm/vs/editor/editor.api.d.ts'),
  371. base: data.base,
  372. contents: Buffer.from(toExternalDTS(contents))
  373. }));
  374. fs.writeFileSync('website/playground/monaco.d.ts.txt', contents);
  375. fs.writeFileSync('typedoc/monaco.d.ts', contents);
  376. this.emit('data', data);
  377. });
  378. }
  379. function toExternalDTS(contents) {
  380. let lines = contents.split(/\r\n|\r|\n/);
  381. let killNextCloseCurlyBrace = false;
  382. for (let i = 0; i < lines.length; i++) {
  383. let line = lines[i];
  384. if (killNextCloseCurlyBrace) {
  385. if ('}' === line) {
  386. lines[i] = '';
  387. killNextCloseCurlyBrace = false;
  388. continue;
  389. }
  390. if (line.indexOf(' ') === 0) {
  391. lines[i] = line.substr(4);
  392. } else if (line.charAt(0) === '\t') {
  393. lines[i] = line.substr(1);
  394. }
  395. continue;
  396. }
  397. if ('declare namespace monaco {' === line) {
  398. lines[i] = '';
  399. killNextCloseCurlyBrace = true;
  400. continue;
  401. }
  402. if (line.indexOf('declare namespace monaco.') === 0) {
  403. lines[i] = line.replace('declare namespace monaco.', 'export namespace ');
  404. }
  405. if (line.indexOf('declare let MonacoEnvironment') === 0) {
  406. lines[i] = `declare global {\n let MonacoEnvironment: Environment | undefined;\n}`;
  407. }
  408. if (line.indexOf(' MonacoEnvironment?') === 0) {
  409. lines[i] = ` MonacoEnvironment?: Environment | undefined;`;
  410. }
  411. }
  412. return lines.join('\n').replace(/\n\n\n+/g, '\n\n');
  413. }
  414. /**
  415. * Normalize line endings and ensure consistent 4 spaces indentation
  416. */
  417. function cleanFile(contents) {
  418. return contents.split(/\r\n|\r|\n/).map(function(line) {
  419. var m = line.match(/^(\t+)/);
  420. if (!m) {
  421. return line;
  422. }
  423. var tabsCount = m[1].length;
  424. var newIndent = '';
  425. for (var i = 0; i < 4 * tabsCount; i++) {
  426. newIndent += ' ';
  427. }
  428. return newIndent + line.substring(tabsCount);
  429. }).join('\n');
  430. }
  431. /**
  432. * Edit ThirdPartyNotices.txt:
  433. * - append ThirdPartyNotices.txt from plugins
  434. */
  435. function addPluginThirdPartyNotices() {
  436. return es.through(function(data) {
  437. if (!/ThirdPartyNotices\.txt$/.test(data.path)) {
  438. this.emit('data', data);
  439. return;
  440. }
  441. var contents = data.contents.toString();
  442. var extraContent = [];
  443. metadata.METADATA.PLUGINS.forEach(function(plugin) {
  444. if (!plugin.thirdPartyNotices) {
  445. return;
  446. }
  447. console.log('ADDING ThirdPartyNotices from ' + plugin.thirdPartyNotices);
  448. var thirdPartyNoticeContent = fs.readFileSync(plugin.thirdPartyNotices).toString();
  449. thirdPartyNoticeContent = thirdPartyNoticeContent.split('\n').slice(8).join('\n');
  450. extraContent.push(thirdPartyNoticeContent);
  451. });
  452. contents += '\n' + extraContent.join('\n');
  453. data.contents = Buffer.from(contents);
  454. this.emit('data', data);
  455. });
  456. }
  457. // --- website
  458. const cleanWebsiteTask = function(cb) { rimraf('../monaco-editor-website', { maxBusyTries: 1 }, cb); };
  459. const buildWebsiteTask = taskSeries(cleanWebsiteTask, function() {
  460. function replaceWithRelativeResource(dataPath, contents, regex, callback) {
  461. return contents.replace(regex, function(_, m0) {
  462. var filePath = path.join(path.dirname(dataPath), m0);
  463. return callback(m0, fs.readFileSync(filePath));
  464. });
  465. }
  466. var waiting = 0;
  467. var done = false;
  468. return (
  469. es.merge(
  470. gulp.src([
  471. 'website/**/*'
  472. ], { dot: true })
  473. .pipe(es.through(function(data) {
  474. if (!data.contents || !/\.(html)$/.test(data.path) || /new-samples/.test(data.path)) {
  475. return this.emit('data', data);
  476. }
  477. var contents = data.contents.toString();
  478. contents = contents.replace(/\.\.\/release\/dev/g, 'node_modules/monaco-editor/min');
  479. contents = contents.replace(/{{version}}/g, MONACO_EDITOR_VERSION);
  480. contents = contents.replace(/{{year}}/g, new Date().getFullYear());
  481. // Preload xhr contents
  482. contents = replaceWithRelativeResource(data.path, contents, /<pre data-preload="([^"]+)".*/g, function(m0, fileContents) {
  483. return (
  484. '<pre data-preload="' + m0 + '" style="display:none">'
  485. + fileContents.toString('utf8')
  486. .replace(/&/g, '&amp;')
  487. .replace(/</g, '&lt;')
  488. .replace(/>/g, '&gt;')
  489. + '</pre>'
  490. );
  491. });
  492. // Inline fork.png
  493. contents = replaceWithRelativeResource(data.path, contents, /src="(\.\/fork.png)"/g, function(m0, fileContents) {
  494. return (
  495. 'src="data:image/png;base64,' + fileContents.toString('base64') + '"'
  496. );
  497. });
  498. var allCSS = '';
  499. var tmpcontents = replaceWithRelativeResource(data.path, contents, /<link data-inline="yes-please" href="([^"]+)".*/g, function(m0, fileContents) {
  500. allCSS += fileContents.toString('utf8');
  501. return '';
  502. });
  503. tmpcontents = tmpcontents.replace(/<script.*/g, '');
  504. tmpcontents = tmpcontents.replace(/<link.*/g, '');
  505. waiting++;
  506. uncss(tmpcontents, {
  507. raw: allCSS,
  508. ignore: [/\.alert\b/, /\.alert-error\b/, /\.playground-page\b/]
  509. }, function(err, output) {
  510. waiting--;
  511. if (!err) {
  512. output = new CleanCSS().minify(output).styles;
  513. var isFirst = true;
  514. contents = contents.replace(/<link data-inline="yes-please" href="([^"]+)".*/g, function(_, m0) {
  515. if (isFirst) {
  516. isFirst = false;
  517. return '<style>' + output + '</style>';
  518. }
  519. return '';
  520. });
  521. }
  522. // Inline javascript
  523. contents = replaceWithRelativeResource(data.path, contents, /<script data-inline="yes-please" src="([^"]+)".*/g, function(m0, fileContents) {
  524. return '<script>' + fileContents.toString('utf8') + '</script>';
  525. });
  526. data.contents = Buffer.from(contents.split(/\r\n|\r|\n/).join('\n'));
  527. this.emit('data', data);
  528. if (done && waiting === 0) {
  529. this.emit('end');
  530. }
  531. }.bind(this));
  532. }, function() {
  533. done = true;
  534. if (waiting === 0) {
  535. this.emit('end');
  536. }
  537. }))
  538. .pipe(gulp.dest('../monaco-editor-website'))
  539. )
  540. .pipe(es.through(function(data) {
  541. this.emit('data', data);
  542. }, function() {
  543. // temporarily create package.json so that npm install doesn't bark
  544. fs.writeFileSync('../monaco-editor-website/package.json', '{}');
  545. fs.writeFileSync('../monaco-editor-website/.nojekyll', '');
  546. cp.execSync('npm install monaco-editor', {
  547. cwd: path.join(__dirname, '../monaco-editor-website')
  548. });
  549. fs.unlinkSync('../monaco-editor-website/package.json');
  550. this.emit('end');
  551. }))
  552. );
  553. });
  554. gulp.task('build-website', buildWebsiteTask);
  555. gulp.task('prepare-website-branch', async function() {
  556. cp.execSync('git init', {
  557. cwd: path.join(__dirname, '../monaco-editor-website')
  558. });
  559. let remoteUrl = cp.execSync('git remote get-url origin')
  560. let committerUserName = cp.execSync('git log --format=\'%an\' -1');
  561. let committerEmail = cp.execSync('git log --format=\'%ae\' -1');
  562. cp.execSync(`git config user.name ${committerUserName}`, {
  563. cwd: path.join(__dirname, '../monaco-editor-website')
  564. });
  565. cp.execSync(`git config user.email ${committerEmail}`, {
  566. cwd: path.join(__dirname, '../monaco-editor-website')
  567. });
  568. cp.execSync(`git remote add origin ${remoteUrl}`, {
  569. cwd: path.join(__dirname, '../monaco-editor-website')
  570. });
  571. cp.execSync('git checkout -b gh-pages', {
  572. cwd: path.join(__dirname, '../monaco-editor-website')
  573. });
  574. cp.execSync('git add .', {
  575. cwd: path.join(__dirname, '../monaco-editor-website')
  576. });
  577. cp.execSync('git commit -m "Publish website"', {
  578. cwd: path.join(__dirname, '../monaco-editor-website')
  579. });
  580. console.log('RUN monaco-editor-website>git push origin gh-pages --force');
  581. });
  582. const generateTestSamplesTask = function() {
  583. var sampleNames = fs.readdirSync(path.join(__dirname, 'test/samples'));
  584. var samples = sampleNames.map(function(sampleName) {
  585. var samplePath = path.join(__dirname, 'test/samples', sampleName);
  586. var sampleContent = fs.readFileSync(samplePath).toString();
  587. return {
  588. name: sampleName,
  589. content: sampleContent
  590. };
  591. });
  592. var prefix = '//This is a generated file via gulp generate-test-samples\ndefine([], function() { return';
  593. var suffix = '; });'
  594. fs.writeFileSync(path.join(__dirname, 'test/samples-all.generated.js'), prefix + JSON.stringify(samples, null, '\t') + suffix );
  595. var PLAY_SAMPLES = require(path.join(WEBSITE_GENERATED_PATH, 'all.js')).PLAY_SAMPLES;
  596. var locations = [];
  597. for (var i = 0; i < PLAY_SAMPLES.length; i++) {
  598. var sample = PLAY_SAMPLES[i];
  599. var sampleId = sample.id;
  600. var samplePath = path.join(WEBSITE_GENERATED_PATH, sample.path);
  601. var html = fs.readFileSync(path.join(samplePath, 'sample.html'));
  602. var js = fs.readFileSync(path.join(samplePath, 'sample.js'));
  603. var css = fs.readFileSync(path.join(samplePath, 'sample.css'));
  604. var result = [
  605. '<!DOCTYPE html>',
  606. '<!-- THIS IS A GENERATED FILE VIA gulp generate-test-samples -->',
  607. '<html>',
  608. '<head>',
  609. ' <base href="..">',
  610. ' <meta http-equiv="Content-Type" content="text/html;charset=utf-8" />',
  611. '</head>',
  612. '<body>',
  613. '<style>',
  614. '/*----------------------------------------SAMPLE CSS START*/',
  615. '',
  616. css,
  617. '',
  618. '/*----------------------------------------SAMPLE CSS END*/',
  619. '</style>',
  620. '<a class="loading-opts" href="playground.generated/index.html">[&lt;&lt; BACK]</a> <br/>',
  621. 'THIS IS A GENERATED FILE VIA gulp generate-test-samples',
  622. '',
  623. '<div id="bar" style="margin-bottom: 6px;"></div>',
  624. '',
  625. '<div style="clear:both"></div>',
  626. '<div id="outer-container" style="width:800px;height:450px;border: 1px solid grey">',
  627. '<!-- ----------------------------------------SAMPLE HTML START-->',
  628. '',
  629. html,
  630. '',
  631. '<!-- ----------------------------------------SAMPLE HTML END-->',
  632. '</div>',
  633. '<div style="clear:both"></div>',
  634. '',
  635. '<script src="../metadata.js"></script>',
  636. '<script src="dev-setup.js"></script>',
  637. '<script>',
  638. 'loadEditor(function() {',
  639. '/*----------------------------------------SAMPLE JS START*/',
  640. '',
  641. js,
  642. '',
  643. '/*----------------------------------------SAMPLE JS END*/',
  644. '});',
  645. '</script>',
  646. '</body>',
  647. '</html>',
  648. ];
  649. fs.writeFileSync(path.join(__dirname, 'test/playground.generated/' + sampleId + '.html'), result.join('\n'));
  650. locations.push({
  651. path: sampleId + '.html',
  652. name: sample.chapter + ' &gt; ' + sample.name
  653. })
  654. }
  655. var index = [
  656. '<!DOCTYPE html>',
  657. '<!-- THIS IS A GENERATED FILE VIA gulp generate-test-samples -->',
  658. '<html>',
  659. '<head>',
  660. ' <base href="..">',
  661. '</head>',
  662. '<body>',
  663. '<a class="loading-opts" href="index.html">[&lt;&lt; BACK]</a><br/>',
  664. 'THIS IS A GENERATED FILE VIA gulp generate-test-samples<br/><br/>',
  665. locations.map(function(location) {
  666. return '<a class="loading-opts" href="playground.generated/' + location.path + '">' + location.name + '</a>';
  667. }).join('<br/>\n'),
  668. '<script src="../metadata.js"></script>',
  669. '<script src="dev-setup.js"></script>',
  670. '</body>',
  671. '</html>',
  672. ]
  673. fs.writeFileSync(path.join(__dirname, 'test/playground.generated/index.html'), index.join('\n'));
  674. };
  675. function createSimpleServer(rootDir, port) {
  676. yaserver.createServer({
  677. rootDir: rootDir
  678. }).then((staticServer) => {
  679. const server = http.createServer((request, response) => {
  680. return staticServer.handle(request, response);
  681. });
  682. server.listen(port, '127.0.0.1', () => {
  683. console.log(`Running at http://127.0.0.1:${port}`);
  684. });
  685. });
  686. }
  687. gulp.task('generate-test-samples', taskSeries(generateTestSamplesTask));
  688. gulp.task('simpleserver', taskSeries(generateTestSamplesTask, function() {
  689. const SERVER_ROOT = path.normalize(path.join(__dirname, '../'));
  690. createSimpleServer(SERVER_ROOT, 8080);
  691. createSimpleServer(SERVER_ROOT, 8088);
  692. }));