react app

This commit is contained in:
Mario Romano
2016-04-06 17:52:19 +01:00
parent f7e6ef55a2
commit 29df96a085
4425 changed files with 446323 additions and 0 deletions
Generated Vendored Symlink
+1
View File
@@ -0,0 +1 @@
../babel/cli.js
+1
View File
@@ -0,0 +1 @@
../babel/cli.js
Generated Vendored Symlink
+1
View File
@@ -0,0 +1 @@
../babel/cli.js
Generated Vendored Symlink
+1
View File
@@ -0,0 +1 @@
../babylon/bin/babylon.js
+1
View File
@@ -0,0 +1 @@
../detect-indent/cli.js
Generated Vendored Symlink
+1
View File
@@ -0,0 +1 @@
../envify/bin/envify
Generated Vendored Symlink
+1
View File
@@ -0,0 +1 @@
../esprima-fb/bin/esparse.js
Generated Vendored Symlink
+1
View File
@@ -0,0 +1 @@
../esprima-fb/bin/esvalidate.js
Generated Vendored Symlink
+1
View File
@@ -0,0 +1 @@
../json5/lib/cli.js
Generated Vendored Symlink
+1
View File
@@ -0,0 +1 @@
../mkdirp/bin/cmd.js
Generated Vendored Symlink
+1
View File
@@ -0,0 +1 @@
../repeating/cli.js
Generated Vendored Symlink
+1
View File
@@ -0,0 +1 @@
../user-home/cli.js
+58
View File
@@ -0,0 +1,58 @@
amdefine is released under two licenses: new BSD, and MIT. You may pick the
license that best suits your development needs. The text of both licenses are
provided below.
The "New" BSD License:
----------------------
Copyright (c) 2011-2015, The Dojo Foundation
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the Dojo Foundation nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
MIT License
-----------
Copyright (c) 2011-2015, The Dojo Foundation
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
+171
View File
@@ -0,0 +1,171 @@
# amdefine
A module that can be used to implement AMD's define() in Node. This allows you
to code to the AMD API and have the module work in node programs without
requiring those other programs to use AMD.
## Usage
**1)** Update your package.json to indicate amdefine as a dependency:
```javascript
"dependencies": {
"amdefine": ">=0.1.0"
}
```
Then run `npm install` to get amdefine into your project.
**2)** At the top of each module that uses define(), place this code:
```javascript
if (typeof define !== 'function') { var define = require('amdefine')(module) }
```
**Only use these snippets** when loading amdefine. If you preserve the basic structure,
with the braces, it will be stripped out when using the [RequireJS optimizer](#optimizer).
You can add spaces, line breaks and even require amdefine with a local path, but
keep the rest of the structure to get the stripping behavior.
As you may know, because `if` statements in JavaScript don't have their own scope, the var
declaration in the above snippet is made whether the `if` expression is truthy or not. If
RequireJS is loaded then the declaration is superfluous because `define` is already already
declared in the same scope in RequireJS. Fortunately JavaScript handles multiple `var`
declarations of the same variable in the same scope gracefully.
If you want to deliver amdefine.js with your code rather than specifying it as a dependency
with npm, then just download the latest release and refer to it using a relative path:
[Latest Version](https://github.com/jrburke/amdefine/raw/latest/amdefine.js)
### amdefine/intercept
Consider this very experimental.
Instead of pasting the piece of text for the amdefine setup of a `define`
variable in each module you create or consume, you can use `amdefine/intercept`
instead. It will automatically insert the above snippet in each .js file loaded
by Node.
**Warning**: you should only use this if you are creating an application that
is consuming AMD style defined()'d modules that are distributed via npm and want
to run that code in Node.
For library code where you are not sure if it will be used by others in Node or
in the browser, then explicitly depending on amdefine and placing the code
snippet above is suggested path, instead of using `amdefine/intercept`. The
intercept module affects all .js files loaded in the Node app, and it is
inconsiderate to modify global state like that unless you are also controlling
the top level app.
#### Why distribute AMD-style modules via npm?
npm has a lot of weaknesses for front-end use (installed layout is not great,
should have better support for the `baseUrl + moduleID + '.js' style of loading,
single file JS installs), but some people want a JS package manager and are
willing to live with those constraints. If that is you, but still want to author
in AMD style modules to get dynamic require([]), better direct source usage and
powerful loader plugin support in the browser, then this tool can help.
#### amdefine/intercept usage
Just require it in your top level app module (for example index.js, server.js):
```javascript
require('amdefine/intercept');
```
The module does not return a value, so no need to assign the result to a local
variable.
Then just require() code as you normally would with Node's require(). Any .js
loaded after the intercept require will have the amdefine check injected in
the .js source as it is loaded. It does not modify the source on disk, just
prepends some content to the text of the module as it is loaded by Node.
#### How amdefine/intercept works
It overrides the `Module._extensions['.js']` in Node to automatically prepend
the amdefine snippet above. So, it will affect any .js file loaded by your
app.
## define() usage
It is best if you use the anonymous forms of define() in your module:
```javascript
define(function (require) {
var dependency = require('dependency');
});
```
or
```javascript
define(['dependency'], function (dependency) {
});
```
## RequireJS optimizer integration. <a name="optimizer"></name>
Version 1.0.3 of the [RequireJS optimizer](http://requirejs.org/docs/optimization.html)
will have support for stripping the `if (typeof define !== 'function')` check
mentioned above, so you can include this snippet for code that runs in the
browser, but avoid taking the cost of the if() statement once the code is
optimized for deployment.
## Node 0.4 Support
If you want to support Node 0.4, then add `require` as the second parameter to amdefine:
```javascript
//Only if you want Node 0.4. If using 0.5 or later, use the above snippet.
if (typeof define !== 'function') { var define = require('amdefine')(module, require) }
```
## Limitations
### Synchronous vs Asynchronous
amdefine creates a define() function that is callable by your code. It will
execute and trace dependencies and call the factory function *synchronously*,
to keep the behavior in line with Node's synchronous dependency tracing.
The exception: calling AMD's callback-style require() from inside a factory
function. The require callback is called on process.nextTick():
```javascript
define(function (require) {
require(['a'], function(a) {
//'a' is loaded synchronously, but
//this callback is called on process.nextTick().
});
});
```
### Loader Plugins
Loader plugins are supported as long as they call their load() callbacks
synchronously. So ones that do network requests will not work. However plugins
like [text](http://requirejs.org/docs/api.html#text) can load text files locally.
The plugin API's `load.fromText()` is **not supported** in amdefine, so this means
transpiler plugins like the [CoffeeScript loader plugin](https://github.com/jrburke/require-cs)
will not work. This may be fixable, but it is a bit complex, and I do not have
enough node-fu to figure it out yet. See the source for amdefine.js if you want
to get an idea of the issues involved.
## Tests
To run the tests, cd to **tests** and run:
```
node all.js
node all-intercept.js
```
## License
New BSD and MIT. Check the LICENSE file for all the details.
+301
View File
@@ -0,0 +1,301 @@
/** vim: et:ts=4:sw=4:sts=4
* @license amdefine 1.0.0 Copyright (c) 2011-2015, The Dojo Foundation All Rights Reserved.
* Available via the MIT or new BSD license.
* see: http://github.com/jrburke/amdefine for details
*/
/*jslint node: true */
/*global module, process */
'use strict';
/**
* Creates a define for node.
* @param {Object} module the "module" object that is defined by Node for the
* current module.
* @param {Function} [requireFn]. Node's require function for the current module.
* It only needs to be passed in Node versions before 0.5, when module.require
* did not exist.
* @returns {Function} a define function that is usable for the current node
* module.
*/
function amdefine(module, requireFn) {
'use strict';
var defineCache = {},
loaderCache = {},
alreadyCalled = false,
path = require('path'),
makeRequire, stringRequire;
/**
* Trims the . and .. from an array of path segments.
* It will keep a leading path segment if a .. will become
* the first path segment, to help with module name lookups,
* which act like paths, but can be remapped. But the end result,
* all paths that use this function should look normalized.
* NOTE: this method MODIFIES the input array.
* @param {Array} ary the array of path segments.
*/
function trimDots(ary) {
var i, part;
for (i = 0; ary[i]; i+= 1) {
part = ary[i];
if (part === '.') {
ary.splice(i, 1);
i -= 1;
} else if (part === '..') {
if (i === 1 && (ary[2] === '..' || ary[0] === '..')) {
//End of the line. Keep at least one non-dot
//path segment at the front so it can be mapped
//correctly to disk. Otherwise, there is likely
//no path mapping for a path starting with '..'.
//This can still fail, but catches the most reasonable
//uses of ..
break;
} else if (i > 0) {
ary.splice(i - 1, 2);
i -= 2;
}
}
}
}
function normalize(name, baseName) {
var baseParts;
//Adjust any relative paths.
if (name && name.charAt(0) === '.') {
//If have a base name, try to normalize against it,
//otherwise, assume it is a top-level require that will
//be relative to baseUrl in the end.
if (baseName) {
baseParts = baseName.split('/');
baseParts = baseParts.slice(0, baseParts.length - 1);
baseParts = baseParts.concat(name.split('/'));
trimDots(baseParts);
name = baseParts.join('/');
}
}
return name;
}
/**
* Create the normalize() function passed to a loader plugin's
* normalize method.
*/
function makeNormalize(relName) {
return function (name) {
return normalize(name, relName);
};
}
function makeLoad(id) {
function load(value) {
loaderCache[id] = value;
}
load.fromText = function (id, text) {
//This one is difficult because the text can/probably uses
//define, and any relative paths and requires should be relative
//to that id was it would be found on disk. But this would require
//bootstrapping a module/require fairly deeply from node core.
//Not sure how best to go about that yet.
throw new Error('amdefine does not implement load.fromText');
};
return load;
}
makeRequire = function (systemRequire, exports, module, relId) {
function amdRequire(deps, callback) {
if (typeof deps === 'string') {
//Synchronous, single module require('')
return stringRequire(systemRequire, exports, module, deps, relId);
} else {
//Array of dependencies with a callback.
//Convert the dependencies to modules.
deps = deps.map(function (depName) {
return stringRequire(systemRequire, exports, module, depName, relId);
});
//Wait for next tick to call back the require call.
if (callback) {
process.nextTick(function () {
callback.apply(null, deps);
});
}
}
}
amdRequire.toUrl = function (filePath) {
if (filePath.indexOf('.') === 0) {
return normalize(filePath, path.dirname(module.filename));
} else {
return filePath;
}
};
return amdRequire;
};
//Favor explicit value, passed in if the module wants to support Node 0.4.
requireFn = requireFn || function req() {
return module.require.apply(module, arguments);
};
function runFactory(id, deps, factory) {
var r, e, m, result;
if (id) {
e = loaderCache[id] = {};
m = {
id: id,
uri: __filename,
exports: e
};
r = makeRequire(requireFn, e, m, id);
} else {
//Only support one define call per file
if (alreadyCalled) {
throw new Error('amdefine with no module ID cannot be called more than once per file.');
}
alreadyCalled = true;
//Use the real variables from node
//Use module.exports for exports, since
//the exports in here is amdefine exports.
e = module.exports;
m = module;
r = makeRequire(requireFn, e, m, module.id);
}
//If there are dependencies, they are strings, so need
//to convert them to dependency values.
if (deps) {
deps = deps.map(function (depName) {
return r(depName);
});
}
//Call the factory with the right dependencies.
if (typeof factory === 'function') {
result = factory.apply(m.exports, deps);
} else {
result = factory;
}
if (result !== undefined) {
m.exports = result;
if (id) {
loaderCache[id] = m.exports;
}
}
}
stringRequire = function (systemRequire, exports, module, id, relId) {
//Split the ID by a ! so that
var index = id.indexOf('!'),
originalId = id,
prefix, plugin;
if (index === -1) {
id = normalize(id, relId);
//Straight module lookup. If it is one of the special dependencies,
//deal with it, otherwise, delegate to node.
if (id === 'require') {
return makeRequire(systemRequire, exports, module, relId);
} else if (id === 'exports') {
return exports;
} else if (id === 'module') {
return module;
} else if (loaderCache.hasOwnProperty(id)) {
return loaderCache[id];
} else if (defineCache[id]) {
runFactory.apply(null, defineCache[id]);
return loaderCache[id];
} else {
if(systemRequire) {
return systemRequire(originalId);
} else {
throw new Error('No module with ID: ' + id);
}
}
} else {
//There is a plugin in play.
prefix = id.substring(0, index);
id = id.substring(index + 1, id.length);
plugin = stringRequire(systemRequire, exports, module, prefix, relId);
if (plugin.normalize) {
id = plugin.normalize(id, makeNormalize(relId));
} else {
//Normalize the ID normally.
id = normalize(id, relId);
}
if (loaderCache[id]) {
return loaderCache[id];
} else {
plugin.load(id, makeRequire(systemRequire, exports, module, relId), makeLoad(id), {});
return loaderCache[id];
}
}
};
//Create a define function specific to the module asking for amdefine.
function define(id, deps, factory) {
if (Array.isArray(id)) {
factory = deps;
deps = id;
id = undefined;
} else if (typeof id !== 'string') {
factory = id;
id = deps = undefined;
}
if (deps && !Array.isArray(deps)) {
factory = deps;
deps = undefined;
}
if (!deps) {
deps = ['require', 'exports', 'module'];
}
//Set up properties for this module. If an ID, then use
//internal cache. If no ID, then use the external variables
//for this node module.
if (id) {
//Put the module in deep freeze until there is a
//require call for it.
defineCache[id] = [id, deps, factory];
} else {
runFactory(id, deps, factory);
}
}
//define.require, which has access to all the values in the
//cache. Useful for AMD modules that all have IDs in the file,
//but need to finally export a value to node based on one of those
//IDs.
define.require = function (id) {
if (loaderCache[id]) {
return loaderCache[id];
}
if (defineCache[id]) {
runFactory.apply(null, defineCache[id]);
return loaderCache[id];
}
};
define.amd = {};
return define;
}
module.exports = amdefine;
+36
View File
@@ -0,0 +1,36 @@
/*jshint node: true */
var inserted,
Module = require('module'),
fs = require('fs'),
existingExtFn = Module._extensions['.js'],
amdefineRegExp = /amdefine\.js/;
inserted = "if (typeof define !== 'function') {var define = require('amdefine')(module)}";
//From the node/lib/module.js source:
function stripBOM(content) {
// Remove byte order marker. This catches EF BB BF (the UTF-8 BOM)
// because the buffer-to-string conversion in `fs.readFileSync()`
// translates it to FEFF, the UTF-16 BOM.
if (content.charCodeAt(0) === 0xFEFF) {
content = content.slice(1);
}
return content;
}
//Also adapted from the node/lib/module.js source:
function intercept(module, filename) {
var content = stripBOM(fs.readFileSync(filename, 'utf8'));
if (!amdefineRegExp.test(module.id)) {
content = inserted + content;
}
module._compile(content, filename);
}
intercept._id = 'amdefine/intercept';
if (!existingExtFn._id || existingExtFn._id !== intercept._id) {
Module._extensions['.js'] = intercept;
}
+75
View File
@@ -0,0 +1,75 @@
{
"_args": [
[
"amdefine@>=0.0.4",
"/Users/mromano/dev/react-sfs/node_modules/source-map-support/node_modules/source-map"
]
],
"_from": "amdefine@>=0.0.4",
"_id": "amdefine@1.0.0",
"_inCache": true,
"_installable": true,
"_location": "/amdefine",
"_nodeVersion": "0.10.36",
"_npmUser": {
"email": "jrburke@gmail.com",
"name": "jrburke"
},
"_npmVersion": "2.12.1",
"_phantomChildren": {},
"_requested": {
"name": "amdefine",
"raw": "amdefine@>=0.0.4",
"rawSpec": ">=0.0.4",
"scope": null,
"spec": ">=0.0.4",
"type": "range"
},
"_requiredBy": [
"/jstransform/source-map",
"/source-map-support/source-map"
],
"_resolved": "https://registry.npmjs.org/amdefine/-/amdefine-1.0.0.tgz",
"_shasum": "fd17474700cb5cc9c2b709f0be9d23ce3c198c33",
"_shrinkwrap": null,
"_spec": "amdefine@>=0.0.4",
"_where": "/Users/mromano/dev/react-sfs/node_modules/source-map-support/node_modules/source-map",
"author": {
"email": "jrburke@gmail.com",
"name": "James Burke",
"url": "http://github.com/jrburke"
},
"bugs": {
"url": "https://github.com/jrburke/amdefine/issues"
},
"dependencies": {},
"description": "Provide AMD's define() API for declaring modules in the AMD format",
"devDependencies": {},
"directories": {},
"dist": {
"shasum": "fd17474700cb5cc9c2b709f0be9d23ce3c198c33",
"tarball": "http://registry.npmjs.org/amdefine/-/amdefine-1.0.0.tgz"
},
"engines": {
"node": ">=0.4.2"
},
"gitHead": "578bc4a3f7dede33f3f3e10edde0c1607005d761",
"homepage": "http://github.com/jrburke/amdefine",
"license": "BSD-3-Clause AND MIT",
"main": "./amdefine.js",
"maintainers": [
{
"email": "jrburke@gmail.com",
"name": "jrburke"
}
],
"name": "amdefine",
"optionalDependencies": {},
"readme": "ERROR: No README data found!",
"repository": {
"type": "git",
"url": "git+https://github.com/jrburke/amdefine.git"
},
"scripts": {},
"version": "1.0.0"
}
+4
View File
@@ -0,0 +1,4 @@
'use strict';
module.exports = function () {
return /[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g;
};
+21
View File
@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
+113
View File
@@ -0,0 +1,113 @@
{
"_args": [
[
"ansi-regex@^2.0.0",
"/Users/mromano/dev/react-sfs/node_modules/has-ansi"
]
],
"_from": "ansi-regex@>=2.0.0 <3.0.0",
"_id": "ansi-regex@2.0.0",
"_inCache": true,
"_installable": true,
"_location": "/ansi-regex",
"_nodeVersion": "0.12.5",
"_npmUser": {
"email": "sindresorhus@gmail.com",
"name": "sindresorhus"
},
"_npmVersion": "2.11.2",
"_phantomChildren": {},
"_requested": {
"name": "ansi-regex",
"raw": "ansi-regex@^2.0.0",
"rawSpec": "^2.0.0",
"scope": null,
"spec": ">=2.0.0 <3.0.0",
"type": "range"
},
"_requiredBy": [
"/has-ansi",
"/strip-ansi"
],
"_resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-2.0.0.tgz",
"_shasum": "c5061b6e0ef8a81775e50f5d66151bf6bf371107",
"_shrinkwrap": null,
"_spec": "ansi-regex@^2.0.0",
"_where": "/Users/mromano/dev/react-sfs/node_modules/has-ansi",
"author": {
"email": "sindresorhus@gmail.com",
"name": "Sindre Sorhus",
"url": "sindresorhus.com"
},
"bugs": {
"url": "https://github.com/sindresorhus/ansi-regex/issues"
},
"dependencies": {},
"description": "Regular expression for matching ANSI escape codes",
"devDependencies": {
"mocha": "*"
},
"directories": {},
"dist": {
"shasum": "c5061b6e0ef8a81775e50f5d66151bf6bf371107",
"tarball": "http://registry.npmjs.org/ansi-regex/-/ansi-regex-2.0.0.tgz"
},
"engines": {
"node": ">=0.10.0"
},
"files": [
"index.js"
],
"gitHead": "57c3f2941a73079fa8b081e02a522e3d29913e2f",
"homepage": "https://github.com/sindresorhus/ansi-regex",
"keywords": [
"ansi",
"styles",
"color",
"colour",
"colors",
"terminal",
"console",
"cli",
"string",
"tty",
"escape",
"formatting",
"rgb",
"256",
"shell",
"xterm",
"command-line",
"text",
"regex",
"regexp",
"re",
"match",
"test",
"find",
"pattern"
],
"license": "MIT",
"maintainers": [
{
"email": "sindresorhus@gmail.com",
"name": "sindresorhus"
},
{
"email": "jappelman@xebia.com",
"name": "jbnicolai"
}
],
"name": "ansi-regex",
"optionalDependencies": {},
"readme": "ERROR: No README data found!",
"repository": {
"type": "git",
"url": "git+https://github.com/sindresorhus/ansi-regex.git"
},
"scripts": {
"test": "mocha test/test.js",
"view-supported": "node test/viewCodes.js"
},
"version": "2.0.0"
}
+31
View File
@@ -0,0 +1,31 @@
# ansi-regex [![Build Status](https://travis-ci.org/sindresorhus/ansi-regex.svg?branch=master)](https://travis-ci.org/sindresorhus/ansi-regex)
> Regular expression for matching [ANSI escape codes](http://en.wikipedia.org/wiki/ANSI_escape_code)
## Install
```
$ npm install --save ansi-regex
```
## Usage
```js
var ansiRegex = require('ansi-regex');
ansiRegex().test('\u001b[4mcake\u001b[0m');
//=> true
ansiRegex().test('cake');
//=> false
'\u001b[4mcake\u001b[0m'.match(ansiRegex());
//=> ['\u001b[4m', '\u001b[0m']
```
## License
MIT © [Sindre Sorhus](http://sindresorhus.com)
+65
View File
@@ -0,0 +1,65 @@
'use strict';
function assembleStyles () {
var styles = {
modifiers: {
reset: [0, 0],
bold: [1, 22], // 21 isn't widely supported and 22 does the same thing
dim: [2, 22],
italic: [3, 23],
underline: [4, 24],
inverse: [7, 27],
hidden: [8, 28],
strikethrough: [9, 29]
},
colors: {
black: [30, 39],
red: [31, 39],
green: [32, 39],
yellow: [33, 39],
blue: [34, 39],
magenta: [35, 39],
cyan: [36, 39],
white: [37, 39],
gray: [90, 39]
},
bgColors: {
bgBlack: [40, 49],
bgRed: [41, 49],
bgGreen: [42, 49],
bgYellow: [43, 49],
bgBlue: [44, 49],
bgMagenta: [45, 49],
bgCyan: [46, 49],
bgWhite: [47, 49]
}
};
// fix humans
styles.colors.grey = styles.colors.gray;
Object.keys(styles).forEach(function (groupName) {
var group = styles[groupName];
Object.keys(group).forEach(function (styleName) {
var style = group[styleName];
styles[styleName] = group[styleName] = {
open: '\u001b[' + style[0] + 'm',
close: '\u001b[' + style[1] + 'm'
};
});
Object.defineProperty(styles, groupName, {
value: group,
enumerable: false
});
});
return styles;
}
Object.defineProperty(module, 'exports', {
enumerable: true,
get: assembleStyles
});
+21
View File
@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
+106
View File
@@ -0,0 +1,106 @@
{
"_args": [
[
"ansi-styles@^2.2.1",
"/Users/mromano/dev/react-sfs/node_modules/chalk"
]
],
"_from": "ansi-styles@>=2.2.1 <3.0.0",
"_id": "ansi-styles@2.2.1",
"_inCache": true,
"_installable": true,
"_location": "/ansi-styles",
"_nodeVersion": "4.3.0",
"_npmOperationalInternal": {
"host": "packages-12-west.internal.npmjs.com",
"tmp": "tmp/ansi-styles-2.2.1.tgz_1459197317833_0.9694824463222176"
},
"_npmUser": {
"email": "sindresorhus@gmail.com",
"name": "sindresorhus"
},
"_npmVersion": "3.8.3",
"_phantomChildren": {},
"_requested": {
"name": "ansi-styles",
"raw": "ansi-styles@^2.2.1",
"rawSpec": "^2.2.1",
"scope": null,
"spec": ">=2.2.1 <3.0.0",
"type": "range"
},
"_requiredBy": [
"/chalk"
],
"_resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-2.2.1.tgz",
"_shasum": "b432dd3358b634cf75e1e4664368240533c1ddbe",
"_shrinkwrap": null,
"_spec": "ansi-styles@^2.2.1",
"_where": "/Users/mromano/dev/react-sfs/node_modules/chalk",
"author": {
"email": "sindresorhus@gmail.com",
"name": "Sindre Sorhus",
"url": "sindresorhus.com"
},
"bugs": {
"url": "https://github.com/chalk/ansi-styles/issues"
},
"dependencies": {},
"description": "ANSI escape codes for styling strings in the terminal",
"devDependencies": {
"mocha": "*"
},
"directories": {},
"dist": {
"shasum": "b432dd3358b634cf75e1e4664368240533c1ddbe",
"tarball": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-2.2.1.tgz"
},
"engines": {
"node": ">=0.10.0"
},
"files": [
"index.js"
],
"gitHead": "95c59b23be760108b6530ca1c89477c21b258032",
"homepage": "https://github.com/chalk/ansi-styles#readme",
"keywords": [
"ansi",
"styles",
"color",
"colour",
"colors",
"terminal",
"console",
"cli",
"string",
"tty",
"escape",
"formatting",
"rgb",
"256",
"shell",
"xterm",
"log",
"logging",
"command-line",
"text"
],
"license": "MIT",
"maintainers": [
{
"email": "sindresorhus@gmail.com",
"name": "sindresorhus"
}
],
"name": "ansi-styles",
"optionalDependencies": {},
"readme": "ERROR: No README data found!",
"repository": {
"type": "git",
"url": "git+https://github.com/chalk/ansi-styles.git"
},
"scripts": {
"test": "mocha"
},
"version": "2.2.1"
}
+86
View File
@@ -0,0 +1,86 @@
# ansi-styles [![Build Status](https://travis-ci.org/chalk/ansi-styles.svg?branch=master)](https://travis-ci.org/chalk/ansi-styles)
> [ANSI escape codes](http://en.wikipedia.org/wiki/ANSI_escape_code#Colors_and_Styles) for styling strings in the terminal
You probably want the higher-level [chalk](https://github.com/chalk/chalk) module for styling your strings.
![](screenshot.png)
## Install
```
$ npm install --save ansi-styles
```
## Usage
```js
var ansi = require('ansi-styles');
console.log(ansi.green.open + 'Hello world!' + ansi.green.close);
```
## API
Each style has an `open` and `close` property.
## Styles
### Modifiers
- `reset`
- `bold`
- `dim`
- `italic` *(not widely supported)*
- `underline`
- `inverse`
- `hidden`
- `strikethrough` *(not widely supported)*
### Colors
- `black`
- `red`
- `green`
- `yellow`
- `blue`
- `magenta`
- `cyan`
- `white`
- `gray`
### Background colors
- `bgBlack`
- `bgRed`
- `bgGreen`
- `bgYellow`
- `bgBlue`
- `bgMagenta`
- `bgCyan`
- `bgWhite`
## Advanced usage
By default you get a map of styles, but the styles are also available as groups. They are non-enumerable so they don't show up unless you access them explicitly. This makes it easier to expose only a subset in a higher-level module.
- `ansi.modifiers`
- `ansi.colors`
- `ansi.bgColors`
###### Example
```js
console.log(ansi.colors.green.open);
```
## License
MIT © [Sindre Sorhus](http://sindresorhus.com)
+3
View File
@@ -0,0 +1,3 @@
src
test
node_modules
+32
View File
@@ -0,0 +1,32 @@
# babel-code-frame
> Generate errors that contain a code frame that point to source locations.
## Install
```sh
$ npm install babel-code-frame
```
## Usage
```js
import codeFrame from 'babel-code-frame';
const rawLines = `class Foo {
constructor()
}`;
const lineNumber = 2;
const colNumber = 16;
const result = codeFrame(rawLines, lineNumber, colNumber, { /* options */ });
console.log(result);
```
```sh
1 | class Foo {
> 2 | constructor()
| ^
3 | }
```
+148
View File
@@ -0,0 +1,148 @@
/* eslint indent: 0 */
/* eslint max-len: 0 */
//import lineNumbers from "line-numbers";
"use strict";
var _interopRequireDefault = require("babel-runtime/helpers/interop-require-default")["default"];
exports.__esModule = true;
var _repeating = require("repeating");
var _repeating2 = _interopRequireDefault(_repeating);
var _jsTokens = require("js-tokens");
var _jsTokens2 = _interopRequireDefault(_jsTokens);
var _esutils = require("esutils");
var _esutils2 = _interopRequireDefault(_esutils);
var _chalk = require("chalk");
var _chalk2 = _interopRequireDefault(_chalk);
function lineNumbers(lines) {
return lines;
}
/**
* Chalk styles for token types.
*/
var defs = {
string: _chalk2["default"].red,
punctuator: _chalk2["default"].bold,
curly: _chalk2["default"].green,
parens: _chalk2["default"].blue.bold,
square: _chalk2["default"].yellow,
keyword: _chalk2["default"].cyan,
number: _chalk2["default"].magenta,
regex: _chalk2["default"].magenta,
comment: _chalk2["default"].grey,
invalid: _chalk2["default"].inverse
};
/**
* RegExp to test for newlines in terminal.
*/
var NEWLINE = /\r\n|[\n\r\u2028\u2029]/;
/**
* Get the type of token, specifying punctuator type.
*/
function getTokenType(match) {
var token = _jsTokens2["default"].matchToToken(match);
if (token.type === "name" && _esutils2["default"].keyword.isReservedWordES6(token.value)) {
return "keyword";
}
if (token.type === "punctuator") {
switch (token.value) {
case "{":
case "}":
return "curly";
case "(":
case ")":
return "parens";
case "[":
case "]":
return "square";
}
}
return token.type;
}
/**
* Highlight `text`.
*/
function highlight(text) {
return text.replace(_jsTokens2["default"], function () {
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
var type = getTokenType(args);
var colorize = defs[type];
if (colorize) {
return args[0].split(NEWLINE).map(function (str) {
return colorize(str);
}).join("\n");
} else {
return args[0];
}
});
}
/**
* Create a code frame, adding line numbers, code highlighting, and pointing to a given position.
*/
exports["default"] = function (rawLines, lineNumber, colNumber) {
var opts = arguments.length <= 3 || arguments[3] === undefined ? {} : arguments[3];
colNumber = Math.max(colNumber, 0);
var highlighted = opts.highlightCode && _chalk2["default"].supportsColor;
if (highlighted) rawLines = highlight(rawLines);
var lines = rawLines.split(NEWLINE);
var start = Math.max(lineNumber - 3, 0);
var end = Math.min(lines.length, lineNumber + 3);
if (!lineNumber && !colNumber) {
start = 0;
end = lines.length;
}
var frame = lineNumbers(lines.slice(start, end), {
start: start + 1,
before: " ",
after: " | ",
transform: function transform(params) {
if (params.number !== lineNumber) {
return;
}
if (colNumber) {
params.line += "\n" + params.before + _repeating2["default"](" ", params.width) + params.after + _repeating2["default"](" ", colNumber - 1) + "^";
}
params.before = params.before.replace(/^./, ">");
}
}).join("\n");
if (highlighted) {
return _chalk2["default"].reset(frame);
} else {
return frame;
}
};
module.exports = exports["default"];
+97
View File
@@ -0,0 +1,97 @@
{
"_args": [
[
"babel-code-frame@^6.7.4",
"/Users/mromano/dev/react-sfs/node_modules/babel-traverse"
]
],
"_from": "babel-code-frame@>=6.7.4 <7.0.0",
"_id": "babel-code-frame@6.7.4",
"_inCache": true,
"_installable": true,
"_location": "/babel-code-frame",
"_nodeVersion": "5.9.0",
"_npmOperationalInternal": {
"host": "packages-13-west.internal.npmjs.com",
"tmp": "tmp/babel-code-frame-6.7.4.tgz_1458704268242_0.11339025967754424"
},
"_npmUser": {
"email": "loganfsmyth@gmail.com",
"name": "loganfsmyth"
},
"_npmVersion": "3.7.3",
"_phantomChildren": {},
"_requested": {
"name": "babel-code-frame",
"raw": "babel-code-frame@^6.7.4",
"rawSpec": "^6.7.4",
"scope": null,
"spec": ">=6.7.4 <7.0.0",
"type": "range"
},
"_requiredBy": [
"/babel-core",
"/babel-traverse"
],
"_resolved": "https://registry.npmjs.org/babel-code-frame/-/babel-code-frame-6.7.4.tgz",
"_shasum": "9ce81b410d696bc59e8261c8e2a59f91d8e126d4",
"_shrinkwrap": null,
"_spec": "babel-code-frame@^6.7.4",
"_where": "/Users/mromano/dev/react-sfs/node_modules/babel-traverse",
"author": {
"email": "sebmck@gmail.com",
"name": "Sebastian McKenzie"
},
"dependencies": {
"babel-runtime": "^5.0.0",
"chalk": "^1.1.0",
"esutils": "^2.0.2",
"js-tokens": "^1.0.1",
"repeating": "^1.1.3"
},
"description": "Generate errors that contain a code frame that point to source locations.",
"devDependencies": {},
"directories": {},
"dist": {
"shasum": "9ce81b410d696bc59e8261c8e2a59f91d8e126d4",
"tarball": "https://registry.npmjs.org/babel-code-frame/-/babel-code-frame-6.7.4.tgz"
},
"homepage": "https://babeljs.io/",
"license": "MIT",
"main": "lib/index.js",
"maintainers": [
{
"email": "amjad.masad@gmail.com",
"name": "amasad"
},
{
"email": "hi@henryzoo.com",
"name": "hzoo"
},
{
"email": "npm-public@jessemccarthy.net",
"name": "jmm"
},
{
"email": "loganfsmyth@gmail.com",
"name": "loganfsmyth"
},
{
"email": "sebmck@gmail.com",
"name": "sebmck"
},
{
"email": "me@thejameskyle.com",
"name": "thejameskyle"
}
],
"name": "babel-code-frame",
"optionalDependencies": {},
"readme": "ERROR: No README data found!",
"repository": {
"type": "git",
"url": "https://github.com/babel/babel/tree/master/packages/babel-code-frame"
},
"scripts": {},
"version": "6.7.4"
}
+24
View File
@@ -0,0 +1,24 @@
# babel-core
> Babel compiler core.
## Install
```
$ npm install babel-core
```
## Usage
```js
import babel from 'babel-core';
const code = `class Example {}`;
const result = babel.transform(code, { /* options */ });
result.code; // Generated code
result.map; // Sourcemap
result.ast; // AST
```
For more in depth documentation see: http://babeljs.io/docs/usage/api/
+1
View File
@@ -0,0 +1 @@
module.exports = require("./lib/api/node.js");
+109
View File
@@ -0,0 +1,109 @@
/* eslint max-len: 0 */
/* eslint no-new-func: 0 */
"use strict";
var _defaults = require("babel-runtime/helpers/defaults")["default"];
var _interopExportWildcard = require("babel-runtime/helpers/interop-export-wildcard")["default"];
exports.__esModule = true;
exports.run = run;
exports.load = load;
var _node = require("./node");
_defaults(exports, _interopExportWildcard(_node, _defaults));
function run(code) {
var opts = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
return new Function(_node.transform(code, opts).code)();
}
function load(url, callback, opts, hold) {
if (opts === undefined) opts = {};
opts.filename = opts.filename || url;
var xhr = global.ActiveXObject ? new global.ActiveXObject("Microsoft.XMLHTTP") : new global.XMLHttpRequest();
xhr.open("GET", url, true);
if ("overrideMimeType" in xhr) xhr.overrideMimeType("text/plain");
xhr.onreadystatechange = function () {
if (xhr.readyState !== 4) return;
var status = xhr.status;
if (status === 0 || status === 200) {
var param = [xhr.responseText, opts];
if (!hold) run(param);
if (callback) callback(param);
} else {
throw new Error("Could not load " + url);
}
};
xhr.send(null);
}
function runScripts() {
var scripts = [];
var types = ["text/ecmascript-6", "text/6to5", "text/babel", "module"];
var index = 0;
/**
* Transform and execute script. Ensures correct load order.
*/
function exec() {
var param = scripts[index];
if (param instanceof Array) {
run(param, index);
index++;
exec();
}
}
/**
* Load, transform, and execute all scripts.
*/
function run(script, i) {
var opts = {};
if (script.src) {
load(script.src, function (param) {
scripts[i] = param;
exec();
}, opts, true);
} else {
opts.filename = "embedded";
scripts[i] = [script.innerHTML, opts];
}
}
// Collect scripts with Babel `types`.
var _scripts = global.document.getElementsByTagName("script");
for (var i = 0; i < _scripts.length; ++i) {
var _script = _scripts[i];
if (types.indexOf(_script.type) >= 0) scripts.push(_script);
}
for (var i = 0; i < scripts.length; i++) {
run(scripts[i], i);
}
exec();
}
/**
* Register load event to transform and execute scripts.
*/
if (global.addEventListener) {
global.addEventListener("DOMContentLoaded", runScripts, false);
} else if (global.attachEvent) {
global.attachEvent("onload", runScripts);
}
+125
View File
@@ -0,0 +1,125 @@
"use strict";
var _interopRequireDefault = require("babel-runtime/helpers/interop-require-default")["default"];
var _interopRequireWildcard = require("babel-runtime/helpers/interop-require-wildcard")["default"];
var _interopRequire = require("babel-runtime/helpers/interop-require")["default"];
exports.__esModule = true;
exports.Plugin = Plugin;
exports.transformFile = transformFile;
exports.transformFileSync = transformFileSync;
var _lodashLangIsFunction = require("lodash/lang/isFunction");
var _lodashLangIsFunction2 = _interopRequireDefault(_lodashLangIsFunction);
var _fs = require("fs");
var _fs2 = _interopRequireDefault(_fs);
//
//
var _util = require("../util");
var util = _interopRequireWildcard(_util);
var _babelMessages = require("babel-messages");
var messages = _interopRequireWildcard(_babelMessages);
var _babelTypes = require("babel-types");
var t = _interopRequireWildcard(_babelTypes);
var _babelTraverse = require("babel-traverse");
var _babelTraverse2 = _interopRequireDefault(_babelTraverse);
var _transformationFileOptionsOptionManager = require("../transformation/file/options/option-manager");
var _transformationFileOptionsOptionManager2 = _interopRequireDefault(_transformationFileOptionsOptionManager);
//
var _transformationPipeline = require("../transformation/pipeline");
var _transformationPipeline2 = _interopRequireDefault(_transformationPipeline);
var _transformationFile = require("../transformation/file");
exports.File = _interopRequire(_transformationFile);
var _transformationFileOptionsConfig = require("../transformation/file/options/config");
exports.options = _interopRequire(_transformationFileOptionsConfig);
var _toolsBuildExternalHelpers = require("../tools/build-external-helpers");
exports.buildExternalHelpers = _interopRequire(_toolsBuildExternalHelpers);
var _babelTemplate = require("babel-template");
exports.template = _interopRequire(_babelTemplate);
var _package = require("../../package");
exports.version = _package.version;
exports.util = util;
exports.messages = messages;
exports.types = t;
exports.traverse = _babelTraverse2["default"];
exports.OptionManager = _transformationFileOptionsOptionManager2["default"];
function Plugin(alias) {
throw new Error("The (" + alias + ") Babel 5 plugin is being run with Babel 6.");
}
exports.Pipeline = _transformationPipeline2["default"];
var pipeline = new _transformationPipeline2["default"]();
var analyse = pipeline.analyse.bind(pipeline);
exports.analyse = analyse;
var transform = pipeline.transform.bind(pipeline);
exports.transform = transform;
var transformFromAst = pipeline.transformFromAst.bind(pipeline);
exports.transformFromAst = transformFromAst;
//
function transformFile(filename, opts, callback) {
if (_lodashLangIsFunction2["default"](opts)) {
callback = opts;
opts = {};
}
opts.filename = filename;
_fs2["default"].readFile(filename, function (err, code) {
var result = undefined;
if (!err) {
try {
result = transform(code, opts);
} catch (_err) {
err = _err;
}
}
if (err) {
callback(err);
} else {
callback(null, result);
}
});
}
function transformFileSync(filename) {
var opts = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
opts.filename = filename;
return transform(_fs2["default"].readFileSync(filename, "utf8"), opts);
}
+44
View File
@@ -0,0 +1,44 @@
"use strict";
var _getIterator = require("babel-runtime/core-js/get-iterator")["default"];
var _interopRequireDefault = require("babel-runtime/helpers/interop-require-default")["default"];
exports.__esModule = true;
var _lodashObjectMerge = require("lodash/object/merge");
var _lodashObjectMerge2 = _interopRequireDefault(_lodashObjectMerge);
exports["default"] = function (dest, src) {
if (!dest || !src) return;
return _lodashObjectMerge2["default"](dest, src, function (a, b) {
if (b && Array.isArray(a)) {
var newArray = b.slice(0);
for (var _iterator = a, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _getIterator(_iterator);;) {
var _ref;
if (_isArray) {
if (_i >= _iterator.length) break;
_ref = _iterator[_i++];
} else {
_i = _iterator.next();
if (_i.done) break;
_ref = _i.value;
}
var item = _ref;
if (newArray.indexOf(item) < 0) {
newArray.push(item);
}
}
return newArray;
}
});
};
module.exports = exports["default"];
+29
View File
@@ -0,0 +1,29 @@
"use strict";
var _interopRequireWildcard = require("babel-runtime/helpers/interop-require-wildcard")["default"];
exports.__esModule = true;
var _babelTypes = require("babel-types");
var t = _interopRequireWildcard(_babelTypes);
/**
* Normalize an AST.
*
* - Wrap `Program` node with a `File` node.
*/
exports["default"] = function (ast, comments, tokens) {
if (ast) {
if (ast.type === "Program") {
return t.file(ast, comments || [], tokens || []);
} else if (ast.type === "File") {
return ast;
}
}
throw new Error("Not a valid ast?");
};
module.exports = exports["default"];
+49
View File
@@ -0,0 +1,49 @@
"use strict";
var _interopRequireDefault = require("babel-runtime/helpers/interop-require-default")["default"];
exports.__esModule = true;
var _module2 = require("module");
var _module3 = _interopRequireDefault(_module2);
var _path = require("path");
var _path2 = _interopRequireDefault(_path);
var relativeModules = {};
exports["default"] = function (loc) {
var relative = arguments.length <= 1 || arguments[1] === undefined ? process.cwd() : arguments[1];
// we're in the browser, probably
if (typeof _module3["default"] === "object") return null;
var relativeMod = relativeModules[relative];
if (!relativeMod) {
relativeMod = new _module3["default"]();
// We need to define an id and filename on our "fake" relative` module so that
// Node knows what "." means in the case of us trying to resolve a plugin
// such as "./myPlugins/somePlugin.js". If we don't specify id and filename here,
// Node presumes "." is process.cwd(), not our relative path.
// Since this fake module is never "loaded", we don't have to worry about mutating
// any global Node module cache state here.
var filename = _path2["default"].join(relative, ".babelrc");
relativeMod.id = filename;
relativeMod.filename = filename;
relativeMod.paths = _module3["default"]._nodeModulePaths(relative);
relativeModules[relative] = relativeMod;
}
try {
return _module3["default"]._resolveFilename(loc, relativeMod);
} catch (err) {
return null;
}
};
module.exports = exports["default"];
+41
View File
@@ -0,0 +1,41 @@
"use strict";
var _inherits = require("babel-runtime/helpers/inherits")["default"];
var _classCallCheck = require("babel-runtime/helpers/class-call-check")["default"];
var _Map2 = require("babel-runtime/core-js/map")["default"];
exports.__esModule = true;
var Store = (function (_Map) {
_inherits(Store, _Map);
function Store() {
_classCallCheck(this, Store);
_Map.call(this);
this.dynamicData = {};
}
Store.prototype.setDynamic = function setDynamic(key, fn) {
this.dynamicData[key] = fn;
};
Store.prototype.get = function get(key) {
if (this.has(key)) {
return _Map.prototype.get.call(this, key);
} else {
if (Object.prototype.hasOwnProperty.call(this.dynamicData, key)) {
var val = this.dynamicData[key]();
this.set(key, val);
return val;
}
}
};
return Store;
})(_Map2);
exports["default"] = Store;
module.exports = exports["default"];
+108
View File
@@ -0,0 +1,108 @@
/* eslint max-len: 0 */
"use strict";
var _interopRequireWildcard = require("babel-runtime/helpers/interop-require-wildcard")["default"];
var _interopRequireDefault = require("babel-runtime/helpers/interop-require-default")["default"];
exports.__esModule = true;
var _babelHelpers = require("babel-helpers");
var helpers = _interopRequireWildcard(_babelHelpers);
var _babelGenerator = require("babel-generator");
var _babelGenerator2 = _interopRequireDefault(_babelGenerator);
var _babelMessages = require("babel-messages");
var messages = _interopRequireWildcard(_babelMessages);
var _babelTemplate = require("babel-template");
var _babelTemplate2 = _interopRequireDefault(_babelTemplate);
var _lodashCollectionEach = require("lodash/collection/each");
var _lodashCollectionEach2 = _interopRequireDefault(_lodashCollectionEach);
var _babelTypes = require("babel-types");
var t = _interopRequireWildcard(_babelTypes);
var buildUmdWrapper = _babelTemplate2["default"]("\n (function (root, factory) {\n if (typeof define === \"function\" && define.amd) {\n define(AMD_ARGUMENTS, factory);\n } else if (typeof exports === \"object\") {\n factory(COMMON_ARGUMENTS);\n } else {\n factory(BROWSER_ARGUMENTS);\n }\n })(UMD_ROOT, function (FACTORY_PARAMETERS) {\n FACTORY_BODY\n });\n");
function buildGlobal(namespace, builder) {
var body = [];
var container = t.functionExpression(null, [t.identifier("global")], t.blockStatement(body));
var tree = t.program([t.expressionStatement(t.callExpression(container, [helpers.get("selfGlobal")]))]);
body.push(t.variableDeclaration("var", [t.variableDeclarator(namespace, t.assignmentExpression("=", t.memberExpression(t.identifier("global"), namespace), t.objectExpression([])))]));
builder(body);
return tree;
}
function buildUmd(namespace, builder) {
var body = [];
body.push(t.variableDeclaration("var", [t.variableDeclarator(namespace, t.identifier("global"))]));
builder(body);
return t.program([buildUmdWrapper({
FACTORY_PARAMETERS: t.identifier("global"),
BROWSER_ARGUMENTS: t.assignmentExpression("=", t.memberExpression(t.identifier("root"), namespace), t.objectExpression([])),
COMMON_ARGUMENTS: t.identifier("exports"),
AMD_ARGUMENTS: t.arrayExpression([t.stringLiteral("exports")]),
FACTORY_BODY: body,
UMD_ROOT: t.identifier("this")
})]);
}
function buildVar(namespace, builder) {
var body = [];
body.push(t.variableDeclaration("var", [t.variableDeclarator(namespace, t.objectExpression([]))]));
builder(body);
body.push(t.expressionStatement(namespace));
return t.program(body);
}
function buildHelpers(body, namespace, whitelist) {
_lodashCollectionEach2["default"](helpers.list, function (name) {
if (whitelist && whitelist.indexOf(name) < 0) return;
var key = t.identifier(name);
body.push(t.expressionStatement(t.assignmentExpression("=", t.memberExpression(namespace, key), helpers.get(name))));
});
}
exports["default"] = function (whitelist) {
var outputType = arguments.length <= 1 || arguments[1] === undefined ? "global" : arguments[1];
var namespace = t.identifier("babelHelpers");
var builder = function builder(body) {
return buildHelpers(body, namespace, whitelist);
};
var tree = undefined;
var build = ({
global: buildGlobal,
umd: buildUmd,
"var": buildVar
})[outputType];
if (build) {
tree = build(namespace, builder);
} else {
throw new Error(messages.get("unsupportedOutputType", outputType));
}
return _babelGenerator2["default"](tree).code;
};
module.exports = exports["default"];
+677
View File
@@ -0,0 +1,677 @@
/* global BabelFileResult, BabelParserOptions, BabelFileMetadata */
/* eslint max-len: 0 */
"use strict";
var _inherits = require("babel-runtime/helpers/inherits")["default"];
var _classCallCheck = require("babel-runtime/helpers/class-call-check")["default"];
var _Object$assign = require("babel-runtime/core-js/object/assign")["default"];
var _Object$create = require("babel-runtime/core-js/object/create")["default"];
var _interopRequireDefault = require("babel-runtime/helpers/interop-require-default")["default"];
var _interopRequireWildcard = require("babel-runtime/helpers/interop-require-wildcard")["default"];
exports.__esModule = true;
var _babelHelpers = require("babel-helpers");
var _babelHelpers2 = _interopRequireDefault(_babelHelpers);
var _metadata = require("./metadata");
var metadataVisitor = _interopRequireWildcard(_metadata);
var _convertSourceMap = require("convert-source-map");
var _convertSourceMap2 = _interopRequireDefault(_convertSourceMap);
var _optionsOptionManager = require("./options/option-manager");
var _optionsOptionManager2 = _interopRequireDefault(_optionsOptionManager);
var _pluginPass = require("../plugin-pass");
var _pluginPass2 = _interopRequireDefault(_pluginPass);
var _shebangRegex = require("shebang-regex");
var _shebangRegex2 = _interopRequireDefault(_shebangRegex);
var _babelTraverse = require("babel-traverse");
var _sourceMap = require("source-map");
var _sourceMap2 = _interopRequireDefault(_sourceMap);
var _babelGenerator = require("babel-generator");
var _babelGenerator2 = _interopRequireDefault(_babelGenerator);
var _babelCodeFrame = require("babel-code-frame");
var _babelCodeFrame2 = _interopRequireDefault(_babelCodeFrame);
var _lodashObjectDefaults = require("lodash/object/defaults");
var _lodashObjectDefaults2 = _interopRequireDefault(_lodashObjectDefaults);
var _babelTraverse2 = _interopRequireDefault(_babelTraverse);
var _logger = require("./logger");
var _logger2 = _interopRequireDefault(_logger);
var _store = require("../../store");
var _store2 = _interopRequireDefault(_store);
var _babylon = require("babylon");
var _util = require("../../util");
var util = _interopRequireWildcard(_util);
var _path = require("path");
var _path2 = _interopRequireDefault(_path);
var _babelTypes = require("babel-types");
var t = _interopRequireWildcard(_babelTypes);
var _internalPluginsBlockHoist = require("../internal-plugins/block-hoist");
var _internalPluginsBlockHoist2 = _interopRequireDefault(_internalPluginsBlockHoist);
var _internalPluginsShadowFunctions = require("../internal-plugins/shadow-functions");
var _internalPluginsShadowFunctions2 = _interopRequireDefault(_internalPluginsShadowFunctions);
var INTERNAL_PLUGINS = [[_internalPluginsBlockHoist2["default"]], [_internalPluginsShadowFunctions2["default"]]];
var errorVisitor = {
enter: function enter(path, state) {
var loc = path.node.loc;
if (loc) {
state.loc = loc;
path.stop();
}
}
};
var File = (function (_Store) {
_inherits(File, _Store);
function File(opts, pipeline) {
// istanbul ignore next
var _this = this;
if (opts === undefined) opts = {};
_classCallCheck(this, File);
_Store.call(this);
this.pipeline = pipeline;
this.log = new _logger2["default"](this, opts.filename || "unknown");
this.opts = this.initOptions(opts);
this.parserOpts = {
highlightCode: this.opts.highlightCode,
nonStandard: this.opts.nonStandard,
sourceType: this.opts.sourceType,
filename: this.opts.filename,
plugins: []
};
this.pluginVisitors = [];
this.pluginPasses = [];
// Plugins for top-level options.
this.buildPluginsForOptions(this.opts);
// If we are in the "pass per preset" mode, build
// also plugins for each preset.
if (this.opts.passPerPreset) {
// All the "per preset" options are inherited from the main options.
this.perPresetOpts = [];
this.opts.presets.forEach(function (presetOpts) {
var perPresetOpts = _Object$assign(_Object$create(_this.opts), presetOpts);
_this.perPresetOpts.push(perPresetOpts);
_this.buildPluginsForOptions(perPresetOpts);
});
}
this.metadata = {
usedHelpers: [],
marked: [],
modules: {
imports: [],
exports: {
exported: [],
specifiers: []
}
}
};
this.dynamicImportTypes = {};
this.dynamicImportIds = {};
this.dynamicImports = [];
this.declarations = {};
this.usedHelpers = {};
this.path = null;
this.ast = {};
this.code = "";
this.shebang = "";
this.hub = new _babelTraverse.Hub(this);
}
File.prototype.getMetadata = function getMetadata() {
var has = false;
var _arr = this.ast.program.body;
for (var _i = 0; _i < _arr.length; _i++) {
var node = _arr[_i];
if (t.isModuleDeclaration(node)) {
has = true;
break;
}
}
if (has) {
this.path.traverse(metadataVisitor, this);
}
};
File.prototype.initOptions = function initOptions(opts) {
opts = new _optionsOptionManager2["default"](this.log, this.pipeline).init(opts);
if (opts.inputSourceMap) {
opts.sourceMaps = true;
}
if (opts.moduleId) {
opts.moduleIds = true;
}
opts.basename = _path2["default"].basename(opts.filename, _path2["default"].extname(opts.filename));
opts.ignore = util.arrayify(opts.ignore, util.regexify);
if (opts.only) opts.only = util.arrayify(opts.only, util.regexify);
_lodashObjectDefaults2["default"](opts, {
moduleRoot: opts.sourceRoot
});
_lodashObjectDefaults2["default"](opts, {
sourceRoot: opts.moduleRoot
});
_lodashObjectDefaults2["default"](opts, {
filenameRelative: opts.filename
});
var basenameRelative = _path2["default"].basename(opts.filenameRelative);
_lodashObjectDefaults2["default"](opts, {
sourceFileName: basenameRelative,
sourceMapTarget: basenameRelative
});
return opts;
};
File.prototype.buildPluginsForOptions = function buildPluginsForOptions(opts) {
if (!Array.isArray(opts.plugins)) {
return;
}
var plugins = opts.plugins.concat(INTERNAL_PLUGINS);
var currentPluginVisitors = [];
var currentPluginPasses = [];
// init plugins!
for (var _i2 = 0; _i2 < plugins.length; _i2++) {
var ref = plugins[_i2];var plugin = ref[0];
var pluginOpts = ref[1];
// todo: fix - can't embed in loop head because of flow bug
currentPluginVisitors.push(plugin.visitor);
currentPluginPasses.push(new _pluginPass2["default"](this, plugin, pluginOpts));
if (plugin.manipulateOptions) {
plugin.manipulateOptions(opts, this.parserOpts, this);
}
}
this.pluginVisitors.push(currentPluginVisitors);
this.pluginPasses.push(currentPluginPasses);
};
File.prototype.getModuleName = function getModuleName() {
var opts = this.opts;
if (!opts.moduleIds) {
return null;
}
// moduleId is n/a if a `getModuleId()` is provided
if (opts.moduleId != null && !opts.getModuleId) {
return opts.moduleId;
}
var filenameRelative = opts.filenameRelative;
var moduleName = "";
if (opts.moduleRoot != null) {
moduleName = opts.moduleRoot + "/";
}
if (!opts.filenameRelative) {
return moduleName + opts.filename.replace(/^\//, "");
}
if (opts.sourceRoot != null) {
// remove sourceRoot from filename
var sourceRootRegEx = new RegExp("^" + opts.sourceRoot + "\/?");
filenameRelative = filenameRelative.replace(sourceRootRegEx, "");
}
// remove extension
filenameRelative = filenameRelative.replace(/\.(\w*?)$/, "");
moduleName += filenameRelative;
// normalize path separators
moduleName = moduleName.replace(/\\/g, "/");
if (opts.getModuleId) {
// If return is falsy, assume they want us to use our generated default name
return opts.getModuleId(moduleName) || moduleName;
} else {
return moduleName;
}
};
File.prototype.resolveModuleSource = function resolveModuleSource(source) {
var resolveModuleSource = this.opts.resolveModuleSource;
if (resolveModuleSource) source = resolveModuleSource(source, this.opts.filename);
return source;
};
File.prototype.addImport = function addImport(source, imported) {
var name = arguments.length <= 2 || arguments[2] === undefined ? imported : arguments[2];
return (function () {
var alias = source + ":" + imported;
var id = this.dynamicImportIds[alias];
if (!id) {
source = this.resolveModuleSource(source);
id = this.dynamicImportIds[alias] = this.scope.generateUidIdentifier(name);
var specifiers = [];
if (imported === "*") {
specifiers.push(t.importNamespaceSpecifier(id));
} else if (imported === "default") {
specifiers.push(t.importDefaultSpecifier(id));
} else {
specifiers.push(t.importSpecifier(id, t.identifier(imported)));
}
var declar = t.importDeclaration(specifiers, t.stringLiteral(source));
declar._blockHoist = 3;
this.path.unshiftContainer("body", declar);
}
return id;
}).apply(this, arguments);
};
File.prototype.addHelper = function addHelper(name) {
var declar = this.declarations[name];
if (declar) return declar;
if (!this.usedHelpers[name]) {
this.metadata.usedHelpers.push(name);
this.usedHelpers[name] = true;
}
var generator = this.get("helperGenerator");
var runtime = this.get("helpersNamespace");
if (generator) {
var res = generator(name);
if (res) return res;
} else if (runtime) {
return t.memberExpression(runtime, t.identifier(name));
}
var ref = _babelHelpers2["default"](name);
var uid = this.declarations[name] = this.scope.generateUidIdentifier(name);
if (t.isFunctionExpression(ref) && !ref.id) {
ref.body._compact = true;
ref._generated = true;
ref.id = uid;
ref.type = "FunctionDeclaration";
this.path.unshiftContainer("body", ref);
} else {
ref._compact = true;
this.scope.push({
id: uid,
init: ref,
unique: true
});
}
return uid;
};
File.prototype.addTemplateObject = function addTemplateObject(helperName, strings, raw) {
// Generate a unique name based on the string literals so we dedupe
// identical strings used in the program.
var stringIds = raw.elements.map(function (string) {
return string.value;
});
var name = helperName + "_" + raw.elements.length + "_" + stringIds.join(",");
var declar = this.declarations[name];
if (declar) return declar;
var uid = this.declarations[name] = this.scope.generateUidIdentifier("templateObject");
var helperId = this.addHelper(helperName);
var init = t.callExpression(helperId, [strings, raw]);
init._compact = true;
this.scope.push({
id: uid,
init: init,
_blockHoist: 1.9 // This ensures that we don't fail if not using function expression helpers
});
return uid;
};
File.prototype.buildCodeFrameError = function buildCodeFrameError(node, msg) {
var Error = arguments.length <= 2 || arguments[2] === undefined ? SyntaxError : arguments[2];
var loc = node && (node.loc || node._loc);
var err = new Error(msg);
if (loc) {
err.loc = loc.start;
} else {
_babelTraverse2["default"](node, errorVisitor, this.scope, err);
err.message += " (This is an error on an internal node. Probably an internal error";
if (err.loc) {
err.message += ". Location has been estimated.";
}
err.message += ")";
}
return err;
};
File.prototype.mergeSourceMap = function mergeSourceMap(map) {
var inputMap = this.opts.inputSourceMap;
if (inputMap) {
var _ret = (function () {
var inputMapConsumer = new _sourceMap2["default"].SourceMapConsumer(inputMap);
var outputMapConsumer = new _sourceMap2["default"].SourceMapConsumer(map);
var mergedGenerator = new _sourceMap2["default"].SourceMapGenerator({
file: inputMapConsumer.file,
sourceRoot: inputMapConsumer.sourceRoot
});
// This assumes the output map always has a single source, since Babel always compiles a single source file to a
// single output file.
var source = outputMapConsumer.sources[0];
inputMapConsumer.eachMapping(function (mapping) {
var generatedPosition = outputMapConsumer.generatedPositionFor({
line: mapping.generatedLine,
column: mapping.generatedColumn,
source: source
});
if (generatedPosition.column != null) {
mergedGenerator.addMapping({
source: mapping.source,
original: {
line: mapping.originalLine,
column: mapping.originalColumn
},
generated: generatedPosition
});
}
});
var mergedMap = mergedGenerator.toJSON();
inputMap.mappings = mergedMap.mappings;
return {
v: inputMap
};
})();
// istanbul ignore next
if (typeof _ret === "object") return _ret.v;
} else {
return map;
}
};
File.prototype.parse = function parse(code) {
this.log.debug("Parse start");
var ast = _babylon.parse(code, this.parserOpts);
this.log.debug("Parse stop");
return ast;
};
File.prototype._addAst = function _addAst(ast) {
this.path = _babelTraverse.NodePath.get({
hub: this.hub,
parentPath: null,
parent: ast,
container: ast,
key: "program"
}).setContext();
this.scope = this.path.scope;
this.ast = ast;
this.getMetadata();
};
File.prototype.addAst = function addAst(ast) {
this.log.debug("Start set AST");
this._addAst(ast);
this.log.debug("End set AST");
};
File.prototype.transform = function transform() {
// istanbul ignore next
var _this2 = this;
// In the "pass per preset" mode, we have grouped passes.
// Otherwise, there is only one plain pluginPasses array.
this.pluginPasses.forEach(function (pluginPasses, index) {
_this2.call("pre", pluginPasses);
_this2.log.debug("Start transform traverse");
_babelTraverse2["default"](_this2.ast, _babelTraverse2["default"].visitors.merge(_this2.pluginVisitors[index], pluginPasses), _this2.scope);
_this2.log.debug("End transform traverse");
_this2.call("post", pluginPasses);
});
return this.generate();
};
File.prototype.wrap = function wrap(code, callback) {
code = code + "";
try {
if (this.shouldIgnore()) {
return this.makeResult({ code: code, ignored: true });
} else {
return callback();
}
} catch (err) {
if (err._babel) {
throw err;
} else {
err._babel = true;
}
var message = err.message = this.opts.filename + ": " + err.message;
var loc = err.loc;
if (loc) {
err.codeFrame = _babelCodeFrame2["default"](code, loc.line, loc.column + 1, this.opts);
message += "\n" + err.codeFrame;
}
if (process.browser) {
// chrome has it's own pretty stringifier which doesn't use the stack property
// https://github.com/babel/babel/issues/2175
err.message = message;
}
if (err.stack) {
var newStack = err.stack.replace(err.message, message);
err.stack = newStack;
}
throw err;
}
};
File.prototype.addCode = function addCode(code) {
code = (code || "") + "";
code = this.parseInputSourceMap(code);
this.code = code;
};
File.prototype.parseCode = function parseCode() {
this.parseShebang();
var ast = this.parse(this.code);
this.addAst(ast);
};
File.prototype.shouldIgnore = function shouldIgnore() {
var opts = this.opts;
return util.shouldIgnore(opts.filename, opts.ignore, opts.only);
};
File.prototype.call = function call(key, pluginPasses) {
for (var _i3 = 0; _i3 < pluginPasses.length; _i3++) {
var pass = pluginPasses[_i3];
var plugin = pass.plugin;
var fn = plugin[key];
if (fn) fn.call(pass, this);
}
};
File.prototype.parseInputSourceMap = function parseInputSourceMap(code) {
var opts = this.opts;
if (opts.inputSourceMap !== false) {
var inputMap = _convertSourceMap2["default"].fromSource(code);
if (inputMap) {
opts.inputSourceMap = inputMap.toObject();
code = _convertSourceMap2["default"].removeComments(code);
}
}
return code;
};
File.prototype.parseShebang = function parseShebang() {
var shebangMatch = _shebangRegex2["default"].exec(this.code);
if (shebangMatch) {
this.shebang = shebangMatch[0];
this.code = this.code.replace(_shebangRegex2["default"], "");
}
};
File.prototype.makeResult = function makeResult(_ref) {
var code = _ref.code;
var map = _ref.map;
var ast = _ref.ast;
var ignored = _ref.ignored;
var result = {
metadata: null,
options: this.opts,
ignored: !!ignored,
code: null,
ast: null,
map: map || null
};
if (this.opts.code) {
result.code = code;
}
if (this.opts.ast) {
result.ast = ast;
}
if (this.opts.metadata) {
result.metadata = this.metadata;
}
return result;
};
File.prototype.generate = function generate() {
var opts = this.opts;
var ast = this.ast;
var result = { ast: ast };
if (!opts.code) return this.makeResult(result);
this.log.debug("Generation start");
var _result = _babelGenerator2["default"](ast, opts, this.code);
result.code = _result.code;
result.map = _result.map;
this.log.debug("Generation end");
if (this.shebang) {
// add back shebang
result.code = this.shebang + "\n" + result.code;
}
if (result.map) {
result.map = this.mergeSourceMap(result.map);
}
if (opts.sourceMaps === "inline" || opts.sourceMaps === "both") {
result.code += "\n" + _convertSourceMap2["default"].fromObject(result.map).toComment();
}
if (opts.sourceMaps === "inline") {
result.map = null;
}
return this.makeResult(result);
};
return File;
})(_store2["default"]);
exports["default"] = File;
exports.File = File;
+72
View File
@@ -0,0 +1,72 @@
"use strict";
var _classCallCheck = require("babel-runtime/helpers/class-call-check")["default"];
var _interopRequireDefault = require("babel-runtime/helpers/interop-require-default")["default"];
exports.__esModule = true;
var _debugNode = require("debug/node");
var _debugNode2 = _interopRequireDefault(_debugNode);
var verboseDebug = _debugNode2["default"]("babel:verbose");
var generalDebug = _debugNode2["default"]("babel");
var seenDeprecatedMessages = [];
var Logger = (function () {
function Logger(file, filename) {
_classCallCheck(this, Logger);
this.filename = filename;
this.file = file;
}
Logger.prototype._buildMessage = function _buildMessage(msg) {
var parts = "[BABEL] " + this.filename;
if (msg) parts += ": " + msg;
return parts;
};
Logger.prototype.warn = function warn(msg) {
console.warn(this._buildMessage(msg));
};
Logger.prototype.error = function error(msg) {
var Constructor = arguments.length <= 1 || arguments[1] === undefined ? Error : arguments[1];
throw new Constructor(this._buildMessage(msg));
};
Logger.prototype.deprecate = function deprecate(msg) {
if (this.file.opts && this.file.opts.suppressDeprecationMessages) return;
msg = this._buildMessage(msg);
// already seen this message
if (seenDeprecatedMessages.indexOf(msg) >= 0) return;
// make sure we don't see it again
seenDeprecatedMessages.push(msg);
console.error(msg);
};
Logger.prototype.verbose = function verbose(msg) {
if (verboseDebug.enabled) verboseDebug(this._buildMessage(msg));
};
Logger.prototype.debug = function debug(msg) {
if (generalDebug.enabled) generalDebug(this._buildMessage(msg));
};
Logger.prototype.deopt = function deopt(node, msg) {
this.debug(msg);
};
return Logger;
})();
exports["default"] = Logger;
module.exports = exports["default"];
+160
View File
@@ -0,0 +1,160 @@
"use strict";
var _interopRequireWildcard = require("babel-runtime/helpers/interop-require-wildcard")["default"];
exports.__esModule = true;
exports.ExportDeclaration = ExportDeclaration;
exports.Scope = Scope;
var _babelTypes = require("babel-types");
var t = _interopRequireWildcard(_babelTypes);
var ModuleDeclaration = {
enter: function enter(path, file) {
var node = path.node;
if (node.source) {
node.source.value = file.resolveModuleSource(node.source.value);
}
}
};
exports.ModuleDeclaration = ModuleDeclaration;
var ImportDeclaration = {
exit: function exit(path, file) {
var node = path.node;
var specifiers = [];
var imported = [];
file.metadata.modules.imports.push({
source: node.source.value,
imported: imported,
specifiers: specifiers
});
var _arr = path.get("specifiers");
for (var _i = 0; _i < _arr.length; _i++) {
var specifier = _arr[_i];
var local = specifier.node.local.name;
if (specifier.isImportDefaultSpecifier()) {
imported.push("default");
specifiers.push({
kind: "named",
imported: "default",
local: local
});
}
if (specifier.isImportSpecifier()) {
var importedName = specifier.node.imported.name;
imported.push(importedName);
specifiers.push({
kind: "named",
imported: importedName,
local: local
});
}
if (specifier.isImportNamespaceSpecifier()) {
imported.push("*");
specifiers.push({
kind: "namespace",
local: local
});
}
}
}
};
exports.ImportDeclaration = ImportDeclaration;
function ExportDeclaration(path, file) {
var node = path.node;
var source = node.source ? node.source.value : null;
var exports = file.metadata.modules.exports;
// export function foo() {}
// export let foo = "bar";
var declar = path.get("declaration");
if (declar.isStatement()) {
var bindings = declar.getBindingIdentifiers();
for (var _name in bindings) {
exports.exported.push(_name);
exports.specifiers.push({
kind: "local",
local: _name,
exported: path.isExportDefaultDeclaration() ? "default" : _name
});
}
}
if (path.isExportNamedDeclaration() && node.specifiers) {
var _arr2 = node.specifiers;
for (var _i2 = 0; _i2 < _arr2.length; _i2++) {
var specifier = _arr2[_i2];
var exported = specifier.exported.name;
exports.exported.push(exported);
// export foo from "bar";
if (t.isExportDefaultSpecifier(specifier)) {
exports.specifiers.push({
kind: "external",
local: exported,
exported: exported,
source: source
});
}
// export * as foo from "bar";
if (t.isExportNamespaceSpecifier(specifier)) {
exports.specifiers.push({
kind: "external-namespace",
exported: exported,
source: source
});
}
var local = specifier.local;
if (!local) continue;
// export { foo } from "bar";
// export { foo as bar } from "bar";
if (source) {
exports.specifiers.push({
kind: "external",
local: local.name,
exported: exported,
source: source
});
}
// export { foo };
// export { foo as bar };
if (!source) {
exports.specifiers.push({
kind: "local",
local: local.name,
exported: exported
});
}
}
}
// export * from "bar";
if (path.isExportAllDeclaration()) {
exports.specifiers.push({
kind: "external-all",
source: source
});
}
}
function Scope(path) {
path.skip();
}
@@ -0,0 +1,198 @@
/* eslint max-len: 0 */
"use strict";
module.exports = {
filename: {
type: "filename",
description: "filename to use when reading from stdin - this will be used in source-maps, errors etc",
"default": "unknown",
shorthand: "f"
},
filenameRelative: {
hidden: true,
type: "string"
},
inputSourceMap: {
hidden: true
},
env: {
hidden: true,
"default": {}
},
mode: {
description: "",
hidden: true
},
retainLines: {
type: "boolean",
"default": false,
description: "retain line numbers - will result in really ugly code"
},
highlightCode: {
description: "enable/disable ANSI syntax highlighting of code frames (on by default)",
type: "boolean",
"default": true
},
suppressDeprecationMessages: {
type: "boolean",
"default": false,
hidden: true
},
presets: {
type: "list",
description: "",
"default": []
},
plugins: {
type: "list",
"default": [],
description: ""
},
ignore: {
type: "list",
description: "list of glob paths to **not** compile",
"default": []
},
only: {
type: "list",
description: "list of glob paths to **only** compile"
},
code: {
hidden: true,
"default": true,
type: "boolean"
},
metadata: {
hidden: true,
"default": true,
type: "boolean"
},
ast: {
hidden: true,
"default": true,
type: "boolean"
},
"extends": {
type: "string",
hidden: true
},
comments: {
type: "boolean",
"default": true,
description: "write comments to generated output (true by default)"
},
shouldPrintComment: {
hidden: true,
description: "optional callback to control whether a comment should be inserted, when this is used the comments option is ignored"
},
compact: {
type: "booleanString",
"default": "auto",
description: "do not include superfluous whitespace characters and line terminators [true|false|auto]"
},
minified: {
type: "boolean",
"default": false,
description: "save as much bytes when printing [true|false]"
},
sourceMap: {
alias: "sourceMaps",
hidden: true
},
sourceMaps: {
type: "booleanString",
description: "[true|false|inline]",
"default": false,
shorthand: "s"
},
sourceMapTarget: {
type: "string",
description: "set `file` on returned source map"
},
sourceFileName: {
type: "string",
description: "set `sources[0]` on returned source map"
},
sourceRoot: {
type: "filename",
description: "the root from which all sources are relative"
},
babelrc: {
description: "Whether or not to look up .babelrc and .babelignore files",
type: "boolean",
"default": true
},
sourceType: {
description: "",
"default": "module"
},
auxiliaryCommentBefore: {
type: "string",
description: "print a comment before any injected non-user code"
},
auxiliaryCommentAfter: {
type: "string",
description: "print a comment after any injected non-user code"
},
resolveModuleSource: {
hidden: true
},
getModuleId: {
hidden: true
},
moduleRoot: {
type: "filename",
description: "optional prefix for the AMD module formatter that will be prepend to the filename on module definitions"
},
moduleIds: {
type: "boolean",
"default": false,
shorthand: "M",
description: "insert an explicit id for modules"
},
moduleId: {
description: "specify a custom name for module ids",
type: "string"
},
passPerPreset: {
description: "Whether to spawn a traversal pass per a preset. By default all presets are merged.",
type: "boolean",
"default": false,
hidden: true
}
};
@@ -0,0 +1,38 @@
"use strict";
var _interopRequireWildcard = require("babel-runtime/helpers/interop-require-wildcard")["default"];
var _interopRequireDefault = require("babel-runtime/helpers/interop-require-default")["default"];
exports.__esModule = true;
exports.normaliseOptions = normaliseOptions;
var _parsers = require("./parsers");
var parsers = _interopRequireWildcard(_parsers);
var _config = require("./config");
var _config2 = _interopRequireDefault(_config);
exports.config = _config2["default"];
function normaliseOptions() {
var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
for (var key in options) {
var val = options[key];
if (val == null) continue;
var opt = _config2["default"][key];
if (opt && opt.alias) opt = _config2["default"][opt.alias];
if (!opt) continue;
var parser = parsers[opt.type];
if (parser) val = parser(val);
options[key] = val;
}
return options;
}
@@ -0,0 +1,483 @@
/* eslint max-len: 0 */
"use strict";
var _classCallCheck = require("babel-runtime/helpers/class-call-check")["default"];
var _Object$assign = require("babel-runtime/core-js/object/assign")["default"];
var _interopRequireWildcard = require("babel-runtime/helpers/interop-require-wildcard")["default"];
var _interopRequireDefault = require("babel-runtime/helpers/interop-require-default")["default"];
exports.__esModule = true;
var _apiNode = require("../../../api/node");
var context = _interopRequireWildcard(_apiNode);
var _plugin2 = require("../../plugin");
var _plugin3 = _interopRequireDefault(_plugin2);
var _babelMessages = require("babel-messages");
var messages = _interopRequireWildcard(_babelMessages);
var _index = require("./index");
var _helpersResolve = require("../../../helpers/resolve");
var _helpersResolve2 = _interopRequireDefault(_helpersResolve);
var _json5 = require("json5");
var _json52 = _interopRequireDefault(_json5);
var _pathIsAbsolute = require("path-is-absolute");
var _pathIsAbsolute2 = _interopRequireDefault(_pathIsAbsolute);
var _pathExists = require("path-exists");
var _pathExists2 = _interopRequireDefault(_pathExists);
var _lodashLangCloneDeep = require("lodash/lang/cloneDeep");
var _lodashLangCloneDeep2 = _interopRequireDefault(_lodashLangCloneDeep);
var _lodashLangClone = require("lodash/lang/clone");
var _lodashLangClone2 = _interopRequireDefault(_lodashLangClone);
var _helpersMerge = require("../../../helpers/merge");
var _helpersMerge2 = _interopRequireDefault(_helpersMerge);
var _config = require("./config");
var _config2 = _interopRequireDefault(_config);
var _removed = require("./removed");
var _removed2 = _interopRequireDefault(_removed);
var _path = require("path");
var _path2 = _interopRequireDefault(_path);
var _fs = require("fs");
var _fs2 = _interopRequireDefault(_fs);
var existsCache = {};
var jsonCache = {};
var BABELIGNORE_FILENAME = ".babelignore";
var BABELRC_FILENAME = ".babelrc";
var PACKAGE_FILENAME = "package.json";
function exists(filename) {
var cached = existsCache[filename];
if (cached == null) {
return existsCache[filename] = _pathExists2["default"].sync(filename);
} else {
return cached;
}
}
var OptionManager = (function () {
function OptionManager(log) {
_classCallCheck(this, OptionManager);
this.resolvedConfigs = [];
this.options = OptionManager.createBareOptions();
this.log = log;
}
OptionManager.memoisePluginContainer = function memoisePluginContainer(fn, loc, i, alias) {
var _arr = OptionManager.memoisedPlugins;
for (var _i = 0; _i < _arr.length; _i++) {
var cache = _arr[_i];
if (cache.container === fn) return cache.plugin;
}
var obj = undefined;
if (typeof fn === "function") {
obj = fn(context);
} else {
obj = fn;
}
if (typeof obj === "object") {
var _plugin = new _plugin3["default"](obj, alias);
OptionManager.memoisedPlugins.push({
container: fn,
plugin: _plugin
});
return _plugin;
} else {
throw new TypeError(messages.get("pluginNotObject", loc, i, typeof obj) + loc + i);
}
};
OptionManager.createBareOptions = function createBareOptions() {
var opts = {};
for (var _key in _config2["default"]) {
var opt = _config2["default"][_key];
opts[_key] = _lodashLangClone2["default"](opt["default"]);
}
return opts;
};
OptionManager.normalisePlugin = function normalisePlugin(plugin, loc, i, alias) {
plugin = plugin.__esModule ? plugin["default"] : plugin;
if (!(plugin instanceof _plugin3["default"])) {
// allow plugin containers to be specified so they don't have to manually require
if (typeof plugin === "function" || typeof plugin === "object") {
plugin = OptionManager.memoisePluginContainer(plugin, loc, i, alias);
} else {
throw new TypeError(messages.get("pluginNotFunction", loc, i, typeof plugin));
}
}
plugin.init(loc, i);
return plugin;
};
OptionManager.normalisePlugins = function normalisePlugins(loc, dirname, plugins) {
return plugins.map(function (val, i) {
var plugin = undefined,
options = undefined;
if (!val) {
throw new TypeError("Falsy value found in plugins");
}
// destructure plugins
if (Array.isArray(val)) {
plugin = val[0];
options = val[1];
} else {
plugin = val;
}
var alias = typeof plugin === "string" ? plugin : loc + "$" + i;
// allow plugins to be specified as strings
if (typeof plugin === "string") {
var pluginLoc = _helpersResolve2["default"]("babel-plugin-" + plugin, dirname) || _helpersResolve2["default"](plugin, dirname);
if (pluginLoc) {
plugin = require(pluginLoc);
} else {
throw new ReferenceError(messages.get("pluginUnknown", plugin, loc, i, dirname));
}
}
plugin = OptionManager.normalisePlugin(plugin, loc, i, alias);
return [plugin, options];
});
};
OptionManager.prototype.addConfig = function addConfig(loc, key) {
var json = arguments.length <= 2 || arguments[2] === undefined ? _json52["default"] : arguments[2];
if (this.resolvedConfigs.indexOf(loc) >= 0) {
return false;
}
var content = _fs2["default"].readFileSync(loc, "utf8");
var opts = undefined;
try {
opts = jsonCache[content] = jsonCache[content] || json.parse(content);
if (key) opts = opts[key];
} catch (err) {
err.message = loc + ": Error while parsing JSON - " + err.message;
throw err;
}
this.mergeOptions({
options: opts,
alias: loc,
dirname: _path2["default"].dirname(loc)
});
this.resolvedConfigs.push(loc);
return !!opts;
};
/**
* This is called when we want to merge the input `opts` into the
* base options (passed as the `extendingOpts`: at top-level it's the
* main options, at presets level it's presets options).
*
* - `alias` is used to output pretty traces back to the original source.
* - `loc` is used to point to the original config.
* - `dirname` is used to resolve plugins relative to it.
*/
OptionManager.prototype.mergeOptions = function mergeOptions(_ref) {
// istanbul ignore next
var _this = this;
var rawOpts = _ref.options;
var extendingOpts = _ref.extending;
var alias = _ref.alias;
var loc = _ref.loc;
var dirname = _ref.dirname;
alias = alias || "foreign";
if (!rawOpts) return;
//
if (typeof rawOpts !== "object" || Array.isArray(rawOpts)) {
this.log.error("Invalid options type for " + alias, TypeError);
}
//
var opts = _lodashLangCloneDeep2["default"](rawOpts, function (val) {
if (val instanceof _plugin3["default"]) {
return val;
}
});
//
dirname = dirname || process.cwd();
loc = loc || alias;
for (var _key2 in opts) {
var option = _config2["default"][_key2];
// check for an unknown option
if (!option && this.log) {
var pluginOptsInfo = "Check out http://babeljs.io/docs/usage/options/ for more info";
if (_removed2["default"][_key2]) {
this.log.error("Using removed Babel 5 option: " + alias + "." + _key2 + " - " + _removed2["default"][_key2].message, ReferenceError);
} else {
this.log.error("Unknown option: " + alias + "." + _key2 + ". " + pluginOptsInfo, ReferenceError);
}
}
}
// normalise options
_index.normaliseOptions(opts);
// resolve plugins
if (opts.plugins) {
opts.plugins = OptionManager.normalisePlugins(loc, dirname, opts.plugins);
}
// add extends clause
if (opts["extends"]) {
var extendsLoc = _helpersResolve2["default"](opts["extends"], dirname);
if (extendsLoc) {
this.addConfig(extendsLoc);
} else {
if (this.log) this.log.error("Couldn't resolve extends clause of " + opts["extends"] + " in " + alias);
}
delete opts["extends"];
}
// resolve presets
if (opts.presets) {
// If we're in the "pass per preset" mode, we resolve the presets
// and keep them for further execution to calculate the options.
if (opts.passPerPreset) {
opts.presets = this.resolvePresets(opts.presets, dirname, function (preset, presetLoc) {
_this.mergeOptions({
options: preset,
extending: preset,
alias: presetLoc,
loc: presetLoc,
dirname: dirname
});
});
} else {
// Otherwise, just merge presets options into the main options.
this.mergePresets(opts.presets, dirname);
delete opts.presets;
}
}
// env
var envOpts = undefined;
var envKey = process.env.BABEL_ENV || process.env.NODE_ENV || "development";
if (opts.env) {
envOpts = opts.env[envKey];
delete opts.env;
}
// Merge them into current extending options in case of top-level
// options. In case of presets, just re-assign options which are got
// normalized during the `mergeOptions`.
if (rawOpts === extendingOpts) {
_Object$assign(extendingOpts, opts);
} else {
_helpersMerge2["default"](extendingOpts || this.options, opts);
}
// merge in env options
this.mergeOptions({
options: envOpts,
extending: extendingOpts,
alias: alias + ".env." + envKey,
dirname: dirname
});
};
/**
* Merges all presets into the main options in case we are not in the
* "pass per preset" mode. Otherwise, options are calculated per preset.
*/
OptionManager.prototype.mergePresets = function mergePresets(presets, dirname) {
// istanbul ignore next
var _this2 = this;
this.resolvePresets(presets, dirname, function (presetOpts, presetLoc) {
_this2.mergeOptions({
options: presetOpts,
alias: presetLoc,
loc: presetLoc,
dirname: _path2["default"].dirname(presetLoc)
});
});
};
/**
* Resolves presets options which can be either direct object data,
* or a module name to require.
*/
OptionManager.prototype.resolvePresets = function resolvePresets(presets, dirname, onResolve) {
return presets.map(function (val) {
if (typeof val === "string") {
var presetLoc = _helpersResolve2["default"]("babel-preset-" + val, dirname) || _helpersResolve2["default"](val, dirname);
if (presetLoc) {
var _val = require(presetLoc);
onResolve && onResolve(_val, presetLoc);
return _val;
} else {
throw new Error("Couldn't find preset " + JSON.stringify(val) + " relative to directory " + JSON.stringify(dirname));
}
} else if (typeof val === "object") {
onResolve && onResolve(val);
return val;
} else {
throw new Error("Unsupported preset format: " + val + ".");
}
});
};
OptionManager.prototype.addIgnoreConfig = function addIgnoreConfig(loc) {
var file = _fs2["default"].readFileSync(loc, "utf8");
var lines = file.split("\n");
lines = lines.map(function (line) {
return line.replace(/#(.*?)$/, "").trim();
}).filter(function (line) {
return !!line;
});
this.mergeOptions({
options: { ignore: lines },
loc: loc
});
};
OptionManager.prototype.findConfigs = function findConfigs(loc) {
if (!loc) return;
if (!_pathIsAbsolute2["default"](loc)) {
loc = _path2["default"].join(process.cwd(), loc);
}
var foundConfig = false;
var foundIgnore = false;
while (loc !== (loc = _path2["default"].dirname(loc))) {
if (!foundConfig) {
var configLoc = _path2["default"].join(loc, BABELRC_FILENAME);
if (exists(configLoc)) {
this.addConfig(configLoc);
foundConfig = true;
}
var pkgLoc = _path2["default"].join(loc, PACKAGE_FILENAME);
if (!foundConfig && exists(pkgLoc)) {
foundConfig = this.addConfig(pkgLoc, "babel", JSON);
}
}
if (!foundIgnore) {
var ignoreLoc = _path2["default"].join(loc, BABELIGNORE_FILENAME);
if (exists(ignoreLoc)) {
this.addIgnoreConfig(ignoreLoc);
foundIgnore = true;
}
}
if (foundIgnore && foundConfig) return;
}
};
OptionManager.prototype.normaliseOptions = function normaliseOptions() {
var opts = this.options;
for (var _key3 in _config2["default"]) {
var option = _config2["default"][_key3];
var val = opts[_key3];
// optional
if (!val && option.optional) continue;
// aliases
if (option.alias) {
opts[option.alias] = opts[option.alias] || val;
} else {
opts[_key3] = val;
}
}
};
OptionManager.prototype.init = function init() {
var opts = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
var filename = opts.filename;
// resolve all .babelrc files
if (opts.babelrc !== false) {
this.findConfigs(filename);
}
// merge in base options
this.mergeOptions({
options: opts,
alias: "base",
dirname: filename && _path2["default"].dirname(filename)
});
// normalise
this.normaliseOptions(opts);
return this.options;
};
return OptionManager;
})();
exports["default"] = OptionManager;
OptionManager.memoisedPlugins = [];
module.exports = exports["default"];
@@ -0,0 +1,34 @@
"use strict";
var _interopRequireDefault = require("babel-runtime/helpers/interop-require-default")["default"];
var _interopRequireWildcard = require("babel-runtime/helpers/interop-require-wildcard")["default"];
exports.__esModule = true;
exports.boolean = boolean;
exports.booleanString = booleanString;
exports.list = list;
var _slash = require("slash");
var _slash2 = _interopRequireDefault(_slash);
var _util = require("../../../util");
var util = _interopRequireWildcard(_util);
var filename = _slash2["default"];
exports.filename = filename;
function boolean(val) {
return !!val;
}
function booleanString(val) {
return util.booleanify(val);
}
function list(val) {
return util.list(val);
}
@@ -0,0 +1,54 @@
/* eslint max-len: 0 */
"use strict";
module.exports = {
"auxiliaryComment": {
"message": "Use `auxiliaryCommentBefore` or `auxiliaryCommentAfter`"
},
"blacklist": {
"message": "Put the specific transforms you want in the `plugins` option"
},
"breakConfig": {
"message": "This is not a necessary option in Babel 6"
},
"experimental": {
"message": "Put the specific transforms you want in the `plugins` option"
},
"externalHelpers": {
"message": "Use the `external-helpers` plugin instead. Check out http://babeljs.io/docs/plugins/external-helpers/"
},
"extra": {
"message": ""
},
"jsxPragma": {
"message": "use the `pragma` option in the `react-jsx` plugin . Check out http://babeljs.io/docs/plugins/transform-react-jsx/"
},
// "keepModuleIdExtensions": {
// "message": ""
// },
"loose": {
"message": "Specify the `loose` option for the relevant plugin you are using or use a preset that sets the option."
},
"metadataUsedHelpers": {
"message": "Not required anymore as this is enabled by default"
},
"modules": {
"message": "Use the corresponding module transform plugin in the `plugins` option. Check out http://babeljs.io/docs/plugins/#modules"
},
"nonStandard": {
"message": "Use the `react-jsx` and `flow-strip-types` plugins to support JSX and Flow. Also check out the react preset http://babeljs.io/docs/plugins/preset-react/"
},
"optional": {
"message": "Put the specific transforms you want in the `plugins` option"
},
"sourceMapName": {
"message": "Use the `sourceMapTarget` option"
},
"stage": {
"message": "Check out the corresponding stage-x presets http://babeljs.io/docs/plugins/#presets"
},
"whitelist": {
"message": "Put the specific transforms you want in the `plugins` option"
}
};
@@ -0,0 +1,54 @@
"use strict";
var _interopRequireDefault = require("babel-runtime/helpers/interop-require-default")["default"];
exports.__esModule = true;
var _plugin = require("../plugin");
var _plugin2 = _interopRequireDefault(_plugin);
var _lodashCollectionSortBy = require("lodash/collection/sortBy");
var _lodashCollectionSortBy2 = _interopRequireDefault(_lodashCollectionSortBy);
exports["default"] = new _plugin2["default"]({
/**
* [Please add a description.]
*
* Priority:
*
* - 0 We want this to be at the **very** bottom
* - 1 Default node position
* - 2 Priority over normal nodes
* - 3 We want this to be at the **very** top
*/
visitor: {
Block: {
exit: function exit(_ref) {
var node = _ref.node;
var hasChange = false;
for (var i = 0; i < node.body.length; i++) {
var bodyNode = node.body[i];
if (bodyNode && bodyNode._blockHoist != null) {
hasChange = true;
break;
}
}
if (!hasChange) return;
node.body = _lodashCollectionSortBy2["default"](node.body, function (bodyNode) {
var priority = bodyNode && bodyNode._blockHoist;
if (priority == null) priority = 1;
if (priority === true) priority = 2;
// Higher priorities should move toward the top.
return -1 * priority;
});
}
}
}
});
module.exports = exports["default"];
@@ -0,0 +1,104 @@
"use strict";
var _interopRequireDefault = require("babel-runtime/helpers/interop-require-default")["default"];
var _interopRequireWildcard = require("babel-runtime/helpers/interop-require-wildcard")["default"];
exports.__esModule = true;
var _plugin = require("../plugin");
var _plugin2 = _interopRequireDefault(_plugin);
var _babelTypes = require("babel-types");
var t = _interopRequireWildcard(_babelTypes);
exports["default"] = new _plugin2["default"]({
visitor: {
ThisExpression: function ThisExpression(path) {
remap(path, "this", function () {
return t.thisExpression();
});
},
ReferencedIdentifier: function ReferencedIdentifier(path) {
if (path.node.name === "arguments") {
remap(path, "arguments", function () {
return t.identifier("arguments");
});
}
}
}
});
function shouldShadow(path, shadowPath) {
if (path.is("_forceShadow")) {
return true;
} else {
return shadowPath;
}
}
function remap(path, key, create) {
// ensure that we're shadowed
var shadowPath = path.inShadow(key);
if (!shouldShadow(path, shadowPath)) return;
var shadowFunction = path.node._shadowedFunctionLiteral;
var currentFunction = undefined;
var passedShadowFunction = false;
var fnPath = path.findParent(function (path) {
if (path.isProgram() || path.isFunction()) {
// catch current function in case this is the shadowed one and we can ignore it
currentFunction = currentFunction || path;
}
if (path.isProgram()) {
passedShadowFunction = true;
return true;
} else if (path.isFunction() && !path.isArrowFunctionExpression()) {
if (shadowFunction) {
if (path === shadowFunction || path.node === shadowFunction.node) return true;
} else {
if (!path.is("shadow")) return true;
}
passedShadowFunction = true;
return false;
}
return false;
});
if (shadowFunction && fnPath.isProgram() && !shadowFunction.isProgram()) {
// If the shadow wasn't found, take the closest function as a backup.
// This is a bit of a hack, but it will allow the parameter transforms to work properly
// without introducing yet another shadow-controlling flag.
fnPath = path.findParent(function (p) {
return p.isProgram() || p.isFunction();
});
}
// no point in realiasing if we're in this function
if (fnPath === currentFunction) return;
// If the only functions that were encountered are arrow functions, skip remapping the
// binding since arrow function syntax already does that.
if (!passedShadowFunction) return;
var cached = fnPath.getData(key);
if (cached) return path.replaceWith(cached);
var init = create();
var id = path.scope.generateUidIdentifier(key);
fnPath.setData(key, id);
fnPath.scope.push({ id: id, init: init });
return path.replaceWith(id);
}
module.exports = exports["default"];
+79
View File
@@ -0,0 +1,79 @@
/* global BabelFileResult, BabelFileMetadata */
"use strict";
var _classCallCheck = require("babel-runtime/helpers/class-call-check")["default"];
var _interopRequireDefault = require("babel-runtime/helpers/interop-require-default")["default"];
exports.__esModule = true;
var _helpersNormalizeAst = require("../helpers/normalize-ast");
var _helpersNormalizeAst2 = _interopRequireDefault(_helpersNormalizeAst);
var _plugin = require("./plugin");
var _plugin2 = _interopRequireDefault(_plugin);
var _file = require("./file");
var _file2 = _interopRequireDefault(_file);
var Pipeline = (function () {
function Pipeline() {
_classCallCheck(this, Pipeline);
}
Pipeline.prototype.lint = function lint(code) {
var opts = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
opts.code = false;
opts.mode = "lint";
return this.transform(code, opts);
};
Pipeline.prototype.pretransform = function pretransform(code, opts) {
var file = new _file2["default"](opts, this);
return file.wrap(code, function () {
file.addCode(code);
file.parseCode(code);
return file;
});
};
Pipeline.prototype.transform = function transform(code, opts) {
var file = new _file2["default"](opts, this);
return file.wrap(code, function () {
file.addCode(code);
file.parseCode(code);
return file.transform();
});
};
Pipeline.prototype.analyse = function analyse(code, opts, visitor) {
if (opts === undefined) opts = {};
opts.code = false;
if (visitor) {
opts.plugins = opts.plugins || [];
opts.plugins.push(new _plugin2["default"]({ visitor: visitor }));
}
return this.transform(code, opts).metadata;
};
Pipeline.prototype.transformFromAst = function transformFromAst(ast, code, opts) {
ast = _helpersNormalizeAst2["default"](ast);
var file = new _file2["default"](opts, this);
return file.wrap(code, function () {
file.addCode(code);
file.addAst(ast);
return file.transform();
});
};
return Pipeline;
})();
exports["default"] = Pipeline;
module.exports = exports["default"];
+80
View File
@@ -0,0 +1,80 @@
"use strict";
var _inherits = require("babel-runtime/helpers/inherits")["default"];
var _classCallCheck = require("babel-runtime/helpers/class-call-check")["default"];
var _interopRequireDefault = require("babel-runtime/helpers/interop-require-default")["default"];
exports.__esModule = true;
var _store = require("../store");
var _store2 = _interopRequireDefault(_store);
var _babelTraverse = require("babel-traverse");
var _babelTraverse2 = _interopRequireDefault(_babelTraverse);
var _file5 = require("./file");
var _file6 = _interopRequireDefault(_file5);
var PluginPass = (function (_Store) {
_inherits(PluginPass, _Store);
function PluginPass(file, plugin) {
var options = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2];
_classCallCheck(this, PluginPass);
_Store.call(this);
this.plugin = plugin;
this.file = file;
this.opts = options;
}
PluginPass.prototype.transform = function transform() {
var file = this.file;
file.log.debug("Start transformer " + this.key);
_babelTraverse2["default"](file.ast, this.plugin.visitor, file.scope, file);
file.log.debug("Finish transformer " + this.key);
};
PluginPass.prototype.addHelper = function addHelper() {
// istanbul ignore next
var _file;
return (_file = this.file).addHelper.apply(_file, arguments);
};
PluginPass.prototype.addImport = function addImport() {
// istanbul ignore next
var _file2;
return (_file2 = this.file).addImport.apply(_file2, arguments);
};
PluginPass.prototype.getModuleName = function getModuleName() {
// istanbul ignore next
var _file3;
return (_file3 = this.file).getModuleName.apply(_file3, arguments);
};
PluginPass.prototype.buildCodeFrameError = function buildCodeFrameError() {
// istanbul ignore next
var _file4;
return (_file4 = this.file).buildCodeFrameError.apply(_file4, arguments);
};
return PluginPass;
})(_store2["default"]);
exports["default"] = PluginPass;
module.exports = exports["default"];
+147
View File
@@ -0,0 +1,147 @@
/* eslint max-len: 0 */
"use strict";
var _inherits = require("babel-runtime/helpers/inherits")["default"];
var _classCallCheck = require("babel-runtime/helpers/class-call-check")["default"];
var _getIterator = require("babel-runtime/core-js/get-iterator")["default"];
var _interopRequireDefault = require("babel-runtime/helpers/interop-require-default")["default"];
var _interopRequireWildcard = require("babel-runtime/helpers/interop-require-wildcard")["default"];
exports.__esModule = true;
var _fileOptionsOptionManager = require("./file/options/option-manager");
var _fileOptionsOptionManager2 = _interopRequireDefault(_fileOptionsOptionManager);
var _babelMessages = require("babel-messages");
var messages = _interopRequireWildcard(_babelMessages);
var _store = require("../store");
var _store2 = _interopRequireDefault(_store);
var _babelTraverse = require("babel-traverse");
var _babelTraverse2 = _interopRequireDefault(_babelTraverse);
var _lodashObjectAssign = require("lodash/object/assign");
var _lodashObjectAssign2 = _interopRequireDefault(_lodashObjectAssign);
var _lodashLangClone = require("lodash/lang/clone");
var _lodashLangClone2 = _interopRequireDefault(_lodashLangClone);
var GLOBAL_VISITOR_PROPS = ["enter", "exit"];
var Plugin = (function (_Store) {
_inherits(Plugin, _Store);
function Plugin(plugin, key) {
_classCallCheck(this, Plugin);
_Store.call(this);
this.initialized = false;
this.raw = _lodashObjectAssign2["default"]({}, plugin);
this.key = key;
this.manipulateOptions = this.take("manipulateOptions");
this.post = this.take("post");
this.pre = this.take("pre");
this.visitor = this.normaliseVisitor(_lodashLangClone2["default"](this.take("visitor")) || {});
}
Plugin.prototype.take = function take(key) {
var val = this.raw[key];
delete this.raw[key];
return val;
};
Plugin.prototype.chain = function chain(target, key) {
if (!target[key]) return this[key];
if (!this[key]) return target[key];
var fns = [target[key], this[key]];
return function () {
var val = undefined;
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
for (var _i = 0; _i < fns.length; _i++) {
var fn = fns[_i];
if (fn) {
var ret = fn.apply(this, args);
if (ret != null) val = ret;
}
}
return val;
};
};
Plugin.prototype.maybeInherit = function maybeInherit(loc) {
var inherits = this.take("inherits");
if (!inherits) return;
inherits = _fileOptionsOptionManager2["default"].normalisePlugin(inherits, loc, "inherits");
this.manipulateOptions = this.chain(inherits, "manipulateOptions");
this.post = this.chain(inherits, "post");
this.pre = this.chain(inherits, "pre");
this.visitor = _babelTraverse2["default"].visitors.merge([inherits.visitor, this.visitor]);
};
/**
* We lazy initialise parts of a plugin that rely on contextual information such as
* position on disk and how it was specified.
*/
Plugin.prototype.init = function init(loc, i) {
if (this.initialized) return;
this.initialized = true;
this.maybeInherit(loc);
for (var key in this.raw) {
throw new Error(messages.get("pluginInvalidProperty", loc, i, key));
}
};
Plugin.prototype.normaliseVisitor = function normaliseVisitor(visitor) {
for (var _iterator = GLOBAL_VISITOR_PROPS, _isArray = Array.isArray(_iterator), _i2 = 0, _iterator = _isArray ? _iterator : _getIterator(_iterator);;) {
var _ref;
if (_isArray) {
if (_i2 >= _iterator.length) break;
_ref = _iterator[_i2++];
} else {
_i2 = _iterator.next();
if (_i2.done) break;
_ref = _i2.value;
}
var key = _ref;
if (visitor[key]) {
throw new Error("Plugins aren't allowed to specify catch-all enter/exit handlers. Please target individual nodes.");
}
}
_babelTraverse2["default"].explode(visitor);
return visitor;
};
return Plugin;
})(_store2["default"]);
exports["default"] = Plugin;
module.exports = exports["default"];
+187
View File
@@ -0,0 +1,187 @@
"use strict";
var _interopRequireDefault = require("babel-runtime/helpers/interop-require-default")["default"];
exports.__esModule = true;
exports.canCompile = canCompile;
exports.list = list;
exports.regexify = regexify;
exports.arrayify = arrayify;
exports.booleanify = booleanify;
exports.shouldIgnore = shouldIgnore;
var _lodashStringEscapeRegExp = require("lodash/string/escapeRegExp");
var _lodashStringEscapeRegExp2 = _interopRequireDefault(_lodashStringEscapeRegExp);
var _lodashStringStartsWith = require("lodash/string/startsWith");
var _lodashStringStartsWith2 = _interopRequireDefault(_lodashStringStartsWith);
var _lodashLangIsBoolean = require("lodash/lang/isBoolean");
var _lodashLangIsBoolean2 = _interopRequireDefault(_lodashLangIsBoolean);
var _minimatch = require("minimatch");
var _minimatch2 = _interopRequireDefault(_minimatch);
var _lodashCollectionContains = require("lodash/collection/contains");
var _lodashCollectionContains2 = _interopRequireDefault(_lodashCollectionContains);
var _lodashLangIsString = require("lodash/lang/isString");
var _lodashLangIsString2 = _interopRequireDefault(_lodashLangIsString);
var _lodashLangIsRegExp = require("lodash/lang/isRegExp");
var _lodashLangIsRegExp2 = _interopRequireDefault(_lodashLangIsRegExp);
var _path = require("path");
var _path2 = _interopRequireDefault(_path);
var _slash = require("slash");
var _slash2 = _interopRequireDefault(_slash);
var _util = require("util");
exports.inherits = _util.inherits;
exports.inspect = _util.inspect;
/**
* Test if a filename ends with a compilable extension.
*/
function canCompile(filename, altExts) {
var exts = altExts || canCompile.EXTENSIONS;
var ext = _path2["default"].extname(filename);
return _lodashCollectionContains2["default"](exts, ext);
}
/**
* Default set of compilable extensions.
*/
canCompile.EXTENSIONS = [".js", ".jsx", ".es6", ".es"];
/**
* Create an array from any value, splitting strings by ",".
*/
function list(val) {
if (!val) {
return [];
} else if (Array.isArray(val)) {
return val;
} else if (typeof val === "string") {
return val.split(",");
} else {
return [val];
}
}
/**
* Create a RegExp from a string, array, or regexp.
*/
function regexify(val) {
if (!val) {
return new RegExp(/.^/);
}
if (Array.isArray(val)) {
val = new RegExp(val.map(_lodashStringEscapeRegExp2["default"]).join("|"), "i");
}
if (typeof val === "string") {
// normalise path separators
val = _slash2["default"](val);
// remove starting wildcards or relative separator if present
if (_lodashStringStartsWith2["default"](val, "./") || _lodashStringStartsWith2["default"](val, "*/")) val = val.slice(2);
if (_lodashStringStartsWith2["default"](val, "**/")) val = val.slice(3);
var regex = _minimatch2["default"].makeRe(val, { nocase: true });
return new RegExp(regex.source.slice(1, -1), "i");
}
if (_lodashLangIsRegExp2["default"](val)) {
return val;
}
throw new TypeError("illegal type for regexify");
}
/**
* Create an array from a boolean, string, or array, mapped by and optional function.
*/
function arrayify(val, mapFn) {
if (!val) return [];
if (_lodashLangIsBoolean2["default"](val)) return arrayify([val], mapFn);
if (_lodashLangIsString2["default"](val)) return arrayify(list(val), mapFn);
if (Array.isArray(val)) {
if (mapFn) val = val.map(mapFn);
return val;
}
return [val];
}
/**
* Makes boolean-like strings into booleans.
*/
function booleanify(val) {
if (val === "true" || val == 1) {
return true;
}
if (val === "false" || val == 0 || !val) {
return false;
}
return val;
}
/**
* Tests if a filename should be ignored based on "ignore" and "only" options.
*/
function shouldIgnore(filename, ignore, only) {
if (ignore === undefined) ignore = [];
filename = _slash2["default"](filename);
if (only) {
for (var _i = 0; _i < only.length; _i++) {
var pattern = only[_i];
if (_shouldIgnore(pattern, filename)) return false;
}
return true;
} else if (ignore.length) {
for (var _i2 = 0; _i2 < ignore.length; _i2++) {
var pattern = ignore[_i2];
if (_shouldIgnore(pattern, filename)) return true;
}
}
return false;
}
/**
* Returns result of calling function with filename if pattern is a function.
* Otherwise returns result of matching pattern Regex with filename.
*/
function _shouldIgnore(pattern, filename) {
if (typeof pattern === "function") {
return pattern(filename);
} else {
return pattern.test(filename);
}
}
+132
View File
@@ -0,0 +1,132 @@
{
"_args": [
[
"babel-core@^6.0.14",
"/Users/mromano/dev/react-sfs/node_modules/babelify"
]
],
"_from": "babel-core@>=6.0.14 <7.0.0",
"_id": "babel-core@6.7.4",
"_inCache": true,
"_installable": true,
"_location": "/babel-core",
"_nodeVersion": "5.9.0",
"_npmOperationalInternal": {
"host": "packages-13-west.internal.npmjs.com",
"tmp": "tmp/babel-core-6.7.4.tgz_1458704268353_0.5215817883145064"
},
"_npmUser": {
"email": "loganfsmyth@gmail.com",
"name": "loganfsmyth"
},
"_npmVersion": "3.7.3",
"_phantomChildren": {},
"_requested": {
"name": "babel-core",
"raw": "babel-core@^6.0.14",
"rawSpec": "^6.0.14",
"scope": null,
"spec": ">=6.0.14 <7.0.0",
"type": "range"
},
"_requiredBy": [
"/babel-register",
"/babelify"
],
"_resolved": "https://registry.npmjs.org/babel-core/-/babel-core-6.7.4.tgz",
"_shasum": "aeeea5da586c043e1a1b61dea2c57652df03ee49",
"_shrinkwrap": null,
"_spec": "babel-core@^6.0.14",
"_where": "/Users/mromano/dev/react-sfs/node_modules/babelify",
"author": {
"email": "sebmck@gmail.com",
"name": "Sebastian McKenzie"
},
"dependencies": {
"babel-code-frame": "^6.7.4",
"babel-generator": "^6.7.2",
"babel-helpers": "^6.6.0",
"babel-messages": "^6.7.2",
"babel-register": "^6.7.2",
"babel-runtime": "^5.0.0",
"babel-template": "^6.7.0",
"babel-traverse": "^6.7.4",
"babel-types": "^6.7.2",
"babylon": "^6.7.0",
"convert-source-map": "^1.1.0",
"debug": "^2.1.1",
"json5": "^0.4.0",
"lodash": "^3.10.0",
"minimatch": "^2.0.3",
"path-exists": "^1.0.0",
"path-is-absolute": "^1.0.0",
"private": "^0.1.6",
"shebang-regex": "^1.0.0",
"slash": "^1.0.0",
"source-map": "^0.5.0"
},
"description": "Babel compiler core.",
"devDependencies": {
"babel-helper-fixtures": "^6.6.5",
"babel-helper-transform-fixture-test-runner": "^6.6.5",
"babel-polyfill": "^6.7.4"
},
"directories": {},
"dist": {
"shasum": "aeeea5da586c043e1a1b61dea2c57652df03ee49",
"tarball": "https://registry.npmjs.org/babel-core/-/babel-core-6.7.4.tgz"
},
"homepage": "https://babeljs.io/",
"keywords": [
"6to5",
"babel",
"classes",
"const",
"es6",
"harmony",
"let",
"modules",
"transpile",
"transpiler",
"var"
],
"license": "MIT",
"maintainers": [
{
"email": "amjad.masad@gmail.com",
"name": "amasad"
},
{
"email": "hi@henryzoo.com",
"name": "hzoo"
},
{
"email": "npm-public@jessemccarthy.net",
"name": "jmm"
},
{
"email": "loganfsmyth@gmail.com",
"name": "loganfsmyth"
},
{
"email": "sebmck@gmail.com",
"name": "sebmck"
},
{
"email": "me@thejameskyle.com",
"name": "thejameskyle"
}
],
"name": "babel-core",
"optionalDependencies": {},
"readme": "ERROR: No README data found!",
"repository": {
"type": "git",
"url": "https://github.com/babel/babel/tree/master/packages/babel-core"
},
"scripts": {
"bench": "make bench",
"test": "make test"
},
"version": "6.7.4"
}
+3
View File
@@ -0,0 +1,3 @@
/* eslint max-len: 0 */
// TODO: eventually deprecate this console.trace("use the `babel-register` package instead of `babel-core/register`");
module.exports = require("babel-register");
+84
View File
@@ -0,0 +1,84 @@
# babel-generator
> Turns an AST into code.
## Install
```sh
$ npm install babel-generator
```
## Usage
```js
import {parse} from 'babylon';
import generate from 'babel-generator';
const code = 'class Example {}';
const ast = parse(code);
const output = generate(ast, { /* options */ }, code);
```
## Options
Options for formatting output:
name | type | default | description
-----------------------|----------|-----------------|--------------------------------------------------------------------------
auxiliaryCommentBefore | string | | Optional string to add as a block comment at the start of the output file
auxiliaryCommentAfter | string | | Optional string to add as a block comment at the end of the output file
shouldPrintComment | function | `opts.comments` | Function that takes a comment (as a string) and returns `true` if the comment should be included in the output. By default, comments are included if `opts.comments` is `true` or if `opts.minifed` is `false` and the comment contains `@preserve` or `@license`
retainLines | boolean | `false` | Attempt to use the same line numbers in the output code as in the source code (helps preserve stack traces)
comments | boolean | `true` | Should comments be included in output
compact | boolean or `'auto'` | `opts.minified` | Set to `true` to avoid adding whitespace for formatting
minified | boolean | `false` | Should the output be minified
concise | boolean | `false` | Set to `true` to reduce whitespace (but not as much as `opts.compact`)
quotes | `'single'` or `'double'` | autodetect based on `ast.tokens` | The type of quote to use in the output
filename | string | | Used in warning messages
Options for source maps:
name | type | default | description
-----------------------|----------|-----------------|--------------------------------------------------------------------------
sourceMaps | boolean | `false` | Enable generating source maps
sourceMapTarget | string | | The filename of the generated code that the source map will be associated with
sourceRoot | string | | A root for all relative URLs in the source map
sourceFileName | string | | The filename for the source code (i.e. the code in the `code` argument). This will only be used if `code` is a string.
## AST from Multiple Sources
In most cases, Babel does a 1:1 transformation of input-file to output-file. However,
you may be dealing with AST constructed from multiple sources - JS files, templates, etc.
If this is the case, and you want the sourcemaps to reflect the correct sources, you'll need
to make some changes to your code.
First, each node with a `loc` property (which indicates that node's original placement in the
source document) must also include a `loc.filename` property, set to the source filename.
Second, you should pass an object to `generate` as the `code` parameter. Keys
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 traverse from "babel-traverse";
import generate from 'babel-generator';
const a = 'var a = 1;';
const b = 'var b = 2;';
const astA = parse(a, { filename: 'a.js' });
const astB = parse(b, { filename: 'b.js' });
const ast = {
type: 'Program',
body: [].concat(astA.body, ast2.body)
};
const { code, map } = generate(ast, { /* options */ }, {
'a.js': a,
'b.js': b
});
// Sourcemap will point to both a.js and b.js where appropriate.
```
+326
View File
@@ -0,0 +1,326 @@
"use strict";
var _classCallCheck = require("babel-runtime/helpers/class-call-check")["default"];
var _interopRequireDefault = require("babel-runtime/helpers/interop-require-default")["default"];
exports.__esModule = true;
var _repeating = require("repeating");
var _repeating2 = _interopRequireDefault(_repeating);
var _trimRight = require("trim-right");
var _trimRight2 = _interopRequireDefault(_trimRight);
/**
* Buffer for collecting generated output.
*/
var Buffer = (function () {
function Buffer(position, format) {
_classCallCheck(this, Buffer);
this.printedCommentStarts = {};
this.parenPushNewlineState = null;
this.position = position;
this._indent = format.indent.base;
this.format = format;
this.buf = "";
// Maintaining a reference to the last char in the buffer is an optimization
// to make sure that v8 doesn't "flatten" the string more often than needed
// see https://github.com/babel/babel/pull/3283 for details.
this.last = "";
}
/**
* Description
*/
Buffer.prototype.catchUp = function catchUp(node) {
// catch up to this nodes newline if we're behind
if (node.loc && this.format.retainLines && this.buf) {
while (this.position.line < node.loc.start.line) {
this._push("\n");
}
}
};
/**
* Get the current trimmed buffer.
*/
Buffer.prototype.get = function get() {
return _trimRight2["default"](this.buf);
};
/**
* Get the current indent.
*/
Buffer.prototype.getIndent = function getIndent() {
if (this.format.compact || this.format.concise) {
return "";
} else {
return _repeating2["default"](this.format.indent.style, this._indent);
}
};
/**
* Get the current indent size.
*/
Buffer.prototype.indentSize = function indentSize() {
return this.getIndent().length;
};
/**
* Increment indent size.
*/
Buffer.prototype.indent = function indent() {
this._indent++;
};
/**
* Decrement indent size.
*/
Buffer.prototype.dedent = function dedent() {
this._indent--;
};
/**
* Add a semicolon to the buffer.
*/
Buffer.prototype.semicolon = function semicolon() {
this.push(";");
};
/**
* Ensure last character is a semicolon.
*/
Buffer.prototype.ensureSemicolon = function ensureSemicolon() {
if (!this.isLast(";")) this.semicolon();
};
/**
* Add a right brace to the buffer.
*/
Buffer.prototype.rightBrace = function rightBrace() {
this.newline(true);
if (this.format.minified && !this._lastPrintedIsEmptyStatement) {
this._removeLast(";");
}
this.push("}");
};
/**
* Add a keyword to the buffer.
*/
Buffer.prototype.keyword = function keyword(name) {
this.push(name);
this.space();
};
/**
* Add a space to the buffer unless it is compact (override with force).
*/
Buffer.prototype.space = function space(force) {
if (!force && this.format.compact) return;
if (force || this.buf && !this.isLast(" ") && !this.isLast("\n")) {
this.push(" ");
}
};
/**
* Remove the last character.
*/
Buffer.prototype.removeLast = function removeLast(cha) {
if (this.format.compact) return;
return this._removeLast(cha);
};
Buffer.prototype._removeLast = function _removeLast(cha) {
if (!this._isLast(cha)) return;
this.buf = this.buf.slice(0, -1);
this.last = this.buf[this.buf.length - 1];
this.position.unshift(cha);
};
/**
* Set some state that will be modified if a newline has been inserted before any
* non-space characters.
*
* This is to prevent breaking semantics for terminatorless separator nodes. eg:
*
* return foo;
*
* returns `foo`. But if we do:
*
* return
* foo;
*
* `undefined` will be returned and not `foo` due to the terminator.
*/
Buffer.prototype.startTerminatorless = function startTerminatorless() {
return this.parenPushNewlineState = {
printed: false
};
};
/**
* Print an ending parentheses if a starting one has been printed.
*/
Buffer.prototype.endTerminatorless = function endTerminatorless(state) {
if (state.printed) {
this.dedent();
this.newline();
this.push(")");
}
};
/**
* Add a newline (or many newlines), maintaining formatting.
* Strips multiple newlines if removeLast is true.
*/
Buffer.prototype.newline = function newline(i, removeLast) {
if (this.format.retainLines || this.format.compact) return;
if (this.format.concise) {
this.space();
return;
}
// never allow more than two lines
if (this.endsWith("\n\n")) return;
if (typeof i === "boolean") removeLast = i;
if (typeof i !== "number") i = 1;
i = Math.min(2, i);
if (this.endsWith("{\n") || this.endsWith(":\n")) i--;
if (i <= 0) return;
// remove the last newline
if (removeLast) {
this.removeLast("\n");
}
this.removeLast(" ");
this._removeSpacesAfterLastNewline();
this._push(_repeating2["default"]("\n", i));
};
/**
* If buffer ends with a newline and some spaces after it, trim those spaces.
*/
Buffer.prototype._removeSpacesAfterLastNewline = function _removeSpacesAfterLastNewline() {
var lastNewlineIndex = this.buf.lastIndexOf("\n");
if (lastNewlineIndex >= 0 && this.get().length <= lastNewlineIndex) {
this.buf = this.buf.substring(0, lastNewlineIndex + 1);
this.last = "\n";
}
};
/**
* Push a string to the buffer, maintaining indentation and newlines.
*/
Buffer.prototype.push = function push(str, noIndent) {
if (!this.format.compact && this._indent && !noIndent && str !== "\n") {
// we have an indent level and we aren't pushing a newline
var indent = this.getIndent();
// replace all newlines with newlines with the indentation
str = str.replace(/\n/g, "\n" + indent);
// we've got a newline before us so prepend on the indentation
if (this.isLast("\n")) this._push(indent);
}
this._push(str);
};
/**
* Push a string to the buffer.
*/
Buffer.prototype._push = function _push(str) {
// see startTerminatorless() instance method
var parenPushNewlineState = this.parenPushNewlineState;
if (parenPushNewlineState) {
for (var i = 0; i < str.length; i++) {
var cha = str[i];
// we can ignore spaces since they wont interupt a terminatorless separator
if (cha === " ") continue;
this.parenPushNewlineState = null;
if (cha === "\n" || cha === "/") {
// we're going to break this terminator expression so we need to add a parentheses
this._push("(");
this.indent();
parenPushNewlineState.printed = true;
}
break;
}
}
//
this.position.push(str);
this.buf += str;
this.last = str[str.length - 1];
};
/**
* Test if the buffer ends with a string.
*/
Buffer.prototype.endsWith = function endsWith(str) {
if (str.length === 1) {
return this.last === str;
} else {
return this.buf.slice(-str.length) === str;
}
};
/**
* Test if a character is last in the buffer.
*/
Buffer.prototype.isLast = function isLast(cha) {
if (this.format.compact) return false;
return this._isLast(cha);
};
Buffer.prototype._isLast = function _isLast(cha) {
var last = this.last;
if (Array.isArray(cha)) {
return cha.indexOf(last) >= 0;
} else {
return cha === last;
}
};
return Buffer;
})();
exports["default"] = Buffer;
module.exports = exports["default"];
+50
View File
@@ -0,0 +1,50 @@
"use strict";
exports.__esModule = true;
exports.File = File;
exports.Program = Program;
exports.BlockStatement = BlockStatement;
exports.Noop = Noop;
exports.Directive = Directive;
exports.DirectiveLiteral = DirectiveLiteral;
function File(node) {
this.print(node.program, node);
}
function Program(node) {
this.printInnerComments(node, false);
this.printSequence(node.directives, node);
if (node.directives && node.directives.length) this.newline();
this.printSequence(node.body, node);
}
function BlockStatement(node) {
this.push("{");
this.printInnerComments(node);
if (node.body.length) {
this.newline();
this.printSequence(node.directives, node, { indent: true });
if (node.directives && node.directives.length) this.newline();
this.printSequence(node.body, node, { indent: true });
if (!this.format.retainLines && !this.format.concise) this.removeLast("\n");
this.rightBrace();
} else {
this.push("}");
}
}
function Noop() {}
function Directive(node) {
this.print(node.value, node);
this.semicolon();
}
function DirectiveLiteral(node) {
this.push(this._stringLiteral(node.value));
}
+80
View File
@@ -0,0 +1,80 @@
"use strict";
exports.__esModule = true;
exports.ClassDeclaration = ClassDeclaration;
exports.ClassBody = ClassBody;
exports.ClassProperty = ClassProperty;
exports.ClassMethod = ClassMethod;
function ClassDeclaration(node) {
this.printJoin(node.decorators, node, { separator: "" });
this.push("class");
if (node.id) {
this.push(" ");
this.print(node.id, node);
}
this.print(node.typeParameters, node);
if (node.superClass) {
this.push(" extends ");
this.print(node.superClass, node);
this.print(node.superTypeParameters, node);
}
if (node["implements"]) {
this.push(" implements ");
this.printJoin(node["implements"], node, { separator: ", " });
}
this.space();
this.print(node.body, node);
}
exports.ClassExpression = ClassDeclaration;
function ClassBody(node) {
this.push("{");
this.printInnerComments(node);
if (node.body.length === 0) {
this.push("}");
} else {
this.newline();
this.indent();
this.printSequence(node.body, node);
this.dedent();
this.rightBrace();
}
}
function ClassProperty(node) {
this.printJoin(node.decorators, node, { separator: "" });
if (node["static"]) this.push("static ");
this.print(node.key, node);
this.print(node.typeAnnotation, node);
if (node.value) {
this.space();
this.push("=");
this.space();
this.print(node.value, node);
}
this.semicolon();
}
function ClassMethod(node) {
this.printJoin(node.decorators, node, { separator: "" });
if (node["static"]) {
this.push("static ");
}
if (node.kind === "constructorCall") {
this.push("call ");
}
this._method(node);
}
+280
View File
@@ -0,0 +1,280 @@
/* eslint max-len: 0 */
"use strict";
var _interopRequireDefault = require("babel-runtime/helpers/interop-require-default")["default"];
var _interopRequireWildcard = require("babel-runtime/helpers/interop-require-wildcard")["default"];
exports.__esModule = true;
exports.UnaryExpression = UnaryExpression;
exports.DoExpression = DoExpression;
exports.ParenthesizedExpression = ParenthesizedExpression;
exports.UpdateExpression = UpdateExpression;
exports.ConditionalExpression = ConditionalExpression;
exports.NewExpression = NewExpression;
exports.SequenceExpression = SequenceExpression;
exports.ThisExpression = ThisExpression;
exports.Super = Super;
exports.Decorator = Decorator;
exports.CallExpression = CallExpression;
exports.EmptyStatement = EmptyStatement;
exports.ExpressionStatement = ExpressionStatement;
exports.AssignmentPattern = AssignmentPattern;
exports.AssignmentExpression = AssignmentExpression;
exports.BindExpression = BindExpression;
exports.MemberExpression = MemberExpression;
exports.MetaProperty = MetaProperty;
var _isInteger = require("is-integer");
var _isInteger2 = _interopRequireDefault(_isInteger);
var _lodashLangIsNumber = require("lodash/lang/isNumber");
var _lodashLangIsNumber2 = _interopRequireDefault(_lodashLangIsNumber);
var _babelTypes = require("babel-types");
var t = _interopRequireWildcard(_babelTypes);
var _node = require("../node");
var n = _interopRequireWildcard(_node);
var SCIENTIFIC_NOTATION = /e/i;
var ZERO_DECIMAL_INTEGER = /\.0+$/;
var NON_DECIMAL_LITERAL = /^0[box]/;
function UnaryExpression(node) {
var needsSpace = /[a-z]$/.test(node.operator);
var arg = node.argument;
if (t.isUpdateExpression(arg) || t.isUnaryExpression(arg)) {
needsSpace = true;
}
if (t.isUnaryExpression(arg) && arg.operator === "!") {
needsSpace = false;
}
this.push(node.operator);
if (needsSpace) this.push(" ");
this.print(node.argument, node);
}
function DoExpression(node) {
this.push("do");
this.space();
this.print(node.body, node);
}
function ParenthesizedExpression(node) {
this.push("(");
this.print(node.expression, node);
this.push(")");
}
function UpdateExpression(node) {
if (node.prefix) {
this.push(node.operator);
this.print(node.argument, node);
} else {
this.print(node.argument, node);
this.push(node.operator);
}
}
function ConditionalExpression(node) {
this.print(node.test, node);
this.space();
this.push("?");
this.space();
this.print(node.consequent, node);
this.space();
this.push(":");
this.space();
this.print(node.alternate, node);
}
function NewExpression(node, parent) {
this.push("new ");
this.print(node.callee, node);
if (node.arguments.length === 0 && this.format.minified && !t.isCallExpression(parent, { callee: node }) && !t.isMemberExpression(parent) && !t.isNewExpression(parent)) return;
this.push("(");
this.printList(node.arguments, node);
this.push(")");
}
function SequenceExpression(node) {
this.printList(node.expressions, node);
}
function ThisExpression() {
this.push("this");
}
function Super() {
this.push("super");
}
function Decorator(node) {
this.push("@");
this.print(node.expression, node);
this.newline();
}
function CallExpression(node) {
this.print(node.callee, node);
if (node.loc) this.printAuxAfterComment();
this.push("(");
var isPrettyCall = node._prettyCall && !this.format.retainLines && !this.format.compact;
var separator = undefined;
if (isPrettyCall) {
separator = ",\n";
this.newline();
this.indent();
}
this.printList(node.arguments, node, { separator: separator });
if (isPrettyCall) {
this.newline();
this.dedent();
}
this.push(")");
}
function buildYieldAwait(keyword) {
return function (node) {
this.push(keyword);
if (node.delegate) {
this.push("*");
}
if (node.argument) {
this.push(" ");
var terminatorState = this.startTerminatorless();
this.print(node.argument, node);
this.endTerminatorless(terminatorState);
}
};
}
var YieldExpression = buildYieldAwait("yield");
exports.YieldExpression = YieldExpression;
var AwaitExpression = buildYieldAwait("await");
exports.AwaitExpression = AwaitExpression;
function EmptyStatement() {
this._lastPrintedIsEmptyStatement = true;
this.semicolon();
}
function ExpressionStatement(node) {
this.print(node.expression, node);
this.semicolon();
}
function AssignmentPattern(node) {
this.print(node.left, node);
this.space();
this.push("=");
this.space();
this.print(node.right, node);
}
function AssignmentExpression(node, parent) {
// Somewhere inside a for statement `init` node but doesn't usually
// needs a paren except for `in` expressions: `for (a in b ? a : b;;)`
var parens = this._inForStatementInitCounter && node.operator === "in" && !n.needsParens(node, parent);
if (parens) {
this.push("(");
}
this.print(node.left, node);
var spaces = !this.format.compact || node.operator === "in" || node.operator === "instanceof";
if (spaces) this.push(" ");
this.push(node.operator);
if (!spaces) {
// space is mandatory to avoid outputting <!--
// http://javascript.spec.whatwg.org/#comment-syntax
spaces = node.operator === "<" && t.isUnaryExpression(node.right, { prefix: true, operator: "!" }) && t.isUnaryExpression(node.right.argument, { prefix: true, operator: "--" });
// Need spaces for operators of the same kind to avoid: `a+++b`
if (!spaces) {
var right = getLeftMost(node.right);
spaces = t.isUnaryExpression(right, { prefix: true, operator: node.operator }) || t.isUpdateExpression(right, { prefix: true, operator: node.operator + node.operator });
}
}
if (spaces) this.push(" ");
this.print(node.right, node);
if (parens) {
this.push(")");
}
}
function BindExpression(node) {
this.print(node.object, node);
this.push("::");
this.print(node.callee, node);
}
exports.BinaryExpression = AssignmentExpression;
exports.LogicalExpression = AssignmentExpression;
function MemberExpression(node) {
this.print(node.object, node);
if (!node.computed && t.isMemberExpression(node.property)) {
throw new TypeError("Got a MemberExpression for MemberExpression property");
}
var computed = node.computed;
if (t.isLiteral(node.property) && _lodashLangIsNumber2["default"](node.property.value)) {
computed = true;
}
if (computed) {
this.push("[");
this.print(node.property, node);
this.push("]");
} else {
if (t.isNumericLiteral(node.object)) {
var val = this.getPossibleRaw(node.object) || node.object.value;
if (_isInteger2["default"](+val) && !NON_DECIMAL_LITERAL.test(val) && !SCIENTIFIC_NOTATION.test(val) && !ZERO_DECIMAL_INTEGER.test(val) && !this.endsWith(".")) {
this.push(".");
}
}
this.push(".");
this.print(node.property, node);
}
}
function MetaProperty(node) {
this.print(node.meta, node);
this.push(".");
this.print(node.property, node);
}
function getLeftMost(binaryExpr) {
if (!t.isBinaryExpression(binaryExpr)) {
return binaryExpr;
}
return getLeftMost(binaryExpr.left);
}
+331
View File
@@ -0,0 +1,331 @@
/* eslint max-len: 0 */
"use strict";
var _interopRequireWildcard = require("babel-runtime/helpers/interop-require-wildcard")["default"];
exports.__esModule = true;
exports.AnyTypeAnnotation = AnyTypeAnnotation;
exports.ArrayTypeAnnotation = ArrayTypeAnnotation;
exports.BooleanTypeAnnotation = BooleanTypeAnnotation;
exports.BooleanLiteralTypeAnnotation = BooleanLiteralTypeAnnotation;
exports.NullLiteralTypeAnnotation = NullLiteralTypeAnnotation;
exports.DeclareClass = DeclareClass;
exports.DeclareFunction = DeclareFunction;
exports.DeclareInterface = DeclareInterface;
exports.DeclareModule = DeclareModule;
exports.DeclareTypeAlias = DeclareTypeAlias;
exports.DeclareVariable = DeclareVariable;
exports.ExistentialTypeParam = ExistentialTypeParam;
exports.FunctionTypeAnnotation = FunctionTypeAnnotation;
exports.FunctionTypeParam = FunctionTypeParam;
exports.InterfaceExtends = InterfaceExtends;
exports._interfaceish = _interfaceish;
exports.InterfaceDeclaration = InterfaceDeclaration;
exports.IntersectionTypeAnnotation = IntersectionTypeAnnotation;
exports.MixedTypeAnnotation = MixedTypeAnnotation;
exports.NullableTypeAnnotation = NullableTypeAnnotation;
exports.NumberTypeAnnotation = NumberTypeAnnotation;
exports.StringLiteralTypeAnnotation = StringLiteralTypeAnnotation;
exports.StringTypeAnnotation = StringTypeAnnotation;
exports.ThisTypeAnnotation = ThisTypeAnnotation;
exports.TupleTypeAnnotation = TupleTypeAnnotation;
exports.TypeofTypeAnnotation = TypeofTypeAnnotation;
exports.TypeAlias = TypeAlias;
exports.TypeAnnotation = TypeAnnotation;
exports.TypeParameterInstantiation = TypeParameterInstantiation;
exports.ObjectTypeAnnotation = ObjectTypeAnnotation;
exports.ObjectTypeCallProperty = ObjectTypeCallProperty;
exports.ObjectTypeIndexer = ObjectTypeIndexer;
exports.ObjectTypeProperty = ObjectTypeProperty;
exports.QualifiedTypeIdentifier = QualifiedTypeIdentifier;
exports.UnionTypeAnnotation = UnionTypeAnnotation;
exports.TypeCastExpression = TypeCastExpression;
exports.VoidTypeAnnotation = VoidTypeAnnotation;
var _babelTypes = require("babel-types");
var t = _interopRequireWildcard(_babelTypes);
function AnyTypeAnnotation() {
this.push("any");
}
function ArrayTypeAnnotation(node) {
this.print(node.elementType, node);
this.push("[");
this.push("]");
}
function BooleanTypeAnnotation() {
this.push("bool");
}
function BooleanLiteralTypeAnnotation(node) {
this.push(node.value ? "true" : "false");
}
function NullLiteralTypeAnnotation() {
this.push("null");
}
function DeclareClass(node) {
this.push("declare class ");
this._interfaceish(node);
}
function DeclareFunction(node) {
this.push("declare function ");
this.print(node.id, node);
this.print(node.id.typeAnnotation.typeAnnotation, node);
this.semicolon();
}
function DeclareInterface(node) {
this.push("declare ");
this.InterfaceDeclaration(node);
}
function DeclareModule(node) {
this.push("declare module ");
this.print(node.id, node);
this.space();
this.print(node.body, node);
}
function DeclareTypeAlias(node) {
this.push("declare ");
this.TypeAlias(node);
}
function DeclareVariable(node) {
this.push("declare var ");
this.print(node.id, node);
this.print(node.id.typeAnnotation, node);
this.semicolon();
}
function ExistentialTypeParam() {
this.push("*");
}
function FunctionTypeAnnotation(node, parent) {
this.print(node.typeParameters, node);
this.push("(");
this.printList(node.params, node);
if (node.rest) {
if (node.params.length) {
this.push(",");
this.space();
}
this.push("...");
this.print(node.rest, node);
}
this.push(")");
// this node type is overloaded, not sure why but it makes it EXTREMELY annoying
if (parent.type === "ObjectTypeProperty" || parent.type === "ObjectTypeCallProperty" || parent.type === "DeclareFunction") {
this.push(":");
} else {
this.space();
this.push("=>");
}
this.space();
this.print(node.returnType, node);
}
function FunctionTypeParam(node) {
this.print(node.name, node);
if (node.optional) this.push("?");
this.push(":");
this.space();
this.print(node.typeAnnotation, node);
}
function InterfaceExtends(node) {
this.print(node.id, node);
this.print(node.typeParameters, node);
}
exports.ClassImplements = InterfaceExtends;
exports.GenericTypeAnnotation = InterfaceExtends;
function _interfaceish(node) {
this.print(node.id, node);
this.print(node.typeParameters, node);
if (node["extends"].length) {
this.push(" extends ");
this.printJoin(node["extends"], node, { separator: ", " });
}
if (node.mixins && node.mixins.length) {
this.push(" mixins ");
this.printJoin(node.mixins, node, { separator: ", " });
}
this.space();
this.print(node.body, node);
}
function InterfaceDeclaration(node) {
this.push("interface ");
this._interfaceish(node);
}
function IntersectionTypeAnnotation(node) {
this.printJoin(node.types, node, { separator: " & " });
}
function MixedTypeAnnotation() {
this.push("mixed");
}
function NullableTypeAnnotation(node) {
this.push("?");
this.print(node.typeAnnotation, node);
}
var _types = require("./types");
exports.NumericLiteralTypeAnnotation = _types.NumericLiteral;
function NumberTypeAnnotation() {
this.push("number");
}
function StringLiteralTypeAnnotation(node) {
this.push(this._stringLiteral(node.value));
}
function StringTypeAnnotation() {
this.push("string");
}
function ThisTypeAnnotation() {
this.push("this");
}
function TupleTypeAnnotation(node) {
this.push("[");
this.printJoin(node.types, node, { separator: ", " });
this.push("]");
}
function TypeofTypeAnnotation(node) {
this.push("typeof ");
this.print(node.argument, node);
}
function TypeAlias(node) {
this.push("type ");
this.print(node.id, node);
this.print(node.typeParameters, node);
this.space();
this.push("=");
this.space();
this.print(node.right, node);
this.semicolon();
}
function TypeAnnotation(node) {
this.push(":");
this.space();
if (node.optional) this.push("?");
this.print(node.typeAnnotation, node);
}
function TypeParameterInstantiation(node) {
// istanbul ignore next
var _this = this;
this.push("<");
this.printJoin(node.params, node, {
separator: ", ",
iterator: function iterator(node) {
_this.print(node.typeAnnotation, node);
}
});
this.push(">");
}
exports.TypeParameterDeclaration = TypeParameterInstantiation;
function ObjectTypeAnnotation(node) {
// istanbul ignore next
var _this2 = this;
this.push("{");
var props = node.properties.concat(node.callProperties, node.indexers);
if (props.length) {
this.space();
this.printJoin(props, node, {
separator: false,
indent: true,
iterator: function iterator() {
if (props.length !== 1) {
_this2.semicolon();
_this2.space();
}
}
});
this.space();
}
this.push("}");
}
function ObjectTypeCallProperty(node) {
if (node["static"]) this.push("static ");
this.print(node.value, node);
}
function ObjectTypeIndexer(node) {
if (node["static"]) this.push("static ");
this.push("[");
this.print(node.id, node);
this.push(":");
this.space();
this.print(node.key, node);
this.push("]");
this.push(":");
this.space();
this.print(node.value, node);
}
function ObjectTypeProperty(node) {
if (node["static"]) this.push("static ");
this.print(node.key, node);
if (node.optional) this.push("?");
if (!t.isFunctionTypeAnnotation(node.value)) {
this.push(":");
this.space();
}
this.print(node.value, node);
}
function QualifiedTypeIdentifier(node) {
this.print(node.qualification, node);
this.push(".");
this.print(node.id, node);
}
function UnionTypeAnnotation(node) {
this.printJoin(node.types, node, { separator: " | " });
}
function TypeCastExpression(node) {
this.push("(");
this.print(node.expression, node);
this.print(node.typeAnnotation, node);
this.push(")");
}
function VoidTypeAnnotation() {
this.push("void");
}
+88
View File
@@ -0,0 +1,88 @@
"use strict";
exports.__esModule = true;
exports.JSXAttribute = JSXAttribute;
exports.JSXIdentifier = JSXIdentifier;
exports.JSXNamespacedName = JSXNamespacedName;
exports.JSXMemberExpression = JSXMemberExpression;
exports.JSXSpreadAttribute = JSXSpreadAttribute;
exports.JSXExpressionContainer = JSXExpressionContainer;
exports.JSXText = JSXText;
exports.JSXElement = JSXElement;
exports.JSXOpeningElement = JSXOpeningElement;
exports.JSXClosingElement = JSXClosingElement;
exports.JSXEmptyExpression = JSXEmptyExpression;
function JSXAttribute(node) {
this.print(node.name, node);
if (node.value) {
this.push("=");
this.print(node.value, node);
}
}
function JSXIdentifier(node) {
this.push(node.name);
}
function JSXNamespacedName(node) {
this.print(node.namespace, node);
this.push(":");
this.print(node.name, node);
}
function JSXMemberExpression(node) {
this.print(node.object, node);
this.push(".");
this.print(node.property, node);
}
function JSXSpreadAttribute(node) {
this.push("{...");
this.print(node.argument, node);
this.push("}");
}
function JSXExpressionContainer(node) {
this.push("{");
this.print(node.expression, node);
this.push("}");
}
function JSXText(node) {
this.push(node.value, true);
}
function JSXElement(node) {
var open = node.openingElement;
this.print(open, node);
if (open.selfClosing) return;
this.indent();
var _arr = node.children;
for (var _i = 0; _i < _arr.length; _i++) {
var child = _arr[_i];
this.print(child, node);
}
this.dedent();
this.print(node.closingElement, node);
}
function JSXOpeningElement(node) {
this.push("<");
this.print(node.name, node);
if (node.attributes.length > 0) {
this.push(" ");
this.printJoin(node.attributes, node, { separator: " " });
}
this.push(node.selfClosing ? " />" : ">");
}
function JSXClosingElement(node) {
this.push("</");
this.print(node.name, node);
this.push(">");
}
function JSXEmptyExpression() {}
+95
View File
@@ -0,0 +1,95 @@
"use strict";
var _interopRequireWildcard = require("babel-runtime/helpers/interop-require-wildcard")["default"];
exports.__esModule = true;
exports._params = _params;
exports._method = _method;
exports.FunctionExpression = FunctionExpression;
exports.ArrowFunctionExpression = ArrowFunctionExpression;
var _babelTypes = require("babel-types");
var t = _interopRequireWildcard(_babelTypes);
function _params(node) {
// istanbul ignore next
var _this = this;
this.print(node.typeParameters, node);
this.push("(");
this.printList(node.params, node, {
iterator: function iterator(node) {
if (node.optional) _this.push("?");
_this.print(node.typeAnnotation, node);
}
});
this.push(")");
if (node.returnType) {
this.print(node.returnType, node);
}
}
function _method(node) {
var kind = node.kind;
var key = node.key;
if (kind === "method" || kind === "init") {
if (node.generator) {
this.push("*");
}
}
if (kind === "get" || kind === "set") {
this.push(kind + " ");
}
if (node.async) this.push("async ");
if (node.computed) {
this.push("[");
this.print(key, node);
this.push("]");
} else {
this.print(key, node);
}
this._params(node);
this.space();
this.print(node.body, node);
}
function FunctionExpression(node) {
if (node.async) this.push("async ");
this.push("function");
if (node.generator) this.push("*");
if (node.id) {
this.push(" ");
this.print(node.id, node);
} else {
this.space();
}
this._params(node);
this.space();
this.print(node.body, node);
}
exports.FunctionDeclaration = FunctionExpression;
function ArrowFunctionExpression(node) {
if (node.async) this.push("async ");
if (node.params.length === 1 && t.isIdentifier(node.params[0])) {
this.print(node.params[0], node);
} else {
this._params(node);
}
this.push(" => ");
this.print(node.body, node);
}
+157
View File
@@ -0,0 +1,157 @@
"use strict";
var _interopRequireWildcard = require("babel-runtime/helpers/interop-require-wildcard")["default"];
exports.__esModule = true;
exports.ImportSpecifier = ImportSpecifier;
exports.ImportDefaultSpecifier = ImportDefaultSpecifier;
exports.ExportDefaultSpecifier = ExportDefaultSpecifier;
exports.ExportSpecifier = ExportSpecifier;
exports.ExportNamespaceSpecifier = ExportNamespaceSpecifier;
exports.ExportAllDeclaration = ExportAllDeclaration;
exports.ExportNamedDeclaration = ExportNamedDeclaration;
exports.ExportDefaultDeclaration = ExportDefaultDeclaration;
exports.ImportDeclaration = ImportDeclaration;
exports.ImportNamespaceSpecifier = ImportNamespaceSpecifier;
var _babelTypes = require("babel-types");
var t = _interopRequireWildcard(_babelTypes);
function ImportSpecifier(node) {
this.print(node.imported, node);
if (node.local && node.local.name !== node.imported.name) {
this.push(" as ");
this.print(node.local, node);
}
}
function ImportDefaultSpecifier(node) {
this.print(node.local, node);
}
function ExportDefaultSpecifier(node) {
this.print(node.exported, node);
}
function ExportSpecifier(node) {
this.print(node.local, node);
if (node.exported && node.local.name !== node.exported.name) {
this.push(" as ");
this.print(node.exported, node);
}
}
function ExportNamespaceSpecifier(node) {
this.push("* as ");
this.print(node.exported, node);
}
function ExportAllDeclaration(node) {
this.push("export *");
if (node.exported) {
this.push(" as ");
this.print(node.exported, node);
}
this.push(" from ");
this.print(node.source, node);
this.semicolon();
}
function ExportNamedDeclaration() {
this.push("export ");
ExportDeclaration.apply(this, arguments);
}
function ExportDefaultDeclaration() {
this.push("export default ");
ExportDeclaration.apply(this, arguments);
}
function ExportDeclaration(node) {
if (node.declaration) {
var declar = node.declaration;
this.print(declar, node);
if (t.isStatement(declar) || t.isFunction(declar) || t.isClass(declar)) return;
} else {
if (node.exportKind === "type") {
this.push("type ");
}
var specifiers = node.specifiers.slice(0);
// print "special" specifiers first
var hasSpecial = false;
while (true) {
var first = specifiers[0];
if (t.isExportDefaultSpecifier(first) || t.isExportNamespaceSpecifier(first)) {
hasSpecial = true;
this.print(specifiers.shift(), node);
if (specifiers.length) {
this.push(", ");
}
} else {
break;
}
}
if (specifiers.length || !specifiers.length && !hasSpecial) {
this.push("{");
if (specifiers.length) {
this.space();
this.printJoin(specifiers, node, { separator: ", " });
this.space();
}
this.push("}");
}
if (node.source) {
this.push(" from ");
this.print(node.source, node);
}
}
this.ensureSemicolon();
}
function ImportDeclaration(node) {
this.push("import ");
if (node.importKind === "type" || node.importKind === "typeof") {
this.push(node.importKind + " ");
}
var specifiers = node.specifiers.slice(0);
if (specifiers && specifiers.length) {
// print "special" specifiers first
while (true) {
var first = specifiers[0];
if (t.isImportDefaultSpecifier(first) || t.isImportNamespaceSpecifier(first)) {
this.print(specifiers.shift(), node);
if (specifiers.length) {
this.push(", ");
}
} else {
break;
}
}
if (specifiers.length) {
this.push("{");
this.space();
this.printJoin(specifiers, node, { separator: ", " });
this.space();
this.push("}");
}
this.push(" from ");
}
this.print(node.source, node);
this.semicolon();
}
function ImportNamespaceSpecifier(node) {
this.push("* as ");
this.print(node.local, node);
}
+294
View File
@@ -0,0 +1,294 @@
"use strict";
var _interopRequireDefault = require("babel-runtime/helpers/interop-require-default")["default"];
var _interopRequireWildcard = require("babel-runtime/helpers/interop-require-wildcard")["default"];
exports.__esModule = true;
exports.WithStatement = WithStatement;
exports.IfStatement = IfStatement;
exports.ForStatement = ForStatement;
exports.WhileStatement = WhileStatement;
exports.DoWhileStatement = DoWhileStatement;
exports.LabeledStatement = LabeledStatement;
exports.TryStatement = TryStatement;
exports.CatchClause = CatchClause;
exports.SwitchStatement = SwitchStatement;
exports.SwitchCase = SwitchCase;
exports.DebuggerStatement = DebuggerStatement;
exports.VariableDeclaration = VariableDeclaration;
exports.VariableDeclarator = VariableDeclarator;
var _repeating = require("repeating");
var _repeating2 = _interopRequireDefault(_repeating);
var _babelTypes = require("babel-types");
var t = _interopRequireWildcard(_babelTypes);
var NON_ALPHABETIC_UNARY_OPERATORS = t.UPDATE_OPERATORS.concat(t.NUMBER_UNARY_OPERATORS).concat(["!"]);
function WithStatement(node) {
this.keyword("with");
this.push("(");
this.print(node.object, node);
this.push(")");
this.printBlock(node);
}
function IfStatement(node) {
this.keyword("if");
this.push("(");
this.print(node.test, node);
this.push(")");
this.space();
var needsBlock = node.alternate && t.isIfStatement(getLastStatement(node.consequent));
if (needsBlock) {
this.push("{");
this.newline();
this.indent();
}
this.printAndIndentOnComments(node.consequent, node);
if (needsBlock) {
this.dedent();
this.newline();
this.push("}");
}
if (node.alternate) {
if (this.isLast("}")) this.space();
this.push("else ");
this.printAndIndentOnComments(node.alternate, node);
}
}
// Recursively get the last statement.
function getLastStatement(statement) {
if (!t.isStatement(statement.body)) return statement;
return getLastStatement(statement.body);
}
function ForStatement(node) {
this.keyword("for");
this.push("(");
this._inForStatementInitCounter++;
this.print(node.init, node);
this._inForStatementInitCounter--;
this.push(";");
if (node.test) {
this.space();
this.print(node.test, node);
}
this.push(";");
if (node.update) {
this.space();
this.print(node.update, node);
}
this.push(")");
this.printBlock(node);
}
function WhileStatement(node) {
this.keyword("while");
this.push("(");
this.print(node.test, node);
this.push(")");
this.printBlock(node);
}
var buildForXStatement = function buildForXStatement(op) {
return function (node) {
this.keyword("for");
this.push("(");
this.print(node.left, node);
this.push(" " + op + " ");
this.print(node.right, node);
this.push(")");
this.printBlock(node);
};
};
var ForInStatement = buildForXStatement("in");
exports.ForInStatement = ForInStatement;
var ForOfStatement = buildForXStatement("of");
exports.ForOfStatement = ForOfStatement;
function DoWhileStatement(node) {
this.push("do ");
this.print(node.body, node);
this.space();
this.keyword("while");
this.push("(");
this.print(node.test, node);
this.push(");");
}
function buildLabelStatement(prefix) {
var key = arguments.length <= 1 || arguments[1] === undefined ? "label" : arguments[1];
return function (node) {
this.push(prefix);
var label = node[key];
if (label) {
if (!(this.format.minified && (t.isUnaryExpression(label, { prefix: true }) || t.isUpdateExpression(label, { prefix: true })) && NON_ALPHABETIC_UNARY_OPERATORS.indexOf(label.operator) > -1)) {
this.push(" ");
}
var terminatorState = this.startTerminatorless();
this.print(label, node);
this.endTerminatorless(terminatorState);
}
this.semicolon();
};
}
var ContinueStatement = buildLabelStatement("continue");
exports.ContinueStatement = ContinueStatement;
var ReturnStatement = buildLabelStatement("return", "argument");
exports.ReturnStatement = ReturnStatement;
var BreakStatement = buildLabelStatement("break");
exports.BreakStatement = BreakStatement;
var ThrowStatement = buildLabelStatement("throw", "argument");
exports.ThrowStatement = ThrowStatement;
function LabeledStatement(node) {
this.print(node.label, node);
this.push(": ");
this.print(node.body, node);
}
function TryStatement(node) {
this.keyword("try");
this.print(node.block, node);
this.space();
// Esprima bug puts the catch clause in a `handlers` array.
// see https://code.google.com/p/esprima/issues/detail?id=433
// We run into this from regenerator generated ast.
if (node.handlers) {
this.print(node.handlers[0], node);
} else {
this.print(node.handler, node);
}
if (node.finalizer) {
this.space();
this.push("finally ");
this.print(node.finalizer, node);
}
}
function CatchClause(node) {
this.keyword("catch");
this.push("(");
this.print(node.param, node);
this.push(")");
this.space();
this.print(node.body, node);
}
function SwitchStatement(node) {
this.keyword("switch");
this.push("(");
this.print(node.discriminant, node);
this.push(")");
this.space();
this.push("{");
this.printSequence(node.cases, node, {
indent: true,
addNewlines: function addNewlines(leading, cas) {
if (!leading && node.cases[node.cases.length - 1] === cas) return -1;
}
});
this.push("}");
}
function SwitchCase(node) {
if (node.test) {
this.push("case ");
this.print(node.test, node);
this.push(":");
} else {
this.push("default:");
}
if (node.consequent.length) {
this.newline();
this.printSequence(node.consequent, node, { indent: true });
}
}
function DebuggerStatement() {
this.push("debugger;");
}
function VariableDeclaration(node, parent) {
this.push(node.kind + " ");
var hasInits = false;
// don't add whitespace to loop heads
if (!t.isFor(parent)) {
var _arr = node.declarations;
for (var _i = 0; _i < _arr.length; _i++) {
var declar = _arr[_i];
if (declar.init) {
// has an init so let's split it up over multiple lines
hasInits = true;
}
}
}
//
// use a pretty separator when we aren't in compact mode, have initializers and don't have retainLines on
// this will format declarations like:
//
// let foo = "bar", bar = "foo";
//
// into
//
// let foo = "bar",
// bar = "foo";
//
var sep = undefined;
if (!this.format.compact && !this.format.concise && hasInits && !this.format.retainLines) {
sep = ",\n" + _repeating2["default"](" ", node.kind.length + 1);
}
//
this.printList(node.declarations, node, { separator: sep });
if (t.isFor(parent)) {
// don't give semicolons to these nodes since they'll be inserted in the parent generator
if (parent.left === node || parent.init === node) return;
}
this.semicolon();
}
function VariableDeclarator(node) {
this.print(node.id, node);
this.print(node.id.typeAnnotation, node);
if (node.init) {
this.space();
this.push("=");
this.space();
this.print(node.init, node);
}
}
@@ -0,0 +1,33 @@
"use strict";
exports.__esModule = true;
exports.TaggedTemplateExpression = TaggedTemplateExpression;
exports.TemplateElement = TemplateElement;
exports.TemplateLiteral = TemplateLiteral;
function TaggedTemplateExpression(node) {
this.print(node.tag, node);
this.print(node.quasi, node);
}
function TemplateElement(node) {
this._push(node.value.raw);
}
function TemplateLiteral(node) {
this.push("`");
var quasis = node.quasis;
for (var i = 0; i < quasis.length; i++) {
this.print(quasis[i], node);
if (i + 1 < quasis.length) {
this._push("${ ");
this.print(node.expressions[i], node);
this.push(" }");
}
}
this._push("`");
}
+169
View File
@@ -0,0 +1,169 @@
/* eslint max-len: 0 */
/* eslint quotes: 0 */
"use strict";
var _interopRequireWildcard = require("babel-runtime/helpers/interop-require-wildcard")["default"];
exports.__esModule = true;
exports.Identifier = Identifier;
exports.RestElement = RestElement;
exports.ObjectExpression = ObjectExpression;
exports.ObjectMethod = ObjectMethod;
exports.ObjectProperty = ObjectProperty;
exports.ArrayExpression = ArrayExpression;
exports.RegExpLiteral = RegExpLiteral;
exports.BooleanLiteral = BooleanLiteral;
exports.NullLiteral = NullLiteral;
exports.NumericLiteral = NumericLiteral;
exports.StringLiteral = StringLiteral;
exports._stringLiteral = _stringLiteral;
var _babelTypes = require("babel-types");
var t = _interopRequireWildcard(_babelTypes);
function Identifier(node) {
// FIXME: We hang variance off Identifer to support Flow's def-site variance.
// This is a terrible hack, but changing type annotations to use a new,
// dedicated node would be a breaking change. This should be cleaned up in
// the next major.
if (node.variance === "plus") {
this.push("+");
} else if (node.variance === "minus") {
this.push("-");
}
this.push(node.name);
}
function RestElement(node) {
this.push("...");
this.print(node.argument, node);
}
exports.SpreadElement = RestElement;
exports.SpreadProperty = RestElement;
exports.RestProperty = RestElement;
function ObjectExpression(node) {
var props = node.properties;
this.push("{");
this.printInnerComments(node);
if (props.length) {
this.space();
this.printList(props, node, { indent: true });
this.space();
}
this.push("}");
}
exports.ObjectPattern = ObjectExpression;
function ObjectMethod(node) {
this.printJoin(node.decorators, node, { separator: "" });
this._method(node);
}
function ObjectProperty(node) {
this.printJoin(node.decorators, node, { separator: "" });
if (node.computed) {
this.push("[");
this.print(node.key, node);
this.push("]");
} else {
// print `({ foo: foo = 5 } = {})` as `({ foo = 5 } = {});`
if (t.isAssignmentPattern(node.value) && t.isIdentifier(node.key) && node.key.name === node.value.left.name) {
this.print(node.value, node);
return;
}
this.print(node.key, node);
// shorthand!
if (node.shorthand && t.isIdentifier(node.key) && t.isIdentifier(node.value) && node.key.name === node.value.name) {
return;
}
}
this.push(":");
this.space();
this.print(node.value, node);
}
function ArrayExpression(node) {
var elems = node.elements;
var len = elems.length;
this.push("[");
this.printInnerComments(node);
for (var i = 0; i < elems.length; i++) {
var elem = elems[i];
if (elem) {
if (i > 0) this.space();
this.print(elem, node);
if (i < len - 1) this.push(",");
} else {
// If the array expression ends with a hole, that hole
// will be ignored by the interpreter, but if it ends with
// two (or more) holes, we need to write out two (or more)
// commas so that the resulting code is interpreted with
// both (all) of the holes.
this.push(",");
}
}
this.push("]");
}
exports.ArrayPattern = ArrayExpression;
function RegExpLiteral(node) {
this.push("/" + node.pattern + "/" + node.flags);
}
function BooleanLiteral(node) {
this.push(node.value ? "true" : "false");
}
function NullLiteral() {
this.push("null");
}
function NumericLiteral(node) {
this.push(node.value + "");
}
function StringLiteral(node, parent) {
this.push(this._stringLiteral(node.value, parent));
}
function _stringLiteral(val, parent) {
val = JSON.stringify(val);
// escape illegal js but valid json unicode characters
val = val.replace(/[\u000A\u000D\u2028\u2029]/g, function (c) {
return "\\u" + ("0000" + c.charCodeAt(0).toString(16)).slice(-4);
});
if (this.format.quotes === "single" && !t.isJSX(parent)) {
// remove double quotes
val = val.slice(1, -1);
// unescape double quotes
val = val.replace(/\\"/g, '"');
// escape single quotes
val = val.replace(/'/g, "\\'");
// add single quotes
val = "'" + val + "'";
}
return val;
}
+177
View File
@@ -0,0 +1,177 @@
"use strict";
var _inherits = require("babel-runtime/helpers/inherits")["default"];
var _classCallCheck = require("babel-runtime/helpers/class-call-check")["default"];
var _interopRequireDefault = require("babel-runtime/helpers/interop-require-default")["default"];
var _interopRequireWildcard = require("babel-runtime/helpers/interop-require-wildcard")["default"];
exports.__esModule = true;
var _detectIndent = require("detect-indent");
var _detectIndent2 = _interopRequireDefault(_detectIndent);
var _whitespace = require("./whitespace");
var _whitespace2 = _interopRequireDefault(_whitespace);
var _sourceMap = require("./source-map");
var _sourceMap2 = _interopRequireDefault(_sourceMap);
var _position = require("./position");
var _position2 = _interopRequireDefault(_position);
var _babelMessages = require("babel-messages");
var messages = _interopRequireWildcard(_babelMessages);
var _printer = require("./printer");
var _printer2 = _interopRequireDefault(_printer);
/**
* Babel's code generator, turns an ast into code, maintaining sourcemaps,
* user preferences, and valid output.
*/
var CodeGenerator = (function (_Printer) {
_inherits(CodeGenerator, _Printer);
function CodeGenerator(ast, opts, code) {
_classCallCheck(this, CodeGenerator);
opts = opts || {};
var comments = ast.comments || [];
var tokens = ast.tokens || [];
var format = CodeGenerator.normalizeOptions(code, opts, tokens);
var position = new _position2["default"]();
_Printer.call(this, position, format);
this.comments = comments;
this.position = position;
this.tokens = tokens;
this.format = format;
this.opts = opts;
this.ast = ast;
this._inForStatementInitCounter = 0;
this.whitespace = new _whitespace2["default"](tokens);
this.map = new _sourceMap2["default"](position, opts, code);
}
/**
* Normalize generator options, setting defaults.
*
* - Detects code indentation.
* - If `opts.compact = "auto"` and the code is over 100KB, `compact` will be set to `true`.
*/
CodeGenerator.normalizeOptions = function normalizeOptions(code, opts, tokens) {
var style = " ";
if (code && typeof code === "string") {
var _indent = _detectIndent2["default"](code).indent;
if (_indent && _indent !== " ") style = _indent;
}
var format = {
auxiliaryCommentBefore: opts.auxiliaryCommentBefore,
auxiliaryCommentAfter: opts.auxiliaryCommentAfter,
shouldPrintComment: opts.shouldPrintComment,
retainLines: opts.retainLines,
comments: opts.comments == null || opts.comments,
compact: opts.compact,
minified: opts.minified,
concise: opts.concise,
quotes: opts.quotes || CodeGenerator.findCommonStringDelimiter(code, tokens),
indent: {
adjustMultilineComment: true,
style: style,
base: 0
}
};
if (format.minified) {
format.compact = true;
}
if (format.compact === "auto") {
format.compact = code.length > 100000; // 100KB
if (format.compact) {
console.error("[BABEL] " + messages.get("codeGeneratorDeopt", opts.filename, "100KB"));
}
}
if (format.compact) {
format.indent.adjustMultilineComment = false;
}
return format;
};
/**
* Determine if input code uses more single or double quotes.
*/
CodeGenerator.findCommonStringDelimiter = function findCommonStringDelimiter(code, tokens) {
var occurences = {
single: 0,
double: 0
};
var checked = 0;
for (var i = 0; i < tokens.length; i++) {
var token = tokens[i];
if (token.type.label !== "string") continue;
var raw = code.slice(token.start, token.end);
if (raw[0] === "'") {
occurences.single++;
} else {
occurences.double++;
}
checked++;
if (checked >= 3) break;
}
if (occurences.single > occurences.double) {
return "single";
} else {
return "double";
}
};
/**
* Generate code and sourcemap from ast.
*
* Appends comments that weren't attached to any node to the end of the generated output.
*/
CodeGenerator.prototype.generate = function generate() {
this.print(this.ast);
this.printAuxAfterComment();
return {
map: this.map.get(),
code: this.get()
};
};
return CodeGenerator;
})(_printer2["default"]);
exports.CodeGenerator = CodeGenerator;
exports["default"] = function (ast, opts, code) {
var gen = new CodeGenerator(ast, opts, code);
return gen.generate();
};
+100
View File
@@ -0,0 +1,100 @@
"use strict";
var _Object$keys = require("babel-runtime/core-js/object/keys")["default"];
var _interopRequireDefault = require("babel-runtime/helpers/interop-require-default")["default"];
var _interopRequireWildcard = require("babel-runtime/helpers/interop-require-wildcard")["default"];
exports.__esModule = true;
exports.isUserWhitespacable = isUserWhitespacable;
exports.needsWhitespace = needsWhitespace;
exports.needsWhitespaceBefore = needsWhitespaceBefore;
exports.needsWhitespaceAfter = needsWhitespaceAfter;
exports.needsParens = needsParens;
var _whitespace = require("./whitespace");
var _whitespace2 = _interopRequireDefault(_whitespace);
var _parentheses = require("./parentheses");
var parens = _interopRequireWildcard(_parentheses);
var _babelTypes = require("babel-types");
var t = _interopRequireWildcard(_babelTypes);
function find(obj, node, parent, printStack) {
if (!obj) return;
var result = undefined;
var types = _Object$keys(obj);
for (var i = 0; i < types.length; i++) {
var type = types[i];
if (t.is(type, node)) {
var fn = obj[type];
result = fn(node, parent, printStack);
if (result != null) break;
}
}
return result;
}
function isOrHasCallExpression(node) {
if (t.isCallExpression(node)) {
return true;
}
if (t.isMemberExpression(node)) {
return isOrHasCallExpression(node.object) || !node.computed && isOrHasCallExpression(node.property);
} else {
return false;
}
}
function isUserWhitespacable(node) {
return t.isUserWhitespacable(node);
}
function needsWhitespace(node, parent, type) {
if (!node) return 0;
if (t.isExpressionStatement(node)) {
node = node.expression;
}
var linesInfo = find(_whitespace2["default"].nodes, node, parent);
if (!linesInfo) {
var items = find(_whitespace2["default"].list, node, parent);
if (items) {
for (var i = 0; i < items.length; i++) {
linesInfo = needsWhitespace(items[i], node, type);
if (linesInfo) break;
}
}
}
return linesInfo && linesInfo[type] || 0;
}
function needsWhitespaceBefore(node, parent) {
return needsWhitespace(node, parent, "before");
}
function needsWhitespaceAfter(node, parent) {
return needsWhitespace(node, parent, "after");
}
function needsParens(node, parent, printStack) {
if (!parent) return false;
if (t.isNewExpression(parent) && parent.callee === node) {
if (isOrHasCallExpression(node)) return true;
}
return find(parens, node, parent, printStack);
}
+281
View File
@@ -0,0 +1,281 @@
"use strict";
var _interopRequireWildcard = require("babel-runtime/helpers/interop-require-wildcard")["default"];
exports.__esModule = true;
exports.NullableTypeAnnotation = NullableTypeAnnotation;
exports.UpdateExpression = UpdateExpression;
exports.ObjectExpression = ObjectExpression;
exports.Binary = Binary;
exports.BinaryExpression = BinaryExpression;
exports.SequenceExpression = SequenceExpression;
exports.YieldExpression = YieldExpression;
exports.ClassExpression = ClassExpression;
exports.UnaryLike = UnaryLike;
exports.FunctionExpression = FunctionExpression;
exports.ArrowFunctionExpression = ArrowFunctionExpression;
exports.ConditionalExpression = ConditionalExpression;
exports.AssignmentExpression = AssignmentExpression;
var _babelTypes = require("babel-types");
var t = _interopRequireWildcard(_babelTypes);
var PRECEDENCE = {
"||": 0,
"&&": 1,
"|": 2,
"^": 3,
"&": 4,
"==": 5,
"===": 5,
"!=": 5,
"!==": 5,
"<": 6,
">": 6,
"<=": 6,
">=": 6,
"in": 6,
"instanceof": 6,
">>": 7,
"<<": 7,
">>>": 7,
"+": 8,
"-": 8,
"*": 9,
"/": 9,
"%": 9,
"**": 10
};
function NullableTypeAnnotation(node, parent) {
return t.isArrayTypeAnnotation(parent);
}
exports.FunctionTypeAnnotation = NullableTypeAnnotation;
function UpdateExpression(node, parent) {
if (t.isMemberExpression(parent) && parent.object === node) {
// (foo++).test()
return true;
}
return false;
}
function ObjectExpression(node, parent, printStack) {
if (t.isExpressionStatement(parent)) {
// ({ foo: "bar" });
return true;
}
return isFirstInStatement(printStack, true);
}
function Binary(node, parent) {
if ((t.isCallExpression(parent) || t.isNewExpression(parent)) && parent.callee === node) {
return true;
}
if (t.isUnaryLike(parent)) {
return true;
}
if (t.isMemberExpression(parent) && parent.object === node) {
return true;
}
if (t.isBinary(parent)) {
var parentOp = parent.operator;
var parentPos = PRECEDENCE[parentOp];
var nodeOp = node.operator;
var nodePos = PRECEDENCE[nodeOp];
if (parentPos > nodePos) {
return true;
}
// Logical expressions with the same precedence don't need parens.
if (parentPos === nodePos && parent.right === node && !t.isLogicalExpression(parent)) {
return true;
}
}
return false;
}
function BinaryExpression(node, parent) {
if (node.operator === "in") {
// let i = (1 in []);
if (t.isVariableDeclarator(parent)) {
return true;
}
// for ((1 in []);;);
if (t.isFor(parent)) {
return true;
}
}
return false;
}
function SequenceExpression(node, parent) {
if (t.isForStatement(parent)) {
// Although parentheses wouldn"t hurt around sequence
// expressions in the head of for loops, traditional style
// dictates that e.g. i++, j++ should not be wrapped with
// parentheses.
return false;
}
if (t.isExpressionStatement(parent) && parent.expression === node) {
return false;
}
if (t.isReturnStatement(parent)) {
return false;
}
if (t.isThrowStatement(parent)) {
return false;
}
if (t.isSwitchStatement(parent) && parent.discriminant === node) {
return false;
}
if (t.isWhileStatement(parent) && parent.test === node) {
return false;
}
if (t.isIfStatement(parent) && parent.test === node) {
return false;
}
if (t.isForInStatement(parent) && parent.right === node) {
return false;
}
// Otherwise err on the side of overparenthesization, adding
// explicit exceptions above if this proves overzealous.
return true;
}
function YieldExpression(node, parent) {
return t.isBinary(parent) || t.isUnaryLike(parent) || t.isCallExpression(parent) || t.isMemberExpression(parent) || t.isNewExpression(parent);
}
exports.AwaitExpression = YieldExpression;
function ClassExpression(node, parent) {
// (class {});
if (t.isExpressionStatement(parent)) {
return true;
}
// export default (class () {});
if (t.isExportDeclaration(parent)) {
return true;
}
return false;
}
function UnaryLike(node, parent) {
if (t.isMemberExpression(parent, { object: node })) {
return true;
}
if (t.isCallExpression(parent, { callee: node }) || t.isNewExpression(parent, { callee: node })) {
return true;
}
return false;
}
function FunctionExpression(node, parent, printStack) {
// (function () {});
if (t.isExpressionStatement(parent)) {
return true;
}
// export default (function () {});
if (t.isExportDeclaration(parent)) {
return true;
}
return isFirstInStatement(printStack);
}
function ArrowFunctionExpression(node, parent) {
// export default (function () {});
if (t.isExportDeclaration(parent)) {
return true;
}
if (t.isBinaryExpression(parent) || t.isLogicalExpression(parent)) {
return true;
}
if (t.isUnaryExpression(parent)) {
return true;
}
return UnaryLike(node, parent);
}
function ConditionalExpression(node, parent) {
if (t.isUnaryLike(parent)) {
return true;
}
if (t.isBinary(parent)) {
return true;
}
if (t.isConditionalExpression(parent, { test: node })) {
return true;
}
return UnaryLike(node, parent);
}
function AssignmentExpression(node) {
if (t.isObjectPattern(node.left)) {
return true;
} else {
return ConditionalExpression.apply(undefined, arguments);
}
}
// Walk up the print stack to deterimine if our node can come first
// in statement.
function isFirstInStatement(printStack) {
var considerArrow = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1];
var i = printStack.length - 1;
var node = printStack[i];
i--;
var parent = printStack[i];
while (i > 0) {
if (t.isExpressionStatement(parent, { expression: node })) {
return true;
}
if (considerArrow && t.isArrowFunctionExpression(parent, { body: node })) {
return true;
}
if (t.isCallExpression(parent, { callee: node }) || t.isSequenceExpression(parent) && parent.expressions[0] === node || t.isMemberExpression(parent, { object: node }) || t.isConditional(parent, { test: node }) || t.isBinary(parent, { left: node }) || t.isAssignmentExpression(parent, { left: node })) {
node = parent;
i--;
parent = printStack[i];
} else {
return false;
}
}
return false;
}
+242
View File
@@ -0,0 +1,242 @@
"use strict";
var _interopRequireDefault = require("babel-runtime/helpers/interop-require-default")["default"];
var _interopRequireWildcard = require("babel-runtime/helpers/interop-require-wildcard")["default"];
var _lodashLangIsBoolean = require("lodash/lang/isBoolean");
var _lodashLangIsBoolean2 = _interopRequireDefault(_lodashLangIsBoolean);
var _lodashCollectionEach = require("lodash/collection/each");
var _lodashCollectionEach2 = _interopRequireDefault(_lodashCollectionEach);
var _lodashCollectionMap = require("lodash/collection/map");
var _lodashCollectionMap2 = _interopRequireDefault(_lodashCollectionMap);
var _babelTypes = require("babel-types");
var t = _interopRequireWildcard(_babelTypes);
/**
* Crawl a node to test if it contains a CallExpression, a Function, or a Helper.
*
* @example
* crawl(node)
* // { hasCall: false, hasFunction: true, hasHelper: false }
*/
function crawl(node) {
var state = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
if (t.isMemberExpression(node)) {
crawl(node.object, state);
if (node.computed) crawl(node.property, state);
} else if (t.isBinary(node) || t.isAssignmentExpression(node)) {
crawl(node.left, state);
crawl(node.right, state);
} else if (t.isCallExpression(node)) {
state.hasCall = true;
crawl(node.callee, state);
} else if (t.isFunction(node)) {
state.hasFunction = true;
} else if (t.isIdentifier(node)) {
state.hasHelper = state.hasHelper || isHelper(node.callee);
}
return state;
}
/**
* Test if a node is or has a helper.
*/
function isHelper(node) {
if (t.isMemberExpression(node)) {
return isHelper(node.object) || isHelper(node.property);
} else if (t.isIdentifier(node)) {
return node.name === "require" || node.name[0] === "_";
} else if (t.isCallExpression(node)) {
return isHelper(node.callee);
} else if (t.isBinary(node) || t.isAssignmentExpression(node)) {
return t.isIdentifier(node.left) && isHelper(node.left) || isHelper(node.right);
} else {
return false;
}
}
function isType(node) {
return t.isLiteral(node) || t.isObjectExpression(node) || t.isArrayExpression(node) || t.isIdentifier(node) || t.isMemberExpression(node);
}
/**
* Tests for node types that need whitespace.
*/
exports.nodes = {
/**
* Test if AssignmentExpression needs whitespace.
*/
AssignmentExpression: function AssignmentExpression(node) {
var state = crawl(node.right);
if (state.hasCall && state.hasHelper || state.hasFunction) {
return {
before: state.hasFunction,
after: true
};
}
},
/**
* Test if SwitchCase needs whitespace.
*/
SwitchCase: function SwitchCase(node, parent) {
return {
before: node.consequent.length || parent.cases[0] === node
};
},
/**
* Test if LogicalExpression needs whitespace.
*/
LogicalExpression: function LogicalExpression(node) {
if (t.isFunction(node.left) || t.isFunction(node.right)) {
return {
after: true
};
}
},
/**
* Test if Literal needs whitespace.
*/
Literal: function Literal(node) {
if (node.value === "use strict") {
return {
after: true
};
}
},
/**
* Test if CallExpression needs whitespace.
*/
CallExpression: function CallExpression(node) {
if (t.isFunction(node.callee) || isHelper(node)) {
return {
before: true,
after: true
};
}
},
/**
* Test if VariableDeclaration needs whitespace.
*/
VariableDeclaration: function VariableDeclaration(node) {
for (var i = 0; i < node.declarations.length; i++) {
var declar = node.declarations[i];
var enabled = isHelper(declar.id) && !isType(declar.init);
if (!enabled) {
var state = crawl(declar.init);
enabled = isHelper(declar.init) && state.hasCall || state.hasFunction;
}
if (enabled) {
return {
before: true,
after: true
};
}
}
},
/**
* Test if IfStatement needs whitespace.
*/
IfStatement: function IfStatement(node) {
if (t.isBlockStatement(node.consequent)) {
return {
before: true,
after: true
};
}
}
};
/**
* Test if Property or SpreadProperty needs whitespace.
*/
exports.nodes.ObjectProperty = exports.nodes.ObjectMethod = exports.nodes.SpreadProperty = function (node, parent) {
if (parent.properties[0] === node) {
return {
before: true
};
}
};
/**
* Returns lists from node types that need whitespace.
*/
exports.list = {
/**
* Return VariableDeclaration declarations init properties.
*/
VariableDeclaration: function VariableDeclaration(node) {
return _lodashCollectionMap2["default"](node.declarations, "init");
},
/**
* Return VariableDeclaration elements.
*/
ArrayExpression: function ArrayExpression(node) {
return node.elements;
},
/**
* Return VariableDeclaration properties.
*/
ObjectExpression: function ObjectExpression(node) {
return node.properties;
}
};
/**
* Add whitespace tests for nodes and their aliases.
*/
_lodashCollectionEach2["default"]({
Function: true,
Class: true,
Loop: true,
LabeledStatement: true,
SwitchStatement: true,
TryStatement: true
}, function (amounts, type) {
if (_lodashLangIsBoolean2["default"](amounts)) {
amounts = { after: amounts, before: amounts };
}
_lodashCollectionEach2["default"]([type].concat(t.FLIPPED_ALIAS_KEYS[type] || []), function (type) {
exports.nodes[type] = function () {
return amounts;
};
});
});
+52
View File
@@ -0,0 +1,52 @@
/**
* Track current position in code generation.
*/
"use strict";
var _classCallCheck = require("babel-runtime/helpers/class-call-check")["default"];
exports.__esModule = true;
var Position = (function () {
function Position() {
_classCallCheck(this, Position);
this.line = 1;
this.column = 0;
}
/**
* Push a string to the current position, mantaining the current line and column.
*/
Position.prototype.push = function push(str) {
for (var i = 0; i < str.length; i++) {
if (str[i] === "\n") {
this.line++;
this.column = 0;
} else {
this.column++;
}
}
};
/**
* Unshift a string from the current position, mantaining the current line and column.
*/
Position.prototype.unshift = function unshift(str) {
for (var i = 0; i < str.length; i++) {
if (str[i] === "\n") {
this.line--;
} else {
this.column--;
}
}
};
return Position;
})();
exports["default"] = Position;
module.exports = exports["default"];
+379
View File
@@ -0,0 +1,379 @@
/* eslint max-len: 0 */
"use strict";
var _inherits = require("babel-runtime/helpers/inherits")["default"];
var _classCallCheck = require("babel-runtime/helpers/class-call-check")["default"];
var _Object$assign = require("babel-runtime/core-js/object/assign")["default"];
var _interopRequireDefault = require("babel-runtime/helpers/interop-require-default")["default"];
var _interopRequireWildcard = require("babel-runtime/helpers/interop-require-wildcard")["default"];
exports.__esModule = true;
var _repeating = require("repeating");
var _repeating2 = _interopRequireDefault(_repeating);
var _buffer = require("./buffer");
var _buffer2 = _interopRequireDefault(_buffer);
var _node = require("./node");
var n = _interopRequireWildcard(_node);
var _babelTypes = require("babel-types");
var t = _interopRequireWildcard(_babelTypes);
var Printer = (function (_Buffer) {
_inherits(Printer, _Buffer);
function Printer() {
_classCallCheck(this, Printer);
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
_Buffer.call.apply(_Buffer, [this].concat(args));
this.insideAux = false;
this.printAuxAfterOnNextUserNode = false;
this._printStack = [];
}
Printer.prototype.print = function print(node, parent) {
var opts = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2];
if (!node) return;
this._lastPrintedIsEmptyStatement = false;
if (parent && parent._compact) {
node._compact = true;
}
var oldInAux = this.insideAux;
this.insideAux = !node.loc;
var oldConcise = this.format.concise;
if (node._compact) {
this.format.concise = true;
}
var printMethod = this[node.type];
if (!printMethod) {
throw new ReferenceError("unknown node of type " + JSON.stringify(node.type) + " with constructor " + JSON.stringify(node && node.constructor.name));
}
this._printStack.push(node);
if (node.loc) this.printAuxAfterComment();
this.printAuxBeforeComment(oldInAux);
var needsParens = n.needsParens(node, parent, this._printStack);
if (needsParens) this.push("(");
this.printLeadingComments(node, parent);
this.catchUp(node);
this._printNewline(true, node, parent, opts);
if (opts.before) opts.before();
this.map.mark(node);
this._print(node, parent);
// Check again if any of our children may have left an aux comment on the stack
if (node.loc) this.printAuxAfterComment();
this.printTrailingComments(node, parent);
if (needsParens) this.push(")");
// end
this._printStack.pop();
if (parent) this.map.mark(parent);
if (opts.after) opts.after();
this.format.concise = oldConcise;
this.insideAux = oldInAux;
this._printNewline(false, node, parent, opts);
};
Printer.prototype.printAuxBeforeComment = function printAuxBeforeComment(wasInAux) {
var comment = this.format.auxiliaryCommentBefore;
if (!wasInAux && this.insideAux && !this.printAuxAfterOnNextUserNode) {
this.printAuxAfterOnNextUserNode = true;
if (comment) this.printComment({
type: "CommentBlock",
value: comment
});
}
};
Printer.prototype.printAuxAfterComment = function printAuxAfterComment() {
if (this.printAuxAfterOnNextUserNode) {
this.printAuxAfterOnNextUserNode = false;
var comment = this.format.auxiliaryCommentAfter;
if (comment) this.printComment({
type: "CommentBlock",
value: comment
});
}
};
Printer.prototype.getPossibleRaw = function getPossibleRaw(node) {
var extra = node.extra;
if (extra && extra.raw != null && extra.rawValue != null && node.value === extra.rawValue) {
return extra.raw;
}
};
Printer.prototype._print = function _print(node, parent) {
// In minified mode we need to produce as little bytes as needed
// and need to make sure that string quoting is consistent.
// That means we have to always reprint as opposed to getting
// the raw value.
if (!this.format.minified) {
var extra = this.getPossibleRaw(node);
if (extra) {
this.push("");
this._push(extra);
return;
}
}
var printMethod = this[node.type];
printMethod.call(this, node, parent);
};
Printer.prototype.printJoin = function printJoin(nodes, parent) {
// istanbul ignore next
var _this = this;
var opts = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2];
if (!nodes || !nodes.length) return;
var len = nodes.length;
var node = undefined,
i = undefined;
if (opts.indent) this.indent();
var printOpts = {
statement: opts.statement,
addNewlines: opts.addNewlines,
after: function after() {
if (opts.iterator) {
opts.iterator(node, i);
}
if (opts.separator && parent.loc) {
_this.printAuxAfterComment();
}
if (opts.separator && i < len - 1) {
_this.push(opts.separator);
}
}
};
for (i = 0; i < nodes.length; i++) {
node = nodes[i];
this.print(node, parent, printOpts);
}
if (opts.indent) this.dedent();
};
Printer.prototype.printAndIndentOnComments = function printAndIndentOnComments(node, parent) {
var indent = !!node.leadingComments;
if (indent) this.indent();
this.print(node, parent);
if (indent) this.dedent();
};
Printer.prototype.printBlock = function printBlock(parent) {
var node = parent.body;
if (!t.isEmptyStatement(node)) {
this.space();
}
this.print(node, parent);
};
Printer.prototype.generateComment = function generateComment(comment) {
var val = comment.value;
if (comment.type === "CommentLine") {
val = "//" + val;
} else {
val = "/*" + val + "*/";
}
return val;
};
Printer.prototype.printTrailingComments = function printTrailingComments(node, parent) {
this.printComments(this.getComments("trailingComments", node, parent));
};
Printer.prototype.printLeadingComments = function printLeadingComments(node, parent) {
this.printComments(this.getComments("leadingComments", node, parent));
};
Printer.prototype.printInnerComments = function printInnerComments(node) {
var indent = arguments.length <= 1 || arguments[1] === undefined ? true : arguments[1];
if (!node.innerComments) return;
if (indent) this.indent();
this.printComments(node.innerComments);
if (indent) this.dedent();
};
Printer.prototype.printSequence = function printSequence(nodes, parent) {
var opts = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2];
opts.statement = true;
return this.printJoin(nodes, parent, opts);
};
Printer.prototype.printList = function printList(items, parent) {
var opts = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2];
if (opts.separator == null) {
opts.separator = ",";
if (!this.format.compact) opts.separator += " ";
}
return this.printJoin(items, parent, opts);
};
Printer.prototype._printNewline = function _printNewline(leading, node, parent, opts) {
if (!opts.statement && !n.isUserWhitespacable(node, parent)) {
return;
}
var lines = 0;
if (node.start != null && !node._ignoreUserWhitespace && this.tokens.length) {
// user node
if (leading) {
lines = this.whitespace.getNewlinesBefore(node);
} else {
lines = this.whitespace.getNewlinesAfter(node);
}
} else {
// generated node
if (!leading) lines++; // always include at least a single line after
if (opts.addNewlines) lines += opts.addNewlines(leading, node) || 0;
var needs = n.needsWhitespaceAfter;
if (leading) needs = n.needsWhitespaceBefore;
if (needs(node, parent)) lines++;
// generated nodes can't add starting file whitespace
if (!this.buf) lines = 0;
}
this.newline(lines);
};
Printer.prototype.getComments = function getComments(key, node) {
return node && node[key] || [];
};
Printer.prototype.shouldPrintComment = function shouldPrintComment(comment) {
if (this.format.shouldPrintComment) {
return this.format.shouldPrintComment(comment.value);
} else {
if (!this.format.minified && (comment.value.indexOf("@license") >= 0 || comment.value.indexOf("@preserve") >= 0)) {
return true;
} else {
return this.format.comments;
}
}
};
Printer.prototype.printComment = function printComment(comment) {
if (!this.shouldPrintComment(comment)) return;
if (comment.ignore) return;
comment.ignore = true;
if (comment.start != null) {
if (this.printedCommentStarts[comment.start]) return;
this.printedCommentStarts[comment.start] = true;
}
this.catchUp(comment);
// whitespace before
this.newline(this.whitespace.getNewlinesBefore(comment));
var column = this.position.column;
var val = this.generateComment(comment);
if (column && !this.isLast(["\n", " ", "[", "{"])) {
this._push(" ");
column++;
}
//
if (comment.type === "CommentBlock" && this.format.indent.adjustMultilineComment) {
var offset = comment.loc && comment.loc.start.column;
if (offset) {
var newlineRegex = new RegExp("\\n\\s{1," + offset + "}", "g");
val = val.replace(newlineRegex, "\n");
}
var indent = Math.max(this.indentSize(), column);
val = val.replace(/\n/g, "\n" + _repeating2["default"](" ", indent));
}
if (column === 0) {
val = this.getIndent() + val;
}
// force a newline for line comments when retainLines is set in case the next printed node
// doesn't catch up
if ((this.format.compact || this.format.concise || this.format.retainLines) && comment.type === "CommentLine") {
val += "\n";
}
//
this._push(val);
// whitespace after
this.newline(this.whitespace.getNewlinesAfter(comment));
};
Printer.prototype.printComments = function printComments(comments) {
if (!comments || !comments.length) return;
for (var _i = 0; _i < comments.length; _i++) {
var comment = comments[_i];
this.printComment(comment);
}
};
return Printer;
})(_buffer2["default"]);
exports["default"] = Printer;
var _arr = [require("./generators/template-literals"), require("./generators/expressions"), require("./generators/statements"), require("./generators/classes"), require("./generators/methods"), require("./generators/modules"), require("./generators/types"), require("./generators/flow"), require("./generators/base"), require("./generators/jsx")];
for (var _i2 = 0; _i2 < _arr.length; _i2++) {
var generator = _arr[_i2];
_Object$assign(Printer.prototype, generator);
}
module.exports = exports["default"];
+115
View File
@@ -0,0 +1,115 @@
"use strict";
var _classCallCheck = require("babel-runtime/helpers/class-call-check")["default"];
var _Object$keys = require("babel-runtime/core-js/object/keys")["default"];
var _interopRequireDefault = require("babel-runtime/helpers/interop-require-default")["default"];
var _interopRequireWildcard = require("babel-runtime/helpers/interop-require-wildcard")["default"];
exports.__esModule = true;
var _sourceMap = require("source-map");
var _sourceMap2 = _interopRequireDefault(_sourceMap);
var _babelTypes = require("babel-types");
var t = _interopRequireWildcard(_babelTypes);
/**
* Build a sourcemap.
*/
var SourceMap = (function () {
function SourceMap(position, opts, code) {
// istanbul ignore next
var _this = this;
_classCallCheck(this, SourceMap);
this.position = position;
this.opts = opts;
this.last = { generated: {}, original: {} };
if (opts.sourceMaps) {
this.map = new _sourceMap2["default"].SourceMapGenerator({
file: opts.sourceMapTarget,
sourceRoot: opts.sourceRoot
});
if (typeof code === "string") {
this.map.setSourceContent(opts.sourceFileName, code);
} else if (typeof code === "object") {
_Object$keys(code).forEach(function (sourceFileName) {
_this.map.setSourceContent(sourceFileName, code[sourceFileName]);
});
}
} else {
this.map = null;
}
}
/**
* Get the sourcemap.
*/
SourceMap.prototype.get = function get() {
var map = this.map;
if (map) {
return map.toJSON();
} else {
return map;
}
};
/**
* Mark a node's generated position, and add it to the sourcemap.
*/
SourceMap.prototype.mark = function mark(node) {
var loc = node.loc;
if (!loc) return; // no location info
var map = this.map;
if (!map) return; // no source map
if (t.isProgram(node) || t.isFile(node)) return; // illegal mapping nodes
var position = this.position;
var generated = {
line: position.line,
column: position.column
};
var original = loc.start;
// Avoid emitting duplicates on either side. Duplicated
// original values creates unnecesssarily large source maps
// and increases compile time. Duplicates on the generated
// side can lead to incorrect mappings.
if (comparePosition(original, this.last.original) || comparePosition(generated, this.last.generated)) {
return;
}
this.last = {
source: loc.filename || this.opts.sourceFileName,
generated: generated,
original: original
};
map.addMapping(this.last);
};
return SourceMap;
})();
exports["default"] = SourceMap;
function comparePosition(a, b) {
return a.line === b.line && a.column === b.column;
}
module.exports = exports["default"];
+115
View File
@@ -0,0 +1,115 @@
/**
* Get whitespace around tokens.
*/
"use strict";
var _classCallCheck = require("babel-runtime/helpers/class-call-check")["default"];
exports.__esModule = true;
var Whitespace = (function () {
function Whitespace(tokens) {
_classCallCheck(this, Whitespace);
this.tokens = tokens;
this.used = {};
}
/**
* Count all the newlines before a node.
*/
Whitespace.prototype.getNewlinesBefore = function getNewlinesBefore(node) {
var startToken = undefined;
var endToken = undefined;
var tokens = this.tokens;
var index = this._findToken(function (token) {
return token.start - node.start;
}, 0, tokens.length);
if (index >= 0) {
while (index && node.start === tokens[index - 1].start) --index;
startToken = tokens[index - 1];
endToken = tokens[index];
}
return this.getNewlinesBetween(startToken, endToken);
};
/**
* Count all the newlines after a node.
*/
Whitespace.prototype.getNewlinesAfter = function getNewlinesAfter(node) {
var startToken = undefined;
var endToken = undefined;
var tokens = this.tokens;
var index = this._findToken(function (token) {
return token.end - node.end;
}, 0, tokens.length);
if (index >= 0) {
while (index && node.end === tokens[index - 1].end) --index;
startToken = tokens[index];
endToken = tokens[index + 1];
if (endToken.type.label === ",") endToken = tokens[index + 2];
}
if (endToken && endToken.type.label === "eof") {
return 1;
} else {
var lines = this.getNewlinesBetween(startToken, endToken);
if (node.type === "CommentLine" && !lines) {
// line comment
return 1;
} else {
return lines;
}
}
};
/**
* Count all the newlines between two tokens.
*/
Whitespace.prototype.getNewlinesBetween = function getNewlinesBetween(startToken, endToken) {
if (!endToken || !endToken.loc) return 0;
var start = startToken ? startToken.loc.end.line : 1;
var end = endToken.loc.start.line;
var lines = 0;
for (var line = start; line < end; line++) {
if (typeof this.used[line] === "undefined") {
this.used[line] = true;
lines++;
}
}
return lines;
};
/**
* Find a token between start and end.
*/
Whitespace.prototype._findToken = function _findToken(test, start, end) {
if (start >= end) return -1;
var middle = start + end >>> 1;
var match = test(this.tokens[middle]);
if (match < 0) {
return this._findToken(test, middle + 1, end);
} else if (match > 0) {
return this._findToken(test, start, middle);
} else if (match === 0) {
return middle;
}
return -1;
};
return Whitespace;
})();
exports["default"] = Whitespace;
module.exports = exports["default"];
+106
View File
@@ -0,0 +1,106 @@
{
"_args": [
[
"babel-generator@^6.7.2",
"/Users/mromano/dev/react-sfs/node_modules/babel-core"
]
],
"_from": "babel-generator@>=6.7.2 <7.0.0",
"_id": "babel-generator@6.7.2",
"_inCache": true,
"_installable": true,
"_location": "/babel-generator",
"_nodeVersion": "5.5.0",
"_npmOperationalInternal": {
"host": "packages-13-west.internal.npmjs.com",
"tmp": "tmp/babel-generator-6.7.2.tgz_1457649689534_0.3395618465729058"
},
"_npmUser": {
"email": "amjad.masad@gmail.com",
"name": "amasad"
},
"_npmVersion": "3.3.12",
"_phantomChildren": {},
"_requested": {
"name": "babel-generator",
"raw": "babel-generator@^6.7.2",
"rawSpec": "^6.7.2",
"scope": null,
"spec": ">=6.7.2 <7.0.0",
"type": "range"
},
"_requiredBy": [
"/babel-core"
],
"_resolved": "https://registry.npmjs.org/babel-generator/-/babel-generator-6.7.2.tgz",
"_shasum": "cc9b6e013ecca7461bfd3a30017da5422815ef1f",
"_shrinkwrap": null,
"_spec": "babel-generator@^6.7.2",
"_where": "/Users/mromano/dev/react-sfs/node_modules/babel-core",
"author": {
"email": "sebmck@gmail.com",
"name": "Sebastian McKenzie"
},
"dependencies": {
"babel-messages": "^6.7.2",
"babel-runtime": "^5.0.0",
"babel-types": "^6.7.2",
"detect-indent": "^3.0.1",
"is-integer": "^1.0.4",
"lodash": "^3.10.1",
"repeating": "^1.1.3",
"source-map": "^0.5.0",
"trim-right": "^1.0.1"
},
"description": "Turns an AST into code.",
"devDependencies": {
"babel-helper-fixtures": "^6.6.5",
"babylon": "^6.7.0"
},
"directories": {},
"dist": {
"shasum": "cc9b6e013ecca7461bfd3a30017da5422815ef1f",
"tarball": "https://registry.npmjs.org/babel-generator/-/babel-generator-6.7.2.tgz"
},
"files": [
"lib"
],
"homepage": "https://babeljs.io/",
"license": "MIT",
"main": "lib/index.js",
"maintainers": [
{
"email": "amjad.masad@gmail.com",
"name": "amasad"
},
{
"email": "hi@henryzoo.com",
"name": "hzoo"
},
{
"email": "npm-public@jessemccarthy.net",
"name": "jmm"
},
{
"email": "loganfsmyth@gmail.com",
"name": "loganfsmyth"
},
{
"email": "sebmck@gmail.com",
"name": "sebmck"
},
{
"email": "me@thejameskyle.com",
"name": "thejameskyle"
}
],
"name": "babel-generator",
"optionalDependencies": {},
"readme": "ERROR: No README data found!",
"repository": {
"type": "git",
"url": "https://github.com/babel/babel/tree/master/packages/babel-generator"
},
"scripts": {},
"version": "6.7.2"
}
+3
View File
@@ -0,0 +1,3 @@
src
test
node_modules
+24
View File
@@ -0,0 +1,24 @@
# babel-helper-builder-react-jsx
## Usage
```javascript
type ElementState = {
tagExpr: Object; // tag node
tagName: string; // raw string tag name
args: Array<Object>; // array of call arguments
call?: Object; // optional call property that can be set to override the call expression returned
pre?: Function; // function called with (state: ElementState) before building attribs
post?: Function; // function called with (state: ElementState) after building attribs
};
require("babel-helper-builder-react-jsx")({
pre: function (state: ElementState) {
// called before building the element
},
post: function (state: ElementState) {
// called after building the element
}
});
```
+173
View File
@@ -0,0 +1,173 @@
"use strict";
var _interopRequireDefault = require("babel-runtime/helpers/interop-require-default")["default"];
var _interopRequireWildcard = require("babel-runtime/helpers/interop-require-wildcard")["default"];
exports.__esModule = true;
var _esutils = require("esutils");
var _esutils2 = _interopRequireDefault(_esutils);
var _babelTypes = require("babel-types");
var t = _interopRequireWildcard(_babelTypes);
// function called with (state: ElementState) after building attribs
exports["default"] = function (opts) {
var visitor = {};
visitor.JSXNamespacedName = function (path) {
throw path.buildCodeFrameError("Namespace tags are not supported. ReactJSX is not XML.");
};
visitor.JSXElement = {
exit: function exit(path, file) {
var callExpr = buildElementCall(path.get("openingElement"), file);
callExpr.arguments = callExpr.arguments.concat(path.node.children);
if (callExpr.arguments.length >= 3) {
callExpr._prettyCall = true;
}
path.replaceWith(t.inherits(callExpr, path.node));
}
};
return visitor;
function convertJSXIdentifier(node, parent) {
if (t.isJSXIdentifier(node)) {
if (node.name === "this" && t.isReferenced(node, parent)) {
return t.thisExpression();
} else if (_esutils2["default"].keyword.isIdentifierNameES6(node.name)) {
node.type = "Identifier";
} else {
return t.stringLiteral(node.name);
}
} else if (t.isJSXMemberExpression(node)) {
return t.memberExpression(convertJSXIdentifier(node.object, node), convertJSXIdentifier(node.property, node));
}
return node;
}
function convertAttributeValue(node) {
if (t.isJSXExpressionContainer(node)) {
return node.expression;
} else {
return node;
}
}
function convertAttribute(node) {
var value = convertAttributeValue(node.value || t.booleanLiteral(true));
if (t.isStringLiteral(value)) {
value.value = value.value.replace(/\n\s+/g, " ");
}
if (t.isValidIdentifier(node.name.name)) {
node.name.type = "Identifier";
} else {
node.name = t.stringLiteral(node.name.name);
}
return t.inherits(t.objectProperty(node.name, value), node);
}
function buildElementCall(path, file) {
path.parent.children = t.react.buildChildren(path.parent);
var tagExpr = convertJSXIdentifier(path.node.name, path.node);
var args = [];
var tagName = undefined;
if (t.isIdentifier(tagExpr)) {
tagName = tagExpr.name;
} else if (t.isLiteral(tagExpr)) {
tagName = tagExpr.value;
}
var state = {
tagExpr: tagExpr,
tagName: tagName,
args: args
};
if (opts.pre) {
opts.pre(state, file);
}
var attribs = path.node.attributes;
if (attribs.length) {
attribs = buildOpeningElementAttributes(attribs, file);
} else {
attribs = t.nullLiteral();
}
args.push(attribs);
if (opts.post) {
opts.post(state, file);
}
return state.call || t.callExpression(state.callee, args);
}
/**
* The logic for this is quite terse. It's because we need to
* support spread elements. We loop over all attributes,
* breaking on spreads, we then push a new object containg
* all prior attributes to an array for later processing.
*/
function buildOpeningElementAttributes(attribs, file) {
var _props = [];
var objs = [];
function pushProps() {
if (!_props.length) return;
objs.push(t.objectExpression(_props));
_props = [];
}
while (attribs.length) {
var prop = attribs.shift();
if (t.isJSXSpreadAttribute(prop)) {
pushProps();
objs.push(prop.argument);
} else {
_props.push(convertAttribute(prop));
}
}
pushProps();
if (objs.length === 1) {
// only one object
attribs = objs[0];
} else {
// looks like we have multiple objects
if (!t.isObjectExpression(objs[0])) {
objs.unshift(t.objectExpression([]));
}
// spread it
attribs = t.callExpression(file.addHelper("extends"), objs);
}
return attribs;
}
};
module.exports = exports["default"];
// tag node
// raw string tag name
// array of call arguments
// optional call property that can be set to override the call expression returned
// function called with (state: ElementState) before building attribs
+90
View File
@@ -0,0 +1,90 @@
{
"_args": [
[
"babel-helper-builder-react-jsx@^6.6.5",
"/Users/mromano/dev/react-sfs/node_modules/babel-plugin-transform-react-jsx"
]
],
"_from": "babel-helper-builder-react-jsx@>=6.6.5 <7.0.0",
"_id": "babel-helper-builder-react-jsx@6.6.5",
"_inCache": true,
"_installable": true,
"_location": "/babel-helper-builder-react-jsx",
"_nodeVersion": "5.1.0",
"_npmOperationalInternal": {
"host": "packages-12-west.internal.npmjs.com",
"tmp": "tmp/babel-helper-builder-react-jsx-6.6.5.tgz_1457133386284_0.9943406709935516"
},
"_npmUser": {
"email": "hi@henryzoo.com",
"name": "hzoo"
},
"_npmVersion": "3.6.0",
"_phantomChildren": {},
"_requested": {
"name": "babel-helper-builder-react-jsx",
"raw": "babel-helper-builder-react-jsx@^6.6.5",
"rawSpec": "^6.6.5",
"scope": null,
"spec": ">=6.6.5 <7.0.0",
"type": "range"
},
"_requiredBy": [
"/babel-plugin-transform-react-jsx"
],
"_resolved": "https://registry.npmjs.org/babel-helper-builder-react-jsx/-/babel-helper-builder-react-jsx-6.6.5.tgz",
"_shasum": "41b952de264ed3cbdc47dcfae40ac48d945ae368",
"_shrinkwrap": null,
"_spec": "babel-helper-builder-react-jsx@^6.6.5",
"_where": "/Users/mromano/dev/react-sfs/node_modules/babel-plugin-transform-react-jsx",
"dependencies": {
"babel-runtime": "^5.0.0",
"babel-types": "^6.6.5",
"esutils": "^2.0.0",
"lodash": "^3.10.0"
},
"description": "## Usage",
"devDependencies": {},
"directories": {},
"dist": {
"shasum": "41b952de264ed3cbdc47dcfae40ac48d945ae368",
"tarball": "https://registry.npmjs.org/babel-helper-builder-react-jsx/-/babel-helper-builder-react-jsx-6.6.5.tgz"
},
"license": "MIT",
"main": "lib/index.js",
"maintainers": [
{
"email": "amjad.masad@gmail.com",
"name": "amasad"
},
{
"email": "hi@henryzoo.com",
"name": "hzoo"
},
{
"email": "npm-public@jessemccarthy.net",
"name": "jmm"
},
{
"email": "loganfsmyth@gmail.com",
"name": "loganfsmyth"
},
{
"email": "sebmck@gmail.com",
"name": "sebmck"
},
{
"email": "me@thejameskyle.com",
"name": "thejameskyle"
}
],
"name": "babel-helper-builder-react-jsx",
"optionalDependencies": {},
"readme": "ERROR: No README data found!",
"repository": {
"type": "git",
"url": "https://github.com/babel/babel/tree/master/packages/babel-helper-builder-react-jsx"
},
"scripts": {},
"version": "6.6.5"
}
+3
View File
@@ -0,0 +1,3 @@
src
test
node_modules
+21
View File
@@ -0,0 +1,21 @@
# babel-helpers
> Collection of helper functions used by Babel transforms.
## Install
```js
$ npm install babel-helpers
```
## Usage
```js
import * as helpers from 'babel-helpers';
import * as t from 'babel-types';
const typeofHelper = helpers.get('typeof');
t.isExpressionStatement(typeofHelper);
// true
```
+71
View File
@@ -0,0 +1,71 @@
/* eslint max-len: 0 */
"use strict";
var _interopRequireDefault = require("babel-runtime/helpers/interop-require-default")["default"];
exports.__esModule = true;
var _babelTemplate = require("babel-template");
var _babelTemplate2 = _interopRequireDefault(_babelTemplate);
var helpers = {};
exports["default"] = helpers;
helpers["typeof"] = _babelTemplate2["default"]("\n (typeof Symbol === \"function\" && typeof Symbol.iterator === \"symbol\")\n ? function (obj) { return typeof obj; }\n : function (obj) { return obj && typeof Symbol === \"function\" && obj.constructor === Symbol ? \"symbol\" : typeof obj; };\n");
helpers.jsx = _babelTemplate2["default"]("\n (function () {\n var REACT_ELEMENT_TYPE = (typeof Symbol === \"function\" && Symbol.for && Symbol.for(\"react.element\")) || 0xeac7;\n\n return function createRawReactElement (type, props, key, children) {\n var defaultProps = type && type.defaultProps;\n var childrenLength = arguments.length - 3;\n\n if (!props && childrenLength !== 0) {\n // If we're going to assign props.children, we create a new object now\n // to avoid mutating defaultProps.\n props = {};\n }\n if (props && defaultProps) {\n for (var propName in defaultProps) {\n if (props[propName] === void 0) {\n props[propName] = defaultProps[propName];\n }\n }\n } else if (!props) {\n props = defaultProps || {};\n }\n\n if (childrenLength === 1) {\n props.children = children;\n } else if (childrenLength > 1) {\n var childArray = Array(childrenLength);\n for (var i = 0; i < childrenLength; i++) {\n childArray[i] = arguments[i + 3];\n }\n props.children = childArray;\n }\n\n return {\n $$typeof: REACT_ELEMENT_TYPE,\n type: type,\n key: key === undefined ? null : '' + key,\n ref: null,\n props: props,\n _owner: null,\n };\n };\n\n })()\n");
helpers.asyncToGenerator = _babelTemplate2["default"]("\n (function (fn) {\n return function () {\n var gen = fn.apply(this, arguments);\n return new Promise(function (resolve, reject) {\n function step(key, arg) {\n try {\n var info = gen[key](arg);\n var value = info.value;\n } catch (error) {\n reject(error);\n return;\n }\n\n if (info.done) {\n resolve(value);\n } else {\n return Promise.resolve(value).then(function (value) {\n return step(\"next\", value);\n }, function (err) {\n return step(\"throw\", err);\n });\n }\n }\n\n return step(\"next\");\n });\n };\n })\n");
helpers.classCallCheck = _babelTemplate2["default"]("\n (function (instance, Constructor) {\n if (!(instance instanceof Constructor)) {\n throw new TypeError(\"Cannot call a class as a function\");\n }\n });\n");
helpers.createClass = _babelTemplate2["default"]("\n (function() {\n function defineProperties(target, props) {\n for (var i = 0; i < props.length; i ++) {\n var descriptor = props[i];\n descriptor.enumerable = descriptor.enumerable || false;\n descriptor.configurable = true;\n if (\"value\" in descriptor) descriptor.writable = true;\n Object.defineProperty(target, descriptor.key, descriptor);\n }\n }\n\n return function (Constructor, protoProps, staticProps) {\n if (protoProps) defineProperties(Constructor.prototype, protoProps);\n if (staticProps) defineProperties(Constructor, staticProps);\n return Constructor;\n };\n })()\n");
helpers.defineEnumerableProperties = _babelTemplate2["default"]("\n (function (obj, descs) {\n for (var key in descs) {\n var desc = descs[key];\n desc.configurable = desc.enumerable = true;\n if (\"value\" in desc) desc.writable = true;\n Object.defineProperty(obj, key, desc);\n }\n return obj;\n })\n");
helpers.defaults = _babelTemplate2["default"]("\n (function (obj, defaults) {\n var keys = Object.getOwnPropertyNames(defaults);\n for (var i = 0; i < keys.length; i++) {\n var key = keys[i];\n var value = Object.getOwnPropertyDescriptor(defaults, key);\n if (value && value.configurable && obj[key] === undefined) {\n Object.defineProperty(obj, key, value);\n }\n }\n return obj;\n })\n");
helpers.defineProperty = _babelTemplate2["default"]("\n (function (obj, key, value) {\n // Shortcircuit the slow defineProperty path when possible.\n // We are trying to avoid issues where setters defined on the\n // prototype cause side effects under the fast path of simple\n // assignment. By checking for existence of the property with\n // the in operator, we can optimize most of this overhead away.\n if (key in obj) {\n Object.defineProperty(obj, key, {\n value: value,\n enumerable: true,\n configurable: true,\n writable: true\n });\n } else {\n obj[key] = value;\n }\n return obj;\n });\n");
helpers["extends"] = _babelTemplate2["default"]("\n Object.assign || (function (target) {\n for (var i = 1; i < arguments.length; i++) {\n var source = arguments[i];\n for (var key in source) {\n if (Object.prototype.hasOwnProperty.call(source, key)) {\n target[key] = source[key];\n }\n }\n }\n return target;\n })\n");
helpers.get = _babelTemplate2["default"]("\n (function get(object, property, receiver) {\n if (object === null) object = Function.prototype;\n\n var desc = Object.getOwnPropertyDescriptor(object, property);\n\n if (desc === undefined) {\n var parent = Object.getPrototypeOf(object);\n\n if (parent === null) {\n return undefined;\n } else {\n return get(parent, property, receiver);\n }\n } else if (\"value\" in desc) {\n return desc.value;\n } else {\n var getter = desc.get;\n\n if (getter === undefined) {\n return undefined;\n }\n\n return getter.call(receiver);\n }\n });\n");
helpers.inherits = _babelTemplate2["default"]("\n (function (subClass, superClass) {\n if (typeof superClass !== \"function\" && superClass !== null) {\n throw new TypeError(\"Super expression must either be null or a function, not \" + typeof superClass);\n }\n subClass.prototype = Object.create(superClass && superClass.prototype, {\n constructor: {\n value: subClass,\n enumerable: false,\n writable: true,\n configurable: true\n }\n });\n if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;\n })\n");
helpers["instanceof"] = _babelTemplate2["default"]("\n (function (left, right) {\n if (right != null && typeof Symbol !== \"undefined\" && right[Symbol.hasInstance]) {\n return right[Symbol.hasInstance](left);\n } else {\n return left instanceof right;\n }\n });\n");
helpers.interopRequireDefault = _babelTemplate2["default"]("\n (function (obj) {\n return obj && obj.__esModule ? obj : { default: obj };\n })\n");
helpers.interopRequireWildcard = _babelTemplate2["default"]("\n (function (obj) {\n if (obj && obj.__esModule) {\n return obj;\n } else {\n var newObj = {};\n if (obj != null) {\n for (var key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key];\n }\n }\n newObj.default = obj;\n return newObj;\n }\n })\n");
helpers.newArrowCheck = _babelTemplate2["default"]("\n (function (innerThis, boundThis) {\n if (innerThis !== boundThis) {\n throw new TypeError(\"Cannot instantiate an arrow function\");\n }\n });\n");
helpers.objectDestructuringEmpty = _babelTemplate2["default"]("\n (function (obj) {\n if (obj == null) throw new TypeError(\"Cannot destructure undefined\");\n });\n");
helpers.objectWithoutProperties = _babelTemplate2["default"]("\n (function (obj, keys) {\n var target = {};\n for (var i in obj) {\n if (keys.indexOf(i) >= 0) continue;\n if (!Object.prototype.hasOwnProperty.call(obj, i)) continue;\n target[i] = obj[i];\n }\n return target;\n })\n");
helpers.possibleConstructorReturn = _babelTemplate2["default"]("\n (function (self, call) {\n if (!self) {\n throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\");\n }\n return call && (typeof call === \"object\" || typeof call === \"function\") ? call : self;\n });\n");
helpers.selfGlobal = _babelTemplate2["default"]("\n typeof global === \"undefined\" ? self : global\n");
helpers.set = _babelTemplate2["default"]("\n (function set(object, property, value, receiver) {\n var desc = Object.getOwnPropertyDescriptor(object, property);\n\n if (desc === undefined) {\n var parent = Object.getPrototypeOf(object);\n\n if (parent !== null) {\n set(parent, property, value, receiver);\n }\n } else if (\"value\" in desc && desc.writable) {\n desc.value = value;\n } else {\n var setter = desc.set;\n\n if (setter !== undefined) {\n setter.call(receiver, value);\n }\n }\n\n return value;\n });\n");
helpers.slicedToArray = _babelTemplate2["default"]("\n (function () {\n // Broken out into a separate function to avoid deoptimizations due to the try/catch for the\n // array iterator case.\n function sliceIterator(arr, i) {\n // this is an expanded form of `for...of` that properly supports abrupt completions of\n // iterators etc. variable names have been minimised to reduce the size of this massive\n // helper. sometimes spec compliancy is annoying :(\n //\n // _n = _iteratorNormalCompletion\n // _d = _didIteratorError\n // _e = _iteratorError\n // _i = _iterator\n // _s = _step\n\n var _arr = [];\n var _n = true;\n var _d = false;\n var _e = undefined;\n try {\n for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {\n _arr.push(_s.value);\n if (i && _arr.length === i) break;\n }\n } catch (err) {\n _d = true;\n _e = err;\n } finally {\n try {\n if (!_n && _i[\"return\"]) _i[\"return\"]();\n } finally {\n if (_d) throw _e;\n }\n }\n return _arr;\n }\n\n return function (arr, i) {\n if (Array.isArray(arr)) {\n return arr;\n } else if (Symbol.iterator in Object(arr)) {\n return sliceIterator(arr, i);\n } else {\n throw new TypeError(\"Invalid attempt to destructure non-iterable instance\");\n }\n };\n })();\n");
helpers.slicedToArrayLoose = _babelTemplate2["default"]("\n (function (arr, i) {\n if (Array.isArray(arr)) {\n return arr;\n } else if (Symbol.iterator in Object(arr)) {\n var _arr = [];\n for (var _iterator = arr[Symbol.iterator](), _step; !(_step = _iterator.next()).done;) {\n _arr.push(_step.value);\n if (i && _arr.length === i) break;\n }\n return _arr;\n } else {\n throw new TypeError(\"Invalid attempt to destructure non-iterable instance\");\n }\n });\n");
helpers.taggedTemplateLiteral = _babelTemplate2["default"]("\n (function (strings, raw) {\n return Object.freeze(Object.defineProperties(strings, {\n raw: { value: Object.freeze(raw) }\n }));\n });\n");
helpers.taggedTemplateLiteralLoose = _babelTemplate2["default"]("\n (function (strings, raw) {\n strings.raw = raw;\n return strings;\n });\n");
helpers.temporalRef = _babelTemplate2["default"]("\n (function (val, name, undef) {\n if (val === undef) {\n throw new ReferenceError(name + \" is not defined - temporal dead zone\");\n } else {\n return val;\n }\n })\n");
helpers.temporalUndefined = _babelTemplate2["default"]("\n ({})\n");
helpers.toArray = _babelTemplate2["default"]("\n (function (arr) {\n return Array.isArray(arr) ? arr : Array.from(arr);\n });\n");
helpers.toConsumableArray = _babelTemplate2["default"]("\n (function (arr) {\n if (Array.isArray(arr)) {\n for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) arr2[i] = arr[i];\n return arr2;\n } else {\n return Array.from(arr);\n }\n });\n");
module.exports = exports["default"];
+30
View File
@@ -0,0 +1,30 @@
/* eslint no-confusing-arrow: 0 */
"use strict";
var _Object$keys = require("babel-runtime/core-js/object/keys")["default"];
var _interopRequireDefault = require("babel-runtime/helpers/interop-require-default")["default"];
exports.__esModule = true;
exports.get = get;
var _helpers = require("./helpers");
var _helpers2 = _interopRequireDefault(_helpers);
function get(name) {
var fn = _helpers2["default"][name];
if (!fn) throw new ReferenceError("Unknown helper " + name);
return fn().expression;
}
var list = _Object$keys(_helpers2["default"]).map(function (name) {
return name[0] === "_" ? name.slice(1) : name;
}).filter(function (name) {
return name !== "__esModule";
});
exports.list = list;
exports["default"] = get;
+93
View File
@@ -0,0 +1,93 @@
{
"_args": [
[
"babel-helpers@^6.6.0",
"/Users/mromano/dev/react-sfs/node_modules/babel-core"
]
],
"_from": "babel-helpers@>=6.6.0 <7.0.0",
"_id": "babel-helpers@6.6.0",
"_inCache": true,
"_installable": true,
"_location": "/babel-helpers",
"_nodeVersion": "5.1.0",
"_npmOperationalInternal": {
"host": "packages-5-east.internal.npmjs.com",
"tmp": "tmp/babel-helpers-6.6.0.tgz_1456780353970_0.22683173697441816"
},
"_npmUser": {
"email": "hi@henryzoo.com",
"name": "hzoo"
},
"_npmVersion": "3.6.0",
"_phantomChildren": {},
"_requested": {
"name": "babel-helpers",
"raw": "babel-helpers@^6.6.0",
"rawSpec": "^6.6.0",
"scope": null,
"spec": ">=6.6.0 <7.0.0",
"type": "range"
},
"_requiredBy": [
"/babel-core"
],
"_resolved": "https://registry.npmjs.org/babel-helpers/-/babel-helpers-6.6.0.tgz",
"_shasum": "4fb005326569eeec9f5990176b539ea3a424b71c",
"_shrinkwrap": null,
"_spec": "babel-helpers@^6.6.0",
"_where": "/Users/mromano/dev/react-sfs/node_modules/babel-core",
"author": {
"email": "sebmck@gmail.com",
"name": "Sebastian McKenzie"
},
"dependencies": {
"babel-runtime": "^5.0.0",
"babel-template": "^6.6.0"
},
"description": "Collection of helper functions used by Babel transforms.",
"devDependencies": {},
"directories": {},
"dist": {
"shasum": "4fb005326569eeec9f5990176b539ea3a424b71c",
"tarball": "https://registry.npmjs.org/babel-helpers/-/babel-helpers-6.6.0.tgz"
},
"homepage": "https://babeljs.io/",
"license": "MIT",
"main": "lib/index.js",
"maintainers": [
{
"email": "amjad.masad@gmail.com",
"name": "amasad"
},
{
"email": "hi@henryzoo.com",
"name": "hzoo"
},
{
"email": "npm-public@jessemccarthy.net",
"name": "jmm"
},
{
"email": "loganfsmyth@gmail.com",
"name": "loganfsmyth"
},
{
"email": "sebmck@gmail.com",
"name": "sebmck"
},
{
"email": "me@thejameskyle.com",
"name": "thejameskyle"
}
],
"name": "babel-helpers",
"optionalDependencies": {},
"readme": "ERROR: No README data found!",
"repository": {
"type": "git",
"url": "https://github.com/babel/babel/tree/master/packages/babel-helpers"
},
"scripts": {},
"version": "6.6.0"
}
+3
View File
@@ -0,0 +1,3 @@
src
test
node_modules
+18
View File
@@ -0,0 +1,18 @@
# babel-messages
> Collection of debug messages used by Babel.
## Install
```sh
$ npm install babel-messages
```
## Usage
```js
import * as messages from 'babel-messages';
messages.get('tailCallReassignmentDeopt');
// > "Function reference has been..."
```
+94
View File
@@ -0,0 +1,94 @@
/* eslint max-len: 0 */
"use strict";
var _interopRequireWildcard = require("babel-runtime/helpers/interop-require-wildcard")["default"];
exports.__esModule = true;
exports.get = get;
exports.parseArgs = parseArgs;
var _util = require("util");
var util = _interopRequireWildcard(_util);
/**
* Mapping of messages to be used in Babel.
* Messages can include $0-style placeholders.
*/
var MESSAGES = {
tailCallReassignmentDeopt: "Function reference has been reassigned, so it will probably be dereferenced, therefore we can't optimise this with confidence",
classesIllegalBareSuper: "Illegal use of bare super",
classesIllegalSuperCall: "Direct super call is illegal in non-constructor, use super.$1() instead",
scopeDuplicateDeclaration: "Duplicate declaration $1",
settersNoRest: "Setters aren't allowed to have a rest",
noAssignmentsInForHead: "No assignments allowed in for-in/of head",
expectedMemberExpressionOrIdentifier: "Expected type MemberExpression or Identifier",
invalidParentForThisNode: "We don't know how to handle this node within the current parent - please open an issue",
readOnly: "$1 is read-only",
unknownForHead: "Unknown node type $1 in ForStatement",
didYouMean: "Did you mean $1?",
codeGeneratorDeopt: "Note: The code generator has deoptimised the styling of $1 as it exceeds the max of $2.",
missingTemplatesDirectory: "no templates directory - this is most likely the result of a broken `npm publish`. Please report to https://github.com/babel/babel/issues",
unsupportedOutputType: "Unsupported output type $1",
illegalMethodName: "Illegal method name $1",
lostTrackNodePath: "We lost track of this node's position, likely because the AST was directly manipulated",
modulesIllegalExportName: "Illegal export $1",
modulesDuplicateDeclarations: "Duplicate module declarations with the same source but in different scopes",
undeclaredVariable: "Reference to undeclared variable $1",
undeclaredVariableType: "Referencing a type alias outside of a type annotation",
undeclaredVariableSuggestion: "Reference to undeclared variable $1 - did you mean $2?",
traverseNeedsParent: "You must pass a scope and parentPath unless traversing a Program/File. Instead of that you tried to traverse a $1 node without passing scope and parentPath.",
traverseVerifyRootFunction: "You passed `traverse()` a function when it expected a visitor object, are you sure you didn't mean `{ enter: Function }`?",
traverseVerifyVisitorProperty: "You passed `traverse()` a visitor object with the property $1 that has the invalid property $2",
traverseVerifyNodeType: "You gave us a visitor for the node type $1 but it's not a valid type",
pluginNotObject: "Plugin $2 specified in $1 was expected to return an object when invoked but returned $3",
pluginNotFunction: "Plugin $2 specified in $1 was expected to return a function but returned $3",
pluginUnknown: "Unknown plugin $1 specified in $2 at $3, attempted to resolve relative to $4",
pluginInvalidProperty: "Plugin $2 specified in $1 provided an invalid property of $3"
};
exports.MESSAGES = MESSAGES;
/**
* Get a message with $0 placeholders replaced by arguments.
*/
function get(key) {
for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
args[_key - 1] = arguments[_key];
}
var msg = MESSAGES[key];
if (!msg) throw new ReferenceError("Unknown message " + JSON.stringify(key));
// stringify args
args = parseArgs(args);
// replace $0 placeholders with args
return msg.replace(/\$(\d+)/g, function (str, i) {
return args[i - 1];
});
}
/**
* Stingify arguments to be used inside messages.
*/
function parseArgs(args) {
return args.map(function (val) {
if (val != null && val.inspect) {
return val.inspect();
} else {
try {
return JSON.stringify(val) || val + "";
} catch (e) {
return util.inspect(val);
}
}
});
}
+94
View File
@@ -0,0 +1,94 @@
{
"_args": [
[
"babel-messages@^6.7.2",
"/Users/mromano/dev/react-sfs/node_modules/babel-traverse"
]
],
"_from": "babel-messages@>=6.7.2 <7.0.0",
"_id": "babel-messages@6.7.2",
"_inCache": true,
"_installable": true,
"_location": "/babel-messages",
"_nodeVersion": "5.5.0",
"_npmOperationalInternal": {
"host": "packages-12-west.internal.npmjs.com",
"tmp": "tmp/babel-messages-6.7.2.tgz_1457649689408_0.05176954669877887"
},
"_npmUser": {
"email": "amjad.masad@gmail.com",
"name": "amasad"
},
"_npmVersion": "3.3.12",
"_phantomChildren": {},
"_requested": {
"name": "babel-messages",
"raw": "babel-messages@^6.7.2",
"rawSpec": "^6.7.2",
"scope": null,
"spec": ">=6.7.2 <7.0.0",
"type": "range"
},
"_requiredBy": [
"/babel-core",
"/babel-generator",
"/babel-traverse"
],
"_resolved": "https://registry.npmjs.org/babel-messages/-/babel-messages-6.7.2.tgz",
"_shasum": "d46dbfc69da4c27e0e145c17441fc617cf76af71",
"_shrinkwrap": null,
"_spec": "babel-messages@^6.7.2",
"_where": "/Users/mromano/dev/react-sfs/node_modules/babel-traverse",
"author": {
"email": "sebmck@gmail.com",
"name": "Sebastian McKenzie"
},
"dependencies": {
"babel-runtime": "^5.0.0"
},
"description": "Collection of debug messages used by Babel.",
"devDependencies": {},
"directories": {},
"dist": {
"shasum": "d46dbfc69da4c27e0e145c17441fc617cf76af71",
"tarball": "https://registry.npmjs.org/babel-messages/-/babel-messages-6.7.2.tgz"
},
"homepage": "https://babeljs.io/",
"license": "MIT",
"main": "lib/index.js",
"maintainers": [
{
"email": "amjad.masad@gmail.com",
"name": "amasad"
},
{
"email": "hi@henryzoo.com",
"name": "hzoo"
},
{
"email": "npm-public@jessemccarthy.net",
"name": "jmm"
},
{
"email": "loganfsmyth@gmail.com",
"name": "loganfsmyth"
},
{
"email": "sebmck@gmail.com",
"name": "sebmck"
},
{
"email": "me@thejameskyle.com",
"name": "thejameskyle"
}
],
"name": "babel-messages",
"optionalDependencies": {},
"readme": "ERROR: No README data found!",
"repository": {
"type": "git",
"url": "https://github.com/babel/babel/tree/master/packages/babel-messages"
},
"scripts": {},
"version": "6.7.2"
}
+3
View File
@@ -0,0 +1,3 @@
node_modules
*.log
src
+35
View File
@@ -0,0 +1,35 @@
# babel-plugin-syntax-flow
## Installation
```sh
$ npm install babel-plugin-syntax-flow
```
## Usage
### Via `.babelrc` (Recommended)
**.babelrc**
```json
{
"plugins": ["syntax-flow"]
}
```
### Via CLI
```sh
$ babel --plugins syntax-flow script.js
```
### Via Node API
```javascript
require("babel-core").transform("code", {
plugins: ["syntax-flow"]
});
```
+13
View File
@@ -0,0 +1,13 @@
"use strict";
exports.__esModule = true;
exports["default"] = function () {
return {
manipulateOptions: function manipulateOptions(opts, parserOpts) {
parserOpts.plugins.push("flow");
}
};
};
module.exports = exports["default"];
+93
View File
@@ -0,0 +1,93 @@
{
"_args": [
[
"babel-plugin-syntax-flow@^6.3.13",
"/Users/mromano/dev/react-sfs/node_modules/babel-preset-react"
]
],
"_from": "babel-plugin-syntax-flow@>=6.3.13 <7.0.0",
"_id": "babel-plugin-syntax-flow@6.5.0",
"_inCache": true,
"_installable": true,
"_location": "/babel-plugin-syntax-flow",
"_nodeVersion": "5.1.0",
"_npmOperationalInternal": {
"host": "packages-5-east.internal.npmjs.com",
"tmp": "tmp/babel-plugin-syntax-flow-6.5.0.tgz_1454803636839_0.2558803544379771"
},
"_npmUser": {
"email": "hi@henryzoo.com",
"name": "hzoo"
},
"_npmVersion": "3.6.0",
"_phantomChildren": {},
"_requested": {
"name": "babel-plugin-syntax-flow",
"raw": "babel-plugin-syntax-flow@^6.3.13",
"rawSpec": "^6.3.13",
"scope": null,
"spec": ">=6.3.13 <7.0.0",
"type": "range"
},
"_requiredBy": [
"/babel-plugin-transform-flow-strip-types",
"/babel-preset-react"
],
"_resolved": "https://registry.npmjs.org/babel-plugin-syntax-flow/-/babel-plugin-syntax-flow-6.5.0.tgz",
"_shasum": "07dfe735b45fce8905296296a40072afce82b215",
"_shrinkwrap": null,
"_spec": "babel-plugin-syntax-flow@^6.3.13",
"_where": "/Users/mromano/dev/react-sfs/node_modules/babel-preset-react",
"dependencies": {
"babel-runtime": "^5.0.0"
},
"description": "",
"devDependencies": {
"babel-helper-plugin-test-runner": "^6.3.13"
},
"directories": {},
"dist": {
"shasum": "07dfe735b45fce8905296296a40072afce82b215",
"tarball": "https://registry.npmjs.org/babel-plugin-syntax-flow/-/babel-plugin-syntax-flow-6.5.0.tgz"
},
"keywords": [
"babel-plugin"
],
"license": "MIT",
"main": "lib/index.js",
"maintainers": [
{
"email": "amjad.masad@gmail.com",
"name": "amasad"
},
{
"email": "hi@henryzoo.com",
"name": "hzoo"
},
{
"email": "npm-public@jessemccarthy.net",
"name": "jmm"
},
{
"email": "loganfsmyth@gmail.com",
"name": "loganfsmyth"
},
{
"email": "sebmck@gmail.com",
"name": "sebmck"
},
{
"email": "me@thejameskyle.com",
"name": "thejameskyle"
}
],
"name": "babel-plugin-syntax-flow",
"optionalDependencies": {},
"readme": "ERROR: No README data found!",
"repository": {
"type": "git",
"url": "https://github.com/babel/babel/tree/master/packages/babel-plugin-syntax-flow"
},
"scripts": {},
"version": "6.5.0"
}
+3
View File
@@ -0,0 +1,3 @@
node_modules
*.log
src
+35
View File
@@ -0,0 +1,35 @@
# babel-plugin-syntax-jsx
## Installation
```sh
$ npm install babel-plugin-syntax-jsx
```
## Usage
### Via `.babelrc` (Recommended)
**.babelrc**
```json
{
"plugins": ["syntax-jsx"]
}
```
### Via CLI
```sh
$ babel --plugins syntax-jsx script.js
```
### Via Node API
```javascript
require("babel-core").transform("code", {
plugins: ["syntax-jsx"]
});
```
+13
View File
@@ -0,0 +1,13 @@
"use strict";
exports.__esModule = true;
exports["default"] = function () {
return {
manipulateOptions: function manipulateOptions(opts, parserOpts) {
parserOpts.plugins.push("jsx");
}
};
};
module.exports = exports["default"];
+94
View File
@@ -0,0 +1,94 @@
{
"_args": [
[
"babel-plugin-syntax-jsx@^6.3.13",
"/Users/mromano/dev/react-sfs/node_modules/babel-preset-react"
]
],
"_from": "babel-plugin-syntax-jsx@>=6.3.13 <7.0.0",
"_id": "babel-plugin-syntax-jsx@6.5.0",
"_inCache": true,
"_installable": true,
"_location": "/babel-plugin-syntax-jsx",
"_nodeVersion": "5.1.0",
"_npmOperationalInternal": {
"host": "packages-5-east.internal.npmjs.com",
"tmp": "tmp/babel-plugin-syntax-jsx-6.5.0.tgz_1454803639252_0.10849612834863365"
},
"_npmUser": {
"email": "hi@henryzoo.com",
"name": "hzoo"
},
"_npmVersion": "3.6.0",
"_phantomChildren": {},
"_requested": {
"name": "babel-plugin-syntax-jsx",
"raw": "babel-plugin-syntax-jsx@^6.3.13",
"rawSpec": "^6.3.13",
"scope": null,
"spec": ">=6.3.13 <7.0.0",
"type": "range"
},
"_requiredBy": [
"/babel-plugin-transform-react-jsx",
"/babel-plugin-transform-react-jsx-source",
"/babel-preset-react"
],
"_resolved": "https://registry.npmjs.org/babel-plugin-syntax-jsx/-/babel-plugin-syntax-jsx-6.5.0.tgz",
"_shasum": "fa708c5761d13ec39128a4ba24abfe8be6ad8170",
"_shrinkwrap": null,
"_spec": "babel-plugin-syntax-jsx@^6.3.13",
"_where": "/Users/mromano/dev/react-sfs/node_modules/babel-preset-react",
"dependencies": {
"babel-runtime": "^5.0.0"
},
"description": "",
"devDependencies": {
"babel-helper-plugin-test-runner": "^6.3.13"
},
"directories": {},
"dist": {
"shasum": "fa708c5761d13ec39128a4ba24abfe8be6ad8170",
"tarball": "https://registry.npmjs.org/babel-plugin-syntax-jsx/-/babel-plugin-syntax-jsx-6.5.0.tgz"
},
"keywords": [
"babel-plugin"
],
"license": "MIT",
"main": "lib/index.js",
"maintainers": [
{
"email": "amjad.masad@gmail.com",
"name": "amasad"
},
{
"email": "hi@henryzoo.com",
"name": "hzoo"
},
{
"email": "npm-public@jessemccarthy.net",
"name": "jmm"
},
{
"email": "loganfsmyth@gmail.com",
"name": "loganfsmyth"
},
{
"email": "sebmck@gmail.com",
"name": "sebmck"
},
{
"email": "me@thejameskyle.com",
"name": "thejameskyle"
}
],
"name": "babel-plugin-syntax-jsx",
"optionalDependencies": {},
"readme": "ERROR: No README data found!",
"repository": {
"type": "git",
"url": "https://github.com/babel/babel/tree/master/packages/babel-plugin-syntax-jsx"
},
"scripts": {},
"version": "6.5.0"
}
@@ -0,0 +1,4 @@
node_modules
*.log
src
test
@@ -0,0 +1,35 @@
# babel-plugin-transform-flow-strip-types
Strip flow type annotations from your output code.
## Installation
```sh
$ npm install babel-plugin-transform-flow-strip-types
```
## Usage
### Via `.babelrc` (Recommended)
**.babelrc**
```json
{
"plugins": ["transform-flow-strip-types"]
}
```
### Via CLI
```sh
$ babel --plugins transform-flow-strip-types script.js
```
### Via Node API
```javascript
require("babel-core").transform("code", {
plugins: ["transform-flow-strip-types"]
});
```
@@ -0,0 +1,66 @@
"use strict";
exports.__esModule = true;
exports["default"] = function (_ref) {
var t = _ref.types;
var FLOW_DIRECTIVE = "@flow";
return {
inherits: require("babel-plugin-syntax-flow"),
visitor: {
Program: function Program(path, _ref2) {
var comments = _ref2.file.ast.comments;
var _arr = comments;
for (var _i = 0; _i < _arr.length; _i++) {
var comment = _arr[_i];
if (comment.value.indexOf(FLOW_DIRECTIVE) >= 0) {
// remove flow directive
comment.value = comment.value.replace(FLOW_DIRECTIVE, "");
// remove the comment completely if it only consists of whitespace and/or stars
if (!comment.value.replace(/\*/g, "").trim()) comment.ignore = true;
}
}
},
Flow: function Flow(path) {
path.remove();
},
ClassProperty: function ClassProperty(path) {
path.node.typeAnnotation = null;
if (!path.node.value) path.remove();
},
Class: function Class(_ref3) {
var node = _ref3.node;
node["implements"] = null;
},
Function: function Function(_ref4) {
var node = _ref4.node;
for (var i = 0; i < node.params.length; i++) {
var param = node.params[i];
param.optional = false;
}
},
TypeCastExpression: function TypeCastExpression(path) {
var node = path.node;
do {
node = node.expression;
} while (t.isTypeCastExpression(node));
path.replaceWith(node);
}
}
};
};
module.exports = exports["default"];
@@ -0,0 +1,93 @@
{
"_args": [
[
"babel-plugin-transform-flow-strip-types@^6.3.13",
"/Users/mromano/dev/react-sfs/node_modules/babel-preset-react"
]
],
"_from": "babel-plugin-transform-flow-strip-types@>=6.3.13 <7.0.0",
"_id": "babel-plugin-transform-flow-strip-types@6.7.0",
"_inCache": true,
"_installable": true,
"_location": "/babel-plugin-transform-flow-strip-types",
"_nodeVersion": "5.5.0",
"_npmOperationalInternal": {
"host": "packages-12-west.internal.npmjs.com",
"tmp": "tmp/babel-plugin-transform-flow-strip-types-6.7.0.tgz_1457484781821_0.697082552826032"
},
"_npmUser": {
"email": "amjad.masad@gmail.com",
"name": "amasad"
},
"_npmVersion": "3.3.12",
"_phantomChildren": {},
"_requested": {
"name": "babel-plugin-transform-flow-strip-types",
"raw": "babel-plugin-transform-flow-strip-types@^6.3.13",
"rawSpec": "^6.3.13",
"scope": null,
"spec": ">=6.3.13 <7.0.0",
"type": "range"
},
"_requiredBy": [
"/babel-preset-react"
],
"_resolved": "https://registry.npmjs.org/babel-plugin-transform-flow-strip-types/-/babel-plugin-transform-flow-strip-types-6.7.0.tgz",
"_shasum": "ebbdc8e44320b875bdb3c1c12b2e317f21f49837",
"_shrinkwrap": null,
"_spec": "babel-plugin-transform-flow-strip-types@^6.3.13",
"_where": "/Users/mromano/dev/react-sfs/node_modules/babel-preset-react",
"dependencies": {
"babel-plugin-syntax-flow": "^6.3.13",
"babel-runtime": "^5.0.0"
},
"description": "Strip flow type annotations from your output code.",
"devDependencies": {
"babel-helper-plugin-test-runner": "^6.3.13"
},
"directories": {},
"dist": {
"shasum": "ebbdc8e44320b875bdb3c1c12b2e317f21f49837",
"tarball": "https://registry.npmjs.org/babel-plugin-transform-flow-strip-types/-/babel-plugin-transform-flow-strip-types-6.7.0.tgz"
},
"keywords": [
"babel-plugin"
],
"license": "MIT",
"main": "lib/index.js",
"maintainers": [
{
"email": "amjad.masad@gmail.com",
"name": "amasad"
},
{
"email": "hi@henryzoo.com",
"name": "hzoo"
},
{
"email": "npm-public@jessemccarthy.net",
"name": "jmm"
},
{
"email": "loganfsmyth@gmail.com",
"name": "loganfsmyth"
},
{
"email": "sebmck@gmail.com",
"name": "sebmck"
},
{
"email": "me@thejameskyle.com",
"name": "thejameskyle"
}
],
"name": "babel-plugin-transform-flow-strip-types",
"optionalDependencies": {},
"readme": "ERROR: No README data found!",
"repository": {
"type": "git",
"url": "https://github.com/babel/babel/tree/master/packages/babel-plugin-transform-flow-strip-types"
},
"scripts": {},
"version": "6.7.0"
}

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