utils.js 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321
  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. //@ts-check
  6. const fs = require('fs');
  7. const path = require('path');
  8. const cp = require('child_process');
  9. const esbuild = require('esbuild');
  10. const alias = require('esbuild-plugin-alias');
  11. const REPO_ROOT = path.join(__dirname, '..');
  12. /**
  13. * Copy a file.
  14. *
  15. * @param {string} _source
  16. * @param {string} _destination
  17. */
  18. function copyFile(_source, _destination) {
  19. const source = path.join(REPO_ROOT, _source);
  20. const destination = path.join(REPO_ROOT, _destination);
  21. // ensure target dir
  22. (function () {
  23. /** @type {string[]} */
  24. const dirs = [];
  25. /** @type {string} */
  26. let dirname = path.dirname(destination);
  27. while (dirname.length > REPO_ROOT.length) {
  28. dirs.push(dirname);
  29. dirname = path.dirname(dirname);
  30. }
  31. dirs.reverse();
  32. dirs.forEach(function (dir) {
  33. try {
  34. fs.mkdirSync(dir);
  35. } catch (err) {}
  36. });
  37. })();
  38. fs.writeFileSync(destination, fs.readFileSync(source));
  39. console.log(`Copied ${_source} to ${_destination}`);
  40. }
  41. exports.copyFile = copyFile;
  42. /**
  43. * Remove a directory and all its contents.
  44. *
  45. * @param {string} _dirPath
  46. */
  47. function removeDir(_dirPath) {
  48. const dirPath = path.join(REPO_ROOT, _dirPath);
  49. if (!fs.existsSync(dirPath)) {
  50. return;
  51. }
  52. rmDir(dirPath);
  53. console.log(`Deleted ${_dirPath}`);
  54. /**
  55. * @param {string} dirPath
  56. */
  57. function rmDir(dirPath) {
  58. const entries = fs.readdirSync(dirPath);
  59. for (const entry of entries) {
  60. const filePath = path.join(dirPath, entry);
  61. if (fs.statSync(filePath).isFile()) {
  62. fs.unlinkSync(filePath);
  63. } else {
  64. rmDir(filePath);
  65. }
  66. }
  67. fs.rmdirSync(dirPath);
  68. }
  69. }
  70. exports.removeDir = removeDir;
  71. /**
  72. * Launch the typescript compiler synchronously over a project.
  73. *
  74. * @param {string} _projectPath
  75. */
  76. function tsc(_projectPath) {
  77. const projectPath = path.join(REPO_ROOT, _projectPath);
  78. console.log(`Launching compiler at ${_projectPath}...`);
  79. cp.spawnSync(
  80. process.execPath,
  81. [path.join(__dirname, '../node_modules/typescript/lib/tsc.js'), '-p', projectPath],
  82. { stdio: 'inherit' }
  83. );
  84. console.log(`Compiled ${_projectPath}`);
  85. }
  86. exports.tsc = tsc;
  87. /**
  88. * Launch prettier on a specific file.
  89. *
  90. * @param {string} _filePath
  91. */
  92. function prettier(_filePath) {
  93. const filePath = path.join(REPO_ROOT, _filePath);
  94. cp.spawnSync(
  95. process.execPath,
  96. [path.join(__dirname, '../node_modules/prettier/bin-prettier.js'), '--write', filePath],
  97. { stdio: 'inherit' }
  98. );
  99. console.log(`Ran prettier over ${_filePath}`);
  100. }
  101. exports.prettier = prettier;
  102. /**
  103. * Transform an external .d.ts file to an internal .d.ts file
  104. *
  105. * @param {string} _source
  106. * @param {string} _destination
  107. * @param {string} namespace
  108. */
  109. function dts(_source, _destination, namespace) {
  110. const source = path.join(REPO_ROOT, _source);
  111. const destination = path.join(REPO_ROOT, _destination);
  112. const lines = fs
  113. .readFileSync(source)
  114. .toString()
  115. .split(/\r\n|\r|\n/);
  116. let result = [
  117. `/*---------------------------------------------------------------------------------------------`,
  118. ` * Copyright (c) Microsoft Corporation. All rights reserved.`,
  119. ` * Licensed under the MIT License. See License.txt in the project root for license information.`,
  120. ` *--------------------------------------------------------------------------------------------*/`,
  121. ``,
  122. `/// <reference path="../node_modules/monaco-editor-core/monaco.d.ts" />`,
  123. ``,
  124. `declare namespace ${namespace} {`
  125. ];
  126. for (let line of lines) {
  127. if (/^import/.test(line)) {
  128. continue;
  129. }
  130. line = line.replace(/ /g, '\t');
  131. line = line.replace(/declare /g, '');
  132. if (line.length > 0) {
  133. line = `\t${line}`;
  134. result.push(line);
  135. }
  136. }
  137. result.push(`}`);
  138. result.push(``);
  139. fs.writeFileSync(destination, result.join('\n'));
  140. prettier(_destination);
  141. }
  142. exports.dts = dts;
  143. /**
  144. * @param {import('esbuild').BuildOptions} options
  145. */
  146. function build(options) {
  147. esbuild.build(options).then((result) => {
  148. if (result.errors.length > 0) {
  149. console.error(result.errors);
  150. }
  151. if (result.warnings.length > 0) {
  152. console.error(result.warnings);
  153. }
  154. });
  155. }
  156. exports.build = build;
  157. /**
  158. * @param {{
  159. * entryPoints: string[];
  160. * external: string[];
  161. * }} options
  162. */
  163. function buildESM(options) {
  164. build({
  165. entryPoints: options.entryPoints,
  166. bundle: true,
  167. target: 'esnext',
  168. format: 'esm',
  169. define: {
  170. AMD: 'false'
  171. },
  172. external: options.external,
  173. outbase: 'src',
  174. outdir: 'release/esm/',
  175. plugins: [
  176. alias({
  177. 'vscode-nls': path.join(__dirname, 'fillers/vscode-nls.ts')
  178. })
  179. ]
  180. });
  181. }
  182. exports.buildESM = buildESM;
  183. /**
  184. * @param {'dev'|'min'} type
  185. * @param {{
  186. * entryPoint: string;
  187. * banner: string;
  188. * }} options
  189. */
  190. function buildOneAMD(type, options) {
  191. /** @type {import('esbuild').BuildOptions} */
  192. const opts = {
  193. entryPoints: [options.entryPoint],
  194. bundle: true,
  195. target: 'esnext',
  196. format: 'iife',
  197. define: {
  198. AMD: 'true'
  199. },
  200. globalName: 'moduleExports',
  201. banner: {
  202. js: options.banner
  203. },
  204. footer: {
  205. js: 'return moduleExports;\n});'
  206. },
  207. outbase: 'src',
  208. outdir: `release/${type}/`,
  209. plugins: [
  210. alias({
  211. 'vscode-nls': path.join(__dirname, '../build/fillers/vscode-nls.ts'),
  212. 'monaco-editor-core': path.join(__dirname, '../build/fillers/monaco-editor-core-amd.ts')
  213. })
  214. ]
  215. };
  216. if (type === 'min') {
  217. opts.minify = true;
  218. }
  219. build(opts);
  220. }
  221. /**
  222. * @param {{
  223. * entryPoint: string;
  224. * banner: string;
  225. * }} options
  226. */
  227. function buildAMD(options) {
  228. buildOneAMD('dev', options);
  229. buildOneAMD('min', options);
  230. }
  231. exports.buildAMD = buildAMD;
  232. function getGitVersion() {
  233. const git = path.join(REPO_ROOT, '.git');
  234. const headPath = path.join(git, 'HEAD');
  235. let head;
  236. try {
  237. head = fs.readFileSync(headPath, 'utf8').trim();
  238. } catch (e) {
  239. return void 0;
  240. }
  241. if (/^[0-9a-f]{40}$/i.test(head)) {
  242. return head;
  243. }
  244. const refMatch = /^ref: (.*)$/.exec(head);
  245. if (!refMatch) {
  246. return void 0;
  247. }
  248. const ref = refMatch[1];
  249. const refPath = path.join(git, ref);
  250. try {
  251. return fs.readFileSync(refPath, 'utf8').trim();
  252. } catch (e) {
  253. // noop
  254. }
  255. const packedRefsPath = path.join(git, 'packed-refs');
  256. let refsRaw;
  257. try {
  258. refsRaw = fs.readFileSync(packedRefsPath, 'utf8').trim();
  259. } catch (e) {
  260. return void 0;
  261. }
  262. const refsRegex = /^([0-9a-f]{40})\s+(.+)$/gm;
  263. let refsMatch;
  264. const refs = {};
  265. while ((refsMatch = refsRegex.exec(refsRaw))) {
  266. refs[refsMatch[2]] = refsMatch[1];
  267. }
  268. return refs[ref];
  269. }
  270. function getBundledFileHeader() {
  271. const sha1 = getGitVersion();
  272. const semver = require('../package.json').version;
  273. const headerVersion = semver + '(' + sha1 + ')';
  274. const BUNDLED_FILE_HEADER = [
  275. '/*!-----------------------------------------------------------------------------',
  276. ' * Copyright (c) Microsoft Corporation. All rights reserved.',
  277. ' * Version: ' + headerVersion,
  278. ' * Released under the MIT license',
  279. ' * https://github.com/microsoft/monaco-editor/blob/main/LICENSE.txt',
  280. ' *-----------------------------------------------------------------------------*/',
  281. ''
  282. ].join('\n');
  283. return BUNDLED_FILE_HEADER;
  284. }
  285. exports.getBundledFileHeader = getBundledFileHeader;