Debian Codegraph @

packages/babel-core/test/config-chain.js

raw
1 import fs from "fs";
2 import os from "os";
3 import path from "path";
4 import { fileURLToPath } from "url";
5 import * as babel from "../lib/index.js";
6 import rimraf from "rimraf";
7
8 import _getTargets from "@babel/helper-compilation-targets";
9 const getTargets = _getTargets.default || _getTargets;
10
11 const dirname = path.dirname(fileURLToPath(import.meta.url));
12
13 import { isMJS, loadOptionsAsync, skipUnsupportedESM } from "./helpers/esm.js";
14
15 // TODO: In Babel 8, we can directly uses fs.promises which is supported by
16 // node 8+
17 const pfs =
18 fs.promises ||
19 new Proxy(fs, {
20 get(target, name) {
21 if (name === "copyFile") {
22 // fs.copyFile is only supported since node 8.5
23 // https://stackoverflow.com/a/30405105/2359289
24 return function copyFile(source, target) {
25 const rd = fs.createReadStream(source);
26 const wr = fs.createWriteStream(target);
27 return new Promise(function (resolve, reject) {
28 rd.on("error", reject);
29 wr.on("error", reject);
30 wr.on("finish", resolve);
31 rd.pipe(wr);
32 }).catch(function (error) {
33 rd.destroy();
34 wr.end();
35 throw error;
36 });
37 };
38 }
39
40 return (...args) =>
41 new Promise((resolve, reject) =>
42 target[name](...args, (error, result) => {
43 if (error) reject(error);
44 else resolve(result);
45 }),
46 );
47 },
48 });
49
50 function fixture(...args) {
51 return path.join(dirname, "fixtures", "config", ...args);
52 }
53
54 function loadOptions(opts) {
55 return babel.loadOptions({ cwd: dirname, ...opts });
56 }
57
58 function pairs(items) {
59 const pairs = [];
60 for (let i = 0; i < items.length - 1; i++) {
61 for (let j = i + 1; j < items.length; j++) {
62 pairs.push([items[i], items[j]]);
63 }
64 }
65 return pairs;
66 }
67
68 function escapeRegExp(string) {
69 return string.replace(/[|\\{}()[\]^$+*?.]/g, "\\$&");
70 }
71
72 const tempDirs = [];
73
74 async function getTemp(name) {
75 const tempDir = os.tmpdir() + path.sep + name;
76 tempDirs.push(tempDir);
77 const cwd = await pfs.mkdtemp(tempDir);
78 const tmp = name => path.join(cwd, name);
79 const config = name =>
80 pfs.copyFile(fixture("config-files-templates", name), tmp(name));
81 return { cwd, tmp, config };
82 }
83
84 afterAll(() => {
85 for (const dir of tempDirs) {
86 rimraf.sync(dir);
87 }
88 });
89
90 describe("buildConfigChain", function () {
91 describe("test", () => {
92 describe("single", () => {
93 it("should process matching string values", () => {
94 const opts = loadOptions({
95 cwd: fixture("nonexistant-fake"),
96 filename: fixture("nonexistant-fake", "src.js"),
97 babelrc: false,
98 test: fixture("nonexistant-fake"),
99 comments: true,
100 });
101
102 expect(opts.comments).toBe(true);
103 });
104
105 it("should process matching RegExp values", () => {
106 const opts = loadOptions({
107 cwd: fixture("nonexistant-fake"),
108 filename: fixture("nonexistant-fake", "src.js"),
109 babelrc: false,
110 test: new RegExp(escapeRegExp(fixture("nonexistant-fake"))),
111 comments: true,
112 });
113
114 expect(opts.comments).toBe(true);
115 });
116
117 it("should process matching function values", () => {
118 const opts = loadOptions({
119 cwd: fixture("nonexistant-fake"),
120 filename: fixture("nonexistant-fake", "src.js"),
121 babelrc: false,
122 test: p => p.indexOf(fixture("nonexistant-fake")) === 0,
123 comments: true,
124 });
125
126 expect(opts.comments).toBe(true);
127 });
128
129 it("should process non-matching string values", () => {
130 const opts = loadOptions({
131 cwd: fixture("nonexistant-fake"),
132 filename: fixture("nonexistant-fake", "src.js"),
133 babelrc: false,
134 test: fixture("nonexistant-fake-unknown"),
135 comments: true,
136 });
137
138 expect(opts.comments).toBeUndefined();
139 });
140
141 it("should process non-matching RegExp values", () => {
142 const opts = loadOptions({
143 cwd: fixture("nonexistant-fake"),
144 filename: fixture("nonexistant-fake", "src.js"),
145 babelrc: false,
146 test: new RegExp(escapeRegExp(fixture("nonexistant-unknown"))),
147 comments: true,
148 });
149
150 expect(opts.comments).toBeUndefined();
151 });
152
153 it("should process non-matching function values", () => {
154 const opts = loadOptions({
155 cwd: fixture("nonexistant-fake"),
156 filename: fixture("nonexistant-fake", "src.js"),
157 babelrc: false,
158 test: p => p.indexOf(fixture("nonexistant-unknown")) === 0,
159 comments: true,
160 });
161
162 expect(opts.comments).toBeUndefined();
163 });
164 });
165
166 describe("array", () => {
167 it("should process matching string values", () => {
168 const opts = loadOptions({
169 cwd: fixture("nonexistant-fake"),
170 filename: fixture("nonexistant-fake", "src.js"),
171 babelrc: false,
172 test: [fixture("nonexistant-fake")],
173 comments: true,
174 });
175
176 expect(opts.comments).toBe(true);
177 });
178
179 it("should process matching RegExp values", () => {
180 const opts = loadOptions({
181 cwd: fixture("nonexistant-fake"),
182 filename: fixture("nonexistant-fake", "src.js"),
183 babelrc: false,
184 test: [new RegExp(escapeRegExp(fixture("nonexistant-fake")))],
185 comments: true,
186 });
187
188 expect(opts.comments).toBe(true);
189 });
190
191 it("should process matching function values", () => {
192 const opts = loadOptions({
193 cwd: fixture("nonexistant-fake"),
194 filename: fixture("nonexistant-fake", "src.js"),
195 babelrc: false,
196 test: [p => p.indexOf(fixture("nonexistant-fake")) === 0],
197 comments: true,
198 });
199
200 expect(opts.comments).toBe(true);
201 });
202
203 it("should process non-matching string values", () => {
204 const opts = loadOptions({
205 cwd: fixture("nonexistant-fake"),
206 filename: fixture("nonexistant-fake", "src.js"),
207 babelrc: false,
208 test: [fixture("nonexistant-fake-unknown")],
209 comments: true,
210 });
211
212 expect(opts.comments).toBeUndefined();
213 });
214
215 it("should process non-matching RegExp values", () => {
216 const opts = loadOptions({
217 cwd: fixture("nonexistant-fake"),
218 filename: fixture("nonexistant-fake", "src.js"),
219 babelrc: false,
220 test: [new RegExp(escapeRegExp(fixture("nonexistant-unknown")))],
221 comments: true,
222 });
223
224 expect(opts.comments).toBeUndefined();
225 });
226
227 it("should process non-matching function values", () => {
228 const opts = loadOptions({
229 cwd: fixture("nonexistant-fake"),
230 filename: fixture("nonexistant-fake", "src.js"),
231 babelrc: false,
232 test: [p => p.indexOf(fixture("nonexistant-unknown")) === 0],
233 comments: true,
234 });
235
236 expect(opts.comments).toBeUndefined();
237 });
238 });
239
240 describe("filename requirement", () => {
241 const BASE_OPTS = {
242 cwd: fixture("nonexistant-fake"),
243 babelrc: false,
244 configFile: false,
245 };
246
247 describe("in config", () => {
248 it("requires filename if string", () => {
249 expect(() =>
250 loadOptions({
251 ...BASE_OPTS,
252 test: fixture("nonexistant-fake"),
253 }),
254 ).toThrow(/no filename was passed/);
255 });
256
257 it("requires filename if RegExp", () => {
258 expect(() =>
259 loadOptions({
260 ...BASE_OPTS,
261 test: /file/,
262 }),
263 ).toThrow(/no filename was passed/);
264 });
265
266 it("does not require filename if function", () => {
267 const mock = jest.fn().mockReturnValue(true);
268
269 expect(() =>
270 loadOptions({
271 ...BASE_OPTS,
272 test: mock,
273 }),
274 ).not.toThrow();
275 expect(mock).toHaveBeenCalledWith(undefined, expect.anything());
276
277 expect(() =>
278 loadOptions({
279 ...BASE_OPTS,
280 filename: "some-filename",
281 test: mock,
282 }),
283 ).not.toThrow();
284 expect(mock.mock.calls[1][0].endsWith("some-filename")).toBe(true);
285 });
286 });
287
288 describe("in preset", () => {
289 it("requires filename if string", () => {
290 expect(() =>
291 loadOptions({
292 ...BASE_OPTS,
293 presets: [() => ({ test: fixture("nonexistant-fake") })],
294 }),
295 ).toThrow(/requires a filename/);
296 });
297
298 it("requires filename if RegExp", () => {
299 expect(() =>
300 loadOptions({
301 ...BASE_OPTS,
302 presets: [() => ({ test: /file/ })],
303 }),
304 ).toThrow(/requires a filename/);
305 });
306
307 it("does not require filename if function", () => {
308 const mock = jest.fn().mockReturnValue(true);
309
310 expect(() =>
311 loadOptions({
312 ...BASE_OPTS,
313 presets: [() => ({ test: mock })],
314 }),
315 ).not.toThrow();
316 expect(mock).toHaveBeenCalledWith(undefined, expect.anything());
317
318 expect(() =>
319 loadOptions({
320 ...BASE_OPTS,
321 filename: "some-filename",
322 presets: [() => ({ test: mock })],
323 }),
324 ).not.toThrow();
325 expect(mock.mock.calls[1][0].endsWith("some-filename")).toBe(true);
326 });
327 });
328 });
329 });
330
331 describe("include", () => {
332 describe("single", () => {
333 it("should process matching string values", () => {
334 const opts = loadOptions({
335 cwd: fixture("nonexistant-fake"),
336 filename: fixture("nonexistant-fake", "src.js"),
337 babelrc: false,
338 include: fixture("nonexistant-fake"),
339 comments: true,
340 });
341
342 expect(opts.comments).toBe(true);
343 });
344
345 it("should process matching RegExp values", () => {
346 const opts = loadOptions({
347 cwd: fixture("nonexistant-fake"),
348 filename: fixture("nonexistant-fake", "src.js"),
349 babelrc: false,
350 include: new RegExp(escapeRegExp(fixture("nonexistant-fake"))),
351 comments: true,
352 });
353
354 expect(opts.comments).toBe(true);
355 });
356
357 it("should process matching function values", () => {
358 const opts = loadOptions({
359 cwd: fixture("nonexistant-fake"),
360 filename: fixture("nonexistant-fake", "src.js"),
361 babelrc: false,
362 include: p => p.indexOf(fixture("nonexistant-fake")) === 0,
363 comments: true,
364 });
365
366 expect(opts.comments).toBe(true);
367 });
368
369 it("should process non-matching string values", () => {
370 const opts = loadOptions({
371 cwd: fixture("nonexistant-fake"),
372 filename: fixture("nonexistant-fake", "src.js"),
373 babelrc: false,
374 include: fixture("nonexistant-fake-unknown"),
375 comments: true,
376 });
377
378 expect(opts.comments).toBeUndefined();
379 });
380
381 it("should process non-matching RegExp values", () => {
382 const opts = loadOptions({
383 cwd: fixture("nonexistant-fake"),
384 filename: fixture("nonexistant-fake", "src.js"),
385 babelrc: false,
386 include: new RegExp(escapeRegExp(fixture("nonexistant-unknown"))),
387 comments: true,
388 });
389
390 expect(opts.comments).toBeUndefined();
391 });
392
393 it("should process non-matching function values", () => {
394 const opts = loadOptions({
395 cwd: fixture("nonexistant-fake"),
396 filename: fixture("nonexistant-fake", "src.js"),
397 babelrc: false,
398 include: p => p.indexOf(fixture("nonexistant-unknown")) === 0,
399 comments: true,
400 });
401
402 expect(opts.comments).toBeUndefined();
403 });
404 });
405
406 describe("array", () => {
407 it("should process matching string values", () => {
408 const opts = loadOptions({
409 cwd: fixture("nonexistant-fake"),
410 filename: fixture("nonexistant-fake", "src.js"),
411 babelrc: false,
412 include: [fixture("nonexistant-fake")],
413 comments: true,
414 });
415
416 expect(opts.comments).toBe(true);
417 });
418
419 it("should process matching RegExp values", () => {
420 const opts = loadOptions({
421 cwd: fixture("nonexistant-fake"),
422 filename: fixture("nonexistant-fake", "src.js"),
423 babelrc: false,
424 include: [new RegExp(escapeRegExp(fixture("nonexistant-fake")))],
425 comments: true,
426 });
427
428 expect(opts.comments).toBe(true);
429 });
430
431 it("should process matching function values", () => {
432 const opts = loadOptions({
433 cwd: fixture("nonexistant-fake"),
434 filename: fixture("nonexistant-fake", "src.js"),
435 babelrc: false,
436 include: [p => p.indexOf(fixture("nonexistant-fake")) === 0],
437 comments: true,
438 });
439
440 expect(opts.comments).toBe(true);
441 });
442
443 it("should process non-matching string values", () => {
444 const opts = loadOptions({
445 cwd: fixture("nonexistant-fake"),
446 filename: fixture("nonexistant-fake", "src.js"),
447 babelrc: false,
448 include: [fixture("nonexistant-fake-unknown")],
449 comments: true,
450 });
451
452 expect(opts.comments).toBeUndefined();
453 });
454
455 it("should process non-matching RegExp values", () => {
456 const opts = loadOptions({
457 cwd: fixture("nonexistant-fake"),
458 filename: fixture("nonexistant-fake", "src.js"),
459 babelrc: false,
460 include: [new RegExp(escapeRegExp(fixture("nonexistant-unknown")))],
461 comments: true,
462 });
463
464 expect(opts.comments).toBeUndefined();
465 });
466
467 it("should process non-matching function values", () => {
468 const opts = loadOptions({
469 cwd: fixture("nonexistant-fake"),
470 filename: fixture("nonexistant-fake", "src.js"),
471 babelrc: false,
472 include: [p => p.indexOf(fixture("nonexistant-unknown")) === 0],
473 comments: true,
474 });
475
476 expect(opts.comments).toBeUndefined();
477 });
478 });
479 });
480
481 describe("exclude", () => {
482 describe("single", () => {
483 it("should process matching string values", () => {
484 const opts = loadOptions({
485 cwd: fixture("nonexistant-fake"),
486 filename: fixture("nonexistant-fake", "src.js"),
487 babelrc: false,
488 exclude: fixture("nonexistant-fake"),
489 comments: true,
490 });
491
492 expect(opts.comments).toBeUndefined();
493 });
494
495 it("should process matching RegExp values", () => {
496 const opts = loadOptions({
497 cwd: fixture("nonexistant-fake"),
498 filename: fixture("nonexistant-fake", "src.js"),
499 babelrc: false,
500 exclude: new RegExp(escapeRegExp(fixture("nonexistant-fake"))),
501 comments: true,
502 });
503
504 expect(opts.comments).toBeUndefined();
505 });
506
507 it("should process matching function values", () => {
508 const opts = loadOptions({
509 cwd: fixture("nonexistant-fake"),
510 filename: fixture("nonexistant-fake", "src.js"),
511 babelrc: false,
512 exclude: p => p.indexOf(fixture("nonexistant-fake")) === 0,
513 comments: true,
514 });
515
516 expect(opts.comments).toBeUndefined();
517 });
518
519 it("should process non-matching string values", () => {
520 const opts = loadOptions({
521 cwd: fixture("nonexistant-fake"),
522 filename: fixture("nonexistant-fake", "src.js"),
523 babelrc: false,
524 exclude: fixture("nonexistant-fake-unknown"),
525 comments: true,
526 });
527
528 expect(opts.comments).toBe(true);
529 });
530
531 it("should process non-matching RegExp values", () => {
532 const opts = loadOptions({
533 cwd: fixture("nonexistant-fake"),
534 filename: fixture("nonexistant-fake", "src.js"),
535 babelrc: false,
536 exclude: new RegExp(escapeRegExp(fixture("nonexistant-unknown"))),
537 comments: true,
538 });
539
540 expect(opts.comments).toBe(true);
541 });
542
543 it("should process non-matching function values", () => {
544 const opts = loadOptions({
545 cwd: fixture("nonexistant-fake"),
546 filename: fixture("nonexistant-fake", "src.js"),
547 babelrc: false,
548 exclude: p => p.indexOf(fixture("nonexistant-unknown")) === 0,
549 comments: true,
550 });
551
552 expect(opts.comments).toBe(true);
553 });
554 });
555
556 describe("array", () => {
557 it("should process matching string values", () => {
558 const opts = loadOptions({
559 cwd: fixture("nonexistant-fake"),
560 filename: fixture("nonexistant-fake", "src.js"),
561 babelrc: false,
562 exclude: [fixture("nonexistant-fake")],
563 comments: true,
564 });
565
566 expect(opts.comments).toBeUndefined();
567 });
568
569 it("should process matching RegExp values", () => {
570 const opts = loadOptions({
571 cwd: fixture("nonexistant-fake"),
572 filename: fixture("nonexistant-fake", "src.js"),
573 babelrc: false,
574 exclude: [new RegExp(escapeRegExp(fixture("nonexistant-fake")))],
575 comments: true,
576 });
577
578 expect(opts.comments).toBeUndefined();
579 });
580
581 it("should process matching function values", () => {
582 const opts = loadOptions({
583 cwd: fixture("nonexistant-fake"),
584 filename: fixture("nonexistant-fake", "src.js"),
585 babelrc: false,
586 exclude: [p => p.indexOf(fixture("nonexistant-fake")) === 0],
587 comments: true,
588 });
589
590 expect(opts.comments).toBeUndefined();
591 });
592
593 it("should process non-matching string values", () => {
594 const opts = loadOptions({
595 cwd: fixture("nonexistant-fake"),
596 filename: fixture("nonexistant-fake", "src.js"),
597 babelrc: false,
598 exclude: [fixture("nonexistant-fake-unknown")],
599 comments: true,
600 });
601
602 expect(opts.comments).toBe(true);
603 });
604
605 it("should process non-matching RegExp values", () => {
606 const opts = loadOptions({
607 cwd: fixture("nonexistant-fake"),
608 filename: fixture("nonexistant-fake", "src.js"),
609 babelrc: false,
610 exclude: [new RegExp(escapeRegExp(fixture("nonexistant-unknown")))],
611 comments: true,
612 });
613
614 expect(opts.comments).toBe(true);
615 });
616
617 it("should process non-matching function values", () => {
618 const opts = loadOptions({
619 cwd: fixture("nonexistant-fake"),
620 filename: fixture("nonexistant-fake", "src.js"),
621 babelrc: false,
622 exclude: [p => p.indexOf(fixture("nonexistant-unknown")) === 0],
623 comments: true,
624 });
625
626 expect(opts.comments).toBe(true);
627 });
628 });
629 });
630
631 describe("ignore", () => {
632 it("should ignore files that match", () => {
633 const opts = loadOptions({
634 cwd: fixture("nonexistant-fake"),
635 filename: fixture("nonexistant-fake", "src.js"),
636 babelrc: false,
637 ignore: [
638 fixture("nonexistant-fake", "src.js"),
639
640 // We had a regression where multiple ignore patterns broke things, so
641 // we keep some extra random items in here.
642 fixture("nonexistant-fake", "other.js"),
643 fixture("nonexistant-fake", "misc.js"),
644 ],
645 });
646
647 expect(opts).toBeNull();
648 });
649
650 it("should not ignore files that don't match", () => {
651 const opts = loadOptions({
652 cwd: fixture("nonexistant-fake"),
653 filename: fixture("nonexistant-fake", "src.js"),
654 babelrc: false,
655 ignore: [
656 fixture("nonexistant-fake", "other.js"),
657 fixture("nonexistant-fake", "misc.js"),
658 ],
659 });
660
661 expect(opts).not.toBeNull();
662 });
663 });
664
665 describe("only", () => {
666 it("should ignore files that don't match", () => {
667 const opts = loadOptions({
668 cwd: fixture("nonexistant-fake"),
669 filename: fixture("nonexistant-fake", "src.js"),
670 babelrc: false,
671 only: [
672 fixture("nonexistant-fake", "other.js"),
673 fixture("nonexistant-fake", "misc.js"),
674 ],
675 });
676
677 expect(opts).toBeNull();
678 });
679
680 it("should not ignore files that match", () => {
681 const opts = loadOptions({
682 cwd: fixture("nonexistant-fake"),
683 filename: fixture("nonexistant-fake", "src.js"),
684 babelrc: false,
685 only: [
686 fixture("nonexistant-fake", "src.js"),
687 fixture("nonexistant-fake", "misc.js"),
688 ],
689 });
690
691 expect(opts).not.toBeNull();
692 });
693 });
694
695 describe("ignore/only", () => {
696 it("should ignore files that match ignore and don't match only", () => {
697 const opts = loadOptions({
698 cwd: fixture("nonexistant-fake"),
699 filename: fixture("nonexistant-fake", "src.js"),
700 babelrc: false,
701 ignore: [fixture("nonexistant-fake", "src.js")],
702 only: [],
703 });
704
705 expect(opts).toBeNull();
706 });
707
708 it("should ignore files that match ignore and also only", () => {
709 const opts = loadOptions({
710 cwd: fixture("nonexistant-fake"),
711 filename: fixture("nonexistant-fake", "src.js"),
712 babelrc: false,
713 ignore: [fixture("nonexistant-fake", "src.js")],
714 only: [fixture("nonexistant-fake", "src.js")],
715 });
716
717 expect(opts).toBeNull();
718 });
719
720 it("should not ignore files that match only and not ignore", () => {
721 const opts = loadOptions({
722 cwd: fixture("nonexistant-fake"),
723 filename: fixture("nonexistant-fake", "src.js"),
724 babelrc: false,
725 only: [fixture("nonexistant-fake", "src.js")],
726 });
727
728 expect(opts).not.toBeNull();
729 });
730
731 it("should not ignore files when no ignore/only are specified", () => {
732 const opts = loadOptions({
733 cwd: fixture("nonexistant-fake"),
734 filename: fixture("nonexistant-fake", "src.js"),
735 babelrc: false,
736 });
737
738 expect(opts).not.toBeNull();
739 });
740
741 it("should allow negation of only", () => {
742 const opts1 = loadOptions({
743 cwd: fixture("nonexistant-fake"),
744 filename: fixture("nonexistant-fake", "src.js"),
745 babelrc: false,
746 only: [
747 "!" + fixture("nonexistant-fake"),
748 fixture("nonexistant-fake", "other.js"),
749 ],
750 });
751 expect(opts1).toBeNull();
752
753 const opts2 = loadOptions({
754 cwd: fixture("nonexistant-fake"),
755 filename: fixture("nonexistant-fake", "src.js"),
756 babelrc: false,
757 only: [
758 "!" + fixture("nonexistant-fake"),
759 fixture("nonexistant-fake", "src.js"),
760 ],
761 });
762 expect(opts2).not.toBeNull();
763
764 const opts3 = loadOptions({
765 cwd: fixture("nonexistant-fake"),
766 filename: fixture("nonexistant-fake", "folder", "src.js"),
767 babelrc: false,
768 only: [
769 "!" + fixture("nonexistant-fake"),
770 fixture("nonexistant-fake", "folder"),
771 ],
772 });
773 expect(opts3).not.toBeNull();
774 });
775
776 it("should allow negation of ignore", () => {
777 const opts1 = loadOptions({
778 cwd: fixture("nonexistant-fake"),
779 filename: fixture("nonexistant-fake", "src.js"),
780 babelrc: false,
781 ignore: [
782 "!" + fixture("nonexistant-fake", "other.js"),
783 fixture("nonexistant-fake"),
784 ],
785 });
786 expect(opts1).toBeNull();
787
788 // Tests disabled pending https://github.com/babel/babel/issues/6907
789 // const opts2 = loadOptions({
790 // cwd: fixture("nonexistant-fake"),
791 // filename: fixture("nonexistant-fake", "src.js"),
792 // babelrc: false,
793 // ignore: [
794 // "!" + fixture("nonexistant-fake", "src.js"),
795 // fixture("nonexistant-fake"),
796 // ],
797 // });
798 // expect(opts2).not.toBeNull();
799 //
800 // const opts3 = loadOptions({
801 // cwd: fixture("nonexistant-fake"),
802 // filename: fixture("nonexistant-fake", "folder", "src.js"),
803 // babelrc: false,
804 // ignore: [
805 // "!" + fixture("nonexistant-fake", "folder"),
806 // fixture("nonexistant-fake"),
807 // ],
808 // });
809 // expect(opts3).not.toBeNull();
810 });
811 });
812
813 describe("caching", function () {
814 describe("programmatic options", function () {
815 const plugins1 = [() => ({})];
816 const plugins2 = [() => ({})];
817
818 it("should not cache the input options by identity", () => {
819 const inputOpts = { plugins: plugins1 };
820
821 const opts1 = loadOptions(inputOpts);
822
823 inputOpts.plugins = plugins2;
824 const opts2 = loadOptions(inputOpts);
825
826 expect(opts1.plugins).toHaveLength(1);
827 expect(opts2.plugins).toHaveLength(1);
828 expect(opts1.plugins[0]).not.toBe(opts2.plugins[1]);
829 });
830
831 it("should cache the env plugins by identity", () => {
832 const plugins = [() => ({})];
833
834 const opts1 = loadOptions({
835 envName: "foo",
836 env: {
837 foo: {
838 plugins,
839 },
840 },
841 });
842 const opts2 = loadOptions({
843 envName: "foo",
844 env: {
845 foo: {
846 plugins,
847 },
848 },
849 });
850
851 expect(opts1.plugins).toHaveLength(1);
852 expect(opts2.plugins).toHaveLength(1);
853 expect(opts1.plugins[0]).toBe(opts2.plugins[0]);
854 });
855
856 it("should cache the env presets by identity", () => {
857 const presets = [() => ({ plugins: [() => ({})] })];
858
859 const opts1 = loadOptions({
860 envName: "foo",
861 env: {
862 foo: {
863 presets,
864 },
865 },
866 });
867 const opts2 = loadOptions({
868 envName: "foo",
869 env: {
870 foo: {
871 presets,
872 },
873 },
874 });
875
876 expect(opts1.plugins).toHaveLength(1);
877 expect(opts2.plugins).toHaveLength(1);
878 expect(opts1.plugins[0]).toBe(opts2.plugins[0]);
879 });
880
881 it("should cache the plugin options by identity", () => {
882 const plugins = [() => ({})];
883
884 const opts1 = loadOptions({ plugins });
885 const opts2 = loadOptions({ plugins });
886
887 expect(opts1.plugins).toHaveLength(1);
888 expect(opts2.plugins).toHaveLength(1);
889 expect(opts1.plugins[0]).toBe(opts2.plugins[0]);
890 });
891
892 it("should cache the presets options by identity", () => {
893 const presets = [() => ({ plugins: [() => ({})] })];
894
895 const opts1 = loadOptions({ presets });
896 const opts2 = loadOptions({ presets });
897
898 expect(opts1.plugins).toHaveLength(1);
899 expect(opts2.plugins).toHaveLength(1);
900 expect(opts1.plugins[0]).toBe(opts2.plugins[0]);
901 });
902
903 it("should not cache the presets options with passPerPreset", () => {
904 const presets = [() => ({ plugins: [() => ({})] })];
905
906 const opts1 = loadOptions({ presets });
907 const opts2 = loadOptions({ presets, passPerPreset: true });
908 const opts3 = loadOptions({ presets, passPerPreset: false });
909
910 expect(opts1.plugins).toHaveLength(1);
911 expect(opts2.plugins).toHaveLength(0);
912 expect(opts3.plugins).toHaveLength(1);
913
914 expect(opts1.plugins[0]).toBe(opts3.plugins[0]);
915 });
916 });
917
918 describe("config file options", function () {
919 function touch(filepath) {
920 const s = fs.statSync(filepath);
921 fs.utimesSync(
922 filepath,
923 s.atime,
924 s.mtime + Math.random() > 0.5 ? 1 : -1,
925 );
926 }
927
928 it("should cache package.json files by mtime", () => {
929 const filename = fixture(
930 "complex-plugin-config",
931 "config-identity",
932 "pkg",
933 "src.js",
934 );
935 const pkgJSON = fixture(
936 "complex-plugin-config",
937 "config-identity",
938 "pkg",
939 "package.json",
940 );
941
942 const opts1 = loadOptions({ filename, cwd: path.dirname(filename) });
943 const opts2 = loadOptions({ filename, cwd: path.dirname(filename) });
944
945 touch(pkgJSON);
946
947 const opts3 = loadOptions({ filename, cwd: path.dirname(filename) });
948 const opts4 = loadOptions({ filename, cwd: path.dirname(filename) });
949
950 expect(opts1.plugins).toHaveLength(1);
951 expect(opts2.plugins).toHaveLength(1);
952 expect(opts1.plugins[0]).toBe(opts2.plugins[0]);
953
954 expect(opts1.plugins).toHaveLength(1);
955 expect(opts2.plugins).toHaveLength(1);
956 expect(opts3.plugins[0]).toBe(opts4.plugins[0]);
957
958 // Identity changed after touch().
959 expect(opts1.plugins[0]).not.toBe(opts3.plugins[0]);
960 });
961
962 it("should cache .babelrc files by mtime", () => {
963 const filename = fixture(
964 "complex-plugin-config",
965 "config-identity",
966 "babelrc",
967 "src.js",
968 );
969 const babelrcFile = fixture(
970 "complex-plugin-config",
971 "config-identity",
972 "babelrc",
973 ".babelrc",
974 );
975
976 const opts1 = loadOptions({ filename, cwd: path.dirname(filename) });
977 const opts2 = loadOptions({ filename, cwd: path.dirname(filename) });
978
979 touch(babelrcFile);
980
981 const opts3 = loadOptions({ filename, cwd: path.dirname(filename) });
982 const opts4 = loadOptions({ filename, cwd: path.dirname(filename) });
983
984 expect(opts1.plugins).toHaveLength(1);
985 expect(opts2.plugins).toHaveLength(1);
986 expect(opts1.plugins[0]).toBe(opts2.plugins[0]);
987
988 expect(opts3.plugins).toHaveLength(1);
989 expect(opts4.plugins).toHaveLength(1);
990 expect(opts3.plugins[0]).toBe(opts4.plugins[0]);
991
992 // Identity changed after touch().
993 expect(opts1.plugins[0]).not.toBe(opts3.plugins[0]);
994 });
995
996 it("should cache .babelrc.js files programmable behavior", () => {
997 const filename = fixture(
998 "complex-plugin-config",
999 "config-identity",
1000 "babelrc-js",
1001 "src.js",
1002 );
1003
1004 const opts1 = loadOptions({ filename, cwd: path.dirname(filename) });
1005 const opts2 = loadOptions({ filename, cwd: path.dirname(filename) });
1006
1007 const opts3 = loadOptions({
1008 filename,
1009 envName: "new-env",
1010 cwd: path.dirname(filename),
1011 });
1012 const opts4 = loadOptions({
1013 filename,
1014 envName: "new-env",
1015 cwd: path.dirname(filename),
1016 });
1017
1018 expect(opts1.plugins).toHaveLength(1);
1019 expect(opts2.plugins).toHaveLength(1);
1020 expect(opts1.plugins[0]).toBe(opts2.plugins[0]);
1021
1022 expect(opts3.plugins).toHaveLength(1);
1023 expect(opts4.plugins).toHaveLength(1);
1024 expect(opts3.plugins[0]).toBe(opts4.plugins[0]);
1025
1026 // Identity changed with different .env
1027 expect(opts1.plugins[0]).not.toBe(opts3.plugins[0]);
1028 });
1029 });
1030 });
1031
1032 describe("overrides merging", () => {
1033 it("should apply matching overrides over base configs", () => {
1034 const opts = loadOptions({
1035 cwd: fixture("nonexistant-fake"),
1036 filename: fixture("nonexistant-fake", "src.js"),
1037 babelrc: false,
1038 comments: true,
1039 overrides: [
1040 {
1041 test: fixture("nonexistant-fake"),
1042 comments: false,
1043 },
1044 ],
1045 });
1046
1047 expect(opts.comments).toBe(false);
1048 });
1049
1050 it("should not apply non-matching overrides over base configs", () => {
1051 const opts = loadOptions({
1052 cwd: fixture("nonexistant-fake"),
1053 filename: fixture("nonexistant-fake", "src.js"),
1054 babelrc: false,
1055 comments: true,
1056 overrides: [
1057 {
1058 test: fixture("nonexistant-unknown"),
1059 comments: false,
1060 },
1061 ],
1062 });
1063
1064 expect(opts.comments).toBe(true);
1065 });
1066
1067 it("should remove the overrides and filtering fields from the options", () => {
1068 const opts = loadOptions({
1069 cwd: fixture("nonexistant-fake"),
1070 filename: fixture("nonexistant-fake", "src.js"),
1071 babelrc: false,
1072 overrides: [],
1073 test: /^/,
1074 include: /^/,
1075 exclude: [],
1076 });
1077
1078 expect(opts.overrides).toBeUndefined();
1079 expect(opts.test).toBeUndefined();
1080 expect(opts.include).toBeUndefined();
1081 expect(opts.exclude).toBeUndefined();
1082 });
1083 });
1084
1085 describe("config files", () => {
1086 const defaultTargets = getTargets();
1087 const getDefaults = () => ({
1088 babelrc: false,
1089 configFile: false,
1090 browserslistConfigFile: false,
1091 cwd: process.cwd(),
1092 root: process.cwd(),
1093 rootMode: "root",
1094 envName: "development",
1095 passPerPreset: false,
1096 plugins: [],
1097 presets: [],
1098 cloneInputAst: true,
1099 targets: defaultTargets,
1100 assumptions: {},
1101 });
1102 const realEnv = process.env.NODE_ENV;
1103 const realBabelEnv = process.env.BABEL_ENV;
1104
1105 beforeAll(() => {
1106 delete process.env.NODE_ENV;
1107 delete process.env.BABEL_ENV;
1108 });
1109 afterAll(() => {
1110 if (realEnv) {
1111 process.env.NODE_ENV = realEnv;
1112 process.env.NODE_ENV = realBabelEnv;
1113 }
1114 });
1115
1116 describe("root", () => {
1117 test.each(["babel.config.json", "babel.config.js", "babel.config.cjs"])(
1118 "should load %s synchronously",
1119 async name => {
1120 const { cwd, tmp, config } = await getTemp(
1121 `babel-test-load-config-sync-${name}`,
1122 );
1123 const filename = tmp("src.js");
1124
1125 await config(name);
1126
1127 expect(loadOptions({ filename, cwd })).toEqual({
1128 ...getDefaults(),
1129 filename,
1130 cwd,
1131 root: cwd,
1132 comments: true,
1133 });
1134 },
1135 );
1136
1137 test("should not load babel.config.mjs synchronously", async () => {
1138 const { cwd, tmp, config } = await getTemp(
1139 "babel-test-load-config-sync-babel.config.mjs",
1140 );
1141 const filename = tmp("src.js");
1142
1143 await config("babel.config.mjs");
1144
1145 expect(() => loadOptions({ filename, cwd })).toThrow(
1146 /is only supported when running Babel asynchronously/,
1147 );
1148 });
1149
1150 test.each([
1151 "babel.config.json",
1152 "babel.config.js",
1153 "babel.config.cjs",
1154 "babel.config.mjs",
1155 ])("should load %s asynchronously", async name => {
1156 const esm = isMJS(name);
1157 if (esm && skipUnsupportedESM(`should load ${name} asynchronously`)) {
1158 return;
1159 }
1160
1161 const { cwd, tmp, config } = await getTemp(
1162 `babel-test-load-config-async-${name}`,
1163 );
1164 const filename = tmp("src.js");
1165
1166 await config(name);
1167
1168 await expect(loadOptionsAsync({ filename, cwd }, esm)).resolves.toEqual(
1169 {
1170 ...getDefaults(),
1171 filename,
1172 cwd,
1173 root: cwd,
1174 comments: true,
1175 },
1176 );
1177 });
1178
1179 test.each(
1180 pairs([
1181 "babel.config.json",
1182 "babel.config.js",
1183 "babel.config.cjs",
1184 "babel.config.mjs",
1185 ]),
1186 )("should throw if both %s and %s are used", async (name1, name2) => {
1187 const esm = isMJS(name1) || isMJS(name2);
1188 if (
1189 esm &&
1190 skipUnsupportedESM(
1191 `should throw if both ${name1} and ${name2} are used`,
1192 )
1193 ) {
1194 return;
1195 }
1196
1197 const { cwd, tmp, config } = await getTemp(
1198 `babel-test-dup-config-${name1}-${name2}`,
1199 );
1200
1201 await Promise.all([config(name1), config(name2)]);
1202
1203 await expect(
1204 loadOptionsAsync({ filename: tmp("src.js"), cwd }, esm),
1205 ).rejects.toThrow(/Multiple configuration files found/);
1206 });
1207 });
1208
1209 describe("relative", () => {
1210 test.each([
1211 "package.json",
1212 ".babelrc",
1213 ".babelrc.js",
1214 ".babelrc.cjs",
1215 ".babelrc.json",
1216 ])("should load %s synchronously", async name => {
1217 const { cwd, tmp, config } = await getTemp(
1218 `babel-test-load-config-${name}`,
1219 );
1220 const filename = tmp("src.js");
1221
1222 await config(name);
1223
1224 expect(loadOptions({ filename, cwd })).toEqual({
1225 ...getDefaults(),
1226 filename,
1227 cwd,
1228 root: cwd,
1229 comments: true,
1230 });
1231 });
1232
1233 test("should not load .babelrc.mjs synchronously", async () => {
1234 const { cwd, tmp, config } = await getTemp(
1235 "babel-test-load-config-sync-.babelrc.mjs",
1236 );
1237 const filename = tmp("src.js");
1238
1239 await config(".babelrc.mjs");
1240
1241 expect(() => loadOptions({ filename, cwd })).toThrow(
1242 /is only supported when running Babel asynchronously/,
1243 );
1244 });
1245
1246 test.each(
1247 [
1248 "package.json",
1249 ".babelrc",
1250 ".babelrc.js",
1251 ".babelrc.cjs",
1252 ".babelrc.mjs",
1253 ].filter(Boolean),
1254 )("should load %s asynchronously", async name => {
1255 const esm = isMJS(name);
1256 if (esm && skipUnsupportedESM(`should load ${name} asynchronously`)) {
1257 return;
1258 }
1259
1260 const { cwd, tmp, config } = await getTemp(
1261 `babel-test-load-config-${name}`,
1262 );
1263 const filename = tmp("src.js");
1264
1265 await config(name);
1266
1267 await expect(loadOptionsAsync({ filename, cwd }, esm)).resolves.toEqual(
1268 {
1269 ...getDefaults(),
1270 filename,
1271 cwd,
1272 root: cwd,
1273 comments: true,
1274 },
1275 );
1276 });
1277
1278 it("should load .babelignore", () => {
1279 const filename = fixture("config-files", "babelignore", "src.js");
1280
1281 expect(
1282 loadOptions({ filename, cwd: path.dirname(filename) }),
1283 ).toBeNull();
1284 });
1285
1286 test.each(
1287 pairs([
1288 "package.json",
1289 ".babelrc",
1290 ".babelrc.js",
1291 ".babelrc.cjs",
1292 ".babelrc.mjs",
1293 ".babelrc.json",
1294 ]),
1295 )("should throw if both %s and %s are used", async (name1, name2) => {
1296 const esm = isMJS(name1) || isMJS(name2);
1297 if (
1298 esm &&
1299 skipUnsupportedESM(
1300 `should throw if both ${name1} and ${name2} are used`,
1301 )
1302 ) {
1303 return;
1304 }
1305
1306 const { cwd, tmp, config } = await getTemp(
1307 `babel-test-dup-config-${name1}-${name2}`,
1308 );
1309
1310 await Promise.all([config(name1), config(name2)]);
1311
1312 await expect(
1313 loadOptionsAsync({ filename: tmp("src.js"), cwd }, esm),
1314 ).rejects.toThrow(/Multiple configuration files found/);
1315 });
1316
1317 it("should ignore package.json without a 'babel' property", () => {
1318 const filename = fixture("config-files", "pkg-ignored", "src.js");
1319
1320 expect(loadOptions({ filename, cwd: path.dirname(filename) })).toEqual({
1321 ...getDefaults(),
1322 filename: filename,
1323 cwd: path.dirname(filename),
1324 root: path.dirname(filename),
1325 comments: true,
1326 });
1327 });
1328
1329 test.each`
1330 config | dir | error
1331 ${".babelrc"} | ${"babelrc-error"} | ${/Error while parsing config - /}
1332 ${".babelrc.json"} | ${"babelrc-json-error"} | ${/Error while parsing config - /}
1333 ${".babelrc.js"} | ${"babelrc-js-error"} | ${/Babelrc threw an error/}
1334 ${".babelrc.cjs"} | ${"babelrc-cjs-error"} | ${/Babelrc threw an error/}
1335 ${".babelrc.mjs"} | ${"babelrc-mjs-error"} | ${/Babelrc threw an error/}
1336 ${"package.json"} | ${"pkg-error"} | ${/Error while parsing JSON - /}
1337 `(
1338 "should show helpful errors for $config",
1339 async ({ config, dir, error }) => {
1340 const esm = isMJS(config);
1341 if (
1342 esm &&
1343 skipUnsupportedESM(`should show helpful errors for ${config}`)
1344 ) {
1345 return;
1346 }
1347
1348 const filename = fixture("config-files", dir, "src.js");
1349
1350 await expect(
1351 loadOptionsAsync({ filename, cwd: path.dirname(filename) }, esm),
1352 ).rejects.toThrow(error);
1353 },
1354 );
1355
1356 it("loadPartialConfig should return a list of files that were extended", () => {
1357 const filename = fixture("config-files", "babelrc-extended", "src.js");
1358
1359 expect(
1360 babel.loadPartialConfig({ filename, cwd: path.dirname(filename) }),
1361 ).toEqual({
1362 babelignore: fixture("config-files", ".babelignore"),
1363 babelrc: fixture("config-files", "babelrc-extended", ".babelrc"),
1364 config: undefined,
1365 fileHandling: "transpile",
1366 options: {
1367 ...getDefaults(),
1368 filename: filename,
1369 cwd: path.dirname(filename),
1370 root: path.dirname(filename),
1371 comments: true,
1372 },
1373 files: new Set([
1374 fixture("config-files", ".babelignore"),
1375 fixture("config-files", "babelrc-extended", ".babelrc-extended"),
1376 fixture("config-files", "babelrc-extended", ".babelrc"),
1377 ]),
1378 });
1379 });
1380
1381 it("loadPartialConfig should return null when ignored", () => {
1382 const filename = fixture("config-files", "babelignore", "src.js");
1383
1384 expect(
1385 babel.loadPartialConfig({ filename, cwd: path.dirname(filename) }),
1386 ).toBeNull();
1387 });
1388
1389 it("loadPartialConfig should return a list of files when ignored with showIgnoredFiles option", () => {
1390 const filename = fixture("config-files", "babelignore", "src.js");
1391
1392 expect(
1393 babel.loadPartialConfig({
1394 filename,
1395 cwd: path.dirname(filename),
1396 showIgnoredFiles: true,
1397 }),
1398 ).toEqual({
1399 babelignore: fixture("config-files", "babelignore", ".babelignore"),
1400 babelrc: undefined,
1401 config: undefined,
1402 fileHandling: "ignored",
1403 options: {
1404 ...getDefaults(),
1405 filename: filename,
1406 cwd: path.dirname(filename),
1407 root: path.dirname(filename),
1408 },
1409 files: new Set([
1410 fixture("config-files", "babelignore", ".babelignore"),
1411 ]),
1412 });
1413 });
1414
1415 it("loadPartialConfig can be called with no arguments", () => {
1416 const cwd = process.cwd();
1417
1418 try {
1419 process.chdir(fixture("config-files", "babelrc-extended"));
1420 expect(() => babel.loadPartialConfig()).not.toThrow();
1421 } finally {
1422 process.chdir(cwd);
1423 }
1424 });
1425 });
1426
1427 it("should throw when `test` presents but `filename` is not passed", () => {
1428 expect(() => loadOptions({ test: /\.ts$/, plugins: [] })).toThrow(
1429 /Configuration contains string\/RegExp pattern/,
1430 );
1431 });
1432
1433 it("should throw when `preset` requires `filename` but it was not passed", () => {
1434 expect(() => {
1435 loadOptions({
1436 presets: ["./fixtures/config-loading/preset4"],
1437 });
1438 }).toThrow(/Preset \/\* your preset \*\/ requires a filename/);
1439 });
1440
1441 it("should throw when `preset.overrides` requires `filename` but it was not passed", () => {
1442 expect(() => {
1443 loadOptions({
1444 presets: ["./fixtures/config-loading/preset5"],
1445 });
1446 }).toThrow(/Preset \/\* your preset \*\/ requires a filename/);
1447 });
1448
1449 it("should not throw error on $schema property in json config files", () => {
1450 const filename = fixture(
1451 "config-files",
1452 "babel-config-json-$schema-property",
1453 "babel.config.json",
1454 );
1455 expect(() => {
1456 babel.loadPartialConfig({
1457 filename,
1458 cwd: path.dirname(filename),
1459 });
1460 }).not.toThrow();
1461 });
1462 });
1463 });