Compare commits

..

65 Commits

Author SHA1 Message Date
Henry Zhu
e6d198eef5 v7.0.0-beta.48 2018-05-24 15:20:31 -04:00
Logan Smyth
86aacad2bc Disallow coverage on bundles. 2018-05-24 09:15:44 -07:00
Nicolò Ribaudo
6eab6f5863 [Babylon] Take the first set of options for plugins (#7994)
* [Babylon] Take the first set of options for plugins

* Fix test

* Docs
2018-05-24 08:54:32 -07:00
Brian Ng
555ee80f43 Fix some ts test fixtures 2018-05-24 10:03:03 -05:00
Brian Ng
a94cbf760a Set exprAllowed to false when parsing TSNonNullExpression (#7968) 2018-05-24 09:31:08 -05:00
Jimmy Jia
7489f8da7b Fix include/exclude syntax in preset-env README [ci skip] (#8020) 2018-05-23 22:09:54 -04:00
Nicolò Ribaudo
dccaec7691 Update types (BigInt) 2018-05-24 00:30:57 +02:00
Nicolò Ribaudo
c992f5b61e Remove duplicated test (in the old babylon folder) 2018-05-24 00:30:57 +02:00
Logan Smyth
5cd1276a27 Expose the Flow 'all' option on the preset too. (#8016)
| Q                        | A <!--(Can use an emoji 👍) -->
| ------------------------ | ---
| Fixed Issues?            | 
| Patch: Bug Fix?          | 
| Major: Breaking Change?  |
| Minor: New Feature?      |
| Tests Added + Pass?      | Yes
| Documentation PR         | <!-- If so, add `[skip ci]` to your commit message to skip CI -->
| Any Dependency Changes?  |
| License                  | MIT

The `all` option landed in https://github.com/babel/babel/pull/7934/files#diff-3a8233bcd2766d2c7d87f23f944f7726R3 but it is only exposed from the plugin, not the preset, so this exposes it there too since the flow preset is what we want people to use.
2018-05-23 13:40:22 -07:00
Justin Ridgewell
2af7a33c4e Fix class inheritance in IE10 (#7969)
* Revert "Move subclass inheritance to end (#7772)"

This reverts commit f8ab9466d3.

* Only use getPrototypeOf if setPrototypeOf is implemented

* Update fixtures

* Helpers updates

* Update fixtures

* Fall back to getPrototypeOf

* Update fixtures
2018-05-23 16:21:21 -04:00
Nicolò Ribaudo
ffe04d9195 [babylon] Refactor mixin plugins handling & validation (#7999) 2018-05-23 15:28:05 -04:00
Nicolò Ribaudo
b33823e7f8 Better error message for invalid decorators syntax (#7986) 2018-05-23 15:26:35 -04:00
Logan Smyth
007bfb6565 Merge pull request #8010 from loganfsmyth/babel-node-options
Add more of babel-cli's options to babel-node too for consistency.
2018-05-23 09:47:58 -07:00
Logan Smyth
c8faa34848 Only set '.babelrc' option if user explicitly set it. 2018-05-23 09:25:43 -07:00
Logan Smyth
5bcca0123a Add --env-name option to babel-node, like babel-cli's option. 2018-05-23 09:25:05 -07:00
Logan Smyth
1d987fb655 Add --config-file option to babel-node, like babel-cli's option. 2018-05-23 09:23:50 -07:00
Logan Smyth
06e5c46c8d Fix typo in option validation. 2018-05-23 09:23:14 -07:00
Sven SAULEAU
52b800decb Add no-babelrc option in babel-node (#5621)
<!-- 
Before making a PR please make sure to read our contributing guidelines 
https://github.com/babel/babel/blob/master/CONTRIBUTING.md

For any 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
-->

| Q                        | A <!--(yes/no) -->
| ------------------------ | ---
| Patch: Bug Fix?          | 
| Major: Breaking Change?  | 
| Minor: New Feature?      | y
| Deprecations?            | 
| Spec Compliancy?         | 
| Tests Added/Pass?        | y/y
| Fixed Tickets            | #5616
| License                  | MIT
| Doc PR                   | <!-- if yes, add `[skip ci]` to your commit message to skip CI builds -->
| Dependency Changes       | 

<!-- Describe your changes below in as much detail as possible -->

Once merged I will make the corresponding documentation changes on the website (in a 7 branch)
2018-05-23 09:19:39 -07:00
Sven SAULEAU
01d969a182 Merge pull request #8009 from babel/xtuc-patch-2
update AST spec - interpreter
2018-05-23 12:57:10 +02:00
Sven SAULEAU
7d99a96f9f docs: [skip ci] add InterpreterDirective 2018-05-23 09:50:23 +02:00
Sven SAULEAU
ad1de09b5f docs: [skip ci] update AST spec 2018-05-23 09:42:33 +02:00
Logan Smyth
6b91d6434d Add a try/catch on inline data-uri sourcemaps too, and add debug logging. 2018-05-22 23:38:16 -07:00
Michael Lavina
18796173ab feat(sourcemap): parse external source maps when normalizing (#7980) 2018-05-22 23:29:10 -07:00
Logan Smyth
eb3334a14e Merge pull request #7955 from loganfsmyth/typescript-filename-required
Verify that files are .ts/.tsx before treating as Typescript files.
2018-05-22 22:41:39 -07:00
Logan Smyth
5e00c96368 Handle Infinity, -Infinity, NaN, and -0 in t.valueToNode(). (#8005)
| Q                        | A <!--(Can use an emoji 👍) -->
| ------------------------ | ---
| Fixed Issues?            | Fixes #8001
| Patch: Bug Fix?          | Y
| Major: Breaking Change?  | Not unless things were relying on a very specific AST structure as output
| Minor: New Feature?      |
| Tests Added + Pass?      | Yes
| Documentation PR         | <!-- If so, add `[skip ci]` to your commit message to skip CI -->
| Any Dependency Changes?  |
| License                  | MIT

The filed bug was for `-0`, but I also realize that `numericLiteral` also shouldn't be getting `-Infinity`/`Infinity` or `NaN` since those just get stringified with the JS-standard stringification logic which means we get a reference to `NaN` or `Infinity` identifiers, which could have been shadowed in a local scope and thus not be the right value. I've avoided that by generating `NaN` as `0/0` and the infinity values as `1/0` and `-1/0`.
2018-05-22 14:37:06 -07:00
Henry Zhu
b4d18f4764 Bigint Support without transform (#8006) 2018-05-22 15:31:34 -04:00
Brian Ng
981bff08e4 Fix some flow issues in @babel/parser flow plugin (#8002) 2018-05-22 10:48:49 -07:00
Nicolò Ribaudo
7d641d2e74 Update babel-types docs (InterpreterDirective) [skip ci] (#8004)
Introduced in #7928
2018-05-22 17:50:15 +02:00
Logan Smyth
f2882d570a Tests for react/ts compat and flow/ts compat. 2018-05-21 21:21:00 -07:00
Logan Smyth
cc5aeb3b50 Allow .ts and .tsx test fixtures. 2018-05-21 20:31:40 -07:00
Logan Smyth
d164f820e6 Merge pull request #7928 from loganfsmyth/shebang-node
Create InterpreterDirective AST node type and use to replace babel/core File's 'shebang' handling
2018-05-21 20:02:12 -07:00
Logan Smyth
43aa61d6be Make the typescript preset require a filename unless the user configured it for general use. 2018-05-21 18:34:50 -07:00
Logan Smyth
ca1c98b255 Allow .overrides and .env inside presets. 2018-05-21 18:23:07 -07:00
Logan Smyth
0963dbddea Rely on Babylon for interpreter directive parsing, instead of babel/core. 2018-05-21 18:19:59 -07:00
Logan Smyth
2058e0686e Add support for an InterpreterDirective AST node. 2018-05-21 18:19:58 -07:00
Logan Smyth
c0013264b7 Add tests for interpreter directive with retainLines and sourcemaps. 2018-05-21 18:08:32 -07:00
Logan Smyth
442ead701c Fix a few out-of-order test results. 2018-05-21 18:08:31 -07:00
Logan Smyth
5fb3696955 Avoid flow errors now that we've renamed Babylon to babel-parser. 2018-05-21 18:06:17 -07:00
Logan Smyth
69cca412eb Make the filename option, as exposed to the plugins, consistently relative to the working directory (#7956)
| Q                        | A <!--(Can use an emoji 👍) -->
| ------------------------ | ---
| Fixed Issues?            | 
| Patch: Bug Fix?          | Y
| Major: Breaking Change?  | N
| Minor: New Feature?      |
| Tests Added + Pass?      | Yes
| Documentation PR         | <!-- If so, add `[skip ci]` to your commit message to skip CI -->
| Any Dependency Changes?  |
| License                  | MIT

Currently the `opts.filename` value exposed to plugins is just whatever the user passed. While it _could_ be relative to the working directory, if Babel was passed an absolute URL, it'll be absolute.

This PR explicitly ensures the filename is a relative path based on the working directory. This also exposes an officially endorsed API for reading the working directory path.
2018-05-21 17:10:57 -07:00
Mike Nason
3bee37b14d fix typo in error message (#7995) 2018-05-21 12:18:09 -07:00
Miguel Albernaz
bc757c8b75 passes the jsxPragma options from preset-typescript to plugin-transform-typescript (#7990) 2018-05-21 14:33:43 -04:00
Conor Hastings
c558dedd7b fix typo of babel in readme (#7992) [skip ci] 2018-05-21 07:42:13 +02:00
Justin Ridgewell
0879a6d608 Subsume json (#7985)
* Add Subsume JSON transform

https://github.com/tc39/proposal-json-superset is at stage 3.

This allows U+2028 LINE SEPARATOR and U+2029 PARAGRAPH SEPARATOR to appear unescaped inside strings and directives.

* Move to Stage 3

* Break diretive parsing

* Update README

* Handle multi-escape sequences

* Remove babylon files after rename
2018-05-19 15:32:05 -04:00
Henry Zhu
51eef099b3 fixes [skip ci] 2018-05-19 00:12:26 -04:00
Chaitanya Kumar Kamatham
daf0ca8680 Rename "babylon" to "@babel/parser" (#7937) 🎉 2018-05-19 00:03:05 -04:00
Justin Ridgewell
0200a3e510 Build InterfaceTypeAnnotation generated type code (#7982) 2018-05-18 14:41:19 -04:00
Justin Ridgewell
27c39c512d Class private properties (#7842)
* Update member-expression-to-functions

1. Babel using British spellings, so `memoise`
2. Provide a helper `AssignmentMemoiser` class, which will assign the memo'd value with the `n`th access.

* Private properties!

* Fixes

* Tests

* Update helper name

* Fix privates that reference other privates

* Don't extend a builtin

* Rebase
2018-05-18 14:03:23 -04:00
Ben Newman
70eb206c03 TypeScript: Fix TSInferType .typeParameter type. (#7967)
Follow-up to https://github.com/babel/babel/pull/7404

There is no TypeParameter type in the Babylon TypeScript AST hierarchy.
Flow does have a TypeParameter type, but it should not be confused with
the TypeScript TSTypeParameter, since Flow !== TypeScript, and the types
have totally different fields. Instead, the .typeParameter.type of a
Babylon-parsed TSInferType node should be TSTypeParameter.

It would probably be fine to leave the declared type of the TSInferType
.typeParameter field as TSType instead of TSTypeParameter, but the more
specific TSTypeParameter type should be safe/correct, since the TypeScript
parseInferType function always uses SyntaxKind.TypeParameter:
66d6e5e6e0/src/compiler/parser.ts (L3006)

I noticed this typo because it has been causing ast-types test failures
lately, e.g. https://travis-ci.org/benjamn/ast-types/jobs/369634972
2018-05-18 10:15:48 -05:00
Nicolò Ribaudo
229179b8aa Update babel-types (flow internal slots) (#7977) 2018-05-18 08:47:31 -05:00
Sam Goldman
6baa36cdc5 Support Flow's inline interface syntax (#7973)
* Support Flow's inline interface syntax

* Fix babel-generator
2018-05-18 08:11:27 -05:00
Sam Goldman
a40f54f847 Add support for explicit type arguments in new and call expressions (#7934)
* Add all option to babel-plugin-syntax-flow

The Flow parser has some conditional logic based on whether types should
be parsed or not, which is based on either (a) the @flow pragma in the
docblock of the file of (b) the `all` configuration, provided via
command line or .flowconfig.

This commit adds the ability to provide the `all` configuration to
Babel as well, via the syntax-flow plugin. This should be set to `true`
if the project uses all=true.

* Parse @flow pragma

The Flow parser has some conditional logic based on whether types should
be parsed or not, which is based on either (a) the @flow pragma in the
docblock of the file of (b) the `all` configuration, provided via
command line or .flowconfig.

This commit parses the @flow (or @noflow) pragma from the first comment
in the source file. Directives are allowed to appear before the comment.

* WIP: add tests for explicit type arguments

This commit includes tests which have unexpected output, but will change
to the expected output as later commits add parsing support for various
features.

* Parse type arguments in new expressions

* Parse type arguments in call expressions

* Parse optional call expressions with explicit type args

* Add explicit type arguments to babel-types

Flow calls these typeArguments instead of typeParameters, which clearly
separates formal/actual parameters, and mirrors the existing arguments
key.

The existing definitions to support TypeScript also included Flow's
TypeParameterInstantiation node type, which I've moved to the the new
field.

* Add support for explicit type arguments to babel-generator

* Add test for explicit type args to transform-flow-strip-types plugin

* Oops. Forgot to regenerate the babel-types README.

* Fix Flow parser shouldParseTypes() function

I was looking at `options.all`, but the correct property ws
`options.flowAll`. Oops!

* Remove typeapp_call from whitelist of expected failures

Now that Babylon parses this syntax extension, we can remove the
typeapp_call tests from the list of expected differences.

Note that I am using the `flowAll` option, mirroring the behavior of the
Flow tests, which assume types without requiring the `@flow` pragma.

* Use Babylon plugin options instead of parser options

* Parse optional call expressions type arguments unambiguously
2018-05-18 08:05:16 -05:00
Nicolò Ribaudo
6226c52f43 Add "legacy" prefix to legacy decorators tests (#7975) 2018-05-18 14:46:07 +02:00
Lars Willighagen
25153359f7 helper-plugin-utils: Move README [skip ci] (#7972)
Move README from src to package root, as in other packages.

Closes #7971
2018-05-18 10:00:25 +02:00
Nicolò Ribaudo
2351a638b5 Fix bugs in the _wrapNativeSuper helper (#7533)
* Remove second wrapper from _wrapNativeSuper

* Fix tests on node 4

I DON'T KNOW WHY IT WORKS.

* Update fixtures

* Use Reflect.construct

* Parens

* Fix things

* Fix things

* Undo changes

* Fix with sham

* Typo
2018-05-18 00:04:12 +02:00
Rubén Norte
bc6f0f989d Re-add support for local Flow bindings (TypeAlias, OpaqueTypeAlias and Interface) (#7900) 2018-05-17 10:54:14 -07:00
Sam Goldman
af7ab71486 Allow flow internal slot properties to be optional (#7959)
See 23d1b1c5f2
2018-05-17 19:01:03 +02:00
Logan Smyth
ac13c302f7 Merge pull request #7929 from loganfsmyth/cli-refactoring
Refactor babel-cli to use async functions for async handling, and centralize option loading
2018-05-16 20:58:46 -07:00
Sam Goldman
b396cdcbe5 Internal slot properties (#7947)
* Support internalSlots to babel-types and babel-generator

* Parsing support for internal slot properties

* Print internal slots in babel-generator

* Add whitespace before first internal slot property
2018-05-16 22:48:12 -05:00
Michal Artazov
8dcfabd0d7 update core-js to 2.5.6 (#7950) 2018-05-16 10:08:19 -07:00
Nicolò Ribaudo
e45d5c3b65 Add an option to Babylon to have decorators before export (#7869)
* Add support for plugin options in Babylon

They work similarly to how they work in Babel. e.g.
  babylon.parse({
    options: [
      "plugin1",
      ["plugin2", { option: true }]
    ]
  });

The inernal api to get an option is
  this.getPluginOption("pluginName", "option")
If the plugin isn't defined, it returns undefined.

* Add Babylon option decorators.secoratorsBeforeExport

* Nit
2018-05-15 11:39:53 -05:00
Logan Smyth
8ff675ad69 Refactor CLI to use promises/async fns. 2018-05-14 23:07:50 -07:00
Logan Smyth
a955efa3e3 Ensure that calling register fully resets the state. (#7930) 2018-05-14 23:04:56 -07:00
Logan Smyth
51db3e9a5d Bug fixing for Node 10 (#7931) 2018-05-14 23:02:01 -07:00
Logan Smyth
41ca312545 Define a clear separation between Babel and CLI options. 2018-05-14 22:03:47 -07:00
Logan Smyth
a192f8beb4 Limit node version to current LTS. 2018-05-14 21:54:16 -07:00
10325 changed files with 386581 additions and 373478 deletions

View File

@@ -22,4 +22,4 @@ packages/babel-preset-env-standalone/babel-preset-env.js
packages/babel-preset-env-standalone/babel-preset-env.min.js
packages/babel-standalone/babel.js
packages/babel-standalone/babel.min.js
packages/babylon/test/expressions
packages/babel-parser/test/expressions

2
.gitignore vendored
View File

@@ -42,6 +42,6 @@ packages/babel-preset-env-standalone/babel-preset-env.js
packages/babel-preset-env-standalone/babel-preset-env.min.js
/codemods/*/lib
/codemods/*/node_modules
/packages/babylon/build
/packages/babel-parser/build
.idea/
/.changelog

View File

@@ -22,14 +22,14 @@ before_install:
install: yarn --ignore-engines
before_script:
- 'if [ "$JOB" = "babylon-flow-tests" ]; then make bootstrap-flow; fi'
- 'if [ "$JOB" = "babylon-test262-tests" ]; then make bootstrap-test262; fi'
- 'if [ "$JOB" = "babel-parser-flow-tests" ]; then make bootstrap-flow; fi'
- 'if [ "$JOB" = "babel-parser-test262-tests" ]; then make bootstrap-test262; fi'
script:
- 'if [ "$JOB" = "test" ]; then make test-ci; fi'
- 'if [ "$JOB" = "lint" ]; then make lint && make flow; fi'
- 'if [ "$JOB" = "babylon-flow-tests" ]; then make test-flow-ci; fi'
- 'if [ "$JOB" = "babylon-test262-tests" ]; then make test-test262-ci; fi'
- 'if [ "$JOB" = "babel-parser-flow-tests" ]; then make test-flow-ci; fi'
- 'if [ "$JOB" = "babel-parser-test262-tests" ]; then make test-test262-ci; fi'
matrix:
fast_finish: true
@@ -37,9 +37,9 @@ matrix:
- node_js: "node"
env: JOB=lint
- node_js: "node"
env: JOB=babylon-flow-tests
env: JOB=babel-parser-flow-tests
- node_js: "node"
env: JOB=babylon-test262-tests
env: JOB=babel-parser-test262-tests
notifications:
slack:

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/babylon/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/babylon#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://github.com/babel/babel/tree/master/packages/babel-parser#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
@@ -226,19 +226,19 @@ If the test requires a minimum Node version, you can add `minNodeVersion` (must
}
```
#### `babylon`
#### `@babel/parser` (babylon)
Writing tests for Babylon is very
Writing tests for the babel parser is very
similar to the other packages.
Inside the `packages/babylon/tests/fixtures` folder are categories/groupings of test fixtures (es2015, flow,
Inside the `packages/babel-parser/tests/fixtures` folder are categories/groupings of test fixtures (es2015, flow,
etc.). To add a test, create a folder under one of these groupings (or create a new one) with a
descriptive name, and add the following:
* Create an `input.js` file that contains the code you want Babylon to parse.
* Create an `input.js` file that contains the code you want the babel parser to parse.
* Add an `output.json` file with the expected parser output. For added convenience, if there is no `output.json` present, the test runner will generate one for you.
After writing tests for babylon, just build it by running:
After writing tests for @babel/parser, just build it by running:
```sh
$ make build
@@ -247,17 +247,17 @@ $ make build
Then, to run the tests, use:
```sh
$ TEST_ONLY=babylon make test-only
$ TEST_ONLY=babel-parser make test-only
```
#### Bootstrapping expected output
For both `@babel/plugin-x` and `babylon`, you can easily generate an `output.js`/`output.json` automatically by just providing `input.js` and running the tests as you usually would.
For both `@babel/plugin-x` and `@babel/parser`, you can easily generate an `output.js`/`output.json` automatically by just providing `input.js` and running the tests as you usually would.
```
// Example
- packages
- babylon
- babel-parser
- test
- fixtures
- comments
@@ -309,14 +309,14 @@ Note that the code shown in Chrome DevTools is compiled code and therefore diffe
- Create a new issue that describes the proposal (ex: [#538](https://github.com/babel/babylon/issues/538)). Include any relevant information like proposal repo/author, examples, parsing approaches, meeting notes, presentation slides, and more.
- The pull request should include:
- [ ] An update to the [plugins](https://github.com/babel/babel/tree/master/packages/babylon#plugins) part of the readme. Add a new entry to that list for the new plugin flag (and link to the proposal)
- [ ] If any new nodes or modifications need to be added to the AST, update [ast/spec.md](https://github.com/babel/babel/bloc/master/packages/babylon/ast/spec.md)
- [ ] Make sure you use the `this.hasPlugin("plugin-name-here")` check in Babylon so that your new plugin code only runs when that flag is turned on (not default behavior)
- [ ] An update to the [plugins](https://github.com/babel/babel/tree/master/packages/babel-parser#plugins) part of the readme. Add a new entry to that list for the new plugin flag (and link to the proposal)
- [ ] If any new nodes or modifications need to be added to the AST, update [ast/spec.md](https://github.com/babel/babel/bloc/master/packages/babel-parser/ast/spec.md)
- [ ] Make sure you use the `this.hasPlugin("plugin-name-here")` check in the babel parser so that your new plugin code only runs when that flag is turned on (not default behavior)
- [ ] Add failing/passing tests according to spec behavior
- Start working about the Babel transform itself!
## Internals
- AST spec ([babylon/ast/spec.md](https://github.com/babel/babel/blob/master/packages/babylon/ast/spec.md))
- AST spec ([babel-parser/ast/spec.md](https://github.com/babel/babel/blob/master/packages/babel-parser/ast/spec.md))
- Versioning ([doc/design/versioning.md](https://github.com/babel/babel/blob/master/doc/design/versioning.md))
- Monorepo ([doc/design/monorepo.md](https://github.com/babel/babel/blob/master/doc/design/monorepo.md))
- Compiler environment support ([doc/design/compiler-environment-support.md](https://github.com/babel/babel/blob/master/doc/design/compiler-environment-support.md))

View File

@@ -98,7 +98,7 @@ function buildRollup(packages) {
format: "cjs",
plugins: [
rollupBabel({
envName: "babylon",
envName: "babel-parser",
}),
rollupNodeResolve(),
],
@@ -113,7 +113,7 @@ function buildRollup(packages) {
}
gulp.task("build", function() {
const bundles = ["packages/babylon"];
const bundles = ["packages/babel-parser"];
return merge([buildBabel(/* exclude */ bundles), buildRollup(bundles)]);
});

View File

@@ -87,12 +87,12 @@ bootstrap-flow:
cd build/flow && git checkout $(FLOW_COMMIT)
test-flow:
node scripts/tests/flow/run_babylon_flow_tests.js
node scripts/tests/flow/run_babel_parser_flow_tests.js
test-flow-ci: bootstrap test-flow
test-flow-update-whitelist:
node scripts/tests/flow/run_babylon_flow_tests.js --update-whitelist
node scripts/tests/flow/run_babel_parser_flow_tests.js --update-whitelist
bootstrap-test262:
rm -rf ./build/test262
@@ -101,12 +101,12 @@ bootstrap-test262:
cd build/test262 && git checkout $(TEST262_COMMIT)
test-test262:
node scripts/tests/test262/run_babylon_test262.js
node scripts/tests/test262/run_babel_parser_test262.js
test-test262-ci: bootstrap test-test262
test-test262-update-whitelist:
node scripts/tests/test262/run_babylon_test262.js --update-whitelist
node scripts/tests/test262/run_babel_parser_test262.js --update-whitelist
publish:
git pull --rebase

View File

@@ -16,7 +16,7 @@ module.exports = function(api) {
switch (env) {
// Configs used during bundling builds.
case "babylon":
case "babel-parser":
case "standalone":
convertESM = false;
ignoreLib = false;
@@ -24,7 +24,7 @@ module.exports = function(api) {
case "production":
// Config during builds before publish.
envOpts.targets = {
node: 6,
node: "6.9",
};
break;
case "development":
@@ -69,7 +69,7 @@ module.exports = function(api) {
].filter(Boolean),
overrides: [
{
test: "packages/babylon",
test: "packages/babel-parser",
plugins: [
"babel-plugin-transform-charcodes",
["@babel/transform-for-of", { assumeArray: true }],

View File

@@ -1,6 +1,6 @@
{
"name": "@babel/plugin-codemod-object-assign-to-object-spread",
"version": "7.0.0-beta.47",
"version": "7.0.0-beta.48",
"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",
@@ -10,14 +10,14 @@
"@babel/plugin"
],
"dependencies": {
"@babel/plugin-syntax-object-rest-spread": "7.0.0-beta.47"
"@babel/plugin-syntax-object-rest-spread": "7.0.0-beta.48"
},
"peerDependencies": {
"@babel/core": "7.0.0-beta.47"
"@babel/core": "7.0.0-beta.48"
},
"devDependencies": {
"@babel/core": "7.0.0-beta.47",
"@babel/helper-plugin-test-runner": "7.0.0-beta.47"
"@babel/core": "7.0.0-beta.48",
"@babel/helper-plugin-test-runner": "7.0.0-beta.48"
},
"publishConfig": {
"access": "public"

View File

@@ -1,6 +1,6 @@
{
"name": "@babel/plugin-codemod-optional-catch-binding",
"version": "7.0.0-beta.47",
"version": "7.0.0-beta.48",
"description": "Remove unused catch bindings",
"repository": "https://github.com/babel/babel/tree/master/codemods/babel-plugin-codemod-remove-unused-catch-binding",
"license": "MIT",
@@ -10,13 +10,13 @@
"@babel/plugin"
],
"dependencies": {
"@babel/plugin-syntax-optional-catch-binding": "7.0.0-beta.47"
"@babel/plugin-syntax-optional-catch-binding": "7.0.0-beta.48"
},
"peerDependencies": {
"@babel/core": "7.0.0-beta.47"
"@babel/core": "7.0.0-beta.48"
},
"devDependencies": {
"@babel/core": "7.0.0-beta.47",
"@babel/helper-plugin-test-runner": "7.0.0-beta.47"
"@babel/core": "7.0.0-beta.48",
"@babel/helper-plugin-test-runner": "7.0.0-beta.48"
}
}

View File

@@ -1 +1 @@
The [AST specification](https://github.com/babel/babel/blob/master/packages/babylon/ast/spec.md) has been moved to the Babylon package, `packages/babylon`.
The [AST specification](https://github.com/babel/babel/blob/master/packages/babel-parser/ast/spec.md) has been moved to the babel parser package, `packages/babel-parser`.

View File

@@ -1,6 +1,6 @@
{
"lerna": "2.0.0-rc.4",
"version": "7.0.0-beta.47",
"version": "7.0.0-beta.48",
"changelog": {
"repo": "babel/babel",
"cacheDir": ".changelog",

View File

@@ -68,7 +68,7 @@
"webpack-stream": "^4.0.0"
},
"engines": {
"node": ">= 6.x <= 9.x",
"node": ">= 6.9.0 <= 11.0.0-0",
"npm": ">= 2.x <= 5.x",
"yarn": ">=0.27.5 || >=1.0.0-20170811"
},
@@ -89,7 +89,7 @@
"/node_modules/",
"/test/fixtures/",
"/test/debug-fixtures/",
"/babylon/test/expressions/",
"/babel-parser/test/expressions/",
"/test/tmp/",
"/test/__data__/",
"/test/helpers/",
@@ -106,6 +106,12 @@
"/test/(fixtures|tmp|__data__)/",
"<rootDir>/(packages|codemods)/[^/]+/lib/"
],
"coveragePathIgnorePatterns": [
"/node_modules/",
"<rootDir>/packages/babel-standalone/babel(\\.min)?\\.js",
"<rootDir>/packages/babel-preset-env-standalone/babel-preset-env(\\.min)?\\.js",
"/test/(fixtures|tmp|__data__)/"
],
"modulePathIgnorePatterns": [
"/test/fixtures/",
"/test/tmp/",

View File

@@ -14,21 +14,21 @@ 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) |
| [`babylon`](/packages/babylon) | [![npm](https://img.shields.io/npm/v/babylon.svg?maxAge=2592000)](https://www.npmjs.com/package/babylon) | [![Dependency Status](https://david-dm.org/babel/babel.svg?path=packages/babylon)](https://david-dm.org/babel/babel?path=packages/babylon) |
| [`@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) is the Babel compiler itself; it exposes the `babel.transform` method, where `transformedCode = transform(src).code`.
The compiler can be broken down into 3 parts:
- The parser: [`babylon`](/packages/babylon)
- The parser: [`@babel/parser`](/packages/babel-parser)
- The transformer[s]: All the plugins/presets
- These all use [`@babel/traverse`](/packages/babel-traverse) to traverse through the AST
- The generator: [`@babel/generator`](/packages/babel-generator)
The flow goes like this:
input string -> `babylon` parser -> `AST` -> transformer[s] -> `AST` -> `@babel/generator` -> output string
input string -> `@babel/parser` parser -> `AST` -> transformer[s] -> `AST` -> `@babel/generator` -> output string
Check out the [`babel-handbook`](https://github.com/thejameskyle/babel-handbook/blob/master/translations/en/plugin-handbook.md#introduction) for more information on this.

View File

@@ -1,6 +1,6 @@
{
"name": "@babel/cli",
"version": "7.0.0-beta.47",
"version": "7.0.0-beta.48",
"description": "Babel command line.",
"author": "Sebastian McKenzie <sebmck@gmail.com>",
"homepage": "https://babeljs.io/",
@@ -29,11 +29,11 @@
"chokidar": "^2.0.3"
},
"peerDependencies": {
"@babel/core": "7.0.0-beta.47"
"@babel/core": "7.0.0-beta.48"
},
"devDependencies": {
"@babel/core": "7.0.0-beta.47",
"@babel/helper-fixtures": "7.0.0-beta.47"
"@babel/core": "7.0.0-beta.48",
"@babel/helper-fixtures": "7.0.0-beta.48"
},
"bin": {
"babel": "./bin/babel.js",

View File

@@ -6,58 +6,69 @@ import fs from "fs";
import * as util from "./util";
let compiledFiles = 0;
export default async function({ cliOptions, babelOptions }) {
const filenames = cliOptions.filenames;
export default function(commander, filenames, opts) {
function write(src, base, callback) {
async function write(src, base) {
let relative = path.relative(base, src);
if (!util.isCompilableExtension(relative, commander.extensions)) {
return process.nextTick(callback);
if (!util.isCompilableExtension(relative, cliOptions.extensions)) {
return false;
}
// remove extension and then append back on .js
relative = util.adjustRelative(relative, commander.keepFileExtension);
relative = util.adjustRelative(relative, cliOptions.keepFileExtension);
const dest = getDest(commander, relative, base);
const dest = getDest(relative, base);
util.compile(
src,
defaults(
{
sourceFileName: slash(path.relative(dest + "/..", src)),
},
opts,
),
function(err, res) {
if (err) return callback(err);
if (!res) return callback();
try {
const res = await util.compile(
src,
defaults(
{
sourceFileName: slash(path.relative(dest + "/..", src)),
},
babelOptions,
),
);
// we've requested explicit sourcemaps to be written to disk
if (
res.map &&
commander.sourceMaps &&
commander.sourceMaps !== "inline"
) {
const mapLoc = dest + ".map";
res.code = util.addSourceMappingUrl(res.code, mapLoc);
res.map.file = path.basename(relative);
outputFileSync(mapLoc, JSON.stringify(res.map));
}
if (!res) return false;
outputFileSync(dest, res.code);
util.chmod(src, dest);
// we've requested explicit sourcemaps to be written to disk
if (
res.map &&
babelOptions.sourceMaps &&
babelOptions.sourceMaps !== "inline"
) {
const mapLoc = dest + ".map";
res.code = util.addSourceMappingUrl(res.code, mapLoc);
res.map.file = path.basename(relative);
outputFileSync(mapLoc, JSON.stringify(res.map));
}
compiledFiles += 1;
outputFileSync(dest, res.code);
util.chmod(src, dest);
util.log(src + " -> " + dest);
return callback(null, true);
},
);
if (cliOptions.verbose) {
console.log(src + " -> " + dest);
}
return true;
} catch (err) {
if (cliOptions.watch) {
console.error(err);
return false;
}
throw err;
}
}
function getDest(commander, filename, base) {
if (commander.relative) return path.join(base, commander.outDir, filename);
return path.join(commander.outDir, filename);
function getDest(filename, base) {
if (cliOptions.relative) {
return path.join(base, cliOptions.outDir, filename);
}
return path.join(cliOptions.outDir, filename);
}
function outputDestFolder(outDir) {
@@ -67,88 +78,65 @@ export default function(commander, filenames, opts) {
}
}
function handleFile(src, base, callback) {
write(src, base, function(err, res) {
if (err) return callback(err);
if (!res && commander.copyFiles) {
const filename = path.relative(base, src);
const dest = getDest(commander, filename, base);
outputFileSync(dest, fs.readFileSync(src));
util.chmod(src, dest);
}
async function handleFile(src, base) {
const written = await write(src, base);
return callback();
});
if (!written && cliOptions.copyFiles) {
const filename = path.relative(base, src);
const dest = getDest(filename, base);
outputFileSync(dest, fs.readFileSync(src));
util.chmod(src, dest);
}
return written;
}
function sequentialHandleFile(files, dirname, index, callback) {
if (files.length === 0) {
outputDestFolder(commander.outDir);
return;
}
async function handle(filenameOrDir) {
if (!fs.existsSync(filenameOrDir)) return 0;
if (typeof index === "function") {
callback = index;
index = 0;
}
const stat = fs.statSync(filenameOrDir);
const filename = files[index];
const src = path.join(dirname, filename);
if (stat.isDirectory(filenameOrDir)) {
const dirname = filenameOrDir;
handleFile(src, dirname, function(err) {
if (err) return callback(err);
index++;
if (index !== files.length) {
sequentialHandleFile(files, dirname, index, callback);
} else {
callback();
}
});
}
let count = 0;
function handle(filename, callback) {
if (!fs.existsSync(filename)) return;
const files = util.readdir(dirname, cliOptions.includeDotfiles);
for (const filename of files) {
const src = path.join(dirname, filename);
const stat = fs.statSync(filename);
if (stat.isDirectory(filename)) {
const dirname = filename;
if (commander.deleteDirOnStart) {
util.deleteDir(commander.outDir);
const written = await handleFile(src, dirname);
if (written) count += 1;
}
const files = util.readdir(dirname, commander.includeDotfiles);
sequentialHandleFile(files, dirname, callback);
return count;
} else {
write(filename, path.dirname(filename), callback);
const filename = filenameOrDir;
const written = await handleFile(filename, path.dirname(filename));
return written ? 1 : 0;
}
}
function sequentialHandle(filenames, index = 0) {
const filename = filenames[index];
if (!cliOptions.skipInitialBuild) {
if (cliOptions.deleteDirOnStart) {
util.deleteDir(cliOptions.outDir);
}
handle(filename, function(err) {
if (err) throw new Error(err);
index++;
if (index !== filenames.length) {
sequentialHandle(filenames, index);
} else {
util.log(
`🎉 Successfully compiled ${compiledFiles} ${
compiledFiles > 1 ? "files" : "file"
} with Babel.`,
true,
);
}
});
outputDestFolder(cliOptions.outDir);
let compiledFiles = 0;
for (const filename of cliOptions.filenames) {
compiledFiles += await handle(filename);
}
console.log(
`🎉 Successfully compiled ${compiledFiles} ${
compiledFiles !== 1 ? "files" : "file"
} with Babel.`,
);
}
if (!commander.skipInitialBuild) {
sequentialHandle(filenames);
}
if (commander.watch) {
if (cliOptions.watch) {
const chokidar = util.requireChokidar();
filenames.forEach(function(filenameOrDir) {
@@ -168,10 +156,9 @@ export default function(commander, filenames, opts) {
filename === filenameOrDir
? path.dirname(filenameOrDir)
: filenameOrDir,
function(err) {
if (err) console.error(err.stack);
},
);
).catch(err => {
console.error(err);
});
});
});
});

View File

@@ -7,26 +7,22 @@ import fs from "fs";
import * as util from "./util";
export default function(commander, filenames, opts) {
if (commander.sourceMaps === "inline") {
opts.sourceMaps = true;
}
let results = [];
const buildResult = function() {
export default async function({ cliOptions, babelOptions }) {
function buildResult(fileResults) {
const map = new sourceMap.SourceMapGenerator({
file:
commander.sourceMapTarget ||
path.basename(commander.outFile || "") ||
cliOptions.sourceMapTarget ||
path.basename(cliOptions.outFile || "") ||
"stdout",
sourceRoot: opts.sourceRoot,
sourceRoot: babelOptions.sourceRoot,
});
let code = "";
let offset = 0;
results.forEach(function(result) {
for (const result of fileResults) {
if (!result) continue;
code += result.code + "\n";
if (result.map) {
@@ -61,13 +57,13 @@ export default function(commander, filenames, opts) {
offset = code.split("\n").length - 1;
}
});
}
// add the inline sourcemap comment if we've either explicitly asked for inline source
// maps, or we've requested them without any output file
if (
commander.sourceMaps === "inline" ||
(!commander.outFile && commander.sourceMaps)
babelOptions.sourceMaps === "inline" ||
(!cliOptions.outFile && babelOptions.sourceMaps)
) {
code += "\n" + convertSourceMap.fromObject(map).toComment();
}
@@ -76,57 +72,62 @@ export default function(commander, filenames, opts) {
map: map,
code: code,
};
};
}
const output = function() {
const result = buildResult();
function output(fileResults) {
const result = buildResult(fileResults);
if (commander.outFile) {
if (cliOptions.outFile) {
// we've requested for a sourcemap to be written to disk
if (commander.sourceMaps && commander.sourceMaps !== "inline") {
const mapLoc = commander.outFile + ".map";
if (babelOptions.sourceMaps && babelOptions.sourceMaps !== "inline") {
const mapLoc = cliOptions.outFile + ".map";
result.code = util.addSourceMappingUrl(result.code, mapLoc);
fs.writeFileSync(mapLoc, JSON.stringify(result.map));
}
fs.writeFileSync(commander.outFile, result.code);
fs.writeFileSync(cliOptions.outFile, result.code);
} else {
process.stdout.write(result.code + "\n");
}
};
}
const stdin = function() {
let code = "";
function readStdin() {
return new Promise((resolve, reject) => {
let code = "";
process.stdin.setEncoding("utf8");
process.stdin.setEncoding("utf8");
process.stdin.on("readable", function() {
const chunk = process.stdin.read();
if (chunk !== null) code += chunk;
process.stdin.on("readable", function() {
const chunk = process.stdin.read();
if (chunk !== null) code += chunk;
});
process.stdin.on("end", function() {
resolve(code);
});
process.stdin.on("error", reject);
});
}
process.stdin.on("end", function() {
util.transform(
commander.filename,
code,
defaults(
{
sourceFileName: "stdin",
},
opts,
),
function(err, res) {
if (err) throw err;
results.push(res);
output();
async function stdin() {
const code = await readStdin();
const res = await util.transform(
cliOptions.filename,
code,
defaults(
{
sourceFileName: "stdin",
},
);
});
};
babelOptions,
),
);
const walk = function() {
output([res]);
}
async function walk(filenames) {
const _filenames = [];
results = [];
filenames.forEach(function(filename) {
if (!fs.existsSync(filename)) return;
@@ -136,7 +137,7 @@ export default function(commander, filenames, opts) {
const dirname = filename;
util
.readdirForCompilable(filename, commander.includeDotfiles)
.readdirForCompilable(filename, cliOptions.includeDotfiles)
.forEach(function(filename) {
_filenames.push(path.join(dirname, filename));
});
@@ -145,46 +146,54 @@ export default function(commander, filenames, opts) {
}
});
let filesProcessed = 0;
const results = await Promise.all(
_filenames.map(async function(filename) {
let sourceFilename = filename;
if (cliOptions.outFile) {
sourceFilename = path.relative(
path.dirname(cliOptions.outFile),
sourceFilename,
);
}
sourceFilename = slash(sourceFilename);
_filenames.forEach(function(filename, index) {
let sourceFilename = filename;
if (commander.outFile) {
sourceFilename = path.relative(
path.dirname(commander.outFile),
sourceFilename,
);
}
sourceFilename = slash(sourceFilename);
util.compile(
filename,
defaults(
{
sourceFileName: sourceFilename,
},
opts,
),
function(err, res) {
if (err) throw err;
filesProcessed++;
if (res) results[index] = res;
if (filesProcessed === _filenames.length) {
output();
try {
return await util.compile(
filename,
defaults(
{
sourceFileName: sourceFilename,
// Since we're compiling everything to be merged together,
// "inline" applies to the final output file, but to the individual
// files being concatenated.
sourceMaps:
babelOptions.sourceMaps === "inline"
? true
: babelOptions.sourceMaps,
},
babelOptions,
),
);
} catch (err) {
if (!cliOptions.watch) {
throw err;
}
},
);
});
};
const files = function() {
if (!commander.skipInitialBuild) {
walk();
console.error(err);
return null;
}
}),
);
output(results);
}
async function files(filenames) {
if (!cliOptions.skipInitialBuild) {
await walk(filenames);
}
if (commander.watch) {
if (cliOptions.watch) {
const chokidar = util.requireChokidar();
chokidar
.watch(filenames, {
@@ -196,25 +205,26 @@ export default function(commander, filenames, opts) {
},
})
.on("all", function(type, filename) {
if (!util.isCompilableExtension(filename, commander.extensions)) {
if (!util.isCompilableExtension(filename, cliOptions.extensions)) {
return;
}
if (type === "add" || type === "change") {
util.log(type + " " + filename);
try {
walk();
} catch (err) {
console.error(err.stack);
if (cliOptions.verbose) {
console.log(type + " " + filename);
}
walk(filenames).catch(err => {
console.error(err);
});
}
});
}
};
}
if (filenames.length) {
files();
if (cliOptions.filenames.length) {
await files(cliOptions.filenames);
} else {
stdin();
await stdin();
}
}

View File

@@ -1,264 +1,13 @@
#!/usr/bin/env node
import fs from "fs";
import commander from "commander";
import { version } from "@babel/core";
import uniq from "lodash/uniq";
import glob from "glob";
import parseArgv from "./options";
import dirCommand from "./dir";
import fileCommand from "./file";
import pkg from "../../package.json";
const opts = parseArgv(process.argv);
function booleanify(val: any): boolean | any {
if (val === "true" || val == 1) {
return true;
}
if (val === "false" || val == 0 || !val) {
return false;
}
return val;
}
function collect(value, previousValue): Array<string> {
// If the user passed the option with no value, like "babel file.js --presets", do nothing.
if (typeof value !== "string") return previousValue;
const values = value.split(",");
return previousValue ? previousValue.concat(values) : values;
}
// Standard Babel input configs.
commander.option(
"-f, --filename [filename]",
"filename to use when reading from stdin - this will be used in source-maps, errors etc",
);
commander.option(
"--presets [list]",
"comma-separated list of preset names",
collect,
);
commander.option(
"--plugins [list]",
"comma-separated list of plugin names",
collect,
);
commander.option("--config-file [path]", "Path a to .babelrc file to use");
commander.option(
"--env-name [name]",
"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'.",
);
// Basic file input configuration.
commander.option("--source-type [script|module]", "");
commander.option(
"--no-babelrc",
"Whether or not to look up .babelrc and .babelignore files",
);
commander.option(
"--ignore [list]",
"list of glob paths to **not** compile",
collect,
);
commander.option(
"--only [list]",
"list of glob paths to **only** compile",
collect,
);
// Misc babel config.
commander.option(
"--no-highlight-code",
"enable/disable ANSI syntax highlighting of code frames (on by default)",
);
// General output formatting.
commander.option(
"--no-comments",
"write comments to generated output (true by default)",
);
commander.option(
"--retain-lines",
"retain line numbers - will result in really ugly code",
);
commander.option(
"--compact [true|false|auto]",
"do not include superfluous whitespace characters and line terminators",
booleanify,
);
commander.option("--minified", "save as much bytes when printing [true|false]");
commander.option(
"--auxiliary-comment-before [string]",
"print a comment before any injected non-user code",
);
commander.option(
"--auxiliary-comment-after [string]",
"print a comment after any injected non-user code",
);
// General soucemap formatting.
commander.option("-s, --source-maps [true|false|inline|both]", "", booleanify);
commander.option(
"--source-map-target [string]",
"set `file` on returned source map",
);
commander.option(
"--source-file-name [string]",
"set `sources[0]` on returned source map",
);
commander.option(
"--source-root [filename]",
"the root from which all sources are relative",
);
// Config params for certain module output formats.
commander.option(
"--module-root [filename]",
"optional prefix for the AMD module formatter that will be prepend to the filename on module definitions",
);
commander.option("-M, --module-ids", "insert an explicit id for modules");
commander.option(
"--module-id [string]",
"specify a custom name for module ids",
);
// "babel" command specific arguments that are not passed to @babel/core.
commander.option(
"-x, --extensions [extensions]",
"List of extensions to compile when a directory has been input [.es6,.js,.es,.jsx,.mjs]",
collect,
);
commander.option(
"--keep-file-extension",
"Preserve the file extensions of the input files",
);
commander.option("-w, --watch", "Recompile files on changes");
commander.option(
"--skip-initial-build",
"Do not compile files before watching",
);
commander.option(
"-o, --out-file [out]",
"Compile all input files into a single file",
);
commander.option(
"-d, --out-dir [out]",
"Compile an input directory of modules into an output directory",
);
commander.option(
"--relative",
"Compile into an output directory relative to input directory or file. Requires --out-dir [out]",
);
commander.option(
"-D, --copy-files",
"When compiling a directory copy over non-compilable files",
);
commander.option(
"--include-dotfiles",
"Include dotfiles when compiling and copying non-compilable files",
);
commander.option("--verbose", "Log everything");
commander.option(
"--delete-dir-on-start",
"Delete the out directory before compilation",
);
commander.version(pkg.version + " (@babel/core " + version + ")");
commander.usage("[options] <files ...>");
commander.parse(process.argv);
//
const errors = [];
let filenames = commander.args.reduce(function(globbed, input) {
let files = glob.sync(input);
if (!files.length) files = [input];
return globbed.concat(files);
}, []);
filenames = uniq(filenames);
filenames.forEach(function(filename) {
if (!fs.existsSync(filename)) {
errors.push(filename + " doesn't exist");
}
const fn = opts.cliOptions.outDir ? dirCommand : fileCommand;
fn(opts).catch(err => {
console.error(err);
process.exit(1);
});
if (commander.outDir && !filenames.length) {
errors.push("filenames required for --out-dir");
}
if (commander.outFile && commander.outDir) {
errors.push("cannot have --out-file and --out-dir");
}
if (commander.relative && !commander.outDir) {
errors.push("output directory required for --relative");
}
if (commander.watch) {
if (!commander.outFile && !commander.outDir) {
errors.push("--watch requires --out-file or --out-dir");
}
if (!filenames.length) {
errors.push("--watch requires filenames");
}
}
if (commander.skipInitialBuild && !commander.watch) {
errors.push("--skip-initial-build requires --watch");
}
if (commander.deleteDirOnStart && !commander.outDir) {
errors.push("--delete-dir-on-start requires --out-dir");
}
if (
!commander.outDir &&
filenames.length === 0 &&
typeof commander.filename !== "string" &&
commander.babelrc !== false
) {
errors.push(
"stdin compilation requires either -f/--filename [filename] or --no-babelrc",
);
}
if (errors.length) {
console.error(errors.join(". "));
process.exit(2);
}
//
const opts = commander.opts();
// Delete options that are specific to @babel/cli and shouldn't be passed to @babel/core.
delete opts.version;
delete opts.extensions;
delete opts.watch;
delete opts.skipInitialBuild;
delete opts.outFile;
delete opts.outDir;
delete opts.copyFiles;
delete opts.includeDotfiles;
delete opts.verbose;
delete opts.deleteDirOnStart;
delete opts.keepFileExtension;
delete opts.relative;
delete opts.sourceMapTarget;
// 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.
if (opts.babelrc === true) opts.babelrc = undefined;
if (opts.comments === true) opts.comments = undefined;
if (opts.highlightCode === true) opts.highlightCode = undefined;
const fn = commander.outDir ? dirCommand : fileCommand;
fn(commander, filenames, opts);

View File

@@ -0,0 +1,283 @@
import fs from "fs";
import commander from "commander";
import { version } from "@babel/core";
import uniq from "lodash/uniq";
import glob from "glob";
import pkg from "../../package.json";
// Standard Babel input configs.
commander.option(
"-f, --filename [filename]",
"filename to use when reading from stdin - this will be used in source-maps, errors etc",
);
commander.option(
"--presets [list]",
"comma-separated list of preset names",
collect,
);
commander.option(
"--plugins [list]",
"comma-separated list of plugin names",
collect,
);
commander.option("--config-file [path]", "Path a to .babelrc file to use");
commander.option(
"--env-name [name]",
"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'.",
);
// Basic file input configuration.
commander.option("--source-type [script|module]", "");
commander.option(
"--no-babelrc",
"Whether or not to look up .babelrc and .babelignore files",
);
commander.option(
"--ignore [list]",
"list of glob paths to **not** compile",
collect,
);
commander.option(
"--only [list]",
"list of glob paths to **only** compile",
collect,
);
// Misc babel config.
commander.option(
"--no-highlight-code",
"enable/disable ANSI syntax highlighting of code frames (on by default)",
);
// General output formatting.
commander.option(
"--no-comments",
"write comments to generated output (true by default)",
);
commander.option(
"--retain-lines",
"retain line numbers - will result in really ugly code",
);
commander.option(
"--compact [true|false|auto]",
"do not include superfluous whitespace characters and line terminators",
booleanify,
);
commander.option("--minified", "save as much bytes when printing [true|false]");
commander.option(
"--auxiliary-comment-before [string]",
"print a comment before any injected non-user code",
);
commander.option(
"--auxiliary-comment-after [string]",
"print a comment after any injected non-user code",
);
// General soucemap formatting.
commander.option("-s, --source-maps [true|false|inline|both]", "", booleanify);
commander.option(
"--source-map-target [string]",
"set `file` on returned source map",
);
commander.option(
"--source-file-name [string]",
"set `sources[0]` on returned source map",
);
commander.option(
"--source-root [filename]",
"the root from which all sources are relative",
);
// Config params for certain module output formats.
commander.option(
"--module-root [filename]",
"optional prefix for the AMD module formatter that will be prepend to the filename on module definitions",
);
commander.option("-M, --module-ids", "insert an explicit id for modules");
commander.option(
"--module-id [string]",
"specify a custom name for module ids",
);
// "babel" command specific arguments that are not passed to @babel/core.
commander.option(
"-x, --extensions [extensions]",
"List of extensions to compile when a directory has been input [.es6,.js,.es,.jsx,.mjs]",
collect,
);
commander.option(
"--keep-file-extension",
"Preserve the file extensions of the input files",
);
commander.option("-w, --watch", "Recompile files on changes");
commander.option(
"--skip-initial-build",
"Do not compile files before watching",
);
commander.option(
"-o, --out-file [out]",
"Compile all input files into a single file",
);
commander.option(
"-d, --out-dir [out]",
"Compile an input directory of modules into an output directory",
);
commander.option(
"--relative",
"Compile into an output directory relative to input directory or file. Requires --out-dir [out]",
);
commander.option(
"-D, --copy-files",
"When compiling a directory copy over non-compilable files",
);
commander.option(
"--include-dotfiles",
"Include dotfiles when compiling and copying non-compilable files",
);
commander.option("--verbose", "Log everything");
commander.option(
"--delete-dir-on-start",
"Delete the out directory before compilation",
);
commander.version(pkg.version + " (@babel/core " + version + ")");
commander.usage("[options] <files ...>");
export default function parseArgv(args: Array<string>) {
//
commander.parse(args);
const errors = [];
let filenames = commander.args.reduce(function(globbed, input) {
let files = glob.sync(input);
if (!files.length) files = [input];
return globbed.concat(files);
}, []);
filenames = uniq(filenames);
filenames.forEach(function(filename) {
if (!fs.existsSync(filename)) {
errors.push(filename + " doesn't exist");
}
});
if (commander.outDir && !filenames.length) {
errors.push("filenames required for --out-dir");
}
if (commander.outFile && commander.outDir) {
errors.push("cannot have --out-file and --out-dir");
}
if (commander.relative && !commander.outDir) {
errors.push("output directory required for --relative");
}
if (commander.watch) {
if (!commander.outFile && !commander.outDir) {
errors.push("--watch requires --out-file or --out-dir");
}
if (!filenames.length) {
errors.push("--watch requires filenames");
}
}
if (commander.skipInitialBuild && !commander.watch) {
errors.push("--skip-initial-build requires --watch");
}
if (commander.deleteDirOnStart && !commander.outDir) {
errors.push("--delete-dir-on-start requires --out-dir");
}
if (
!commander.outDir &&
filenames.length === 0 &&
typeof commander.filename !== "string" &&
commander.babelrc !== false
) {
errors.push(
"stdin compilation requires either -f/--filename [filename] or --no-babelrc",
);
}
if (errors.length) {
console.error(errors.join(". "));
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,
// 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,
},
cliOptions: {
filename: opts.filename,
filenames,
extensions: opts.extensions,
keepFileExtension: opts.keepFileExtension,
watch: opts.watch,
skipInitialBuild: opts.skipInitialBuild,
outFile: opts.outFile,
outDir: opts.outDir,
relative: opts.relative,
copyFiles: opts.copyFiles,
includeDotfiles: opts.includeDotfiles,
verbose: opts.verbose,
deleteDirOnStart: opts.deleteDirOnStart,
sourceMapTarget: opts.sourceMapTarget,
},
};
}
function booleanify(val: any): boolean | any {
if (val === "true" || val == 1) {
return true;
}
if (val === "false" || val == 0 || !val) {
return false;
}
return val;
}
function collect(value, previousValue): Array<string> {
// If the user passed the option with no value, like "babel file.js --presets", do nothing.
if (typeof value !== "string") return previousValue;
const values = value.split(",");
return previousValue ? previousValue.concat(values) : values;
}

View File

@@ -1,4 +1,3 @@
import commander from "commander";
import readdirRecursive from "fs-readdir-recursive";
import * as babel from "@babel/core";
import includes from "lodash/includes";
@@ -46,30 +45,26 @@ export function addSourceMappingUrl(code, loc) {
return code + "\n//# sourceMappingURL=" + path.basename(loc);
}
export function log(msg, force) {
if (force === true || commander.verbose) console.log(msg);
}
export function transform(filename, code, opts, callback) {
export function transform(filename, code, opts) {
opts = {
...opts,
filename,
};
babel.transform(code, opts, callback);
return new Promise((resolve, reject) => {
babel.transform(code, opts, (err, result) => {
if (err) reject(err);
else resolve(result);
});
});
}
export function compile(filename, opts, callback) {
babel.transformFile(filename, opts, function(err, res) {
if (err) {
if (commander.watch) {
console.error(err);
return callback(null, null);
} else {
return callback(err);
}
}
return callback(null, res);
export function compile(filename, opts) {
return new Promise((resolve, reject) => {
babel.transformFile(filename, opts, (err, result) => {
if (err) reject(err);
else resolve(result);
});
});
}

View File

@@ -0,0 +1 @@
🎉 Successfully compiled 0 files with Babel.

View File

@@ -1,4 +1,3 @@
const includes = require("lodash/includes");
const readdir = require("fs-readdir-recursive");
const helper = require("@babel/helper-fixtures");
const rimraf = require("rimraf");
@@ -37,7 +36,9 @@ const readDir = function(loc, filter) {
const saveInFiles = function(files) {
// Place an empty .babelrc in each test so tests won't unexpectedly get to repo-level config.
outputFileSync(".babelrc", "{}");
if (!fs.existsSync(".babelrc")) {
outputFileSync(".babelrc", "{}");
}
Object.keys(files).forEach(function(filename) {
const content = files[filename];
@@ -51,7 +52,7 @@ const assertTest = function(stdout, stderr, opts) {
if (opts.stderr) {
if (opts.stderrContains) {
expect(includes(stderr, expectStderr)).toBe(true);
expect(stderr).toContain(expectStderr);
} else {
expect(stderr).toBe(expectStderr);
}
@@ -65,7 +66,7 @@ const assertTest = function(stdout, stderr, opts) {
if (opts.stdout) {
if (opts.stdoutContains) {
expect(includes(stdout, expectStdout)).toBe(true);
expect(stdout).toContain(expectStdout);
} else {
expect(stdout).toBe(expectStdout);
}

View File

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

View File

@@ -99,7 +99,7 @@ Given an [AST](https://astexplorer.net/), transform it.
```js
const sourceCode = "if (true) return;";
const parsedAst = babylon.parse(sourceCode, { allowReturnOutsideFunction: true });
const parsedAst = babel.parse(sourceCode, { allowReturnOutsideFunction: true });
babel.transformFromAst(parsedAst, sourceCode, options, function(err, result) {
const { code, map, ast } = result;
});
@@ -119,7 +119,7 @@ Given an [AST](https://astexplorer.net/), transform it.
```js
const sourceCode = "if (true) return;";
const parsedAst = babylon.parse(sourceCode, { allowReturnOutsideFunction: true });
const parsedAst = babel.parse(sourceCode, { allowReturnOutsideFunction: true });
const { code, map, ast } = babel.transformFromAstSync(parsedAst, sourceCode, options);
```
@@ -238,7 +238,7 @@ Following is a table of the options you can use:
| `moduleIds` | `false` | If truthy, insert an explicit id for modules. By default, all modules are anonymous. (Not available for `common` modules) |
| `moduleRoot` | `(sourceRoot)` | Optional prefix for the AMD module formatter that will be prepend to the filename on module definitions |
| `only` | `null` | A [glob](https://github.com/isaacs/minimatch), regex, or mixed array of both, matching paths to **only** compile. Can also be an array of arrays containing paths to explicitly match. When attempting to compile a non-matching file it's returned verbatim |
| `parserOpts` | `{}` | An object containing the options to be passed down to the babel parser, babylon |
| `parserOpts` | `{}` | An object containing the options to be passed down to the babel parser, @babel/parser |
| `plugins` | `[]` | List of [plugins](https://babeljs.io/docs/plugins/) to load and use |
| `presets` | `[]` | List of [presets](https://babeljs.io/docs/plugins/#presets) (a set of plugins) to load and use |
| `retainLines` | `false` | Retain line numbers. This will lead to wacky code but is handy for scenarios where you can't use source maps. (**NOTE:** This will not retain the columns) |

View File

@@ -1,6 +1,6 @@
{
"name": "@babel/core",
"version": "7.0.0-beta.47",
"version": "7.0.0-beta.48",
"description": "Babel compiler core.",
"main": "lib/index.js",
"author": "Sebastian McKenzie <sebmck@gmail.com>",
@@ -22,19 +22,22 @@
"babel-core",
"compiler"
],
"engines": {
"node": ">=6.9.0"
},
"browser": {
"./lib/config/files/index.js": "./lib/config/files/index-browser.js",
"./lib/transform-file.js": "./lib/transform-file-browser.js",
"./lib/transform-file-sync.js": "./lib/transform-file-sync-browser.js"
},
"dependencies": {
"@babel/code-frame": "7.0.0-beta.47",
"@babel/generator": "7.0.0-beta.47",
"@babel/helpers": "7.0.0-beta.47",
"@babel/template": "7.0.0-beta.47",
"@babel/traverse": "7.0.0-beta.47",
"@babel/types": "7.0.0-beta.47",
"babylon": "7.0.0-beta.47",
"@babel/code-frame": "7.0.0-beta.48",
"@babel/generator": "7.0.0-beta.48",
"@babel/helpers": "7.0.0-beta.48",
"@babel/parser": "7.0.0-beta.48",
"@babel/template": "7.0.0-beta.48",
"@babel/traverse": "7.0.0-beta.48",
"@babel/types": "7.0.0-beta.48",
"convert-source-map": "^1.1.0",
"debug": "^3.1.0",
"json5": "^0.5.0",
@@ -45,7 +48,7 @@
"source-map": "^0.5.0"
},
"devDependencies": {
"@babel/helper-transform-fixture-test-runner": "7.0.0-beta.47",
"@babel/register": "7.0.0-beta.47"
"@babel/helper-transform-fixture-test-runner": "7.0.0-beta.48",
"@babel/register": "7.0.0-beta.48"
}
}

View File

@@ -46,8 +46,9 @@ export type PresetInstance = {
};
export type ConfigContext = {
filename: string | null,
filename: string | void,
cwd: string,
root: string,
envName: string,
};
@@ -130,18 +131,15 @@ export function buildRootChain(
);
if (!programmaticChain) return null;
const { root: rootDir = ".", configFile: configFileName = true } = opts;
let { babelrc, babelrcRoots } = opts;
const absoluteRoot = path.resolve(context.cwd, rootDir);
let configFile;
if (typeof configFileName === "string") {
configFile = loadConfig(configFileName, context.cwd, context.envName);
} else if (configFileName === true) {
configFile = findRootConfig(absoluteRoot, context.envName);
if (typeof opts.configFile === "string") {
configFile = loadConfig(opts.configFile, context.cwd, context.envName);
} else if (opts.configFile !== false) {
configFile = findRootConfig(context.root, context.envName);
}
let { babelrc, babelrcRoots } = opts;
const configFileChain = emptyChain();
if (configFile) {
const validatedFile = validateConfigFile(configFile);
@@ -171,7 +169,7 @@ export function buildRootChain(
if (
(babelrc === true || babelrc === undefined) &&
pkgData &&
babelrcLoadEnabled(context, pkgData, babelrcRoots, absoluteRoot)
babelrcLoadEnabled(context, pkgData, babelrcRoots)
) {
({ ignore: ignoreFile, config: babelrcFile } = findRelativeConfig(
pkgData,
@@ -214,10 +212,11 @@ function babelrcLoadEnabled(
context: ConfigContext,
pkgData: FilePackageData,
babelrcRoots: BabelrcSearch | void,
absoluteRoot: string,
): boolean {
if (typeof babelrcRoots === "boolean") return babelrcRoots;
const absoluteRoot = context.root;
// Fast path to avoid having to load micromatch if the babelrc is just
// loading in the standard root directory.
if (babelrcRoots === undefined) {
@@ -576,7 +575,7 @@ function configFieldIsApplicable(
test: ConfigApplicableTest,
dirname: string,
): boolean {
if (context.filename === null) {
if (typeof context.filename !== "string") {
throw new Error(
`Configuration contains explicit test/include/exclude checks, but no filename was passed to Babel`,
);
@@ -602,7 +601,7 @@ function shouldIgnore(
dirname: string,
): boolean {
if (ignore) {
if (context.filename === null) {
if (typeof context.filename !== "string") {
throw new Error(
`Configuration contains ignore checks, but no filename was passed to Babel`,
);
@@ -621,7 +620,7 @@ function shouldIgnore(
}
if (only) {
if (context.filename === null) {
if (typeof context.filename !== "string") {
throw new Error(
`Configuration contains ignore checks, but no filename was passed to Babel`,
);
@@ -696,7 +695,7 @@ function matchesPatterns(
const getPossibleDirs = makeWeakCache((context: ConfigContextNamed) => {
let current = context.filename;
if (current === null) return [];
if (typeof current !== "string") return [];
const possibleDirs = [current];
while (true) {

View File

@@ -277,7 +277,7 @@ function assertNoDuplicates(items: Array<UnloadedDescriptor>): void {
[
`Duplicate plugin/preset detected.`,
`If you'd like to use two separate instances of a plugin,`,
`they neen separate names, e.g.`,
`they need separate names, e.g.`,
``,
` plugins: [`,
` ['some-plugin', {}],`,

View File

@@ -28,12 +28,17 @@ export default function loadPrivatePartialConfig(
const args = inputOpts ? validate("arguments", inputOpts) : {};
const { envName = getEnv(), cwd = "." } = args;
const { envName = getEnv(), cwd = ".", root: rootDir = "." } = args;
const absoluteCwd = path.resolve(cwd);
const absoluteRootDir = path.resolve(absoluteCwd, rootDir);
const context: ConfigContext = {
filename: args.filename ? path.resolve(cwd, args.filename) : null,
filename:
typeof args.filename === "string"
? path.resolve(cwd, args.filename)
: undefined,
cwd: absoluteCwd,
root: absoluteRootDir,
envName,
};
@@ -50,9 +55,14 @@ export default function loadPrivatePartialConfig(
// to not change behavior.
options.babelrc = false;
options.configFile = false;
options.envName = envName;
options.cwd = absoluteCwd;
options.passPerPreset = false;
options.envName = context.envName;
options.cwd = context.cwd;
options.root = context.root;
options.filename =
typeof context.filename === "string"
? path.relative(context.cwd, context.filename)
: undefined;
options.plugins = configChain.plugins.map(descriptor =>
createItemFromDescriptor(descriptor),

View File

@@ -57,27 +57,10 @@ const NONPRESET_VALIDATORS: ValidatorSet = {
extends: (assertString: Validator<
$PropertyType<ValidatedOptions, "extends">,
>),
env: (assertEnvSet: Validator<$PropertyType<ValidatedOptions, "env">>),
ignore: (assertIgnoreList: Validator<
$PropertyType<ValidatedOptions, "ignore">,
>),
only: (assertIgnoreList: Validator<$PropertyType<ValidatedOptions, "only">>),
overrides: (assertOverridesList: Validator<
$PropertyType<ValidatedOptions, "overrides">,
>),
// We could limit these to 'overrides' blocks, but it's not clear why we'd
// bother, when the ability to limit a config to a specific set of files
// is a fairly general useful feature.
test: (assertConfigApplicableTest: Validator<
$PropertyType<ValidatedOptions, "test">,
>),
include: (assertConfigApplicableTest: Validator<
$PropertyType<ValidatedOptions, "include">,
>),
exclude: (assertConfigApplicableTest: Validator<
$PropertyType<ValidatedOptions, "exclude">,
>),
};
const COMMON_VALIDATORS: ValidatorSet = {
@@ -96,6 +79,25 @@ const COMMON_VALIDATORS: ValidatorSet = {
passPerPreset: (assertBoolean: Validator<
$PropertyType<ValidatedOptions, "passPerPreset">,
>),
env: (assertEnvSet: Validator<$PropertyType<ValidatedOptions, "env">>),
overrides: (assertOverridesList: Validator<
$PropertyType<ValidatedOptions, "overrides">,
>),
// We could limit these to 'overrides' blocks, but it's not clear why we'd
// bother, when the ability to limit a config to a specific set of files
// is a fairly general useful feature.
test: (assertConfigApplicableTest: Validator<
$PropertyType<ValidatedOptions, "test">,
>),
include: (assertConfigApplicableTest: Validator<
$PropertyType<ValidatedOptions, "include">,
>),
exclude: (assertConfigApplicableTest: Validator<
$PropertyType<ValidatedOptions, "exclude">,
>),
retainLines: (assertBoolean: Validator<
$PropertyType<ValidatedOptions, "retainLines">,
>),

View File

@@ -28,14 +28,12 @@ export default class File {
metadata: {} = {};
hub: Hub = new Hub(this);
code: string = "";
shebang: string | null = "";
inputMap: Object | null = null;
constructor(options: {}, { code, ast, shebang, inputMap }: NormalizedFile) {
constructor(options: {}, { code, ast, inputMap }: NormalizedFile) {
this.opts = options;
this.code = code;
this.ast = ast;
this.shebang = shebang;
this.inputMap = inputMap;
this.path = NodePath.get({
@@ -48,6 +46,23 @@ export default class File {
this.scope = this.path.scope;
}
/**
* Provide backward-compatible access to the interpreter directive handling
* in Babel 6.x. If you are writing a plugin for Babel 7.x, it would be
* best to use 'program.interpreter' directly.
*/
get shebang(): string {
const { interpreter } = this.path.node;
return interpreter ? interpreter.value : "";
}
set shebang(value: string): void {
if (value) {
this.path.get("interpreter").replaceWith(t.interpreterDirective(value));
} else {
this.path.get("interpreter").remove();
}
}
set(key: mixed, val: mixed) {
this._map.set(key, val);
}

View File

@@ -14,7 +14,7 @@ export default function generateCode(
outputCode: string,
outputMap: SourceMap | null,
} {
const { opts, ast, shebang, code, inputMap } = file;
const { opts, ast, code, inputMap } = file;
const results = [];
for (const plugins of pluginPasses) {
@@ -53,11 +53,6 @@ export default function generateCode(
let { code: outputCode, map: outputMap } = result;
if (shebang) {
// add back shebang
outputCode = `${shebang}\n${outputCode}`;
}
if (outputMap && inputMap) {
outputMap = mergeSourceMap(inputMap.toObject(), outputMap);
}

View File

@@ -1,19 +1,19 @@
// @flow
import buildDebug from "debug";
import * as t from "@babel/types";
import type { PluginPasses } from "../config";
import convertSourceMap, { typeof Converter } from "convert-source-map";
import { parse } from "babylon";
import { parse } from "@babel/parser";
import { codeFrameColumns } from "@babel/code-frame";
import File from "./file/file";
import generateMissingPluginMessage from "./util/missing-plugin-helper";
const shebangRegex = /^#!.*/;
const debug = buildDebug("babel:transform:file");
export type NormalizedFile = {
code: string,
ast: {},
shebang: string | null,
inputMap: Converter | null,
};
@@ -25,23 +25,37 @@ export default function normalizeFile(
): File {
code = `${code || ""}`;
let shebang = null;
let inputMap = null;
if (options.inputSourceMap !== false) {
inputMap = convertSourceMap.fromSource(code);
if (inputMap) {
try {
inputMap = convertSourceMap.fromSource(code);
if (inputMap) {
code = convertSourceMap.removeComments(code);
}
} catch (err) {
debug("discarding unknown inline input sourcemap", err);
code = convertSourceMap.removeComments(code);
} else if (typeof options.inputSourceMap === "object") {
}
if (!inputMap) {
try {
inputMap = convertSourceMap.fromMapFileSource(code);
if (inputMap) {
code = convertSourceMap.removeMapFileComments(code);
}
} catch (err) {
debug("discarding unknown file input sourcemap", err);
code = convertSourceMap.removeMapFileComments(code);
}
}
if (!inputMap && typeof options.inputSourceMap === "object") {
inputMap = convertSourceMap.fromObject(options.inputSourceMap);
}
}
const shebangMatch = shebangRegex.exec(code);
if (shebangMatch) {
shebang = shebangMatch[0];
code = code.replace(shebangRegex, "");
}
if (ast) {
if (ast.type === "Program") {
ast = t.file(ast, [], []);
@@ -49,13 +63,15 @@ export default function normalizeFile(
throw new Error("AST root must be a Program or File node");
}
} else {
// The parser's AST types aren't fully compatible with the types generated
// by the logic in babel-types.
// $FlowFixMe
ast = parser(pluginPasses, options, code);
}
return new File(options, {
code,
ast,
shebang,
inputMap,
});
}

View File

@@ -7,14 +7,19 @@ export default class PluginPass {
key: ?string;
file: File;
opts: Object;
// The working directory that Babel's options are loaded relative to.
cwd: string;
// The path of the file being compiled, relative to the working directory.
filename: string | void;
constructor(file: File, key: ?string, options: ?Object) {
this.key = key;
this.file = file;
this.opts = options || {};
this.filename =
typeof file.opts.filename === "string" ? file.opts.filename : undefined;
this.cwd = file.opts.cwd;
this.filename = file.opts.filename;
}
set(key: mixed, val: mixed) {

View File

@@ -209,7 +209,7 @@ const getNameURLCombination = ({ name, url }) => `${name} (${url})`;
/*
Returns a string of the format:
Support for the experimental syntax [babylon plugin name] isn't currently enabled ([loc]):
Support for the experimental syntax [@babel/parser plugin name] isn't currently enabled ([loc]):
[code frame]

View File

@@ -370,6 +370,60 @@ describe("api", function() {
);
});
it("interpreter directive backward-compat", function() {
function doTransform(code, preHandler) {
return transform(code, {
plugins: [
{
pre: preHandler,
},
],
}).code;
}
// Writes value properly.
expect(
doTransform("", file => {
file.shebang = "env node";
}),
).toBe(`#!env node`);
expect(
doTransform("#!env node", file => {
file.shebang = "env node2";
}),
).toBe(`#!env node2`);
expect(
doTransform("", file => {
file.shebang = "";
}),
).toBe(``);
expect(
doTransform("#!env node", file => {
file.shebang = "";
}),
).toBe(``);
// Reads value properly.
doTransform("", file => {
expect(file.shebang).toBe("");
});
doTransform("#!env node", file => {
expect(file.shebang).toBe("env node");
});
// Reads and writes properly.
expect(
doTransform("#!env node", file => {
expect(file.shebang).toBe("env node");
file.shebang = "env node2";
expect(file.shebang).toBe("env node2");
file.shebang = "env node3";
}),
).toBe(`#!env node3`);
});
it("source map merging", function() {
const result = transform(
[

View File

@@ -906,6 +906,7 @@ describe("buildConfigChain", function() {
babelrc: false,
configFile: false,
cwd: process.cwd(),
root: process.cwd(),
envName: "development",
passPerPreset: false,
plugins: [],
@@ -935,8 +936,9 @@ describe("buildConfigChain", function() {
}),
).toEqual({
...getDefaults(),
filename,
filename: path.basename(filename),
cwd: path.dirname(filename),
root: path.dirname(filename),
comments: true,
});
});
@@ -946,8 +948,9 @@ describe("buildConfigChain", function() {
expect(loadOptions({ filename, cwd: path.dirname(filename) })).toEqual({
...getDefaults(),
filename,
filename: path.basename(filename),
cwd: path.dirname(filename),
root: path.dirname(filename),
comments: true,
});
});
@@ -957,8 +960,9 @@ describe("buildConfigChain", function() {
expect(loadOptions({ filename, cwd: path.dirname(filename) })).toEqual({
...getDefaults(),
filename,
filename: path.basename(filename),
cwd: path.dirname(filename),
root: path.dirname(filename),
comments: true,
});
});
@@ -998,8 +1002,9 @@ describe("buildConfigChain", function() {
expect(loadOptions({ filename, cwd: path.dirname(filename) })).toEqual({
...getDefaults(),
filename,
filename: path.basename(filename),
cwd: path.dirname(filename),
root: path.dirname(filename),
comments: true,
});
});

View File

@@ -1,5 +1,5 @@
import traverse from "@babel/traverse";
import { parse } from "babylon";
import { parse } from "@babel/parser";
describe("evaluation", function() {
function addTest(code, type, value, notConfident) {

View File

@@ -26,6 +26,7 @@
"column": 0
}
},
"interpreter": null,
"sourceType": "module",
"body": [
{

View File

@@ -3,6 +3,8 @@ var Foo =
function (_Bar) {
"use strict";
babelHelpers.inherits(Foo, _Bar);
function Foo(options) {
babelHelpers.classCallCheck(this, Foo);
var parentOptions = {};
@@ -14,6 +16,5 @@ function (_Bar) {
return babelHelpers.possibleConstructorReturn(this, babelHelpers.getPrototypeOf(Foo).call(this, parentOptions));
}
babelHelpers.inherits(Foo, _Bar);
return Foo;
}(Bar);

View File

@@ -0,0 +1,2 @@
#!env node
var someFirstLine;

View File

@@ -0,0 +1,4 @@
{
"plugins": ["transform-strict-mode"],
"retainLines": true
}

View File

@@ -0,0 +1,2 @@
#!env node
"use strict";var someFirstLine;

View File

@@ -0,0 +1,3 @@
#!env node
console.log("Hello, world!");

View File

@@ -0,0 +1,3 @@
{
"sourceMap": true
}

View File

@@ -0,0 +1,2 @@
#!env node
console.log("Hello, world!");

View File

@@ -0,0 +1,14 @@
{
"mappings": "AAAA;AAEAA,QAAQC,GAAR,CAAY,eAAZ",
"names": [
"console",
"log"
],
"sources": [
"source-maps/interpreter-directive-prefix/input.js"
],
"sourcesContent": [
"#!env node\n\nconsole.log(\"Hello, world!\");"
],
"version": 3
}

View File

@@ -1,6 +1,6 @@
# @babel/generator
> Turns a [Babylon AST](https://github.com/babel/babel/blob/master/packages/babylon/ast/spec.md) into code.
> Turns the [babel AST](https://github.com/babel/babel/blob/master/packages/babel-parser/ast/spec.md) into code.
## Install
@@ -11,7 +11,7 @@ npm install --save-dev @babel/generator
## Usage
```js
import {parse} from 'babylon';
import {parse} from '@babel/parser';
import generate from '@babel/generator';
const code = 'class Example {}';
@@ -57,7 +57,7 @@ should be the source filenames, and values should be the source content.
Here's an example of what that might look like:
```js
import {parse} from 'babylon';
import {parse} from '@babel/parser';
import generate from '@babel/generator';
const a = 'var a = 1;';

View File

@@ -1,6 +1,6 @@
{
"name": "@babel/generator",
"version": "7.0.0-beta.47",
"version": "7.0.0-beta.48",
"description": "Turns an AST into code.",
"author": "Sebastian McKenzie <sebmck@gmail.com>",
"homepage": "https://babeljs.io/",
@@ -11,14 +11,14 @@
"lib"
],
"dependencies": {
"@babel/types": "7.0.0-beta.47",
"@babel/types": "7.0.0-beta.48",
"jsesc": "^2.5.1",
"lodash": "^4.17.5",
"source-map": "^0.5.0",
"trim-right": "^1.0.1"
},
"devDependencies": {
"@babel/helper-fixtures": "7.0.0-beta.47",
"babylon": "7.0.0-beta.47"
"@babel/helper-fixtures": "7.0.0-beta.48",
"@babel/parser": "7.0.0-beta.48"
}
}

View File

@@ -1,5 +1,5 @@
/*
Copies tests from babylon's TypeScript test suite to @babel/generator.
Copies tests from the @babel/parser's TypeScript test suite to @babel/generator.
*/
const {
copySync,
@@ -10,7 +10,10 @@ const {
} = require("fs-extra");
const { join } = require("path");
const testsFrom = join(__dirname, "../../babylon/test/fixtures/typescript");
const testsFrom = join(
__dirname,
"../../babel-parser/test/fixtures/typescript"
);
const testsTo = join(__dirname, "../test/fixtures/typescript");
emptyDirSync(testsTo);

View File

@@ -1,4 +1,10 @@
export function File(node: Object) {
if (node.program) {
// Print this here to ensure that Program node 'leadingComments' still
// get printed after the hashbang.
this.print(node.program.interpreter, node);
}
this.print(node.program, node);
}
@@ -44,4 +50,8 @@ export function Directive(node: Object) {
this.semicolon();
}
export function InterpreterDirective(node: Object) {
this.token(`#!${node.value}\n`);
}
export { StringLiteral as DirectiveLiteral } from "./types";

View File

@@ -67,6 +67,7 @@ export function NewExpression(node: Object, parent: Object) {
return;
}
this.print(node.typeArguments, node); // Flow
this.print(node.typeParameters, node); // TS
if (node.optional) {
@@ -125,6 +126,7 @@ export function OptionalMemberExpression(node: Object) {
export function OptionalCallExpression(node: Object) {
this.print(node.callee, node);
this.print(node.typeArguments, node); // Flow
this.print(node.typeParameters, node); // TS
if (node.optional) {
@@ -138,6 +140,7 @@ export function OptionalCallExpression(node: Object) {
export function CallExpression(node: Object) {
this.print(node.callee, node);
this.print(node.typeArguments, node); // Flow
this.print(node.typeParameters, node); // TS
this.token("(");
this.printList(node.arguments, node);

View File

@@ -262,6 +262,18 @@ function andSeparator() {
this.space();
}
export function InterfaceTypeAnnotation(node: Object) {
this.word("interface");
if (node.extends && node.extends.length) {
this.space();
this.word("extends");
this.space();
this.printList(node.extends, node);
}
this.space();
this.print(node.body, node);
}
export function IntersectionTypeAnnotation(node: Object) {
this.printJoin(node.types, node, { separator: andSeparator });
}
@@ -384,6 +396,7 @@ export function ObjectTypeAnnotation(node: Object) {
const props = node.properties.concat(
node.callProperties || [],
node.indexers || [],
node.internalSlots || [],
);
if (props.length) {
@@ -413,6 +426,24 @@ export function ObjectTypeAnnotation(node: Object) {
}
}
export function ObjectTypeInternalSlot(node: Object) {
if (node.static) {
this.word("static");
this.space();
}
this.token("[");
this.token("[");
this.print(node.id, node);
this.token("]");
this.token("]");
if (node.optional) this.token("?");
if (!node.method) {
this.token(":");
this.space();
}
this.print(node.value, node);
}
export function ObjectTypeCallProperty(node: Object) {
if (node.static) {
this.word("static");

View File

@@ -143,3 +143,12 @@ export function StringLiteral(node: Object) {
return this.token(val);
}
export function BigIntLiteral(node: Object) {
const raw = this.getPossibleRaw(node);
if (!this.format.minified && raw != null) {
this.token(raw);
return;
}
this.token(node.value);
}

View File

@@ -209,6 +209,22 @@ nodes.ObjectTypeIndexer = function(node: Object, parent): ?WhitespaceObject {
}
};
nodes.ObjectTypeInternalSlot = function(
node: Object,
parent,
): ?WhitespaceObject {
if (
parent.internalSlots[0] === node &&
(!parent.properties || !parent.properties.length) &&
(!parent.callProperties || !parent.callProperties.length) &&
(!parent.indexers || !parent.indexers.length)
) {
return {
before: true,
};
}
};
/**
* Returns lists from node types that need whitespace.
*/

View File

@@ -0,0 +1,3 @@
type A = interface { p: string };
type B = interface extends X { p: string };
type C = interface extends X, Y { p: string };

View File

@@ -0,0 +1,9 @@
type A = interface {
p: string
};
type B = interface extends X {
p: string
};
type C = interface extends X, Y {
p: string
};

View File

@@ -0,0 +1,7 @@
declare class C { static [[foo]]: T }
declare class C { [[foo]]: T }
interface T { [[foo]]: X }
interface T { [[foo]](): X }
type T = { [[foo]]: X }
type T = { [[foo]](): X }
type T = { [[foo]]?: X }

View File

@@ -0,0 +1,21 @@
declare class C {
static [[foo]]: T
}
declare class C {
[[foo]]: T
}
interface T {
[[foo]]: X
}
interface T {
[[foo]]() => X
}
type T = {
[[foo]]: X
};
type T = {
[[foo]]() => X
};
type T = {
[[foo]]?: X
};

View File

@@ -0,0 +1,18 @@
// @flow
f<T>();
f<T><U></U>;
new C<T>;
f<T>(e);
o[e]<T>();
f<T>(x)<U>(y);
async <T>() => {};
async <T>(): T => {}
new C<T>(e);
f<T>[e];
new C<T>();
o.m<T>();
f<T>.0;
o?.m<T>(e);
o.m?.<T>(e);
async<T>();
f?.<T>(e);

View File

@@ -0,0 +1 @@
{ "plugins": ["jsx", "optionalChaining", "flow"] }

View File

@@ -0,0 +1,21 @@
// @flow
f<T>();
f < T > <U></U>;
new C<T>();
f<T>(e);
o[e]<T>();
f<T>(x)<U>(y);
async <T>() => {};
async <T>(): T => {};
new C<T>(e);
f < T > [e];
new C<T>();
o.m<T>();
f < T > .0;
o?.m<T>(e);
o.m<T>?.(e);
async<T>();
f<T>?.(e);

View File

@@ -0,0 +1,5 @@
100n;
9223372036854775807n;
0o16432n;
0xFFF123n;
0b101011101n;

View File

@@ -0,0 +1 @@
{ "plugins": ["bigInt"] }

View File

@@ -0,0 +1,5 @@
100n;
9223372036854775807n;
0o16432n;
0xFFF123n;
0b101011101n;

View File

@@ -0,0 +1,5 @@
#!env node
"use strict";
console.log("test");

View File

@@ -0,0 +1,4 @@
#!env node
"use strict";
console.log("test");

View File

@@ -1,6 +1,6 @@
import Printer from "../lib/printer";
import generate, { CodeGenerator } from "../lib";
import { parse } from "babylon";
import { parse } from "@babel/parser";
import * as t from "@babel/types";
import fs from "fs";
import path from "path";
@@ -304,6 +304,7 @@ describe("programmatic generation", function() {
[t.objectTypeProperty(t.identifier("bar"), t.stringTypeAnnotation())],
null,
null,
null,
);
const output = generate(objectStatement).code;
@@ -317,6 +318,7 @@ describe("programmatic generation", function() {
[t.objectTypeProperty(t.identifier("bar"), t.stringTypeAnnotation())],
null,
null,
null,
true,
);
@@ -336,6 +338,7 @@ describe("programmatic generation", function() {
t.numberTypeAnnotation(),
),
],
null,
);
const output = generate(objectStatement).code;

View File

@@ -1,11 +1,11 @@
{
"name": "@babel/helper-annotate-as-pure",
"version": "7.0.0-beta.47",
"version": "7.0.0-beta.48",
"description": "Helper function to annotate paths and nodes with #__PURE__ comment",
"repository": "https://github.com/babel/babel/tree/master/packages/babel-helper-annotate-as-pure",
"license": "MIT",
"main": "lib/index.js",
"dependencies": {
"@babel/types": "7.0.0-beta.47"
"@babel/types": "7.0.0-beta.48"
}
}

View File

@@ -1,12 +1,12 @@
{
"name": "@babel/helper-bindify-decorators",
"version": "7.0.0-beta.47",
"version": "7.0.0-beta.48",
"description": "Helper function to bindify decorators",
"repository": "https://github.com/babel/babel/tree/master/packages/babel-helper-bindify-decorators",
"license": "MIT",
"main": "lib/index.js",
"dependencies": {
"@babel/traverse": "7.0.0-beta.47",
"@babel/types": "7.0.0-beta.47"
"@babel/traverse": "7.0.0-beta.48",
"@babel/types": "7.0.0-beta.48"
}
}

View File

@@ -1,12 +1,12 @@
{
"name": "@babel/helper-builder-binary-assignment-operator-visitor",
"version": "7.0.0-beta.47",
"version": "7.0.0-beta.48",
"description": "Helper function to build binary assignment operator visitors",
"repository": "https://github.com/babel/babel/tree/master/packages/babel-helper-builder-binary-assignment-operator-visitor",
"license": "MIT",
"main": "lib/index.js",
"dependencies": {
"@babel/helper-explode-assignable-expression": "7.0.0-beta.47",
"@babel/types": "7.0.0-beta.47"
"@babel/helper-explode-assignable-expression": "7.0.0-beta.48",
"@babel/types": "7.0.0-beta.48"
}
}

View File

@@ -1,12 +1,12 @@
{
"name": "@babel/helper-builder-react-jsx",
"version": "7.0.0-beta.47",
"version": "7.0.0-beta.48",
"description": "Helper function to build react jsx",
"repository": "https://github.com/babel/babel/tree/master/packages/babel-helper-builder-react-jsx",
"license": "MIT",
"main": "lib/index.js",
"dependencies": {
"@babel/types": "7.0.0-beta.47",
"@babel/types": "7.0.0-beta.48",
"esutils": "^2.0.0"
}
}

View File

@@ -1,13 +1,13 @@
{
"name": "@babel/helper-call-delegate",
"version": "7.0.0-beta.47",
"version": "7.0.0-beta.48",
"description": "Helper function to call delegate",
"repository": "https://github.com/babel/babel/tree/master/packages/babel-helper-call-delegate",
"license": "MIT",
"main": "lib/index.js",
"dependencies": {
"@babel/helper-hoist-variables": "7.0.0-beta.47",
"@babel/traverse": "7.0.0-beta.47",
"@babel/types": "7.0.0-beta.47"
"@babel/helper-hoist-variables": "7.0.0-beta.48",
"@babel/traverse": "7.0.0-beta.48",
"@babel/types": "7.0.0-beta.48"
}
}

View File

@@ -1,13 +1,13 @@
{
"name": "@babel/helper-define-map",
"version": "7.0.0-beta.47",
"version": "7.0.0-beta.48",
"description": "Helper function to define a map",
"repository": "https://github.com/babel/babel/tree/master/packages/babel-helper-define-map",
"license": "MIT",
"main": "lib/index.js",
"dependencies": {
"@babel/helper-function-name": "7.0.0-beta.47",
"@babel/types": "7.0.0-beta.47",
"@babel/helper-function-name": "7.0.0-beta.48",
"@babel/types": "7.0.0-beta.48",
"lodash": "^4.17.5"
}
}

View File

@@ -1,12 +1,12 @@
{
"name": "@babel/helper-explode-assignable-expression",
"version": "7.0.0-beta.47",
"version": "7.0.0-beta.48",
"description": "Helper function to explode an assignable expression",
"repository": "https://github.com/babel/babel/tree/master/packages/babel-helper-explode-assignable-expression",
"license": "MIT",
"main": "lib/index.js",
"dependencies": {
"@babel/traverse": "7.0.0-beta.47",
"@babel/types": "7.0.0-beta.47"
"@babel/traverse": "7.0.0-beta.48",
"@babel/types": "7.0.0-beta.48"
}
}

View File

@@ -1,13 +1,13 @@
{
"name": "@babel/helper-explode-class",
"version": "7.0.0-beta.47",
"version": "7.0.0-beta.48",
"description": "Helper function to explode class",
"repository": "https://github.com/babel/babel/tree/master/packages/babel-helper-explode-class",
"license": "MIT",
"main": "lib/index.js",
"dependencies": {
"@babel/helper-bindify-decorators": "7.0.0-beta.47",
"@babel/traverse": "7.0.0-beta.47",
"@babel/types": "7.0.0-beta.47"
"@babel/helper-bindify-decorators": "7.0.0-beta.48",
"@babel/traverse": "7.0.0-beta.48",
"@babel/types": "7.0.0-beta.48"
}
}

View File

@@ -1,6 +1,6 @@
{
"name": "@babel/helper-fixtures",
"version": "7.0.0-beta.47",
"version": "7.0.0-beta.48",
"description": "Helper function to support fixtures",
"author": "Sebastian McKenzie <sebmck@gmail.com>",
"license": "MIT",

View File

@@ -1,4 +1,3 @@
import assert from "assert";
import cloneDeep from "lodash/cloneDeep";
import trimEnd from "lodash/trimEnd";
import resolve from "try-resolve";
@@ -56,6 +55,24 @@ function shouldIgnore(name, blacklist?: Array<string>) {
);
}
const EXTENSIONS = [".js", ".mjs", ".ts", ".tsx"];
function findFile(filepath: string, allowJSON: boolean) {
const matches = [];
for (const ext of EXTENSIONS.concat(allowJSON ? ".json" : [])) {
const name = filepath + ext;
if (fs.existsSync(name)) matches.push(name);
}
if (matches.length > 1) {
throw new Error(`Found conflicting file matches: ${matches.join(", ")}`);
}
return matches[0] || filepath + ".js";
}
export default function get(entryLoc): Array<Suite> {
const suites = [];
@@ -84,54 +101,25 @@ export default function get(entryLoc): Array<Suite> {
}
function push(taskName, taskDir) {
let actualLocAlias = suiteName + "/" + taskName + "/input.js";
let expectLocAlias = suiteName + "/" + taskName + "/output.js";
let execLocAlias = suiteName + "/" + taskName + "/exec.js";
const actualLoc = findFile(taskDir + "/input");
const expectLoc = findFile(taskDir + "/output", true /* allowJSON */);
let execLoc = findFile(taskDir + "/exec");
let actualLoc = taskDir + "/input.js";
let expectLoc = taskDir + "/output.js";
let execLoc = taskDir + "/exec.js";
const hasExecJS = fs.existsSync(execLoc);
const hasExecMJS = fs.existsSync(asMJS(execLoc));
if (hasExecMJS) {
assert(!hasExecJS, `${asMJS(execLoc)}: Found conflicting .js`);
execLoc = asMJS(execLoc);
execLocAlias = asMJS(execLocAlias);
}
const hasExpectJS = fs.existsSync(expectLoc);
const hasExpectMJS = fs.existsSync(asMJS(expectLoc));
if (hasExpectMJS) {
assert(!hasExpectJS, `${asMJS(expectLoc)}: Found conflicting .js`);
expectLoc = asMJS(expectLoc);
expectLocAlias = asMJS(expectLocAlias);
}
const hasActualJS = fs.existsSync(actualLoc);
const hasActualMJS = fs.existsSync(asMJS(actualLoc));
if (hasActualMJS) {
assert(!hasActualJS, `${asMJS(actualLoc)}: Found conflicting .js`);
actualLoc = asMJS(actualLoc);
actualLocAlias = asMJS(actualLocAlias);
}
const actualLocAlias =
suiteName + "/" + taskName + "/" + path.basename(actualLoc);
const expectLocAlias =
suiteName + "/" + taskName + "/" + path.basename(actualLoc);
let execLocAlias =
suiteName + "/" + taskName + "/" + path.basename(actualLoc);
if (fs.statSync(taskDir).isFile()) {
const ext = path.extname(taskDir);
if (ext !== ".js" && ext !== ".mjs") return;
if (EXTENSIONS.indexOf(ext) === -1) return;
execLoc = taskDir;
execLocAlias = suiteName + "/" + taskName;
}
if (resolve.relative(expectLoc + "on")) {
expectLoc += "on";
expectLocAlias += "on";
}
const taskOpts = cloneDeep(suite.options);
const taskOptsLoc = resolve(taskDir + "/options");
@@ -222,10 +210,6 @@ export function multiple(entryLoc, ignore?: Array<string>) {
return categories;
}
function asMJS(filepath) {
return filepath.replace(/\.js$/, ".mjs");
}
export function readFile(filename) {
if (fs.existsSync(filename)) {
let file = trimEnd(fs.readFileSync(filename, "utf8"));

View File

@@ -1,13 +1,13 @@
{
"name": "@babel/helper-function-name",
"version": "7.0.0-beta.47",
"version": "7.0.0-beta.48",
"description": "Helper function to change the property 'name' of every function",
"repository": "https://github.com/babel/babel/tree/master/packages/babel-helper-function-name",
"license": "MIT",
"main": "lib/index.js",
"dependencies": {
"@babel/helper-get-function-arity": "7.0.0-beta.47",
"@babel/template": "7.0.0-beta.47",
"@babel/types": "7.0.0-beta.47"
"@babel/helper-get-function-arity": "7.0.0-beta.48",
"@babel/template": "7.0.0-beta.48",
"@babel/types": "7.0.0-beta.48"
}
}

View File

@@ -1,11 +1,11 @@
{
"name": "@babel/helper-get-function-arity",
"version": "7.0.0-beta.47",
"version": "7.0.0-beta.48",
"description": "Helper function to get function arity",
"repository": "https://github.com/babel/babel/tree/master/packages/babel-helper-get-function-arity",
"license": "MIT",
"main": "lib/index.js",
"dependencies": {
"@babel/types": "7.0.0-beta.47"
"@babel/types": "7.0.0-beta.48"
}
}

View File

@@ -1,11 +1,11 @@
{
"name": "@babel/helper-hoist-variables",
"version": "7.0.0-beta.47",
"version": "7.0.0-beta.48",
"description": "Helper function to hoist variables",
"repository": "https://github.com/babel/babel/tree/master/packages/babel-helper-hoist-variables",
"license": "MIT",
"main": "lib/index.js",
"dependencies": {
"@babel/types": "7.0.0-beta.47"
"@babel/types": "7.0.0-beta.48"
}
}

View File

@@ -26,7 +26,7 @@ const visitor = {
// The helper requires three special methods on state: `get`, `set`, and
// `call`.
// Optionally, a special `memoize` method may be defined, which gets
// Optionally, a special `memoise` method may be defined, which gets
// called if the member is in a self-referential update expression.
// Everything else will be passed through as normal.
const state = {
@@ -55,10 +55,10 @@ const state = {
);
},
memoize(memberPath) {
memoise(memberPath) {
const { node } = memberPath;
if (node.computed) {
MEMOIZED.set(node, ...);
MEMOISED.set(node, ...);
}
},

View File

@@ -1,12 +1,12 @@
{
"name": "@babel/helper-member-expression-to-functions",
"version": "7.0.0-beta.47",
"version": "7.0.0-beta.48",
"description": "Helper function to replace certain member expressions with function calls",
"repository": "https://github.com/babel/babel/tree/master/packages/babel-helper-member-expression-to-functions",
"license": "MIT",
"main": "lib/index.js",
"author": "Justin Ridgewell <justin@ridgewell.name>",
"dependencies": {
"@babel/types": "7.0.0-beta.47"
"@babel/types": "7.0.0-beta.48"
}
}

View File

@@ -1,6 +1,39 @@
import * as t from "@babel/types";
class AssignmentMemoiser {
constructor() {
this._map = new WeakMap();
}
has(key) {
return this._map.has(key);
}
get(key) {
if (!this.has(key)) return;
const record = this._map.get(key);
const { value } = record;
record.count--;
if (record.count === 0) {
// The `count` access is the outermost function call (hopefully), so it
// does the assignment.
return t.assignmentExpression("=", value, key);
}
return value;
}
set(key, value, count) {
return this._map.set(key, { count, value });
}
}
const handle = {
memoise() {
// noop.
},
handle(member) {
const { node, parent, parentPath } = member;
@@ -9,11 +42,10 @@ const handle = {
if (parentPath.isUpdateExpression({ argument: node })) {
const { operator, prefix } = parent;
// Give the state handler a chance to memoize the member,
// since we'll reference it twice.
if (this.memoize) {
this.memoize(member);
}
// Give the state handler a chance to memoise the member, since we'll
// reference it twice. The second access (the set) should do the memo
// assignment.
this.memoise(member, 2);
const value = t.binaryExpression(
operator[0],
@@ -44,11 +76,10 @@ const handle = {
let value = right;
if (operator !== "=") {
// Give the state handler a chance to memoize the member,
// since we'll reference it twice.
if (this.memoize) {
this.memoize(member);
}
// Give the state handler a chance to memoise the member, since we'll
// reference it twice. The second access (the set) should do the memo
// assignment.
this.memoise(member, 2);
value = t.binaryExpression(
operator.slice(0, -1),
@@ -79,11 +110,12 @@ const handle = {
// it wishes to be transformed.
// Additionally, the caller must pass in a state object with at least
// get, set, and call methods.
// Optionally, a memoize method may be defined on the state, which will be
// Optionally, a memoise method may be defined on the state, which will be
// called when the member is a self-referential update.
export default function memberExpressionToFunctions(path, visitor, state) {
path.traverse(visitor, {
...state,
...handle,
...state,
memoiser: new AssignmentMemoiser(),
});
}

View File

@@ -1,6 +1,6 @@
{
"name": "@babel/helper-module-imports",
"version": "7.0.0-beta.47",
"version": "7.0.0-beta.48",
"description": "Babel helper functions for inserting module loads",
"author": "Logan Smyth <loganfsmyth@gmail.com>",
"homepage": "https://babeljs.io/",
@@ -8,10 +8,10 @@
"repository": "https://github.com/babel/babel/tree/master/packages/babel-helper-module-imports",
"main": "lib/index.js",
"dependencies": {
"@babel/types": "7.0.0-beta.47",
"@babel/types": "7.0.0-beta.48",
"lodash": "^4.17.5"
},
"devDependencies": {
"@babel/core": "7.0.0-beta.47"
"@babel/core": "7.0.0-beta.48"
}
}

View File

@@ -1,6 +1,6 @@
{
"name": "@babel/helper-module-transforms",
"version": "7.0.0-beta.47",
"version": "7.0.0-beta.48",
"description": "Babel helper functions for implementing ES6 module transformations",
"author": "Logan Smyth <loganfsmyth@gmail.com>",
"homepage": "https://babeljs.io/",
@@ -8,11 +8,11 @@
"repository": "https://github.com/babel/babel/tree/master/packages/babel-helper-module-transforms",
"main": "lib/index.js",
"dependencies": {
"@babel/helper-module-imports": "7.0.0-beta.47",
"@babel/helper-simple-access": "7.0.0-beta.47",
"@babel/helper-split-export-declaration": "7.0.0-beta.47",
"@babel/template": "7.0.0-beta.47",
"@babel/types": "7.0.0-beta.47",
"@babel/helper-module-imports": "7.0.0-beta.48",
"@babel/helper-simple-access": "7.0.0-beta.48",
"@babel/helper-split-export-declaration": "7.0.0-beta.48",
"@babel/template": "7.0.0-beta.48",
"@babel/types": "7.0.0-beta.48",
"lodash": "^4.17.5"
}
}

View File

@@ -1,11 +1,11 @@
{
"name": "@babel/helper-optimise-call-expression",
"version": "7.0.0-beta.47",
"version": "7.0.0-beta.48",
"description": "Helper function to optimise call expression",
"repository": "https://github.com/babel/babel/tree/master/packages/babel-helper-optimise-call-expression",
"license": "MIT",
"main": "lib/index.js",
"dependencies": {
"@babel/types": "7.0.0-beta.47"
"@babel/types": "7.0.0-beta.48"
}
}

View File

@@ -1,11 +1,11 @@
{
"name": "@babel/helper-plugin-test-runner",
"version": "7.0.0-beta.47",
"version": "7.0.0-beta.48",
"description": "Helper function to support test runner",
"repository": "https://github.com/babel/babel/tree/master/packages/babel-helper-plugin-test-runner",
"license": "MIT",
"main": "lib/index.js",
"dependencies": {
"@babel/helper-transform-fixture-test-runner": "7.0.0-beta.47"
"@babel/helper-transform-fixture-test-runner": "7.0.0-beta.48"
}
}

View File

@@ -1,6 +1,6 @@
{
"name": "@babel/helper-plugin-utils",
"version": "7.0.0-beta.47",
"version": "7.0.0-beta.48",
"description": "General utilities for plugins to use",
"author": "Logan Smyth <loganfsmyth@gmail.com>",
"homepage": "https://babeljs.io/",

View File

@@ -1,6 +1,6 @@
{
"name": "@babel/helper-regex",
"version": "7.0.0-beta.47",
"version": "7.0.0-beta.48",
"description": "Helper function to check for literal RegEx",
"repository": "https://github.com/babel/babel/tree/master/packages/babel-helper-regex",
"license": "MIT",

View File

@@ -1,15 +1,15 @@
{
"name": "@babel/helper-remap-async-to-generator",
"version": "7.0.0-beta.47",
"version": "7.0.0-beta.48",
"description": "Helper function to remap async functions to generators",
"repository": "https://github.com/babel/babel/tree/master/packages/babel-helper-remap-async-to-generator",
"license": "MIT",
"main": "lib/index.js",
"dependencies": {
"@babel/helper-annotate-as-pure": "7.0.0-beta.47",
"@babel/helper-wrap-function": "7.0.0-beta.47",
"@babel/template": "7.0.0-beta.47",
"@babel/traverse": "7.0.0-beta.47",
"@babel/types": "7.0.0-beta.47"
"@babel/helper-annotate-as-pure": "7.0.0-beta.48",
"@babel/helper-wrap-function": "7.0.0-beta.48",
"@babel/template": "7.0.0-beta.48",
"@babel/traverse": "7.0.0-beta.48",
"@babel/types": "7.0.0-beta.48"
}
}

View File

@@ -1,14 +1,14 @@
{
"name": "@babel/helper-replace-supers",
"version": "7.0.0-beta.47",
"version": "7.0.0-beta.48",
"description": "Helper function to replace supers",
"repository": "https://github.com/babel/babel/tree/master/packages/babel-helper-replace-supers",
"license": "MIT",
"main": "lib/index.js",
"dependencies": {
"@babel/helper-member-expression-to-functions": "7.0.0-beta.47",
"@babel/helper-optimise-call-expression": "7.0.0-beta.47",
"@babel/traverse": "7.0.0-beta.47",
"@babel/types": "7.0.0-beta.47"
"@babel/helper-member-expression-to-functions": "7.0.0-beta.48",
"@babel/helper-optimise-call-expression": "7.0.0-beta.48",
"@babel/traverse": "7.0.0-beta.48",
"@babel/types": "7.0.0-beta.48"
}
}

View File

@@ -70,9 +70,8 @@ const visitor = traverse.visitors.merge([
},
]);
const memoized = new WeakMap();
const specHandlers = {
memoize(superMember) {
memoise(superMember, count) {
const { scope, node } = superMember;
const { computed, property } = node;
if (!computed) {
@@ -84,44 +83,34 @@ const specHandlers = {
return;
}
memoized.set(property, memo);
this.memoiser.set(property, memo, count);
},
prop(superMember) {
const { computed, property } = superMember.node;
if (this.memoiser.has(property)) {
return t.cloneNode(this.memoiser.get(property));
}
if (computed) {
return t.cloneNode(property);
}
return t.stringLiteral(property.name);
},
get(superMember) {
const { computed, property } = superMember.node;
const thisExpr = t.thisExpression();
let prop;
if (computed && memoized.has(property)) {
prop = t.cloneNode(memoized.get(property));
} else {
prop = computed ? property : t.stringLiteral(property.name);
}
return t.callExpression(this.file.addHelper("get"), [
getPrototypeOfExpression(this.getObjectRef(), this.isStatic, this.file),
prop,
thisExpr,
this.prop(superMember),
t.thisExpression(),
]);
},
set(superMember, value) {
const { computed, property } = superMember.node;
let prop;
if (computed && memoized.has(property)) {
prop = t.assignmentExpression(
"=",
t.cloneNode(memoized.get(property)),
property,
);
} else {
prop = computed ? property : t.stringLiteral(property.name);
}
return t.callExpression(this.file.addHelper("set"), [
getPrototypeOfExpression(this.getObjectRef(), this.isStatic, this.file),
prop,
this.prop(superMember),
value,
t.thisExpression(),
t.booleanLiteral(superMember.isInStrictMode()),
@@ -134,12 +123,21 @@ const specHandlers = {
};
const looseHandlers = {
memoize: specHandlers.memoize,
call: specHandlers.call,
...specHandlers,
prop(superMember) {
const { property } = superMember.node;
if (this.memoiser.has(property)) {
return t.cloneNode(this.memoiser.get(property));
}
return t.cloneNode(property);
},
get(superMember) {
const { isStatic, superRef } = this;
const { property, computed } = superMember.node;
const { computed } = superMember.node;
const prop = this.prop(superMember);
let object;
if (isStatic) {
@@ -155,29 +153,12 @@ const looseHandlers = {
: t.memberExpression(t.identifier("Object"), t.identifier("prototype"));
}
let prop;
if (computed && memoized.has(property)) {
prop = t.cloneNode(memoized.get(property));
} else {
prop = property;
}
return t.memberExpression(object, prop, computed);
},
set(superMember, value) {
const { property, computed } = superMember.node;
let prop;
if (computed && memoized.has(property)) {
prop = t.assignmentExpression(
"=",
t.cloneNode(memoized.get(property)),
property,
);
} else {
prop = property;
}
const { computed } = superMember.node;
const prop = this.prop(superMember);
return t.assignmentExpression(
"=",

View File

@@ -1,6 +1,6 @@
{
"name": "@babel/helper-simple-access",
"version": "7.0.0-beta.47",
"version": "7.0.0-beta.48",
"description": "Babel helper for ensuring that access to a given value is performed through simple accesses",
"author": "Logan Smyth <loganfsmyth@gmail.com>",
"homepage": "https://babeljs.io/",
@@ -8,8 +8,8 @@
"repository": "https://github.com/babel/babel/tree/master/packages/babel-helper-simple-access",
"main": "lib/index.js",
"dependencies": {
"@babel/template": "7.0.0-beta.47",
"@babel/types": "7.0.0-beta.47",
"@babel/template": "7.0.0-beta.48",
"@babel/types": "7.0.0-beta.48",
"lodash": "^4.17.5"
}
}

View File

@@ -1,11 +1,11 @@
{
"name": "@babel/helper-split-export-declaration",
"version": "7.0.0-beta.47",
"version": "7.0.0-beta.48",
"description": "",
"repository": "https://github.com/babel/babel/tree/master/packages/babel-helper-split-export-declaration",
"license": "MIT",
"main": "lib/index.js",
"dependencies": {
"@babel/types": "7.0.0-beta.47"
"@babel/types": "7.0.0-beta.48"
}
}

View File

@@ -1,6 +1,6 @@
{
"name": "@babel/helper-transform-fixture-test-runner",
"version": "7.0.0-beta.47",
"version": "7.0.0-beta.48",
"description": "Transform test runner for @babel/helper-fixtures module",
"author": "Sebastian McKenzie <sebmck@gmail.com>",
"homepage": "https://babeljs.io/",
@@ -8,10 +8,10 @@
"repository": "https://github.com/babel/babel/tree/master/packages/babel-helper-transform-fixture-test-runner",
"main": "lib/index.js",
"dependencies": {
"@babel/code-frame": "7.0.0-beta.47",
"@babel/core": "7.0.0-beta.47",
"@babel/helper-fixtures": "7.0.0-beta.47",
"@babel/polyfill": "7.0.0-beta.47",
"@babel/code-frame": "7.0.0-beta.48",
"@babel/core": "7.0.0-beta.48",
"@babel/helper-fixtures": "7.0.0-beta.48",
"@babel/polyfill": "7.0.0-beta.48",
"jest": "^22.4.2",
"jest-diff": "^22.4.0",
"lodash": "^4.17.5",

View File

@@ -33,7 +33,9 @@ testContext.global = testContext;
runModuleInTestContext("@babel/polyfill", __filename);
// Populate the "babelHelpers" global with Babel's helper utilities.
runCodeInTestContext(buildExternalHelpers());
runCodeInTestContext(buildExternalHelpers(), {
filename: path.join(__dirname, "babel-helpers-in-memory.js"),
});
/**
* A basic implementation of CommonJS so we can execute `@babel/polyfill` inside our test context.
@@ -75,13 +77,10 @@ function runModuleInTestContext(id: string, relativeFilename: string) {
*
* Exposed for unit tests, not for use as an API.
*/
export function runCodeInTestContext(
code: string,
opts: { filename?: string } = {},
) {
const filename = opts.filename || null;
const dirname = filename ? path.dirname(filename) : null;
const req = filename ? id => runModuleInTestContext(id, filename) : null;
export function runCodeInTestContext(code: string, opts: { filename: string }) {
const filename = opts.filename;
const dirname = path.dirname(filename);
const req = id => runModuleInTestContext(id, filename);
const module = {
id: filename,
@@ -344,10 +343,10 @@ function run(task) {
newOpts.presets,
optionsDir,
).map(function(val) {
if (val.length > 2) {
if (val.length > 3) {
throw new Error(
"Unexpected extra options " +
JSON.stringify(val.slice(2)) +
JSON.stringify(val.slice(3)) +
" passed to preset.",
);
}

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