Compare commits

...

165 Commits

Author SHA1 Message Date
Henry Zhu
3f5b7554b8 v7.1.2 2018-09-28 18:19:38 -04:00
Henry Zhu
ead23d7112 v7.1.1 2018-09-28 16:02:43 -04:00
Nicolò Ribaudo
626f47982e Do not unpack array patterns that update a referenced binding (#8535)
Fixes #8528
2018-09-28 11:45:42 -04:00
Brian Ng
55faa27b93 Run test262 tests for exportNamespaceFrom (#8780) 2018-09-27 14:48:58 -05:00
Sampo Kivistö
090c364a90 Improved build performance by optimizing makeMappingKey method. (#8744) 2018-09-26 13:16:40 -07:00
Pig Fang
f38be13113 TypeScript: reserve unknown as TSUnknownKeyword (#8755) 2018-09-25 12:19:32 -05:00
Nicolò Ribaudo
889cdb8da5 Use babel-check-duplicated-nodes (#8768) 2018-09-25 10:00:48 -05:00
Nicolò Ribaudo
af694ebae1 [decorators] Support async and generator methods (#8742) 2018-09-25 10:03:03 +02:00
Brian Ng
a19b72e46d jest@23.6.0 (#8764) 2018-09-24 18:53:41 -05:00
Brian Ng
38cf318f61 Bump lint-related deps (#8765) 2018-09-24 18:09:54 -05:00
Brian Ng
be027fd36c Bump babel-related deps (#8763) 2018-09-24 17:19:01 -05:00
Nicolò Ribaudo
5150f5f500 [decorators] Fields are enumerable (#8761) 2018-09-24 23:36:32 +02:00
Brian Ng
9f407e0735 Fix some missing parens cases with OptionalMemberExpression in generator (#8751) 2018-09-23 10:54:13 -05:00
Logan Smyth
3b0f9a9f1e Delete undefined options so we handle old core versions with new CLI versions. (#8728) 2018-09-19 08:56:40 -07:00
Brian Ng
9e7c7f5683 Handle throw expressions in generator (#8727)
Fixes #8716
2018-09-18 18:10:48 -04:00
Henry Zhu
fad74959f8 v7.1.0 2018-09-17 15:29:37 -04:00
Henry Zhu
2b68181af2 add ignore files [skip ci] 2018-09-17 15:28:38 -04:00
Brian Ng
9b4b436e1f Fix parsing of newline between 'async' and 'function' (#8698) 2018-09-16 22:09:23 -05:00
Logan Smyth
aa33303112 Fix logic/Flow error with versionRange. (#8714) 2018-09-15 15:37:03 -07:00
Logan Smyth
bd0c62dc0c Allow users to choose how the configuration root is selected. (#8660) 2018-09-15 13:03:46 -07:00
Nicolò Ribaudo
aac8118b7f Update helpers version fro 7.0.1 to 7.0.2 (#8703) 2018-09-14 22:55:27 +02:00
Brian Ng
8897b67f40 Fix TSParameterProperty getting lost with transform-classes (#8682) 2018-09-14 10:30:15 -05:00
Brian Ng
380f2a0297 Fix typescript parsing typed object shorthand methods (#8677) 2018-09-14 10:20:59 -05:00
Brian Ng
402bd1cc42 Adjust TSParameterProperty handling to work with transform-parameters (#8695) 2018-09-14 10:20:43 -05:00
Brian Ng
6059637f09 babel-eslint@9.0.0 (#8680) 2018-09-14 10:20:22 -05:00
Brian Ng
880fc1f54e Fix es6.string.iterator mapping in babel-preset-env (#8693) 2018-09-14 10:20:00 -05:00
Henry Zhu
fc1a52cb75 remove force publish, temp tag [skip ci] (#8679) 2018-09-14 10:47:37 -04:00
Nicolò Ribaudo
82a0e681ab Add "decoratorsBeforeExport" to the babel-standalone presets (#8649) 2018-09-13 10:52:40 +02:00
Retsam
8f5e9e143b Fixes the link to the babel-parser output docs (#8678) [skip ci]
The babel-parser output documentation has been moved to the babeljs.io website, but the link in CONTRIBUTING.md is still pointing to the repository itself.
2018-09-12 09:18:20 +02:00
Logan Smyth
13798feefb Fix prerelease checks in .availableHelper and transform-runtime definitions. (#8659) 2018-09-10 18:25:21 -07:00
Retsam
9ad8b2bb2c Fix typescript import elision (#8666) 2018-09-10 17:42:22 -05:00
宋铄运
d2b559af59 Add issue.sh to Patreon Silver sponsors (#8647) [skip ci] 2018-09-10 08:48:44 -06:00
James Garbutt
252660f248 ts generator: allow reserved keywords in interfaces (#8627) 2018-09-10 09:22:36 -05:00
Sven Sauleau
0e7d7cfccc Merge pull request #8661 from babel/feat-run-fix-json-on-fix
Makefile: run fix json on fix
2018-09-10 09:41:55 +02:00
Sven SAULEAU
53c6c98bdb chore: fix-json new options 2018-09-10 08:04:32 +02:00
Sven SAULEAU
802fc2ac80 feat: invoke fix-json on fix target 2018-09-10 08:04:20 +02:00
Siddharth Parmar
e372129d00 Add tests for static math methods (#8626) 2018-09-09 18:08:34 -07:00
Logan Smyth
79b2af5997 Format fixture JSON with Prettier. (#8658) 2018-09-09 17:57:52 -07:00
Frederic Germain
45c28fa785 Use eslint-local-rules plugin
This allows to avoid having errors in editors that
supports eslint

cf https://github.com/eslint/eslint/issues/8769
2018-09-07 16:54:07 -07:00
Mateusz Burzyński
1e1a89ca70 Allow regular plugins/presets resolution algorithm for packages outside of the monorepo (#7582) 2018-09-07 16:37:10 -07:00
Jeff Rafter
1b03906da4 Allow users to specify a module for inline scripts (#6223) 2018-09-07 16:33:19 -07:00
Maaz Syed Adeeb
7accee9c24 [TS] Transform multiple assert and assign correctly (#7217)
* Transform multiple assert and assign correctly

* Handling nested TSAsExpressions in the transform
2018-09-07 16:23:18 -07:00
Logan Smyth
7273cf8fe5 Fix a linting error. 2018-09-07 16:09:25 -07:00
Aaron Ang
dad55ef1d6 Test babel-cli --source-maps and errors (#5377) 2018-09-07 15:30:24 -07:00
Nicolò Ribaudo
9aec4ad159 Add support for the new decorators proposal (#7976) 2018-09-07 15:58:42 +02:00
Vikram Rangaraj
29a2878973 Use jsonc to parse babelrc comments in markdown files (#8643) [skip ci]
* [skip ci] use markdown jsonc to parse comments in README files

* [skip ci] change json to jsonc type in other markdown files
2018-09-07 15:50:51 +02:00
Elian Ibaj
9eef660daa Allow patterns as argument of RestElement (#8414) 2018-09-06 22:35:37 +02:00
Nathan Shane
d9149aa2f3 Fix broken links to old changelogs (#8635) [skip ci] 2018-09-06 00:58:50 +02:00
Brian Ng
58017044a3 Bump flow to 0.80 and fix sourceType error (#8630) 2018-09-05 09:00:53 -05:00
Nicolò Ribaudo
c5279eeca4 [static private] Use explicit descriptors instead of an object (#8620)
This is similar to ec69b4bb12, which
was about private instance fields.

Private properties can be non-writable (thanks to decorators), or have
get/set accessors. If we stored this information on the `privateClass`
object, we would need to always use `Object.getOwnPropertyDescriptor`
before reading or writing a property because accessors need to be called
with the correct `this` context (it should be the actual class, not the
object hat stores the private properties). This commit simplifies that
operation a bit by removing the container object.

It also have another advantage, which instance fields already have
thanks to the use of separate weakmaps: unused private static fields
can be tree-shaken away or garbage-collected, while properties of an
object can't. Also, they can be easilier minified.
2018-09-05 15:08:40 +02:00
Logan Smyth
f6643d1804 Merge pull request #8624 from loganfsmyth/misc-fixes
Verify 'sourceMap' option with hasOwnProperty, and verify string-typed 'version'
2018-09-04 09:27:10 -07:00
Sven Sauleau
07fae82a8a fix(types): missing unambiguous sourceType (#8610) 2018-09-04 10:03:48 -05:00
Logan Smyth
fc91b94a86 Fix misplaced dependency from PR #8616 2018-09-03 23:36:34 -07:00
Nicolò Ribaudo
d4e23b5b2a [static private] Unify loose handling of static and instance props (#8614) 2018-09-04 08:10:46 +02:00
Siddharth Parmar
262787bd92 Add static Math methods to plugin-transform-runtime (#8616)
* Add static Math methods to plugin-transform-runtime

* Remove methods which are not part of TC39 standard

* Use semver to conditionally include Math module
2018-09-03 20:49:51 -07:00
Logan Smyth
9232e8b405 Validate the type of the 'version' option for transform-runtime. 2018-09-03 18:44:10 -07:00
Logan Smyth
dd985c3be3 Verify 'sourceMap' with hasOwnProperty since it can be falsy. 2018-09-03 12:22:22 -07:00
Nicolò Ribaudo
4beb977f15 [static private] Use correct min version in helpers (#8613)
* [staic private] Use correct min version in helpers

* Always use patch version
2018-09-03 11:36:26 -07:00
Adam Noakes
679e4b8f37 align regenerator runtime version (#8618) 2018-09-03 10:03:30 -07:00
Sven Sauleau
fc9becfdf2 Merge pull request #8170 from AviVahl/master
@babel/parser: expose a TypeScript definition file from package
2018-09-03 08:15:56 +02:00
Sven Sauleau
6893b7e7d2 fix: [skip ci] consistent naming 2018-09-03 08:09:26 +02:00
Bartosz Kaszubowski
ffc82374d2 Fix version badges in monorepo README (#8534)
* Fix version badges in monorepo README

Badges caching disabled by removing the maxAge parameter from image URLs to ensure that always the latest version of package is displayed.

* adjust version badges cache time to one hour
2018-09-02 21:49:01 -07:00
Logan Smyth
2921f6cdb1 Pass missing caller metadata for .babelrc files. (#8601) 2018-09-01 15:46:38 -07:00
Robin Ricard
fb66fa6f90 Private Static Fields Features: Stage 3 (#8205)
* Private Static Class Fields Implementation

* Redo testing without class transform for static private

* Add a call() test for private static

* Use Object.defineProperty in loose mode
2018-09-01 00:42:18 -04:00
Sven Sauleau
eda804da11 update COC contact (#8591) 2018-08-31 09:33:27 -05:00
Ryunosuke Sato
15f456651a Fix grammar in error message at @babel/plugin-transform-runtime (#8581) 2018-08-29 11:57:36 -07:00
Nicolò Ribaudo
9d244ae66b More helpful error message for missing decoratorsBeforeExport in parser (#8576) 2018-08-29 09:02:18 -05:00
Henry Zhu
04d09cc754 add access public to all packages [skip ci] (#8573)
If people copy paste to make an new package they might miss this and we will get a publish error later so figured we should add it to all.
2018-08-29 09:54:53 -04:00
Sebastian McKenzie
5447a40719 Remove LICENSE email and refer to other contributors (#8574) [skip ci]
Been years since I've been involved in Babel, so I feel like referencing other contributors is more appropriate now.
2018-08-29 09:48:10 -04:00
Sven Sauleau
d45ea2e5ff Merge pull request #8561 from siddhant1/master
Added pronounciation of babel
2018-08-28 07:45:22 +02:00
Henry Zhu
aeefec5f13 add link to audio [skip ci] 2018-08-28 00:32:44 -04:00
siddhant
9a3af17560 Added pronounciation of babel 2018-08-28 08:29:54 +05:30
Henry Zhu
bcec62c0ac update ourselves to 7.0 (#8558) 2018-08-27 19:22:35 -04:00
Henry Zhu
90fb82a535 v7.0.0 2018-08-27 17:41:21 -04:00
Henry Zhu
8a45fba510 testing temp tag [skip ci] 2018-08-27 17:32:28 -04:00
Logan Smyth
079780b432 Make it easier to re-run local prod builds (#8556) [skip ci] 2018-08-27 13:43:45 -04:00
Henry Zhu
4e64807afc use temp tag while having publishing issues [skip ci] 2018-08-27 13:16:39 -04:00
Henry Zhu
814c564c45 v7.0.0-rc.4 2018-08-27 12:42:00 -04:00
Henry Zhu
7a104e3e1d bump source-map-support (#8553) 2018-08-27 12:32:42 -04:00
Henry Zhu
b98799557a Lerna: remove exact [skip ci] (#8554)
We only wanted all the dependencies to be exact in the pre-release because of breaking changes. This will make it use the default `^`
2018-08-27 12:27:32 -04:00
Logan Smyth
1ac46a256d Merge pull request #8547 from loganfsmyth/runtime-cleanup
Remove nonstandard functions and fake prototype methods from babel-runtime
2018-08-26 21:25:50 -07:00
Logan Smyth
50d3c09883 Add support for asyncIterator. 2018-08-26 13:59:33 -07:00
Logan Smyth
508bfad55a Remove non-standard and prototype methods from constructor property use. 2018-08-26 13:59:33 -07:00
Logan Smyth
130814342a Enable a few disabled core-js utils now that we're reading for them in 7.x. 2018-08-26 13:52:19 -07:00
Logan Smyth
e0ee0570be Default highlightCode:true for the parser highlighting. (#8546) 2018-08-26 13:23:43 -07:00
Justin Ridgewell
edbffda091 Cleanup getLineInfo (#8540)
Removes an ignore control comment
2018-08-26 13:27:06 -04:00
Justin Ridgewell
72ee1816a4 Update to ES6 String methods (#8541) 2018-08-26 13:26:51 -04:00
tsangint
e875fc7bc1 Update url in buildUnknownError tips (#8544) 2018-08-26 15:00:32 +02:00
Justin Ridgewell
524d847763 Flatten TokenType class hierarchy (#8537)
`KeywordTokenType` and `BinopTokenType` were just meant to be factory
helpers, there's no reason for a class hierarchy.
2018-08-25 20:02:32 -04:00
Justin Ridgewell
5899940156 Update parser whitespace for clarity (#8539)
* Update parser whitespace for clarity

Has the nice benefit of not requiring a charCode to String conversion.

* Remove test262 exceptions

Per https://github.com/tc39/ecma262/pull/1218#issuecomment-395340891,
ECMA262 follows whatever the latest Unicode version specifies for Zs
Space_Separator category. MONGOLIAN VOWEL SEPARATOR was moved to the Cf
Other_Format category in Unicode 8.
2018-08-25 19:12:38 -04:00
Logan Smyth
595240f071 Add a 'whitelist' option for the external-helpers plugin to mirror the helper builder. (#8531) 2018-08-24 15:10:46 -07:00
Henry Zhu
cada040bec v7.0.0-rc.3 2018-08-24 14:06:00 -04:00
Nicolò Ribaudo
1f9b2a5c41 [_wrapNativeSuper] Don't wrap non-native constructors (#8501) 2018-08-24 19:58:49 +02:00
Logan Smyth
39fa102ee8 Use supportsStaticESM to toggle runtime module usage. (#8520) 2018-08-24 10:48:47 -07:00
Honza Javorek
e841ccca34 Upgrade slash (#8527) [skip ci]
The 1.x versions do not contain a full license text.
2018-08-24 11:31:27 -04:00
Artem Yavorsky
4249dbc8ea Add browserslist 4 support. (#8509) 2018-08-23 20:09:18 -05:00
Standa Opichal
a7cc3325cd Add LICENSE file to published npm packages [skip ci] (#8409) 2018-08-23 19:49:27 -04:00
Logan Smyth
023044c1d4 Reference the CommonJS helpers when a file is not explicitly a module. (#8518) 2018-08-23 15:09:14 -07:00
Rafael de Oleza
22bcfbe469 Fix path.scope.rename() to not change break clauses (#8478)
* Make labels on break and continue statements not referenced

* Add test for imports and labels with the same name
2018-08-23 14:20:57 -07:00
Jason Quense
47e05d70f3 Fixed issue with non-simple property paths in object-rest-spread loose mode (#8514)
* fix: object rest with default values bug

fixes #8323

* rename variable
2018-08-23 15:53:31 +02:00
Nicolò Ribaudo
c5e3b6d4bc [decorators] Don't set writable on accessors (#8513) 2018-08-23 00:54:28 +02:00
Logan Smyth
b04de1196a Rename exported functions where name conflicts with param. (#8505) 2018-08-21 13:54:29 -07:00
Henry Zhu
d07cef244e Update Babel to rc.2 (#8504) 2018-08-21 15:31:07 -05:00
dnalborczyk
6c68ca8e0a adjust supported npm versions to v3 (#8359) [skip ci] 2018-08-21 15:44:17 -04:00
Henry Zhu
f1d774b34f v7.0.0-rc.2 2018-08-21 15:22:07 -04:00
Jarda Snajdr
8874c5c481 Add missing es7.promise.finally polyfill when using useBuiltIns: usage (#8500)
Usage of a `finally` instance method should trigger import of the `es7.promise.finally` polyfill, but it doesn't. This PR adds the missing definition and a test.
2018-08-21 14:53:11 -04:00
Yi Li
b439013cd4 Fix trailingComments for FunctionExpression that is CallExpression arguments (#8488) 2018-08-21 12:29:11 -05:00
Nicolò Ribaudo
f8b0a5579f Remove File#resolveModuleSource (#8470) 2018-08-20 12:14:55 -07:00
Logan Smyth
2a4f162366 Merge pull request #8485 from loganfsmyth/caller-option
Allow preset-env to toggle module handling based on flags from the caller (like babel-loader)
2018-08-20 10:44:11 -07:00
Brian Ng
55295cc545 Add initial ES2019 and saf12/elec3 support in env (#8438) 2018-08-20 12:32:18 -05:00
Nicolò Ribaudo
59e9c6322b Remove hub.file usage from babel-core 2018-08-20 19:30:29 +02:00
Yongxu Ren
0fd3da110d Rewrite Hub as interface #5047 2018-08-20 19:30:29 +02:00
Logan Smyth
d60c5e1736 Expose caller.supportsStaticESM as a flag to change preset-env behavior. 2018-08-20 10:27:55 -07:00
Logan Smyth
90bebe7186 Pass the caller.name option in Babel's own callers. 2018-08-20 10:27:54 -07:00
Logan Smyth
8d6ed7e0aa Expose an api.caller(...) handler for presets to access caller metadata. 2018-08-20 10:27:54 -07:00
Logan Smyth
8f4bae8ea4 Expose optional caller metadata to Babel ignore/only/test/include/exclude functions. 2018-08-20 10:27:54 -07:00
Logan Smyth
2c3c12fdf7 Enforce a limited set of cache key values for plugins/presets for future caching. 2018-08-20 10:12:19 -07:00
Logan Smyth
25d2f59018 Ensure that presets properly flatten their options. 2018-08-20 10:12:19 -07:00
Logan Smyth
3a399d1eb9 Cache individual programmatic descriptors along with the overall list. (#8494) 2018-08-20 10:08:21 -07:00
Logan Smyth
c2a2e24965 Take top-level config source into consideration when processing nested env/overrides. (#8493) 2018-08-19 21:46:09 -07:00
Logan Smyth
ef68114d67 Fix typo in sourcemap filtering. 2018-08-19 16:37:29 -07:00
Logan Smyth
ca639b4262 Preserve 'false'-options for disabled plugins/presets so that callers can use that to toggle behavior. (#8474) 2018-08-19 16:22:27 -07:00
wtgtybhertgeghgtwtg
7a51d72345 Bump js-tokens in @babel/highlight. (#8490) 2018-08-19 07:35:16 -04:00
dnalborczyk
ab8555a867 Update dependencies (#8364) 2018-08-17 10:26:25 -05:00
Nicolò Ribaudo
0136a26af7 Fix conflict in tests (#8486) 2018-08-17 11:36:10 +02:00
Yeonghoon Park
c75a00bd56 Fix default descriptor setting for class properties with decorators (#7429)
(legacy decorators)
2018-08-17 10:49:03 +02:00
Logan Smyth
ffa8e6cbae Allow babel-plugin/preset to be in package names outside the prefix, when used in a scope. (#8473) 2018-08-16 15:13:52 -07:00
Nikolay Emrikh
5043ec78bc Fixes setter paratemer default value (#8479)
* Fixes setter paratemer default value

* Not changes doesn't mutate loose variable
2018-08-16 01:54:50 -04:00
Nicolò Ribaudo
3989213e37 Remove unused file (#8472) 2018-08-15 09:08:28 +02:00
Nicolò Ribaudo
d79b5eeeff Require decoratorsBeforeExport option for decorators (#8465)
* Require decoratorsBeforeExport option for syntax-decorators

* Also babylon

* Enable test
2018-08-15 09:04:52 +02:00
Logan Smyth
1e0b649485 Allow transform-runtime to insert runtime references with absolute paths. (#8435) 2018-08-14 16:11:19 -07:00
Laxman
8c65230258 Fix link to babel-parser (#8464) [skip ci] 2018-08-13 15:54:07 +02:00
Mauro Bringolf
427aff559f Fix decorators interop bug with class field tdz
Co-authored-by: Jan Buschtöns <jan@buschtoens.me>
2018-08-13 08:57:09 +02:00
wtgtybhertgeghgtwtg
de16ac08be Remove lodash where it isn't used. (#8446) 2018-08-09 23:21:41 -04:00
Henry Zhu
0a958861c9 v7.0.0-rc.1 2018-08-09 16:06:08 -04:00
Henry Zhu
904bcaffe3 fix peer deps [skip ci] (#8445)
Should be anything 7.x
2018-08-09 15:59:14 -04:00
宋铄运
e855987c51 update sponsor [skip ci] (#8444)
Add issue.sh sponsor from Patreon
2018-08-09 15:58:28 -04:00
Henry Zhu
8b1406127a v7.0.0-rc.0 2018-08-09 11:56:00 -04:00
Henry Zhu
c8bb450032 remove proposals polyfills from default import [skip ci] (#8440)
The default import is replaced with only polyfills that are Stage 4; this is in alignment with how we have removed the Stage presets. This also would mean we would need to add new imports when necessary, but that can be in a future release.
2018-08-09 11:43:45 -04:00
Logan Smyth
b6db036ff7 Require v1.1.0 so that correct filter params are passed. (#8436)
PR #8418 introduced some new logic that uses the third parameter of `fs-readdir-recursive`'s `filter` option, the current directory, but missed that our dependencies only required `^1.0.0`, while that parameter was actually added in `1.1.0`. This means that if some other dependency forced a downgrade in the version to satisfy some range, or the user already had 1.0.0 module installed locally, it could cause problems,
2018-08-07 23:28:36 -04:00
Sam Grace
6476a0d089 Whitelist experimental-modules flag for babel-node (#8336) [skip ci] 2018-08-06 11:45:38 -04:00
Henry Zhu
6695f5e2f7 v7.0.0-beta.56 2018-08-03 21:02:42 -04:00
Henry Zhu
86ce2e4e0d remove old deps [skip ci] 2018-08-03 20:42:45 -04:00
Henry Zhu
8cffbbae75 Split @babel/runtime into 2 modules via @babel/runtime-corejs2 (#8266)
In Babel 6, we had `@babel/runtime` which _always_ uses `core-js` in its helpers, meaning that anyone who wants to use our helpers in a centralized modular way had to also use core-js, which isn't always ideal.

Early in the Babel 7 alpha, we added a `useBuiltins: true` option that would use separate copies of the helpers that would skip loading `core-js`, but this _still_ requires users to have an indirect npm dependency on `core-js`.

This PR splits our setup into two separate runtimes:

* ```
  'plugins': [
    ['transform-runtime'],
  ]
  ```
  with `npm install --save @babel/runtime` that just includes our helpers, and relies on users to globally polyfill any APIs they need.
* ```
  'plugins': [
    ['transform-runtime', { corejs: 2 }],
  ]
  ```
  with `npm install --save @babel/runtime-corejs2` that includes everything `@babel/runtime` does, but also includes a passthrough API for `corejs@2.x` and rewrites all of the helper modules to reference `core-js`.
2018-08-03 15:13:33 -04:00
Jan Schmidle
cb51704745 Babel cli fix recursion in file mode (#8418)
* added test case

* remove unnessecary parameter

* check for type directory as well in readRecursive filter
2018-08-03 09:06:27 -07:00
Logan Smyth
a8224d40e2 Split @babel/runtime into two separate runtime modules. 2018-08-02 19:25:07 -07:00
Logan Smyth
3210a7a873 Default to non-corejs helpers. 2018-08-02 19:24:41 -07:00
Logan Smyth
9c598a8e28 Build an explicit runtime. 2018-08-02 19:23:47 -07:00
Logan Smyth
a149466001 Move build-dist script to the runtime transform. 2018-08-02 19:23:47 -07:00
Logan Smyth
ec8330870e Refactor the runtime build-dist script. 2018-08-02 19:22:23 -07:00
Logan Smyth
363c5923f0 Remove unused options.json file. 2018-08-02 19:21:40 -07:00
Logan Smyth
8173b6e694 Merge pull request #8398 from loganfsmyth/helper-whitelisting
Only reference helpers from external/runtime helpers if they are known to be available.
2018-08-02 19:20:56 -07:00
Logan Smyth
e2d64f146c Only reference helpers from external helpers or runtime helpers if they are known to be available. 2018-08-02 18:44:56 -07:00
Logan Smyth
9392783738 Remove helpersNamespace in favor of helperGenerator. 2018-08-02 18:44:56 -07:00
Logan Smyth
810b7916c2 Expose an API to check if a helper is available in a given version range. 2018-08-02 18:44:56 -07:00
Logan Smyth
eb0e999987 Expose a minimum required Babel version for each helper. 2018-08-02 18:44:56 -07:00
kalenikalexander
5c728ea609 Fix private property parsing in Flow (#8340)
* Fix private property parsing in Flow

* Flow tests updated

* Fix type error

* Appropriate name was given to test folder

* Fix

* Empty

* Correct type annotation

* Add required changes in generator package

* Add required changes in flow-strip-types
2018-08-02 08:38:58 +02:00
Leong Jia Meng
b8f9ebf638 Update Documentation[skip ci] (#8412) 2018-08-01 10:33:11 -05:00
Brian Ng
55ca90b3fc Allow TSInterfaceDeclaration to be default export (#8408)
<!--
Before making a PR, please read our contributing guidelines
https://github.com/babel/babel/blob/master/CONTRIBUTING.md

For issue references: Add a comma-separated list of a [closing word](https://help.github.com/articles/closing-issues-via-commit-messages/) followed by the ticket number fixed by the PR. (it should be underlined in the preview if done correctly)

If you are making a change that should have a docs update: submit another PR to https://github.com/babel/website
-->

| Q                        | A <!--(Can use an emoji 👍) -->
| ------------------------ | ---
| Fixed Issues?            | Fixes #7118
| Patch: Bug Fix?          | Y
| Major: Breaking Change?  | N
| Minor: New Feature?      | N
| Tests Added + Pass?      | Yes
| Documentation PR Link    | 
| Any Dependency Changes?  |
| License                  | MIT
2018-07-31 12:57:57 -05:00
Brian Ng
1a0fe993f5 Ensure esmodule targets are parsed by browserslist (#8403) 2018-07-31 07:33:02 -05:00
Logan Smyth
02760d0f70 Run transform-runtime on the standalone bundle so it stays ES5-compatible. (#8024) 2018-07-29 16:52:11 -07:00
Avi Vahl
0e8830f3a8 Fix unneeded uppercasing in comment 2018-06-15 02:46:02 +03:00
Avi Vahl
4cdfee768b Add jsdocs to parse() and parseExpression()
also change parameter name to match docs
2018-06-15 02:42:32 +03:00
Avi Vahl
adbf2a15f9 Clearer naming of interfaces 2018-06-15 01:12:58 +03:00
Avi Vahl
ca65781132 @babel/parser: expose a TypeScript definition file from package
This allows the new parser package to be used in TypeScript projects, with static type checking and auto-completions. IDEs like VSCode will use this to show auto completions even in JavaScript projects, which is a huge benefit to users wanting to use the parser directly.

This PR follows the auto-generated .d.ts that was added to @babel/types in #7101

- took outdated DefinitelyTyped babylon .d.ts and updated it using new site's documentation.
- added "typings" folder to package, with the new .d.ts
- connected new .d.ts via package.json's "types" field. also adjusted "files" so folder will be published.
- definition file uses TypeScript 2.9's new `import('package').Type` syntax.
2018-06-15 01:04:49 +03:00
1634 changed files with 13390 additions and 5286 deletions

View File

@@ -4,8 +4,9 @@
package.json
lerna.json
packages/babel-runtime
!packages/babel-runtime/scripts
!packages/babel-runtime/core-js.js
!packages/babel-plugin-transform-runtime/scripts
!packages/babel-runtime-corejs2/core-js.js
packages/babel-runtime-corejs2
packages/*/node_modules
packages/*/lib
packages/*/dist

View File

@@ -1,11 +1,9 @@
{
"root": true,
"extends": "babel",
"plugins": ["prettier"],
"plugins": ["local-rules", "prettier"],
"rules": {
"curly": ["error", "multi-line"],
"prettier/prettier": "error",
"no-case-declarations": "error"
"prettier/prettier": "error"
},
"env": {
"node": true
@@ -14,8 +12,8 @@
{
"files": ["packages/*/src/**/*.js", "codemods/*/src/**/*.js"],
"rules": {
"no-undefined-identifier": "error",
"no-deprecated-clone": "error"
"local-rules/no-undefined-identifier": "error",
"local-rules/no-deprecated-clone": "error"
}
},
{

View File

@@ -5,6 +5,7 @@
.*/codemods/.*/lib
.*/codemods/.*/test
.*/node_modules/conventional-changelog-core/
.*/node_modules/module-deps/
[include]
packages/*/src

34
.gitignore vendored
View File

@@ -1,6 +1,9 @@
.DS_Store
/node_modules
/packages/*/node_modules
/packages/*/LICENSE
!/packages/babel-parser/LICENSE
!/packages/babel-plugin-transform-object-assign/LICENSE
*.log
*.cache
/build
@@ -12,24 +15,27 @@ coverage
dist
/.package.json
package-lock.json
/packages/babel-runtime/core-js/**/*.js
!/packages/babel-runtime/core-js/map.js
/packages/babel-runtime/helpers/*.js
!/packages/babel-runtime/helpers/toArray.js
!/packages/babel-runtime/helpers/iterableToArray.js
!/packages/babel-runtime/helpers/temporalRef.js
/packages/babel-runtime/helpers/builtin/*.js
!/packages/babel-runtime/helpers/builtin/toArray.js
!/packages/babel-runtime/helpers/builtin/iterableToArray.js
!/packages/babel-runtime/helpers/builtin/temporalRef.js
/packages/babel-runtime/helpers/builtin/es6/*.js
!/packages/babel-runtime/helpers/builtin/es6/toArray.js
!/packages/babel-runtime/helpers/builtin/es6/iterableToArray.js
!/packages/babel-runtime/helpers/builtin/es6/temporalRef.js
/packages/babel-runtime/helpers/es6/*.js
!/packages/babel-runtime/helpers/es6/toArray.js
!/packages/babel-runtime/helpers/es6/iterableToArray.js
!/packages/babel-runtime/helpers/es6/temporalRef.js
/packages/babel-runtime/helpers/esm/*.js
!/packages/babel-runtime/helpers/esm/toArray.js
!/packages/babel-runtime/helpers/esm/iterableToArray.js
!/packages/babel-runtime/helpers/esm/temporalRef.js
/packages/babel-runtime-corejs2/helpers/*.js
!/packages/babel-runtime-corejs2/helpers/toArray.js
!/packages/babel-runtime-corejs2/helpers/iterableToArray.js
!/packages/babel-runtime-corejs2/helpers/temporalRef.js
/packages/babel-runtime-corejs2/helpers/esm/*.js
!/packages/babel-runtime-corejs2/helpers/esm/toArray.js
!/packages/babel-runtime-corejs2/helpers/esm/iterableToArray.js
!/packages/babel-runtime-corejs2/helpers/esm/temporalRef.js
/packages/babel-runtime-corejs2/core-js/**/*.js
!/packages/babel-runtime-corejs2/core-js/map.js
/packages/babel-register/test/.babel
/packages/babel-cli/test/tmp
/packages/babel-node/test/tmp

View File

@@ -7,7 +7,6 @@
"bracketSpacing": true,
"jsxBracketSameLine": false,
"tabWidth": 2,
"parser": "babylon",
"printWidth": 80,
"overrides": [{
"files": [
@@ -16,6 +15,7 @@
"**/packages/*/src/**/*.js",
"**/packages/*/test/**/*.js"
],
"parser": "babylon",
"options": {
"trailingComma": "all"
}

View File

@@ -11,7 +11,7 @@
_Note: Gaps between patch versions are faulty, broken or test releases._
See [CHANGELOG - v4-v6](/.github/CHANGELOG-v4-v6.md) for the v4.x-v6.x changelog.
See [CHANGELOG - v4](/.github/CHANGELOG-v4.md), [CHANGELOG - v5](/.github/CHANGELOG-v5.md), and [CHANGELOG - v6](/.github/CHANGELOG-v6.md) for v4.x-v6.x changes.
See [CHANGELOG - 6to5](/.github/CHANGELOG-6to5.md) for the pre-4.0.0 version changelog.
See [Babylon's CHANGELOG](packages/babylon/CHANGELOG.md) for the Babylon pre-7.0.0-beta.29 version changelog.

View File

@@ -3,7 +3,7 @@
## Our Pledge
In the interest of fostering an open and welcoming environment, we as
contributors and maintainers pledge to making participation in our project and
contributors and maintainers pledge to make participation in our project and
our community a harassment-free experience for everyone, regardless of age, body
size, disability, ethnicity, gender identity and expression, level of experience,
nationality, personal appearance, race, religion, or sexual identity and
@@ -55,7 +55,7 @@ further defined and clarified by project maintainers.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported by contacting hzoo, thejameskyle, sebastian, or loganfsmyth on [Slack](https://slack.babeljs.io/). All
reported by contacting Henry Zhu <hi@henryzoo.com>, Logan Smyth <loganfsmyth@gmail.com> or one of the other [Babel core team members](https://babeljs.io/team). All
complaints will be reviewed and investigated and will result in a response that
is deemed necessary and appropriate to the circumstances. The project team is
obligated to maintain confidentiality with regard to the reporter of an incident.

View File

@@ -24,7 +24,7 @@ contributing, please read the
## Not sure where to start?
- If you aren't just making a documentation change, you'll probably want to learn a bit about a few topics.
- [ASTs](https://en.wikipedia.org/wiki/Abstract_syntax_tree) (Abstract Syntax Tree): The Babel AST [spec](https://github.com/babel/babel/blob/master/packages/babel-parser/ast/spec.md) is a bit different from [ESTree](https://github.com/estree/estree). The differences are listed [here](https://github.com/babel/babel/tree/master/packages/babel-parser#output).
- [ASTs](https://en.wikipedia.org/wiki/Abstract_syntax_tree) (Abstract Syntax Tree): The Babel AST [spec](https://github.com/babel/babel/blob/master/packages/babel-parser/ast/spec.md) is a bit different from [ESTree](https://github.com/estree/estree). The differences are listed [here](https://babeljs.io/docs/en/next/babel-parser.html#output).
- Check out [`/doc`](https://github.com/babel/babel/tree/master/doc) for information about Babel's internals
- Check out [the Babel Plugin Handbook](https://github.com/thejameskyle/babel-handbook/blob/master/translations/en/plugin-handbook.md#babel-plugin-handbook) - core plugins are written the same way as any other plugin!
- Check out [AST Explorer](http://astexplorer.net/#/scUfOmVOG5) to learn more about ASTs or make your own plugin in the browser
@@ -186,7 +186,7 @@ For example, in [`@babel/plugin-transform-exponentiation-operator/test`](https:/
- If you need to expect an error, you can ignore creating the `output.js` file and pass a new `throws` key to the `options.json` that contains the error string that is created.
- The second and preferred type is a test that actually evaluates the produced code and asserts that certain properties are true or false. We do this by creating an [`exec.js`](https://github.com/babel/babel/blob/master/packages/babel-plugin-transform-exponentiation-operator/test/fixtures/exponentian-operator/comprehensive/exec.js) file.
In a fixture test, you simply write out the code you want transformed in `input.js`.
In a fixture test, you simply write out the code you want to transform in `input.js`.
```js
// input.js

View File

@@ -1,6 +1,6 @@
MIT License
Copyright (c) 2014-2018 Sebastian McKenzie <sebmck@gmail.com>
Copyright (c) 2014-2018 Sebastian McKenzie and other contributors
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the

View File

@@ -1,6 +1,6 @@
MAKEFLAGS = -j1
FLOW_COMMIT = 395e045c18d537fcbbc552a96ef2cdcd70b4ab52
TEST262_COMMIT = f90a52b39609a620c0854e0bd0b3a906c930fd17
FLOW_COMMIT = bea8b83f50f597454941d2a7ecef6e93a881e576
TEST262_COMMIT = 06c2f019019cf7850923de4d56828e6dfd9212b8
# Fix color output until TravisCI fixes https://github.com/travis-ci/travis-ci/issues/7967
export FORCE_COLOR = true
@@ -31,7 +31,7 @@ build-preset-env-standalone:
build-dist: build
cd packages/babel-polyfill; \
scripts/build-dist.sh
cd packages/babel-runtime; \
cd packages/babel-plugin-transform-runtime; \
node scripts/build-dist.js
watch: clean clean-lib
@@ -47,10 +47,13 @@ flow:
./node_modules/.bin/flow check --strip-root
lint:
./node_modules/.bin/eslint scripts $(SOURCES) '*.js' --format=codeframe --rulesdir="./scripts/eslint_rules"
./node_modules/.bin/eslint scripts $(SOURCES) '*.js' --format=codeframe
fix:
./node_modules/.bin/eslint scripts $(SOURCES) '*.js' --format=codeframe --fix --rulesdir="./scripts/eslint_rules"
fix: fix-json
./node_modules/.bin/eslint scripts $(SOURCES) '*.js' --format=codeframe --fix
fix-json:
./node_modules/.bin/prettier "{packages,codemod}/*/test/fixtures/**/options.json" --write --loglevel warn
clean: test-clean
rm -rf packages/babel-polyfill/browser*
@@ -104,23 +107,32 @@ test-test262-ci: bootstrap test-test262
test-test262-update-whitelist:
node scripts/tests/test262/run_babel_parser_test262.js --update-whitelist
publish:
git pull --rebase
clone-license:
./scripts/clone-license.sh
prepublish-build:
make clean-lib
rm -rf packages/babel-runtime/helpers
rm -rf packages/babel-runtime/core-js
rm -rf packages/babel-runtime-corejs2/helpers
rm -rf packages/babel-runtime-corejs2/core-js
BABEL_ENV=production make build-dist
make clone-license
prepublish:
git pull --rebase
make prepublish-build
make test
# not using lerna independent mode atm, so only update packages that have changed since we use ^
publish: prepublish
# --only-explicit-updates
./node_modules/.bin/lerna publish --force-publish=* --exact --skip-temp-tag
./node_modules/.bin/lerna publish
make clean
bootstrap: clean-all
yarn --ignore-engines
./node_modules/.bin/lerna bootstrap -- --ignore-engines
make build
cd packages/babel-runtime; \
cd packages/babel-plugin-transform-runtime; \
node scripts/build-dist.js
clean-lib:

View File

@@ -24,7 +24,7 @@
<a href="https://medium.com/friendship-dot-js/i-peeked-into-my-node-modules-directory-and-you-wont-believe-what-happened-next-b89f63d21558"><img alt="Business Strategy Status" src="https://img.shields.io/badge/business%20model-flavortown-green.svg"></a>
</p>
Babel is a community-driven project used by many companies and projects, and is maintained by a group of [volunteers](https://babeljs.io/team). If you'd like to help support the future of the project, please consider:
Babel (pronounced ["babble"](https://soundcloud.com/sebmck/how-to-pronounce-babel)) is a community-driven project used by many companies and projects, and is maintained by a group of [volunteers](https://babeljs.io/team). If you'd like to help support the future of the project, please consider:
- Giving developer time on the project. (Message us on [Twitter](https://twitter.com/babeljs) or [Slack](https://slack.babeljs.io/) for guidance!)
- Giving funds by becoming a sponsor (see below)!
@@ -68,6 +68,10 @@ Become a sponsor and get your logo on our README on Github with a link to your s
Become a sponsor and get your logo on our README on Github with a link to your site. [[Become a sponsor](https://www.patreon.com/henryzhu)]
## Silver
<a href="https://issue.sh/?utm_medium=github&utm_campaign=babel" target="_blank"><img src="https://user-images.githubusercontent.com/5557143/43912065-c8cdff78-9c33-11e8-829a-0b4166ccc215.png"></a>
## Bronze
<a href="http://teamextension.io/" target="_blank"><img src="https://teamextension.io/dist/img/logo/te-logo-compact.png" height="64"></a>

View File

@@ -13,13 +13,18 @@ module.exports = function(api) {
let convertESM = true;
let ignoreLib = true;
let includeRuntime = false;
switch (env) {
// Configs used during bundling builds.
case "babel-parser":
convertESM = false;
ignoreLib = false;
break;
case "standalone":
convertESM = false;
ignoreLib = false;
includeRuntime = true;
break;
case "production":
// Config during builds before publish.
@@ -41,6 +46,10 @@ module.exports = function(api) {
}
const config = {
// Our dependencies are all standard CommonJS, along with all sorts of
// other random files in Babel's codebase, so we use script as the default,
// and then mark actual modules as modules farther down.
sourceType: "script",
comments: false,
ignore: [
// These may not be strictly necessary with the newly-limited scope of
@@ -84,7 +93,29 @@ module.exports = function(api) {
convertESM ? "@babel/transform-modules-commonjs" : null,
].filter(Boolean),
},
],
{
// The vast majority of our src files are modules, but we use
// unambiguous to keep things simple until we get around to renaming
// the modules to be more easily distinguished from CommonJS
test: [
"packages/*/src",
"packages/*/test",
"codemods/*/src",
"codemods/*/test",
],
sourceType: "unambiguous",
},
{
// The runtime transform shouldn't process its own runtime or core-js.
exclude: [
"packages/babel-runtime",
/[\\/]node_modules[\\/](?:@babel\/runtime|babel-runtime|core-js)[\\/]/,
],
plugins: [includeRuntime ? "@babel/transform-runtime" : null].filter(
Boolean
),
},
].filter(Boolean),
};
// we need to do this as long as we do not test everything from source

View File

@@ -36,7 +36,7 @@ npm install --save-dev @babel/plugin-codemod-object-assign-to-object-spread
**.babelrc**
```json
```jsonc
{
"plugins": ["@babel/plugin-codemod-object-assign-to-object-spread"]
}

View File

@@ -1,23 +1,26 @@
{
"name": "@babel/plugin-codemod-object-assign-to-object-spread",
"version": "7.0.0-beta.55",
"version": "7.0.0",
"description": "Transforms Object.assign into object spread syntax",
"repository": "https://github.com/babel/babel/tree/master/codemods/babel-plugin-codemod-object-assign-to-object-spread",
"license": "MIT",
"publishConfig": {
"access": "public"
},
"main": "lib/index.js",
"keywords": [
"@babel/codemod",
"@babel/plugin"
],
"dependencies": {
"@babel/plugin-syntax-object-rest-spread": "7.0.0-beta.55"
"@babel/plugin-syntax-object-rest-spread": "^7.0.0"
},
"peerDependencies": {
"@babel/core": ">=7.0.0-beta.50 <7.0.0-rc.0"
"@babel/core": "^7.0.0-0"
},
"devDependencies": {
"@babel/core": "7.0.0-beta.55",
"@babel/helper-plugin-test-runner": "7.0.0-beta.55"
"@babel/core": "^7.0.0",
"@babel/helper-plugin-test-runner": "^7.0.0"
},
"publishConfig": {
"access": "public"

View File

@@ -34,7 +34,7 @@ npm install --save-dev @babel/plugin-codemod-optional-catch-binding
**.babelrc**
```json
```jsonc
{
"plugins": ["@babel/plugin-codemod-optional-catch-binding"]
}

View File

@@ -1,22 +1,25 @@
{
"name": "@babel/plugin-codemod-optional-catch-binding",
"version": "7.0.0-beta.55",
"version": "7.0.0",
"description": "Remove unused catch bindings",
"repository": "https://github.com/babel/babel/tree/master/codemods/babel-plugin-codemod-remove-unused-catch-binding",
"license": "MIT",
"publishConfig": {
"access": "public"
},
"main": "lib/index.js",
"keywords": [
"@babel/codemod",
"@babel/plugin"
],
"dependencies": {
"@babel/plugin-syntax-optional-catch-binding": "7.0.0-beta.55"
"@babel/plugin-syntax-optional-catch-binding": "^7.0.0"
},
"peerDependencies": {
"@babel/core": ">=7.0.0-beta.50 <7.0.0-rc.0"
"@babel/core": "^7.0.0-0"
},
"devDependencies": {
"@babel/core": "7.0.0-beta.55",
"@babel/helper-plugin-test-runner": "7.0.0-beta.55"
"@babel/core": "^7.0.0",
"@babel/helper-plugin-test-runner": "^7.0.0"
}
}

9
eslint-local-rules.js Normal file
View File

@@ -0,0 +1,9 @@
"use strict";
const noDeprecatedClone = require("./scripts/eslint_rules/no-deprecated-clone");
const noUndefinedIdentifier = require("./scripts/eslint_rules/no-undefined-identifier");
module.exports = {
"no-deprecated-clone": noDeprecatedClone,
"no-undefined-identifier": noUndefinedIdentifier,
};

View File

@@ -1,6 +1,6 @@
{
"lerna": "2.11.0",
"version": "7.0.0-beta.55",
"version": "7.1.2",
"changelog": {
"repo": "babel/babel",
"cacheDir": ".changelog",
@@ -18,8 +18,11 @@
"publish": {
"ignore": [
"*.md",
"*.json",
"*.txt",
"test/**",
"codemods/**"
"codemods/**",
"package.json"
]
}
},

View File

@@ -32,6 +32,20 @@ declare module "lodash/merge" {
declare export default <T: Object>(T, Object) => T;
}
declare module "semver" {
declare module.exports: {
valid(v: string): boolean;
gt(v1: string, v2: string): boolean;
lt(v1: string, v2: string): boolean;
major(v: string): number;
minor(v: string): number;
patch(v: string): number;
satisfies(v1: string, r1: string): boolean;
intersects(r1: string, r2: string): boolean;
}
}
declare module "source-map" {
declare export type SourceMap = {
version: 3,

View File

@@ -6,35 +6,37 @@
"build": "make build",
"fix": "make fix",
"lint": "make lint",
"precommit": "lint-staged",
"test": "make test"
},
"devDependencies": {
"@babel/cli": "7.0.0-beta.52",
"@babel/core": "7.0.0-beta.52",
"@babel/plugin-proposal-class-properties": "7.0.0-beta.52",
"@babel/plugin-proposal-export-namespace-from": "7.0.0-beta.52",
"@babel/plugin-proposal-numeric-separator": "7.0.0-beta.52",
"@babel/plugin-transform-modules-commonjs": "7.0.0-beta.52",
"@babel/preset-env": "7.0.0-beta.52",
"@babel/preset-flow": "7.0.0-beta.52",
"@babel/register": "7.0.0-beta.52",
"@babel/cli": "^7.1.0",
"@babel/core": "^7.1.0",
"@babel/plugin-proposal-class-properties": "^7.1.0",
"@babel/plugin-proposal-export-namespace-from": "^7.0.0",
"@babel/plugin-proposal-numeric-separator": "^7.0.0",
"@babel/plugin-transform-modules-commonjs": "^7.1.0",
"@babel/plugin-transform-runtime": "^7.1.0",
"@babel/preset-env": "^7.1.0",
"@babel/preset-flow": "^7.0.0",
"@babel/register": "^7.0.0",
"@babel/runtime": "^7.0.0",
"babel-core": "^7.0.0-0",
"babel-eslint": "^8.2.6",
"babel-jest": "^23.4.0",
"babel-loader": "8.0.0-beta.0",
"babel-eslint": "^9.0.0",
"babel-jest": "^23.6.0",
"babel-loader": "^8.0.2",
"babel-plugin-transform-charcodes": "^0.1.0",
"browserify": "^13.1.1",
"browserify": "^16.2.2",
"bundle-collapser": "^1.2.1",
"chalk": "^2.3.2",
"charcodes": "^0.1.0",
"derequire": "^2.0.2",
"enhanced-resolve": "^3.0.0",
"eslint": "^5.1.0",
"eslint-config-babel": "^7.0.2",
"eslint-plugin-flowtype": "^2.50.0",
"eslint": "^5.6.0",
"eslint-config-babel": "^8.0.0",
"eslint-plugin-flowtype": "^2.50.1",
"eslint-plugin-local-rules": "0.1.0",
"eslint-plugin-prettier": "^2.6.2",
"flow-bin": "^0.76.0",
"flow-bin": "^0.80.0",
"graceful-fs": "^4.1.11",
"gulp": "^4.0.0",
"gulp-babel": "^8.0.0-beta.2",
@@ -45,15 +47,15 @@
"gulp-uglify": "^3.0.0",
"gulp-util": "^3.0.7",
"gulp-watch": "^5.0.0",
"husky": "^0.14.3",
"jest": "^23.4.1",
"husky": "^1.0.0-rc.15",
"jest": "^23.6.0",
"lerna": "^2.11.0",
"lerna-changelog": "^0.5.0",
"lint-staged": "^6.0.1",
"lint-staged": "^7.3.0",
"lodash": "^4.17.10",
"merge-stream": "^1.0.1",
"output-file-sync": "^2.0.0",
"prettier": "^1.13.7",
"prettier": "^1.14.3",
"pump": "^1.0.2",
"rimraf": "^2.4.3",
"rollup-plugin-babel": "^4.0.0-beta.0",
@@ -70,14 +72,19 @@
},
"engines": {
"node": ">= 6.9.0 <= 11.0.0-0",
"npm": ">= 2.x <= 5.x",
"npm": ">= 3.x <= 6.x",
"yarn": ">=0.27.5 || >=1.0.0-20170811"
},
"lint-staged": {
"*.js": [
"eslint --format=codeframe --rulesdir='./scripts/eslint_rules'"
"eslint --format=codeframe"
]
},
"husky": {
"hooks": {
"pre-commit": "lint-staged"
}
},
"jest": {
"collectCoverageFrom": [
"packages/*/src/**/*.mjs",

View File

@@ -13,10 +13,10 @@ A monorepo, muhahahahahaha. See the [monorepo design doc](/doc/design/monorepo.m
| Package | Version | Dependencies |
|--------|-------|------------|
| [`@babel/core`](/packages/babel-core) | [![npm](https://img.shields.io/npm/v/@babel/core.svg?maxAge=2592000)](https://www.npmjs.com/package/@babel/core) | [![Dependency Status](https://david-dm.org/babel/babel.svg?path=packages/babel-core)](https://david-dm.org/babel/babel?path=packages/babel-core) |
| [`@babel/parser`](/packages/@babel/parser) | [![npm](https://img.shields.io/npm/v/@babel/parser.svg?maxAge=2592000)](https://www.npmjs.com/package/@babel/parser) | [![Dependency Status](https://david-dm.org/babel/babel.svg?path=packages/babel-parser)](https://david-dm.org/babel/babel?path=packages/babel-parser) |
| [`@babel/traverse`](/packages/babel-traverse) | [![npm](https://img.shields.io/npm/v/@babel/traverse.svg?maxAge=2592000)](https://www.npmjs.com/package/@babel/traverse) | [![Dependency Status](https://david-dm.org/babel/babel.svg?path=packages/babel-traverse)](https://david-dm.org/babel/babel?path=packages/babel-traverse) |
| [`@babel/generator`](/packages/babel-generator) | [![npm](https://img.shields.io/npm/v/@babel/generator.svg?maxAge=2592000)](https://www.npmjs.com/package/@babel/generator) | [![Dependency Status](https://david-dm.org/babel/babel.svg?path=packages/babel-generator)](https://david-dm.org/babel/babel?path=packages/babel-generator) |
| [`@babel/core`](/packages/babel-core) | [![npm](https://img.shields.io/npm/v/@babel/core.svg?maxAge=3600)](https://www.npmjs.com/package/@babel/core) | [![Dependency Status](https://david-dm.org/babel/babel.svg?path=packages/babel-core)](https://david-dm.org/babel/babel?path=packages/babel-core) |
| [`@babel/parser`](/packages/babel-parser) | [![npm](https://img.shields.io/npm/v/@babel/parser.svg?maxAge=3600)](https://www.npmjs.com/package/@babel/parser) | [![Dependency Status](https://david-dm.org/babel/babel.svg?path=packages/babel-parser)](https://david-dm.org/babel/babel?path=packages/babel-parser) |
| [`@babel/traverse`](/packages/babel-traverse) | [![npm](https://img.shields.io/npm/v/@babel/traverse.svg?maxAge=3600)](https://www.npmjs.com/package/@babel/traverse) | [![Dependency Status](https://david-dm.org/babel/babel.svg?path=packages/babel-traverse)](https://david-dm.org/babel/babel?path=packages/babel-traverse) |
| [`@babel/generator`](/packages/babel-generator) | [![npm](https://img.shields.io/npm/v/@babel/generator.svg?maxAge=3600)](https://www.npmjs.com/package/@babel/generator) | [![Dependency Status](https://david-dm.org/babel/babel.svg?path=packages/babel-generator)](https://david-dm.org/babel/babel?path=packages/babel-generator) |
[`@babel/core`](/packages/babel-core) is the Babel compiler itself; it exposes the `babel.transform` method, where `transformedCode = transform(src).code`.
@@ -36,14 +36,14 @@ Check out the [`babel-handbook`](https://github.com/thejameskyle/babel-handbook/
| Package | Version | Dependencies |
|--------|-------|------------|
| [`@babel/cli`](/packages/babel-cli) | [![npm](https://img.shields.io/npm/v/@babel/cli.svg?maxAge=2592000)](https://www.npmjs.com/package/@babel/cli) | [![Dependency Status](https://david-dm.org/babel/babel.svg?path=packages/babel-cli)](https://david-dm.org/babel/babel?path=packages/babel-cli) |
| [`@babel/types`](/packages/babel-types) | [![npm](https://img.shields.io/npm/v/@babel/types.svg?maxAge=2592000)](https://www.npmjs.com/package/@babel/types) | [![Dependency Status](https://david-dm.org/babel/babel.svg?path=packages/babel-types)](https://david-dm.org/babel/babel?path=packages/babel-types) |
| [`@babel/polyfill`](/packages/babel-polyfill) | [![npm](https://img.shields.io/npm/v/@babel/polyfill.svg?maxAge=2592000)](https://www.npmjs.com/package/@babel/polyfill) | [![Dependency Status](https://david-dm.org/babel/babel.svg?path=packages/babel-polyfill)](https://david-dm.org/babel/babel?path=packages/babel-polyfill) |
| [`@babel/runtime`](/packages/babel-runtime) | [![npm](https://img.shields.io/npm/v/@babel/runtime.svg?maxAge=2592000)](https://www.npmjs.com/package/@babel/runtime) | [![Dependency Status](https://david-dm.org/babel/babel.svg?path=packages/babel-runtime)](https://david-dm.org/babel/babel?path=packages/babel-runtime) |
| [`@babel/register`](/packages/babel-register) | [![npm](https://img.shields.io/npm/v/@babel/register.svg?maxAge=2592000)](https://www.npmjs.com/package/@babel/register) | [![Dependency Status](https://david-dm.org/babel/babel.svg?path=packages/babel-register)](https://david-dm.org/babel/babel?path=packages/babel-register) |
| [`@babel/template`](/packages/babel-template) | [![npm](https://img.shields.io/npm/v/@babel/template.svg?maxAge=2592000)](https://www.npmjs.com/package/@babel/template) | [![Dependency Status](https://david-dm.org/babel/babel.svg?path=packages/babel-template)](https://david-dm.org/babel/babel?path=packages/babel-template) |
| [`@babel/helpers`](/packages/babel-helpers) | [![npm](https://img.shields.io/npm/v/@babel/helpers.svg?maxAge=2592000)](https://www.npmjs.com/package/@babel/helpers) | [![Dependency Status](https://david-dm.org/babel/babel.svg?path=packages/babel-helpers)](https://david-dm.org/babel/babel?path=packages/babel-helpers) |
| [`@babel/code-frame`](/packages/babel-code-frame) | [![npm](https://img.shields.io/npm/v/@babel/code-frame.svg?maxAge=2592000)](https://www.npmjs.com/package/@babel/code-frame) | [![Dependency Status](https://david-dm.org/babel/babel.svg?path=packages/babel-code-frame)](https://david-dm.org/babel/babel?path=packages/babel-code-frame) |
| [`@babel/cli`](/packages/babel-cli) | [![npm](https://img.shields.io/npm/v/@babel/cli.svg?maxAge=3600)](https://www.npmjs.com/package/@babel/cli) | [![Dependency Status](https://david-dm.org/babel/babel.svg?path=packages/babel-cli)](https://david-dm.org/babel/babel?path=packages/babel-cli) |
| [`@babel/types`](/packages/babel-types) | [![npm](https://img.shields.io/npm/v/@babel/types.svg?maxAge=3600)](https://www.npmjs.com/package/@babel/types) | [![Dependency Status](https://david-dm.org/babel/babel.svg?path=packages/babel-types)](https://david-dm.org/babel/babel?path=packages/babel-types) |
| [`@babel/polyfill`](/packages/babel-polyfill) | [![npm](https://img.shields.io/npm/v/@babel/polyfill.svg?maxAge=3600)](https://www.npmjs.com/package/@babel/polyfill) | [![Dependency Status](https://david-dm.org/babel/babel.svg?path=packages/babel-polyfill)](https://david-dm.org/babel/babel?path=packages/babel-polyfill) |
| [`@babel/runtime`](/packages/babel-runtime) | [![npm](https://img.shields.io/npm/v/@babel/runtime.svg?maxAge=3600)](https://www.npmjs.com/package/@babel/runtime) | [![Dependency Status](https://david-dm.org/babel/babel.svg?path=packages/babel-runtime)](https://david-dm.org/babel/babel?path=packages/babel-runtime) |
| [`@babel/register`](/packages/babel-register) | [![npm](https://img.shields.io/npm/v/@babel/register.svg?maxAge=3600)](https://www.npmjs.com/package/@babel/register) | [![Dependency Status](https://david-dm.org/babel/babel.svg?path=packages/babel-register)](https://david-dm.org/babel/babel?path=packages/babel-register) |
| [`@babel/template`](/packages/babel-template) | [![npm](https://img.shields.io/npm/v/@babel/template.svg?maxAge=3600)](https://www.npmjs.com/package/@babel/template) | [![Dependency Status](https://david-dm.org/babel/babel.svg?path=packages/babel-template)](https://david-dm.org/babel/babel?path=packages/babel-template) |
| [`@babel/helpers`](/packages/babel-helpers) | [![npm](https://img.shields.io/npm/v/@babel/helpers.svg?maxAge=3600)](https://www.npmjs.com/package/@babel/helpers) | [![Dependency Status](https://david-dm.org/babel/babel.svg?path=packages/babel-helpers)](https://david-dm.org/babel/babel?path=packages/babel-helpers) |
| [`@babel/code-frame`](/packages/babel-code-frame) | [![npm](https://img.shields.io/npm/v/@babel/code-frame.svg?maxAge=3600)](https://www.npmjs.com/package/@babel/code-frame) | [![Dependency Status](https://david-dm.org/babel/babel.svg?path=packages/babel-code-frame)](https://david-dm.org/babel/babel?path=packages/babel-code-frame) |
- [`@babel/cli`](/packages/babel-cli) is the CLI tool that runs `@babel/core` and helps with outputting to a directory, a file, stdout and more (also includes `@babel/node` cli). Check out the [docs](https://babeljs.io/docs/usage/cli/).
- [`@babel/types`](/packages/babel-types) is used to validate, build and change AST nodes.
@@ -62,7 +62,7 @@ The transformer[s] used in Babel are the independent pieces of code that transfo
| Package | Version | Dependencies | Description |
|--------|-------|------------|---|
| [`@babel/preset-env`](/packages/babel-preset-env) | [![npm](https://img.shields.io/npm/v/@babel/preset-env.svg?maxAge=2592000)](https://www.npmjs.com/package/@babel/preset-env) | [![Dependency Status](https://david-dm.org/babel/babel/status.svg?path=packages/babel-preset-env)](https://david-dm.org/babel/babel?path=packages/babel-preset-env) | automatically determines plugins and polyfills you need based on your supported environments |
| [`@babel/preset-env`](/packages/babel-preset-env) | [![npm](https://img.shields.io/npm/v/@babel/preset-env.svg?maxAge=?maxAge=3600)](https://www.npmjs.com/package/@babel/preset-env) | [![Dependency Status](https://david-dm.org/babel/babel/status.svg?path=packages/babel-preset-env)](https://david-dm.org/babel/babel?path=packages/babel-preset-env) | automatically determines plugins and polyfills you need based on your supported environments |
> You can find community maintained presets on [npm](https://www.npmjs.com/search?q=babel-preset)

View File

@@ -1,10 +1,13 @@
{
"name": "@babel/cli",
"version": "7.0.0-beta.55",
"version": "7.1.2",
"description": "Babel command line.",
"author": "Sebastian McKenzie <sebmck@gmail.com>",
"homepage": "https://babeljs.io/",
"license": "MIT",
"publishConfig": {
"access": "public"
},
"repository": "https://github.com/babel/babel/tree/master/packages/babel-cli",
"keywords": [
"6to5",
@@ -18,23 +21,23 @@
"dependencies": {
"commander": "^2.8.1",
"convert-source-map": "^1.1.0",
"fs-readdir-recursive": "^1.0.0",
"fs-readdir-recursive": "^1.1.0",
"glob": "^7.0.0",
"lodash": "^4.17.10",
"mkdirp": "^0.5.1",
"output-file-sync": "^2.0.0",
"slash": "^1.0.0",
"slash": "^2.0.0",
"source-map": "^0.5.0"
},
"optionalDependencies": {
"chokidar": "^2.0.3"
},
"peerDependencies": {
"@babel/core": ">=7.0.0-beta.50 <7.0.0-rc.0"
"@babel/core": "^7.0.0-0"
},
"devDependencies": {
"@babel/core": "7.0.0-beta.55",
"@babel/helper-fixtures": "7.0.0-beta.55"
"@babel/core": "^7.0.0",
"@babel/helper-fixtures": "^7.0.0"
},
"bin": {
"babel": "./bin/babel.js",

View File

@@ -89,7 +89,7 @@ export default async function({ cliOptions, babelOptions }) {
const stat = fs.statSync(filenameOrDir);
if (stat.isDirectory(filenameOrDir)) {
if (stat.isDirectory()) {
const dirname = filenameOrDir;
let count = 0;

View File

@@ -28,6 +28,11 @@ commander.option(
"The name of the 'env' to use when loading configs and plugins. " +
"Defaults to the value of BABEL_ENV, or else NODE_ENV, or else 'development'.",
);
commander.option(
"--root-mode [mode]",
"The project-root resolution mode. " +
"One of 'root' (the default), 'upward', or 'upward-optional'.",
);
// Basic file input configuration.
commander.option("--source-type [script|module]", "");
@@ -162,20 +167,20 @@ export default function parseArgv(args: Array<string>) {
filenames.forEach(function(filename) {
if (!fs.existsSync(filename)) {
errors.push(filename + " doesn't exist");
errors.push(filename + " does not exist");
}
});
if (commander.outDir && !filenames.length) {
errors.push("filenames required for --out-dir");
errors.push("--out-dir requires filenames");
}
if (commander.outFile && commander.outDir) {
errors.push("cannot have --out-file and --out-dir");
errors.push("--out-file and --out-dir cannot be used together");
}
if (commander.relative && !commander.outDir) {
errors.push("output directory required for --relative");
errors.push("--relative requires --out-dir usage");
}
if (commander.watch) {
@@ -207,41 +212,56 @@ export default function parseArgv(args: Array<string>) {
}
if (errors.length) {
console.error(errors.join(". "));
console.error("babel:");
errors.forEach(function(e) {
console.error(" " + e);
});
process.exit(2);
}
const opts = commander.opts();
return {
babelOptions: {
presets: opts.presets,
plugins: opts.plugins,
configFile: opts.configFile,
envName: opts.envName,
sourceType: opts.sourceType,
ignore: opts.ignore,
only: opts.only,
retainLines: opts.retainLines,
compact: opts.compact,
minified: opts.minified,
auxiliaryCommentBefore: opts.auxiliaryCommentBefore,
auxiliaryCommentAfter: opts.auxiliaryCommentAfter,
sourceMaps: opts.sourceMaps,
sourceFileName: opts.sourceFileName,
sourceRoot: opts.sourceRoot,
moduleRoot: opts.moduleRoot,
moduleIds: opts.moduleIds,
moduleId: opts.moduleId,
const babelOptions = {
presets: opts.presets,
plugins: opts.plugins,
rootMode: opts.rootMode,
configFile: opts.configFile,
envName: opts.envName,
sourceType: opts.sourceType,
ignore: opts.ignore,
only: opts.only,
retainLines: opts.retainLines,
compact: opts.compact,
minified: opts.minified,
auxiliaryCommentBefore: opts.auxiliaryCommentBefore,
auxiliaryCommentAfter: opts.auxiliaryCommentAfter,
sourceMaps: opts.sourceMaps,
sourceFileName: opts.sourceFileName,
sourceRoot: opts.sourceRoot,
moduleRoot: opts.moduleRoot,
moduleIds: opts.moduleIds,
moduleId: opts.moduleId,
// Commander will default the "--no-" arguments to true, but we want to
// leave them undefined so that @babel/core can handle the
// default-assignment logic on its own.
babelrc: opts.babelrc === true ? undefined : opts.babelrc,
highlightCode:
opts.highlightCode === true ? undefined : opts.highlightCode,
comments: opts.comments === true ? undefined : opts.comments,
},
// Commander will default the "--no-" arguments to true, but we want to
// leave them undefined so that @babel/core can handle the
// default-assignment logic on its own.
babelrc: opts.babelrc === true ? undefined : opts.babelrc,
highlightCode: opts.highlightCode === true ? undefined : opts.highlightCode,
comments: opts.comments === true ? undefined : opts.comments,
};
// If the @babel/cli version is newer than the @babel/core version, and we have added
// new options for @babel/core, we'll potentially get option validation errors from
// @babel/core. To avoid that, we delete undefined options, so @babel/core will only
// give the error if users actually pass an unsupported CLI option.
for (const key of Object.keys(babelOptions)) {
if (babelOptions[key] === undefined) {
delete babelOptions[key];
}
}
return {
babelOptions,
cliOptions: {
filename: opts.filename,
filenames,

View File

@@ -15,11 +15,15 @@ export function readdir(
includeDotfiles: boolean,
filter: ReaddirFilter,
) {
return readdirRecursive(
dirname,
filename =>
(includeDotfiles || filename[0] !== ".") && (!filter || filter(filename)),
);
return readdirRecursive(dirname, (filename, _index, currentDirectory) => {
const stat = fs.statSync(path.join(currentDirectory, filename));
if (stat.isDirectory()) return true;
return (
(includeDotfiles || filename[0] !== ".") && (!filter || filter(filename))
);
});
}
export function readdirForCompilable(
@@ -45,9 +49,14 @@ export function addSourceMappingUrl(code, loc) {
return code + "\n//# sourceMappingURL=" + path.basename(loc);
}
const CALLER = {
name: "@babel/cli",
};
export function transform(filename, code, opts) {
opts = {
...opts,
caller: CALLER,
filename,
};
@@ -60,6 +69,11 @@ export function transform(filename, code, opts) {
}
export function compile(filename, opts) {
opts = {
...opts,
caller: CALLER,
};
return new Promise((resolve, reject) => {
babel.transformFile(filename, opts, (err, result) => {
if (err) reject(err);

View File

@@ -1,10 +1,12 @@
{
"args": [
"src",
"--out-dir", "lib",
"--out-dir",
"lib",
"--copy-files",
"--include-dotfiles",
"--ignore", "src/foo",
"--ignore",
"src/foo",
"--verbose"
]
}

View File

@@ -1,10 +1,12 @@
{
"args": [
"src",
"--out-dir", "lib",
"--out-dir",
"lib",
"--copy-files",
"--include-dotfiles",
"--only", "src/foo",
"--only",
"src/foo",
"--verbose"
]
}

View File

@@ -1,3 +1,10 @@
{
"args": ["src", "--out-dir", "lib", "--copy-files", "--include-dotfiles", "--verbose"]
"args": [
"src",
"--out-dir",
"lib",
"--copy-files",
"--include-dotfiles",
"--verbose"
]
}

View File

@@ -1,9 +1,11 @@
{
"args": [
"src",
"--out-dir", "lib",
"--out-dir",
"lib",
"--copy-files",
"--ignore", "src/foo/*",
"--ignore",
"src/foo/*",
"--verbose"
]
}

View File

@@ -1,9 +1,11 @@
{
"args": [
"src",
"--out-dir", "lib",
"--out-dir",
"lib",
"--copy-files",
"--only", "src/foo/*",
"--only",
"src/foo/*",
"--verbose"
]
}

View File

@@ -1,3 +0,0 @@
{
"args": ["--source-maps", "--out-file", "test.js"]
}

View File

@@ -1,3 +0,0 @@
{
"args": ["--source-maps", "inline"]
}

View File

@@ -1,7 +0,0 @@
"use strict";
arr.map(function (x) {
return x * x;
});
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbInN0ZGluIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7O0FBQUEsR0FBRyxDQUFDLEdBQUcsQ0FBQyxVQUFBLENBQUM7U0FBSSxDQUFDLEdBQUcsQ0FBQztDQUFBLENBQUMsQ0FBQyIsImZpbGUiOiJzdGRvdXQiLCJzb3VyY2VzQ29udGVudCI6WyJhcnIubWFwKHggPT4geCAqIHgpOyJdfQ==

View File

@@ -0,0 +1,3 @@
class Test {
}

View File

@@ -0,0 +1 @@
arr.map(x => x * MULTIPLIER);

View File

@@ -0,0 +1,3 @@
{
"args": ["src", "--out-dir", "lib", "--out-file", "compiled.js"]
}

View File

@@ -0,0 +1,2 @@
babel:
--out-file and --out-dir cannot be used together

View File

@@ -0,0 +1,3 @@
{
"args": ["--out-dir", "lib"]
}

View File

@@ -0,0 +1,2 @@
babel:
--out-dir requires filenames

View File

@@ -0,0 +1 @@
(() => 42)

View File

@@ -0,0 +1 @@
arr.map(x => x * MULTIPLIER);

View File

@@ -0,0 +1,3 @@
{
"args": ["src", "--out-file", "test.js"]
}

View File

@@ -0,0 +1,10 @@
"use strict";
(function () {
return 42;
});
"use strict";
arr.map(function (x) {
return x * MULTIPLIER;
});

View File

@@ -0,0 +1,3 @@
class Test {
}

View File

@@ -0,0 +1 @@
arr.map(x => x * MULTIPLIER);

View File

@@ -0,0 +1,3 @@
{
"args": ["src", "--skip-initial-build", "--out-dir", "lib"]
}

View File

@@ -0,0 +1,2 @@
babel:
--skip-initial-build requires --watch

View File

@@ -0,0 +1 @@
arr.map(x => x * MULTIPLIER);

View File

@@ -0,0 +1,3 @@
{
"args": ["src", "--watch"]
}

View File

@@ -0,0 +1,2 @@
babel:
--watch requires --out-file or --out-dir

View File

@@ -1 +1 @@
filenames required for --out-dir
--out-dir requires filenames

View File

@@ -1 +1 @@
cannot have --out-file and --out-dir
--out-file and --out-dir cannot be used together

View File

@@ -1,4 +1,4 @@
{
"args": ["--relative"],
"args": ["--relative", "--no-babelrc"],
"stderrContains": true
}

View File

@@ -1 +1 @@
output directory required for --relative
--relative requires --out-dir usage

View File

@@ -1 +1 @@
foo.json doesn't exist
foo.json does not exist

View File

@@ -0,0 +1 @@
arr.map(x => x * MULTIPLIER);

View File

@@ -0,0 +1,3 @@
{
"args": ["--watch", "--out-file", "out.js", "--no-babelrc"]
}

View File

@@ -0,0 +1,2 @@
babel:
--watch requires filenames

View File

@@ -0,0 +1,3 @@
{
"args": ["index.js"]
}

View File

@@ -0,0 +1,2 @@
babel:
index.js does not exist

View File

@@ -1,3 +1,10 @@
{
"args": ["script.js", "script2.js", "--source-maps", "inline", "--out-file", "script3.js"]
"args": [
"script.js",
"script2.js",
"--source-maps",
"inline",
"--out-file",
"script3.js"
]
}

View File

@@ -1,3 +1,9 @@
{
"args": ["script.js", "script2.js", "--source-maps", "--out-file", "script3.js"]
"args": [
"script.js",
"script2.js",
"--source-maps",
"--out-file",
"script3.js"
]
}

View File

@@ -0,0 +1,3 @@
{
"args": ["--source-maps", "--out-file", "test.js", "--no-babelrc"]
}

View File

@@ -1 +1 @@
{"version":3,"sources":["stdin"],"names":[],"mappings":";;AAAA,GAAG,CAAC,GAAG,CAAC,UAAA,CAAC;SAAI,CAAC,GAAG,CAAC;CAAA,CAAC,CAAC","file":"test.js","sourcesContent":["arr.map(x => x * x);"]}
{"version":3,"sources":["stdin"],"names":[],"mappings":";;AAAA,GAAG,CAAC,GAAJ,CAAQ,UAAA,CAAC;AAAA,SAAI,CAAC,GAAG,CAAR;AAAA,CAAT","file":"test.js","sourcesContent":["arr.map(x => x * x);"]}

View File

@@ -0,0 +1,3 @@
{
"args": ["--source-maps", "inline", "--no-babelrc"]
}

View File

@@ -0,0 +1,8 @@
"use strict";
arr.map(function (x) {
return x * x;
});
//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbInN0ZGluIl0sIm5hbWVzIjpbImFyciIsIm1hcCIsIngiXSwibWFwcGluZ3MiOiI7O0FBQUFBLEdBQUcsQ0FBQ0MsR0FBSixDQUFRLFVBQUFDLENBQUM7QUFBQSxTQUFJQSxDQUFDLEdBQUdBLENBQVI7QUFBQSxDQUFUIiwic291cmNlc0NvbnRlbnQiOlsiYXJyLm1hcCh4ID0+IHggKiB4KTsiXX0=
//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IiIsImZpbGUiOiJzdGRvdXQifQ==

View File

@@ -1,14 +1,17 @@
{
"name": "@babel/code-frame",
"version": "7.0.0-beta.55",
"version": "7.0.0",
"description": "Generate errors that contain a code frame that point to source locations.",
"author": "Sebastian McKenzie <sebmck@gmail.com>",
"homepage": "https://babeljs.io/",
"license": "MIT",
"publishConfig": {
"access": "public"
},
"repository": "https://github.com/babel/babel/tree/master/packages/babel-code-frame",
"main": "lib/index.js",
"dependencies": {
"@babel/highlight": "7.0.0-beta.55"
"@babel/highlight": "^7.0.0"
},
"devDependencies": {
"chalk": "^2.0.0",

View File

@@ -1,11 +1,14 @@
{
"name": "@babel/core",
"version": "7.0.0-beta.55",
"version": "7.1.2",
"description": "Babel compiler core.",
"main": "lib/index.js",
"author": "Sebastian McKenzie <sebmck@gmail.com>",
"homepage": "https://babeljs.io/",
"license": "MIT",
"publishConfig": {
"access": "public"
},
"repository": "https://github.com/babel/babel/tree/master/packages/babel-core",
"keywords": [
"6to5",
@@ -30,13 +33,13 @@
"./lib/transform-file.js": "./lib/transform-file-browser.js"
},
"dependencies": {
"@babel/code-frame": "7.0.0-beta.55",
"@babel/generator": "7.0.0-beta.55",
"@babel/helpers": "7.0.0-beta.55",
"@babel/parser": "7.0.0-beta.55",
"@babel/template": "7.0.0-beta.55",
"@babel/traverse": "7.0.0-beta.55",
"@babel/types": "7.0.0-beta.55",
"@babel/code-frame": "^7.0.0",
"@babel/generator": "^7.1.2",
"@babel/helpers": "^7.1.2",
"@babel/parser": "^7.1.2",
"@babel/template": "^7.1.2",
"@babel/traverse": "^7.1.0",
"@babel/types": "^7.1.2",
"convert-source-map": "^1.1.0",
"debug": "^3.1.0",
"json5": "^0.5.0",
@@ -46,7 +49,7 @@
"source-map": "^0.5.0"
},
"devDependencies": {
"@babel/helper-transform-fixture-test-runner": "7.0.0-beta.55",
"@babel/register": "7.0.0-beta.55"
"@babel/helper-transform-fixture-test-runner": "^7.0.0",
"@babel/register": "^7.0.0"
}
}

View File

@@ -206,12 +206,29 @@ function makeSimpleConfigurator(
return;
}
return cache.using(val);
return cache.using(() => assertSimpleType(val()));
}
cacheFn.forever = () => cache.forever();
cacheFn.never = () => cache.never();
cacheFn.using = cb => cache.using(() => cb());
cacheFn.invalidate = cb => cache.invalidate(() => cb());
cacheFn.using = cb => cache.using(() => assertSimpleType(cb()));
cacheFn.invalidate = cb => cache.invalidate(() => assertSimpleType(cb()));
return (cacheFn: any);
}
// Types are limited here so that in the future these values can be used
// as part of Babel's caching logic.
type SimpleType = string | boolean | number | null | void;
export function assertSimpleType(value: mixed): SimpleType {
if (
value != null &&
typeof value !== "string" &&
typeof value !== "boolean" &&
typeof value !== "number"
) {
throw new Error(
"Cache keys must be either string, boolean, number, null, or undefined.",
);
}
return value;
}

View File

@@ -8,6 +8,7 @@ import {
type IgnoreList,
type ConfigApplicableTest,
type BabelrcSearch,
type CallerMetadata,
} from "./validation/options";
import pathPatternToRegex from "./pattern-to-regex";
@@ -50,12 +51,27 @@ export type ConfigContext = {
cwd: string,
root: string,
envName: string,
caller: CallerMetadata | void,
};
/**
* Build a config chain for a given preset.
*/
export const buildPresetChain: (
export function buildPresetChain(
arg: PresetInstance,
context: *,
): ConfigChain | null {
const chain = buildPresetChainWalker(arg, context);
if (!chain) return null;
return {
plugins: dedupDescriptors(chain.plugins),
presets: dedupDescriptors(chain.presets),
options: chain.options,
};
}
export const buildPresetChainWalker: (
arg: PresetInstance,
context: *,
) => * = makeChainWalker({
@@ -128,9 +144,14 @@ export function buildRootChain(
let configFile;
if (typeof opts.configFile === "string") {
configFile = loadConfig(opts.configFile, context.cwd, context.envName);
configFile = loadConfig(
opts.configFile,
context.cwd,
context.envName,
context.caller,
);
} else if (opts.configFile !== false) {
configFile = findRootConfig(context.root, context.envName);
configFile = findRootConfig(context.root, context.envName, context.caller);
}
let { babelrc, babelrcRoots } = opts;
@@ -169,6 +190,7 @@ export function buildRootChain(
({ ignore: ignoreFile, config: babelrcFile } = findRelativeConfig(
pkgData,
context.envName,
context.caller,
));
if (
@@ -234,7 +256,7 @@ function babelrcLoadEnabled(
if (typeof pat === "string") pat = pathPatternToRegex(pat, context.cwd);
return pkgData.directories.some(directory => {
return matchPattern(pat, context.cwd, directory);
return matchPattern(pat, context.cwd, directory, context);
});
});
}
@@ -449,7 +471,12 @@ function mergeExtendsChain(
): boolean {
if (opts.extends === undefined) return true;
const file = loadConfig(opts.extends, dirname, context.envName);
const file = loadConfig(
opts.extends,
dirname,
context.envName,
context.caller,
);
if (files.has(file)) {
throw new Error(
@@ -515,7 +542,7 @@ function normalizeOptions(opts: ValidatedOptions): ValidatedOptions {
// "sourceMap" is just aliased to sourceMap, so copy it over as
// we merge the options together.
if (options.sourceMap) {
if (options.hasOwnProperty("sourceMap")) {
options.sourceMaps = options.sourceMap;
delete options.sourceMap;
}
@@ -527,7 +554,7 @@ function dedupDescriptors(
): Array<UnloadedDescriptor> {
const map: Map<
Function,
Map<string | void, { value: UnloadedDescriptor | null }>,
Map<string | void, { value: UnloadedDescriptor }>,
> = new Map();
const descriptors = [];
@@ -542,16 +569,12 @@ function dedupDescriptors(
}
let desc = nameMap.get(item.name);
if (!desc) {
desc = { value: null };
desc = { value: item };
descriptors.push(desc);
// Treat passPerPreset presets as unique, skipping them
// in the merge processing steps.
if (!item.ownPass) nameMap.set(item.name, desc);
}
if (item.options === false) {
desc.value = null;
} else {
desc.value = item;
}
@@ -561,7 +584,7 @@ function dedupDescriptors(
}
return descriptors.reduce((acc, desc) => {
if (desc.value) acc.push(desc.value);
acc.push(desc.value);
return acc;
}, []);
}
@@ -633,12 +656,23 @@ function matchesPatterns(
dirname: string,
): boolean {
return patterns.some(pattern =>
matchPattern(pattern, dirname, context.filename),
matchPattern(pattern, dirname, context.filename, context),
);
}
function matchPattern(pattern, dirname, pathToTest): boolean {
if (typeof pattern === "function") return !!pattern(pathToTest);
function matchPattern(
pattern,
dirname,
pathToTest,
context: ConfigContext,
): boolean {
if (typeof pattern === "function") {
return !!pattern(pathToTest, {
dirname,
envName: context.envName,
caller: context.caller,
});
}
if (typeof pathToTest !== "string") {
throw new Error(

View File

@@ -41,6 +41,22 @@ export type UnloadedDescriptor = {
} | void,
};
function isEqualDescriptor(
a: UnloadedDescriptor,
b: UnloadedDescriptor,
): boolean {
return (
a.name === b.name &&
a.value === b.value &&
a.options === b.options &&
a.dirname === b.dirname &&
a.alias === b.alias &&
a.ownPass === b.ownPass &&
(a.file && a.file.request) === (b.file && b.file.request) &&
(a.file && a.file.resolved) === (b.file && b.file.resolved)
);
}
export type ValidatedFile = {
filepath: string,
dirname: string,
@@ -50,7 +66,7 @@ export type ValidatedFile = {
/**
* Create a set of descriptors from a given options object, preserving
* descriptor identity based on the identity of the plugin/preset arrays
* themselves.
* themselves, and potentially on the identity of the plugins/presets + options.
*/
export function createCachedDescriptors(
dirname: string,
@@ -113,26 +129,82 @@ export function createUncachedDescriptors(
};
}
const PRESET_DESCRIPTOR_CACHE = new WeakMap();
const createCachedPresetDescriptors = makeWeakCache(
(items: PluginList, cache: CacheConfigurator<string>) => {
const dirname = cache.using(dir => dir);
return makeStrongCache((alias: string) =>
makeStrongCache((passPerPreset: boolean) =>
createPresetDescriptors(items, dirname, alias, passPerPreset),
createPresetDescriptors(items, dirname, alias, passPerPreset).map(
// Items are cached using the overall preset array identity when
// possibly, but individual descriptors are also cached if a match
// can be found in the previously-used descriptor lists.
desc => loadCachedDescriptor(PRESET_DESCRIPTOR_CACHE, desc),
),
),
);
},
);
const PLUGIN_DESCRIPTOR_CACHE = new WeakMap();
const createCachedPluginDescriptors = makeWeakCache(
(items: PluginList, cache: CacheConfigurator<string>) => {
const dirname = cache.using(dir => dir);
return makeStrongCache((alias: string) =>
createPluginDescriptors(items, dirname, alias),
createPluginDescriptors(items, dirname, alias).map(
// Items are cached using the overall plugin array identity when
// possibly, but individual descriptors are also cached if a match
// can be found in the previously-used descriptor lists.
desc => loadCachedDescriptor(PLUGIN_DESCRIPTOR_CACHE, desc),
),
);
},
);
/**
* When no options object is given in a descriptor, this object is used
* as a WeakMap key in order to have consistent identity.
*/
const DEFAULT_OPTIONS = {};
/**
* Given the cache and a descriptor, returns a matching descriptor from the
* cache, or else returns the input descriptor and adds it to the cache for
* next time.
*/
function loadCachedDescriptor(
cache: WeakMap<{} | Function, WeakMap<{}, Array<UnloadedDescriptor>>>,
desc: UnloadedDescriptor,
) {
const { value, options = DEFAULT_OPTIONS } = desc;
if (options === false) return desc;
let cacheByOptions = cache.get(value);
if (!cacheByOptions) {
cacheByOptions = new WeakMap();
cache.set(value, cacheByOptions);
}
let possibilities = cacheByOptions.get(options);
if (!possibilities) {
possibilities = [];
cacheByOptions.set(options, possibilities);
}
if (possibilities.indexOf(desc) === -1) {
const matches = possibilities.filter(possibility =>
isEqualDescriptor(possibility, desc),
);
if (matches.length > 0) {
return matches[0];
}
possibilities.push(desc);
}
return desc;
}
function createPresetDescriptors(
items: PluginList,
dirname: string,

View File

@@ -14,6 +14,7 @@ import makeAPI from "../helpers/config-api";
import { makeStaticFileCache } from "./utils";
import pathPatternToRegex from "../pattern-to-regex";
import type { FilePackageData, RelativeConfig, ConfigFile } from "./types";
import type { CallerMetadata } from "../validation/options";
const debug = buildDebug("babel:config:loading:files:configuration");
@@ -23,9 +24,25 @@ const BABELRC_FILENAME = ".babelrc";
const BABELRC_JS_FILENAME = ".babelrc.js";
const BABELIGNORE_FILENAME = ".babelignore";
export function findConfigUpwards(rootDir: string): string | null {
let dirname = rootDir;
while (true) {
if (fs.existsSync(path.join(dirname, BABEL_CONFIG_JS_FILENAME))) {
return dirname;
}
const nextDir = path.dirname(dirname);
if (dirname === nextDir) break;
dirname = nextDir;
}
return null;
}
export function findRelativeConfig(
packageData: FilePackageData,
envName: string,
caller: CallerMetadata | void,
): RelativeConfig {
let config = null;
let ignore = null;
@@ -37,7 +54,7 @@ export function findRelativeConfig(
config = [BABELRC_FILENAME, BABELRC_JS_FILENAME].reduce(
(previousConfig: ConfigFile | null, name) => {
const filepath = path.join(loc, name);
const config = readConfig(filepath, envName);
const config = readConfig(filepath, envName, caller);
if (config && previousConfig) {
throw new Error(
@@ -91,10 +108,11 @@ export function findRelativeConfig(
export function findRootConfig(
dirname: string,
envName: string,
caller: CallerMetadata | void,
): ConfigFile | null {
const filepath = path.resolve(dirname, BABEL_CONFIG_JS_FILENAME);
const conf = readConfig(filepath, envName);
const conf = readConfig(filepath, envName, caller);
if (conf) {
debug("Found root config %o in $o.", BABEL_CONFIG_JS_FILENAME, dirname);
}
@@ -105,10 +123,11 @@ export function loadConfig(
name: string,
dirname: string,
envName: string,
caller: CallerMetadata | void,
): ConfigFile {
const filepath = resolve.sync(name, { basedir: dirname });
const conf = readConfig(filepath, envName);
const conf = readConfig(filepath, envName, caller);
if (!conf) {
throw new Error(`Config file ${filepath} contains no configuration data`);
}
@@ -121,16 +140,22 @@ export function loadConfig(
* Read the given config file, returning the result. Returns null if no config was found, but will
* throw if there are parsing errors while loading a config.
*/
function readConfig(filepath, envName): ConfigFile | null {
function readConfig(filepath, envName, caller): ConfigFile | null {
return path.extname(filepath) === ".js"
? readConfigJS(filepath, { envName })
? readConfigJS(filepath, { envName, caller })
: readConfigJSON5(filepath);
}
const LOADING_CONFIGS = new Set();
const readConfigJS = makeStrongCache(
(filepath, cache: CacheConfigurator<{ envName: string }>) => {
(
filepath,
cache: CacheConfigurator<{
envName: string,
caller: CallerMetadata | void,
}>,
) => {
if (!fs.existsSync(filepath)) {
cache.forever();
return null;

View File

@@ -7,8 +7,16 @@ import type {
FilePackageData,
} from "./types";
import type { CallerMetadata } from "../validation/options";
export type { ConfigFile, IgnoreFile, RelativeConfig, FilePackageData };
export function findConfigUpwards(
rootDir: string, // eslint-disable-line no-unused-vars
): string | null {
return null;
}
export function findPackageData(filepath: string): FilePackageData {
return {
filepath,
@@ -21,6 +29,7 @@ export function findPackageData(filepath: string): FilePackageData {
export function findRelativeConfig(
pkgData: FilePackageData, // eslint-disable-line no-unused-vars
envName: string, // eslint-disable-line no-unused-vars
caller: CallerMetadata | void, // eslint-disable-line no-unused-vars
): RelativeConfig {
return { pkg: null, config: null, ignore: null };
}
@@ -28,6 +37,7 @@ export function findRelativeConfig(
export function findRootConfig(
dirname: string, // eslint-disable-line no-unused-vars
envName: string, // eslint-disable-line no-unused-vars
caller: CallerMetadata | void, // eslint-disable-line no-unused-vars
): ConfigFile | null {
return null;
}
@@ -36,6 +46,7 @@ export function loadConfig(
name: string,
dirname: string,
envName: string, // eslint-disable-line no-unused-vars
caller: CallerMetadata | void, // eslint-disable-line no-unused-vars
): ConfigFile {
throw new Error(`Cannot load ${name} relative to ${dirname} in a browser`);
}

View File

@@ -10,6 +10,7 @@ import typeof * as indexType from "./index";
export { findPackageData } from "./package";
export {
findConfigUpwards,
findRelativeConfig,
findRootConfig,
loadConfig,

View File

@@ -15,8 +15,8 @@ const BABEL_PLUGIN_PREFIX_RE = /^(?!@|module:|[^/]+\/|babel-plugin-)/;
const BABEL_PRESET_PREFIX_RE = /^(?!@|module:|[^/]+\/|babel-preset-)/;
const BABEL_PLUGIN_ORG_RE = /^(@babel\/)(?!plugin-|[^/]+\/)/;
const BABEL_PRESET_ORG_RE = /^(@babel\/)(?!preset-|[^/]+\/)/;
const OTHER_PLUGIN_ORG_RE = /^(@(?!babel\/)[^/]+\/)(?!babel-plugin(?:-|\/|$)|[^/]+\/)/;
const OTHER_PRESET_ORG_RE = /^(@(?!babel\/)[^/]+\/)(?!babel-preset(?:-|\/|$)|[^/]+\/)/;
const OTHER_PLUGIN_ORG_RE = /^(@(?!babel\/)[^/]+\/)(?![^/]*babel-plugin(?:-|\/|$)|[^/]+\/)/;
const OTHER_PRESET_ORG_RE = /^(@(?!babel\/)[^/]+\/)(?![^/]*babel-preset(?:-|\/|$)|[^/]+\/)/;
const OTHER_ORG_DEFAULT_RE = /^(@(?!babel$)[^/]+)$/;
export function resolvePlugin(name: string, dirname: string): string | null {

View File

@@ -13,7 +13,7 @@ import {
import type { UnloadedDescriptor } from "./config-descriptors";
import traverse from "@babel/traverse";
import { makeWeakCache, type CacheConfigurator } from "./caching";
import { validate } from "./validation/options";
import { validate, type CallerMetadata } from "./validation/options";
import { validatePluginObject } from "./validation/plugins";
import makeAPI from "./helpers/config-api";
@@ -41,6 +41,7 @@ export type PluginPasses = Array<PluginPassList>;
// process 'ignore'/'only' and other filename-based logic.
type SimpleContext = {
envName: string,
caller: CallerMetadata | void,
};
export default function loadFullConfig(
@@ -68,15 +69,21 @@ export default function loadFullConfig(
},
pass: Array<Plugin>,
) {
const plugins = config.plugins.map(descriptor => {
return loadPluginDescriptor(descriptor, context);
});
const presets = config.presets.map(descriptor => {
return {
preset: loadPresetDescriptor(descriptor, context),
pass: descriptor.ownPass ? [] : pass,
};
});
const plugins = config.plugins.reduce((acc, descriptor) => {
if (descriptor.options !== false) {
acc.push(loadPluginDescriptor(descriptor, context));
}
return acc;
}, []);
const presets = config.presets.reduce((acc, descriptor) => {
if (descriptor.options !== false) {
acc.push({
preset: loadPresetDescriptor(descriptor, context),
pass: descriptor.ownPass ? [] : pass,
});
}
return acc;
}, []);
// resolve presets
if (presets.length > 0) {

View File

@@ -2,7 +2,13 @@
import semver from "semver";
import { version as coreVersion } from "../../";
import type { CacheConfigurator, SimpleCacheConfigurator } from "../caching";
import {
assertSimpleType,
type CacheConfigurator,
type SimpleCacheConfigurator,
} from "../caching";
import type { CallerMetadata } from "../validation/options";
type EnvFunction = {
(): string,
@@ -20,12 +26,14 @@ export type PluginAPI = {
};
export default function makeAPI(
cache: CacheConfigurator<{ envName: string }>,
cache: CacheConfigurator<{ envName: string, caller: CallerMetadata | void }>,
): PluginAPI {
const env: any = value =>
cache.using(data => {
if (typeof value === "undefined") return data.envName;
if (typeof value === "function") return value(data.envName);
if (typeof value === "function") {
return assertSimpleType(value(data.envName));
}
if (!Array.isArray(value)) value = [value];
return value.some(entry => {
@@ -36,12 +44,16 @@ export default function makeAPI(
});
});
const caller: any = cb =>
cache.using(data => assertSimpleType(cb(data.caller)));
return {
version: coreVersion,
cache: cache.simple(),
// Expose ".env()" so people can easily get the same env that we expose using the "env" key.
env,
async: () => false,
caller,
assertVersion,
};
}

View File

@@ -71,9 +71,11 @@ class ConfigItem {
/**
* The options, if any, that were passed to the item.
* Mutating this will lead to undefined behavior. If you need
* Mutating this will lead to undefined behavior.
*
* "false" means that this item has been disabled.
*/
options: {} | void;
options: {} | void | false;
/**
* The directory that the options for this item are relative to.
@@ -103,10 +105,6 @@ class ConfigItem {
this._descriptor = descriptor;
Object.defineProperty(this, "_descriptor", ({ enumerable: false }: any));
if (this._descriptor.options === false) {
throw new Error("Assertion failure - unexpected false options");
}
this.value = this._descriptor.value;
this.options = this._descriptor.options;
this.dirname = this._descriptor.dirname;

View File

@@ -6,9 +6,43 @@ import { mergeOptions } from "./util";
import { createItemFromDescriptor } from "./item";
import { buildRootChain, type ConfigContext } from "./config-chain";
import { getEnv } from "./helpers/environment";
import { validate, type ValidatedOptions } from "./validation/options";
import {
validate,
type ValidatedOptions,
type RootMode,
} from "./validation/options";
import type { ConfigFile, IgnoreFile } from "./files";
import { findConfigUpwards, type ConfigFile, type IgnoreFile } from "./files";
function resolveRootMode(rootDir: string, rootMode: RootMode): string {
switch (rootMode) {
case "root":
return rootDir;
case "upward-optional": {
const upwardRootDir = findConfigUpwards(rootDir);
return upwardRootDir === null ? rootDir : upwardRootDir;
}
case "upward": {
const upwardRootDir = findConfigUpwards(rootDir);
if (upwardRootDir !== null) return upwardRootDir;
throw Object.assign(
(new Error(
`Babel was run with rootMode:"upward" but a root could not ` +
`be found when searching upward from "${rootDir}"`,
): any),
{
code: "BABEL_ROOT_NOT_FOUND",
dirname: rootDir,
},
);
}
default:
throw new Error(`Assertion failure - unknown rootMode value`);
}
}
export default function loadPrivatePartialConfig(
inputOpts: mixed,
@@ -28,9 +62,18 @@ export default function loadPrivatePartialConfig(
const args = inputOpts ? validate("arguments", inputOpts) : {};
const { envName = getEnv(), cwd = ".", root: rootDir = "." } = args;
const {
envName = getEnv(),
cwd = ".",
root: rootDir = ".",
rootMode = "root",
caller,
} = args;
const absoluteCwd = path.resolve(cwd);
const absoluteRootDir = path.resolve(absoluteCwd, rootDir);
const absoluteRootDir = resolveRootMode(
path.resolve(absoluteCwd, rootDir),
rootMode,
);
const context: ConfigContext = {
filename:
@@ -40,6 +83,7 @@ export default function loadPrivatePartialConfig(
cwd: absoluteCwd,
root: absoluteRootDir,
envName,
caller,
};
const configChain = buildRootChain(args, context);

View File

@@ -13,16 +13,70 @@ import type {
SourceTypeOption,
CompactOption,
RootInputSourceMapOption,
NestingPath,
CallerMetadata,
RootMode,
} from "./options";
export type ValidatorSet = {
[string]: Validator<any>,
};
export type Validator<T> = (string, mixed) => T;
export type Validator<T> = (OptionPath, mixed) => T;
export function msg(loc: NestingPath | GeneralPath) {
switch (loc.type) {
case "root":
return ``;
case "env":
return `${msg(loc.parent)}.env["${loc.name}"]`;
case "overrides":
return `${msg(loc.parent)}.overrides[${loc.index}]`;
case "option":
return `${msg(loc.parent)}.${loc.name}`;
case "access":
return `${msg(loc.parent)}[${JSON.stringify(loc.name)}]`;
default:
throw new Error(`Assertion failure: Unknown type ${loc.type}`);
}
}
export function access(loc: GeneralPath, name: string | number): AccessPath {
return {
type: "access",
name,
parent: loc,
};
}
export type OptionPath = $ReadOnly<{
type: "option",
name: string,
parent: NestingPath,
}>;
type AccessPath = $ReadOnly<{
type: "access",
name: string | number,
parent: GeneralPath,
}>;
type GeneralPath = OptionPath | AccessPath;
export function assertRootMode(loc: OptionPath, value: mixed): RootMode | void {
if (
value !== undefined &&
value !== "root" &&
value !== "upward" &&
value !== "upward-optional"
) {
throw new Error(
`${msg(loc)} must be a "root", "upward", "upward-optional" or undefined`,
);
}
return value;
}
export function assertSourceMaps(
key: string,
loc: OptionPath,
value: mixed,
): SourceMapsOption | void {
if (
@@ -32,21 +86,24 @@ export function assertSourceMaps(
value !== "both"
) {
throw new Error(
`.${key} must be a boolean, "inline", "both", or undefined`,
`${msg(loc)} must be a boolean, "inline", "both", or undefined`,
);
}
return value;
}
export function assertCompact(key: string, value: mixed): CompactOption | void {
export function assertCompact(
loc: OptionPath,
value: mixed,
): CompactOption | void {
if (value !== undefined && typeof value !== "boolean" && value !== "auto") {
throw new Error(`.${key} must be a boolean, "auto", or undefined`);
throw new Error(`${msg(loc)} must be a boolean, "auto", or undefined`);
}
return value;
}
export function assertSourceType(
key: string,
loc: OptionPath,
value: mixed,
): SourceTypeOption | void {
if (
@@ -56,14 +113,49 @@ export function assertSourceType(
value !== "unambiguous"
) {
throw new Error(
`.${key} must be "module", "script", "unambiguous", or undefined`,
`${msg(loc)} must be "module", "script", "unambiguous", or undefined`,
);
}
return value;
}
export function assertCallerMetadata(
loc: OptionPath,
value: mixed,
): CallerMetadata | void {
const obj = assertObject(loc, value);
if (obj) {
if (typeof obj[("name": string)] !== "string") {
throw new Error(
`${msg(loc)} set but does not contain "name" property string`,
);
}
for (const prop of Object.keys(obj)) {
const propLoc = access(loc, prop);
const value = obj[prop];
if (
value != null &&
typeof value !== "boolean" &&
typeof value !== "string" &&
typeof value !== "number"
) {
// NOTE(logan): I'm limiting the type here so that we can guarantee that
// the "caller" value will serialize to JSON nicely. We can always
// allow more complex structures later though.
throw new Error(
`${msg(
propLoc,
)} must be null, undefined, a boolean, a string, or a number.`,
);
}
}
}
return (value: any);
}
export function assertInputSourceMap(
key: string,
loc: OptionPath,
value: mixed,
): RootInputSourceMapOption | void {
if (
@@ -71,75 +163,82 @@ export function assertInputSourceMap(
typeof value !== "boolean" &&
(typeof value !== "object" || !value)
) {
throw new Error(".inputSourceMap must be a boolean, object, or undefined");
throw new Error(`${msg(loc)} must be a boolean, object, or undefined`);
}
return value;
}
export function assertString(key: string, value: mixed): string | void {
export function assertString(loc: GeneralPath, value: mixed): string | void {
if (value !== undefined && typeof value !== "string") {
throw new Error(`.${key} must be a string, or undefined`);
throw new Error(`${msg(loc)} must be a string, or undefined`);
}
return value;
}
export function assertFunction(key: string, value: mixed): Function | void {
export function assertFunction(
loc: GeneralPath,
value: mixed,
): Function | void {
if (value !== undefined && typeof value !== "function") {
throw new Error(`.${key} must be a function, or undefined`);
throw new Error(`${msg(loc)} must be a function, or undefined`);
}
return value;
}
export function assertBoolean(key: string, value: mixed): boolean | void {
export function assertBoolean(loc: GeneralPath, value: mixed): boolean | void {
if (value !== undefined && typeof value !== "boolean") {
throw new Error(`.${key} must be a boolean, or undefined`);
throw new Error(`${msg(loc)} must be a boolean, or undefined`);
}
return value;
}
export function assertObject(key: string, value: mixed): {} | void {
export function assertObject(loc: GeneralPath, value: mixed): {} | void {
if (
value !== undefined &&
(typeof value !== "object" || Array.isArray(value) || !value)
) {
throw new Error(`.${key} must be an object, or undefined`);
throw new Error(`${msg(loc)} must be an object, or undefined`);
}
return value;
}
export function assertArray(key: string, value: mixed): ?$ReadOnlyArray<mixed> {
export function assertArray(
loc: GeneralPath,
value: mixed,
): ?$ReadOnlyArray<mixed> {
if (value != null && !Array.isArray(value)) {
throw new Error(`.${key} must be an array, or undefined`);
throw new Error(`${msg(loc)} must be an array, or undefined`);
}
return value;
}
export function assertIgnoreList(key: string, value: mixed): IgnoreList | void {
const arr = assertArray(key, value);
export function assertIgnoreList(
loc: OptionPath,
value: mixed,
): IgnoreList | void {
const arr = assertArray(loc, value);
if (arr) {
arr.forEach((item, i) => assertIgnoreItem(key, i, item));
arr.forEach((item, i) => assertIgnoreItem(access(loc, i), item));
}
return (arr: any);
}
function assertIgnoreItem(
key: string,
index: number,
value: mixed,
): IgnoreItem {
function assertIgnoreItem(loc: GeneralPath, value: mixed): IgnoreItem {
if (
typeof value !== "string" &&
typeof value !== "function" &&
!(value instanceof RegExp)
) {
throw new Error(
`.${key}[${index}] must be an array of string/Funtion/RegExp values, or undefined`,
`${msg(
loc,
)} must be an array of string/Funtion/RegExp values, or undefined`,
);
}
return value;
}
export function assertConfigApplicableTest(
key: string,
loc: OptionPath,
value: mixed,
): ConfigApplicableTest | void {
if (value === undefined) return value;
@@ -147,12 +246,14 @@ export function assertConfigApplicableTest(
if (Array.isArray(value)) {
value.forEach((item, i) => {
if (!checkValidTest(item)) {
throw new Error(`.${key}[${i}] must be a string/Function/RegExp.`);
throw new Error(
`${msg(access(loc, i))} must be a string/Function/RegExp.`,
);
}
});
} else if (!checkValidTest(value)) {
throw new Error(
`.${key} must be a string/Function/RegExp, or an array of those`,
`${msg(loc)} must be a string/Function/RegExp, or an array of those`,
);
}
return (value: any);
@@ -167,7 +268,7 @@ function checkValidTest(value: mixed): boolean {
}
export function assertConfigFileSearch(
key: string,
loc: OptionPath,
value: mixed,
): ConfigFileSearch | void {
if (
@@ -176,7 +277,7 @@ export function assertConfigFileSearch(
typeof value !== "string"
) {
throw new Error(
`.${key} must be a undefined, a boolean, a string, ` +
`${msg(loc)} must be a undefined, a boolean, a string, ` +
`got ${JSON.stringify(value)}`,
);
}
@@ -185,7 +286,7 @@ export function assertConfigFileSearch(
}
export function assertBabelrcSearch(
key: string,
loc: OptionPath,
value: mixed,
): BabelrcSearch | void {
if (value === undefined || typeof value === "boolean") return value;
@@ -193,44 +294,43 @@ export function assertBabelrcSearch(
if (Array.isArray(value)) {
value.forEach((item, i) => {
if (!checkValidTest(item)) {
throw new Error(`.${key}[${i}] must be a string/Function/RegExp.`);
throw new Error(
`${msg(access(loc, i))} must be a string/Function/RegExp.`,
);
}
});
} else if (!checkValidTest(value)) {
throw new Error(
`.${key} must be a undefined, a boolean, a string/Function/RegExp ` +
`${msg(loc)} must be a undefined, a boolean, a string/Function/RegExp ` +
`or an array of those, got ${JSON.stringify(value)}`,
);
}
return (value: any);
}
export function assertPluginList(key: string, value: mixed): PluginList | void {
const arr = assertArray(key, value);
export function assertPluginList(
loc: OptionPath,
value: mixed,
): PluginList | void {
const arr = assertArray(loc, value);
if (arr) {
// Loop instead of using `.map` in order to preserve object identity
// for plugin array for use during config chain processing.
arr.forEach((item, i) => assertPluginItem(key, i, item));
arr.forEach((item, i) => assertPluginItem(access(loc, i), item));
}
return (arr: any);
}
function assertPluginItem(
key: string,
index: number,
value: mixed,
): PluginItem {
function assertPluginItem(loc: GeneralPath, value: mixed): PluginItem {
if (Array.isArray(value)) {
if (value.length === 0) {
throw new Error(`.${key}[${index}] must include an object`);
throw new Error(`${msg(loc)} must include an object`);
}
if (value.length > 3) {
throw new Error(
`.${key}[${index}] may only be a two-tuple or three-tuple`,
);
throw new Error(`${msg(loc)} may only be a two-tuple or three-tuple`);
}
assertPluginTarget(key, index, true, value[0]);
assertPluginTarget(access(loc, 0), value[0]);
if (value.length > 1) {
const opts = value[1];
@@ -240,38 +340,31 @@ function assertPluginItem(
(typeof opts !== "object" || Array.isArray(opts))
) {
throw new Error(
`.${key}[${index}][1] must be an object, false, or undefined`,
`${msg(access(loc, 1))} must be an object, false, or undefined`,
);
}
}
if (value.length === 3) {
const name = value[2];
if (name !== undefined && typeof name !== "string") {
throw new Error(`.${key}[${index}][2] must be a string, or undefined`);
throw new Error(
`${msg(access(loc, 2))} must be a string, or undefined`,
);
}
}
} else {
assertPluginTarget(key, index, false, value);
assertPluginTarget(loc, value);
}
return (value: any);
}
function assertPluginTarget(
key: string,
index: number,
inArray: boolean,
value: mixed,
): PluginTarget {
function assertPluginTarget(loc: GeneralPath, value: mixed): PluginTarget {
if (
(typeof value !== "object" || !value) &&
typeof value !== "string" &&
typeof value !== "function"
) {
throw new Error(
`.${key}[${index}]${
inArray ? `[0]` : ""
} must be a string, object, function`,
);
throw new Error(`${msg(loc)} must be a string, object, function`);
}
return value;
}

View File

@@ -5,10 +5,13 @@ import Plugin from "../plugin";
import removed from "./removed";
import {
msg,
access,
assertString,
assertBoolean,
assertObject,
assertArray,
assertCallerMetadata,
assertInputSourceMap,
assertIgnoreList,
assertPluginList,
@@ -16,20 +19,28 @@ import {
assertConfigFileSearch,
assertBabelrcSearch,
assertFunction,
assertRootMode,
assertSourceMaps,
assertCompact,
assertSourceType,
type ValidatorSet,
type Validator,
type OptionPath,
} from "./option-assertions";
const ROOT_VALIDATORS: ValidatorSet = {
cwd: (assertString: Validator<$PropertyType<ValidatedOptions, "cwd">>),
root: (assertString: Validator<$PropertyType<ValidatedOptions, "root">>),
rootMode: (assertRootMode: Validator<
$PropertyType<ValidatedOptions, "rootMode">,
>),
configFile: (assertConfigFileSearch: Validator<
$PropertyType<ValidatedOptions, "configFile">,
>),
caller: (assertCallerMetadata: Validator<
$PropertyType<ValidatedOptions, "caller">,
>),
filename: (assertString: Validator<
$PropertyType<ValidatedOptions, "filename">,
>),
@@ -169,10 +180,12 @@ export type ValidatedOptions = {
babelrcRoots?: BabelrcSearch,
configFile?: ConfigFileSearch,
root?: string,
rootMode?: RootMode,
code?: boolean,
ast?: boolean,
inputSourceMap?: RootInputSourceMapOption,
envName?: string,
caller?: CallerMetadata,
extends?: string,
env?: EnvSet<ValidatedOptions>,
@@ -222,6 +235,11 @@ export type ValidatedOptions = {
generatorOpts?: {},
};
export type CallerMetadata = {
// If 'caller' is specified, require that the name is given for debugging
// messages.
name: string,
};
export type EnvSet<T> = {
[string]: ?T,
};
@@ -247,25 +265,64 @@ export type SourceMapsOption = boolean | "inline" | "both";
export type SourceTypeOption = "module" | "script" | "unambiguous";
export type CompactOption = boolean | "auto";
export type RootInputSourceMapOption = {} | boolean;
export type RootMode = "root" | "upward" | "upward-optional";
export type OptionsType =
export type OptionsSource =
| "arguments"
| "env"
| "preset"
| "override"
| "configfile"
| "babelrcfile"
| "extendsfile";
| "extendsfile"
| "preset";
type RootPath = $ReadOnly<{
type: "root",
source: OptionsSource,
}>;
type OverridesPath = $ReadOnly<{
type: "overrides",
index: number,
parent: RootPath,
}>;
type EnvPath = $ReadOnly<{
type: "env",
name: string,
parent: RootPath | OverridesPath,
}>;
export type NestingPath = RootPath | OverridesPath | EnvPath;
function getSource(loc: NestingPath): OptionsSource {
return loc.type === "root" ? loc.source : getSource(loc.parent);
}
export function validate(type: OptionsSource, opts: {}): ValidatedOptions {
return validateNested(
{
type: "root",
source: type,
},
opts,
);
}
function validateNested(loc: NestingPath, opts: {}) {
const type = getSource(loc);
export function validate(type: OptionsType, opts: {}): ValidatedOptions {
assertNoDuplicateSourcemap(opts);
Object.keys(opts).forEach(key => {
const optLoc = {
type: "option",
name: key,
parent: loc,
};
if (type === "preset" && NONPRESET_VALIDATORS[key]) {
throw new Error(`.${key} is not allowed in preset options`);
throw new Error(`${msg(optLoc)} is not allowed in preset options`);
}
if (type !== "arguments" && ROOT_VALIDATORS[key]) {
throw new Error(`.${key} is only allowed in root programmatic options`);
throw new Error(
`${msg(optLoc)} is only allowed in root programmatic options`,
);
}
if (
type !== "arguments" &&
@@ -274,48 +331,47 @@ export function validate(type: OptionsType, opts: {}): ValidatedOptions {
) {
if (type === "babelrcfile" || type === "extendsfile") {
throw new Error(
`.${key} is not allowed in .babelrc or "extend"ed files, only in root programmatic options, ` +
`${msg(
optLoc,
)} is not allowed in .babelrc or "extends"ed files, only in root programmatic options, ` +
`or babel.config.js/config file options`,
);
}
throw new Error(
`.${key} is only allowed in root programmatic options, or babel.config.js/config file options`,
`${msg(
optLoc,
)} is only allowed in root programmatic options, or babel.config.js/config file options`,
);
}
if (type === "env" && key === "env") {
throw new Error(`.${key} is not allowed inside another env block`);
}
if (type === "env" && key === "overrides") {
throw new Error(`.${key} is not allowed inside an env block`);
}
if (type === "override" && key === "overrides") {
throw new Error(`.${key} is not allowed inside an overrides block`);
}
const validator =
COMMON_VALIDATORS[key] ||
NONPRESET_VALIDATORS[key] ||
BABELRC_VALIDATORS[key] ||
ROOT_VALIDATORS[key];
ROOT_VALIDATORS[key] ||
throwUnknownError;
if (validator) validator(key, opts[key]);
else throw buildUnknownError(key);
validator(optLoc, opts[key]);
});
return (opts: any);
}
function buildUnknownError(key: string) {
function throwUnknownError(loc: OptionPath) {
const key = loc.name;
if (removed[key]) {
const { message, version = 5 } = removed[key];
throw new ReferenceError(
`Using removed Babel ${version} option: .${key} - ${message}`,
`Using removed Babel ${version} option: ${msg(loc)} - ${message}`,
);
} else {
// eslint-disable-next-line max-len
const unknownOptErr = `Unknown option: .${key}. Check out http://babeljs.io/docs/usage/options/ for more information about options.`;
const unknownOptErr = `Unknown option: ${msg(
loc,
)}. Check out https://babeljs.io/docs/en/babel-core/#options for more information about options.`;
throw new ReferenceError(unknownOptErr);
}
@@ -331,27 +387,53 @@ function assertNoDuplicateSourcemap(opts: {}): void {
}
}
function assertEnvSet(key: string, value: mixed): EnvSet<ValidatedOptions> {
const obj = assertObject(key, value);
function assertEnvSet(loc: OptionPath, value: mixed): EnvSet<ValidatedOptions> {
if (loc.parent.type === "env") {
throw new Error(`${msg(loc)} is not allowed inside of another .env block`);
}
const parent: RootPath | OverridesPath = loc.parent;
const obj = assertObject(loc, value);
if (obj) {
// Validate but don't copy the .env object in order to preserve
// object identity for use during config chain processing.
for (const key of Object.keys(obj)) {
const env = assertObject(key, obj[key]);
if (env) validate("env", env);
for (const envName of Object.keys(obj)) {
const env = assertObject(access(loc, envName), obj[envName]);
if (!env) continue;
const envLoc = {
type: "env",
name: envName,
parent,
};
validateNested(envLoc, env);
}
}
return (obj: any);
}
function assertOverridesList(key: string, value: mixed): OverridesList {
const arr = assertArray(key, value);
function assertOverridesList(loc: OptionPath, value: mixed): OverridesList {
if (loc.parent.type === "env") {
throw new Error(`${msg(loc)} is not allowed inside an .env block`);
}
if (loc.parent.type === "overrides") {
throw new Error(`${msg(loc)} is not allowed inside an .overrides block`);
}
const parent: RootPath = loc.parent;
const arr = assertArray(loc, value);
if (arr) {
for (const [index, item] of arr.entries()) {
const env = assertObject(`${index}`, item);
if (!env) throw new Error(`.${key}[${index}] must be an object`);
const objLoc = access(loc, index);
const env = assertObject(objLoc, item);
if (!env) throw new Error(`${msg(objLoc)} must be an object`);
validate("override", env);
const overridesLoc = {
type: "overrides",
index,
parent,
};
validateNested(overridesLoc, env);
}
}
return (arr: any);

View File

@@ -1,10 +1,11 @@
// @flow
import * as helpers from "@babel/helpers";
import { NodePath, Hub, Scope } from "@babel/traverse";
import { NodePath, Scope, type HubInterface } from "@babel/traverse";
import { codeFrameColumns } from "@babel/code-frame";
import traverse from "@babel/traverse";
import * as t from "@babel/types";
import semver from "semver";
import type { NormalizedFile } from "../normalize-file";
@@ -26,10 +27,18 @@ export default class File {
ast: Object = {};
scope: Scope;
metadata: {} = {};
hub: Hub = new Hub(this);
code: string = "";
inputMap: Object | null = null;
hub: HubInterface = {
// keep it for the usage in babel-core, ex: path.hub.file.opts.filename
file: this,
getCode: () => this.code,
getScope: () => this.scope,
addHelper: this.addHelper.bind(this),
buildError: this.buildCodeFrameError.bind(this),
};
constructor(options: {}, { code, ast, inputMap }: NormalizedFile) {
this.opts = options;
this.code = code;
@@ -64,6 +73,16 @@ export default class File {
}
set(key: mixed, val: mixed) {
if (key === "helpersNamespace") {
throw new Error(
"Babel 7.0.0-beta.56 has dropped support for the 'helpersNamespace' utility." +
"If you are using @babel/plugin-external-helpers you will need to use a newer " +
"version than the one you currently have installed. " +
"If you have your own implementation, you'll want to explore using 'helperGenerator' " +
"alongside 'file.availableHelper()'.",
);
}
this._map.set(key, val);
}
@@ -121,12 +140,6 @@ export default class File {
}
}
// TODO: Remove this before 7.x's official release. Leaving it in for now to
// prevent unnecessary breakage between beta versions.
resolveModuleSource(source: string): string {
return source;
}
addImport() {
throw new Error(
"This API has been removed. If you're looking for this " +
@@ -136,17 +149,58 @@ export default class File {
);
}
/**
* Check if a given helper is available in @babel/core's helper list.
*
* This _also_ allows you to pass a Babel version specifically. If the
* helper exists, but was not available for the full given range, it will be
* considered unavailable.
*/
availableHelper(name: string, versionRange: ?string): boolean {
let minVersion;
try {
minVersion = helpers.minVersion(name);
} catch (err) {
if (err.code !== "BABEL_HELPER_UNKNOWN") throw err;
return false;
}
if (typeof versionRange !== "string") return true;
// semver.intersects() has some surprising behavior with comparing ranges
// with preprelease versions. We add '^' to ensure that we are always
// comparing ranges with ranges, which sidesteps this logic.
// For example:
//
// semver.intersects(`<7.0.1`, "7.0.0-beta.0") // false - surprising
// semver.intersects(`<7.0.1`, "^7.0.0-beta.0") // true - expected
//
// This is because the first falls back to
//
// semver.satisfies("7.0.0-beta.0", `<7.0.1`) // false - surprising
//
// and this fails because a prerelease version can only satisfy a range
// if it is a prerelease within the same major/minor/patch range.
//
// Note: If this is found to have issues, please also revist the logic in
// transform-runtime's definitions.js file.
if (semver.valid(versionRange)) versionRange = `^${versionRange}`;
return (
!semver.intersects(`<${minVersion}`, versionRange) &&
!semver.intersects(`>=8.0.0`, versionRange)
);
}
addHelper(name: string): Object {
const declar = this.declarations[name];
if (declar) return t.cloneNode(declar);
const generator = this.get("helperGenerator");
const runtime = this.get("helpersNamespace");
if (generator) {
const res = generator(name);
if (res) return res;
} else if (runtime) {
return t.memberExpression(t.cloneNode(runtime), t.identifier(name));
}
const uid = (this.declarations[name] = this.scope.generateUidIdentifier(

View File

@@ -94,7 +94,7 @@ export default function mergeSourceMap(
}
function makeMappingKey(item: { line: number, columnStart: number }) {
return JSON.stringify([item.line, item.columnStart]);
return `${item.line}/${item.columnStart}`;
}
function eachOverlappingGeneratedOutputRange(
@@ -293,7 +293,7 @@ function findInsertionLocation<T>(
// Ensure the value is the start of any set of matches.
let i = left;
if (i < array.length) {
while (i > 0 && callback(array[i]) >= 0) {
while (i >= 0 && callback(array[i]) >= 0) {
i--;
}
return i + 1;

View File

@@ -91,14 +91,18 @@ export default function normalizeFile(
});
}
function parser(pluginPasses, options, code) {
function parser(
pluginPasses: PluginPasses,
{ parserOpts, highlightCode = true, filename = "unknown" }: Object,
code: string,
) {
try {
const results = [];
for (const plugins of pluginPasses) {
for (const plugin of plugins) {
const { parserOverride } = plugin;
if (parserOverride) {
const ast = parserOverride(code, options.parserOpts, parse);
const ast = parserOverride(code, parserOpts, parse);
if (ast !== undefined) results.push(ast);
}
@@ -106,7 +110,7 @@ function parser(pluginPasses, options, code) {
}
if (results.length === 0) {
return parse(code, options.parserOpts);
return parse(code, parserOpts);
} else if (results.length === 1) {
if (typeof results[0].then === "function") {
throw new Error(
@@ -136,15 +140,16 @@ function parser(pluginPasses, options, code) {
column: loc.column + 1,
},
},
options,
{
highlightCode,
},
);
if (missingPlugin) {
err.message =
`${options.filename || "unknown"}: ` +
`${filename}: ` +
generateMissingPluginMessage(missingPlugin[0], loc, codeFrame);
} else {
err.message =
`${options.filename || "unknown"}: ${err.message}\n\n` + codeFrame;
err.message = `${filename}: ${err.message}\n\n` + codeFrame;
}
err.code = "BABEL_PARSE_ERROR";
}

View File

@@ -31,6 +31,10 @@ export default class PluginPass {
return this._map.get(key);
}
availableHelper(name: string, versionRange: ?string) {
return this.file.availableHelper(name, versionRange);
}
addHelper(name: string) {
return this.file.addHelper(name);
}

View File

@@ -1,4 +1,4 @@
import loadConfig from "../lib/config";
import loadConfig, { loadPartialConfig } from "../lib/config";
import path from "path";
describe("@babel/core config loading", () => {
@@ -29,13 +29,53 @@ describe("@babel/core config loading", () => {
filename: FILEPATH,
presets: skipProgrammatic
? null
: [require("./fixtures/config-loading/preset3")],
: [[require("./fixtures/config-loading/preset3"), {}]],
plugins: skipProgrammatic
? null
: [require("./fixtures/config-loading/plugin6")],
: [[require("./fixtures/config-loading/plugin6"), {}]],
};
}
describe("loadPartialConfig", () => {
it("should preserve disabled plugins in the partial config", () => {
const plugin = function() {
return {};
};
const opts = loadPartialConfig({
...makeOpts(true),
babelrc: false,
configFile: false,
plugins: [[plugin, false]],
});
expect(opts.options.plugins.length).toBe(1);
const item = opts.options.plugins[0];
expect(item.value).toBe(plugin);
expect(item.options).toBe(false);
});
it("should preserve disabled presets in the partial config", () => {
const preset = function() {
return {};
};
const opts = loadPartialConfig({
...makeOpts(true),
babelrc: false,
configFile: false,
presets: [[preset, false]],
});
expect(opts.options.presets.length).toBe(1);
const item = opts.options.presets[0];
expect(item.value).toBe(preset);
expect(item.options).toBe(false);
});
});
describe("config file", () => {
it("should load and cache the config with plugins and presets", () => {
const opts = makeOpts();
@@ -173,7 +213,7 @@ describe("@babel/core config loading", () => {
}
});
it("should invalidate the plugins when given a fresh arrays", () => {
it("should not invalidate the plugins when given a fresh arrays", () => {
const opts = makeOpts();
const options1 = loadConfig(opts).options;
@@ -184,6 +224,38 @@ describe("@babel/core config loading", () => {
}).options;
expect(options2.plugins.length).toBe(options1.plugins.length);
for (let i = 0; i < options2.plugins.length; i++) {
expect(options2.plugins[i]).toBe(options1.plugins[i]);
}
});
it("should not invalidate the presets when given a fresh arrays", () => {
const opts = makeOpts();
const options1 = loadConfig(opts).options;
const options2 = loadConfig({
...opts,
presets: opts.presets.slice(),
}).options;
expect(options2.plugins.length).toBe(options1.plugins.length);
for (let i = 0; i < options2.plugins.length; i++) {
expect(options2.plugins[i]).toBe(options1.plugins[i]);
}
});
it("should invalidate the plugins when given a fresh options", () => {
const opts = makeOpts();
const options1 = loadConfig(opts).options;
const options2 = loadConfig({
...opts,
plugins: opts.plugins.map(([plg, opt]) => [plg, { ...opt }]),
}).options;
expect(options2.plugins.length).toBe(options1.plugins.length);
for (let i = 0; i < options2.plugins.length; i++) {
if (i === 2) {
expect(options2.plugins[i]).not.toBe(options1.plugins[i]);
@@ -193,14 +265,14 @@ describe("@babel/core config loading", () => {
}
});
it("should invalidate the presets when given a fresh arrays", () => {
it("should invalidate the presets when given a fresh options", () => {
const opts = makeOpts();
const options1 = loadConfig(opts).options;
const options2 = loadConfig({
...opts,
presets: opts.presets.slice(),
presets: opts.presets.map(([plg, opt]) => [plg, { ...opt }]),
}).options;
expect(options2.plugins.length).toBe(options1.plugins.length);
@@ -251,4 +323,51 @@ describe("@babel/core config loading", () => {
}
});
});
describe("caller metadata", () => {
it("should pass caller data through", () => {
const options1 = loadConfig({
...makeOpts(),
caller: {
name: "babel-test",
someFlag: true,
},
}).options;
expect(options1.caller.name).toBe("babel-test");
expect(options1.caller.someFlag).toBe(true);
});
it("should pass unknown caller data through", () => {
const options1 = loadConfig({
...makeOpts(),
caller: undefined,
}).options;
expect(options1.caller).toBeUndefined();
});
it("should pass caller data to test functions", () => {
const options1 = loadConfig({
...makeOpts(),
caller: {
name: "babel-test",
someFlag: true,
},
overrides: [
{
test: (filename, { caller }) => caller.name === "babel-test",
comments: false,
},
{
test: (filename, { caller }) => caller.name !== "babel-test",
ast: false,
},
],
}).options;
expect(options1.comments).toBe(false);
expect(options1.ast).not.toBe(false);
});
});
});

View File

@@ -0,0 +1,3 @@
module.exports = function() {
return {};
};

View File

@@ -0,0 +1,3 @@
module.exports = function() {
return {};
};

View File

@@ -0,0 +1,3 @@
module.exports = function() {
return {};
};

View File

@@ -0,0 +1,3 @@
module.exports = function() {
return {};
};

View File

@@ -1,3 +1,7 @@
{
"plugins": ["transform-classes", "external-helpers", "transform-block-scoping"]
"plugins": [
"transform-classes",
"external-helpers",
"transform-block-scoping"
]
}

View File

@@ -1,3 +1,8 @@
{
"plugins": ["syntax-flow", "transform-flow-strip-types", "transform-parameters", "transform-block-scoping"]
"plugins": [
"syntax-flow",
"transform-flow-strip-types",
"transform-parameters",
"transform-block-scoping"
]
}

View File

@@ -1,3 +1,7 @@
{
"plugins": ["transform-parameters", "transform-arrow-functions", "transform-block-scoping"]
"plugins": [
"transform-parameters",
"transform-arrow-functions",
"transform-block-scoping"
]
}

View File

@@ -1,10 +1,5 @@
{
"compact": false,
"presets": [
"env"
],
"plugins": [
"external-helpers",
"proposal-object-rest-spread"
]
"presets": ["env"],
"plugins": ["external-helpers", "proposal-object-rest-spread"]
}

View File

@@ -1,3 +1,8 @@
{
"plugins": ["transform-destructuring", "transform-parameters", "transform-block-scoping", "transform-regenerator"]
"plugins": [
"transform-destructuring",
"transform-parameters",
"transform-block-scoping",
"transform-regenerator"
]
}

Some files were not shown because too many files have changed in this diff Show More