utils.ts 7.4 KB

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