watch-cli.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511
  1. /*
  2. @license
  3. Rollup.js v2.79.1
  4. Thu, 22 Sep 2022 04:55:29 GMT - commit 69ff4181e701a0fe0026d0ba147f31bc86beffa8
  5. https://github.com/rollup/rollup
  6. Released under the MIT License.
  7. */
  8. 'use strict';
  9. Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
  10. const require$$0$2 = require('fs');
  11. const process$2 = require('process');
  12. const index = require('./index.js');
  13. const cli = require('../bin/rollup');
  14. const rollup = require('./rollup.js');
  15. const require$$0 = require('assert');
  16. const require$$0$1 = require('events');
  17. const loadConfigFile_js = require('./loadConfigFile.js');
  18. const child_process = require('child_process');
  19. require('util');
  20. require('stream');
  21. require('path');
  22. require('os');
  23. require('./mergeOptions.js');
  24. require('perf_hooks');
  25. require('crypto');
  26. require('url');
  27. require('tty');
  28. function timeZone(date = new Date()) {
  29. const offset = date.getTimezoneOffset();
  30. const absOffset = Math.abs(offset);
  31. const hours = Math.floor(absOffset / 60);
  32. const minutes = absOffset % 60;
  33. const minutesOut = minutes > 0 ? ':' + ('0' + minutes).slice(-2) : '';
  34. return (offset < 0 ? '+' : '-') + hours + minutesOut;
  35. }
  36. function dateTime(options = {}) {
  37. let {
  38. date = new Date(),
  39. local = true,
  40. showTimeZone = false,
  41. showMilliseconds = false
  42. } = options;
  43. if (local) {
  44. // Offset the date so it will return the correct value when getting the ISO string.
  45. date = new Date(date.getTime() - (date.getTimezoneOffset() * 60000));
  46. }
  47. let end = '';
  48. if (showTimeZone) {
  49. end = ' UTC' + (local ? timeZone(date) : '');
  50. }
  51. if (showMilliseconds && date.getUTCMilliseconds() > 0) {
  52. end = ` ${date.getUTCMilliseconds()}ms${end}`;
  53. }
  54. return date
  55. .toISOString()
  56. .replace(/T/, ' ')
  57. .replace(/\..+/, end);
  58. }
  59. var signalExit = {exports: {}};
  60. var signals$1 = {exports: {}};
  61. var hasRequiredSignals;
  62. function requireSignals () {
  63. if (hasRequiredSignals) return signals$1.exports;
  64. hasRequiredSignals = 1;
  65. (function (module) {
  66. // This is not the set of all possible signals.
  67. //
  68. // It IS, however, the set of all signals that trigger
  69. // an exit on either Linux or BSD systems. Linux is a
  70. // superset of the signal names supported on BSD, and
  71. // the unknown signals just fail to register, so we can
  72. // catch that easily enough.
  73. //
  74. // Don't bother with SIGKILL. It's uncatchable, which
  75. // means that we can't fire any callbacks anyway.
  76. //
  77. // If a user does happen to register a handler on a non-
  78. // fatal signal like SIGWINCH or something, and then
  79. // exit, it'll end up firing `process.emit('exit')`, so
  80. // the handler will be fired anyway.
  81. //
  82. // SIGBUS, SIGFPE, SIGSEGV and SIGILL, when not raised
  83. // artificially, inherently leave the process in a
  84. // state from which it is not safe to try and enter JS
  85. // listeners.
  86. module.exports = [
  87. 'SIGABRT',
  88. 'SIGALRM',
  89. 'SIGHUP',
  90. 'SIGINT',
  91. 'SIGTERM'
  92. ];
  93. if (process.platform !== 'win32') {
  94. module.exports.push(
  95. 'SIGVTALRM',
  96. 'SIGXCPU',
  97. 'SIGXFSZ',
  98. 'SIGUSR2',
  99. 'SIGTRAP',
  100. 'SIGSYS',
  101. 'SIGQUIT',
  102. 'SIGIOT'
  103. // should detect profiler and enable/disable accordingly.
  104. // see #21
  105. // 'SIGPROF'
  106. );
  107. }
  108. if (process.platform === 'linux') {
  109. module.exports.push(
  110. 'SIGIO',
  111. 'SIGPOLL',
  112. 'SIGPWR',
  113. 'SIGSTKFLT',
  114. 'SIGUNUSED'
  115. );
  116. }
  117. } (signals$1));
  118. return signals$1.exports;
  119. }
  120. // Note: since nyc uses this module to output coverage, any lines
  121. // that are in the direct sync flow of nyc's outputCoverage are
  122. // ignored, since we can never get coverage for them.
  123. // grab a reference to node's real process object right away
  124. var process$1 = rollup.commonjsGlobal.process;
  125. const processOk = function (process) {
  126. return process &&
  127. typeof process === 'object' &&
  128. typeof process.removeListener === 'function' &&
  129. typeof process.emit === 'function' &&
  130. typeof process.reallyExit === 'function' &&
  131. typeof process.listeners === 'function' &&
  132. typeof process.kill === 'function' &&
  133. typeof process.pid === 'number' &&
  134. typeof process.on === 'function'
  135. };
  136. // some kind of non-node environment, just no-op
  137. /* istanbul ignore if */
  138. if (!processOk(process$1)) {
  139. signalExit.exports = function () {
  140. return function () {}
  141. };
  142. } else {
  143. var assert = require$$0;
  144. var signals = requireSignals();
  145. var isWin = /^win/i.test(process$1.platform);
  146. var EE = require$$0$1;
  147. /* istanbul ignore if */
  148. if (typeof EE !== 'function') {
  149. EE = EE.EventEmitter;
  150. }
  151. var emitter;
  152. if (process$1.__signal_exit_emitter__) {
  153. emitter = process$1.__signal_exit_emitter__;
  154. } else {
  155. emitter = process$1.__signal_exit_emitter__ = new EE();
  156. emitter.count = 0;
  157. emitter.emitted = {};
  158. }
  159. // Because this emitter is a global, we have to check to see if a
  160. // previous version of this library failed to enable infinite listeners.
  161. // I know what you're about to say. But literally everything about
  162. // signal-exit is a compromise with evil. Get used to it.
  163. if (!emitter.infinite) {
  164. emitter.setMaxListeners(Infinity);
  165. emitter.infinite = true;
  166. }
  167. signalExit.exports = function (cb, opts) {
  168. /* istanbul ignore if */
  169. if (!processOk(rollup.commonjsGlobal.process)) {
  170. return function () {}
  171. }
  172. assert.equal(typeof cb, 'function', 'a callback must be provided for exit handler');
  173. if (loaded === false) {
  174. load();
  175. }
  176. var ev = 'exit';
  177. if (opts && opts.alwaysLast) {
  178. ev = 'afterexit';
  179. }
  180. var remove = function () {
  181. emitter.removeListener(ev, cb);
  182. if (emitter.listeners('exit').length === 0 &&
  183. emitter.listeners('afterexit').length === 0) {
  184. unload();
  185. }
  186. };
  187. emitter.on(ev, cb);
  188. return remove
  189. };
  190. var unload = function unload () {
  191. if (!loaded || !processOk(rollup.commonjsGlobal.process)) {
  192. return
  193. }
  194. loaded = false;
  195. signals.forEach(function (sig) {
  196. try {
  197. process$1.removeListener(sig, sigListeners[sig]);
  198. } catch (er) {}
  199. });
  200. process$1.emit = originalProcessEmit;
  201. process$1.reallyExit = originalProcessReallyExit;
  202. emitter.count -= 1;
  203. };
  204. signalExit.exports.unload = unload;
  205. var emit = function emit (event, code, signal) {
  206. /* istanbul ignore if */
  207. if (emitter.emitted[event]) {
  208. return
  209. }
  210. emitter.emitted[event] = true;
  211. emitter.emit(event, code, signal);
  212. };
  213. // { <signal>: <listener fn>, ... }
  214. var sigListeners = {};
  215. signals.forEach(function (sig) {
  216. sigListeners[sig] = function listener () {
  217. /* istanbul ignore if */
  218. if (!processOk(rollup.commonjsGlobal.process)) {
  219. return
  220. }
  221. // If there are no other listeners, an exit is coming!
  222. // Simplest way: remove us and then re-send the signal.
  223. // We know that this will kill the process, so we can
  224. // safely emit now.
  225. var listeners = process$1.listeners(sig);
  226. if (listeners.length === emitter.count) {
  227. unload();
  228. emit('exit', null, sig);
  229. /* istanbul ignore next */
  230. emit('afterexit', null, sig);
  231. /* istanbul ignore next */
  232. if (isWin && sig === 'SIGHUP') {
  233. // "SIGHUP" throws an `ENOSYS` error on Windows,
  234. // so use a supported signal instead
  235. sig = 'SIGINT';
  236. }
  237. /* istanbul ignore next */
  238. process$1.kill(process$1.pid, sig);
  239. }
  240. };
  241. });
  242. signalExit.exports.signals = function () {
  243. return signals
  244. };
  245. var loaded = false;
  246. var load = function load () {
  247. if (loaded || !processOk(rollup.commonjsGlobal.process)) {
  248. return
  249. }
  250. loaded = true;
  251. // This is the number of onSignalExit's that are in play.
  252. // It's important so that we can count the correct number of
  253. // listeners on signals, and don't wait for the other one to
  254. // handle it instead of us.
  255. emitter.count += 1;
  256. signals = signals.filter(function (sig) {
  257. try {
  258. process$1.on(sig, sigListeners[sig]);
  259. return true
  260. } catch (er) {
  261. return false
  262. }
  263. });
  264. process$1.emit = processEmit;
  265. process$1.reallyExit = processReallyExit;
  266. };
  267. signalExit.exports.load = load;
  268. var originalProcessReallyExit = process$1.reallyExit;
  269. var processReallyExit = function processReallyExit (code) {
  270. /* istanbul ignore if */
  271. if (!processOk(rollup.commonjsGlobal.process)) {
  272. return
  273. }
  274. process$1.exitCode = code || /* istanbul ignore next */ 0;
  275. emit('exit', process$1.exitCode, null);
  276. /* istanbul ignore next */
  277. emit('afterexit', process$1.exitCode, null);
  278. /* istanbul ignore next */
  279. originalProcessReallyExit.call(process$1, process$1.exitCode);
  280. };
  281. var originalProcessEmit = process$1.emit;
  282. var processEmit = function processEmit (ev, arg) {
  283. if (ev === 'exit' && processOk(rollup.commonjsGlobal.process)) {
  284. /* istanbul ignore else */
  285. if (arg !== undefined) {
  286. process$1.exitCode = arg;
  287. }
  288. var ret = originalProcessEmit.apply(this, arguments);
  289. /* istanbul ignore next */
  290. emit('exit', process$1.exitCode, null);
  291. /* istanbul ignore next */
  292. emit('afterexit', process$1.exitCode, null);
  293. /* istanbul ignore next */
  294. return ret
  295. } else {
  296. return originalProcessEmit.apply(this, arguments)
  297. }
  298. };
  299. }
  300. const CLEAR_SCREEN = '\u001Bc';
  301. function getResetScreen(configs, allowClearScreen) {
  302. let clearScreen = allowClearScreen;
  303. for (const config of configs) {
  304. if (config.watch && config.watch.clearScreen === false) {
  305. clearScreen = false;
  306. }
  307. }
  308. if (clearScreen) {
  309. return (heading) => loadConfigFile_js.stderr(CLEAR_SCREEN + heading);
  310. }
  311. let firstRun = true;
  312. return (heading) => {
  313. if (firstRun) {
  314. loadConfigFile_js.stderr(heading);
  315. firstRun = false;
  316. }
  317. };
  318. }
  319. function extractWatchHooks(command) {
  320. if (!Array.isArray(command.watch))
  321. return {};
  322. return command.watch
  323. .filter(value => typeof value === 'object')
  324. .reduce((acc, keyValueOption) => ({ ...acc, ...keyValueOption }), {});
  325. }
  326. function createWatchHooks(command) {
  327. const watchHooks = extractWatchHooks(command);
  328. return function (hook) {
  329. if (watchHooks[hook]) {
  330. const cmd = watchHooks[hook];
  331. if (!command.silent) {
  332. loadConfigFile_js.stderr(loadConfigFile_js.cyan(`watch.${hook} ${loadConfigFile_js.bold(`$ ${cmd}`)}`));
  333. }
  334. try {
  335. // !! important - use stderr for all writes from execSync
  336. const stdio = [process.stdin, process.stderr, process.stderr];
  337. child_process.execSync(cmd, { stdio: command.silent ? 'ignore' : stdio });
  338. }
  339. catch (e) {
  340. loadConfigFile_js.stderr(e.message);
  341. }
  342. }
  343. };
  344. }
  345. async function watch(command) {
  346. process$2.env.ROLLUP_WATCH = 'true';
  347. const isTTY = process$2.stderr.isTTY;
  348. const silent = command.silent;
  349. let watcher;
  350. let configWatcher;
  351. let resetScreen;
  352. const configFile = command.config ? await cli.getConfigPath(command.config) : null;
  353. const runWatchHook = createWatchHooks(command);
  354. signalExit.exports(close);
  355. process$2.on('uncaughtException', close);
  356. if (!process$2.stdin.isTTY) {
  357. process$2.stdin.on('end', close);
  358. process$2.stdin.resume();
  359. }
  360. async function loadConfigFromFileAndTrack(configFile) {
  361. let configFileData = null;
  362. let configFileRevision = 0;
  363. configWatcher = index.chokidar.watch(configFile).on('change', reloadConfigFile);
  364. await reloadConfigFile();
  365. async function reloadConfigFile() {
  366. try {
  367. const newConfigFileData = await require$$0$2.promises.readFile(configFile, 'utf8');
  368. if (newConfigFileData === configFileData) {
  369. return;
  370. }
  371. configFileRevision++;
  372. const currentConfigFileRevision = configFileRevision;
  373. if (configFileData) {
  374. loadConfigFile_js.stderr(`\nReloading updated config...`);
  375. }
  376. configFileData = newConfigFileData;
  377. const { options, warnings } = await loadConfigFile_js.loadAndParseConfigFile(configFile, command);
  378. if (currentConfigFileRevision !== configFileRevision) {
  379. return;
  380. }
  381. if (watcher) {
  382. await watcher.close();
  383. }
  384. start(options, warnings);
  385. }
  386. catch (err) {
  387. loadConfigFile_js.handleError(err, true);
  388. }
  389. }
  390. }
  391. if (configFile) {
  392. await loadConfigFromFileAndTrack(configFile);
  393. }
  394. else {
  395. const { options, warnings } = await cli.loadConfigFromCommand(command);
  396. start(options, warnings);
  397. }
  398. function start(configs, warnings) {
  399. try {
  400. watcher = rollup.watch(configs);
  401. }
  402. catch (err) {
  403. return loadConfigFile_js.handleError(err);
  404. }
  405. watcher.on('event', event => {
  406. switch (event.code) {
  407. case 'ERROR':
  408. warnings.flush();
  409. loadConfigFile_js.handleError(event.error, true);
  410. runWatchHook('onError');
  411. break;
  412. case 'START':
  413. if (!silent) {
  414. if (!resetScreen) {
  415. resetScreen = getResetScreen(configs, isTTY);
  416. }
  417. resetScreen(loadConfigFile_js.underline(`rollup v${rollup.version}`));
  418. }
  419. runWatchHook('onStart');
  420. break;
  421. case 'BUNDLE_START':
  422. if (!silent) {
  423. let input = event.input;
  424. if (typeof input !== 'string') {
  425. input = Array.isArray(input)
  426. ? input.join(', ')
  427. : Object.values(input).join(', ');
  428. }
  429. loadConfigFile_js.stderr(loadConfigFile_js.cyan(`bundles ${loadConfigFile_js.bold(input)} → ${loadConfigFile_js.bold(event.output.map(rollup.relativeId).join(', '))}...`));
  430. }
  431. runWatchHook('onBundleStart');
  432. break;
  433. case 'BUNDLE_END':
  434. warnings.flush();
  435. if (!silent)
  436. loadConfigFile_js.stderr(loadConfigFile_js.green(`created ${loadConfigFile_js.bold(event.output.map(rollup.relativeId).join(', '))} in ${loadConfigFile_js.bold(cli.ms(event.duration))}`));
  437. runWatchHook('onBundleEnd');
  438. if (event.result && event.result.getTimings) {
  439. cli.printTimings(event.result.getTimings());
  440. }
  441. break;
  442. case 'END':
  443. runWatchHook('onEnd');
  444. if (!silent && isTTY) {
  445. loadConfigFile_js.stderr(`\n[${dateTime()}] waiting for changes...`);
  446. }
  447. }
  448. if ('result' in event && event.result) {
  449. event.result.close().catch(error => loadConfigFile_js.handleError(error, true));
  450. }
  451. });
  452. }
  453. async function close(code) {
  454. process$2.removeListener('uncaughtException', close);
  455. // removing a non-existent listener is a no-op
  456. process$2.stdin.removeListener('end', close);
  457. if (watcher)
  458. await watcher.close();
  459. if (configWatcher)
  460. configWatcher.close();
  461. if (code) {
  462. process$2.exit(code);
  463. }
  464. }
  465. }
  466. exports.watch = watch;
  467. //# sourceMappingURL=watch-cli.js.map