utils.js 7.6 KB

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