utils.js 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  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. if (line === 'export {};') {
  131. continue;
  132. }
  133. line = line.replace(/ /g, '\t');
  134. line = line.replace(/declare /g, '');
  135. if (line.length > 0) {
  136. line = `\t${line}`;
  137. result.push(line);
  138. }
  139. }
  140. result.push(`}`);
  141. result.push(``);
  142. fs.writeFileSync(destination, result.join('\n'));
  143. prettier(_destination);
  144. }
  145. exports.dts = dts;
  146. /**
  147. * @param {import('esbuild').BuildOptions} options
  148. */
  149. function build(options) {
  150. esbuild.build(options).then((result) => {
  151. if (result.errors.length > 0) {
  152. console.error(result.errors);
  153. }
  154. if (result.warnings.length > 0) {
  155. console.error(result.warnings);
  156. }
  157. });
  158. }
  159. exports.build = build;
  160. /**
  161. * @param {{
  162. * base: string;
  163. * entryPoints: string[];
  164. * external: string[];
  165. * }} options
  166. */
  167. function buildESM(options) {
  168. build({
  169. entryPoints: options.entryPoints.map(e => (`${options.base}/${e}`)),
  170. bundle: true,
  171. target: 'esnext',
  172. format: 'esm',
  173. define: {
  174. AMD: 'false'
  175. },
  176. banner: {
  177. js: bundledFileHeader
  178. },
  179. external: options.external,
  180. outbase: `${options.base}/src`,
  181. outdir: `${options.base}/release/esm/`,
  182. plugins: [
  183. alias({
  184. 'vscode-nls': path.join(__dirname, 'fillers/vscode-nls.ts')
  185. })
  186. ]
  187. });
  188. }
  189. exports.buildESM = buildESM;
  190. /**
  191. * @param {'dev'|'min'} type
  192. * @param {{
  193. * base: string;
  194. * entryPoint: string;
  195. * banner: string;
  196. * }} options
  197. */
  198. function buildOneAMD(type, options) {
  199. /** @type {import('esbuild').BuildOptions} */
  200. const opts = {
  201. entryPoints: [`${options.base}/${options.entryPoint}`],
  202. bundle: true,
  203. target: 'esnext',
  204. format: 'iife',
  205. define: {
  206. AMD: 'true'
  207. },
  208. globalName: 'moduleExports',
  209. banner: {
  210. js: `${bundledFileHeader}${options.banner}`
  211. },
  212. footer: {
  213. js: 'return moduleExports;\n});'
  214. },
  215. outbase: `${options.base}/src`,
  216. outdir: `${options.base}/release/${type}/`,
  217. plugins: [
  218. alias({
  219. 'vscode-nls': path.join(__dirname, '../build/fillers/vscode-nls.ts'),
  220. 'monaco-editor-core': path.join(__dirname, '../build/fillers/monaco-editor-core-amd.ts')
  221. })
  222. ]
  223. };
  224. if (type === 'min') {
  225. opts.minify = true;
  226. }
  227. build(opts);
  228. }
  229. /**
  230. * @param {{
  231. * base: string;
  232. * entryPoint: string;
  233. * banner: string;
  234. * }} options
  235. */
  236. function buildAMD(options) {
  237. buildOneAMD('dev', options);
  238. buildOneAMD('min', options);
  239. }
  240. exports.buildAMD = buildAMD;
  241. function getGitVersion() {
  242. const git = path.join(REPO_ROOT, '.git');
  243. const headPath = path.join(git, 'HEAD');
  244. let head;
  245. try {
  246. head = fs.readFileSync(headPath, 'utf8').trim();
  247. } catch (e) {
  248. return void 0;
  249. }
  250. if (/^[0-9a-f]{40}$/i.test(head)) {
  251. return head;
  252. }
  253. const refMatch = /^ref: (.*)$/.exec(head);
  254. if (!refMatch) {
  255. return void 0;
  256. }
  257. const ref = refMatch[1];
  258. const refPath = path.join(git, ref);
  259. try {
  260. return fs.readFileSync(refPath, 'utf8').trim();
  261. } catch (e) {
  262. // noop
  263. }
  264. const packedRefsPath = path.join(git, 'packed-refs');
  265. let refsRaw;
  266. try {
  267. refsRaw = fs.readFileSync(packedRefsPath, 'utf8').trim();
  268. } catch (e) {
  269. return void 0;
  270. }
  271. const refsRegex = /^([0-9a-f]{40})\s+(.+)$/gm;
  272. let refsMatch;
  273. const refs = {};
  274. while ((refsMatch = refsRegex.exec(refsRaw))) {
  275. refs[refsMatch[2]] = refsMatch[1];
  276. }
  277. return refs[ref];
  278. }
  279. const bundledFileHeader = (() => {
  280. const sha1 = getGitVersion();
  281. const semver = require('../package.json').version;
  282. const headerVersion = semver + '(' + sha1 + ')';
  283. const BUNDLED_FILE_HEADER = [
  284. '/*!-----------------------------------------------------------------------------',
  285. ' * Copyright (c) Microsoft Corporation. All rights reserved.',
  286. ' * Version: ' + headerVersion,
  287. ' * Released under the MIT license',
  288. ' * https://github.com/microsoft/monaco-editor/blob/main/LICENSE.txt',
  289. ' *-----------------------------------------------------------------------------*/',
  290. ''
  291. ].join('\n');
  292. return BUNDLED_FILE_HEADER;
  293. })();
  294. exports.bundledFileHeader = bundledFileHeader;