From 296c10e7dc6dafea8d04cdbe99a79a3d54268646 Mon Sep 17 00:00:00 2001 From: Michael Hurley Date: Wed, 2 Nov 2016 18:38:46 -0400 Subject: [PATCH] change bundle.js -> ramdaRepl.js; add authors to package.json --- dist/{bundle.css => ramdaRepl.css} | 0 dist/ramdaRepl.js | 95268 +++++++++++++++++++++++++ dist/{bundle.js => ramdaRepl.min.js} | 8 +- example/index.html | 4 +- package.json | 20 +- 5 files changed, 95289 insertions(+), 11 deletions(-) rename dist/{bundle.css => ramdaRepl.css} (100%) create mode 100644 dist/ramdaRepl.js rename dist/{bundle.js => ramdaRepl.min.js} (94%) diff --git a/dist/bundle.css b/dist/ramdaRepl.css similarity index 100% rename from dist/bundle.css rename to dist/ramdaRepl.css diff --git a/dist/ramdaRepl.js b/dist/ramdaRepl.js new file mode 100644 index 0000000..ec1abe9 --- /dev/null +++ b/dist/ramdaRepl.js @@ -0,0 +1,95268 @@ +(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o Array String +var getMethodNames = (0, _ramda.compose)(_ramda.keys, (0, _ramda.pickBy)(function (val) { + return typeof val === 'function'; +})); + +// expose :: Window -> script -> script +// +// Side-effectful. +// +// This is intended to take methods introduced by a global made available by the loaded script and +// expose them on the `window` object. +// +// By default all top level methods of the global will be exposed. +// Given a method is present on the window object already it will not be overridden. +// +// Given the `script` has a property `expose` - a list of method names - only those listed +// will be exposed. +// +// Given the `script` has a property `exposeAs` - a string - the global will be made available at +// that namespace on the window object. Methods will not be exposed on `window`. +exports.default = (0, _ramda.curry)(function (win, script) { + + var g = script.global && win[script.global]; + + if ((0, _ramda.isNil)(g)) { + + return script; + } + + if (!(0, _ramda.isNil)(script.exposeAs)) { + + win[script.exposeAs] = g; + return script; + } + + var methodNames = (0, _ramda.isNil)(script.expose) ? getMethodNames(g) : script.expose; + + methodNames.forEach(function (name) { + win[name] = win[name] || g[name]; + }); + + return script; +}); + +},{"ramda":607}],6:[function(require,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = bindShortUrlButton; + +var _ramda = require('ramda'); + +var _ramda2 = _interopRequireDefault(_ramda); + +var _sanctuary = require('sanctuary'); + +var _sanctuary2 = _interopRequireDefault(_sanctuary); + +var _ramdaFantasy = require('ramda-fantasy'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var setValue = _ramda2.default.curry(function (options, data) { + options.urlOut.value = data; + options.urlOut.select(); +}); + +var error = function error(err) { + return console.error(err); +}; + +var xhr = function xhr(options) { + return new _ramdaFantasy.Future(function (reject, resolve) { + var oReq = new XMLHttpRequest(); + + var requestData = { longUrl: '' + options.returnUrl + location.hash }; + + oReq.addEventListener('load', resolve, false); + oReq.addEventListener('error', reject, false); + oReq.addEventListener('abort', reject, false); + oReq.open('POST', options.apiUrl, true); + oReq.setRequestHeader('Content-Type', 'application/json; charset=utf-8'); + oReq.send(JSON.stringify(requestData)); + }); +}; + +var getResponse = _ramda2.default.compose(_ramda2.default.map(_sanctuary2.default.parseJson(Object)), _ramda2.default.map(_ramda2.default.path(['target', 'responseText'])), xhr); + +var getShortUrl = function getShortUrl(options) { + return _ramda2.default.map(_ramda2.default.compose(setValue(options), _ramda2.default.prop('id'))); +}; + +var futureXhr = function futureXhr(options) { + return getResponse(options); +}; + +function bindShortUrlButton(options) { + + // Given a missing or incomplete configuration, do not present or bind the controls. + if (!options.apiUrl || !options.returnUrl) { + options.btnMakeShortUrl.style.display = 'none'; + options.urlOut.style.display = 'none'; + return; + } + + options.btnMakeShortUrl.addEventListener('click', function () { + futureXhr(options).fork(error, getShortUrl(options)); + }); +} + +},{"ramda":607,"ramda-fantasy":595,"sanctuary":670}],7:[function(require,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = bindInputPanel; + +var _babelPresetEs = require('babel-preset-es2015'); + +var _babelPresetEs2 = _interopRequireDefault(_babelPresetEs); + +var _babelPresetStage = require('babel-preset-stage-0'); + +var _babelPresetStage2 = _interopRequireDefault(_babelPresetStage); + +var _ramda = require('ramda'); + +var _ramda2 = _interopRequireDefault(_ramda); + +var _debounce = require('debounce'); + +var _debounce2 = _interopRequireDefault(_debounce); + +var _codeMirrorConfig = require('./codemirror/code-mirror-config.json'); + +var _codeMirrorConfig2 = _interopRequireDefault(_codeMirrorConfig); + +var _codemirror = require('./codemirror/codemirror'); + +var _codemirror2 = _interopRequireDefault(_codemirror); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var babel = require('babel-core'); + +var inputConfig = _ramda2.default.merge(_codeMirrorConfig2.default, { + lineNumbers: true, + extraKeys: { + Tab: 'autocomplete' + }, + autofocus: true, + autoCloseBrackets: true, + historyEventDelay: 2000 +}); + +var transformConfig = { + filename: 'ramda', + presets: [_babelPresetEs2.default, _babelPresetStage2.default] +}; + +var ramdaStr = 'const {' + _ramda2.default.keys(_ramda2.default).join(',') + '} = R;'; +var evalSource = _ramda2.default.compose(_ramda2.default.toString, eval); // eslint-disable-line no-eval + +var formatCode = function formatCode(code) { + return evalSource(code).replace('"use strict"', ''); +}; + +var formatError = function formatError(err) { + return err.message.replace(ramdaStr, '').replace(/(?=\d).*(?=\|)/g, function (a) { + return Number(a.trim()) - 1; + }); +}; + +function compile(input, options) { + + var source = input.getValue(); + var code = ramdaStr + ' \n' + source; + + if (typeof options.onChange === 'function') { + options.onChange(source); + } + + options.evalError.textContent = ''; + + try { + + var transformed = babel.transform(code, transformConfig); + + options.output.setValue(formatCode(transformed.code)); + } catch (err) { + + options.evalError.textContent = formatError(err); + } +} +var debounceCompile = function debounceCompile(delay) { + return (0, _debounce2.default)(compile, delay); +}; + +function bindInputPanel(options) { + + var input = _codemirror2.default.fromTextArea(options.input, inputConfig); + var onChange = debounceCompile(options.delay); + + input.on('change', function () { + return onChange(input, options); + }); + + if (options.initialValue) { + input.setValue(options.initialValue); + } + + return input; +} + +},{"./codemirror/code-mirror-config.json":2,"./codemirror/codemirror":3,"babel-core":19,"babel-preset-es2015":133,"babel-preset-stage-0":134,"debounce":338,"ramda":607}],8:[function(require,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = loadScripts; + +var _ramdaFantasy = require('ramda-fantasy'); + +var _ramda = require('ramda'); + +var _loadScript = require('load-script'); + +var _loadScript2 = _interopRequireDefault(_loadScript); + +var _exposeGlobals = require('./expose-globals'); + +var _exposeGlobals2 = _interopRequireDefault(_exposeGlobals); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +// loadScript :: script -> Future error script +var loadScript = function loadScript(script) { + return (0, _ramdaFantasy.Future)(function (reject, resolve) { + + (0, _loadScript2.default)(script.src, function (err) { + return err ? reject(err) : resolve(script); + }); + }).map((0, _exposeGlobals2.default)(window)); +}; + +// loadParallelScripts = Array scripts -> () -> Future error [scripts] +var loadParallelScripts = function loadParallelScripts(scripts) { + return function () { + return (0, _ramda.sequence)(_ramdaFantasy.Future.of, scripts.map(loadScript)); + }; +}; + +// loadScripts :: Object config -> Future error [scripts] +function loadScripts(config) { + var ramdaScript = config.ramdaScript; + var scripts = config.scripts; + + // First load ramda, then load the remaining scripts in parallel. + + return loadScript(ramdaScript).chain(loadParallelScripts(scripts)); +} + +},{"./expose-globals":5,"load-script":359,"ramda":607,"ramda-fantasy":595}],9:[function(require,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _ramda = require('ramda'); + +var _ramda2 = _interopRequireDefault(_ramda); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var internals = {}; +var reporter = {}; + +var consoleLogElement = void 0, + consoleRef = void 0; + +internals.buffer = []; + +internals.flush = function flush() { + consoleLogElement.textContent = internals.buffer.join('\n'); +}; + +internals.logMethods = ['log', 'info', 'debug']; + +internals.prepLogs = _ramda2.default.cond([[_ramda2.default.is(String), _ramda2.default.identity], [_ramda2.default.is(Function), _ramda2.default.toString], [_ramda2.default.T, JSON.stringify]]); + +internals.intercept = function (method) { + var original = consoleRef[method]; + consoleRef[method] = function () { + for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + + args.reduce(function (buf, arg) { + buf.push(internals.prepLogs(arg)); + return buf; + }, internals.buffer); + original.apply(consoleRef, args); + internals.flush(); + }; +}; + +internals.clear = function () { + var consoleClear = consoleRef.clear; + consoleRef.clear = function () { + internals.buffer = []; + consoleLogElement.textContent = ''; + consoleClear.call(consoleRef); + }; +}; + +reporter.main = function (options) { + consoleLogElement = options.consoleLogElement; + consoleRef = options.consoleRef; + internals.clear(); + internals.buffer = []; + internals.logMethods.reduce(function (fn, method) { + fn(method); + return fn; + }, internals.intercept); +}; + +exports.default = reporter; + +},{"ramda":607}],10:[function(require,module,exports){ +'use strict'; + +var _repl = require('./repl'); + +var _repl2 = _interopRequireDefault(_repl); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/* + * ramdaRepl :: DOMNode targetEl, Object config + * This has the effect of loading the named scripts and adding their functions to the global object + * before modifying the DOM to present the REPL. + */ +window.ramdaRepl = function ramdaRepl(targetEl, config) { + + (0, _repl2.default)(targetEl, config); +}; + +},{"./repl":13}],11:[function(require,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = bindOutputPanel; + +var _ramda = require('ramda'); + +var _ramda2 = _interopRequireDefault(_ramda); + +var _codeMirrorConfig = require('./codemirror/code-mirror-config.json'); + +var _codeMirrorConfig2 = _interopRequireDefault(_codeMirrorConfig); + +var _codemirror = require('./codemirror/codemirror'); + +var _codemirror2 = _interopRequireDefault(_codemirror); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var outputConfig = _ramda2.default.merge(_codeMirrorConfig2.default, { + readOnly: true +}); + +function bindOutputPanel(options) { + return _codemirror2.default.fromTextArea(options.outputEl, outputConfig); +} + +},{"./codemirror/code-mirror-config.json":2,"./codemirror/codemirror":3,"ramda":607}],12:[function(require,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = bindPrettyButton; + +var _prettyJs = require('pretty-js'); + +var _prettyJs2 = _interopRequireDefault(_prettyJs); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function bindPrettyButton(options) { + options.btnPretty.addEventListener('click', function prettify() { + options.output.setValue((0, _prettyJs2.default)(options.output.getValue())); + }); +} + +},{"pretty-js":592}],13:[function(require,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = replaceTarget; + +var _logger = require('./logger'); + +var _logger2 = _interopRequireDefault(_logger); + +var _clear = require('./clear'); + +var _clear2 = _interopRequireDefault(_clear); + +var _reset = require('./reset'); + +var _reset2 = _interopRequireDefault(_reset); + +var _pretty = require('./pretty'); + +var _pretty2 = _interopRequireDefault(_pretty); + +var _googl = require('./googl'); + +var _googl2 = _interopRequireDefault(_googl); + +var _inputPanel = require('./input-panel'); + +var _inputPanel2 = _interopRequireDefault(_inputPanel); + +var _outputPanel = require('./output-panel'); + +var _outputPanel2 = _interopRequireDefault(_outputPanel); + +var _replDOM = require('./dom/replDOM'); + +var _replDOM2 = _interopRequireDefault(_replDOM); + +var _loadScripts = require('./load-scripts'); + +var _loadScripts2 = _interopRequireDefault(_loadScripts); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/* + * bindBehaviour :: HTMLElement el, Object config -> HTMLElement el + * Takes the root element of the REPL and returns the element with DOM event bindings + * attached to its tree. + */ +var bindBehaviour = function bindBehaviour(el, config) { + + var querySelector = el.querySelector.bind(el); + + _logger2.default.main({ + consoleLogElement: querySelector('.js-console-log'), + consoleRef: window.console + }); + + var output = (0, _outputPanel2.default)({ + outputEl: querySelector('.js-output') + }); + + (0, _reset2.default)({ + btnReset: querySelector('.js-btn-reset'), + window: window + }); + + (0, _clear2.default)({ + btnClear: querySelector('.js-btn-clear'), + evalError: querySelector('.js-error'), + output: output + }); + + (0, _googl2.default)({ + btnMakeShortUrl: querySelector('.js-btn-short-url'), + urlOut: querySelector('.js-url-out'), + apiUrl: config.apiUrl, + returnUrl: config.returnUrl + }); + + (0, _pretty2.default)({ + btnPretty: querySelector('.js-btn-pretty'), + output: output + }); + + (0, _inputPanel2.default)({ + input: querySelector('.js-input'), + evalError: querySelector('.js-error'), + initialValue: config.initialValue, + onChange: config.onChange, + output: output, + delay: 1000 + }); + + return el; +}; + +var onLoadEnd = function onLoadEnd(el) { + return el.className = 'repl'; +}; // Removes repl-loading class + +/* + * replaceTarget :: DOMNode targetEl, Object config + * This has the effect of hiding the "target" element and appending the DOM that represents the + * Ramda REPL next to it. + */ +function replaceTarget(targetEl) { + var config = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + + + targetEl.style.display = 'none'; + targetEl.parentNode.insertBefore(_replDOM2.default, targetEl); + + // Given an initial value is not explicitly set, attempt to use the content of the element that + // the REPL is replacing. + if (!config.initialValue) { + config.initialValue = targetEl.value || targetEl.textContent; + } + + (0, _loadScripts2.default)(config).fork(function (err) { + onLoadEnd(_replDOM2.default); + _replDOM2.default.querySelector('.js-error').textContent = err; + }, function () { + onLoadEnd(_replDOM2.default); + bindBehaviour(_replDOM2.default, config); + }); +} + +},{"./clear":1,"./dom/replDOM":4,"./googl":6,"./input-panel":7,"./load-scripts":8,"./logger":9,"./output-panel":11,"./pretty":12,"./reset":14}],14:[function(require,module,exports){ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = bindResetButton; +function bindResetButton(options) { + + options.btnReset.addEventListener('click', function () { + options.window.location = '.'; + }); +} + +},{}],15:[function(require,module,exports){ +'use strict'; +module.exports = function () { + return /[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g; +}; + +},{}],16:[function(require,module,exports){ +'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 +}); + +},{}],17:[function(require,module,exports){ +// http://wiki.commonjs.org/wiki/Unit_Testing/1.0 +// +// THIS IS NOT TESTED NOR LIKELY TO WORK OUTSIDE V8! +// +// Originally from narwhal.js (http://narwhaljs.org) +// Copyright (c) 2009 Thomas Robinson <280north.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 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. + +// when used in node, this will actually load the util module we depend on +// versus loading the builtin util module as happens otherwise +// this is a bug in node module loading as far as I am concerned +var util = require('util/'); + +var pSlice = Array.prototype.slice; +var hasOwn = Object.prototype.hasOwnProperty; + +// 1. The assert module provides functions that throw +// AssertionError's when particular conditions are not met. The +// assert module must conform to the following interface. + +var assert = module.exports = ok; + +// 2. The AssertionError is defined in assert. +// new assert.AssertionError({ message: message, +// actual: actual, +// expected: expected }) + +assert.AssertionError = function AssertionError(options) { + this.name = 'AssertionError'; + this.actual = options.actual; + this.expected = options.expected; + this.operator = options.operator; + if (options.message) { + this.message = options.message; + this.generatedMessage = false; + } else { + this.message = getMessage(this); + this.generatedMessage = true; + } + var stackStartFunction = options.stackStartFunction || fail; + + if (Error.captureStackTrace) { + Error.captureStackTrace(this, stackStartFunction); + } + else { + // non v8 browsers so we can have a stacktrace + var err = new Error(); + if (err.stack) { + var out = err.stack; + + // try to strip useless frames + var fn_name = stackStartFunction.name; + var idx = out.indexOf('\n' + fn_name); + if (idx >= 0) { + // once we have located the function frame + // we need to strip out everything before it (and its line) + var next_line = out.indexOf('\n', idx + 1); + out = out.substring(next_line + 1); + } + + this.stack = out; + } + } +}; + +// assert.AssertionError instanceof Error +util.inherits(assert.AssertionError, Error); + +function replacer(key, value) { + if (util.isUndefined(value)) { + return '' + value; + } + if (util.isNumber(value) && !isFinite(value)) { + return value.toString(); + } + if (util.isFunction(value) || util.isRegExp(value)) { + return value.toString(); + } + return value; +} + +function truncate(s, n) { + if (util.isString(s)) { + return s.length < n ? s : s.slice(0, n); + } else { + return s; + } +} + +function getMessage(self) { + return truncate(JSON.stringify(self.actual, replacer), 128) + ' ' + + self.operator + ' ' + + truncate(JSON.stringify(self.expected, replacer), 128); +} + +// At present only the three keys mentioned above are used and +// understood by the spec. Implementations or sub modules can pass +// other keys to the AssertionError's constructor - they will be +// ignored. + +// 3. All of the following functions must throw an AssertionError +// when a corresponding condition is not met, with a message that +// may be undefined if not provided. All assertion methods provide +// both the actual and expected values to the assertion error for +// display purposes. + +function fail(actual, expected, message, operator, stackStartFunction) { + throw new assert.AssertionError({ + message: message, + actual: actual, + expected: expected, + operator: operator, + stackStartFunction: stackStartFunction + }); +} + +// EXTENSION! allows for well behaved errors defined elsewhere. +assert.fail = fail; + +// 4. Pure assertion tests whether a value is truthy, as determined +// by !!guard. +// assert.ok(guard, message_opt); +// This statement is equivalent to assert.equal(true, !!guard, +// message_opt);. To test strictly for the value true, use +// assert.strictEqual(true, guard, message_opt);. + +function ok(value, message) { + if (!value) fail(value, true, message, '==', assert.ok); +} +assert.ok = ok; + +// 5. The equality assertion tests shallow, coercive equality with +// ==. +// assert.equal(actual, expected, message_opt); + +assert.equal = function equal(actual, expected, message) { + if (actual != expected) fail(actual, expected, message, '==', assert.equal); +}; + +// 6. The non-equality assertion tests for whether two objects are not equal +// with != assert.notEqual(actual, expected, message_opt); + +assert.notEqual = function notEqual(actual, expected, message) { + if (actual == expected) { + fail(actual, expected, message, '!=', assert.notEqual); + } +}; + +// 7. The equivalence assertion tests a deep equality relation. +// assert.deepEqual(actual, expected, message_opt); + +assert.deepEqual = function deepEqual(actual, expected, message) { + if (!_deepEqual(actual, expected)) { + fail(actual, expected, message, 'deepEqual', assert.deepEqual); + } +}; + +function _deepEqual(actual, expected) { + // 7.1. All identical values are equivalent, as determined by ===. + if (actual === expected) { + return true; + + } else if (util.isBuffer(actual) && util.isBuffer(expected)) { + if (actual.length != expected.length) return false; + + for (var i = 0; i < actual.length; i++) { + if (actual[i] !== expected[i]) return false; + } + + return true; + + // 7.2. If the expected value is a Date object, the actual value is + // equivalent if it is also a Date object that refers to the same time. + } else if (util.isDate(actual) && util.isDate(expected)) { + return actual.getTime() === expected.getTime(); + + // 7.3 If the expected value is a RegExp object, the actual value is + // equivalent if it is also a RegExp object with the same source and + // properties (`global`, `multiline`, `lastIndex`, `ignoreCase`). + } else if (util.isRegExp(actual) && util.isRegExp(expected)) { + return actual.source === expected.source && + actual.global === expected.global && + actual.multiline === expected.multiline && + actual.lastIndex === expected.lastIndex && + actual.ignoreCase === expected.ignoreCase; + + // 7.4. Other pairs that do not both pass typeof value == 'object', + // equivalence is determined by ==. + } else if (!util.isObject(actual) && !util.isObject(expected)) { + return actual == expected; + + // 7.5 For all other Object pairs, including Array objects, equivalence is + // determined by having the same number of owned properties (as verified + // with Object.prototype.hasOwnProperty.call), the same set of keys + // (although not necessarily the same order), equivalent values for every + // corresponding key, and an identical 'prototype' property. Note: this + // accounts for both named and indexed properties on Arrays. + } else { + return objEquiv(actual, expected); + } +} + +function isArguments(object) { + return Object.prototype.toString.call(object) == '[object Arguments]'; +} + +function objEquiv(a, b) { + if (util.isNullOrUndefined(a) || util.isNullOrUndefined(b)) + return false; + // an identical 'prototype' property. + if (a.prototype !== b.prototype) return false; + // if one is a primitive, the other must be same + if (util.isPrimitive(a) || util.isPrimitive(b)) { + return a === b; + } + var aIsArgs = isArguments(a), + bIsArgs = isArguments(b); + if ((aIsArgs && !bIsArgs) || (!aIsArgs && bIsArgs)) + return false; + if (aIsArgs) { + a = pSlice.call(a); + b = pSlice.call(b); + return _deepEqual(a, b); + } + var ka = objectKeys(a), + kb = objectKeys(b), + key, i; + // having the same number of owned properties (keys incorporates + // hasOwnProperty) + if (ka.length != kb.length) + return false; + //the same set of keys (although not necessarily the same order), + ka.sort(); + kb.sort(); + //~~~cheap key test + for (i = ka.length - 1; i >= 0; i--) { + if (ka[i] != kb[i]) + return false; + } + //equivalent values for every corresponding key, and + //~~~possibly expensive deep test + for (i = ka.length - 1; i >= 0; i--) { + key = ka[i]; + if (!_deepEqual(a[key], b[key])) return false; + } + return true; +} + +// 8. The non-equivalence assertion tests for any deep inequality. +// assert.notDeepEqual(actual, expected, message_opt); + +assert.notDeepEqual = function notDeepEqual(actual, expected, message) { + if (_deepEqual(actual, expected)) { + fail(actual, expected, message, 'notDeepEqual', assert.notDeepEqual); + } +}; + +// 9. The strict equality assertion tests strict equality, as determined by ===. +// assert.strictEqual(actual, expected, message_opt); + +assert.strictEqual = function strictEqual(actual, expected, message) { + if (actual !== expected) { + fail(actual, expected, message, '===', assert.strictEqual); + } +}; + +// 10. The strict non-equality assertion tests for strict inequality, as +// determined by !==. assert.notStrictEqual(actual, expected, message_opt); + +assert.notStrictEqual = function notStrictEqual(actual, expected, message) { + if (actual === expected) { + fail(actual, expected, message, '!==', assert.notStrictEqual); + } +}; + +function expectedException(actual, expected) { + if (!actual || !expected) { + return false; + } + + if (Object.prototype.toString.call(expected) == '[object RegExp]') { + return expected.test(actual); + } else if (actual instanceof expected) { + return true; + } else if (expected.call({}, actual) === true) { + return true; + } + + return false; +} + +function _throws(shouldThrow, block, expected, message) { + var actual; + + if (util.isString(expected)) { + message = expected; + expected = null; + } + + try { + block(); + } catch (e) { + actual = e; + } + + message = (expected && expected.name ? ' (' + expected.name + ').' : '.') + + (message ? ' ' + message : '.'); + + if (shouldThrow && !actual) { + fail(actual, expected, 'Missing expected exception' + message); + } + + if (!shouldThrow && expectedException(actual, expected)) { + fail(actual, expected, 'Got unwanted exception' + message); + } + + if ((shouldThrow && actual && expected && + !expectedException(actual, expected)) || (!shouldThrow && actual)) { + throw actual; + } +} + +// 11. Expected to throw an error: +// assert.throws(block, Error_opt, message_opt); + +assert.throws = function(block, /*optional*/error, /*optional*/message) { + _throws.apply(this, [true].concat(pSlice.call(arguments))); +}; + +// EXTENSION! This is annoying to write outside this module. +assert.doesNotThrow = function(block, /*optional*/message) { + _throws.apply(this, [false].concat(pSlice.call(arguments))); +}; + +assert.ifError = function(err) { if (err) {throw err;}}; + +var objectKeys = Object.keys || function (obj) { + var keys = []; + for (var key in obj) { + if (hasOwn.call(obj, key)) keys.push(key); + } + return keys; +}; + +},{"util/":691}],18:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +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; + var maybeHighlight = function maybeHighlight(chalkFn, string) { + return highlighted ? chalkFn(string) : string; + }; + if (highlighted) rawLines = highlight(rawLines); + + var linesAbove = opts.linesAbove || 2; + var linesBelow = opts.linesBelow || 3; + + var lines = rawLines.split(NEWLINE); + var start = Math.max(lineNumber - (linesAbove + 1), 0); + var end = Math.min(lines.length, lineNumber + linesBelow); + + if (!lineNumber && !colNumber) { + start = 0; + end = lines.length; + } + + var numberMaxWidth = String(end).length; + + var frame = lines.slice(start, end).map(function (line, index) { + var number = start + 1 + index; + var paddedNumber = (" " + number).slice(-numberMaxWidth); + var gutter = " " + paddedNumber + " | "; + if (number === lineNumber) { + var markerLine = ""; + if (colNumber) { + var markerSpacing = line.slice(0, colNumber - 1).replace(/[^\t]/g, " "); + markerLine = ["\n ", maybeHighlight(defs.gutter, gutter.replace(/\d/g, " ")), markerSpacing, maybeHighlight(defs.marker, "^")].join(""); + } + return [maybeHighlight(defs.marker, ">"), maybeHighlight(defs.gutter, gutter), line, markerLine].join(""); + } else { + return " " + maybeHighlight(defs.gutter, gutter) + line; + } + }).join("\n"); + + if (highlighted) { + return _chalk2.default.reset(frame); + } else { + return frame; + } +}; + +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 _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var defs = { + keyword: _chalk2.default.cyan, + capitalized: _chalk2.default.yellow, + jsx_tag: _chalk2.default.yellow, + punctuator: _chalk2.default.yellow, + + number: _chalk2.default.magenta, + string: _chalk2.default.green, + regex: _chalk2.default.magenta, + comment: _chalk2.default.grey, + invalid: _chalk2.default.white.bgRed.bold, + gutter: _chalk2.default.grey, + marker: _chalk2.default.red.bold +}; + +var NEWLINE = /\r\n|[\n\r\u2028\u2029]/; + +var JSX_TAG = /^[a-z][\w-]*$/i; + +var BRACKET = /^[()\[\]{}]$/; + +function getTokenType(match) { + var _match$slice = match.slice(-2); + + var offset = _match$slice[0]; + var text = _match$slice[1]; + + var token = _jsTokens2.default.matchToToken(match); + + if (token.type === "name") { + if (_esutils2.default.keyword.isReservedWordES6(token.value)) { + return "keyword"; + } + + if (JSX_TAG.test(token.value) && (text[offset - 1] === "<" || text.substr(offset - 2, 2) == "= _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; + } + }); +}; + +var _mergeWith = require("lodash/mergeWith"); + +var _mergeWith2 = _interopRequireDefault(_mergeWith); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +module.exports = exports["default"]; +},{"babel-runtime/core-js/get-iterator":138,"lodash/mergeWith":568}],22:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +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?"); +}; + +var _babelTypes = require("babel-types"); + +var t = _interopRequireWildcard(_babelTypes); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +module.exports = exports["default"]; +},{"babel-types":193}],23:[function(require,module,exports){ +(function (process){ +"use strict"; + +exports.__esModule = true; + +var _typeof2 = require("babel-runtime/helpers/typeof"); + +var _typeof3 = _interopRequireDefault(_typeof2); + +exports.default = function (loc) { + var relative = arguments.length <= 1 || arguments[1] === undefined ? process.cwd() : arguments[1]; + + if ((typeof _module2.default === "undefined" ? "undefined" : (0, _typeof3.default)(_module2.default)) === "object") return null; + + var relativeMod = relativeModules[relative]; + + if (!relativeMod) { + relativeMod = new _module2.default(); + + var filename = _path2.default.join(relative, ".babelrc"); + relativeMod.id = filename; + relativeMod.filename = filename; + + relativeMod.paths = _module2.default._nodeModulePaths(relative); + relativeModules[relative] = relativeMod; + } + + try { + return _module2.default._resolveFilename(loc, relativeMod); + } catch (err) { + return null; + } +}; + +var _module = require("module"); + +var _module2 = _interopRequireDefault(_module); + +var _path = require("path"); + +var _path2 = _interopRequireDefault(_path); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var relativeModules = {}; + +module.exports = exports["default"]; +}).call(this,require('_process')) +},{"_process":594,"babel-runtime/helpers/typeof":155,"module":220,"path":589}],24:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +var _map = require("babel-runtime/core-js/map"); + +var _map2 = _interopRequireDefault(_map); + +var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck"); + +var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); + +var _possibleConstructorReturn2 = require("babel-runtime/helpers/possibleConstructorReturn"); + +var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); + +var _inherits2 = require("babel-runtime/helpers/inherits"); + +var _inherits3 = _interopRequireDefault(_inherits2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var Store = function (_Map) { + (0, _inherits3.default)(Store, _Map); + + function Store() { + (0, _classCallCheck3.default)(this, Store); + + var _this = (0, _possibleConstructorReturn3.default)(this, _Map.call(this)); + + _this.dynamicData = {}; + return _this; + } + + 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.default); + +exports.default = Store; +module.exports = exports["default"]; +},{"babel-runtime/core-js/map":140,"babel-runtime/helpers/classCallCheck":152,"babel-runtime/helpers/inherits":153,"babel-runtime/helpers/possibleConstructorReturn":154}],25:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +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 = void 0; + + var build = { + global: buildGlobal, + umd: buildUmd, + var: buildVar + }[outputType]; + + if (build) { + tree = build(namespace, builder); + } else { + throw new Error(messages.get("unsupportedOutputType", outputType)); + } + + return (0, _babelGenerator2.default)(tree).code; +}; + +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 _each = require("lodash/each"); + +var _each2 = _interopRequireDefault(_each); + +var _babelTypes = require("babel-types"); + +var t = _interopRequireWildcard(_babelTypes); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +var buildUmdWrapper = (0, _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) { + (0, _each2.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)))); + }); +} +module.exports = exports["default"]; +},{"babel-generator":53,"babel-helpers":75,"babel-messages":76,"babel-template":156,"babel-types":193,"lodash/each":533}],26:[function(require,module,exports){ +(function (process){ +"use strict"; + +exports.__esModule = true; +exports.File = undefined; + +var _typeof2 = require("babel-runtime/helpers/typeof"); + +var _typeof3 = _interopRequireDefault(_typeof2); + +var _getIterator2 = require("babel-runtime/core-js/get-iterator"); + +var _getIterator3 = _interopRequireDefault(_getIterator2); + +var _create = require("babel-runtime/core-js/object/create"); + +var _create2 = _interopRequireDefault(_create); + +var _assign = require("babel-runtime/core-js/object/assign"); + +var _assign2 = _interopRequireDefault(_assign); + +var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck"); + +var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); + +var _possibleConstructorReturn2 = require("babel-runtime/helpers/possibleConstructorReturn"); + +var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); + +var _inherits2 = require("babel-runtime/helpers/inherits"); + +var _inherits3 = _interopRequireDefault(_inherits2); + +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 _optionManager = require("./options/option-manager"); + +var _optionManager2 = _interopRequireDefault(_optionManager); + +var _pluginPass = require("../plugin-pass"); + +var _pluginPass2 = _interopRequireDefault(_pluginPass); + +var _shebangRegex = require("shebang-regex"); + +var _shebangRegex2 = _interopRequireDefault(_shebangRegex); + +var _babelTraverse = require("babel-traverse"); + +var _babelTraverse2 = _interopRequireDefault(_babelTraverse); + +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 _defaults = require("lodash/defaults"); + +var _defaults2 = _interopRequireDefault(_defaults); + +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 _resolve = require("../../helpers/resolve"); + +var _resolve2 = _interopRequireDefault(_resolve); + +var _blockHoist = require("../internal-plugins/block-hoist"); + +var _blockHoist2 = _interopRequireDefault(_blockHoist); + +var _shadowFunctions = require("../internal-plugins/shadow-functions"); + +var _shadowFunctions2 = _interopRequireDefault(_shadowFunctions); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var INTERNAL_PLUGINS = [[_blockHoist2.default], [_shadowFunctions2.default]]; + +var errorVisitor = { + enter: function enter(path, state) { + var loc = path.node.loc; + if (loc) { + state.loc = loc; + path.stop(); + } + } +}; + +var File = function (_Store) { + (0, _inherits3.default)(File, _Store); + + function File() { + var opts = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0]; + var pipeline = arguments[1]; + (0, _classCallCheck3.default)(this, File); + + var _this = (0, _possibleConstructorReturn3.default)(this, _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, + sourceFileName: _this.opts.filename, + plugins: [] + }; + + _this.pluginVisitors = []; + _this.pluginPasses = []; + + _this.buildPluginsForOptions(_this.opts); + + if (_this.opts.passPerPreset) { + _this.perPresetOpts = []; + _this.opts.presets.forEach(function (presetOpts) { + var perPresetOpts = (0, _assign2.default)((0, _create2.default)(_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); + return _this; + } + + File.prototype.getMetadata = function getMetadata() { + var has = false; + for (var _iterator = this.ast.program.body, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_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 node = _ref; + + if (t.isModuleDeclaration(node)) { + has = true; + break; + } + } + if (has) { + this.path.traverse(metadataVisitor, this); + } + }; + + File.prototype.initOptions = function initOptions(opts) { + opts = new _optionManager2.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); + + (0, _defaults2.default)(opts, { + moduleRoot: opts.sourceRoot + }); + + (0, _defaults2.default)(opts, { + sourceRoot: opts.moduleRoot + }); + + (0, _defaults2.default)(opts, { + filenameRelative: opts.filename + }); + + var basenameRelative = _path2.default.basename(opts.filenameRelative); + + (0, _defaults2.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 = []; + + for (var _iterator2 = plugins, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : (0, _getIterator3.default)(_iterator2);;) { + var _ref2; + + if (_isArray2) { + if (_i2 >= _iterator2.length) break; + _ref2 = _iterator2[_i2++]; + } else { + _i2 = _iterator2.next(); + if (_i2.done) break; + _ref2 = _i2.value; + } + + var ref = _ref2; + var plugin = ref[0]; + var pluginOpts = ref[1]; + + + 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; + } + + 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) { + var sourceRootRegEx = new RegExp("^" + opts.sourceRoot + "\/?"); + filenameRelative = filenameRelative.replace(sourceRootRegEx, ""); + } + + filenameRelative = filenameRelative.replace(/\.(\w*?)$/, ""); + + moduleName += filenameRelative; + + moduleName = moduleName.replace(/\\/g, "/"); + + if (opts.getModuleId) { + 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]; + + 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; + }; + + 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 = (0, _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) { + 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 }); + 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 { + (0, _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 + }); + + 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: mapping.source == null ? null : { + line: mapping.originalLine, + column: mapping.originalColumn + }, + + generated: generatedPosition + }); + } + }); + + var mergedMap = mergedGenerator.toJSON(); + inputMap.mappings = mergedMap.mappings; + return { + v: inputMap + }; + }(); + + if ((typeof _ret === "undefined" ? "undefined" : (0, _typeof3.default)(_ret)) === "object") return _ret.v; + } else { + return map; + } + }; + + File.prototype.parse = function parse(code) { + var parseCode = _babylon.parse; + var parserOpts = this.opts.parserOpts; + + if (parserOpts) { + parserOpts = (0, _assign2.default)({}, this.parserOpts, parserOpts); + + if (parserOpts.parser) { + if (typeof parserOpts.parser === "string") { + var dirname = _path2.default.dirname(this.opts.filename) || process.cwd(); + var parser = (0, _resolve2.default)(parserOpts.parser, dirname); + if (parser) { + parseCode = require(parser).parse; + } else { + throw new Error("Couldn't find parser " + parserOpts.parser + " with \"parse\" method relative to directory " + dirname); + } + } else { + parseCode = parserOpts.parser; + } + + parserOpts.parser = { + parse: function parse(source) { + return (0, _babylon.parse)(source, parserOpts); + } + }; + } + } + + this.log.debug("Parse start"); + var ast = parseCode(code, parserOpts || 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() { + for (var i = 0; i < this.pluginPasses.length; i++) { + var pluginPasses = this.pluginPasses[i]; + this.call("pre", pluginPasses); + this.log.debug("Start transform traverse"); + + var visitor = _babelTraverse2.default.visitors.merge(this.pluginVisitors[i], pluginPasses, this.opts.wrapPluginVisitorMethod); + (0, _babelTraverse2.default)(this.ast, visitor, this.scope); + + this.log.debug("End transform traverse"); + this.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 = (0, _babelCodeFrame2.default)(code, loc.line, loc.column + 1, this.opts); + message += "\n" + err.codeFrame; + } + + if (process.browser) { + 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 _iterator3 = pluginPasses, _isArray3 = Array.isArray(_iterator3), _i3 = 0, _iterator3 = _isArray3 ? _iterator3 : (0, _getIterator3.default)(_iterator3);;) { + var _ref3; + + if (_isArray3) { + if (_i3 >= _iterator3.length) break; + _ref3 = _iterator3[_i3++]; + } else { + _i3 = _iterator3.next(); + if (_i3.done) break; + _ref3 = _i3.value; + } + + var pass = _ref3; + + 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(_ref4) { + var code = _ref4.code; + var map = _ref4.map; + var ast = _ref4.ast; + var ignored = _ref4.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); + + var gen = _babelGenerator2.default; + if (opts.generatorOpts.generator) { + gen = opts.generatorOpts.generator; + + if (typeof gen === "string") { + var dirname = _path2.default.dirname(this.opts.filename) || process.cwd(); + var generator = (0, _resolve2.default)(gen, dirname); + if (generator) { + gen = require(generator).print; + } else { + throw new Error("Couldn't find generator " + gen + " with \"print\" method relative to directory " + dirname); + } + } + } + + this.log.debug("Generation start"); + + var _result = gen(ast, opts.generatorOpts ? (0, _assign2.default)(opts, opts.generatorOpts) : opts, this.code); + result.code = _result.code; + result.map = _result.map; + + this.log.debug("Generation end"); + + if (this.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; +}).call(this,require('_process')) +},{"../../helpers/resolve":23,"../../store":24,"../../util":40,"../internal-plugins/block-hoist":35,"../internal-plugins/shadow-functions":36,"../plugin-pass":38,"./logger":27,"./metadata":28,"./options/option-manager":32,"_process":594,"babel-code-frame":18,"babel-generator":53,"babel-helpers":75,"babel-runtime/core-js/get-iterator":138,"babel-runtime/core-js/object/assign":142,"babel-runtime/core-js/object/create":143,"babel-runtime/helpers/classCallCheck":152,"babel-runtime/helpers/inherits":153,"babel-runtime/helpers/possibleConstructorReturn":154,"babel-runtime/helpers/typeof":155,"babel-traverse":160,"babel-types":193,"babylon":197,"convert-source-map":231,"lodash/defaults":532,"path":589,"shebang-regex":672,"source-map":684}],27:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck"); + +var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); + +var _node = require("debug/node"); + +var _node2 = _interopRequireDefault(_node); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var verboseDebug = (0, _node2.default)("babel:verbose"); +var generalDebug = (0, _node2.default)("babel"); + +var seenDeprecatedMessages = []; + +var Logger = function () { + function Logger(file, filename) { + (0, _classCallCheck3.default)(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); + + if (seenDeprecatedMessages.indexOf(msg) >= 0) return; + + 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"]; +},{"babel-runtime/helpers/classCallCheck":152,"debug/node":342}],28:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; +exports.ImportDeclaration = exports.ModuleDeclaration = undefined; + +var _getIterator2 = require("babel-runtime/core-js/get-iterator"); + +var _getIterator3 = _interopRequireDefault(_getIterator2); + +exports.ExportDeclaration = ExportDeclaration; +exports.Scope = Scope; + +var _babelTypes = require("babel-types"); + +var t = _interopRequireWildcard(_babelTypes); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var ModuleDeclaration = exports.ModuleDeclaration = { + enter: function enter(path, file) { + var node = path.node; + + if (node.source) { + node.source.value = file.resolveModuleSource(node.source.value); + } + } +}; + +var ImportDeclaration = exports.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 + }); + + for (var _iterator = path.get("specifiers"), _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_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 specifier = _ref; + + 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 + }); + } + } + } +}; + +function ExportDeclaration(path, file) { + var node = path.node; + + + var source = node.source ? node.source.value : null; + var exports = file.metadata.modules.exports; + + 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) { + for (var _iterator2 = node.specifiers, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : (0, _getIterator3.default)(_iterator2);;) { + var _ref2; + + if (_isArray2) { + if (_i2 >= _iterator2.length) break; + _ref2 = _iterator2[_i2++]; + } else { + _i2 = _iterator2.next(); + if (_i2.done) break; + _ref2 = _i2.value; + } + + var specifier = _ref2; + + var exported = specifier.exported.name; + exports.exported.push(exported); + + if (t.isExportDefaultSpecifier(specifier)) { + exports.specifiers.push({ + kind: "external", + local: exported, + exported: exported, + source: source + }); + } + + if (t.isExportNamespaceSpecifier(specifier)) { + exports.specifiers.push({ + kind: "external-namespace", + exported: exported, + source: source + }); + } + + var local = specifier.local; + if (!local) continue; + + if (source) { + exports.specifiers.push({ + kind: "external", + local: local.name, + exported: exported, + source: source + }); + } + + if (!source) { + exports.specifiers.push({ + kind: "local", + local: local.name, + exported: exported + }); + } + } + } + + if (path.isExportAllDeclaration()) { + exports.specifiers.push({ + kind: "external-all", + source: source + }); + } +} + +function Scope(path) { + path.skip(); +} +},{"babel-runtime/core-js/get-iterator":138,"babel-types":193}],29:[function(require,module,exports){ +(function (process){ +"use strict"; + +exports.__esModule = true; + +var _assign = require("babel-runtime/core-js/object/assign"); + +var _assign2 = _interopRequireDefault(_assign); + +var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck"); + +var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); + +exports.default = buildConfigChain; + +var _resolve = require("../../../helpers/resolve"); + +var _resolve2 = _interopRequireDefault(_resolve); + +var _json = require("json5"); + +var _json2 = _interopRequireDefault(_json); + +var _pathIsAbsolute = require("path-is-absolute"); + +var _pathIsAbsolute2 = _interopRequireDefault(_pathIsAbsolute); + +var _pathExists = require("path-exists"); + +var _pathExists2 = _interopRequireDefault(_pathExists); + +var _path = require("path"); + +var _path2 = _interopRequireDefault(_path); + +var _fs = require("fs"); + +var _fs2 = _interopRequireDefault(_fs); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +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; + } +} + +function buildConfigChain() { + var opts = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0]; + var log = arguments[1]; + + var filename = opts.filename; + var builder = new ConfigChainBuilder(log); + + if (opts.babelrc !== false) { + builder.findConfigs(filename); + } + + builder.mergeConfig({ + options: opts, + alias: "base", + dirname: filename && _path2.default.dirname(filename) + }); + + return builder.configs; +} + +var ConfigChainBuilder = function () { + function ConfigChainBuilder(log) { + (0, _classCallCheck3.default)(this, ConfigChainBuilder); + + this.resolvedConfigs = []; + this.configs = []; + this.log = log; + } + + ConfigChainBuilder.prototype.findConfigs = function findConfigs(loc) { + if (!loc) return; + + if (!(0, _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; + } + }; + + ConfigChainBuilder.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; + }); + + if (lines.length) { + this.mergeConfig({ + options: { ignore: lines }, + alias: loc, + dirname: _path2.default.dirname(loc) + }); + } + }; + + ConfigChainBuilder.prototype.addConfig = function addConfig(loc, key) { + var json = arguments.length <= 2 || arguments[2] === undefined ? _json2.default : arguments[2]; + + if (this.resolvedConfigs.indexOf(loc) >= 0) { + return false; + } + + this.resolvedConfigs.push(loc); + + var content = _fs2.default.readFileSync(loc, "utf8"); + var options = void 0; + + try { + options = jsonCache[content] = jsonCache[content] || json.parse(content); + if (key) options = options[key]; + } catch (err) { + err.message = loc + ": Error while parsing JSON - " + err.message; + throw err; + } + + this.mergeConfig({ + options: options, + alias: loc, + dirname: _path2.default.dirname(loc) + }); + + return !!options; + }; + + ConfigChainBuilder.prototype.mergeConfig = function mergeConfig(_ref) { + var options = _ref.options; + var alias = _ref.alias; + var loc = _ref.loc; + var dirname = _ref.dirname; + + if (!options) { + return false; + } + + options = (0, _assign2.default)({}, options); + + dirname = dirname || process.cwd(); + loc = loc || alias; + + if (options.extends) { + var extendsLoc = (0, _resolve2.default)(options.extends, dirname); + if (extendsLoc) { + this.addConfig(extendsLoc); + } else { + if (this.log) this.log.error("Couldn't resolve extends clause of " + options.extends + " in " + alias); + } + delete options.extends; + } + + this.configs.push({ + options: options, + alias: alias, + loc: loc, + dirname: dirname + }); + + var envOpts = void 0; + var envKey = process.env.BABEL_ENV || process.env.NODE_ENV || "development"; + if (options.env) { + envOpts = options.env[envKey]; + delete options.env; + } + + this.mergeConfig({ + options: envOpts, + alias: alias + ".env." + envKey, + dirname: dirname + }); + }; + + return ConfigChainBuilder; +}(); + +module.exports = exports["default"]; +}).call(this,require('_process')) +},{"../../../helpers/resolve":23,"_process":594,"babel-runtime/core-js/object/assign":142,"babel-runtime/helpers/classCallCheck":152,"fs":220,"json5":358,"path":589,"path-exists":590,"path-is-absolute":591}],30:[function(require,module,exports){ +"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" + }, + + wrapPluginVisitorMethod: { + hidden: true, + description: "optional callback to wrap all visitor methods" + }, + + 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 + }, + + parserOpts: { + description: "Options to pass into the parser, or to change parsers (parserOpts.parser)", + default: false + }, + + generatorOpts: { + description: "Options to pass into the generator, or to change generators (generatorOpts.generator)", + default: false + } +}; +},{}],31:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; +exports.config = undefined; +exports.normaliseOptions = normaliseOptions; + +var _parsers = require("./parsers"); + +var parsers = _interopRequireWildcard(_parsers); + +var _config = require("./config"); + +var _config2 = _interopRequireDefault(_config); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +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; +} +},{"./config":30,"./parsers":33}],32:[function(require,module,exports){ +(function (process){ +"use strict"; + +exports.__esModule = true; + +var _stringify = require("babel-runtime/core-js/json/stringify"); + +var _stringify2 = _interopRequireDefault(_stringify); + +var _assign = require("babel-runtime/core-js/object/assign"); + +var _assign2 = _interopRequireDefault(_assign); + +var _getIterator2 = require("babel-runtime/core-js/get-iterator"); + +var _getIterator3 = _interopRequireDefault(_getIterator2); + +var _typeof2 = require("babel-runtime/helpers/typeof"); + +var _typeof3 = _interopRequireDefault(_typeof2); + +var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck"); + +var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); + +var _node = require("../../../api/node"); + +var context = _interopRequireWildcard(_node); + +var _plugin2 = require("../../plugin"); + +var _plugin3 = _interopRequireDefault(_plugin2); + +var _babelMessages = require("babel-messages"); + +var messages = _interopRequireWildcard(_babelMessages); + +var _index = require("./index"); + +var _resolve = require("../../../helpers/resolve"); + +var _resolve2 = _interopRequireDefault(_resolve); + +var _cloneDeepWith = require("lodash/cloneDeepWith"); + +var _cloneDeepWith2 = _interopRequireDefault(_cloneDeepWith); + +var _clone = require("lodash/clone"); + +var _clone2 = _interopRequireDefault(_clone); + +var _merge = require("../../../helpers/merge"); + +var _merge2 = _interopRequireDefault(_merge); + +var _config2 = require("./config"); + +var _config3 = _interopRequireDefault(_config2); + +var _removed = require("./removed"); + +var _removed2 = _interopRequireDefault(_removed); + +var _buildConfigChain = require("./build-config-chain"); + +var _buildConfigChain2 = _interopRequireDefault(_buildConfigChain); + +var _path = require("path"); + +var _path2 = _interopRequireDefault(_path); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var OptionManager = function () { + function OptionManager(log) { + (0, _classCallCheck3.default)(this, OptionManager); + + this.resolvedConfigs = []; + this.options = OptionManager.createBareOptions(); + this.log = log; + } + + OptionManager.memoisePluginContainer = function memoisePluginContainer(fn, loc, i, alias) { + for (var _iterator = OptionManager.memoisedPlugins, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_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 cache = _ref; + + if (cache.container === fn) return cache.plugin; + } + + var obj = void 0; + + if (typeof fn === "function") { + obj = fn(context); + } else { + obj = fn; + } + + if ((typeof obj === "undefined" ? "undefined" : (0, _typeof3.default)(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 === "undefined" ? "undefined" : (0, _typeof3.default)(obj)) + loc + i); + } + }; + + OptionManager.createBareOptions = function createBareOptions() { + var opts = {}; + + for (var _key in _config3.default) { + var opt = _config3.default[_key]; + opts[_key] = (0, _clone2.default)(opt.default); + } + + return opts; + }; + + OptionManager.normalisePlugin = function normalisePlugin(plugin, loc, i, alias) { + plugin = plugin.__esModule ? plugin.default : plugin; + + if (!(plugin instanceof _plugin3.default)) { + if (typeof plugin === "function" || (typeof plugin === "undefined" ? "undefined" : (0, _typeof3.default)(plugin)) === "object") { + plugin = OptionManager.memoisePluginContainer(plugin, loc, i, alias); + } else { + throw new TypeError(messages.get("pluginNotFunction", loc, i, typeof plugin === "undefined" ? "undefined" : (0, _typeof3.default)(plugin))); + } + } + + plugin.init(loc, i); + + return plugin; + }; + + OptionManager.normalisePlugins = function normalisePlugins(loc, dirname, plugins) { + return plugins.map(function (val, i) { + var plugin = void 0, + options = void 0; + + if (!val) { + throw new TypeError("Falsy value found in plugins"); + } + + if (Array.isArray(val)) { + plugin = val[0]; + options = val[1]; + } else { + plugin = val; + } + + var alias = typeof plugin === "string" ? plugin : loc + "$" + i; + + if (typeof plugin === "string") { + var pluginLoc = (0, _resolve2.default)("babel-plugin-" + plugin, dirname) || (0, _resolve2.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.mergeOptions = function mergeOptions(_ref2) { + var _this = this; + + var rawOpts = _ref2.options; + var extendingOpts = _ref2.extending; + var alias = _ref2.alias; + var loc = _ref2.loc; + var dirname = _ref2.dirname; + + alias = alias || "foreign"; + if (!rawOpts) return; + + if ((typeof rawOpts === "undefined" ? "undefined" : (0, _typeof3.default)(rawOpts)) !== "object" || Array.isArray(rawOpts)) { + this.log.error("Invalid options type for " + alias, TypeError); + } + + var opts = (0, _cloneDeepWith2.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 = _config3.default[_key2]; + + 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); + } + } + } + + (0, _index.normaliseOptions)(opts); + + if (opts.plugins) { + opts.plugins = OptionManager.normalisePlugins(loc, dirname, opts.plugins); + } + + if (opts.presets) { + 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 { + this.mergePresets(opts.presets, dirname); + delete opts.presets; + } + } + + if (rawOpts === extendingOpts) { + (0, _assign2.default)(extendingOpts, opts); + } else { + (0, _merge2.default)(extendingOpts || this.options, opts); + } + }; + + OptionManager.prototype.mergePresets = function mergePresets(presets, dirname) { + var _this2 = this; + + this.resolvePresets(presets, dirname, function (presetOpts, presetLoc) { + _this2.mergeOptions({ + options: presetOpts, + alias: presetLoc, + loc: presetLoc, + dirname: _path2.default.dirname(presetLoc || "") + }); + }); + }; + + OptionManager.prototype.resolvePresets = function resolvePresets(presets, dirname, onResolve) { + return presets.map(function (val) { + var options = void 0; + if (Array.isArray(val)) { + if (val.length > 2) { + throw new Error("Unexpected extra options " + (0, _stringify2.default)(val.slice(2)) + " passed to preset."); + } + + var _val = val; + val = _val[0]; + options = _val[1]; + } + + var presetLoc = void 0; + try { + if (typeof val === "string") { + presetLoc = (0, _resolve2.default)("babel-preset-" + val, dirname) || (0, _resolve2.default)(val, dirname); + + if (!presetLoc) { + var matches = val.match(/^(@[^/]+)\/(.+)$/); + if (matches) { + var orgName = matches[1]; + var presetPath = matches[2]; + + val = orgName + "/babel-preset-" + presetPath; + presetLoc = (0, _resolve2.default)(val, dirname); + } + } + + if (!presetLoc) { + throw new Error("Couldn't find preset " + (0, _stringify2.default)(val) + " relative to directory " + (0, _stringify2.default)(dirname)); + } + + val = require(presetLoc); + } + + if ((typeof val === "undefined" ? "undefined" : (0, _typeof3.default)(val)) === "object" && val.__esModule) val = val.default; + + if ((typeof val === "undefined" ? "undefined" : (0, _typeof3.default)(val)) === "object" && val.buildPreset) val = val.buildPreset; + + if (typeof val !== "function" && options !== undefined) { + throw new Error("Options " + (0, _stringify2.default)(options) + " passed to " + (presetLoc || "a preset") + " which does not accept options."); + } + + if (typeof val === "function") val = val(context, options); + + if ((typeof val === "undefined" ? "undefined" : (0, _typeof3.default)(val)) !== "object") { + throw new Error("Unsupported preset format: " + val + "."); + } + + onResolve && onResolve(val, presetLoc); + } catch (e) { + if (presetLoc) { + e.message += " (While processing preset: " + (0, _stringify2.default)(presetLoc) + ")"; + } + throw e; + } + return val; + }); + }; + + OptionManager.prototype.normaliseOptions = function normaliseOptions() { + var opts = this.options; + + for (var _key3 in _config3.default) { + var option = _config3.default[_key3]; + var val = opts[_key3]; + + if (!val && option.optional) continue; + + 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]; + + for (var _iterator2 = (0, _buildConfigChain2.default)(opts, this.log), _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : (0, _getIterator3.default)(_iterator2);;) { + var _ref3; + + if (_isArray2) { + if (_i2 >= _iterator2.length) break; + _ref3 = _iterator2[_i2++]; + } else { + _i2 = _iterator2.next(); + if (_i2.done) break; + _ref3 = _i2.value; + } + + var _config = _ref3; + + this.mergeOptions(_config); + } + + this.normaliseOptions(opts); + + return this.options; + }; + + return OptionManager; +}(); + +exports.default = OptionManager; + + +OptionManager.memoisedPlugins = []; +module.exports = exports["default"]; +}).call(this,require('_process')) +},{"../../../api/node":20,"../../../helpers/merge":21,"../../../helpers/resolve":23,"../../plugin":39,"./build-config-chain":29,"./config":30,"./index":31,"./removed":34,"_process":594,"babel-messages":76,"babel-runtime/core-js/get-iterator":138,"babel-runtime/core-js/json/stringify":139,"babel-runtime/core-js/object/assign":142,"babel-runtime/helpers/classCallCheck":152,"babel-runtime/helpers/typeof":155,"lodash/clone":527,"lodash/cloneDeepWith":529,"path":589}],33:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; +exports.filename = undefined; +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); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var filename = exports.filename = _slash2.default; + +function boolean(val) { + return !!val; +} + +function booleanString(val) { + return util.booleanify(val); +} + +function list(val) { + return util.list(val); +} +},{"../../../util":40,"slash":673}],34:[function(require,module,exports){ +"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/" + }, + + "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" + } +}; +},{}],35:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +var _plugin = require("../plugin"); + +var _plugin2 = _interopRequireDefault(_plugin); + +var _sortBy = require("lodash/sortBy"); + +var _sortBy2 = _interopRequireDefault(_sortBy); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +exports.default = new _plugin2.default({ + + name: "internal.blockHoist", + + 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 = (0, _sortBy2.default)(node.body, function (bodyNode) { + var priority = bodyNode && bodyNode._blockHoist; + if (priority == null) priority = 1; + if (priority === true) priority = 2; + + return -1 * priority; + }); + } + } + } +}); +module.exports = exports["default"]; +},{"../plugin":39,"lodash/sortBy":574}],36:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +var _symbol = require("babel-runtime/core-js/symbol"); + +var _symbol2 = _interopRequireDefault(_symbol); + +var _plugin = require("../plugin"); + +var _plugin2 = _interopRequireDefault(_plugin); + +var _babelTypes = require("babel-types"); + +var t = _interopRequireWildcard(_babelTypes); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var SUPER_THIS_BOUND = (0, _symbol2.default)("super this bound"); + +var superVisitor = { + CallExpression: function CallExpression(path) { + if (!path.get("callee").isSuper()) return; + + var node = path.node; + + if (node[SUPER_THIS_BOUND]) return; + node[SUPER_THIS_BOUND] = true; + + path.replaceWith(t.assignmentExpression("=", this.id, node)); + } +}; + +exports.default = new _plugin2.default({ + name: "internal.shadowFunctions", + + visitor: { + ThisExpression: function ThisExpression(path) { + remap(path, "this"); + }, + ReferencedIdentifier: function ReferencedIdentifier(path) { + if (path.node.name === "arguments") { + remap(path, "arguments"); + } + } + } +}); + + +function shouldShadow(path, shadowPath) { + if (path.is("_forceShadow")) { + return true; + } else { + return shadowPath; + } +} + +function remap(path, key) { + var shadowPath = path.inShadow(key); + if (!shouldShadow(path, shadowPath)) return; + + var shadowFunction = path.node._shadowedFunctionLiteral; + + var currentFunction = void 0; + var passedShadowFunction = false; + + var fnPath = path.findParent(function (path) { + if (path.isProgram() || path.isFunction()) { + 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()) { + fnPath = path.findParent(function (p) { + return p.isProgram() || p.isFunction(); + }); + } + + if (fnPath === currentFunction) return; + + if (!passedShadowFunction) return; + + var cached = fnPath.getData(key); + if (cached) return path.replaceWith(cached); + + var id = path.scope.generateUidIdentifier(key); + + fnPath.setData(key, id); + + var classPath = fnPath.findParent(function (p) { + return p.isClass(); + }); + var hasSuperClass = !!(classPath && classPath.node && classPath.node.superClass); + + if (key === "this" && fnPath.isMethod({ kind: "constructor" }) && hasSuperClass) { + fnPath.scope.push({ id: id }); + + fnPath.traverse(superVisitor, { id: id }); + } else { + var init = key === "this" ? t.thisExpression() : t.identifier(key); + + fnPath.scope.push({ id: id, init: init }); + } + + return path.replaceWith(id); +} +module.exports = exports["default"]; +},{"../plugin":39,"babel-runtime/core-js/symbol":147,"babel-types":193}],37:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck"); + +var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); + +var _normalizeAst = require("../helpers/normalize-ast"); + +var _normalizeAst2 = _interopRequireDefault(_normalizeAst); + +var _plugin = require("./plugin"); + +var _plugin2 = _interopRequireDefault(_plugin); + +var _file = require("./file"); + +var _file2 = _interopRequireDefault(_file); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var Pipeline = function () { + function Pipeline() { + (0, _classCallCheck3.default)(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) { + var opts = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; + var visitor = arguments[2]; + + 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 = (0, _normalizeAst2.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"]; +},{"../helpers/normalize-ast":22,"./file":26,"./plugin":39,"babel-runtime/helpers/classCallCheck":152}],38:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck"); + +var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); + +var _possibleConstructorReturn2 = require("babel-runtime/helpers/possibleConstructorReturn"); + +var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); + +var _inherits2 = require("babel-runtime/helpers/inherits"); + +var _inherits3 = _interopRequireDefault(_inherits2); + +var _store = require("../store"); + +var _store2 = _interopRequireDefault(_store); + +var _file5 = require("./file"); + +var _file6 = _interopRequireDefault(_file5); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var PluginPass = function (_Store) { + (0, _inherits3.default)(PluginPass, _Store); + + function PluginPass(file, plugin) { + var options = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2]; + (0, _classCallCheck3.default)(this, PluginPass); + + var _this = (0, _possibleConstructorReturn3.default)(this, _Store.call(this)); + + _this.plugin = plugin; + _this.key = plugin.key; + _this.file = file; + _this.opts = options; + return _this; + } + + PluginPass.prototype.addHelper = function addHelper() { + var _file; + + return (_file = this.file).addHelper.apply(_file, arguments); + }; + + PluginPass.prototype.addImport = function addImport() { + var _file2; + + return (_file2 = this.file).addImport.apply(_file2, arguments); + }; + + PluginPass.prototype.getModuleName = function getModuleName() { + var _file3; + + return (_file3 = this.file).getModuleName.apply(_file3, arguments); + }; + + PluginPass.prototype.buildCodeFrameError = function buildCodeFrameError() { + var _file4; + + return (_file4 = this.file).buildCodeFrameError.apply(_file4, arguments); + }; + + return PluginPass; +}(_store2.default); + +exports.default = PluginPass; +module.exports = exports["default"]; +},{"../store":24,"./file":26,"babel-runtime/helpers/classCallCheck":152,"babel-runtime/helpers/inherits":153,"babel-runtime/helpers/possibleConstructorReturn":154}],39:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +var _getIterator2 = require("babel-runtime/core-js/get-iterator"); + +var _getIterator3 = _interopRequireDefault(_getIterator2); + +var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck"); + +var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); + +var _possibleConstructorReturn2 = require("babel-runtime/helpers/possibleConstructorReturn"); + +var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); + +var _inherits2 = require("babel-runtime/helpers/inherits"); + +var _inherits3 = _interopRequireDefault(_inherits2); + +var _optionManager = require("./file/options/option-manager"); + +var _optionManager2 = _interopRequireDefault(_optionManager); + +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 _assign = require("lodash/assign"); + +var _assign2 = _interopRequireDefault(_assign); + +var _clone = require("lodash/clone"); + +var _clone2 = _interopRequireDefault(_clone); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var GLOBAL_VISITOR_PROPS = ["enter", "exit"]; + +var Plugin = function (_Store) { + (0, _inherits3.default)(Plugin, _Store); + + function Plugin(plugin, key) { + (0, _classCallCheck3.default)(this, Plugin); + + var _this = (0, _possibleConstructorReturn3.default)(this, _Store.call(this)); + + _this.initialized = false; + _this.raw = (0, _assign2.default)({}, plugin); + _this.key = _this.take("name") || key; + + _this.manipulateOptions = _this.take("manipulateOptions"); + _this.post = _this.take("post"); + _this.pre = _this.take("pre"); + _this.visitor = _this.normaliseVisitor((0, _clone2.default)(_this.take("visitor")) || {}); + return _this; + } + + 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 = void 0; + + for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + + for (var _iterator = fns, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_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 fn = _ref; + + 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 = _optionManager2.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]); + }; + + 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 _iterator2 = GLOBAL_VISITOR_PROPS, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : (0, _getIterator3.default)(_iterator2);;) { + var _ref2; + + if (_isArray2) { + if (_i2 >= _iterator2.length) break; + _ref2 = _iterator2[_i2++]; + } else { + _i2 = _iterator2.next(); + if (_i2.done) break; + _ref2 = _i2.value; + } + + var key = _ref2; + + 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"]; +},{"../store":24,"./file/options/option-manager":32,"babel-messages":76,"babel-runtime/core-js/get-iterator":138,"babel-runtime/helpers/classCallCheck":152,"babel-runtime/helpers/inherits":153,"babel-runtime/helpers/possibleConstructorReturn":154,"babel-traverse":160,"lodash/assign":524,"lodash/clone":527}],40:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; +exports.inspect = exports.inherits = undefined; + +var _getIterator2 = require("babel-runtime/core-js/get-iterator"); + +var _getIterator3 = _interopRequireDefault(_getIterator2); + +var _util = require("util"); + +Object.defineProperty(exports, "inherits", { + enumerable: true, + get: function get() { + return _util.inherits; + } +}); +Object.defineProperty(exports, "inspect", { + enumerable: true, + get: function get() { + return _util.inspect; + } +}); +exports.canCompile = canCompile; +exports.list = list; +exports.regexify = regexify; +exports.arrayify = arrayify; +exports.booleanify = booleanify; +exports.shouldIgnore = shouldIgnore; + +var _escapeRegExp = require("lodash/escapeRegExp"); + +var _escapeRegExp2 = _interopRequireDefault(_escapeRegExp); + +var _startsWith = require("lodash/startsWith"); + +var _startsWith2 = _interopRequireDefault(_startsWith); + +var _isBoolean = require("lodash/isBoolean"); + +var _isBoolean2 = _interopRequireDefault(_isBoolean); + +var _minimatch = require("minimatch"); + +var _minimatch2 = _interopRequireDefault(_minimatch); + +var _includes = require("lodash/includes"); + +var _includes2 = _interopRequireDefault(_includes); + +var _isString = require("lodash/isString"); + +var _isString2 = _interopRequireDefault(_isString); + +var _isRegExp = require("lodash/isRegExp"); + +var _isRegExp2 = _interopRequireDefault(_isRegExp); + +var _path = require("path"); + +var _path2 = _interopRequireDefault(_path); + +var _slash = require("slash"); + +var _slash2 = _interopRequireDefault(_slash); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function canCompile(filename, altExts) { + var exts = altExts || canCompile.EXTENSIONS; + var ext = _path2.default.extname(filename); + return (0, _includes2.default)(exts, ext); +} + +canCompile.EXTENSIONS = [".js", ".jsx", ".es6", ".es"]; + +function list(val) { + if (!val) { + return []; + } else if (Array.isArray(val)) { + return val; + } else if (typeof val === "string") { + return val.split(","); + } else { + return [val]; + } +} + +function regexify(val) { + if (!val) { + return new RegExp(/.^/); + } + + if (Array.isArray(val)) { + val = new RegExp(val.map(_escapeRegExp2.default).join("|"), "i"); + } + + if (typeof val === "string") { + val = (0, _slash2.default)(val); + + if ((0, _startsWith2.default)(val, "./") || (0, _startsWith2.default)(val, "*/")) val = val.slice(2); + if ((0, _startsWith2.default)(val, "**/")) val = val.slice(3); + + var regex = _minimatch2.default.makeRe(val, { nocase: true }); + return new RegExp(regex.source.slice(1, -1), "i"); + } + + if ((0, _isRegExp2.default)(val)) { + return val; + } + + throw new TypeError("illegal type for regexify"); +} + +function arrayify(val, mapFn) { + if (!val) return []; + if ((0, _isBoolean2.default)(val)) return arrayify([val], mapFn); + if ((0, _isString2.default)(val)) return arrayify(list(val), mapFn); + + if (Array.isArray(val)) { + if (mapFn) val = val.map(mapFn); + return val; + } + + return [val]; +} + +function booleanify(val) { + if (val === "true" || val == 1) { + return true; + } + + if (val === "false" || val == 0 || !val) { + return false; + } + + return val; +} + +function shouldIgnore(filename) { + var ignore = arguments.length <= 1 || arguments[1] === undefined ? [] : arguments[1]; + var only = arguments[2]; + + filename = (0, _slash2.default)(filename); + + if (only) { + for (var _iterator = only, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_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 pattern = _ref; + + if (_shouldIgnore(pattern, filename)) return false; + } + return true; + } else if (ignore.length) { + for (var _iterator2 = ignore, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : (0, _getIterator3.default)(_iterator2);;) { + var _ref2; + + if (_isArray2) { + if (_i2 >= _iterator2.length) break; + _ref2 = _iterator2[_i2++]; + } else { + _i2 = _iterator2.next(); + if (_i2.done) break; + _ref2 = _i2.value; + } + + var _pattern = _ref2; + + if (_shouldIgnore(_pattern, filename)) return true; + } + } + + return false; +} + +function _shouldIgnore(pattern, filename) { + if (typeof pattern === "function") { + return pattern(filename); + } else { + return pattern.test(filename); + } +} +},{"babel-runtime/core-js/get-iterator":138,"lodash/escapeRegExp":535,"lodash/includes":546,"lodash/isBoolean":551,"lodash/isRegExp":560,"lodash/isString":561,"lodash/startsWith":575,"minimatch":586,"path":589,"slash":673,"util":691}],41:[function(require,module,exports){ +module.exports={ + "_args": [ + [ + { + "raw": "babel-core@https://registry.npmjs.org/babel-core/-/babel-core-6.16.0.tgz", + "scope": null, + "escapedName": "babel-core", + "name": "babel-core", + "rawSpec": "https://registry.npmjs.org/babel-core/-/babel-core-6.16.0.tgz", + "spec": "https://registry.npmjs.org/babel-core/-/babel-core-6.16.0.tgz", + "type": "remote" + }, + "/home/mike/dev/repl" + ] + ], + "_from": "babel-core@6.16.0", + "_id": "babel-core@6.16.0", + "_inCache": true, + "_location": "/babel-core", + "_phantomChildren": {}, + "_requested": { + "raw": "babel-core@https://registry.npmjs.org/babel-core/-/babel-core-6.16.0.tgz", + "scope": null, + "escapedName": "babel-core", + "name": "babel-core", + "rawSpec": "https://registry.npmjs.org/babel-core/-/babel-core-6.16.0.tgz", + "spec": "https://registry.npmjs.org/babel-core/-/babel-core-6.16.0.tgz", + "type": "remote" + }, + "_requiredBy": [ + "/", + "/babel-register", + "/babelify", + "/systemjs-builder" + ], + "_resolved": "https://registry.npmjs.org/babel-core/-/babel-core-6.16.0.tgz", + "_shasum": "cf8bbfdf0097c4146195d80d9ec96d73acf387d5", + "_shrinkwrap": null, + "_spec": "babel-core@https://registry.npmjs.org/babel-core/-/babel-core-6.16.0.tgz", + "_where": "/home/mike/dev/repl", + "author": { + "name": "Sebastian McKenzie", + "email": "sebmck@gmail.com" + }, + "dependencies": { + "babel-code-frame": "^6.16.0", + "babel-generator": "^6.16.0", + "babel-helpers": "^6.16.0", + "babel-messages": "^6.8.0", + "babel-register": "^6.16.0", + "babel-runtime": "^6.9.1", + "babel-template": "^6.16.0", + "babel-traverse": "^6.16.0", + "babel-types": "^6.16.0", + "babylon": "^6.11.0", + "convert-source-map": "^1.1.0", + "debug": "^2.1.1", + "json5": "^0.4.0", + "lodash": "^4.2.0", + "minimatch": "^3.0.2", + "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.9.0", + "babel-helper-transform-fixture-test-runner": "^6.16.0", + "babel-polyfill": "^6.16.0" + }, + "homepage": "https://babeljs.io/", + "keywords": [ + "6to5", + "babel", + "classes", + "const", + "es6", + "harmony", + "let", + "modules", + "transpile", + "transpiler", + "var" + ], + "license": "MIT", + "name": "babel-core", + "optionalDependencies": {}, + "readme": "# babel-core\n\n> Babel compiler core.\n\n## Install\n\n```\n$ npm install babel-core\n```\n\n## Usage\n\n```js\nimport babel from 'babel-core';\n\nconst code = `class Example {}`;\nconst result = babel.transform(code, { /* options */ });\n\nresult.code; // Generated code\nresult.map; // Sourcemap\nresult.ast; // AST\n```\n\nFor more in depth documentation see: http://babeljs.io/docs/usage/api/\n", + "readmeFilename": "README.md", + "repository": { + "type": "git", + "url": "https://github.com/babel/babel/tree/master/packages/babel-core" + }, + "scripts": { + "bench": "make bench", + "test": "make test" + }, + "version": "6.16.0" +} + +},{}],42:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck"); + +var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); + +var _trimEnd = require("lodash/trimEnd"); + +var _trimEnd2 = _interopRequireDefault(_trimEnd); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var SPACES_RE = /^[ \t]+$/; + +var Buffer = function () { + function Buffer(map) { + (0, _classCallCheck3.default)(this, Buffer); + this._map = null; + this._buf = []; + this._last = ""; + this._queue = []; + this._position = { + line: 1, + column: 0 + }; + this._sourcePosition = { + identifierName: null, + line: null, + column: null, + filename: null + }; + + this._map = map; + } + + Buffer.prototype.get = function get() { + this._flush(); + + return { + code: (0, _trimEnd2.default)(this._buf.join("")), + map: this._map ? this._map.get() : null + }; + }; + + Buffer.prototype.append = function append(str) { + this._flush(); + var _sourcePosition = this._sourcePosition; + var line = _sourcePosition.line; + var column = _sourcePosition.column; + var filename = _sourcePosition.filename; + var identifierName = _sourcePosition.identifierName; + + this._append(str, line, column, identifierName, filename); + }; + + Buffer.prototype.queue = function queue(str) { + if (str === "\n") while (this._queue.length > 0 && SPACES_RE.test(this._queue[0][0])) { + this._queue.shift(); + }var _sourcePosition2 = this._sourcePosition; + var line = _sourcePosition2.line; + var column = _sourcePosition2.column; + var filename = _sourcePosition2.filename; + var identifierName = _sourcePosition2.identifierName; + + this._queue.unshift([str, line, column, identifierName, filename]); + }; + + Buffer.prototype._flush = function _flush() { + var item = void 0; + while (item = this._queue.pop()) { + this._append.apply(this, item); + } + }; + + Buffer.prototype._append = function _append(str, line, column, identifierName, filename) { + if (this._map && str[0] !== "\n") { + this._map.mark(this._position.line, this._position.column, line, column, identifierName, filename); + } + + this._buf.push(str); + this._last = str[str.length - 1]; + + for (var i = 0; i < str.length; i++) { + if (str[i] === "\n") { + this._position.line++; + this._position.column = 0; + } else { + this._position.column++; + } + } + }; + + Buffer.prototype.removeTrailingNewline = function removeTrailingNewline() { + if (this._queue.length > 0 && this._queue[0][0] === "\n") this._queue.shift(); + }; + + Buffer.prototype.removeLastSemicolon = function removeLastSemicolon() { + if (this._queue.length > 0 && this._queue[0][0] === ";") this._queue.shift(); + }; + + Buffer.prototype.endsWith = function endsWith(suffix) { + if (suffix.length === 1) { + var last = void 0; + if (this._queue.length > 0) { + var str = this._queue[0][0]; + last = str[str.length - 1]; + } else { + last = this._last; + } + + return last === suffix; + } + + var end = this._last + this._queue.reduce(function (acc, item) { + return item[0] + acc; + }, ""); + if (suffix.length <= end.length) { + return end.slice(-suffix.length) === suffix; + } + + return false; + }; + + Buffer.prototype.hasContent = function hasContent() { + return this._queue.length > 0 || !!this._last; + }; + + Buffer.prototype.source = function source(prop, loc) { + if (prop && !loc) return; + + var pos = loc ? loc[prop] : null; + + this._sourcePosition.identifierName = loc && loc.identifierName || null; + this._sourcePosition.line = pos ? pos.line : null; + this._sourcePosition.column = pos ? pos.column : null; + this._sourcePosition.filename = loc && loc.filename || null; + }; + + Buffer.prototype.withSource = function withSource(prop, loc, cb) { + if (!this._map) return cb(); + + var originalLine = this._sourcePosition.line; + var originalColumn = this._sourcePosition.column; + var originalFilename = this._sourcePosition.filename; + var originalIdentifierName = this._sourcePosition.identifierName; + + this.source(prop, loc); + + cb(); + + this._sourcePosition.line = originalLine; + this._sourcePosition.column = originalColumn; + this._sourcePosition.filename = originalFilename; + this._sourcePosition.identifierName = originalIdentifierName; + }; + + Buffer.prototype.getCurrentColumn = function getCurrentColumn() { + var extra = this._queue.reduce(function (acc, item) { + return item[0] + acc; + }, ""); + var lastIndex = extra.lastIndexOf("\n"); + + return lastIndex === -1 ? this._position.column + extra.length : extra.length - 1 - lastIndex; + }; + + Buffer.prototype.getCurrentLine = function getCurrentLine() { + var extra = this._queue.reduce(function (acc, item) { + return item[0] + acc; + }, ""); + + var count = 0; + for (var i = 0; i < extra.length; i++) { + if (extra[i] === "\n") count++; + } + + return this._position.line + count; + }; + + return Buffer; +}(); + +exports.default = Buffer; +module.exports = exports["default"]; +},{"babel-runtime/helpers/classCallCheck":152,"lodash/trimEnd":583}],43:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; +exports.File = File; +exports.Program = Program; +exports.BlockStatement = BlockStatement; +exports.Noop = Noop; +exports.Directive = Directive; + +var _types = require("./types"); + +Object.defineProperty(exports, "DirectiveLiteral", { + enumerable: true, + get: function get() { + return _types.StringLiteral; + } +}); +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.token("{"); + 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 }); + this.removeTrailingNewline(); + + this.source("end", node.loc); + + if (!this.endsWith("\n")) this.newline(); + + this.rightBrace(); + } else { + this.source("end", node.loc); + this.token("}"); + } +} + +function Noop() {} + +function Directive(node) { + this.print(node.value, node); + this.semicolon(); +} +},{"./types":52}],44:[function(require,module,exports){ +"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); + this.word("class"); + + if (node.id) { + this.space(); + this.print(node.id, node); + } + + this.print(node.typeParameters, node); + + if (node.superClass) { + this.space(); + this.word("extends"); + this.space(); + this.print(node.superClass, node); + this.print(node.superTypeParameters, node); + } + + if (node.implements) { + this.space(); + this.word("implements"); + this.space(); + this.printList(node.implements, node); + } + + this.space(); + this.print(node.body, node); +} + +exports.ClassExpression = ClassDeclaration; +function ClassBody(node) { + this.token("{"); + this.printInnerComments(node); + if (node.body.length === 0) { + this.token("}"); + } else { + this.newline(); + + this.indent(); + this.printSequence(node.body, node); + this.dedent(); + + if (!this.endsWith("\n")) this.newline(); + + this.rightBrace(); + } +} + +function ClassProperty(node) { + this.printJoin(node.decorators, node); + + if (node.static) { + this.word("static"); + this.space(); + } + if (node.computed) { + this.token("["); + this.print(node.key, node); + this.token("]"); + } else { + this.print(node.key, node); + } + this.print(node.typeAnnotation, node); + if (node.value) { + this.space(); + this.token("="); + this.space(); + this.print(node.value, node); + } + this.semicolon(); +} + +function ClassMethod(node) { + this.printJoin(node.decorators, node); + + if (node.static) { + this.word("static"); + this.space(); + } + + if (node.kind === "constructorCall") { + this.word("call"); + this.space(); + } + + this._method(node); +} +},{}],45:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; +exports.LogicalExpression = exports.BinaryExpression = exports.AwaitExpression = exports.YieldExpression = undefined; +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 _isNumber = require("lodash/isNumber"); + +var _isNumber2 = _interopRequireDefault(_isNumber); + +var _babelTypes = require("babel-types"); + +var t = _interopRequireWildcard(_babelTypes); + +var _node = require("../node"); + +var n = _interopRequireWildcard(_node); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function UnaryExpression(node) { + if (node.operator === "void" || node.operator === "delete" || node.operator === "typeof") { + this.word(node.operator); + this.space(); + } else { + this.token(node.operator); + } + + this.print(node.argument, node); +} + +function DoExpression(node) { + this.word("do"); + this.space(); + this.print(node.body, node); +} + +function ParenthesizedExpression(node) { + this.token("("); + this.print(node.expression, node); + this.token(")"); +} + +function UpdateExpression(node) { + if (node.prefix) { + this.token(node.operator); + this.print(node.argument, node); + } else { + this.print(node.argument, node); + this.token(node.operator); + } +} + +function ConditionalExpression(node) { + this.print(node.test, node); + this.space(); + this.token("?"); + this.space(); + this.print(node.consequent, node); + this.space(); + this.token(":"); + this.space(); + this.print(node.alternate, node); +} + +function NewExpression(node, parent) { + this.word("new"); + this.space(); + 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.token("("); + this.printList(node.arguments, node); + this.token(")"); +} + +function SequenceExpression(node) { + this.printList(node.expressions, node); +} + +function ThisExpression() { + this.word("this"); +} + +function Super() { + this.word("super"); +} + +function Decorator(node) { + this.token("@"); + this.print(node.expression, node); + this.newline(); +} + +function commaSeparatorNewline() { + this.token(","); + this.newline(); + + if (!this.endsWith("\n")) this.space(); +} + +function CallExpression(node) { + this.print(node.callee, node); + + this.token("("); + + var isPrettyCall = node._prettyCall; + + var separator = void 0; + if (isPrettyCall) { + separator = commaSeparatorNewline; + this.newline(); + this.indent(); + } + + this.printList(node.arguments, node, { separator: separator }); + + if (isPrettyCall) { + this.newline(); + this.dedent(); + } + + this.token(")"); +} + +function buildYieldAwait(keyword) { + return function (node) { + this.word(keyword); + + if (node.delegate) { + this.token("*"); + } + + if (node.argument) { + this.space(); + var terminatorState = this.startTerminatorless(); + this.print(node.argument, node); + this.endTerminatorless(terminatorState); + } + }; +} + +var YieldExpression = exports.YieldExpression = buildYieldAwait("yield"); +var AwaitExpression = exports.AwaitExpression = buildYieldAwait("await"); + +function EmptyStatement() { + this.semicolon(true); +} + +function ExpressionStatement(node) { + this.print(node.expression, node); + this.semicolon(); +} + +function AssignmentPattern(node) { + this.print(node.left, node); + this.space(); + this.token("="); + this.space(); + this.print(node.right, node); +} + +function AssignmentExpression(node, parent) { + var parens = this.inForStatementInitCounter && node.operator === "in" && !n.needsParens(node, parent); + + if (parens) { + this.token("("); + } + + this.print(node.left, node); + + this.space(); + if (node.operator === "in" || node.operator === "instanceof") { + this.word(node.operator); + } else { + this.token(node.operator); + } + this.space(); + + this.print(node.right, node); + + if (parens) { + this.token(")"); + } +} + +function BindExpression(node) { + this.print(node.object, node); + this.token("::"); + 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) && (0, _isNumber2.default)(node.property.value)) { + computed = true; + } + + if (computed) { + this.token("["); + this.print(node.property, node); + this.token("]"); + } else { + this.token("."); + this.print(node.property, node); + } +} + +function MetaProperty(node) { + this.print(node.meta, node); + this.token("."); + this.print(node.property, node); +} +},{"../node":54,"babel-types":193,"lodash/isNumber":556}],46:[function(require,module,exports){ +"use strict"; + +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.DeclareModuleExports = DeclareModuleExports; +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; + +var _types = require("./types"); + +Object.defineProperty(exports, "NumericLiteralTypeAnnotation", { + enumerable: true, + get: function get() { + return _types.NumericLiteral; + } +}); +Object.defineProperty(exports, "StringLiteralTypeAnnotation", { + enumerable: true, + get: function get() { + return _types.StringLiteral; + } +}); +exports.NumberTypeAnnotation = NumberTypeAnnotation; +exports.StringTypeAnnotation = StringTypeAnnotation; +exports.ThisTypeAnnotation = ThisTypeAnnotation; +exports.TupleTypeAnnotation = TupleTypeAnnotation; +exports.TypeofTypeAnnotation = TypeofTypeAnnotation; +exports.TypeAlias = TypeAlias; +exports.TypeAnnotation = TypeAnnotation; +exports.TypeParameter = TypeParameter; +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; +function AnyTypeAnnotation() { + this.word("any"); +} + +function ArrayTypeAnnotation(node) { + this.print(node.elementType, node); + this.token("["); + this.token("]"); +} + +function BooleanTypeAnnotation() { + this.word("bool"); +} + +function BooleanLiteralTypeAnnotation(node) { + this.word(node.value ? "true" : "false"); +} + +function NullLiteralTypeAnnotation() { + this.word("null"); +} + +function DeclareClass(node) { + this.word("declare"); + this.space(); + this.word("class"); + this.space(); + this._interfaceish(node); +} + +function DeclareFunction(node) { + this.word("declare"); + this.space(); + this.word("function"); + this.space(); + this.print(node.id, node); + this.print(node.id.typeAnnotation.typeAnnotation, node); + this.semicolon(); +} + +function DeclareInterface(node) { + this.word("declare"); + this.space(); + this.InterfaceDeclaration(node); +} + +function DeclareModule(node) { + this.word("declare"); + this.space(); + this.word("module"); + this.space(); + this.print(node.id, node); + this.space(); + this.print(node.body, node); +} + +function DeclareModuleExports(node) { + this.word("declare"); + this.space(); + this.word("module"); + this.token("."); + this.word("exports"); + this.print(node.typeAnnotation, node); +} + +function DeclareTypeAlias(node) { + this.word("declare"); + this.space(); + this.TypeAlias(node); +} + +function DeclareVariable(node) { + this.word("declare"); + this.space(); + this.word("var"); + this.space(); + this.print(node.id, node); + this.print(node.id.typeAnnotation, node); + this.semicolon(); +} + +function ExistentialTypeParam() { + this.token("*"); +} + +function FunctionTypeAnnotation(node, parent) { + this.print(node.typeParameters, node); + this.token("("); + this.printList(node.params, node); + + if (node.rest) { + if (node.params.length) { + this.token(","); + this.space(); + } + this.token("..."); + this.print(node.rest, node); + } + + this.token(")"); + + if (parent.type === "ObjectTypeCallProperty" || parent.type === "DeclareFunction") { + this.token(":"); + } else { + this.space(); + this.token("=>"); + } + + this.space(); + this.print(node.returnType, node); +} + +function FunctionTypeParam(node) { + this.print(node.name, node); + if (node.optional) this.token("?"); + this.token(":"); + 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.space(); + this.word("extends"); + this.space(); + this.printList(node.extends, node); + } + if (node.mixins && node.mixins.length) { + this.space(); + this.word("mixins"); + this.space(); + this.printList(node.mixins, node); + } + this.space(); + this.print(node.body, node); +} + +function InterfaceDeclaration(node) { + this.word("interface"); + this.space(); + this._interfaceish(node); +} + +function andSeparator() { + this.space(); + this.token("&"); + this.space(); +} + +function IntersectionTypeAnnotation(node) { + this.printJoin(node.types, node, { separator: andSeparator }); +} + +function MixedTypeAnnotation() { + this.word("mixed"); +} + +function NullableTypeAnnotation(node) { + this.token("?"); + this.print(node.typeAnnotation, node); +} + +function NumberTypeAnnotation() { + this.word("number"); +} + +function StringTypeAnnotation() { + this.word("string"); +} + +function ThisTypeAnnotation() { + this.word("this"); +} + +function TupleTypeAnnotation(node) { + this.token("["); + this.printList(node.types, node); + this.token("]"); +} + +function TypeofTypeAnnotation(node) { + this.word("typeof"); + this.space(); + this.print(node.argument, node); +} + +function TypeAlias(node) { + this.word("type"); + this.space(); + this.print(node.id, node); + this.print(node.typeParameters, node); + this.space(); + this.token("="); + this.space(); + this.print(node.right, node); + this.semicolon(); +} + +function TypeAnnotation(node) { + this.token(":"); + this.space(); + if (node.optional) this.token("?"); + this.print(node.typeAnnotation, node); +} + +function TypeParameter(node) { + if (node.variance === "plus") { + this.token("+"); + } else if (node.variance === "minus") { + this.token("-"); + } + + this.word(node.name); + + if (node.bound) { + this.print(node.bound, node); + } + + if (node.default) { + this.space(); + this.token("="); + this.space(); + this.print(node.default, node); + } +} + +function TypeParameterInstantiation(node) { + this.token("<"); + this.printList(node.params, node, {}); + this.token(">"); +} + +exports.TypeParameterDeclaration = TypeParameterInstantiation; +function ObjectTypeAnnotation(node) { + var _this = this; + + if (node.exact) { + this.token("{|"); + } else { + this.token("{"); + } + + var props = node.properties.concat(node.callProperties, node.indexers); + + if (props.length) { + this.space(); + + this.printJoin(props, node, { + indent: true, + statement: true, + iterator: function iterator() { + if (props.length !== 1) { + _this.semicolon(); + _this.space(); + } + } + }); + + this.space(); + } + + if (node.exact) { + this.token("|}"); + } else { + this.token("}"); + } +} + +function ObjectTypeCallProperty(node) { + if (node.static) { + this.word("static"); + this.space(); + } + this.print(node.value, node); +} + +function ObjectTypeIndexer(node) { + if (node.static) { + this.word("static"); + this.space(); + } + this.token("["); + this.print(node.id, node); + this.token(":"); + this.space(); + this.print(node.key, node); + this.token("]"); + this.token(":"); + this.space(); + this.print(node.value, node); +} + +function ObjectTypeProperty(node) { + if (node.static) { + this.word("static"); + this.space(); + } + this.print(node.key, node); + if (node.optional) this.token("?"); + this.token(":"); + this.space(); + this.print(node.value, node); +} + +function QualifiedTypeIdentifier(node) { + this.print(node.qualification, node); + this.token("."); + this.print(node.id, node); +} + +function orSeparator() { + this.space(); + this.token("|"); + this.space(); +} + +function UnionTypeAnnotation(node) { + this.printJoin(node.types, node, { separator: orSeparator }); +} + +function TypeCastExpression(node) { + this.token("("); + this.print(node.expression, node); + this.print(node.typeAnnotation, node); + this.token(")"); +} + +function VoidTypeAnnotation() { + this.word("void"); +} +},{"./types":52}],47:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +var _getIterator2 = require("babel-runtime/core-js/get-iterator"); + +var _getIterator3 = _interopRequireDefault(_getIterator2); + +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 _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function JSXAttribute(node) { + this.print(node.name, node); + if (node.value) { + this.token("="); + this.print(node.value, node); + } +} + +function JSXIdentifier(node) { + this.word(node.name); +} + +function JSXNamespacedName(node) { + this.print(node.namespace, node); + this.token(":"); + this.print(node.name, node); +} + +function JSXMemberExpression(node) { + this.print(node.object, node); + this.token("."); + this.print(node.property, node); +} + +function JSXSpreadAttribute(node) { + this.token("{"); + this.token("..."); + this.print(node.argument, node); + this.token("}"); +} + +function JSXExpressionContainer(node) { + this.token("{"); + this.print(node.expression, node); + this.token("}"); +} + +function JSXText(node) { + this.token(node.value); +} + +function JSXElement(node) { + var open = node.openingElement; + this.print(open, node); + if (open.selfClosing) return; + + this.indent(); + for (var _iterator = node.children, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_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 child = _ref; + + this.print(child, node); + } + this.dedent(); + + this.print(node.closingElement, node); +} + +function spaceSeparator() { + this.space(); +} + +function JSXOpeningElement(node) { + this.token("<"); + this.print(node.name, node); + if (node.attributes.length > 0) { + this.space(); + this.printJoin(node.attributes, node, { separator: spaceSeparator }); + } + if (node.selfClosing) { + this.space(); + this.token("/>"); + } else { + this.token(">"); + } +} + +function JSXClosingElement(node) { + this.token(""); +} + +function JSXEmptyExpression() {} +},{"babel-runtime/core-js/get-iterator":138}],48:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; +exports.FunctionDeclaration = undefined; +exports._params = _params; +exports._method = _method; +exports.FunctionExpression = FunctionExpression; +exports.ArrowFunctionExpression = ArrowFunctionExpression; + +var _babelTypes = require("babel-types"); + +var t = _interopRequireWildcard(_babelTypes); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _params(node) { + var _this = this; + + this.print(node.typeParameters, node); + this.token("("); + this.printList(node.params, node, { + iterator: function iterator(node) { + if (node.optional) _this.token("?"); + _this.print(node.typeAnnotation, node); + } + }); + this.token(")"); + + 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.token("*"); + } + } + + if (kind === "get" || kind === "set") { + this.word(kind); + this.space(); + } + + if (node.async) { + this.word("async"); + this.space(); + } + + if (node.computed) { + this.token("["); + this.print(key, node); + this.token("]"); + } else { + this.print(key, node); + } + + this._params(node); + this.space(); + this.print(node.body, node); +} + +function FunctionExpression(node) { + if (node.async) { + this.word("async"); + this.space(); + } + this.word("function"); + if (node.generator) this.token("*"); + + if (node.id) { + this.space(); + 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.word("async"); + this.space(); + } + + var firstParam = node.params[0]; + + if (node.params.length === 1 && t.isIdentifier(firstParam) && !hasTypes(node, firstParam)) { + this.print(firstParam, node); + } else { + this._params(node); + } + + this.space(); + this.token("=>"); + this.space(); + + this.print(node.body, node); +} + +function hasTypes(node, param) { + return node.typeParameters || node.returnType || param.typeAnnotation || param.optional || param.trailingComments; +} +},{"babel-types":193}],49:[function(require,module,exports){ +"use strict"; + +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 _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function ImportSpecifier(node) { + this.print(node.imported, node); + if (node.local && node.local.name !== node.imported.name) { + this.space(); + this.word("as"); + this.space(); + 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.space(); + this.word("as"); + this.space(); + this.print(node.exported, node); + } +} + +function ExportNamespaceSpecifier(node) { + this.token("*"); + this.space(); + this.word("as"); + this.space(); + this.print(node.exported, node); +} + +function ExportAllDeclaration(node) { + this.word("export"); + this.space(); + this.token("*"); + if (node.exported) { + this.space(); + this.word("as"); + this.space(); + this.print(node.exported, node); + } + this.space(); + this.word("from"); + this.space(); + this.print(node.source, node); + this.semicolon(); +} + +function ExportNamedDeclaration() { + this.word("export"); + this.space(); + ExportDeclaration.apply(this, arguments); +} + +function ExportDefaultDeclaration() { + this.word("export"); + this.space(); + this.word("default"); + this.space(); + ExportDeclaration.apply(this, arguments); +} + +function ExportDeclaration(node) { + if (node.declaration) { + var declar = node.declaration; + this.print(declar, node); + if (!t.isStatement(declar)) this.semicolon(); + } else { + if (node.exportKind === "type") { + this.word("type"); + this.space(); + } + + var specifiers = node.specifiers.slice(0); + + 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.token(","); + this.space(); + } + } else { + break; + } + } + + if (specifiers.length || !specifiers.length && !hasSpecial) { + this.token("{"); + if (specifiers.length) { + this.space(); + this.printList(specifiers, node); + this.space(); + } + this.token("}"); + } + + if (node.source) { + this.space(); + this.word("from"); + this.space(); + this.print(node.source, node); + } + + this.semicolon(); + } +} + +function ImportDeclaration(node) { + this.word("import"); + this.space(); + + if (node.importKind === "type" || node.importKind === "typeof") { + this.word(node.importKind); + this.space(); + } + + var specifiers = node.specifiers.slice(0); + if (specifiers && specifiers.length) { + while (true) { + var first = specifiers[0]; + if (t.isImportDefaultSpecifier(first) || t.isImportNamespaceSpecifier(first)) { + this.print(specifiers.shift(), node); + if (specifiers.length) { + this.token(","); + this.space(); + } + } else { + break; + } + } + + if (specifiers.length) { + this.token("{"); + this.space(); + this.printList(specifiers, node); + this.space(); + this.token("}"); + } + + this.space(); + this.word("from"); + this.space(); + } + + this.print(node.source, node); + this.semicolon(); +} + +function ImportNamespaceSpecifier(node) { + this.token("*"); + this.space(); + this.word("as"); + this.space(); + this.print(node.local, node); +} +},{"babel-types":193}],50:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; +exports.ThrowStatement = exports.BreakStatement = exports.ReturnStatement = exports.ContinueStatement = exports.ForAwaitStatement = exports.ForOfStatement = exports.ForInStatement = undefined; + +var _getIterator2 = require("babel-runtime/core-js/get-iterator"); + +var _getIterator3 = _interopRequireDefault(_getIterator2); + +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 _babelTypes = require("babel-types"); + +var t = _interopRequireWildcard(_babelTypes); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function WithStatement(node) { + this.word("with"); + this.space(); + this.token("("); + this.print(node.object, node); + this.token(")"); + this.printBlock(node); +} + +function IfStatement(node) { + this.word("if"); + this.space(); + this.token("("); + this.print(node.test, node); + this.token(")"); + this.space(); + + var needsBlock = node.alternate && t.isIfStatement(getLastStatement(node.consequent)); + if (needsBlock) { + this.token("{"); + this.newline(); + this.indent(); + } + + this.printAndIndentOnComments(node.consequent, node); + + if (needsBlock) { + this.dedent(); + this.newline(); + this.token("}"); + } + + if (node.alternate) { + if (this.endsWith("}")) this.space(); + this.word("else"); + this.space(); + this.printAndIndentOnComments(node.alternate, node); + } +} + +function getLastStatement(statement) { + if (!t.isStatement(statement.body)) return statement; + return getLastStatement(statement.body); +} + +function ForStatement(node) { + this.word("for"); + this.space(); + this.token("("); + + this.inForStatementInitCounter++; + this.print(node.init, node); + this.inForStatementInitCounter--; + this.token(";"); + + if (node.test) { + this.space(); + this.print(node.test, node); + } + this.token(";"); + + if (node.update) { + this.space(); + this.print(node.update, node); + } + + this.token(")"); + this.printBlock(node); +} + +function WhileStatement(node) { + this.word("while"); + this.space(); + this.token("("); + this.print(node.test, node); + this.token(")"); + this.printBlock(node); +} + +var buildForXStatement = function buildForXStatement(op) { + return function (node) { + this.word("for"); + this.space(); + if (op === "await") { + this.word("await"); + this.space(); + op = "of"; + } + this.token("("); + + this.print(node.left, node); + this.space(); + this.word(op); + this.space(); + this.print(node.right, node); + this.token(")"); + this.printBlock(node); + }; +}; + +var ForInStatement = exports.ForInStatement = buildForXStatement("in"); +var ForOfStatement = exports.ForOfStatement = buildForXStatement("of"); +var ForAwaitStatement = exports.ForAwaitStatement = buildForXStatement("await"); + +function DoWhileStatement(node) { + this.word("do"); + this.space(); + this.print(node.body, node); + this.space(); + this.word("while"); + this.space(); + this.token("("); + this.print(node.test, node); + this.token(")"); + this.semicolon(); +} + +function buildLabelStatement(prefix) { + var key = arguments.length <= 1 || arguments[1] === undefined ? "label" : arguments[1]; + + return function (node) { + this.word(prefix); + + var label = node[key]; + if (label) { + this.space(); + + var terminatorState = this.startTerminatorless(); + this.print(label, node); + this.endTerminatorless(terminatorState); + } + + this.semicolon(); + }; +} + +var ContinueStatement = exports.ContinueStatement = buildLabelStatement("continue"); +var ReturnStatement = exports.ReturnStatement = buildLabelStatement("return", "argument"); +var BreakStatement = exports.BreakStatement = buildLabelStatement("break"); +var ThrowStatement = exports.ThrowStatement = buildLabelStatement("throw", "argument"); + +function LabeledStatement(node) { + this.print(node.label, node); + this.token(":"); + this.space(); + this.print(node.body, node); +} + +function TryStatement(node) { + this.word("try"); + this.space(); + this.print(node.block, node); + this.space(); + + if (node.handlers) { + this.print(node.handlers[0], node); + } else { + this.print(node.handler, node); + } + + if (node.finalizer) { + this.space(); + this.word("finally"); + this.space(); + this.print(node.finalizer, node); + } +} + +function CatchClause(node) { + this.word("catch"); + this.space(); + this.token("("); + this.print(node.param, node); + this.token(")"); + this.space(); + this.print(node.body, node); +} + +function SwitchStatement(node) { + this.word("switch"); + this.space(); + this.token("("); + this.print(node.discriminant, node); + this.token(")"); + this.space(); + this.token("{"); + + this.printSequence(node.cases, node, { + indent: true, + addNewlines: function addNewlines(leading, cas) { + if (!leading && node.cases[node.cases.length - 1] === cas) return -1; + } + }); + + this.token("}"); +} + +function SwitchCase(node) { + if (node.test) { + this.word("case"); + this.space(); + this.print(node.test, node); + this.token(":"); + } else { + this.word("default"); + this.token(":"); + } + + if (node.consequent.length) { + this.newline(); + this.printSequence(node.consequent, node, { indent: true }); + } +} + +function DebuggerStatement() { + this.word("debugger"); + this.semicolon(); +} + +function variableDeclarationIdent() { + this.token(","); + this.newline(); + if (this.endsWith("\n")) for (var i = 0; i < 4; i++) { + this.space(true); + } +} + +function constDeclarationIdent() { + this.token(","); + this.newline(); + if (this.endsWith("\n")) for (var i = 0; i < 6; i++) { + this.space(true); + } +} + +function VariableDeclaration(node, parent) { + this.word(node.kind); + this.space(); + + var hasInits = false; + + if (!t.isFor(parent)) { + for (var _iterator = node.declarations, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_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 declar = _ref; + + if (declar.init) { + hasInits = true; + } + } + } + + var separator = void 0; + if (hasInits) { + separator = node.kind === "const" ? constDeclarationIdent : variableDeclarationIdent; + } + + this.printList(node.declarations, node, { separator: separator }); + + if (t.isFor(parent)) { + 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.token("="); + this.space(); + this.print(node.init, node); + } +} +},{"babel-runtime/core-js/get-iterator":138,"babel-types":193}],51:[function(require,module,exports){ +"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, parent) { + var isFirst = parent.quasis[0] === node; + var isLast = parent.quasis[parent.quasis.length - 1] === node; + + var value = (isFirst ? "`" : "}") + node.value.raw + (isLast ? "`" : "${"); + + if (!isFirst) this.space(); + this.token(value); + if (!isLast) this.space(); +} + +function TemplateLiteral(node) { + var quasis = node.quasis; + + for (var i = 0; i < quasis.length; i++) { + this.print(quasis[i], node); + + if (i + 1 < quasis.length) { + this.print(node.expressions[i], node); + } + } +} +},{}],52:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; +exports.ArrayPattern = exports.ObjectPattern = exports.RestProperty = exports.SpreadProperty = exports.SpreadElement = undefined; +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; + +var _babelTypes = require("babel-types"); + +var t = _interopRequireWildcard(_babelTypes); + +var _jsesc = require("jsesc"); + +var _jsesc2 = _interopRequireDefault(_jsesc); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function Identifier(node) { + if (node.variance) { + if (node.variance === "plus") { + this.token("+"); + } else if (node.variance === "minus") { + this.token("-"); + } + } + + this.word(node.name); +} + +function RestElement(node) { + this.token("..."); + this.print(node.argument, node); +} + +exports.SpreadElement = RestElement; +exports.SpreadProperty = RestElement; +exports.RestProperty = RestElement; +function ObjectExpression(node) { + var props = node.properties; + + this.token("{"); + this.printInnerComments(node); + + if (props.length) { + this.space(); + this.printList(props, node, { indent: true, statement: true }); + this.space(); + } + + this.token("}"); +} + +exports.ObjectPattern = ObjectExpression; +function ObjectMethod(node) { + this.printJoin(node.decorators, node); + this._method(node); +} + +function ObjectProperty(node) { + this.printJoin(node.decorators, node); + + if (node.computed) { + this.token("["); + this.print(node.key, node); + this.token("]"); + } else { + 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); + + if (node.shorthand && t.isIdentifier(node.key) && t.isIdentifier(node.value) && node.key.name === node.value.name) { + return; + } + } + + this.token(":"); + this.space(); + this.print(node.value, node); +} + +function ArrayExpression(node) { + var elems = node.elements; + var len = elems.length; + + this.token("["); + 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.token(","); + } else { + this.token(","); + } + } + + this.token("]"); +} + +exports.ArrayPattern = ArrayExpression; +function RegExpLiteral(node) { + this.word("/" + node.pattern + "/" + node.flags); +} + +function BooleanLiteral(node) { + this.word(node.value ? "true" : "false"); +} + +function NullLiteral() { + this.word("null"); +} + +function NumericLiteral(node) { + var raw = this.getPossibleRaw(node); + + this.number(raw == null ? node.value + "" : raw); +} + +function StringLiteral(node, parent) { + var raw = this.getPossibleRaw(node); + if (raw != null) { + this.token(raw); + return; + } + + var val = (0, _jsesc2.default)(node.value, { + quotes: t.isJSX(parent) ? "double" : this.format.quotes, + wrap: true + }); + + return this.token(val); +} +},{"babel-types":193,"jsesc":357}],53:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; +exports.CodeGenerator = undefined; + +var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck"); + +var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); + +var _possibleConstructorReturn2 = require("babel-runtime/helpers/possibleConstructorReturn"); + +var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); + +var _inherits2 = require("babel-runtime/helpers/inherits"); + +var _inherits3 = _interopRequireDefault(_inherits2); + +exports.default = function (ast, opts, code) { + var gen = new Generator(ast, opts, code); + return gen.generate(); +}; + +var _detectIndent = require("detect-indent"); + +var _detectIndent2 = _interopRequireDefault(_detectIndent); + +var _sourceMap = require("./source-map"); + +var _sourceMap2 = _interopRequireDefault(_sourceMap); + +var _babelMessages = require("babel-messages"); + +var messages = _interopRequireWildcard(_babelMessages); + +var _printer = require("./printer"); + +var _printer2 = _interopRequireDefault(_printer); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var Generator = function (_Printer) { + (0, _inherits3.default)(Generator, _Printer); + + function Generator(ast, opts, code) { + (0, _classCallCheck3.default)(this, Generator); + + opts = opts || {}; + + var tokens = ast.tokens || []; + var format = normalizeOptions(code, opts, tokens); + var map = opts.sourceMaps ? new _sourceMap2.default(opts, code) : null; + + var _this = (0, _possibleConstructorReturn3.default)(this, _Printer.call(this, format, map, tokens)); + + _this.ast = ast; + return _this; + } + + Generator.prototype.generate = function generate() { + return _Printer.prototype.generate.call(this, this.ast); + }; + + return Generator; +}(_printer2.default); + +function normalizeOptions(code, opts, tokens) { + var style = " "; + if (code && typeof code === "string") { + var indent = (0, _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 || findCommonStringDelimiter(code, tokens), + indent: { + adjustMultilineComment: true, + style: style, + base: 0 + } + }; + + if (format.minified) { + format.compact = true; + + format.shouldPrintComment = format.shouldPrintComment || function () { + return format.comments; + }; + } else { + format.shouldPrintComment = format.shouldPrintComment || function (value) { + return format.comments || value.indexOf("@license") >= 0 || value.indexOf("@preserve") >= 0; + }; + } + + if (format.compact === "auto") { + format.compact = code.length > 100000; + + if (format.compact) { + console.error("[BABEL] " + messages.get("codeGeneratorDeopt", opts.filename, "100KB")); + } + } + + if (format.compact) { + format.indent.adjustMultilineComment = false; + } + + return format; +} + +function findCommonStringDelimiter(code, tokens) { + var DEFAULT_STRING_DELIMITER = "double"; + if (!code) { + return DEFAULT_STRING_DELIMITER; + } + + 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"; + } +} + +var CodeGenerator = exports.CodeGenerator = function () { + function CodeGenerator(ast, opts, code) { + (0, _classCallCheck3.default)(this, CodeGenerator); + + this._generator = new Generator(ast, opts, code); + } + + CodeGenerator.prototype.generate = function generate() { + return this._generator.generate(); + }; + + return CodeGenerator; +}(); +},{"./printer":57,"./source-map":58,"babel-messages":76,"babel-runtime/helpers/classCallCheck":152,"babel-runtime/helpers/inherits":153,"babel-runtime/helpers/possibleConstructorReturn":154,"detect-indent":343}],54:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +var _getIterator2 = require("babel-runtime/core-js/get-iterator"); + +var _getIterator3 = _interopRequireDefault(_getIterator2); + +var _keys = require("babel-runtime/core-js/object/keys"); + +var _keys2 = _interopRequireDefault(_keys); + +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 _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function expandAliases(obj) { + var newObj = {}; + + function add(type, func) { + var fn = newObj[type]; + newObj[type] = fn ? function (node, parent, stack) { + var result = fn(node, parent, stack); + + return result == null ? func(node, parent, stack) : result; + } : func; + } + + for (var _iterator = (0, _keys2.default)(obj), _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_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 type = _ref; + + + var aliases = t.FLIPPED_ALIAS_KEYS[type]; + if (aliases) { + for (var _iterator2 = aliases, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : (0, _getIterator3.default)(_iterator2);;) { + var _ref2; + + if (_isArray2) { + if (_i2 >= _iterator2.length) break; + _ref2 = _iterator2[_i2++]; + } else { + _i2 = _iterator2.next(); + if (_i2.done) break; + _ref2 = _i2.value; + } + + var alias = _ref2; + + add(alias, obj[type]); + } + } else { + add(type, obj[type]); + } + } + + return newObj; +} + +var expandedParens = expandAliases(parens); +var expandedWhitespaceNodes = expandAliases(_whitespace2.default.nodes); +var expandedWhitespaceList = expandAliases(_whitespace2.default.list); + +function find(obj, node, parent, printStack) { + var fn = obj[node.type]; + return fn ? fn(node, parent, printStack) : null; +} + +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 needsWhitespace(node, parent, type) { + if (!node) return 0; + + if (t.isExpressionStatement(node)) { + node = node.expression; + } + + var linesInfo = find(expandedWhitespaceNodes, node, parent); + + if (!linesInfo) { + var items = find(expandedWhitespaceList, 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(expandedParens, node, parent, printStack); +} +},{"./parentheses":55,"./whitespace":56,"babel-runtime/core-js/get-iterator":138,"babel-runtime/core-js/object/keys":145,"babel-types":193}],55:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; +exports.AwaitExpression = exports.FunctionTypeAnnotation = undefined; +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); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +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) { + return true; + } + + return false; +} + +function ObjectExpression(node, parent, printStack) { + return isFirstInStatement(printStack, { considerArrow: 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; + } + + if (parentPos === nodePos && parent.right === node && !t.isLogicalExpression(parent)) { + return true; + } + } + + return false; +} + +function BinaryExpression(node, parent) { + if (node.operator === "in") { + if (t.isVariableDeclarator(parent)) { + return true; + } + + if (t.isFor(parent)) { + return true; + } + } + + return false; +} + +function SequenceExpression(node, parent) { + if (t.isForStatement(parent)) { + 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; + } + + 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, printStack) { + return isFirstInStatement(printStack, { considerDefaultExports: true }); +} + +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) { + return isFirstInStatement(printStack, { considerDefaultExports: true }); +} + +function ArrowFunctionExpression(node, parent) { + 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); + } +} + +function isFirstInStatement(printStack) { + var _ref = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; + + var _ref$considerArrow = _ref.considerArrow; + var considerArrow = _ref$considerArrow === undefined ? false : _ref$considerArrow; + var _ref$considerDefaultE = _ref.considerDefaultExports; + var considerDefaultExports = _ref$considerDefaultE === undefined ? false : _ref$considerDefaultE; + + 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 (considerDefaultExports && t.isExportDefaultDeclaration(parent, { declaration: 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; +} +},{"babel-types":193}],56:[function(require,module,exports){ +"use strict"; + +var _isBoolean = require("lodash/isBoolean"); + +var _isBoolean2 = _interopRequireDefault(_isBoolean); + +var _each = require("lodash/each"); + +var _each2 = _interopRequireDefault(_each); + +var _map = require("lodash/map"); + +var _map2 = _interopRequireDefault(_map); + +var _babelTypes = require("babel-types"); + +var t = _interopRequireWildcard(_babelTypes); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +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; +} + +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); +} + +exports.nodes = { + AssignmentExpression: function AssignmentExpression(node) { + var state = crawl(node.right); + if (state.hasCall && state.hasHelper || state.hasFunction) { + return { + before: state.hasFunction, + after: true + }; + } + }, + SwitchCase: function SwitchCase(node, parent) { + return { + before: node.consequent.length || parent.cases[0] === node + }; + }, + LogicalExpression: function LogicalExpression(node) { + if (t.isFunction(node.left) || t.isFunction(node.right)) { + return { + after: true + }; + } + }, + Literal: function Literal(node) { + if (node.value === "use strict") { + return { + after: true + }; + } + }, + CallExpression: function CallExpression(node) { + if (t.isFunction(node.callee) || isHelper(node)) { + return { + before: true, + after: true + }; + } + }, + 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 + }; + } + } + }, + IfStatement: function IfStatement(node) { + if (t.isBlockStatement(node.consequent)) { + return { + before: true, + after: true + }; + } + } +}; + +exports.nodes.ObjectProperty = exports.nodes.ObjectTypeProperty = exports.nodes.ObjectMethod = exports.nodes.SpreadProperty = function (node, parent) { + if (parent.properties[0] === node) { + return { + before: true + }; + } +}; + +exports.list = { + VariableDeclaration: function VariableDeclaration(node) { + return (0, _map2.default)(node.declarations, "init"); + }, + ArrayExpression: function ArrayExpression(node) { + return node.elements; + }, + ObjectExpression: function ObjectExpression(node) { + return node.properties; + } +}; + +(0, _each2.default)({ + Function: true, + Class: true, + Loop: true, + LabeledStatement: true, + SwitchStatement: true, + TryStatement: true +}, function (amounts, type) { + if ((0, _isBoolean2.default)(amounts)) { + amounts = { after: amounts, before: amounts }; + } + + (0, _each2.default)([type].concat(t.FLIPPED_ALIAS_KEYS[type] || []), function (type) { + exports.nodes[type] = function () { + return amounts; + }; + }); +}); +},{"babel-types":193,"lodash/each":533,"lodash/isBoolean":551,"lodash/map":566}],57:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +var _assign = require("babel-runtime/core-js/object/assign"); + +var _assign2 = _interopRequireDefault(_assign); + +var _getIterator2 = require("babel-runtime/core-js/get-iterator"); + +var _getIterator3 = _interopRequireDefault(_getIterator2); + +var _stringify = require("babel-runtime/core-js/json/stringify"); + +var _stringify2 = _interopRequireDefault(_stringify); + +var _weakSet = require("babel-runtime/core-js/weak-set"); + +var _weakSet2 = _interopRequireDefault(_weakSet); + +var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck"); + +var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); + +var _find = require("lodash/find"); + +var _find2 = _interopRequireDefault(_find); + +var _findLast = require("lodash/findLast"); + +var _findLast2 = _interopRequireDefault(_findLast); + +var _isInteger = require("lodash/isInteger"); + +var _isInteger2 = _interopRequireDefault(_isInteger); + +var _repeat = require("lodash/repeat"); + +var _repeat2 = _interopRequireDefault(_repeat); + +var _buffer = require("./buffer"); + +var _buffer2 = _interopRequireDefault(_buffer); + +var _node = require("./node"); + +var n = _interopRequireWildcard(_node); + +var _whitespace = require("./whitespace"); + +var _whitespace2 = _interopRequireDefault(_whitespace); + +var _babelTypes = require("babel-types"); + +var t = _interopRequireWildcard(_babelTypes); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var SCIENTIFIC_NOTATION = /e/i; +var ZERO_DECIMAL_INTEGER = /\.0+$/; +var NON_DECIMAL_LITERAL = /^0[box]/; + +var Printer = function () { + function Printer(format, map, tokens) { + (0, _classCallCheck3.default)(this, Printer); + this.inForStatementInitCounter = 0; + this._printStack = []; + this._indent = 0; + this._insideAux = false; + this._printedCommentStarts = {}; + this._parenPushNewlineState = null; + this._printAuxAfterOnNextUserNode = false; + this._printedComments = new _weakSet2.default(); + this._endsWithInteger = false; + this._endsWithWord = false; + + this.format = format || {}; + this._buf = new _buffer2.default(map); + this._whitespace = tokens.length > 0 ? new _whitespace2.default(tokens) : null; + } + + Printer.prototype.generate = function generate(ast) { + this.print(ast); + this._maybeAddAuxComment(); + + return this._buf.get(); + }; + + Printer.prototype.indent = function indent() { + if (this.format.compact || this.format.concise) return; + + this._indent++; + }; + + Printer.prototype.dedent = function dedent() { + if (this.format.compact || this.format.concise) return; + + this._indent--; + }; + + Printer.prototype.semicolon = function semicolon() { + var force = arguments.length <= 0 || arguments[0] === undefined ? false : arguments[0]; + + this._maybeAddAuxComment(); + this._append(";", !force); + }; + + Printer.prototype.rightBrace = function rightBrace() { + if (this.format.minified) { + this._buf.removeLastSemicolon(); + } + this.token("}"); + }; + + Printer.prototype.space = function space() { + var force = arguments.length <= 0 || arguments[0] === undefined ? false : arguments[0]; + + if (this.format.compact) return; + + if (this._buf.hasContent() && !this.endsWith(" ") && !this.endsWith("\n") || force) { + this._space(); + } + }; + + Printer.prototype.word = function word(str) { + if (this._endsWithWord) this._space(); + + this._maybeAddAuxComment(); + this._append(str); + + this._endsWithWord = true; + }; + + Printer.prototype.number = function number(str) { + this.word(str); + + this._endsWithInteger = (0, _isInteger2.default)(+str) && !NON_DECIMAL_LITERAL.test(str) && !SCIENTIFIC_NOTATION.test(str) && !ZERO_DECIMAL_INTEGER.test(str) && str[str.length - 1] !== "."; + }; + + Printer.prototype.token = function token(str) { + if (str === "--" && this.endsWith("!") || str[0] === "+" && this.endsWith("+") || str[0] === "-" && this.endsWith("-") || str[0] === "." && this._endsWithInteger) { + this._space(); + } + + this._maybeAddAuxComment(); + this._append(str); + }; + + Printer.prototype.newline = function newline(i) { + if (this.format.retainLines || this.format.compact) return; + + if (this.format.concise) { + this.space(); + return; + } + + if (this.endsWith("\n\n")) return; + + if (typeof i !== "number") i = 1; + + i = Math.min(2, i); + if (this.endsWith("{\n") || this.endsWith(":\n")) i--; + if (i <= 0) return; + + for (var j = 0; j < i; j++) { + this._newline(); + } + }; + + Printer.prototype.endsWith = function endsWith(str) { + return this._buf.endsWith(str); + }; + + Printer.prototype.removeTrailingNewline = function removeTrailingNewline() { + this._buf.removeTrailingNewline(); + }; + + Printer.prototype.source = function source(prop, loc) { + this._catchUp(prop, loc); + + this._buf.source(prop, loc); + }; + + Printer.prototype.withSource = function withSource(prop, loc, cb) { + this._catchUp(prop, loc); + + this._buf.withSource(prop, loc, cb); + }; + + Printer.prototype._space = function _space() { + this._append(" ", true); + }; + + Printer.prototype._newline = function _newline() { + this._append("\n", true); + }; + + Printer.prototype._append = function _append(str) { + var queue = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1]; + + this._maybeAddParen(str); + this._maybeIndent(str); + + if (queue) this._buf.queue(str);else this._buf.append(str); + + this._endsWithWord = false; + this._endsWithInteger = false; + }; + + Printer.prototype._maybeIndent = function _maybeIndent(str) { + if (this._indent && this.endsWith("\n") && str[0] !== "\n") { + this._buf.queue(this._getIndent()); + } + }; + + Printer.prototype._maybeAddParen = function _maybeAddParen(str) { + var parenPushNewlineState = this._parenPushNewlineState; + if (!parenPushNewlineState) return; + this._parenPushNewlineState = null; + + var i = void 0; + for (i = 0; i < str.length && str[i] === " "; i++) { + continue; + }if (i === str.length) return; + + var cha = str[i]; + if (cha === "\n" || cha === "/") { + this.token("("); + this.indent(); + parenPushNewlineState.printed = true; + } + }; + + Printer.prototype._catchUp = function _catchUp(prop, loc) { + if (!this.format.retainLines) return; + + var pos = loc ? loc[prop] : null; + if (pos && pos.line !== null) { + var count = pos.line - this._buf.getCurrentLine(); + + for (var i = 0; i < count; i++) { + this._newline(); + } + } + }; + + Printer.prototype._getIndent = function _getIndent() { + return (0, _repeat2.default)(this.format.indent.style, this._indent); + }; + + Printer.prototype.startTerminatorless = function startTerminatorless() { + return this._parenPushNewlineState = { + printed: false + }; + }; + + Printer.prototype.endTerminatorless = function endTerminatorless(state) { + if (state.printed) { + this.dedent(); + this.newline(); + this.token(")"); + } + }; + + Printer.prototype.print = function print(node, parent) { + var _this = this; + + if (!node) return; + + 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 " + (0, _stringify2.default)(node.type) + " with constructor " + (0, _stringify2.default)(node && node.constructor.name)); + } + + this._printStack.push(node); + + var oldInAux = this._insideAux; + this._insideAux = !node.loc; + this._maybeAddAuxComment(this._insideAux && !oldInAux); + + var needsParens = n.needsParens(node, parent, this._printStack); + if (needsParens) this.token("("); + + this._printLeadingComments(node, parent); + + var loc = t.isProgram(node) || t.isFile(node) ? null : node.loc; + this.withSource("start", loc, function () { + _this[node.type](node, parent); + }); + + this._printTrailingComments(node, parent); + + if (needsParens) this.token(")"); + + this._printStack.pop(); + + this.format.concise = oldConcise; + this._insideAux = oldInAux; + }; + + Printer.prototype._maybeAddAuxComment = function _maybeAddAuxComment(enteredPositionlessNode) { + if (enteredPositionlessNode) this._printAuxBeforeComment(); + if (!this._insideAux) this._printAuxAfterComment(); + }; + + Printer.prototype._printAuxBeforeComment = function _printAuxBeforeComment() { + if (this._printAuxAfterOnNextUserNode) return; + this._printAuxAfterOnNextUserNode = true; + + var comment = this.format.auxiliaryCommentBefore; + if (comment) { + this._printComment({ + type: "CommentBlock", + value: comment + }); + } + }; + + Printer.prototype._printAuxAfterComment = function _printAuxAfterComment() { + if (!this._printAuxAfterOnNextUserNode) return; + this._printAuxAfterOnNextUserNode = false; + + var comment = this.format.auxiliaryCommentAfter; + if (comment) { + this._printComment({ + type: "CommentBlock", + value: comment + }); + } + }; + + Printer.prototype.getPossibleRaw = function getPossibleRaw(node) { + if (this.format.minified) return; + + var extra = node.extra; + if (extra && extra.raw != null && extra.rawValue != null && node.value === extra.rawValue) { + return extra.raw; + } + }; + + Printer.prototype.printJoin = function printJoin(nodes, parent) { + var opts = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2]; + + if (!nodes || !nodes.length) return; + + if (opts.indent) this.indent(); + + var newlineOpts = { + addNewlines: opts.addNewlines + }; + + for (var i = 0; i < nodes.length; i++) { + var node = nodes[i]; + if (!node) continue; + + if (opts.statement) this._printNewline(true, node, parent, newlineOpts); + + this.print(node, parent); + + if (opts.iterator) { + opts.iterator(node, i); + } + + if (opts.separator && i < nodes.length - 1) { + opts.separator.call(this); + } + + if (opts.statement) this._printNewline(false, node, parent, newlineOpts); + } + + 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._printTrailingComments = function _printTrailingComments(node, parent) { + this._printComments(this._getComments(false, node, parent)); + }; + + Printer.prototype._printLeadingComments = function _printLeadingComments(node, parent) { + this._printComments(this._getComments(true, 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 = commaSeparator; + } + + return this.printJoin(items, parent, opts); + }; + + Printer.prototype._printNewline = function _printNewline(leading, node, parent, opts) { + var _this2 = this; + + if (this.format.retainLines || this.format.compact) return; + + if (this.format.concise) { + this.space(); + return; + } + + var lines = 0; + + if (node.start != null && !node._ignoreUserWhitespace && this._whitespace) { + if (leading) { + var _comments = node.leadingComments; + var _comment = _comments && (0, _find2.default)(_comments, function (comment) { + return !!comment.loc && _this2.format.shouldPrintComment(comment.value); + }); + + lines = this._whitespace.getNewlinesBefore(_comment || node); + } else { + var _comments2 = node.trailingComments; + var _comment2 = _comments2 && (0, _findLast2.default)(_comments2, function (comment) { + return !!comment.loc && _this2.format.shouldPrintComment(comment.value); + }); + + lines = this._whitespace.getNewlinesAfter(_comment2 || node); + } + } else { + if (!leading) lines++; + if (opts.addNewlines) lines += opts.addNewlines(leading, node) || 0; + + var needs = n.needsWhitespaceAfter; + if (leading) needs = n.needsWhitespaceBefore; + if (needs(node, parent)) lines++; + + if (!this._buf.hasContent()) lines = 0; + } + + this.newline(lines); + }; + + Printer.prototype._getComments = function _getComments(leading, node) { + return node && (leading ? node.leadingComments : node.trailingComments) || []; + }; + + Printer.prototype._printComment = function _printComment(comment) { + var _this3 = this; + + if (!this.format.shouldPrintComment(comment.value)) return; + + if (comment.ignore) return; + + if (this._printedComments.has(comment)) return; + this._printedComments.add(comment); + + if (comment.start != null) { + if (this._printedCommentStarts[comment.start]) return; + this._printedCommentStarts[comment.start] = true; + } + + this.newline(this._whitespace ? this._whitespace.getNewlinesBefore(comment) : 0); + + if (!this.endsWith("[") && !this.endsWith("{")) this.space(); + + var val = comment.type === "CommentLine" ? "//" + comment.value + "\n" : "/*" + comment.value + "*/"; + + 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 indentSize = Math.max(this._getIndent().length, this._buf.getCurrentColumn()); + val = val.replace(/\n(?!$)/g, "\n" + (0, _repeat2.default)(" ", indentSize)); + } + + this.withSource("start", comment.loc, function () { + _this3._append(val); + }); + + this.newline((this._whitespace ? this._whitespace.getNewlinesAfter(comment) : 0) + (comment.type === "CommentLine" ? -1 : 0)); + }; + + Printer.prototype._printComments = function _printComments(comments) { + if (!comments || !comments.length) return; + + for (var _iterator = comments, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_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 _comment3 = _ref; + + this._printComment(_comment3); + } + }; + + return Printer; +}(); + +exports.default = Printer; + + +function commaSeparator() { + this.token(","); + this.space(); +} + +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]; + (0, _assign2.default)(Printer.prototype, generator); +} +module.exports = exports["default"]; +},{"./buffer":42,"./generators/base":43,"./generators/classes":44,"./generators/expressions":45,"./generators/flow":46,"./generators/jsx":47,"./generators/methods":48,"./generators/modules":49,"./generators/statements":50,"./generators/template-literals":51,"./generators/types":52,"./node":54,"./whitespace":59,"babel-runtime/core-js/get-iterator":138,"babel-runtime/core-js/json/stringify":139,"babel-runtime/core-js/object/assign":142,"babel-runtime/core-js/weak-set":151,"babel-runtime/helpers/classCallCheck":152,"babel-types":193,"lodash/find":537,"lodash/findLast":539,"lodash/isInteger":554,"lodash/repeat":573}],58:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +var _keys = require("babel-runtime/core-js/object/keys"); + +var _keys2 = _interopRequireDefault(_keys); + +var _typeof2 = require("babel-runtime/helpers/typeof"); + +var _typeof3 = _interopRequireDefault(_typeof2); + +var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck"); + +var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); + +var _sourceMap = require("source-map"); + +var _sourceMap2 = _interopRequireDefault(_sourceMap); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var SourceMap = function () { + function SourceMap(opts, code) { + var _this = this; + + (0, _classCallCheck3.default)(this, SourceMap); + + this._opts = opts; + 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 === "undefined" ? "undefined" : (0, _typeof3.default)(code)) === "object") { + (0, _keys2.default)(code).forEach(function (sourceFileName) { + _this._map.setSourceContent(sourceFileName, code[sourceFileName]); + }); + } + } + + SourceMap.prototype.get = function get() { + return this._map.toJSON(); + }; + + SourceMap.prototype.mark = function mark(generatedLine, generatedColumn, line, column, identifierName, filename) { + if (this._lastGenLine !== generatedLine && line === null) return; + + if (this._lastGenLine === generatedLine && this._lastSourceLine === line && this._lastSourceColumn === column) { + return; + } + + this._lastGenLine = generatedLine; + this._lastSourceLine = line; + this._lastSourceColumn = column; + + this._map.addMapping({ + name: identifierName, + generated: { + line: generatedLine, + column: generatedColumn + }, + source: line == null ? null : filename || this._opts.sourceFileName, + original: line == null ? null : { + line: line, + column: column + } + }); + }; + + return SourceMap; +}(); + +exports.default = SourceMap; +module.exports = exports["default"]; +},{"babel-runtime/core-js/object/keys":145,"babel-runtime/helpers/classCallCheck":152,"babel-runtime/helpers/typeof":155,"source-map":684}],59:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck"); + +var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var Whitespace = function () { + function Whitespace(tokens) { + (0, _classCallCheck3.default)(this, Whitespace); + + this.tokens = tokens; + this.used = {}; + } + + Whitespace.prototype.getNewlinesBefore = function getNewlinesBefore(node) { + var startToken = void 0; + var endToken = void 0; + 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); + }; + + Whitespace.prototype.getNewlinesAfter = function getNewlinesAfter(node) { + var startToken = void 0; + var endToken = void 0; + 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 { + return this._getNewlinesBetween(startToken, endToken); + } + }; + + 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; + }; + + 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"]; +},{"babel-runtime/helpers/classCallCheck":152}],60:[function(require,module,exports){ +/*istanbul ignore next*/"use strict"; + +exports.__esModule = true; + +var _getIterator2 = require("babel-runtime/core-js/get-iterator"); + +var _getIterator3 = _interopRequireDefault(_getIterator2); + +exports.default = bindifyDecorators; + +var /*istanbul ignore next*/_babelTypes = require("babel-types"); + +/*istanbul ignore next*/ +var t = _interopRequireWildcard(_babelTypes); + +/*istanbul ignore next*/ +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function bindifyDecorators(decorators) { + for ( /*istanbul ignore next*/var _iterator = decorators, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { + /*istanbul ignore next*/ + var _ref; + + if (_isArray) { + if (_i >= _iterator.length) break; + _ref = _iterator[_i++]; + } else { + _i = _iterator.next(); + if (_i.done) break; + _ref = _i.value; + } + + var decoratorPath = _ref; + + var decorator = decoratorPath.node; + var expression = decorator.expression; + if (!t.isMemberExpression(expression)) continue; + + var temp = decoratorPath.scope.maybeGenerateMemoised(expression.object); + var ref = /*istanbul ignore next*/void 0; + + var nodes = []; + + if (temp) { + ref = temp; + nodes.push(t.assignmentExpression("=", temp, expression.object)); + } else { + ref = expression.object; + } + + nodes.push(t.callExpression(t.memberExpression(t.memberExpression(ref, expression.property, expression.computed), t.identifier("bind")), [ref])); + + if (nodes.length === 1) { + decorator.expression = nodes[0]; + } else { + decorator.expression = t.sequenceExpression(nodes); + } + } +} +/*istanbul ignore next*/module.exports = exports["default"]; +},{"babel-runtime/core-js/get-iterator":138,"babel-types":193}],61:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +exports.default = function (opts) { + var visitor = {}; + + function isAssignment(node) { + return node && node.operator === opts.operator + "="; + } + + function buildAssignment(left, right) { + return t.assignmentExpression("=", left, right); + } + + visitor.ExpressionStatement = function (path, file) { + if (path.isCompletionRecord()) return; + + var expr = path.node.expression; + if (!isAssignment(expr)) return; + + var nodes = []; + var exploded = (0, _babelHelperExplodeAssignableExpression2.default)(expr.left, nodes, file, path.scope, true); + + nodes.push(t.expressionStatement(buildAssignment(exploded.ref, opts.build(exploded.uid, expr.right)))); + + path.replaceWithMultiple(nodes); + }; + + visitor.AssignmentExpression = function (path, file) { + var node = path.node; + var scope = path.scope; + + if (!isAssignment(node)) return; + + var nodes = []; + var exploded = (0, _babelHelperExplodeAssignableExpression2.default)(node.left, nodes, file, scope); + nodes.push(buildAssignment(exploded.ref, opts.build(exploded.uid, node.right))); + path.replaceWithMultiple(nodes); + }; + + visitor.BinaryExpression = function (path) { + var node = path.node; + + if (node.operator === opts.operator) { + path.replaceWith(opts.build(node.left, node.right)); + } + }; + + return visitor; +}; + +var _babelHelperExplodeAssignableExpression = require("babel-helper-explode-assignable-expression"); + +var _babelHelperExplodeAssignableExpression2 = _interopRequireDefault(_babelHelperExplodeAssignableExpression); + +var _babelTypes = require("babel-types"); + +var t = _interopRequireWildcard(_babelTypes); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +module.exports = exports["default"]; +},{"babel-helper-explode-assignable-expression":64,"babel-types":193}],62:[function(require,module,exports){ +/*istanbul ignore next*/"use strict"; + +exports.__esModule = true; + +exports.default = function (path) { + /*istanbul ignore next*/var scope = arguments.length <= 1 || arguments[1] === undefined ? path.scope : arguments[1]; + /*istanbul ignore next*/var node = path.node; + + var container = t.functionExpression(null, [], node.body, node.generator, node.async); + + var callee = container; + var args = []; + + // todo: only hoist if necessary + /*istanbul ignore next*/(0, _babelHelperHoistVariables2.default)(path, function (id) /*istanbul ignore next*/{ + return scope.push({ id: id }); + }); + + var state = { + foundThis: false, + foundArguments: false + }; + + path.traverse(visitor, state); + + if (state.foundArguments) { + callee = t.memberExpression(container, t.identifier("apply")); + args = []; + + if (state.foundThis) { + args.push(t.thisExpression()); + } + + if (state.foundArguments) { + if (!state.foundThis) args.push(t.nullLiteral()); + args.push(t.identifier("arguments")); + } + } + + var call = t.callExpression(callee, args); + if (node.generator) call = t.yieldExpression(call, true); + + return t.returnStatement(call); +}; + +var /*istanbul ignore next*/_babelHelperHoistVariables = require("babel-helper-hoist-variables"); + +/*istanbul ignore next*/ +var _babelHelperHoistVariables2 = _interopRequireDefault(_babelHelperHoistVariables); + +var /*istanbul ignore next*/_babelTypes = require("babel-types"); + +/*istanbul ignore next*/ +var t = _interopRequireWildcard(_babelTypes); + +/*istanbul ignore next*/ +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var visitor = { /*istanbul ignore next*/ + enter: function enter(path, state) { + if (path.isThisExpression()) { + state.foundThis = true; + } + + if (path.isReferencedIdentifier({ name: "arguments" })) { + state.foundArguments = true; + } + }, + /*istanbul ignore next*/Function: function Function(path) { + path.skip(); + } +}; + +/*istanbul ignore next*/module.exports = exports["default"]; +},{"babel-helper-hoist-variables":68,"babel-types":193}],63:[function(require,module,exports){ +/*istanbul ignore next*/"use strict"; + +exports.__esModule = true; +exports.push = push; +/*istanbul ignore next*/exports.hasComputed = hasComputed; +/*istanbul ignore next*/exports.toComputedObjectFromClass = toComputedObjectFromClass; +/*istanbul ignore next*/exports.toClassObject = toClassObject; +/*istanbul ignore next*/exports.toDefineObject = toDefineObject; + +var /*istanbul ignore next*/_babelHelperFunctionName = require("babel-helper-function-name"); + +/*istanbul ignore next*/ +var _babelHelperFunctionName2 = _interopRequireDefault(_babelHelperFunctionName); + +var /*istanbul ignore next*/_each = require("lodash/each"); + +/*istanbul ignore next*/ +var _each2 = _interopRequireDefault(_each); + +var /*istanbul ignore next*/_has = require("lodash/has"); + +/*istanbul ignore next*/ +var _has2 = _interopRequireDefault(_has); + +var /*istanbul ignore next*/_babelTypes = require("babel-types"); + +/*istanbul ignore next*/ +var t = _interopRequireWildcard(_babelTypes); + +/*istanbul ignore next*/ +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/* eslint max-len: 0 */ + +function toKind(node) { + if (t.isClassMethod(node) || t.isObjectMethod(node)) { + if (node.kind === "get" || node.kind === "set") { + return node.kind; + } + } + + return "value"; +} + +function push(mutatorMap, node, kind, file, scope) { + var alias = t.toKeyAlias(node); + + // + + var map = {}; + if ( /*istanbul ignore next*/(0, _has2.default)(mutatorMap, alias)) map = mutatorMap[alias]; + mutatorMap[alias] = map; + + // + + map._inherits = map._inherits || []; + map._inherits.push(node); + + map._key = node.key; + + if (node.computed) { + map._computed = true; + } + + if (node.decorators) { + var decorators = map.decorators = map.decorators || t.arrayExpression([]); + decorators.elements = decorators.elements.concat(node.decorators.map(function (dec) /*istanbul ignore next*/{ + return dec.expression; + }).reverse()); + } + + if (map.value || map.initializer) { + throw file.buildCodeFrameError(node, "Key conflict with sibling node"); + } + + var key = /*istanbul ignore next*/void 0, + value = /*istanbul ignore next*/void 0; + + // save the key so we can possibly do function name inferences + if (t.isObjectProperty(node) || t.isObjectMethod(node) || t.isClassMethod(node)) { + key = t.toComputedKey(node, node.key); + } + + if (t.isObjectProperty(node) || t.isClassProperty(node)) { + value = node.value; + } else if (t.isObjectMethod(node) || t.isClassMethod(node)) { + value = t.functionExpression(null, node.params, node.body, node.generator, node.async); + } + + var inheritedKind = toKind(node); + if (!kind || inheritedKind !== "value") { + kind = inheritedKind; + } + + // infer function name + if (scope && t.isStringLiteral(key) && (kind === "value" || kind === "initializer") && t.isFunctionExpression(value)) { + value = /*istanbul ignore next*/(0, _babelHelperFunctionName2.default)({ id: key, node: value, scope: scope }); + } + + if (value) { + t.inheritsComments(value, node); + map[kind] = value; + } + + return map; +} + +function hasComputed(mutatorMap) { + for (var key in mutatorMap) { + if (mutatorMap[key]._computed) { + return true; + } + } + return false; +} + +function toComputedObjectFromClass(obj) { + var objExpr = t.arrayExpression([]); + + for (var i = 0; i < obj.properties.length; i++) { + var prop = obj.properties[i]; + var val = prop.value; + val.properties.unshift(t.objectProperty(t.identifier("key"), t.toComputedKey(prop))); + objExpr.elements.push(val); + } + + return objExpr; +} + +function toClassObject(mutatorMap) { + var objExpr = t.objectExpression([]); + + /*istanbul ignore next*/(0, _each2.default)(mutatorMap, function (map) { + var mapNode = t.objectExpression([]); + + var propNode = t.objectProperty(map._key, mapNode, map._computed); + + /*istanbul ignore next*/(0, _each2.default)(map, function (node, key) { + if (key[0] === "_") return; + + var inheritNode = node; + if (t.isClassMethod(node) || t.isClassProperty(node)) node = node.value; + + var prop = t.objectProperty(t.identifier(key), node); + t.inheritsComments(prop, inheritNode); + t.removeComments(inheritNode); + + mapNode.properties.push(prop); + }); + + objExpr.properties.push(propNode); + }); + + return objExpr; +} + +function toDefineObject(mutatorMap) { + /*istanbul ignore next*/(0, _each2.default)(mutatorMap, function (map) { + if (map.value) map.writable = t.booleanLiteral(true); + map.configurable = t.booleanLiteral(true); + map.enumerable = t.booleanLiteral(true); + }); + + return toClassObject(mutatorMap); +} +},{"babel-helper-function-name":66,"babel-types":193,"lodash/each":533,"lodash/has":543}],64:[function(require,module,exports){ +/*istanbul ignore next*/"use strict"; + +exports.__esModule = true; + +exports.default = function (node, nodes, file, scope, allowedSingleIdent) { + var obj = /*istanbul ignore next*/void 0; + if (t.isIdentifier(node) && allowedSingleIdent) { + obj = node; + } else { + obj = getObjRef(node, nodes, file, scope); + } + + var ref = /*istanbul ignore next*/void 0, + uid = /*istanbul ignore next*/void 0; + + if (t.isIdentifier(node)) { + ref = node; + uid = obj; + } else { + var prop = getPropRef(node, nodes, file, scope); + var computed = node.computed || t.isLiteral(prop); + uid = ref = t.memberExpression(obj, prop, computed); + } + + return { + uid: uid, + ref: ref + }; +}; + +var /*istanbul ignore next*/_babelTypes = require("babel-types"); + +/*istanbul ignore next*/ +var t = _interopRequireWildcard(_babelTypes); + +/*istanbul ignore next*/ +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function getObjRef(node, nodes, file, scope) { + var ref = /*istanbul ignore next*/void 0; + if (t.isIdentifier(node)) { + if (scope.hasBinding(node.name)) { + // this variable is declared in scope so we can be 100% sure + // that evaluating it multiple times wont trigger a getter + // or something else + return node; + } else { + // could possibly trigger a getter so we need to only evaluate + // it once + ref = node; + } + } else if (t.isMemberExpression(node)) { + ref = node.object; + + if (t.isIdentifier(ref) && scope.hasBinding(ref.name)) { + // the object reference that we need to save is locally declared + // so as per the previous comment we can be 100% sure evaluating + // it multiple times will be safe + return ref; + } + } else { + throw new Error( /*istanbul ignore next*/"We can't explode this node type " + node.type); + } + + var temp = scope.generateUidIdentifierBasedOnNode(ref); + nodes.push(t.variableDeclaration("var", [t.variableDeclarator(temp, ref)])); + return temp; +} + +function getPropRef(node, nodes, file, scope) { + var prop = node.property; + var key = t.toComputedKey(node, prop); + if (t.isLiteral(key)) return key; + + var temp = scope.generateUidIdentifierBasedOnNode(prop); + nodes.push(t.variableDeclaration("var", [t.variableDeclarator(temp, prop)])); + return temp; +} + +/*istanbul ignore next*/module.exports = exports["default"]; +},{"babel-types":193}],65:[function(require,module,exports){ +/*istanbul ignore next*/"use strict"; + +exports.__esModule = true; + +var _getIterator2 = require("babel-runtime/core-js/get-iterator"); + +var _getIterator3 = _interopRequireDefault(_getIterator2); + +exports.default = function (classPath) { + classPath.assertClass(); + + var memoisedExpressions = []; + + function maybeMemoise(path) { + if (!path.node || path.isPure()) return; + + var uid = classPath.scope.generateDeclaredUidIdentifier(); + memoisedExpressions.push(t.assignmentExpression("=", uid, path.node)); + path.replaceWith(uid); + } + + function memoiseDecorators(paths) { + if (!Array.isArray(paths) || !paths.length) return; + + // ensure correct evaluation order of decorators + paths = paths.reverse(); + + // bind decorators if they're member expressions + /*istanbul ignore next*/(0, _babelHelperBindifyDecorators2.default)(paths); + + for ( /*istanbul ignore next*/var _iterator = paths, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { + /*istanbul ignore next*/ + var _ref; + + if (_isArray) { + if (_i >= _iterator.length) break; + _ref = _iterator[_i++]; + } else { + _i = _iterator.next(); + if (_i.done) break; + _ref = _i.value; + } + + var path = _ref; + + maybeMemoise(path); + } + } + + maybeMemoise(classPath.get("superClass")); + memoiseDecorators(classPath.get("decorators"), true); + + var methods = classPath.get("body.body"); + for ( /*istanbul ignore next*/var _iterator2 = methods, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : (0, _getIterator3.default)(_iterator2);;) { + /*istanbul ignore next*/ + var _ref2; + + if (_isArray2) { + if (_i2 >= _iterator2.length) break; + _ref2 = _iterator2[_i2++]; + } else { + _i2 = _iterator2.next(); + if (_i2.done) break; + _ref2 = _i2.value; + } + + var methodPath = _ref2; + + if (methodPath.is("computed")) { + maybeMemoise(methodPath.get("key")); + } + + if (methodPath.has("decorators")) { + memoiseDecorators(classPath.get("decorators")); + } + } + + if (memoisedExpressions) { + classPath.insertBefore(memoisedExpressions.map(function (expr) /*istanbul ignore next*/{ + return t.expressionStatement(expr); + })); + } +}; + +var /*istanbul ignore next*/_babelHelperBindifyDecorators = require("babel-helper-bindify-decorators"); + +/*istanbul ignore next*/ +var _babelHelperBindifyDecorators2 = _interopRequireDefault(_babelHelperBindifyDecorators); + +var /*istanbul ignore next*/_babelTypes = require("babel-types"); + +/*istanbul ignore next*/ +var t = _interopRequireWildcard(_babelTypes); + +/*istanbul ignore next*/ +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +module.exports = exports["default"]; +},{"babel-helper-bindify-decorators":60,"babel-runtime/core-js/get-iterator":138,"babel-types":193}],66:[function(require,module,exports){ +/*istanbul ignore next*/"use strict"; + +exports.__esModule = true; + +exports.default = function ( /*istanbul ignore next*/_ref) { + /*istanbul ignore next*/var node = _ref.node; + /*istanbul ignore next*/var parent = _ref.parent; + /*istanbul ignore next*/var scope = _ref.scope; + /*istanbul ignore next*/var id = _ref.id; + + // has an `id` so we don't need to infer one + if (node.id) return; + + if ((t.isObjectProperty(parent) || t.isObjectMethod(parent, { kind: "method" })) && (!parent.computed || t.isLiteral(parent.key))) { + // { foo() {} }; + id = parent.key; + } else if (t.isVariableDeclarator(parent)) { + // let foo = function () {}; + id = parent.id; + + if (t.isIdentifier(id)) { + var binding = scope.parent.getBinding(id.name); + if (binding && binding.constant && scope.getBinding(id.name) === binding) { + // always going to reference this method + node.id = id; + node.id[t.NOT_LOCAL_BINDING] = true; + return; + } + } + } else if (t.isAssignmentExpression(parent)) { + // foo = function () {}; + id = parent.left; + } else if (!id) { + return; + } + + var name = /*istanbul ignore next*/void 0; + if (id && t.isLiteral(id)) { + name = id.value; + } else if (id && t.isIdentifier(id)) { + name = id.name; + } else { + return; + } + + name = t.toBindingIdentifierName(name); + id = t.identifier(name); + + // The id shouldn't be considered a local binding to the function because + // we are simply trying to set the function name and not actually create + // a local binding. + id[t.NOT_LOCAL_BINDING] = true; + + var state = visit(node, name, scope); + return wrap(state, node, id, scope) || node; +}; + +var /*istanbul ignore next*/_babelHelperGetFunctionArity = require("babel-helper-get-function-arity"); + +/*istanbul ignore next*/ +var _babelHelperGetFunctionArity2 = _interopRequireDefault(_babelHelperGetFunctionArity); + +var /*istanbul ignore next*/_babelTemplate = require("babel-template"); + +/*istanbul ignore next*/ +var _babelTemplate2 = _interopRequireDefault(_babelTemplate); + +var /*istanbul ignore next*/_babelTypes = require("babel-types"); + +/*istanbul ignore next*/ +var t = _interopRequireWildcard(_babelTypes); + +/*istanbul ignore next*/ +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var buildPropertyMethodAssignmentWrapper = /*istanbul ignore next*/(0, _babelTemplate2.default)( /*istanbul ignore next*/"\n (function (FUNCTION_KEY) {\n function FUNCTION_ID() {\n return FUNCTION_KEY.apply(this, arguments);\n }\n\n FUNCTION_ID.toString = function () {\n return FUNCTION_KEY.toString();\n }\n\n return FUNCTION_ID;\n })(FUNCTION)\n"); /* eslint max-len: 0 */ + +var buildGeneratorPropertyMethodAssignmentWrapper = /*istanbul ignore next*/(0, _babelTemplate2.default)( /*istanbul ignore next*/"\n (function (FUNCTION_KEY) {\n function* FUNCTION_ID() {\n return yield* FUNCTION_KEY.apply(this, arguments);\n }\n\n FUNCTION_ID.toString = function () {\n return FUNCTION_KEY.toString();\n };\n\n return FUNCTION_ID;\n })(FUNCTION)\n"); + +var visitor = { /*istanbul ignore next*/ + "ReferencedIdentifier|BindingIdentifier": function ReferencedIdentifierBindingIdentifier(path, state) { + // check if this node matches our function id + if (path.node.name !== state.name) return; + + // check that we don't have a local variable declared as that removes the need + // for the wrapper + var localDeclar = path.scope.getBindingIdentifier(state.name); + if (localDeclar !== state.outerDeclar) return; + + state.selfReference = true; + path.stop(); + } +}; + +function wrap(state, method, id, scope) { + if (state.selfReference) { + if (scope.hasBinding(id.name) && !scope.hasGlobal(id.name)) { + // we can just munge the local binding + scope.rename(id.name); + } else { + // we don't currently support wrapping class expressions + if (!t.isFunction(method)) return; + + // need to add a wrapper since we can't change the references + var build = buildPropertyMethodAssignmentWrapper; + if (method.generator) build = buildGeneratorPropertyMethodAssignmentWrapper; + var _template = build({ + FUNCTION: method, + FUNCTION_ID: id, + FUNCTION_KEY: scope.generateUidIdentifier(id.name) + }).expression; + _template.callee._skipModulesRemap = true; + + // shim in dummy params to retain function arity, if you try to read the + // source then you'll get the original since it's proxied so it's all good + var params = _template.callee.body.body[0].params; + for (var i = 0, len = /*istanbul ignore next*/(0, _babelHelperGetFunctionArity2.default)(method); i < len; i++) { + params.push(scope.generateUidIdentifier("x")); + } + + return _template; + } + } + + method.id = id; + scope.getProgramParent().references[id.name] = true; +} + +function visit(node, name, scope) { + var state = { + selfAssignment: false, + selfReference: false, + outerDeclar: scope.getBindingIdentifier(name), + references: [], + name: name + }; + + // check to see if we have a local binding of the id we're setting inside of + // the function, this is important as there are caveats associated + + var binding = scope.getOwnBinding(name); + + if (binding) { + if (binding.kind === "param") { + // safari will blow up in strict mode with code like: + // + // let t = function t(t) {}; + // + // with the error: + // + // Cannot declare a parameter named 't' as it shadows the name of a + // strict mode function. + // + // this isn't to the spec and they've invented this behaviour which is + // **extremely** annoying so we avoid setting the name if it has a param + // with the same id + state.selfReference = true; + } else { + // otherwise it's defined somewhere in scope like: + // + // let t = function () { + // let t = 2; + // }; + // + // so we can safely just set the id and move along as it shadows the + // bound function id + } + } else if (state.outerDeclar || scope.hasGlobal(name)) { + scope.traverse(node, visitor, state); + } + + return state; +} + +/*istanbul ignore next*/module.exports = exports["default"]; +},{"babel-helper-get-function-arity":67,"babel-template":156,"babel-types":193}],67:[function(require,module,exports){ +/*istanbul ignore next*/"use strict"; + +exports.__esModule = true; + +exports.default = function (node) { + var params = node.params; + for (var i = 0; i < params.length; i++) { + var param = params[i]; + if (t.isAssignmentPattern(param) || t.isRestElement(param)) { + return i; + } + } + return params.length; +}; + +var /*istanbul ignore next*/_babelTypes = require("babel-types"); + +/*istanbul ignore next*/ +var t = _interopRequireWildcard(_babelTypes); + +/*istanbul ignore next*/ +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +module.exports = exports["default"]; +},{"babel-types":193}],68:[function(require,module,exports){ +/*istanbul ignore next*/"use strict"; + +exports.__esModule = true; + +var _getIterator2 = require("babel-runtime/core-js/get-iterator"); + +var _getIterator3 = _interopRequireDefault(_getIterator2); + +exports.default = function (path, emit) { + /*istanbul ignore next*/var kind = arguments.length <= 2 || arguments[2] === undefined ? "var" : arguments[2]; + + path.traverse(visitor, { kind: kind, emit: emit }); +}; + +var /*istanbul ignore next*/_babelTypes = require("babel-types"); + +/*istanbul ignore next*/ +var t = _interopRequireWildcard(_babelTypes); + +/*istanbul ignore next*/ +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var visitor = { /*istanbul ignore next*/ + Scope: function Scope(path, state) { + if (state.kind === "let") path.skip(); + }, + /*istanbul ignore next*/Function: function Function(path) { + path.skip(); + }, + /*istanbul ignore next*/VariableDeclaration: function VariableDeclaration(path, state) { + if (state.kind && path.node.kind !== state.kind) return; + + var nodes = []; + + var declarations = path.get("declarations"); + var firstId = /*istanbul ignore next*/void 0; + + for ( /*istanbul ignore next*/var _iterator = declarations, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { + /*istanbul ignore next*/ + var _ref; + + if (_isArray) { + if (_i >= _iterator.length) break; + _ref = _iterator[_i++]; + } else { + _i = _iterator.next(); + if (_i.done) break; + _ref = _i.value; + } + + var declar = _ref; + + firstId = declar.node.id; + + if (declar.node.init) { + nodes.push(t.expressionStatement(t.assignmentExpression("=", declar.node.id, declar.node.init))); + } + + for (var name in declar.getBindingIdentifiers()) { + state.emit(t.identifier(name), name); + } + } + + // for (var i in test) + if (path.parentPath.isFor({ left: path.node })) { + path.replaceWith(firstId); + } else { + path.replaceWithMultiple(nodes); + } + } +}; + +/*istanbul ignore next*/module.exports = exports["default"]; +},{"babel-runtime/core-js/get-iterator":138,"babel-types":193}],69:[function(require,module,exports){ +/*istanbul ignore next*/"use strict"; + +exports.__esModule = true; + +exports.default = function (callee, thisNode, args) { + if (args.length === 1 && t.isSpreadElement(args[0]) && t.isIdentifier(args[0].argument, { name: "arguments" })) { + // eg. super(...arguments); + return t.callExpression(t.memberExpression(callee, t.identifier("apply")), [thisNode, args[0].argument]); + } else { + return t.callExpression(t.memberExpression(callee, t.identifier("call")), /*istanbul ignore next*/[thisNode].concat(args)); + } +}; + +var /*istanbul ignore next*/_babelTypes = require("babel-types"); + +/*istanbul ignore next*/ +var t = _interopRequireWildcard(_babelTypes); + +/*istanbul ignore next*/ +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +/* eslint max-len: 0 */ + +module.exports = exports["default"]; +},{"babel-types":193}],70:[function(require,module,exports){ +/*istanbul ignore next*/"use strict"; + +exports.__esModule = true; +exports.is = is; +/*istanbul ignore next*/exports.pullFlag = pullFlag; + +var /*istanbul ignore next*/_pull = require("lodash/pull"); + +/*istanbul ignore next*/ +var _pull2 = _interopRequireDefault(_pull); + +var /*istanbul ignore next*/_babelTypes = require("babel-types"); + +/*istanbul ignore next*/ +var t = _interopRequireWildcard(_babelTypes); + +/*istanbul ignore next*/ +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function is(node, flag) { + return t.isRegExpLiteral(node) && node.flags.indexOf(flag) >= 0; +} + +function pullFlag(node, flag) { + var flags = node.flags.split(""); + if (node.flags.indexOf(flag) < 0) return; + /*istanbul ignore next*/(0, _pull2.default)(flags, flag); + node.flags = flags.join(""); +} +},{"babel-types":193,"lodash/pull":571}],71:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +exports.default = function (path, helpers) { + var node = path.node; + var scope = path.scope; + var parent = path.parent; + + + var stepKey = scope.generateUidIdentifier("step"); + var stepValue = scope.generateUidIdentifier("value"); + var left = node.left; + var declar = void 0; + + if (t.isIdentifier(left) || t.isPattern(left) || t.isMemberExpression(left)) { + declar = t.expressionStatement(t.assignmentExpression("=", left, stepValue)); + } else if (t.isVariableDeclaration(left)) { + declar = t.variableDeclaration(left.kind, [t.variableDeclarator(left.declarations[0].id, stepValue)]); + } + + var template = buildForAwait(); + + (0, _babelTraverse2.default)(template, forAwaitVisitor, null, { + ITERATOR_HAD_ERROR_KEY: scope.generateUidIdentifier("didIteratorError"), + ITERATOR_COMPLETION: scope.generateUidIdentifier("iteratorNormalCompletion"), + ITERATOR_ERROR_KEY: scope.generateUidIdentifier("iteratorError"), + ITERATOR_KEY: scope.generateUidIdentifier("iterator"), + GET_ITERATOR: helpers.getAsyncIterator, + OBJECT: node.right, + STEP_VALUE: stepValue, + STEP_KEY: stepKey, + AWAIT: helpers.wrapAwait + }); + + template = template.body.body; + + var isLabeledParent = t.isLabeledStatement(parent); + var tryBody = template[3].block.body; + var loop = tryBody[0]; + + if (isLabeledParent) { + tryBody[0] = t.labeledStatement(parent.label, loop); + } + + return { + replaceParent: isLabeledParent, + node: template, + declar: declar, + loop: loop + }; +}; + +var _babelTypes = require("babel-types"); + +var t = _interopRequireWildcard(_babelTypes); + +var _babelTemplate = require("babel-template"); + +var _babelTemplate2 = _interopRequireDefault(_babelTemplate); + +var _babelTraverse = require("babel-traverse"); + +var _babelTraverse2 = _interopRequireDefault(_babelTraverse); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +var buildForAwait = (0, _babelTemplate2.default)("\n function* wrapper() {\n var ITERATOR_COMPLETION = true;\n var ITERATOR_HAD_ERROR_KEY = false;\n var ITERATOR_ERROR_KEY = undefined;\n try {\n for (\n var ITERATOR_KEY = GET_ITERATOR(OBJECT), STEP_KEY, STEP_VALUE;\n (\n STEP_KEY = yield AWAIT(ITERATOR_KEY.next()),\n ITERATOR_COMPLETION = STEP_KEY.done,\n STEP_VALUE = yield AWAIT(STEP_KEY.value),\n !ITERATOR_COMPLETION\n );\n ITERATOR_COMPLETION = true) {\n }\n } catch (err) {\n ITERATOR_HAD_ERROR_KEY = true;\n ITERATOR_ERROR_KEY = err;\n } finally {\n try {\n if (!ITERATOR_COMPLETION && ITERATOR_KEY.return) {\n yield AWAIT(ITERATOR_KEY.return());\n }\n } finally {\n if (ITERATOR_HAD_ERROR_KEY) {\n throw ITERATOR_ERROR_KEY;\n }\n }\n }\n }\n"); + +var forAwaitVisitor = { + noScope: true, + + Identifier: function Identifier(path, replacements) { + if (path.node.name in replacements) { + path.replaceInline(replacements[path.node.name]); + } + }, + CallExpression: function CallExpression(path, replacements) { + var callee = path.node.callee; + + if (t.isIdentifier(callee) && callee.name === "AWAIT" && !replacements.AWAIT) { + path.replaceWith(path.node.arguments[0]); + } + } +}; + +module.exports = exports["default"]; +},{"babel-template":156,"babel-traverse":160,"babel-types":193}],72:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +exports.default = function (path, file, helpers) { + if (!helpers) { + helpers = { wrapAsync: file }; + file = null; + } + path.traverse(awaitVisitor, { + file: file, + wrapAwait: helpers.wrapAwait + }); + + if (path.isClassMethod() || path.isObjectMethod()) { + classOrObjectMethod(path, helpers.wrapAsync); + } else { + plainFunction(path, helpers.wrapAsync); + } +}; + +var _babelHelperFunctionName = require("babel-helper-function-name"); + +var _babelHelperFunctionName2 = _interopRequireDefault(_babelHelperFunctionName); + +var _babelTemplate = require("babel-template"); + +var _babelTemplate2 = _interopRequireDefault(_babelTemplate); + +var _babelTypes = require("babel-types"); + +var t = _interopRequireWildcard(_babelTypes); + +var _forAwait = require("./for-await"); + +var _forAwait2 = _interopRequireDefault(_forAwait); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var buildWrapper = (0, _babelTemplate2.default)("\n (() => {\n var REF = FUNCTION;\n return function NAME(PARAMS) {\n return REF.apply(this, arguments);\n };\n })\n"); + +var namedBuildWrapper = (0, _babelTemplate2.default)("\n (() => {\n var REF = FUNCTION;\n function NAME(PARAMS) {\n return REF.apply(this, arguments);\n }\n return NAME;\n })\n"); + +var awaitVisitor = { + Function: function Function(path) { + if (path.isArrowFunctionExpression() && !path.node.async) { + path.arrowFunctionToShadowed(); + return; + } + path.skip(); + }, + AwaitExpression: function AwaitExpression(_ref, _ref2) { + var node = _ref.node; + var wrapAwait = _ref2.wrapAwait; + + node.type = "YieldExpression"; + if (wrapAwait) { + node.argument = t.callExpression(wrapAwait, [node.argument]); + } + }, + ForAwaitStatement: function ForAwaitStatement(path, _ref3) { + var file = _ref3.file; + var wrapAwait = _ref3.wrapAwait; + var node = path.node; + + + var build = (0, _forAwait2.default)(path, { + getAsyncIterator: file.addHelper("asyncIterator"), + wrapAwait: wrapAwait + }); + + var declar = build.declar; + var loop = build.loop; + + var block = loop.body; + + path.ensureBlock(); + + if (declar) { + block.body.push(declar); + } + + block.body = block.body.concat(node.body.body); + + t.inherits(loop, node); + t.inherits(loop.body, node.body); + + if (build.replaceParent) { + path.parentPath.replaceWithMultiple(build.node); + path.remove(); + } else { + path.replaceWithMultiple(build.node); + } + } +}; + +function classOrObjectMethod(path, callId) { + var node = path.node; + var body = node.body; + + node.async = false; + + var container = t.functionExpression(null, [], t.blockStatement(body.body), true); + container.shadow = true; + body.body = [t.returnStatement(t.callExpression(t.callExpression(callId, [container]), []))]; +} + +function plainFunction(path, callId) { + var node = path.node; + var isDeclaration = path.isFunctionDeclaration(); + var asyncFnId = node.id; + var wrapper = buildWrapper; + + if (path.isArrowFunctionExpression()) { + path.arrowFunctionToShadowed(); + } else if (!isDeclaration && asyncFnId) { + wrapper = namedBuildWrapper; + } + + node.async = false; + node.generator = true; + + node.id = null; + + if (isDeclaration) { + node.type = "FunctionExpression"; + } + + var built = t.callExpression(callId, [node]); + var container = wrapper({ + NAME: asyncFnId, + REF: path.scope.generateUidIdentifier("ref"), + FUNCTION: built, + PARAMS: node.params.map(function () { + return path.scope.generateUidIdentifier("x"); + }) + }).expression; + + if (isDeclaration) { + var declar = t.variableDeclaration("let", [t.variableDeclarator(t.identifier(asyncFnId.name), t.callExpression(container, []))]); + declar._blockHoist = true; + + path.replaceWith(declar); + } else { + var retFunction = container.body.body[1].argument; + if (!asyncFnId) { + (0, _babelHelperFunctionName2.default)({ + node: retFunction, + parent: path.parent, + scope: path.scope + }); + } + + if (!retFunction || retFunction.id || node.params.length) { + path.replaceWith(t.callExpression(container, [])); + } else { + path.replaceWith(built); + } + } +} + +module.exports = exports["default"]; +},{"./for-await":71,"babel-helper-function-name":66,"babel-template":156,"babel-types":193}],73:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck"); + +var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); + +var _symbol = require("babel-runtime/core-js/symbol"); + +var _symbol2 = _interopRequireDefault(_symbol); + +var _babelHelperOptimiseCallExpression = require("babel-helper-optimise-call-expression"); + +var _babelHelperOptimiseCallExpression2 = _interopRequireDefault(_babelHelperOptimiseCallExpression); + +var _babelMessages = require("babel-messages"); + +var messages = _interopRequireWildcard(_babelMessages); + +var _babelTypes = require("babel-types"); + +var t = _interopRequireWildcard(_babelTypes); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var HARDCORE_THIS_REF = (0, _symbol2.default)(); + +function isIllegalBareSuper(node, parent) { + if (!t.isSuper(node)) return false; + if (t.isMemberExpression(parent, { computed: false })) return false; + if (t.isCallExpression(parent, { callee: node })) return false; + return true; +} + +function isMemberExpressionSuper(node) { + return t.isMemberExpression(node) && t.isSuper(node.object); +} + +function getPrototypeOfExpression(objectRef, isStatic) { + var targetRef = isStatic ? objectRef : t.memberExpression(objectRef, t.identifier("prototype")); + + return t.logicalExpression("||", t.memberExpression(targetRef, t.identifier("__proto__")), t.callExpression(t.memberExpression(t.identifier("Object"), t.identifier("getPrototypeOf")), [targetRef])); +} + +var visitor = { + Function: function Function(path) { + if (!path.inShadow("this")) { + path.skip(); + } + }, + ReturnStatement: function ReturnStatement(path, state) { + if (!path.inShadow("this")) { + state.returns.push(path); + } + }, + ThisExpression: function ThisExpression(path, state) { + if (!path.node[HARDCORE_THIS_REF]) { + state.thises.push(path); + } + }, + enter: function enter(path, state) { + var callback = state.specHandle; + if (state.isLoose) callback = state.looseHandle; + + var isBareSuper = path.isCallExpression() && path.get("callee").isSuper(); + + var result = callback.call(state, path); + + if (result) { + state.hasSuper = true; + } + + if (isBareSuper) { + state.bareSupers.push(path); + } + + if (result === true) { + path.requeue(); + } + + if (result !== true && result) { + if (Array.isArray(result)) { + path.replaceWithMultiple(result); + } else { + path.replaceWith(result); + } + } + } +}; + +var ReplaceSupers = function () { + function ReplaceSupers(opts) { + var inClass = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1]; + (0, _classCallCheck3.default)(this, ReplaceSupers); + + this.forceSuperMemoisation = opts.forceSuperMemoisation; + this.methodPath = opts.methodPath; + this.methodNode = opts.methodNode; + this.superRef = opts.superRef; + this.isStatic = opts.isStatic; + this.hasSuper = false; + this.inClass = inClass; + this.isLoose = opts.isLoose; + this.scope = this.methodPath.scope; + this.file = opts.file; + this.opts = opts; + + this.bareSupers = []; + this.returns = []; + this.thises = []; + } + + ReplaceSupers.prototype.getObjectRef = function getObjectRef() { + return this.opts.objectRef || this.opts.getObjectRef(); + }; + + ReplaceSupers.prototype.setSuperProperty = function setSuperProperty(property, value, isComputed) { + return t.callExpression(this.file.addHelper("set"), [getPrototypeOfExpression(this.getObjectRef(), this.isStatic), isComputed ? property : t.stringLiteral(property.name), value, t.thisExpression()]); + }; + + ReplaceSupers.prototype.getSuperProperty = function getSuperProperty(property, isComputed) { + return t.callExpression(this.file.addHelper("get"), [getPrototypeOfExpression(this.getObjectRef(), this.isStatic), isComputed ? property : t.stringLiteral(property.name), t.thisExpression()]); + }; + + ReplaceSupers.prototype.replace = function replace() { + this.methodPath.traverse(visitor, this); + }; + + ReplaceSupers.prototype.getLooseSuperProperty = function getLooseSuperProperty(id, parent) { + var methodNode = this.methodNode; + var superRef = this.superRef || t.identifier("Function"); + + if (parent.property === id) { + return; + } else if (t.isCallExpression(parent, { callee: id })) { + return; + } else if (t.isMemberExpression(parent) && !methodNode.static) { + return t.memberExpression(superRef, t.identifier("prototype")); + } else { + return superRef; + } + }; + + ReplaceSupers.prototype.looseHandle = function looseHandle(path) { + var node = path.node; + if (path.isSuper()) { + return this.getLooseSuperProperty(node, path.parent); + } else if (path.isCallExpression()) { + var callee = node.callee; + if (!t.isMemberExpression(callee)) return; + if (!t.isSuper(callee.object)) return; + + t.appendToMemberExpression(callee, t.identifier("call")); + node.arguments.unshift(t.thisExpression()); + return true; + } + }; + + ReplaceSupers.prototype.specHandleAssignmentExpression = function specHandleAssignmentExpression(ref, path, node) { + if (node.operator === "=") { + return this.setSuperProperty(node.left.property, node.right, node.left.computed); + } else { + ref = ref || path.scope.generateUidIdentifier("ref"); + return [t.variableDeclaration("var", [t.variableDeclarator(ref, node.left)]), t.expressionStatement(t.assignmentExpression("=", node.left, t.binaryExpression(node.operator[0], ref, node.right)))]; + } + }; + + ReplaceSupers.prototype.specHandle = function specHandle(path) { + var property = void 0; + var computed = void 0; + var args = void 0; + + var parent = path.parent; + var node = path.node; + + if (isIllegalBareSuper(node, parent)) { + throw path.buildCodeFrameError(messages.get("classesIllegalBareSuper")); + } + + if (t.isCallExpression(node)) { + var callee = node.callee; + if (t.isSuper(callee)) { + return; + } else if (isMemberExpressionSuper(callee)) { + property = callee.property; + computed = callee.computed; + args = node.arguments; + } + } else if (t.isMemberExpression(node) && t.isSuper(node.object)) { + property = node.property; + computed = node.computed; + } else if (t.isUpdateExpression(node) && isMemberExpressionSuper(node.argument)) { + var binary = t.binaryExpression(node.operator[0], node.argument, t.numericLiteral(1)); + if (node.prefix) { + return this.specHandleAssignmentExpression(null, path, binary); + } else { + var ref = path.scope.generateUidIdentifier("ref"); + return this.specHandleAssignmentExpression(ref, path, binary).concat(t.expressionStatement(ref)); + } + } else if (t.isAssignmentExpression(node) && isMemberExpressionSuper(node.left)) { + return this.specHandleAssignmentExpression(null, path, node); + } + + if (!property) return; + + var superProperty = this.getSuperProperty(property, computed); + + if (args) { + return this.optimiseCall(superProperty, args); + } else { + return superProperty; + } + }; + + ReplaceSupers.prototype.optimiseCall = function optimiseCall(callee, args) { + var thisNode = t.thisExpression(); + thisNode[HARDCORE_THIS_REF] = true; + return (0, _babelHelperOptimiseCallExpression2.default)(callee, thisNode, args); + }; + + return ReplaceSupers; +}(); + +exports.default = ReplaceSupers; +module.exports = exports["default"]; +},{"babel-helper-optimise-call-expression":69,"babel-messages":76,"babel-runtime/core-js/symbol":147,"babel-runtime/helpers/classCallCheck":152,"babel-types":193}],74:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +var _babelTemplate = require("babel-template"); + +var _babelTemplate2 = _interopRequireDefault(_babelTemplate); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var helpers = {}; +exports.default = helpers; + + +helpers.typeof = (0, _babelTemplate2.default)("\n (typeof Symbol === \"function\" && typeof Symbol.iterator === \"symbol\")\n ? function (obj) { return typeof obj; }\n : function (obj) {\n return obj && typeof Symbol === \"function\" && obj.constructor === Symbol && obj !== Symbol.prototype\n ? \"symbol\"\n : typeof obj;\n };\n"); + +helpers.jsx = (0, _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.asyncIterator = (0, _babelTemplate2.default)("\n (function (iterable) {\n if (typeof Symbol === \"function\") {\n if (Symbol.asyncIterator) {\n var method = iterable[Symbol.asyncIterator];\n if (method != null) return method.call(iterable);\n }\n if (Symbol.iterator) {\n return iterable[Symbol.iterator]();\n }\n }\n throw new TypeError(\"Object is not async iterable\");\n })\n"); + +helpers.asyncGenerator = (0, _babelTemplate2.default)("\n (function () {\n function AwaitValue(value) {\n this.value = value;\n }\n\n function AsyncGenerator(gen) {\n var front, back;\n\n function send(key, arg) {\n return new Promise(function (resolve, reject) {\n var request = {\n key: key,\n arg: arg,\n resolve: resolve,\n reject: reject,\n next: null\n };\n\n if (back) {\n back = back.next = request;\n } else {\n front = back = request;\n resume(key, arg);\n }\n });\n }\n\n function resume(key, arg) {\n try {\n var result = gen[key](arg)\n var value = result.value;\n if (value instanceof AwaitValue) {\n Promise.resolve(value.value).then(\n function (arg) { resume(\"next\", arg); },\n function (arg) { resume(\"throw\", arg); });\n } else {\n settle(result.done ? \"return\" : \"normal\", result.value);\n }\n } catch (err) {\n settle(\"throw\", err);\n }\n }\n\n function settle(type, value) {\n switch (type) {\n case \"return\":\n front.resolve({ value: value, done: true });\n break;\n case \"throw\":\n front.reject(value);\n break;\n default:\n front.resolve({ value: value, done: false });\n break;\n }\n\n front = front.next;\n if (front) {\n resume(front.key, front.arg);\n } else {\n back = null;\n }\n }\n\n this._invoke = send;\n\n // Hide \"return\" method if generator return is not supported\n if (typeof gen.return !== \"function\") {\n this.return = undefined;\n }\n }\n\n if (typeof Symbol === \"function\" && Symbol.asyncIterator) {\n AsyncGenerator.prototype[Symbol.asyncIterator] = function () { return this; };\n }\n\n AsyncGenerator.prototype.next = function (arg) { return this._invoke(\"next\", arg); };\n AsyncGenerator.prototype.throw = function (arg) { return this._invoke(\"throw\", arg); };\n AsyncGenerator.prototype.return = function (arg) { return this._invoke(\"return\", arg); };\n\n return {\n wrap: function (fn) {\n return function () {\n return new AsyncGenerator(fn.apply(this, arguments));\n };\n },\n await: function (value) {\n return new AwaitValue(value);\n }\n };\n\n })()\n"); + +helpers.asyncGeneratorDelegate = (0, _babelTemplate2.default)("\n (function (inner, awaitWrap) {\n var iter = {}, waiting = false;\n\n function pump(key, value) {\n waiting = true;\n value = new Promise(function (resolve) { resolve(inner[key](value)); });\n return { done: false, value: awaitWrap(value) };\n };\n\n if (typeof Symbol === \"function\" && Symbol.iterator) {\n iter[Symbol.iterator] = function () { return this; };\n }\n\n iter.next = function (value) {\n if (waiting) {\n waiting = false;\n return value;\n }\n return pump(\"next\", value);\n };\n\n if (typeof inner.throw === \"function\") {\n iter.throw = function (value) {\n if (waiting) {\n waiting = false;\n throw value;\n }\n return pump(\"throw\", value);\n };\n }\n\n if (typeof inner.return === \"function\") {\n iter.return = function (value) {\n return pump(\"return\", value);\n };\n }\n\n return iter;\n })\n"); + +helpers.asyncToGenerator = (0, _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 step(\"next\", value);\n }, function (err) {\n step(\"throw\", err);\n });\n }\n }\n\n return step(\"next\");\n });\n };\n })\n"); + +helpers.classCallCheck = (0, _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 = (0, _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 = (0, _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 = (0, _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 = (0, _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 = (0, _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 = (0, _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 = (0, _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 = (0, _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 = (0, _babelTemplate2.default)("\n (function (obj) {\n return obj && obj.__esModule ? obj : { default: obj };\n })\n"); + +helpers.interopRequireWildcard = (0, _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 = (0, _babelTemplate2.default)("\n (function (innerThis, boundThis) {\n if (innerThis !== boundThis) {\n throw new TypeError(\"Cannot instantiate an arrow function\");\n }\n });\n"); + +helpers.objectDestructuringEmpty = (0, _babelTemplate2.default)("\n (function (obj) {\n if (obj == null) throw new TypeError(\"Cannot destructure undefined\");\n });\n"); + +helpers.objectWithoutProperties = (0, _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 = (0, _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 = (0, _babelTemplate2.default)("\n typeof global === \"undefined\" ? self : global\n"); + +helpers.set = (0, _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 = (0, _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 = (0, _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 = (0, _babelTemplate2.default)("\n (function (strings, raw) {\n return Object.freeze(Object.defineProperties(strings, {\n raw: { value: Object.freeze(raw) }\n }));\n });\n"); + +helpers.taggedTemplateLiteralLoose = (0, _babelTemplate2.default)("\n (function (strings, raw) {\n strings.raw = raw;\n return strings;\n });\n"); + +helpers.temporalRef = (0, _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 = (0, _babelTemplate2.default)("\n ({})\n"); + +helpers.toArray = (0, _babelTemplate2.default)("\n (function (arr) {\n return Array.isArray(arr) ? arr : Array.from(arr);\n });\n"); + +helpers.toConsumableArray = (0, _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"]; +},{"babel-template":156}],75:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; +exports.list = undefined; + +var _keys = require("babel-runtime/core-js/object/keys"); + +var _keys2 = _interopRequireDefault(_keys); + +exports.get = get; + +var _helpers = require("./helpers"); + +var _helpers2 = _interopRequireDefault(_helpers); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function get(name) { + var fn = _helpers2.default[name]; + if (!fn) throw new ReferenceError("Unknown helper " + name); + + return fn().expression; +} + +var list = exports.list = (0, _keys2.default)(_helpers2.default).map(function (name) { + return name[0] === "_" ? name.slice(1) : name; +}).filter(function (name) { + return name !== "__esModule"; +}); + +exports.default = get; +},{"./helpers":74,"babel-runtime/core-js/object/keys":145}],76:[function(require,module,exports){ +/*istanbul ignore next*/"use strict"; + +exports.__esModule = true; +exports.MESSAGES = undefined; + +var _stringify = require("babel-runtime/core-js/json/stringify"); + +var _stringify2 = _interopRequireDefault(_stringify); + +exports.get = get; +/*istanbul ignore next*/exports.parseArgs = parseArgs; + +var /*istanbul ignore next*/_util = require("util"); + +/*istanbul ignore next*/ +var util = _interopRequireWildcard(_util); + +/*istanbul ignore next*/ +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Mapping of messages to be used in Babel. + * Messages can include $0-style placeholders. + */ + +var MESSAGES = /*istanbul ignore next*/exports.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" +}; + +/** + * Get a message with $0 placeholders replaced by arguments. + */ + +/* eslint max-len: 0 */ + +function get(key) { + /*istanbul ignore next*/ + 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( /*istanbul ignore next*/"Unknown message " + /*istanbul ignore next*/(0, _stringify2.default)(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 (/*istanbul ignore next*/(0, _stringify2.default)(val) || val + "" + ); + } catch (e) { + return util.inspect(val); + } + } + }); +} +},{"babel-runtime/core-js/json/stringify":139,"util":691}],77:[function(require,module,exports){ +/*istanbul ignore next*/"use strict"; + +exports.__esModule = true; + +var _getIterator2 = require("babel-runtime/core-js/get-iterator"); + +var _getIterator3 = _interopRequireDefault(_getIterator2); + +exports.default = function ( /*istanbul ignore next*/_ref) { + /*istanbul ignore next*/var messages = _ref.messages; + + return { + visitor: { /*istanbul ignore next*/ + Scope: function Scope(_ref2) { + /*istanbul ignore next*/var scope = _ref2.scope; + + for (var name in scope.bindings) { + var binding = scope.bindings[name]; + if (binding.kind !== "const" && binding.kind !== "module") continue; + + for ( /*istanbul ignore next*/var _iterator = binding.constantViolations, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { + /*istanbul ignore next*/ + var _ref3; + + if (_isArray) { + if (_i >= _iterator.length) break; + _ref3 = _iterator[_i++]; + } else { + _i = _iterator.next(); + if (_i.done) break; + _ref3 = _i.value; + } + + var violation = _ref3; + + throw violation.buildCodeFrameError(messages.get("readOnly", name)); + } + } + } + } + }; +}; + +/*istanbul ignore next*/ +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +module.exports = exports["default"]; +},{"babel-runtime/core-js/get-iterator":138}],78:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +exports.default = function () { + return { + manipulateOptions: function manipulateOptions(opts, parserOpts) { + parserOpts.plugins.push("asyncFunctions"); + } + }; +}; + +module.exports = exports["default"]; +},{}],79:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +exports.default = function () { + return { + manipulateOptions: function manipulateOptions(opts, parserOpts) { + parserOpts.plugins.push("classConstructorCall"); + } + }; +}; + +module.exports = exports["default"]; +},{}],80:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +exports.default = function () { + return { + manipulateOptions: function manipulateOptions(opts, parserOpts) { + parserOpts.plugins.push("classProperties"); + } + }; +}; + +module.exports = exports["default"]; +},{}],81:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +exports.default = function () { + return { + manipulateOptions: function manipulateOptions(opts, parserOpts) { + parserOpts.plugins.push("decorators"); + } + }; +}; + +module.exports = exports["default"]; +},{}],82:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +exports.default = function () { + return { + manipulateOptions: function manipulateOptions(opts, parserOpts) { + parserOpts.plugins.push("doExpressions"); + } + }; +}; + +module.exports = exports["default"]; +},{}],83:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +exports.default = function () { + return { + manipulateOptions: function manipulateOptions(opts, parserOpts) { + parserOpts.plugins.push("exponentiationOperator"); + } + }; +}; + +module.exports = exports["default"]; +},{}],84:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +exports.default = function () { + return { + manipulateOptions: function manipulateOptions(opts, parserOpts) { + parserOpts.plugins.push("exportExtensions"); + } + }; +}; + +module.exports = exports["default"]; +},{}],85:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +exports.default = function () { + return { + manipulateOptions: function manipulateOptions(opts, parserOpts) { + parserOpts.plugins.push("functionBind"); + } + }; +}; + +module.exports = exports["default"]; +},{}],86:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +exports.default = function () { + return { + manipulateOptions: function manipulateOptions(opts, parserOpts) { + parserOpts.plugins.push("objectRestSpread"); + } + }; +}; + +module.exports = exports["default"]; +},{}],87:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +exports.default = function () { + return { + manipulateOptions: function manipulateOptions(opts, parserOpts) { + parserOpts.plugins.push("trailingFunctionCommas"); + } + }; +}; + +module.exports = exports["default"]; +},{}],88:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +exports.default = function () { + return { + inherits: require("babel-plugin-syntax-async-functions"), + + visitor: { + Function: function Function(path, state) { + if (!path.node.async || path.node.generator) return; + + (0, _babelHelperRemapAsyncToGenerator2.default)(path, state.file, { + wrapAsync: state.addHelper("asyncToGenerator") + }); + } + } + }; +}; + +var _babelHelperRemapAsyncToGenerator = require("babel-helper-remap-async-to-generator"); + +var _babelHelperRemapAsyncToGenerator2 = _interopRequireDefault(_babelHelperRemapAsyncToGenerator); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +module.exports = exports["default"]; +},{"babel-helper-remap-async-to-generator":72,"babel-plugin-syntax-async-functions":78}],89:[function(require,module,exports){ +/*istanbul ignore next*/"use strict"; + +exports.__esModule = true; + +var _getIterator2 = require("babel-runtime/core-js/get-iterator"); + +var _getIterator3 = _interopRequireDefault(_getIterator2); + +var _symbol = require("babel-runtime/core-js/symbol"); + +var _symbol2 = _interopRequireDefault(_symbol); + +exports.default = function ( /*istanbul ignore next*/_ref) { + /*istanbul ignore next*/var t = _ref.types; + + var ALREADY_VISITED = /*istanbul ignore next*/(0, _symbol2.default)(); + + function findConstructorCall(path) { + var methods = path.get("body.body"); + + for ( /*istanbul ignore next*/var _iterator = methods, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { + /*istanbul ignore next*/ + var _ref2; + + if (_isArray) { + if (_i >= _iterator.length) break; + _ref2 = _iterator[_i++]; + } else { + _i = _iterator.next(); + if (_i.done) break; + _ref2 = _i.value; + } + + var method = _ref2; + + if (method.node.kind === "constructorCall") { + return method; + } + } + + return null; + } + + function handleClassWithCall(constructorCall, classPath) { + /*istanbul ignore next*/var _classPath = classPath; + /*istanbul ignore next*/var node = _classPath.node; + + var ref = node.id || classPath.scope.generateUidIdentifier("class"); + + if (classPath.parentPath.isExportDefaultDeclaration()) { + classPath = classPath.parentPath; + classPath.insertAfter(t.exportDefaultDeclaration(ref)); + } + + classPath.replaceWithMultiple(buildWrapper({ + CLASS_REF: classPath.scope.generateUidIdentifier(ref.name), + CALL_REF: classPath.scope.generateUidIdentifier( /*istanbul ignore next*/ref.name + "Call"), + CALL: t.functionExpression(null, constructorCall.node.params, constructorCall.node.body), + CLASS: t.toExpression(node), + WRAPPER_REF: ref + })); + + constructorCall.remove(); + } + + return { + inherits: require("babel-plugin-syntax-class-constructor-call"), + + visitor: { /*istanbul ignore next*/ + Class: function Class(path) { + if (path.node[ALREADY_VISITED]) return; + path.node[ALREADY_VISITED] = true; + + var constructorCall = findConstructorCall(path); + + if (constructorCall) { + handleClassWithCall(constructorCall, path); + } else { + return; + } + } + } + }; +}; + +var /*istanbul ignore next*/_babelTemplate = require("babel-template"); + +/*istanbul ignore next*/ +var _babelTemplate2 = _interopRequireDefault(_babelTemplate); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var buildWrapper = /*istanbul ignore next*/(0, _babelTemplate2.default)( /*istanbul ignore next*/"\n let CLASS_REF = CLASS;\n var CALL_REF = CALL;\n var WRAPPER_REF = function (...args) {\n if (this instanceof WRAPPER_REF) {\n return Reflect.construct(CLASS_REF, args);\n } else {\n return CALL_REF.apply(this, args);\n }\n };\n WRAPPER_REF.__proto__ = CLASS_REF;\n WRAPPER_REF;\n"); + +/*istanbul ignore next*/module.exports = exports["default"]; +},{"babel-plugin-syntax-class-constructor-call":79,"babel-runtime/core-js/get-iterator":138,"babel-runtime/core-js/symbol":147,"babel-template":156}],90:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +var _getIterator2 = require("babel-runtime/core-js/get-iterator"); + +var _getIterator3 = _interopRequireDefault(_getIterator2); + +exports.default = function (_ref) { + var t = _ref.types; + + var findBareSupers = { + Super: function Super(path) { + if (path.parentPath.isCallExpression({ callee: path.node })) { + this.push(path.parentPath); + } + } + }; + + var referenceVisitor = { + ReferencedIdentifier: function ReferencedIdentifier(path) { + if (this.scope.hasOwnBinding(path.node.name)) { + this.collision = true; + path.skip(); + } + } + }; + + return { + inherits: require("babel-plugin-syntax-class-properties"), + + visitor: { + Class: function Class(path) { + var isDerived = !!path.node.superClass; + var constructor = void 0; + var props = []; + var body = path.get("body"); + + for (var _iterator = body.get("body"), _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { + var _ref2; + + if (_isArray) { + if (_i >= _iterator.length) break; + _ref2 = _iterator[_i++]; + } else { + _i = _iterator.next(); + if (_i.done) break; + _ref2 = _i.value; + } + + var _path = _ref2; + + if (_path.isClassProperty()) { + props.push(_path); + } else if (_path.isClassMethod({ kind: "constructor" })) { + constructor = _path; + } + } + + if (!props.length) return; + + var nodes = []; + var ref = void 0; + + if (path.isClassExpression() || !path.node.id) { + (0, _babelHelperFunctionName2.default)(path); + ref = path.scope.generateUidIdentifier("class"); + } else { + ref = path.node.id; + } + + var instanceBody = []; + + for (var _iterator2 = props, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : (0, _getIterator3.default)(_iterator2);;) { + var _ref3; + + if (_isArray2) { + if (_i2 >= _iterator2.length) break; + _ref3 = _iterator2[_i2++]; + } else { + _i2 = _iterator2.next(); + if (_i2.done) break; + _ref3 = _i2.value; + } + + var _prop = _ref3; + + var propNode = _prop.node; + if (propNode.decorators && propNode.decorators.length > 0) continue; + if (!propNode.value) continue; + + var isStatic = propNode.static; + var isComputed = propNode.computed || t.isLiteral(_prop.key); + + if (isStatic) { + nodes.push(t.expressionStatement(t.assignmentExpression("=", t.memberExpression(ref, propNode.key, isComputed), propNode.value))); + } else { + instanceBody.push(t.expressionStatement(t.assignmentExpression("=", t.memberExpression(t.thisExpression(), propNode.key, isComputed), propNode.value))); + } + } + + if (instanceBody.length) { + if (!constructor) { + var newConstructor = t.classMethod("constructor", t.identifier("constructor"), [], t.blockStatement([])); + if (isDerived) { + newConstructor.params = [t.restElement(t.identifier("args"))]; + newConstructor.body.body.push(t.returnStatement(t.callExpression(t.super(), [t.spreadElement(t.identifier("args"))]))); + } + + var _body$unshiftContaine = body.unshiftContainer("body", newConstructor); + + constructor = _body$unshiftContaine[0]; + } + + var collisionState = { + collision: false, + scope: constructor.scope + }; + + for (var _iterator3 = props, _isArray3 = Array.isArray(_iterator3), _i3 = 0, _iterator3 = _isArray3 ? _iterator3 : (0, _getIterator3.default)(_iterator3);;) { + var _ref4; + + if (_isArray3) { + if (_i3 >= _iterator3.length) break; + _ref4 = _iterator3[_i3++]; + } else { + _i3 = _iterator3.next(); + if (_i3.done) break; + _ref4 = _i3.value; + } + + var prop = _ref4; + + prop.traverse(referenceVisitor, collisionState); + if (collisionState.collision) break; + } + + if (collisionState.collision) { + var initialisePropsRef = path.scope.generateUidIdentifier("initialiseProps"); + + nodes.push(t.variableDeclaration("var", [t.variableDeclarator(initialisePropsRef, t.functionExpression(null, [], t.blockStatement(instanceBody)))])); + + instanceBody = [t.expressionStatement(t.callExpression(t.memberExpression(initialisePropsRef, t.identifier("call")), [t.thisExpression()]))]; + } + + if (isDerived) { + var bareSupers = []; + constructor.traverse(findBareSupers, bareSupers); + for (var _iterator4 = bareSupers, _isArray4 = Array.isArray(_iterator4), _i4 = 0, _iterator4 = _isArray4 ? _iterator4 : (0, _getIterator3.default)(_iterator4);;) { + var _ref5; + + if (_isArray4) { + if (_i4 >= _iterator4.length) break; + _ref5 = _iterator4[_i4++]; + } else { + _i4 = _iterator4.next(); + if (_i4.done) break; + _ref5 = _i4.value; + } + + var bareSuper = _ref5; + + bareSuper.insertAfter(instanceBody); + } + } else { + constructor.get("body").unshiftContainer("body", instanceBody); + } + } + + for (var _iterator5 = props, _isArray5 = Array.isArray(_iterator5), _i5 = 0, _iterator5 = _isArray5 ? _iterator5 : (0, _getIterator3.default)(_iterator5);;) { + var _ref6; + + if (_isArray5) { + if (_i5 >= _iterator5.length) break; + _ref6 = _iterator5[_i5++]; + } else { + _i5 = _iterator5.next(); + if (_i5.done) break; + _ref6 = _i5.value; + } + + var _prop2 = _ref6; + + _prop2.remove(); + } + + if (!nodes.length) return; + + if (path.isClassExpression()) { + path.scope.push({ id: ref }); + path.replaceWith(t.assignmentExpression("=", ref, path.node)); + } else { + if (!path.node.id) { + path.node.id = ref; + } + + if (path.parentPath.isExportDeclaration()) { + path = path.parentPath; + } + } + + path.insertAfter(nodes); + }, + ArrowFunctionExpression: function ArrowFunctionExpression(path) { + var classExp = path.get("body"); + if (!classExp.isClassExpression()) return; + + var body = classExp.get("body"); + var members = body.get("body"); + if (members.some(function (member) { + return member.isClassProperty(); + })) { + path.ensureBlock(); + } + } + } + }; +}; + +var _babelHelperFunctionName = require("babel-helper-function-name"); + +var _babelHelperFunctionName2 = _interopRequireDefault(_babelHelperFunctionName); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +module.exports = exports["default"]; +},{"babel-helper-function-name":66,"babel-plugin-syntax-class-properties":80,"babel-runtime/core-js/get-iterator":138}],91:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +var _create = require("babel-runtime/core-js/object/create"); + +var _create2 = _interopRequireDefault(_create); + +var _getIterator2 = require("babel-runtime/core-js/get-iterator"); + +var _getIterator3 = _interopRequireDefault(_getIterator2); + +exports.default = function (_ref) { + var t = _ref.types; + + function cleanDecorators(decorators) { + return decorators.reverse().map(function (dec) { + return dec.expression; + }); + } + + function transformClass(path, ref, state) { + var nodes = []; + + state; + + var classDecorators = path.node.decorators; + if (classDecorators) { + path.node.decorators = null; + classDecorators = cleanDecorators(classDecorators); + + for (var _iterator = classDecorators, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { + var _ref2; + + if (_isArray) { + if (_i >= _iterator.length) break; + _ref2 = _iterator[_i++]; + } else { + _i = _iterator.next(); + if (_i.done) break; + _ref2 = _i.value; + } + + var decorator = _ref2; + + nodes.push(buildClassDecorator({ + CLASS_REF: ref, + DECORATOR: decorator + })); + } + } + + var map = (0, _create2.default)(null); + + for (var _iterator2 = path.get("body.body"), _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : (0, _getIterator3.default)(_iterator2);;) { + var _ref3; + + if (_isArray2) { + if (_i2 >= _iterator2.length) break; + _ref3 = _iterator2[_i2++]; + } else { + _i2 = _iterator2.next(); + if (_i2.done) break; + _ref3 = _i2.value; + } + + var method = _ref3; + + var decorators = method.node.decorators; + if (!decorators) continue; + + var _alias = t.toKeyAlias(method.node); + map[_alias] = map[_alias] || []; + map[_alias].push(method.node); + + method.remove(); + } + + for (var alias in map) { + var items = map[alias]; + + items; + } + + return nodes; + } + + function hasDecorators(path) { + if (path.isClass()) { + if (path.node.decorators) return true; + + for (var _iterator3 = path.node.body.body, _isArray3 = Array.isArray(_iterator3), _i3 = 0, _iterator3 = _isArray3 ? _iterator3 : (0, _getIterator3.default)(_iterator3);;) { + var _ref4; + + if (_isArray3) { + if (_i3 >= _iterator3.length) break; + _ref4 = _iterator3[_i3++]; + } else { + _i3 = _iterator3.next(); + if (_i3.done) break; + _ref4 = _i3.value; + } + + var method = _ref4; + + if (method.decorators) { + return true; + } + } + } else if (path.isObjectExpression()) { + for (var _iterator4 = path.node.properties, _isArray4 = Array.isArray(_iterator4), _i4 = 0, _iterator4 = _isArray4 ? _iterator4 : (0, _getIterator3.default)(_iterator4);;) { + var _ref5; + + if (_isArray4) { + if (_i4 >= _iterator4.length) break; + _ref5 = _iterator4[_i4++]; + } else { + _i4 = _iterator4.next(); + if (_i4.done) break; + _ref5 = _i4.value; + } + + var prop = _ref5; + + if (prop.decorators) { + return true; + } + } + } + + return false; + } + + function doError(path) { + throw path.buildCodeFrameError("Decorators are not officially supported yet in 6.x pending a proposal update.\nHowever, if you need to use them you can install the legacy decorators transform with:\n\nnpm install babel-plugin-transform-decorators-legacy --save-dev\n\nand add the following line to your .babelrc file:\n\n{\n \"plugins\": [\"transform-decorators-legacy\"]\n}\n\nThe repo url is: https://github.com/loganfsmyth/babel-plugin-transform-decorators-legacy.\n "); + } + + return { + inherits: require("babel-plugin-syntax-decorators"), + + visitor: { + ClassExpression: function ClassExpression(path) { + if (!hasDecorators(path)) return; + doError(path); + + (0, _babelHelperExplodeClass2.default)(path); + + var ref = path.scope.generateDeclaredUidIdentifier("ref"); + var nodes = []; + + nodes.push(t.assignmentExpression("=", ref, path.node)); + + nodes = nodes.concat(transformClass(path, ref, this)); + + nodes.push(ref); + + path.replaceWith(t.sequenceExpression(nodes)); + }, + ClassDeclaration: function ClassDeclaration(path) { + if (!hasDecorators(path)) return; + doError(path); + (0, _babelHelperExplodeClass2.default)(path); + + var ref = path.node.id; + var nodes = []; + + nodes = nodes.concat(transformClass(path, ref, this).map(function (expr) { + return t.expressionStatement(expr); + })); + nodes.push(t.expressionStatement(ref)); + + path.insertAfter(nodes); + }, + ObjectExpression: function ObjectExpression(path) { + if (!hasDecorators(path)) return; + doError(path); + } + } + }; +}; + +var _babelTemplate = require("babel-template"); + +var _babelTemplate2 = _interopRequireDefault(_babelTemplate); + +var _babelHelperExplodeClass = require("babel-helper-explode-class"); + +var _babelHelperExplodeClass2 = _interopRequireDefault(_babelHelperExplodeClass); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var buildClassDecorator = (0, _babelTemplate2.default)("\n CLASS_REF = DECORATOR(CLASS_REF) || CLASS_REF;\n"); + +module.exports = exports["default"]; +},{"babel-helper-explode-class":65,"babel-plugin-syntax-decorators":81,"babel-runtime/core-js/get-iterator":138,"babel-runtime/core-js/object/create":143,"babel-template":156}],92:[function(require,module,exports){ +/*istanbul ignore next*/"use strict"; + +exports.__esModule = true; + +exports.default = function () { + return { + inherits: require("babel-plugin-syntax-do-expressions"), + + visitor: { /*istanbul ignore next*/ + DoExpression: function DoExpression(path) { + var body = path.node.body.body; + if (body.length) { + path.replaceWithMultiple(body); + } else { + path.replaceWith(path.scope.buildUndefinedNode()); + } + } + } + }; +}; + +/*istanbul ignore next*/module.exports = exports["default"]; +},{"babel-plugin-syntax-do-expressions":82}],93:[function(require,module,exports){ +/*istanbul ignore next*/"use strict"; + +exports.__esModule = true; + +exports.default = function ( /*istanbul ignore next*/_ref) { + /*istanbul ignore next*/var t = _ref.types; + + return { + visitor: { /*istanbul ignore next*/ + ArrowFunctionExpression: function ArrowFunctionExpression(path, state) { + if (state.opts.spec) { + /*istanbul ignore next*/var node = path.node; + + if (node.shadow) return; + + node.shadow = { this: false }; + node.type = "FunctionExpression"; + + var boundThis = t.thisExpression(); + boundThis._forceShadow = path; + + // make sure that arrow function won't be instantiated + path.ensureBlock(); + path.get("body").unshiftContainer("body", t.expressionStatement(t.callExpression(state.addHelper("newArrowCheck"), [t.thisExpression(), boundThis]))); + + path.replaceWith(t.callExpression(t.memberExpression(node, t.identifier("bind")), [t.thisExpression()])); + } else { + path.arrowFunctionToShadowed(); + } + } + } + }; +}; + +/*istanbul ignore next*/module.exports = exports["default"]; +},{}],94:[function(require,module,exports){ +/*istanbul ignore next*/"use strict"; + +exports.__esModule = true; + +var _getIterator2 = require("babel-runtime/core-js/get-iterator"); + +var _getIterator3 = _interopRequireDefault(_getIterator2); + +exports.default = function ( /*istanbul ignore next*/_ref) { + /*istanbul ignore next*/var t = _ref.types; + + function statementList(key, path) { + var paths = path.get(key); + + for ( /*istanbul ignore next*/var _iterator = paths, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { + /*istanbul ignore next*/ + var _ref2; + + if (_isArray) { + if (_i >= _iterator.length) break; + _ref2 = _iterator[_i++]; + } else { + _i = _iterator.next(); + if (_i.done) break; + _ref2 = _i.value; + } + + var _path = _ref2; + + var func = _path.node; + if (!_path.isFunctionDeclaration()) continue; + + var declar = t.variableDeclaration("let", [t.variableDeclarator(func.id, t.toExpression(func))]); + + // hoist it up above everything else + declar._blockHoist = 2; + + // todo: name this + func.id = null; + + _path.replaceWith(declar); + } + } + + return { + visitor: { /*istanbul ignore next*/ + BlockStatement: function BlockStatement(path) { + /*istanbul ignore next*/var node = path.node; + /*istanbul ignore next*/var parent = path.parent; + + if (t.isFunction(parent, { body: node }) || t.isExportDeclaration(parent)) { + return; + } + + statementList("body", path); + }, + /*istanbul ignore next*/SwitchCase: function SwitchCase(path) { + statementList("consequent", path); + } + } + }; +}; + +/*istanbul ignore next*/ +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +module.exports = exports["default"]; +},{"babel-runtime/core-js/get-iterator":138}],95:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +var _symbol = require("babel-runtime/core-js/symbol"); + +var _symbol2 = _interopRequireDefault(_symbol); + +var _create = require("babel-runtime/core-js/object/create"); + +var _create2 = _interopRequireDefault(_create); + +var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck"); + +var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); + +exports.default = function () { + return { + visitor: { + VariableDeclaration: function VariableDeclaration(path, file) { + var node = path.node; + var parent = path.parent; + var scope = path.scope; + + if (!isBlockScoped(node)) return; + convertBlockScopedToVar(path, null, parent, scope, true); + + if (node._tdzThis) { + var nodes = [node]; + + for (var i = 0; i < node.declarations.length; i++) { + var decl = node.declarations[i]; + if (decl.init) { + var assign = t.assignmentExpression("=", decl.id, decl.init); + assign._ignoreBlockScopingTDZ = true; + nodes.push(t.expressionStatement(assign)); + } + decl.init = file.addHelper("temporalUndefined"); + } + + node._blockHoist = 2; + + if (path.isCompletionRecord()) { + nodes.push(t.expressionStatement(scope.buildUndefinedNode())); + } + + path.replaceWithMultiple(nodes); + } + }, + Loop: function Loop(path, file) { + var node = path.node; + var parent = path.parent; + var scope = path.scope; + + t.ensureBlock(node); + var blockScoping = new BlockScoping(path, path.get("body"), parent, scope, file); + var replace = blockScoping.run(); + if (replace) path.replaceWith(replace); + }, + CatchClause: function CatchClause(path, file) { + var parent = path.parent; + var scope = path.scope; + + var blockScoping = new BlockScoping(null, path.get("body"), parent, scope, file); + blockScoping.run(); + }, + "BlockStatement|SwitchStatement|Program": function BlockStatementSwitchStatementProgram(path, file) { + if (!ignoreBlock(path)) { + var blockScoping = new BlockScoping(null, path, path.parent, path.scope, file); + blockScoping.run(); + } + } + } + }; +}; + +var _babelTraverse = require("babel-traverse"); + +var _babelTraverse2 = _interopRequireDefault(_babelTraverse); + +var _tdz = require("./tdz"); + +var _babelTypes = require("babel-types"); + +var t = _interopRequireWildcard(_babelTypes); + +var _values = require("lodash/values"); + +var _values2 = _interopRequireDefault(_values); + +var _extend = require("lodash/extend"); + +var _extend2 = _interopRequireDefault(_extend); + +var _babelTemplate = require("babel-template"); + +var _babelTemplate2 = _interopRequireDefault(_babelTemplate); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function ignoreBlock(path) { + return t.isLoop(path.parent) || t.isCatchClause(path.parent); +} + +var buildRetCheck = (0, _babelTemplate2.default)("\n if (typeof RETURN === \"object\") return RETURN.v;\n"); + +function isBlockScoped(node) { + if (!t.isVariableDeclaration(node)) return false; + if (node[t.BLOCK_SCOPED_SYMBOL]) return true; + if (node.kind !== "let" && node.kind !== "const") return false; + return true; +} + +function convertBlockScopedToVar(path, node, parent, scope) { + var moveBindingsToParent = arguments.length <= 4 || arguments[4] === undefined ? false : arguments[4]; + + if (!node) { + node = path.node; + } + + if (!t.isFor(parent)) { + for (var i = 0; i < node.declarations.length; i++) { + var declar = node.declarations[i]; + declar.init = declar.init || scope.buildUndefinedNode(); + } + } + + node[t.BLOCK_SCOPED_SYMBOL] = true; + node.kind = "var"; + + if (moveBindingsToParent) { + var parentScope = scope.getFunctionParent(); + var ids = path.getBindingIdentifiers(); + for (var name in ids) { + var binding = scope.getOwnBinding(name); + if (binding) binding.kind = "var"; + scope.moveBindingTo(name, parentScope); + } + } +} + +function isVar(node) { + return t.isVariableDeclaration(node, { kind: "var" }) && !isBlockScoped(node); +} + +var letReferenceBlockVisitor = _babelTraverse2.default.visitors.merge([{ + Function: function Function(path, state) { + path.traverse(letReferenceFunctionVisitor, state); + return path.skip(); + } +}, _tdz.visitor]); + +var letReferenceFunctionVisitor = _babelTraverse2.default.visitors.merge([{ + ReferencedIdentifier: function ReferencedIdentifier(path, state) { + var ref = state.letReferences[path.node.name]; + + if (!ref) return; + + var localBinding = path.scope.getBindingIdentifier(path.node.name); + if (localBinding && localBinding !== ref) return; + + state.closurify = true; + } +}, _tdz.visitor]); + +var hoistVarDeclarationsVisitor = { + enter: function enter(path, self) { + var node = path.node; + var parent = path.parent; + + + if (path.isForStatement()) { + if (isVar(node.init, node)) { + var nodes = self.pushDeclar(node.init); + if (nodes.length === 1) { + node.init = nodes[0]; + } else { + node.init = t.sequenceExpression(nodes); + } + } + } else if (path.isFor()) { + if (isVar(node.left, node)) { + self.pushDeclar(node.left); + node.left = node.left.declarations[0].id; + } + } else if (isVar(node, parent)) { + path.replaceWithMultiple(self.pushDeclar(node).map(function (expr) { + return t.expressionStatement(expr); + })); + } else if (path.isFunction()) { + return path.skip(); + } + } +}; + +var loopLabelVisitor = { + LabeledStatement: function LabeledStatement(_ref, state) { + var node = _ref.node; + + state.innerLabels.push(node.label.name); + } +}; + +var continuationVisitor = { + enter: function enter(path, state) { + if (path.isAssignmentExpression() || path.isUpdateExpression()) { + var bindings = path.getBindingIdentifiers(); + for (var name in bindings) { + if (state.outsideReferences[name] !== path.scope.getBindingIdentifier(name)) continue; + state.reassignments[name] = true; + } + } + } +}; + +function loopNodeTo(node) { + if (t.isBreakStatement(node)) { + return "break"; + } else if (t.isContinueStatement(node)) { + return "continue"; + } +} + +var loopVisitor = { + Loop: function Loop(path, state) { + var oldIgnoreLabeless = state.ignoreLabeless; + state.ignoreLabeless = true; + path.traverse(loopVisitor, state); + state.ignoreLabeless = oldIgnoreLabeless; + path.skip(); + }, + Function: function Function(path) { + path.skip(); + }, + SwitchCase: function SwitchCase(path, state) { + var oldInSwitchCase = state.inSwitchCase; + state.inSwitchCase = true; + path.traverse(loopVisitor, state); + state.inSwitchCase = oldInSwitchCase; + path.skip(); + }, + "BreakStatement|ContinueStatement|ReturnStatement": function BreakStatementContinueStatementReturnStatement(path, state) { + var node = path.node; + var parent = path.parent; + var scope = path.scope; + + if (node[this.LOOP_IGNORE]) return; + + var replace = void 0; + var loopText = loopNodeTo(node); + + if (loopText) { + if (node.label) { + if (state.innerLabels.indexOf(node.label.name) >= 0) { + return; + } + + loopText = loopText + "|" + node.label.name; + } else { + if (state.ignoreLabeless) return; + + if (state.inSwitchCase) return; + + if (t.isBreakStatement(node) && t.isSwitchCase(parent)) return; + } + + state.hasBreakContinue = true; + state.map[loopText] = node; + replace = t.stringLiteral(loopText); + } + + if (path.isReturnStatement()) { + state.hasReturn = true; + replace = t.objectExpression([t.objectProperty(t.identifier("v"), node.argument || scope.buildUndefinedNode())]); + } + + if (replace) { + replace = t.returnStatement(replace); + replace[this.LOOP_IGNORE] = true; + path.skip(); + path.replaceWith(t.inherits(replace, node)); + } + } +}; + +var BlockScoping = function () { + function BlockScoping(loopPath, blockPath, parent, scope, file) { + (0, _classCallCheck3.default)(this, BlockScoping); + + this.parent = parent; + this.scope = scope; + this.file = file; + + this.blockPath = blockPath; + this.block = blockPath.node; + + this.outsideLetReferences = (0, _create2.default)(null); + this.hasLetReferences = false; + this.letReferences = (0, _create2.default)(null); + this.body = []; + + if (loopPath) { + this.loopParent = loopPath.parent; + this.loopLabel = t.isLabeledStatement(this.loopParent) && this.loopParent.label; + this.loopPath = loopPath; + this.loop = loopPath.node; + } + } + + BlockScoping.prototype.run = function run() { + var block = this.block; + if (block._letDone) return; + block._letDone = true; + + var needsClosure = this.getLetReferences(); + + if (t.isFunction(this.parent) || t.isProgram(this.block)) { + this.updateScopeInfo(); + return; + } + + if (!this.hasLetReferences) return; + + if (needsClosure) { + this.wrapClosure(); + } else { + this.remap(); + } + + this.updateScopeInfo(); + + if (this.loopLabel && !t.isLabeledStatement(this.loopParent)) { + return t.labeledStatement(this.loopLabel, this.loop); + } + }; + + BlockScoping.prototype.updateScopeInfo = function updateScopeInfo() { + var scope = this.scope; + var parentScope = scope.getFunctionParent(); + var letRefs = this.letReferences; + + for (var key in letRefs) { + var ref = letRefs[key]; + var binding = scope.getBinding(ref.name); + if (!binding) continue; + if (binding.kind === "let" || binding.kind === "const") { + binding.kind = "var"; + scope.moveBindingTo(ref.name, parentScope); + } + } + }; + + BlockScoping.prototype.remap = function remap() { + var letRefs = this.letReferences; + var scope = this.scope; + + for (var key in letRefs) { + var ref = letRefs[key]; + + if (scope.parentHasBinding(key) || scope.hasGlobal(key)) { + if (scope.hasOwnBinding(key)) scope.rename(ref.name); + + if (this.blockPath.scope.hasOwnBinding(key)) this.blockPath.scope.rename(ref.name); + } + } + }; + + BlockScoping.prototype.wrapClosure = function wrapClosure() { + var block = this.block; + + var outsideRefs = this.outsideLetReferences; + + if (this.loop) { + for (var name in outsideRefs) { + var id = outsideRefs[name]; + + if (this.scope.hasGlobal(id.name) || this.scope.parentHasBinding(id.name)) { + delete outsideRefs[id.name]; + delete this.letReferences[id.name]; + + this.scope.rename(id.name); + + this.letReferences[id.name] = id; + outsideRefs[id.name] = id; + } + } + } + + this.has = this.checkLoop(); + + this.hoistVarDeclarations(); + + var params = (0, _values2.default)(outsideRefs); + var args = (0, _values2.default)(outsideRefs); + + var isSwitch = this.blockPath.isSwitchStatement(); + + var fn = t.functionExpression(null, params, t.blockStatement(isSwitch ? [block] : block.body)); + fn.shadow = true; + + this.addContinuations(fn); + + var ref = fn; + + if (this.loop) { + ref = this.scope.generateUidIdentifier("loop"); + this.loopPath.insertBefore(t.variableDeclaration("var", [t.variableDeclarator(ref, fn)])); + } + + var call = t.callExpression(ref, args); + var ret = this.scope.generateUidIdentifier("ret"); + + var hasYield = _babelTraverse2.default.hasType(fn.body, this.scope, "YieldExpression", t.FUNCTION_TYPES); + if (hasYield) { + fn.generator = true; + call = t.yieldExpression(call, true); + } + + var hasAsync = _babelTraverse2.default.hasType(fn.body, this.scope, "AwaitExpression", t.FUNCTION_TYPES); + if (hasAsync) { + fn.async = true; + call = t.awaitExpression(call); + } + + this.buildClosure(ret, call); + + if (isSwitch) this.blockPath.replaceWithMultiple(this.body);else block.body = this.body; + }; + + BlockScoping.prototype.buildClosure = function buildClosure(ret, call) { + var has = this.has; + if (has.hasReturn || has.hasBreakContinue) { + this.buildHas(ret, call); + } else { + this.body.push(t.expressionStatement(call)); + } + }; + + BlockScoping.prototype.addContinuations = function addContinuations(fn) { + var state = { + reassignments: {}, + outsideReferences: this.outsideLetReferences + }; + + this.scope.traverse(fn, continuationVisitor, state); + + for (var i = 0; i < fn.params.length; i++) { + var param = fn.params[i]; + if (!state.reassignments[param.name]) continue; + + var newParam = this.scope.generateUidIdentifier(param.name); + fn.params[i] = newParam; + + this.scope.rename(param.name, newParam.name, fn); + + fn.body.body.push(t.expressionStatement(t.assignmentExpression("=", param, newParam))); + } + }; + + BlockScoping.prototype.getLetReferences = function getLetReferences() { + var block = this.block; + + var declarators = []; + + if (this.loop) { + var init = this.loop.left || this.loop.init; + if (isBlockScoped(init)) { + declarators.push(init); + (0, _extend2.default)(this.outsideLetReferences, t.getBindingIdentifiers(init)); + } + } + + if (block.body) { + for (var i = 0; i < block.body.length; i++) { + var declar = block.body[i]; + if (t.isClassDeclaration(declar) || t.isFunctionDeclaration(declar) || isBlockScoped(declar)) { + var declarPath = this.blockPath.get("body")[i]; + if (isBlockScoped(declar)) { + convertBlockScopedToVar(declarPath, null, block, this.scope); + } + declarators = declarators.concat(declar.declarations || declar); + } + } + } + + if (block.cases) { + for (var _i = 0; _i < block.cases.length; _i++) { + var consequents = block.cases[_i].consequent; + + for (var j = 0; j < consequents.length; j++) { + var _declar = consequents[j]; + if (t.isClassDeclaration(_declar) || t.isFunctionDeclaration(_declar) || isBlockScoped(_declar)) { + var _declarPath = this.blockPath.get("cases")[_i]; + if (isBlockScoped(_declar)) { + convertBlockScopedToVar(_declarPath, _declar, block, this.scope); + } + declarators = declarators.concat(_declar.declarations || _declar); + } + } + } + } + + for (var _i2 = 0; _i2 < declarators.length; _i2++) { + var _declar2 = declarators[_i2]; + var keys = t.getBindingIdentifiers(_declar2); + (0, _extend2.default)(this.letReferences, keys); + this.hasLetReferences = true; + } + + if (!this.hasLetReferences) return; + + var state = { + letReferences: this.letReferences, + closurify: false, + file: this.file + }; + + this.blockPath.traverse(letReferenceBlockVisitor, state); + + return state.closurify; + }; + + BlockScoping.prototype.checkLoop = function checkLoop() { + var state = { + hasBreakContinue: false, + ignoreLabeless: false, + inSwitchCase: false, + innerLabels: [], + hasReturn: false, + isLoop: !!this.loop, + map: {}, + LOOP_IGNORE: (0, _symbol2.default)() + }; + + this.blockPath.traverse(loopLabelVisitor, state); + this.blockPath.traverse(loopVisitor, state); + + return state; + }; + + BlockScoping.prototype.hoistVarDeclarations = function hoistVarDeclarations() { + this.blockPath.traverse(hoistVarDeclarationsVisitor, this); + }; + + BlockScoping.prototype.pushDeclar = function pushDeclar(node) { + var declars = []; + var names = t.getBindingIdentifiers(node); + for (var name in names) { + declars.push(t.variableDeclarator(names[name])); + } + + this.body.push(t.variableDeclaration(node.kind, declars)); + + var replace = []; + + for (var i = 0; i < node.declarations.length; i++) { + var declar = node.declarations[i]; + if (!declar.init) continue; + + var expr = t.assignmentExpression("=", declar.id, declar.init); + replace.push(t.inherits(expr, declar)); + } + + return replace; + }; + + BlockScoping.prototype.buildHas = function buildHas(ret, call) { + var body = this.body; + + body.push(t.variableDeclaration("var", [t.variableDeclarator(ret, call)])); + + var retCheck = void 0; + var has = this.has; + var cases = []; + + if (has.hasReturn) { + retCheck = buildRetCheck({ + RETURN: ret + }); + } + + if (has.hasBreakContinue) { + for (var key in has.map) { + cases.push(t.switchCase(t.stringLiteral(key), [has.map[key]])); + } + + if (has.hasReturn) { + cases.push(t.switchCase(null, [retCheck])); + } + + if (cases.length === 1) { + var single = cases[0]; + body.push(t.ifStatement(t.binaryExpression("===", ret, single.test), single.consequent[0])); + } else { + if (this.loop) { + for (var i = 0; i < cases.length; i++) { + var caseConsequent = cases[i].consequent[0]; + if (t.isBreakStatement(caseConsequent) && !caseConsequent.label) { + caseConsequent.label = this.loopLabel = this.loopLabel || this.scope.generateUidIdentifier("loop"); + } + } + } + + body.push(t.switchStatement(ret, cases)); + } + } else { + if (has.hasReturn) { + body.push(retCheck); + } + } + }; + + return BlockScoping; +}(); + +module.exports = exports["default"]; +},{"./tdz":96,"babel-runtime/core-js/object/create":143,"babel-runtime/core-js/symbol":147,"babel-runtime/helpers/classCallCheck":152,"babel-template":156,"babel-traverse":160,"babel-types":193,"lodash/extend":536,"lodash/values":585}],96:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; +exports.visitor = undefined; + +var _babelTypes = require("babel-types"); + +var t = _interopRequireWildcard(_babelTypes); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function getTDZStatus(refPath, bindingPath) { + var executionStatus = bindingPath._guessExecutionStatusRelativeTo(refPath); + + if (executionStatus === "before") { + return "inside"; + } else if (executionStatus === "after") { + return "outside"; + } else { + return "maybe"; + } +} + +function buildTDZAssert(node, file) { + return t.callExpression(file.addHelper("temporalRef"), [node, t.stringLiteral(node.name), file.addHelper("temporalUndefined")]); +} + +function isReference(node, scope, state) { + var declared = state.letReferences[node.name]; + if (!declared) return false; + + return scope.getBindingIdentifier(node.name) === declared; +} + +var visitor = exports.visitor = { + ReferencedIdentifier: function ReferencedIdentifier(path, state) { + if (!this.file.opts.tdz) return; + + var node = path.node; + var parent = path.parent; + var scope = path.scope; + + + if (path.parentPath.isFor({ left: node })) return; + if (!isReference(node, scope, state)) return; + + var bindingPath = scope.getBinding(node.name).path; + + var status = getTDZStatus(path, bindingPath); + if (status === "inside") return; + + if (status === "maybe") { + var assert = buildTDZAssert(node, state.file); + + bindingPath.parent._tdzThis = true; + + path.skip(); + + if (path.parentPath.isUpdateExpression()) { + if (parent._ignoreBlockScopingTDZ) return; + path.parentPath.replaceWith(t.sequenceExpression([assert, parent])); + } else { + path.replaceWith(assert); + } + } else if (status === "outside") { + path.replaceWith(t.throwStatement(t.inherits(t.newExpression(t.identifier("ReferenceError"), [t.stringLiteral(node.name + " is not defined - temporal dead zone")]), node))); + } + }, + + + AssignmentExpression: { + exit: function exit(path, state) { + if (!this.file.opts.tdz) return; + + var node = path.node; + + if (node._ignoreBlockScopingTDZ) return; + + var nodes = []; + var ids = path.getBindingIdentifiers(); + + for (var name in ids) { + var id = ids[name]; + + if (isReference(id, path.scope, state)) { + nodes.push(buildTDZAssert(id, state.file)); + } + } + + if (nodes.length) { + node._ignoreBlockScopingTDZ = true; + nodes.push(node); + path.replaceWithMultiple(nodes.map(t.expressionStatement)); + } + } + } +}; +},{"babel-types":193}],97:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +var _symbol = require("babel-runtime/core-js/symbol"); + +var _symbol2 = _interopRequireDefault(_symbol); + +exports.default = function (_ref) { + var t = _ref.types; + + var VISITED = (0, _symbol2.default)(); + + return { + visitor: { + ExportDefaultDeclaration: function ExportDefaultDeclaration(path) { + if (!path.get("declaration").isClassDeclaration()) return; + + var node = path.node; + + var ref = node.declaration.id || path.scope.generateUidIdentifier("class"); + node.declaration.id = ref; + + path.replaceWith(node.declaration); + path.insertAfter(t.exportDefaultDeclaration(ref)); + }, + ClassDeclaration: function ClassDeclaration(path) { + var node = path.node; + + + var ref = node.id || path.scope.generateUidIdentifier("class"); + + path.replaceWith(t.variableDeclaration("let", [t.variableDeclarator(ref, t.toExpression(node))])); + }, + ClassExpression: function ClassExpression(path, state) { + var node = path.node; + + if (node[VISITED]) return; + + var inferred = (0, _babelHelperFunctionName2.default)(path); + if (inferred && inferred !== node) return path.replaceWith(inferred); + + node[VISITED] = true; + + var Constructor = _vanilla2.default; + if (state.opts.loose) Constructor = _loose2.default; + + path.replaceWith(new Constructor(path, state.file).run()); + } + } + }; +}; + +var _loose = require("./loose"); + +var _loose2 = _interopRequireDefault(_loose); + +var _vanilla = require("./vanilla"); + +var _vanilla2 = _interopRequireDefault(_vanilla); + +var _babelHelperFunctionName = require("babel-helper-function-name"); + +var _babelHelperFunctionName2 = _interopRequireDefault(_babelHelperFunctionName); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +module.exports = exports["default"]; +},{"./loose":98,"./vanilla":99,"babel-helper-function-name":66,"babel-runtime/core-js/symbol":147}],98:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck"); + +var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); + +var _possibleConstructorReturn2 = require("babel-runtime/helpers/possibleConstructorReturn"); + +var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); + +var _inherits2 = require("babel-runtime/helpers/inherits"); + +var _inherits3 = _interopRequireDefault(_inherits2); + +var _babelHelperFunctionName = require("babel-helper-function-name"); + +var _babelHelperFunctionName2 = _interopRequireDefault(_babelHelperFunctionName); + +var _vanilla = require("./vanilla"); + +var _vanilla2 = _interopRequireDefault(_vanilla); + +var _babelTypes = require("babel-types"); + +var t = _interopRequireWildcard(_babelTypes); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var LooseClassTransformer = function (_VanillaTransformer) { + (0, _inherits3.default)(LooseClassTransformer, _VanillaTransformer); + + function LooseClassTransformer() { + (0, _classCallCheck3.default)(this, LooseClassTransformer); + + var _this = (0, _possibleConstructorReturn3.default)(this, _VanillaTransformer.apply(this, arguments)); + + _this.isLoose = true; + return _this; + } + + LooseClassTransformer.prototype._processMethod = function _processMethod(node, scope) { + if (!node.decorators) { + + var classRef = this.classRef; + if (!node.static) classRef = t.memberExpression(classRef, t.identifier("prototype")); + var methodName = t.memberExpression(classRef, node.key, node.computed || t.isLiteral(node.key)); + + var func = t.functionExpression(null, node.params, node.body, node.generator, node.async); + var key = t.toComputedKey(node, node.key); + if (t.isStringLiteral(key)) { + func = (0, _babelHelperFunctionName2.default)({ + node: func, + id: key, + scope: scope + }); + } + + var expr = t.expressionStatement(t.assignmentExpression("=", methodName, func)); + t.inheritsComments(expr, node); + this.body.push(expr); + return true; + } + }; + + return LooseClassTransformer; +}(_vanilla2.default); + +exports.default = LooseClassTransformer; +module.exports = exports["default"]; +},{"./vanilla":99,"babel-helper-function-name":66,"babel-runtime/helpers/classCallCheck":152,"babel-runtime/helpers/inherits":153,"babel-runtime/helpers/possibleConstructorReturn":154,"babel-types":193}],99:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +var _getIterator2 = require("babel-runtime/core-js/get-iterator"); + +var _getIterator3 = _interopRequireDefault(_getIterator2); + +var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck"); + +var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); + +var _babelTraverse = require("babel-traverse"); + +var _babelHelperReplaceSupers = require("babel-helper-replace-supers"); + +var _babelHelperReplaceSupers2 = _interopRequireDefault(_babelHelperReplaceSupers); + +var _babelHelperOptimiseCallExpression = require("babel-helper-optimise-call-expression"); + +var _babelHelperOptimiseCallExpression2 = _interopRequireDefault(_babelHelperOptimiseCallExpression); + +var _babelHelperDefineMap = require("babel-helper-define-map"); + +var defineMap = _interopRequireWildcard(_babelHelperDefineMap); + +var _babelTemplate = require("babel-template"); + +var _babelTemplate2 = _interopRequireDefault(_babelTemplate); + +var _babelTypes = require("babel-types"); + +var t = _interopRequireWildcard(_babelTypes); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var buildDerivedConstructor = (0, _babelTemplate2.default)("\n (function () {\n super(...arguments);\n })\n"); + +var noMethodVisitor = { + "FunctionExpression|FunctionDeclaration": function FunctionExpressionFunctionDeclaration(path) { + if (!path.is("shadow")) { + path.skip(); + } + }, + Method: function Method(path) { + path.skip(); + } +}; + +var verifyConstructorVisitor = _babelTraverse.visitors.merge([noMethodVisitor, { + Super: function Super(path) { + if (this.isDerived && !this.hasBareSuper && !path.parentPath.isCallExpression({ callee: path.node })) { + throw path.buildCodeFrameError("'super.*' is not allowed before super()"); + } + }, + + + CallExpression: { + exit: function exit(path) { + if (path.get("callee").isSuper()) { + this.hasBareSuper = true; + + if (!this.isDerived) { + throw path.buildCodeFrameError("super() is only allowed in a derived constructor"); + } + } + } + }, + + ThisExpression: function ThisExpression(path) { + if (this.isDerived && !this.hasBareSuper) { + if (!path.inShadow("this")) { + throw path.buildCodeFrameError("'this' is not allowed before super()"); + } + } + } +}]); + +var findThisesVisitor = _babelTraverse.visitors.merge([noMethodVisitor, { + ThisExpression: function ThisExpression(path) { + this.superThises.push(path); + } +}]); + +var ClassTransformer = function () { + function ClassTransformer(path, file) { + (0, _classCallCheck3.default)(this, ClassTransformer); + + this.parent = path.parent; + this.scope = path.scope; + this.node = path.node; + this.path = path; + this.file = file; + + this.clearDescriptors(); + + this.instancePropBody = []; + this.instancePropRefs = {}; + this.staticPropBody = []; + this.body = []; + + this.bareSuperAfter = []; + this.bareSupers = []; + + this.pushedConstructor = false; + this.pushedInherits = false; + this.isLoose = false; + + this.superThises = []; + + this.classId = this.node.id; + + this.classRef = this.node.id ? t.identifier(this.node.id.name) : this.scope.generateUidIdentifier("class"); + + this.superName = this.node.superClass || t.identifier("Function"); + this.isDerived = !!this.node.superClass; + } + + ClassTransformer.prototype.run = function run() { + var _this = this; + + var superName = this.superName; + var file = this.file; + var body = this.body; + + var constructorBody = this.constructorBody = t.blockStatement([]); + this.constructor = this.buildConstructor(); + + var closureParams = []; + var closureArgs = []; + + if (this.isDerived) { + closureArgs.push(superName); + + superName = this.scope.generateUidIdentifierBasedOnNode(superName); + closureParams.push(superName); + + this.superName = superName; + } + + this.buildBody(); + + constructorBody.body.unshift(t.expressionStatement(t.callExpression(file.addHelper("classCallCheck"), [t.thisExpression(), this.classRef]))); + + body = body.concat(this.staticPropBody.map(function (fn) { + return fn(_this.classRef); + })); + + if (this.classId) { + if (body.length === 1) return t.toExpression(body[0]); + } + + body.push(t.returnStatement(this.classRef)); + + var container = t.functionExpression(null, closureParams, t.blockStatement(body)); + container.shadow = true; + return t.callExpression(container, closureArgs); + }; + + ClassTransformer.prototype.buildConstructor = function buildConstructor() { + var func = t.functionDeclaration(this.classRef, [], this.constructorBody); + t.inherits(func, this.node); + return func; + }; + + ClassTransformer.prototype.pushToMap = function pushToMap(node, enumerable) { + var kind = arguments.length <= 2 || arguments[2] === undefined ? "value" : arguments[2]; + var scope = arguments[3]; + + var mutatorMap = void 0; + if (node.static) { + this.hasStaticDescriptors = true; + mutatorMap = this.staticMutatorMap; + } else { + this.hasInstanceDescriptors = true; + mutatorMap = this.instanceMutatorMap; + } + + var map = defineMap.push(mutatorMap, node, kind, this.file, scope); + + if (enumerable) { + map.enumerable = t.booleanLiteral(true); + } + + return map; + }; + + ClassTransformer.prototype.constructorMeMaybe = function constructorMeMaybe() { + var hasConstructor = false; + var paths = this.path.get("body.body"); + for (var _iterator = paths, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_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 path = _ref; + + hasConstructor = path.equals("kind", "constructor"); + if (hasConstructor) break; + } + if (hasConstructor) return; + + var params = void 0, + body = void 0; + + if (this.isDerived) { + var _constructor = buildDerivedConstructor().expression; + params = _constructor.params; + body = _constructor.body; + } else { + params = []; + body = t.blockStatement([]); + } + + this.path.get("body").unshiftContainer("body", t.classMethod("constructor", t.identifier("constructor"), params, body)); + }; + + ClassTransformer.prototype.buildBody = function buildBody() { + this.constructorMeMaybe(); + this.pushBody(); + this.verifyConstructor(); + + if (this.userConstructor) { + var constructorBody = this.constructorBody; + constructorBody.body = constructorBody.body.concat(this.userConstructor.body.body); + t.inherits(this.constructor, this.userConstructor); + t.inherits(constructorBody, this.userConstructor.body); + } + + this.pushDescriptors(); + }; + + ClassTransformer.prototype.pushBody = function pushBody() { + var classBodyPaths = this.path.get("body.body"); + + for (var _iterator2 = classBodyPaths, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : (0, _getIterator3.default)(_iterator2);;) { + var _ref2; + + if (_isArray2) { + if (_i2 >= _iterator2.length) break; + _ref2 = _iterator2[_i2++]; + } else { + _i2 = _iterator2.next(); + if (_i2.done) break; + _ref2 = _i2.value; + } + + var path = _ref2; + + var node = path.node; + + if (path.isClassProperty()) { + throw path.buildCodeFrameError("Missing class properties transform."); + } + + if (node.decorators) { + throw path.buildCodeFrameError("Method has decorators, put the decorator plugin before the classes one."); + } + + if (t.isClassMethod(node)) { + var isConstructor = node.kind === "constructor"; + + if (isConstructor) { + path.traverse(verifyConstructorVisitor, this); + + if (!this.hasBareSuper && this.isDerived) { + throw path.buildCodeFrameError("missing super() call in constructor"); + } + } + + var replaceSupers = new _babelHelperReplaceSupers2.default({ + forceSuperMemoisation: isConstructor, + methodPath: path, + methodNode: node, + objectRef: this.classRef, + superRef: this.superName, + isStatic: node.static, + isLoose: this.isLoose, + scope: this.scope, + file: this.file + }, true); + + replaceSupers.replace(); + + if (isConstructor) { + this.pushConstructor(replaceSupers, node, path); + } else { + this.pushMethod(node, path); + } + } + } + }; + + ClassTransformer.prototype.clearDescriptors = function clearDescriptors() { + this.hasInstanceDescriptors = false; + this.hasStaticDescriptors = false; + + this.instanceMutatorMap = {}; + this.staticMutatorMap = {}; + }; + + ClassTransformer.prototype.pushDescriptors = function pushDescriptors() { + this.pushInherits(); + + var body = this.body; + + var instanceProps = void 0; + var staticProps = void 0; + + if (this.hasInstanceDescriptors) { + instanceProps = defineMap.toClassObject(this.instanceMutatorMap); + } + + if (this.hasStaticDescriptors) { + staticProps = defineMap.toClassObject(this.staticMutatorMap); + } + + if (instanceProps || staticProps) { + if (instanceProps) instanceProps = defineMap.toComputedObjectFromClass(instanceProps); + if (staticProps) staticProps = defineMap.toComputedObjectFromClass(staticProps); + + var nullNode = t.nullLiteral(); + + var args = [this.classRef, nullNode, nullNode, nullNode, nullNode]; + + if (instanceProps) args[1] = instanceProps; + if (staticProps) args[2] = staticProps; + + if (this.instanceInitializersId) { + args[3] = this.instanceInitializersId; + body.unshift(this.buildObjectAssignment(this.instanceInitializersId)); + } + + if (this.staticInitializersId) { + args[4] = this.staticInitializersId; + body.unshift(this.buildObjectAssignment(this.staticInitializersId)); + } + + var lastNonNullIndex = 0; + for (var i = 0; i < args.length; i++) { + if (args[i] !== nullNode) lastNonNullIndex = i; + } + args = args.slice(0, lastNonNullIndex + 1); + + body.push(t.expressionStatement(t.callExpression(this.file.addHelper("createClass"), args))); + } + + this.clearDescriptors(); + }; + + ClassTransformer.prototype.buildObjectAssignment = function buildObjectAssignment(id) { + return t.variableDeclaration("var", [t.variableDeclarator(id, t.objectExpression([]))]); + }; + + ClassTransformer.prototype.wrapSuperCall = function wrapSuperCall(bareSuper, superRef, thisRef, body) { + var bareSuperNode = bareSuper.node; + + if (this.isLoose) { + bareSuperNode.arguments.unshift(t.thisExpression()); + if (bareSuperNode.arguments.length === 2 && t.isSpreadElement(bareSuperNode.arguments[1]) && t.isIdentifier(bareSuperNode.arguments[1].argument, { name: "arguments" })) { + bareSuperNode.arguments[1] = bareSuperNode.arguments[1].argument; + bareSuperNode.callee = t.memberExpression(superRef, t.identifier("apply")); + } else { + bareSuperNode.callee = t.memberExpression(superRef, t.identifier("call")); + } + } else { + bareSuperNode = (0, _babelHelperOptimiseCallExpression2.default)(t.logicalExpression("||", t.memberExpression(this.classRef, t.identifier("__proto__")), t.callExpression(t.memberExpression(t.identifier("Object"), t.identifier("getPrototypeOf")), [this.classRef])), t.thisExpression(), bareSuperNode.arguments); + } + + var call = t.callExpression(this.file.addHelper("possibleConstructorReturn"), [t.thisExpression(), bareSuperNode]); + + var bareSuperAfter = this.bareSuperAfter.map(function (fn) { + return fn(thisRef); + }); + + if (bareSuper.parentPath.isExpressionStatement() && bareSuper.parentPath.container === body.node.body && body.node.body.length - 1 === bareSuper.parentPath.key) { + + if (this.superThises.length || bareSuperAfter.length) { + bareSuper.scope.push({ id: thisRef }); + call = t.assignmentExpression("=", thisRef, call); + } + + if (bareSuperAfter.length) { + call = t.toSequenceExpression([call].concat(bareSuperAfter, [thisRef])); + } + + bareSuper.parentPath.replaceWith(t.returnStatement(call)); + } else { + bareSuper.replaceWithMultiple([t.variableDeclaration("var", [t.variableDeclarator(thisRef, call)])].concat(bareSuperAfter, [t.expressionStatement(thisRef)])); + } + }; + + ClassTransformer.prototype.verifyConstructor = function verifyConstructor() { + var _this2 = this; + + if (!this.isDerived) return; + + var path = this.userConstructorPath; + var body = path.get("body"); + + path.traverse(findThisesVisitor, this); + + var guaranteedSuperBeforeFinish = !!this.bareSupers.length; + + var superRef = this.superName || t.identifier("Function"); + var thisRef = path.scope.generateUidIdentifier("this"); + + for (var _iterator3 = this.bareSupers, _isArray3 = Array.isArray(_iterator3), _i3 = 0, _iterator3 = _isArray3 ? _iterator3 : (0, _getIterator3.default)(_iterator3);;) { + var _ref3; + + if (_isArray3) { + if (_i3 >= _iterator3.length) break; + _ref3 = _iterator3[_i3++]; + } else { + _i3 = _iterator3.next(); + if (_i3.done) break; + _ref3 = _i3.value; + } + + var bareSuper = _ref3; + + this.wrapSuperCall(bareSuper, superRef, thisRef, body); + + if (guaranteedSuperBeforeFinish) { + bareSuper.find(function (parentPath) { + if (parentPath === path) { + return true; + } + + if (parentPath.isLoop() || parentPath.isConditional()) { + guaranteedSuperBeforeFinish = false; + return true; + } + }); + } + } + + for (var _iterator4 = this.superThises, _isArray4 = Array.isArray(_iterator4), _i4 = 0, _iterator4 = _isArray4 ? _iterator4 : (0, _getIterator3.default)(_iterator4);;) { + var _ref4; + + if (_isArray4) { + if (_i4 >= _iterator4.length) break; + _ref4 = _iterator4[_i4++]; + } else { + _i4 = _iterator4.next(); + if (_i4.done) break; + _ref4 = _i4.value; + } + + var thisPath = _ref4; + + thisPath.replaceWith(thisRef); + } + + var wrapReturn = function wrapReturn(returnArg) { + return t.callExpression(_this2.file.addHelper("possibleConstructorReturn"), [thisRef].concat(returnArg || [])); + }; + + var bodyPaths = body.get("body"); + if (bodyPaths.length && !bodyPaths.pop().isReturnStatement()) { + body.pushContainer("body", t.returnStatement(guaranteedSuperBeforeFinish ? thisRef : wrapReturn())); + } + + for (var _iterator5 = this.superReturns, _isArray5 = Array.isArray(_iterator5), _i5 = 0, _iterator5 = _isArray5 ? _iterator5 : (0, _getIterator3.default)(_iterator5);;) { + var _ref5; + + if (_isArray5) { + if (_i5 >= _iterator5.length) break; + _ref5 = _iterator5[_i5++]; + } else { + _i5 = _iterator5.next(); + if (_i5.done) break; + _ref5 = _i5.value; + } + + var returnPath = _ref5; + + if (returnPath.node.argument) { + var ref = returnPath.scope.generateDeclaredUidIdentifier("ret"); + returnPath.get("argument").replaceWithMultiple([t.assignmentExpression("=", ref, returnPath.node.argument), wrapReturn(ref)]); + } else { + returnPath.get("argument").replaceWith(wrapReturn()); + } + } + }; + + ClassTransformer.prototype.pushMethod = function pushMethod(node, path) { + var scope = path ? path.scope : this.scope; + + if (node.kind === "method") { + if (this._processMethod(node, scope)) return; + } + + this.pushToMap(node, false, null, scope); + }; + + ClassTransformer.prototype._processMethod = function _processMethod() { + return false; + }; + + ClassTransformer.prototype.pushConstructor = function pushConstructor(replaceSupers, method, path) { + this.bareSupers = replaceSupers.bareSupers; + this.superReturns = replaceSupers.returns; + + if (path.scope.hasOwnBinding(this.classRef.name)) { + path.scope.rename(this.classRef.name); + } + + var construct = this.constructor; + + this.userConstructorPath = path; + this.userConstructor = method; + this.hasConstructor = true; + + t.inheritsComments(construct, method); + + construct._ignoreUserWhitespace = true; + construct.params = method.params; + + t.inherits(construct.body, method.body); + construct.body.directives = method.body.directives; + + this._pushConstructor(); + }; + + ClassTransformer.prototype._pushConstructor = function _pushConstructor() { + if (this.pushedConstructor) return; + this.pushedConstructor = true; + + if (this.hasInstanceDescriptors || this.hasStaticDescriptors) { + this.pushDescriptors(); + } + + this.body.push(this.constructor); + + this.pushInherits(); + }; + + ClassTransformer.prototype.pushInherits = function pushInherits() { + if (!this.isDerived || this.pushedInherits) return; + + this.pushedInherits = true; + this.body.unshift(t.expressionStatement(t.callExpression(this.file.addHelper("inherits"), [this.classRef, this.superName]))); + }; + + return ClassTransformer; +}(); + +exports.default = ClassTransformer; +module.exports = exports["default"]; +},{"babel-helper-define-map":63,"babel-helper-optimise-call-expression":69,"babel-helper-replace-supers":73,"babel-runtime/core-js/get-iterator":138,"babel-runtime/helpers/classCallCheck":152,"babel-template":156,"babel-traverse":160,"babel-types":193}],100:[function(require,module,exports){ +/*istanbul ignore next*/"use strict"; + +exports.__esModule = true; + +var _getIterator2 = require("babel-runtime/core-js/get-iterator"); + +var _getIterator3 = _interopRequireDefault(_getIterator2); + +exports.default = function ( /*istanbul ignore next*/_ref) { + /*istanbul ignore next*/var t = _ref.types; + /*istanbul ignore next*/var template = _ref.template; + + var buildMutatorMapAssign = template( /*istanbul ignore next*/"\n MUTATOR_MAP_REF[KEY] = MUTATOR_MAP_REF[KEY] || {};\n MUTATOR_MAP_REF[KEY].KIND = VALUE;\n "); + + function getValue(prop) { + if (t.isObjectProperty(prop)) { + return prop.value; + } else if (t.isObjectMethod(prop)) { + return t.functionExpression(null, prop.params, prop.body, prop.generator, prop.async); + } + } + + function pushAssign(objId, prop, body) { + if (prop.kind === "get" && prop.kind === "set") { + pushMutatorDefine(objId, prop, body); + } else { + body.push(t.expressionStatement(t.assignmentExpression("=", t.memberExpression(objId, prop.key, prop.computed || t.isLiteral(prop.key)), getValue(prop)))); + } + } + + function pushMutatorDefine( /*istanbul ignore next*/_ref2, prop) { + /*istanbul ignore next*/var objId = _ref2.objId; + /*istanbul ignore next*/var body = _ref2.body; + /*istanbul ignore next*/var getMutatorId = _ref2.getMutatorId; + /*istanbul ignore next*/var scope = _ref2.scope; + + var key = !prop.computed && t.isIdentifier(prop.key) ? t.stringLiteral(prop.key.name) : prop.key; + + var maybeMemoise = scope.maybeGenerateMemoised(key); + if (maybeMemoise) { + body.push(t.expressionStatement(t.assignmentExpression("=", maybeMemoise, key))); + key = maybeMemoise; + } + + /*istanbul ignore next*/body.push. /*istanbul ignore next*/apply(body, buildMutatorMapAssign({ + MUTATOR_MAP_REF: getMutatorId(), + KEY: key, + VALUE: getValue(prop), + KIND: t.identifier(prop.kind) + })); + } + + function loose(info) { + for ( /*istanbul ignore next*/var _iterator = info.computedProps, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { + /*istanbul ignore next*/ + var _ref3; + + if (_isArray) { + if (_i >= _iterator.length) break; + _ref3 = _iterator[_i++]; + } else { + _i = _iterator.next(); + if (_i.done) break; + _ref3 = _i.value; + } + + var prop = _ref3; + + if (prop.kind === "get" || prop.kind === "set") { + pushMutatorDefine(info, prop); + } else { + pushAssign(info.objId, prop, info.body); + } + } + } + + function spec(info) { + /*istanbul ignore next*/var objId = info.objId; + /*istanbul ignore next*/var body = info.body; + /*istanbul ignore next*/var computedProps = info.computedProps; + /*istanbul ignore next*/var state = info.state; + + + for ( /*istanbul ignore next*/var _iterator2 = computedProps, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : (0, _getIterator3.default)(_iterator2);;) { + /*istanbul ignore next*/ + var _ref4; + + if (_isArray2) { + if (_i2 >= _iterator2.length) break; + _ref4 = _iterator2[_i2++]; + } else { + _i2 = _iterator2.next(); + if (_i2.done) break; + _ref4 = _i2.value; + } + + var prop = _ref4; + + var key = t.toComputedKey(prop); + + if (prop.kind === "get" || prop.kind === "set") { + pushMutatorDefine(info, prop); + } else if (t.isStringLiteral(key, { value: "__proto__" })) { + pushAssign(objId, prop, body); + } else { + if (computedProps.length === 1) { + return t.callExpression(state.addHelper("defineProperty"), [info.initPropExpression, key, getValue(prop)]); + } else { + body.push(t.expressionStatement(t.callExpression(state.addHelper("defineProperty"), [objId, key, getValue(prop)]))); + } + } + } + } + + return { + visitor: { + ObjectExpression: { /*istanbul ignore next*/ + exit: function exit(path, state) { + /*istanbul ignore next*/var node = path.node; + /*istanbul ignore next*/var parent = path.parent; + /*istanbul ignore next*/var scope = path.scope; + + var hasComputed = false; + for ( /*istanbul ignore next*/var _iterator3 = node.properties, _isArray3 = Array.isArray(_iterator3), _i3 = 0, _iterator3 = _isArray3 ? _iterator3 : (0, _getIterator3.default)(_iterator3);;) { + /*istanbul ignore next*/ + var _ref5; + + if (_isArray3) { + if (_i3 >= _iterator3.length) break; + _ref5 = _iterator3[_i3++]; + } else { + _i3 = _iterator3.next(); + if (_i3.done) break; + _ref5 = _i3.value; + } + + var prop = _ref5; + + hasComputed = prop.computed === true; + if (hasComputed) break; + } + if (!hasComputed) return; + + // put all getters/setters into the first object expression as well as all initialisers up + // to the first computed property + + var initProps = []; + var computedProps = []; + var foundComputed = false; + + for ( /*istanbul ignore next*/var _iterator4 = node.properties, _isArray4 = Array.isArray(_iterator4), _i4 = 0, _iterator4 = _isArray4 ? _iterator4 : (0, _getIterator3.default)(_iterator4);;) { + /*istanbul ignore next*/ + var _ref6; + + if (_isArray4) { + if (_i4 >= _iterator4.length) break; + _ref6 = _iterator4[_i4++]; + } else { + _i4 = _iterator4.next(); + if (_i4.done) break; + _ref6 = _i4.value; + } + + var _prop = _ref6; + + if (_prop.computed) { + foundComputed = true; + } + + if (foundComputed) { + computedProps.push(_prop); + } else { + initProps.push(_prop); + } + } + + var objId = scope.generateUidIdentifierBasedOnNode(parent); + var initPropExpression = t.objectExpression(initProps); + var body = []; + + body.push(t.variableDeclaration("var", [t.variableDeclarator(objId, initPropExpression)])); + + var callback = spec; + if (state.opts.loose) callback = loose; + + var mutatorRef = /*istanbul ignore next*/void 0; + + var getMutatorId = function getMutatorId() { + if (!mutatorRef) { + mutatorRef = scope.generateUidIdentifier("mutatorMap"); + + body.push(t.variableDeclaration("var", [t.variableDeclarator(mutatorRef, t.objectExpression([]))])); + } + + return mutatorRef; + }; + + var single = callback({ + scope: scope, + objId: objId, + body: body, + computedProps: computedProps, + initPropExpression: initPropExpression, + getMutatorId: getMutatorId, + state: state + }); + + if (mutatorRef) { + body.push(t.expressionStatement(t.callExpression(state.addHelper("defineEnumerableProperties"), [objId, mutatorRef]))); + } + + if (single) { + path.replaceWith(single); + } else { + body.push(t.expressionStatement(objId)); + path.replaceWithMultiple(body); + } + } + } + } + }; +}; + +/*istanbul ignore next*/ +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +module.exports = exports["default"]; +},{"babel-runtime/core-js/get-iterator":138}],101:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck"); + +var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); + +var _getIterator2 = require("babel-runtime/core-js/get-iterator"); + +var _getIterator3 = _interopRequireDefault(_getIterator2); + +exports.default = function (_ref) { + var t = _ref.types; + + + function variableDeclarationHasPattern(node) { + for (var _iterator = node.declarations, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { + var _ref2; + + if (_isArray) { + if (_i >= _iterator.length) break; + _ref2 = _iterator[_i++]; + } else { + _i = _iterator.next(); + if (_i.done) break; + _ref2 = _i.value; + } + + var declar = _ref2; + + if (t.isPattern(declar.id)) { + return true; + } + } + return false; + } + + function hasRest(pattern) { + for (var _iterator2 = pattern.elements, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : (0, _getIterator3.default)(_iterator2);;) { + var _ref3; + + if (_isArray2) { + if (_i2 >= _iterator2.length) break; + _ref3 = _iterator2[_i2++]; + } else { + _i2 = _iterator2.next(); + if (_i2.done) break; + _ref3 = _i2.value; + } + + var elem = _ref3; + + if (t.isRestElement(elem)) { + return true; + } + } + return false; + } + + var arrayUnpackVisitor = { + ReferencedIdentifier: function ReferencedIdentifier(path, state) { + if (state.bindings[path.node.name]) { + state.deopt = true; + path.stop(); + } + } + }; + + var DestructuringTransformer = function () { + function DestructuringTransformer(opts) { + (0, _classCallCheck3.default)(this, DestructuringTransformer); + + this.blockHoist = opts.blockHoist; + this.operator = opts.operator; + this.arrays = {}; + this.nodes = opts.nodes || []; + this.scope = opts.scope; + this.file = opts.file; + this.kind = opts.kind; + } + + DestructuringTransformer.prototype.buildVariableAssignment = function buildVariableAssignment(id, init) { + var op = this.operator; + if (t.isMemberExpression(id)) op = "="; + + var node = void 0; + + if (op) { + node = t.expressionStatement(t.assignmentExpression(op, id, init)); + } else { + node = t.variableDeclaration(this.kind, [t.variableDeclarator(id, init)]); + } + + node._blockHoist = this.blockHoist; + + return node; + }; + + DestructuringTransformer.prototype.buildVariableDeclaration = function buildVariableDeclaration(id, init) { + var declar = t.variableDeclaration("var", [t.variableDeclarator(id, init)]); + declar._blockHoist = this.blockHoist; + return declar; + }; + + DestructuringTransformer.prototype.push = function push(id, init) { + if (t.isObjectPattern(id)) { + this.pushObjectPattern(id, init); + } else if (t.isArrayPattern(id)) { + this.pushArrayPattern(id, init); + } else if (t.isAssignmentPattern(id)) { + this.pushAssignmentPattern(id, init); + } else { + this.nodes.push(this.buildVariableAssignment(id, init)); + } + }; + + DestructuringTransformer.prototype.toArray = function toArray(node, count) { + if (this.file.opts.loose || t.isIdentifier(node) && this.arrays[node.name]) { + return node; + } else { + return this.scope.toArray(node, count); + } + }; + + DestructuringTransformer.prototype.pushAssignmentPattern = function pushAssignmentPattern(pattern, valueRef) { + + var tempValueRef = this.scope.generateUidIdentifierBasedOnNode(valueRef); + + var declar = t.variableDeclaration("var", [t.variableDeclarator(tempValueRef, valueRef)]); + declar._blockHoist = this.blockHoist; + this.nodes.push(declar); + + var tempConditional = t.conditionalExpression(t.binaryExpression("===", tempValueRef, t.identifier("undefined")), pattern.right, tempValueRef); + + var left = pattern.left; + if (t.isPattern(left)) { + var tempValueDefault = t.expressionStatement(t.assignmentExpression("=", tempValueRef, tempConditional)); + tempValueDefault._blockHoist = this.blockHoist; + + this.nodes.push(tempValueDefault); + this.push(left, tempValueRef); + } else { + this.nodes.push(this.buildVariableAssignment(left, tempConditional)); + } + }; + + DestructuringTransformer.prototype.pushObjectRest = function pushObjectRest(pattern, objRef, spreadProp, spreadPropIndex) { + + var keys = []; + + for (var i = 0; i < pattern.properties.length; i++) { + var prop = pattern.properties[i]; + + if (i >= spreadPropIndex) break; + + if (t.isRestProperty(prop)) continue; + + var key = prop.key; + if (t.isIdentifier(key) && !prop.computed) key = t.stringLiteral(prop.key.name); + keys.push(key); + } + + keys = t.arrayExpression(keys); + + var value = t.callExpression(this.file.addHelper("objectWithoutProperties"), [objRef, keys]); + this.nodes.push(this.buildVariableAssignment(spreadProp.argument, value)); + }; + + DestructuringTransformer.prototype.pushObjectProperty = function pushObjectProperty(prop, propRef) { + if (t.isLiteral(prop.key)) prop.computed = true; + + var pattern = prop.value; + var objRef = t.memberExpression(propRef, prop.key, prop.computed); + + if (t.isPattern(pattern)) { + this.push(pattern, objRef); + } else { + this.nodes.push(this.buildVariableAssignment(pattern, objRef)); + } + }; + + DestructuringTransformer.prototype.pushObjectPattern = function pushObjectPattern(pattern, objRef) { + + if (!pattern.properties.length) { + this.nodes.push(t.expressionStatement(t.callExpression(this.file.addHelper("objectDestructuringEmpty"), [objRef]))); + } + + if (pattern.properties.length > 1 && !this.scope.isStatic(objRef)) { + var temp = this.scope.generateUidIdentifierBasedOnNode(objRef); + this.nodes.push(this.buildVariableDeclaration(temp, objRef)); + objRef = temp; + } + + for (var i = 0; i < pattern.properties.length; i++) { + var prop = pattern.properties[i]; + if (t.isRestProperty(prop)) { + this.pushObjectRest(pattern, objRef, prop, i); + } else { + this.pushObjectProperty(prop, objRef); + } + } + }; + + DestructuringTransformer.prototype.canUnpackArrayPattern = function canUnpackArrayPattern(pattern, arr) { + if (!t.isArrayExpression(arr)) return false; + + if (pattern.elements.length > arr.elements.length) return; + if (pattern.elements.length < arr.elements.length && !hasRest(pattern)) return false; + + for (var _iterator3 = pattern.elements, _isArray3 = Array.isArray(_iterator3), _i3 = 0, _iterator3 = _isArray3 ? _iterator3 : (0, _getIterator3.default)(_iterator3);;) { + var _ref4; + + if (_isArray3) { + if (_i3 >= _iterator3.length) break; + _ref4 = _iterator3[_i3++]; + } else { + _i3 = _iterator3.next(); + if (_i3.done) break; + _ref4 = _i3.value; + } + + var elem = _ref4; + + if (!elem) return false; + + if (t.isMemberExpression(elem)) return false; + } + + for (var _iterator4 = arr.elements, _isArray4 = Array.isArray(_iterator4), _i4 = 0, _iterator4 = _isArray4 ? _iterator4 : (0, _getIterator3.default)(_iterator4);;) { + var _ref5; + + if (_isArray4) { + if (_i4 >= _iterator4.length) break; + _ref5 = _iterator4[_i4++]; + } else { + _i4 = _iterator4.next(); + if (_i4.done) break; + _ref5 = _i4.value; + } + + var _elem = _ref5; + + if (t.isSpreadElement(_elem)) return false; + + if (t.isCallExpression(_elem)) return false; + + if (t.isMemberExpression(_elem)) return false; + } + + var bindings = t.getBindingIdentifiers(pattern); + var state = { deopt: false, bindings: bindings }; + this.scope.traverse(arr, arrayUnpackVisitor, state); + return !state.deopt; + }; + + DestructuringTransformer.prototype.pushUnpackedArrayPattern = function pushUnpackedArrayPattern(pattern, arr) { + for (var i = 0; i < pattern.elements.length; i++) { + var elem = pattern.elements[i]; + if (t.isRestElement(elem)) { + this.push(elem.argument, t.arrayExpression(arr.elements.slice(i))); + } else { + this.push(elem, arr.elements[i]); + } + } + }; + + DestructuringTransformer.prototype.pushArrayPattern = function pushArrayPattern(pattern, arrayRef) { + if (!pattern.elements) return; + + if (this.canUnpackArrayPattern(pattern, arrayRef)) { + return this.pushUnpackedArrayPattern(pattern, arrayRef); + } + + var count = !hasRest(pattern) && pattern.elements.length; + + var toArray = this.toArray(arrayRef, count); + + if (t.isIdentifier(toArray)) { + arrayRef = toArray; + } else { + arrayRef = this.scope.generateUidIdentifierBasedOnNode(arrayRef); + this.arrays[arrayRef.name] = true; + this.nodes.push(this.buildVariableDeclaration(arrayRef, toArray)); + } + + for (var i = 0; i < pattern.elements.length; i++) { + var elem = pattern.elements[i]; + + if (!elem) continue; + + var elemRef = void 0; + + if (t.isRestElement(elem)) { + elemRef = this.toArray(arrayRef); + + if (i > 0) { + elemRef = t.callExpression(t.memberExpression(elemRef, t.identifier("slice")), [t.numericLiteral(i)]); + } + + elem = elem.argument; + } else { + elemRef = t.memberExpression(arrayRef, t.numericLiteral(i), true); + } + + this.push(elem, elemRef); + } + }; + + DestructuringTransformer.prototype.init = function init(pattern, ref) { + + if (!t.isArrayExpression(ref) && !t.isMemberExpression(ref)) { + var memo = this.scope.maybeGenerateMemoised(ref, true); + if (memo) { + this.nodes.push(this.buildVariableDeclaration(memo, ref)); + ref = memo; + } + } + + this.push(pattern, ref); + + return this.nodes; + }; + + return DestructuringTransformer; + }(); + + return { + visitor: { + ExportNamedDeclaration: function ExportNamedDeclaration(path) { + var declaration = path.get("declaration"); + if (!declaration.isVariableDeclaration()) return; + if (!variableDeclarationHasPattern(declaration.node)) return; + + var specifiers = []; + + for (var name in path.getOuterBindingIdentifiers(path)) { + var id = t.identifier(name); + specifiers.push(t.exportSpecifier(id, id)); + } + + path.replaceWith(declaration.node); + path.insertAfter(t.exportNamedDeclaration(null, specifiers)); + }, + ForXStatement: function ForXStatement(path, file) { + var node = path.node; + var scope = path.scope; + + var left = node.left; + + if (t.isPattern(left)) { + + var temp = scope.generateUidIdentifier("ref"); + + node.left = t.variableDeclaration("var", [t.variableDeclarator(temp)]); + + path.ensureBlock(); + + node.body.body.unshift(t.variableDeclaration("var", [t.variableDeclarator(left, temp)])); + + return; + } + + if (!t.isVariableDeclaration(left)) return; + + var pattern = left.declarations[0].id; + if (!t.isPattern(pattern)) return; + + var key = scope.generateUidIdentifier("ref"); + node.left = t.variableDeclaration(left.kind, [t.variableDeclarator(key, null)]); + + var nodes = []; + + var destructuring = new DestructuringTransformer({ + kind: left.kind, + file: file, + scope: scope, + nodes: nodes + }); + + destructuring.init(pattern, key); + + path.ensureBlock(); + + var block = node.body; + block.body = nodes.concat(block.body); + }, + CatchClause: function CatchClause(_ref6, file) { + var node = _ref6.node; + var scope = _ref6.scope; + + var pattern = node.param; + if (!t.isPattern(pattern)) return; + + var ref = scope.generateUidIdentifier("ref"); + node.param = ref; + + var nodes = []; + + var destructuring = new DestructuringTransformer({ + kind: "let", + file: file, + scope: scope, + nodes: nodes + }); + destructuring.init(pattern, ref); + + node.body.body = nodes.concat(node.body.body); + }, + AssignmentExpression: function AssignmentExpression(path, file) { + var node = path.node; + var scope = path.scope; + + if (!t.isPattern(node.left)) return; + + var nodes = []; + + var destructuring = new DestructuringTransformer({ + operator: node.operator, + file: file, + scope: scope, + nodes: nodes + }); + + var ref = void 0; + if (path.isCompletionRecord() || !path.parentPath.isExpressionStatement()) { + ref = scope.generateUidIdentifierBasedOnNode(node.right, "ref"); + + nodes.push(t.variableDeclaration("var", [t.variableDeclarator(ref, node.right)])); + + if (t.isArrayExpression(node.right)) { + destructuring.arrays[ref.name] = true; + } + } + + destructuring.init(node.left, ref || node.right); + + if (ref) { + nodes.push(t.expressionStatement(ref)); + } + + path.replaceWithMultiple(nodes); + }, + VariableDeclaration: function VariableDeclaration(path, file) { + var node = path.node; + var scope = path.scope; + var parent = path.parent; + + if (t.isForXStatement(parent)) return; + if (!parent || !path.container) return; + if (!variableDeclarationHasPattern(node)) return; + + var nodes = []; + var declar = void 0; + + for (var i = 0; i < node.declarations.length; i++) { + declar = node.declarations[i]; + + var patternId = declar.init; + var pattern = declar.id; + + var destructuring = new DestructuringTransformer({ + blockHoist: node._blockHoist, + nodes: nodes, + scope: scope, + kind: node.kind, + file: file + }); + + if (t.isPattern(pattern)) { + destructuring.init(pattern, patternId); + + if (+i !== node.declarations.length - 1) { + t.inherits(nodes[nodes.length - 1], declar); + } + } else { + nodes.push(t.inherits(destructuring.buildVariableAssignment(declar.id, declar.init), declar)); + } + } + + path.replaceWithMultiple(nodes); + } + } + }; +}; + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +module.exports = exports["default"]; +},{"babel-runtime/core-js/get-iterator":138,"babel-runtime/helpers/classCallCheck":152}],102:[function(require,module,exports){ +/*istanbul ignore next*/"use strict"; + +exports.__esModule = true; + +var _getIterator2 = require("babel-runtime/core-js/get-iterator"); + +var _getIterator3 = _interopRequireDefault(_getIterator2); + +var _create = require("babel-runtime/core-js/object/create"); + +var _create2 = _interopRequireDefault(_create); + +exports.default = function () { + return { + visitor: { /*istanbul ignore next*/ + ObjectExpression: function ObjectExpression(path) { + /*istanbul ignore next*/var node = path.node; + + var plainProps = node.properties.filter(function (prop) /*istanbul ignore next*/{ + return !t.isSpreadProperty(prop) && !prop.computed; + }); + + // A property is a duplicate key if: + // * the property is a data property, and is preceeded by a data, + // getter, or setter property of the same name. + // * the property is a getter property, and is preceeded by a data or + // getter property of the same name. + // * the property is a setter property, and is preceeded by a data or + // setter property of the same name. + + var alreadySeenData = /*istanbul ignore next*/(0, _create2.default)(null); + var alreadySeenGetters = /*istanbul ignore next*/(0, _create2.default)(null); + var alreadySeenSetters = /*istanbul ignore next*/(0, _create2.default)(null); + + for ( /*istanbul ignore next*/var _iterator = plainProps, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { + /*istanbul ignore next*/ + var _ref; + + if (_isArray) { + if (_i >= _iterator.length) break; + _ref = _iterator[_i++]; + } else { + _i = _iterator.next(); + if (_i.done) break; + _ref = _i.value; + } + + var prop = _ref; + + var name = getName(prop.key); + var isDuplicate = false; + switch (prop.kind) { + case "get": + if (alreadySeenData[name] || alreadySeenGetters[name]) { + isDuplicate = true; + } + alreadySeenGetters[name] = true; + break; + case "set": + if (alreadySeenData[name] || alreadySeenSetters[name]) { + isDuplicate = true; + } + alreadySeenSetters[name] = true; + break; + default: + if (alreadySeenData[name] || alreadySeenGetters[name] || alreadySeenSetters[name]) { + isDuplicate = true; + } + alreadySeenData[name] = true; + } + + if (isDuplicate) { + // Rely on the computed properties transform to split the property + // assignment out of the object literal. + prop.computed = true; + prop.key = t.stringLiteral(name); + } + } + } + } + }; +}; + +var /*istanbul ignore next*/_babelTypes = require("babel-types"); + +/*istanbul ignore next*/ +var t = _interopRequireWildcard(_babelTypes); + +/*istanbul ignore next*/ +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function getName(key) { + if (t.isIdentifier(key)) { + return key.name; + } + return key.value.toString(); +} + +/*istanbul ignore next*/module.exports = exports["default"]; +},{"babel-runtime/core-js/get-iterator":138,"babel-runtime/core-js/object/create":143,"babel-types":193}],103:[function(require,module,exports){ +/*istanbul ignore next*/"use strict"; + +exports.__esModule = true; + +exports.default = function ( /*istanbul ignore next*/_ref) { + /*istanbul ignore next*/var /* eslint max-len: 0 */ + + messages = _ref.messages; + /*istanbul ignore next*/var template = _ref.template; + /*istanbul ignore next*/var t = _ref.types; + + var buildForOfArray = template( /*istanbul ignore next*/"\n for (var KEY = 0; KEY < ARR.length; KEY++) BODY;\n "); + + var buildForOfLoose = template( /*istanbul ignore next*/"\n for (var LOOP_OBJECT = OBJECT,\n IS_ARRAY = Array.isArray(LOOP_OBJECT),\n INDEX = 0,\n LOOP_OBJECT = IS_ARRAY ? LOOP_OBJECT : LOOP_OBJECT[Symbol.iterator]();;) {\n var ID;\n if (IS_ARRAY) {\n if (INDEX >= LOOP_OBJECT.length) break;\n ID = LOOP_OBJECT[INDEX++];\n } else {\n INDEX = LOOP_OBJECT.next();\n if (INDEX.done) break;\n ID = INDEX.value;\n }\n }\n "); + + var buildForOf = template( /*istanbul ignore next*/"\n var ITERATOR_COMPLETION = true;\n var ITERATOR_HAD_ERROR_KEY = false;\n var ITERATOR_ERROR_KEY = undefined;\n try {\n for (var ITERATOR_KEY = OBJECT[Symbol.iterator](), STEP_KEY; !(ITERATOR_COMPLETION = (STEP_KEY = ITERATOR_KEY.next()).done); ITERATOR_COMPLETION = true) {\n }\n } catch (err) {\n ITERATOR_HAD_ERROR_KEY = true;\n ITERATOR_ERROR_KEY = err;\n } finally {\n try {\n if (!ITERATOR_COMPLETION && ITERATOR_KEY.return) {\n ITERATOR_KEY.return();\n }\n } finally {\n if (ITERATOR_HAD_ERROR_KEY) {\n throw ITERATOR_ERROR_KEY;\n }\n }\n }\n "); + + function _ForOfStatementArray(path) { + /*istanbul ignore next*/var node = path.node; + /*istanbul ignore next*/var scope = path.scope; + + var nodes = []; + var right = node.right; + + if (!t.isIdentifier(right) || !scope.hasBinding(right.name)) { + var uid = scope.generateUidIdentifier("arr"); + nodes.push(t.variableDeclaration("var", [t.variableDeclarator(uid, right)])); + right = uid; + } + + var iterationKey = scope.generateUidIdentifier("i"); + + var loop = buildForOfArray({ + BODY: node.body, + KEY: iterationKey, + ARR: right + }); + + t.inherits(loop, node); + t.ensureBlock(loop); + + var iterationValue = t.memberExpression(right, iterationKey, true); + + var left = node.left; + if (t.isVariableDeclaration(left)) { + left.declarations[0].init = iterationValue; + loop.body.body.unshift(left); + } else { + loop.body.body.unshift(t.expressionStatement(t.assignmentExpression("=", left, iterationValue))); + } + + if (path.parentPath.isLabeledStatement()) { + loop = t.labeledStatement(path.parentPath.node.label, loop); + } + + nodes.push(loop); + + return nodes; + } + + return { + visitor: { /*istanbul ignore next*/ + ForOfStatement: function ForOfStatement(path, state) { + if (path.get("right").isArrayExpression()) { + return path.replaceWithMultiple(_ForOfStatementArray.call(this, path, state)); + } + + var callback = spec; + if (state.opts.loose) callback = loose; + + /*istanbul ignore next*/var node = path.node; + + var build = callback(path, state); + var declar = build.declar; + var loop = build.loop; + var block = loop.body; + + // ensure that it's a block so we can take all its statements + path.ensureBlock(); + + // add the value declaration to the new loop body + if (declar) { + block.body.push(declar); + } + + // push the rest of the original loop body onto our new body + block.body = block.body.concat(node.body.body); + + t.inherits(loop, node); + t.inherits(loop.body, node.body); + + if (build.replaceParent) { + path.parentPath.replaceWithMultiple(build.node); + path.remove(); + } else { + path.replaceWithMultiple(build.node); + } + } + } + }; + + function loose(path, file) { + /*istanbul ignore next*/var node = path.node; + /*istanbul ignore next*/var scope = path.scope; + + + var left = node.left; + var declar = /*istanbul ignore next*/void 0, + id = /*istanbul ignore next*/void 0; + + if (t.isIdentifier(left) || t.isPattern(left) || t.isMemberExpression(left)) { + // for (i of test), for ({ i } of test) + id = left; + } else if (t.isVariableDeclaration(left)) { + // for (let i of test) + id = scope.generateUidIdentifier("ref"); + declar = t.variableDeclaration(left.kind, [t.variableDeclarator(left.declarations[0].id, id)]); + } else { + throw file.buildCodeFrameError(left, messages.get("unknownForHead", left.type)); + } + + var iteratorKey = scope.generateUidIdentifier("iterator"); + var isArrayKey = scope.generateUidIdentifier("isArray"); + + var loop = buildForOfLoose({ + LOOP_OBJECT: iteratorKey, + IS_ARRAY: isArrayKey, + OBJECT: node.right, + INDEX: scope.generateUidIdentifier("i"), + ID: id + }); + + if (!declar) { + // no declaration so we need to remove the variable declaration at the top of + // the for-of-loose template + loop.body.body.shift(); + } + + // + + return { + declar: declar, + node: loop, + loop: loop + }; + } + + function spec(path, file) { + /*istanbul ignore next*/var node = path.node; + /*istanbul ignore next*/var scope = path.scope; + /*istanbul ignore next*/var parent = path.parent; + + var left = node.left; + var declar = /*istanbul ignore next*/void 0; + + var stepKey = scope.generateUidIdentifier("step"); + var stepValue = t.memberExpression(stepKey, t.identifier("value")); + + if (t.isIdentifier(left) || t.isPattern(left) || t.isMemberExpression(left)) { + // for (i of test), for ({ i } of test) + declar = t.expressionStatement(t.assignmentExpression("=", left, stepValue)); + } else if (t.isVariableDeclaration(left)) { + // for (let i of test) + declar = t.variableDeclaration(left.kind, [t.variableDeclarator(left.declarations[0].id, stepValue)]); + } else { + throw file.buildCodeFrameError(left, messages.get("unknownForHead", left.type)); + } + + // + + var iteratorKey = scope.generateUidIdentifier("iterator"); + + var template = buildForOf({ + ITERATOR_HAD_ERROR_KEY: scope.generateUidIdentifier("didIteratorError"), + ITERATOR_COMPLETION: scope.generateUidIdentifier("iteratorNormalCompletion"), + ITERATOR_ERROR_KEY: scope.generateUidIdentifier("iteratorError"), + ITERATOR_KEY: iteratorKey, + STEP_KEY: stepKey, + OBJECT: node.right, + BODY: null + }); + + var isLabeledParent = t.isLabeledStatement(parent); + + var tryBody = template[3].block.body; + var loop = tryBody[0]; + + if (isLabeledParent) { + tryBody[0] = t.labeledStatement(parent.label, loop); + } + + // + + return { + replaceParent: isLabeledParent, + declar: declar, + loop: loop, + node: template + }; + } +}; + +/*istanbul ignore next*/module.exports = exports["default"]; +},{}],104:[function(require,module,exports){ +/*istanbul ignore next*/"use strict"; + +exports.__esModule = true; + +exports.default = function () { + return { + visitor: { + "ArrowFunctionExpression|FunctionExpression": { /*istanbul ignore next*/ + exit: function exit(path) { + if (path.key !== "value" && !path.parentPath.isObjectProperty()) { + var replacement = /*istanbul ignore next*/(0, _babelHelperFunctionName2.default)(path); + if (replacement) path.replaceWith(replacement); + } + } + }, + + /*istanbul ignore next*/ObjectProperty: function ObjectProperty(path) { + var value = path.get("value"); + if (value.isFunction()) { + var newNode = /*istanbul ignore next*/(0, _babelHelperFunctionName2.default)(value); + if (newNode) value.replaceWith(newNode); + } + } + } + }; +}; + +var /*istanbul ignore next*/_babelHelperFunctionName = require("babel-helper-function-name"); + +/*istanbul ignore next*/ +var _babelHelperFunctionName2 = _interopRequireDefault(_babelHelperFunctionName); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +module.exports = exports["default"]; +},{"babel-helper-function-name":66}],105:[function(require,module,exports){ +/*istanbul ignore next*/"use strict"; + +exports.__esModule = true; + +exports.default = function () { + return { + visitor: { /*istanbul ignore next*/ + NumericLiteral: function NumericLiteral(_ref) { + /*istanbul ignore next*/var node = _ref.node; + + // number octal like 0b10 or 0o70 + if (node.extra && /^0[ob]/i.test(node.extra.raw)) { + node.extra = undefined; + } + }, + /*istanbul ignore next*/StringLiteral: function StringLiteral(_ref2) { + /*istanbul ignore next*/var node = _ref2.node; + + // unicode escape + if (node.extra && /\\[u]/gi.test(node.extra.raw)) { + node.extra = undefined; + } + } + } + }; +}; + +/*istanbul ignore next*/module.exports = exports["default"]; +},{}],106:[function(require,module,exports){ +/*istanbul ignore next*/"use strict"; + +exports.__esModule = true; + +var _create = require("babel-runtime/core-js/object/create"); + +var _create2 = _interopRequireDefault(_create); + +exports.default = function ( /*istanbul ignore next*/_ref) { + /*istanbul ignore next*/var t = _ref.types; + + function isValidRequireCall(path) { + if (!path.isCallExpression()) return false; + if (!path.get("callee").isIdentifier({ name: "require" })) return false; + if (path.scope.getBinding("require")) return false; + + var args = path.get("arguments"); + if (args.length !== 1) return false; + + var arg = args[0]; + if (!arg.isStringLiteral()) return false; + + return true; + } + + var amdVisitor = { /*istanbul ignore next*/ + ReferencedIdentifier: function ReferencedIdentifier(_ref2) { + /*istanbul ignore next*/var node = _ref2.node; + /*istanbul ignore next*/var scope = _ref2.scope; + + if (node.name === "exports" && !scope.getBinding("exports")) { + this.hasExports = true; + } + + if (node.name === "module" && !scope.getBinding("module")) { + this.hasModule = true; + } + }, + /*istanbul ignore next*/CallExpression: function CallExpression(path) { + if (!isValidRequireCall(path)) return; + this.bareSources.push(path.node.arguments[0]); + path.remove(); + }, + /*istanbul ignore next*/VariableDeclarator: function VariableDeclarator(path) { + var id = path.get("id"); + if (!id.isIdentifier()) return; + + var init = path.get("init"); + if (!isValidRequireCall(init)) return; + + var source = init.node.arguments[0]; + this.sourceNames[source.value] = true; + this.sources.push([id.node, source]); + + path.remove(); + } + }; + + return { + inherits: require("babel-plugin-transform-es2015-modules-commonjs"), + + /*istanbul ignore next*/pre: function pre() { + // source strings + this.sources = []; + this.sourceNames = /*istanbul ignore next*/(0, _create2.default)(null); + + // bare sources + this.bareSources = []; + + this.hasExports = false; + this.hasModule = false; + }, + + + visitor: { + Program: { /*istanbul ignore next*/ + exit: function exit(path) { + /*istanbul ignore next*/ + var _this = this; + + if (this.ran) return; + this.ran = true; + + path.traverse(amdVisitor, this); + + var params = this.sources.map(function (source) /*istanbul ignore next*/{ + return source[0]; + }); + var sources = this.sources.map(function (source) /*istanbul ignore next*/{ + return source[1]; + }); + + sources = sources.concat(this.bareSources.filter(function (str) { + return ! /*istanbul ignore next*/_this.sourceNames[str.value]; + })); + + var moduleName = this.getModuleName(); + if (moduleName) moduleName = t.stringLiteral(moduleName); + + if (this.hasExports) { + sources.unshift(t.stringLiteral("exports")); + params.unshift(t.identifier("exports")); + } + + if (this.hasModule) { + sources.unshift(t.stringLiteral("module")); + params.unshift(t.identifier("module")); + } + + /*istanbul ignore next*/var node = path.node; + + var factory = buildFactory({ + PARAMS: params, + BODY: node.body + }); + factory.expression.body.directives = node.directives; + node.directives = []; + + node.body = [buildDefine({ + MODULE_NAME: moduleName, + SOURCES: sources, + FACTORY: factory + })]; + } + } + } + }; +}; + +var /*istanbul ignore next*/_babelTemplate = require("babel-template"); + +/*istanbul ignore next*/ +var _babelTemplate2 = _interopRequireDefault(_babelTemplate); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var buildDefine = /*istanbul ignore next*/(0, _babelTemplate2.default)( /*istanbul ignore next*/"\n define(MODULE_NAME, [SOURCES], FACTORY);\n"); + +var buildFactory = /*istanbul ignore next*/(0, _babelTemplate2.default)( /*istanbul ignore next*/"\n (function (PARAMS) {\n BODY;\n })\n"); + +/*istanbul ignore next*/module.exports = exports["default"]; +},{"babel-plugin-transform-es2015-modules-commonjs":107,"babel-runtime/core-js/object/create":143,"babel-template":156}],107:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +var _keys = require("babel-runtime/core-js/object/keys"); + +var _keys2 = _interopRequireDefault(_keys); + +var _create = require("babel-runtime/core-js/object/create"); + +var _create2 = _interopRequireDefault(_create); + +var _getIterator2 = require("babel-runtime/core-js/get-iterator"); + +var _getIterator3 = _interopRequireDefault(_getIterator2); + +var _symbol = require("babel-runtime/core-js/symbol"); + +var _symbol2 = _interopRequireDefault(_symbol); + +exports.default = function () { + var REASSIGN_REMAP_SKIP = (0, _symbol2.default)(); + + var reassignmentVisitor = { + ReferencedIdentifier: function ReferencedIdentifier(path) { + var name = path.node.name; + var remap = this.remaps[name]; + if (!remap) return; + + if (this.scope.getBinding(name) !== path.scope.getBinding(name)) return; + + if (path.parentPath.isCallExpression({ callee: path.node })) { + path.replaceWith(t.sequenceExpression([t.numericLiteral(0), remap])); + } else { + path.replaceWith(remap); + } + this.requeueInParent(path); + }, + AssignmentExpression: function AssignmentExpression(path) { + var node = path.node; + if (node[REASSIGN_REMAP_SKIP]) return; + + var left = path.get("left"); + if (!left.isIdentifier()) return; + + var name = left.node.name; + var exports = this.exports[name]; + if (!exports) return; + + if (this.scope.getBinding(name) !== path.scope.getBinding(name)) return; + + node[REASSIGN_REMAP_SKIP] = true; + + for (var _iterator = exports, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_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 reid = _ref; + + node = buildExportsAssignment(reid, node).expression; + } + + path.replaceWith(node); + this.requeueInParent(path); + }, + UpdateExpression: function UpdateExpression(path) { + var arg = path.get("argument"); + if (!arg.isIdentifier()) return; + + var name = arg.node.name; + var exports = this.exports[name]; + if (!exports) return; + + if (this.scope.getBinding(name) !== path.scope.getBinding(name)) return; + + var node = t.assignmentExpression(path.node.operator[0] + "=", arg.node, t.numericLiteral(1)); + + if (path.parentPath.isExpressionStatement() && !path.isCompletionRecord() || path.node.prefix) { + path.replaceWith(node); + this.requeueInParent(path); + return; + } + + var nodes = []; + nodes.push(node); + + var operator = void 0; + if (path.node.operator === "--") { + operator = "+"; + } else { + operator = "-"; + } + nodes.push(t.binaryExpression(operator, arg.node, t.numericLiteral(1))); + + path.replaceWithMultiple(t.sequenceExpression(nodes)); + } + }; + + return { + inherits: require("babel-plugin-transform-strict-mode"), + + visitor: { + ThisExpression: function ThisExpression(path, state) { + if (this.ranCommonJS) return; + + if (state.opts.allowTopLevelThis !== true && !path.findParent(function (path) { + return !path.is("shadow") && THIS_BREAK_KEYS.indexOf(path.type) >= 0; + })) { + path.replaceWith(t.identifier("undefined")); + } + }, + + + Program: { + exit: function exit(path) { + this.ranCommonJS = true; + + var strict = !!this.opts.strict; + + var scope = path.scope; + + scope.rename("module"); + scope.rename("exports"); + scope.rename("require"); + + var hasExports = false; + var hasImports = false; + + var body = path.get("body"); + var imports = (0, _create2.default)(null); + var exports = (0, _create2.default)(null); + + var nonHoistedExportNames = (0, _create2.default)(null); + + var topNodes = []; + var remaps = (0, _create2.default)(null); + + var requires = (0, _create2.default)(null); + + function addRequire(source, blockHoist) { + var cached = requires[source]; + if (cached) return cached; + + var ref = path.scope.generateUidIdentifier((0, _path2.basename)(source, (0, _path2.extname)(source))); + + var varDecl = t.variableDeclaration("var", [t.variableDeclarator(ref, buildRequire(t.stringLiteral(source)).expression)]); + + if (imports[source]) { + varDecl.loc = imports[source].loc; + } + + if (typeof blockHoist === "number" && blockHoist > 0) { + varDecl._blockHoist = blockHoist; + } + + topNodes.push(varDecl); + + return requires[source] = ref; + } + + function addTo(obj, key, arr) { + var existing = obj[key] || []; + obj[key] = existing.concat(arr); + } + + for (var _iterator2 = body, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : (0, _getIterator3.default)(_iterator2);;) { + var _ref2; + + if (_isArray2) { + if (_i2 >= _iterator2.length) break; + _ref2 = _iterator2[_i2++]; + } else { + _i2 = _iterator2.next(); + if (_i2.done) break; + _ref2 = _i2.value; + } + + var _path = _ref2; + + if (_path.isExportDeclaration()) { + hasExports = true; + + var specifiers = [].concat(_path.get("declaration"), _path.get("specifiers")); + for (var _iterator4 = specifiers, _isArray4 = Array.isArray(_iterator4), _i4 = 0, _iterator4 = _isArray4 ? _iterator4 : (0, _getIterator3.default)(_iterator4);;) { + var _ref4; + + if (_isArray4) { + if (_i4 >= _iterator4.length) break; + _ref4 = _iterator4[_i4++]; + } else { + _i4 = _iterator4.next(); + if (_i4.done) break; + _ref4 = _i4.value; + } + + var _specifier2 = _ref4; + + var ids = _specifier2.getBindingIdentifiers(); + if (ids.__esModule) { + throw _specifier2.buildCodeFrameError("Illegal export \"__esModule\""); + } + } + } + + if (_path.isImportDeclaration()) { + var _importsEntry$specifi; + + hasImports = true; + + var key = _path.node.source.value; + var importsEntry = imports[key] || { + specifiers: [], + maxBlockHoist: 0, + loc: _path.node.loc + }; + + (_importsEntry$specifi = importsEntry.specifiers).push.apply(_importsEntry$specifi, _path.node.specifiers); + + if (typeof _path.node._blockHoist === "number") { + importsEntry.maxBlockHoist = Math.max(_path.node._blockHoist, importsEntry.maxBlockHoist); + } + + imports[key] = importsEntry; + + _path.remove(); + } else if (_path.isExportDefaultDeclaration()) { + var declaration = _path.get("declaration"); + if (declaration.isFunctionDeclaration()) { + var id = declaration.node.id; + var defNode = t.identifier("default"); + if (id) { + addTo(exports, id.name, defNode); + topNodes.push(buildExportsAssignment(defNode, id)); + _path.replaceWith(declaration.node); + } else { + topNodes.push(buildExportsAssignment(defNode, t.toExpression(declaration.node))); + _path.remove(); + } + } else if (declaration.isClassDeclaration()) { + var _id = declaration.node.id; + var _defNode = t.identifier("default"); + if (_id) { + addTo(exports, _id.name, _defNode); + _path.replaceWithMultiple([declaration.node, buildExportsAssignment(_defNode, _id)]); + } else { + _path.replaceWith(buildExportsAssignment(_defNode, t.toExpression(declaration.node))); + + _path.parentPath.requeue(_path.get("expression.left")); + } + } else { + _path.replaceWith(buildExportsAssignment(t.identifier("default"), declaration.node)); + + _path.parentPath.requeue(_path.get("expression.left")); + } + } else if (_path.isExportNamedDeclaration()) { + var _declaration = _path.get("declaration"); + if (_declaration.node) { + if (_declaration.isFunctionDeclaration()) { + var _id2 = _declaration.node.id; + addTo(exports, _id2.name, _id2); + topNodes.push(buildExportsAssignment(_id2, _id2)); + _path.replaceWith(_declaration.node); + } else if (_declaration.isClassDeclaration()) { + var _id3 = _declaration.node.id; + addTo(exports, _id3.name, _id3); + _path.replaceWithMultiple([_declaration.node, buildExportsAssignment(_id3, _id3)]); + nonHoistedExportNames[_id3.name] = true; + } else if (_declaration.isVariableDeclaration()) { + var declarators = _declaration.get("declarations"); + for (var _iterator5 = declarators, _isArray5 = Array.isArray(_iterator5), _i5 = 0, _iterator5 = _isArray5 ? _iterator5 : (0, _getIterator3.default)(_iterator5);;) { + var _ref5; + + if (_isArray5) { + if (_i5 >= _iterator5.length) break; + _ref5 = _iterator5[_i5++]; + } else { + _i5 = _iterator5.next(); + if (_i5.done) break; + _ref5 = _i5.value; + } + + var decl = _ref5; + + var _id4 = decl.get("id"); + + var init = decl.get("init"); + if (!init.node) init.replaceWith(t.identifier("undefined")); + + if (_id4.isIdentifier()) { + addTo(exports, _id4.node.name, _id4.node); + init.replaceWith(buildExportsAssignment(_id4.node, init.node).expression); + nonHoistedExportNames[_id4.node.name] = true; + } else {} + } + _path.replaceWith(_declaration.node); + } + continue; + } + + var _specifiers = _path.get("specifiers"); + var nodes = []; + var _source = _path.node.source; + if (_source) { + var ref = addRequire(_source.value, _path.node._blockHoist); + + for (var _iterator6 = _specifiers, _isArray6 = Array.isArray(_iterator6), _i6 = 0, _iterator6 = _isArray6 ? _iterator6 : (0, _getIterator3.default)(_iterator6);;) { + var _ref6; + + if (_isArray6) { + if (_i6 >= _iterator6.length) break; + _ref6 = _iterator6[_i6++]; + } else { + _i6 = _iterator6.next(); + if (_i6.done) break; + _ref6 = _i6.value; + } + + var _specifier3 = _ref6; + + if (_specifier3.isExportNamespaceSpecifier()) {} else if (_specifier3.isExportDefaultSpecifier()) {} else if (_specifier3.isExportSpecifier()) { + if (_specifier3.node.local.name === "default") { + topNodes.push(buildExportsFrom(t.stringLiteral(_specifier3.node.exported.name), t.memberExpression(t.callExpression(this.addHelper("interopRequireDefault"), [ref]), _specifier3.node.local))); + } else { + topNodes.push(buildExportsFrom(t.stringLiteral(_specifier3.node.exported.name), t.memberExpression(ref, _specifier3.node.local))); + } + nonHoistedExportNames[_specifier3.node.exported.name] = true; + } + } + } else { + for (var _iterator7 = _specifiers, _isArray7 = Array.isArray(_iterator7), _i7 = 0, _iterator7 = _isArray7 ? _iterator7 : (0, _getIterator3.default)(_iterator7);;) { + var _ref7; + + if (_isArray7) { + if (_i7 >= _iterator7.length) break; + _ref7 = _iterator7[_i7++]; + } else { + _i7 = _iterator7.next(); + if (_i7.done) break; + _ref7 = _i7.value; + } + + var _specifier4 = _ref7; + + if (_specifier4.isExportSpecifier()) { + addTo(exports, _specifier4.node.local.name, _specifier4.node.exported); + nonHoistedExportNames[_specifier4.node.exported.name] = true; + nodes.push(buildExportsAssignment(_specifier4.node.exported, _specifier4.node.local)); + } + } + } + _path.replaceWithMultiple(nodes); + } else if (_path.isExportAllDeclaration()) { + var exportNode = buildExportAll({ + OBJECT: addRequire(_path.node.source.value, _path.node._blockHoist) + }); + exportNode.loc = _path.node.loc; + topNodes.push(exportNode); + _path.remove(); + } + } + + for (var source in imports) { + var _imports$source = imports[source]; + var specifiers = _imports$source.specifiers; + var maxBlockHoist = _imports$source.maxBlockHoist; + + if (specifiers.length) { + var uid = addRequire(source, maxBlockHoist); + + var wildcard = void 0; + + for (var i = 0; i < specifiers.length; i++) { + var specifier = specifiers[i]; + if (t.isImportNamespaceSpecifier(specifier)) { + if (strict) { + remaps[specifier.local.name] = uid; + } else { + var varDecl = t.variableDeclaration("var", [t.variableDeclarator(specifier.local, t.callExpression(this.addHelper("interopRequireWildcard"), [uid]))]); + + if (maxBlockHoist > 0) { + varDecl._blockHoist = maxBlockHoist; + } + + topNodes.push(varDecl); + } + wildcard = specifier.local; + } else if (t.isImportDefaultSpecifier(specifier)) { + specifiers[i] = t.importSpecifier(specifier.local, t.identifier("default")); + } + } + + for (var _iterator3 = specifiers, _isArray3 = Array.isArray(_iterator3), _i3 = 0, _iterator3 = _isArray3 ? _iterator3 : (0, _getIterator3.default)(_iterator3);;) { + var _ref3; + + if (_isArray3) { + if (_i3 >= _iterator3.length) break; + _ref3 = _iterator3[_i3++]; + } else { + _i3 = _iterator3.next(); + if (_i3.done) break; + _ref3 = _i3.value; + } + + var _specifier = _ref3; + + if (t.isImportSpecifier(_specifier)) { + var target = uid; + if (_specifier.imported.name === "default") { + if (wildcard) { + target = wildcard; + } else { + target = wildcard = path.scope.generateUidIdentifier(uid.name); + var _varDecl = t.variableDeclaration("var", [t.variableDeclarator(target, t.callExpression(this.addHelper("interopRequireDefault"), [uid]))]); + + if (maxBlockHoist > 0) { + _varDecl._blockHoist = maxBlockHoist; + } + + topNodes.push(_varDecl); + } + } + remaps[_specifier.local.name] = t.memberExpression(target, t.cloneWithoutLoc(_specifier.imported)); + } + } + } else { + var requireNode = buildRequire(t.stringLiteral(source)); + requireNode.loc = imports[source].loc; + topNodes.push(requireNode); + } + } + + if (hasImports && (0, _keys2.default)(nonHoistedExportNames).length) { + var hoistedExportsNode = t.identifier("undefined"); + + for (var name in nonHoistedExportNames) { + hoistedExportsNode = buildExportsAssignment(t.identifier(name), hoistedExportsNode).expression; + } + + var node = t.expressionStatement(hoistedExportsNode); + node._blockHoist = 3; + + topNodes.unshift(node); + } + + if (hasExports && !strict) { + var buildTemplate = buildExportsModuleDeclaration; + if (this.opts.loose) buildTemplate = buildLooseExportsModuleDeclaration; + + var declar = buildTemplate(); + declar._blockHoist = 3; + + topNodes.unshift(declar); + } + + path.unshiftContainer("body", topNodes); + path.traverse(reassignmentVisitor, { + remaps: remaps, + scope: scope, + exports: exports, + requeueInParent: function requeueInParent(newPath) { + return path.requeue(newPath); + } + }); + } + } + } + }; +}; + +var _path2 = require("path"); + +var _babelTemplate = require("babel-template"); + +var _babelTemplate2 = _interopRequireDefault(_babelTemplate); + +var _babelTypes = require("babel-types"); + +var t = _interopRequireWildcard(_babelTypes); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var buildRequire = (0, _babelTemplate2.default)("\n require($0);\n"); + +var buildExportsModuleDeclaration = (0, _babelTemplate2.default)("\n Object.defineProperty(exports, \"__esModule\", {\n value: true\n });\n"); + +var buildExportsFrom = (0, _babelTemplate2.default)("\n Object.defineProperty(exports, $0, {\n enumerable: true,\n get: function () {\n return $1;\n }\n });\n"); + +var buildLooseExportsModuleDeclaration = (0, _babelTemplate2.default)("\n exports.__esModule = true;\n"); + +var buildExportsAssignment = (0, _babelTemplate2.default)("\n exports.$0 = $1;\n"); + +var buildExportAll = (0, _babelTemplate2.default)("\n Object.keys(OBJECT).forEach(function (key) {\n if (key === \"default\" || key === \"__esModule\") return;\n Object.defineProperty(exports, key, {\n enumerable: true,\n get: function () {\n return OBJECT[key];\n }\n });\n });\n"); + +var THIS_BREAK_KEYS = ["FunctionExpression", "FunctionDeclaration", "ClassProperty", "ClassMethod", "ObjectMethod"]; + +module.exports = exports["default"]; +},{"babel-plugin-transform-strict-mode":132,"babel-runtime/core-js/get-iterator":138,"babel-runtime/core-js/object/create":143,"babel-runtime/core-js/object/keys":145,"babel-runtime/core-js/symbol":147,"babel-template":156,"babel-types":193,"path":589}],108:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +var _create = require("babel-runtime/core-js/object/create"); + +var _create2 = _interopRequireDefault(_create); + +var _getIterator2 = require("babel-runtime/core-js/get-iterator"); + +var _getIterator3 = _interopRequireDefault(_getIterator2); + +var _symbol = require("babel-runtime/core-js/symbol"); + +var _symbol2 = _interopRequireDefault(_symbol); + +exports.default = function (_ref) { + var t = _ref.types; + + var IGNORE_REASSIGNMENT_SYMBOL = (0, _symbol2.default)(); + + var reassignmentVisitor = { + "AssignmentExpression|UpdateExpression": function AssignmentExpressionUpdateExpression(path) { + if (path.node[IGNORE_REASSIGNMENT_SYMBOL]) return; + path.node[IGNORE_REASSIGNMENT_SYMBOL] = true; + + var arg = path.get(path.isAssignmentExpression() ? "left" : "argument"); + if (!arg.isIdentifier()) return; + + var name = arg.node.name; + + if (this.scope.getBinding(name) !== path.scope.getBinding(name)) return; + + var exportedNames = this.exports[name]; + if (!exportedNames) return; + + var node = path.node; + + var isPostUpdateExpression = path.isUpdateExpression() && !node.prefix; + if (isPostUpdateExpression) { + if (node.operator === "++") node = t.binaryExpression("+", node.argument, t.numericLiteral(1));else if (node.operator === "--") node = t.binaryExpression("-", node.argument, t.numericLiteral(1));else isPostUpdateExpression = false; + } + + for (var _iterator = exportedNames, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { + var _ref2; + + if (_isArray) { + if (_i >= _iterator.length) break; + _ref2 = _iterator[_i++]; + } else { + _i = _iterator.next(); + if (_i.done) break; + _ref2 = _i.value; + } + + var exportedName = _ref2; + + node = this.buildCall(exportedName, node).expression; + } + + if (isPostUpdateExpression) node = t.sequenceExpression([node, path.node]); + + path.replaceWith(node); + } + }; + + return { + visitor: { + ReferencedIdentifier: function ReferencedIdentifier(path, state) { + if (path.node.name == "__moduleName" && !path.scope.hasBinding("__moduleName")) { + path.replaceWith(t.memberExpression(state.contextIdent, t.identifier("id"))); + } + }, + + + Program: { + enter: function enter(path, state) { + state.contextIdent = path.scope.generateUidIdentifier("context"); + }, + exit: function exit(path, state) { + var exportIdent = path.scope.generateUidIdentifier("export"); + var contextIdent = state.contextIdent; + + var exportNames = (0, _create2.default)(null); + var modules = (0, _create2.default)(null); + + var beforeBody = []; + var setters = []; + var sources = []; + var variableIds = []; + var removedPaths = []; + + function addExportName(key, val) { + exportNames[key] = exportNames[key] || []; + exportNames[key].push(val); + } + + function pushModule(source, key, specifiers) { + var _modules = modules[source] = modules[source] || { imports: [], exports: [] }; + _modules[key] = _modules[key].concat(specifiers); + } + + function buildExportCall(name, val) { + return t.expressionStatement(t.callExpression(exportIdent, [t.stringLiteral(name), val])); + } + + var body = path.get("body"); + + var canHoist = true; + for (var _iterator2 = body, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : (0, _getIterator3.default)(_iterator2);;) { + var _ref3; + + if (_isArray2) { + if (_i2 >= _iterator2.length) break; + _ref3 = _iterator2[_i2++]; + } else { + _i2 = _iterator2.next(); + if (_i2.done) break; + _ref3 = _i2.value; + } + + var _path = _ref3; + + if (_path.isExportDeclaration()) _path = _path.get("declaration"); + if (_path.isVariableDeclaration() && _path.node.kind !== "var") { + canHoist = false; + break; + } + } + + for (var _iterator3 = body, _isArray3 = Array.isArray(_iterator3), _i3 = 0, _iterator3 = _isArray3 ? _iterator3 : (0, _getIterator3.default)(_iterator3);;) { + var _ref4; + + if (_isArray3) { + if (_i3 >= _iterator3.length) break; + _ref4 = _iterator3[_i3++]; + } else { + _i3 = _iterator3.next(); + if (_i3.done) break; + _ref4 = _i3.value; + } + + var _path2 = _ref4; + + if (canHoist && _path2.isFunctionDeclaration()) { + beforeBody.push(_path2.node); + removedPaths.push(_path2); + } else if (_path2.isImportDeclaration()) { + var _source = _path2.node.source.value; + pushModule(_source, "imports", _path2.node.specifiers); + for (var name in _path2.getBindingIdentifiers()) { + _path2.scope.removeBinding(name); + variableIds.push(t.identifier(name)); + } + _path2.remove(); + } else if (_path2.isExportAllDeclaration()) { + pushModule(_path2.node.source.value, "exports", _path2.node); + _path2.remove(); + } else if (_path2.isExportDefaultDeclaration()) { + var declar = _path2.get("declaration"); + if (declar.isClassDeclaration() || declar.isFunctionDeclaration()) { + var id = declar.node.id; + var nodes = []; + + if (id) { + nodes.push(declar.node); + nodes.push(buildExportCall("default", id)); + addExportName(id.name, "default"); + } else { + nodes.push(buildExportCall("default", t.toExpression(declar.node))); + } + + if (!canHoist || declar.isClassDeclaration()) { + _path2.replaceWithMultiple(nodes); + } else { + beforeBody = beforeBody.concat(nodes); + removedPaths.push(_path2); + } + } else { + _path2.replaceWith(buildExportCall("default", declar.node)); + } + } else if (_path2.isExportNamedDeclaration()) { + var _declar = _path2.get("declaration"); + + if (_declar.node) { + _path2.replaceWith(_declar); + + var _nodes = []; + var bindingIdentifiers = void 0; + if (_path2.isFunction()) { + var _node = _declar.node; + var _name = _node.id.name; + if (canHoist) { + addExportName(_name, _name); + beforeBody.push(_node); + beforeBody.push(buildExportCall(_name, _node.id)); + removedPaths.push(_path2); + } else { + var _bindingIdentifiers; + + bindingIdentifiers = (_bindingIdentifiers = {}, _bindingIdentifiers[_name] = _node.id, _bindingIdentifiers); + } + } else { + bindingIdentifiers = _declar.getBindingIdentifiers(); + } + for (var _name2 in bindingIdentifiers) { + addExportName(_name2, _name2); + _nodes.push(buildExportCall(_name2, t.identifier(_name2))); + } + _path2.insertAfter(_nodes); + } else { + var _specifiers = _path2.node.specifiers; + if (_specifiers && _specifiers.length) { + if (_path2.node.source) { + pushModule(_path2.node.source.value, "exports", _specifiers); + _path2.remove(); + } else { + var _nodes2 = []; + + for (var _iterator7 = _specifiers, _isArray7 = Array.isArray(_iterator7), _i7 = 0, _iterator7 = _isArray7 ? _iterator7 : (0, _getIterator3.default)(_iterator7);;) { + var _ref8; + + if (_isArray7) { + if (_i7 >= _iterator7.length) break; + _ref8 = _iterator7[_i7++]; + } else { + _i7 = _iterator7.next(); + if (_i7.done) break; + _ref8 = _i7.value; + } + + var _specifier = _ref8; + + _nodes2.push(buildExportCall(_specifier.exported.name, _specifier.local)); + addExportName(_specifier.local.name, _specifier.exported.name); + } + + _path2.replaceWithMultiple(_nodes2); + } + } + } + } + } + + for (var source in modules) { + var specifiers = modules[source]; + + var setterBody = []; + var target = path.scope.generateUidIdentifier(source); + + for (var _iterator4 = specifiers.imports, _isArray4 = Array.isArray(_iterator4), _i4 = 0, _iterator4 = _isArray4 ? _iterator4 : (0, _getIterator3.default)(_iterator4);;) { + var _ref5; + + if (_isArray4) { + if (_i4 >= _iterator4.length) break; + _ref5 = _iterator4[_i4++]; + } else { + _i4 = _iterator4.next(); + if (_i4.done) break; + _ref5 = _i4.value; + } + + var specifier = _ref5; + + if (t.isImportNamespaceSpecifier(specifier)) { + setterBody.push(t.expressionStatement(t.assignmentExpression("=", specifier.local, target))); + } else if (t.isImportDefaultSpecifier(specifier)) { + specifier = t.importSpecifier(specifier.local, t.identifier("default")); + } + + if (t.isImportSpecifier(specifier)) { + setterBody.push(t.expressionStatement(t.assignmentExpression("=", specifier.local, t.memberExpression(target, specifier.imported)))); + } + } + + if (specifiers.exports.length) { + var exportObjRef = path.scope.generateUidIdentifier("exportObj"); + + setterBody.push(t.variableDeclaration("var", [t.variableDeclarator(exportObjRef, t.objectExpression([]))])); + + for (var _iterator5 = specifiers.exports, _isArray5 = Array.isArray(_iterator5), _i5 = 0, _iterator5 = _isArray5 ? _iterator5 : (0, _getIterator3.default)(_iterator5);;) { + var _ref6; + + if (_isArray5) { + if (_i5 >= _iterator5.length) break; + _ref6 = _iterator5[_i5++]; + } else { + _i5 = _iterator5.next(); + if (_i5.done) break; + _ref6 = _i5.value; + } + + var node = _ref6; + + if (t.isExportAllDeclaration(node)) { + setterBody.push(buildExportAll({ + KEY: path.scope.generateUidIdentifier("key"), + EXPORT_OBJ: exportObjRef, + TARGET: target + })); + } else if (t.isExportSpecifier(node)) { + setterBody.push(t.expressionStatement(t.assignmentExpression("=", t.memberExpression(exportObjRef, node.exported), t.memberExpression(target, node.local)))); + } else {} + } + + setterBody.push(t.expressionStatement(t.callExpression(exportIdent, [exportObjRef]))); + } + + sources.push(t.stringLiteral(source)); + setters.push(t.functionExpression(null, [target], t.blockStatement(setterBody))); + } + + var moduleName = this.getModuleName(); + if (moduleName) moduleName = t.stringLiteral(moduleName); + + if (canHoist) { + (0, _babelHelperHoistVariables2.default)(path, function (id) { + return variableIds.push(id); + }); + } + + if (variableIds.length) { + beforeBody.unshift(t.variableDeclaration("var", variableIds.map(function (id) { + return t.variableDeclarator(id); + }))); + } + + path.traverse(reassignmentVisitor, { + exports: exportNames, + buildCall: buildExportCall, + scope: path.scope + }); + + for (var _iterator6 = removedPaths, _isArray6 = Array.isArray(_iterator6), _i6 = 0, _iterator6 = _isArray6 ? _iterator6 : (0, _getIterator3.default)(_iterator6);;) { + var _ref7; + + if (_isArray6) { + if (_i6 >= _iterator6.length) break; + _ref7 = _iterator6[_i6++]; + } else { + _i6 = _iterator6.next(); + if (_i6.done) break; + _ref7 = _i6.value; + } + + var _path3 = _ref7; + + _path3.remove(); + } + + path.node.body = [buildTemplate({ + SYSTEM_REGISTER: t.memberExpression(t.identifier(state.opts.systemGlobal || "System"), t.identifier("register")), + BEFORE_BODY: beforeBody, + MODULE_NAME: moduleName, + SETTERS: setters, + SOURCES: sources, + BODY: path.node.body, + EXPORT_IDENTIFIER: exportIdent, + CONTEXT_IDENTIFIER: contextIdent + })]; + } + } + } + }; +}; + +var _babelHelperHoistVariables = require("babel-helper-hoist-variables"); + +var _babelHelperHoistVariables2 = _interopRequireDefault(_babelHelperHoistVariables); + +var _babelTemplate = require("babel-template"); + +var _babelTemplate2 = _interopRequireDefault(_babelTemplate); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var buildTemplate = (0, _babelTemplate2.default)("\n SYSTEM_REGISTER(MODULE_NAME, [SOURCES], function (EXPORT_IDENTIFIER, CONTEXT_IDENTIFIER) {\n \"use strict\";\n BEFORE_BODY;\n return {\n setters: [SETTERS],\n execute: function () {\n BODY;\n }\n };\n });\n"); + +var buildExportAll = (0, _babelTemplate2.default)("\n for (var KEY in TARGET) {\n if (KEY !== \"default\" && KEY !== \"__esModule\") EXPORT_OBJ[KEY] = TARGET[KEY];\n }\n"); + +module.exports = exports["default"]; +},{"babel-helper-hoist-variables":68,"babel-runtime/core-js/get-iterator":138,"babel-runtime/core-js/object/create":143,"babel-runtime/core-js/symbol":147,"babel-template":156}],109:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +exports.default = function (_ref) { + var t = _ref.types; + + function isValidDefine(path) { + if (!path.isExpressionStatement()) return; + + var expr = path.get("expression"); + if (!expr.isCallExpression()) return false; + if (!expr.get("callee").isIdentifier({ name: "define" })) return false; + + var args = expr.get("arguments"); + if (args.length === 3 && !args.shift().isStringLiteral()) return false; + if (args.length !== 2) return false; + if (!args.shift().isArrayExpression()) return false; + if (!args.shift().isFunctionExpression()) return false; + + return true; + } + + return { + inherits: require("babel-plugin-transform-es2015-modules-amd"), + + visitor: { + Program: { + exit: function exit(path, state) { + var last = path.get("body").pop(); + if (!isValidDefine(last)) return; + + var call = last.node.expression; + var args = call.arguments; + + var moduleName = args.length === 3 ? args.shift() : null; + var amdArgs = call.arguments[0]; + var func = call.arguments[1]; + var browserGlobals = state.opts.globals || {}; + + var commonArgs = amdArgs.elements.map(function (arg) { + if (arg.value === "module" || arg.value === "exports") { + return t.identifier(arg.value); + } else { + return t.callExpression(t.identifier("require"), [arg]); + } + }); + + var browserArgs = amdArgs.elements.map(function (arg) { + if (arg.value === "module") { + return t.identifier("mod"); + } else if (arg.value === "exports") { + return t.memberExpression(t.identifier("mod"), t.identifier("exports")); + } else { + var memberExpression = void 0; + + if (state.opts.exactGlobals) { + var globalRef = browserGlobals[arg.value]; + if (globalRef) { + memberExpression = globalRef.split(".").reduce(function (accum, curr) { + return t.memberExpression(accum, t.identifier(curr)); + }, t.identifier("global")); + } else { + memberExpression = t.memberExpression(t.identifier("global"), t.identifier(t.toIdentifier(arg.value))); + } + } else { + var requireName = (0, _path.basename)(arg.value, (0, _path.extname)(arg.value)); + var globalName = browserGlobals[requireName] || requireName; + memberExpression = t.memberExpression(t.identifier("global"), t.identifier(t.toIdentifier(globalName))); + } + + return memberExpression; + } + }); + + var moduleNameOrBasename = moduleName ? moduleName.value : this.file.opts.basename; + var globalToAssign = t.memberExpression(t.identifier("global"), t.identifier(t.toIdentifier(moduleNameOrBasename))); + var prerequisiteAssignments = null; + + if (state.opts.exactGlobals) { + var globalName = browserGlobals[moduleNameOrBasename]; + + if (globalName) { + prerequisiteAssignments = []; + + var members = globalName.split("."); + globalToAssign = members.slice(1).reduce(function (accum, curr) { + prerequisiteAssignments.push(buildPrerequisiteAssignment({ GLOBAL_REFERENCE: accum })); + return t.memberExpression(accum, t.identifier(curr)); + }, t.memberExpression(t.identifier("global"), t.identifier(members[0]))); + } + } + + var globalExport = buildGlobalExport({ + BROWSER_ARGUMENTS: browserArgs, + PREREQUISITE_ASSIGNMENTS: prerequisiteAssignments, + GLOBAL_TO_ASSIGN: globalToAssign + }); + + last.replaceWith(buildWrapper({ + MODULE_NAME: moduleName, + AMD_ARGUMENTS: amdArgs, + COMMON_ARGUMENTS: commonArgs, + GLOBAL_EXPORT: globalExport, + FUNC: func + })); + } + } + } + }; +}; + +var _path = require("path"); + +var _babelTemplate = require("babel-template"); + +var _babelTemplate2 = _interopRequireDefault(_babelTemplate); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/* eslint max-len: 0 */ + +var buildPrerequisiteAssignment = (0, _babelTemplate2.default)("\n GLOBAL_REFERENCE = GLOBAL_REFERENCE || {}\n"); + +var buildGlobalExport = (0, _babelTemplate2.default)("\n var mod = { exports: {} };\n factory(BROWSER_ARGUMENTS);\n PREREQUISITE_ASSIGNMENTS\n GLOBAL_TO_ASSIGN = mod.exports;\n"); + +var buildWrapper = (0, _babelTemplate2.default)("\n (function (global, factory) {\n if (typeof define === \"function\" && define.amd) {\n define(MODULE_NAME, AMD_ARGUMENTS, factory);\n } else if (typeof exports !== \"undefined\") {\n factory(COMMON_ARGUMENTS);\n } else {\n GLOBAL_EXPORT\n }\n })(this, FUNC);\n"); + +module.exports = exports["default"]; +},{"babel-plugin-transform-es2015-modules-amd":106,"babel-template":156,"path":589}],110:[function(require,module,exports){ +/*istanbul ignore next*/"use strict"; + +exports.__esModule = true; + +var _getIterator2 = require("babel-runtime/core-js/get-iterator"); + +var _getIterator3 = _interopRequireDefault(_getIterator2); + +var _symbol = require("babel-runtime/core-js/symbol"); + +var _symbol2 = _interopRequireDefault(_symbol); + +exports.default = function ( /*istanbul ignore next*/_ref) { + /*istanbul ignore next*/var t = _ref.types; + + function Property(path, node, scope, getObjectRef, file) { + var replaceSupers = new /*istanbul ignore next*/_babelHelperReplaceSupers2.default({ + getObjectRef: getObjectRef, + methodNode: node, + methodPath: path, + isStatic: true, + scope: scope, + file: file + }); + + replaceSupers.replace(); + } + + var CONTAINS_SUPER = /*istanbul ignore next*/(0, _symbol2.default)(); + + return { + visitor: { /*istanbul ignore next*/ + Super: function Super(path) { + var parentObj = path.findParent(function (path) /*istanbul ignore next*/{ + return path.isObjectExpression(); + }); + if (parentObj) parentObj.node[CONTAINS_SUPER] = true; + }, + + + ObjectExpression: { /*istanbul ignore next*/ + exit: function exit(path, file) { + if (!path.node[CONTAINS_SUPER]) return; + + var objectRef = /*istanbul ignore next*/void 0; + var getObjectRef = function getObjectRef() /*istanbul ignore next*/{ + return objectRef = objectRef || path.scope.generateUidIdentifier("obj"); + }; + + var propPaths = path.get("properties"); + for ( /*istanbul ignore next*/var _iterator = propPaths, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { + /*istanbul ignore next*/ + var _ref2; + + if (_isArray) { + if (_i >= _iterator.length) break; + _ref2 = _iterator[_i++]; + } else { + _i = _iterator.next(); + if (_i.done) break; + _ref2 = _i.value; + } + + var propPath = _ref2; + + if (propPath.isObjectProperty()) propPath = propPath.get("value"); + Property(propPath, propPath.node, path.scope, getObjectRef, file); + } + + if (objectRef) { + path.scope.push({ id: objectRef }); + path.replaceWith(t.assignmentExpression("=", objectRef, path.node)); + } + } + } + } + }; +}; + +var /*istanbul ignore next*/_babelHelperReplaceSupers = require("babel-helper-replace-supers"); + +/*istanbul ignore next*/ +var _babelHelperReplaceSupers2 = _interopRequireDefault(_babelHelperReplaceSupers); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +module.exports = exports["default"]; +},{"babel-helper-replace-supers":73,"babel-runtime/core-js/get-iterator":138,"babel-runtime/core-js/symbol":147}],111:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; +exports.visitor = undefined; + +var _getIterator2 = require("babel-runtime/core-js/get-iterator"); + +var _getIterator3 = _interopRequireDefault(_getIterator2); + +var _babelHelperGetFunctionArity = require("babel-helper-get-function-arity"); + +var _babelHelperGetFunctionArity2 = _interopRequireDefault(_babelHelperGetFunctionArity); + +var _babelHelperCallDelegate = require("babel-helper-call-delegate"); + +var _babelHelperCallDelegate2 = _interopRequireDefault(_babelHelperCallDelegate); + +var _babelTemplate = require("babel-template"); + +var _babelTemplate2 = _interopRequireDefault(_babelTemplate); + +var _babelTypes = require("babel-types"); + +var t = _interopRequireWildcard(_babelTypes); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var buildDefaultParam = (0, _babelTemplate2.default)("\n let VARIABLE_NAME =\n ARGUMENTS.length > ARGUMENT_KEY && ARGUMENTS[ARGUMENT_KEY] !== undefined ?\n ARGUMENTS[ARGUMENT_KEY]\n :\n DEFAULT_VALUE;\n"); + +var buildCutOff = (0, _babelTemplate2.default)("\n let $0 = $1[$2];\n"); + +function hasDefaults(node) { + for (var _iterator = node.params, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_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 param = _ref; + + if (!t.isIdentifier(param)) return true; + } + return false; +} + +var iifeVisitor = { + ReferencedIdentifier: function ReferencedIdentifier(path, state) { + var name = path.node.name; + if (name === "eval" || path.scope.hasOwnBinding(name) && path.scope.getOwnBinding(name).kind !== "param") { + state.iife = true; + path.stop(); + } + }, + Scope: function Scope(path) { + path.skip(); + } +}; + +var visitor = exports.visitor = { + Function: function Function(path) { + var node = path.node; + var scope = path.scope; + + if (!hasDefaults(node)) return; + + path.ensureBlock(); + + var state = { + iife: false, + scope: scope + }; + + var body = []; + + var argsIdentifier = t.identifier("arguments"); + argsIdentifier._shadowedFunctionLiteral = path; + + function pushDefNode(left, right, i) { + var defNode = buildDefaultParam({ + VARIABLE_NAME: left, + DEFAULT_VALUE: right, + ARGUMENT_KEY: t.numericLiteral(i), + ARGUMENTS: argsIdentifier + }); + defNode._blockHoist = node.params.length - i; + body.push(defNode); + } + + var lastNonDefaultParam = (0, _babelHelperGetFunctionArity2.default)(node); + + var params = path.get("params"); + for (var i = 0; i < params.length; i++) { + var param = params[i]; + + if (!param.isAssignmentPattern()) { + if (!state.iife && !param.isIdentifier()) { + param.traverse(iifeVisitor, state); + } + + continue; + } + + var left = param.get("left"); + var right = param.get("right"); + + if (i >= lastNonDefaultParam || left.isPattern()) { + var placeholder = scope.generateUidIdentifier("x"); + placeholder._isDefaultPlaceholder = true; + node.params[i] = placeholder; + } else { + node.params[i] = left.node; + } + + if (!state.iife) { + if (right.isIdentifier() && scope.hasOwnBinding(right.node.name) && scope.getOwnBinding(right.node.name).kind !== "param") { + state.iife = true; + } else { + right.traverse(iifeVisitor, state); + } + } + + pushDefNode(left.node, right.node, i); + } + + for (var _i2 = lastNonDefaultParam + 1; _i2 < node.params.length; _i2++) { + var _param = node.params[_i2]; + if (_param._isDefaultPlaceholder) continue; + + var declar = buildCutOff(_param, argsIdentifier, t.numericLiteral(_i2)); + declar._blockHoist = node.params.length - _i2; + body.push(declar); + } + + node.params = node.params.slice(0, lastNonDefaultParam); + + if (state.iife) { + body.push((0, _babelHelperCallDelegate2.default)(path, scope)); + path.set("body", t.blockStatement(body)); + } else { + path.get("body").unshiftContainer("body", body); + } + } +}; +},{"babel-helper-call-delegate":62,"babel-helper-get-function-arity":67,"babel-runtime/core-js/get-iterator":138,"babel-template":156,"babel-types":193}],112:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; +exports.visitor = undefined; + +var _babelTypes = require("babel-types"); + +var t = _interopRequireWildcard(_babelTypes); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +var visitor = exports.visitor = { + Function: function Function(path) { + var params = path.get("params"); + + var hoistTweak = t.isRestElement(params[params.length - 1]) ? 1 : 0; + var outputParamsLength = params.length - hoistTweak; + + for (var i = 0; i < outputParamsLength; i++) { + var param = params[i]; + if (param.isArrayPattern() || param.isObjectPattern()) { + var uid = path.scope.generateUidIdentifier("ref"); + + var declar = t.variableDeclaration("let", [t.variableDeclarator(param.node, uid)]); + declar._blockHoist = outputParamsLength - i; + + path.ensureBlock(); + path.get("body").unshiftContainer("body", declar); + + param.replaceWith(uid); + } + } + } +}; +},{"babel-types":193}],113:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +var _getIterator2 = require("babel-runtime/core-js/get-iterator"); + +var _getIterator3 = _interopRequireDefault(_getIterator2); + +exports.default = function () { + return { + visitor: _babelTraverse.visitors.merge([{ + ArrowFunctionExpression: function ArrowFunctionExpression(path) { + var params = path.get("params"); + for (var _iterator = params, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_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 param = _ref; + + if (param.isRestElement() || param.isAssignmentPattern()) { + path.arrowFunctionToShadowed(); + break; + } + } + } + }, destructuring.visitor, rest.visitor, def.visitor]) + }; +}; + +var _babelTraverse = require("babel-traverse"); + +var _destructuring = require("./destructuring"); + +var destructuring = _interopRequireWildcard(_destructuring); + +var _default = require("./default"); + +var def = _interopRequireWildcard(_default); + +var _rest = require("./rest"); + +var rest = _interopRequireWildcard(_rest); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +module.exports = exports["default"]; +},{"./default":111,"./destructuring":112,"./rest":114,"babel-runtime/core-js/get-iterator":138,"babel-traverse":160}],114:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; +exports.visitor = undefined; + +var _getIterator2 = require("babel-runtime/core-js/get-iterator"); + +var _getIterator3 = _interopRequireDefault(_getIterator2); + +var _babelTemplate = require("babel-template"); + +var _babelTemplate2 = _interopRequireDefault(_babelTemplate); + +var _babelTypes = require("babel-types"); + +var t = _interopRequireWildcard(_babelTypes); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var buildRest = (0, _babelTemplate2.default)("\n for (var LEN = ARGUMENTS.length,\n ARRAY = Array(ARRAY_LEN),\n KEY = START;\n KEY < LEN;\n KEY++) {\n ARRAY[ARRAY_KEY] = ARGUMENTS[KEY];\n }\n"); + +var restIndex = (0, _babelTemplate2.default)("\n ARGUMENTS.length <= INDEX ? undefined : ARGUMENTS[INDEX]\n"); + +var restLength = (0, _babelTemplate2.default)("\n ARGUMENTS.length <= OFFSET ? 0 : ARGUMENTS.length - OFFSET\n"); + +var memberExpressionOptimisationVisitor = { + Scope: function Scope(path, state) { + if (!path.scope.bindingIdentifierEquals(state.name, state.outerBinding)) { + path.skip(); + } + }, + Flow: function Flow(path) { + path.skip(); + }, + + + "Function|ClassProperty": function FunctionClassProperty(path, state) { + var oldNoOptimise = state.noOptimise; + state.noOptimise = true; + path.traverse(memberExpressionOptimisationVisitor, state); + state.noOptimise = oldNoOptimise; + + path.skip(); + }, + + ReferencedIdentifier: function ReferencedIdentifier(path, state) { + var node = path.node; + + if (node.name === "arguments") { + state.deopted = true; + } + + if (node.name !== state.name) return; + + if (state.noOptimise) { + state.deopted = true; + } else { + var parentPath = path.parentPath; + + if (parentPath.isMemberExpression({ object: node })) { + var grandparentPath = parentPath.parentPath; + + var argsOptEligible = !state.deopted && !(grandparentPath.isAssignmentExpression() && parentPath.node === grandparentPath.node.left || grandparentPath.isLVal() || grandparentPath.isForXStatement() || grandparentPath.isUpdateExpression() || grandparentPath.isUnaryExpression({ operator: "delete" }) || (grandparentPath.isCallExpression() || grandparentPath.isNewExpression()) && parentPath.node === grandparentPath.node.callee); + + if (argsOptEligible) { + if (parentPath.node.computed) { + if (parentPath.get("property").isBaseType("number")) { + state.candidates.push({ cause: "indexGetter", path: path }); + return; + } + } else if (parentPath.node.property.name === "length") { + state.candidates.push({ cause: "lengthGetter", path: path }); + return; + } + } + } + + if (state.offset === 0 && parentPath.isSpreadElement()) { + var call = parentPath.parentPath; + if (call.isCallExpression() && call.node.arguments.length === 1) { + state.candidates.push({ cause: "argSpread", path: path }); + return; + } + } + + state.references.push(path); + } + }, + BindingIdentifier: function BindingIdentifier(_ref, state) { + var node = _ref.node; + + if (node.name === state.name) { + state.deopted = true; + } + } +}; +function hasRest(node) { + return t.isRestElement(node.params[node.params.length - 1]); +} + +function optimiseIndexGetter(path, argsId, offset) { + var index = void 0; + + if (t.isNumericLiteral(path.parent.property)) { + index = t.numericLiteral(path.parent.property.value + offset); + } else { + index = t.binaryExpression("+", path.parent.property, t.numericLiteral(offset)); + } + + path.parentPath.replaceWith(restIndex({ + ARGUMENTS: argsId, + INDEX: index + })); +} + +function optimiseLengthGetter(path, argsId, offset) { + if (offset) { + path.parentPath.replaceWith(restLength({ + ARGUMENTS: argsId, + OFFSET: t.numericLiteral(offset) + })); + } else { + path.replaceWith(argsId); + } +} + +var visitor = exports.visitor = { + Function: function Function(path) { + var node = path.node; + var scope = path.scope; + + if (!hasRest(node)) return; + + var rest = node.params.pop().argument; + + var argsId = t.identifier("arguments"); + + argsId._shadowedFunctionLiteral = path; + + var state = { + references: [], + offset: node.params.length, + + argumentsNode: argsId, + outerBinding: scope.getBindingIdentifier(rest.name), + + candidates: [], + + name: rest.name, + + deopted: false + }; + + path.traverse(memberExpressionOptimisationVisitor, state); + + if (!state.deopted && !state.references.length) { + for (var _iterator = state.candidates, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { + var _ref2; + + if (_isArray) { + if (_i >= _iterator.length) break; + _ref2 = _iterator[_i++]; + } else { + _i = _iterator.next(); + if (_i.done) break; + _ref2 = _i.value; + } + + var _ref3 = _ref2; + var _path = _ref3.path; + var cause = _ref3.cause; + + switch (cause) { + case "indexGetter": + optimiseIndexGetter(_path, argsId, state.offset); + break; + case "lengthGetter": + optimiseLengthGetter(_path, argsId, state.offset); + break; + default: + _path.replaceWith(argsId); + } + } + return; + } + + state.references = state.references.concat(state.candidates.map(function (_ref4) { + var path = _ref4.path; + return path; + })); + + state.deopted = state.deopted || !!node.shadow; + + var start = t.numericLiteral(node.params.length); + var key = scope.generateUidIdentifier("key"); + var len = scope.generateUidIdentifier("len"); + + var arrKey = key; + var arrLen = len; + if (node.params.length) { + arrKey = t.binaryExpression("-", key, start); + + arrLen = t.conditionalExpression(t.binaryExpression(">", len, start), t.binaryExpression("-", len, start), t.numericLiteral(0)); + } + + var loop = buildRest({ + ARGUMENTS: argsId, + ARRAY_KEY: arrKey, + ARRAY_LEN: arrLen, + START: start, + ARRAY: rest, + KEY: key, + LEN: len + }); + + if (state.deopted) { + loop._blockHoist = node.params.length + 1; + node.body.body.unshift(loop); + } else { + loop._blockHoist = 1; + + var target = path.getEarliestCommonAncestorFrom(state.references).getStatementParent(); + + target.findParent(function (path) { + if (path.isLoop()) { + target = path; + } else { + return path.isFunction(); + } + }); + + target.insertBefore(loop); + } + } +}; +},{"babel-runtime/core-js/get-iterator":138,"babel-template":156,"babel-types":193}],115:[function(require,module,exports){ +/*istanbul ignore next*/"use strict"; + +exports.__esModule = true; + +exports.default = function () { + return { + visitor: { /*istanbul ignore next*/ + ObjectMethod: function ObjectMethod(path) { + /*istanbul ignore next*/var node = path.node; + + if (node.kind === "method") { + path.replaceWith(t.objectProperty(node.key, t.functionExpression(null, node.params, node.body, node.generator, node.async), node.computed)); + } + }, + /*istanbul ignore next*/ObjectProperty: function ObjectProperty(_ref) { + /*istanbul ignore next*/var node = _ref.node; + + if (node.shorthand) { + node.shorthand = false; + } + } + } + }; +}; + +var /*istanbul ignore next*/_babelTypes = require("babel-types"); + +/*istanbul ignore next*/ +var t = _interopRequireWildcard(_babelTypes); + +/*istanbul ignore next*/ +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +module.exports = exports["default"]; +},{"babel-types":193}],116:[function(require,module,exports){ +/*istanbul ignore next*/"use strict"; + +exports.__esModule = true; + +var _getIterator2 = require("babel-runtime/core-js/get-iterator"); + +var _getIterator3 = _interopRequireDefault(_getIterator2); + +exports.default = function ( /*istanbul ignore next*/_ref) { + /*istanbul ignore next*/var t = _ref.types; + + function getSpreadLiteral(spread, scope, state) { + if (state.opts.loose && !t.isIdentifier(spread.argument, { name: "arguments" })) { + return spread.argument; + } else { + return scope.toArray(spread.argument, true); + } + } + + function hasSpread(nodes) { + for (var i = 0; i < nodes.length; i++) { + if (t.isSpreadElement(nodes[i])) { + return true; + } + } + return false; + } + + function build(props, scope, state) { + var nodes = []; + + var _props = []; + + function push() { + if (!_props.length) return; + nodes.push(t.arrayExpression(_props)); + _props = []; + } + + for ( /*istanbul ignore next*/var _iterator = props, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { + /*istanbul ignore next*/ + var _ref2; + + if (_isArray) { + if (_i >= _iterator.length) break; + _ref2 = _iterator[_i++]; + } else { + _i = _iterator.next(); + if (_i.done) break; + _ref2 = _i.value; + } + + var prop = _ref2; + + if (t.isSpreadElement(prop)) { + push(); + nodes.push(getSpreadLiteral(prop, scope, state)); + } else { + _props.push(prop); + } + } + + push(); + + return nodes; + } + + return { + visitor: { /*istanbul ignore next*/ + ArrayExpression: function ArrayExpression(path, state) { + /*istanbul ignore next*/var node = path.node; + /*istanbul ignore next*/var scope = path.scope; + + var elements = node.elements; + if (!hasSpread(elements)) return; + + var nodes = build(elements, scope, state); + var first = nodes.shift(); + + if (!t.isArrayExpression(first)) { + nodes.unshift(first); + first = t.arrayExpression([]); + } + + path.replaceWith(t.callExpression(t.memberExpression(first, t.identifier("concat")), nodes)); + }, + /*istanbul ignore next*/CallExpression: function CallExpression(path, state) { + /*istanbul ignore next*/var node = path.node; + /*istanbul ignore next*/var scope = path.scope; + + + var args = node.arguments; + if (!hasSpread(args)) return; + + var calleePath = path.get("callee"); + if (calleePath.isSuper()) return; + + var contextLiteral = t.identifier("undefined"); + + node.arguments = []; + + var nodes = /*istanbul ignore next*/void 0; + if (args.length === 1 && args[0].argument.name === "arguments") { + nodes = [args[0].argument]; + } else { + nodes = build(args, scope, state); + } + + var first = nodes.shift(); + if (nodes.length) { + node.arguments.push(t.callExpression(t.memberExpression(first, t.identifier("concat")), nodes)); + } else { + node.arguments.push(first); + } + + var callee = node.callee; + + if (calleePath.isMemberExpression()) { + var temp = scope.maybeGenerateMemoised(callee.object); + if (temp) { + callee.object = t.assignmentExpression("=", temp, callee.object); + contextLiteral = temp; + } else { + contextLiteral = callee.object; + } + t.appendToMemberExpression(callee, t.identifier("apply")); + } else { + node.callee = t.memberExpression(node.callee, t.identifier("apply")); + } + + if (t.isSuper(contextLiteral)) { + contextLiteral = t.thisExpression(); + } + + node.arguments.unshift(contextLiteral); + }, + /*istanbul ignore next*/NewExpression: function NewExpression(path, state) { + /*istanbul ignore next*/var node = path.node; + /*istanbul ignore next*/var scope = path.scope; + + var args = node.arguments; + if (!hasSpread(args)) return; + + var nodes = build(args, scope, state); + + var context = t.arrayExpression([t.nullLiteral()]); + + args = t.callExpression(t.memberExpression(context, t.identifier("concat")), nodes); + + path.replaceWith(t.newExpression(t.callExpression(t.memberExpression(t.memberExpression(t.memberExpression(t.identifier("Function"), t.identifier("prototype")), t.identifier("bind")), t.identifier("apply")), [node.callee, args]), [])); + } + } + }; +}; + +/*istanbul ignore next*/ +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +module.exports = exports["default"]; +},{"babel-runtime/core-js/get-iterator":138}],117:[function(require,module,exports){ +/*istanbul ignore next*/"use strict"; + +exports.__esModule = true; + +exports.default = function () { + return { + visitor: { /*istanbul ignore next*/ + RegExpLiteral: function RegExpLiteral(path) { + /*istanbul ignore next*/var node = path.node; + + if (!regex.is(node, "y")) return; + + path.replaceWith(t.newExpression(t.identifier("RegExp"), [t.stringLiteral(node.pattern), t.stringLiteral(node.flags)])); + } + } + }; +}; + +var /*istanbul ignore next*/_babelHelperRegex = require("babel-helper-regex"); + +/*istanbul ignore next*/ +var regex = _interopRequireWildcard(_babelHelperRegex); + +var /*istanbul ignore next*/_babelTypes = require("babel-types"); + +/*istanbul ignore next*/ +var t = _interopRequireWildcard(_babelTypes); + +/*istanbul ignore next*/ +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +module.exports = exports["default"]; +},{"babel-helper-regex":70,"babel-types":193}],118:[function(require,module,exports){ +/*istanbul ignore next*/"use strict"; + +exports.__esModule = true; + +var _getIterator2 = require("babel-runtime/core-js/get-iterator"); + +var _getIterator3 = _interopRequireDefault(_getIterator2); + +exports.default = function ( /*istanbul ignore next*/_ref) { + /*istanbul ignore next*/var t = _ref.types; + + function isString(node) { + return t.isLiteral(node) && typeof node.value === "string"; + } + + function buildBinaryExpression(left, right) { + return t.binaryExpression("+", left, right); + } + + return { + visitor: { /*istanbul ignore next*/ + TaggedTemplateExpression: function TaggedTemplateExpression(path, state) { + /*istanbul ignore next*/var node = path.node; + + var quasi = node.quasi; + var args = []; + + var strings = []; + var raw = []; + + for ( /*istanbul ignore next*/var _iterator = quasi.quasis, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { + /*istanbul ignore next*/ + var _ref2; + + if (_isArray) { + if (_i >= _iterator.length) break; + _ref2 = _iterator[_i++]; + } else { + _i = _iterator.next(); + if (_i.done) break; + _ref2 = _i.value; + } + + var elem = _ref2; + + strings.push(t.stringLiteral(elem.value.cooked)); + raw.push(t.stringLiteral(elem.value.raw)); + } + + strings = t.arrayExpression(strings); + raw = t.arrayExpression(raw); + + var templateName = "taggedTemplateLiteral"; + if (state.opts.loose) templateName += "Loose"; + + var templateObject = state.file.addTemplateObject(templateName, strings, raw); + args.push(templateObject); + + args = args.concat(quasi.expressions); + + path.replaceWith(t.callExpression(node.tag, args)); + }, + /*istanbul ignore next*/TemplateLiteral: function TemplateLiteral(path, state) { + var nodes = []; + + var expressions = path.get("expressions"); + + for ( /*istanbul ignore next*/var _iterator2 = path.node.quasis, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : (0, _getIterator3.default)(_iterator2);;) { + /*istanbul ignore next*/ + var _ref3; + + if (_isArray2) { + if (_i2 >= _iterator2.length) break; + _ref3 = _iterator2[_i2++]; + } else { + _i2 = _iterator2.next(); + if (_i2.done) break; + _ref3 = _i2.value; + } + + var elem = _ref3; + + nodes.push(t.stringLiteral(elem.value.cooked)); + + var expr = expressions.shift(); + if (expr) { + if (state.opts.spec && !expr.isBaseType("string") && !expr.isBaseType("number")) { + nodes.push(t.callExpression(t.identifier("String"), [expr.node])); + } else { + nodes.push(expr.node); + } + } + } + + // filter out empty string literals + nodes = nodes.filter(function (n) /*istanbul ignore next*/{ + return !t.isLiteral(n, { value: "" }); + }); + + // since `+` is left-to-right associative + // ensure the first node is a string if first/second isn't + if (!isString(nodes[0]) && !isString(nodes[1])) { + nodes.unshift(t.stringLiteral("")); + } + + if (nodes.length > 1) { + var root = buildBinaryExpression(nodes.shift(), nodes.shift()); + + for ( /*istanbul ignore next*/var _iterator3 = nodes, _isArray3 = Array.isArray(_iterator3), _i3 = 0, _iterator3 = _isArray3 ? _iterator3 : (0, _getIterator3.default)(_iterator3);;) { + /*istanbul ignore next*/ + var _ref4; + + if (_isArray3) { + if (_i3 >= _iterator3.length) break; + _ref4 = _iterator3[_i3++]; + } else { + _i3 = _iterator3.next(); + if (_i3.done) break; + _ref4 = _i3.value; + } + + var node = _ref4; + + root = buildBinaryExpression(root, node); + } + + path.replaceWith(root); + } else { + path.replaceWith(nodes[0]); + } + } + } + }; +}; + +/*istanbul ignore next*/ +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +module.exports = exports["default"]; +},{"babel-runtime/core-js/get-iterator":138}],119:[function(require,module,exports){ +/*istanbul ignore next*/"use strict"; + +exports.__esModule = true; + +var _symbol = require("babel-runtime/core-js/symbol"); + +var _symbol2 = _interopRequireDefault(_symbol); + +exports.default = function ( /*istanbul ignore next*/_ref) { + /*istanbul ignore next*/var t = _ref.types; + + var IGNORE = /*istanbul ignore next*/(0, _symbol2.default)(); + + return { + visitor: { /*istanbul ignore next*/ + Scope: function Scope(_ref2) { + /*istanbul ignore next*/var scope = _ref2.scope; + + if (!scope.getBinding("Symbol")) { + return; + } + + scope.rename("Symbol"); + }, + /*istanbul ignore next*/UnaryExpression: function UnaryExpression(path) { + /*istanbul ignore next*/var node = path.node; + /*istanbul ignore next*/var parent = path.parent; + + if (node[IGNORE]) return; + if (path.find(function (path) /*istanbul ignore next*/{ + return path.node && !!path.node._generated; + })) return; + + if (path.parentPath.isBinaryExpression() && t.EQUALITY_BINARY_OPERATORS.indexOf(parent.operator) >= 0) { + // optimise `typeof foo === "string"` since we can determine that they'll never need to handle symbols + var opposite = path.getOpposite(); + if (opposite.isLiteral() && opposite.node.value !== "symbol" && opposite.node.value !== "object") { + return; + } + } + + if (node.operator === "typeof") { + var call = t.callExpression(this.addHelper("typeof"), [node.argument]); + if (path.get("argument").isIdentifier()) { + var undefLiteral = t.stringLiteral("undefined"); + var unary = t.unaryExpression("typeof", node.argument); + unary[IGNORE] = true; + path.replaceWith(t.conditionalExpression(t.binaryExpression("===", unary, undefLiteral), undefLiteral, call)); + } else { + path.replaceWith(call); + } + } + } + } + }; +}; + +/*istanbul ignore next*/ +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +module.exports = exports["default"]; /* eslint max-len: 0 */ +},{"babel-runtime/core-js/symbol":147}],120:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +exports.default = function () { + return { + visitor: { + RegExpLiteral: function RegExpLiteral(_ref) { + var node = _ref.node; + + if (!regex.is(node, "u")) return; + node.pattern = (0, _regexpuCore2.default)(node.pattern, node.flags); + regex.pullFlag(node, "u"); + } + } + }; +}; + +var _regexpuCore = require("regexpu-core"); + +var _regexpuCore2 = _interopRequireDefault(_regexpuCore); + +var _babelHelperRegex = require("babel-helper-regex"); + +var regex = _interopRequireWildcard(_babelHelperRegex); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +module.exports = exports["default"]; +},{"babel-helper-regex":70,"regexpu-core":665}],121:[function(require,module,exports){ +/*istanbul ignore next*/"use strict"; + +exports.__esModule = true; + +exports.default = function ( /*istanbul ignore next*/_ref) { + /*istanbul ignore next*/var t = _ref.types; + + return { + inherits: require("babel-plugin-syntax-exponentiation-operator"), + + visitor: /*istanbul ignore next*/(0, _babelHelperBuilderBinaryAssignmentOperatorVisitor2.default)({ + operator: "**", + + /*istanbul ignore next*/build: function build(left, right) { + return t.callExpression(t.memberExpression(t.identifier("Math"), t.identifier("pow")), [left, right]); + } + }) + }; +}; + +var /*istanbul ignore next*/_babelHelperBuilderBinaryAssignmentOperatorVisitor = require("babel-helper-builder-binary-assignment-operator-visitor"); + +/*istanbul ignore next*/ +var _babelHelperBuilderBinaryAssignmentOperatorVisitor2 = _interopRequireDefault(_babelHelperBuilderBinaryAssignmentOperatorVisitor); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +module.exports = exports["default"]; +},{"babel-helper-builder-binary-assignment-operator-visitor":61,"babel-plugin-syntax-exponentiation-operator":83}],122:[function(require,module,exports){ +/*istanbul ignore next*/"use strict"; + +exports.__esModule = true; + +exports.default = function ( /*istanbul ignore next*/_ref) { + /*istanbul ignore next*/var t = _ref.types; + + function build(node, nodes, scope) { + var first = node.specifiers[0]; + if (!t.isExportNamespaceSpecifier(first) && !t.isExportDefaultSpecifier(first)) return; + + var specifier = node.specifiers.shift(); + var uid = scope.generateUidIdentifier(specifier.exported.name); + + var newSpecifier = /*istanbul ignore next*/void 0; + if (t.isExportNamespaceSpecifier(specifier)) { + newSpecifier = t.importNamespaceSpecifier(uid); + } else { + newSpecifier = t.importDefaultSpecifier(uid); + } + + nodes.push(t.importDeclaration([newSpecifier], node.source)); + nodes.push(t.exportNamedDeclaration(null, [t.exportSpecifier(uid, specifier.exported)])); + + build(node, nodes, scope); + } + + return { + inherits: require("babel-plugin-syntax-export-extensions"), + + visitor: { /*istanbul ignore next*/ + ExportNamedDeclaration: function ExportNamedDeclaration(path) { + /*istanbul ignore next*/var node = path.node; + /*istanbul ignore next*/var scope = path.scope; + + var nodes = []; + build(node, nodes, scope); + if (!nodes.length) return; + + if (node.specifiers.length >= 1) { + nodes.push(node); + } + path.replaceWithMultiple(nodes); + } + } + }; +}; + +/*istanbul ignore next*/module.exports = exports["default"]; +},{"babel-plugin-syntax-export-extensions":84}],123:[function(require,module,exports){ +/*istanbul ignore next*/"use strict"; + +exports.__esModule = true; + +exports.default = function ( /*istanbul ignore next*/_ref) { + /*istanbul ignore next*/var t = _ref.types; + + function getTempId(scope) { + var id = scope.path.getData("functionBind"); + if (id) return id; + + id = scope.generateDeclaredUidIdentifier("context"); + return scope.path.setData("functionBind", id); + } + + function getStaticContext(bind, scope) { + var object = bind.object || bind.callee.object; + return scope.isStatic(object) && object; + } + + function inferBindContext(bind, scope) { + var staticContext = getStaticContext(bind, scope); + if (staticContext) return staticContext; + + var tempId = getTempId(scope); + if (bind.object) { + bind.callee = t.sequenceExpression([t.assignmentExpression("=", tempId, bind.object), bind.callee]); + } else { + bind.callee.object = t.assignmentExpression("=", tempId, bind.callee.object); + } + return tempId; + } + + return { + inherits: require("babel-plugin-syntax-function-bind"), + + visitor: { /*istanbul ignore next*/ + CallExpression: function CallExpression(_ref2) { + /*istanbul ignore next*/var node = _ref2.node; + /*istanbul ignore next*/var scope = _ref2.scope; + + var bind = node.callee; + if (!t.isBindExpression(bind)) return; + + var context = inferBindContext(bind, scope); + node.callee = t.memberExpression(bind.callee, t.identifier("call")); + node.arguments.unshift(context); + }, + /*istanbul ignore next*/BindExpression: function BindExpression(path) { + /*istanbul ignore next*/var node = path.node; + /*istanbul ignore next*/var scope = path.scope; + + var context = inferBindContext(node, scope); + path.replaceWith(t.callExpression(t.memberExpression(node.callee, t.identifier("bind")), [context])); + } + } + }; +}; + +/*istanbul ignore next*/module.exports = exports["default"]; +},{"babel-plugin-syntax-function-bind":85}],124:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +var _getIterator2 = require("babel-runtime/core-js/get-iterator"); + +var _getIterator3 = _interopRequireDefault(_getIterator2); + +exports.default = function (_ref) { + var t = _ref.types; + + function hasSpread(node) { + for (var _iterator = node.properties, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { + var _ref2; + + if (_isArray) { + if (_i >= _iterator.length) break; + _ref2 = _iterator[_i++]; + } else { + _i = _iterator.next(); + if (_i.done) break; + _ref2 = _i.value; + } + + var prop = _ref2; + + if (t.isSpreadProperty(prop)) { + return true; + } + } + return false; + } + + return { + inherits: require("babel-plugin-syntax-object-rest-spread"), + + visitor: { + ObjectExpression: function ObjectExpression(path, file) { + if (!hasSpread(path.node)) return; + + var useBuiltIns = file.opts.useBuiltIns || false; + if (typeof useBuiltIns !== "boolean") { + throw new Error("transform-object-rest-spread currently only accepts a boolean option for useBuiltIns (defaults to false)"); + } + + var args = []; + var props = []; + + function push() { + if (!props.length) return; + args.push(t.objectExpression(props)); + props = []; + } + + for (var _iterator2 = path.node.properties, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : (0, _getIterator3.default)(_iterator2);;) { + var _ref3; + + if (_isArray2) { + if (_i2 >= _iterator2.length) break; + _ref3 = _iterator2[_i2++]; + } else { + _i2 = _iterator2.next(); + if (_i2.done) break; + _ref3 = _i2.value; + } + + var prop = _ref3; + + if (t.isSpreadProperty(prop)) { + push(); + args.push(prop.argument); + } else { + props.push(prop); + } + } + + push(); + + if (!t.isObjectExpression(args[0])) { + args.unshift(t.objectExpression([])); + } + + var helper = useBuiltIns ? t.memberExpression(t.identifier("Object"), t.identifier("assign")) : file.addHelper("extends"); + + path.replaceWith(t.callExpression(helper, args)); + } + } + }; +}; + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +module.exports = exports["default"]; +},{"babel-plugin-syntax-object-rest-spread":86,"babel-runtime/core-js/get-iterator":138}],125:[function(require,module,exports){ +"use strict"; + +var _typeof2 = require("babel-runtime/helpers/typeof"); + +var _typeof3 = _interopRequireDefault(_typeof2); + +var _stringify = require("babel-runtime/core-js/json/stringify"); + +var _stringify2 = _interopRequireDefault(_stringify); + +var _assert = require("assert"); + +var _assert2 = _interopRequireDefault(_assert); + +var _babelTypes = require("babel-types"); + +var t = _interopRequireWildcard(_babelTypes); + +var _leap = require("./leap"); + +var leap = _interopRequireWildcard(_leap); + +var _meta = require("./meta"); + +var meta = _interopRequireWildcard(_meta); + +var _util = require("./util"); + +var util = _interopRequireWildcard(_util); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var hasOwn = Object.prototype.hasOwnProperty; + +function Emitter(contextId) { + _assert2.default.ok(this instanceof Emitter); + t.assertIdentifier(contextId); + + this.nextTempId = 0; + + this.contextId = contextId; + + this.listing = []; + + this.marked = [true]; + + this.finalLoc = loc(); + + this.tryEntries = []; + + this.leapManager = new leap.LeapManager(this); +} + +var Ep = Emitter.prototype; +exports.Emitter = Emitter; + +function loc() { + return t.numericLiteral(-1); +} + +Ep.mark = function (loc) { + t.assertLiteral(loc); + var index = this.listing.length; + if (loc.value === -1) { + loc.value = index; + } else { + _assert2.default.strictEqual(loc.value, index); + } + this.marked[index] = true; + return loc; +}; + +Ep.emit = function (node) { + if (t.isExpression(node)) { + node = t.expressionStatement(node); + } + + t.assertStatement(node); + this.listing.push(node); +}; + +Ep.emitAssign = function (lhs, rhs) { + this.emit(this.assign(lhs, rhs)); + return lhs; +}; + +Ep.assign = function (lhs, rhs) { + return t.expressionStatement(t.assignmentExpression("=", lhs, rhs)); +}; + +Ep.contextProperty = function (name, computed) { + return t.memberExpression(this.contextId, computed ? t.stringLiteral(name) : t.identifier(name), !!computed); +}; + +Ep.stop = function (rval) { + if (rval) { + this.setReturnValue(rval); + } + + this.jump(this.finalLoc); +}; + +Ep.setReturnValue = function (valuePath) { + t.assertExpression(valuePath.value); + + this.emitAssign(this.contextProperty("rval"), this.explodeExpression(valuePath)); +}; + +Ep.clearPendingException = function (tryLoc, assignee) { + t.assertLiteral(tryLoc); + + var catchCall = t.callExpression(this.contextProperty("catch", true), [tryLoc]); + + if (assignee) { + this.emitAssign(assignee, catchCall); + } else { + this.emit(catchCall); + } +}; + +Ep.jump = function (toLoc) { + this.emitAssign(this.contextProperty("next"), toLoc); + this.emit(t.breakStatement()); +}; + +Ep.jumpIf = function (test, toLoc) { + t.assertExpression(test); + t.assertLiteral(toLoc); + + this.emit(t.ifStatement(test, t.blockStatement([this.assign(this.contextProperty("next"), toLoc), t.breakStatement()]))); +}; + +Ep.jumpIfNot = function (test, toLoc) { + t.assertExpression(test); + t.assertLiteral(toLoc); + + var negatedTest = void 0; + if (t.isUnaryExpression(test) && test.operator === "!") { + negatedTest = test.argument; + } else { + negatedTest = t.unaryExpression("!", test); + } + + this.emit(t.ifStatement(negatedTest, t.blockStatement([this.assign(this.contextProperty("next"), toLoc), t.breakStatement()]))); +}; + +Ep.makeTempVar = function () { + return this.contextProperty("t" + this.nextTempId++); +}; + +Ep.getContextFunction = function (id) { + return t.functionExpression(id || null, [this.contextId], t.blockStatement([this.getDispatchLoop()]), false, false); +}; + +Ep.getDispatchLoop = function () { + var self = this; + var cases = []; + var current = void 0; + + var alreadyEnded = false; + + self.listing.forEach(function (stmt, i) { + if (self.marked.hasOwnProperty(i)) { + cases.push(t.switchCase(t.numericLiteral(i), current = [])); + alreadyEnded = false; + } + + if (!alreadyEnded) { + current.push(stmt); + if (t.isCompletionStatement(stmt)) alreadyEnded = true; + } + }); + + this.finalLoc.value = this.listing.length; + + cases.push(t.switchCase(this.finalLoc, []), t.switchCase(t.stringLiteral("end"), [t.returnStatement(t.callExpression(this.contextProperty("stop"), []))])); + + return t.whileStatement(t.numericLiteral(1), t.switchStatement(t.assignmentExpression("=", this.contextProperty("prev"), this.contextProperty("next")), cases)); +}; + +Ep.getTryLocsList = function () { + if (this.tryEntries.length === 0) { + return null; + } + + var lastLocValue = 0; + + return t.arrayExpression(this.tryEntries.map(function (tryEntry) { + var thisLocValue = tryEntry.firstLoc.value; + _assert2.default.ok(thisLocValue >= lastLocValue, "try entries out of order"); + lastLocValue = thisLocValue; + + var ce = tryEntry.catchEntry; + var fe = tryEntry.finallyEntry; + + var locs = [tryEntry.firstLoc, ce ? ce.firstLoc : null]; + + if (fe) { + locs[2] = fe.firstLoc; + locs[3] = fe.afterLoc; + } + + return t.arrayExpression(locs); + })); +}; + +Ep.explode = function (path, ignoreResult) { + var node = path.node; + var self = this; + + t.assertNode(node); + + if (t.isDeclaration(node)) throw getDeclError(node); + + if (t.isStatement(node)) return self.explodeStatement(path); + + if (t.isExpression(node)) return self.explodeExpression(path, ignoreResult); + + switch (node.type) { + case "Program": + return path.get("body").map(self.explodeStatement, self); + + case "VariableDeclarator": + throw getDeclError(node); + + case "Property": + case "SwitchCase": + case "CatchClause": + throw new Error(node.type + " nodes should be handled by their parents"); + + default: + throw new Error("unknown Node of type " + (0, _stringify2.default)(node.type)); + } +}; + +function getDeclError(node) { + return new Error("all declarations should have been transformed into " + "assignments before the Exploder began its work: " + (0, _stringify2.default)(node)); +} + +Ep.explodeStatement = function (path, labelId) { + var stmt = path.node; + var self = this; + var before = void 0, + after = void 0, + head = void 0; + + t.assertStatement(stmt); + + if (labelId) { + t.assertIdentifier(labelId); + } else { + labelId = null; + } + + if (t.isBlockStatement(stmt)) { + path.get("body").forEach(function (path) { + self.explodeStatement(path); + }); + return; + } + + if (!meta.containsLeap(stmt)) { + self.emit(stmt); + return; + } + + var _ret = function () { + switch (stmt.type) { + case "ExpressionStatement": + self.explodeExpression(path.get("expression"), true); + break; + + case "LabeledStatement": + after = loc(); + + self.leapManager.withEntry(new leap.LabeledEntry(after, stmt.label), function () { + self.explodeStatement(path.get("body"), stmt.label); + }); + + self.mark(after); + + break; + + case "WhileStatement": + before = loc(); + after = loc(); + + self.mark(before); + self.jumpIfNot(self.explodeExpression(path.get("test")), after); + self.leapManager.withEntry(new leap.LoopEntry(after, before, labelId), function () { + self.explodeStatement(path.get("body")); + }); + self.jump(before); + self.mark(after); + + break; + + case "DoWhileStatement": + var first = loc(); + var test = loc(); + after = loc(); + + self.mark(first); + self.leapManager.withEntry(new leap.LoopEntry(after, test, labelId), function () { + self.explode(path.get("body")); + }); + self.mark(test); + self.jumpIf(self.explodeExpression(path.get("test")), first); + self.mark(after); + + break; + + case "ForStatement": + head = loc(); + var update = loc(); + after = loc(); + + if (stmt.init) { + self.explode(path.get("init"), true); + } + + self.mark(head); + + if (stmt.test) { + self.jumpIfNot(self.explodeExpression(path.get("test")), after); + } else {} + + self.leapManager.withEntry(new leap.LoopEntry(after, update, labelId), function () { + self.explodeStatement(path.get("body")); + }); + + self.mark(update); + + if (stmt.update) { + self.explode(path.get("update"), true); + } + + self.jump(head); + + self.mark(after); + + break; + + case "TypeCastExpression": + return { + v: self.explodeExpression(path.get("expression")) + }; + + case "ForInStatement": + head = loc(); + after = loc(); + + var keyIterNextFn = self.makeTempVar(); + self.emitAssign(keyIterNextFn, t.callExpression(util.runtimeProperty("keys"), [self.explodeExpression(path.get("right"))])); + + self.mark(head); + + var keyInfoTmpVar = self.makeTempVar(); + self.jumpIf(t.memberExpression(t.assignmentExpression("=", keyInfoTmpVar, t.callExpression(keyIterNextFn, [])), t.identifier("done"), false), after); + + self.emitAssign(stmt.left, t.memberExpression(keyInfoTmpVar, t.identifier("value"), false)); + + self.leapManager.withEntry(new leap.LoopEntry(after, head, labelId), function () { + self.explodeStatement(path.get("body")); + }); + + self.jump(head); + + self.mark(after); + + break; + + case "BreakStatement": + self.emitAbruptCompletion({ + type: "break", + target: self.leapManager.getBreakLoc(stmt.label) + }); + + break; + + case "ContinueStatement": + self.emitAbruptCompletion({ + type: "continue", + target: self.leapManager.getContinueLoc(stmt.label) + }); + + break; + + case "SwitchStatement": + var disc = self.emitAssign(self.makeTempVar(), self.explodeExpression(path.get("discriminant"))); + + after = loc(); + var defaultLoc = loc(); + var condition = defaultLoc; + var caseLocs = []; + + var cases = stmt.cases || []; + + for (var i = cases.length - 1; i >= 0; --i) { + var c = cases[i]; + t.assertSwitchCase(c); + + if (c.test) { + condition = t.conditionalExpression(t.binaryExpression("===", disc, c.test), caseLocs[i] = loc(), condition); + } else { + caseLocs[i] = defaultLoc; + } + } + + var discriminant = path.get("discriminant"); + discriminant.replaceWith(condition); + self.jump(self.explodeExpression(discriminant)); + + self.leapManager.withEntry(new leap.SwitchEntry(after), function () { + path.get("cases").forEach(function (casePath) { + var i = casePath.key; + self.mark(caseLocs[i]); + + casePath.get("consequent").forEach(function (path) { + self.explodeStatement(path); + }); + }); + }); + + self.mark(after); + if (defaultLoc.value === -1) { + self.mark(defaultLoc); + _assert2.default.strictEqual(after.value, defaultLoc.value); + } + + break; + + case "IfStatement": + var elseLoc = stmt.alternate && loc(); + after = loc(); + + self.jumpIfNot(self.explodeExpression(path.get("test")), elseLoc || after); + + self.explodeStatement(path.get("consequent")); + + if (elseLoc) { + self.jump(after); + self.mark(elseLoc); + self.explodeStatement(path.get("alternate")); + } + + self.mark(after); + + break; + + case "ReturnStatement": + self.emitAbruptCompletion({ + type: "return", + value: self.explodeExpression(path.get("argument")) + }); + + break; + + case "WithStatement": + throw new Error("WithStatement not supported in generator functions."); + + case "TryStatement": + after = loc(); + + var handler = stmt.handler; + + var catchLoc = handler && loc(); + var catchEntry = catchLoc && new leap.CatchEntry(catchLoc, handler.param); + + var finallyLoc = stmt.finalizer && loc(); + var finallyEntry = finallyLoc && new leap.FinallyEntry(finallyLoc, after); + + var tryEntry = new leap.TryEntry(self.getUnmarkedCurrentLoc(), catchEntry, finallyEntry); + + self.tryEntries.push(tryEntry); + self.updateContextPrevLoc(tryEntry.firstLoc); + + self.leapManager.withEntry(tryEntry, function () { + self.explodeStatement(path.get("block")); + + if (catchLoc) { + (function () { + if (finallyLoc) { + self.jump(finallyLoc); + } else { + self.jump(after); + } + + self.updateContextPrevLoc(self.mark(catchLoc)); + + var bodyPath = path.get("handler.body"); + var safeParam = self.makeTempVar(); + self.clearPendingException(tryEntry.firstLoc, safeParam); + + bodyPath.traverse(catchParamVisitor, { + safeParam: safeParam, + catchParamName: handler.param.name + }); + + self.leapManager.withEntry(catchEntry, function () { + self.explodeStatement(bodyPath); + }); + })(); + } + + if (finallyLoc) { + self.updateContextPrevLoc(self.mark(finallyLoc)); + + self.leapManager.withEntry(finallyEntry, function () { + self.explodeStatement(path.get("finalizer")); + }); + + self.emit(t.returnStatement(t.callExpression(self.contextProperty("finish"), [finallyEntry.firstLoc]))); + } + }); + + self.mark(after); + + break; + + case "ThrowStatement": + self.emit(t.throwStatement(self.explodeExpression(path.get("argument")))); + + break; + + default: + throw new Error("unknown Statement of type " + (0, _stringify2.default)(stmt.type)); + } + }(); + + if ((typeof _ret === "undefined" ? "undefined" : (0, _typeof3.default)(_ret)) === "object") return _ret.v; +}; + +var catchParamVisitor = { + Identifier: function Identifier(path, state) { + if (path.node.name === state.catchParamName && util.isReference(path)) { + path.replaceWith(state.safeParam); + } + }, + + Scope: function Scope(path, state) { + if (path.scope.hasOwnBinding(state.catchParamName)) { + path.skip(); + } + } +}; + +Ep.emitAbruptCompletion = function (record) { + if (!isValidCompletion(record)) { + _assert2.default.ok(false, "invalid completion record: " + (0, _stringify2.default)(record)); + } + + _assert2.default.notStrictEqual(record.type, "normal", "normal completions are not abrupt"); + + var abruptArgs = [t.stringLiteral(record.type)]; + + if (record.type === "break" || record.type === "continue") { + t.assertLiteral(record.target); + abruptArgs[1] = record.target; + } else if (record.type === "return" || record.type === "throw") { + if (record.value) { + t.assertExpression(record.value); + abruptArgs[1] = record.value; + } + } + + this.emit(t.returnStatement(t.callExpression(this.contextProperty("abrupt"), abruptArgs))); +}; + +function isValidCompletion(record) { + var type = record.type; + + if (type === "normal") { + return !hasOwn.call(record, "target"); + } + + if (type === "break" || type === "continue") { + return !hasOwn.call(record, "value") && t.isLiteral(record.target); + } + + if (type === "return" || type === "throw") { + return hasOwn.call(record, "value") && !hasOwn.call(record, "target"); + } + + return false; +} + +Ep.getUnmarkedCurrentLoc = function () { + return t.numericLiteral(this.listing.length); +}; + +Ep.updateContextPrevLoc = function (loc) { + if (loc) { + t.assertLiteral(loc); + + if (loc.value === -1) { + loc.value = this.listing.length; + } else { + _assert2.default.strictEqual(loc.value, this.listing.length); + } + } else { + loc = this.getUnmarkedCurrentLoc(); + } + + this.emitAssign(this.contextProperty("prev"), loc); +}; + +Ep.explodeExpression = function (path, ignoreResult) { + var expr = path.node; + if (expr) { + t.assertExpression(expr); + } else { + return expr; + } + + var self = this; + var result = void 0; + var after = void 0; + + function finish(expr) { + t.assertExpression(expr); + if (ignoreResult) { + self.emit(expr); + } else { + return expr; + } + } + + if (!meta.containsLeap(expr)) { + return finish(expr); + } + + var hasLeapingChildren = meta.containsLeap.onlyChildren(expr); + + function explodeViaTempVar(tempVar, childPath, ignoreChildResult) { + _assert2.default.ok(!ignoreChildResult || !tempVar, "Ignoring the result of a child expression but forcing it to " + "be assigned to a temporary variable?"); + + var result = self.explodeExpression(childPath, ignoreChildResult); + + if (ignoreChildResult) {} else if (tempVar || hasLeapingChildren && !t.isLiteral(result)) { + result = self.emitAssign(tempVar || self.makeTempVar(), result); + } + return result; + } + + var _ret3 = function () { + + switch (expr.type) { + case "MemberExpression": + return { + v: finish(t.memberExpression(self.explodeExpression(path.get("object")), expr.computed ? explodeViaTempVar(null, path.get("property")) : expr.property, expr.computed)) + }; + + case "CallExpression": + var calleePath = path.get("callee"); + var argsPath = path.get("arguments"); + + var newCallee = void 0; + var newArgs = []; + + var hasLeapingArgs = false; + argsPath.forEach(function (argPath) { + hasLeapingArgs = hasLeapingArgs || meta.containsLeap(argPath.node); + }); + + if (t.isMemberExpression(calleePath.node)) { + if (hasLeapingArgs) { + + var newObject = explodeViaTempVar(self.makeTempVar(), calleePath.get("object")); + + var newProperty = calleePath.node.computed ? explodeViaTempVar(null, calleePath.get("property")) : calleePath.node.property; + + newArgs.unshift(newObject); + + newCallee = t.memberExpression(t.memberExpression(newObject, newProperty, calleePath.node.computed), t.identifier("call"), false); + } else { + newCallee = self.explodeExpression(calleePath); + } + } else { + newCallee = self.explodeExpression(calleePath); + + if (t.isMemberExpression(newCallee)) { + newCallee = t.sequenceExpression([t.numericLiteral(0), newCallee]); + } + } + + argsPath.forEach(function (argPath) { + newArgs.push(explodeViaTempVar(null, argPath)); + }); + + return { + v: finish(t.callExpression(newCallee, newArgs)) + }; + + case "NewExpression": + return { + v: finish(t.newExpression(explodeViaTempVar(null, path.get("callee")), path.get("arguments").map(function (argPath) { + return explodeViaTempVar(null, argPath); + }))) + }; + + case "ObjectExpression": + return { + v: finish(t.objectExpression(path.get("properties").map(function (propPath) { + if (propPath.isObjectProperty()) { + return t.objectProperty(propPath.node.key, explodeViaTempVar(null, propPath.get("value")), propPath.node.computed); + } else { + return propPath.node; + } + }))) + }; + + case "ArrayExpression": + return { + v: finish(t.arrayExpression(path.get("elements").map(function (elemPath) { + return explodeViaTempVar(null, elemPath); + }))) + }; + + case "SequenceExpression": + var lastIndex = expr.expressions.length - 1; + + path.get("expressions").forEach(function (exprPath) { + if (exprPath.key === lastIndex) { + result = self.explodeExpression(exprPath, ignoreResult); + } else { + self.explodeExpression(exprPath, true); + } + }); + + return { + v: result + }; + + case "LogicalExpression": + after = loc(); + + if (!ignoreResult) { + result = self.makeTempVar(); + } + + var left = explodeViaTempVar(result, path.get("left")); + + if (expr.operator === "&&") { + self.jumpIfNot(left, after); + } else { + _assert2.default.strictEqual(expr.operator, "||"); + self.jumpIf(left, after); + } + + explodeViaTempVar(result, path.get("right"), ignoreResult); + + self.mark(after); + + return { + v: result + }; + + case "ConditionalExpression": + var elseLoc = loc(); + after = loc(); + var test = self.explodeExpression(path.get("test")); + + self.jumpIfNot(test, elseLoc); + + if (!ignoreResult) { + result = self.makeTempVar(); + } + + explodeViaTempVar(result, path.get("consequent"), ignoreResult); + self.jump(after); + + self.mark(elseLoc); + explodeViaTempVar(result, path.get("alternate"), ignoreResult); + + self.mark(after); + + return { + v: result + }; + + case "UnaryExpression": + return { + v: finish(t.unaryExpression(expr.operator, self.explodeExpression(path.get("argument")), !!expr.prefix)) + }; + + case "BinaryExpression": + return { + v: finish(t.binaryExpression(expr.operator, explodeViaTempVar(null, path.get("left")), explodeViaTempVar(null, path.get("right")))) + }; + + case "AssignmentExpression": + return { + v: finish(t.assignmentExpression(expr.operator, self.explodeExpression(path.get("left")), self.explodeExpression(path.get("right")))) + }; + + case "UpdateExpression": + return { + v: finish(t.updateExpression(expr.operator, self.explodeExpression(path.get("argument")), expr.prefix)) + }; + + case "YieldExpression": + after = loc(); + var arg = expr.argument && self.explodeExpression(path.get("argument")); + + if (arg && expr.delegate) { + var _result = self.makeTempVar(); + + self.emit(t.returnStatement(t.callExpression(self.contextProperty("delegateYield"), [arg, t.stringLiteral(_result.property.name), after]))); + + self.mark(after); + + return { + v: _result + }; + } + + self.emitAssign(self.contextProperty("next"), after); + self.emit(t.returnStatement(arg || null)); + self.mark(after); + + return { + v: self.contextProperty("sent") + }; + + default: + throw new Error("unknown Expression of type " + (0, _stringify2.default)(expr.type)); + } + }(); + + if ((typeof _ret3 === "undefined" ? "undefined" : (0, _typeof3.default)(_ret3)) === "object") return _ret3.v; +}; +},{"./leap":128,"./meta":129,"./util":130,"assert":17,"babel-runtime/core-js/json/stringify":139,"babel-runtime/helpers/typeof":155,"babel-types":193}],126:[function(require,module,exports){ +"use strict"; + +var _keys = require("babel-runtime/core-js/object/keys"); + +var _keys2 = _interopRequireDefault(_keys); + +var _babelTypes = require("babel-types"); + +var t = _interopRequireWildcard(_babelTypes); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var hasOwn = Object.prototype.hasOwnProperty; + +exports.hoist = function (funPath) { + t.assertFunction(funPath.node); + + var vars = {}; + + function varDeclToExpr(vdec, includeIdentifiers) { + t.assertVariableDeclaration(vdec); + + var exprs = []; + + vdec.declarations.forEach(function (dec) { + vars[dec.id.name] = t.identifier(dec.id.name); + + if (dec.init) { + exprs.push(t.assignmentExpression("=", dec.id, dec.init)); + } else if (includeIdentifiers) { + exprs.push(dec.id); + } + }); + + if (exprs.length === 0) return null; + + if (exprs.length === 1) return exprs[0]; + + return t.sequenceExpression(exprs); + } + + funPath.get("body").traverse({ + VariableDeclaration: { + exit: function exit(path) { + var expr = varDeclToExpr(path.node, false); + if (expr === null) { + path.remove(); + } else { + path.replaceWith(t.expressionStatement(expr)); + } + + path.skip(); + } + }, + + ForStatement: function ForStatement(path) { + var init = path.node.init; + if (t.isVariableDeclaration(init)) { + path.get("init").replaceWith(varDeclToExpr(init, false)); + } + }, + + ForXStatement: function ForXStatement(path) { + var left = path.get("left"); + if (left.isVariableDeclaration()) { + left.replaceWith(varDeclToExpr(left.node, true)); + } + }, + + FunctionDeclaration: function FunctionDeclaration(path) { + var node = path.node; + vars[node.id.name] = node.id; + + var assignment = t.expressionStatement(t.assignmentExpression("=", node.id, t.functionExpression(node.id, node.params, node.body, node.generator, node.expression))); + + if (path.parentPath.isBlockStatement()) { + path.parentPath.unshiftContainer("body", assignment); + + path.remove(); + } else { + path.replaceWith(assignment); + } + + path.skip(); + }, + + FunctionExpression: function FunctionExpression(path) { + path.skip(); + } + }); + + var paramNames = {}; + funPath.get("params").forEach(function (paramPath) { + var param = paramPath.node; + if (t.isIdentifier(param)) { + paramNames[param.name] = param; + } else {} + }); + + var declarations = []; + + (0, _keys2.default)(vars).forEach(function (name) { + if (!hasOwn.call(paramNames, name)) { + declarations.push(t.variableDeclarator(vars[name], null)); + } + }); + + if (declarations.length === 0) { + return null; + } + + return t.variableDeclaration("var", declarations); +}; +},{"babel-runtime/core-js/object/keys":145,"babel-types":193}],127:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +exports.default = function () { + return require("./visit"); +}; + +module.exports = exports["default"]; +},{"./visit":131}],128:[function(require,module,exports){ +"use strict"; + +var _assert = require("assert"); + +var _assert2 = _interopRequireDefault(_assert); + +var _babelTypes = require("babel-types"); + +var t = _interopRequireWildcard(_babelTypes); + +var _util = require("util"); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function Entry() { + _assert2.default.ok(this instanceof Entry); +} + +function FunctionEntry(returnLoc) { + Entry.call(this); + t.assertLiteral(returnLoc); + this.returnLoc = returnLoc; +} + +(0, _util.inherits)(FunctionEntry, Entry); +exports.FunctionEntry = FunctionEntry; + +function LoopEntry(breakLoc, continueLoc, label) { + Entry.call(this); + + t.assertLiteral(breakLoc); + t.assertLiteral(continueLoc); + + if (label) { + t.assertIdentifier(label); + } else { + label = null; + } + + this.breakLoc = breakLoc; + this.continueLoc = continueLoc; + this.label = label; +} + +(0, _util.inherits)(LoopEntry, Entry); +exports.LoopEntry = LoopEntry; + +function SwitchEntry(breakLoc) { + Entry.call(this); + t.assertLiteral(breakLoc); + this.breakLoc = breakLoc; +} + +(0, _util.inherits)(SwitchEntry, Entry); +exports.SwitchEntry = SwitchEntry; + +function TryEntry(firstLoc, catchEntry, finallyEntry) { + Entry.call(this); + + t.assertLiteral(firstLoc); + + if (catchEntry) { + _assert2.default.ok(catchEntry instanceof CatchEntry); + } else { + catchEntry = null; + } + + if (finallyEntry) { + _assert2.default.ok(finallyEntry instanceof FinallyEntry); + } else { + finallyEntry = null; + } + + _assert2.default.ok(catchEntry || finallyEntry); + + this.firstLoc = firstLoc; + this.catchEntry = catchEntry; + this.finallyEntry = finallyEntry; +} + +(0, _util.inherits)(TryEntry, Entry); +exports.TryEntry = TryEntry; + +function CatchEntry(firstLoc, paramId) { + Entry.call(this); + + t.assertLiteral(firstLoc); + t.assertIdentifier(paramId); + + this.firstLoc = firstLoc; + this.paramId = paramId; +} + +(0, _util.inherits)(CatchEntry, Entry); +exports.CatchEntry = CatchEntry; + +function FinallyEntry(firstLoc, afterLoc) { + Entry.call(this); + t.assertLiteral(firstLoc); + t.assertLiteral(afterLoc); + this.firstLoc = firstLoc; + this.afterLoc = afterLoc; +} + +(0, _util.inherits)(FinallyEntry, Entry); +exports.FinallyEntry = FinallyEntry; + +function LabeledEntry(breakLoc, label) { + Entry.call(this); + + t.assertLiteral(breakLoc); + t.assertIdentifier(label); + + this.breakLoc = breakLoc; + this.label = label; +} + +(0, _util.inherits)(LabeledEntry, Entry); +exports.LabeledEntry = LabeledEntry; + +function LeapManager(emitter) { + _assert2.default.ok(this instanceof LeapManager); + + var Emitter = require("./emit").Emitter; + _assert2.default.ok(emitter instanceof Emitter); + + this.emitter = emitter; + this.entryStack = [new FunctionEntry(emitter.finalLoc)]; +} + +var LMp = LeapManager.prototype; +exports.LeapManager = LeapManager; + +LMp.withEntry = function (entry, callback) { + _assert2.default.ok(entry instanceof Entry); + this.entryStack.push(entry); + try { + callback.call(this.emitter); + } finally { + var popped = this.entryStack.pop(); + _assert2.default.strictEqual(popped, entry); + } +}; + +LMp._findLeapLocation = function (property, label) { + for (var i = this.entryStack.length - 1; i >= 0; --i) { + var entry = this.entryStack[i]; + var loc = entry[property]; + if (loc) { + if (label) { + if (entry.label && entry.label.name === label.name) { + return loc; + } + } else if (entry instanceof LabeledEntry) {} else { + return loc; + } + } + } + + return null; +}; + +LMp.getBreakLoc = function (label) { + return this._findLeapLocation("breakLoc", label); +}; + +LMp.getContinueLoc = function (label) { + return this._findLeapLocation("continueLoc", label); +}; +},{"./emit":125,"assert":17,"babel-types":193,"util":691}],129:[function(require,module,exports){ +"use strict"; + +var _assert = require("assert"); + +var _assert2 = _interopRequireDefault(_assert); + +var _babelTypes = require("babel-types"); + +var t = _interopRequireWildcard(_babelTypes); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var m = require("private").makeAccessor(); + +var hasOwn = Object.prototype.hasOwnProperty; + +function makePredicate(propertyName, knownTypes) { + function onlyChildren(node) { + t.assertNode(node); + + var result = false; + + function check(child) { + if (result) {} else if (Array.isArray(child)) { + child.some(check); + } else if (t.isNode(child)) { + _assert2.default.strictEqual(result, false); + result = predicate(child); + } + return result; + } + + var keys = t.VISITOR_KEYS[node.type]; + if (keys) { + for (var i = 0; i < keys.length; i++) { + var key = keys[i]; + var child = node[key]; + check(child); + } + } + + return result; + } + + function predicate(node) { + t.assertNode(node); + + var meta = m(node); + if (hasOwn.call(meta, propertyName)) return meta[propertyName]; + + if (hasOwn.call(opaqueTypes, node.type)) return meta[propertyName] = false; + + if (hasOwn.call(knownTypes, node.type)) return meta[propertyName] = true; + + return meta[propertyName] = onlyChildren(node); + } + + predicate.onlyChildren = onlyChildren; + + return predicate; +} + +var opaqueTypes = { + FunctionExpression: true +}; + +var sideEffectTypes = { + CallExpression: true, + ForInStatement: true, + UnaryExpression: true, + BinaryExpression: true, + AssignmentExpression: true, + UpdateExpression: true, + NewExpression: true }; + +var leapTypes = { + YieldExpression: true, + BreakStatement: true, + ContinueStatement: true, + ReturnStatement: true, + ThrowStatement: true +}; + +for (var type in leapTypes) { + if (hasOwn.call(leapTypes, type)) { + sideEffectTypes[type] = leapTypes[type]; + } +} + +exports.hasSideEffects = makePredicate("hasSideEffects", sideEffectTypes); +exports.containsLeap = makePredicate("containsLeap", leapTypes); +},{"assert":17,"babel-types":193,"private":593}],130:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; +exports.runtimeProperty = runtimeProperty; +exports.isReference = isReference; + +var _babelTypes = require("babel-types"); + +var t = _interopRequireWildcard(_babelTypes); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function runtimeProperty(name) { + return t.memberExpression(t.identifier("regeneratorRuntime"), t.identifier(name), false); +} + +function isReference(path) { + return path.isReferenced() || path.parentPath.isAssignmentExpression({ left: path.node }); +} +},{"babel-types":193}],131:[function(require,module,exports){ +"use strict"; + +var _assert = require("assert"); + +var _assert2 = _interopRequireDefault(_assert); + +var _babelTypes = require("babel-types"); + +var t = _interopRequireWildcard(_babelTypes); + +var _hoist = require("./hoist"); + +var _emit = require("./emit"); + +var _util = require("./util"); + +var util = _interopRequireWildcard(_util); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var getMarkInfo = require("private").makeAccessor(); + +exports.visitor = { + Function: { + exit: function exit(path, state) { + var node = path.node; + + if (node.generator) { + if (node.async) { + if (state.opts.asyncGenerators === false) return; + } else { + if (state.opts.generators === false) return; + } + } else if (node.async) { + if (state.opts.async === false) return; + } else { + return; + } + + var contextId = path.scope.generateUidIdentifier("context"); + var argsId = path.scope.generateUidIdentifier("args"); + + path.ensureBlock(); + var bodyBlockPath = path.get("body"); + + if (node.async) { + bodyBlockPath.traverse(awaitVisitor); + } + + bodyBlockPath.traverse(functionSentVisitor, { + context: contextId + }); + + var outerBody = []; + var innerBody = []; + + bodyBlockPath.get("body").forEach(function (childPath) { + var node = childPath.node; + if (node && node._blockHoist != null) { + outerBody.push(node); + } else { + innerBody.push(node); + } + }); + + if (outerBody.length > 0) { + bodyBlockPath.node.body = innerBody; + } + + var outerFnExpr = getOuterFnExpr(path); + + t.assertIdentifier(node.id); + var innerFnId = t.identifier(node.id.name + "$"); + + var vars = (0, _hoist.hoist)(path); + + var didRenameArguments = renameArguments(path, argsId); + if (didRenameArguments) { + vars = vars || t.variableDeclaration("var", []); + vars.declarations.push(t.variableDeclarator(argsId, t.identifier("arguments"))); + } + + var emitter = new _emit.Emitter(contextId); + emitter.explode(path.get("body")); + + if (vars && vars.declarations.length > 0) { + outerBody.push(vars); + } + + var wrapArgs = [emitter.getContextFunction(innerFnId), node.generator ? outerFnExpr : t.nullLiteral(), t.thisExpression()]; + + var tryLocsList = emitter.getTryLocsList(); + if (tryLocsList) { + wrapArgs.push(tryLocsList); + } + + var wrapCall = t.callExpression(util.runtimeProperty(node.async ? "async" : "wrap"), wrapArgs); + + outerBody.push(t.returnStatement(wrapCall)); + node.body = t.blockStatement(outerBody); + + var wasGeneratorFunction = node.generator; + if (wasGeneratorFunction) { + node.generator = false; + } + + if (node.async) { + node.async = false; + } + + if (wasGeneratorFunction && t.isExpression(node)) { + path.replaceWith(t.callExpression(util.runtimeProperty("mark"), [node])); + } + + path.requeue(); + } + } +}; + +function getOuterFnExpr(funPath) { + var node = funPath.node; + t.assertFunction(node); + + if (!node.id) { + node.id = funPath.scope.parent.generateUidIdentifier("callee"); + } + + if (node.generator && t.isFunctionDeclaration(node)) { + var pp = funPath.findParent(function (path) { + return path.isProgram() || path.isBlockStatement(); + }); + + if (!pp) { + return node.id; + } + + var markDecl = getRuntimeMarkDecl(pp); + var markedArray = markDecl.declarations[0].id; + var funDeclIdArray = markDecl.declarations[0].init.callee.object; + t.assertArrayExpression(funDeclIdArray); + + var index = funDeclIdArray.elements.length; + funDeclIdArray.elements.push(node.id); + + return t.memberExpression(markedArray, t.numericLiteral(index), true); + } + + return node.id; +} + +function getRuntimeMarkDecl(blockPath) { + var block = blockPath.node; + _assert2.default.ok(Array.isArray(block.body)); + + var info = getMarkInfo(block); + if (info.decl) { + return info.decl; + } + + info.decl = t.variableDeclaration("var", [t.variableDeclarator(blockPath.scope.generateUidIdentifier("marked"), t.callExpression(t.memberExpression(t.arrayExpression([]), t.identifier("map"), false), [util.runtimeProperty("mark")]))]); + + blockPath.unshiftContainer("body", info.decl); + + return info.decl; +} + +function renameArguments(funcPath, argsId) { + var state = { + didRenameArguments: false, + argsId: argsId + }; + + funcPath.traverse(argumentsVisitor, state); + + return state.didRenameArguments; +} + +var argumentsVisitor = { + "FunctionExpression|FunctionDeclaration": function FunctionExpressionFunctionDeclaration(path) { + path.skip(); + }, + + Identifier: function Identifier(path, state) { + if (path.node.name === "arguments" && util.isReference(path)) { + path.replaceWith(state.argsId); + state.didRenameArguments = true; + } + } +}; + +var functionSentVisitor = { + MetaProperty: function MetaProperty(path) { + var node = path.node; + + + if (node.meta.name === "function" && node.property.name === "sent") { + path.replaceWith(t.memberExpression(this.context, t.identifier("_sent"))); + } + } +}; + +var awaitVisitor = { + Function: function Function(path) { + path.skip(); + }, + + AwaitExpression: function AwaitExpression(path) { + var argument = path.node.argument; + + path.replaceWith(t.yieldExpression(t.callExpression(util.runtimeProperty("awrap"), [argument]), false)); + } +}; +},{"./emit":125,"./hoist":126,"./util":130,"assert":17,"babel-types":193,"private":593}],132:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +var _getIterator2 = require("babel-runtime/core-js/get-iterator"); + +var _getIterator3 = _interopRequireDefault(_getIterator2); + +exports.default = function () { + return { + visitor: { + Program: function Program(path, state) { + if (state.opts.strict === false || state.opts.strictMode === false) return; + + var node = path.node; + + + for (var _iterator = node.directives, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_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 directive = _ref; + + if (directive.value.value === "use strict") return; + } + + path.unshiftContainer("directives", t.directive(t.directiveLiteral("use strict"))); + } + } + }; +}; + +var _babelTypes = require("babel-types"); + +var t = _interopRequireWildcard(_babelTypes); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +module.exports = exports["default"]; +},{"babel-runtime/core-js/get-iterator":138,"babel-types":193}],133:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +var _babelPluginTransformEs2015TemplateLiterals = require("babel-plugin-transform-es2015-template-literals"); + +var _babelPluginTransformEs2015TemplateLiterals2 = _interopRequireDefault(_babelPluginTransformEs2015TemplateLiterals); + +var _babelPluginTransformEs2015Literals = require("babel-plugin-transform-es2015-literals"); + +var _babelPluginTransformEs2015Literals2 = _interopRequireDefault(_babelPluginTransformEs2015Literals); + +var _babelPluginTransformEs2015FunctionName = require("babel-plugin-transform-es2015-function-name"); + +var _babelPluginTransformEs2015FunctionName2 = _interopRequireDefault(_babelPluginTransformEs2015FunctionName); + +var _babelPluginTransformEs2015ArrowFunctions = require("babel-plugin-transform-es2015-arrow-functions"); + +var _babelPluginTransformEs2015ArrowFunctions2 = _interopRequireDefault(_babelPluginTransformEs2015ArrowFunctions); + +var _babelPluginTransformEs2015BlockScopedFunctions = require("babel-plugin-transform-es2015-block-scoped-functions"); + +var _babelPluginTransformEs2015BlockScopedFunctions2 = _interopRequireDefault(_babelPluginTransformEs2015BlockScopedFunctions); + +var _babelPluginTransformEs2015Classes = require("babel-plugin-transform-es2015-classes"); + +var _babelPluginTransformEs2015Classes2 = _interopRequireDefault(_babelPluginTransformEs2015Classes); + +var _babelPluginTransformEs2015ObjectSuper = require("babel-plugin-transform-es2015-object-super"); + +var _babelPluginTransformEs2015ObjectSuper2 = _interopRequireDefault(_babelPluginTransformEs2015ObjectSuper); + +var _babelPluginTransformEs2015ShorthandProperties = require("babel-plugin-transform-es2015-shorthand-properties"); + +var _babelPluginTransformEs2015ShorthandProperties2 = _interopRequireDefault(_babelPluginTransformEs2015ShorthandProperties); + +var _babelPluginTransformEs2015DuplicateKeys = require("babel-plugin-transform-es2015-duplicate-keys"); + +var _babelPluginTransformEs2015DuplicateKeys2 = _interopRequireDefault(_babelPluginTransformEs2015DuplicateKeys); + +var _babelPluginTransformEs2015ComputedProperties = require("babel-plugin-transform-es2015-computed-properties"); + +var _babelPluginTransformEs2015ComputedProperties2 = _interopRequireDefault(_babelPluginTransformEs2015ComputedProperties); + +var _babelPluginTransformEs2015ForOf = require("babel-plugin-transform-es2015-for-of"); + +var _babelPluginTransformEs2015ForOf2 = _interopRequireDefault(_babelPluginTransformEs2015ForOf); + +var _babelPluginTransformEs2015StickyRegex = require("babel-plugin-transform-es2015-sticky-regex"); + +var _babelPluginTransformEs2015StickyRegex2 = _interopRequireDefault(_babelPluginTransformEs2015StickyRegex); + +var _babelPluginTransformEs2015UnicodeRegex = require("babel-plugin-transform-es2015-unicode-regex"); + +var _babelPluginTransformEs2015UnicodeRegex2 = _interopRequireDefault(_babelPluginTransformEs2015UnicodeRegex); + +var _babelPluginCheckEs2015Constants = require("babel-plugin-check-es2015-constants"); + +var _babelPluginCheckEs2015Constants2 = _interopRequireDefault(_babelPluginCheckEs2015Constants); + +var _babelPluginTransformEs2015Spread = require("babel-plugin-transform-es2015-spread"); + +var _babelPluginTransformEs2015Spread2 = _interopRequireDefault(_babelPluginTransformEs2015Spread); + +var _babelPluginTransformEs2015Parameters = require("babel-plugin-transform-es2015-parameters"); + +var _babelPluginTransformEs2015Parameters2 = _interopRequireDefault(_babelPluginTransformEs2015Parameters); + +var _babelPluginTransformEs2015Destructuring = require("babel-plugin-transform-es2015-destructuring"); + +var _babelPluginTransformEs2015Destructuring2 = _interopRequireDefault(_babelPluginTransformEs2015Destructuring); + +var _babelPluginTransformEs2015BlockScoping = require("babel-plugin-transform-es2015-block-scoping"); + +var _babelPluginTransformEs2015BlockScoping2 = _interopRequireDefault(_babelPluginTransformEs2015BlockScoping); + +var _babelPluginTransformEs2015TypeofSymbol = require("babel-plugin-transform-es2015-typeof-symbol"); + +var _babelPluginTransformEs2015TypeofSymbol2 = _interopRequireDefault(_babelPluginTransformEs2015TypeofSymbol); + +var _babelPluginTransformEs2015ModulesCommonjs = require("babel-plugin-transform-es2015-modules-commonjs"); + +var _babelPluginTransformEs2015ModulesCommonjs2 = _interopRequireDefault(_babelPluginTransformEs2015ModulesCommonjs); + +var _babelPluginTransformEs2015ModulesSystemjs = require("babel-plugin-transform-es2015-modules-systemjs"); + +var _babelPluginTransformEs2015ModulesSystemjs2 = _interopRequireDefault(_babelPluginTransformEs2015ModulesSystemjs); + +var _babelPluginTransformEs2015ModulesAmd = require("babel-plugin-transform-es2015-modules-amd"); + +var _babelPluginTransformEs2015ModulesAmd2 = _interopRequireDefault(_babelPluginTransformEs2015ModulesAmd); + +var _babelPluginTransformEs2015ModulesUmd = require("babel-plugin-transform-es2015-modules-umd"); + +var _babelPluginTransformEs2015ModulesUmd2 = _interopRequireDefault(_babelPluginTransformEs2015ModulesUmd); + +var _babelPluginTransformRegenerator = require("babel-plugin-transform-regenerator"); + +var _babelPluginTransformRegenerator2 = _interopRequireDefault(_babelPluginTransformRegenerator); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function preset(context) { + var opts = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; + + var moduleTypes = ["commonjs", "amd", "umd", "systemjs"]; + var loose = false; + var modules = "commonjs"; + var spec = false; + + if (opts !== undefined) { + if (opts.loose !== undefined) loose = opts.loose; + if (opts.modules !== undefined) modules = opts.modules; + if (opts.spec !== undefined) spec = opts.spec; + } + + if (typeof loose !== "boolean") throw new Error("Preset es2015 'loose' option must be a boolean."); + if (typeof spec !== "boolean") throw new Error("Preset es2015 'spec' option must be a boolean."); + if (modules !== false && moduleTypes.indexOf(modules) === -1) { + throw new Error("Preset es2015 'modules' option must be 'false' to indicate no modules\n" + "or a module type which be be one of: 'commonjs' (default), 'amd', 'umd', 'systemjs'"); + } + + var optsLoose = { loose: loose }; + + return { + plugins: [[_babelPluginTransformEs2015TemplateLiterals2.default, { loose: loose, spec: spec }], _babelPluginTransformEs2015Literals2.default, _babelPluginTransformEs2015FunctionName2.default, [_babelPluginTransformEs2015ArrowFunctions2.default, { spec: spec }], _babelPluginTransformEs2015BlockScopedFunctions2.default, [_babelPluginTransformEs2015Classes2.default, optsLoose], _babelPluginTransformEs2015ObjectSuper2.default, _babelPluginTransformEs2015ShorthandProperties2.default, _babelPluginTransformEs2015DuplicateKeys2.default, [_babelPluginTransformEs2015ComputedProperties2.default, optsLoose], [_babelPluginTransformEs2015ForOf2.default, optsLoose], _babelPluginTransformEs2015StickyRegex2.default, _babelPluginTransformEs2015UnicodeRegex2.default, _babelPluginCheckEs2015Constants2.default, [_babelPluginTransformEs2015Spread2.default, optsLoose], _babelPluginTransformEs2015Parameters2.default, [_babelPluginTransformEs2015Destructuring2.default, optsLoose], _babelPluginTransformEs2015BlockScoping2.default, _babelPluginTransformEs2015TypeofSymbol2.default, modules === "commonjs" && [_babelPluginTransformEs2015ModulesCommonjs2.default, optsLoose], modules === "systemjs" && [_babelPluginTransformEs2015ModulesSystemjs2.default, optsLoose], modules === "amd" && [_babelPluginTransformEs2015ModulesAmd2.default, optsLoose], modules === "umd" && [_babelPluginTransformEs2015ModulesUmd2.default, optsLoose], [_babelPluginTransformRegenerator2.default, { async: false, asyncGenerators: false }]].filter(Boolean) }; +} + +var oldConfig = preset({}); + +exports.default = oldConfig; + +Object.defineProperty(oldConfig, "buildPreset", { + configurable: true, + writable: true, + + enumerable: false, + value: preset +}); +module.exports = exports["default"]; +},{"babel-plugin-check-es2015-constants":77,"babel-plugin-transform-es2015-arrow-functions":93,"babel-plugin-transform-es2015-block-scoped-functions":94,"babel-plugin-transform-es2015-block-scoping":95,"babel-plugin-transform-es2015-classes":97,"babel-plugin-transform-es2015-computed-properties":100,"babel-plugin-transform-es2015-destructuring":101,"babel-plugin-transform-es2015-duplicate-keys":102,"babel-plugin-transform-es2015-for-of":103,"babel-plugin-transform-es2015-function-name":104,"babel-plugin-transform-es2015-literals":105,"babel-plugin-transform-es2015-modules-amd":106,"babel-plugin-transform-es2015-modules-commonjs":107,"babel-plugin-transform-es2015-modules-systemjs":108,"babel-plugin-transform-es2015-modules-umd":109,"babel-plugin-transform-es2015-object-super":110,"babel-plugin-transform-es2015-parameters":113,"babel-plugin-transform-es2015-shorthand-properties":115,"babel-plugin-transform-es2015-spread":116,"babel-plugin-transform-es2015-sticky-regex":117,"babel-plugin-transform-es2015-template-literals":118,"babel-plugin-transform-es2015-typeof-symbol":119,"babel-plugin-transform-es2015-unicode-regex":120,"babel-plugin-transform-regenerator":127}],134:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +var _babelPresetStage = require("babel-preset-stage-1"); + +var _babelPresetStage2 = _interopRequireDefault(_babelPresetStage); + +var _babelPluginTransformDoExpressions = require("babel-plugin-transform-do-expressions"); + +var _babelPluginTransformDoExpressions2 = _interopRequireDefault(_babelPluginTransformDoExpressions); + +var _babelPluginTransformFunctionBind = require("babel-plugin-transform-function-bind"); + +var _babelPluginTransformFunctionBind2 = _interopRequireDefault(_babelPluginTransformFunctionBind); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +exports.default = { + presets: [_babelPresetStage2.default], + plugins: [_babelPluginTransformDoExpressions2.default, _babelPluginTransformFunctionBind2.default] +}; +module.exports = exports["default"]; +},{"babel-plugin-transform-do-expressions":92,"babel-plugin-transform-function-bind":123,"babel-preset-stage-1":135}],135:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +var _babelPresetStage = require("babel-preset-stage-2"); + +var _babelPresetStage2 = _interopRequireDefault(_babelPresetStage); + +var _babelPluginTransformClassConstructorCall = require("babel-plugin-transform-class-constructor-call"); + +var _babelPluginTransformClassConstructorCall2 = _interopRequireDefault(_babelPluginTransformClassConstructorCall); + +var _babelPluginTransformExportExtensions = require("babel-plugin-transform-export-extensions"); + +var _babelPluginTransformExportExtensions2 = _interopRequireDefault(_babelPluginTransformExportExtensions); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +exports.default = { + presets: [_babelPresetStage2.default], + plugins: [_babelPluginTransformClassConstructorCall2.default, _babelPluginTransformExportExtensions2.default] +}; +module.exports = exports["default"]; +},{"babel-plugin-transform-class-constructor-call":89,"babel-plugin-transform-export-extensions":122,"babel-preset-stage-2":136}],136:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +var _babelPresetStage = require("babel-preset-stage-3"); + +var _babelPresetStage2 = _interopRequireDefault(_babelPresetStage); + +var _babelPluginTransformClassProperties = require("babel-plugin-transform-class-properties"); + +var _babelPluginTransformClassProperties2 = _interopRequireDefault(_babelPluginTransformClassProperties); + +var _babelPluginTransformObjectRestSpread = require("babel-plugin-transform-object-rest-spread"); + +var _babelPluginTransformObjectRestSpread2 = _interopRequireDefault(_babelPluginTransformObjectRestSpread); + +var _babelPluginTransformDecorators = require("babel-plugin-transform-decorators"); + +var _babelPluginTransformDecorators2 = _interopRequireDefault(_babelPluginTransformDecorators); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +exports.default = { + presets: [_babelPresetStage2.default], + plugins: [_babelPluginTransformClassProperties2.default, _babelPluginTransformObjectRestSpread2.default, _babelPluginTransformDecorators2.default] +}; +module.exports = exports["default"]; +},{"babel-plugin-transform-class-properties":90,"babel-plugin-transform-decorators":91,"babel-plugin-transform-object-rest-spread":124,"babel-preset-stage-3":137}],137:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +var _babelPluginSyntaxTrailingFunctionCommas = require("babel-plugin-syntax-trailing-function-commas"); + +var _babelPluginSyntaxTrailingFunctionCommas2 = _interopRequireDefault(_babelPluginSyntaxTrailingFunctionCommas); + +var _babelPluginTransformAsyncToGenerator = require("babel-plugin-transform-async-to-generator"); + +var _babelPluginTransformAsyncToGenerator2 = _interopRequireDefault(_babelPluginTransformAsyncToGenerator); + +var _babelPluginTransformExponentiationOperator = require("babel-plugin-transform-exponentiation-operator"); + +var _babelPluginTransformExponentiationOperator2 = _interopRequireDefault(_babelPluginTransformExponentiationOperator); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +exports.default = { + plugins: [_babelPluginSyntaxTrailingFunctionCommas2.default, _babelPluginTransformAsyncToGenerator2.default, _babelPluginTransformExponentiationOperator2.default] +}; +module.exports = exports["default"]; +},{"babel-plugin-syntax-trailing-function-commas":87,"babel-plugin-transform-async-to-generator":88,"babel-plugin-transform-exponentiation-operator":121}],138:[function(require,module,exports){ +module.exports = { "default": require("core-js/library/fn/get-iterator"), __esModule: true }; +},{"core-js/library/fn/get-iterator":232}],139:[function(require,module,exports){ +module.exports = { "default": require("core-js/library/fn/json/stringify"), __esModule: true }; +},{"core-js/library/fn/json/stringify":233}],140:[function(require,module,exports){ +module.exports = { "default": require("core-js/library/fn/map"), __esModule: true }; +},{"core-js/library/fn/map":234}],141:[function(require,module,exports){ +module.exports = { "default": require("core-js/library/fn/number/max-safe-integer"), __esModule: true }; +},{"core-js/library/fn/number/max-safe-integer":235}],142:[function(require,module,exports){ +module.exports = { "default": require("core-js/library/fn/object/assign"), __esModule: true }; +},{"core-js/library/fn/object/assign":236}],143:[function(require,module,exports){ +module.exports = { "default": require("core-js/library/fn/object/create"), __esModule: true }; +},{"core-js/library/fn/object/create":237}],144:[function(require,module,exports){ +module.exports = { "default": require("core-js/library/fn/object/get-own-property-symbols"), __esModule: true }; +},{"core-js/library/fn/object/get-own-property-symbols":238}],145:[function(require,module,exports){ +module.exports = { "default": require("core-js/library/fn/object/keys"), __esModule: true }; +},{"core-js/library/fn/object/keys":239}],146:[function(require,module,exports){ +module.exports = { "default": require("core-js/library/fn/object/set-prototype-of"), __esModule: true }; +},{"core-js/library/fn/object/set-prototype-of":240}],147:[function(require,module,exports){ +module.exports = { "default": require("core-js/library/fn/symbol"), __esModule: true }; +},{"core-js/library/fn/symbol":242}],148:[function(require,module,exports){ +module.exports = { "default": require("core-js/library/fn/symbol/for"), __esModule: true }; +},{"core-js/library/fn/symbol/for":241}],149:[function(require,module,exports){ +module.exports = { "default": require("core-js/library/fn/symbol/iterator"), __esModule: true }; +},{"core-js/library/fn/symbol/iterator":243}],150:[function(require,module,exports){ +module.exports = { "default": require("core-js/library/fn/weak-map"), __esModule: true }; +},{"core-js/library/fn/weak-map":244}],151:[function(require,module,exports){ +module.exports = { "default": require("core-js/library/fn/weak-set"), __esModule: true }; +},{"core-js/library/fn/weak-set":245}],152:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +exports.default = function (instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError("Cannot call a class as a function"); + } +}; +},{}],153:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +var _setPrototypeOf = require("../core-js/object/set-prototype-of"); + +var _setPrototypeOf2 = _interopRequireDefault(_setPrototypeOf); + +var _create = require("../core-js/object/create"); + +var _create2 = _interopRequireDefault(_create); + +var _typeof2 = require("../helpers/typeof"); + +var _typeof3 = _interopRequireDefault(_typeof2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +exports.default = function (subClass, superClass) { + if (typeof superClass !== "function" && superClass !== null) { + throw new TypeError("Super expression must either be null or a function, not " + (typeof superClass === "undefined" ? "undefined" : (0, _typeof3.default)(superClass))); + } + + subClass.prototype = (0, _create2.default)(superClass && superClass.prototype, { + constructor: { + value: subClass, + enumerable: false, + writable: true, + configurable: true + } + }); + if (superClass) _setPrototypeOf2.default ? (0, _setPrototypeOf2.default)(subClass, superClass) : subClass.__proto__ = superClass; +}; +},{"../core-js/object/create":143,"../core-js/object/set-prototype-of":146,"../helpers/typeof":155}],154:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +var _typeof2 = require("../helpers/typeof"); + +var _typeof3 = _interopRequireDefault(_typeof2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +exports.default = function (self, call) { + if (!self) { + throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); + } + + return call && ((typeof call === "undefined" ? "undefined" : (0, _typeof3.default)(call)) === "object" || typeof call === "function") ? call : self; +}; +},{"../helpers/typeof":155}],155:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +var _iterator = require("../core-js/symbol/iterator"); + +var _iterator2 = _interopRequireDefault(_iterator); + +var _symbol = require("../core-js/symbol"); + +var _symbol2 = _interopRequireDefault(_symbol); + +var _typeof = typeof _symbol2.default === "function" && typeof _iterator2.default === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof _symbol2.default === "function" && obj.constructor === _symbol2.default ? "symbol" : typeof obj; }; + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +exports.default = typeof _symbol2.default === "function" && _typeof(_iterator2.default) === "symbol" ? function (obj) { + return typeof obj === "undefined" ? "undefined" : _typeof(obj); +} : function (obj) { + return obj && typeof _symbol2.default === "function" && obj.constructor === _symbol2.default ? "symbol" : typeof obj === "undefined" ? "undefined" : _typeof(obj); +}; +},{"../core-js/symbol":147,"../core-js/symbol/iterator":149}],156:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +var _symbol = require("babel-runtime/core-js/symbol"); + +var _symbol2 = _interopRequireDefault(_symbol); + +exports.default = function (code, opts) { + var stack = void 0; + try { + throw new Error(); + } catch (error) { + if (error.stack) { + stack = error.stack.split("\n").slice(1).join("\n"); + } + } + + opts = (0, _assign2.default)({ + allowReturnOutsideFunction: true, + allowSuperOutsideMethod: true, + preserveComments: false + }, opts); + + var _getAst = function getAst() { + var ast = void 0; + + try { + ast = babylon.parse(code, opts); + + ast = _babelTraverse2.default.removeProperties(ast, { preserveComments: opts.preserveComments }); + + _babelTraverse2.default.cheap(ast, function (node) { + node[FROM_TEMPLATE] = true; + }); + } catch (err) { + err.stack = err.stack + "from\n" + stack; + throw err; + } + + _getAst = function getAst() { + return ast; + }; + + return ast; + }; + + return function () { + for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + + return useTemplate(_getAst(), args); + }; +}; + +var _cloneDeep = require("lodash/cloneDeep"); + +var _cloneDeep2 = _interopRequireDefault(_cloneDeep); + +var _assign = require("lodash/assign"); + +var _assign2 = _interopRequireDefault(_assign); + +var _has = require("lodash/has"); + +var _has2 = _interopRequireDefault(_has); + +var _babelTraverse = require("babel-traverse"); + +var _babelTraverse2 = _interopRequireDefault(_babelTraverse); + +var _babylon = require("babylon"); + +var babylon = _interopRequireWildcard(_babylon); + +var _babelTypes = require("babel-types"); + +var t = _interopRequireWildcard(_babelTypes); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var FROM_TEMPLATE = "_fromTemplate"; +var TEMPLATE_SKIP = (0, _symbol2.default)(); + +function useTemplate(ast, nodes) { + ast = (0, _cloneDeep2.default)(ast); + var _ast = ast; + var program = _ast.program; + + + if (nodes.length) { + (0, _babelTraverse2.default)(ast, templateVisitor, null, nodes); + } + + if (program.body.length > 1) { + return program.body; + } else { + return program.body[0]; + } +} + +var templateVisitor = { + noScope: true, + + enter: function enter(path, args) { + var node = path.node; + + if (node[TEMPLATE_SKIP]) return path.skip(); + + if (t.isExpressionStatement(node)) { + node = node.expression; + } + + var replacement = void 0; + + if (t.isIdentifier(node) && node[FROM_TEMPLATE]) { + if ((0, _has2.default)(args[0], node.name)) { + replacement = args[0][node.name]; + } else if (node.name[0] === "$") { + var i = +node.name.slice(1); + if (args[i]) replacement = args[i]; + } + } + + if (replacement === null) { + path.remove(); + } + + if (replacement) { + replacement[TEMPLATE_SKIP] = true; + path.replaceInline(replacement); + } + }, + exit: function exit(_ref) { + var node = _ref.node; + + if (!node.loc) _babelTraverse2.default.clearNode(node); + } +}; +module.exports = exports["default"]; +},{"babel-runtime/core-js/symbol":147,"babel-traverse":160,"babel-types":193,"babylon":197,"lodash/assign":524,"lodash/cloneDeep":528,"lodash/has":543}],157:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; +exports.scope = exports.path = undefined; + +var _weakMap = require("babel-runtime/core-js/weak-map"); + +var _weakMap2 = _interopRequireDefault(_weakMap); + +exports.clear = clear; + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var path = exports.path = new _weakMap2.default(); +var scope = exports.scope = new _weakMap2.default(); + +function clear() { + exports.path = path = new _weakMap2.default(); + exports.scope = scope = new _weakMap2.default(); +} +},{"babel-runtime/core-js/weak-map":150}],158:[function(require,module,exports){ +(function (process){ +"use strict"; + +exports.__esModule = true; + +var _getIterator2 = require("babel-runtime/core-js/get-iterator"); + +var _getIterator3 = _interopRequireDefault(_getIterator2); + +var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck"); + +var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); + +var _path2 = require("./path"); + +var _path3 = _interopRequireDefault(_path2); + +var _babelTypes = require("babel-types"); + +var t = _interopRequireWildcard(_babelTypes); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var testing = process.env.NODE_ENV === "test"; + +var TraversalContext = function () { + function TraversalContext(scope, opts, state, parentPath) { + (0, _classCallCheck3.default)(this, TraversalContext); + this.queue = null; + + this.parentPath = parentPath; + this.scope = scope; + this.state = state; + this.opts = opts; + } + + TraversalContext.prototype.shouldVisit = function shouldVisit(node) { + var opts = this.opts; + if (opts.enter || opts.exit) return true; + + if (opts[node.type]) return true; + + var keys = t.VISITOR_KEYS[node.type]; + if (!keys || !keys.length) return false; + + for (var _iterator = keys, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_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 key = _ref; + + if (node[key]) return true; + } + + return false; + }; + + TraversalContext.prototype.create = function create(node, obj, key, listKey) { + return _path3.default.get({ + parentPath: this.parentPath, + parent: node, + container: obj, + key: key, + listKey: listKey + }); + }; + + TraversalContext.prototype.maybeQueue = function maybeQueue(path, notPriority) { + if (this.trap) { + throw new Error("Infinite cycle detected"); + } + + if (this.queue) { + if (notPriority) { + this.queue.push(path); + } else { + this.priorityQueue.push(path); + } + } + }; + + TraversalContext.prototype.visitMultiple = function visitMultiple(container, parent, listKey) { + if (container.length === 0) return false; + + var queue = []; + + for (var key = 0; key < container.length; key++) { + var node = container[key]; + if (node && this.shouldVisit(node)) { + queue.push(this.create(parent, container, key, listKey)); + } + } + + return this.visitQueue(queue); + }; + + TraversalContext.prototype.visitSingle = function visitSingle(node, key) { + if (this.shouldVisit(node[key])) { + return this.visitQueue([this.create(node, node, key)]); + } else { + return false; + } + }; + + TraversalContext.prototype.visitQueue = function visitQueue(queue) { + this.queue = queue; + this.priorityQueue = []; + + var visited = []; + var stop = false; + + for (var _iterator2 = queue, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : (0, _getIterator3.default)(_iterator2);;) { + var _ref2; + + if (_isArray2) { + if (_i2 >= _iterator2.length) break; + _ref2 = _iterator2[_i2++]; + } else { + _i2 = _iterator2.next(); + if (_i2.done) break; + _ref2 = _i2.value; + } + + var path = _ref2; + + path.resync(); + + if (path.contexts.length === 0 || path.contexts[path.contexts.length - 1] !== this) { + path.pushContext(this); + } + + if (path.key === null) continue; + + if (testing && queue.length >= 10000) { + this.trap = true; + } + + if (visited.indexOf(path.node) >= 0) continue; + visited.push(path.node); + + if (path.visit()) { + stop = true; + break; + } + + if (this.priorityQueue.length) { + stop = this.visitQueue(this.priorityQueue); + this.priorityQueue = []; + this.queue = queue; + if (stop) break; + } + } + + for (var _iterator3 = queue, _isArray3 = Array.isArray(_iterator3), _i3 = 0, _iterator3 = _isArray3 ? _iterator3 : (0, _getIterator3.default)(_iterator3);;) { + var _ref3; + + if (_isArray3) { + if (_i3 >= _iterator3.length) break; + _ref3 = _iterator3[_i3++]; + } else { + _i3 = _iterator3.next(); + if (_i3.done) break; + _ref3 = _i3.value; + } + + var _path = _ref3; + + _path.popContext(); + } + + this.queue = null; + + return stop; + }; + + TraversalContext.prototype.visit = function visit(node, key) { + var nodes = node[key]; + if (!nodes) return false; + + if (Array.isArray(nodes)) { + return this.visitMultiple(nodes, node, key); + } else { + return this.visitSingle(node, key); + } + }; + + return TraversalContext; +}(); + +exports.default = TraversalContext; +module.exports = exports["default"]; +}).call(this,require('_process')) +},{"./path":167,"_process":594,"babel-runtime/core-js/get-iterator":138,"babel-runtime/helpers/classCallCheck":152,"babel-types":193}],159:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck"); + +var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var Hub = function Hub(file, options) { + (0, _classCallCheck3.default)(this, Hub); + + this.file = file; + this.options = options; +}; + +exports.default = Hub; +module.exports = exports["default"]; +},{"babel-runtime/helpers/classCallCheck":152}],160:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; +exports.visitors = exports.Hub = exports.Scope = exports.NodePath = undefined; + +var _getIterator2 = require("babel-runtime/core-js/get-iterator"); + +var _getIterator3 = _interopRequireDefault(_getIterator2); + +var _path = require("./path"); + +Object.defineProperty(exports, "NodePath", { + enumerable: true, + get: function get() { + return _interopRequireDefault(_path).default; + } +}); + +var _scope = require("./scope"); + +Object.defineProperty(exports, "Scope", { + enumerable: true, + get: function get() { + return _interopRequireDefault(_scope).default; + } +}); + +var _hub = require("./hub"); + +Object.defineProperty(exports, "Hub", { + enumerable: true, + get: function get() { + return _interopRequireDefault(_hub).default; + } +}); +exports.default = traverse; + +var _context = require("./context"); + +var _context2 = _interopRequireDefault(_context); + +var _visitors = require("./visitors"); + +var visitors = _interopRequireWildcard(_visitors); + +var _babelMessages = require("babel-messages"); + +var messages = _interopRequireWildcard(_babelMessages); + +var _includes = require("lodash/includes"); + +var _includes2 = _interopRequireDefault(_includes); + +var _babelTypes = require("babel-types"); + +var t = _interopRequireWildcard(_babelTypes); + +var _cache = require("./cache"); + +var cache = _interopRequireWildcard(_cache); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +exports.visitors = visitors; +function traverse(parent, opts, scope, state, parentPath) { + if (!parent) return; + if (!opts) opts = {}; + + if (!opts.noScope && !scope) { + if (parent.type !== "Program" && parent.type !== "File") { + throw new Error(messages.get("traverseNeedsParent", parent.type)); + } + } + + visitors.explode(opts); + + traverse.node(parent, opts, scope, state, parentPath); +} + +traverse.visitors = visitors; +traverse.verify = visitors.verify; +traverse.explode = visitors.explode; + +traverse.NodePath = require("./path"); +traverse.Scope = require("./scope"); +traverse.Hub = require("./hub"); + +traverse.cheap = function (node, enter) { + return t.traverseFast(node, enter); +}; + +traverse.node = function (node, opts, scope, state, parentPath, skipKeys) { + var keys = t.VISITOR_KEYS[node.type]; + if (!keys) return; + + var context = new _context2.default(scope, opts, state, parentPath); + for (var _iterator = keys, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_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 key = _ref; + + if (skipKeys && skipKeys[key]) continue; + if (context.visit(node, key)) return; + } +}; + +traverse.clearNode = function (node, opts) { + t.removeProperties(node, opts); + + cache.path.delete(node); +}; + +traverse.removeProperties = function (tree, opts) { + t.traverseFast(tree, traverse.clearNode, opts); + return tree; +}; + +function hasBlacklistedType(path, state) { + if (path.node.type === state.type) { + state.has = true; + path.stop(); + } +} + +traverse.hasType = function (tree, scope, type, blacklistTypes) { + if ((0, _includes2.default)(blacklistTypes, tree.type)) return false; + + if (tree.type === type) return true; + + var state = { + has: false, + type: type + }; + + traverse(tree, { + blacklist: blacklistTypes, + enter: hasBlacklistedType + }, scope, state); + + return state.has; +}; + +traverse.clearCache = function () { + cache.clear(); +}; + +traverse.copyCache = function (source, destination) { + if (cache.path.has(source)) { + cache.path.set(destination, cache.path.get(source)); + } +}; +},{"./cache":157,"./context":158,"./hub":159,"./path":167,"./scope":179,"./visitors":181,"babel-messages":76,"babel-runtime/core-js/get-iterator":138,"babel-types":193,"lodash/includes":546}],161:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +var _getIterator2 = require("babel-runtime/core-js/get-iterator"); + +var _getIterator3 = _interopRequireDefault(_getIterator2); + +exports.findParent = findParent; +exports.find = find; +exports.getFunctionParent = getFunctionParent; +exports.getStatementParent = getStatementParent; +exports.getEarliestCommonAncestorFrom = getEarliestCommonAncestorFrom; +exports.getDeepestCommonAncestorFrom = getDeepestCommonAncestorFrom; +exports.getAncestry = getAncestry; +exports.inType = inType; +exports.inShadow = inShadow; + +var _babelTypes = require("babel-types"); + +var t = _interopRequireWildcard(_babelTypes); + +var _index = require("./index"); + +var _index2 = _interopRequireDefault(_index); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function findParent(callback) { + var path = this; + while (path = path.parentPath) { + if (callback(path)) return path; + } + return null; +} + +function find(callback) { + var path = this; + do { + if (callback(path)) return path; + } while (path = path.parentPath); + return null; +} + +function getFunctionParent() { + return this.findParent(function (path) { + return path.isFunction() || path.isProgram(); + }); +} + +function getStatementParent() { + var path = this; + do { + if (Array.isArray(path.container)) { + return path; + } + } while (path = path.parentPath); +} + +function getEarliestCommonAncestorFrom(paths) { + return this.getDeepestCommonAncestorFrom(paths, function (deepest, i, ancestries) { + var earliest = void 0; + var keys = t.VISITOR_KEYS[deepest.type]; + + for (var _iterator = ancestries, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_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 ancestry = _ref; + + var path = ancestry[i + 1]; + + if (!earliest) { + earliest = path; + continue; + } + + if (path.listKey && earliest.listKey === path.listKey) { + if (path.key < earliest.key) { + earliest = path; + continue; + } + } + + var earliestKeyIndex = keys.indexOf(earliest.parentKey); + var currentKeyIndex = keys.indexOf(path.parentKey); + if (earliestKeyIndex > currentKeyIndex) { + earliest = path; + } + } + + return earliest; + }); +} + +function getDeepestCommonAncestorFrom(paths, filter) { + var _this = this; + + if (!paths.length) { + return this; + } + + if (paths.length === 1) { + return paths[0]; + } + + var minDepth = Infinity; + + var lastCommonIndex = void 0, + lastCommon = void 0; + + var ancestries = paths.map(function (path) { + var ancestry = []; + + do { + ancestry.unshift(path); + } while ((path = path.parentPath) && path !== _this); + + if (ancestry.length < minDepth) { + minDepth = ancestry.length; + } + + return ancestry; + }); + + var first = ancestries[0]; + + depthLoop: for (var i = 0; i < minDepth; i++) { + var shouldMatch = first[i]; + + for (var _iterator2 = ancestries, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : (0, _getIterator3.default)(_iterator2);;) { + var _ref2; + + if (_isArray2) { + if (_i2 >= _iterator2.length) break; + _ref2 = _iterator2[_i2++]; + } else { + _i2 = _iterator2.next(); + if (_i2.done) break; + _ref2 = _i2.value; + } + + var ancestry = _ref2; + + if (ancestry[i] !== shouldMatch) { + break depthLoop; + } + } + + lastCommonIndex = i; + lastCommon = shouldMatch; + } + + if (lastCommon) { + if (filter) { + return filter(lastCommon, lastCommonIndex, ancestries); + } else { + return lastCommon; + } + } else { + throw new Error("Couldn't find intersection"); + } +} + +function getAncestry() { + var path = this; + var paths = []; + do { + paths.push(path); + } while (path = path.parentPath); + return paths; +} + +function inType() { + var path = this; + while (path) { + for (var _iterator3 = arguments, _isArray3 = Array.isArray(_iterator3), _i3 = 0, _iterator3 = _isArray3 ? _iterator3 : (0, _getIterator3.default)(_iterator3);;) { + var _ref3; + + if (_isArray3) { + if (_i3 >= _iterator3.length) break; + _ref3 = _iterator3[_i3++]; + } else { + _i3 = _iterator3.next(); + if (_i3.done) break; + _ref3 = _i3.value; + } + + var type = _ref3; + + if (path.node.type === type) return true; + } + path = path.parentPath; + } + + return false; +} + +function inShadow(key) { + var parentFn = this.isFunction() ? this : this.findParent(function (p) { + return p.isFunction(); + }); + if (!parentFn) return; + + if (parentFn.isFunctionExpression() || parentFn.isFunctionDeclaration()) { + var shadow = parentFn.node.shadow; + + if (shadow && (!key || shadow[key] !== false)) { + return parentFn; + } + } else if (parentFn.isArrowFunctionExpression()) { + return parentFn; + } + + return null; +} +},{"./index":167,"babel-runtime/core-js/get-iterator":138,"babel-types":193}],162:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; +exports.shareCommentsWithSiblings = shareCommentsWithSiblings; +exports.addComment = addComment; +exports.addComments = addComments; +function shareCommentsWithSiblings() { + var node = this.node; + if (!node) return; + + var trailing = node.trailingComments; + var leading = node.leadingComments; + if (!trailing && !leading) return; + + var prev = this.getSibling(this.key - 1); + var next = this.getSibling(this.key + 1); + + if (!prev.node) prev = next; + if (!next.node) next = prev; + + prev.addComments("trailing", leading); + next.addComments("leading", trailing); +} + +function addComment(type, content, line) { + this.addComments(type, [{ + type: line ? "CommentLine" : "CommentBlock", + value: content + }]); +} + +function addComments(type, comments) { + if (!comments) return; + + var node = this.node; + if (!node) return; + + var key = type + "Comments"; + + if (node[key]) { + node[key] = node[key].concat(comments); + } else { + node[key] = comments; + } +} +},{}],163:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +var _getIterator2 = require("babel-runtime/core-js/get-iterator"); + +var _getIterator3 = _interopRequireDefault(_getIterator2); + +exports.call = call; +exports._call = _call; +exports.isBlacklisted = isBlacklisted; +exports.visit = visit; +exports.skip = skip; +exports.skipKey = skipKey; +exports.stop = stop; +exports.setScope = setScope; +exports.setContext = setContext; +exports.resync = resync; +exports._resyncParent = _resyncParent; +exports._resyncKey = _resyncKey; +exports._resyncList = _resyncList; +exports._resyncRemoved = _resyncRemoved; +exports.popContext = popContext; +exports.pushContext = pushContext; +exports.setup = setup; +exports.setKey = setKey; +exports.requeue = requeue; +exports._getQueueContexts = _getQueueContexts; + +var _index = require("../index"); + +var _index2 = _interopRequireDefault(_index); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function call(key) { + var opts = this.opts; + + this.debug(function () { + return key; + }); + + if (this.node) { + if (this._call(opts[key])) return true; + } + + if (this.node) { + return this._call(opts[this.node.type] && opts[this.node.type][key]); + } + + return false; +} + +function _call(fns) { + if (!fns) return false; + + for (var _iterator = fns, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_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 fn = _ref; + + if (!fn) continue; + + var node = this.node; + if (!node) return true; + + var ret = fn.call(this.state, this, this.state); + if (ret) throw new Error("Unexpected return value from visitor method " + fn); + + if (this.node !== node) return true; + + if (this.shouldStop || this.shouldSkip || this.removed) return true; + } + + return false; +} + +function isBlacklisted() { + var blacklist = this.opts.blacklist; + return blacklist && blacklist.indexOf(this.node.type) > -1; +} + +function visit() { + if (!this.node) { + return false; + } + + if (this.isBlacklisted()) { + return false; + } + + if (this.opts.shouldSkip && this.opts.shouldSkip(this)) { + return false; + } + + if (this.call("enter") || this.shouldSkip) { + this.debug(function () { + return "Skip..."; + }); + return this.shouldStop; + } + + this.debug(function () { + return "Recursing into..."; + }); + _index2.default.node(this.node, this.opts, this.scope, this.state, this, this.skipKeys); + + this.call("exit"); + + return this.shouldStop; +} + +function skip() { + this.shouldSkip = true; +} + +function skipKey(key) { + this.skipKeys[key] = true; +} + +function stop() { + this.shouldStop = true; + this.shouldSkip = true; +} + +function setScope() { + if (this.opts && this.opts.noScope) return; + + var target = this.context && this.context.scope; + + if (!target) { + var path = this.parentPath; + while (path && !target) { + if (path.opts && path.opts.noScope) return; + + target = path.scope; + path = path.parentPath; + } + } + + this.scope = this.getScope(target); + if (this.scope) this.scope.init(); +} + +function setContext(context) { + this.shouldSkip = false; + this.shouldStop = false; + this.removed = false; + this.skipKeys = {}; + + if (context) { + this.context = context; + this.state = context.state; + this.opts = context.opts; + } + + this.setScope(); + + return this; +} + +function resync() { + if (this.removed) return; + + this._resyncParent(); + this._resyncList(); + this._resyncKey(); +} + +function _resyncParent() { + if (this.parentPath) { + this.parent = this.parentPath.node; + } +} + +function _resyncKey() { + if (!this.container) return; + + if (this.node === this.container[this.key]) return; + + if (Array.isArray(this.container)) { + for (var i = 0; i < this.container.length; i++) { + if (this.container[i] === this.node) { + return this.setKey(i); + } + } + } else { + for (var key in this.container) { + if (this.container[key] === this.node) { + return this.setKey(key); + } + } + } + + this.key = null; +} + +function _resyncList() { + if (!this.parent || !this.inList) return; + + var newContainer = this.parent[this.listKey]; + if (this.container === newContainer) return; + + this.container = newContainer || null; +} + +function _resyncRemoved() { + if (this.key == null || !this.container || this.container[this.key] !== this.node) { + this._markRemoved(); + } +} + +function popContext() { + this.contexts.pop(); + this.setContext(this.contexts[this.contexts.length - 1]); +} + +function pushContext(context) { + this.contexts.push(context); + this.setContext(context); +} + +function setup(parentPath, container, listKey, key) { + this.inList = !!listKey; + this.listKey = listKey; + this.parentKey = listKey || key; + this.container = container; + + this.parentPath = parentPath || this.parentPath; + this.setKey(key); +} + +function setKey(key) { + this.key = key; + this.node = this.container[this.key]; + this.type = this.node && this.node.type; +} + +function requeue() { + var pathToQueue = arguments.length <= 0 || arguments[0] === undefined ? this : arguments[0]; + + if (pathToQueue.removed) return; + + var contexts = this.contexts; + + for (var _iterator2 = contexts, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : (0, _getIterator3.default)(_iterator2);;) { + var _ref2; + + if (_isArray2) { + if (_i2 >= _iterator2.length) break; + _ref2 = _iterator2[_i2++]; + } else { + _i2 = _iterator2.next(); + if (_i2.done) break; + _ref2 = _i2.value; + } + + var context = _ref2; + + context.maybeQueue(pathToQueue); + } +} + +function _getQueueContexts() { + var path = this; + var contexts = this.contexts; + while (!contexts.length) { + path = path.parentPath; + contexts = path.contexts; + } + return contexts; +} +},{"../index":160,"babel-runtime/core-js/get-iterator":138}],164:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; +exports.toComputedKey = toComputedKey; +exports.ensureBlock = ensureBlock; +exports.arrowFunctionToShadowed = arrowFunctionToShadowed; + +var _babelTypes = require("babel-types"); + +var t = _interopRequireWildcard(_babelTypes); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function toComputedKey() { + var node = this.node; + + var key = void 0; + if (this.isMemberExpression()) { + key = node.property; + } else if (this.isProperty() || this.isMethod()) { + key = node.key; + } else { + throw new ReferenceError("todo"); + } + + if (!node.computed) { + if (t.isIdentifier(key)) key = t.stringLiteral(key.name); + } + + return key; +} + +function ensureBlock() { + return t.ensureBlock(this.node); +} + +function arrowFunctionToShadowed() { + if (!this.isArrowFunctionExpression()) return; + + this.ensureBlock(); + + var node = this.node; + + node.expression = false; + node.type = "FunctionExpression"; + node.shadow = node.shadow || true; +} +},{"babel-types":193}],165:[function(require,module,exports){ +(function (global){ +"use strict"; + +exports.__esModule = true; + +var _typeof2 = require("babel-runtime/helpers/typeof"); + +var _typeof3 = _interopRequireDefault(_typeof2); + +var _getIterator2 = require("babel-runtime/core-js/get-iterator"); + +var _getIterator3 = _interopRequireDefault(_getIterator2); + +var _map = require("babel-runtime/core-js/map"); + +var _map2 = _interopRequireDefault(_map); + +exports.evaluateTruthy = evaluateTruthy; +exports.evaluate = evaluate; + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var VALID_CALLEES = ["String", "Number", "Math"]; +var INVALID_METHODS = ["random"]; + +function evaluateTruthy() { + var res = this.evaluate(); + if (res.confident) return !!res.value; +} + +function evaluate() { + var confident = true; + var deoptPath = void 0; + var seen = new _map2.default(); + + function deopt(path) { + if (!confident) return; + deoptPath = path; + confident = false; + } + + var value = evaluate(this); + if (!confident) value = undefined; + return { + confident: confident, + deopt: deoptPath, + value: value + }; + + function evaluate(path) { + var node = path.node; + + + if (seen.has(node)) { + var existing = seen.get(node); + if (existing.resolved) { + return existing.value; + } else { + deopt(path); + return; + } + } else { + var item = { resolved: false }; + seen.set(node, item); + + var val = _evaluate(path); + if (confident) { + item.resolved = true; + item.value = val; + } + return val; + } + } + + function _evaluate(path) { + if (!confident) return; + + var node = path.node; + + + if (path.isSequenceExpression()) { + var exprs = path.get("expressions"); + return evaluate(exprs[exprs.length - 1]); + } + + if (path.isStringLiteral() || path.isNumericLiteral() || path.isBooleanLiteral()) { + return node.value; + } + + if (path.isNullLiteral()) { + return null; + } + + if (path.isTemplateLiteral()) { + var str = ""; + + var i = 0; + var _exprs = path.get("expressions"); + + for (var _iterator = node.quasis, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_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 elem = _ref; + + if (!confident) break; + + str += elem.value.cooked; + + var expr = _exprs[i++]; + if (expr) str += String(evaluate(expr)); + } + + if (!confident) return; + return str; + } + + if (path.isConditionalExpression()) { + var testResult = evaluate(path.get("test")); + if (!confident) return; + if (testResult) { + return evaluate(path.get("consequent")); + } else { + return evaluate(path.get("alternate")); + } + } + + if (path.isExpressionWrapper()) { + return evaluate(path.get("expression")); + } + + if (path.isMemberExpression() && !path.parentPath.isCallExpression({ callee: node })) { + var property = path.get("property"); + var object = path.get("object"); + + if (object.isLiteral() && property.isIdentifier()) { + var _value = object.node.value; + var type = typeof _value === "undefined" ? "undefined" : (0, _typeof3.default)(_value); + if (type === "number" || type === "string") { + return _value[property.node.name]; + } + } + } + + if (path.isReferencedIdentifier()) { + var binding = path.scope.getBinding(node.name); + + if (binding && binding.constantViolations.length > 0) { + return deopt(binding.path); + } + + if (binding && binding.hasValue) { + return binding.value; + } else { + if (node.name === "undefined") { + return undefined; + } else if (node.name === "Infinity") { + return Infinity; + } else if (node.name === "NaN") { + return NaN; + } + + var resolved = path.resolve(); + if (resolved === path) { + return deopt(path); + } else { + return evaluate(resolved); + } + } + } + + if (path.isUnaryExpression({ prefix: true })) { + if (node.operator === "void") { + return undefined; + } + + var argument = path.get("argument"); + if (node.operator === "typeof" && (argument.isFunction() || argument.isClass())) { + return "function"; + } + + var arg = evaluate(argument); + if (!confident) return; + switch (node.operator) { + case "!": + return !arg; + case "+": + return +arg; + case "-": + return -arg; + case "~": + return ~arg; + case "typeof": + return typeof arg === "undefined" ? "undefined" : (0, _typeof3.default)(arg); + } + } + + if (path.isArrayExpression()) { + var arr = []; + var elems = path.get("elements"); + for (var _iterator2 = elems, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : (0, _getIterator3.default)(_iterator2);;) { + var _ref2; + + if (_isArray2) { + if (_i2 >= _iterator2.length) break; + _ref2 = _iterator2[_i2++]; + } else { + _i2 = _iterator2.next(); + if (_i2.done) break; + _ref2 = _i2.value; + } + + var _elem = _ref2; + + _elem = _elem.evaluate(); + + if (_elem.confident) { + arr.push(_elem.value); + } else { + return deopt(_elem); + } + } + return arr; + } + + if (path.isObjectExpression()) {} + + if (path.isLogicalExpression()) { + var wasConfident = confident; + var left = evaluate(path.get("left")); + var leftConfident = confident; + confident = wasConfident; + var right = evaluate(path.get("right")); + var rightConfident = confident; + confident = leftConfident && rightConfident; + + switch (node.operator) { + case "||": + if (left && leftConfident) { + confident = true; + return left; + } + + if (!confident) return; + + return left || right; + case "&&": + if (!left && leftConfident || !right && rightConfident) { + confident = true; + } + + if (!confident) return; + + return left && right; + } + } + + if (path.isBinaryExpression()) { + var _left = evaluate(path.get("left")); + if (!confident) return; + var _right = evaluate(path.get("right")); + if (!confident) return; + + switch (node.operator) { + case "-": + return _left - _right; + case "+": + return _left + _right; + case "/": + return _left / _right; + case "*": + return _left * _right; + case "%": + return _left % _right; + case "**": + return Math.pow(_left, _right); + case "<": + return _left < _right; + case ">": + return _left > _right; + case "<=": + return _left <= _right; + case ">=": + return _left >= _right; + case "==": + return _left == _right; + case "!=": + return _left != _right; + case "===": + return _left === _right; + case "!==": + return _left !== _right; + case "|": + return _left | _right; + case "&": + return _left & _right; + case "^": + return _left ^ _right; + case "<<": + return _left << _right; + case ">>": + return _left >> _right; + case ">>>": + return _left >>> _right; + } + } + + if (path.isCallExpression()) { + var callee = path.get("callee"); + var context = void 0; + var func = void 0; + + if (callee.isIdentifier() && !path.scope.getBinding(callee.node.name, true) && VALID_CALLEES.indexOf(callee.node.name) >= 0) { + func = global[node.callee.name]; + } + + if (callee.isMemberExpression()) { + var _object = callee.get("object"); + var _property = callee.get("property"); + + if (_object.isIdentifier() && _property.isIdentifier() && VALID_CALLEES.indexOf(_object.node.name) >= 0 && INVALID_METHODS.indexOf(_property.node.name) < 0) { + context = global[_object.node.name]; + func = context[_property.node.name]; + } + + if (_object.isLiteral() && _property.isIdentifier()) { + var _type = (0, _typeof3.default)(_object.node.value); + if (_type === "string" || _type === "number") { + context = _object.node.value; + func = context[_property.node.name]; + } + } + } + + if (func) { + var args = path.get("arguments").map(evaluate); + if (!confident) return; + + return func.apply(context, args); + } + } + + deopt(path); + } +} +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"babel-runtime/core-js/get-iterator":138,"babel-runtime/core-js/map":140,"babel-runtime/helpers/typeof":155}],166:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +var _getIterator2 = require("babel-runtime/core-js/get-iterator"); + +var _getIterator3 = _interopRequireDefault(_getIterator2); + +exports.getStatementParent = getStatementParent; +exports.getOpposite = getOpposite; +exports.getCompletionRecords = getCompletionRecords; +exports.getSibling = getSibling; +exports.get = get; +exports._getKey = _getKey; +exports._getPattern = _getPattern; +exports.getBindingIdentifiers = getBindingIdentifiers; +exports.getOuterBindingIdentifiers = getOuterBindingIdentifiers; + +var _index = require("./index"); + +var _index2 = _interopRequireDefault(_index); + +var _babelTypes = require("babel-types"); + +var t = _interopRequireWildcard(_babelTypes); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function getStatementParent() { + var path = this; + + do { + if (!path.parentPath || Array.isArray(path.container) && path.isStatement()) { + break; + } else { + path = path.parentPath; + } + } while (path); + + if (path && (path.isProgram() || path.isFile())) { + throw new Error("File/Program node, we can't possibly find a statement parent to this"); + } + + return path; +} + +function getOpposite() { + if (this.key === "left") { + return this.getSibling("right"); + } else if (this.key === "right") { + return this.getSibling("left"); + } +} + +function getCompletionRecords() { + var paths = []; + + var add = function add(path) { + if (path) paths = paths.concat(path.getCompletionRecords()); + }; + + if (this.isIfStatement()) { + add(this.get("consequent")); + add(this.get("alternate")); + } else if (this.isDoExpression() || this.isFor() || this.isWhile()) { + add(this.get("body")); + } else if (this.isProgram() || this.isBlockStatement()) { + add(this.get("body").pop()); + } else if (this.isFunction()) { + return this.get("body").getCompletionRecords(); + } else if (this.isTryStatement()) { + add(this.get("block")); + add(this.get("handler")); + add(this.get("finalizer")); + } else { + paths.push(this); + } + + return paths; +} + +function getSibling(key) { + return _index2.default.get({ + parentPath: this.parentPath, + parent: this.parent, + container: this.container, + listKey: this.listKey, + key: key + }); +} + +function get(key, context) { + if (context === true) context = this.context; + var parts = key.split("."); + if (parts.length === 1) { + return this._getKey(key, context); + } else { + return this._getPattern(parts, context); + } +} + +function _getKey(key, context) { + var _this = this; + + var node = this.node; + var container = node[key]; + + if (Array.isArray(container)) { + return container.map(function (_, i) { + return _index2.default.get({ + listKey: key, + parentPath: _this, + parent: node, + container: container, + key: i + }).setContext(context); + }); + } else { + return _index2.default.get({ + parentPath: this, + parent: node, + container: node, + key: key + }).setContext(context); + } +} + +function _getPattern(parts, context) { + var path = this; + for (var _iterator = parts, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_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 part = _ref; + + if (part === ".") { + path = path.parentPath; + } else { + if (Array.isArray(path)) { + path = path[part]; + } else { + path = path.get(part, context); + } + } + } + return path; +} + +function getBindingIdentifiers(duplicates) { + return t.getBindingIdentifiers(this.node, duplicates); +} + +function getOuterBindingIdentifiers(duplicates) { + return t.getOuterBindingIdentifiers(this.node, duplicates); +} +},{"./index":167,"babel-runtime/core-js/get-iterator":138,"babel-types":193}],167:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +var _getIterator2 = require("babel-runtime/core-js/get-iterator"); + +var _getIterator3 = _interopRequireDefault(_getIterator2); + +var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck"); + +var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); + +var _virtualTypes = require("./lib/virtual-types"); + +var virtualTypes = _interopRequireWildcard(_virtualTypes); + +var _debug2 = require("debug"); + +var _debug3 = _interopRequireDefault(_debug2); + +var _invariant = require("invariant"); + +var _invariant2 = _interopRequireDefault(_invariant); + +var _index = require("../index"); + +var _index2 = _interopRequireDefault(_index); + +var _assign = require("lodash/assign"); + +var _assign2 = _interopRequireDefault(_assign); + +var _scope = require("../scope"); + +var _scope2 = _interopRequireDefault(_scope); + +var _babelTypes = require("babel-types"); + +var t = _interopRequireWildcard(_babelTypes); + +var _cache = require("../cache"); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var _debug = (0, _debug3.default)("babel"); + +var NodePath = function () { + function NodePath(hub, parent) { + (0, _classCallCheck3.default)(this, NodePath); + + this.parent = parent; + this.hub = hub; + this.contexts = []; + this.data = {}; + this.shouldSkip = false; + this.shouldStop = false; + this.removed = false; + this.state = null; + this.opts = null; + this.skipKeys = null; + this.parentPath = null; + this.context = null; + this.container = null; + this.listKey = null; + this.inList = false; + this.parentKey = null; + this.key = null; + this.node = null; + this.scope = null; + this.type = null; + this.typeAnnotation = null; + } + + NodePath.get = function get(_ref) { + var hub = _ref.hub; + var parentPath = _ref.parentPath; + var parent = _ref.parent; + var container = _ref.container; + var listKey = _ref.listKey; + var key = _ref.key; + + if (!hub && parentPath) { + hub = parentPath.hub; + } + + (0, _invariant2.default)(parent, "To get a node path the parent needs to exist"); + + var targetNode = container[key]; + + var paths = _cache.path.get(parent) || []; + if (!_cache.path.has(parent)) { + _cache.path.set(parent, paths); + } + + var path = void 0; + + for (var i = 0; i < paths.length; i++) { + var pathCheck = paths[i]; + if (pathCheck.node === targetNode) { + path = pathCheck; + break; + } + } + + if (!path) { + path = new NodePath(hub, parent); + paths.push(path); + } + + path.setup(parentPath, container, listKey, key); + + return path; + }; + + NodePath.prototype.getScope = function getScope(scope) { + var ourScope = scope; + + if (this.isScope()) { + ourScope = new _scope2.default(this, scope); + } + + return ourScope; + }; + + NodePath.prototype.setData = function setData(key, val) { + return this.data[key] = val; + }; + + NodePath.prototype.getData = function getData(key, def) { + var val = this.data[key]; + if (!val && def) val = this.data[key] = def; + return val; + }; + + NodePath.prototype.buildCodeFrameError = function buildCodeFrameError(msg) { + var Error = arguments.length <= 1 || arguments[1] === undefined ? SyntaxError : arguments[1]; + + return this.hub.file.buildCodeFrameError(this.node, msg, Error); + }; + + NodePath.prototype.traverse = function traverse(visitor, state) { + (0, _index2.default)(this.node, visitor, this.scope, state, this); + }; + + NodePath.prototype.mark = function mark(type, message) { + this.hub.file.metadata.marked.push({ + type: type, + message: message, + loc: this.node.loc + }); + }; + + NodePath.prototype.set = function set(key, node) { + t.validate(this.node, key, node); + this.node[key] = node; + }; + + NodePath.prototype.getPathLocation = function getPathLocation() { + var parts = []; + var path = this; + do { + var key = path.key; + if (path.inList) key = path.listKey + "[" + key + "]"; + parts.unshift(key); + } while (path = path.parentPath); + return parts.join("."); + }; + + NodePath.prototype.debug = function debug(buildMessage) { + if (!_debug.enabled) return; + _debug(this.getPathLocation() + " " + this.type + ": " + buildMessage()); + }; + + return NodePath; +}(); + +exports.default = NodePath; + + +(0, _assign2.default)(NodePath.prototype, require("./ancestry")); +(0, _assign2.default)(NodePath.prototype, require("./inference")); +(0, _assign2.default)(NodePath.prototype, require("./replacement")); +(0, _assign2.default)(NodePath.prototype, require("./evaluation")); +(0, _assign2.default)(NodePath.prototype, require("./conversion")); +(0, _assign2.default)(NodePath.prototype, require("./introspection")); +(0, _assign2.default)(NodePath.prototype, require("./context")); +(0, _assign2.default)(NodePath.prototype, require("./removal")); +(0, _assign2.default)(NodePath.prototype, require("./modification")); +(0, _assign2.default)(NodePath.prototype, require("./family")); +(0, _assign2.default)(NodePath.prototype, require("./comments")); + +var _loop2 = function _loop2() { + if (_isArray) { + if (_i >= _iterator.length) return "break"; + _ref2 = _iterator[_i++]; + } else { + _i = _iterator.next(); + if (_i.done) return "break"; + _ref2 = _i.value; + } + + var type = _ref2; + + var typeKey = "is" + type; + NodePath.prototype[typeKey] = function (opts) { + return t[typeKey](this.node, opts); + }; + + NodePath.prototype["assert" + type] = function (opts) { + if (!this[typeKey](opts)) { + throw new TypeError("Expected node path of type " + type); + } + }; +}; + +for (var _iterator = t.TYPES, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) { + var _ref2; + + var _ret2 = _loop2(); + + if (_ret2 === "break") break; +} + +var _loop = function _loop(type) { + if (type[0] === "_") return "continue"; + if (t.TYPES.indexOf(type) < 0) t.TYPES.push(type); + + var virtualType = virtualTypes[type]; + + NodePath.prototype["is" + type] = function (opts) { + return virtualType.checkPath(this, opts); + }; +}; + +for (var type in virtualTypes) { + var _ret = _loop(type); + + if (_ret === "continue") continue; +} +module.exports = exports["default"]; +},{"../cache":157,"../index":160,"../scope":179,"./ancestry":161,"./comments":162,"./context":163,"./conversion":164,"./evaluation":165,"./family":166,"./inference":168,"./introspection":171,"./lib/virtual-types":174,"./modification":175,"./removal":176,"./replacement":177,"babel-runtime/core-js/get-iterator":138,"babel-runtime/helpers/classCallCheck":152,"babel-types":193,"debug":340,"invariant":353,"lodash/assign":524}],168:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +var _getIterator2 = require("babel-runtime/core-js/get-iterator"); + +var _getIterator3 = _interopRequireDefault(_getIterator2); + +exports.getTypeAnnotation = getTypeAnnotation; +exports._getTypeAnnotation = _getTypeAnnotation; +exports.isBaseType = isBaseType; +exports.couldBeBaseType = couldBeBaseType; +exports.baseTypeStrictlyMatches = baseTypeStrictlyMatches; +exports.isGenericType = isGenericType; + +var _inferers = require("./inferers"); + +var inferers = _interopRequireWildcard(_inferers); + +var _babelTypes = require("babel-types"); + +var t = _interopRequireWildcard(_babelTypes); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function getTypeAnnotation() { + if (this.typeAnnotation) return this.typeAnnotation; + + var type = this._getTypeAnnotation() || t.anyTypeAnnotation(); + if (t.isTypeAnnotation(type)) type = type.typeAnnotation; + return this.typeAnnotation = type; +} + +function _getTypeAnnotation() { + var node = this.node; + + if (!node) { + if (this.key === "init" && this.parentPath.isVariableDeclarator()) { + var declar = this.parentPath.parentPath; + var declarParent = declar.parentPath; + + if (declar.key === "left" && declarParent.isForInStatement()) { + return t.stringTypeAnnotation(); + } + + if (declar.key === "left" && declarParent.isForOfStatement()) { + return t.anyTypeAnnotation(); + } + + return t.voidTypeAnnotation(); + } else { + return; + } + } + + if (node.typeAnnotation) { + return node.typeAnnotation; + } + + var inferer = inferers[node.type]; + if (inferer) { + return inferer.call(this, node); + } + + inferer = inferers[this.parentPath.type]; + if (inferer && inferer.validParent) { + return this.parentPath.getTypeAnnotation(); + } +} + +function isBaseType(baseName, soft) { + return _isBaseType(baseName, this.getTypeAnnotation(), soft); +} + +function _isBaseType(baseName, type, soft) { + if (baseName === "string") { + return t.isStringTypeAnnotation(type); + } else if (baseName === "number") { + return t.isNumberTypeAnnotation(type); + } else if (baseName === "boolean") { + return t.isBooleanTypeAnnotation(type); + } else if (baseName === "any") { + return t.isAnyTypeAnnotation(type); + } else if (baseName === "mixed") { + return t.isMixedTypeAnnotation(type); + } else if (baseName === "void") { + return t.isVoidTypeAnnotation(type); + } else { + if (soft) { + return false; + } else { + throw new Error("Unknown base type " + baseName); + } + } +} + +function couldBeBaseType(name) { + var type = this.getTypeAnnotation(); + if (t.isAnyTypeAnnotation(type)) return true; + + if (t.isUnionTypeAnnotation(type)) { + for (var _iterator = type.types, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_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 type2 = _ref; + + if (t.isAnyTypeAnnotation(type2) || _isBaseType(name, type2, true)) { + return true; + } + } + return false; + } else { + return _isBaseType(name, type, true); + } +} + +function baseTypeStrictlyMatches(right) { + var left = this.getTypeAnnotation(); + right = right.getTypeAnnotation(); + + if (!t.isAnyTypeAnnotation(left) && t.isFlowBaseAnnotation(left)) { + return right.type === left.type; + } +} + +function isGenericType(genericName) { + var type = this.getTypeAnnotation(); + return t.isGenericTypeAnnotation(type) && t.isIdentifier(type.id, { name: genericName }); +} +},{"./inferers":170,"babel-runtime/core-js/get-iterator":138,"babel-types":193}],169:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +var _getIterator2 = require("babel-runtime/core-js/get-iterator"); + +var _getIterator3 = _interopRequireDefault(_getIterator2); + +exports.default = function (node) { + if (!this.isReferenced()) return; + + var binding = this.scope.getBinding(node.name); + if (binding) { + if (binding.identifier.typeAnnotation) { + return binding.identifier.typeAnnotation; + } else { + return getTypeAnnotationBindingConstantViolations(this, node.name); + } + } + + if (node.name === "undefined") { + return t.voidTypeAnnotation(); + } else if (node.name === "NaN" || node.name === "Infinity") { + return t.numberTypeAnnotation(); + } else if (node.name === "arguments") {} +}; + +var _babelTypes = require("babel-types"); + +var t = _interopRequireWildcard(_babelTypes); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function getTypeAnnotationBindingConstantViolations(path, name) { + var binding = path.scope.getBinding(name); + + var types = []; + path.typeAnnotation = t.unionTypeAnnotation(types); + + var functionConstantViolations = []; + var constantViolations = getConstantViolationsBefore(binding, path, functionConstantViolations); + + var testType = getConditionalAnnotation(path, name); + if (testType) { + (function () { + var testConstantViolations = getConstantViolationsBefore(binding, testType.ifStatement); + + constantViolations = constantViolations.filter(function (path) { + return testConstantViolations.indexOf(path) < 0; + }); + + types.push(testType.typeAnnotation); + })(); + } + + if (constantViolations.length) { + constantViolations = constantViolations.concat(functionConstantViolations); + + for (var _iterator = constantViolations, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_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 violation = _ref; + + types.push(violation.getTypeAnnotation()); + } + } + + if (types.length) { + return t.createUnionTypeAnnotation(types); + } +} + +function getConstantViolationsBefore(binding, path, functions) { + var violations = binding.constantViolations.slice(); + violations.unshift(binding.path); + return violations.filter(function (violation) { + violation = violation.resolve(); + var status = violation._guessExecutionStatusRelativeTo(path); + if (functions && status === "function") functions.push(violation); + return status === "before"; + }); +} + +function inferAnnotationFromBinaryExpression(name, path) { + var operator = path.node.operator; + + var right = path.get("right").resolve(); + var left = path.get("left").resolve(); + + var target = void 0; + if (left.isIdentifier({ name: name })) { + target = right; + } else if (right.isIdentifier({ name: name })) { + target = left; + } + if (target) { + if (operator === "===") { + return target.getTypeAnnotation(); + } else if (t.BOOLEAN_NUMBER_BINARY_OPERATORS.indexOf(operator) >= 0) { + return t.numberTypeAnnotation(); + } else { + return; + } + } else { + if (operator !== "===") return; + } + + var typeofPath = void 0; + var typePath = void 0; + if (left.isUnaryExpression({ operator: "typeof" })) { + typeofPath = left; + typePath = right; + } else if (right.isUnaryExpression({ operator: "typeof" })) { + typeofPath = right; + typePath = left; + } + if (!typePath && !typeofPath) return; + + typePath = typePath.resolve(); + if (!typePath.isLiteral()) return; + + var typeValue = typePath.node.value; + if (typeof typeValue !== "string") return; + + if (!typeofPath.get("argument").isIdentifier({ name: name })) return; + + return t.createTypeAnnotationBasedOnTypeof(typePath.node.value); +} + +function getParentConditionalPath(path) { + var parentPath = void 0; + while (parentPath = path.parentPath) { + if (parentPath.isIfStatement() || parentPath.isConditionalExpression()) { + if (path.key === "test") { + return; + } else { + return parentPath; + } + } else { + path = parentPath; + } + } +} + +function getConditionalAnnotation(path, name) { + var ifStatement = getParentConditionalPath(path); + if (!ifStatement) return; + + var test = ifStatement.get("test"); + var paths = [test]; + var types = []; + + do { + var _path = paths.shift().resolve(); + + if (_path.isLogicalExpression()) { + paths.push(_path.get("left")); + paths.push(_path.get("right")); + } + + if (_path.isBinaryExpression()) { + var type = inferAnnotationFromBinaryExpression(name, _path); + if (type) types.push(type); + } + } while (paths.length); + + if (types.length) { + return { + typeAnnotation: t.createUnionTypeAnnotation(types), + ifStatement: ifStatement + }; + } else { + return getConditionalAnnotation(ifStatement, name); + } +} +module.exports = exports["default"]; +},{"babel-runtime/core-js/get-iterator":138,"babel-types":193}],170:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; +exports.Class = exports.Function = exports.Identifier = undefined; + +var _infererReference = require("./inferer-reference"); + +Object.defineProperty(exports, "Identifier", { + enumerable: true, + get: function get() { + return _interopRequireDefault(_infererReference).default; + } +}); +exports.VariableDeclarator = VariableDeclarator; +exports.TypeCastExpression = TypeCastExpression; +exports.NewExpression = NewExpression; +exports.TemplateLiteral = TemplateLiteral; +exports.UnaryExpression = UnaryExpression; +exports.BinaryExpression = BinaryExpression; +exports.LogicalExpression = LogicalExpression; +exports.ConditionalExpression = ConditionalExpression; +exports.SequenceExpression = SequenceExpression; +exports.AssignmentExpression = AssignmentExpression; +exports.UpdateExpression = UpdateExpression; +exports.StringLiteral = StringLiteral; +exports.NumericLiteral = NumericLiteral; +exports.BooleanLiteral = BooleanLiteral; +exports.NullLiteral = NullLiteral; +exports.RegExpLiteral = RegExpLiteral; +exports.ObjectExpression = ObjectExpression; +exports.ArrayExpression = ArrayExpression; +exports.RestElement = RestElement; +exports.CallExpression = CallExpression; +exports.TaggedTemplateExpression = TaggedTemplateExpression; + +var _babelTypes = require("babel-types"); + +var t = _interopRequireWildcard(_babelTypes); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function VariableDeclarator() { + var id = this.get("id"); + + if (id.isIdentifier()) { + return this.get("init").getTypeAnnotation(); + } else { + return; + } +} + +function TypeCastExpression(node) { + return node.typeAnnotation; +} + +TypeCastExpression.validParent = true; + +function NewExpression(node) { + if (this.get("callee").isIdentifier()) { + return t.genericTypeAnnotation(node.callee); + } +} + +function TemplateLiteral() { + return t.stringTypeAnnotation(); +} + +function UnaryExpression(node) { + var operator = node.operator; + + if (operator === "void") { + return t.voidTypeAnnotation(); + } else if (t.NUMBER_UNARY_OPERATORS.indexOf(operator) >= 0) { + return t.numberTypeAnnotation(); + } else if (t.STRING_UNARY_OPERATORS.indexOf(operator) >= 0) { + return t.stringTypeAnnotation(); + } else if (t.BOOLEAN_UNARY_OPERATORS.indexOf(operator) >= 0) { + return t.booleanTypeAnnotation(); + } +} + +function BinaryExpression(node) { + var operator = node.operator; + + if (t.NUMBER_BINARY_OPERATORS.indexOf(operator) >= 0) { + return t.numberTypeAnnotation(); + } else if (t.BOOLEAN_BINARY_OPERATORS.indexOf(operator) >= 0) { + return t.booleanTypeAnnotation(); + } else if (operator === "+") { + var right = this.get("right"); + var left = this.get("left"); + + if (left.isBaseType("number") && right.isBaseType("number")) { + return t.numberTypeAnnotation(); + } else if (left.isBaseType("string") || right.isBaseType("string")) { + return t.stringTypeAnnotation(); + } + + return t.unionTypeAnnotation([t.stringTypeAnnotation(), t.numberTypeAnnotation()]); + } +} + +function LogicalExpression() { + return t.createUnionTypeAnnotation([this.get("left").getTypeAnnotation(), this.get("right").getTypeAnnotation()]); +} + +function ConditionalExpression() { + return t.createUnionTypeAnnotation([this.get("consequent").getTypeAnnotation(), this.get("alternate").getTypeAnnotation()]); +} + +function SequenceExpression() { + return this.get("expressions").pop().getTypeAnnotation(); +} + +function AssignmentExpression() { + return this.get("right").getTypeAnnotation(); +} + +function UpdateExpression(node) { + var operator = node.operator; + if (operator === "++" || operator === "--") { + return t.numberTypeAnnotation(); + } +} + +function StringLiteral() { + return t.stringTypeAnnotation(); +} + +function NumericLiteral() { + return t.numberTypeAnnotation(); +} + +function BooleanLiteral() { + return t.booleanTypeAnnotation(); +} + +function NullLiteral() { + return t.nullLiteralTypeAnnotation(); +} + +function RegExpLiteral() { + return t.genericTypeAnnotation(t.identifier("RegExp")); +} + +function ObjectExpression() { + return t.genericTypeAnnotation(t.identifier("Object")); +} + +function ArrayExpression() { + return t.genericTypeAnnotation(t.identifier("Array")); +} + +function RestElement() { + return ArrayExpression(); +} + +RestElement.validParent = true; + +function Func() { + return t.genericTypeAnnotation(t.identifier("Function")); +} + +exports.Function = Func; +exports.Class = Func; +function CallExpression() { + return resolveCall(this.get("callee")); +} + +function TaggedTemplateExpression() { + return resolveCall(this.get("tag")); +} + +function resolveCall(callee) { + callee = callee.resolve(); + + if (callee.isFunction()) { + if (callee.is("async")) { + if (callee.is("generator")) { + return t.genericTypeAnnotation(t.identifier("AsyncIterator")); + } else { + return t.genericTypeAnnotation(t.identifier("Promise")); + } + } else { + if (callee.node.returnType) { + return callee.node.returnType; + } else {} + } + } +} +},{"./inferer-reference":169,"babel-types":193}],171:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; +exports.is = undefined; + +var _typeof2 = require("babel-runtime/helpers/typeof"); + +var _typeof3 = _interopRequireDefault(_typeof2); + +var _getIterator2 = require("babel-runtime/core-js/get-iterator"); + +var _getIterator3 = _interopRequireDefault(_getIterator2); + +exports.matchesPattern = matchesPattern; +exports.has = has; +exports.isStatic = isStatic; +exports.isnt = isnt; +exports.equals = equals; +exports.isNodeType = isNodeType; +exports.canHaveVariableDeclarationOrExpression = canHaveVariableDeclarationOrExpression; +exports.canSwapBetweenExpressionAndStatement = canSwapBetweenExpressionAndStatement; +exports.isCompletionRecord = isCompletionRecord; +exports.isStatementOrBlock = isStatementOrBlock; +exports.referencesImport = referencesImport; +exports.getSource = getSource; +exports.willIMaybeExecuteBefore = willIMaybeExecuteBefore; +exports._guessExecutionStatusRelativeTo = _guessExecutionStatusRelativeTo; +exports._guessExecutionStatusRelativeToDifferentFunctions = _guessExecutionStatusRelativeToDifferentFunctions; +exports.resolve = resolve; +exports._resolve = _resolve; + +var _includes = require("lodash/includes"); + +var _includes2 = _interopRequireDefault(_includes); + +var _babelTypes = require("babel-types"); + +var t = _interopRequireWildcard(_babelTypes); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function matchesPattern(pattern, allowPartial) { + if (!this.isMemberExpression()) return false; + + var parts = pattern.split("."); + var search = [this.node]; + var i = 0; + + function matches(name) { + var part = parts[i]; + return part === "*" || name === part; + } + + while (search.length) { + var node = search.shift(); + + if (allowPartial && i === parts.length) { + return true; + } + + if (t.isIdentifier(node)) { + if (!matches(node.name)) return false; + } else if (t.isLiteral(node)) { + if (!matches(node.value)) return false; + } else if (t.isMemberExpression(node)) { + if (node.computed && !t.isLiteral(node.property)) { + return false; + } else { + search.unshift(node.property); + search.unshift(node.object); + continue; + } + } else if (t.isThisExpression(node)) { + if (!matches("this")) return false; + } else { + return false; + } + + if (++i > parts.length) { + return false; + } + } + + return i === parts.length; +} + +function has(key) { + var val = this.node && this.node[key]; + if (val && Array.isArray(val)) { + return !!val.length; + } else { + return !!val; + } +} + +function isStatic() { + return this.scope.isStatic(this.node); +} + +var is = exports.is = has; + +function isnt(key) { + return !this.has(key); +} + +function equals(key, value) { + return this.node[key] === value; +} + +function isNodeType(type) { + return t.isType(this.type, type); +} + +function canHaveVariableDeclarationOrExpression() { + return (this.key === "init" || this.key === "left") && this.parentPath.isFor(); +} + +function canSwapBetweenExpressionAndStatement(replacement) { + if (this.key !== "body" || !this.parentPath.isArrowFunctionExpression()) { + return false; + } + + if (this.isExpression()) { + return t.isBlockStatement(replacement); + } else if (this.isBlockStatement()) { + return t.isExpression(replacement); + } + + return false; +} + +function isCompletionRecord(allowInsideFunction) { + var path = this; + var first = true; + + do { + var container = path.container; + + if (path.isFunction() && !first) { + return !!allowInsideFunction; + } + + first = false; + + if (Array.isArray(container) && path.key !== container.length - 1) { + return false; + } + } while ((path = path.parentPath) && !path.isProgram()); + + return true; +} + +function isStatementOrBlock() { + if (this.parentPath.isLabeledStatement() || t.isBlockStatement(this.container)) { + return false; + } else { + return (0, _includes2.default)(t.STATEMENT_OR_BLOCK_KEYS, this.key); + } +} + +function referencesImport(moduleSource, importName) { + if (!this.isReferencedIdentifier()) return false; + + var binding = this.scope.getBinding(this.node.name); + if (!binding || binding.kind !== "module") return false; + + var path = binding.path; + var parent = path.parentPath; + if (!parent.isImportDeclaration()) return false; + + if (parent.node.source.value === moduleSource) { + if (!importName) return true; + } else { + return false; + } + + if (path.isImportDefaultSpecifier() && importName === "default") { + return true; + } + + if (path.isImportNamespaceSpecifier() && importName === "*") { + return true; + } + + if (path.isImportSpecifier() && path.node.imported.name === importName) { + return true; + } + + return false; +} + +function getSource() { + var node = this.node; + if (node.end) { + return this.hub.file.code.slice(node.start, node.end); + } else { + return ""; + } +} + +function willIMaybeExecuteBefore(target) { + return this._guessExecutionStatusRelativeTo(target) !== "after"; +} + +function _guessExecutionStatusRelativeTo(target) { + var targetFuncParent = target.scope.getFunctionParent(); + var selfFuncParent = this.scope.getFunctionParent(); + + if (targetFuncParent.node !== selfFuncParent.node) { + var status = this._guessExecutionStatusRelativeToDifferentFunctions(targetFuncParent); + if (status) { + return status; + } else { + target = targetFuncParent.path; + } + } + + var targetPaths = target.getAncestry(); + if (targetPaths.indexOf(this) >= 0) return "after"; + + var selfPaths = this.getAncestry(); + + var commonPath = void 0; + var targetIndex = void 0; + var selfIndex = void 0; + for (selfIndex = 0; selfIndex < selfPaths.length; selfIndex++) { + var selfPath = selfPaths[selfIndex]; + targetIndex = targetPaths.indexOf(selfPath); + if (targetIndex >= 0) { + commonPath = selfPath; + break; + } + } + if (!commonPath) { + return "before"; + } + + var targetRelationship = targetPaths[targetIndex - 1]; + var selfRelationship = selfPaths[selfIndex - 1]; + if (!targetRelationship || !selfRelationship) { + return "before"; + } + + if (targetRelationship.listKey && targetRelationship.container === selfRelationship.container) { + return targetRelationship.key > selfRelationship.key ? "before" : "after"; + } + + var targetKeyPosition = t.VISITOR_KEYS[targetRelationship.type].indexOf(targetRelationship.key); + var selfKeyPosition = t.VISITOR_KEYS[selfRelationship.type].indexOf(selfRelationship.key); + return targetKeyPosition > selfKeyPosition ? "before" : "after"; +} + +function _guessExecutionStatusRelativeToDifferentFunctions(targetFuncParent) { + var targetFuncPath = targetFuncParent.path; + if (!targetFuncPath.isFunctionDeclaration()) return; + + var binding = targetFuncPath.scope.getBinding(targetFuncPath.node.id.name); + + if (!binding.references) return "before"; + + var referencePaths = binding.referencePaths; + + for (var _iterator = referencePaths, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_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 path = _ref; + + if (path.key !== "callee" || !path.parentPath.isCallExpression()) { + return; + } + } + + var allStatus = void 0; + + for (var _iterator2 = referencePaths, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : (0, _getIterator3.default)(_iterator2);;) { + var _ref2; + + if (_isArray2) { + if (_i2 >= _iterator2.length) break; + _ref2 = _iterator2[_i2++]; + } else { + _i2 = _iterator2.next(); + if (_i2.done) break; + _ref2 = _i2.value; + } + + var _path = _ref2; + + var childOfFunction = !!_path.find(function (path) { + return path.node === targetFuncPath.node; + }); + if (childOfFunction) continue; + + var status = this._guessExecutionStatusRelativeTo(_path); + + if (allStatus) { + if (allStatus !== status) return; + } else { + allStatus = status; + } + } + + return allStatus; +} + +function resolve(dangerous, resolved) { + return this._resolve(dangerous, resolved) || this; +} + +function _resolve(dangerous, resolved) { + var _this = this; + + if (resolved && resolved.indexOf(this) >= 0) return; + + resolved = resolved || []; + resolved.push(this); + + if (this.isVariableDeclarator()) { + if (this.get("id").isIdentifier()) { + return this.get("init").resolve(dangerous, resolved); + } else {} + } else if (this.isReferencedIdentifier()) { + var binding = this.scope.getBinding(this.node.name); + if (!binding) return; + + if (!binding.constant) return; + + if (binding.kind === "module") return; + + if (binding.path !== this) { + var _ret = function () { + var ret = binding.path.resolve(dangerous, resolved); + + if (_this.find(function (parent) { + return parent.node === ret.node; + })) return { + v: void 0 + }; + return { + v: ret + }; + }(); + + if ((typeof _ret === "undefined" ? "undefined" : (0, _typeof3.default)(_ret)) === "object") return _ret.v; + } + } else if (this.isTypeCastExpression()) { + return this.get("expression").resolve(dangerous, resolved); + } else if (dangerous && this.isMemberExpression()) { + + var targetKey = this.toComputedKey(); + if (!t.isLiteral(targetKey)) return; + + var targetName = targetKey.value; + + var target = this.get("object").resolve(dangerous, resolved); + + if (target.isObjectExpression()) { + var props = target.get("properties"); + for (var _iterator3 = props, _isArray3 = Array.isArray(_iterator3), _i3 = 0, _iterator3 = _isArray3 ? _iterator3 : (0, _getIterator3.default)(_iterator3);;) { + var _ref3; + + if (_isArray3) { + if (_i3 >= _iterator3.length) break; + _ref3 = _iterator3[_i3++]; + } else { + _i3 = _iterator3.next(); + if (_i3.done) break; + _ref3 = _i3.value; + } + + var prop = _ref3; + + if (!prop.isProperty()) continue; + + var key = prop.get("key"); + + var match = prop.isnt("computed") && key.isIdentifier({ name: targetName }); + + match = match || key.isLiteral({ value: targetName }); + + if (match) return prop.get("value").resolve(dangerous, resolved); + } + } else if (target.isArrayExpression() && !isNaN(+targetName)) { + var elems = target.get("elements"); + var elem = elems[targetName]; + if (elem) return elem.resolve(dangerous, resolved); + } + } +} +},{"babel-runtime/core-js/get-iterator":138,"babel-runtime/helpers/typeof":155,"babel-types":193,"lodash/includes":546}],172:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck"); + +var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); + +var _getIterator2 = require("babel-runtime/core-js/get-iterator"); + +var _getIterator3 = _interopRequireDefault(_getIterator2); + +var _babelTypes = require("babel-types"); + +var t = _interopRequireWildcard(_babelTypes); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var referenceVisitor = { + ReferencedIdentifier: function ReferencedIdentifier(path, state) { + if (path.isJSXIdentifier() && _babelTypes.react.isCompatTag(path.node.name)) { + return; + } + + var binding = path.scope.getBinding(path.node.name); + if (!binding) return; + + if (binding !== state.scope.getBinding(path.node.name)) return; + + if (binding.constant) { + state.bindings[path.node.name] = binding; + } else { + for (var _iterator = binding.constantViolations, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_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 violationPath = _ref; + + state.breakOnScopePaths = state.breakOnScopePaths.concat(violationPath.getAncestry()); + } + } + } +}; + +var PathHoister = function () { + function PathHoister(path, scope) { + (0, _classCallCheck3.default)(this, PathHoister); + + this.breakOnScopePaths = []; + this.bindings = {}; + this.scopes = []; + this.scope = scope; + this.path = path; + } + + PathHoister.prototype.isCompatibleScope = function isCompatibleScope(scope) { + for (var key in this.bindings) { + var binding = this.bindings[key]; + if (!scope.bindingIdentifierEquals(key, binding.identifier)) { + return false; + } + } + + return true; + }; + + PathHoister.prototype.getCompatibleScopes = function getCompatibleScopes() { + var scope = this.path.scope; + do { + if (this.isCompatibleScope(scope)) { + this.scopes.push(scope); + } else { + break; + } + + if (this.breakOnScopePaths.indexOf(scope.path) >= 0) { + break; + } + } while (scope = scope.parent); + }; + + PathHoister.prototype.getAttachmentPath = function getAttachmentPath() { + var path = this._getAttachmentPath(); + if (!path) return; + + var targetScope = path.scope; + + if (targetScope.path === path) { + targetScope = path.scope.parent; + } + + if (targetScope.path.isProgram() || targetScope.path.isFunction()) { + for (var name in this.bindings) { + if (!targetScope.hasOwnBinding(name)) continue; + + var binding = this.bindings[name]; + + if (binding.kind === "param") continue; + + if (binding.path.getStatementParent().key > path.key) return; + } + } + + return path; + }; + + PathHoister.prototype._getAttachmentPath = function _getAttachmentPath() { + var scopes = this.scopes; + + var scope = scopes.pop(); + if (!scope) return; + + if (scope.path.isFunction()) { + if (this.hasOwnParamBindings(scope)) { + if (this.scope === scope) return; + + return scope.path.get("body").get("body")[0]; + } else { + return this.getNextScopeStatementParent(); + } + } else if (scope.path.isProgram()) { + return this.getNextScopeStatementParent(); + } + }; + + PathHoister.prototype.getNextScopeStatementParent = function getNextScopeStatementParent() { + var scope = this.scopes.pop(); + if (scope) return scope.path.getStatementParent(); + }; + + PathHoister.prototype.hasOwnParamBindings = function hasOwnParamBindings(scope) { + for (var name in this.bindings) { + if (!scope.hasOwnBinding(name)) continue; + + var binding = this.bindings[name]; + if (binding.kind === "param") return true; + } + return false; + }; + + PathHoister.prototype.run = function run() { + var node = this.path.node; + if (node._hoisted) return; + node._hoisted = true; + + this.path.traverse(referenceVisitor, this); + + this.getCompatibleScopes(); + + var attachTo = this.getAttachmentPath(); + if (!attachTo) return; + + if (attachTo.getFunctionParent() === this.path.getFunctionParent()) return; + + var uid = attachTo.scope.generateUidIdentifier("ref"); + attachTo.insertBefore([t.variableDeclaration("var", [t.variableDeclarator(uid, this.path.node)])]); + + var parent = this.path.parentPath; + if (parent.isJSXElement() && this.path.container === parent.node.children) { + uid = t.JSXExpressionContainer(uid); + } + + this.path.replaceWith(uid); + }; + + return PathHoister; +}(); + +exports.default = PathHoister; +module.exports = exports["default"]; +},{"babel-runtime/core-js/get-iterator":138,"babel-runtime/helpers/classCallCheck":152,"babel-types":193}],173:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; +var hooks = exports.hooks = [function (self, parent) { + if (self.key === "body" && parent.isArrowFunctionExpression()) { + self.replaceWith(self.scope.buildUndefinedNode()); + return true; + } +}, function (self, parent) { + var removeParent = false; + + removeParent = removeParent || self.key === "test" && (parent.isWhile() || parent.isSwitchCase()); + + removeParent = removeParent || self.key === "declaration" && parent.isExportDeclaration(); + + removeParent = removeParent || self.key === "body" && parent.isLabeledStatement(); + + removeParent = removeParent || self.listKey === "declarations" && parent.isVariableDeclaration() && parent.node.declarations.length === 1; + + removeParent = removeParent || self.key === "expression" && parent.isExpressionStatement(); + + if (removeParent) { + parent.remove(); + return true; + } +}, function (self, parent) { + if (parent.isSequenceExpression() && parent.node.expressions.length === 1) { + parent.replaceWith(parent.node.expressions[0]); + return true; + } +}, function (self, parent) { + if (parent.isBinary()) { + if (self.key === "left") { + parent.replaceWith(parent.node.right); + } else { + parent.replaceWith(parent.node.left); + } + return true; + } +}, function (self, parent) { + if (parent.isIfStatement() && (self.key === 'consequent' || self.key === 'alternate') || parent.isLoop() && self.key === 'body') { + self.replaceWith({ + type: 'BlockStatement', + body: [] + }); + return true; + } +}]; +},{}],174:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; +exports.Flow = exports.Pure = exports.Generated = exports.User = exports.Var = exports.BlockScoped = exports.Referenced = exports.Scope = exports.Expression = exports.Statement = exports.BindingIdentifier = exports.ReferencedMemberExpression = exports.ReferencedIdentifier = undefined; + +var _babelTypes = require("babel-types"); + +var t = _interopRequireWildcard(_babelTypes); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +var ReferencedIdentifier = exports.ReferencedIdentifier = { + types: ["Identifier", "JSXIdentifier"], + checkPath: function checkPath(_ref, opts) { + var node = _ref.node; + var parent = _ref.parent; + + if (!t.isIdentifier(node, opts)) { + if (t.isJSXIdentifier(node, opts)) { + if (_babelTypes.react.isCompatTag(node.name)) return false; + } else { + return false; + } + } + + return t.isReferenced(node, parent); + } +}; + +var ReferencedMemberExpression = exports.ReferencedMemberExpression = { + types: ["MemberExpression"], + checkPath: function checkPath(_ref2) { + var node = _ref2.node; + var parent = _ref2.parent; + + return t.isMemberExpression(node) && t.isReferenced(node, parent); + } +}; + +var BindingIdentifier = exports.BindingIdentifier = { + types: ["Identifier"], + checkPath: function checkPath(_ref3) { + var node = _ref3.node; + var parent = _ref3.parent; + + return t.isIdentifier(node) && t.isBinding(node, parent); + } +}; + +var Statement = exports.Statement = { + types: ["Statement"], + checkPath: function checkPath(_ref4) { + var node = _ref4.node; + var parent = _ref4.parent; + + if (t.isStatement(node)) { + if (t.isVariableDeclaration(node)) { + if (t.isForXStatement(parent, { left: node })) return false; + if (t.isForStatement(parent, { init: node })) return false; + } + + return true; + } else { + return false; + } + } +}; + +var Expression = exports.Expression = { + types: ["Expression"], + checkPath: function checkPath(path) { + if (path.isIdentifier()) { + return path.isReferencedIdentifier(); + } else { + return t.isExpression(path.node); + } + } +}; + +var Scope = exports.Scope = { + types: ["Scopable"], + checkPath: function checkPath(path) { + return t.isScope(path.node, path.parent); + } +}; + +var Referenced = exports.Referenced = { + checkPath: function checkPath(path) { + return t.isReferenced(path.node, path.parent); + } +}; + +var BlockScoped = exports.BlockScoped = { + checkPath: function checkPath(path) { + return t.isBlockScoped(path.node); + } +}; + +var Var = exports.Var = { + types: ["VariableDeclaration"], + checkPath: function checkPath(path) { + return t.isVar(path.node); + } +}; + +var User = exports.User = { + checkPath: function checkPath(path) { + return path.node && !!path.node.loc; + } +}; + +var Generated = exports.Generated = { + checkPath: function checkPath(path) { + return !path.isUser(); + } +}; + +var Pure = exports.Pure = { + checkPath: function checkPath(path, opts) { + return path.scope.isPure(path.node, opts); + } +}; + +var Flow = exports.Flow = { + types: ["Flow", "ImportDeclaration", "ExportDeclaration"], + checkPath: function checkPath(_ref5) { + var node = _ref5.node; + + if (t.isFlow(node)) { + return true; + } else if (t.isImportDeclaration(node)) { + return node.importKind === "type" || node.importKind === "typeof"; + } else if (t.isExportDeclaration(node)) { + return node.exportKind === "type"; + } else { + return false; + } + } +}; +},{"babel-types":193}],175:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +var _typeof2 = require("babel-runtime/helpers/typeof"); + +var _typeof3 = _interopRequireDefault(_typeof2); + +var _getIterator2 = require("babel-runtime/core-js/get-iterator"); + +var _getIterator3 = _interopRequireDefault(_getIterator2); + +exports.insertBefore = insertBefore; +exports._containerInsert = _containerInsert; +exports._containerInsertBefore = _containerInsertBefore; +exports._containerInsertAfter = _containerInsertAfter; +exports._maybePopFromStatements = _maybePopFromStatements; +exports.insertAfter = insertAfter; +exports.updateSiblingKeys = updateSiblingKeys; +exports._verifyNodeList = _verifyNodeList; +exports.unshiftContainer = unshiftContainer; +exports.pushContainer = pushContainer; +exports.hoist = hoist; + +var _cache = require("../cache"); + +var _hoister = require("./lib/hoister"); + +var _hoister2 = _interopRequireDefault(_hoister); + +var _index = require("./index"); + +var _index2 = _interopRequireDefault(_index); + +var _babelTypes = require("babel-types"); + +var t = _interopRequireWildcard(_babelTypes); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function insertBefore(nodes) { + this._assertUnremoved(); + + nodes = this._verifyNodeList(nodes); + + if (this.parentPath.isExpressionStatement() || this.parentPath.isLabeledStatement()) { + return this.parentPath.insertBefore(nodes); + } else if (this.isNodeType("Expression") || this.parentPath.isForStatement() && this.key === "init") { + if (this.node) nodes.push(this.node); + this.replaceExpressionWithStatements(nodes); + } else { + this._maybePopFromStatements(nodes); + if (Array.isArray(this.container)) { + return this._containerInsertBefore(nodes); + } else if (this.isStatementOrBlock()) { + if (this.node) nodes.push(this.node); + this._replaceWith(t.blockStatement(nodes)); + } else { + throw new Error("We don't know what to do with this node type. We were previously a Statement but we can't fit in here?"); + } + } + + return [this]; +} + +function _containerInsert(from, nodes) { + this.updateSiblingKeys(from, nodes.length); + + var paths = []; + + for (var i = 0; i < nodes.length; i++) { + var to = from + i; + var node = nodes[i]; + this.container.splice(to, 0, node); + + if (this.context) { + var path = this.context.create(this.parent, this.container, to, this.listKey); + + if (this.context.queue) path.pushContext(this.context); + paths.push(path); + } else { + paths.push(_index2.default.get({ + parentPath: this.parentPath, + parent: this.parent, + container: this.container, + listKey: this.listKey, + key: to + })); + } + } + + var contexts = this._getQueueContexts(); + + for (var _iterator = paths, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_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 _path = _ref; + + _path.setScope(); + _path.debug(function () { + return "Inserted."; + }); + + for (var _iterator2 = contexts, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : (0, _getIterator3.default)(_iterator2);;) { + var _ref2; + + if (_isArray2) { + if (_i2 >= _iterator2.length) break; + _ref2 = _iterator2[_i2++]; + } else { + _i2 = _iterator2.next(); + if (_i2.done) break; + _ref2 = _i2.value; + } + + var context = _ref2; + + context.maybeQueue(_path, true); + } + } + + return paths; +} + +function _containerInsertBefore(nodes) { + return this._containerInsert(this.key, nodes); +} + +function _containerInsertAfter(nodes) { + return this._containerInsert(this.key + 1, nodes); +} + +function _maybePopFromStatements(nodes) { + var last = nodes[nodes.length - 1]; + var isIdentifier = t.isIdentifier(last) || t.isExpressionStatement(last) && t.isIdentifier(last.expression); + + if (isIdentifier && !this.isCompletionRecord()) { + nodes.pop(); + } +} + +function insertAfter(nodes) { + this._assertUnremoved(); + + nodes = this._verifyNodeList(nodes); + + if (this.parentPath.isExpressionStatement() || this.parentPath.isLabeledStatement()) { + return this.parentPath.insertAfter(nodes); + } else if (this.isNodeType("Expression") || this.parentPath.isForStatement() && this.key === "init") { + if (this.node) { + var temp = this.scope.generateDeclaredUidIdentifier(); + nodes.unshift(t.expressionStatement(t.assignmentExpression("=", temp, this.node))); + nodes.push(t.expressionStatement(temp)); + } + this.replaceExpressionWithStatements(nodes); + } else { + this._maybePopFromStatements(nodes); + if (Array.isArray(this.container)) { + return this._containerInsertAfter(nodes); + } else if (this.isStatementOrBlock()) { + if (this.node) nodes.unshift(this.node); + this._replaceWith(t.blockStatement(nodes)); + } else { + throw new Error("We don't know what to do with this node type. We were previously a Statement but we can't fit in here?"); + } + } + + return [this]; +} + +function updateSiblingKeys(fromIndex, incrementBy) { + if (!this.parent) return; + + var paths = _cache.path.get(this.parent); + for (var i = 0; i < paths.length; i++) { + var path = paths[i]; + if (path.key >= fromIndex) { + path.key += incrementBy; + } + } +} + +function _verifyNodeList(nodes) { + if (!nodes) { + return []; + } + + if (nodes.constructor !== Array) { + nodes = [nodes]; + } + + for (var i = 0; i < nodes.length; i++) { + var node = nodes[i]; + var msg = void 0; + + if (!node) { + msg = "has falsy node"; + } else if ((typeof node === "undefined" ? "undefined" : (0, _typeof3.default)(node)) !== "object") { + msg = "contains a non-object node"; + } else if (!node.type) { + msg = "without a type"; + } else if (node instanceof _index2.default) { + msg = "has a NodePath when it expected a raw object"; + } + + if (msg) { + var type = Array.isArray(node) ? "array" : typeof node === "undefined" ? "undefined" : (0, _typeof3.default)(node); + throw new Error("Node list " + msg + " with the index of " + i + " and type of " + type); + } + } + + return nodes; +} + +function unshiftContainer(listKey, nodes) { + this._assertUnremoved(); + + nodes = this._verifyNodeList(nodes); + + var path = _index2.default.get({ + parentPath: this, + parent: this.node, + container: this.node[listKey], + listKey: listKey, + key: 0 + }); + + return path.insertBefore(nodes); +} + +function pushContainer(listKey, nodes) { + this._assertUnremoved(); + + nodes = this._verifyNodeList(nodes); + + var container = this.node[listKey]; + var path = _index2.default.get({ + parentPath: this, + parent: this.node, + container: container, + listKey: listKey, + key: container.length + }); + + return path.replaceWithMultiple(nodes); +} + +function hoist() { + var scope = arguments.length <= 0 || arguments[0] === undefined ? this.scope : arguments[0]; + + var hoister = new _hoister2.default(this, scope); + return hoister.run(); +} +},{"../cache":157,"./index":167,"./lib/hoister":172,"babel-runtime/core-js/get-iterator":138,"babel-runtime/helpers/typeof":155,"babel-types":193}],176:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +var _getIterator2 = require("babel-runtime/core-js/get-iterator"); + +var _getIterator3 = _interopRequireDefault(_getIterator2); + +exports.remove = remove; +exports._callRemovalHooks = _callRemovalHooks; +exports._remove = _remove; +exports._markRemoved = _markRemoved; +exports._assertUnremoved = _assertUnremoved; + +var _removalHooks = require("./lib/removal-hooks"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function remove() { + this._assertUnremoved(); + + this.resync(); + + if (this._callRemovalHooks()) { + this._markRemoved(); + return; + } + + this.shareCommentsWithSiblings(); + this._remove(); + this._markRemoved(); +} + +function _callRemovalHooks() { + for (var _iterator = _removalHooks.hooks, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_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 fn = _ref; + + if (fn(this, this.parentPath)) return true; + } +} + +function _remove() { + if (Array.isArray(this.container)) { + this.container.splice(this.key, 1); + this.updateSiblingKeys(this.key, -1); + } else { + this._replaceWith(null); + } +} + +function _markRemoved() { + this.shouldSkip = true; + this.removed = true; + this.node = null; +} + +function _assertUnremoved() { + if (this.removed) { + throw this.buildCodeFrameError("NodePath has been removed so is read-only."); + } +} +},{"./lib/removal-hooks":173,"babel-runtime/core-js/get-iterator":138}],177:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +var _getIterator2 = require("babel-runtime/core-js/get-iterator"); + +var _getIterator3 = _interopRequireDefault(_getIterator2); + +exports.replaceWithMultiple = replaceWithMultiple; +exports.replaceWithSourceString = replaceWithSourceString; +exports.replaceWith = replaceWith; +exports._replaceWith = _replaceWith; +exports.replaceExpressionWithStatements = replaceExpressionWithStatements; +exports.replaceInline = replaceInline; + +var _babelCodeFrame = require("babel-code-frame"); + +var _babelCodeFrame2 = _interopRequireDefault(_babelCodeFrame); + +var _index = require("../index"); + +var _index2 = _interopRequireDefault(_index); + +var _index3 = require("./index"); + +var _index4 = _interopRequireDefault(_index3); + +var _babylon = require("babylon"); + +var _babelTypes = require("babel-types"); + +var t = _interopRequireWildcard(_babelTypes); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var hoistVariablesVisitor = { + Function: function Function(path) { + path.skip(); + }, + VariableDeclaration: function VariableDeclaration(path) { + if (path.node.kind !== "var") return; + + var bindings = path.getBindingIdentifiers(); + for (var key in bindings) { + path.scope.push({ id: bindings[key] }); + } + + var exprs = []; + + for (var _iterator = path.node.declarations, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_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 declar = _ref; + + if (declar.init) { + exprs.push(t.expressionStatement(t.assignmentExpression("=", declar.id, declar.init))); + } + } + + path.replaceWithMultiple(exprs); + } +}; + +function replaceWithMultiple(nodes) { + this.resync(); + + nodes = this._verifyNodeList(nodes); + t.inheritLeadingComments(nodes[0], this.node); + t.inheritTrailingComments(nodes[nodes.length - 1], this.node); + this.node = this.container[this.key] = null; + this.insertAfter(nodes); + + if (this.node) { + this.requeue(); + } else { + this.remove(); + } +} + +function replaceWithSourceString(replacement) { + this.resync(); + + try { + replacement = "(" + replacement + ")"; + replacement = (0, _babylon.parse)(replacement); + } catch (err) { + var loc = err.loc; + if (loc) { + err.message += " - make sure this is an expression."; + err.message += "\n" + (0, _babelCodeFrame2.default)(replacement, loc.line, loc.column + 1); + } + throw err; + } + + replacement = replacement.program.body[0].expression; + _index2.default.removeProperties(replacement); + return this.replaceWith(replacement); +} + +function replaceWith(replacement) { + this.resync(); + + if (this.removed) { + throw new Error("You can't replace this node, we've already removed it"); + } + + if (replacement instanceof _index4.default) { + replacement = replacement.node; + } + + if (!replacement) { + throw new Error("You passed `path.replaceWith()` a falsy node, use `path.remove()` instead"); + } + + if (this.node === replacement) { + return; + } + + if (this.isProgram() && !t.isProgram(replacement)) { + throw new Error("You can only replace a Program root node with another Program node"); + } + + if (Array.isArray(replacement)) { + throw new Error("Don't use `path.replaceWith()` with an array of nodes, use `path.replaceWithMultiple()`"); + } + + if (typeof replacement === "string") { + throw new Error("Don't use `path.replaceWith()` with a source string, use `path.replaceWithSourceString()`"); + } + + if (this.isNodeType("Statement") && t.isExpression(replacement)) { + if (!this.canHaveVariableDeclarationOrExpression() && !this.canSwapBetweenExpressionAndStatement(replacement)) { + replacement = t.expressionStatement(replacement); + } + } + + if (this.isNodeType("Expression") && t.isStatement(replacement)) { + if (!this.canHaveVariableDeclarationOrExpression() && !this.canSwapBetweenExpressionAndStatement(replacement)) { + return this.replaceExpressionWithStatements([replacement]); + } + } + + var oldNode = this.node; + if (oldNode) { + t.inheritsComments(replacement, oldNode); + t.removeComments(oldNode); + } + + this._replaceWith(replacement); + this.type = replacement.type; + + this.setScope(); + + this.requeue(); +} + +function _replaceWith(node) { + if (!this.container) { + throw new ReferenceError("Container is falsy"); + } + + if (this.inList) { + t.validate(this.parent, this.key, [node]); + } else { + t.validate(this.parent, this.key, node); + } + + this.debug(function () { + return "Replace with " + (node && node.type); + }); + + this.node = this.container[this.key] = node; +} + +function replaceExpressionWithStatements(nodes) { + this.resync(); + + var toSequenceExpression = t.toSequenceExpression(nodes, this.scope); + + if (t.isSequenceExpression(toSequenceExpression)) { + var exprs = toSequenceExpression.expressions; + + if (exprs.length >= 2 && this.parentPath.isExpressionStatement()) { + this._maybePopFromStatements(exprs); + } + + if (exprs.length === 1) { + this.replaceWith(exprs[0]); + } else { + this.replaceWith(toSequenceExpression); + } + } else if (toSequenceExpression) { + this.replaceWith(toSequenceExpression); + } else { + var container = t.functionExpression(null, [], t.blockStatement(nodes)); + container.shadow = true; + + this.replaceWith(t.callExpression(container, [])); + this.traverse(hoistVariablesVisitor); + + var completionRecords = this.get("callee").getCompletionRecords(); + for (var _iterator2 = completionRecords, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : (0, _getIterator3.default)(_iterator2);;) { + var _ref2; + + if (_isArray2) { + if (_i2 >= _iterator2.length) break; + _ref2 = _iterator2[_i2++]; + } else { + _i2 = _iterator2.next(); + if (_i2.done) break; + _ref2 = _i2.value; + } + + var path = _ref2; + + if (!path.isExpressionStatement()) continue; + + var loop = path.findParent(function (path) { + return path.isLoop(); + }); + if (loop) { + var callee = this.get("callee"); + + var uid = callee.scope.generateDeclaredUidIdentifier("ret"); + callee.get("body").pushContainer("body", t.returnStatement(uid)); + + path.get("expression").replaceWith(t.assignmentExpression("=", uid, path.node.expression)); + } else { + path.replaceWith(t.returnStatement(path.node.expression)); + } + } + + return this.node; + } +} + +function replaceInline(nodes) { + this.resync(); + + if (Array.isArray(nodes)) { + if (Array.isArray(this.container)) { + nodes = this._verifyNodeList(nodes); + this._containerInsertAfter(nodes); + return this.remove(); + } else { + return this.replaceWithMultiple(nodes); + } + } else { + return this.replaceWith(nodes); + } +} +},{"../index":160,"./index":167,"babel-code-frame":18,"babel-runtime/core-js/get-iterator":138,"babel-types":193,"babylon":197}],178:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck"); + +var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var Binding = function () { + function Binding(_ref) { + var existing = _ref.existing; + var identifier = _ref.identifier; + var scope = _ref.scope; + var path = _ref.path; + var kind = _ref.kind; + (0, _classCallCheck3.default)(this, Binding); + + this.identifier = identifier; + this.scope = scope; + this.path = path; + this.kind = kind; + + this.constantViolations = []; + this.constant = true; + + this.referencePaths = []; + this.referenced = false; + this.references = 0; + + this.clearValue(); + + if (existing) { + this.constantViolations = [].concat(existing.path, existing.constantViolations, this.constantViolations); + } + } + + Binding.prototype.deoptValue = function deoptValue() { + this.clearValue(); + this.hasDeoptedValue = true; + }; + + Binding.prototype.setValue = function setValue(value) { + if (this.hasDeoptedValue) return; + this.hasValue = true; + this.value = value; + }; + + Binding.prototype.clearValue = function clearValue() { + this.hasDeoptedValue = false; + this.hasValue = false; + this.value = null; + }; + + Binding.prototype.reassign = function reassign(path) { + this.constant = false; + if (this.constantViolations.indexOf(path) !== -1) { + return; + } + this.constantViolations.push(path); + }; + + Binding.prototype.reference = function reference(path) { + if (this.referencePaths.indexOf(path) !== -1) { + return; + } + this.referenced = true; + this.references++; + this.referencePaths.push(path); + }; + + Binding.prototype.dereference = function dereference() { + this.references--; + this.referenced = !!this.references; + }; + + return Binding; +}(); + +exports.default = Binding; +module.exports = exports["default"]; +},{"babel-runtime/helpers/classCallCheck":152}],179:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +var _keys = require("babel-runtime/core-js/object/keys"); + +var _keys2 = _interopRequireDefault(_keys); + +var _create = require("babel-runtime/core-js/object/create"); + +var _create2 = _interopRequireDefault(_create); + +var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck"); + +var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); + +var _getIterator2 = require("babel-runtime/core-js/get-iterator"); + +var _getIterator3 = _interopRequireDefault(_getIterator2); + +var _includes = require("lodash/includes"); + +var _includes2 = _interopRequireDefault(_includes); + +var _repeat = require("lodash/repeat"); + +var _repeat2 = _interopRequireDefault(_repeat); + +var _renamer = require("./lib/renamer"); + +var _renamer2 = _interopRequireDefault(_renamer); + +var _index = require("../index"); + +var _index2 = _interopRequireDefault(_index); + +var _defaults = require("lodash/defaults"); + +var _defaults2 = _interopRequireDefault(_defaults); + +var _babelMessages = require("babel-messages"); + +var messages = _interopRequireWildcard(_babelMessages); + +var _binding2 = require("./binding"); + +var _binding3 = _interopRequireDefault(_binding2); + +var _globals = require("globals"); + +var _globals2 = _interopRequireDefault(_globals); + +var _babelTypes = require("babel-types"); + +var t = _interopRequireWildcard(_babelTypes); + +var _cache = require("../cache"); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var _crawlCallsCount = 0; + +function getCache(path, parentScope, self) { + var scopes = _cache.scope.get(path.node) || []; + + for (var _iterator = scopes, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_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 scope = _ref; + + if (scope.parent === parentScope && scope.path === path) return scope; + } + + scopes.push(self); + + if (!_cache.scope.has(path.node)) { + _cache.scope.set(path.node, scopes); + } +} + +var collectorVisitor = { + For: function For(path) { + for (var _iterator2 = t.FOR_INIT_KEYS, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : (0, _getIterator3.default)(_iterator2);;) { + var _ref2; + + if (_isArray2) { + if (_i2 >= _iterator2.length) break; + _ref2 = _iterator2[_i2++]; + } else { + _i2 = _iterator2.next(); + if (_i2.done) break; + _ref2 = _i2.value; + } + + var key = _ref2; + + var declar = path.get(key); + if (declar.isVar()) path.scope.getFunctionParent().registerBinding("var", declar); + } + }, + Declaration: function Declaration(path) { + if (path.isBlockScoped()) return; + + if (path.isExportDeclaration() && path.get("declaration").isDeclaration()) return; + + path.scope.getFunctionParent().registerDeclaration(path); + }, + ReferencedIdentifier: function ReferencedIdentifier(path, state) { + state.references.push(path); + }, + ForXStatement: function ForXStatement(path, state) { + var left = path.get("left"); + if (left.isPattern() || left.isIdentifier()) { + state.constantViolations.push(left); + } + }, + + + ExportDeclaration: { + exit: function exit(path) { + var node = path.node; + var scope = path.scope; + + var declar = node.declaration; + if (t.isClassDeclaration(declar) || t.isFunctionDeclaration(declar)) { + var _id = declar.id; + if (!_id) return; + + var binding = scope.getBinding(_id.name); + if (binding) binding.reference(path); + } else if (t.isVariableDeclaration(declar)) { + for (var _iterator3 = declar.declarations, _isArray3 = Array.isArray(_iterator3), _i3 = 0, _iterator3 = _isArray3 ? _iterator3 : (0, _getIterator3.default)(_iterator3);;) { + var _ref3; + + if (_isArray3) { + if (_i3 >= _iterator3.length) break; + _ref3 = _iterator3[_i3++]; + } else { + _i3 = _iterator3.next(); + if (_i3.done) break; + _ref3 = _i3.value; + } + + var decl = _ref3; + + var ids = t.getBindingIdentifiers(decl); + for (var name in ids) { + var _binding = scope.getBinding(name); + if (_binding) _binding.reference(path); + } + } + } + } + }, + + LabeledStatement: function LabeledStatement(path) { + path.scope.getProgramParent().addGlobal(path.node); + path.scope.getBlockParent().registerDeclaration(path); + }, + AssignmentExpression: function AssignmentExpression(path, state) { + state.assignments.push(path); + }, + UpdateExpression: function UpdateExpression(path, state) { + state.constantViolations.push(path.get("argument")); + }, + UnaryExpression: function UnaryExpression(path, state) { + if (path.node.operator === "delete") { + state.constantViolations.push(path.get("argument")); + } + }, + BlockScoped: function BlockScoped(path) { + var scope = path.scope; + if (scope.path === path) scope = scope.parent; + scope.getBlockParent().registerDeclaration(path); + }, + ClassDeclaration: function ClassDeclaration(path) { + var id = path.node.id; + if (!id) return; + + var name = id.name; + path.scope.bindings[name] = path.scope.getBinding(name); + }, + Block: function Block(path) { + var paths = path.get("body"); + for (var _iterator4 = paths, _isArray4 = Array.isArray(_iterator4), _i4 = 0, _iterator4 = _isArray4 ? _iterator4 : (0, _getIterator3.default)(_iterator4);;) { + var _ref4; + + if (_isArray4) { + if (_i4 >= _iterator4.length) break; + _ref4 = _iterator4[_i4++]; + } else { + _i4 = _iterator4.next(); + if (_i4.done) break; + _ref4 = _i4.value; + } + + var bodyPath = _ref4; + + if (bodyPath.isFunctionDeclaration()) { + path.scope.getBlockParent().registerDeclaration(bodyPath); + } + } + } +}; + +var uid = 0; + +var Scope = function () { + function Scope(path, parentScope) { + (0, _classCallCheck3.default)(this, Scope); + + if (parentScope && parentScope.block === path.node) { + return parentScope; + } + + var cached = getCache(path, parentScope, this); + if (cached) return cached; + + this.uid = uid++; + this.parent = parentScope; + this.hub = path.hub; + + this.parentBlock = path.parent; + this.block = path.node; + this.path = path; + } + + Scope.prototype.traverse = function traverse(node, opts, state) { + (0, _index2.default)(node, opts, this, state, this.path); + }; + + Scope.prototype.generateDeclaredUidIdentifier = function generateDeclaredUidIdentifier() { + var name = arguments.length <= 0 || arguments[0] === undefined ? "temp" : arguments[0]; + + var id = this.generateUidIdentifier(name); + this.push({ id: id }); + return id; + }; + + Scope.prototype.generateUidIdentifier = function generateUidIdentifier() { + var name = arguments.length <= 0 || arguments[0] === undefined ? "temp" : arguments[0]; + + return t.identifier(this.generateUid(name)); + }; + + Scope.prototype.generateUid = function generateUid() { + var name = arguments.length <= 0 || arguments[0] === undefined ? "temp" : arguments[0]; + + name = t.toIdentifier(name).replace(/^_+/, "").replace(/[0-9]+$/g, ""); + + var uid = void 0; + var i = 0; + do { + uid = this._generateUid(name, i); + i++; + } while (this.hasBinding(uid) || this.hasGlobal(uid) || this.hasReference(uid)); + + var program = this.getProgramParent(); + program.references[uid] = true; + program.uids[uid] = true; + + return uid; + }; + + Scope.prototype._generateUid = function _generateUid(name, i) { + var id = name; + if (i > 1) id += i; + return "_" + id; + }; + + Scope.prototype.generateUidIdentifierBasedOnNode = function generateUidIdentifierBasedOnNode(parent, defaultName) { + var node = parent; + + if (t.isAssignmentExpression(parent)) { + node = parent.left; + } else if (t.isVariableDeclarator(parent)) { + node = parent.id; + } else if (t.isObjectProperty(node) || t.isObjectMethod(node)) { + node = node.key; + } + + var parts = []; + + var add = function add(node) { + if (t.isModuleDeclaration(node)) { + if (node.source) { + add(node.source); + } else if (node.specifiers && node.specifiers.length) { + for (var _iterator5 = node.specifiers, _isArray5 = Array.isArray(_iterator5), _i5 = 0, _iterator5 = _isArray5 ? _iterator5 : (0, _getIterator3.default)(_iterator5);;) { + var _ref5; + + if (_isArray5) { + if (_i5 >= _iterator5.length) break; + _ref5 = _iterator5[_i5++]; + } else { + _i5 = _iterator5.next(); + if (_i5.done) break; + _ref5 = _i5.value; + } + + var specifier = _ref5; + + add(specifier); + } + } else if (node.declaration) { + add(node.declaration); + } + } else if (t.isModuleSpecifier(node)) { + add(node.local); + } else if (t.isMemberExpression(node)) { + add(node.object); + add(node.property); + } else if (t.isIdentifier(node)) { + parts.push(node.name); + } else if (t.isLiteral(node)) { + parts.push(node.value); + } else if (t.isCallExpression(node)) { + add(node.callee); + } else if (t.isObjectExpression(node) || t.isObjectPattern(node)) { + for (var _iterator6 = node.properties, _isArray6 = Array.isArray(_iterator6), _i6 = 0, _iterator6 = _isArray6 ? _iterator6 : (0, _getIterator3.default)(_iterator6);;) { + var _ref6; + + if (_isArray6) { + if (_i6 >= _iterator6.length) break; + _ref6 = _iterator6[_i6++]; + } else { + _i6 = _iterator6.next(); + if (_i6.done) break; + _ref6 = _i6.value; + } + + var prop = _ref6; + + add(prop.key || prop.argument); + } + } + }; + + add(node); + + var id = parts.join("$"); + id = id.replace(/^_/, "") || defaultName || "ref"; + + return this.generateUidIdentifier(id.slice(0, 20)); + }; + + Scope.prototype.isStatic = function isStatic(node) { + if (t.isThisExpression(node) || t.isSuper(node)) { + return true; + } + + if (t.isIdentifier(node)) { + var binding = this.getBinding(node.name); + if (binding) { + return binding.constant; + } else { + return this.hasBinding(node.name); + } + } + + return false; + }; + + Scope.prototype.maybeGenerateMemoised = function maybeGenerateMemoised(node, dontPush) { + if (this.isStatic(node)) { + return null; + } else { + var _id2 = this.generateUidIdentifierBasedOnNode(node); + if (!dontPush) this.push({ id: _id2 }); + return _id2; + } + }; + + Scope.prototype.checkBlockScopedCollisions = function checkBlockScopedCollisions(local, kind, name, id) { + if (kind === "param") return; + + if (kind === "hoisted" && local.kind === "let") return; + + var duplicate = false; + + if (!duplicate) duplicate = kind === "let" || local.kind === "let" || local.kind === "const" || local.kind === "module"; + + if (!duplicate) duplicate = local.kind === "param" && (kind === "let" || kind === "const"); + + if (duplicate) { + throw this.hub.file.buildCodeFrameError(id, messages.get("scopeDuplicateDeclaration", name), TypeError); + } + }; + + Scope.prototype.rename = function rename(oldName, newName, block) { + var binding = this.getBinding(oldName); + if (binding) { + newName = newName || this.generateUidIdentifier(oldName).name; + return new _renamer2.default(binding, oldName, newName).rename(block); + } + }; + + Scope.prototype._renameFromMap = function _renameFromMap(map, oldName, newName, value) { + if (map[oldName]) { + map[newName] = value; + map[oldName] = null; + } + }; + + Scope.prototype.dump = function dump() { + var sep = (0, _repeat2.default)("-", 60); + console.log(sep); + var scope = this; + do { + console.log("#", scope.block.type); + for (var name in scope.bindings) { + var binding = scope.bindings[name]; + console.log(" -", name, { + constant: binding.constant, + references: binding.references, + violations: binding.constantViolations.length, + kind: binding.kind + }); + } + } while (scope = scope.parent); + console.log(sep); + }; + + Scope.prototype.toArray = function toArray(node, i) { + var file = this.hub.file; + + if (t.isIdentifier(node)) { + var binding = this.getBinding(node.name); + if (binding && binding.constant && binding.path.isGenericType("Array")) return node; + } + + if (t.isArrayExpression(node)) { + return node; + } + + if (t.isIdentifier(node, { name: "arguments" })) { + return t.callExpression(t.memberExpression(t.memberExpression(t.memberExpression(t.identifier("Array"), t.identifier("prototype")), t.identifier("slice")), t.identifier("call")), [node]); + } + + var helperName = "toArray"; + var args = [node]; + if (i === true) { + helperName = "toConsumableArray"; + } else if (i) { + args.push(t.numericLiteral(i)); + helperName = "slicedToArray"; + } + return t.callExpression(file.addHelper(helperName), args); + }; + + Scope.prototype.registerDeclaration = function registerDeclaration(path) { + if (path.isLabeledStatement()) { + this.registerBinding("label", path); + } else if (path.isFunctionDeclaration()) { + this.registerBinding("hoisted", path.get("id"), path); + } else if (path.isVariableDeclaration()) { + var declarations = path.get("declarations"); + for (var _iterator7 = declarations, _isArray7 = Array.isArray(_iterator7), _i7 = 0, _iterator7 = _isArray7 ? _iterator7 : (0, _getIterator3.default)(_iterator7);;) { + var _ref7; + + if (_isArray7) { + if (_i7 >= _iterator7.length) break; + _ref7 = _iterator7[_i7++]; + } else { + _i7 = _iterator7.next(); + if (_i7.done) break; + _ref7 = _i7.value; + } + + var declar = _ref7; + + this.registerBinding(path.node.kind, declar); + } + } else if (path.isClassDeclaration()) { + this.registerBinding("let", path); + } else if (path.isImportDeclaration()) { + var specifiers = path.get("specifiers"); + for (var _iterator8 = specifiers, _isArray8 = Array.isArray(_iterator8), _i8 = 0, _iterator8 = _isArray8 ? _iterator8 : (0, _getIterator3.default)(_iterator8);;) { + var _ref8; + + if (_isArray8) { + if (_i8 >= _iterator8.length) break; + _ref8 = _iterator8[_i8++]; + } else { + _i8 = _iterator8.next(); + if (_i8.done) break; + _ref8 = _i8.value; + } + + var specifier = _ref8; + + this.registerBinding("module", specifier); + } + } else if (path.isExportDeclaration()) { + var _declar = path.get("declaration"); + if (_declar.isClassDeclaration() || _declar.isFunctionDeclaration() || _declar.isVariableDeclaration()) { + this.registerDeclaration(_declar); + } + } else { + this.registerBinding("unknown", path); + } + }; + + Scope.prototype.buildUndefinedNode = function buildUndefinedNode() { + if (this.hasBinding("undefined")) { + return t.unaryExpression("void", t.numericLiteral(0), true); + } else { + return t.identifier("undefined"); + } + }; + + Scope.prototype.registerConstantViolation = function registerConstantViolation(path) { + var ids = path.getBindingIdentifiers(); + for (var name in ids) { + var binding = this.getBinding(name); + if (binding) binding.reassign(path); + } + }; + + Scope.prototype.registerBinding = function registerBinding(kind, path) { + var bindingPath = arguments.length <= 2 || arguments[2] === undefined ? path : arguments[2]; + + if (!kind) throw new ReferenceError("no `kind`"); + + if (path.isVariableDeclaration()) { + var declarators = path.get("declarations"); + for (var _iterator9 = declarators, _isArray9 = Array.isArray(_iterator9), _i9 = 0, _iterator9 = _isArray9 ? _iterator9 : (0, _getIterator3.default)(_iterator9);;) { + var _ref9; + + if (_isArray9) { + if (_i9 >= _iterator9.length) break; + _ref9 = _iterator9[_i9++]; + } else { + _i9 = _iterator9.next(); + if (_i9.done) break; + _ref9 = _i9.value; + } + + var declar = _ref9; + + this.registerBinding(kind, declar); + } + return; + } + + var parent = this.getProgramParent(); + var ids = path.getBindingIdentifiers(true); + + for (var name in ids) { + for (var _iterator10 = ids[name], _isArray10 = Array.isArray(_iterator10), _i10 = 0, _iterator10 = _isArray10 ? _iterator10 : (0, _getIterator3.default)(_iterator10);;) { + var _ref10; + + if (_isArray10) { + if (_i10 >= _iterator10.length) break; + _ref10 = _iterator10[_i10++]; + } else { + _i10 = _iterator10.next(); + if (_i10.done) break; + _ref10 = _i10.value; + } + + var _id3 = _ref10; + + var local = this.getOwnBinding(name); + if (local) { + if (local.identifier === _id3) continue; + + this.checkBlockScopedCollisions(local, kind, name, _id3); + } + + if (local && local.path.isFlow()) local = null; + + parent.references[name] = true; + + this.bindings[name] = new _binding3.default({ + identifier: _id3, + existing: local, + scope: this, + path: bindingPath, + kind: kind + }); + } + } + }; + + Scope.prototype.addGlobal = function addGlobal(node) { + this.globals[node.name] = node; + }; + + Scope.prototype.hasUid = function hasUid(name) { + var scope = this; + + do { + if (scope.uids[name]) return true; + } while (scope = scope.parent); + + return false; + }; + + Scope.prototype.hasGlobal = function hasGlobal(name) { + var scope = this; + + do { + if (scope.globals[name]) return true; + } while (scope = scope.parent); + + return false; + }; + + Scope.prototype.hasReference = function hasReference(name) { + var scope = this; + + do { + if (scope.references[name]) return true; + } while (scope = scope.parent); + + return false; + }; + + Scope.prototype.isPure = function isPure(node, constantsOnly) { + if (t.isIdentifier(node)) { + var binding = this.getBinding(node.name); + if (!binding) return false; + if (constantsOnly) return binding.constant; + return true; + } else if (t.isClass(node)) { + if (node.superClass && !this.isPure(node.superClass, constantsOnly)) return false; + return this.isPure(node.body, constantsOnly); + } else if (t.isClassBody(node)) { + for (var _iterator11 = node.body, _isArray11 = Array.isArray(_iterator11), _i11 = 0, _iterator11 = _isArray11 ? _iterator11 : (0, _getIterator3.default)(_iterator11);;) { + var _ref11; + + if (_isArray11) { + if (_i11 >= _iterator11.length) break; + _ref11 = _iterator11[_i11++]; + } else { + _i11 = _iterator11.next(); + if (_i11.done) break; + _ref11 = _i11.value; + } + + var method = _ref11; + + if (!this.isPure(method, constantsOnly)) return false; + } + return true; + } else if (t.isBinary(node)) { + return this.isPure(node.left, constantsOnly) && this.isPure(node.right, constantsOnly); + } else if (t.isArrayExpression(node)) { + for (var _iterator12 = node.elements, _isArray12 = Array.isArray(_iterator12), _i12 = 0, _iterator12 = _isArray12 ? _iterator12 : (0, _getIterator3.default)(_iterator12);;) { + var _ref12; + + if (_isArray12) { + if (_i12 >= _iterator12.length) break; + _ref12 = _iterator12[_i12++]; + } else { + _i12 = _iterator12.next(); + if (_i12.done) break; + _ref12 = _i12.value; + } + + var elem = _ref12; + + if (!this.isPure(elem, constantsOnly)) return false; + } + return true; + } else if (t.isObjectExpression(node)) { + for (var _iterator13 = node.properties, _isArray13 = Array.isArray(_iterator13), _i13 = 0, _iterator13 = _isArray13 ? _iterator13 : (0, _getIterator3.default)(_iterator13);;) { + var _ref13; + + if (_isArray13) { + if (_i13 >= _iterator13.length) break; + _ref13 = _iterator13[_i13++]; + } else { + _i13 = _iterator13.next(); + if (_i13.done) break; + _ref13 = _i13.value; + } + + var prop = _ref13; + + if (!this.isPure(prop, constantsOnly)) return false; + } + return true; + } else if (t.isClassMethod(node)) { + if (node.computed && !this.isPure(node.key, constantsOnly)) return false; + if (node.kind === "get" || node.kind === "set") return false; + return true; + } else if (t.isClassProperty(node) || t.isObjectProperty(node)) { + if (node.computed && !this.isPure(node.key, constantsOnly)) return false; + return this.isPure(node.value, constantsOnly); + } else if (t.isUnaryExpression(node)) { + return this.isPure(node.argument, constantsOnly); + } else { + return t.isPureish(node); + } + }; + + Scope.prototype.setData = function setData(key, val) { + return this.data[key] = val; + }; + + Scope.prototype.getData = function getData(key) { + var scope = this; + do { + var data = scope.data[key]; + if (data != null) return data; + } while (scope = scope.parent); + }; + + Scope.prototype.removeData = function removeData(key) { + var scope = this; + do { + var data = scope.data[key]; + if (data != null) scope.data[key] = null; + } while (scope = scope.parent); + }; + + Scope.prototype.init = function init() { + if (!this.references) this.crawl(); + }; + + Scope.prototype.crawl = function crawl() { + _crawlCallsCount++; + this._crawl(); + _crawlCallsCount--; + }; + + Scope.prototype._crawl = function _crawl() { + var path = this.path; + + this.references = (0, _create2.default)(null); + this.bindings = (0, _create2.default)(null); + this.globals = (0, _create2.default)(null); + this.uids = (0, _create2.default)(null); + this.data = (0, _create2.default)(null); + + if (path.isLoop()) { + for (var _iterator14 = t.FOR_INIT_KEYS, _isArray14 = Array.isArray(_iterator14), _i14 = 0, _iterator14 = _isArray14 ? _iterator14 : (0, _getIterator3.default)(_iterator14);;) { + var _ref14; + + if (_isArray14) { + if (_i14 >= _iterator14.length) break; + _ref14 = _iterator14[_i14++]; + } else { + _i14 = _iterator14.next(); + if (_i14.done) break; + _ref14 = _i14.value; + } + + var key = _ref14; + + var node = path.get(key); + if (node.isBlockScoped()) this.registerBinding(node.node.kind, node); + } + } + + if (path.isFunctionExpression() && path.has("id")) { + if (!path.get("id").node[t.NOT_LOCAL_BINDING]) { + this.registerBinding("local", path.get("id"), path); + } + } + + if (path.isClassExpression() && path.has("id")) { + if (!path.get("id").node[t.NOT_LOCAL_BINDING]) { + this.registerBinding("local", path); + } + } + + if (path.isFunction()) { + var params = path.get("params"); + for (var _iterator15 = params, _isArray15 = Array.isArray(_iterator15), _i15 = 0, _iterator15 = _isArray15 ? _iterator15 : (0, _getIterator3.default)(_iterator15);;) { + var _ref15; + + if (_isArray15) { + if (_i15 >= _iterator15.length) break; + _ref15 = _iterator15[_i15++]; + } else { + _i15 = _iterator15.next(); + if (_i15.done) break; + _ref15 = _i15.value; + } + + var param = _ref15; + + this.registerBinding("param", param); + } + } + + if (path.isCatchClause()) { + this.registerBinding("let", path); + } + + var parent = this.getProgramParent(); + if (parent.crawling) return; + + var state = { + references: [], + constantViolations: [], + assignments: [] + }; + + this.crawling = true; + path.traverse(collectorVisitor, state); + this.crawling = false; + + for (var _iterator16 = state.assignments, _isArray16 = Array.isArray(_iterator16), _i16 = 0, _iterator16 = _isArray16 ? _iterator16 : (0, _getIterator3.default)(_iterator16);;) { + var _ref16; + + if (_isArray16) { + if (_i16 >= _iterator16.length) break; + _ref16 = _iterator16[_i16++]; + } else { + _i16 = _iterator16.next(); + if (_i16.done) break; + _ref16 = _i16.value; + } + + var _path = _ref16; + + var ids = _path.getBindingIdentifiers(); + var programParent = void 0; + for (var name in ids) { + if (_path.scope.getBinding(name)) continue; + + programParent = programParent || _path.scope.getProgramParent(); + programParent.addGlobal(ids[name]); + } + + _path.scope.registerConstantViolation(_path); + } + + for (var _iterator17 = state.references, _isArray17 = Array.isArray(_iterator17), _i17 = 0, _iterator17 = _isArray17 ? _iterator17 : (0, _getIterator3.default)(_iterator17);;) { + var _ref17; + + if (_isArray17) { + if (_i17 >= _iterator17.length) break; + _ref17 = _iterator17[_i17++]; + } else { + _i17 = _iterator17.next(); + if (_i17.done) break; + _ref17 = _i17.value; + } + + var ref = _ref17; + + var binding = ref.scope.getBinding(ref.node.name); + if (binding) { + binding.reference(ref); + } else { + ref.scope.getProgramParent().addGlobal(ref.node); + } + } + + for (var _iterator18 = state.constantViolations, _isArray18 = Array.isArray(_iterator18), _i18 = 0, _iterator18 = _isArray18 ? _iterator18 : (0, _getIterator3.default)(_iterator18);;) { + var _ref18; + + if (_isArray18) { + if (_i18 >= _iterator18.length) break; + _ref18 = _iterator18[_i18++]; + } else { + _i18 = _iterator18.next(); + if (_i18.done) break; + _ref18 = _i18.value; + } + + var _path2 = _ref18; + + _path2.scope.registerConstantViolation(_path2); + } + }; + + Scope.prototype.push = function push(opts) { + var path = this.path; + + if (!path.isBlockStatement() && !path.isProgram()) { + path = this.getBlockParent().path; + } + + if (path.isSwitchStatement()) { + path = this.getFunctionParent().path; + } + + if (path.isLoop() || path.isCatchClause() || path.isFunction()) { + t.ensureBlock(path.node); + path = path.get("body"); + } + + var unique = opts.unique; + var kind = opts.kind || "var"; + var blockHoist = opts._blockHoist == null ? 2 : opts._blockHoist; + + var dataKey = "declaration:" + kind + ":" + blockHoist; + var declarPath = !unique && path.getData(dataKey); + + if (!declarPath) { + var declar = t.variableDeclaration(kind, []); + declar._generated = true; + declar._blockHoist = blockHoist; + + var _path$unshiftContaine = path.unshiftContainer("body", [declar]); + + declarPath = _path$unshiftContaine[0]; + + if (!unique) path.setData(dataKey, declarPath); + } + + var declarator = t.variableDeclarator(opts.id, opts.init); + declarPath.node.declarations.push(declarator); + this.registerBinding(kind, declarPath.get("declarations").pop()); + }; + + Scope.prototype.getProgramParent = function getProgramParent() { + var scope = this; + do { + if (scope.path.isProgram()) { + return scope; + } + } while (scope = scope.parent); + throw new Error("We couldn't find a Function or Program..."); + }; + + Scope.prototype.getFunctionParent = function getFunctionParent() { + var scope = this; + do { + if (scope.path.isFunctionParent()) { + return scope; + } + } while (scope = scope.parent); + throw new Error("We couldn't find a Function or Program..."); + }; + + Scope.prototype.getBlockParent = function getBlockParent() { + var scope = this; + do { + if (scope.path.isBlockParent()) { + return scope; + } + } while (scope = scope.parent); + throw new Error("We couldn't find a BlockStatement, For, Switch, Function, Loop or Program..."); + }; + + Scope.prototype.getAllBindings = function getAllBindings() { + var ids = (0, _create2.default)(null); + + var scope = this; + do { + (0, _defaults2.default)(ids, scope.bindings); + scope = scope.parent; + } while (scope); + + return ids; + }; + + Scope.prototype.getAllBindingsOfKind = function getAllBindingsOfKind() { + var ids = (0, _create2.default)(null); + + for (var _iterator19 = arguments, _isArray19 = Array.isArray(_iterator19), _i19 = 0, _iterator19 = _isArray19 ? _iterator19 : (0, _getIterator3.default)(_iterator19);;) { + var _ref19; + + if (_isArray19) { + if (_i19 >= _iterator19.length) break; + _ref19 = _iterator19[_i19++]; + } else { + _i19 = _iterator19.next(); + if (_i19.done) break; + _ref19 = _i19.value; + } + + var kind = _ref19; + + var scope = this; + do { + for (var name in scope.bindings) { + var binding = scope.bindings[name]; + if (binding.kind === kind) ids[name] = binding; + } + scope = scope.parent; + } while (scope); + } + + return ids; + }; + + Scope.prototype.bindingIdentifierEquals = function bindingIdentifierEquals(name, node) { + return this.getBindingIdentifier(name) === node; + }; + + Scope.prototype.warnOnFlowBinding = function warnOnFlowBinding(binding) { + if (_crawlCallsCount === 0 && binding && binding.path.isFlow()) { + console.warn("\n You or one of the Babel plugins you are using are using Flow declarations as bindings.\n Support for this will be removed in version 6.8. To find out the caller, grep for this\n message and change it to a `console.trace()`.\n "); + } + return binding; + }; + + Scope.prototype.getBinding = function getBinding(name) { + var scope = this; + + do { + var binding = scope.getOwnBinding(name); + if (binding) return this.warnOnFlowBinding(binding); + } while (scope = scope.parent); + }; + + Scope.prototype.getOwnBinding = function getOwnBinding(name) { + return this.warnOnFlowBinding(this.bindings[name]); + }; + + Scope.prototype.getBindingIdentifier = function getBindingIdentifier(name) { + var info = this.getBinding(name); + return info && info.identifier; + }; + + Scope.prototype.getOwnBindingIdentifier = function getOwnBindingIdentifier(name) { + var binding = this.bindings[name]; + return binding && binding.identifier; + }; + + Scope.prototype.hasOwnBinding = function hasOwnBinding(name) { + return !!this.getOwnBinding(name); + }; + + Scope.prototype.hasBinding = function hasBinding(name, noGlobals) { + if (!name) return false; + if (this.hasOwnBinding(name)) return true; + if (this.parentHasBinding(name, noGlobals)) return true; + if (this.hasUid(name)) return true; + if (!noGlobals && (0, _includes2.default)(Scope.globals, name)) return true; + if (!noGlobals && (0, _includes2.default)(Scope.contextVariables, name)) return true; + return false; + }; + + Scope.prototype.parentHasBinding = function parentHasBinding(name, noGlobals) { + return this.parent && this.parent.hasBinding(name, noGlobals); + }; + + Scope.prototype.moveBindingTo = function moveBindingTo(name, scope) { + var info = this.getBinding(name); + if (info) { + info.scope.removeOwnBinding(name); + info.scope = scope; + scope.bindings[name] = info; + } + }; + + Scope.prototype.removeOwnBinding = function removeOwnBinding(name) { + delete this.bindings[name]; + }; + + Scope.prototype.removeBinding = function removeBinding(name) { + var info = this.getBinding(name); + if (info) { + info.scope.removeOwnBinding(name); + } + + var scope = this; + do { + if (scope.uids[name]) { + scope.uids[name] = false; + } + } while (scope = scope.parent); + }; + + return Scope; +}(); + +Scope.globals = (0, _keys2.default)(_globals2.default.builtin); +Scope.contextVariables = ["arguments", "undefined", "Infinity", "NaN"]; +exports.default = Scope; +module.exports = exports["default"]; +},{"../cache":157,"../index":160,"./binding":178,"./lib/renamer":180,"babel-messages":76,"babel-runtime/core-js/get-iterator":138,"babel-runtime/core-js/object/create":143,"babel-runtime/core-js/object/keys":145,"babel-runtime/helpers/classCallCheck":152,"babel-types":193,"globals":350,"lodash/defaults":532,"lodash/includes":546,"lodash/repeat":573}],180:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck"); + +var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); + +var _binding = require("../binding"); + +var _binding2 = _interopRequireDefault(_binding); + +var _babelTypes = require("babel-types"); + +var t = _interopRequireWildcard(_babelTypes); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var renameVisitor = { + ReferencedIdentifier: function ReferencedIdentifier(_ref, state) { + var node = _ref.node; + + if (node.name === state.oldName) { + node.name = state.newName; + } + }, + Scope: function Scope(path, state) { + if (!path.scope.bindingIdentifierEquals(state.oldName, state.binding.identifier)) { + path.skip(); + } + }, + "AssignmentExpression|Declaration": function AssignmentExpressionDeclaration(path, state) { + var ids = path.getOuterBindingIdentifiers(); + + for (var name in ids) { + if (name === state.oldName) ids[name].name = state.newName; + } + } +}; + +var Renamer = function () { + function Renamer(binding, oldName, newName) { + (0, _classCallCheck3.default)(this, Renamer); + + this.newName = newName; + this.oldName = oldName; + this.binding = binding; + } + + Renamer.prototype.maybeConvertFromExportDeclaration = function maybeConvertFromExportDeclaration(parentDeclar) { + var exportDeclar = parentDeclar.parentPath.isExportDeclaration() && parentDeclar.parentPath; + if (!exportDeclar) return; + + var isDefault = exportDeclar.isExportDefaultDeclaration(); + + if (isDefault && (parentDeclar.isFunctionDeclaration() || parentDeclar.isClassDeclaration()) && !parentDeclar.node.id) { + parentDeclar.node.id = parentDeclar.scope.generateUidIdentifier("default"); + } + + var bindingIdentifiers = parentDeclar.getOuterBindingIdentifiers(); + var specifiers = []; + + for (var name in bindingIdentifiers) { + var localName = name === this.oldName ? this.newName : name; + var exportedName = isDefault ? "default" : name; + specifiers.push(t.exportSpecifier(t.identifier(localName), t.identifier(exportedName))); + } + + if (specifiers.length) { + var aliasDeclar = t.exportNamedDeclaration(null, specifiers); + + if (parentDeclar.isFunctionDeclaration()) { + aliasDeclar._blockHoist = 3; + } + + exportDeclar.insertAfter(aliasDeclar); + exportDeclar.replaceWith(parentDeclar.node); + } + }; + + Renamer.prototype.maybeConvertFromClassFunctionDeclaration = function maybeConvertFromClassFunctionDeclaration(path) { + return; + + if (!path.isFunctionDeclaration() && !path.isClassDeclaration()) return; + if (this.binding.kind !== "hoisted") return; + + path.node.id = t.identifier(this.oldName); + path.node._blockHoist = 3; + + path.replaceWith(t.variableDeclaration("let", [t.variableDeclarator(t.identifier(this.newName), t.toExpression(path.node))])); + }; + + Renamer.prototype.maybeConvertFromClassFunctionExpression = function maybeConvertFromClassFunctionExpression(path) { + return; + + if (!path.isFunctionExpression() && !path.isClassExpression()) return; + if (this.binding.kind !== "local") return; + + path.node.id = t.identifier(this.oldName); + + this.binding.scope.parent.push({ + id: t.identifier(this.newName) + }); + + path.replaceWith(t.assignmentExpression("=", t.identifier(this.newName), path.node)); + }; + + Renamer.prototype.rename = function rename(block) { + var binding = this.binding; + var oldName = this.oldName; + var newName = this.newName; + var scope = binding.scope; + var path = binding.path; + + + var parentDeclar = path.find(function (path) { + return path.isDeclaration() || path.isFunctionExpression(); + }); + if (parentDeclar) { + this.maybeConvertFromExportDeclaration(parentDeclar); + } + + scope.traverse(block || scope.block, renameVisitor, this); + + if (!block) { + scope.removeOwnBinding(oldName); + scope.bindings[newName] = binding; + this.binding.identifier.name = newName; + } + + if (binding.type === "hoisted") {} + + if (parentDeclar) { + this.maybeConvertFromClassFunctionDeclaration(parentDeclar); + this.maybeConvertFromClassFunctionExpression(parentDeclar); + } + }; + + return Renamer; +}(); + +exports.default = Renamer; +module.exports = exports["default"]; +},{"../binding":178,"babel-runtime/helpers/classCallCheck":152,"babel-types":193}],181:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +var _typeof2 = require("babel-runtime/helpers/typeof"); + +var _typeof3 = _interopRequireDefault(_typeof2); + +var _keys = require("babel-runtime/core-js/object/keys"); + +var _keys2 = _interopRequireDefault(_keys); + +var _getIterator2 = require("babel-runtime/core-js/get-iterator"); + +var _getIterator3 = _interopRequireDefault(_getIterator2); + +exports.explode = explode; +exports.verify = verify; +exports.merge = merge; + +var _virtualTypes = require("./path/lib/virtual-types"); + +var virtualTypes = _interopRequireWildcard(_virtualTypes); + +var _babelMessages = require("babel-messages"); + +var messages = _interopRequireWildcard(_babelMessages); + +var _babelTypes = require("babel-types"); + +var t = _interopRequireWildcard(_babelTypes); + +var _clone = require("lodash/clone"); + +var _clone2 = _interopRequireDefault(_clone); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function explode(visitor) { + if (visitor._exploded) return visitor; + visitor._exploded = true; + + for (var nodeType in visitor) { + if (shouldIgnoreKey(nodeType)) continue; + + var parts = nodeType.split("|"); + if (parts.length === 1) continue; + + var fns = visitor[nodeType]; + delete visitor[nodeType]; + + for (var _iterator = parts, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_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 part = _ref; + + visitor[part] = fns; + } + } + + verify(visitor); + + delete visitor.__esModule; + + ensureEntranceObjects(visitor); + + ensureCallbackArrays(visitor); + + for (var _iterator2 = (0, _keys2.default)(visitor), _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : (0, _getIterator3.default)(_iterator2);;) { + var _ref2; + + if (_isArray2) { + if (_i2 >= _iterator2.length) break; + _ref2 = _iterator2[_i2++]; + } else { + _i2 = _iterator2.next(); + if (_i2.done) break; + _ref2 = _i2.value; + } + + var _nodeType3 = _ref2; + + if (shouldIgnoreKey(_nodeType3)) continue; + + var wrapper = virtualTypes[_nodeType3]; + if (!wrapper) continue; + + var _fns2 = visitor[_nodeType3]; + for (var type in _fns2) { + _fns2[type] = wrapCheck(wrapper, _fns2[type]); + } + + delete visitor[_nodeType3]; + + if (wrapper.types) { + for (var _iterator4 = wrapper.types, _isArray4 = Array.isArray(_iterator4), _i4 = 0, _iterator4 = _isArray4 ? _iterator4 : (0, _getIterator3.default)(_iterator4);;) { + var _ref4; + + if (_isArray4) { + if (_i4 >= _iterator4.length) break; + _ref4 = _iterator4[_i4++]; + } else { + _i4 = _iterator4.next(); + if (_i4.done) break; + _ref4 = _i4.value; + } + + var _type = _ref4; + + if (visitor[_type]) { + mergePair(visitor[_type], _fns2); + } else { + visitor[_type] = _fns2; + } + } + } else { + mergePair(visitor, _fns2); + } + } + + for (var _nodeType in visitor) { + if (shouldIgnoreKey(_nodeType)) continue; + + var _fns = visitor[_nodeType]; + + var aliases = t.FLIPPED_ALIAS_KEYS[_nodeType]; + + var deprecratedKey = t.DEPRECATED_KEYS[_nodeType]; + if (deprecratedKey) { + console.trace("Visitor defined for " + _nodeType + " but it has been renamed to " + deprecratedKey); + aliases = [deprecratedKey]; + } + + if (!aliases) continue; + + delete visitor[_nodeType]; + + for (var _iterator3 = aliases, _isArray3 = Array.isArray(_iterator3), _i3 = 0, _iterator3 = _isArray3 ? _iterator3 : (0, _getIterator3.default)(_iterator3);;) { + var _ref3; + + if (_isArray3) { + if (_i3 >= _iterator3.length) break; + _ref3 = _iterator3[_i3++]; + } else { + _i3 = _iterator3.next(); + if (_i3.done) break; + _ref3 = _i3.value; + } + + var alias = _ref3; + + var existing = visitor[alias]; + if (existing) { + mergePair(existing, _fns); + } else { + visitor[alias] = (0, _clone2.default)(_fns); + } + } + } + + for (var _nodeType2 in visitor) { + if (shouldIgnoreKey(_nodeType2)) continue; + + ensureCallbackArrays(visitor[_nodeType2]); + } + + return visitor; +} + +function verify(visitor) { + if (visitor._verified) return; + + if (typeof visitor === "function") { + throw new Error(messages.get("traverseVerifyRootFunction")); + } + + for (var nodeType in visitor) { + if (nodeType === "enter" || nodeType === "exit") { + validateVisitorMethods(nodeType, visitor[nodeType]); + } + + if (shouldIgnoreKey(nodeType)) continue; + + if (t.TYPES.indexOf(nodeType) < 0) { + throw new Error(messages.get("traverseVerifyNodeType", nodeType)); + } + + var visitors = visitor[nodeType]; + if ((typeof visitors === "undefined" ? "undefined" : (0, _typeof3.default)(visitors)) === "object") { + for (var visitorKey in visitors) { + if (visitorKey === "enter" || visitorKey === "exit") { + validateVisitorMethods(nodeType + "." + visitorKey, visitors[visitorKey]); + } else { + throw new Error(messages.get("traverseVerifyVisitorProperty", nodeType, visitorKey)); + } + } + } + } + + visitor._verified = true; +} + +function validateVisitorMethods(path, val) { + var fns = [].concat(val); + for (var _iterator5 = fns, _isArray5 = Array.isArray(_iterator5), _i5 = 0, _iterator5 = _isArray5 ? _iterator5 : (0, _getIterator3.default)(_iterator5);;) { + var _ref5; + + if (_isArray5) { + if (_i5 >= _iterator5.length) break; + _ref5 = _iterator5[_i5++]; + } else { + _i5 = _iterator5.next(); + if (_i5.done) break; + _ref5 = _i5.value; + } + + var fn = _ref5; + + if (typeof fn !== "function") { + throw new TypeError("Non-function found defined in " + path + " with type " + (typeof fn === "undefined" ? "undefined" : (0, _typeof3.default)(fn))); + } + } +} + +function merge(visitors) { + var states = arguments.length <= 1 || arguments[1] === undefined ? [] : arguments[1]; + var wrapper = arguments[2]; + + var rootVisitor = {}; + + for (var i = 0; i < visitors.length; i++) { + var visitor = visitors[i]; + var state = states[i]; + + explode(visitor); + + for (var type in visitor) { + var visitorType = visitor[type]; + + if (state || wrapper) { + visitorType = wrapWithStateOrWrapper(visitorType, state, wrapper); + } + + var nodeVisitor = rootVisitor[type] = rootVisitor[type] || {}; + mergePair(nodeVisitor, visitorType); + } + } + + return rootVisitor; +} + +function wrapWithStateOrWrapper(oldVisitor, state, wrapper) { + var newVisitor = {}; + + var _loop = function _loop(key) { + var fns = oldVisitor[key]; + + if (!Array.isArray(fns)) return "continue"; + + fns = fns.map(function (fn) { + var newFn = fn; + + if (state) { + newFn = function newFn(path) { + return fn.call(state, path, state); + }; + } + + if (wrapper) { + newFn = wrapper(state.key, key, newFn); + } + + return newFn; + }); + + newVisitor[key] = fns; + }; + + for (var key in oldVisitor) { + var _ret = _loop(key); + + if (_ret === "continue") continue; + } + + return newVisitor; +} + +function ensureEntranceObjects(obj) { + for (var key in obj) { + if (shouldIgnoreKey(key)) continue; + + var fns = obj[key]; + if (typeof fns === "function") { + obj[key] = { enter: fns }; + } + } +} + +function ensureCallbackArrays(obj) { + if (obj.enter && !Array.isArray(obj.enter)) obj.enter = [obj.enter]; + if (obj.exit && !Array.isArray(obj.exit)) obj.exit = [obj.exit]; +} + +function wrapCheck(wrapper, fn) { + var newFn = function newFn(path) { + if (wrapper.checkPath(path)) { + return fn.apply(this, arguments); + } + }; + newFn.toString = function () { + return fn.toString(); + }; + return newFn; +} + +function shouldIgnoreKey(key) { + if (key[0] === "_") return true; + + if (key === "enter" || key === "exit" || key === "shouldSkip") return true; + + if (key === "blacklist" || key === "noScope" || key === "skipKeys") return true; + + return false; +} + +function mergePair(dest, src) { + for (var key in src) { + dest[key] = [].concat(dest[key] || [], src[key]); + } +} +},{"./path/lib/virtual-types":174,"babel-messages":76,"babel-runtime/core-js/get-iterator":138,"babel-runtime/core-js/object/keys":145,"babel-runtime/helpers/typeof":155,"babel-types":193,"lodash/clone":527}],182:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; +exports.NOT_LOCAL_BINDING = exports.BLOCK_SCOPED_SYMBOL = exports.INHERIT_KEYS = exports.UNARY_OPERATORS = exports.STRING_UNARY_OPERATORS = exports.NUMBER_UNARY_OPERATORS = exports.BOOLEAN_UNARY_OPERATORS = exports.BINARY_OPERATORS = exports.NUMBER_BINARY_OPERATORS = exports.BOOLEAN_BINARY_OPERATORS = exports.COMPARISON_BINARY_OPERATORS = exports.EQUALITY_BINARY_OPERATORS = exports.BOOLEAN_NUMBER_BINARY_OPERATORS = exports.UPDATE_OPERATORS = exports.LOGICAL_OPERATORS = exports.COMMENT_KEYS = exports.FOR_INIT_KEYS = exports.FLATTENABLE_KEYS = exports.STATEMENT_OR_BLOCK_KEYS = undefined; + +var _for = require("babel-runtime/core-js/symbol/for"); + +var _for2 = _interopRequireDefault(_for); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var STATEMENT_OR_BLOCK_KEYS = exports.STATEMENT_OR_BLOCK_KEYS = ["consequent", "body", "alternate"]; +var FLATTENABLE_KEYS = exports.FLATTENABLE_KEYS = ["body", "expressions"]; +var FOR_INIT_KEYS = exports.FOR_INIT_KEYS = ["left", "init"]; +var COMMENT_KEYS = exports.COMMENT_KEYS = ["leadingComments", "trailingComments", "innerComments"]; + +var LOGICAL_OPERATORS = exports.LOGICAL_OPERATORS = ["||", "&&"]; +var UPDATE_OPERATORS = exports.UPDATE_OPERATORS = ["++", "--"]; + +var BOOLEAN_NUMBER_BINARY_OPERATORS = exports.BOOLEAN_NUMBER_BINARY_OPERATORS = [">", "<", ">=", "<="]; +var EQUALITY_BINARY_OPERATORS = exports.EQUALITY_BINARY_OPERATORS = ["==", "===", "!=", "!=="]; +var COMPARISON_BINARY_OPERATORS = exports.COMPARISON_BINARY_OPERATORS = [].concat(EQUALITY_BINARY_OPERATORS, ["in", "instanceof"]); +var BOOLEAN_BINARY_OPERATORS = exports.BOOLEAN_BINARY_OPERATORS = [].concat(COMPARISON_BINARY_OPERATORS, BOOLEAN_NUMBER_BINARY_OPERATORS); +var NUMBER_BINARY_OPERATORS = exports.NUMBER_BINARY_OPERATORS = ["-", "/", "%", "*", "**", "&", "|", ">>", ">>>", "<<", "^"]; +var BINARY_OPERATORS = exports.BINARY_OPERATORS = ["+"].concat(NUMBER_BINARY_OPERATORS, BOOLEAN_BINARY_OPERATORS); + +var BOOLEAN_UNARY_OPERATORS = exports.BOOLEAN_UNARY_OPERATORS = ["delete", "!"]; +var NUMBER_UNARY_OPERATORS = exports.NUMBER_UNARY_OPERATORS = ["+", "-", "++", "--", "~"]; +var STRING_UNARY_OPERATORS = exports.STRING_UNARY_OPERATORS = ["typeof"]; +var UNARY_OPERATORS = exports.UNARY_OPERATORS = ["void"].concat(BOOLEAN_UNARY_OPERATORS, NUMBER_UNARY_OPERATORS, STRING_UNARY_OPERATORS); + +var INHERIT_KEYS = exports.INHERIT_KEYS = { + optional: ["typeAnnotation", "typeParameters", "returnType"], + force: ["start", "loc", "end"] +}; + +var BLOCK_SCOPED_SYMBOL = exports.BLOCK_SCOPED_SYMBOL = (0, _for2.default)("var used to be block scoped"); +var NOT_LOCAL_BINDING = exports.NOT_LOCAL_BINDING = (0, _for2.default)("should not be considered a local binding"); +},{"babel-runtime/core-js/symbol/for":148}],183:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +var _maxSafeInteger = require("babel-runtime/core-js/number/max-safe-integer"); + +var _maxSafeInteger2 = _interopRequireDefault(_maxSafeInteger); + +var _stringify = require("babel-runtime/core-js/json/stringify"); + +var _stringify2 = _interopRequireDefault(_stringify); + +var _getIterator2 = require("babel-runtime/core-js/get-iterator"); + +var _getIterator3 = _interopRequireDefault(_getIterator2); + +exports.toComputedKey = toComputedKey; +exports.toSequenceExpression = toSequenceExpression; +exports.toKeyAlias = toKeyAlias; +exports.toIdentifier = toIdentifier; +exports.toBindingIdentifierName = toBindingIdentifierName; +exports.toStatement = toStatement; +exports.toExpression = toExpression; +exports.toBlock = toBlock; +exports.valueToNode = valueToNode; + +var _isPlainObject = require("lodash/isPlainObject"); + +var _isPlainObject2 = _interopRequireDefault(_isPlainObject); + +var _isNumber = require("lodash/isNumber"); + +var _isNumber2 = _interopRequireDefault(_isNumber); + +var _isRegExp = require("lodash/isRegExp"); + +var _isRegExp2 = _interopRequireDefault(_isRegExp); + +var _isString = require("lodash/isString"); + +var _isString2 = _interopRequireDefault(_isString); + +var _index = require("./index"); + +var t = _interopRequireWildcard(_index); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function toComputedKey(node) { + var key = arguments.length <= 1 || arguments[1] === undefined ? node.key || node.property : arguments[1]; + + if (!node.computed) { + if (t.isIdentifier(key)) key = t.stringLiteral(key.name); + } + return key; +} + +function toSequenceExpression(nodes, scope) { + if (!nodes || !nodes.length) return; + + var declars = []; + var bailed = false; + + var result = convert(nodes); + if (bailed) return; + + for (var i = 0; i < declars.length; i++) { + scope.push(declars[i]); + } + + return result; + + function convert(nodes) { + var ensureLastUndefined = false; + var exprs = []; + + for (var _iterator = nodes, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_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 node = _ref; + + if (t.isExpression(node)) { + exprs.push(node); + } else if (t.isExpressionStatement(node)) { + exprs.push(node.expression); + } else if (t.isVariableDeclaration(node)) { + if (node.kind !== "var") return bailed = true; + + for (var _iterator2 = node.declarations, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : (0, _getIterator3.default)(_iterator2);;) { + var _ref2; + + if (_isArray2) { + if (_i2 >= _iterator2.length) break; + _ref2 = _iterator2[_i2++]; + } else { + _i2 = _iterator2.next(); + if (_i2.done) break; + _ref2 = _i2.value; + } + + var declar = _ref2; + + var bindings = t.getBindingIdentifiers(declar); + for (var key in bindings) { + declars.push({ + kind: node.kind, + id: bindings[key] + }); + } + + if (declar.init) { + exprs.push(t.assignmentExpression("=", declar.id, declar.init)); + } + } + + ensureLastUndefined = true; + continue; + } else if (t.isIfStatement(node)) { + var consequent = node.consequent ? convert([node.consequent]) : scope.buildUndefinedNode(); + var alternate = node.alternate ? convert([node.alternate]) : scope.buildUndefinedNode(); + if (!consequent || !alternate) return bailed = true; + + exprs.push(t.conditionalExpression(node.test, consequent, alternate)); + } else if (t.isBlockStatement(node)) { + exprs.push(convert(node.body)); + } else if (t.isEmptyStatement(node)) { + ensureLastUndefined = true; + continue; + } else { + return bailed = true; + } + + ensureLastUndefined = false; + } + + if (ensureLastUndefined || exprs.length === 0) { + exprs.push(scope.buildUndefinedNode()); + } + + if (exprs.length === 1) { + return exprs[0]; + } else { + return t.sequenceExpression(exprs); + } + } +} + +function toKeyAlias(node) { + var key = arguments.length <= 1 || arguments[1] === undefined ? node.key : arguments[1]; + + var alias = void 0; + + if (node.kind === "method") { + return toKeyAlias.increment() + ""; + } else if (t.isIdentifier(key)) { + alias = key.name; + } else if (t.isStringLiteral(key)) { + alias = (0, _stringify2.default)(key.value); + } else { + alias = (0, _stringify2.default)(t.removePropertiesDeep(t.cloneDeep(key))); + } + + if (node.computed) { + alias = "[" + alias + "]"; + } + + if (node.static) { + alias = "static:" + alias; + } + + return alias; +} + +toKeyAlias.uid = 0; + +toKeyAlias.increment = function () { + if (toKeyAlias.uid >= _maxSafeInteger2.default) { + return toKeyAlias.uid = 0; + } else { + return toKeyAlias.uid++; + } +}; + +function toIdentifier(name) { + name = name + ""; + + name = name.replace(/[^a-zA-Z0-9$_]/g, "-"); + + name = name.replace(/^[-0-9]+/, ""); + + name = name.replace(/[-\s]+(.)?/g, function (match, c) { + return c ? c.toUpperCase() : ""; + }); + + if (!t.isValidIdentifier(name)) { + name = "_" + name; + } + + return name || "_"; +} + +function toBindingIdentifierName(name) { + name = toIdentifier(name); + if (name === "eval" || name === "arguments") name = "_" + name; + return name; +} + +function toStatement(node, ignore) { + if (t.isStatement(node)) { + return node; + } + + var mustHaveId = false; + var newType = void 0; + + if (t.isClass(node)) { + mustHaveId = true; + newType = "ClassDeclaration"; + } else if (t.isFunction(node)) { + mustHaveId = true; + newType = "FunctionDeclaration"; + } else if (t.isAssignmentExpression(node)) { + return t.expressionStatement(node); + } + + if (mustHaveId && !node.id) { + newType = false; + } + + if (!newType) { + if (ignore) { + return false; + } else { + throw new Error("cannot turn " + node.type + " to a statement"); + } + } + + node.type = newType; + + return node; +} + +function toExpression(node) { + if (t.isExpressionStatement(node)) { + node = node.expression; + } + + if (t.isExpression(node)) { + return node; + } + + if (t.isClass(node)) { + node.type = "ClassExpression"; + } else if (t.isFunction(node)) { + node.type = "FunctionExpression"; + } + + if (!t.isExpression(node)) { + throw new Error("cannot turn " + node.type + " to an expression"); + } + + return node; +} + +function toBlock(node, parent) { + if (t.isBlockStatement(node)) { + return node; + } + + if (t.isEmptyStatement(node)) { + node = []; + } + + if (!Array.isArray(node)) { + if (!t.isStatement(node)) { + if (t.isFunction(parent)) { + node = t.returnStatement(node); + } else { + node = t.expressionStatement(node); + } + } + + node = [node]; + } + + return t.blockStatement(node); +} + +function valueToNode(value) { + if (value === undefined) { + return t.identifier("undefined"); + } + + if (value === true || value === false) { + return t.booleanLiteral(value); + } + + if (value === null) { + return t.nullLiteral(); + } + + if ((0, _isString2.default)(value)) { + return t.stringLiteral(value); + } + + if ((0, _isNumber2.default)(value)) { + return t.numericLiteral(value); + } + + if ((0, _isRegExp2.default)(value)) { + var pattern = value.source; + var flags = value.toString().match(/\/([a-z]+|)$/)[1]; + return t.regExpLiteral(pattern, flags); + } + + if (Array.isArray(value)) { + return t.arrayExpression(value.map(t.valueToNode)); + } + + if ((0, _isPlainObject2.default)(value)) { + var props = []; + for (var key in value) { + var nodeKey = void 0; + if (t.isValidIdentifier(key)) { + nodeKey = t.identifier(key); + } else { + nodeKey = t.stringLiteral(key); + } + props.push(t.objectProperty(nodeKey, t.valueToNode(value[key]))); + } + return t.objectExpression(props); + } + + throw new Error("don't know how to turn this value into a node"); +} +},{"./index":193,"babel-runtime/core-js/get-iterator":138,"babel-runtime/core-js/json/stringify":139,"babel-runtime/core-js/number/max-safe-integer":141,"lodash/isNumber":556,"lodash/isPlainObject":559,"lodash/isRegExp":560,"lodash/isString":561}],184:[function(require,module,exports){ +"use strict"; + +var _index = require("../index"); + +var t = _interopRequireWildcard(_index); + +var _constants = require("../constants"); + +var _index2 = require("./index"); + +var _index3 = _interopRequireDefault(_index2); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +(0, _index3.default)("ArrayExpression", { + fields: { + elements: { + validate: (0, _index2.chain)((0, _index2.assertValueType)("array"), (0, _index2.assertEach)((0, _index2.assertNodeOrValueType)("null", "Expression", "SpreadElement"))), + default: [] + } + }, + visitor: ["elements"], + aliases: ["Expression"] +}); + +(0, _index3.default)("AssignmentExpression", { + fields: { + operator: { + validate: (0, _index2.assertValueType)("string") + }, + left: { + validate: (0, _index2.assertNodeType)("LVal") + }, + right: { + validate: (0, _index2.assertNodeType)("Expression") + } + }, + builder: ["operator", "left", "right"], + visitor: ["left", "right"], + aliases: ["Expression"] +}); + +(0, _index3.default)("BinaryExpression", { + builder: ["operator", "left", "right"], + fields: { + operator: { + validate: _index2.assertOneOf.apply(undefined, _constants.BINARY_OPERATORS) + }, + left: { + validate: (0, _index2.assertNodeType)("Expression") + }, + right: { + validate: (0, _index2.assertNodeType)("Expression") + } + }, + visitor: ["left", "right"], + aliases: ["Binary", "Expression"] +}); + +(0, _index3.default)("Directive", { + visitor: ["value"], + fields: { + value: { + validate: (0, _index2.assertNodeType)("DirectiveLiteral") + } + } +}); + +(0, _index3.default)("DirectiveLiteral", { + builder: ["value"], + fields: { + value: { + validate: (0, _index2.assertValueType)("string") + } + } +}); + +(0, _index3.default)("BlockStatement", { + builder: ["body", "directives"], + visitor: ["directives", "body"], + fields: { + directives: { + validate: (0, _index2.chain)((0, _index2.assertValueType)("array"), (0, _index2.assertEach)((0, _index2.assertNodeType)("Directive"))), + default: [] + }, + body: { + validate: (0, _index2.chain)((0, _index2.assertValueType)("array"), (0, _index2.assertEach)((0, _index2.assertNodeType)("Statement"))) + } + }, + aliases: ["Scopable", "BlockParent", "Block", "Statement"] +}); + +(0, _index3.default)("BreakStatement", { + visitor: ["label"], + fields: { + label: { + validate: (0, _index2.assertNodeType)("Identifier"), + optional: true + } + }, + aliases: ["Statement", "Terminatorless", "CompletionStatement"] +}); + +(0, _index3.default)("CallExpression", { + visitor: ["callee", "arguments"], + fields: { + callee: { + validate: (0, _index2.assertNodeType)("Expression") + }, + arguments: { + validate: (0, _index2.chain)((0, _index2.assertValueType)("array"), (0, _index2.assertEach)((0, _index2.assertNodeType)("Expression", "SpreadElement"))) + } + }, + aliases: ["Expression"] +}); + +(0, _index3.default)("CatchClause", { + visitor: ["param", "body"], + fields: { + param: { + validate: (0, _index2.assertNodeType)("Identifier") + }, + body: { + validate: (0, _index2.assertNodeType)("BlockStatement") + } + }, + aliases: ["Scopable"] +}); + +(0, _index3.default)("ConditionalExpression", { + visitor: ["test", "consequent", "alternate"], + fields: { + test: { + validate: (0, _index2.assertNodeType)("Expression") + }, + consequent: { + validate: (0, _index2.assertNodeType)("Expression") + }, + alternate: { + validate: (0, _index2.assertNodeType)("Expression") + } + }, + aliases: ["Expression", "Conditional"] +}); + +(0, _index3.default)("ContinueStatement", { + visitor: ["label"], + fields: { + label: { + validate: (0, _index2.assertNodeType)("Identifier"), + optional: true + } + }, + aliases: ["Statement", "Terminatorless", "CompletionStatement"] +}); + +(0, _index3.default)("DebuggerStatement", { + aliases: ["Statement"] +}); + +(0, _index3.default)("DoWhileStatement", { + visitor: ["test", "body"], + fields: { + test: { + validate: (0, _index2.assertNodeType)("Expression") + }, + body: { + validate: (0, _index2.assertNodeType)("Statement") + } + }, + aliases: ["Statement", "BlockParent", "Loop", "While", "Scopable"] +}); + +(0, _index3.default)("EmptyStatement", { + aliases: ["Statement"] +}); + +(0, _index3.default)("ExpressionStatement", { + visitor: ["expression"], + fields: { + expression: { + validate: (0, _index2.assertNodeType)("Expression") + } + }, + aliases: ["Statement", "ExpressionWrapper"] +}); + +(0, _index3.default)("File", { + builder: ["program", "comments", "tokens"], + visitor: ["program"], + fields: { + program: { + validate: (0, _index2.assertNodeType)("Program") + } + } +}); + +(0, _index3.default)("ForInStatement", { + visitor: ["left", "right", "body"], + aliases: ["Scopable", "Statement", "For", "BlockParent", "Loop", "ForXStatement"], + fields: { + left: { + validate: (0, _index2.assertNodeType)("VariableDeclaration", "LVal") + }, + right: { + validate: (0, _index2.assertNodeType)("Expression") + }, + body: { + validate: (0, _index2.assertNodeType)("Statement") + } + } +}); + +(0, _index3.default)("ForStatement", { + visitor: ["init", "test", "update", "body"], + aliases: ["Scopable", "Statement", "For", "BlockParent", "Loop"], + fields: { + init: { + validate: (0, _index2.assertNodeType)("VariableDeclaration", "Expression"), + optional: true + }, + test: { + validate: (0, _index2.assertNodeType)("Expression"), + optional: true + }, + update: { + validate: (0, _index2.assertNodeType)("Expression"), + optional: true + }, + body: { + validate: (0, _index2.assertNodeType)("Statement") + } + } +}); + +(0, _index3.default)("FunctionDeclaration", { + builder: ["id", "params", "body", "generator", "async"], + visitor: ["id", "params", "body", "returnType", "typeParameters"], + fields: { + id: { + validate: (0, _index2.assertNodeType)("Identifier") + }, + params: { + validate: (0, _index2.chain)((0, _index2.assertValueType)("array"), (0, _index2.assertEach)((0, _index2.assertNodeType)("LVal"))) + }, + body: { + validate: (0, _index2.assertNodeType)("BlockStatement") + }, + generator: { + default: false, + validate: (0, _index2.assertValueType)("boolean") + }, + async: { + default: false, + validate: (0, _index2.assertValueType)("boolean") + } + }, + aliases: ["Scopable", "Function", "BlockParent", "FunctionParent", "Statement", "Pureish", "Declaration"] +}); + +(0, _index3.default)("FunctionExpression", { + inherits: "FunctionDeclaration", + aliases: ["Scopable", "Function", "BlockParent", "FunctionParent", "Expression", "Pureish"], + fields: { + id: { + validate: (0, _index2.assertNodeType)("Identifier"), + optional: true + }, + params: { + validate: (0, _index2.chain)((0, _index2.assertValueType)("array"), (0, _index2.assertEach)((0, _index2.assertNodeType)("LVal"))) + }, + body: { + validate: (0, _index2.assertNodeType)("BlockStatement") + }, + generator: { + default: false, + validate: (0, _index2.assertValueType)("boolean") + }, + async: { + default: false, + validate: (0, _index2.assertValueType)("boolean") + } + } +}); + +(0, _index3.default)("Identifier", { + builder: ["name"], + visitor: ["typeAnnotation"], + aliases: ["Expression", "LVal"], + fields: { + name: { + validate: function validate(node, key, val) { + if (!t.isValidIdentifier(val)) {} + } + }, + decorators: { + validate: (0, _index2.chain)((0, _index2.assertValueType)("array"), (0, _index2.assertEach)((0, _index2.assertNodeType)("Decorator"))) + } + } +}); + +(0, _index3.default)("IfStatement", { + visitor: ["test", "consequent", "alternate"], + aliases: ["Statement", "Conditional"], + fields: { + test: { + validate: (0, _index2.assertNodeType)("Expression") + }, + consequent: { + validate: (0, _index2.assertNodeType)("Statement") + }, + alternate: { + optional: true, + validate: (0, _index2.assertNodeType)("Statement") + } + } +}); + +(0, _index3.default)("LabeledStatement", { + visitor: ["label", "body"], + aliases: ["Statement"], + fields: { + label: { + validate: (0, _index2.assertNodeType)("Identifier") + }, + body: { + validate: (0, _index2.assertNodeType)("Statement") + } + } +}); + +(0, _index3.default)("StringLiteral", { + builder: ["value"], + fields: { + value: { + validate: (0, _index2.assertValueType)("string") + } + }, + aliases: ["Expression", "Pureish", "Literal", "Immutable"] +}); + +(0, _index3.default)("NumericLiteral", { + builder: ["value"], + deprecatedAlias: "NumberLiteral", + fields: { + value: { + validate: (0, _index2.assertValueType)("number") + } + }, + aliases: ["Expression", "Pureish", "Literal", "Immutable"] +}); + +(0, _index3.default)("NullLiteral", { + aliases: ["Expression", "Pureish", "Literal", "Immutable"] +}); + +(0, _index3.default)("BooleanLiteral", { + builder: ["value"], + fields: { + value: { + validate: (0, _index2.assertValueType)("boolean") + } + }, + aliases: ["Expression", "Pureish", "Literal", "Immutable"] +}); + +(0, _index3.default)("RegExpLiteral", { + builder: ["pattern", "flags"], + deprecatedAlias: "RegexLiteral", + aliases: ["Expression", "Literal"], + fields: { + pattern: { + validate: (0, _index2.assertValueType)("string") + }, + flags: { + validate: (0, _index2.assertValueType)("string"), + default: "" + } + } +}); + +(0, _index3.default)("LogicalExpression", { + builder: ["operator", "left", "right"], + visitor: ["left", "right"], + aliases: ["Binary", "Expression"], + fields: { + operator: { + validate: _index2.assertOneOf.apply(undefined, _constants.LOGICAL_OPERATORS) + }, + left: { + validate: (0, _index2.assertNodeType)("Expression") + }, + right: { + validate: (0, _index2.assertNodeType)("Expression") + } + } +}); + +(0, _index3.default)("MemberExpression", { + builder: ["object", "property", "computed"], + visitor: ["object", "property"], + aliases: ["Expression", "LVal"], + fields: { + object: { + validate: (0, _index2.assertNodeType)("Expression") + }, + property: { + validate: function validate(node, key, val) { + var expectedType = node.computed ? "Expression" : "Identifier"; + (0, _index2.assertNodeType)(expectedType)(node, key, val); + } + }, + computed: { + default: false + } + } +}); + +(0, _index3.default)("NewExpression", { + visitor: ["callee", "arguments"], + aliases: ["Expression"], + fields: { + callee: { + validate: (0, _index2.assertNodeType)("Expression") + }, + arguments: { + validate: (0, _index2.chain)((0, _index2.assertValueType)("array"), (0, _index2.assertEach)((0, _index2.assertNodeType)("Expression", "SpreadElement"))) + } + } +}); + +(0, _index3.default)("Program", { + visitor: ["directives", "body"], + builder: ["body", "directives"], + fields: { + directives: { + validate: (0, _index2.chain)((0, _index2.assertValueType)("array"), (0, _index2.assertEach)((0, _index2.assertNodeType)("Directive"))), + default: [] + }, + body: { + validate: (0, _index2.chain)((0, _index2.assertValueType)("array"), (0, _index2.assertEach)((0, _index2.assertNodeType)("Statement"))) + } + }, + aliases: ["Scopable", "BlockParent", "Block", "FunctionParent"] +}); + +(0, _index3.default)("ObjectExpression", { + visitor: ["properties"], + aliases: ["Expression"], + fields: { + properties: { + validate: (0, _index2.chain)((0, _index2.assertValueType)("array"), (0, _index2.assertEach)((0, _index2.assertNodeType)("ObjectMethod", "ObjectProperty", "SpreadProperty"))) + } + } +}); + +(0, _index3.default)("ObjectMethod", { + builder: ["kind", "key", "params", "body", "computed"], + fields: { + kind: { + validate: (0, _index2.chain)((0, _index2.assertValueType)("string"), (0, _index2.assertOneOf)("method", "get", "set")), + default: "method" + }, + computed: { + validate: (0, _index2.assertValueType)("boolean"), + default: false + }, + key: { + validate: function validate(node, key, val) { + var expectedTypes = node.computed ? ["Expression"] : ["Identifier", "StringLiteral", "NumericLiteral"]; + _index2.assertNodeType.apply(undefined, expectedTypes)(node, key, val); + } + }, + decorators: { + validate: (0, _index2.chain)((0, _index2.assertValueType)("array"), (0, _index2.assertEach)((0, _index2.assertNodeType)("Decorator"))) + }, + body: { + validate: (0, _index2.assertNodeType)("BlockStatement") + }, + generator: { + default: false, + validate: (0, _index2.assertValueType)("boolean") + }, + async: { + default: false, + validate: (0, _index2.assertValueType)("boolean") + } + }, + visitor: ["key", "params", "body", "decorators", "returnType", "typeParameters"], + aliases: ["UserWhitespacable", "Function", "Scopable", "BlockParent", "FunctionParent", "Method", "ObjectMember"] +}); + +(0, _index3.default)("ObjectProperty", { + builder: ["key", "value", "computed", "shorthand", "decorators"], + fields: { + computed: { + validate: (0, _index2.assertValueType)("boolean"), + default: false + }, + key: { + validate: function validate(node, key, val) { + var expectedTypes = node.computed ? ["Expression"] : ["Identifier", "StringLiteral", "NumericLiteral"]; + _index2.assertNodeType.apply(undefined, expectedTypes)(node, key, val); + } + }, + value: { + validate: (0, _index2.assertNodeType)("Expression") + }, + shorthand: { + validate: (0, _index2.assertValueType)("boolean"), + default: false + }, + decorators: { + validate: (0, _index2.chain)((0, _index2.assertValueType)("array"), (0, _index2.assertEach)((0, _index2.assertNodeType)("Decorator"))), + optional: true + } + }, + visitor: ["key", "value", "decorators"], + aliases: ["UserWhitespacable", "Property", "ObjectMember"] +}); + +(0, _index3.default)("RestElement", { + visitor: ["argument", "typeAnnotation"], + aliases: ["LVal"], + fields: { + argument: { + validate: (0, _index2.assertNodeType)("LVal") + }, + decorators: { + validate: (0, _index2.chain)((0, _index2.assertValueType)("array"), (0, _index2.assertEach)((0, _index2.assertNodeType)("Decorator"))) + } + } +}); + +(0, _index3.default)("ReturnStatement", { + visitor: ["argument"], + aliases: ["Statement", "Terminatorless", "CompletionStatement"], + fields: { + argument: { + validate: (0, _index2.assertNodeType)("Expression"), + optional: true + } + } +}); + +(0, _index3.default)("SequenceExpression", { + visitor: ["expressions"], + fields: { + expressions: { + validate: (0, _index2.chain)((0, _index2.assertValueType)("array"), (0, _index2.assertEach)((0, _index2.assertNodeType)("Expression"))) + } + }, + aliases: ["Expression"] +}); + +(0, _index3.default)("SwitchCase", { + visitor: ["test", "consequent"], + fields: { + test: { + validate: (0, _index2.assertNodeType)("Expression"), + optional: true + }, + consequent: { + validate: (0, _index2.chain)((0, _index2.assertValueType)("array"), (0, _index2.assertEach)((0, _index2.assertNodeType)("Statement"))) + } + } +}); + +(0, _index3.default)("SwitchStatement", { + visitor: ["discriminant", "cases"], + aliases: ["Statement", "BlockParent", "Scopable"], + fields: { + discriminant: { + validate: (0, _index2.assertNodeType)("Expression") + }, + cases: { + validate: (0, _index2.chain)((0, _index2.assertValueType)("array"), (0, _index2.assertEach)((0, _index2.assertNodeType)("SwitchCase"))) + } + } +}); + +(0, _index3.default)("ThisExpression", { + aliases: ["Expression"] +}); + +(0, _index3.default)("ThrowStatement", { + visitor: ["argument"], + aliases: ["Statement", "Terminatorless", "CompletionStatement"], + fields: { + argument: { + validate: (0, _index2.assertNodeType)("Expression") + } + } +}); + +(0, _index3.default)("TryStatement", { + visitor: ["block", "handler", "finalizer"], + aliases: ["Statement"], + fields: { + body: { + validate: (0, _index2.assertNodeType)("BlockStatement") + }, + handler: { + optional: true, + handler: (0, _index2.assertNodeType)("BlockStatement") + }, + finalizer: { + optional: true, + validate: (0, _index2.assertNodeType)("BlockStatement") + } + } +}); + +(0, _index3.default)("UnaryExpression", { + builder: ["operator", "argument", "prefix"], + fields: { + prefix: { + default: true + }, + argument: { + validate: (0, _index2.assertNodeType)("Expression") + }, + operator: { + validate: _index2.assertOneOf.apply(undefined, _constants.UNARY_OPERATORS) + } + }, + visitor: ["argument"], + aliases: ["UnaryLike", "Expression"] +}); + +(0, _index3.default)("UpdateExpression", { + builder: ["operator", "argument", "prefix"], + fields: { + prefix: { + default: false + }, + argument: { + validate: (0, _index2.assertNodeType)("Expression") + }, + operator: { + validate: _index2.assertOneOf.apply(undefined, _constants.UPDATE_OPERATORS) + } + }, + visitor: ["argument"], + aliases: ["Expression"] +}); + +(0, _index3.default)("VariableDeclaration", { + builder: ["kind", "declarations"], + visitor: ["declarations"], + aliases: ["Statement", "Declaration"], + fields: { + kind: { + validate: (0, _index2.chain)((0, _index2.assertValueType)("string"), (0, _index2.assertOneOf)("var", "let", "const")) + }, + declarations: { + validate: (0, _index2.chain)((0, _index2.assertValueType)("array"), (0, _index2.assertEach)((0, _index2.assertNodeType)("VariableDeclarator"))) + } + } +}); + +(0, _index3.default)("VariableDeclarator", { + visitor: ["id", "init"], + fields: { + id: { + validate: (0, _index2.assertNodeType)("LVal") + }, + init: { + optional: true, + validate: (0, _index2.assertNodeType)("Expression") + } + } +}); + +(0, _index3.default)("WhileStatement", { + visitor: ["test", "body"], + aliases: ["Statement", "BlockParent", "Loop", "While", "Scopable"], + fields: { + test: { + validate: (0, _index2.assertNodeType)("Expression") + }, + body: { + validate: (0, _index2.assertNodeType)("BlockStatement", "Statement") + } + } +}); + +(0, _index3.default)("WithStatement", { + visitor: ["object", "body"], + aliases: ["Statement"], + fields: { + object: { + object: (0, _index2.assertNodeType)("Expression") + }, + body: { + validate: (0, _index2.assertNodeType)("BlockStatement", "Statement") + } + } +}); +},{"../constants":182,"../index":193,"./index":188}],185:[function(require,module,exports){ +"use strict"; + +var _index = require("./index"); + +var _index2 = _interopRequireDefault(_index); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +(0, _index2.default)("AssignmentPattern", { + visitor: ["left", "right"], + aliases: ["Pattern", "LVal"], + fields: { + left: { + validate: (0, _index.assertNodeType)("Identifier") + }, + right: { + validate: (0, _index.assertNodeType)("Expression") + }, + decorators: { + validate: (0, _index.chain)((0, _index.assertValueType)("array"), (0, _index.assertEach)((0, _index.assertNodeType)("Decorator"))) + } + } +}); + +(0, _index2.default)("ArrayPattern", { + visitor: ["elements", "typeAnnotation"], + aliases: ["Pattern", "LVal"], + fields: { + elements: { + validate: (0, _index.chain)((0, _index.assertValueType)("array"), (0, _index.assertEach)((0, _index.assertNodeType)("Expression"))) + }, + decorators: { + validate: (0, _index.chain)((0, _index.assertValueType)("array"), (0, _index.assertEach)((0, _index.assertNodeType)("Decorator"))) + } + } +}); + +(0, _index2.default)("ArrowFunctionExpression", { + builder: ["params", "body", "async"], + visitor: ["params", "body", "returnType", "typeParameters"], + aliases: ["Scopable", "Function", "BlockParent", "FunctionParent", "Expression", "Pureish"], + fields: { + params: { + validate: (0, _index.chain)((0, _index.assertValueType)("array"), (0, _index.assertEach)((0, _index.assertNodeType)("LVal"))) + }, + body: { + validate: (0, _index.assertNodeType)("BlockStatement", "Expression") + }, + async: { + validate: (0, _index.assertValueType)("boolean"), + default: false + } + } +}); + +(0, _index2.default)("ClassBody", { + visitor: ["body"], + fields: { + body: { + validate: (0, _index.chain)((0, _index.assertValueType)("array"), (0, _index.assertEach)((0, _index.assertNodeType)("ClassMethod", "ClassProperty"))) + } + } +}); + +(0, _index2.default)("ClassDeclaration", { + builder: ["id", "superClass", "body", "decorators"], + visitor: ["id", "body", "superClass", "mixins", "typeParameters", "superTypeParameters", "implements", "decorators"], + aliases: ["Scopable", "Class", "Statement", "Declaration", "Pureish"], + fields: { + id: { + validate: (0, _index.assertNodeType)("Identifier") + }, + body: { + validate: (0, _index.assertNodeType)("ClassBody") + }, + superClass: { + optional: true, + validate: (0, _index.assertNodeType)("Expression") + }, + decorators: { + validate: (0, _index.chain)((0, _index.assertValueType)("array"), (0, _index.assertEach)((0, _index.assertNodeType)("Decorator"))) + } + } +}); + +(0, _index2.default)("ClassExpression", { + inherits: "ClassDeclaration", + aliases: ["Scopable", "Class", "Expression", "Pureish"], + fields: { + id: { + optional: true, + validate: (0, _index.assertNodeType)("Identifier") + }, + body: { + validate: (0, _index.assertNodeType)("ClassBody") + }, + superClass: { + optional: true, + validate: (0, _index.assertNodeType)("Expression") + }, + decorators: { + validate: (0, _index.chain)((0, _index.assertValueType)("array"), (0, _index.assertEach)((0, _index.assertNodeType)("Decorator"))) + } + } +}); + +(0, _index2.default)("ExportAllDeclaration", { + visitor: ["source"], + aliases: ["Statement", "Declaration", "ModuleDeclaration", "ExportDeclaration"], + fields: { + source: { + validate: (0, _index.assertNodeType)("StringLiteral") + } + } +}); + +(0, _index2.default)("ExportDefaultDeclaration", { + visitor: ["declaration"], + aliases: ["Statement", "Declaration", "ModuleDeclaration", "ExportDeclaration"], + fields: { + declaration: { + validate: (0, _index.assertNodeType)("FunctionDeclaration", "ClassDeclaration", "Expression") + } + } +}); + +(0, _index2.default)("ExportNamedDeclaration", { + visitor: ["declaration", "specifiers", "source"], + aliases: ["Statement", "Declaration", "ModuleDeclaration", "ExportDeclaration"], + fields: { + declaration: { + validate: (0, _index.assertNodeType)("Declaration"), + optional: true + }, + specifiers: { + validate: (0, _index.chain)((0, _index.assertValueType)("array"), (0, _index.assertEach)((0, _index.assertNodeType)("ExportSpecifier"))) + }, + source: { + validate: (0, _index.assertNodeType)("StringLiteral"), + optional: true + } + } +}); + +(0, _index2.default)("ExportSpecifier", { + visitor: ["local", "exported"], + aliases: ["ModuleSpecifier"], + fields: { + local: { + validate: (0, _index.assertNodeType)("Identifier") + }, + exported: { + validate: (0, _index.assertNodeType)("Identifier") + } + } +}); + +(0, _index2.default)("ForOfStatement", { + visitor: ["left", "right", "body"], + aliases: ["Scopable", "Statement", "For", "BlockParent", "Loop", "ForXStatement"], + fields: { + left: { + validate: (0, _index.assertNodeType)("VariableDeclaration", "LVal") + }, + right: { + validate: (0, _index.assertNodeType)("Expression") + }, + body: { + validate: (0, _index.assertNodeType)("Statement") + } + } +}); + +(0, _index2.default)("ImportDeclaration", { + visitor: ["specifiers", "source"], + aliases: ["Statement", "Declaration", "ModuleDeclaration"], + fields: { + specifiers: { + validate: (0, _index.chain)((0, _index.assertValueType)("array"), (0, _index.assertEach)((0, _index.assertNodeType)("ImportSpecifier", "ImportDefaultSpecifier", "ImportNamespaceSpecifier"))) + }, + source: { + validate: (0, _index.assertNodeType)("StringLiteral") + } + } +}); + +(0, _index2.default)("ImportDefaultSpecifier", { + visitor: ["local"], + aliases: ["ModuleSpecifier"], + fields: { + local: { + validate: (0, _index.assertNodeType)("Identifier") + } + } +}); + +(0, _index2.default)("ImportNamespaceSpecifier", { + visitor: ["local"], + aliases: ["ModuleSpecifier"], + fields: { + local: { + validate: (0, _index.assertNodeType)("Identifier") + } + } +}); + +(0, _index2.default)("ImportSpecifier", { + visitor: ["local", "imported"], + aliases: ["ModuleSpecifier"], + fields: { + local: { + validate: (0, _index.assertNodeType)("Identifier") + }, + imported: { + validate: (0, _index.assertNodeType)("Identifier") + } + } +}); + +(0, _index2.default)("MetaProperty", { + visitor: ["meta", "property"], + aliases: ["Expression"], + fields: { + meta: { + validate: (0, _index.assertValueType)("string") + }, + property: { + validate: (0, _index.assertValueType)("string") + } + } +}); + +(0, _index2.default)("ClassMethod", { + aliases: ["Function", "Scopable", "BlockParent", "FunctionParent", "Method"], + builder: ["kind", "key", "params", "body", "computed", "static"], + visitor: ["key", "params", "body", "decorators", "returnType", "typeParameters"], + fields: { + kind: { + validate: (0, _index.chain)((0, _index.assertValueType)("string"), (0, _index.assertOneOf)("get", "set", "method", "constructor")), + default: "method" + }, + computed: { + default: false, + validate: (0, _index.assertValueType)("boolean") + }, + static: { + default: false, + validate: (0, _index.assertValueType)("boolean") + }, + key: { + validate: function validate(node, key, val) { + var expectedTypes = node.computed ? ["Expression"] : ["Identifier", "StringLiteral", "NumericLiteral"]; + _index.assertNodeType.apply(undefined, expectedTypes)(node, key, val); + } + }, + params: { + validate: (0, _index.chain)((0, _index.assertValueType)("array"), (0, _index.assertEach)((0, _index.assertNodeType)("LVal"))) + }, + body: { + validate: (0, _index.assertNodeType)("BlockStatement") + }, + generator: { + default: false, + validate: (0, _index.assertValueType)("boolean") + }, + async: { + default: false, + validate: (0, _index.assertValueType)("boolean") + } + } +}); + +(0, _index2.default)("ObjectPattern", { + visitor: ["properties", "typeAnnotation"], + aliases: ["Pattern", "LVal"], + fields: { + properties: { + validate: (0, _index.chain)((0, _index.assertValueType)("array"), (0, _index.assertEach)((0, _index.assertNodeType)("RestProperty", "Property"))) + }, + decorators: { + validate: (0, _index.chain)((0, _index.assertValueType)("array"), (0, _index.assertEach)((0, _index.assertNodeType)("Decorator"))) + } + } +}); + +(0, _index2.default)("SpreadElement", { + visitor: ["argument"], + aliases: ["UnaryLike"], + fields: { + argument: { + validate: (0, _index.assertNodeType)("Expression") + } + } +}); + +(0, _index2.default)("Super", { + aliases: ["Expression"] +}); + +(0, _index2.default)("TaggedTemplateExpression", { + visitor: ["tag", "quasi"], + aliases: ["Expression"], + fields: { + tag: { + validate: (0, _index.assertNodeType)("Expression") + }, + quasi: { + validate: (0, _index.assertNodeType)("TemplateLiteral") + } + } +}); + +(0, _index2.default)("TemplateElement", { + builder: ["value", "tail"], + fields: { + value: {}, + tail: { + validate: (0, _index.assertValueType)("boolean"), + default: false + } + } +}); + +(0, _index2.default)("TemplateLiteral", { + visitor: ["quasis", "expressions"], + aliases: ["Expression", "Literal"], + fields: { + quasis: { + validate: (0, _index.chain)((0, _index.assertValueType)("array"), (0, _index.assertEach)((0, _index.assertNodeType)("TemplateElement"))) + }, + expressions: { + validate: (0, _index.chain)((0, _index.assertValueType)("array"), (0, _index.assertEach)((0, _index.assertNodeType)("Expression"))) + } + } +}); + +(0, _index2.default)("YieldExpression", { + builder: ["argument", "delegate"], + visitor: ["argument"], + aliases: ["Expression", "Terminatorless"], + fields: { + delegate: { + validate: (0, _index.assertValueType)("boolean"), + default: false + }, + argument: { + optional: true, + validate: (0, _index.assertNodeType)("Expression") + } + } +}); +},{"./index":188}],186:[function(require,module,exports){ +"use strict"; + +var _index = require("./index"); + +var _index2 = _interopRequireDefault(_index); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +(0, _index2.default)("AwaitExpression", { + builder: ["argument"], + visitor: ["argument"], + aliases: ["Expression", "Terminatorless"], + fields: { + argument: { + validate: (0, _index.assertNodeType)("Expression") + } + } +}); + +(0, _index2.default)("ForAwaitStatement", { + visitor: ["left", "right", "body"], + aliases: ["Scopable", "Statement", "For", "BlockParent", "Loop", "ForXStatement"], + fields: { + left: { + validate: (0, _index.assertNodeType)("VariableDeclaration", "LVal") + }, + right: { + validate: (0, _index.assertNodeType)("Expression") + }, + body: { + validate: (0, _index.assertNodeType)("Statement") + } + } +}); + +(0, _index2.default)("BindExpression", { + visitor: ["object", "callee"], + aliases: ["Expression"], + fields: {} +}); + +(0, _index2.default)("Decorator", { + visitor: ["expression"], + fields: { + expression: { + validate: (0, _index.assertNodeType)("Expression") + } + } +}); + +(0, _index2.default)("DoExpression", { + visitor: ["body"], + aliases: ["Expression"], + fields: { + body: { + validate: (0, _index.assertNodeType)("BlockStatement") + } + } +}); + +(0, _index2.default)("ExportDefaultSpecifier", { + visitor: ["exported"], + aliases: ["ModuleSpecifier"], + fields: { + exported: { + validate: (0, _index.assertNodeType)("Identifier") + } + } +}); + +(0, _index2.default)("ExportNamespaceSpecifier", { + visitor: ["exported"], + aliases: ["ModuleSpecifier"], + fields: { + exported: { + validate: (0, _index.assertNodeType)("Identifier") + } + } +}); + +(0, _index2.default)("RestProperty", { + visitor: ["argument"], + aliases: ["UnaryLike"], + fields: { + argument: { + validate: (0, _index.assertNodeType)("LVal") + } + } +}); + +(0, _index2.default)("SpreadProperty", { + visitor: ["argument"], + aliases: ["UnaryLike"], + fields: { + argument: { + validate: (0, _index.assertNodeType)("Expression") + } + } +}); +},{"./index":188}],187:[function(require,module,exports){ +"use strict"; + +var _index = require("./index"); + +var _index2 = _interopRequireDefault(_index); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +(0, _index2.default)("AnyTypeAnnotation", { + aliases: ["Flow", "FlowBaseAnnotation"], + fields: {} +}); + +(0, _index2.default)("ArrayTypeAnnotation", { + visitor: ["elementType"], + aliases: ["Flow"], + fields: {} +}); + +(0, _index2.default)("BooleanTypeAnnotation", { + aliases: ["Flow", "FlowBaseAnnotation"], + fields: {} +}); + +(0, _index2.default)("BooleanLiteralTypeAnnotation", { + aliases: ["Flow"], + fields: {} +}); + +(0, _index2.default)("NullLiteralTypeAnnotation", { + aliases: ["Flow", "FlowBaseAnnotation"], + fields: {} +}); + +(0, _index2.default)("ClassImplements", { + visitor: ["id", "typeParameters"], + aliases: ["Flow"], + fields: {} +}); + +(0, _index2.default)("ClassProperty", { + visitor: ["key", "value", "typeAnnotation", "decorators"], + builder: ["key", "value", "typeAnnotation", "decorators", "computed"], + aliases: ["Property"], + fields: { + computed: { + validate: (0, _index.assertValueType)("boolean"), + default: false + } + } +}); + +(0, _index2.default)("DeclareClass", { + visitor: ["id", "typeParameters", "extends", "body"], + aliases: ["Flow", "FlowDeclaration", "Statement", "Declaration"], + fields: {} +}); + +(0, _index2.default)("DeclareFunction", { + visitor: ["id"], + aliases: ["Flow", "FlowDeclaration", "Statement", "Declaration"], + fields: {} +}); + +(0, _index2.default)("DeclareInterface", { + visitor: ["id", "typeParameters", "extends", "body"], + aliases: ["Flow", "FlowDeclaration", "Statement", "Declaration"], + fields: {} +}); + +(0, _index2.default)("DeclareModule", { + visitor: ["id", "body"], + aliases: ["Flow", "FlowDeclaration", "Statement", "Declaration"], + fields: {} +}); + +(0, _index2.default)("DeclareModuleExports", { + visitor: ["typeAnnotation"], + aliases: ["Flow", "FlowDeclaration", "Statement", "Declaration"], + fields: {} +}); + +(0, _index2.default)("DeclareTypeAlias", { + visitor: ["id", "typeParameters", "right"], + aliases: ["Flow", "FlowDeclaration", "Statement", "Declaration"], + fields: {} +}); + +(0, _index2.default)("DeclareVariable", { + visitor: ["id"], + aliases: ["Flow", "FlowDeclaration", "Statement", "Declaration"], + fields: {} +}); + +(0, _index2.default)("ExistentialTypeParam", { + aliases: ["Flow"] +}); + +(0, _index2.default)("FunctionTypeAnnotation", { + visitor: ["typeParameters", "params", "rest", "returnType"], + aliases: ["Flow"], + fields: {} +}); + +(0, _index2.default)("FunctionTypeParam", { + visitor: ["name", "typeAnnotation"], + aliases: ["Flow"], + fields: {} +}); + +(0, _index2.default)("GenericTypeAnnotation", { + visitor: ["id", "typeParameters"], + aliases: ["Flow"], + fields: {} +}); + +(0, _index2.default)("InterfaceExtends", { + visitor: ["id", "typeParameters"], + aliases: ["Flow"], + fields: {} +}); + +(0, _index2.default)("InterfaceDeclaration", { + visitor: ["id", "typeParameters", "extends", "body"], + aliases: ["Flow", "FlowDeclaration", "Statement", "Declaration"], + fields: {} +}); + +(0, _index2.default)("IntersectionTypeAnnotation", { + visitor: ["types"], + aliases: ["Flow"], + fields: {} +}); + +(0, _index2.default)("MixedTypeAnnotation", { + aliases: ["Flow", "FlowBaseAnnotation"] +}); + +(0, _index2.default)("NullableTypeAnnotation", { + visitor: ["typeAnnotation"], + aliases: ["Flow"], + fields: {} +}); + +(0, _index2.default)("NumericLiteralTypeAnnotation", { + aliases: ["Flow"], + fields: {} +}); + +(0, _index2.default)("NumberTypeAnnotation", { + aliases: ["Flow", "FlowBaseAnnotation"], + fields: {} +}); + +(0, _index2.default)("StringLiteralTypeAnnotation", { + aliases: ["Flow"], + fields: {} +}); + +(0, _index2.default)("StringTypeAnnotation", { + aliases: ["Flow", "FlowBaseAnnotation"], + fields: {} +}); + +(0, _index2.default)("ThisTypeAnnotation", { + aliases: ["Flow", "FlowBaseAnnotation"], + fields: {} +}); + +(0, _index2.default)("TupleTypeAnnotation", { + visitor: ["types"], + aliases: ["Flow"], + fields: {} +}); + +(0, _index2.default)("TypeofTypeAnnotation", { + visitor: ["argument"], + aliases: ["Flow"], + fields: {} +}); + +(0, _index2.default)("TypeAlias", { + visitor: ["id", "typeParameters", "right"], + aliases: ["Flow", "FlowDeclaration", "Statement", "Declaration"], + fields: {} +}); + +(0, _index2.default)("TypeAnnotation", { + visitor: ["typeAnnotation"], + aliases: ["Flow"], + fields: {} +}); + +(0, _index2.default)("TypeCastExpression", { + visitor: ["expression", "typeAnnotation"], + aliases: ["Flow", "ExpressionWrapper", "Expression"], + fields: {} +}); + +(0, _index2.default)("TypeParameter", { + visitor: ["bound"], + aliases: ["Flow"], + fields: {} +}); + +(0, _index2.default)("TypeParameterDeclaration", { + visitor: ["params"], + aliases: ["Flow"], + fields: {} +}); + +(0, _index2.default)("TypeParameterInstantiation", { + visitor: ["params"], + aliases: ["Flow"], + fields: {} +}); + +(0, _index2.default)("ObjectTypeAnnotation", { + visitor: ["properties", "indexers", "callProperties"], + aliases: ["Flow"], + fields: {} +}); + +(0, _index2.default)("ObjectTypeCallProperty", { + visitor: ["value"], + aliases: ["Flow", "UserWhitespacable"], + fields: {} +}); + +(0, _index2.default)("ObjectTypeIndexer", { + visitor: ["id", "key", "value"], + aliases: ["Flow", "UserWhitespacable"], + fields: {} +}); + +(0, _index2.default)("ObjectTypeProperty", { + visitor: ["key", "value"], + aliases: ["Flow", "UserWhitespacable"], + fields: {} +}); + +(0, _index2.default)("QualifiedTypeIdentifier", { + visitor: ["id", "qualification"], + aliases: ["Flow"], + fields: {} +}); + +(0, _index2.default)("UnionTypeAnnotation", { + visitor: ["types"], + aliases: ["Flow"], + fields: {} +}); + +(0, _index2.default)("VoidTypeAnnotation", { + aliases: ["Flow", "FlowBaseAnnotation"], + fields: {} +}); +},{"./index":188}],188:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; +exports.DEPRECATED_KEYS = exports.BUILDER_KEYS = exports.NODE_FIELDS = exports.ALIAS_KEYS = exports.VISITOR_KEYS = undefined; + +var _getIterator2 = require("babel-runtime/core-js/get-iterator"); + +var _getIterator3 = _interopRequireDefault(_getIterator2); + +var _stringify = require("babel-runtime/core-js/json/stringify"); + +var _stringify2 = _interopRequireDefault(_stringify); + +var _typeof2 = require("babel-runtime/helpers/typeof"); + +var _typeof3 = _interopRequireDefault(_typeof2); + +exports.assertEach = assertEach; +exports.assertOneOf = assertOneOf; +exports.assertNodeType = assertNodeType; +exports.assertNodeOrValueType = assertNodeOrValueType; +exports.assertValueType = assertValueType; +exports.chain = chain; +exports.default = defineType; + +var _index = require("../index"); + +var t = _interopRequireWildcard(_index); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var VISITOR_KEYS = exports.VISITOR_KEYS = {}; +var ALIAS_KEYS = exports.ALIAS_KEYS = {}; +var NODE_FIELDS = exports.NODE_FIELDS = {}; +var BUILDER_KEYS = exports.BUILDER_KEYS = {}; +var DEPRECATED_KEYS = exports.DEPRECATED_KEYS = {}; + +function getType(val) { + if (Array.isArray(val)) { + return "array"; + } else if (val === null) { + return "null"; + } else if (val === undefined) { + return "undefined"; + } else { + return typeof val === "undefined" ? "undefined" : (0, _typeof3.default)(val); + } +} + +function assertEach(callback) { + function validator(node, key, val) { + if (!Array.isArray(val)) return; + + for (var i = 0; i < val.length; i++) { + callback(node, key + "[" + i + "]", val[i]); + } + } + validator.each = callback; + return validator; +} + +function assertOneOf() { + for (var _len = arguments.length, vals = Array(_len), _key = 0; _key < _len; _key++) { + vals[_key] = arguments[_key]; + } + + function validate(node, key, val) { + if (vals.indexOf(val) < 0) { + throw new TypeError("Property " + key + " expected value to be one of " + (0, _stringify2.default)(vals) + " but got " + (0, _stringify2.default)(val)); + } + } + + validate.oneOf = vals; + + return validate; +} + +function assertNodeType() { + for (var _len2 = arguments.length, types = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { + types[_key2] = arguments[_key2]; + } + + function validate(node, key, val) { + var valid = false; + + for (var _iterator = types, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_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 type = _ref; + + if (t.is(type, val)) { + valid = true; + break; + } + } + + if (!valid) { + throw new TypeError("Property " + key + " of " + node.type + " expected node to be of a type " + (0, _stringify2.default)(types) + " " + ("but instead got " + (0, _stringify2.default)(val && val.type))); + } + } + + validate.oneOfNodeTypes = types; + + return validate; +} + +function assertNodeOrValueType() { + for (var _len3 = arguments.length, types = Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { + types[_key3] = arguments[_key3]; + } + + function validate(node, key, val) { + var valid = false; + + for (var _iterator2 = types, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : (0, _getIterator3.default)(_iterator2);;) { + var _ref2; + + if (_isArray2) { + if (_i2 >= _iterator2.length) break; + _ref2 = _iterator2[_i2++]; + } else { + _i2 = _iterator2.next(); + if (_i2.done) break; + _ref2 = _i2.value; + } + + var type = _ref2; + + if (getType(val) === type || t.is(type, val)) { + valid = true; + break; + } + } + + if (!valid) { + throw new TypeError("Property " + key + " of " + node.type + " expected node to be of a type " + (0, _stringify2.default)(types) + " " + ("but instead got " + (0, _stringify2.default)(val && val.type))); + } + } + + validate.oneOfNodeOrValueTypes = types; + + return validate; +} + +function assertValueType(type) { + function validate(node, key, val) { + var valid = getType(val) === type; + + if (!valid) { + throw new TypeError("Property " + key + " expected type of " + type + " but got " + getType(val)); + } + } + + validate.type = type; + + return validate; +} + +function chain() { + for (var _len4 = arguments.length, fns = Array(_len4), _key4 = 0; _key4 < _len4; _key4++) { + fns[_key4] = arguments[_key4]; + } + + function validate() { + for (var _iterator3 = fns, _isArray3 = Array.isArray(_iterator3), _i3 = 0, _iterator3 = _isArray3 ? _iterator3 : (0, _getIterator3.default)(_iterator3);;) { + var _ref3; + + if (_isArray3) { + if (_i3 >= _iterator3.length) break; + _ref3 = _iterator3[_i3++]; + } else { + _i3 = _iterator3.next(); + if (_i3.done) break; + _ref3 = _i3.value; + } + + var fn = _ref3; + + fn.apply(undefined, arguments); + } + } + validate.chainOf = fns; + return validate; +} + +function defineType(type) { + var opts = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; + + var inherits = opts.inherits && store[opts.inherits] || {}; + + opts.fields = opts.fields || inherits.fields || {}; + opts.visitor = opts.visitor || inherits.visitor || []; + opts.aliases = opts.aliases || inherits.aliases || []; + opts.builder = opts.builder || inherits.builder || opts.visitor || []; + + if (opts.deprecatedAlias) { + DEPRECATED_KEYS[opts.deprecatedAlias] = type; + } + + for (var _iterator4 = opts.visitor.concat(opts.builder), _isArray4 = Array.isArray(_iterator4), _i4 = 0, _iterator4 = _isArray4 ? _iterator4 : (0, _getIterator3.default)(_iterator4);;) { + var _ref4; + + if (_isArray4) { + if (_i4 >= _iterator4.length) break; + _ref4 = _iterator4[_i4++]; + } else { + _i4 = _iterator4.next(); + if (_i4.done) break; + _ref4 = _i4.value; + } + + var _key5 = _ref4; + + opts.fields[_key5] = opts.fields[_key5] || {}; + } + + for (var key in opts.fields) { + var field = opts.fields[key]; + + if (opts.builder.indexOf(key) === -1) { + field.optional = true; + } + if (field.default === undefined) { + field.default = null; + } else if (!field.validate) { + field.validate = assertValueType(getType(field.default)); + } + } + + VISITOR_KEYS[type] = opts.visitor; + BUILDER_KEYS[type] = opts.builder; + NODE_FIELDS[type] = opts.fields; + ALIAS_KEYS[type] = opts.aliases; + + store[type] = opts; +} + +var store = {}; +},{"../index":193,"babel-runtime/core-js/get-iterator":138,"babel-runtime/core-js/json/stringify":139,"babel-runtime/helpers/typeof":155}],189:[function(require,module,exports){ +"use strict"; + +require("./index"); + +require("./core"); + +require("./es2015"); + +require("./flow"); + +require("./jsx"); + +require("./misc"); + +require("./experimental"); +},{"./core":184,"./es2015":185,"./experimental":186,"./flow":187,"./index":188,"./jsx":190,"./misc":191}],190:[function(require,module,exports){ +"use strict"; + +var _index = require("./index"); + +var _index2 = _interopRequireDefault(_index); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +(0, _index2.default)("JSXAttribute", { + visitor: ["name", "value"], + aliases: ["JSX", "Immutable"], + fields: { + name: { + validate: (0, _index.assertNodeType)("JSXIdentifier", "JSXNamespacedName") + }, + value: { + optional: true, + validate: (0, _index.assertNodeType)("JSXElement", "StringLiteral", "JSXExpressionContainer") + } + } +}); + +(0, _index2.default)("JSXClosingElement", { + visitor: ["name"], + aliases: ["JSX", "Immutable"], + fields: { + name: { + validate: (0, _index.assertNodeType)("JSXIdentifier", "JSXMemberExpression") + } + } +}); + +(0, _index2.default)("JSXElement", { + builder: ["openingElement", "closingElement", "children", "selfClosing"], + visitor: ["openingElement", "children", "closingElement"], + aliases: ["JSX", "Immutable", "Expression"], + fields: { + openingElement: { + validate: (0, _index.assertNodeType)("JSXOpeningElement") + }, + closingElement: { + optional: true, + validate: (0, _index.assertNodeType)("JSXClosingElement") + }, + children: { + validate: (0, _index.chain)((0, _index.assertValueType)("array"), (0, _index.assertEach)((0, _index.assertNodeType)("JSXText", "JSXExpressionContainer", "JSXElement"))) + } + } +}); + +(0, _index2.default)("JSXEmptyExpression", { + aliases: ["JSX", "Expression"] +}); + +(0, _index2.default)("JSXExpressionContainer", { + visitor: ["expression"], + aliases: ["JSX", "Immutable"], + fields: { + expression: { + validate: (0, _index.assertNodeType)("Expression") + } + } +}); + +(0, _index2.default)("JSXIdentifier", { + builder: ["name"], + aliases: ["JSX", "Expression"], + fields: { + name: { + validate: (0, _index.assertValueType)("string") + } + } +}); + +(0, _index2.default)("JSXMemberExpression", { + visitor: ["object", "property"], + aliases: ["JSX", "Expression"], + fields: { + object: { + validate: (0, _index.assertNodeType)("JSXMemberExpression", "JSXIdentifier") + }, + property: { + validate: (0, _index.assertNodeType)("JSXIdentifier") + } + } +}); + +(0, _index2.default)("JSXNamespacedName", { + visitor: ["namespace", "name"], + aliases: ["JSX"], + fields: { + namespace: { + validate: (0, _index.assertNodeType)("JSXIdentifier") + }, + name: { + validate: (0, _index.assertNodeType)("JSXIdentifier") + } + } +}); + +(0, _index2.default)("JSXOpeningElement", { + builder: ["name", "attributes", "selfClosing"], + visitor: ["name", "attributes"], + aliases: ["JSX", "Immutable"], + fields: { + name: { + validate: (0, _index.assertNodeType)("JSXIdentifier", "JSXMemberExpression") + }, + selfClosing: { + default: false, + validate: (0, _index.assertValueType)("boolean") + }, + attributes: { + validate: (0, _index.chain)((0, _index.assertValueType)("array"), (0, _index.assertEach)((0, _index.assertNodeType)("JSXAttribute", "JSXSpreadAttribute"))) + } + } +}); + +(0, _index2.default)("JSXSpreadAttribute", { + visitor: ["argument"], + aliases: ["JSX"], + fields: { + argument: { + validate: (0, _index.assertNodeType)("Expression") + } + } +}); + +(0, _index2.default)("JSXText", { + aliases: ["JSX", "Immutable"], + builder: ["value"], + fields: { + value: { + validate: (0, _index.assertValueType)("string") + } + } +}); +},{"./index":188}],191:[function(require,module,exports){ +"use strict"; + +var _index = require("./index"); + +var _index2 = _interopRequireDefault(_index); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +(0, _index2.default)("Noop", { + visitor: [] +}); + +(0, _index2.default)("ParenthesizedExpression", { + visitor: ["expression"], + aliases: ["Expression", "ExpressionWrapper"], + fields: { + expression: { + validate: (0, _index.assertNodeType)("Expression") + } + } +}); +},{"./index":188}],192:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; +exports.createUnionTypeAnnotation = createUnionTypeAnnotation; +exports.removeTypeDuplicates = removeTypeDuplicates; +exports.createTypeAnnotationBasedOnTypeof = createTypeAnnotationBasedOnTypeof; + +var _index = require("./index"); + +var t = _interopRequireWildcard(_index); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function createUnionTypeAnnotation(types) { + var flattened = removeTypeDuplicates(types); + + if (flattened.length === 1) { + return flattened[0]; + } else { + return t.unionTypeAnnotation(flattened); + } +} + +function removeTypeDuplicates(nodes) { + var generics = {}; + var bases = {}; + + var typeGroups = []; + + var types = []; + + for (var i = 0; i < nodes.length; i++) { + var node = nodes[i]; + if (!node) continue; + + if (types.indexOf(node) >= 0) { + continue; + } + + if (t.isAnyTypeAnnotation(node)) { + return [node]; + } + + if (t.isFlowBaseAnnotation(node)) { + bases[node.type] = node; + continue; + } + + if (t.isUnionTypeAnnotation(node)) { + if (typeGroups.indexOf(node.types) < 0) { + nodes = nodes.concat(node.types); + typeGroups.push(node.types); + } + continue; + } + + if (t.isGenericTypeAnnotation(node)) { + var name = node.id.name; + + if (generics[name]) { + var existing = generics[name]; + if (existing.typeParameters) { + if (node.typeParameters) { + existing.typeParameters.params = removeTypeDuplicates(existing.typeParameters.params.concat(node.typeParameters.params)); + } + } else { + existing = node.typeParameters; + } + } else { + generics[name] = node; + } + + continue; + } + + types.push(node); + } + + for (var type in bases) { + types.push(bases[type]); + } + + for (var _name in generics) { + types.push(generics[_name]); + } + + return types; +} + +function createTypeAnnotationBasedOnTypeof(type) { + if (type === "string") { + return t.stringTypeAnnotation(); + } else if (type === "number") { + return t.numberTypeAnnotation(); + } else if (type === "undefined") { + return t.voidTypeAnnotation(); + } else if (type === "boolean") { + return t.booleanTypeAnnotation(); + } else if (type === "function") { + return t.genericTypeAnnotation(t.identifier("Function")); + } else if (type === "object") { + return t.genericTypeAnnotation(t.identifier("Object")); + } else if (type === "symbol") { + return t.genericTypeAnnotation(t.identifier("Symbol")); + } else { + throw new Error("Invalid typeof value"); + } +} +},{"./index":193}],193:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; +exports.createTypeAnnotationBasedOnTypeof = exports.removeTypeDuplicates = exports.createUnionTypeAnnotation = exports.valueToNode = exports.toBlock = exports.toExpression = exports.toStatement = exports.toBindingIdentifierName = exports.toIdentifier = exports.toKeyAlias = exports.toSequenceExpression = exports.toComputedKey = exports.isImmutable = exports.isScope = exports.isSpecifierDefault = exports.isVar = exports.isBlockScoped = exports.isLet = exports.isValidIdentifier = exports.isReferenced = exports.isBinding = exports.getOuterBindingIdentifiers = exports.getBindingIdentifiers = exports.TYPES = exports.react = exports.DEPRECATED_KEYS = exports.BUILDER_KEYS = exports.NODE_FIELDS = exports.ALIAS_KEYS = exports.VISITOR_KEYS = exports.NOT_LOCAL_BINDING = exports.BLOCK_SCOPED_SYMBOL = exports.INHERIT_KEYS = exports.UNARY_OPERATORS = exports.STRING_UNARY_OPERATORS = exports.NUMBER_UNARY_OPERATORS = exports.BOOLEAN_UNARY_OPERATORS = exports.BINARY_OPERATORS = exports.NUMBER_BINARY_OPERATORS = exports.BOOLEAN_BINARY_OPERATORS = exports.COMPARISON_BINARY_OPERATORS = exports.EQUALITY_BINARY_OPERATORS = exports.BOOLEAN_NUMBER_BINARY_OPERATORS = exports.UPDATE_OPERATORS = exports.LOGICAL_OPERATORS = exports.COMMENT_KEYS = exports.FOR_INIT_KEYS = exports.FLATTENABLE_KEYS = exports.STATEMENT_OR_BLOCK_KEYS = undefined; + +var _getOwnPropertySymbols = require("babel-runtime/core-js/object/get-own-property-symbols"); + +var _getOwnPropertySymbols2 = _interopRequireDefault(_getOwnPropertySymbols); + +var _getIterator2 = require("babel-runtime/core-js/get-iterator"); + +var _getIterator3 = _interopRequireDefault(_getIterator2); + +var _keys = require("babel-runtime/core-js/object/keys"); + +var _keys2 = _interopRequireDefault(_keys); + +var _stringify = require("babel-runtime/core-js/json/stringify"); + +var _stringify2 = _interopRequireDefault(_stringify); + +var _constants = require("./constants"); + +Object.defineProperty(exports, "STATEMENT_OR_BLOCK_KEYS", { + enumerable: true, + get: function get() { + return _constants.STATEMENT_OR_BLOCK_KEYS; + } +}); +Object.defineProperty(exports, "FLATTENABLE_KEYS", { + enumerable: true, + get: function get() { + return _constants.FLATTENABLE_KEYS; + } +}); +Object.defineProperty(exports, "FOR_INIT_KEYS", { + enumerable: true, + get: function get() { + return _constants.FOR_INIT_KEYS; + } +}); +Object.defineProperty(exports, "COMMENT_KEYS", { + enumerable: true, + get: function get() { + return _constants.COMMENT_KEYS; + } +}); +Object.defineProperty(exports, "LOGICAL_OPERATORS", { + enumerable: true, + get: function get() { + return _constants.LOGICAL_OPERATORS; + } +}); +Object.defineProperty(exports, "UPDATE_OPERATORS", { + enumerable: true, + get: function get() { + return _constants.UPDATE_OPERATORS; + } +}); +Object.defineProperty(exports, "BOOLEAN_NUMBER_BINARY_OPERATORS", { + enumerable: true, + get: function get() { + return _constants.BOOLEAN_NUMBER_BINARY_OPERATORS; + } +}); +Object.defineProperty(exports, "EQUALITY_BINARY_OPERATORS", { + enumerable: true, + get: function get() { + return _constants.EQUALITY_BINARY_OPERATORS; + } +}); +Object.defineProperty(exports, "COMPARISON_BINARY_OPERATORS", { + enumerable: true, + get: function get() { + return _constants.COMPARISON_BINARY_OPERATORS; + } +}); +Object.defineProperty(exports, "BOOLEAN_BINARY_OPERATORS", { + enumerable: true, + get: function get() { + return _constants.BOOLEAN_BINARY_OPERATORS; + } +}); +Object.defineProperty(exports, "NUMBER_BINARY_OPERATORS", { + enumerable: true, + get: function get() { + return _constants.NUMBER_BINARY_OPERATORS; + } +}); +Object.defineProperty(exports, "BINARY_OPERATORS", { + enumerable: true, + get: function get() { + return _constants.BINARY_OPERATORS; + } +}); +Object.defineProperty(exports, "BOOLEAN_UNARY_OPERATORS", { + enumerable: true, + get: function get() { + return _constants.BOOLEAN_UNARY_OPERATORS; + } +}); +Object.defineProperty(exports, "NUMBER_UNARY_OPERATORS", { + enumerable: true, + get: function get() { + return _constants.NUMBER_UNARY_OPERATORS; + } +}); +Object.defineProperty(exports, "STRING_UNARY_OPERATORS", { + enumerable: true, + get: function get() { + return _constants.STRING_UNARY_OPERATORS; + } +}); +Object.defineProperty(exports, "UNARY_OPERATORS", { + enumerable: true, + get: function get() { + return _constants.UNARY_OPERATORS; + } +}); +Object.defineProperty(exports, "INHERIT_KEYS", { + enumerable: true, + get: function get() { + return _constants.INHERIT_KEYS; + } +}); +Object.defineProperty(exports, "BLOCK_SCOPED_SYMBOL", { + enumerable: true, + get: function get() { + return _constants.BLOCK_SCOPED_SYMBOL; + } +}); +Object.defineProperty(exports, "NOT_LOCAL_BINDING", { + enumerable: true, + get: function get() { + return _constants.NOT_LOCAL_BINDING; + } +}); +exports.is = is; +exports.isType = isType; +exports.validate = validate; +exports.shallowEqual = shallowEqual; +exports.appendToMemberExpression = appendToMemberExpression; +exports.prependToMemberExpression = prependToMemberExpression; +exports.ensureBlock = ensureBlock; +exports.clone = clone; +exports.cloneWithoutLoc = cloneWithoutLoc; +exports.cloneDeep = cloneDeep; +exports.buildMatchMemberExpression = buildMatchMemberExpression; +exports.removeComments = removeComments; +exports.inheritsComments = inheritsComments; +exports.inheritTrailingComments = inheritTrailingComments; +exports.inheritLeadingComments = inheritLeadingComments; +exports.inheritInnerComments = inheritInnerComments; +exports.inherits = inherits; +exports.assertNode = assertNode; +exports.isNode = isNode; +exports.traverseFast = traverseFast; +exports.removeProperties = removeProperties; +exports.removePropertiesDeep = removePropertiesDeep; + +var _retrievers = require("./retrievers"); + +Object.defineProperty(exports, "getBindingIdentifiers", { + enumerable: true, + get: function get() { + return _retrievers.getBindingIdentifiers; + } +}); +Object.defineProperty(exports, "getOuterBindingIdentifiers", { + enumerable: true, + get: function get() { + return _retrievers.getOuterBindingIdentifiers; + } +}); + +var _validators = require("./validators"); + +Object.defineProperty(exports, "isBinding", { + enumerable: true, + get: function get() { + return _validators.isBinding; + } +}); +Object.defineProperty(exports, "isReferenced", { + enumerable: true, + get: function get() { + return _validators.isReferenced; + } +}); +Object.defineProperty(exports, "isValidIdentifier", { + enumerable: true, + get: function get() { + return _validators.isValidIdentifier; + } +}); +Object.defineProperty(exports, "isLet", { + enumerable: true, + get: function get() { + return _validators.isLet; + } +}); +Object.defineProperty(exports, "isBlockScoped", { + enumerable: true, + get: function get() { + return _validators.isBlockScoped; + } +}); +Object.defineProperty(exports, "isVar", { + enumerable: true, + get: function get() { + return _validators.isVar; + } +}); +Object.defineProperty(exports, "isSpecifierDefault", { + enumerable: true, + get: function get() { + return _validators.isSpecifierDefault; + } +}); +Object.defineProperty(exports, "isScope", { + enumerable: true, + get: function get() { + return _validators.isScope; + } +}); +Object.defineProperty(exports, "isImmutable", { + enumerable: true, + get: function get() { + return _validators.isImmutable; + } +}); + +var _converters = require("./converters"); + +Object.defineProperty(exports, "toComputedKey", { + enumerable: true, + get: function get() { + return _converters.toComputedKey; + } +}); +Object.defineProperty(exports, "toSequenceExpression", { + enumerable: true, + get: function get() { + return _converters.toSequenceExpression; + } +}); +Object.defineProperty(exports, "toKeyAlias", { + enumerable: true, + get: function get() { + return _converters.toKeyAlias; + } +}); +Object.defineProperty(exports, "toIdentifier", { + enumerable: true, + get: function get() { + return _converters.toIdentifier; + } +}); +Object.defineProperty(exports, "toBindingIdentifierName", { + enumerable: true, + get: function get() { + return _converters.toBindingIdentifierName; + } +}); +Object.defineProperty(exports, "toStatement", { + enumerable: true, + get: function get() { + return _converters.toStatement; + } +}); +Object.defineProperty(exports, "toExpression", { + enumerable: true, + get: function get() { + return _converters.toExpression; + } +}); +Object.defineProperty(exports, "toBlock", { + enumerable: true, + get: function get() { + return _converters.toBlock; + } +}); +Object.defineProperty(exports, "valueToNode", { + enumerable: true, + get: function get() { + return _converters.valueToNode; + } +}); + +var _flow = require("./flow"); + +Object.defineProperty(exports, "createUnionTypeAnnotation", { + enumerable: true, + get: function get() { + return _flow.createUnionTypeAnnotation; + } +}); +Object.defineProperty(exports, "removeTypeDuplicates", { + enumerable: true, + get: function get() { + return _flow.removeTypeDuplicates; + } +}); +Object.defineProperty(exports, "createTypeAnnotationBasedOnTypeof", { + enumerable: true, + get: function get() { + return _flow.createTypeAnnotationBasedOnTypeof; + } +}); + +var _toFastProperties = require("to-fast-properties"); + +var _toFastProperties2 = _interopRequireDefault(_toFastProperties); + +var _compact = require("lodash/compact"); + +var _compact2 = _interopRequireDefault(_compact); + +var _clone = require("lodash/clone"); + +var _clone2 = _interopRequireDefault(_clone); + +var _each = require("lodash/each"); + +var _each2 = _interopRequireDefault(_each); + +var _uniq = require("lodash/uniq"); + +var _uniq2 = _interopRequireDefault(_uniq); + +require("./definitions/init"); + +var _definitions = require("./definitions"); + +var _react2 = require("./react"); + +var _react = _interopRequireWildcard(_react2); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var t = exports; + +function registerType(type) { + var is = t["is" + type]; + if (!is) { + is = t["is" + type] = function (node, opts) { + return t.is(type, node, opts); + }; + } + + t["assert" + type] = function (node, opts) { + opts = opts || {}; + if (!is(node, opts)) { + throw new Error("Expected type " + (0, _stringify2.default)(type) + " with option " + (0, _stringify2.default)(opts)); + } + }; +} + +exports.VISITOR_KEYS = _definitions.VISITOR_KEYS; +exports.ALIAS_KEYS = _definitions.ALIAS_KEYS; +exports.NODE_FIELDS = _definitions.NODE_FIELDS; +exports.BUILDER_KEYS = _definitions.BUILDER_KEYS; +exports.DEPRECATED_KEYS = _definitions.DEPRECATED_KEYS; +exports.react = _react; + + +for (var type in t.VISITOR_KEYS) { + registerType(type); +} + +t.FLIPPED_ALIAS_KEYS = {}; + +(0, _each2.default)(t.ALIAS_KEYS, function (aliases, type) { + (0, _each2.default)(aliases, function (alias) { + var types = t.FLIPPED_ALIAS_KEYS[alias] = t.FLIPPED_ALIAS_KEYS[alias] || []; + types.push(type); + }); +}); + +(0, _each2.default)(t.FLIPPED_ALIAS_KEYS, function (types, type) { + t[type.toUpperCase() + "_TYPES"] = types; + registerType(type); +}); + +var TYPES = exports.TYPES = (0, _keys2.default)(t.VISITOR_KEYS).concat((0, _keys2.default)(t.FLIPPED_ALIAS_KEYS)).concat((0, _keys2.default)(t.DEPRECATED_KEYS)); + +function is(type, node, opts) { + if (!node) return false; + + var matches = isType(node.type, type); + if (!matches) return false; + + if (typeof opts === "undefined") { + return true; + } else { + return t.shallowEqual(node, opts); + } +} + +function isType(nodeType, targetType) { + if (nodeType === targetType) return true; + + if (t.ALIAS_KEYS[targetType]) return false; + + var aliases = t.FLIPPED_ALIAS_KEYS[targetType]; + if (aliases) { + if (aliases[0] === nodeType) return true; + + for (var _iterator = aliases, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_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 alias = _ref; + + if (nodeType === alias) return true; + } + } + + return false; +} + +(0, _each2.default)(t.BUILDER_KEYS, function (keys, type) { + function builder() { + if (arguments.length > keys.length) { + throw new Error("t." + type + ": Too many arguments passed. Received " + arguments.length + " but can receive " + ("no more than " + keys.length)); + } + + var node = {}; + node.type = type; + + var i = 0; + + for (var _iterator2 = keys, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : (0, _getIterator3.default)(_iterator2);;) { + var _ref2; + + if (_isArray2) { + if (_i2 >= _iterator2.length) break; + _ref2 = _iterator2[_i2++]; + } else { + _i2 = _iterator2.next(); + if (_i2.done) break; + _ref2 = _i2.value; + } + + var _key = _ref2; + + var field = t.NODE_FIELDS[type][_key]; + + var arg = arguments[i++]; + if (arg === undefined) arg = (0, _clone2.default)(field.default); + + node[_key] = arg; + } + + for (var key in node) { + validate(node, key, node[key]); + } + + return node; + } + + t[type] = builder; + t[type[0].toLowerCase() + type.slice(1)] = builder; +}); + +var _loop = function _loop(_type) { + var newType = t.DEPRECATED_KEYS[_type]; + + function proxy(fn) { + return function () { + console.trace("The node type " + _type + " has been renamed to " + newType); + return fn.apply(this, arguments); + }; + } + + t[_type] = t[_type[0].toLowerCase() + _type.slice(1)] = proxy(t[newType]); + t["is" + _type] = proxy(t["is" + newType]); + t["assert" + _type] = proxy(t["assert" + newType]); +}; + +for (var _type in t.DEPRECATED_KEYS) { + _loop(_type); +} + +function validate(node, key, val) { + if (!node) return; + + var fields = t.NODE_FIELDS[node.type]; + if (!fields) return; + + var field = fields[key]; + if (!field || !field.validate) return; + if (field.optional && val == null) return; + + field.validate(node, key, val); +} + +function shallowEqual(actual, expected) { + var keys = (0, _keys2.default)(expected); + + for (var _iterator3 = keys, _isArray3 = Array.isArray(_iterator3), _i3 = 0, _iterator3 = _isArray3 ? _iterator3 : (0, _getIterator3.default)(_iterator3);;) { + var _ref3; + + if (_isArray3) { + if (_i3 >= _iterator3.length) break; + _ref3 = _iterator3[_i3++]; + } else { + _i3 = _iterator3.next(); + if (_i3.done) break; + _ref3 = _i3.value; + } + + var key = _ref3; + + if (actual[key] !== expected[key]) { + return false; + } + } + + return true; +} + +function appendToMemberExpression(member, append, computed) { + member.object = t.memberExpression(member.object, member.property, member.computed); + member.property = append; + member.computed = !!computed; + return member; +} + +function prependToMemberExpression(member, prepend) { + member.object = t.memberExpression(prepend, member.object); + return member; +} + +function ensureBlock(node) { + var key = arguments.length <= 1 || arguments[1] === undefined ? "body" : arguments[1]; + + return node[key] = t.toBlock(node[key], node); +} + +function clone(node) { + var newNode = {}; + for (var key in node) { + if (key[0] === "_") continue; + newNode[key] = node[key]; + } + return newNode; +} + +function cloneWithoutLoc(node) { + var newNode = clone(node); + delete newNode.loc; + return newNode; +} + +function cloneDeep(node) { + var newNode = {}; + + for (var key in node) { + if (key[0] === "_") continue; + + var val = node[key]; + + if (val) { + if (val.type) { + val = t.cloneDeep(val); + } else if (Array.isArray(val)) { + val = val.map(t.cloneDeep); + } + } + + newNode[key] = val; + } + + return newNode; +} + +function buildMatchMemberExpression(match, allowPartial) { + var parts = match.split("."); + + return function (member) { + if (!t.isMemberExpression(member)) return false; + + var search = [member]; + var i = 0; + + while (search.length) { + var node = search.shift(); + + if (allowPartial && i === parts.length) { + return true; + } + + if (t.isIdentifier(node)) { + if (parts[i] !== node.name) return false; + } else if (t.isStringLiteral(node)) { + if (parts[i] !== node.value) return false; + } else if (t.isMemberExpression(node)) { + if (node.computed && !t.isStringLiteral(node.property)) { + return false; + } else { + search.push(node.object); + search.push(node.property); + continue; + } + } else { + return false; + } + + if (++i > parts.length) { + return false; + } + } + + return true; + }; +} + +function removeComments(node) { + for (var _iterator4 = t.COMMENT_KEYS, _isArray4 = Array.isArray(_iterator4), _i4 = 0, _iterator4 = _isArray4 ? _iterator4 : (0, _getIterator3.default)(_iterator4);;) { + var _ref4; + + if (_isArray4) { + if (_i4 >= _iterator4.length) break; + _ref4 = _iterator4[_i4++]; + } else { + _i4 = _iterator4.next(); + if (_i4.done) break; + _ref4 = _i4.value; + } + + var key = _ref4; + + delete node[key]; + } + return node; +} + +function inheritsComments(child, parent) { + inheritTrailingComments(child, parent); + inheritLeadingComments(child, parent); + inheritInnerComments(child, parent); + return child; +} + +function inheritTrailingComments(child, parent) { + _inheritComments("trailingComments", child, parent); +} + +function inheritLeadingComments(child, parent) { + _inheritComments("leadingComments", child, parent); +} + +function inheritInnerComments(child, parent) { + _inheritComments("innerComments", child, parent); +} + +function _inheritComments(key, child, parent) { + if (child && parent) { + child[key] = (0, _uniq2.default)((0, _compact2.default)([].concat(child[key], parent[key]))); + } +} + +function inherits(child, parent) { + if (!child || !parent) return child; + + for (var _iterator5 = t.INHERIT_KEYS.optional, _isArray5 = Array.isArray(_iterator5), _i5 = 0, _iterator5 = _isArray5 ? _iterator5 : (0, _getIterator3.default)(_iterator5);;) { + var _ref5; + + if (_isArray5) { + if (_i5 >= _iterator5.length) break; + _ref5 = _iterator5[_i5++]; + } else { + _i5 = _iterator5.next(); + if (_i5.done) break; + _ref5 = _i5.value; + } + + var _key2 = _ref5; + + if (child[_key2] == null) { + child[_key2] = parent[_key2]; + } + } + + for (var key in parent) { + if (key[0] === "_") child[key] = parent[key]; + } + + for (var _iterator6 = t.INHERIT_KEYS.force, _isArray6 = Array.isArray(_iterator6), _i6 = 0, _iterator6 = _isArray6 ? _iterator6 : (0, _getIterator3.default)(_iterator6);;) { + var _ref6; + + if (_isArray6) { + if (_i6 >= _iterator6.length) break; + _ref6 = _iterator6[_i6++]; + } else { + _i6 = _iterator6.next(); + if (_i6.done) break; + _ref6 = _i6.value; + } + + var _key3 = _ref6; + + child[_key3] = parent[_key3]; + } + + t.inheritsComments(child, parent); + + return child; +} + +function assertNode(node) { + if (!isNode(node)) { + throw new TypeError("Not a valid node " + (node && node.type)); + } +} + +function isNode(node) { + return !!(node && _definitions.VISITOR_KEYS[node.type]); +} + +(0, _toFastProperties2.default)(t); +(0, _toFastProperties2.default)(t.VISITOR_KEYS); + +function traverseFast(node, enter, opts) { + if (!node) return; + + var keys = t.VISITOR_KEYS[node.type]; + if (!keys) return; + + opts = opts || {}; + enter(node, opts); + + for (var _iterator7 = keys, _isArray7 = Array.isArray(_iterator7), _i7 = 0, _iterator7 = _isArray7 ? _iterator7 : (0, _getIterator3.default)(_iterator7);;) { + var _ref7; + + if (_isArray7) { + if (_i7 >= _iterator7.length) break; + _ref7 = _iterator7[_i7++]; + } else { + _i7 = _iterator7.next(); + if (_i7.done) break; + _ref7 = _i7.value; + } + + var key = _ref7; + + var subNode = node[key]; + + if (Array.isArray(subNode)) { + for (var _iterator8 = subNode, _isArray8 = Array.isArray(_iterator8), _i8 = 0, _iterator8 = _isArray8 ? _iterator8 : (0, _getIterator3.default)(_iterator8);;) { + var _ref8; + + if (_isArray8) { + if (_i8 >= _iterator8.length) break; + _ref8 = _iterator8[_i8++]; + } else { + _i8 = _iterator8.next(); + if (_i8.done) break; + _ref8 = _i8.value; + } + + var _node = _ref8; + + traverseFast(_node, enter, opts); + } + } else { + traverseFast(subNode, enter, opts); + } + } +} + +var CLEAR_KEYS = ["tokens", "start", "end", "loc", "raw", "rawValue"]; + +var CLEAR_KEYS_PLUS_COMMENTS = t.COMMENT_KEYS.concat(["comments"]).concat(CLEAR_KEYS); + +function removeProperties(node, opts) { + opts = opts || {}; + var map = opts.preserveComments ? CLEAR_KEYS : CLEAR_KEYS_PLUS_COMMENTS; + for (var _iterator9 = map, _isArray9 = Array.isArray(_iterator9), _i9 = 0, _iterator9 = _isArray9 ? _iterator9 : (0, _getIterator3.default)(_iterator9);;) { + var _ref9; + + if (_isArray9) { + if (_i9 >= _iterator9.length) break; + _ref9 = _iterator9[_i9++]; + } else { + _i9 = _iterator9.next(); + if (_i9.done) break; + _ref9 = _i9.value; + } + + var _key4 = _ref9; + + if (node[_key4] != null) node[_key4] = undefined; + } + + for (var key in node) { + if (key[0] === "_" && node[key] != null) node[key] = undefined; + } + + var syms = (0, _getOwnPropertySymbols2.default)(node); + for (var _iterator10 = syms, _isArray10 = Array.isArray(_iterator10), _i10 = 0, _iterator10 = _isArray10 ? _iterator10 : (0, _getIterator3.default)(_iterator10);;) { + var _ref10; + + if (_isArray10) { + if (_i10 >= _iterator10.length) break; + _ref10 = _iterator10[_i10++]; + } else { + _i10 = _iterator10.next(); + if (_i10.done) break; + _ref10 = _i10.value; + } + + var sym = _ref10; + + node[sym] = null; + } +} + +function removePropertiesDeep(tree, opts) { + traverseFast(tree, removeProperties, opts); + return tree; +} +},{"./constants":182,"./converters":183,"./definitions":188,"./definitions/init":189,"./flow":192,"./react":194,"./retrievers":195,"./validators":196,"babel-runtime/core-js/get-iterator":138,"babel-runtime/core-js/json/stringify":139,"babel-runtime/core-js/object/get-own-property-symbols":144,"babel-runtime/core-js/object/keys":145,"lodash/clone":527,"lodash/compact":530,"lodash/each":533,"lodash/uniq":584,"to-fast-properties":687}],194:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; +exports.isReactComponent = undefined; +exports.isCompatTag = isCompatTag; +exports.buildChildren = buildChildren; + +var _index = require("./index"); + +var t = _interopRequireWildcard(_index); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +var isReactComponent = exports.isReactComponent = t.buildMatchMemberExpression("React.Component"); + +function isCompatTag(tagName) { + return !!tagName && /^[a-z]|\-/.test(tagName); +} + +function cleanJSXElementLiteralChild(child, args) { + var lines = child.value.split(/\r\n|\n|\r/); + + var lastNonEmptyLine = 0; + + for (var i = 0; i < lines.length; i++) { + if (lines[i].match(/[^ \t]/)) { + lastNonEmptyLine = i; + } + } + + var str = ""; + + for (var _i = 0; _i < lines.length; _i++) { + var line = lines[_i]; + + var isFirstLine = _i === 0; + var isLastLine = _i === lines.length - 1; + var isLastNonEmptyLine = _i === lastNonEmptyLine; + + var trimmedLine = line.replace(/\t/g, " "); + + if (!isFirstLine) { + trimmedLine = trimmedLine.replace(/^[ ]+/, ""); + } + + if (!isLastLine) { + trimmedLine = trimmedLine.replace(/[ ]+$/, ""); + } + + if (trimmedLine) { + if (!isLastNonEmptyLine) { + trimmedLine += " "; + } + + str += trimmedLine; + } + } + + if (str) args.push(t.stringLiteral(str)); +} + +function buildChildren(node) { + var elems = []; + + for (var i = 0; i < node.children.length; i++) { + var child = node.children[i]; + + if (t.isJSXText(child)) { + cleanJSXElementLiteralChild(child, elems); + continue; + } + + if (t.isJSXExpressionContainer(child)) child = child.expression; + if (t.isJSXEmptyExpression(child)) continue; + + elems.push(child); + } + + return elems; +} +},{"./index":193}],195:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +var _create = require("babel-runtime/core-js/object/create"); + +var _create2 = _interopRequireDefault(_create); + +exports.getBindingIdentifiers = getBindingIdentifiers; +exports.getOuterBindingIdentifiers = getOuterBindingIdentifiers; + +var _index = require("./index"); + +var t = _interopRequireWildcard(_index); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function getBindingIdentifiers(node, duplicates, outerOnly) { + var search = [].concat(node); + var ids = (0, _create2.default)(null); + + while (search.length) { + var id = search.shift(); + if (!id) continue; + + var keys = t.getBindingIdentifiers.keys[id.type]; + + if (t.isIdentifier(id)) { + if (duplicates) { + var _ids = ids[id.name] = ids[id.name] || []; + _ids.push(id); + } else { + ids[id.name] = id; + } + continue; + } + + if (t.isExportDeclaration(id)) { + if (t.isDeclaration(node.declaration)) { + search.push(node.declaration); + } + continue; + } + + if (outerOnly) { + if (t.isFunctionDeclaration(id)) { + search.push(id.id); + continue; + } + + if (t.isFunctionExpression(id)) { + continue; + } + } + + if (keys) { + for (var i = 0; i < keys.length; i++) { + var key = keys[i]; + if (id[key]) { + search = search.concat(id[key]); + } + } + } + } + + return ids; +} + +getBindingIdentifiers.keys = { + DeclareClass: ["id"], + DeclareFunction: ["id"], + DeclareModule: ["id"], + DeclareVariable: ["id"], + InterfaceDeclaration: ["id"], + TypeAlias: ["id"], + + CatchClause: ["param"], + LabeledStatement: ["label"], + UnaryExpression: ["argument"], + AssignmentExpression: ["left"], + + ImportSpecifier: ["local"], + ImportNamespaceSpecifier: ["local"], + ImportDefaultSpecifier: ["local"], + ImportDeclaration: ["specifiers"], + + ExportSpecifier: ["exported"], + ExportNamespaceSpecifier: ["exported"], + ExportDefaultSpecifier: ["exported"], + + FunctionDeclaration: ["id", "params"], + FunctionExpression: ["id", "params"], + + ClassDeclaration: ["id"], + ClassExpression: ["id"], + + RestElement: ["argument"], + UpdateExpression: ["argument"], + + RestProperty: ["argument"], + ObjectProperty: ["value"], + + AssignmentPattern: ["left"], + ArrayPattern: ["elements"], + ObjectPattern: ["properties"], + + VariableDeclaration: ["declarations"], + VariableDeclarator: ["id"] +}; + +function getOuterBindingIdentifiers(node, duplicates) { + return getBindingIdentifiers(node, duplicates, true); +} +},{"./index":193,"babel-runtime/core-js/object/create":143}],196:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +var _getIterator2 = require("babel-runtime/core-js/get-iterator"); + +var _getIterator3 = _interopRequireDefault(_getIterator2); + +exports.isBinding = isBinding; +exports.isReferenced = isReferenced; +exports.isValidIdentifier = isValidIdentifier; +exports.isLet = isLet; +exports.isBlockScoped = isBlockScoped; +exports.isVar = isVar; +exports.isSpecifierDefault = isSpecifierDefault; +exports.isScope = isScope; +exports.isImmutable = isImmutable; + +var _retrievers = require("./retrievers"); + +var _esutils = require("esutils"); + +var _esutils2 = _interopRequireDefault(_esutils); + +var _index = require("./index"); + +var t = _interopRequireWildcard(_index); + +var _constants = require("./constants"); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function isBinding(node, parent) { + var keys = _retrievers.getBindingIdentifiers.keys[parent.type]; + if (keys) { + for (var i = 0; i < keys.length; i++) { + var key = keys[i]; + var val = parent[key]; + if (Array.isArray(val)) { + if (val.indexOf(node) >= 0) return true; + } else { + if (val === node) return true; + } + } + } + + return false; +} + +function isReferenced(node, parent) { + switch (parent.type) { + case "BindExpression": + return parent.object === node || parent.callee === node; + + case "MemberExpression": + case "JSXMemberExpression": + if (parent.property === node && parent.computed) { + return true; + } else if (parent.object === node) { + return true; + } else { + return false; + } + + case "MetaProperty": + return false; + + case "ObjectProperty": + if (parent.key === node) { + return parent.computed; + } + + case "VariableDeclarator": + return parent.id !== node; + + case "ArrowFunctionExpression": + case "FunctionDeclaration": + case "FunctionExpression": + for (var _iterator = parent.params, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_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 param = _ref; + + if (param === node) return false; + } + + return parent.id !== node; + + case "ExportSpecifier": + if (parent.source) { + return false; + } else { + return parent.local === node; + } + + case "ExportNamespaceSpecifier": + case "ExportDefaultSpecifier": + return false; + + case "JSXAttribute": + return parent.name !== node; + + case "ClassProperty": + if (parent.key === node) { + return parent.computed; + } else { + return parent.value === node; + } + + case "ImportDefaultSpecifier": + case "ImportNamespaceSpecifier": + case "ImportSpecifier": + return false; + + case "ClassDeclaration": + case "ClassExpression": + return parent.id !== node; + + case "ClassMethod": + case "ObjectMethod": + return parent.key === node && parent.computed; + + case "LabeledStatement": + return false; + + case "CatchClause": + return parent.param !== node; + + case "RestElement": + return false; + + case "AssignmentExpression": + return parent.right === node; + + case "AssignmentPattern": + return parent.right === node; + + case "ObjectPattern": + case "ArrayPattern": + return false; + } + + return true; +} + +function isValidIdentifier(name) { + if (typeof name !== "string" || _esutils2.default.keyword.isReservedWordES6(name, true)) { + return false; + } else { + return _esutils2.default.keyword.isIdentifierNameES6(name); + } +} + +function isLet(node) { + return t.isVariableDeclaration(node) && (node.kind !== "var" || node[_constants.BLOCK_SCOPED_SYMBOL]); +} + +function isBlockScoped(node) { + return t.isFunctionDeclaration(node) || t.isClassDeclaration(node) || t.isLet(node); +} + +function isVar(node) { + return t.isVariableDeclaration(node, { kind: "var" }) && !node[_constants.BLOCK_SCOPED_SYMBOL]; +} + +function isSpecifierDefault(specifier) { + return t.isImportDefaultSpecifier(specifier) || t.isIdentifier(specifier.imported || specifier.exported, { name: "default" }); +} + +function isScope(node, parent) { + if (t.isBlockStatement(node) && t.isFunction(parent, { body: node })) { + return false; + } + + return t.isScopable(node); +} + +function isImmutable(node) { + if (t.isType(node.type, "Immutable")) return true; + + if (t.isIdentifier(node)) { + if (node.name === "undefined") { + return true; + } else { + return false; + } + } + + return false; +} +},{"./constants":182,"./index":193,"./retrievers":195,"babel-runtime/core-js/get-iterator":138,"esutils":348}],197:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; +exports.tokTypes = undefined; +exports.parse = parse; + +var _parser = require("./parser"); + +var _parser2 = _interopRequireDefault(_parser); + +require("./parser/util"); + +require("./parser/statement"); + +require("./parser/lval"); + +require("./parser/expression"); + +require("./parser/node"); + +require("./parser/location"); + +require("./parser/comments"); + +var _types = require("./tokenizer/types"); + +require("./tokenizer"); + +require("./tokenizer/context"); + +var _flow = require("./plugins/flow"); + +var _flow2 = _interopRequireDefault(_flow); + +var _jsx = require("./plugins/jsx"); + +var _jsx2 = _interopRequireDefault(_jsx); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +_parser.plugins.flow = _flow2.default; +_parser.plugins.jsx = _jsx2.default; + +function parse(input, options) { + return new _parser2.default(options, input).parse(); +} + +exports.tokTypes = _types.types; +},{"./parser":201,"./parser/comments":199,"./parser/expression":200,"./parser/location":202,"./parser/lval":203,"./parser/node":204,"./parser/statement":205,"./parser/util":206,"./plugins/flow":207,"./plugins/jsx":208,"./tokenizer":211,"./tokenizer/context":210,"./tokenizer/types":213}],198:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; +exports.getOptions = getOptions; +// A second optional argument can be given to further configure +var defaultOptions = exports.defaultOptions = { + // Source type ("script" or "module") for different semantics + sourceType: "script", + // Source filename. + sourceFilename: undefined, + // When enabled, a return at the top level is not considered an + // error. + allowReturnOutsideFunction: false, + // When enabled, import/export statements are not constrained to + // appearing at the top of the program. + allowImportExportEverywhere: false, + // TODO + allowSuperOutsideMethod: false, + // An array of plugins to enable + plugins: [], + // TODO + strictMode: null +}; + +// Interpret and default an options object + +function getOptions(opts) { + var options = {}; + for (var key in defaultOptions) { + options[key] = opts && key in opts ? opts[key] : defaultOptions[key]; + } + return options; +} +},{}],199:[function(require,module,exports){ +"use strict"; + +var _index = require("./index"); + +var _index2 = _interopRequireDefault(_index); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function last(stack) { + return stack[stack.length - 1]; +} /* eslint max-len: 0 */ + +/** + * Based on the comment attachment algorithm used in espree and estraverse. + * + * 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. + * + * 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 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. + */ + +var pp = _index2.default.prototype; + +pp.addComment = function (comment) { + if (this.filename) comment.loc.filename = this.filename; + this.state.trailingComments.push(comment); + this.state.leadingComments.push(comment); +}; + +pp.processComment = function (node) { + if (node.type === "Program" && node.body.length > 0) return; + + var stack = this.state.commentStack; + + var lastChild = void 0, + trailingComments = void 0, + i = void 0, + j = void 0; + + if (this.state.trailingComments.length > 0) { + // If the first comment in trailingComments comes after the + // current node, then we're good - all comments in the array will + // come after the node and so it's safe to add them as official + // trailingComments. + if (this.state.trailingComments[0].start >= node.end) { + trailingComments = this.state.trailingComments; + this.state.trailingComments = []; + } else { + // Otherwise, if the first comment doesn't come after the + // current node, that means we have a mix of leading and trailing + // comments in the array and that leadingComments contains the + // same items as trailingComments. Reset trailingComments to + // zero items and we'll handle this by evaluating leadingComments + // later. + this.state.trailingComments.length = 0; + } + } else { + var lastInStack = last(stack); + if (stack.length > 0 && lastInStack.trailingComments && lastInStack.trailingComments[0].start >= node.end) { + trailingComments = lastInStack.trailingComments; + lastInStack.trailingComments = null; + } + } + + // Eating the stack. + while (stack.length > 0 && last(stack).start >= node.start) { + lastChild = stack.pop(); + } + + if (lastChild) { + if (lastChild.leadingComments) { + if (lastChild !== node && last(lastChild.leadingComments).end <= node.start) { + node.leadingComments = lastChild.leadingComments; + lastChild.leadingComments = null; + } else { + // A leading comment for an anonymous class had been stolen by its first ClassMethod, + // so this takes back the leading comment. + // See also: https://github.com/eslint/espree/issues/158 + for (i = lastChild.leadingComments.length - 2; i >= 0; --i) { + if (lastChild.leadingComments[i].end <= node.start) { + node.leadingComments = lastChild.leadingComments.splice(0, i + 1); + break; + } + } + } + } + } else if (this.state.leadingComments.length > 0) { + if (last(this.state.leadingComments).end <= node.start) { + if (this.state.commentPreviousNode) { + for (j = 0; j < this.state.leadingComments.length; j++) { + if (this.state.leadingComments[j].end < this.state.commentPreviousNode.end) { + this.state.leadingComments.splice(j, 1); + j--; + } + } + } + if (this.state.leadingComments.length > 0) { + node.leadingComments = this.state.leadingComments; + this.state.leadingComments = []; + } + } else { + // https://github.com/eslint/espree/issues/2 + // + // In special cases, such as return (without a value) and + // debugger, all comments will end up as leadingComments and + // will otherwise be eliminated. This step runs when the + // commentStack is empty and there are comments left + // in leadingComments. + // + // This loop figures out the stopping point between the actual + // leading and trailing comments by finding the location of the + // first comment that comes after the given node. + for (i = 0; i < this.state.leadingComments.length; i++) { + if (this.state.leadingComments[i].end > node.start) { + break; + } + } + + // Split the array based on the location of the first comment + // that comes after the node. Keep in mind that this could + // result in an empty array, and if so, the array must be + // deleted. + node.leadingComments = this.state.leadingComments.slice(0, i); + if (node.leadingComments.length === 0) { + node.leadingComments = null; + } + + // Similarly, trailing comments are attached later. The variable + // must be reset to null if there are no trailing comments. + trailingComments = this.state.leadingComments.slice(i); + if (trailingComments.length === 0) { + trailingComments = null; + } + } + } + + this.state.commentPreviousNode = node; + + if (trailingComments) { + if (trailingComments.length && trailingComments[0].start >= node.start && last(trailingComments).end <= node.end) { + node.innerComments = trailingComments; + } else { + node.trailingComments = trailingComments; + } + } + + stack.push(node); +}; +},{"./index":201}],200:[function(require,module,exports){ +"use strict"; + +var _types = require("../tokenizer/types"); + +var _index = require("./index"); + +var _index2 = _interopRequireDefault(_index); + +var _identifier = require("../util/identifier"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var pp = _index2.default.prototype; + +// Check if property name clashes with already added. +// Object/class getters and setters are not allowed to clash — +// either with each other or with an init property — and in +// strict mode, init properties are also not allowed to be repeated. + +/* eslint indent: 0 */ +/* eslint max-len: 0 */ + +// A recursive descent parser operates by defining functions for all +// syntactic elements, and recursively calling those, each function +// advancing the input stream and returning an AST node. Precedence +// of constructs (for example, the fact that `!x[1]` means `!(x[1])` +// instead of `(!x)[1]` is handled by the fact that the parser +// function that parses unary prefix operators is called first, and +// in turn calls the function that parses `[]` subscripts — that +// way, it'll receive the node for `x[1]` already parsed, and wraps +// *that* in the unary operator node. +// +// Acorn uses an [operator precedence parser][opp] to handle binary +// operator precedence, because it is much more compact than using +// the technique outlined above, which uses different, nesting +// functions to specify precedence, for all of the ten binary +// precedence levels that JavaScript defines. +// +// [opp]: http://en.wikipedia.org/wiki/Operator-precedence_parser + +pp.checkPropClash = function (prop, propHash) { + if (prop.computed) return; + + var key = prop.key; + var name = void 0; + switch (key.type) { + case "Identifier": + name = key.name; + break; + + case "StringLiteral": + case "NumericLiteral": + name = String(key.value); + break; + + default: + return; + } + + if (name === "__proto__" && prop.kind === "init") { + if (propHash.proto) this.raise(key.start, "Redefinition of __proto__ property"); + propHash.proto = true; + } +}; + +// ### Expression parsing + +// These nest, from the most general expression type at the top to +// 'atomic', nondivisible expression types at the bottom. Most of +// the functions will simply let the function (s) below them parse, +// and, *if* the syntactic construct they handle is present, wrap +// the AST node that the inner parser gave them in another node. + +// Parse a full expression. The optional arguments are used to +// forbid the `in` operator (in for loops initalization expressions) +// and provide reference for storing '=' operator inside shorthand +// property assignment in contexts where both object expression +// and object pattern might appear (so it's possible to raise +// delayed syntax error at correct position). + +pp.parseExpression = function (noIn, refShorthandDefaultPos) { + var startPos = this.state.start, + startLoc = this.state.startLoc; + var expr = this.parseMaybeAssign(noIn, refShorthandDefaultPos); + if (this.match(_types.types.comma)) { + var node = this.startNodeAt(startPos, startLoc); + node.expressions = [expr]; + while (this.eat(_types.types.comma)) { + node.expressions.push(this.parseMaybeAssign(noIn, refShorthandDefaultPos)); + } + this.toReferencedList(node.expressions); + return this.finishNode(node, "SequenceExpression"); + } + return expr; +}; + +// Parse an assignment expression. This includes applications of +// operators like `+=`. + +pp.parseMaybeAssign = function (noIn, refShorthandDefaultPos, afterLeftParse, refNeedsArrowPos) { + if (this.match(_types.types._yield) && this.state.inGenerator) { + return this.parseYield(); + } + + var failOnShorthandAssign = void 0; + if (refShorthandDefaultPos) { + failOnShorthandAssign = false; + } else { + refShorthandDefaultPos = { start: 0 }; + failOnShorthandAssign = true; + } + + var startPos = this.state.start; + var startLoc = this.state.startLoc; + + if (this.match(_types.types.parenL) || this.match(_types.types.name)) { + this.state.potentialArrowAt = this.state.start; + } + + var left = this.parseMaybeConditional(noIn, refShorthandDefaultPos, refNeedsArrowPos); + if (afterLeftParse) left = afterLeftParse.call(this, left, startPos, startLoc); + if (this.state.type.isAssign) { + var node = this.startNodeAt(startPos, startLoc); + node.operator = this.state.value; + node.left = this.match(_types.types.eq) ? this.toAssignable(left, undefined, "assignment expression") : left; + refShorthandDefaultPos.start = 0; // reset because shorthand default was used correctly + + this.checkLVal(left, undefined, undefined, "assignment expression"); + + if (left.extra && left.extra.parenthesized) { + var errorMsg = void 0; + if (left.type === "ObjectPattern") { + errorMsg = "`({a}) = 0` use `({a} = 0)`"; + } else if (left.type === "ArrayPattern") { + errorMsg = "`([a]) = 0` use `([a] = 0)`"; + } + if (errorMsg) { + this.raise(left.start, "You're trying to assign to a parenthesized expression, eg. instead of " + errorMsg); + } + } + + this.next(); + node.right = this.parseMaybeAssign(noIn); + return this.finishNode(node, "AssignmentExpression"); + } else if (failOnShorthandAssign && refShorthandDefaultPos.start) { + this.unexpected(refShorthandDefaultPos.start); + } + + return left; +}; + +// Parse a ternary conditional (`?:`) operator. + +pp.parseMaybeConditional = function (noIn, refShorthandDefaultPos, refNeedsArrowPos) { + var startPos = this.state.start, + startLoc = this.state.startLoc; + var expr = this.parseExprOps(noIn, refShorthandDefaultPos); + if (refShorthandDefaultPos && refShorthandDefaultPos.start) return expr; + + return this.parseConditional(expr, noIn, startPos, startLoc, refNeedsArrowPos); +}; + +pp.parseConditional = function (expr, noIn, startPos, startLoc) { + if (this.eat(_types.types.question)) { + var node = this.startNodeAt(startPos, startLoc); + node.test = expr; + node.consequent = this.parseMaybeAssign(); + this.expect(_types.types.colon); + node.alternate = this.parseMaybeAssign(noIn); + return this.finishNode(node, "ConditionalExpression"); + } + return expr; +}; + +// Start the precedence parser. + +pp.parseExprOps = function (noIn, refShorthandDefaultPos) { + var startPos = this.state.start, + startLoc = this.state.startLoc; + var expr = this.parseMaybeUnary(refShorthandDefaultPos); + if (refShorthandDefaultPos && refShorthandDefaultPos.start) { + return expr; + } else { + return this.parseExprOp(expr, startPos, startLoc, -1, noIn); + } +}; + +// Parse binary operators with the operator precedence parsing +// algorithm. `left` is the left-hand side of the operator. +// `minPrec` provides context that allows the function to stop and +// defer further parser to one of its callers when it encounters an +// operator that has a lower precedence than the set it is parsing. + +pp.parseExprOp = function (left, leftStartPos, leftStartLoc, minPrec, noIn) { + var prec = this.state.type.binop; + if (prec != null && (!noIn || !this.match(_types.types._in))) { + if (prec > minPrec) { + var node = this.startNodeAt(leftStartPos, leftStartLoc); + node.left = left; + node.operator = this.state.value; + + if (node.operator === "**" && left.type === "UnaryExpression" && left.extra && !left.extra.parenthesizedArgument && !left.extra.parenthesized) { + this.raise(left.argument.start, "Illegal expression. Wrap left hand side or entire exponentiation in parentheses."); + } + + var op = this.state.type; + this.next(); + + var startPos = this.state.start; + var startLoc = this.state.startLoc; + node.right = this.parseExprOp(this.parseMaybeUnary(), startPos, startLoc, op.rightAssociative ? prec - 1 : prec, noIn); + + this.finishNode(node, op === _types.types.logicalOR || op === _types.types.logicalAND ? "LogicalExpression" : "BinaryExpression"); + return this.parseExprOp(node, leftStartPos, leftStartLoc, minPrec, noIn); + } + } + return left; +}; + +// Parse unary operators, both prefix and postfix. + +pp.parseMaybeUnary = function (refShorthandDefaultPos) { + if (this.state.type.prefix) { + var node = this.startNode(); + var update = this.match(_types.types.incDec); + node.operator = this.state.value; + node.prefix = true; + this.next(); + + var argType = this.state.type; + node.argument = this.parseMaybeUnary(); + + this.addExtra(node, "parenthesizedArgument", argType === _types.types.parenL && (!node.argument.extra || !node.argument.extra.parenthesized)); + + if (refShorthandDefaultPos && refShorthandDefaultPos.start) { + this.unexpected(refShorthandDefaultPos.start); + } + + if (update) { + this.checkLVal(node.argument, undefined, undefined, "prefix operation"); + } else if (this.state.strict && node.operator === "delete" && node.argument.type === "Identifier") { + this.raise(node.start, "Deleting local variable in strict mode"); + } + + return this.finishNode(node, update ? "UpdateExpression" : "UnaryExpression"); + } + + var startPos = this.state.start, + startLoc = this.state.startLoc; + var expr = this.parseExprSubscripts(refShorthandDefaultPos); + if (refShorthandDefaultPos && refShorthandDefaultPos.start) return expr; + while (this.state.type.postfix && !this.canInsertSemicolon()) { + var _node = this.startNodeAt(startPos, startLoc); + _node.operator = this.state.value; + _node.prefix = false; + _node.argument = expr; + this.checkLVal(expr, undefined, undefined, "postfix operation"); + this.next(); + expr = this.finishNode(_node, "UpdateExpression"); + } + return expr; +}; + +// Parse call, dot, and `[]`-subscript expressions. + +pp.parseExprSubscripts = function (refShorthandDefaultPos) { + var startPos = this.state.start, + startLoc = this.state.startLoc; + var potentialArrowAt = this.state.potentialArrowAt; + var expr = this.parseExprAtom(refShorthandDefaultPos); + + if (expr.type === "ArrowFunctionExpression" && expr.start === potentialArrowAt) { + return expr; + } + + if (refShorthandDefaultPos && refShorthandDefaultPos.start) { + return expr; + } + + return this.parseSubscripts(expr, startPos, startLoc); +}; + +pp.parseSubscripts = function (base, startPos, startLoc, noCalls) { + for (;;) { + if (!noCalls && this.eat(_types.types.doubleColon)) { + var node = this.startNodeAt(startPos, startLoc); + node.object = base; + node.callee = this.parseNoCallExpr(); + return this.parseSubscripts(this.finishNode(node, "BindExpression"), startPos, startLoc, noCalls); + } else if (this.eat(_types.types.dot)) { + var _node2 = this.startNodeAt(startPos, startLoc); + _node2.object = base; + _node2.property = this.parseIdentifier(true); + _node2.computed = false; + base = this.finishNode(_node2, "MemberExpression"); + } else if (this.eat(_types.types.bracketL)) { + var _node3 = this.startNodeAt(startPos, startLoc); + _node3.object = base; + _node3.property = this.parseExpression(); + _node3.computed = true; + this.expect(_types.types.bracketR); + base = this.finishNode(_node3, "MemberExpression"); + } else if (!noCalls && this.match(_types.types.parenL)) { + var possibleAsync = this.state.potentialArrowAt === base.start && base.type === "Identifier" && base.name === "async" && !this.canInsertSemicolon(); + this.next(); + + var _node4 = this.startNodeAt(startPos, startLoc); + _node4.callee = base; + _node4.arguments = this.parseCallExpressionArguments(_types.types.parenR, possibleAsync); + base = this.finishNode(_node4, "CallExpression"); + + if (possibleAsync && this.shouldParseAsyncArrow()) { + return this.parseAsyncArrowFromCallExpression(this.startNodeAt(startPos, startLoc), _node4); + } else { + this.toReferencedList(_node4.arguments); + } + } else if (this.match(_types.types.backQuote)) { + var _node5 = this.startNodeAt(startPos, startLoc); + _node5.tag = base; + _node5.quasi = this.parseTemplate(); + base = this.finishNode(_node5, "TaggedTemplateExpression"); + } else { + return base; + } + } +}; + +pp.parseCallExpressionArguments = function (close, possibleAsyncArrow) { + var innerParenStart = void 0; + + var elts = [], + first = true; + while (!this.eat(close)) { + if (first) { + first = false; + } else { + this.expect(_types.types.comma); + if (this.eat(close)) break; + } + + // we need to make sure that if this is an async arrow functions, that we don't allow inner parens inside the params + if (this.match(_types.types.parenL) && !innerParenStart) { + innerParenStart = this.state.start; + } + + elts.push(this.parseExprListItem(undefined, possibleAsyncArrow ? { start: 0 } : undefined)); + } + + // we found an async arrow function so let's not allow any inner parens + if (possibleAsyncArrow && innerParenStart && this.shouldParseAsyncArrow()) { + this.unexpected(); + } + + return elts; +}; + +pp.shouldParseAsyncArrow = function () { + return this.match(_types.types.arrow); +}; + +pp.parseAsyncArrowFromCallExpression = function (node, call) { + this.expect(_types.types.arrow); + return this.parseArrowExpression(node, call.arguments, true); +}; + +// Parse a no-call expression (like argument of `new` or `::` operators). + +pp.parseNoCallExpr = function () { + var startPos = this.state.start, + startLoc = this.state.startLoc; + return this.parseSubscripts(this.parseExprAtom(), startPos, startLoc, true); +}; + +// Parse an atomic expression — either a single token that is an +// expression, an expression started by a keyword like `function` or +// `new`, or an expression wrapped in punctuation like `()`, `[]`, +// or `{}`. + +pp.parseExprAtom = function (refShorthandDefaultPos) { + var node = void 0, + canBeArrow = this.state.potentialArrowAt === this.state.start; + switch (this.state.type) { + case _types.types._super: + if (!this.state.inMethod && !this.options.allowSuperOutsideMethod) { + this.raise(this.state.start, "'super' outside of function or class"); + } + + node = this.startNode(); + this.next(); + if (!this.match(_types.types.parenL) && !this.match(_types.types.bracketL) && !this.match(_types.types.dot)) { + this.unexpected(); + } + if (this.match(_types.types.parenL) && this.state.inMethod !== "constructor" && !this.options.allowSuperOutsideMethod) { + this.raise(node.start, "super() outside of class constructor"); + } + return this.finishNode(node, "Super"); + + case _types.types._this: + node = this.startNode(); + this.next(); + return this.finishNode(node, "ThisExpression"); + + case _types.types._yield: + if (this.state.inGenerator) this.unexpected(); + + case _types.types.name: + node = this.startNode(); + var allowAwait = this.state.value === "await" && this.state.inAsync; + var allowYield = this.shouldAllowYieldIdentifier(); + var id = this.parseIdentifier(allowAwait || allowYield); + + if (id.name === "await") { + if (this.state.inAsync || this.inModule) { + return this.parseAwait(node); + } + } else if (id.name === "async" && this.match(_types.types._function) && !this.canInsertSemicolon()) { + this.next(); + return this.parseFunction(node, false, false, true); + } else if (canBeArrow && id.name === "async" && this.match(_types.types.name)) { + var params = [this.parseIdentifier()]; + this.expect(_types.types.arrow); + // let foo = bar => {}; + return this.parseArrowExpression(node, params, true); + } + + if (canBeArrow && !this.canInsertSemicolon() && this.eat(_types.types.arrow)) { + return this.parseArrowExpression(node, [id]); + } + + return id; + + case _types.types._do: + if (this.hasPlugin("doExpressions")) { + var _node6 = this.startNode(); + this.next(); + var oldInFunction = this.state.inFunction; + var oldLabels = this.state.labels; + this.state.labels = []; + this.state.inFunction = false; + _node6.body = this.parseBlock(false, true); + this.state.inFunction = oldInFunction; + this.state.labels = oldLabels; + return this.finishNode(_node6, "DoExpression"); + } + + case _types.types.regexp: + var value = this.state.value; + node = this.parseLiteral(value.value, "RegExpLiteral"); + node.pattern = value.pattern; + node.flags = value.flags; + return node; + + case _types.types.num: + return this.parseLiteral(this.state.value, "NumericLiteral"); + + case _types.types.string: + return this.parseLiteral(this.state.value, "StringLiteral"); + + case _types.types._null: + node = this.startNode(); + this.next(); + return this.finishNode(node, "NullLiteral"); + + case _types.types._true:case _types.types._false: + node = this.startNode(); + node.value = this.match(_types.types._true); + this.next(); + return this.finishNode(node, "BooleanLiteral"); + + case _types.types.parenL: + return this.parseParenAndDistinguishExpression(null, null, canBeArrow); + + case _types.types.bracketL: + node = this.startNode(); + this.next(); + node.elements = this.parseExprList(_types.types.bracketR, true, refShorthandDefaultPos); + this.toReferencedList(node.elements); + return this.finishNode(node, "ArrayExpression"); + + case _types.types.braceL: + return this.parseObj(false, refShorthandDefaultPos); + + case _types.types._function: + return this.parseFunctionExpression(); + + case _types.types.at: + this.parseDecorators(); + + case _types.types._class: + node = this.startNode(); + this.takeDecorators(node); + return this.parseClass(node, false); + + case _types.types._new: + return this.parseNew(); + + case _types.types.backQuote: + return this.parseTemplate(); + + case _types.types.doubleColon: + node = this.startNode(); + this.next(); + node.object = null; + var callee = node.callee = this.parseNoCallExpr(); + if (callee.type === "MemberExpression") { + return this.finishNode(node, "BindExpression"); + } else { + this.raise(callee.start, "Binding should be performed on object property."); + } + + default: + this.unexpected(); + } +}; + +pp.parseFunctionExpression = function () { + var node = this.startNode(); + var meta = this.parseIdentifier(true); + if (this.state.inGenerator && this.eat(_types.types.dot) && this.hasPlugin("functionSent")) { + return this.parseMetaProperty(node, meta, "sent"); + } else { + return this.parseFunction(node, false); + } +}; + +pp.parseMetaProperty = function (node, meta, propertyName) { + node.meta = meta; + node.property = this.parseIdentifier(true); + + if (node.property.name !== propertyName) { + this.raise(node.property.start, "The only valid meta property for new is " + meta.name + "." + propertyName); + } + + return this.finishNode(node, "MetaProperty"); +}; + +pp.parseLiteral = function (value, type) { + var node = this.startNode(); + this.addExtra(node, "rawValue", value); + this.addExtra(node, "raw", this.input.slice(this.state.start, this.state.end)); + node.value = value; + this.next(); + return this.finishNode(node, type); +}; + +pp.parseParenExpression = function () { + this.expect(_types.types.parenL); + var val = this.parseExpression(); + this.expect(_types.types.parenR); + return val; +}; + +pp.parseParenAndDistinguishExpression = function (startPos, startLoc, canBeArrow, isAsync) { + startPos = startPos || this.state.start; + startLoc = startLoc || this.state.startLoc; + + var val = void 0; + this.expect(_types.types.parenL); + + var innerStartPos = this.state.start, + innerStartLoc = this.state.startLoc; + var exprList = [], + first = true; + var refShorthandDefaultPos = { start: 0 }, + spreadStart = void 0, + optionalCommaStart = void 0; + var refNeedsArrowPos = { start: 0 }; + while (!this.match(_types.types.parenR)) { + if (first) { + first = false; + } else { + this.expect(_types.types.comma, refNeedsArrowPos.start || null); + if (this.match(_types.types.parenR)) { + optionalCommaStart = this.state.start; + break; + } + } + + if (this.match(_types.types.ellipsis)) { + var spreadNodeStartPos = this.state.start, + spreadNodeStartLoc = this.state.startLoc; + spreadStart = this.state.start; + exprList.push(this.parseParenItem(this.parseRest(), spreadNodeStartLoc, spreadNodeStartPos)); + break; + } else { + exprList.push(this.parseMaybeAssign(false, refShorthandDefaultPos, this.parseParenItem, refNeedsArrowPos)); + } + } + + var innerEndPos = this.state.start; + var innerEndLoc = this.state.startLoc; + this.expect(_types.types.parenR); + + var arrowNode = this.startNodeAt(startPos, startLoc); + if (canBeArrow && this.shouldParseArrow() && (arrowNode = this.parseArrow(arrowNode))) { + for (var _iterator = exprList, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.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 param = _ref; + + if (param.extra && param.extra.parenthesized) this.unexpected(param.extra.parenStart); + } + + return this.parseArrowExpression(arrowNode, exprList, isAsync); + } + + if (!exprList.length) { + if (isAsync) { + return; + } else { + this.unexpected(this.state.lastTokStart); + } + } + if (optionalCommaStart) this.unexpected(optionalCommaStart); + if (spreadStart) this.unexpected(spreadStart); + if (refShorthandDefaultPos.start) this.unexpected(refShorthandDefaultPos.start); + if (refNeedsArrowPos.start) this.unexpected(refNeedsArrowPos.start); + + if (exprList.length > 1) { + val = this.startNodeAt(innerStartPos, innerStartLoc); + val.expressions = exprList; + this.toReferencedList(val.expressions); + this.finishNodeAt(val, "SequenceExpression", innerEndPos, innerEndLoc); + } else { + val = exprList[0]; + } + + this.addExtra(val, "parenthesized", true); + this.addExtra(val, "parenStart", startPos); + + return val; +}; + +pp.shouldParseArrow = function () { + return !this.canInsertSemicolon(); +}; + +pp.parseArrow = function (node) { + if (this.eat(_types.types.arrow)) { + return node; + } +}; + +pp.parseParenItem = function (node) { + return node; +}; + +// New's precedence is slightly tricky. It must allow its argument +// to be a `[]` or dot subscript expression, but not a call — at +// least, not without wrapping it in parentheses. Thus, it uses the + +pp.parseNew = function () { + var node = this.startNode(); + var meta = this.parseIdentifier(true); + + if (this.eat(_types.types.dot)) { + return this.parseMetaProperty(node, meta, "target"); + } + + node.callee = this.parseNoCallExpr(); + + if (this.eat(_types.types.parenL)) { + node.arguments = this.parseExprList(_types.types.parenR); + this.toReferencedList(node.arguments); + } else { + node.arguments = []; + } + + return this.finishNode(node, "NewExpression"); +}; + +// Parse template expression. + +pp.parseTemplateElement = function () { + var elem = this.startNode(); + elem.value = { + raw: this.input.slice(this.state.start, this.state.end).replace(/\r\n?/g, "\n"), + cooked: this.state.value + }; + this.next(); + elem.tail = this.match(_types.types.backQuote); + return this.finishNode(elem, "TemplateElement"); +}; + +pp.parseTemplate = function () { + var node = this.startNode(); + this.next(); + node.expressions = []; + var curElt = this.parseTemplateElement(); + node.quasis = [curElt]; + while (!curElt.tail) { + this.expect(_types.types.dollarBraceL); + node.expressions.push(this.parseExpression()); + this.expect(_types.types.braceR); + node.quasis.push(curElt = this.parseTemplateElement()); + } + this.next(); + return this.finishNode(node, "TemplateLiteral"); +}; + +// Parse an object literal or binding pattern. + +pp.parseObj = function (isPattern, refShorthandDefaultPos) { + var decorators = []; + var propHash = Object.create(null); + var first = true; + var node = this.startNode(); + + node.properties = []; + this.next(); + + while (!this.eat(_types.types.braceR)) { + if (first) { + first = false; + } else { + this.expect(_types.types.comma); + if (this.eat(_types.types.braceR)) break; + } + + while (this.match(_types.types.at)) { + decorators.push(this.parseDecorator()); + } + + var prop = this.startNode(), + isGenerator = false, + isAsync = false, + startPos = void 0, + startLoc = void 0; + if (decorators.length) { + prop.decorators = decorators; + decorators = []; + } + + if (this.hasPlugin("objectRestSpread") && this.match(_types.types.ellipsis)) { + prop = this.parseSpread(); + prop.type = isPattern ? "RestProperty" : "SpreadProperty"; + node.properties.push(prop); + continue; + } + + prop.method = false; + prop.shorthand = false; + + if (isPattern || refShorthandDefaultPos) { + startPos = this.state.start; + startLoc = this.state.startLoc; + } + + if (!isPattern) { + isGenerator = this.eat(_types.types.star); + } + + if (!isPattern && this.isContextual("async")) { + if (isGenerator) this.unexpected(); + + var asyncId = this.parseIdentifier(); + if (this.match(_types.types.colon) || this.match(_types.types.parenL) || this.match(_types.types.braceR)) { + prop.key = asyncId; + } else { + isAsync = true; + if (this.hasPlugin("asyncGenerators")) isGenerator = this.eat(_types.types.star); + this.parsePropertyName(prop); + } + } else { + this.parsePropertyName(prop); + } + + this.parseObjPropValue(prop, startPos, startLoc, isGenerator, isAsync, isPattern, refShorthandDefaultPos); + this.checkPropClash(prop, propHash); + + if (prop.shorthand) { + this.addExtra(prop, "shorthand", true); + } + + node.properties.push(prop); + } + + if (decorators.length) { + this.raise(this.state.start, "You have trailing decorators with no property"); + } + + return this.finishNode(node, isPattern ? "ObjectPattern" : "ObjectExpression"); +}; + +pp.parseObjPropValue = function (prop, startPos, startLoc, isGenerator, isAsync, isPattern, refShorthandDefaultPos) { + if (isAsync || isGenerator || this.match(_types.types.parenL)) { + if (isPattern) this.unexpected(); + prop.kind = "method"; + prop.method = true; + this.parseMethod(prop, isGenerator, isAsync); + return this.finishNode(prop, "ObjectMethod"); + } + + if (this.eat(_types.types.colon)) { + prop.value = isPattern ? this.parseMaybeDefault(this.state.start, this.state.startLoc) : this.parseMaybeAssign(false, refShorthandDefaultPos); + return this.finishNode(prop, "ObjectProperty"); + } + + if (!prop.computed && prop.key.type === "Identifier" && (prop.key.name === "get" || prop.key.name === "set") && !this.match(_types.types.comma) && !this.match(_types.types.braceR)) { + if (isGenerator || isAsync || isPattern) this.unexpected(); + prop.kind = prop.key.name; + this.parsePropertyName(prop); + this.parseMethod(prop, false); + var paramCount = prop.kind === "get" ? 0 : 1; + if (prop.params.length !== paramCount) { + var start = prop.start; + if (prop.kind === "get") { + this.raise(start, "getter should have no params"); + } else { + this.raise(start, "setter should have exactly one param"); + } + } + return this.finishNode(prop, "ObjectMethod"); + } + + if (!prop.computed && prop.key.type === "Identifier") { + if (isPattern) { + var illegalBinding = this.isKeyword(prop.key.name); + if (!illegalBinding && this.state.strict) { + illegalBinding = _identifier.reservedWords.strictBind(prop.key.name) || _identifier.reservedWords.strict(prop.key.name); + } + if (illegalBinding) { + this.raise(prop.key.start, "Binding " + prop.key.name); + } + prop.value = this.parseMaybeDefault(startPos, startLoc, prop.key.__clone()); + } else if (this.match(_types.types.eq) && refShorthandDefaultPos) { + if (!refShorthandDefaultPos.start) { + refShorthandDefaultPos.start = this.state.start; + } + prop.value = this.parseMaybeDefault(startPos, startLoc, prop.key.__clone()); + } else { + prop.value = prop.key.__clone(); + } + prop.shorthand = true; + return this.finishNode(prop, "ObjectProperty"); + } + + this.unexpected(); +}; + +pp.parsePropertyName = function (prop) { + if (this.eat(_types.types.bracketL)) { + prop.computed = true; + prop.key = this.parseMaybeAssign(); + this.expect(_types.types.bracketR); + return prop.key; + } else { + prop.computed = false; + return prop.key = this.match(_types.types.num) || this.match(_types.types.string) ? this.parseExprAtom() : this.parseIdentifier(true); + } +}; + +// Initialize empty function node. + +pp.initFunction = function (node, isAsync) { + node.id = null; + node.generator = false; + node.expression = false; + node.async = !!isAsync; +}; + +// Parse object or class method. + +pp.parseMethod = function (node, isGenerator, isAsync) { + var oldInMethod = this.state.inMethod; + this.state.inMethod = node.kind || true; + this.initFunction(node, isAsync); + this.expect(_types.types.parenL); + node.params = this.parseBindingList(_types.types.parenR); + node.generator = isGenerator; + this.parseFunctionBody(node); + this.state.inMethod = oldInMethod; + return node; +}; + +// Parse arrow function expression with given parameters. + +pp.parseArrowExpression = function (node, params, isAsync) { + this.initFunction(node, isAsync); + node.params = this.toAssignableList(params, true, "arrow function parameters"); + this.parseFunctionBody(node, true); + return this.finishNode(node, "ArrowFunctionExpression"); +}; + +// Parse function body and check parameters. + +pp.parseFunctionBody = function (node, allowExpression) { + var isExpression = allowExpression && !this.match(_types.types.braceL); + + var oldInAsync = this.state.inAsync; + this.state.inAsync = node.async; + if (isExpression) { + node.body = this.parseMaybeAssign(); + node.expression = true; + } else { + // Start a new scope with regard to labels and the `inFunction` + // flag (restore them to their old value afterwards). + var oldInFunc = this.state.inFunction, + oldInGen = this.state.inGenerator, + oldLabels = this.state.labels; + this.state.inFunction = true;this.state.inGenerator = node.generator;this.state.labels = []; + node.body = this.parseBlock(true); + node.expression = false; + this.state.inFunction = oldInFunc;this.state.inGenerator = oldInGen;this.state.labels = oldLabels; + } + this.state.inAsync = oldInAsync; + + // If this is a strict mode function, verify that argument names + // are not repeated, and it does not try to bind the words `eval` + // or `arguments`. + var checkLVal = this.state.strict; + var isStrict = false; + + // arrow function + if (allowExpression) checkLVal = true; + + // normal function + if (!isExpression && node.body.directives.length) { + for (var _iterator2 = node.body.directives, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : _iterator2[Symbol.iterator]();;) { + var _ref2; + + if (_isArray2) { + if (_i2 >= _iterator2.length) break; + _ref2 = _iterator2[_i2++]; + } else { + _i2 = _iterator2.next(); + if (_i2.done) break; + _ref2 = _i2.value; + } + + var directive = _ref2; + + if (directive.value.value === "use strict") { + isStrict = true; + checkLVal = true; + break; + } + } + } + + // + if (isStrict && node.id && node.id.type === "Identifier" && node.id.name === "yield") { + this.raise(node.id.start, "Binding yield in strict mode"); + } + + if (checkLVal) { + var nameHash = Object.create(null); + var oldStrict = this.state.strict; + if (isStrict) this.state.strict = true; + if (node.id) { + this.checkLVal(node.id, true, undefined, "function name"); + } + for (var _iterator3 = node.params, _isArray3 = Array.isArray(_iterator3), _i3 = 0, _iterator3 = _isArray3 ? _iterator3 : _iterator3[Symbol.iterator]();;) { + var _ref3; + + if (_isArray3) { + if (_i3 >= _iterator3.length) break; + _ref3 = _iterator3[_i3++]; + } else { + _i3 = _iterator3.next(); + if (_i3.done) break; + _ref3 = _i3.value; + } + + var param = _ref3; + + if (isStrict && param.type !== "Identifier") { + this.raise(param.start, "Non-simple parameter in strict mode"); + } + this.checkLVal(param, true, nameHash, "function parameter list"); + } + this.state.strict = oldStrict; + } +}; + +// Parses a comma-separated list of expressions, and returns them as +// an array. `close` is the token type that ends the list, and +// `allowEmpty` can be turned on to allow subsequent commas with +// nothing in between them to be parsed as `null` (which is needed +// for array literals). + +pp.parseExprList = function (close, allowEmpty, refShorthandDefaultPos) { + var elts = [], + first = true; + while (!this.eat(close)) { + if (first) { + first = false; + } else { + this.expect(_types.types.comma); + if (this.eat(close)) break; + } + + elts.push(this.parseExprListItem(allowEmpty, refShorthandDefaultPos)); + } + return elts; +}; + +pp.parseExprListItem = function (allowEmpty, refShorthandDefaultPos) { + var elt = void 0; + if (allowEmpty && this.match(_types.types.comma)) { + elt = null; + } else if (this.match(_types.types.ellipsis)) { + elt = this.parseSpread(refShorthandDefaultPos); + } else { + elt = this.parseMaybeAssign(false, refShorthandDefaultPos, this.parseParenItem); + } + return elt; +}; + +// Parse the next token as an identifier. If `liberal` is true (used +// when parsing properties), it will also convert keywords into +// identifiers. + +pp.parseIdentifier = function (liberal) { + var node = this.startNode(); + + if (this.match(_types.types.name)) { + if (!liberal && this.state.strict && _identifier.reservedWords.strict(this.state.value)) { + this.raise(this.state.start, "The keyword '" + this.state.value + "' is reserved"); + } + + node.name = this.state.value; + } else if (liberal && this.state.type.keyword) { + node.name = this.state.type.keyword; + } else { + this.unexpected(); + } + + if (!liberal && node.name === "await" && this.state.inAsync) { + this.raise(node.start, "invalid use of await inside of an async function"); + } + + node.loc.identifierName = node.name; + + this.next(); + return this.finishNode(node, "Identifier"); +}; + +// Parses await expression inside async function. + +pp.parseAwait = function (node) { + if (!this.state.inAsync) { + this.unexpected(); + } + if (this.match(_types.types.star)) { + this.raise(node.start, "await* has been removed from the async functions proposal. Use Promise.all() instead."); + } + node.argument = this.parseMaybeUnary(); + return this.finishNode(node, "AwaitExpression"); +}; + +// Parses yield expression inside generator. + +pp.parseYield = function () { + var node = this.startNode(); + this.next(); + if (this.match(_types.types.semi) || this.canInsertSemicolon() || !this.match(_types.types.star) && !this.state.type.startsExpr) { + node.delegate = false; + node.argument = null; + } else { + node.delegate = this.eat(_types.types.star); + node.argument = this.parseMaybeAssign(); + } + return this.finishNode(node, "YieldExpression"); +}; +},{"../tokenizer/types":213,"../util/identifier":214,"./index":201}],201:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; +exports.plugins = undefined; + +var _identifier = require("../util/identifier"); + +var _options = require("../options"); + +var _tokenizer = require("../tokenizer"); + +var _tokenizer2 = _interopRequireDefault(_tokenizer); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var plugins = exports.plugins = {}; + +var Parser = function (_Tokenizer) { + _inherits(Parser, _Tokenizer); + + function Parser(options, input) { + _classCallCheck(this, Parser); + + options = (0, _options.getOptions)(options); + + var _this = _possibleConstructorReturn(this, _Tokenizer.call(this, options, input)); + + _this.options = options; + _this.inModule = _this.options.sourceType === "module"; + _this.isReservedWord = _identifier.reservedWords[6]; + _this.input = input; + _this.plugins = _this.loadPlugins(_this.options.plugins); + _this.filename = options.sourceFilename; + + // If enabled, skip leading hashbang line. + if (_this.state.pos === 0 && _this.input[0] === "#" && _this.input[1] === "!") { + _this.skipLineComment(2); + } + return _this; + } + + Parser.prototype.hasPlugin = function hasPlugin(name) { + return !!(this.plugins["*"] || this.plugins[name]); + }; + + Parser.prototype.extend = function extend(name, f) { + this[name] = f(this[name]); + }; + + Parser.prototype.loadPlugins = function loadPlugins(plugins) { + var pluginMap = {}; + + if (plugins.indexOf("flow") >= 0) { + // ensure flow plugin loads last + plugins = plugins.filter(function (plugin) { + return plugin !== "flow"; + }); + plugins.push("flow"); + } + + for (var _iterator = plugins, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.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 name = _ref; + + if (!pluginMap[name]) { + pluginMap[name] = true; + + var plugin = exports.plugins[name]; + if (plugin) plugin(this); + } + } + + return pluginMap; + }; + + Parser.prototype.parse = function parse() { + var file = this.startNode(); + var program = this.startNode(); + this.nextToken(); + return this.parseTopLevel(file, program); + }; + + return Parser; +}(_tokenizer2.default); + +exports.default = Parser; +},{"../options":198,"../tokenizer":211,"../util/identifier":214}],202:[function(require,module,exports){ +"use strict"; + +var _location = require("../util/location"); + +var _index = require("./index"); + +var _index2 = _interopRequireDefault(_index); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var pp = _index2.default.prototype; + +// This function is used to raise exceptions on parse errors. It +// takes an offset integer (into the current `input`) to indicate +// the location of the error, attaches the position to the end +// of the error message, and then raises a `SyntaxError` with that +// message. + +pp.raise = function (pos, message) { + var loc = (0, _location.getLineInfo)(this.input, pos); + message += " (" + loc.line + ":" + loc.column + ")"; + var err = new SyntaxError(message); + err.pos = pos; + err.loc = loc; + throw err; +}; +},{"../util/location":215,"./index":201}],203:[function(require,module,exports){ +"use strict"; + +var _types = require("../tokenizer/types"); + +var _index = require("./index"); + +var _index2 = _interopRequireDefault(_index); + +var _identifier = require("../util/identifier"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var pp = _index2.default.prototype; + +// Convert existing expression atom to assignable pattern +// if possible. + +/* eslint indent: 0 */ + +pp.toAssignable = function (node, isBinding, contextDescription) { + if (node) { + switch (node.type) { + case "Identifier": + case "ObjectPattern": + case "ArrayPattern": + case "AssignmentPattern": + break; + + case "ObjectExpression": + node.type = "ObjectPattern"; + for (var _iterator = node.properties, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.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 prop = _ref; + + if (prop.type === "ObjectMethod") { + if (prop.kind === "get" || prop.kind === "set") { + this.raise(prop.key.start, "Object pattern can't contain getter or setter"); + } else { + this.raise(prop.key.start, "Object pattern can't contain methods"); + } + } else { + this.toAssignable(prop, isBinding, "object destructuring pattern"); + } + } + break; + + case "ObjectProperty": + this.toAssignable(node.value, isBinding, contextDescription); + break; + + case "SpreadProperty": + node.type = "RestProperty"; + break; + + case "ArrayExpression": + node.type = "ArrayPattern"; + this.toAssignableList(node.elements, isBinding, contextDescription); + break; + + case "AssignmentExpression": + if (node.operator === "=") { + node.type = "AssignmentPattern"; + delete node.operator; + } else { + this.raise(node.left.end, "Only '=' operator can be used for specifying default value."); + } + break; + + case "MemberExpression": + if (!isBinding) break; + + default: + { + var message = "Invalid left-hand side" + (contextDescription ? " in " + contextDescription : /* istanbul ignore next */"expression"); + this.raise(node.start, message); + } + } + } + return node; +}; + +// Convert list of expression atoms to binding list. + +pp.toAssignableList = function (exprList, isBinding, contextDescription) { + var end = exprList.length; + if (end) { + var last = exprList[end - 1]; + if (last && last.type === "RestElement") { + --end; + } else if (last && last.type === "SpreadElement") { + last.type = "RestElement"; + var arg = last.argument; + this.toAssignable(arg, isBinding, contextDescription); + if (arg.type !== "Identifier" && arg.type !== "MemberExpression" && arg.type !== "ArrayPattern") { + this.unexpected(arg.start); + } + --end; + } + } + for (var i = 0; i < end; i++) { + var elt = exprList[i]; + if (elt) this.toAssignable(elt, isBinding, contextDescription); + } + return exprList; +}; + +// Convert list of expression atoms to a list of + +pp.toReferencedList = function (exprList) { + return exprList; +}; + +// Parses spread element. + +pp.parseSpread = function (refShorthandDefaultPos) { + var node = this.startNode(); + this.next(); + node.argument = this.parseMaybeAssign(false, refShorthandDefaultPos); + return this.finishNode(node, "SpreadElement"); +}; + +pp.parseRest = function () { + var node = this.startNode(); + this.next(); + node.argument = this.parseBindingIdentifier(); + return this.finishNode(node, "RestElement"); +}; + +pp.shouldAllowYieldIdentifier = function () { + return this.match(_types.types._yield) && !this.state.strict && !this.state.inGenerator; +}; + +pp.parseBindingIdentifier = function () { + return this.parseIdentifier(this.shouldAllowYieldIdentifier()); +}; + +// Parses lvalue (assignable) atom. + +pp.parseBindingAtom = function () { + switch (this.state.type) { + case _types.types._yield: + if (this.state.strict || this.state.inGenerator) this.unexpected(); + // fall-through + case _types.types.name: + return this.parseIdentifier(true); + + case _types.types.bracketL: + var node = this.startNode(); + this.next(); + node.elements = this.parseBindingList(_types.types.bracketR, true); + return this.finishNode(node, "ArrayPattern"); + + case _types.types.braceL: + return this.parseObj(true); + + default: + this.unexpected(); + } +}; + +pp.parseBindingList = function (close, allowEmpty) { + var elts = []; + var first = true; + while (!this.eat(close)) { + if (first) { + first = false; + } else { + this.expect(_types.types.comma); + } + if (allowEmpty && this.match(_types.types.comma)) { + elts.push(null); + } else if (this.eat(close)) { + break; + } else if (this.match(_types.types.ellipsis)) { + elts.push(this.parseAssignableListItemTypes(this.parseRest())); + this.expect(close); + break; + } else { + var decorators = []; + while (this.match(_types.types.at)) { + decorators.push(this.parseDecorator()); + } + var left = this.parseMaybeDefault(); + if (decorators.length) { + left.decorators = decorators; + } + this.parseAssignableListItemTypes(left); + elts.push(this.parseMaybeDefault(left.start, left.loc.start, left)); + } + } + return elts; +}; + +pp.parseAssignableListItemTypes = function (param) { + return param; +}; + +// Parses assignment pattern around given atom if possible. + +pp.parseMaybeDefault = function (startPos, startLoc, left) { + startLoc = startLoc || this.state.startLoc; + startPos = startPos || this.state.start; + left = left || this.parseBindingAtom(); + if (!this.eat(_types.types.eq)) return left; + + var node = this.startNodeAt(startPos, startLoc); + node.left = left; + node.right = this.parseMaybeAssign(); + return this.finishNode(node, "AssignmentPattern"); +}; + +// Verify that a node is an lval — something that can be assigned +// to. + +pp.checkLVal = function (expr, isBinding, checkClashes, contextDescription) { + switch (expr.type) { + case "Identifier": + if (this.state.strict && (_identifier.reservedWords.strictBind(expr.name) || _identifier.reservedWords.strict(expr.name))) { + this.raise(expr.start, (isBinding ? "Binding " : "Assigning to ") + expr.name + " in strict mode"); + } + + if (checkClashes) { + // we need to prefix this with an underscore for the cases where we have a key of + // `__proto__`. there's a bug in old V8 where the following wouldn't work: + // + // > var obj = Object.create(null); + // undefined + // > obj.__proto__ + // null + // > obj.__proto__ = true; + // true + // > obj.__proto__ + // null + var key = "_" + expr.name; + + if (checkClashes[key]) { + this.raise(expr.start, "Argument name clash in strict mode"); + } else { + checkClashes[key] = true; + } + } + break; + + case "MemberExpression": + if (isBinding) this.raise(expr.start, (isBinding ? "Binding" : "Assigning to") + " member expression"); + break; + + case "ObjectPattern": + for (var _iterator2 = expr.properties, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : _iterator2[Symbol.iterator]();;) { + var _ref2; + + if (_isArray2) { + if (_i2 >= _iterator2.length) break; + _ref2 = _iterator2[_i2++]; + } else { + _i2 = _iterator2.next(); + if (_i2.done) break; + _ref2 = _i2.value; + } + + var prop = _ref2; + + if (prop.type === "ObjectProperty") prop = prop.value; + this.checkLVal(prop, isBinding, checkClashes, "object destructuring pattern"); + } + break; + + case "ArrayPattern": + for (var _iterator3 = expr.elements, _isArray3 = Array.isArray(_iterator3), _i3 = 0, _iterator3 = _isArray3 ? _iterator3 : _iterator3[Symbol.iterator]();;) { + var _ref3; + + if (_isArray3) { + if (_i3 >= _iterator3.length) break; + _ref3 = _iterator3[_i3++]; + } else { + _i3 = _iterator3.next(); + if (_i3.done) break; + _ref3 = _i3.value; + } + + var elem = _ref3; + + if (elem) this.checkLVal(elem, isBinding, checkClashes, "array destructuring pattern"); + } + break; + + case "AssignmentPattern": + this.checkLVal(expr.left, isBinding, checkClashes, "assignment pattern"); + break; + + case "RestProperty": + this.checkLVal(expr.argument, isBinding, checkClashes, "rest property"); + break; + + case "RestElement": + this.checkLVal(expr.argument, isBinding, checkClashes, "rest element"); + break; + + default: + { + var message = (isBinding ? /* istanbul ignore next */"Binding invalid" : "Invalid") + " left-hand side" + (contextDescription ? " in " + contextDescription : /* istanbul ignore next */"expression"); + this.raise(expr.start, message); + } + } +}; +},{"../tokenizer/types":213,"../util/identifier":214,"./index":201}],204:[function(require,module,exports){ +"use strict"; + +var _index = require("./index"); + +var _index2 = _interopRequireDefault(_index); + +var _location = require("../util/location"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +// Start an AST node, attaching a start offset. + +var pp = _index2.default.prototype; +var commentKeys = ["leadingComments", "trailingComments", "innerComments"]; + +var Node = function () { + function Node(pos, loc, filename) { + _classCallCheck(this, Node); + + this.type = ""; + this.start = pos; + this.end = 0; + this.loc = new _location.SourceLocation(loc); + if (filename) this.loc.filename = filename; + } + + Node.prototype.__clone = function __clone() { + var node2 = new Node(); + for (var key in this) { + // Do not clone comments that are already attached to the node + if (commentKeys.indexOf(key) < 0) { + node2[key] = this[key]; + } + } + + return node2; + }; + + return Node; +}(); + +pp.startNode = function () { + return new Node(this.state.start, this.state.startLoc, this.filename); +}; + +pp.startNodeAt = function (pos, loc) { + return new Node(pos, loc, this.filename); +}; + +function finishNodeAt(node, type, pos, loc) { + node.type = type; + node.end = pos; + node.loc.end = loc; + this.processComment(node); + return node; +} + +// Finish an AST node, adding `type` and `end` properties. + +pp.finishNode = function (node, type) { + return finishNodeAt.call(this, node, type, this.state.lastTokEnd, this.state.lastTokEndLoc); +}; + +// Finish node at given position + +pp.finishNodeAt = function (node, type, pos, loc) { + return finishNodeAt.call(this, node, type, pos, loc); +}; +},{"../util/location":215,"./index":201}],205:[function(require,module,exports){ +"use strict"; + +var _types = require("../tokenizer/types"); + +var _index = require("./index"); + +var _index2 = _interopRequireDefault(_index); + +var _whitespace = require("../util/whitespace"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var pp = _index2.default.prototype; + +// ### Statement parsing + +// Parse a program. Initializes the parser, reads any number of +// statements, and wraps them in a Program node. Optionally takes a +// `program` argument. If present, the statements will be appended +// to its body instead of creating a new node. + +/* eslint indent: 0 */ +/* eslint max-len: 0 */ + +pp.parseTopLevel = function (file, program) { + program.sourceType = this.options.sourceType; + + this.parseBlockBody(program, true, true, _types.types.eof); + + file.program = this.finishNode(program, "Program"); + file.comments = this.state.comments; + file.tokens = this.state.tokens; + + return this.finishNode(file, "File"); +}; + +var loopLabel = { kind: "loop" }, + switchLabel = { kind: "switch" }; + +// TODO + +pp.stmtToDirective = function (stmt) { + var expr = stmt.expression; + + var directiveLiteral = this.startNodeAt(expr.start, expr.loc.start); + var directive = this.startNodeAt(stmt.start, stmt.loc.start); + + var raw = this.input.slice(expr.start, expr.end); + var val = directiveLiteral.value = raw.slice(1, -1); // remove quotes + + this.addExtra(directiveLiteral, "raw", raw); + this.addExtra(directiveLiteral, "rawValue", val); + + directive.value = this.finishNodeAt(directiveLiteral, "DirectiveLiteral", expr.end, expr.loc.end); + + return this.finishNodeAt(directive, "Directive", stmt.end, stmt.loc.end); +}; + +// Parse a single statement. +// +// If expecting a statement and finding a slash operator, parse a +// regular expression literal. This is to handle cases like +// `if (foo) /blah/.exec(foo)`, where looking at the previous token +// does not help. + +pp.parseStatement = function (declaration, topLevel) { + if (this.match(_types.types.at)) { + this.parseDecorators(true); + } + + var starttype = this.state.type, + node = this.startNode(); + + // Most types of statements are recognized by the keyword they + // start with. Many are trivial to parse, some require a bit of + // complexity. + + switch (starttype) { + case _types.types._break:case _types.types._continue: + return this.parseBreakContinueStatement(node, starttype.keyword); + case _types.types._debugger: + return this.parseDebuggerStatement(node); + case _types.types._do: + return this.parseDoStatement(node); + case _types.types._for: + return this.parseForStatement(node); + case _types.types._function: + if (!declaration) this.unexpected(); + return this.parseFunctionStatement(node); + + case _types.types._class: + if (!declaration) this.unexpected(); + this.takeDecorators(node); + return this.parseClass(node, true); + + case _types.types._if: + return this.parseIfStatement(node); + case _types.types._return: + return this.parseReturnStatement(node); + case _types.types._switch: + return this.parseSwitchStatement(node); + case _types.types._throw: + return this.parseThrowStatement(node); + case _types.types._try: + return this.parseTryStatement(node); + + case _types.types._let: + case _types.types._const: + if (!declaration) this.unexpected(); // NOTE: falls through to _var + + case _types.types._var: + return this.parseVarStatement(node, starttype); + + case _types.types._while: + return this.parseWhileStatement(node); + case _types.types._with: + return this.parseWithStatement(node); + case _types.types.braceL: + return this.parseBlock(); + case _types.types.semi: + return this.parseEmptyStatement(node); + case _types.types._export: + case _types.types._import: + if (!this.options.allowImportExportEverywhere) { + if (!topLevel) { + this.raise(this.state.start, "'import' and 'export' may only appear at the top level"); + } + + if (!this.inModule) { + this.raise(this.state.start, "'import' and 'export' may appear only with 'sourceType: module'"); + } + } + return starttype === _types.types._import ? this.parseImport(node) : this.parseExport(node); + + case _types.types.name: + if (this.state.value === "async") { + // peek ahead and see if next token is a function + var state = this.state.clone(); + this.next(); + if (this.match(_types.types._function) && !this.canInsertSemicolon()) { + this.expect(_types.types._function); + return this.parseFunction(node, true, false, true); + } else { + this.state = state; + } + } + } + + // If the statement does not start with a statement keyword or a + // brace, it's an ExpressionStatement or LabeledStatement. We + // simply start parsing an expression, and afterwards, if the + // next token is a colon and the expression was a simple + // Identifier node, we switch to interpreting it as a label. + var maybeName = this.state.value; + var expr = this.parseExpression(); + + if (starttype === _types.types.name && expr.type === "Identifier" && this.eat(_types.types.colon)) { + return this.parseLabeledStatement(node, maybeName, expr); + } else { + return this.parseExpressionStatement(node, expr); + } +}; + +pp.takeDecorators = function (node) { + if (this.state.decorators.length) { + node.decorators = this.state.decorators; + this.state.decorators = []; + } +}; + +pp.parseDecorators = function (allowExport) { + while (this.match(_types.types.at)) { + this.state.decorators.push(this.parseDecorator()); + } + + if (allowExport && this.match(_types.types._export)) { + return; + } + + if (!this.match(_types.types._class)) { + this.raise(this.state.start, "Leading decorators must be attached to a class declaration"); + } +}; + +pp.parseDecorator = function () { + if (!this.hasPlugin("decorators")) { + this.unexpected(); + } + var node = this.startNode(); + this.next(); + node.expression = this.parseMaybeAssign(); + return this.finishNode(node, "Decorator"); +}; + +pp.parseBreakContinueStatement = function (node, keyword) { + var isBreak = keyword === "break"; + this.next(); + + if (this.isLineTerminator()) { + node.label = null; + } else if (!this.match(_types.types.name)) { + this.unexpected(); + } else { + node.label = this.parseIdentifier(); + this.semicolon(); + } + + // Verify that there is an actual destination to break or + // continue to. + var i = void 0; + for (i = 0; i < this.state.labels.length; ++i) { + var lab = this.state.labels[i]; + if (node.label == null || lab.name === node.label.name) { + if (lab.kind != null && (isBreak || lab.kind === "loop")) break; + if (node.label && isBreak) break; + } + } + if (i === this.state.labels.length) this.raise(node.start, "Unsyntactic " + keyword); + return this.finishNode(node, isBreak ? "BreakStatement" : "ContinueStatement"); +}; + +pp.parseDebuggerStatement = function (node) { + this.next(); + this.semicolon(); + return this.finishNode(node, "DebuggerStatement"); +}; + +pp.parseDoStatement = function (node) { + this.next(); + this.state.labels.push(loopLabel); + node.body = this.parseStatement(false); + this.state.labels.pop(); + this.expect(_types.types._while); + node.test = this.parseParenExpression(); + this.eat(_types.types.semi); + return this.finishNode(node, "DoWhileStatement"); +}; + +// Disambiguating between a `for` and a `for`/`in` or `for`/`of` +// loop is non-trivial. Basically, we have to parse the init `var` +// statement or expression, disallowing the `in` operator (see +// the second parameter to `parseExpression`), and then check +// whether the next token is `in` or `of`. When there is no init +// part (semicolon immediately after the opening parenthesis), it +// is a regular `for` loop. + +pp.parseForStatement = function (node) { + this.next(); + this.state.labels.push(loopLabel); + + var forAwait = false; + if (this.hasPlugin("asyncGenerators") && this.state.inAsync && this.isContextual("await")) { + forAwait = true; + this.next(); + } + this.expect(_types.types.parenL); + + if (this.match(_types.types.semi)) { + if (forAwait) { + this.unexpected(); + } + return this.parseFor(node, null); + } + + if (this.match(_types.types._var) || this.match(_types.types._let) || this.match(_types.types._const)) { + var _init = this.startNode(), + varKind = this.state.type; + this.next(); + this.parseVar(_init, true, varKind); + this.finishNode(_init, "VariableDeclaration"); + + if (this.match(_types.types._in) || this.isContextual("of")) { + if (_init.declarations.length === 1 && !_init.declarations[0].init) { + return this.parseForIn(node, _init, forAwait); + } + } + if (forAwait) { + this.unexpected(); + } + return this.parseFor(node, _init); + } + + var refShorthandDefaultPos = { start: 0 }; + var init = this.parseExpression(true, refShorthandDefaultPos); + if (this.match(_types.types._in) || this.isContextual("of")) { + var description = this.isContextual("of") ? "for-of statement" : "for-in statement"; + this.toAssignable(init, undefined, description); + this.checkLVal(init, undefined, undefined, description); + return this.parseForIn(node, init, forAwait); + } else if (refShorthandDefaultPos.start) { + this.unexpected(refShorthandDefaultPos.start); + } + if (forAwait) { + this.unexpected(); + } + return this.parseFor(node, init); +}; + +pp.parseFunctionStatement = function (node) { + this.next(); + return this.parseFunction(node, true); +}; + +pp.parseIfStatement = function (node) { + this.next(); + node.test = this.parseParenExpression(); + node.consequent = this.parseStatement(false); + node.alternate = this.eat(_types.types._else) ? this.parseStatement(false) : null; + return this.finishNode(node, "IfStatement"); +}; + +pp.parseReturnStatement = function (node) { + if (!this.state.inFunction && !this.options.allowReturnOutsideFunction) { + this.raise(this.state.start, "'return' outside of function"); + } + + this.next(); + + // In `return` (and `break`/`continue`), the keywords with + // optional arguments, we eagerly look for a semicolon or the + // possibility to insert one. + + if (this.isLineTerminator()) { + node.argument = null; + } else { + node.argument = this.parseExpression(); + this.semicolon(); + } + + return this.finishNode(node, "ReturnStatement"); +}; + +pp.parseSwitchStatement = function (node) { + this.next(); + node.discriminant = this.parseParenExpression(); + node.cases = []; + this.expect(_types.types.braceL); + this.state.labels.push(switchLabel); + + // Statements under must be grouped (by label) in SwitchCase + // nodes. `cur` is used to keep the node that we are currently + // adding statements to. + + var cur = void 0; + for (var sawDefault; !this.match(_types.types.braceR);) { + if (this.match(_types.types._case) || this.match(_types.types._default)) { + var isCase = this.match(_types.types._case); + if (cur) this.finishNode(cur, "SwitchCase"); + node.cases.push(cur = this.startNode()); + cur.consequent = []; + this.next(); + if (isCase) { + cur.test = this.parseExpression(); + } else { + if (sawDefault) this.raise(this.state.lastTokStart, "Multiple default clauses"); + sawDefault = true; + cur.test = null; + } + this.expect(_types.types.colon); + } else { + if (cur) { + cur.consequent.push(this.parseStatement(true)); + } else { + this.unexpected(); + } + } + } + if (cur) this.finishNode(cur, "SwitchCase"); + this.next(); // Closing brace + this.state.labels.pop(); + return this.finishNode(node, "SwitchStatement"); +}; + +pp.parseThrowStatement = function (node) { + this.next(); + if (_whitespace.lineBreak.test(this.input.slice(this.state.lastTokEnd, this.state.start))) this.raise(this.state.lastTokEnd, "Illegal newline after throw"); + node.argument = this.parseExpression(); + this.semicolon(); + return this.finishNode(node, "ThrowStatement"); +}; + +// Reused empty array added for node fields that are always empty. + +var empty = []; + +pp.parseTryStatement = function (node) { + this.next(); + + node.block = this.parseBlock(); + node.handler = null; + + if (this.match(_types.types._catch)) { + var clause = this.startNode(); + this.next(); + + this.expect(_types.types.parenL); + clause.param = this.parseBindingAtom(); + this.checkLVal(clause.param, true, Object.create(null), "catch clause"); + this.expect(_types.types.parenR); + + clause.body = this.parseBlock(); + node.handler = this.finishNode(clause, "CatchClause"); + } + + node.guardedHandlers = empty; + node.finalizer = this.eat(_types.types._finally) ? this.parseBlock() : null; + + if (!node.handler && !node.finalizer) { + this.raise(node.start, "Missing catch or finally clause"); + } + + return this.finishNode(node, "TryStatement"); +}; + +pp.parseVarStatement = function (node, kind) { + this.next(); + this.parseVar(node, false, kind); + this.semicolon(); + return this.finishNode(node, "VariableDeclaration"); +}; + +pp.parseWhileStatement = function (node) { + this.next(); + node.test = this.parseParenExpression(); + this.state.labels.push(loopLabel); + node.body = this.parseStatement(false); + this.state.labels.pop(); + return this.finishNode(node, "WhileStatement"); +}; + +pp.parseWithStatement = function (node) { + if (this.state.strict) this.raise(this.state.start, "'with' in strict mode"); + this.next(); + node.object = this.parseParenExpression(); + node.body = this.parseStatement(false); + return this.finishNode(node, "WithStatement"); +}; + +pp.parseEmptyStatement = function (node) { + this.next(); + return this.finishNode(node, "EmptyStatement"); +}; + +pp.parseLabeledStatement = function (node, maybeName, expr) { + for (var _iterator = this.state.labels, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.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 _label = _ref; + + if (_label.name === maybeName) { + this.raise(expr.start, "Label '" + maybeName + "' is already declared"); + } + } + + var kind = this.state.type.isLoop ? "loop" : this.match(_types.types._switch) ? "switch" : null; + for (var i = this.state.labels.length - 1; i >= 0; i--) { + var label = this.state.labels[i]; + if (label.statementStart === node.start) { + label.statementStart = this.state.start; + label.kind = kind; + } else { + break; + } + } + + this.state.labels.push({ name: maybeName, kind: kind, statementStart: this.state.start }); + node.body = this.parseStatement(true); + this.state.labels.pop(); + node.label = expr; + return this.finishNode(node, "LabeledStatement"); +}; + +pp.parseExpressionStatement = function (node, expr) { + node.expression = expr; + this.semicolon(); + return this.finishNode(node, "ExpressionStatement"); +}; + +// Parse a semicolon-enclosed block of statements, handling `"use +// strict"` declarations when `allowStrict` is true (used for +// function bodies). + +pp.parseBlock = function (allowDirectives) { + var node = this.startNode(); + this.expect(_types.types.braceL); + this.parseBlockBody(node, allowDirectives, false, _types.types.braceR); + return this.finishNode(node, "BlockStatement"); +}; + +// TODO + +pp.parseBlockBody = function (node, allowDirectives, topLevel, end) { + node.body = []; + node.directives = []; + + var parsedNonDirective = false; + var oldStrict = void 0; + var octalPosition = void 0; + + while (!this.eat(end)) { + if (!parsedNonDirective && this.state.containsOctal && !octalPosition) { + octalPosition = this.state.octalPosition; + } + + var stmt = this.parseStatement(true, topLevel); + + if (allowDirectives && !parsedNonDirective && stmt.type === "ExpressionStatement" && stmt.expression.type === "StringLiteral" && !stmt.expression.extra.parenthesized) { + var directive = this.stmtToDirective(stmt); + node.directives.push(directive); + + if (oldStrict === undefined && directive.value.value === "use strict") { + oldStrict = this.state.strict; + this.setStrict(true); + + if (octalPosition) { + this.raise(octalPosition, "Octal literal in strict mode"); + } + } + + continue; + } + + parsedNonDirective = true; + node.body.push(stmt); + } + + if (oldStrict === false) { + this.setStrict(false); + } +}; + +// Parse a regular `for` loop. The disambiguation code in +// `parseStatement` will already have parsed the init statement or +// expression. + +pp.parseFor = function (node, init) { + node.init = init; + this.expect(_types.types.semi); + node.test = this.match(_types.types.semi) ? null : this.parseExpression(); + this.expect(_types.types.semi); + node.update = this.match(_types.types.parenR) ? null : this.parseExpression(); + this.expect(_types.types.parenR); + node.body = this.parseStatement(false); + this.state.labels.pop(); + return this.finishNode(node, "ForStatement"); +}; + +// Parse a `for`/`in` and `for`/`of` loop, which are almost +// same from parser's perspective. + +pp.parseForIn = function (node, init, forAwait) { + var type = void 0; + if (forAwait) { + this.eatContextual("of"); + type = "ForAwaitStatement"; + } else { + type = this.match(_types.types._in) ? "ForInStatement" : "ForOfStatement"; + this.next(); + } + node.left = init; + node.right = this.parseExpression(); + this.expect(_types.types.parenR); + node.body = this.parseStatement(false); + this.state.labels.pop(); + return this.finishNode(node, type); +}; + +// Parse a list of variable declarations. + +pp.parseVar = function (node, isFor, kind) { + node.declarations = []; + node.kind = kind.keyword; + for (;;) { + var decl = this.startNode(); + this.parseVarHead(decl); + if (this.eat(_types.types.eq)) { + decl.init = this.parseMaybeAssign(isFor); + } else if (kind === _types.types._const && !(this.match(_types.types._in) || this.isContextual("of"))) { + this.unexpected(); + } else if (decl.id.type !== "Identifier" && !(isFor && (this.match(_types.types._in) || this.isContextual("of")))) { + this.raise(this.state.lastTokEnd, "Complex binding patterns require an initialization value"); + } else { + decl.init = null; + } + node.declarations.push(this.finishNode(decl, "VariableDeclarator")); + if (!this.eat(_types.types.comma)) break; + } + return node; +}; + +pp.parseVarHead = function (decl) { + decl.id = this.parseBindingAtom(); + this.checkLVal(decl.id, true, undefined, "variable declaration"); +}; + +// Parse a function declaration or literal (depending on the +// `isStatement` parameter). + +pp.parseFunction = function (node, isStatement, allowExpressionBody, isAsync, optionalId) { + var oldInMethod = this.state.inMethod; + this.state.inMethod = false; + + this.initFunction(node, isAsync); + + if (this.match(_types.types.star)) { + if (node.async && !this.hasPlugin("asyncGenerators")) { + this.unexpected(); + } else { + node.generator = true; + this.next(); + } + } + + if (isStatement && !optionalId && !this.match(_types.types.name) && !this.match(_types.types._yield)) { + this.unexpected(); + } + + if (this.match(_types.types.name) || this.match(_types.types._yield)) { + node.id = this.parseBindingIdentifier(); + } + + this.parseFunctionParams(node); + this.parseFunctionBody(node, allowExpressionBody); + + this.state.inMethod = oldInMethod; + + return this.finishNode(node, isStatement ? "FunctionDeclaration" : "FunctionExpression"); +}; + +pp.parseFunctionParams = function (node) { + this.expect(_types.types.parenL); + node.params = this.parseBindingList(_types.types.parenR); +}; + +// Parse a class declaration or literal (depending on the +// `isStatement` parameter). + +pp.parseClass = function (node, isStatement, optionalId) { + this.next(); + this.parseClassId(node, isStatement, optionalId); + this.parseClassSuper(node); + this.parseClassBody(node); + return this.finishNode(node, isStatement ? "ClassDeclaration" : "ClassExpression"); +}; + +pp.isClassProperty = function () { + return this.match(_types.types.eq) || this.isLineTerminator(); +}; + +pp.isClassMutatorStarter = function () { + return false; +}; + +pp.parseClassBody = function (node) { + // class bodies are implicitly strict + var oldStrict = this.state.strict; + this.state.strict = true; + + var hadConstructorCall = false; + var hadConstructor = false; + var decorators = []; + var classBody = this.startNode(); + + classBody.body = []; + + this.expect(_types.types.braceL); + + while (!this.eat(_types.types.braceR)) { + if (this.eat(_types.types.semi)) { + continue; + } + + if (this.match(_types.types.at)) { + decorators.push(this.parseDecorator()); + continue; + } + + var method = this.startNode(); + + // steal the decorators if there are any + if (decorators.length) { + method.decorators = decorators; + decorators = []; + } + + var isConstructorCall = false; + var isMaybeStatic = this.match(_types.types.name) && this.state.value === "static"; + var isGenerator = this.eat(_types.types.star); + var isGetSet = false; + var isAsync = false; + + this.parsePropertyName(method); + + method.static = isMaybeStatic && !this.match(_types.types.parenL); + if (method.static) { + if (isGenerator) this.unexpected(); + isGenerator = this.eat(_types.types.star); + this.parsePropertyName(method); + } + + if (!isGenerator) { + if (this.isClassProperty()) { + classBody.body.push(this.parseClassProperty(method)); + continue; + } + + if (method.key.type === "Identifier" && !method.computed && this.hasPlugin("classConstructorCall") && method.key.name === "call" && this.match(_types.types.name) && this.state.value === "constructor") { + isConstructorCall = true; + this.parsePropertyName(method); + } + } + + var isAsyncMethod = !this.match(_types.types.parenL) && !method.computed && method.key.type === "Identifier" && method.key.name === "async"; + if (isAsyncMethod) { + if (this.hasPlugin("asyncGenerators") && this.eat(_types.types.star)) isGenerator = true; + isAsync = true; + this.parsePropertyName(method); + } + + method.kind = "method"; + + if (!method.computed) { + var key = method.key; + + // handle get/set methods + // eg. class Foo { get bar() {} set bar() {} } + + if (!isAsync && !isGenerator && !this.isClassMutatorStarter() && key.type === "Identifier" && !this.match(_types.types.parenL) && (key.name === "get" || key.name === "set")) { + isGetSet = true; + method.kind = key.name; + key = this.parsePropertyName(method); + } + + // disallow invalid constructors + var isConstructor = !isConstructorCall && !method.static && (key.type === "Identifier" && key.name === "constructor" || key.type === "StringLiteral" && key.value === "constructor"); + if (isConstructor) { + if (hadConstructor) this.raise(key.start, "Duplicate constructor in the same class"); + if (isGetSet) this.raise(key.start, "Constructor can't have get/set modifier"); + if (isGenerator) this.raise(key.start, "Constructor can't be a generator"); + if (isAsync) this.raise(key.start, "Constructor can't be an async function"); + method.kind = "constructor"; + hadConstructor = true; + } + + // disallow static prototype method + var isStaticPrototype = method.static && (key.type === "Identifier" && key.name === "prototype" || key.type === "StringLiteral" && key.value === "prototype"); + if (isStaticPrototype) { + this.raise(key.start, "Classes may not have static property named prototype"); + } + } + + // convert constructor to a constructor call + if (isConstructorCall) { + if (hadConstructorCall) this.raise(method.start, "Duplicate constructor call in the same class"); + method.kind = "constructorCall"; + hadConstructorCall = true; + } + + // disallow decorators on class constructors + if ((method.kind === "constructor" || method.kind === "constructorCall") && method.decorators) { + this.raise(method.start, "You can't attach decorators to a class constructor"); + } + + this.parseClassMethod(classBody, method, isGenerator, isAsync); + + // get methods aren't allowed to have any parameters + // set methods must have exactly 1 parameter + if (isGetSet) { + var paramCount = method.kind === "get" ? 0 : 1; + if (method.params.length !== paramCount) { + var start = method.start; + if (method.kind === "get") { + this.raise(start, "getter should have no params"); + } else { + this.raise(start, "setter should have exactly one param"); + } + } + } + } + + if (decorators.length) { + this.raise(this.state.start, "You have trailing decorators with no method"); + } + + node.body = this.finishNode(classBody, "ClassBody"); + + this.state.strict = oldStrict; +}; + +pp.parseClassProperty = function (node) { + if (this.match(_types.types.eq)) { + if (!this.hasPlugin("classProperties")) this.unexpected(); + this.next(); + node.value = this.parseMaybeAssign(); + } else { + node.value = null; + } + this.semicolon(); + return this.finishNode(node, "ClassProperty"); +}; + +pp.parseClassMethod = function (classBody, method, isGenerator, isAsync) { + this.parseMethod(method, isGenerator, isAsync); + classBody.body.push(this.finishNode(method, "ClassMethod")); +}; + +pp.parseClassId = function (node, isStatement, optionalId) { + if (this.match(_types.types.name)) { + node.id = this.parseIdentifier(); + } else { + if (optionalId || !isStatement) { + node.id = null; + } else { + this.unexpected(); + } + } +}; + +pp.parseClassSuper = function (node) { + node.superClass = this.eat(_types.types._extends) ? this.parseExprSubscripts() : null; +}; + +// Parses module export declaration. + +pp.parseExport = function (node) { + this.next(); + // export * from '...' + if (this.match(_types.types.star)) { + var specifier = this.startNode(); + this.next(); + if (this.hasPlugin("exportExtensions") && this.eatContextual("as")) { + specifier.exported = this.parseIdentifier(); + node.specifiers = [this.finishNode(specifier, "ExportNamespaceSpecifier")]; + this.parseExportSpecifiersMaybe(node); + this.parseExportFrom(node, true); + } else { + this.parseExportFrom(node, true); + return this.finishNode(node, "ExportAllDeclaration"); + } + } else if (this.hasPlugin("exportExtensions") && this.isExportDefaultSpecifier()) { + var _specifier = this.startNode(); + _specifier.exported = this.parseIdentifier(true); + node.specifiers = [this.finishNode(_specifier, "ExportDefaultSpecifier")]; + if (this.match(_types.types.comma) && this.lookahead().type === _types.types.star) { + this.expect(_types.types.comma); + var _specifier2 = this.startNode(); + this.expect(_types.types.star); + this.expectContextual("as"); + _specifier2.exported = this.parseIdentifier(); + node.specifiers.push(this.finishNode(_specifier2, "ExportNamespaceSpecifier")); + } else { + this.parseExportSpecifiersMaybe(node); + } + this.parseExportFrom(node, true); + } else if (this.eat(_types.types._default)) { + // export default ... + var expr = this.startNode(); + var needsSemi = false; + if (this.eat(_types.types._function)) { + expr = this.parseFunction(expr, true, false, false, true); + } else if (this.match(_types.types._class)) { + expr = this.parseClass(expr, true, true); + } else { + needsSemi = true; + expr = this.parseMaybeAssign(); + } + node.declaration = expr; + if (needsSemi) this.semicolon(); + this.checkExport(node, true, true); + return this.finishNode(node, "ExportDefaultDeclaration"); + } else if (this.state.type.keyword || this.shouldParseExportDeclaration()) { + node.specifiers = []; + node.source = null; + node.declaration = this.parseExportDeclaration(node); + } else { + // export { x, y as z } [from '...'] + node.declaration = null; + node.specifiers = this.parseExportSpecifiers(); + this.parseExportFrom(node); + } + this.checkExport(node, true); + return this.finishNode(node, "ExportNamedDeclaration"); +}; + +pp.parseExportDeclaration = function () { + return this.parseStatement(true); +}; + +pp.isExportDefaultSpecifier = function () { + if (this.match(_types.types.name)) { + return this.state.value !== "type" && this.state.value !== "async" && this.state.value !== "interface"; + } + + if (!this.match(_types.types._default)) { + return false; + } + + var lookahead = this.lookahead(); + return lookahead.type === _types.types.comma || lookahead.type === _types.types.name && lookahead.value === "from"; +}; + +pp.parseExportSpecifiersMaybe = function (node) { + if (this.eat(_types.types.comma)) { + node.specifiers = node.specifiers.concat(this.parseExportSpecifiers()); + } +}; + +pp.parseExportFrom = function (node, expect) { + if (this.eatContextual("from")) { + node.source = this.match(_types.types.string) ? this.parseExprAtom() : this.unexpected(); + this.checkExport(node); + } else { + if (expect) { + this.unexpected(); + } else { + node.source = null; + } + } + + this.semicolon(); +}; + +pp.shouldParseExportDeclaration = function () { + return this.isContextual("async"); +}; + +pp.checkExport = function (node, checkNames, isDefault) { + if (checkNames) { + // Check for duplicate exports + if (isDefault) { + // Default exports + this.checkDuplicateExports(node, "default", isDefault); + } else if (node.specifiers && node.specifiers.length) { + // Named exports + for (var _iterator2 = node.specifiers, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : _iterator2[Symbol.iterator]();;) { + var _ref2; + + if (_isArray2) { + if (_i2 >= _iterator2.length) break; + _ref2 = _iterator2[_i2++]; + } else { + _i2 = _iterator2.next(); + if (_i2.done) break; + _ref2 = _i2.value; + } + + var specifier = _ref2; + + var name = specifier.exported.name; + if (name === "default") isDefault = true; + this.checkDuplicateExports(specifier, name, isDefault); + } + } else if (node.declaration) { + // Exported declarations + if (node.declaration.type === "FunctionDeclaration" || node.declaration.type === "ClassDeclaration") { + this.checkDuplicateExports(node, node.declaration.id.name, isDefault); + } else if (node.declaration.type === "VariableDeclaration") { + for (var _iterator3 = node.declaration.declarations, _isArray3 = Array.isArray(_iterator3), _i3 = 0, _iterator3 = _isArray3 ? _iterator3 : _iterator3[Symbol.iterator]();;) { + var _ref3; + + if (_isArray3) { + if (_i3 >= _iterator3.length) break; + _ref3 = _iterator3[_i3++]; + } else { + _i3 = _iterator3.next(); + if (_i3.done) break; + _ref3 = _i3.value; + } + + var declaration = _ref3; + + if (declaration.id.name) { + this.checkDuplicateExports(declaration, declaration.id.name, isDefault); + } + } + } + } + } + + if (this.state.decorators.length) { + var isClass = node.declaration && (node.declaration.type === "ClassDeclaration" || node.declaration.type === "ClassExpression"); + if (!node.declaration || !isClass) { + this.raise(node.start, "You can only use decorators on an export when exporting a class"); + } + this.takeDecorators(node.declaration); + } +}; + +pp.checkDuplicateExports = function (node, name, isDefault) { + if (this.state.exportedIdentifiers.indexOf(name) > -1) { + this.raiseDuplicateExportError(node, name, isDefault); + } + this.state.exportedIdentifiers.push(name); +}; + +pp.raiseDuplicateExportError = function (node, name, isDefault) { + this.raise(node.start, isDefault ? "Only one default export allowed per module." : "`" + name + "` has already been exported. Exported identifiers must be unique."); +}; + +// Parses a comma-separated list of module exports. + +pp.parseExportSpecifiers = function () { + var nodes = []; + var first = true; + var needsFrom = void 0; + + // export { x, y as z } [from '...'] + this.expect(_types.types.braceL); + + while (!this.eat(_types.types.braceR)) { + if (first) { + first = false; + } else { + this.expect(_types.types.comma); + if (this.eat(_types.types.braceR)) break; + } + + var isDefault = this.match(_types.types._default); + if (isDefault && !needsFrom) needsFrom = true; + + var node = this.startNode(); + node.local = this.parseIdentifier(isDefault); + node.exported = this.eatContextual("as") ? this.parseIdentifier(true) : node.local.__clone(); + nodes.push(this.finishNode(node, "ExportSpecifier")); + } + + // https://github.com/ember-cli/ember-cli/pull/3739 + if (needsFrom && !this.isContextual("from")) { + this.unexpected(); + } + + return nodes; +}; + +// Parses import declaration. + +pp.parseImport = function (node) { + this.next(); + + // import '...' + if (this.match(_types.types.string)) { + node.specifiers = []; + node.source = this.parseExprAtom(); + } else { + node.specifiers = []; + this.parseImportSpecifiers(node); + this.expectContextual("from"); + node.source = this.match(_types.types.string) ? this.parseExprAtom() : this.unexpected(); + } + this.semicolon(); + return this.finishNode(node, "ImportDeclaration"); +}; + +// Parses a comma-separated list of module imports. + +pp.parseImportSpecifiers = function (node) { + var first = true; + if (this.match(_types.types.name)) { + // import defaultObj, { x, y as z } from '...' + var startPos = this.state.start, + startLoc = this.state.startLoc; + node.specifiers.push(this.parseImportSpecifierDefault(this.parseIdentifier(), startPos, startLoc)); + if (!this.eat(_types.types.comma)) return; + } + + if (this.match(_types.types.star)) { + var specifier = this.startNode(); + this.next(); + this.expectContextual("as"); + specifier.local = this.parseIdentifier(); + this.checkLVal(specifier.local, true, undefined, "import namespace specifier"); + node.specifiers.push(this.finishNode(specifier, "ImportNamespaceSpecifier")); + return; + } + + this.expect(_types.types.braceL); + while (!this.eat(_types.types.braceR)) { + if (first) { + first = false; + } else { + this.expect(_types.types.comma); + if (this.eat(_types.types.braceR)) break; + } + + var _specifier3 = this.startNode(); + _specifier3.imported = this.parseIdentifier(true); + _specifier3.local = this.eatContextual("as") ? this.parseIdentifier() : _specifier3.imported.__clone(); + this.checkLVal(_specifier3.local, true, undefined, "import specifier"); + node.specifiers.push(this.finishNode(_specifier3, "ImportSpecifier")); + } +}; + +pp.parseImportSpecifierDefault = function (id, startPos, startLoc) { + var node = this.startNodeAt(startPos, startLoc); + node.local = id; + this.checkLVal(node.local, true, undefined, "default import specifier"); + return this.finishNode(node, "ImportDefaultSpecifier"); +}; +},{"../tokenizer/types":213,"../util/whitespace":216,"./index":201}],206:[function(require,module,exports){ +"use strict"; + +var _types = require("../tokenizer/types"); + +var _index = require("./index"); + +var _index2 = _interopRequireDefault(_index); + +var _whitespace = require("../util/whitespace"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var pp = _index2.default.prototype; + +// ## Parser utilities + +// TODO + +pp.addExtra = function (node, key, val) { + if (!node) return; + + var extra = node.extra = node.extra || {}; + extra[key] = val; +}; + +// TODO + +pp.isRelational = function (op) { + return this.match(_types.types.relational) && this.state.value === op; +}; + +// TODO + +pp.expectRelational = function (op) { + if (this.isRelational(op)) { + this.next(); + } else { + this.unexpected(); + } +}; + +// Tests whether parsed token is a contextual keyword. + +pp.isContextual = function (name) { + return this.match(_types.types.name) && this.state.value === name; +}; + +// Consumes contextual keyword if possible. + +pp.eatContextual = function (name) { + return this.state.value === name && this.eat(_types.types.name); +}; + +// Asserts that following token is given contextual keyword. + +pp.expectContextual = function (name, message) { + if (!this.eatContextual(name)) this.unexpected(null, message); +}; + +// Test whether a semicolon can be inserted at the current position. + +pp.canInsertSemicolon = function () { + return this.match(_types.types.eof) || this.match(_types.types.braceR) || _whitespace.lineBreak.test(this.input.slice(this.state.lastTokEnd, this.state.start)); +}; + +// TODO + +pp.isLineTerminator = function () { + return this.eat(_types.types.semi) || this.canInsertSemicolon(); +}; + +// Consume a semicolon, or, failing that, see if we are allowed to +// pretend that there is a semicolon at this position. + +pp.semicolon = function () { + if (!this.isLineTerminator()) this.unexpected(); +}; + +// Expect a token of a given type. If found, consume it, otherwise, +// raise an unexpected token error at given pos. + +pp.expect = function (type, pos) { + return this.eat(type) || this.unexpected(pos); +}; + +// Raise an unexpected token error. + +pp.unexpected = function (pos) { + var message = arguments.length <= 1 || arguments[1] === undefined ? "Unexpected token" : arguments[1]; + + this.raise(pos != null ? pos : this.state.start, message); +}; +},{"../tokenizer/types":213,"../util/whitespace":216,"./index":201}],207:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +exports.default = function (instance) { + // plain function return types: function name(): string {} + instance.extend("parseFunctionBody", function (inner) { + return function (node, allowExpression) { + if (this.match(_types.types.colon) && !allowExpression) { + // if allowExpression is true then we're parsing an arrow function and if + // there's a return type then it's been handled elsewhere + node.returnType = this.flowParseTypeAnnotation(); + } + + return inner.call(this, node, allowExpression); + }; + }); + + // interfaces + instance.extend("parseStatement", function (inner) { + return function (declaration, topLevel) { + // strict mode handling of `interface` since it's a reserved word + if (this.state.strict && this.match(_types.types.name) && this.state.value === "interface") { + var node = this.startNode(); + this.next(); + return this.flowParseInterface(node); + } else { + return inner.call(this, declaration, topLevel); + } + }; + }); + + // declares, interfaces and type aliases + instance.extend("parseExpressionStatement", function (inner) { + return function (node, expr) { + if (expr.type === "Identifier") { + if (expr.name === "declare") { + if (this.match(_types.types._class) || this.match(_types.types.name) || this.match(_types.types._function) || this.match(_types.types._var)) { + return this.flowParseDeclare(node); + } + } else if (this.match(_types.types.name)) { + if (expr.name === "interface") { + return this.flowParseInterface(node); + } else if (expr.name === "type") { + return this.flowParseTypeAlias(node); + } + } + } + + return inner.call(this, node, expr); + }; + }); + + // export type + instance.extend("shouldParseExportDeclaration", function (inner) { + return function () { + return this.isContextual("type") || this.isContextual("interface") || inner.call(this); + }; + }); + + instance.extend("parseConditional", function (inner) { + return function (expr, noIn, startPos, startLoc, refNeedsArrowPos) { + // only do the expensive clone if there is a question mark + // and if we come from inside parens + if (refNeedsArrowPos && this.match(_types.types.question)) { + var state = this.state.clone(); + try { + return inner.call(this, expr, noIn, startPos, startLoc); + } catch (err) { + if (err instanceof SyntaxError) { + this.state = state; + refNeedsArrowPos.start = err.pos || this.state.start; + return expr; + } else { + throw err; + } + } + } + + return inner.call(this, expr, noIn, startPos, startLoc); + }; + }); + + instance.extend("parseParenItem", function (inner) { + return function (node, startLoc, startPos) { + node = inner.call(this, node, startLoc, startPos); + if (this.eat(_types.types.question)) { + node.optional = true; + } + + if (this.match(_types.types.colon)) { + var typeCastNode = this.startNodeAt(startLoc, startPos); + typeCastNode.expression = node; + typeCastNode.typeAnnotation = this.flowParseTypeAnnotation(); + + return this.finishNode(typeCastNode, "TypeCastExpression"); + } + + return node; + }; + }); + + instance.extend("parseExport", function (inner) { + return function (node) { + node = inner.call(this, node); + if (node.type === "ExportNamedDeclaration") { + node.exportKind = node.exportKind || "value"; + } + return node; + }; + }); + + instance.extend("parseExportDeclaration", function (inner) { + return function (node) { + if (this.isContextual("type")) { + node.exportKind = "type"; + + var declarationNode = this.startNode(); + this.next(); + + if (this.match(_types.types.braceL)) { + // export type { foo, bar }; + node.specifiers = this.parseExportSpecifiers(); + this.parseExportFrom(node); + return null; + } else { + // export type Foo = Bar; + return this.flowParseTypeAlias(declarationNode); + } + } else if (this.isContextual("interface")) { + node.exportKind = "type"; + var _declarationNode = this.startNode(); + this.next(); + return this.flowParseInterface(_declarationNode); + } else { + return inner.call(this, node); + } + }; + }); + + instance.extend("parseClassId", function (inner) { + return function (node) { + inner.apply(this, arguments); + if (this.isRelational("<")) { + node.typeParameters = this.flowParseTypeParameterDeclaration(); + } + }; + }); + + // don't consider `void` to be a keyword as then it'll use the void token type + // and set startExpr + instance.extend("isKeyword", function (inner) { + return function (name) { + if (this.state.inType && name === "void") { + return false; + } else { + return inner.call(this, name); + } + }; + }); + + // ensure that inside flow types, we bypass the jsx parser plugin + instance.extend("readToken", function (inner) { + return function (code) { + if (this.state.inType && (code === 62 || code === 60)) { + return this.finishOp(_types.types.relational, 1); + } else { + return inner.call(this, code); + } + }; + }); + + // don't lex any token as a jsx one inside a flow type + instance.extend("jsx_readToken", function (inner) { + return function () { + if (!this.state.inType) return inner.call(this); + }; + }); + + instance.extend("toAssignable", function (inner) { + return function (node, isBinding, contextDescription) { + if (node.type === "TypeCastExpression") { + return inner.call(this, this.typeCastToParameter(node), isBinding, contextDescription); + } else { + return inner.call(this, node, isBinding, contextDescription); + } + }; + }); + + // turn type casts that we found in function parameter head into type annotated params + instance.extend("toAssignableList", function (inner) { + return function (exprList, isBinding, contextDescription) { + for (var i = 0; i < exprList.length; i++) { + var expr = exprList[i]; + if (expr && expr.type === "TypeCastExpression") { + exprList[i] = this.typeCastToParameter(expr); + } + } + return inner.call(this, exprList, isBinding, contextDescription); + }; + }); + + // this is a list of nodes, from something like a call expression, we need to filter the + // type casts that we've found that are illegal in this context + instance.extend("toReferencedList", function () { + return function (exprList) { + for (var i = 0; i < exprList.length; i++) { + var expr = exprList[i]; + if (expr && expr._exprListItem && expr.type === "TypeCastExpression") { + this.raise(expr.start, "Unexpected type cast"); + } + } + + return exprList; + }; + }); + + // parse an item inside a expression list eg. `(NODE, NODE)` where NODE represents + // the position where this function is called + instance.extend("parseExprListItem", function (inner) { + return function (allowEmpty, refShorthandDefaultPos) { + var container = this.startNode(); + var node = inner.call(this, allowEmpty, refShorthandDefaultPos); + if (this.match(_types.types.colon)) { + container._exprListItem = true; + container.expression = node; + container.typeAnnotation = this.flowParseTypeAnnotation(); + return this.finishNode(container, "TypeCastExpression"); + } else { + return node; + } + }; + }); + + instance.extend("checkLVal", function (inner) { + return function (node) { + if (node.type !== "TypeCastExpression") { + return inner.apply(this, arguments); + } + }; + }); + + // parse class property type annotations + instance.extend("parseClassProperty", function (inner) { + return function (node) { + if (this.match(_types.types.colon)) { + node.typeAnnotation = this.flowParseTypeAnnotation(); + } + return inner.call(this, node); + }; + }); + + // determine whether or not we're currently in the position where a class property would appear + instance.extend("isClassProperty", function (inner) { + return function () { + return this.match(_types.types.colon) || inner.call(this); + }; + }); + + // parse type parameters for class methods + instance.extend("parseClassMethod", function () { + return function (classBody, method, isGenerator, isAsync) { + if (this.isRelational("<")) { + method.typeParameters = this.flowParseTypeParameterDeclaration(); + } + this.parseMethod(method, isGenerator, isAsync); + classBody.body.push(this.finishNode(method, "ClassMethod")); + }; + }); + + // parse a the super class type parameters and implements + instance.extend("parseClassSuper", function (inner) { + return function (node, isStatement) { + inner.call(this, node, isStatement); + if (node.superClass && this.isRelational("<")) { + node.superTypeParameters = this.flowParseTypeParameterInstantiation(); + } + if (this.isContextual("implements")) { + this.next(); + var implemented = node.implements = []; + do { + var _node = this.startNode(); + _node.id = this.parseIdentifier(); + if (this.isRelational("<")) { + _node.typeParameters = this.flowParseTypeParameterInstantiation(); + } else { + _node.typeParameters = null; + } + implemented.push(this.finishNode(_node, "ClassImplements")); + } while (this.eat(_types.types.comma)); + } + }; + }); + + // parse type parameters for object method shorthand + instance.extend("parseObjPropValue", function (inner) { + return function (prop) { + var typeParameters = void 0; + + // method shorthand + if (this.isRelational("<")) { + typeParameters = this.flowParseTypeParameterDeclaration(); + if (!this.match(_types.types.parenL)) this.unexpected(); + } + + inner.apply(this, arguments); + + // add typeParameters if we found them + if (typeParameters) { + (prop.value || prop).typeParameters = typeParameters; + } + }; + }); + + instance.extend("parseAssignableListItemTypes", function () { + return function (param) { + if (this.eat(_types.types.question)) { + param.optional = true; + } + if (this.match(_types.types.colon)) { + param.typeAnnotation = this.flowParseTypeAnnotation(); + } + this.finishNode(param, param.type); + return param; + }; + }); + + instance.extend("parseMaybeDefault", function (inner) { + return function () { + for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + + var node = inner.apply(this, args); + + if (node.type === "AssignmentPattern" && node.typeAnnotation && node.right.start < node.typeAnnotation.start) { + this.raise(node.typeAnnotation.start, "Type annotations must come before default assignments, e.g. instead of `age = 25: number` use `age: number = 25`"); + } + + return node; + }; + }); + + // parse typeof and type imports + instance.extend("parseImportSpecifiers", function (inner) { + return function (node) { + node.importKind = "value"; + + var kind = null; + if (this.match(_types.types._typeof)) { + kind = "typeof"; + } else if (this.isContextual("type")) { + kind = "type"; + } + if (kind) { + var lh = this.lookahead(); + if (lh.type === _types.types.name && lh.value !== "from" || lh.type === _types.types.braceL || lh.type === _types.types.star) { + this.next(); + node.importKind = kind; + } + } + + inner.call(this, node); + }; + }); + + // parse function type parameters - function foo() {} + instance.extend("parseFunctionParams", function (inner) { + return function (node) { + if (this.isRelational("<")) { + node.typeParameters = this.flowParseTypeParameterDeclaration(); + } + inner.call(this, node); + }; + }); + + // parse flow type annotations on variable declarator heads - let foo: string = bar + instance.extend("parseVarHead", function (inner) { + return function (decl) { + inner.call(this, decl); + if (this.match(_types.types.colon)) { + decl.id.typeAnnotation = this.flowParseTypeAnnotation(); + this.finishNode(decl.id, decl.id.type); + } + }; + }); + + // parse the return type of an async arrow function - let foo = (async (): number => {}); + instance.extend("parseAsyncArrowFromCallExpression", function (inner) { + return function (node, call) { + if (this.match(_types.types.colon)) { + node.returnType = this.flowParseTypeAnnotation(); + } + + return inner.call(this, node, call); + }; + }); + + // todo description + instance.extend("shouldParseAsyncArrow", function (inner) { + return function () { + return this.match(_types.types.colon) || inner.call(this); + }; + }); + + // We need to support type parameter declarations for arrow functions. This + // is tricky. There are three situations we need to handle + // + // 1. This is either JSX or an arrow function. We'll try JSX first. If that + // fails, we'll try an arrow function. If that fails, we'll throw the JSX + // error. + // 2. This is an arrow function. We'll parse the type parameter declaration, + // parse the rest, make sure the rest is an arrow function, and go from + // there + // 3. This is neither. Just call the inner function + instance.extend("parseMaybeAssign", function (inner) { + return function () { + var jsxError = null; + + for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { + args[_key2] = arguments[_key2]; + } + + if (_types.types.jsxTagStart && this.match(_types.types.jsxTagStart)) { + var state = this.state.clone(); + try { + return inner.apply(this, args); + } catch (err) { + if (err instanceof SyntaxError) { + this.state = state; + jsxError = err; + } else { + throw err; + } + } + } + + // Need to push something onto the context to stop + // the JSX plugin from messing with the tokens + this.state.context.push(_context.types.parenExpression); + if (jsxError != null || this.isRelational("<")) { + var arrowExpression = void 0; + var typeParameters = void 0; + try { + typeParameters = this.flowParseTypeParameterDeclaration(); + + arrowExpression = inner.apply(this, args); + arrowExpression.typeParameters = typeParameters; + arrowExpression.start = typeParameters.start; + arrowExpression.loc.start = typeParameters.loc.start; + } catch (err) { + throw jsxError || err; + } + + if (arrowExpression.type === "ArrowFunctionExpression") { + return arrowExpression; + } else if (jsxError != null) { + throw jsxError; + } else { + this.raise(typeParameters.start, "Expected an arrow function after this type parameter declaration"); + } + } + this.state.context.pop(); + + return inner.apply(this, args); + }; + }); + + // handle return types for arrow functions + instance.extend("parseArrow", function (inner) { + return function (node) { + if (this.match(_types.types.colon)) { + var state = this.state.clone(); + try { + var returnType = this.flowParseTypeAnnotation(); + if (this.canInsertSemicolon()) this.unexpected(); + if (!this.match(_types.types.arrow)) this.unexpected(); + // assign after it is clear it is an arrow + node.returnType = returnType; + } catch (err) { + if (err instanceof SyntaxError) { + this.state = state; + } else { + throw err; + } + } + } + + return inner.call(this, node); + }; + }); + + instance.extend("shouldParseArrow", function (inner) { + return function () { + return this.match(_types.types.colon) || inner.call(this); + }; + }); + + instance.extend("isClassMutatorStarter", function (inner) { + return function () { + if (this.isRelational("<")) { + return true; + } else { + return inner.call(this); + } + }; + }); +}; + +var _types = require("../tokenizer/types"); + +var _context = require("../tokenizer/context"); + +var _parser = require("../parser"); + +var _parser2 = _interopRequireDefault(_parser); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +var pp = _parser2.default.prototype; /* eslint indent: 0 */ +/* eslint max-len: 0 */ + +pp.flowParseTypeInitialiser = function (tok, allowLeadingPipeOrAnd) { + var oldInType = this.state.inType; + this.state.inType = true; + this.expect(tok || _types.types.colon); + if (allowLeadingPipeOrAnd) { + if (this.match(_types.types.bitwiseAND) || this.match(_types.types.bitwiseOR)) { + this.next(); + } + } + var type = this.flowParseType(); + this.state.inType = oldInType; + return type; +}; + +pp.flowParseDeclareClass = function (node) { + this.next(); + this.flowParseInterfaceish(node, true); + return this.finishNode(node, "DeclareClass"); +}; + +pp.flowParseDeclareFunction = function (node) { + this.next(); + + var id = node.id = this.parseIdentifier(); + + var typeNode = this.startNode(); + var typeContainer = this.startNode(); + + if (this.isRelational("<")) { + typeNode.typeParameters = this.flowParseTypeParameterDeclaration(); + } else { + typeNode.typeParameters = null; + } + + this.expect(_types.types.parenL); + var tmp = this.flowParseFunctionTypeParams(); + typeNode.params = tmp.params; + typeNode.rest = tmp.rest; + this.expect(_types.types.parenR); + typeNode.returnType = this.flowParseTypeInitialiser(); + + typeContainer.typeAnnotation = this.finishNode(typeNode, "FunctionTypeAnnotation"); + id.typeAnnotation = this.finishNode(typeContainer, "TypeAnnotation"); + + this.finishNode(id, id.type); + + this.semicolon(); + + return this.finishNode(node, "DeclareFunction"); +}; + +pp.flowParseDeclare = function (node) { + if (this.match(_types.types._class)) { + return this.flowParseDeclareClass(node); + } else if (this.match(_types.types._function)) { + return this.flowParseDeclareFunction(node); + } else if (this.match(_types.types._var)) { + return this.flowParseDeclareVariable(node); + } else if (this.isContextual("module")) { + if (this.lookahead().type === _types.types.dot) { + return this.flowParseDeclareModuleExports(node); + } else { + return this.flowParseDeclareModule(node); + } + } else if (this.isContextual("type")) { + return this.flowParseDeclareTypeAlias(node); + } else if (this.isContextual("interface")) { + return this.flowParseDeclareInterface(node); + } else { + this.unexpected(); + } +}; + +pp.flowParseDeclareVariable = function (node) { + this.next(); + node.id = this.flowParseTypeAnnotatableIdentifier(); + this.semicolon(); + return this.finishNode(node, "DeclareVariable"); +}; + +pp.flowParseDeclareModule = function (node) { + this.next(); + + if (this.match(_types.types.string)) { + node.id = this.parseExprAtom(); + } else { + node.id = this.parseIdentifier(); + } + + var bodyNode = node.body = this.startNode(); + var body = bodyNode.body = []; + this.expect(_types.types.braceL); + while (!this.match(_types.types.braceR)) { + var node2 = this.startNode(); + + this.expectContextual("declare", "Unexpected token. Only declares are allowed inside declare module"); + + body.push(this.flowParseDeclare(node2)); + } + this.expect(_types.types.braceR); + + this.finishNode(bodyNode, "BlockStatement"); + return this.finishNode(node, "DeclareModule"); +}; + +pp.flowParseDeclareModuleExports = function (node) { + this.expectContextual("module"); + this.expect(_types.types.dot); + this.expectContextual("exports"); + node.typeAnnotation = this.flowParseTypeAnnotation(); + return this.finishNode(node, "DeclareModuleExports"); +}; + +pp.flowParseDeclareTypeAlias = function (node) { + this.next(); + this.flowParseTypeAlias(node); + return this.finishNode(node, "DeclareTypeAlias"); +}; + +pp.flowParseDeclareInterface = function (node) { + this.next(); + this.flowParseInterfaceish(node); + return this.finishNode(node, "DeclareInterface"); +}; + +// Interfaces + +pp.flowParseInterfaceish = function (node, allowStatic) { + node.id = this.parseIdentifier(); + + if (this.isRelational("<")) { + node.typeParameters = this.flowParseTypeParameterDeclaration(); + } else { + node.typeParameters = null; + } + + node.extends = []; + node.mixins = []; + + if (this.eat(_types.types._extends)) { + do { + node.extends.push(this.flowParseInterfaceExtends()); + } while (this.eat(_types.types.comma)); + } + + if (this.isContextual("mixins")) { + this.next(); + do { + node.mixins.push(this.flowParseInterfaceExtends()); + } while (this.eat(_types.types.comma)); + } + + node.body = this.flowParseObjectType(allowStatic); +}; + +pp.flowParseInterfaceExtends = function () { + var node = this.startNode(); + + node.id = this.flowParseQualifiedTypeIdentifier(); + if (this.isRelational("<")) { + node.typeParameters = this.flowParseTypeParameterInstantiation(); + } else { + node.typeParameters = null; + } + + return this.finishNode(node, "InterfaceExtends"); +}; + +pp.flowParseInterface = function (node) { + this.flowParseInterfaceish(node, false); + return this.finishNode(node, "InterfaceDeclaration"); +}; + +// Type aliases + +pp.flowParseTypeAlias = function (node) { + node.id = this.parseIdentifier(); + + if (this.isRelational("<")) { + node.typeParameters = this.flowParseTypeParameterDeclaration(); + } else { + node.typeParameters = null; + } + + node.right = this.flowParseTypeInitialiser(_types.types.eq, + /*allowLeadingPipeOrAnd*/true); + this.semicolon(); + + return this.finishNode(node, "TypeAlias"); +}; + +// Type annotations + +pp.flowParseTypeParameter = function () { + var node = this.startNode(); + + var variance = void 0; + if (this.match(_types.types.plusMin)) { + if (this.state.value === "+") { + variance = "plus"; + } else if (this.state.value === "-") { + variance = "minus"; + } + this.eat(_types.types.plusMin); + } + + var ident = this.flowParseTypeAnnotatableIdentifier(false, false); + node.name = ident.name; + node.variance = variance; + node.bound = ident.typeAnnotation; + + if (this.match(_types.types.eq)) { + this.eat(_types.types.eq); + node.default = this.flowParseType(); + } + + return this.finishNode(node, "TypeParameter"); +}; + +pp.flowParseTypeParameterDeclaration = function () { + var oldInType = this.state.inType; + var node = this.startNode(); + node.params = []; + + this.state.inType = true; + + if (this.isRelational("<") || this.match(_types.types.jsxTagStart)) { + this.next(); + } else { + this.unexpected(); + } + + do { + node.params.push(this.flowParseTypeParameter()); + if (!this.isRelational(">")) { + this.expect(_types.types.comma); + } + } while (!this.isRelational(">")); + this.expectRelational(">"); + + this.state.inType = oldInType; + + return this.finishNode(node, "TypeParameterDeclaration"); +}; + +pp.flowParseTypeParameterInstantiation = function () { + var node = this.startNode(), + oldInType = this.state.inType; + node.params = []; + + this.state.inType = true; + + this.expectRelational("<"); + while (!this.isRelational(">")) { + node.params.push(this.flowParseType()); + if (!this.isRelational(">")) { + this.expect(_types.types.comma); + } + } + this.expectRelational(">"); + + this.state.inType = oldInType; + + return this.finishNode(node, "TypeParameterInstantiation"); +}; + +pp.flowParseObjectPropertyKey = function () { + return this.match(_types.types.num) || this.match(_types.types.string) ? this.parseExprAtom() : this.parseIdentifier(true); +}; + +pp.flowParseObjectTypeIndexer = function (node, isStatic) { + node.static = isStatic; + + this.expect(_types.types.bracketL); + node.id = this.flowParseObjectPropertyKey(); + node.key = this.flowParseTypeInitialiser(); + this.expect(_types.types.bracketR); + node.value = this.flowParseTypeInitialiser(); + + this.flowObjectTypeSemicolon(); + return this.finishNode(node, "ObjectTypeIndexer"); +}; + +pp.flowParseObjectTypeMethodish = function (node) { + node.params = []; + node.rest = null; + node.typeParameters = null; + + if (this.isRelational("<")) { + node.typeParameters = this.flowParseTypeParameterDeclaration(); + } + + this.expect(_types.types.parenL); + while (this.match(_types.types.name)) { + node.params.push(this.flowParseFunctionTypeParam()); + if (!this.match(_types.types.parenR)) { + this.expect(_types.types.comma); + } + } + + if (this.eat(_types.types.ellipsis)) { + node.rest = this.flowParseFunctionTypeParam(); + } + this.expect(_types.types.parenR); + node.returnType = this.flowParseTypeInitialiser(); + + return this.finishNode(node, "FunctionTypeAnnotation"); +}; + +pp.flowParseObjectTypeMethod = function (startPos, startLoc, isStatic, key) { + var node = this.startNodeAt(startPos, startLoc); + node.value = this.flowParseObjectTypeMethodish(this.startNodeAt(startPos, startLoc)); + node.static = isStatic; + node.key = key; + node.optional = false; + this.flowObjectTypeSemicolon(); + return this.finishNode(node, "ObjectTypeProperty"); +}; + +pp.flowParseObjectTypeCallProperty = function (node, isStatic) { + var valueNode = this.startNode(); + node.static = isStatic; + node.value = this.flowParseObjectTypeMethodish(valueNode); + this.flowObjectTypeSemicolon(); + return this.finishNode(node, "ObjectTypeCallProperty"); +}; + +pp.flowParseObjectType = function (allowStatic, allowExact) { + var nodeStart = this.startNode(); + var node = void 0; + var propertyKey = void 0; + var isStatic = false; + + nodeStart.callProperties = []; + nodeStart.properties = []; + nodeStart.indexers = []; + + var endDelim = void 0; + var exact = void 0; + if (allowExact && this.match(_types.types.braceBarL)) { + this.expect(_types.types.braceBarL); + endDelim = _types.types.braceBarR; + exact = true; + } else { + this.expect(_types.types.braceL); + endDelim = _types.types.braceR; + exact = false; + } + + nodeStart.exact = exact; + + while (!this.match(endDelim)) { + var optional = false; + var startPos = this.state.start, + startLoc = this.state.startLoc; + node = this.startNode(); + if (allowStatic && this.isContextual("static")) { + this.next(); + isStatic = true; + } + + if (this.match(_types.types.bracketL)) { + nodeStart.indexers.push(this.flowParseObjectTypeIndexer(node, isStatic)); + } else if (this.match(_types.types.parenL) || this.isRelational("<")) { + nodeStart.callProperties.push(this.flowParseObjectTypeCallProperty(node, allowStatic)); + } else { + if (isStatic && this.match(_types.types.colon)) { + propertyKey = this.parseIdentifier(); + } else { + propertyKey = this.flowParseObjectPropertyKey(); + } + if (this.isRelational("<") || this.match(_types.types.parenL)) { + // This is a method property + nodeStart.properties.push(this.flowParseObjectTypeMethod(startPos, startLoc, isStatic, propertyKey)); + } else { + if (this.eat(_types.types.question)) { + optional = true; + } + node.key = propertyKey; + node.value = this.flowParseTypeInitialiser(); + node.optional = optional; + node.static = isStatic; + this.flowObjectTypeSemicolon(); + nodeStart.properties.push(this.finishNode(node, "ObjectTypeProperty")); + } + } + + isStatic = false; + } + + this.expect(endDelim); + + return this.finishNode(nodeStart, "ObjectTypeAnnotation"); +}; + +pp.flowObjectTypeSemicolon = function () { + if (!this.eat(_types.types.semi) && !this.eat(_types.types.comma) && !this.match(_types.types.braceR) && !this.match(_types.types.braceBarR)) { + this.unexpected(); + } +}; + +pp.flowParseQualifiedTypeIdentifier = function (startPos, startLoc, id) { + startPos = startPos || this.state.start; + startLoc = startLoc || this.state.startLoc; + var node = id || this.parseIdentifier(); + + while (this.eat(_types.types.dot)) { + var node2 = this.startNodeAt(startPos, startLoc); + node2.qualification = node; + node2.id = this.parseIdentifier(); + node = this.finishNode(node2, "QualifiedTypeIdentifier"); + } + + return node; +}; + +pp.flowParseGenericType = function (startPos, startLoc, id) { + var node = this.startNodeAt(startPos, startLoc); + + node.typeParameters = null; + node.id = this.flowParseQualifiedTypeIdentifier(startPos, startLoc, id); + + if (this.isRelational("<")) { + node.typeParameters = this.flowParseTypeParameterInstantiation(); + } + + return this.finishNode(node, "GenericTypeAnnotation"); +}; + +pp.flowParseTypeofType = function () { + var node = this.startNode(); + this.expect(_types.types._typeof); + node.argument = this.flowParsePrimaryType(); + return this.finishNode(node, "TypeofTypeAnnotation"); +}; + +pp.flowParseTupleType = function () { + var node = this.startNode(); + node.types = []; + this.expect(_types.types.bracketL); + // We allow trailing commas + while (this.state.pos < this.input.length && !this.match(_types.types.bracketR)) { + node.types.push(this.flowParseType()); + if (this.match(_types.types.bracketR)) break; + this.expect(_types.types.comma); + } + this.expect(_types.types.bracketR); + return this.finishNode(node, "TupleTypeAnnotation"); +}; + +pp.flowParseFunctionTypeParam = function () { + var optional = false; + var node = this.startNode(); + node.name = this.parseIdentifier(); + if (this.eat(_types.types.question)) { + optional = true; + } + node.optional = optional; + node.typeAnnotation = this.flowParseTypeInitialiser(); + return this.finishNode(node, "FunctionTypeParam"); +}; + +pp.flowParseFunctionTypeParams = function () { + var ret = { params: [], rest: null }; + while (this.match(_types.types.name)) { + ret.params.push(this.flowParseFunctionTypeParam()); + if (!this.match(_types.types.parenR)) { + this.expect(_types.types.comma); + } + } + if (this.eat(_types.types.ellipsis)) { + ret.rest = this.flowParseFunctionTypeParam(); + } + return ret; +}; + +pp.flowIdentToTypeAnnotation = function (startPos, startLoc, node, id) { + switch (id.name) { + case "any": + return this.finishNode(node, "AnyTypeAnnotation"); + + case "void": + return this.finishNode(node, "VoidTypeAnnotation"); + + case "bool": + case "boolean": + return this.finishNode(node, "BooleanTypeAnnotation"); + + case "mixed": + return this.finishNode(node, "MixedTypeAnnotation"); + + case "number": + return this.finishNode(node, "NumberTypeAnnotation"); + + case "string": + return this.finishNode(node, "StringTypeAnnotation"); + + default: + return this.flowParseGenericType(startPos, startLoc, id); + } +}; + +// The parsing of types roughly parallels the parsing of expressions, and +// primary types are kind of like primary expressions...they're the +// primitives with which other types are constructed. +pp.flowParsePrimaryType = function () { + var startPos = this.state.start, + startLoc = this.state.startLoc; + var node = this.startNode(); + var tmp = void 0; + var type = void 0; + var isGroupedType = false; + + switch (this.state.type) { + case _types.types.name: + return this.flowIdentToTypeAnnotation(startPos, startLoc, node, this.parseIdentifier()); + + case _types.types.braceL: + return this.flowParseObjectType(false, false); + + case _types.types.braceBarL: + return this.flowParseObjectType(false, true); + + case _types.types.bracketL: + return this.flowParseTupleType(); + + case _types.types.relational: + if (this.state.value === "<") { + node.typeParameters = this.flowParseTypeParameterDeclaration(); + this.expect(_types.types.parenL); + tmp = this.flowParseFunctionTypeParams(); + node.params = tmp.params; + node.rest = tmp.rest; + this.expect(_types.types.parenR); + + this.expect(_types.types.arrow); + + node.returnType = this.flowParseType(); + + return this.finishNode(node, "FunctionTypeAnnotation"); + } + break; + + case _types.types.parenL: + this.next(); + + // Check to see if this is actually a grouped type + if (!this.match(_types.types.parenR) && !this.match(_types.types.ellipsis)) { + if (this.match(_types.types.name)) { + var token = this.lookahead().type; + isGroupedType = token !== _types.types.question && token !== _types.types.colon; + } else { + isGroupedType = true; + } + } + + if (isGroupedType) { + type = this.flowParseType(); + this.expect(_types.types.parenR); + return type; + } + + tmp = this.flowParseFunctionTypeParams(); + node.params = tmp.params; + node.rest = tmp.rest; + + this.expect(_types.types.parenR); + + this.expect(_types.types.arrow); + + node.returnType = this.flowParseType(); + node.typeParameters = null; + + return this.finishNode(node, "FunctionTypeAnnotation"); + + case _types.types.string: + node.value = this.state.value; + this.addExtra(node, "rawValue", node.value); + this.addExtra(node, "raw", this.input.slice(this.state.start, this.state.end)); + this.next(); + return this.finishNode(node, "StringLiteralTypeAnnotation"); + + case _types.types._true:case _types.types._false: + node.value = this.match(_types.types._true); + this.next(); + return this.finishNode(node, "BooleanLiteralTypeAnnotation"); + + case _types.types.plusMin: + if (this.state.value === "-") { + this.next(); + if (!this.match(_types.types.num)) this.unexpected(); + + node.value = -this.state.value; + this.addExtra(node, "rawValue", node.value); + this.addExtra(node, "raw", this.input.slice(this.state.start, this.state.end)); + this.next(); + return this.finishNode(node, "NumericLiteralTypeAnnotation"); + } + + case _types.types.num: + node.value = this.state.value; + this.addExtra(node, "rawValue", node.value); + this.addExtra(node, "raw", this.input.slice(this.state.start, this.state.end)); + this.next(); + return this.finishNode(node, "NumericLiteralTypeAnnotation"); + + case _types.types._null: + node.value = this.match(_types.types._null); + this.next(); + return this.finishNode(node, "NullLiteralTypeAnnotation"); + + case _types.types._this: + node.value = this.match(_types.types._this); + this.next(); + return this.finishNode(node, "ThisTypeAnnotation"); + + case _types.types.star: + this.next(); + return this.finishNode(node, "ExistentialTypeParam"); + + default: + if (this.state.type.keyword === "typeof") { + return this.flowParseTypeofType(); + } + } + + this.unexpected(); +}; + +pp.flowParsePostfixType = function () { + var node = this.startNode(); + var type = node.elementType = this.flowParsePrimaryType(); + if (this.match(_types.types.bracketL)) { + this.expect(_types.types.bracketL); + this.expect(_types.types.bracketR); + return this.finishNode(node, "ArrayTypeAnnotation"); + } else { + return type; + } +}; + +pp.flowParsePrefixType = function () { + var node = this.startNode(); + if (this.eat(_types.types.question)) { + node.typeAnnotation = this.flowParsePrefixType(); + return this.finishNode(node, "NullableTypeAnnotation"); + } else { + return this.flowParsePostfixType(); + } +}; + +pp.flowParseIntersectionType = function () { + var node = this.startNode(); + var type = this.flowParsePrefixType(); + node.types = [type]; + while (this.eat(_types.types.bitwiseAND)) { + node.types.push(this.flowParsePrefixType()); + } + return node.types.length === 1 ? type : this.finishNode(node, "IntersectionTypeAnnotation"); +}; + +pp.flowParseUnionType = function () { + var node = this.startNode(); + var type = this.flowParseIntersectionType(); + node.types = [type]; + while (this.eat(_types.types.bitwiseOR)) { + node.types.push(this.flowParseIntersectionType()); + } + return node.types.length === 1 ? type : this.finishNode(node, "UnionTypeAnnotation"); +}; + +pp.flowParseType = function () { + var oldInType = this.state.inType; + this.state.inType = true; + var type = this.flowParseUnionType(); + this.state.inType = oldInType; + return type; +}; + +pp.flowParseTypeAnnotation = function () { + var node = this.startNode(); + node.typeAnnotation = this.flowParseTypeInitialiser(); + return this.finishNode(node, "TypeAnnotation"); +}; + +pp.flowParseTypeAnnotatableIdentifier = function (requireTypeAnnotation, canBeOptionalParam) { + + var ident = this.parseIdentifier(); + var isOptionalParam = false; + + if (canBeOptionalParam && this.eat(_types.types.question)) { + this.expect(_types.types.question); + isOptionalParam = true; + } + + if (requireTypeAnnotation || this.match(_types.types.colon)) { + ident.typeAnnotation = this.flowParseTypeAnnotation(); + this.finishNode(ident, ident.type); + } + + if (isOptionalParam) { + ident.optional = true; + this.finishNode(ident, ident.type); + } + + return ident; +}; + +pp.typeCastToParameter = function (node) { + node.expression.typeAnnotation = node.typeAnnotation; + + return this.finishNodeAt(node.expression, node.expression.type, node.typeAnnotation.end, node.typeAnnotation.loc.end); +}; +},{"../parser":201,"../tokenizer/context":210,"../tokenizer/types":213}],208:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; + +exports.default = function (instance) { + instance.extend("parseExprAtom", function (inner) { + return function (refShortHandDefaultPos) { + if (this.match(_types.types.jsxText)) { + var node = this.parseLiteral(this.state.value, "JSXText"); + // https://github.com/babel/babel/issues/2078 + node.extra = null; + return node; + } else if (this.match(_types.types.jsxTagStart)) { + return this.jsxParseElement(); + } else { + return inner.call(this, refShortHandDefaultPos); + } + }; + }); + + instance.extend("readToken", function (inner) { + return function (code) { + var context = this.curContext(); + + if (context === _context.types.j_expr) { + return this.jsxReadToken(); + } + + if (context === _context.types.j_oTag || context === _context.types.j_cTag) { + if ((0, _identifier.isIdentifierStart)(code)) { + return this.jsxReadWord(); + } + + if (code === 62) { + ++this.state.pos; + return this.finishToken(_types.types.jsxTagEnd); + } + + if ((code === 34 || code === 39) && context === _context.types.j_oTag) { + return this.jsxReadString(code); + } + } + + if (code === 60 && this.state.exprAllowed) { + ++this.state.pos; + return this.finishToken(_types.types.jsxTagStart); + } + + return inner.call(this, code); + }; + }); + + instance.extend("updateContext", function (inner) { + return function (prevType) { + if (this.match(_types.types.braceL)) { + var curContext = this.curContext(); + if (curContext === _context.types.j_oTag) { + this.state.context.push(_context.types.braceExpression); + } else if (curContext === _context.types.j_expr) { + this.state.context.push(_context.types.templateQuasi); + } else { + inner.call(this, prevType); + } + this.state.exprAllowed = true; + } else if (this.match(_types.types.slash) && prevType === _types.types.jsxTagStart) { + this.state.context.length -= 2; // do not consider JSX expr -> JSX open tag -> ... anymore + this.state.context.push(_context.types.j_cTag); // reconsider as closing tag context + this.state.exprAllowed = false; + } else { + return inner.call(this, prevType); + } + }; + }); +}; + +var _xhtml = require("./xhtml"); + +var _xhtml2 = _interopRequireDefault(_xhtml); + +var _types = require("../../tokenizer/types"); + +var _context = require("../../tokenizer/context"); + +var _parser = require("../../parser"); + +var _parser2 = _interopRequireDefault(_parser); + +var _identifier = require("../../util/identifier"); + +var _whitespace = require("../../util/whitespace"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/* eslint indent: 0 */ + +var HEX_NUMBER = /^[\da-fA-F]+$/; +var DECIMAL_NUMBER = /^\d+$/; + +_context.types.j_oTag = new _context.TokContext("...", true, true); + +_types.types.jsxName = new _types.TokenType("jsxName"); +_types.types.jsxText = new _types.TokenType("jsxText", { beforeExpr: true }); +_types.types.jsxTagStart = new _types.TokenType("jsxTagStart", { startsExpr: true }); +_types.types.jsxTagEnd = new _types.TokenType("jsxTagEnd"); + +_types.types.jsxTagStart.updateContext = function () { + this.state.context.push(_context.types.j_expr); // treat as beginning of JSX expression + this.state.context.push(_context.types.j_oTag); // start opening tag context + this.state.exprAllowed = false; +}; + +_types.types.jsxTagEnd.updateContext = function (prevType) { + var out = this.state.context.pop(); + if (out === _context.types.j_oTag && prevType === _types.types.slash || out === _context.types.j_cTag) { + this.state.context.pop(); + this.state.exprAllowed = this.curContext() === _context.types.j_expr; + } else { + this.state.exprAllowed = true; + } +}; + +var pp = _parser2.default.prototype; + +// Reads inline JSX contents token. + +pp.jsxReadToken = function () { + var out = ""; + var chunkStart = this.state.pos; + for (;;) { + if (this.state.pos >= this.input.length) { + this.raise(this.state.start, "Unterminated JSX contents"); + } + + var ch = this.input.charCodeAt(this.state.pos); + + switch (ch) { + case 60: // "<" + case 123: + // "{" + if (this.state.pos === this.state.start) { + if (ch === 60 && this.state.exprAllowed) { + ++this.state.pos; + return this.finishToken(_types.types.jsxTagStart); + } + return this.getTokenFromCode(ch); + } + out += this.input.slice(chunkStart, this.state.pos); + return this.finishToken(_types.types.jsxText, out); + + case 38: + // "&" + out += this.input.slice(chunkStart, this.state.pos); + out += this.jsxReadEntity(); + chunkStart = this.state.pos; + break; + + default: + if ((0, _whitespace.isNewLine)(ch)) { + out += this.input.slice(chunkStart, this.state.pos); + out += this.jsxReadNewLine(true); + chunkStart = this.state.pos; + } else { + ++this.state.pos; + } + } + } +}; + +pp.jsxReadNewLine = function (normalizeCRLF) { + var ch = this.input.charCodeAt(this.state.pos); + var out = void 0; + ++this.state.pos; + if (ch === 13 && this.input.charCodeAt(this.state.pos) === 10) { + ++this.state.pos; + out = normalizeCRLF ? "\n" : "\r\n"; + } else { + out = String.fromCharCode(ch); + } + ++this.state.curLine; + this.state.lineStart = this.state.pos; + + return out; +}; + +pp.jsxReadString = function (quote) { + var out = ""; + var chunkStart = ++this.state.pos; + for (;;) { + if (this.state.pos >= this.input.length) { + this.raise(this.state.start, "Unterminated string constant"); + } + + var ch = this.input.charCodeAt(this.state.pos); + if (ch === quote) break; + if (ch === 38) { + // "&" + out += this.input.slice(chunkStart, this.state.pos); + out += this.jsxReadEntity(); + chunkStart = this.state.pos; + } else if ((0, _whitespace.isNewLine)(ch)) { + out += this.input.slice(chunkStart, this.state.pos); + out += this.jsxReadNewLine(false); + chunkStart = this.state.pos; + } else { + ++this.state.pos; + } + } + out += this.input.slice(chunkStart, this.state.pos++); + return this.finishToken(_types.types.string, out); +}; + +pp.jsxReadEntity = function () { + var str = ""; + var count = 0; + var entity = void 0; + var ch = this.input[this.state.pos]; + + var startPos = ++this.state.pos; + while (this.state.pos < this.input.length && count++ < 10) { + ch = this.input[this.state.pos++]; + if (ch === ";") { + if (str[0] === "#") { + if (str[1] === "x") { + str = str.substr(2); + if (HEX_NUMBER.test(str)) entity = String.fromCharCode(parseInt(str, 16)); + } else { + str = str.substr(1); + if (DECIMAL_NUMBER.test(str)) entity = String.fromCharCode(parseInt(str, 10)); + } + } else { + entity = _xhtml2.default[str]; + } + break; + } + str += ch; + } + if (!entity) { + this.state.pos = startPos; + return "&"; + } + return entity; +}; + +// Read a JSX identifier (valid tag or attribute name). +// +// Optimized version since JSX identifiers can"t contain +// escape characters and so can be read as single slice. +// Also assumes that first character was already checked +// by isIdentifierStart in readToken. + +pp.jsxReadWord = function () { + var ch = void 0; + var start = this.state.pos; + do { + ch = this.input.charCodeAt(++this.state.pos); + } while ((0, _identifier.isIdentifierChar)(ch) || ch === 45); // "-" + return this.finishToken(_types.types.jsxName, this.input.slice(start, this.state.pos)); +}; + +// Transforms JSX element name to string. + +function getQualifiedJSXName(object) { + if (object.type === "JSXIdentifier") { + return object.name; + } + + if (object.type === "JSXNamespacedName") { + return object.namespace.name + ":" + object.name.name; + } + + if (object.type === "JSXMemberExpression") { + return getQualifiedJSXName(object.object) + "." + getQualifiedJSXName(object.property); + } +} + +// Parse next token as JSX identifier + +pp.jsxParseIdentifier = function () { + var node = this.startNode(); + if (this.match(_types.types.jsxName)) { + node.name = this.state.value; + } else if (this.state.type.keyword) { + node.name = this.state.type.keyword; + } else { + this.unexpected(); + } + this.next(); + return this.finishNode(node, "JSXIdentifier"); +}; + +// Parse namespaced identifier. + +pp.jsxParseNamespacedName = function () { + var startPos = this.state.start, + startLoc = this.state.startLoc; + var name = this.jsxParseIdentifier(); + if (!this.eat(_types.types.colon)) return name; + + var node = this.startNodeAt(startPos, startLoc); + node.namespace = name; + node.name = this.jsxParseIdentifier(); + return this.finishNode(node, "JSXNamespacedName"); +}; + +// Parses element name in any form - namespaced, member +// or single identifier. + +pp.jsxParseElementName = function () { + var startPos = this.state.start, + startLoc = this.state.startLoc; + var node = this.jsxParseNamespacedName(); + while (this.eat(_types.types.dot)) { + var newNode = this.startNodeAt(startPos, startLoc); + newNode.object = node; + newNode.property = this.jsxParseIdentifier(); + node = this.finishNode(newNode, "JSXMemberExpression"); + } + return node; +}; + +// Parses any type of JSX attribute value. + +pp.jsxParseAttributeValue = function () { + var node = void 0; + switch (this.state.type) { + case _types.types.braceL: + node = this.jsxParseExpressionContainer(); + if (node.expression.type === "JSXEmptyExpression") { + this.raise(node.start, "JSX attributes must only be assigned a non-empty expression"); + } else { + return node; + } + + case _types.types.jsxTagStart: + case _types.types.string: + node = this.parseExprAtom(); + node.extra = null; + return node; + + default: + this.raise(this.state.start, "JSX value should be either an expression or a quoted JSX text"); + } +}; + +// JSXEmptyExpression is unique type since it doesn't actually parse anything, +// and so it should start at the end of last read token (left brace) and finish +// at the beginning of the next one (right brace). + +pp.jsxParseEmptyExpression = function () { + var node = this.startNodeAt(this.lastTokEnd, this.lastTokEndLoc); + return this.finishNodeAt(node, "JSXEmptyExpression", this.start, this.startLoc); +}; + +// Parse JSX spread child + +pp.jsxParseSpreadChild = function () { + var node = this.startNode(); + this.expect(_types.types.braceL); + this.expect(_types.types.ellipsis); + node.expression = this.parseExpression(); + this.expect(_types.types.braceR); + + return this.finishNode(node, "JSXSpreadChild"); +}; + +// Parses JSX expression enclosed into curly brackets. + + +pp.jsxParseExpressionContainer = function () { + var node = this.startNode(); + this.next(); + if (this.match(_types.types.braceR)) { + node.expression = this.jsxParseEmptyExpression(); + } else { + node.expression = this.parseExpression(); + } + this.expect(_types.types.braceR); + return this.finishNode(node, "JSXExpressionContainer"); +}; + +// Parses following JSX attribute name-value pair. + +pp.jsxParseAttribute = function () { + var node = this.startNode(); + if (this.eat(_types.types.braceL)) { + this.expect(_types.types.ellipsis); + node.argument = this.parseMaybeAssign(); + this.expect(_types.types.braceR); + return this.finishNode(node, "JSXSpreadAttribute"); + } + node.name = this.jsxParseNamespacedName(); + node.value = this.eat(_types.types.eq) ? this.jsxParseAttributeValue() : null; + return this.finishNode(node, "JSXAttribute"); +}; + +// Parses JSX opening tag starting after "<". + +pp.jsxParseOpeningElementAt = function (startPos, startLoc) { + var node = this.startNodeAt(startPos, startLoc); + node.attributes = []; + node.name = this.jsxParseElementName(); + while (!this.match(_types.types.slash) && !this.match(_types.types.jsxTagEnd)) { + node.attributes.push(this.jsxParseAttribute()); + } + node.selfClosing = this.eat(_types.types.slash); + this.expect(_types.types.jsxTagEnd); + return this.finishNode(node, "JSXOpeningElement"); +}; + +// Parses JSX closing tag starting after ""); + } + } + + node.openingElement = openingElement; + node.closingElement = closingElement; + node.children = children; + if (this.match(_types.types.relational) && this.state.value === "<") { + this.raise(this.state.start, "Adjacent JSX elements must be wrapped in an enclosing tag"); + } + return this.finishNode(node, "JSXElement"); +}; + +// Parses entire JSX element from current position. + +pp.jsxParseElement = function () { + var startPos = this.state.start, + startLoc = this.state.startLoc; + this.next(); + return this.jsxParseElementAt(startPos, startLoc); +}; +},{"../../parser":201,"../../tokenizer/context":210,"../../tokenizer/types":213,"../../util/identifier":214,"../../util/whitespace":216,"./xhtml":209}],209:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; +exports.default = { + quot: "\"", + amp: "&", + apos: "'", + lt: "<", + gt: ">", + nbsp: " ", + iexcl: "¡", + cent: "¢", + pound: "£", + curren: "¤", + yen: "¥", + brvbar: "¦", + sect: "§", + uml: "¨", + copy: "©", + ordf: "ª", + laquo: "«", + not: "¬", + shy: "­", + reg: "®", + macr: "¯", + deg: "°", + plusmn: "±", + sup2: "²", + sup3: "³", + acute: "´", + micro: "µ", + para: "¶", + middot: "·", + cedil: "¸", + sup1: "¹", + ordm: "º", + raquo: "»", + frac14: "¼", + frac12: "½", + frac34: "¾", + iquest: "¿", + Agrave: "À", + Aacute: "Á", + Acirc: "Â", + Atilde: "Ã", + Auml: "Ä", + Aring: "Å", + AElig: "Æ", + Ccedil: "Ç", + Egrave: "È", + Eacute: "É", + Ecirc: "Ê", + Euml: "Ë", + Igrave: "Ì", + Iacute: "Í", + Icirc: "Î", + Iuml: "Ï", + ETH: "Ð", + Ntilde: "Ñ", + Ograve: "Ò", + Oacute: "Ó", + Ocirc: "Ô", + Otilde: "Õ", + Ouml: "Ö", + times: "×", + Oslash: "Ø", + Ugrave: "Ù", + Uacute: "Ú", + Ucirc: "Û", + Uuml: "Ü", + Yacute: "Ý", + THORN: "Þ", + szlig: "ß", + agrave: "à", + aacute: "á", + acirc: "â", + atilde: "ã", + auml: "ä", + aring: "å", + aelig: "æ", + ccedil: "ç", + egrave: "è", + eacute: "é", + ecirc: "ê", + euml: "ë", + igrave: "ì", + iacute: "í", + icirc: "î", + iuml: "ï", + eth: "ð", + ntilde: "ñ", + ograve: "ò", + oacute: "ó", + ocirc: "ô", + otilde: "õ", + ouml: "ö", + divide: "÷", + oslash: "ø", + ugrave: "ù", + uacute: "ú", + ucirc: "û", + uuml: "ü", + yacute: "ý", + thorn: "þ", + yuml: "ÿ", + OElig: "Œ", + oelig: "œ", + Scaron: "Š", + scaron: "š", + Yuml: "Ÿ", + fnof: "ƒ", + circ: "ˆ", + tilde: "˜", + Alpha: "Α", + Beta: "Β", + Gamma: "Γ", + Delta: "Δ", + Epsilon: "Ε", + Zeta: "Ζ", + Eta: "Η", + Theta: "Θ", + Iota: "Ι", + Kappa: "Κ", + Lambda: "Λ", + Mu: "Μ", + Nu: "Ν", + Xi: "Ξ", + Omicron: "Ο", + Pi: "Π", + Rho: "Ρ", + Sigma: "Σ", + Tau: "Τ", + Upsilon: "Υ", + Phi: "Φ", + Chi: "Χ", + Psi: "Ψ", + Omega: "Ω", + alpha: "α", + beta: "β", + gamma: "γ", + delta: "δ", + epsilon: "ε", + zeta: "ζ", + eta: "η", + theta: "θ", + iota: "ι", + kappa: "κ", + lambda: "λ", + mu: "μ", + nu: "ν", + xi: "ξ", + omicron: "ο", + pi: "π", + rho: "ρ", + sigmaf: "ς", + sigma: "σ", + tau: "τ", + upsilon: "υ", + phi: "φ", + chi: "χ", + psi: "ψ", + omega: "ω", + thetasym: "ϑ", + upsih: "ϒ", + piv: "ϖ", + ensp: " ", + emsp: " ", + thinsp: " ", + zwnj: "‌", + zwj: "‍", + lrm: "‎", + rlm: "‏", + ndash: "–", + mdash: "—", + lsquo: "‘", + rsquo: "’", + sbquo: "‚", + ldquo: "“", + rdquo: "”", + bdquo: "„", + dagger: "†", + Dagger: "‡", + bull: "•", + hellip: "…", + permil: "‰", + prime: "′", + Prime: "″", + lsaquo: "‹", + rsaquo: "›", + oline: "‾", + frasl: "⁄", + euro: "€", + image: "ℑ", + weierp: "℘", + real: "ℜ", + trade: "™", + alefsym: "ℵ", + larr: "←", + uarr: "↑", + rarr: "→", + darr: "↓", + harr: "↔", + crarr: "↵", + lArr: "⇐", + uArr: "⇑", + rArr: "⇒", + dArr: "⇓", + hArr: "⇔", + forall: "∀", + part: "∂", + exist: "∃", + empty: "∅", + nabla: "∇", + isin: "∈", + notin: "∉", + ni: "∋", + prod: "∏", + sum: "∑", + minus: "−", + lowast: "∗", + radic: "√", + prop: "∝", + infin: "∞", + ang: "∠", + and: "∧", + or: "∨", + cap: "∩", + cup: "∪", + "int": "∫", + there4: "∴", + sim: "∼", + cong: "≅", + asymp: "≈", + ne: "≠", + equiv: "≡", + le: "≤", + ge: "≥", + sub: "⊂", + sup: "⊃", + nsub: "⊄", + sube: "⊆", + supe: "⊇", + oplus: "⊕", + otimes: "⊗", + perp: "⊥", + sdot: "⋅", + lceil: "⌈", + rceil: "⌉", + lfloor: "⌊", + rfloor: "⌋", + lang: "〈", + rang: "〉", + loz: "◊", + spades: "♠", + clubs: "♣", + hearts: "♥", + diams: "♦" +}; +},{}],210:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; +exports.types = exports.TokContext = undefined; + +var _types = require("./types"); + +var _whitespace = require("../util/whitespace"); + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } // The algorithm used to determine whether a regexp can appear at a +// given point in the program is loosely based on sweet.js' approach. +// See https://github.com/mozilla/sweet.js/wiki/design + +var TokContext = exports.TokContext = function TokContext(token, isExpr, preserveSpace, override) { + _classCallCheck(this, TokContext); + + this.token = token; + this.isExpr = !!isExpr; + this.preserveSpace = !!preserveSpace; + this.override = override; +}; + +var types = exports.types = { + braceStatement: new TokContext("{", false), + braceExpression: new TokContext("{", true), + templateQuasi: new TokContext("${", true), + parenStatement: new TokContext("(", false), + parenExpression: new TokContext("(", true), + template: new TokContext("`", true, true, function (p) { + return p.readTmplToken(); + }), + functionExpression: new TokContext("function", true) +}; + +// Token-specific context update code + +_types.types.parenR.updateContext = _types.types.braceR.updateContext = function () { + if (this.state.context.length === 1) { + this.state.exprAllowed = true; + return; + } + + var out = this.state.context.pop(); + if (out === types.braceStatement && this.curContext() === types.functionExpression) { + this.state.context.pop(); + this.state.exprAllowed = false; + } else if (out === types.templateQuasi) { + this.state.exprAllowed = true; + } else { + this.state.exprAllowed = !out.isExpr; + } +}; + +_types.types.name.updateContext = function (prevType) { + this.state.exprAllowed = false; + + if (prevType === _types.types._let || prevType === _types.types._const || prevType === _types.types._var) { + if (_whitespace.lineBreak.test(this.input.slice(this.state.end))) { + this.state.exprAllowed = true; + } + } +}; + +_types.types.braceL.updateContext = function (prevType) { + this.state.context.push(this.braceIsBlock(prevType) ? types.braceStatement : types.braceExpression); + this.state.exprAllowed = true; +}; + +_types.types.dollarBraceL.updateContext = function () { + this.state.context.push(types.templateQuasi); + this.state.exprAllowed = true; +}; + +_types.types.parenL.updateContext = function (prevType) { + var statementParens = prevType === _types.types._if || prevType === _types.types._for || prevType === _types.types._with || prevType === _types.types._while; + this.state.context.push(statementParens ? types.parenStatement : types.parenExpression); + this.state.exprAllowed = true; +}; + +_types.types.incDec.updateContext = function () { + // tokExprAllowed stays unchanged +}; + +_types.types._function.updateContext = function () { + if (this.curContext() !== types.braceStatement) { + this.state.context.push(types.functionExpression); + } + + this.state.exprAllowed = false; +}; + +_types.types.backQuote.updateContext = function () { + if (this.curContext() === types.template) { + this.state.context.pop(); + } else { + this.state.context.push(types.template); + } + this.state.exprAllowed = false; +}; +},{"../util/whitespace":216,"./types":213}],211:[function(require,module,exports){ +"use strict"; + +exports.__esModule = true; +exports.Token = undefined; + +var _identifier = require("../util/identifier"); + +var _types = require("./types"); + +var _context = require("./context"); + +var _location = require("../util/location"); + +var _whitespace = require("../util/whitespace"); + +var _state = require("./state"); + +var _state2 = _interopRequireDefault(_state); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } /* eslint max-len: 0 */ +/* eslint indent: 0 */ + +// Object type used to represent tokens. Note that normally, tokens +// simply exist as properties on the parser object. This is only +// used for the onToken callback and the external tokenizer. + +var Token = exports.Token = function Token(state) { + _classCallCheck(this, Token); + + this.type = state.type; + this.value = state.value; + this.start = state.start; + this.end = state.end; + this.loc = new _location.SourceLocation(state.startLoc, state.endLoc); +}; + +// ## Tokenizer + +function codePointToString(code) { + // UTF-16 Decoding + if (code <= 0xFFFF) { + return String.fromCharCode(code); + } else { + return String.fromCharCode((code - 0x10000 >> 10) + 0xD800, (code - 0x10000 & 1023) + 0xDC00); + } +} + +var Tokenizer = function () { + function Tokenizer(options, input) { + _classCallCheck(this, Tokenizer); + + this.state = new _state2.default(); + this.state.init(options, input); + } + + // Move to the next token + + Tokenizer.prototype.next = function next() { + if (!this.isLookahead) { + this.state.tokens.push(new Token(this.state)); + } + + this.state.lastTokEnd = this.state.end; + this.state.lastTokStart = this.state.start; + this.state.lastTokEndLoc = this.state.endLoc; + this.state.lastTokStartLoc = this.state.startLoc; + this.nextToken(); + }; + + // TODO + + Tokenizer.prototype.eat = function eat(type) { + if (this.match(type)) { + this.next(); + return true; + } else { + return false; + } + }; + + // TODO + + Tokenizer.prototype.match = function match(type) { + return this.state.type === type; + }; + + // TODO + + Tokenizer.prototype.isKeyword = function isKeyword(word) { + return (0, _identifier.isKeyword)(word); + }; + + // TODO + + Tokenizer.prototype.lookahead = function lookahead() { + var old = this.state; + this.state = old.clone(true); + + this.isLookahead = true; + this.next(); + this.isLookahead = false; + + var curr = this.state.clone(true); + this.state = old; + return curr; + }; + + // Toggle strict mode. Re-reads the next number or string to please + // pedantic tests (`"use strict"; 010;` should fail). + + Tokenizer.prototype.setStrict = function setStrict(strict) { + this.state.strict = strict; + if (!this.match(_types.types.num) && !this.match(_types.types.string)) return; + this.state.pos = this.state.start; + while (this.state.pos < this.state.lineStart) { + this.state.lineStart = this.input.lastIndexOf("\n", this.state.lineStart - 2) + 1; + --this.state.curLine; + } + this.nextToken(); + }; + + Tokenizer.prototype.curContext = function curContext() { + return this.state.context[this.state.context.length - 1]; + }; + + // Read a single token, updating the parser object's token-related + // properties. + + Tokenizer.prototype.nextToken = function nextToken() { + var curContext = this.curContext(); + if (!curContext || !curContext.preserveSpace) this.skipSpace(); + + this.state.containsOctal = false; + this.state.octalPosition = null; + this.state.start = this.state.pos; + this.state.startLoc = this.state.curPosition(); + if (this.state.pos >= this.input.length) return this.finishToken(_types.types.eof); + + if (curContext.override) { + return curContext.override(this); + } else { + return this.readToken(this.fullCharCodeAtPos()); + } + }; + + Tokenizer.prototype.readToken = function readToken(code) { + // Identifier or keyword. '\uXXXX' sequences are allowed in + // identifiers, so '\' also dispatches to that. + if ((0, _identifier.isIdentifierStart)(code) || code === 92 /* '\' */) { + return this.readWord(); + } else { + return this.getTokenFromCode(code); + } + }; + + Tokenizer.prototype.fullCharCodeAtPos = function fullCharCodeAtPos() { + var code = this.input.charCodeAt(this.state.pos); + if (code <= 0xd7ff || code >= 0xe000) return code; + + var next = this.input.charCodeAt(this.state.pos + 1); + return (code << 10) + next - 0x35fdc00; + }; + + Tokenizer.prototype.pushComment = function pushComment(block, text, start, end, startLoc, endLoc) { + var comment = { + type: block ? "CommentBlock" : "CommentLine", + value: text, + start: start, + end: end, + loc: new _location.SourceLocation(startLoc, endLoc) + }; + + if (!this.isLookahead) { + this.state.tokens.push(comment); + this.state.comments.push(comment); + this.addComment(comment); + } + }; + + Tokenizer.prototype.skipBlockComment = function skipBlockComment() { + var startLoc = this.state.curPosition(); + var start = this.state.pos, + end = this.input.indexOf("*/", this.state.pos += 2); + if (end === -1) this.raise(this.state.pos - 2, "Unterminated comment"); + + this.state.pos = end + 2; + _whitespace.lineBreakG.lastIndex = start; + var match = void 0; + while ((match = _whitespace.lineBreakG.exec(this.input)) && match.index < this.state.pos) { + ++this.state.curLine; + this.state.lineStart = match.index + match[0].length; + } + + this.pushComment(true, this.input.slice(start + 2, end), start, this.state.pos, startLoc, this.state.curPosition()); + }; + + Tokenizer.prototype.skipLineComment = function skipLineComment(startSkip) { + var start = this.state.pos; + var startLoc = this.state.curPosition(); + var ch = this.input.charCodeAt(this.state.pos += startSkip); + while (this.state.pos < this.input.length && ch !== 10 && ch !== 13 && ch !== 8232 && ch !== 8233) { + ++this.state.pos; + ch = this.input.charCodeAt(this.state.pos); + } + + this.pushComment(false, this.input.slice(start + startSkip, this.state.pos), start, this.state.pos, startLoc, this.state.curPosition()); + }; + + // Called at the start of the parse and after every token. Skips + // whitespace and comments, and. + + Tokenizer.prototype.skipSpace = function skipSpace() { + loop: while (this.state.pos < this.input.length) { + var ch = this.input.charCodeAt(this.state.pos); + switch (ch) { + case 32:case 160: + // ' ' + ++this.state.pos; + break; + + case 13: + if (this.input.charCodeAt(this.state.pos + 1) === 10) { + ++this.state.pos; + } + + case 10:case 8232:case 8233: + ++this.state.pos; + ++this.state.curLine; + this.state.lineStart = this.state.pos; + break; + + case 47: + // '/' + switch (this.input.charCodeAt(this.state.pos + 1)) { + case 42: + // '*' + this.skipBlockComment(); + break; + + case 47: + this.skipLineComment(2); + break; + + default: + break loop; + } + break; + + default: + if (ch > 8 && ch < 14 || ch >= 5760 && _whitespace.nonASCIIwhitespace.test(String.fromCharCode(ch))) { + ++this.state.pos; + } else { + break loop; + } + } + } + }; + + // Called at the end of every token. Sets `end`, `val`, and + // maintains `context` and `exprAllowed`, and skips the space after + // the token, so that the next one's `start` will point at the + // right position. + + Tokenizer.prototype.finishToken = function finishToken(type, val) { + this.state.end = this.state.pos; + this.state.endLoc = this.state.curPosition(); + var prevType = this.state.type; + this.state.type = type; + this.state.value = val; + + this.updateContext(prevType); + }; + + // ### Token reading + + // This is the function that is called to fetch the next token. It + // is somewhat obscure, because it works in character codes rather + // than characters, and because operator parsing has been inlined + // into it. + // + // All in the name of speed. + // + + + Tokenizer.prototype.readToken_dot = function readToken_dot() { + var next = this.input.charCodeAt(this.state.pos + 1); + if (next >= 48 && next <= 57) { + return this.readNumber(true); + } + + var next2 = this.input.charCodeAt(this.state.pos + 2); + if (next === 46 && next2 === 46) { + // 46 = dot '.' + this.state.pos += 3; + return this.finishToken(_types.types.ellipsis); + } else { + ++this.state.pos; + return this.finishToken(_types.types.dot); + } + }; + + Tokenizer.prototype.readToken_slash = function readToken_slash() { + // '/' + if (this.state.exprAllowed) { + ++this.state.pos; + return this.readRegexp(); + } + + var next = this.input.charCodeAt(this.state.pos + 1); + if (next === 61) { + return this.finishOp(_types.types.assign, 2); + } else { + return this.finishOp(_types.types.slash, 1); + } + }; + + Tokenizer.prototype.readToken_mult_modulo = function readToken_mult_modulo(code) { + // '%*' + var type = code === 42 ? _types.types.star : _types.types.modulo; + var width = 1; + var next = this.input.charCodeAt(this.state.pos + 1); + + if (next === 42) { + // '*' + width++; + next = this.input.charCodeAt(this.state.pos + 2); + type = _types.types.exponent; + } + + if (next === 61) { + width++; + type = _types.types.assign; + } + + return this.finishOp(type, width); + }; + + Tokenizer.prototype.readToken_pipe_amp = function readToken_pipe_amp(code) { + // '|&' + var next = this.input.charCodeAt(this.state.pos + 1); + if (next === code) return this.finishOp(code === 124 ? _types.types.logicalOR : _types.types.logicalAND, 2); + if (next === 61) return this.finishOp(_types.types.assign, 2); + if (code === 124 && next === 125 && this.hasPlugin("flow")) return this.finishOp(_types.types.braceBarR, 2); + return this.finishOp(code === 124 ? _types.types.bitwiseOR : _types.types.bitwiseAND, 1); + }; + + Tokenizer.prototype.readToken_caret = function readToken_caret() { + // '^' + var next = this.input.charCodeAt(this.state.pos + 1); + if (next === 61) { + return this.finishOp(_types.types.assign, 2); + } else { + return this.finishOp(_types.types.bitwiseXOR, 1); + } + }; + + Tokenizer.prototype.readToken_plus_min = function readToken_plus_min(code) { + // '+-' + var next = this.input.charCodeAt(this.state.pos + 1); + + if (next === code) { + if (next === 45 && this.input.charCodeAt(this.state.pos + 2) === 62 && _whitespace.lineBreak.test(this.input.slice(this.state.lastTokEnd, this.state.pos))) { + // A `-->` line comment + this.skipLineComment(3); + this.skipSpace(); + return this.nextToken(); + } + return this.finishOp(_types.types.incDec, 2); + } + + if (next === 61) { + return this.finishOp(_types.types.assign, 2); + } else { + return this.finishOp(_types.types.plusMin, 1); + } + }; + + Tokenizer.prototype.readToken_lt_gt = function readToken_lt_gt(code) { + // '<>' + var next = this.input.charCodeAt(this.state.pos + 1); + var size = 1; + + if (next === code) { + size = code === 62 && this.input.charCodeAt(this.state.pos + 2) === 62 ? 3 : 2; + if (this.input.charCodeAt(this.state.pos + size) === 61) return this.finishOp(_types.types.assign, size + 1); + return this.finishOp(_types.types.bitShift, size); + } + + if (next === 33 && code === 60 && this.input.charCodeAt(this.state.pos + 2) === 45 && this.input.charCodeAt(this.state.pos + 3) === 45) { + if (this.inModule) this.unexpected(); + // ` regexps + set = set.map(function (s, si, set) { + return s.map(this.parse, this) + }, this) + + this.debug(this.pattern, set) + + // filter out everything that didn't compile properly. + set = set.filter(function (s) { + return s.indexOf(false) === -1 + }) + + this.debug(this.pattern, set) + + this.set = set +} + +Minimatch.prototype.parseNegate = parseNegate +function parseNegate () { + var pattern = this.pattern + var negate = false + var options = this.options + var negateOffset = 0 + + if (options.nonegate) return + + for (var i = 0, l = pattern.length + ; i < l && pattern.charAt(i) === '!' + ; i++) { + negate = !negate + negateOffset++ + } + + if (negateOffset) this.pattern = pattern.substr(negateOffset) + this.negate = negate +} + +// Brace expansion: +// a{b,c}d -> abd acd +// a{b,}c -> abc ac +// a{0..3}d -> a0d a1d a2d a3d +// a{b,c{d,e}f}g -> abg acdfg acefg +// a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg +// +// Invalid sets are not expanded. +// a{2..}b -> a{2..}b +// a{b}c -> a{b}c +minimatch.braceExpand = function (pattern, options) { + return braceExpand(pattern, options) +} + +Minimatch.prototype.braceExpand = braceExpand + +function braceExpand (pattern, options) { + if (!options) { + if (this instanceof Minimatch) { + options = this.options + } else { + options = {} + } + } + + pattern = typeof pattern === 'undefined' + ? this.pattern : pattern + + if (typeof pattern === 'undefined') { + throw new TypeError('undefined pattern') + } + + if (options.nobrace || + !pattern.match(/\{.*\}/)) { + // shortcut. no need to expand. + return [pattern] + } + + return expand(pattern) +} + +// parse a component of the expanded set. +// At this point, no pattern may contain "/" in it +// so we're going to return a 2d array, where each entry is the full +// pattern, split on '/', and then turned into a regular expression. +// A regexp is made at the end which joins each array with an +// escaped /, and another full one which joins each regexp with |. +// +// Following the lead of Bash 4.1, note that "**" only has special meaning +// when it is the *only* thing in a path portion. Otherwise, any series +// of * is equivalent to a single *. Globstar behavior is enabled by +// default, and can be disabled by setting options.noglobstar. +Minimatch.prototype.parse = parse +var SUBPARSE = {} +function parse (pattern, isSub) { + if (pattern.length > 1024 * 64) { + throw new TypeError('pattern is too long') + } + + var options = this.options + + // shortcuts + if (!options.noglobstar && pattern === '**') return GLOBSTAR + if (pattern === '') return '' + + var re = '' + var hasMagic = !!options.nocase + var escaping = false + // ? => one single character + var patternListStack = [] + var negativeLists = [] + var stateChar + var inClass = false + var reClassStart = -1 + var classStart = -1 + // . and .. never match anything that doesn't start with ., + // even when options.dot is set. + var patternStart = pattern.charAt(0) === '.' ? '' // anything + // not (start or / followed by . or .. followed by / or end) + : options.dot ? '(?!(?:^|\\\/)\\.{1,2}(?:$|\\\/))' + : '(?!\\.)' + var self = this + + function clearStateChar () { + if (stateChar) { + // we had some state-tracking character + // that wasn't consumed by this pass. + switch (stateChar) { + case '*': + re += star + hasMagic = true + break + case '?': + re += qmark + hasMagic = true + break + default: + re += '\\' + stateChar + break + } + self.debug('clearStateChar %j %j', stateChar, re) + stateChar = false + } + } + + for (var i = 0, len = pattern.length, c + ; (i < len) && (c = pattern.charAt(i)) + ; i++) { + this.debug('%s\t%s %s %j', pattern, i, re, c) + + // skip over any that are escaped. + if (escaping && reSpecials[c]) { + re += '\\' + c + escaping = false + continue + } + + switch (c) { + case '/': + // completely not allowed, even escaped. + // Should already be path-split by now. + return false + + case '\\': + clearStateChar() + escaping = true + continue + + // the various stateChar values + // for the "extglob" stuff. + case '?': + case '*': + case '+': + case '@': + case '!': + this.debug('%s\t%s %s %j <-- stateChar', pattern, i, re, c) + + // all of those are literals inside a class, except that + // the glob [!a] means [^a] in regexp + if (inClass) { + this.debug(' in class') + if (c === '!' && i === classStart + 1) c = '^' + re += c + continue + } + + // if we already have a stateChar, then it means + // that there was something like ** or +? in there. + // Handle the stateChar, then proceed with this one. + self.debug('call clearStateChar %j', stateChar) + clearStateChar() + stateChar = c + // if extglob is disabled, then +(asdf|foo) isn't a thing. + // just clear the statechar *now*, rather than even diving into + // the patternList stuff. + if (options.noext) clearStateChar() + continue + + case '(': + if (inClass) { + re += '(' + continue + } + + if (!stateChar) { + re += '\\(' + continue + } + + patternListStack.push({ + type: stateChar, + start: i - 1, + reStart: re.length, + open: plTypes[stateChar].open, + close: plTypes[stateChar].close + }) + // negation is (?:(?!js)[^/]*) + re += stateChar === '!' ? '(?:(?!(?:' : '(?:' + this.debug('plType %j %j', stateChar, re) + stateChar = false + continue + + case ')': + if (inClass || !patternListStack.length) { + re += '\\)' + continue + } + + clearStateChar() + hasMagic = true + var pl = patternListStack.pop() + // negation is (?:(?!js)[^/]*) + // The others are (?:) + re += pl.close + if (pl.type === '!') { + negativeLists.push(pl) + } + pl.reEnd = re.length + continue + + case '|': + if (inClass || !patternListStack.length || escaping) { + re += '\\|' + escaping = false + continue + } + + clearStateChar() + re += '|' + continue + + // these are mostly the same in regexp and glob + case '[': + // swallow any state-tracking char before the [ + clearStateChar() + + if (inClass) { + re += '\\' + c + continue + } + + inClass = true + classStart = i + reClassStart = re.length + re += c + continue + + case ']': + // a right bracket shall lose its special + // meaning and represent itself in + // a bracket expression if it occurs + // first in the list. -- POSIX.2 2.8.3.2 + if (i === classStart + 1 || !inClass) { + re += '\\' + c + escaping = false + continue + } + + // handle the case where we left a class open. + // "[z-a]" is valid, equivalent to "\[z-a\]" + if (inClass) { + // split where the last [ was, make sure we don't have + // an invalid re. if so, re-walk the contents of the + // would-be class to re-translate any characters that + // were passed through as-is + // TODO: It would probably be faster to determine this + // without a try/catch and a new RegExp, but it's tricky + // to do safely. For now, this is safe and works. + var cs = pattern.substring(classStart + 1, i) + try { + RegExp('[' + cs + ']') + } catch (er) { + // not a valid class! + var sp = this.parse(cs, SUBPARSE) + re = re.substr(0, reClassStart) + '\\[' + sp[0] + '\\]' + hasMagic = hasMagic || sp[1] + inClass = false + continue + } + } + + // finish up the class. + hasMagic = true + inClass = false + re += c + continue + + default: + // swallow any state char that wasn't consumed + clearStateChar() + + if (escaping) { + // no need + escaping = false + } else if (reSpecials[c] + && !(c === '^' && inClass)) { + re += '\\' + } + + re += c + + } // switch + } // for + + // handle the case where we left a class open. + // "[abc" is valid, equivalent to "\[abc" + if (inClass) { + // split where the last [ was, and escape it + // this is a huge pita. We now have to re-walk + // the contents of the would-be class to re-translate + // any characters that were passed through as-is + cs = pattern.substr(classStart + 1) + sp = this.parse(cs, SUBPARSE) + re = re.substr(0, reClassStart) + '\\[' + sp[0] + hasMagic = hasMagic || sp[1] + } + + // handle the case where we had a +( thing at the *end* + // of the pattern. + // each pattern list stack adds 3 chars, and we need to go through + // and escape any | chars that were passed through as-is for the regexp. + // Go through and escape them, taking care not to double-escape any + // | chars that were already escaped. + for (pl = patternListStack.pop(); pl; pl = patternListStack.pop()) { + var tail = re.slice(pl.reStart + pl.open.length) + this.debug('setting tail', re, pl) + // maybe some even number of \, then maybe 1 \, followed by a | + tail = tail.replace(/((?:\\{2}){0,64})(\\?)\|/g, function (_, $1, $2) { + if (!$2) { + // the | isn't already escaped, so escape it. + $2 = '\\' + } + + // need to escape all those slashes *again*, without escaping the + // one that we need for escaping the | character. As it works out, + // escaping an even number of slashes can be done by simply repeating + // it exactly after itself. That's why this trick works. + // + // I am sorry that you have to see this. + return $1 + $1 + $2 + '|' + }) + + this.debug('tail=%j\n %s', tail, tail, pl, re) + var t = pl.type === '*' ? star + : pl.type === '?' ? qmark + : '\\' + pl.type + + hasMagic = true + re = re.slice(0, pl.reStart) + t + '\\(' + tail + } + + // handle trailing things that only matter at the very end. + clearStateChar() + if (escaping) { + // trailing \\ + re += '\\\\' + } + + // only need to apply the nodot start if the re starts with + // something that could conceivably capture a dot + var addPatternStart = false + switch (re.charAt(0)) { + case '.': + case '[': + case '(': addPatternStart = true + } + + // Hack to work around lack of negative lookbehind in JS + // A pattern like: *.!(x).!(y|z) needs to ensure that a name + // like 'a.xyz.yz' doesn't match. So, the first negative + // lookahead, has to look ALL the way ahead, to the end of + // the pattern. + for (var n = negativeLists.length - 1; n > -1; n--) { + var nl = negativeLists[n] + + var nlBefore = re.slice(0, nl.reStart) + var nlFirst = re.slice(nl.reStart, nl.reEnd - 8) + var nlLast = re.slice(nl.reEnd - 8, nl.reEnd) + var nlAfter = re.slice(nl.reEnd) + + nlLast += nlAfter + + // Handle nested stuff like *(*.js|!(*.json)), where open parens + // mean that we should *not* include the ) in the bit that is considered + // "after" the negated section. + var openParensBefore = nlBefore.split('(').length - 1 + var cleanAfter = nlAfter + for (i = 0; i < openParensBefore; i++) { + cleanAfter = cleanAfter.replace(/\)[+*?]?/, '') + } + nlAfter = cleanAfter + + var dollar = '' + if (nlAfter === '' && isSub !== SUBPARSE) { + dollar = '$' + } + var newRe = nlBefore + nlFirst + nlAfter + dollar + nlLast + re = newRe + } + + // if the re is not "" at this point, then we need to make sure + // it doesn't match against an empty path part. + // Otherwise a/* will match a/, which it should not. + if (re !== '' && hasMagic) { + re = '(?=.)' + re + } + + if (addPatternStart) { + re = patternStart + re + } + + // parsing just a piece of a larger pattern. + if (isSub === SUBPARSE) { + return [re, hasMagic] + } + + // skip the regexp for non-magical patterns + // unescape anything in it, though, so that it'll be + // an exact match against a file etc. + if (!hasMagic) { + return globUnescape(pattern) + } + + var flags = options.nocase ? 'i' : '' + try { + var regExp = new RegExp('^' + re + '$', flags) + } catch (er) { + // If it was an invalid regular expression, then it can't match + // anything. This trick looks for a character after the end of + // the string, which is of course impossible, except in multi-line + // mode, but it's not a /m regex. + return new RegExp('$.') + } + + regExp._glob = pattern + regExp._src = re + + return regExp +} + +minimatch.makeRe = function (pattern, options) { + return new Minimatch(pattern, options || {}).makeRe() +} + +Minimatch.prototype.makeRe = makeRe +function makeRe () { + if (this.regexp || this.regexp === false) return this.regexp + + // at this point, this.set is a 2d array of partial + // pattern strings, or "**". + // + // It's better to use .match(). This function shouldn't + // be used, really, but it's pretty convenient sometimes, + // when you just want to work with a regex. + var set = this.set + + if (!set.length) { + this.regexp = false + return this.regexp + } + var options = this.options + + var twoStar = options.noglobstar ? star + : options.dot ? twoStarDot + : twoStarNoDot + var flags = options.nocase ? 'i' : '' + + var re = set.map(function (pattern) { + return pattern.map(function (p) { + return (p === GLOBSTAR) ? twoStar + : (typeof p === 'string') ? regExpEscape(p) + : p._src + }).join('\\\/') + }).join('|') + + // must match entire pattern + // ending in a * or ** will make it less strict. + re = '^(?:' + re + ')$' + + // can match anything, as long as it's not this. + if (this.negate) re = '^(?!' + re + ').*$' + + try { + this.regexp = new RegExp(re, flags) + } catch (ex) { + this.regexp = false + } + return this.regexp +} + +minimatch.match = function (list, pattern, options) { + options = options || {} + var mm = new Minimatch(pattern, options) + list = list.filter(function (f) { + return mm.match(f) + }) + if (mm.options.nonull && !list.length) { + list.push(pattern) + } + return list +} + +Minimatch.prototype.match = match +function match (f, partial) { + this.debug('match', f, this.pattern) + // short-circuit in the case of busted things. + // comments, etc. + if (this.comment) return false + if (this.empty) return f === '' + + if (f === '/' && partial) return true + + var options = this.options + + // windows: need to use /, not \ + if (path.sep !== '/') { + f = f.split(path.sep).join('/') + } + + // treat the test path as a set of pathparts. + f = f.split(slashSplit) + this.debug(this.pattern, 'split', f) + + // just ONE of the pattern sets in this.set needs to match + // in order for it to be valid. If negating, then just one + // match means that we have failed. + // Either way, return on the first hit. + + var set = this.set + this.debug(this.pattern, 'set', set) + + // Find the basename of the path by looking for the last non-empty segment + var filename + var i + for (i = f.length - 1; i >= 0; i--) { + filename = f[i] + if (filename) break + } + + for (i = 0; i < set.length; i++) { + var pattern = set[i] + var file = f + if (options.matchBase && pattern.length === 1) { + file = [filename] + } + var hit = this.matchOne(file, pattern, partial) + if (hit) { + if (options.flipNegate) return true + return !this.negate + } + } + + // didn't get any hits. this is success if it's a negative + // pattern, failure otherwise. + if (options.flipNegate) return false + return this.negate +} + +// set partial to true to test if, for example, +// "/a/b" matches the start of "/*/b/*/d" +// Partial means, if you run out of file before you run +// out of pattern, then that's fine, as long as all +// the parts match. +Minimatch.prototype.matchOne = function (file, pattern, partial) { + var options = this.options + + this.debug('matchOne', + { 'this': this, file: file, pattern: pattern }) + + this.debug('matchOne', file.length, pattern.length) + + for (var fi = 0, + pi = 0, + fl = file.length, + pl = pattern.length + ; (fi < fl) && (pi < pl) + ; fi++, pi++) { + this.debug('matchOne loop') + var p = pattern[pi] + var f = file[fi] + + this.debug(pattern, p, f) + + // should be impossible. + // some invalid regexp stuff in the set. + if (p === false) return false + + if (p === GLOBSTAR) { + this.debug('GLOBSTAR', [pattern, p, f]) + + // "**" + // a/**/b/**/c would match the following: + // a/b/x/y/z/c + // a/x/y/z/b/c + // a/b/x/b/x/c + // a/b/c + // To do this, take the rest of the pattern after + // the **, and see if it would match the file remainder. + // If so, return success. + // If not, the ** "swallows" a segment, and try again. + // This is recursively awful. + // + // a/**/b/**/c matching a/b/x/y/z/c + // - a matches a + // - doublestar + // - matchOne(b/x/y/z/c, b/**/c) + // - b matches b + // - doublestar + // - matchOne(x/y/z/c, c) -> no + // - matchOne(y/z/c, c) -> no + // - matchOne(z/c, c) -> no + // - matchOne(c, c) yes, hit + var fr = fi + var pr = pi + 1 + if (pr === pl) { + this.debug('** at the end') + // a ** at the end will just swallow the rest. + // We have found a match. + // however, it will not swallow /.x, unless + // options.dot is set. + // . and .. are *never* matched by **, for explosively + // exponential reasons. + for (; fi < fl; fi++) { + if (file[fi] === '.' || file[fi] === '..' || + (!options.dot && file[fi].charAt(0) === '.')) return false + } + return true + } + + // ok, let's see if we can swallow whatever we can. + while (fr < fl) { + var swallowee = file[fr] + + this.debug('\nglobstar while', file, fr, pattern, pr, swallowee) + + // XXX remove this slice. Just pass the start index. + if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) { + this.debug('globstar found match!', fr, fl, swallowee) + // found a match. + return true + } else { + // can't swallow "." or ".." ever. + // can only swallow ".foo" when explicitly asked. + if (swallowee === '.' || swallowee === '..' || + (!options.dot && swallowee.charAt(0) === '.')) { + this.debug('dot detected!', file, fr, pattern, pr) + break + } + + // ** swallows a segment, and continue. + this.debug('globstar swallow a segment, and continue') + fr++ + } + } + + // no match was found. + // However, in partial mode, we can't say this is necessarily over. + // If there's more *pattern* left, then + if (partial) { + // ran out of file + this.debug('\n>>> no match, partial?', file, fr, pattern, pr) + if (fr === fl) return true + } + return false + } + + // something other than ** + // non-magic patterns just have to match exactly + // patterns with magic have been turned into regexps. + var hit + if (typeof p === 'string') { + if (options.nocase) { + hit = f.toLowerCase() === p.toLowerCase() + } else { + hit = f === p + } + this.debug('string match', p, f, hit) + } else { + hit = f.match(p) + this.debug('pattern match', p, f, hit) + } + + if (!hit) return false + } + + // Note: ending in / means that we'll get a final "" + // at the end of the pattern. This can only match a + // corresponding "" at the end of the file. + // If the file ends in /, then it can only match a + // a pattern that ends in /, unless the pattern just + // doesn't have any more for it. But, a/b/ should *not* + // match "a/b/*", even though "" matches against the + // [^/]*? pattern, except in partial mode, where it might + // simply not be reached yet. + // However, a/b/ should still satisfy a/* + + // now either we fell off the end of the pattern, or we're done. + if (fi === fl && pi === pl) { + // ran out of pattern and filename at the same time. + // an exact hit! + return true + } else if (fi === fl) { + // ran out of file, but still had pattern left. + // this is ok if we're doing the match as part of + // a glob fs traversal. + return partial + } else if (pi === pl) { + // ran out of pattern, still have file left. + // this is only acceptable if we're on the very last + // empty segment of a file with a trailing slash. + // a/* should match a/b/ + var emptyFileEnd = (fi === fl - 1) && (file[fi] === '') + return emptyFileEnd + } + + // should be unreachable. + throw new Error('wtf?') +} + +// replace stuff like \* with * +function globUnescape (s) { + return s.replace(/\\(.)/g, '$1') +} + +function regExpEscape (s) { + return s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&') +} + +},{"brace-expansion":219,"path":589}],587:[function(require,module,exports){ +/** + * Helpers. + */ + +var s = 1000; +var m = s * 60; +var h = m * 60; +var d = h * 24; +var y = d * 365.25; + +/** + * Parse or format the given `val`. + * + * Options: + * + * - `long` verbose formatting [false] + * + * @param {String|Number} val + * @param {Object} options + * @return {String|Number} + * @api public + */ + +module.exports = function(val, options){ + options = options || {}; + if ('string' == typeof val) return parse(val); + return options.long + ? long(val) + : short(val); +}; + +/** + * Parse the given `str` and return milliseconds. + * + * @param {String} str + * @return {Number} + * @api private + */ + +function parse(str) { + str = '' + str; + if (str.length > 10000) return; + var match = /^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(str); + if (!match) return; + var n = parseFloat(match[1]); + var type = (match[2] || 'ms').toLowerCase(); + switch (type) { + case 'years': + case 'year': + case 'yrs': + case 'yr': + case 'y': + return n * y; + case 'days': + case 'day': + case 'd': + return n * d; + case 'hours': + case 'hour': + case 'hrs': + case 'hr': + case 'h': + return n * h; + case 'minutes': + case 'minute': + case 'mins': + case 'min': + case 'm': + return n * m; + case 'seconds': + case 'second': + case 'secs': + case 'sec': + case 's': + return n * s; + case 'milliseconds': + case 'millisecond': + case 'msecs': + case 'msec': + case 'ms': + return n; + } +} + +/** + * Short format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ + +function short(ms) { + if (ms >= d) return Math.round(ms / d) + 'd'; + if (ms >= h) return Math.round(ms / h) + 'h'; + if (ms >= m) return Math.round(ms / m) + 'm'; + if (ms >= s) return Math.round(ms / s) + 's'; + return ms + 'ms'; +} + +/** + * Long format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ + +function long(ms) { + return plural(ms, d, 'day') + || plural(ms, h, 'hour') + || plural(ms, m, 'minute') + || plural(ms, s, 'second') + || ms + ' ms'; +} + +/** + * Pluralization helper. + */ + +function plural(ms, n, name) { + if (ms < n) return; + if (ms < n * 1.5) return Math.floor(ms / n) + ' ' + name; + return Math.ceil(ms / n) + ' ' + name + 's'; +} + +},{}],588:[function(require,module,exports){ +'use strict'; +module.exports = Number.isNaN || function (x) { + return x !== x; +}; + +},{}],589:[function(require,module,exports){ +(function (process){ +// Copyright Joyent, Inc. and other Node contributors. +// +// 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. + +// resolves . and .. elements in a path array with directory names there +// must be no slashes, empty elements, or device names (c:\) in the array +// (so also no leading and trailing slashes - it does not distinguish +// relative and absolute paths) +function normalizeArray(parts, allowAboveRoot) { + // if the path tries to go above the root, `up` ends up > 0 + var up = 0; + for (var i = parts.length - 1; i >= 0; i--) { + var last = parts[i]; + if (last === '.') { + parts.splice(i, 1); + } else if (last === '..') { + parts.splice(i, 1); + up++; + } else if (up) { + parts.splice(i, 1); + up--; + } + } + + // if the path is allowed to go above the root, restore leading ..s + if (allowAboveRoot) { + for (; up--; up) { + parts.unshift('..'); + } + } + + return parts; +} + +// Split a filename into [root, dir, basename, ext], unix version +// 'root' is just a slash, or nothing. +var splitPathRe = + /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/; +var splitPath = function(filename) { + return splitPathRe.exec(filename).slice(1); +}; + +// path.resolve([from ...], to) +// posix version +exports.resolve = function() { + var resolvedPath = '', + resolvedAbsolute = false; + + for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) { + var path = (i >= 0) ? arguments[i] : process.cwd(); + + // Skip empty and invalid entries + if (typeof path !== 'string') { + throw new TypeError('Arguments to path.resolve must be strings'); + } else if (!path) { + continue; + } + + resolvedPath = path + '/' + resolvedPath; + resolvedAbsolute = path.charAt(0) === '/'; + } + + // At this point the path should be resolved to a full absolute path, but + // handle relative paths to be safe (might happen when process.cwd() fails) + + // Normalize the path + resolvedPath = normalizeArray(filter(resolvedPath.split('/'), function(p) { + return !!p; + }), !resolvedAbsolute).join('/'); + + return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.'; +}; + +// path.normalize(path) +// posix version +exports.normalize = function(path) { + var isAbsolute = exports.isAbsolute(path), + trailingSlash = substr(path, -1) === '/'; + + // Normalize the path + path = normalizeArray(filter(path.split('/'), function(p) { + return !!p; + }), !isAbsolute).join('/'); + + if (!path && !isAbsolute) { + path = '.'; + } + if (path && trailingSlash) { + path += '/'; + } + + return (isAbsolute ? '/' : '') + path; +}; + +// posix version +exports.isAbsolute = function(path) { + return path.charAt(0) === '/'; +}; + +// posix version +exports.join = function() { + var paths = Array.prototype.slice.call(arguments, 0); + return exports.normalize(filter(paths, function(p, index) { + if (typeof p !== 'string') { + throw new TypeError('Arguments to path.join must be strings'); + } + return p; + }).join('/')); +}; + + +// path.relative(from, to) +// posix version +exports.relative = function(from, to) { + from = exports.resolve(from).substr(1); + to = exports.resolve(to).substr(1); + + function trim(arr) { + var start = 0; + for (; start < arr.length; start++) { + if (arr[start] !== '') break; + } + + var end = arr.length - 1; + for (; end >= 0; end--) { + if (arr[end] !== '') break; + } + + if (start > end) return []; + return arr.slice(start, end - start + 1); + } + + var fromParts = trim(from.split('/')); + var toParts = trim(to.split('/')); + + var length = Math.min(fromParts.length, toParts.length); + var samePartsLength = length; + for (var i = 0; i < length; i++) { + if (fromParts[i] !== toParts[i]) { + samePartsLength = i; + break; + } + } + + var outputParts = []; + for (var i = samePartsLength; i < fromParts.length; i++) { + outputParts.push('..'); + } + + outputParts = outputParts.concat(toParts.slice(samePartsLength)); + + return outputParts.join('/'); +}; + +exports.sep = '/'; +exports.delimiter = ':'; + +exports.dirname = function(path) { + var result = splitPath(path), + root = result[0], + dir = result[1]; + + if (!root && !dir) { + // No dirname whatsoever + return '.'; + } + + if (dir) { + // It has a dirname, strip trailing slash + dir = dir.substr(0, dir.length - 1); + } + + return root + dir; +}; + + +exports.basename = function(path, ext) { + var f = splitPath(path)[2]; + // TODO: make this comparison case-insensitive on windows? + if (ext && f.substr(-1 * ext.length) === ext) { + f = f.substr(0, f.length - ext.length); + } + return f; +}; + + +exports.extname = function(path) { + return splitPath(path)[3]; +}; + +function filter (xs, f) { + if (xs.filter) return xs.filter(f); + var res = []; + for (var i = 0; i < xs.length; i++) { + if (f(xs[i], i, xs)) res.push(xs[i]); + } + return res; +} + +// String.prototype.substr - negative index don't work in IE8 +var substr = 'ab'.substr(-1) === 'b' + ? function (str, start, len) { return str.substr(start, len) } + : function (str, start, len) { + if (start < 0) start = str.length + start; + return str.substr(start, len); + } +; + +}).call(this,require('_process')) +},{"_process":594}],590:[function(require,module,exports){ +'use strict'; +var fs = require('fs') + +module.exports = function (pth, cb) { + var fn = typeof fs.access === 'function' ? fs.access : fs.stat; + + fn(pth, function (err) { + cb(null, !err); + }); +}; + +module.exports.sync = function (pth) { + var fn = typeof fs.accessSync === 'function' ? fs.accessSync : fs.statSync; + + try { + fn(pth); + return true; + } catch (err) { + return false; + } +}; + +},{"fs":220}],591:[function(require,module,exports){ +(function (process){ +'use strict'; + +function posix(path) { + return path.charAt(0) === '/'; +} + +function win32(path) { + // https://github.com/nodejs/node/blob/b3fcc245fb25539909ef1d5eaa01dbf92e168633/lib/path.js#L56 + var splitDeviceRe = /^([a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/]+[^\\\/]+)?([\\\/])?([\s\S]*?)$/; + var result = splitDeviceRe.exec(path); + var device = result[1] || ''; + var isUnc = Boolean(device && device.charAt(1) !== ':'); + + // UNC paths are always absolute + return Boolean(result[2] || isUnc); +} + +module.exports = process.platform === 'win32' ? win32 : posix; +module.exports.posix = posix; +module.exports.win32 = win32; + +}).call(this,require('_process')) +},{"_process":594}],592:[function(require,module,exports){ +/** + * JavaScript beautifier + * + * The code will call on Complexion to first tokenize the JavaScript and + * then run through these rules to insert appropriate whitespace. + * + * In procedure will be to run through each token. Whitespace tokens are + * removed and others will add whitespace again just after each token. All + * whitespace is managed by this beautifier. + */ +/*global exports, module, require*/ +// fid-umd {"depends":[{"name":"Complexion","commonjs":"complexion"},{"name":"complexionJs","commonjs":"complexion-js"}],"jslint":1,"name":"prettyJs"} +/*global define, YUI*/ +(function (n, r, f) { + "use strict"; + try { module.exports = f(require("complexion"), require("complexion-js")); return; } catch (ignore) {} + try { exports[n] = f(require("complexion"), require("complexion-js")); return; } catch (ignore) {} + try { return define.amd && define(n, ["Complexion", "complexionJs"], f); } catch (ignore) {} + try { return YUI.add(n, function (Y) { Y[n] = f(Y.Complexion, Y.complexionJs); }, "", { requires: ["Complexion", "complexionJs"] }); } catch (ignore) {} + try { r[n] = f(r.Complexion, r.complexionJs); return; } catch (ignore) {} + throw new Error("Unable to export " + n); +}("prettyJs", this, function (Complexion, complexionJs) { + "use strict"; + // fid-umd end + + var keywordContentProcessors, processors, punctuatorContentProcessors, tokenizer; + + /** + * Allowed options + * + * @typedef {Object} prettyJs~options + * @property {?boolean} bom Always add, remove, or just preserve BOM + * @property {string} commentSpace Spaces to the left of single comments + * @property {?string} convertStrings Set to "double", "single" or falsy + * @property {boolean} elseNewline When enabled, else and catch on new line + * @property {string} indent What to use for a single indent level + * @property {boolean} jslint Use jslint-compatible rules + * @property {string} newline What string to use for newlines + * @property {boolean} noSpaceAfterIf Remove space in "if (" + * @property {boolean} noSpaceAfterFor Remove space in "for (" + * @property {boolean} noSpaceAfterFunction Remove space in "function (" + * @property {boolean} noSpaceAfterSwitch Remove space in "switch (" + * @property {?boolean} quoteProperties Wrap object properties in quotes + */ + + /** + * @typedef {Object} prettyJs~resultBit + * @property {string} code + * @property {string} content + */ + + /** + * This is where the result of all of the hard work will end up + * + * @property {Array.} contexts Context and indentation + * @property {Array.} fragments Formatted output + * @property {prettyJs~options} options + */ + function Result(options) { + this.contexts = []; + this.fragments = []; + this.options = options; + } + + /** + * Adds a blank line if the previous non-whitespace token is a } or ; + */ + Result.prototype.addConditionalNewline = function () { + var prev; + + prev = this.getPreviousNonWhitespace(); + + if (!prev) { + return; + } + + if (prev.content === ';' || prev.content === '}') { + this.removeWhitespace(); + this.addNewline(); + this.addNewline(); + } + }; + + /** + * Sets a context and adds the indentation to the output + * + * @param {(string|prettyJs~resultBit)} code + * @param {string} [indent] defaults to this.options.indent + */ + Result.prototype.addContext = function (code, indent) { + if (typeof code !== 'object') { + if (indent === undefined) { + indent = this.options.indent; + } + + this.contexts.push({ + code: code, + content: indent + }); + } else { + this.contexts.push(code); + } + }; + + /** + * Adds a chunk of text to the list + * + * @param {string} code + * @param {string} type + */ + Result.prototype.addFragment = function (code, content) { + this.fragments.push({ + code: code, + content: content + }); + }; + + /** + * Adds a newline to the list + * + * Also can strip spaces and indentation so we don't have extra whitespace + * at the end of lines. + */ + Result.prototype.addNewline = function () { + var type; + + type = this.getType(); + + while (type === 'INDENT' || type === 'SPACE') { + this.removeFragment(); + type = this.getType(); + } + + this.addFragment('NEWLINE', this.options.newline); + this.addFragment('INDENT', this.getIndentation()); + }; + + /** + * Adds a space to the list + */ + Result.prototype.addSpace = function () { + return this.addFragment('SPACE', ' '); + }; + + /** + * Adds a chunk of text to the list based on a token + * + * @param {complexionJs~ComplexionJsToken} token + */ + Result.prototype.addToken = function (token) { + this.fragments.push({ + code: token.type, + content: token.content + }); + }; + + /** + * Returns true if a blank line should be added at the current position + * before adding a comment + * + * @return {boolean} + */ + Result.prototype.commentShouldHaveNewline = function () { + var check, last; + + last = this.getPreviousNonWhitespace(); + + // No extra newline at the beginning of a file + if (!last) { + return false; + } + + // No extra newline when following an open symbol + check = last.content; + + if (check === '{' || check === '(' || check === '[') { + return false; + } + + // No extra newline after some token types + check = last.code; + + if (check === 'LINE_COMMENT' || check === 'BOM') { + return false; + } + + return true; + }; + + /** + * Gets the current context, if there is one + * + * @return {?string} + */ + Result.prototype.getContextCode = function () { + if (!this.contexts.length) { + return null; + } + + return this.contexts[this.contexts.length - 1].code; + }; + + /** + * Returns the last fragment object + * + * @return {?prettyJs~resultBit} + */ + Result.prototype.getFragment = function () { + if (!this.fragments.length) { + return null; + } + + return this.fragments[this.fragments.length - 1]; + }; + + /** + * Returns the current indentation string + * + * @return {string} + */ + Result.prototype.getIndentation = function () { + var i, str; + + str = ''; + + for (i = 0; i < this.contexts.length; i += 1) { + str += this.contexts[i].content; + } + + return str; + }; + + /** + * Returns the last fragment which is not whitespace. + * + * @return {?prettyJs~resultBit} + */ + Result.prototype.getPreviousNonWhitespace = function () { + var code, i; + + for (i = this.fragments.length - 1; i >= 0; i -= 1) { + code = this.fragments[i].code; + + if (code !== 'SPACE' && code !== 'INDENT' && code !== 'NEWLINE') { + return this.fragments[i]; + } + } + + return null; + }; + + /** + * Returns the text from the last fragment added + * + * Does not call getFragment for speed (saves a function call) + * + * @return {?string} + */ + Result.prototype.getText = function () { + if (!this.fragments.length) { + return null; + } + + return this.fragments[this.fragments.length - 1].content; + }; + + /** + * Returns the code from the last fragment added + * + * Does not call getFragment for speed (saves a function call) + * + * @return {?string} + */ + Result.prototype.getType = function () { + if (!this.fragments.length) { + return null; + } + + return this.fragments[this.fragments.length - 1].code; + }; + + /** + * Return true if we could be making an array literal + * + * Does not call getFragment for speed (saves a function call) + * + * @return {boolean} + */ + Result.prototype.isArrayLiteral = function () { + var prev; + + prev = this.getPreviousNonWhitespace(); + + if (!prev) { + return true; + } + + if (prev.code === 'KEYWORD') { + // Things that allow properties + if (prev.content === 'this' || prev.content === 'super') { + // this['some property'] + return false; + } + + return true; + } + + if (prev.code === 'IDENTIFIER_NAME') { + // thing[1] + return false; + } + + if (prev.content === ')' || prev.content === ']') { + // test()[1] + // multiArray[0][1] + return false; + } + + return true; + }; + + /** + * Return true if we could be doing type conversion at this point + * + * @return {boolean} + */ + Result.prototype.isTypeConversion = function () { + var prev; + + if (!this.fragments.length) { + return true; + } + + prev = this.getPreviousNonWhitespace(); + + if (!prev) { + return true; + } + + if (prev.code === 'KEYWORD') { + return true; + } + + // Most punctuators imply that the next thing done will likely be + // a type conversion. The rest seem to imply math. + if (prev.code !== 'PUNCTUATOR') { + return false; + } + + // These are all flags for math + if (prev.content === ')' || prev.content === '}' || prev.content === ']') { + return false; + } + + return true; + }; + + /** + * Returns true if the last token was a newline. Skips spaces and + * indentation. + * + * @return {boolean} + */ + Result.prototype.lastWasNewline = function () { + var code, i; + + i = this.fragments.length - 1; + + while (i >= 0) { + code = this.fragments[i].code; + + if (code === 'NEWLINE') { + return true; + } + + if (code !== 'SPACE' && code !== 'INDENT') { + return false; + } + + i -= 1; + } + + // Slightly odd. No content's the same as a newline. + return true; + }; + + /** + * Removes a level from the context + * + * @return {?prettyJs~resultBit} + */ + Result.prototype.removeContext = function () { + var self; + + self = this; + + if (!self.contexts.length) { + // Force indents to go up when there were no contexts + self.fragments.forEach(function (fragment) { + if (fragment.code === 'INDENT') { + fragment.content = self.options.indent + fragment.content; + } + }); + + return null; + } + + return self.contexts.pop(); + }; + + + /** + * Removes a level from the context when the context should end at + * the end of a statement. This method will get called when hitting + * a semicolon, closing brace, and in other situations that would + * indicate that a statement is complete. The contexts associated + * with statement-level constructs would be removed. + */ + Result.prototype.removeContextForStatement = function () { + var context; + + context = this.getContextCode(); + + while (context === 'IF' || context === 'ELSE' || context === 'FOR' || context === 'TERNARY' || context === 'VAR') { + this.removeContext(); + context = this.getContextCode(); + } + }; + + + /** + * Removes a fragment from the stack + * + * @return {?prettyJs~resultBit} + */ + Result.prototype.removeFragment = function () { + if (!this.fragments.length) { + return null; + } + + return this.fragments.pop(); + }; + + /** + * Removes whitespace from the end of the fragments + */ + Result.prototype.removeWhitespace = function () { + var type; + + type = this.getType(); + + while (type === 'NEWLINE' || type === 'SPACE' || type === 'INDENT') { + this.removeFragment(); + type = this.getType(); + } + }; + + /** + * Returns the result as a string + * + * @return {string} + */ + Result.prototype.toString = function () { + var i, str; + + str = ''; + + for (i = 0; i < this.fragments.length; i += 1) { + str += this.fragments[i].content; + } + + return str; + }; + + /** + * Convert a quoted string to a different quoting method + * + * @param {prettyJs~Result} result + * @param {string} content String content WITH QUOTES + * @return {string} Converted string + */ + function convertString(result, content) { + var converted, quote; + + if (!result.options.convertStrings) { + return content; + } + + if (result.options.convertStrings === 'single') { + quote = "'"; + } else { + quote = '"'; + } + + if (content.charAt(0) === quote) { + return content; + } + + // Remove quotes + converted = content.substr(1, content.length - 2); + + /* Unescape all quotes and be careful with properly escaped + * backslashes, like "\\'" + */ + /*jslint regexp:true*/ + converted = converted.replace(/\\./g, function (match) { + /*jslint regexp:false*/ + var c; + + c = match.charAt(1); + + if (c === '"' || c === "'") { + return c; + } + + return match; + }); + + // Escape our quotes again + converted = converted.replace(new RegExp(quote, 'g'), '\\' + quote); + + return quote + converted + quote; + } + + /** + * Initialize options with their default values and guarantee that the + * options variable is an object. + * + * @param {*} options + * @return {prettyJs~options} options + */ + function initializeOptions(options) { + var defaults; + + defaults = { + bom: false, // Causes problems and unnecessary with UTF-8 + commentSpace: " ", // Looks nice before single line comments + convertStrings: "double", // Mimics JSON + elseNewline: false, // Matches jslint rules + indent: ' ', // The eternal spaces vs. tabs debate + jslint: false, // Some jslint-specific rules + newline: "\n", // Unix-style newlines + quoteProperties: false, // Prefer to unquote properties + trailingNewline: false // Prefer to remove trailing newline + }; + + if (!options) { + options = {}; + } + + Object.keys(defaults).forEach(function (key) { + if (options[key] === undefined) { + options[key] = defaults[key]; + } + }); + + if (options.convertStrings !== 'single' && options.convertStrings !== 'double') { + options.convertStrings = false; + } + + if (options.jslint) { + options.quoteProperties = false; + } + + return options; + } + + /** + * Token processing function + * + * @typedef {Function} prettyJs~processor + * @param {prettyJs~Result} result + * @param {complexionJs~ComplexionJsToken} token + */ + + /** + * Hand off the token processing to another function based on + * the token's content. + * + * @param {Object} rules Map of exact string to processor + * @param {prettyJs~processor} defaultProcessor + * @return {prettyJs~processor} + */ + function processByContent(rules, defaultProcessor) { + return function (result, token) { + var fn; + + if (rules.hasOwnProperty(token.content)) { + fn = rules[token.content]; + } else { + fn = defaultProcessor; + } + + return fn(result, token); + }; + } + + + /** + * Passes off an individual token to a processing function. + * + * @param {prettyJs~result} + * @param {complexionJs~ComplexionJsToken} token + * @param {number} index + * @param {Array.} tokenList + */ + function processToken(result, token, index, tokenList) { + var fn; + + fn = processors[token.type]; + + if (!fn) { + throw new Error('Unhandled token type ' + token.type + ' at line ' + token.line + ' col ' + token.col + ', offset ' + token.offset); + } + + fn(result, token, index, tokenList); + } + + /** + * Byte order mark + * + * If the `bom` option is set to `true` or `false` we always remove it. + * When it's true, the BOM is added immediately by the prettyJs + * function itself. + * + * @param {prettyJs~Result} result + */ + function tokenBom(result) { + if (result.options.bom === null || result.options.bom === undefined) { + result.addFragment("BOM", "\ufeff"); + } + } + + /** + * Copy a token to the result. + * + * @param {prettyJs~Result} result + * @param {complexionJs~ComplexionJsToken} token + */ + function tokenCopy(result, token) { + result.addToken(token); + } + + /** + * Copy a token to the result and add a newline. + * + * @param {prettyJs~Result} result + * @param {complexionJs~ComplexionJsToken} token + */ + function tokenCopyAndNewline(result, token) { + result.addToken(token); + result.addNewline(); + } + + /** + * Copy a token to the result and add a space. + * + * @param {prettyJs~Result} result + * @param {complexionJs~ComplexionJsToken} token + */ + function tokenCopyAndSpace(result, token) { + result.addToken(token); + result.addSpace(); + } + + /** + * Switches may have "case" and "default" outdented. + * + * @param {prettyJs~Result} result + * @param {complexionJs~ComplexionJsToken} token + */ + function tokenKeywordCase(result, token) { + var context; + + context = result.getContextCode(); + + if (context === 'BRACE') { + // Treat this as an identifier + return tokenCopyAndSpace(result, token); + } + + result.removeWhitespace(); + + /* Add a blank line between this keyword and the previous + * content unless it's the first "case" in a switch or + * there's multiple "case"/"default" rules together. + */ + if (result.getText() !== '{' && result.getText() !== ':') { + result.addNewline(); + } + + if (result.options.jslint) { + context = result.removeContext(); + result.addNewline(); + result.addContext(context); + } else { + if (result.getContextCode() !== 'SWITCH_BLOCK') { + result.removeContext(); + } + + result.addNewline(); + result.addContext(token.content.toUpperCase()); + } + + tokenCopyAndSpace(result, token); + } + + /** + * The start of a control flow block + * + * @param {prettyJs~Result} result + * @param {complexionJs~ComplexionJsToken} token + */ + function tokenKeywordControlFlow(result, token) { + result.addConditionalNewline(); + tokenCopyAndSpace(result, token); + result.addContext(token.content.toUpperCase(), ''); + } + + /** + * "else" and "catch" should be on the same line as a closing } + * but "else" should be on a new, unindented line when there was no } + * + * @param {prettyJs~Result} result + * @param {complexionJs~ComplexionJsToken} token + */ + function tokenKeywordElse(result, token) { + var prev; + + // Remove newlines and indentation + result.removeWhitespace(); + + if (!result.options.elseNewline) { + prev = result.getFragment(); + + if (prev) { + if (prev.content === '}') { + result.addSpace(); + } else { + result.addNewline(); + } + } + } else { + // Reducing to just one newline + result.addNewline(); + } + + tokenCopyAndSpace(result, token); + result.addContext(token.content.toUpperCase(), ''); + } + + /** + * These statements should have a newline in front of them if + * they are the first content on the line + * + * @param {prettyJs~Result} result + * @param {complexionJs~ComplexionJsToken} token + */ + function tokenKeywordOffsetLine(result, token) { + result.addConditionalNewline(); + tokenCopyAndSpace(result, token); + } + + /** + * The variables declared in `var` should be indented. + * + * @param {prettyJs~Result} result + * @param {complexionJs~ComplexionJsToken} token + */ + function tokenKeywordVar(result, token) { + tokenCopyAndSpace(result, token); + result.addContext('VAR'); + } + + /** + * Lots of minor changes: + * - Standardizes newlines + * - Removes trailing whitespace + * - Starts all lines with an aligned "*" + * - Reindents + * - 2 blank lines before multi-line comments + * + * @param {prettyJs~Result} result + * @param {complexionJs~ComplexionJsToken} token + */ + function tokenMultiLineComment(result, token) { + var addNewline, addSpace, str; + + // Standardize newlines into ones I prefer + str = token.content.replace(/\r?\n|\r/g, "\n"); + + // Removing closing comment tag + str = str.replace(/\*\/$/, ''); + + // Remember if there was a newline right before this tag + addNewline = false; + + if (str.match(/\n[ \t\f]*$/)) { + addSpace = false; + addNewline = true; + str = str.replace(/\n[ \t\f]*$/, ''); + } else { + // Remember if there was a space right before the end tag + /*jslint regexp:true*/ + addSpace = str.match(/[^ \t\f\n]([ \t\f]*)$/); + /*jslint regexp:false*/ + + if (addSpace && addSpace[1]) { + addSpace = addSpace[1]; + str = str.substr(0, str.length - addSpace.length); + } else { + addSpace = false; + } + } + + // Remove trailing whitespace and whitespace after newlines + str = str.replace(/[ \t\f]*\n/g, "\n").replace(/\n[ \t\f]*/g, "\n"); + + // Force all lines to start with indentation + space + star + space + str = str.replace(/\n\*/g, "\n"); // Remove stars + /*jslint regexp:true*/ + str = str.replace(/\n([^ \n])/g, "\n $1"); // Adds a space + /*jslint regexp:false*/ + str = str.replace(/\n/g, "\n" + result.getIndentation() + " *"); // Add star + + /*jslint regexp:true*/ + str = str.replace(/([^\* ])(\*\/)$/, '$1 $2'); + /*jslint regexp:false*/ + + // Convert newlines into ones you prefer + if (result.options.newline !== "\n") { + str = str.replace(/\n/g, result.options.newline); + } + + // Add closing tag back + if (addNewline) { + str += "\n" + result.getIndentation() + ' '; + } else { + // Add the spacing back + if (addSpace) { + str += addSpace; + } + } + + str += '*/'; + + if (result.commentShouldHaveNewline()) { + result.removeWhitespace(); + result.addNewline(); + result.addNewline(); + result.addNewline(); + } + + result.addFragment('BLOCK_COMMENT', str); + result.addNewline(); + } + + /** + * Handles what happens with close braces + * + * @param {prettyJs~Result} result + * @param {complexionJs~ComplexionJsToken} token + */ + function tokenPunctuatorBraceClose(result, token) { + var context, extraNewline; + + // Terminate a statement if one was started + result.removeContextForStatement(); + + // Decrease indentation + result.removeContext(); + result.removeWhitespace(); + context = result.getContextCode(); + extraNewline = false; + + if (context === 'SWITCH_BLOCK') { + // The last context could have been from "case" or "default" + result.removeContext(); + context = result.getContextCode(); + } + + if (context === 'CATCH' || context === 'ELSE' || context === 'FOR' || context === 'FINALLY' || context === 'FUNCTION' || context === 'IF' || context === 'SWITCH') { + // Done with the function declaration or block of code + result.removeContext(); + + if (result.getContextCode() === 'ELSE') { + result.removeContext(); + } + + extraNewline = true; + } + + // If not empty, add a newline + if (result.getText() !== '{') { + result.addNewline(); + } + + // Add content, newline + result.addFragment('PUNCTUATOR', token.content); + result.addNewline(); + + // If this was a function or similar, add another newline + if (extraNewline) { + result.addNewline(); + } + } + + /** + * Handles what happens after open braces + * + * @param {prettyJs~Result} result + * @param {complexionJs~ComplexionJsToken} token + */ + function tokenPunctuatorBraceOpen(result, token) { + var context; + + context = result.getContextCode(); + + // Remember some contexts so we can key off them later + if (context === 'FOR' || context === 'FUNCTION' || context === 'SWITCH' || context === 'IF' || context === 'ELSE') { + result.addContext(context + '_BLOCK'); + } else { + result.addContext('BRACE'); + } + + result.addToken(token); + result.addNewline(); + } + + /** + * Handles what happens after closing brackets + * + * @param {prettyJs~Result} result + * @param {complexionJs~ComplexionJsToken} token + */ + function tokenPunctuatorBracketClose(result, token) { + var lastText, prevContext; + + // Decrease indentation + prevContext = result.removeContext(); + result.removeWhitespace(); + lastText = result.getText(); + + if (prevContext.code !== 'ARRAY_INDEX' && (lastText !== '(' && lastText !== '{' && lastText !== '[')) { + result.addNewline(); + } + + return tokenCopyAndSpace(result, token); + } + + /** + * Handles what happens after open brackets + * + * @param {prettyJs~Result} result + * @param {complexionJs~ComplexionJsToken} token + */ + function tokenPunctuatorBracketOpen(result, token) { + if (result.isArrayLiteral()) { + result.addContext('BRACKET'); + result.addToken(token); + result.addNewline(); + } else { + result.removeWhitespace(); + result.addContext('ARRAY_INDEX'); + result.addToken(token); + } + } + + /** + * Handles colons + * + * Switches, ternary, object literals + * + * @param {prettyJs~Result} result + * @param {complexionJs~ComplexionJsToken} token + */ + function tokenPunctuatorColon(result, token) { + var context, prev; + + /** + * Returns true if the string passed in can be an identifier without + * additional quoting + * + * @param {string} content + * @return {boolean} + */ + function canBeIdentifier(content) { + var tokenList; + + // Reuse the tokenizer to see if the content is an identifier + tokenList = tokenizer.tokenize(content); + + if (tokenList.length !== 1 || tokenList[0].type !== 'IDENTIFIER_NAME') { + return false; + } + + if (!result.options.jslint) { + return true; + } + + if (content.charAt(0) === '_' || content.charAt(-1) === '_') { + return false; + } + + return true; + } + + context = result.getContextCode(); + + if (context === 'CATCH') { + /* This should be a keyword instead + * + * { catch: false } + * + * Remove the CATCH context + */ + result.removeContext(); + context = result.getContextCode(); + } + + if (context === 'SWITCH_BLOCK' || context === 'CASE' || context === 'DEFAULT') { + result.removeWhitespace(); + result.addToken(token); + result.addNewline(); + + return; + } + + if (context !== 'TERNARY') { + // Property name as a string or identifier + result.removeWhitespace(); + + if (result.options.quoteProperties === true) { + // Force quotes + if (result.getType() === 'IDENTIFIER_NAME' || result.getType() === 'KEYWORD') { + prev = result.removeFragment(); + result.addFragment('STRING', convertString(result, JSON.stringify(prev.content))); + } + } else if (result.options.quoteProperties === false) { + // Remove quotes when possible + if (result.getType() === 'STRING') { + prev = result.getFragment().content; + prev = prev.substr(1, prev.length - 2); + + if (canBeIdentifier(prev)) { + result.removeFragment(); + result.addFragment('IDENTIFIER_NAME', prev); + } + } + } + } + + return tokenCopyAndSpace(result, token); + } + + /** + * Pre/Post Increment/Decrement (++ and --) + * + * No space between the identifier and the punctuator when the + * specific option is enabled. + * + * @param {prettyJs~Result} result + * @param {complexionJs~ComplexionJsToken} token + */ + function tokenPunctuatorIncDec(result, token) { + function isPre() { + var prev; + + prev = result.getPreviousNonWhitespace(); + + if (!prev || prev.code !== 'IDENTIFIER_NAME') { + return true; + } + + return false; + } + + if (!result.options.noSpaceWithIncDec) { + return tokenCopyAndSpace(result, token); + } + + if (isPre()) { + return tokenCopy(result, token); + } + + result.removeWhitespace(); + + return tokenCopyAndSpace(result, token); + } + + /** + * Handles commas + * + * jslint only increases indentation when there is a comma + * inside a function's argument list. + * test(function () { + * oneLevelIndent(); + * }); + * test2(true, + * function () { + * twoLevelIndent(); + * }); + * + * In order to attach to the previous token, no whitespace before this one. + * + * Add newline if we are not in a var / function's context. + * + * { + * a: a, + * b: b + * } + * + * return a(), + * b; + * + * No newline sometimes (var / function call) + * + * var a, b; + * + * a(b, c); + * + * @param {prettyJs~Result} result + * @param {complexionJs~ComplexionJsToken} token + */ + function tokenPunctuatorComma(result, token) { + var context; + + result.removeWhitespace(); + context = result.getContextCode(); + + if (context === 'TERNARY') { + result.removeContext(); + context = result.getContextCode(); + } + + result.addToken(token); + + if (context === 'FUNCTION_ARGS') { + /* This is the first comma seen in a function call. It sets a + * new context that can be used for indentation on other things + * for jslint-compatible formatting. + */ + result.addContext('FUNCTION_ARGS_COMMA', ''); + result.addSpace(); + } else if (context === 'FUNCTION_ARGS_COMMA' || context === 'VAR' || context === 'FOR_CONDITION') { + /* Only add a space for "var" and "for" + * + * var a, b, c; + * + * for (a = 1, b = 2; ... + * + * x(1, 2) + */ + result.addSpace(); + } else if (context === 'BRACE' || context === 'BRACKET') { + /* Add newlines inside arrays and objects + * + * x = [ + * 1, + * 2 + * ]; + * + * x = { + * a: 1, + * b: 2 + * }; + */ + result.addNewline(); + } else { + /* Merging multiple lines onto one, typically from a minifier + * + * return a = f(), + * a[1] = 123, + * a; + */ + result.addContext('COMMA_OPERATOR'); + result.addNewline(); + result.removeContext('COMMA_OPERATOR'); + } + } + + /** + * Handles what happens after closing parenthesis + * + * @param {prettyJs~Result} result + * @param {complexionJs~ComplexionJsToken} token + */ + function tokenPunctuatorParenthesisClose(result, token) { + result.removeContextForStatement(); + + if (result.getContextCode() === 'FUNCTION_ARGS_COMMA') { + result.removeContext(); + } + + result.removeContext(); + result.removeWhitespace(); + + return tokenCopyAndSpace(result, token); + } + + /** + * Handles what happens after open parenthesis + * + * @param {prettyJs~Result} result + * @param {complexionJs~ComplexionJsToken} token + */ + function tokenPunctuatorParenthesisOpen(result, token) { + var context, prev; + + prev = result.getPreviousNonWhitespace(); + + if (!prev) { + result.addContext('PAREN', ''); + } else if (prev.code === 'IDENTIFIER_NAME' || prev.content === '}' || prev.content === ')' || prev.content === ']') { + // someFunction( + // function something() {}( + // (function () {})( + // methods[x]( + result.removeWhitespace(); + result.addContext('FUNCTION_ARGS', ''); + } else if (prev.content === 'function') { + // function ( + if (result.options.noSpaceAfterFunction) { + result.removeWhitespace(); + } + + result.addContext('FUNCTION_ARGS', ''); + } else { + context = result.getContextCode(); + + if (context === 'IF') { + // if ( + if (result.options.noSpaceAfterIf) { + result.removeWhitespace(); + } + + result.addContext('IF_CONDITION'); + } else if (context === 'FOR') { + // for ( + if (result.options.noSpaceAfterFor) { + result.removeWhitespace(); + } + + result.addContext('FOR_CONDITION', ''); + } else { + // This function can only be called for "function", + // "for", "if" and "switch". This needs to be "switch". + if (result.options.noSpaceAfterSwitch) { + result.removeWhitespace(); + } + + result.addContext('PAREN', ''); + } + } + + // No space after open parenthesis + result.addToken(token); + } + + /** + * Handles periods + * + * Attach to the content before and after. + * + * @param {prettyJs~Result} result + * @param {complexionJs~ComplexionJsToken} token + */ + function tokenPunctuatorPeriod(result, token) { + result.removeWhitespace(); + result.addToken(token); + } + + /** + * Plus and Minus + * + * No space following the plus or minus if we are doing type conversion. + * + * @param {prettyJs~Result} result + * @param {complexionJs~ComplexionJsToken} token + */ + function tokenPunctuatorPlusMinus(result, token) { + var isTypeConversion; + + // Check if this is type conversion before adding the symbol + isTypeConversion = result.isTypeConversion(); + result.addToken(token); + + if (!isTypeConversion) { + result.addSpace(); + } + } + + /** + * Handles question marks, a ternary operation + * + * @param {prettyJs~Result} result + * @param {complexionJs~ComplexionJsToken} token + */ + function tokenPunctuatorQuestion(result, token) { + result.addContext('TERNARY', ''); + result.addToken(token); + result.addSpace(); + } + + /** + * Adds a semicolon and newline + * + * Do not use the token content here because it may be an implicit + * semicolon, which does not have content. + * + * Extra newlines after a "var" statement and after a "use strict". + * + * @param {prettyJs~Result} result + */ + function tokenSemicolon(result) { + var oldContext, previousText; + + function needsTwoNewlines() { + if (oldContext === 'VAR') { + // var a, b, c; + return true; + } + + if (previousText === '"use strict"' || previousText === "'use strict'") { + // "use strict"; + // 'use strict'; + return true; + } + + return false; + } + + oldContext = result.getContextCode(); + result.removeContextForStatement(); + result.removeWhitespace(); + previousText = result.getText(); + result.addFragment('SEMICOLON', ';'); // Do not use token.content here + + if (result.getContextCode() === 'FOR_CONDITION') { + // for (a = 1; + // for (a = 1; a < b; + result.addSpace(); + } else { + if (needsTwoNewlines()) { + result.addNewline(); + } + + result.addNewline(); + } + } + + /** + * Skips the addition of a token to the result + */ + function tokenSkip() { + return undefined; + } + + /** + * If the comment had no prior content on the line, then check if the + * the comment should have a newline. If so, wipe out the whitespace + * and add a couple of newlines. If there was content already on the + * line, remove whitespace and add the commentSpace before the comment. + * + * @param {prettyJs~Result} result + * @param {complexionJs~ComplexionJsToken} token + * @param {number} index + * @param {Array.} tokenList + */ + function tokenSingleLineComment(result, token, index, tokenList) { + var str; + + /** + * Detect if the comment was originally on the same line as + * some code. + * + * @return {boolean} + */ + function originallyOnSameLine() { + var check; + + while (index) { + index -= 1; + check = tokenList[index].type; + + if (check === 'LINE_TERMINATOR') { + return false; + } + + if (check !== 'WHITESPACE') { + /** + * Check the content to see if a newline would make sense + * in this situation. + */ + check = tokenList[index].content; + + if (check === '{' || check === '[') { + return false; + } + + return true; + } + } + } + + // Remove trailing whitespace + str = token.content.replace(/ [\t\f]*\n/g, result.options.newline); + + if (originallyOnSameLine() || !result.lastWasNewline()) { + result.removeWhitespace(); + result.addFragment('COMMENT_WHITESPACE', result.options.commentSpace); + result.addFragment('STATEMENT_COMMENT', str); + } else { + if (result.commentShouldHaveNewline(index, tokenList)) { + result.removeWhitespace(); + result.addNewline(); + result.addNewline(); + } + + result.addFragment('LINE_COMMENT', str); + } + + result.addNewline(); + } + + /** + * Processes a string and may convert the string to single or double + * quotes. + * + * @param {prettyJs~Result} result + * @param {complexionJs~ComplexionJsToken} token + */ + function tokenString(result, token) { + var str; + + str = convertString(result, token.content); + result.addFragment('STRING', str); + result.addSpace(); + } + + // Initialize a new tokenizer with the default options + tokenizer = new Complexion(); + complexionJs(tokenizer); + keywordContentProcessors = { + 'case': tokenKeywordCase, + 'catch': tokenKeywordElse, + 'default': tokenKeywordCase, + 'else': tokenKeywordElse, + 'finally': tokenKeywordElse, + 'for': tokenKeywordControlFlow, + 'function': tokenKeywordControlFlow, + 'if': tokenKeywordControlFlow, + 'return': tokenKeywordOffsetLine, + 'switch': tokenKeywordControlFlow, + 'throw': tokenKeywordOffsetLine, + 'try': tokenKeywordOffsetLine, + 'var': tokenKeywordVar, + 'while': tokenKeywordOffsetLine + }; + punctuatorContentProcessors = { + '{': tokenPunctuatorBraceOpen, + '}': tokenPunctuatorBraceClose, + '[': tokenPunctuatorBracketOpen, + ']': tokenPunctuatorBracketClose, + '(': tokenPunctuatorParenthesisOpen, + ')': tokenPunctuatorParenthesisClose, + '.': tokenPunctuatorPeriod, + ';': tokenSemicolon, + ',': tokenPunctuatorComma, + ':': tokenPunctuatorColon, + '+': tokenPunctuatorPlusMinus, + '-': tokenPunctuatorPlusMinus, + '++': tokenPunctuatorIncDec, + '--': tokenPunctuatorIncDec, + '!': tokenCopy, + '?': tokenPunctuatorQuestion + }; + processors = { + BOM: tokenBom, + BOOLEAN_LITERAL: tokenCopyAndSpace, + IDENTIFIER_NAME: tokenCopyAndSpace, + IMPLICIT_SEMICOLON: tokenSemicolon, + KEYWORD: processByContent(keywordContentProcessors, tokenCopyAndSpace), + LINE_TERMINATOR: tokenSkip, // Other rules manage all spaces + MULTI_LINE_COMMENT: tokenMultiLineComment, + NULL_LITERAL: tokenCopyAndSpace, + NUMERIC_LITERAL: tokenCopyAndSpace, + PUNCTUATOR: processByContent(punctuatorContentProcessors, tokenCopyAndSpace), + REGULAR_EXPRESSION_LITERAL: tokenCopyAndSpace, + SHEBANG: tokenCopyAndNewline, + SINGLE_LINE_COMMENT: tokenSingleLineComment, + STRING_LITERAL: tokenString, + WHITESPACE: tokenSkip // Other rules manage all whitespace + }; + + return function (str, options) { + var result, tokenList; + + options = initializeOptions(options); + tokenList = tokenizer.tokenize(str); + result = new Result(options); + + if (options.bom === true) { + // See tokenBom for why this always adds a new token + result.addFragment("BOM", "\ufeff"); + } + + // Set a placeholder for a zero-length indentation + result.addFragment('INDENT', result.getIndentation()); + tokenList.forEach(function (token, index) { + processToken(result, token, index, tokenList); + }); + result.removeWhitespace(); + + if (options.trailingNewline === true) { + result.addNewline(); + } + + return result.toString(); + }; + + // fid-umd post +})); +// fid-umd post-end + +},{"complexion":229,"complexion-js":228}],593:[function(require,module,exports){ +"use strict"; + +var originalObject = Object; +var originalDefProp = Object.defineProperty; +var originalCreate = Object.create; + +function defProp(obj, name, value) { + if (originalDefProp) try { + originalDefProp.call(originalObject, obj, name, { value: value }); + } catch (definePropertyIsBrokenInIE8) { + obj[name] = value; + } else { + obj[name] = value; + } +} + +// For functions that will be invoked using .call or .apply, we need to +// define those methods on the function objects themselves, rather than +// inheriting them from Function.prototype, so that a malicious or clumsy +// third party cannot interfere with the functionality of this module by +// redefining Function.prototype.call or .apply. +function makeSafeToCall(fun) { + if (fun) { + defProp(fun, "call", fun.call); + defProp(fun, "apply", fun.apply); + } + return fun; +} + +makeSafeToCall(originalDefProp); +makeSafeToCall(originalCreate); + +var hasOwn = makeSafeToCall(Object.prototype.hasOwnProperty); +var numToStr = makeSafeToCall(Number.prototype.toString); +var strSlice = makeSafeToCall(String.prototype.slice); + +var cloner = function(){}; +function create(prototype) { + if (originalCreate) { + return originalCreate.call(originalObject, prototype); + } + cloner.prototype = prototype || null; + return new cloner; +} + +var rand = Math.random; +var uniqueKeys = create(null); + +function makeUniqueKey() { + // Collisions are highly unlikely, but this module is in the business of + // making guarantees rather than safe bets. + do var uniqueKey = internString(strSlice.call(numToStr.call(rand(), 36), 2)); + while (hasOwn.call(uniqueKeys, uniqueKey)); + return uniqueKeys[uniqueKey] = uniqueKey; +} + +function internString(str) { + var obj = {}; + obj[str] = true; + return Object.keys(obj)[0]; +} + +// External users might find this function useful, but it is not necessary +// for the typical use of this module. +defProp(exports, "makeUniqueKey", makeUniqueKey); + +// Object.getOwnPropertyNames is the only way to enumerate non-enumerable +// properties, so if we wrap it to ignore our secret keys, there should be +// no way (except guessing) to access those properties. +var originalGetOPNs = Object.getOwnPropertyNames; +Object.getOwnPropertyNames = function getOwnPropertyNames(object) { + for (var names = originalGetOPNs(object), + src = 0, + dst = 0, + len = names.length; + src < len; + ++src) { + if (!hasOwn.call(uniqueKeys, names[src])) { + if (src > dst) { + names[dst] = names[src]; + } + ++dst; + } + } + names.length = dst; + return names; +}; + +function defaultCreatorFn(object) { + return create(null); +} + +function makeAccessor(secretCreatorFn) { + var brand = makeUniqueKey(); + var passkey = create(null); + + secretCreatorFn = secretCreatorFn || defaultCreatorFn; + + function register(object) { + var secret; // Created lazily. + + function vault(key, forget) { + // Only code that has access to the passkey can retrieve (or forget) + // the secret object. + if (key === passkey) { + return forget + ? secret = null + : secret || (secret = secretCreatorFn(object)); + } + } + + defProp(object, brand, vault); + } + + function accessor(object) { + if (!hasOwn.call(object, brand)) + register(object); + return object[brand](passkey); + } + + accessor.forget = function(object) { + if (hasOwn.call(object, brand)) + object[brand](passkey, true); + }; + + return accessor; +} + +defProp(exports, "makeAccessor", makeAccessor); + +},{}],594:[function(require,module,exports){ +// shim for using process in browser +var process = module.exports = {}; + +// cached from whatever global is present so that test runners that stub it +// don't break things. But we need to wrap it in a try catch in case it is +// wrapped in strict mode code which doesn't define any globals. It's inside a +// function because try/catches deoptimize in certain engines. + +var cachedSetTimeout; +var cachedClearTimeout; + +function defaultSetTimout() { + throw new Error('setTimeout has not been defined'); +} +function defaultClearTimeout () { + throw new Error('clearTimeout has not been defined'); +} +(function () { + try { + if (typeof setTimeout === 'function') { + cachedSetTimeout = setTimeout; + } else { + cachedSetTimeout = defaultSetTimout; + } + } catch (e) { + cachedSetTimeout = defaultSetTimout; + } + try { + if (typeof clearTimeout === 'function') { + cachedClearTimeout = clearTimeout; + } else { + cachedClearTimeout = defaultClearTimeout; + } + } catch (e) { + cachedClearTimeout = defaultClearTimeout; + } +} ()) +function runTimeout(fun) { + if (cachedSetTimeout === setTimeout) { + //normal enviroments in sane situations + return setTimeout(fun, 0); + } + // if setTimeout wasn't available but was latter defined + if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { + cachedSetTimeout = setTimeout; + return setTimeout(fun, 0); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedSetTimeout(fun, 0); + } catch(e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedSetTimeout.call(null, fun, 0); + } catch(e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error + return cachedSetTimeout.call(this, fun, 0); + } + } + + +} +function runClearTimeout(marker) { + if (cachedClearTimeout === clearTimeout) { + //normal enviroments in sane situations + return clearTimeout(marker); + } + // if clearTimeout wasn't available but was latter defined + if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { + cachedClearTimeout = clearTimeout; + return clearTimeout(marker); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedClearTimeout(marker); + } catch (e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedClearTimeout.call(null, marker); + } catch (e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. + // Some versions of I.E. have different rules for clearTimeout vs setTimeout + return cachedClearTimeout.call(this, marker); + } + } + + + +} +var queue = []; +var draining = false; +var currentQueue; +var queueIndex = -1; + +function cleanUpNextTick() { + if (!draining || !currentQueue) { + return; + } + draining = false; + if (currentQueue.length) { + queue = currentQueue.concat(queue); + } else { + queueIndex = -1; + } + if (queue.length) { + drainQueue(); + } +} + +function drainQueue() { + if (draining) { + return; + } + var timeout = runTimeout(cleanUpNextTick); + draining = true; + + var len = queue.length; + while(len) { + currentQueue = queue; + queue = []; + while (++queueIndex < len) { + if (currentQueue) { + currentQueue[queueIndex].run(); + } + } + queueIndex = -1; + len = queue.length; + } + currentQueue = null; + draining = false; + runClearTimeout(timeout); +} + +process.nextTick = function (fun) { + var args = new Array(arguments.length - 1); + if (arguments.length > 1) { + for (var i = 1; i < arguments.length; i++) { + args[i - 1] = arguments[i]; + } + } + queue.push(new Item(fun, args)); + if (queue.length === 1 && !draining) { + runTimeout(drainQueue); + } +}; + +// v8 likes predictible objects +function Item(fun, array) { + this.fun = fun; + this.array = array; +} +Item.prototype.run = function () { + this.fun.apply(null, this.array); +}; +process.title = 'browser'; +process.browser = true; +process.env = {}; +process.argv = []; +process.version = ''; // empty string to avoid regexp issues +process.versions = {}; + +function noop() {} + +process.on = noop; +process.addListener = noop; +process.once = noop; +process.off = noop; +process.removeListener = noop; +process.removeAllListeners = noop; +process.emit = noop; + +process.binding = function (name) { + throw new Error('process.binding is not supported'); +}; + +process.cwd = function () { return '/' }; +process.chdir = function (dir) { + throw new Error('process.chdir is not supported'); +}; +process.umask = function() { return 0; }; + +},{}],595:[function(require,module,exports){ +module.exports = { + Either: require('./src/Either'), + Future: require('./src/Future'), + Identity: require('./src/Identity'), + IO: require('./src/IO'), + lift2: require('./src/lift2'), + lift3: require('./src/lift3'), + Maybe: require('./src/Maybe'), + Reader: require('./src/Reader'), + State: require('./src/State'), + Tuple: require('./src/Tuple') +}; + +},{"./src/Either":596,"./src/Future":597,"./src/IO":598,"./src/Identity":599,"./src/Maybe":600,"./src/Reader":601,"./src/State":602,"./src/Tuple":603,"./src/lift2":605,"./src/lift3":606}],596:[function(require,module,exports){ +var curry = require('ramda/src/curry'); +var toString = require('ramda/src/toString'); + +var util = require('./internal/util'); + + +function Either(left, right) { + switch (arguments.length) { + case 0: + throw new TypeError('no arguments to Either'); + case 1: + return function(right) { + return right == null ? Either.Left(left) : Either.Right(right); + }; + default: + return right == null ? Either.Left(left) : Either.Right(right); + } +} + +Either.prototype['@@type'] = 'ramda-fantasy/Either'; + +Either.prototype.map = util.returnThis; + +Either.of = Either.prototype.of = function(value) { + return Either.Right(value); +}; + +Either.prototype.chain = util.returnThis; // throw? + + +Either.equals = Either.prototype.equals = util.getEquals(Either); + +Either.either = curry(function either(leftFn, rightFn, e) { + if (e instanceof _Left) { + return leftFn(e.value); + } else if (e instanceof _Right) { + return rightFn(e.value); + } else { + throw new TypeError('invalid type given to Either.either'); + } +}); + +Either.isLeft = function(x) { + return x.isLeft; +}; + +Either.isRight = function(x) { + return x.isRight; +}; + + +// Right +function _Right(x) { + this.value = x; +} +util.extend(_Right, Either); + +_Right.prototype.isRight = true; +_Right.prototype.isLeft = false; + +_Right.prototype.map = function(fn) { + return new _Right(fn(this.value)); +}; + +_Right.prototype.ap = function(that) { + return that.map(this.value); +}; + +_Right.prototype.chain = function(f) { + return f(this.value); +}; + +//chainRec +Either.chainRec = Either.prototype.chainRec = function(f, i) { + var res, state = util.chainRecNext(i); + while (state.isNext) { + res = f(util.chainRecNext, util.chainRecDone, state.value); + if (Either.isLeft(res)) { + return res; + } + state = res.value; + } + return Either.Right(state.value); +}; + +_Right.prototype.bimap = function(_, f) { + return new _Right(f(this.value)); +}; + +_Right.prototype.extend = function(f) { + return new _Right(f(this)); +}; + +_Right.prototype.toString = function() { + return 'Either.Right(' + toString(this.value) + ')'; +}; + +Either.Right = function(value) { + return new _Right(value); +}; + + +// Left +function _Left(x) { + this.value = x; +} +util.extend(_Left, Either); + +_Left.prototype.isLeft = true; +_Left.prototype.isRight = false; + +_Left.prototype.ap = util.returnThis; + +_Left.prototype.bimap = function(f) { + return new _Left(f(this.value)); +}; + +_Left.prototype.extend = util.returnThis; + +_Left.prototype.toString = function() { + return 'Either.Left(' + toString(this.value) + ')'; +}; + +Either.Left = function(value) { + return new _Left(value); +}; + + +module.exports = Either; + +},{"./internal/util":604,"ramda/src/curry":611,"ramda/src/toString":659}],597:[function(require,module,exports){ +var once = require('ramda/src/once'); +var forEach = require('ramda/src/forEach'); +var toString = require('ramda/src/toString'); +var curry = require('ramda/src/curry'); + +var util = require('./internal/util'); + +function jail(handler, f){ + return function(a){ + try{ + return f(a); + } catch(err) { + handler(err); + } + }; +} + +// `f` is a function that takes two function arguments: `reject` (failure) and `resolve` (success) +function Future(f) { + if (!(this instanceof Future)) { + return new Future(f); + } + this._fork = f; +} + +Future.prototype['@@type'] = 'ramda-fantasy/Future'; + +Future.prototype.fork = function(reject, resolve) { + this._fork(reject, jail(reject, resolve)); +}; + +// functor +Future.prototype.map = function(f) { + return this.chain(function(a) { return Future.of(f(a)); }); +}; + +// apply +Future.prototype.ap = function(m) { + var self = this; + + return new Future(function(rej, res) { + var applyFn, val; + var doReject = once(rej); + + var resolveIfDone = jail(doReject, function() { + if (applyFn != null && val != null) { + return res(applyFn(val)); + } + }); + + self._fork(doReject, function(fn) { + applyFn = fn; + resolveIfDone(); + }); + + m._fork(doReject, function(v) { + val = v; + resolveIfDone(); + }); + + }); + +}; + +// applicative +Future.of = function(x) { + // should include a default rejection? + return new Future(function(_, resolve) { return resolve(x); }); +}; + +Future.prototype.of = Future.of; + +// chain +// f must be a function which returns a value +// f must return a value of the same Chain +// chain must return a value of the same Chain +//:: Future a, b => (b -> Future c) -> Future c +Future.prototype.chain = function(f) { // Sorella's: + return new Future(function(reject, resolve) { + return this._fork( + function(a) { return reject(a); }, + jail(reject, function(b) { return f(b)._fork(reject, resolve); }) + ); + }.bind(this)); +}; + +// chainRec +// +// Heavily influenced by the Aff MonadRec instance +// https://github.com/slamdata/purescript-aff/blob/51106474122d0e5aec8e3d5da5bb66cfe8062f55/src/Control/Monad/Aff.js#L263-L322 +Future.chainRec = Future.prototype.chainRec = function(f, a) { + return Future(function(reject, resolve) { + return function go(acc) { + // isSync could be in three possable states + // * null - unresolved status + // * true - synchronous future + // * false - asynchronous future + var isSync = null; + var state = util.chainRecNext(acc); + var onResolve = function(v) { + // If the `isSync` is still unresolved, we have observed a + // synchronous future. Otherwise, `isSync` will be `false`. + if (isSync === null) { + isSync = true; + // Store the result for further synchronous processing. + state = v; + } else { + // When we have observed an asynchronous future, we use normal + // recursion. This is safe because we will be on a new stack. + (v.isNext ? go : resolve)(v.value); + } + }; + while (state.isNext) { + isSync = null; + f(util.chainRecNext, util.chainRecDone, state.value).fork(reject, onResolve); + // If the `isSync` has already resolved to `true` by our `onResolve`, then + // we have observed a synchronous future. Otherwise it will still be `null`. + if (isSync === true) { + continue; + } else { + // If the status has not resolved yet, then we have observed an + // asynchronous or failed future so update status and exit the loop. + isSync = false; + return; + } + } + resolve(state.value); + }(a); + }); +}; + +// chainReject +// Like chain but operates on the reject instead of the resolve case. +//:: Future a, b => (a -> Future c) -> Future c +Future.prototype.chainReject = function(f) { + return new Future(function(reject, resolve) { + return this._fork( + jail(reject, function(a) { return f(a)._fork(reject, resolve); }), + function(b) { return resolve(b); } + ); + }.bind(this)); +}; + +// monad +// A value that implements the Monad specification must also implement the Applicative and Chain specifications. +// see above. + +Future.prototype.bimap = function(errFn, successFn) { + var self = this; + return new Future(function(reject, resolve) { + self._fork( + jail(reject, function(err) { reject(errFn(err)); }), + jail(reject, function(val) { resolve(successFn(val)); }) + ); + }); +}; + +Future.reject = function(val) { + return new Future(function(reject) { + reject(val); + }); +}; + +Future.prototype.toString = function() { + return 'Future(' + toString(this._fork) + ')'; +}; + +Future.cache = function(f) { + var status = 'IDLE'; + var listeners = []; + var cachedValue; + + var handleCompletion = curry(function(newStatus, cb, val) { + status = newStatus; + cachedValue = val; + cb(val); + forEach(function(listener) { + listener[status](cachedValue); + }, listeners); + }); + + function addListeners(reject, resolve) { + listeners.push({ REJECTED: reject, RESOLVED: resolve } ); + } + + function doResolve(reject, resolve) { + status = 'PENDING'; + return f._fork( + handleCompletion('REJECTED', reject), + handleCompletion('RESOLVED', resolve) + ); + } + + return new Future(function(reject, resolve) { + + switch(status) { + case 'IDLE': doResolve(reject, resolve); break; + case 'PENDING': addListeners(reject, resolve); break; + case 'REJECTED': reject(cachedValue); break; + case 'RESOLVED': resolve(cachedValue); break; + } + + }); +}; + +module.exports = Future; + +},{"./internal/util":604,"ramda/src/curry":611,"ramda/src/forEach":615,"ramda/src/once":652,"ramda/src/toString":659}],598:[function(require,module,exports){ +var compose = require('ramda/src/compose'); +var toString = require('ramda/src/toString'); + +var util = require('./internal/util'); + +module.exports = IO; + +function IO(fn) { + if (!(this instanceof IO)) { + return new IO(fn); + } + this.fn = fn; +} + +IO.prototype['@@type'] = 'ramda-fantasy/IO'; + +// `f` must return an IO +IO.prototype.chain = function(f) { + var io = this; + return new IO(function() { + var next = f(io.fn.apply(io, arguments)); + return next.fn.apply(next, arguments); + }); +}; + +//chainRec +IO.chainRec = IO.prototype.chainRec = function(f, i) { + return new IO(function() { + var state = util.chainRecNext(i); + while (state.isNext) { + state = f(util.chainRecNext, util.chainRecDone, state.value).fn(); + } + return state.value; + }); +}; + +IO.prototype.map = function(f) { + var io = this; + return new IO(compose(f, io.fn)); +}; + +// `this` IO must wrap a function `f` that takes an IO (`thatIo`) as input +// `f` must return an IO +IO.prototype.ap = function(thatIo) { + return this.chain(function(f) { + return thatIo.map(f); + }); +}; + +IO.runIO = function(io) { + return io.runIO.apply(io, [].slice.call(arguments, 1)); +}; + +IO.prototype.runIO = function() { + return this.fn.apply(this, arguments); +}; + +IO.prototype.of = function(x) { + return new IO(function() { return x; }); +}; + +IO.of = IO.prototype.of; + +IO.prototype.toString = function() { + return 'IO(' + toString(this.fn) + ')'; +}; + +},{"./internal/util":604,"ramda/src/compose":610,"ramda/src/toString":659}],599:[function(require,module,exports){ +var toString = require('ramda/src/toString'); + +var util = require('./internal/util'); + + +/** + * A data type that holds a value and exposes a monadic api. + */ + +/** + * Constructs a new `Identity[a]` data type that holds a single + * value `a`. + * @param {*} a Value of any type + * @sig a -> Identity[a] + */ +function Identity(x) { + if (!(this instanceof Identity)) { + return new Identity(x); + } + this.value = x; +} + +Identity.prototype['@@type'] = 'ramda-fantasy/Identity'; + +/** + * Applicative specification. Creates a new `Identity[a]` holding the value `a`. + * @param {*} a Value of any type + * @returns Identity[a] + * @sig a -> Identity[a] + */ +Identity.of = function(x) { + return new Identity(x); +}; +Identity.prototype.of = Identity.of; + +/** + * Functor specification. Creates a new `Identity[a]` mapping function `f` onto + * `a` returning any value b. + * @param {Function} f Maps `a` to any value `b` + * @returns Identity[b] + * @sig @Identity[a] => (a -> b) -> Identity[b] + */ +Identity.prototype.map = function(f) { + return new Identity(f(this.value)); +}; + +/** + * Apply specification. Applies the function inside the `Identity[a]` + * type to another applicative type. + * @param {Applicative[a]} app Applicative that will apply its function + * @returns Applicative[b] + * @sig (Identity[a -> b], f: Applicative[_]) => f[a] -> f[b] + */ +Identity.prototype.ap = function(app) { + return app.map(this.value); +}; + +/** + * Chain specification. Transforms the value of the `Identity[a]` + * type using an unary function to monads. The `Identity[a]` type + * should contain a function, otherwise an error is thrown. + * + * @param {Function} fn Transforms `a` into a `Monad[b]` + * @returns Monad[b] + * @sig (Identity[a], m: Monad[_]) => (a -> m[b]) -> m[b] + */ +Identity.prototype.chain = function(fn) { + return fn(this.value); +}; + +// chainRec +Identity.chainRec = Identity.prototype.chainRec = function(f, i) { + var state = util.chainRecNext(i); + while (state.isNext) { + state = f(util.chainRecNext, util.chainRecDone, state.value).get(); + } + return Identity(state.value); +}; + +/** + * Returns the value of `Identity[a]` + * + * @returns a + * @sig (Identity[a]) => a + */ +Identity.prototype.get = function() { + return this.value; +}; + +// equality method to enable testing +Identity.prototype.equals = util.getEquals(Identity); + +Identity.prototype.toString = function() { + return 'Identity(' + toString(this.value) + ')'; +}; + +module.exports = Identity; + +},{"./internal/util":604,"ramda/src/toString":659}],600:[function(require,module,exports){ +var toString = require('ramda/src/toString'); +var curry = require('ramda/src/curry'); + +var util = require('./internal/util.js'); + +function Maybe(x) { + return x == null ? _nothing : Maybe.Just(x); +} + +Maybe.prototype['@@type'] = 'ramda-fantasy/Maybe'; + +function Just(x) { + this.value = x; +} +util.extend(Just, Maybe); + +Just.prototype.isJust = true; +Just.prototype.isNothing = false; + +function Nothing() {} +util.extend(Nothing, Maybe); + +Nothing.prototype.isNothing = true; +Nothing.prototype.isJust = false; + +var _nothing = new Nothing(); + +Maybe.Nothing = function() { + return _nothing; +}; + +Maybe.Just = function(x) { + return new Just(x); +}; + +Maybe.of = Maybe.Just; + +Maybe.prototype.of = Maybe.Just; + +Maybe.isJust = function(x) { + return x.isJust; +}; + +Maybe.isNothing = function(x) { + return x.isNothing; +}; + +Maybe.maybe = curry(function(nothingVal, justFn, m) { + return m.reduce(function(_, x) { + return justFn(x); + }, nothingVal); +}); + +// functor +Just.prototype.map = function(f) { + return this.of(f(this.value)); +}; + +Nothing.prototype.map = util.returnThis; + +// apply +// takes a Maybe that wraps a function (`app`) and applies its `map` +// method to this Maybe's value, which must be a function. +Just.prototype.ap = function(m) { + return m.map(this.value); +}; + +Nothing.prototype.ap = util.returnThis; + +// applicative +// `of` inherited from `Maybe` + + +// chain +// f must be a function which returns a value +// f must return a value of the same Chain +// chain must return a value of the same Chain +Just.prototype.chain = util.baseMap; + +Nothing.prototype.chain = util.returnThis; + + +//chainRec +Maybe.chainRec = Maybe.prototype.chainRec = function(f, i) { + var res, state = util.chainRecNext(i); + while (state.isNext) { + res = f(util.chainRecNext, util.chainRecDone, state.value); + if (Maybe.isNothing(res)) { + return res; + } + state = res.value; + } + return Maybe.Just(state.value); +}; + + +// +Just.prototype.datatype = Just; + +Nothing.prototype.datatype = Nothing; + +// monad +// A value that implements the Monad specification must also implement the Applicative and Chain specifications. +// see above. + +// equality method to enable testing +Just.prototype.equals = util.getEquals(Just); + +Nothing.prototype.equals = function(that) { + return that === _nothing; +}; + +Maybe.prototype.isNothing = function() { + return this === _nothing; +}; + +Maybe.prototype.isJust = function() { + return this instanceof Just; +}; + +Just.prototype.getOrElse = function() { + return this.value; +}; + +Nothing.prototype.getOrElse = function(a) { + return a; +}; + +Just.prototype.reduce = function(f, x) { + return f(x, this.value); +}; + +Nothing.prototype.reduce = function(f, x) { + return x; +}; + +Just.prototype.toString = function() { + return 'Maybe.Just(' + toString(this.value) + ')'; +}; + +Nothing.prototype.toString = function() { + return 'Maybe.Nothing()'; +}; + +module.exports = Maybe; + +},{"./internal/util.js":604,"ramda/src/curry":611,"ramda/src/toString":659}],601:[function(require,module,exports){ +var compose = require('ramda/src/compose'); +var identity = require('ramda/src/identity'); +var toString = require('ramda/src/toString'); +var always = require('ramda/src/always'); + + +function Reader(run) { + if (!(this instanceof Reader)) { + return new Reader(run); + } + this.run = run; +} + +Reader.run = function(reader) { + return reader.run.apply(reader, [].slice.call(arguments, 1)); +}; + +Reader.prototype['@@type'] = 'ramda-fantasy/Reader'; + +Reader.prototype.chain = function(f) { + var reader = this; + return new Reader(function(r) { + return f(reader.run(r)).run(r); + }); +}; + +Reader.prototype.ap = function(a) { + return this.chain(function(f) { + return a.map(f); + }); +}; + +Reader.prototype.map = function(f) { + return this.chain(function(a) { + return Reader.of(f(a)); + }); +}; + +Reader.prototype.of = function(a) { + return new Reader(function() { + return a; + }); +}; +Reader.of = Reader.prototype.of; + +Reader.ask = Reader(identity); + +Reader.prototype.toString = function() { + return 'Reader(' + toString(this.run) + ')'; +}; + +Reader.T = function(M) { + var ReaderT = function ReaderT(run) { + if (!(this instanceof ReaderT)) { + return new ReaderT(run); + } + this.run = run; + }; + + ReaderT.lift = compose(ReaderT, always); + + ReaderT.ask = ReaderT(M.of); + + ReaderT.prototype.of = ReaderT.of = function(a) { + return ReaderT(function() { + return M.of(a); + }); + }; + + ReaderT.prototype.chain = function(f) { + var readerT = this; + return ReaderT(function(e) { + var m = readerT.run(e); + return m.chain(function(a) { + return f(a).run(e); + }); + }); + }; + + ReaderT.prototype.map = function(f) { + return this.chain(function(a) { + return ReaderT.of(f(a)); + }); + }; + + ReaderT.prototype.ap = function(a) { + var readerT = this; + return ReaderT(function(e) { + return readerT.run(e).ap(a.run(e)); + }); + }; + + ReaderT.prototype.toString = function() { + return 'ReaderT[' + M.name + '](' + toString(this.run) + ')'; + }; + + return ReaderT; +}; + +module.exports = Reader; + +},{"ramda/src/always":608,"ramda/src/compose":610,"ramda/src/identity":617,"ramda/src/toString":659}],602:[function(require,module,exports){ +var curry = require('ramda/src/curry'); + +var Identity = require('./Identity'); +var Tuple = require('./Tuple'); +var util = require('./internal/util'); + + +function T(M) { + function StateT(run) { + if (!(this instanceof StateT)) { + return new StateT(run); + } + this._run = run; + } + StateT.prototype.run = function(s) { + return this._run(s); + }; + StateT.prototype.eval = function(s) { + return Tuple.fst(this.run(s)); + }; + StateT.prototype.exec = function(s) { + return Tuple.snd(this.run(s)); + }; + StateT.prototype.chain = function(f) { + var state = this; + return StateT(function(s) { + return state._run(s).chain(function(t) { + return f(Tuple.fst(t))._run(Tuple.snd(t)); + }); + }); + }; + StateT.of = StateT.prototype.of = function(a) { + return StateT(function (s) { + return M.of(Tuple(a, s)); + }); + }; + StateT.prototype.ap = util.deriveAp(StateT); + StateT.prototype.map = util.deriveMap(StateT); + StateT.tailRec = curry(function(stepFn, init) { + return StateT(function(s) { + return M.tailRec(function(t) { + return stepFn(Tuple.fst(t))._run(Tuple.snd(t)).chain(function (t_) { + return M.of(Tuple.fst(t_).bimap( + function(a) { return Tuple(a, Tuple.snd(t_)); }, + function(b) { return Tuple(b, Tuple.snd(t_)); } + )); + }); + }, Tuple(init, s)); + }); + }); + StateT.lift = function(ma) { + return StateT(function(s) { + return ma.chain(function(a) { + return M.of(Tuple(a, s)); + }); + }); + }; + StateT.get = StateT(function(s) { + return M.of(Tuple(s, s)); + }); + StateT.gets = function(f) { + return StateT(function(s) { + return M.of(Tuple(f(s), s)); + }); + }; + StateT.put = function(s) { + return StateT(function(_) { + return M.of(Tuple(void _, s)); + }); + }; + StateT.modify = function(f) { + return StateT(function(s) { + return M.of(Tuple(void 0, f(s))); + }); + }; + + return StateT; +} + +var State = T(Identity); +State.T = T; +State.prototype.run = function(s) { + return this._run(s).value; +}; + +module.exports = State; + +},{"./Identity":599,"./Tuple":603,"./internal/util":604,"ramda/src/curry":611}],603:[function(require,module,exports){ +var toString = require('ramda/src/toString'); +var equals = require('ramda/src/equals'); + + +function Tuple(x, y) { + switch (arguments.length) { + case 0: + throw new TypeError('no arguments to Tuple'); + case 1: + return function(y) { + return new _Tuple(x, y); + }; + default: + return new _Tuple(x, y); + } +} + +function _Tuple(x, y) { + this[0] = x; + this[1] = y; + this.length = 2; +} + +function ensureConcat(xs) { + xs.forEach(function(x) { + if (typeof x.concat != 'function') { + throw new TypeError(toString(x) + ' must be a semigroup to perform this operation'); + } + }); +} + +Tuple.fst = function(x) { + return x[0]; +}; + +Tuple.snd = function(x) { + return x[1]; +}; + +_Tuple.prototype['@@type'] = 'ramda-fantasy/Tuple'; + +// semigroup +_Tuple.prototype.concat = function(x) { + ensureConcat([this[0], this[1]]); + return Tuple(this[0].concat(x[0]), this[1].concat(x[1])); +}; + +// functor +_Tuple.prototype.map = function(f) { + return Tuple(this[0], f(this[1])); +}; + +// apply +_Tuple.prototype.ap = function(m) { + ensureConcat([this[0]]); + return Tuple(this[0].concat(m[0]), this[1](m[1])); +}; + +// setoid +_Tuple.prototype.equals = function(that) { + return that instanceof _Tuple && equals(this[0], that[0]) && equals(this[1], that[1]); +}; + +_Tuple.prototype.toString = function() { + return 'Tuple(' + toString(this[0]) + ', ' + toString(this[1]) + ')'; +}; + +module.exports = Tuple; + +},{"ramda/src/equals":613,"ramda/src/toString":659}],604:[function(require,module,exports){ +var _equals = require('ramda/src/equals'); + + +module.exports = { + + baseMap: function(f) { + return f(this.value); + }, + + getEquals: function(constructor) { + return function equals(that) { + return that instanceof constructor && _equals(this.value, that.value); + }; + }, + + extend: function(Child, Parent) { + function Ctor() { + this.constructor = Child; + } + Ctor.prototype = Parent.prototype; + Child.prototype = new Ctor(); + Child.super_ = Parent.prototype; + }, + + identity: function(x) { return x; }, + + notImplemented: function(str) { + return function() { + throw new Error(str + ' is not implemented'); + }; + }, + + notCallable: function(fn) { + return function() { + throw new Error(fn + ' cannot be called directly'); + }; + }, + + returnThis: function() { return this; }, + + chainRecNext: function(v) { + return { isNext: true, value: v }; + }, + + chainRecDone: function(v) { + return { isNext: false, value: v }; + }, + + deriveAp: function (Type) { + return function(fa) { + return this.chain(function (f) { + return fa.chain(function (a) { + return Type.of(f(a)); + }); + }); + }; + }, + + deriveMap: function (Type) { + return function (f) { + return this.chain(function (a) { + return Type.of(f(a)); + }); + }; + } + +}; + +},{"ramda/src/equals":613}],605:[function(require,module,exports){ +var curryN = require('ramda/src/curryN'); + +module.exports = curryN(3, function lift2(f, a1, a2) { + return a1.map(f).ap(a2); +}); + +},{"ramda/src/curryN":612}],606:[function(require,module,exports){ +var curryN = require('ramda/src/curryN'); + +module.exports = curryN(4, function lift3(f, a1, a2, a3) { + return a1.map(f).ap(a2).ap(a3); +}); + +},{"ramda/src/curryN":612}],607:[function(require,module,exports){ +// Ramda v0.22.1 +// https://github.com/ramda/ramda +// (c) 2013-2016 Scott Sauyet, Michael Hurley, and David Chambers +// Ramda may be freely distributed under the MIT license. + +;(function() { + + 'use strict'; + + /** + * A special placeholder value used to specify "gaps" within curried functions, + * allowing partial application of any combination of arguments, regardless of + * their positions. + * + * If `g` is a curried ternary function and `_` is `R.__`, the following are + * equivalent: + * + * - `g(1, 2, 3)` + * - `g(_, 2, 3)(1)` + * - `g(_, _, 3)(1)(2)` + * - `g(_, _, 3)(1, 2)` + * - `g(_, 2, _)(1, 3)` + * - `g(_, 2)(1)(3)` + * - `g(_, 2)(1, 3)` + * - `g(_, 2)(_, 3)(1)` + * + * @constant + * @memberOf R + * @since v0.6.0 + * @category Function + * @example + * + * var greet = R.replace('{name}', R.__, 'Hello, {name}!'); + * greet('Alice'); //=> 'Hello, Alice!' + */ + var __ = { '@@functional/placeholder': true }; + + /* eslint-disable no-unused-vars */ + var _arity = function _arity(n, fn) { + /* eslint-disable no-unused-vars */ + switch (n) { + case 0: + return function () { + return fn.apply(this, arguments); + }; + case 1: + return function (a0) { + return fn.apply(this, arguments); + }; + case 2: + return function (a0, a1) { + return fn.apply(this, arguments); + }; + case 3: + return function (a0, a1, a2) { + return fn.apply(this, arguments); + }; + case 4: + return function (a0, a1, a2, a3) { + return fn.apply(this, arguments); + }; + case 5: + return function (a0, a1, a2, a3, a4) { + return fn.apply(this, arguments); + }; + case 6: + return function (a0, a1, a2, a3, a4, a5) { + return fn.apply(this, arguments); + }; + case 7: + return function (a0, a1, a2, a3, a4, a5, a6) { + return fn.apply(this, arguments); + }; + case 8: + return function (a0, a1, a2, a3, a4, a5, a6, a7) { + return fn.apply(this, arguments); + }; + case 9: + return function (a0, a1, a2, a3, a4, a5, a6, a7, a8) { + return fn.apply(this, arguments); + }; + case 10: + return function (a0, a1, a2, a3, a4, a5, a6, a7, a8, a9) { + return fn.apply(this, arguments); + }; + default: + throw new Error('First argument to _arity must be a non-negative integer no greater than ten'); + } + }; + + var _arrayFromIterator = function _arrayFromIterator(iter) { + var list = []; + var next; + while (!(next = iter.next()).done) { + list.push(next.value); + } + return list; + }; + + var _arrayOf = function _arrayOf() { + return Array.prototype.slice.call(arguments); + }; + + var _cloneRegExp = function _cloneRegExp(pattern) { + return new RegExp(pattern.source, (pattern.global ? 'g' : '') + (pattern.ignoreCase ? 'i' : '') + (pattern.multiline ? 'm' : '') + (pattern.sticky ? 'y' : '') + (pattern.unicode ? 'u' : '')); + }; + + var _complement = function _complement(f) { + return function () { + return !f.apply(this, arguments); + }; + }; + + /** + * Private `concat` function to merge two array-like objects. + * + * @private + * @param {Array|Arguments} [set1=[]] An array-like object. + * @param {Array|Arguments} [set2=[]] An array-like object. + * @return {Array} A new, merged array. + * @example + * + * _concat([4, 5, 6], [1, 2, 3]); //=> [4, 5, 6, 1, 2, 3] + */ + var _concat = function _concat(set1, set2) { + set1 = set1 || []; + set2 = set2 || []; + var idx; + var len1 = set1.length; + var len2 = set2.length; + var result = []; + idx = 0; + while (idx < len1) { + result[result.length] = set1[idx]; + idx += 1; + } + idx = 0; + while (idx < len2) { + result[result.length] = set2[idx]; + idx += 1; + } + return result; + }; + + var _containsWith = function _containsWith(pred, x, list) { + var idx = 0; + var len = list.length; + while (idx < len) { + if (pred(x, list[idx])) { + return true; + } + idx += 1; + } + return false; + }; + + var _filter = function _filter(fn, list) { + var idx = 0; + var len = list.length; + var result = []; + while (idx < len) { + if (fn(list[idx])) { + result[result.length] = list[idx]; + } + idx += 1; + } + return result; + }; + + var _forceReduced = function _forceReduced(x) { + return { + '@@transducer/value': x, + '@@transducer/reduced': true + }; + }; + + // String(x => x) evaluates to "x => x", so the pattern may not match. + var _functionName = function _functionName(f) { + // String(x => x) evaluates to "x => x", so the pattern may not match. + var match = String(f).match(/^function (\w*)/); + return match == null ? '' : match[1]; + }; + + var _has = function _has(prop, obj) { + return Object.prototype.hasOwnProperty.call(obj, prop); + }; + + var _identity = function _identity(x) { + return x; + }; + + var _isArguments = function () { + var toString = Object.prototype.toString; + return toString.call(arguments) === '[object Arguments]' ? function _isArguments(x) { + return toString.call(x) === '[object Arguments]'; + } : function _isArguments(x) { + return _has('callee', x); + }; + }(); + + /** + * Tests whether or not an object is an array. + * + * @private + * @param {*} val The object to test. + * @return {Boolean} `true` if `val` is an array, `false` otherwise. + * @example + * + * _isArray([]); //=> true + * _isArray(null); //=> false + * _isArray({}); //=> false + */ + var _isArray = Array.isArray || function _isArray(val) { + return val != null && val.length >= 0 && Object.prototype.toString.call(val) === '[object Array]'; + }; + + var _isFunction = function _isFunction(x) { + return Object.prototype.toString.call(x) === '[object Function]'; + }; + + /** + * Determine if the passed argument is an integer. + * + * @private + * @param {*} n + * @category Type + * @return {Boolean} + */ + var _isInteger = Number.isInteger || function _isInteger(n) { + return n << 0 === n; + }; + + var _isNumber = function _isNumber(x) { + return Object.prototype.toString.call(x) === '[object Number]'; + }; + + var _isObject = function _isObject(x) { + return Object.prototype.toString.call(x) === '[object Object]'; + }; + + var _isPlaceholder = function _isPlaceholder(a) { + return a != null && typeof a === 'object' && a['@@functional/placeholder'] === true; + }; + + var _isRegExp = function _isRegExp(x) { + return Object.prototype.toString.call(x) === '[object RegExp]'; + }; + + var _isString = function _isString(x) { + return Object.prototype.toString.call(x) === '[object String]'; + }; + + var _isTransformer = function _isTransformer(obj) { + return typeof obj['@@transducer/step'] === 'function'; + }; + + var _map = function _map(fn, functor) { + var idx = 0; + var len = functor.length; + var result = Array(len); + while (idx < len) { + result[idx] = fn(functor[idx]); + idx += 1; + } + return result; + }; + + // Based on https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/assign + var _objectAssign = function _objectAssign(target) { + if (target == null) { + throw new TypeError('Cannot convert undefined or null to object'); + } + var output = Object(target); + var idx = 1; + var length = arguments.length; + while (idx < length) { + var source = arguments[idx]; + if (source != null) { + for (var nextKey in source) { + if (_has(nextKey, source)) { + output[nextKey] = source[nextKey]; + } + } + } + idx += 1; + } + return output; + }; + + var _of = function _of(x) { + return [x]; + }; + + var _pipe = function _pipe(f, g) { + return function () { + return g.call(this, f.apply(this, arguments)); + }; + }; + + var _pipeP = function _pipeP(f, g) { + return function () { + var ctx = this; + return f.apply(ctx, arguments).then(function (x) { + return g.call(ctx, x); + }); + }; + }; + + // \b matches word boundary; [\b] matches backspace + var _quote = function _quote(s) { + var escaped = s.replace(/\\/g, '\\\\').replace(/[\b]/g, '\\b') // \b matches word boundary; [\b] matches backspace + .replace(/\f/g, '\\f').replace(/\n/g, '\\n').replace(/\r/g, '\\r').replace(/\t/g, '\\t').replace(/\v/g, '\\v').replace(/\0/g, '\\0'); + return '"' + escaped.replace(/"/g, '\\"') + '"'; + }; + + var _reduced = function _reduced(x) { + return x && x['@@transducer/reduced'] ? x : { + '@@transducer/value': x, + '@@transducer/reduced': true + }; + }; + + /** + * An optimized, private array `slice` implementation. + * + * @private + * @param {Arguments|Array} args The array or arguments object to consider. + * @param {Number} [from=0] The array index to slice from, inclusive. + * @param {Number} [to=args.length] The array index to slice to, exclusive. + * @return {Array} A new, sliced array. + * @example + * + * _slice([1, 2, 3, 4, 5], 1, 3); //=> [2, 3] + * + * var firstThreeArgs = function(a, b, c, d) { + * return _slice(arguments, 0, 3); + * }; + * firstThreeArgs(1, 2, 3, 4); //=> [1, 2, 3] + */ + var _slice = function _slice(args, from, to) { + switch (arguments.length) { + case 1: + return _slice(args, 0, args.length); + case 2: + return _slice(args, from, args.length); + default: + var list = []; + var idx = 0; + var len = Math.max(0, Math.min(args.length, to) - from); + while (idx < len) { + list[idx] = args[from + idx]; + idx += 1; + } + return list; + } + }; + + /** + * Polyfill from . + */ + var _toISOString = function () { + var pad = function pad(n) { + return (n < 10 ? '0' : '') + n; + }; + return typeof Date.prototype.toISOString === 'function' ? function _toISOString(d) { + return d.toISOString(); + } : function _toISOString(d) { + return d.getUTCFullYear() + '-' + pad(d.getUTCMonth() + 1) + '-' + pad(d.getUTCDate()) + 'T' + pad(d.getUTCHours()) + ':' + pad(d.getUTCMinutes()) + ':' + pad(d.getUTCSeconds()) + '.' + (d.getUTCMilliseconds() / 1000).toFixed(3).slice(2, 5) + 'Z'; + }; + }(); + + var _xfBase = { + init: function () { + return this.xf['@@transducer/init'](); + }, + result: function (result) { + return this.xf['@@transducer/result'](result); + } + }; + + var _xwrap = function () { + function XWrap(fn) { + this.f = fn; + } + XWrap.prototype['@@transducer/init'] = function () { + throw new Error('init not implemented on XWrap'); + }; + XWrap.prototype['@@transducer/result'] = function (acc) { + return acc; + }; + XWrap.prototype['@@transducer/step'] = function (acc, x) { + return this.f(acc, x); + }; + return function _xwrap(fn) { + return new XWrap(fn); + }; + }(); + + var _aperture = function _aperture(n, list) { + var idx = 0; + var limit = list.length - (n - 1); + var acc = new Array(limit >= 0 ? limit : 0); + while (idx < limit) { + acc[idx] = _slice(list, idx, idx + n); + idx += 1; + } + return acc; + }; + + var _assign = typeof Object.assign === 'function' ? Object.assign : _objectAssign; + + /** + * Similar to hasMethod, this checks whether a function has a [methodname] + * function. If it isn't an array it will execute that function otherwise it + * will default to the ramda implementation. + * + * @private + * @param {Function} fn ramda implemtation + * @param {String} methodname property to check for a custom implementation + * @return {Object} Whatever the return value of the method is. + */ + var _checkForMethod = function _checkForMethod(methodname, fn) { + return function () { + var length = arguments.length; + if (length === 0) { + return fn(); + } + var obj = arguments[length - 1]; + return _isArray(obj) || typeof obj[methodname] !== 'function' ? fn.apply(this, arguments) : obj[methodname].apply(obj, _slice(arguments, 0, length - 1)); + }; + }; + + /** + * Optimized internal one-arity curry function. + * + * @private + * @category Function + * @param {Function} fn The function to curry. + * @return {Function} The curried function. + */ + var _curry1 = function _curry1(fn) { + return function f1(a) { + if (arguments.length === 0 || _isPlaceholder(a)) { + return f1; + } else { + return fn.apply(this, arguments); + } + }; + }; + + /** + * Optimized internal two-arity curry function. + * + * @private + * @category Function + * @param {Function} fn The function to curry. + * @return {Function} The curried function. + */ + var _curry2 = function _curry2(fn) { + return function f2(a, b) { + switch (arguments.length) { + case 0: + return f2; + case 1: + return _isPlaceholder(a) ? f2 : _curry1(function (_b) { + return fn(a, _b); + }); + default: + return _isPlaceholder(a) && _isPlaceholder(b) ? f2 : _isPlaceholder(a) ? _curry1(function (_a) { + return fn(_a, b); + }) : _isPlaceholder(b) ? _curry1(function (_b) { + return fn(a, _b); + }) : fn(a, b); + } + }; + }; + + /** + * Optimized internal three-arity curry function. + * + * @private + * @category Function + * @param {Function} fn The function to curry. + * @return {Function} The curried function. + */ + var _curry3 = function _curry3(fn) { + return function f3(a, b, c) { + switch (arguments.length) { + case 0: + return f3; + case 1: + return _isPlaceholder(a) ? f3 : _curry2(function (_b, _c) { + return fn(a, _b, _c); + }); + case 2: + return _isPlaceholder(a) && _isPlaceholder(b) ? f3 : _isPlaceholder(a) ? _curry2(function (_a, _c) { + return fn(_a, b, _c); + }) : _isPlaceholder(b) ? _curry2(function (_b, _c) { + return fn(a, _b, _c); + }) : _curry1(function (_c) { + return fn(a, b, _c); + }); + default: + return _isPlaceholder(a) && _isPlaceholder(b) && _isPlaceholder(c) ? f3 : _isPlaceholder(a) && _isPlaceholder(b) ? _curry2(function (_a, _b) { + return fn(_a, _b, c); + }) : _isPlaceholder(a) && _isPlaceholder(c) ? _curry2(function (_a, _c) { + return fn(_a, b, _c); + }) : _isPlaceholder(b) && _isPlaceholder(c) ? _curry2(function (_b, _c) { + return fn(a, _b, _c); + }) : _isPlaceholder(a) ? _curry1(function (_a) { + return fn(_a, b, c); + }) : _isPlaceholder(b) ? _curry1(function (_b) { + return fn(a, _b, c); + }) : _isPlaceholder(c) ? _curry1(function (_c) { + return fn(a, b, _c); + }) : fn(a, b, c); + } + }; + }; + + /** + * Internal curryN function. + * + * @private + * @category Function + * @param {Number} length The arity of the curried function. + * @param {Array} received An array of arguments received thus far. + * @param {Function} fn The function to curry. + * @return {Function} The curried function. + */ + var _curryN = function _curryN(length, received, fn) { + return function () { + var combined = []; + var argsIdx = 0; + var left = length; + var combinedIdx = 0; + while (combinedIdx < received.length || argsIdx < arguments.length) { + var result; + if (combinedIdx < received.length && (!_isPlaceholder(received[combinedIdx]) || argsIdx >= arguments.length)) { + result = received[combinedIdx]; + } else { + result = arguments[argsIdx]; + argsIdx += 1; + } + combined[combinedIdx] = result; + if (!_isPlaceholder(result)) { + left -= 1; + } + combinedIdx += 1; + } + return left <= 0 ? fn.apply(this, combined) : _arity(left, _curryN(length, combined, fn)); + }; + }; + + /** + * Returns a function that dispatches with different strategies based on the + * object in list position (last argument). If it is an array, executes [fn]. + * Otherwise, if it has a function with [methodname], it will execute that + * function (functor case). Otherwise, if it is a transformer, uses transducer + * [xf] to return a new transformer (transducer case). Otherwise, it will + * default to executing [fn]. + * + * @private + * @param {String} methodname property to check for a custom implementation + * @param {Function} xf transducer to initialize if object is transformer + * @param {Function} fn default ramda implementation + * @return {Function} A function that dispatches on object in list position + */ + var _dispatchable = function _dispatchable(methodname, xf, fn) { + return function () { + var length = arguments.length; + if (length === 0) { + return fn(); + } + var obj = arguments[length - 1]; + if (!_isArray(obj)) { + var args = _slice(arguments, 0, length - 1); + if (typeof obj[methodname] === 'function') { + return obj[methodname].apply(obj, args); + } + if (_isTransformer(obj)) { + var transducer = xf.apply(null, args); + return transducer(obj); + } + } + return fn.apply(this, arguments); + }; + }; + + var _dropLastWhile = function dropLastWhile(pred, list) { + var idx = list.length - 1; + while (idx >= 0 && pred(list[idx])) { + idx -= 1; + } + return _slice(list, 0, idx + 1); + }; + + var _xall = function () { + function XAll(f, xf) { + this.xf = xf; + this.f = f; + this.all = true; + } + XAll.prototype['@@transducer/init'] = _xfBase.init; + XAll.prototype['@@transducer/result'] = function (result) { + if (this.all) { + result = this.xf['@@transducer/step'](result, true); + } + return this.xf['@@transducer/result'](result); + }; + XAll.prototype['@@transducer/step'] = function (result, input) { + if (!this.f(input)) { + this.all = false; + result = _reduced(this.xf['@@transducer/step'](result, false)); + } + return result; + }; + return _curry2(function _xall(f, xf) { + return new XAll(f, xf); + }); + }(); + + var _xany = function () { + function XAny(f, xf) { + this.xf = xf; + this.f = f; + this.any = false; + } + XAny.prototype['@@transducer/init'] = _xfBase.init; + XAny.prototype['@@transducer/result'] = function (result) { + if (!this.any) { + result = this.xf['@@transducer/step'](result, false); + } + return this.xf['@@transducer/result'](result); + }; + XAny.prototype['@@transducer/step'] = function (result, input) { + if (this.f(input)) { + this.any = true; + result = _reduced(this.xf['@@transducer/step'](result, true)); + } + return result; + }; + return _curry2(function _xany(f, xf) { + return new XAny(f, xf); + }); + }(); + + var _xaperture = function () { + function XAperture(n, xf) { + this.xf = xf; + this.pos = 0; + this.full = false; + this.acc = new Array(n); + } + XAperture.prototype['@@transducer/init'] = _xfBase.init; + XAperture.prototype['@@transducer/result'] = function (result) { + this.acc = null; + return this.xf['@@transducer/result'](result); + }; + XAperture.prototype['@@transducer/step'] = function (result, input) { + this.store(input); + return this.full ? this.xf['@@transducer/step'](result, this.getCopy()) : result; + }; + XAperture.prototype.store = function (input) { + this.acc[this.pos] = input; + this.pos += 1; + if (this.pos === this.acc.length) { + this.pos = 0; + this.full = true; + } + }; + XAperture.prototype.getCopy = function () { + return _concat(_slice(this.acc, this.pos), _slice(this.acc, 0, this.pos)); + }; + return _curry2(function _xaperture(n, xf) { + return new XAperture(n, xf); + }); + }(); + + var _xdrop = function () { + function XDrop(n, xf) { + this.xf = xf; + this.n = n; + } + XDrop.prototype['@@transducer/init'] = _xfBase.init; + XDrop.prototype['@@transducer/result'] = _xfBase.result; + XDrop.prototype['@@transducer/step'] = function (result, input) { + if (this.n > 0) { + this.n -= 1; + return result; + } + return this.xf['@@transducer/step'](result, input); + }; + return _curry2(function _xdrop(n, xf) { + return new XDrop(n, xf); + }); + }(); + + var _xdropLast = function () { + function XDropLast(n, xf) { + this.xf = xf; + this.pos = 0; + this.full = false; + this.acc = new Array(n); + } + XDropLast.prototype['@@transducer/init'] = _xfBase.init; + XDropLast.prototype['@@transducer/result'] = function (result) { + this.acc = null; + return this.xf['@@transducer/result'](result); + }; + XDropLast.prototype['@@transducer/step'] = function (result, input) { + if (this.full) { + result = this.xf['@@transducer/step'](result, this.acc[this.pos]); + } + this.store(input); + return result; + }; + XDropLast.prototype.store = function (input) { + this.acc[this.pos] = input; + this.pos += 1; + if (this.pos === this.acc.length) { + this.pos = 0; + this.full = true; + } + }; + return _curry2(function _xdropLast(n, xf) { + return new XDropLast(n, xf); + }); + }(); + + var _xdropRepeatsWith = function () { + function XDropRepeatsWith(pred, xf) { + this.xf = xf; + this.pred = pred; + this.lastValue = undefined; + this.seenFirstValue = false; + } + XDropRepeatsWith.prototype['@@transducer/init'] = function () { + return this.xf['@@transducer/init'](); + }; + XDropRepeatsWith.prototype['@@transducer/result'] = function (result) { + return this.xf['@@transducer/result'](result); + }; + XDropRepeatsWith.prototype['@@transducer/step'] = function (result, input) { + var sameAsLast = false; + if (!this.seenFirstValue) { + this.seenFirstValue = true; + } else if (this.pred(this.lastValue, input)) { + sameAsLast = true; + } + this.lastValue = input; + return sameAsLast ? result : this.xf['@@transducer/step'](result, input); + }; + return _curry2(function _xdropRepeatsWith(pred, xf) { + return new XDropRepeatsWith(pred, xf); + }); + }(); + + var _xdropWhile = function () { + function XDropWhile(f, xf) { + this.xf = xf; + this.f = f; + } + XDropWhile.prototype['@@transducer/init'] = _xfBase.init; + XDropWhile.prototype['@@transducer/result'] = _xfBase.result; + XDropWhile.prototype['@@transducer/step'] = function (result, input) { + if (this.f) { + if (this.f(input)) { + return result; + } + this.f = null; + } + return this.xf['@@transducer/step'](result, input); + }; + return _curry2(function _xdropWhile(f, xf) { + return new XDropWhile(f, xf); + }); + }(); + + var _xfilter = function () { + function XFilter(f, xf) { + this.xf = xf; + this.f = f; + } + XFilter.prototype['@@transducer/init'] = _xfBase.init; + XFilter.prototype['@@transducer/result'] = _xfBase.result; + XFilter.prototype['@@transducer/step'] = function (result, input) { + return this.f(input) ? this.xf['@@transducer/step'](result, input) : result; + }; + return _curry2(function _xfilter(f, xf) { + return new XFilter(f, xf); + }); + }(); + + var _xfind = function () { + function XFind(f, xf) { + this.xf = xf; + this.f = f; + this.found = false; + } + XFind.prototype['@@transducer/init'] = _xfBase.init; + XFind.prototype['@@transducer/result'] = function (result) { + if (!this.found) { + result = this.xf['@@transducer/step'](result, void 0); + } + return this.xf['@@transducer/result'](result); + }; + XFind.prototype['@@transducer/step'] = function (result, input) { + if (this.f(input)) { + this.found = true; + result = _reduced(this.xf['@@transducer/step'](result, input)); + } + return result; + }; + return _curry2(function _xfind(f, xf) { + return new XFind(f, xf); + }); + }(); + + var _xfindIndex = function () { + function XFindIndex(f, xf) { + this.xf = xf; + this.f = f; + this.idx = -1; + this.found = false; + } + XFindIndex.prototype['@@transducer/init'] = _xfBase.init; + XFindIndex.prototype['@@transducer/result'] = function (result) { + if (!this.found) { + result = this.xf['@@transducer/step'](result, -1); + } + return this.xf['@@transducer/result'](result); + }; + XFindIndex.prototype['@@transducer/step'] = function (result, input) { + this.idx += 1; + if (this.f(input)) { + this.found = true; + result = _reduced(this.xf['@@transducer/step'](result, this.idx)); + } + return result; + }; + return _curry2(function _xfindIndex(f, xf) { + return new XFindIndex(f, xf); + }); + }(); + + var _xfindLast = function () { + function XFindLast(f, xf) { + this.xf = xf; + this.f = f; + } + XFindLast.prototype['@@transducer/init'] = _xfBase.init; + XFindLast.prototype['@@transducer/result'] = function (result) { + return this.xf['@@transducer/result'](this.xf['@@transducer/step'](result, this.last)); + }; + XFindLast.prototype['@@transducer/step'] = function (result, input) { + if (this.f(input)) { + this.last = input; + } + return result; + }; + return _curry2(function _xfindLast(f, xf) { + return new XFindLast(f, xf); + }); + }(); + + var _xfindLastIndex = function () { + function XFindLastIndex(f, xf) { + this.xf = xf; + this.f = f; + this.idx = -1; + this.lastIdx = -1; + } + XFindLastIndex.prototype['@@transducer/init'] = _xfBase.init; + XFindLastIndex.prototype['@@transducer/result'] = function (result) { + return this.xf['@@transducer/result'](this.xf['@@transducer/step'](result, this.lastIdx)); + }; + XFindLastIndex.prototype['@@transducer/step'] = function (result, input) { + this.idx += 1; + if (this.f(input)) { + this.lastIdx = this.idx; + } + return result; + }; + return _curry2(function _xfindLastIndex(f, xf) { + return new XFindLastIndex(f, xf); + }); + }(); + + var _xmap = function () { + function XMap(f, xf) { + this.xf = xf; + this.f = f; + } + XMap.prototype['@@transducer/init'] = _xfBase.init; + XMap.prototype['@@transducer/result'] = _xfBase.result; + XMap.prototype['@@transducer/step'] = function (result, input) { + return this.xf['@@transducer/step'](result, this.f(input)); + }; + return _curry2(function _xmap(f, xf) { + return new XMap(f, xf); + }); + }(); + + var _xreduceBy = function () { + function XReduceBy(valueFn, valueAcc, keyFn, xf) { + this.valueFn = valueFn; + this.valueAcc = valueAcc; + this.keyFn = keyFn; + this.xf = xf; + this.inputs = {}; + } + XReduceBy.prototype['@@transducer/init'] = _xfBase.init; + XReduceBy.prototype['@@transducer/result'] = function (result) { + var key; + for (key in this.inputs) { + if (_has(key, this.inputs)) { + result = this.xf['@@transducer/step'](result, this.inputs[key]); + if (result['@@transducer/reduced']) { + result = result['@@transducer/value']; + break; + } + } + } + this.inputs = null; + return this.xf['@@transducer/result'](result); + }; + XReduceBy.prototype['@@transducer/step'] = function (result, input) { + var key = this.keyFn(input); + this.inputs[key] = this.inputs[key] || [ + key, + this.valueAcc + ]; + this.inputs[key][1] = this.valueFn(this.inputs[key][1], input); + return result; + }; + return _curryN(4, [], function _xreduceBy(valueFn, valueAcc, keyFn, xf) { + return new XReduceBy(valueFn, valueAcc, keyFn, xf); + }); + }(); + + var _xtake = function () { + function XTake(n, xf) { + this.xf = xf; + this.n = n; + this.i = 0; + } + XTake.prototype['@@transducer/init'] = _xfBase.init; + XTake.prototype['@@transducer/result'] = _xfBase.result; + XTake.prototype['@@transducer/step'] = function (result, input) { + this.i += 1; + var ret = this.n === 0 ? result : this.xf['@@transducer/step'](result, input); + return this.i >= this.n ? _reduced(ret) : ret; + }; + return _curry2(function _xtake(n, xf) { + return new XTake(n, xf); + }); + }(); + + var _xtakeWhile = function () { + function XTakeWhile(f, xf) { + this.xf = xf; + this.f = f; + } + XTakeWhile.prototype['@@transducer/init'] = _xfBase.init; + XTakeWhile.prototype['@@transducer/result'] = _xfBase.result; + XTakeWhile.prototype['@@transducer/step'] = function (result, input) { + return this.f(input) ? this.xf['@@transducer/step'](result, input) : _reduced(result); + }; + return _curry2(function _xtakeWhile(f, xf) { + return new XTakeWhile(f, xf); + }); + }(); + + /** + * Adds two values. + * + * @func + * @memberOf R + * @since v0.1.0 + * @category Math + * @sig Number -> Number -> Number + * @param {Number} a + * @param {Number} b + * @return {Number} + * @see R.subtract + * @example + * + * R.add(2, 3); //=> 5 + * R.add(7)(10); //=> 17 + */ + var add = _curry2(function add(a, b) { + return Number(a) + Number(b); + }); + + /** + * Applies a function to the value at the given index of an array, returning a + * new copy of the array with the element at the given index replaced with the + * result of the function application. + * + * @func + * @memberOf R + * @since v0.14.0 + * @category List + * @sig (a -> a) -> Number -> [a] -> [a] + * @param {Function} fn The function to apply. + * @param {Number} idx The index. + * @param {Array|Arguments} list An array-like object whose value + * at the supplied index will be replaced. + * @return {Array} A copy of the supplied array-like object with + * the element at index `idx` replaced with the value + * returned by applying `fn` to the existing element. + * @see R.update + * @example + * + * R.adjust(R.add(10), 1, [0, 1, 2]); //=> [0, 11, 2] + * R.adjust(R.add(10))(1)([0, 1, 2]); //=> [0, 11, 2] + */ + var adjust = _curry3(function adjust(fn, idx, list) { + if (idx >= list.length || idx < -list.length) { + return list; + } + var start = idx < 0 ? list.length : 0; + var _idx = start + idx; + var _list = _concat(list); + _list[_idx] = fn(list[_idx]); + return _list; + }); + + /** + * Returns `true` if all elements of the list match the predicate, `false` if + * there are any that don't. + * + * Dispatches to the `all` method of the second argument, if present. + * + * Acts as a transducer if a transformer is given in list position. + * + * @func + * @memberOf R + * @since v0.1.0 + * @category List + * @sig (a -> Boolean) -> [a] -> Boolean + * @param {Function} fn The predicate function. + * @param {Array} list The array to consider. + * @return {Boolean} `true` if the predicate is satisfied by every element, `false` + * otherwise. + * @see R.any, R.none, R.transduce + * @example + * + * var lessThan2 = R.flip(R.lt)(2); + * var lessThan3 = R.flip(R.lt)(3); + * R.all(lessThan2)([1, 2]); //=> false + * R.all(lessThan3)([1, 2]); //=> true + */ + var all = _curry2(_dispatchable('all', _xall, function all(fn, list) { + var idx = 0; + while (idx < list.length) { + if (!fn(list[idx])) { + return false; + } + idx += 1; + } + return true; + })); + + /** + * Returns a function that always returns the given value. Note that for + * non-primitives the value returned is a reference to the original value. + * + * This function is known as `const`, `constant`, or `K` (for K combinator) in + * other languages and libraries. + * + * @func + * @memberOf R + * @since v0.1.0 + * @category Function + * @sig a -> (* -> a) + * @param {*} val The value to wrap in a function + * @return {Function} A Function :: * -> val. + * @example + * + * var t = R.always('Tee'); + * t(); //=> 'Tee' + */ + var always = _curry1(function always(val) { + return function () { + return val; + }; + }); + + /** + * Returns `true` if both arguments are `true`; `false` otherwise. + * + * @func + * @memberOf R + * @since v0.1.0 + * @category Logic + * @sig * -> * -> * + * @param {Boolean} a A boolean value + * @param {Boolean} b A boolean value + * @return {Boolean} `true` if both arguments are `true`, `false` otherwise + * @see R.both + * @example + * + * R.and(true, true); //=> true + * R.and(true, false); //=> false + * R.and(false, true); //=> false + * R.and(false, false); //=> false + */ + var and = _curry2(function and(a, b) { + return a && b; + }); + + /** + * Returns `true` if at least one of elements of the list match the predicate, + * `false` otherwise. + * + * Dispatches to the `any` method of the second argument, if present. + * + * Acts as a transducer if a transformer is given in list position. + * + * @func + * @memberOf R + * @since v0.1.0 + * @category List + * @sig (a -> Boolean) -> [a] -> Boolean + * @param {Function} fn The predicate function. + * @param {Array} list The array to consider. + * @return {Boolean} `true` if the predicate is satisfied by at least one element, `false` + * otherwise. + * @see R.all, R.none, R.transduce + * @example + * + * var lessThan0 = R.flip(R.lt)(0); + * var lessThan2 = R.flip(R.lt)(2); + * R.any(lessThan0)([1, 2]); //=> false + * R.any(lessThan2)([1, 2]); //=> true + */ + var any = _curry2(_dispatchable('any', _xany, function any(fn, list) { + var idx = 0; + while (idx < list.length) { + if (fn(list[idx])) { + return true; + } + idx += 1; + } + return false; + })); + + /** + * Returns a new list, composed of n-tuples of consecutive elements If `n` is + * greater than the length of the list, an empty list is returned. + * + * Dispatches to the `aperture` method of the second argument, if present. + * + * Acts as a transducer if a transformer is given in list position. + * + * @func + * @memberOf R + * @since v0.12.0 + * @category List + * @sig Number -> [a] -> [[a]] + * @param {Number} n The size of the tuples to create + * @param {Array} list The list to split into `n`-tuples + * @return {Array} The new list. + * @see R.transduce + * @example + * + * R.aperture(2, [1, 2, 3, 4, 5]); //=> [[1, 2], [2, 3], [3, 4], [4, 5]] + * R.aperture(3, [1, 2, 3, 4, 5]); //=> [[1, 2, 3], [2, 3, 4], [3, 4, 5]] + * R.aperture(7, [1, 2, 3, 4, 5]); //=> [] + */ + var aperture = _curry2(_dispatchable('aperture', _xaperture, _aperture)); + + /** + * Returns a new list containing the contents of the given list, followed by + * the given element. + * + * @func + * @memberOf R + * @since v0.1.0 + * @category List + * @sig a -> [a] -> [a] + * @param {*} el The element to add to the end of the new list. + * @param {Array} list The list whose contents will be added to the beginning of the output + * list. + * @return {Array} A new list containing the contents of the old list followed by `el`. + * @see R.prepend + * @example + * + * R.append('tests', ['write', 'more']); //=> ['write', 'more', 'tests'] + * R.append('tests', []); //=> ['tests'] + * R.append(['tests'], ['write', 'more']); //=> ['write', 'more', ['tests']] + */ + var append = _curry2(function append(el, list) { + return _concat(list, [el]); + }); + + /** + * Applies function `fn` to the argument list `args`. This is useful for + * creating a fixed-arity function from a variadic function. `fn` should be a + * bound function if context is significant. + * + * @func + * @memberOf R + * @since v0.7.0 + * @category Function + * @sig (*... -> a) -> [*] -> a + * @param {Function} fn + * @param {Array} args + * @return {*} + * @see R.call, R.unapply + * @example + * + * var nums = [1, 2, 3, -99, 42, 6, 7]; + * R.apply(Math.max, nums); //=> 42 + */ + var apply = _curry2(function apply(fn, args) { + return fn.apply(this, args); + }); + + /** + * Makes a shallow clone of an object, setting or overriding the specified + * property with the given value. Note that this copies and flattens prototype + * properties onto the new object as well. All non-primitive properties are + * copied by reference. + * + * @func + * @memberOf R + * @since v0.8.0 + * @category Object + * @sig String -> a -> {k: v} -> {k: v} + * @param {String} prop the property name to set + * @param {*} val the new value + * @param {Object} obj the object to clone + * @return {Object} a new object similar to the original except for the specified property. + * @see R.dissoc + * @example + * + * R.assoc('c', 3, {a: 1, b: 2}); //=> {a: 1, b: 2, c: 3} + */ + var assoc = _curry3(function assoc(prop, val, obj) { + var result = {}; + for (var p in obj) { + result[p] = obj[p]; + } + result[prop] = val; + return result; + }); + + /** + * Makes a shallow clone of an object, setting or overriding the nodes required + * to create the given path, and placing the specific value at the tail end of + * that path. Note that this copies and flattens prototype properties onto the + * new object as well. All non-primitive properties are copied by reference. + * + * @func + * @memberOf R + * @since v0.8.0 + * @category Object + * @sig [String] -> a -> {k: v} -> {k: v} + * @param {Array} path the path to set + * @param {*} val the new value + * @param {Object} obj the object to clone + * @return {Object} a new object similar to the original except along the specified path. + * @see R.dissocPath + * @example + * + * R.assocPath(['a', 'b', 'c'], 42, {a: {b: {c: 0}}}); //=> {a: {b: {c: 42}}} + */ + var assocPath = _curry3(function assocPath(path, val, obj) { + switch (path.length) { + case 0: + return val; + case 1: + return assoc(path[0], val, obj); + default: + return assoc(path[0], assocPath(_slice(path, 1), val, Object(obj[path[0]])), obj); + } + }); + + /** + * Creates a function that is bound to a context. + * Note: `R.bind` does not provide the additional argument-binding capabilities of + * [Function.prototype.bind](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind). + * + * @func + * @memberOf R + * @since v0.6.0 + * @category Function + * @category Object + * @sig (* -> *) -> {*} -> (* -> *) + * @param {Function} fn The function to bind to context + * @param {Object} thisObj The context to bind `fn` to + * @return {Function} A function that will execute in the context of `thisObj`. + * @see R.partial + * @example + * + * var log = R.bind(console.log, console); + * R.pipe(R.assoc('a', 2), R.tap(log), R.assoc('a', 3))({a: 1}); //=> {a: 3} + * // logs {a: 2} + */ + var bind = _curry2(function bind(fn, thisObj) { + return _arity(fn.length, function () { + return fn.apply(thisObj, arguments); + }); + }); + + /** + * Restricts a number to be within a range. + * + * Also works for other ordered types such as Strings and Dates. + * + * @func + * @memberOf R + * @since v0.20.0 + * @category Relation + * @sig Ord a => a -> a -> a -> a + * @param {Number} minimum number + * @param {Number} maximum number + * @param {Number} value to be clamped + * @return {Number} Returns the clamped value + * @example + * + * R.clamp(1, 10, -1) // => 1 + * R.clamp(1, 10, 11) // => 10 + * R.clamp(1, 10, 4) // => 4 + */ + var clamp = _curry3(function clamp(min, max, value) { + if (min > max) { + throw new Error('min must not be greater than max in clamp(min, max, value)'); + } + return value < min ? min : value > max ? max : value; + }); + + /** + * Makes a comparator function out of a function that reports whether the first + * element is less than the second. + * + * @func + * @memberOf R + * @since v0.1.0 + * @category Function + * @sig (a, b -> Boolean) -> (a, b -> Number) + * @param {Function} pred A predicate function of arity two. + * @return {Function} A Function :: a -> b -> Int that returns `-1` if a < b, `1` if b < a, otherwise `0`. + * @example + * + * var cmp = R.comparator((a, b) => a.age < b.age); + * var people = [ + * // ... + * ]; + * R.sort(cmp, people); + */ + var comparator = _curry1(function comparator(pred) { + return function (a, b) { + return pred(a, b) ? -1 : pred(b, a) ? 1 : 0; + }; + }); + + /** + * Returns a curried equivalent of the provided function, with the specified + * arity. The curried function has two unusual capabilities. First, its + * arguments needn't be provided one at a time. If `g` is `R.curryN(3, f)`, the + * following are equivalent: + * + * - `g(1)(2)(3)` + * - `g(1)(2, 3)` + * - `g(1, 2)(3)` + * - `g(1, 2, 3)` + * + * Secondly, the special placeholder value `R.__` may be used to specify + * "gaps", allowing partial application of any combination of arguments, + * regardless of their positions. If `g` is as above and `_` is `R.__`, the + * following are equivalent: + * + * - `g(1, 2, 3)` + * - `g(_, 2, 3)(1)` + * - `g(_, _, 3)(1)(2)` + * - `g(_, _, 3)(1, 2)` + * - `g(_, 2)(1)(3)` + * - `g(_, 2)(1, 3)` + * - `g(_, 2)(_, 3)(1)` + * + * @func + * @memberOf R + * @since v0.5.0 + * @category Function + * @sig Number -> (* -> a) -> (* -> a) + * @param {Number} length The arity for the returned function. + * @param {Function} fn The function to curry. + * @return {Function} A new, curried function. + * @see R.curry + * @example + * + * var sumArgs = (...args) => R.sum(args); + * + * var curriedAddFourNumbers = R.curryN(4, sumArgs); + * var f = curriedAddFourNumbers(1, 2); + * var g = f(3); + * g(4); //=> 10 + */ + var curryN = _curry2(function curryN(length, fn) { + if (length === 1) { + return _curry1(fn); + } + return _arity(length, _curryN(length, [], fn)); + }); + + /** + * Decrements its argument. + * + * @func + * @memberOf R + * @since v0.9.0 + * @category Math + * @sig Number -> Number + * @param {Number} n + * @return {Number} + * @see R.inc + * @example + * + * R.dec(42); //=> 41 + */ + var dec = add(-1); + + /** + * Returns the second argument if it is not `null`, `undefined` or `NaN` + * otherwise the first argument is returned. + * + * @func + * @memberOf R + * @since v0.10.0 + * @category Logic + * @sig a -> b -> a | b + * @param {a} val The default value. + * @param {b} val The value to return if it is not null or undefined + * @return {*} The the second value or the default value + * @example + * + * var defaultTo42 = R.defaultTo(42); + * + * defaultTo42(null); //=> 42 + * defaultTo42(undefined); //=> 42 + * defaultTo42('Ramda'); //=> 'Ramda' + * defaultTo42(parseInt('string')); //=> 42 + */ + var defaultTo = _curry2(function defaultTo(d, v) { + return v == null || v !== v ? d : v; + }); + + /** + * Finds the set (i.e. no duplicates) of all elements in the first list not + * contained in the second list. Duplication is determined according to the + * value returned by applying the supplied predicate to two list elements. + * + * @func + * @memberOf R + * @since v0.1.0 + * @category Relation + * @sig (a -> a -> Boolean) -> [*] -> [*] -> [*] + * @param {Function} pred A predicate used to test whether two items are equal. + * @param {Array} list1 The first list. + * @param {Array} list2 The second list. + * @return {Array} The elements in `list1` that are not in `list2`. + * @see R.difference, R.symmetricDifference, R.symmetricDifferenceWith + * @example + * + * var cmp = (x, y) => x.a === y.a; + * var l1 = [{a: 1}, {a: 2}, {a: 3}]; + * var l2 = [{a: 3}, {a: 4}]; + * R.differenceWith(cmp, l1, l2); //=> [{a: 1}, {a: 2}] + */ + var differenceWith = _curry3(function differenceWith(pred, first, second) { + var out = []; + var idx = 0; + var firstLen = first.length; + while (idx < firstLen) { + if (!_containsWith(pred, first[idx], second) && !_containsWith(pred, first[idx], out)) { + out.push(first[idx]); + } + idx += 1; + } + return out; + }); + + /** + * Returns a new object that does not contain a `prop` property. + * + * @func + * @memberOf R + * @since v0.10.0 + * @category Object + * @sig String -> {k: v} -> {k: v} + * @param {String} prop the name of the property to dissociate + * @param {Object} obj the object to clone + * @return {Object} a new object similar to the original but without the specified property + * @see R.assoc + * @example + * + * R.dissoc('b', {a: 1, b: 2, c: 3}); //=> {a: 1, c: 3} + */ + var dissoc = _curry2(function dissoc(prop, obj) { + var result = {}; + for (var p in obj) { + if (p !== prop) { + result[p] = obj[p]; + } + } + return result; + }); + + /** + * Makes a shallow clone of an object, omitting the property at the given path. + * Note that this copies and flattens prototype properties onto the new object + * as well. All non-primitive properties are copied by reference. + * + * @func + * @memberOf R + * @since v0.11.0 + * @category Object + * @sig [String] -> {k: v} -> {k: v} + * @param {Array} path the path to set + * @param {Object} obj the object to clone + * @return {Object} a new object without the property at path + * @see R.assocPath + * @example + * + * R.dissocPath(['a', 'b', 'c'], {a: {b: {c: 42}}}); //=> {a: {b: {}}} + */ + var dissocPath = _curry2(function dissocPath(path, obj) { + switch (path.length) { + case 0: + return obj; + case 1: + return dissoc(path[0], obj); + default: + var head = path[0]; + var tail = _slice(path, 1); + return obj[head] == null ? obj : assoc(head, dissocPath(tail, obj[head]), obj); + } + }); + + /** + * Divides two numbers. Equivalent to `a / b`. + * + * @func + * @memberOf R + * @since v0.1.0 + * @category Math + * @sig Number -> Number -> Number + * @param {Number} a The first value. + * @param {Number} b The second value. + * @return {Number} The result of `a / b`. + * @see R.multiply + * @example + * + * R.divide(71, 100); //=> 0.71 + * + * var half = R.divide(R.__, 2); + * half(42); //=> 21 + * + * var reciprocal = R.divide(1); + * reciprocal(4); //=> 0.25 + */ + var divide = _curry2(function divide(a, b) { + return a / b; + }); + + /** + * Returns a new list excluding the leading elements of a given list which + * satisfy the supplied predicate function. It passes each value to the supplied + * predicate function, skipping elements while the predicate function returns + * `true`. The predicate function is applied to one argument: *(value)*. + * + * Dispatches to the `dropWhile` method of the second argument, if present. + * + * Acts as a transducer if a transformer is given in list position. + * + * @func + * @memberOf R + * @since v0.9.0 + * @category List + * @sig (a -> Boolean) -> [a] -> [a] + * @param {Function} fn The function called per iteration. + * @param {Array} list The collection to iterate over. + * @return {Array} A new array. + * @see R.takeWhile, R.transduce, R.addIndex + * @example + * + * var lteTwo = x => x <= 2; + * + * R.dropWhile(lteTwo, [1, 2, 3, 4, 3, 2, 1]); //=> [3, 4, 3, 2, 1] + */ + var dropWhile = _curry2(_dispatchable('dropWhile', _xdropWhile, function dropWhile(pred, list) { + var idx = 0; + var len = list.length; + while (idx < len && pred(list[idx])) { + idx += 1; + } + return _slice(list, idx); + })); + + /** + * Returns the empty value of its argument's type. Ramda defines the empty + * value of Array (`[]`), Object (`{}`), String (`''`), and Arguments. Other + * types are supported if they define `.empty` and/or + * `.prototype.empty`. + * + * Dispatches to the `empty` method of the first argument, if present. + * + * @func + * @memberOf R + * @since v0.3.0 + * @category Function + * @sig a -> a + * @param {*} x + * @return {*} + * @example + * + * R.empty(Just(42)); //=> Nothing() + * R.empty([1, 2, 3]); //=> [] + * R.empty('unicorns'); //=> '' + * R.empty({x: 1, y: 2}); //=> {} + */ + // else + var empty = _curry1(function empty(x) { + return x != null && typeof x.empty === 'function' ? x.empty() : x != null && x.constructor != null && typeof x.constructor.empty === 'function' ? x.constructor.empty() : _isArray(x) ? [] : _isString(x) ? '' : _isObject(x) ? {} : _isArguments(x) ? function () { + return arguments; + }() : // else + void 0; + }); + + /** + * Creates a new object by recursively evolving a shallow copy of `object`, + * according to the `transformation` functions. All non-primitive properties + * are copied by reference. + * + * A `transformation` function will not be invoked if its corresponding key + * does not exist in the evolved object. + * + * @func + * @memberOf R + * @since v0.9.0 + * @category Object + * @sig {k: (v -> v)} -> {k: v} -> {k: v} + * @param {Object} transformations The object specifying transformation functions to apply + * to the object. + * @param {Object} object The object to be transformed. + * @return {Object} The transformed object. + * @example + * + * var tomato = {firstName: ' Tomato ', data: {elapsed: 100, remaining: 1400}, id:123}; + * var transformations = { + * firstName: R.trim, + * lastName: R.trim, // Will not get invoked. + * data: {elapsed: R.add(1), remaining: R.add(-1)} + * }; + * R.evolve(transformations, tomato); //=> {firstName: 'Tomato', data: {elapsed: 101, remaining: 1399}, id:123} + */ + var evolve = _curry2(function evolve(transformations, object) { + var result = {}; + var transformation, key, type; + for (key in object) { + transformation = transformations[key]; + type = typeof transformation; + result[key] = type === 'function' ? transformation(object[key]) : type === 'object' ? evolve(transformations[key], object[key]) : object[key]; + } + return result; + }); + + /** + * Returns the first element of the list which matches the predicate, or + * `undefined` if no element matches. + * + * Dispatches to the `find` method of the second argument, if present. + * + * Acts as a transducer if a transformer is given in list position. + * + * @func + * @memberOf R + * @since v0.1.0 + * @category List + * @sig (a -> Boolean) -> [a] -> a | undefined + * @param {Function} fn The predicate function used to determine if the element is the + * desired one. + * @param {Array} list The array to consider. + * @return {Object} The element found, or `undefined`. + * @see R.transduce + * @example + * + * var xs = [{a: 1}, {a: 2}, {a: 3}]; + * R.find(R.propEq('a', 2))(xs); //=> {a: 2} + * R.find(R.propEq('a', 4))(xs); //=> undefined + */ + var find = _curry2(_dispatchable('find', _xfind, function find(fn, list) { + var idx = 0; + var len = list.length; + while (idx < len) { + if (fn(list[idx])) { + return list[idx]; + } + idx += 1; + } + })); + + /** + * Returns the index of the first element of the list which matches the + * predicate, or `-1` if no element matches. + * + * Dispatches to the `findIndex` method of the second argument, if present. + * + * Acts as a transducer if a transformer is given in list position. + * + * @func + * @memberOf R + * @since v0.1.1 + * @category List + * @sig (a -> Boolean) -> [a] -> Number + * @param {Function} fn The predicate function used to determine if the element is the + * desired one. + * @param {Array} list The array to consider. + * @return {Number} The index of the element found, or `-1`. + * @see R.transduce + * @example + * + * var xs = [{a: 1}, {a: 2}, {a: 3}]; + * R.findIndex(R.propEq('a', 2))(xs); //=> 1 + * R.findIndex(R.propEq('a', 4))(xs); //=> -1 + */ + var findIndex = _curry2(_dispatchable('findIndex', _xfindIndex, function findIndex(fn, list) { + var idx = 0; + var len = list.length; + while (idx < len) { + if (fn(list[idx])) { + return idx; + } + idx += 1; + } + return -1; + })); + + /** + * Returns the last element of the list which matches the predicate, or + * `undefined` if no element matches. + * + * Dispatches to the `findLast` method of the second argument, if present. + * + * Acts as a transducer if a transformer is given in list position. + * + * @func + * @memberOf R + * @since v0.1.1 + * @category List + * @sig (a -> Boolean) -> [a] -> a | undefined + * @param {Function} fn The predicate function used to determine if the element is the + * desired one. + * @param {Array} list The array to consider. + * @return {Object} The element found, or `undefined`. + * @see R.transduce + * @example + * + * var xs = [{a: 1, b: 0}, {a:1, b: 1}]; + * R.findLast(R.propEq('a', 1))(xs); //=> {a: 1, b: 1} + * R.findLast(R.propEq('a', 4))(xs); //=> undefined + */ + var findLast = _curry2(_dispatchable('findLast', _xfindLast, function findLast(fn, list) { + var idx = list.length - 1; + while (idx >= 0) { + if (fn(list[idx])) { + return list[idx]; + } + idx -= 1; + } + })); + + /** + * Returns the index of the last element of the list which matches the + * predicate, or `-1` if no element matches. + * + * Dispatches to the `findLastIndex` method of the second argument, if present. + * + * Acts as a transducer if a transformer is given in list position. + * + * @func + * @memberOf R + * @since v0.1.1 + * @category List + * @sig (a -> Boolean) -> [a] -> Number + * @param {Function} fn The predicate function used to determine if the element is the + * desired one. + * @param {Array} list The array to consider. + * @return {Number} The index of the element found, or `-1`. + * @see R.transduce + * @example + * + * var xs = [{a: 1, b: 0}, {a:1, b: 1}]; + * R.findLastIndex(R.propEq('a', 1))(xs); //=> 1 + * R.findLastIndex(R.propEq('a', 4))(xs); //=> -1 + */ + var findLastIndex = _curry2(_dispatchable('findLastIndex', _xfindLastIndex, function findLastIndex(fn, list) { + var idx = list.length - 1; + while (idx >= 0) { + if (fn(list[idx])) { + return idx; + } + idx -= 1; + } + return -1; + })); + + /** + * Iterate over an input `list`, calling a provided function `fn` for each + * element in the list. + * + * `fn` receives one argument: *(value)*. + * + * Note: `R.forEach` does not skip deleted or unassigned indices (sparse + * arrays), unlike the native `Array.prototype.forEach` method. For more + * details on this behavior, see: + * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach#Description + * + * Also note that, unlike `Array.prototype.forEach`, Ramda's `forEach` returns + * the original array. In some libraries this function is named `each`. + * + * Dispatches to the `forEach` method of the second argument, if present. + * + * @func + * @memberOf R + * @since v0.1.1 + * @category List + * @sig (a -> *) -> [a] -> [a] + * @param {Function} fn The function to invoke. Receives one argument, `value`. + * @param {Array} list The list to iterate over. + * @return {Array} The original list. + * @see R.addIndex + * @example + * + * var printXPlusFive = x => console.log(x + 5); + * R.forEach(printXPlusFive, [1, 2, 3]); //=> [1, 2, 3] + * // logs 6 + * // logs 7 + * // logs 8 + */ + var forEach = _curry2(_checkForMethod('forEach', function forEach(fn, list) { + var len = list.length; + var idx = 0; + while (idx < len) { + fn(list[idx]); + idx += 1; + } + return list; + })); + + /** + * Creates a new object from a list key-value pairs. If a key appears in + * multiple pairs, the rightmost pair is included in the object. + * + * @func + * @memberOf R + * @since v0.3.0 + * @category List + * @sig [[k,v]] -> {k: v} + * @param {Array} pairs An array of two-element arrays that will be the keys and values of the output object. + * @return {Object} The object made by pairing up `keys` and `values`. + * @see R.toPairs, R.pair + * @example + * + * R.fromPairs([['a', 1], ['b', 2], ['c', 3]]); //=> {a: 1, b: 2, c: 3} + */ + var fromPairs = _curry1(function fromPairs(pairs) { + var result = {}; + var idx = 0; + while (idx < pairs.length) { + result[pairs[idx][0]] = pairs[idx][1]; + idx += 1; + } + return result; + }); + + /** + * Takes a list and returns a list of lists where each sublist's elements are + * all "equal" according to the provided equality function. + * + * @func + * @memberOf R + * @since v0.21.0 + * @category List + * @sig ((a, a) → Boolean) → [a] → [[a]] + * @param {Function} fn Function for determining whether two given (adjacent) + * elements should be in the same group + * @param {Array} list The array to group. Also accepts a string, which will be + * treated as a list of characters. + * @return {List} A list that contains sublists of equal elements, + * whose concatenations are equal to the original list. + * @example + * + * R.groupWith(R.equals, [0, 1, 1, 2, 3, 5, 8, 13, 21]) + * //=> [[0], [1, 1], [2], [3], [5], [8], [13], [21]] + * + * R.groupWith((a, b) => a % 2 === b % 2, [0, 1, 1, 2, 3, 5, 8, 13, 21]) + * //=> [[0], [1, 1], [2], [3, 5], [8], [13, 21]] + * + * R.groupWith(R.eqBy(isVowel), 'aestiou') + * //=> ['ae', 'st', 'iou'] + */ + var groupWith = _curry2(function (fn, list) { + var res = []; + var idx = 0; + var len = list.length; + while (idx < len) { + var nextidx = idx + 1; + while (nextidx < len && fn(list[idx], list[nextidx])) { + nextidx += 1; + } + res.push(list.slice(idx, nextidx)); + idx = nextidx; + } + return res; + }); + + /** + * Returns `true` if the first argument is greater than the second; `false` + * otherwise. + * + * @func + * @memberOf R + * @since v0.1.0 + * @category Relation + * @sig Ord a => a -> a -> Boolean + * @param {*} a + * @param {*} b + * @return {Boolean} + * @see R.lt + * @example + * + * R.gt(2, 1); //=> true + * R.gt(2, 2); //=> false + * R.gt(2, 3); //=> false + * R.gt('a', 'z'); //=> false + * R.gt('z', 'a'); //=> true + */ + var gt = _curry2(function gt(a, b) { + return a > b; + }); + + /** + * Returns `true` if the first argument is greater than or equal to the second; + * `false` otherwise. + * + * @func + * @memberOf R + * @since v0.1.0 + * @category Relation + * @sig Ord a => a -> a -> Boolean + * @param {Number} a + * @param {Number} b + * @return {Boolean} + * @see R.lte + * @example + * + * R.gte(2, 1); //=> true + * R.gte(2, 2); //=> true + * R.gte(2, 3); //=> false + * R.gte('a', 'z'); //=> false + * R.gte('z', 'a'); //=> true + */ + var gte = _curry2(function gte(a, b) { + return a >= b; + }); + + /** + * Returns whether or not an object has an own property with the specified name + * + * @func + * @memberOf R + * @since v0.7.0 + * @category Object + * @sig s -> {s: x} -> Boolean + * @param {String} prop The name of the property to check for. + * @param {Object} obj The object to query. + * @return {Boolean} Whether the property exists. + * @example + * + * var hasName = R.has('name'); + * hasName({name: 'alice'}); //=> true + * hasName({name: 'bob'}); //=> true + * hasName({}); //=> false + * + * var point = {x: 0, y: 0}; + * var pointHas = R.has(R.__, point); + * pointHas('x'); //=> true + * pointHas('y'); //=> true + * pointHas('z'); //=> false + */ + var has = _curry2(_has); + + /** + * Returns whether or not an object or its prototype chain has a property with + * the specified name + * + * @func + * @memberOf R + * @since v0.7.0 + * @category Object + * @sig s -> {s: x} -> Boolean + * @param {String} prop The name of the property to check for. + * @param {Object} obj The object to query. + * @return {Boolean} Whether the property exists. + * @example + * + * function Rectangle(width, height) { + * this.width = width; + * this.height = height; + * } + * Rectangle.prototype.area = function() { + * return this.width * this.height; + * }; + * + * var square = new Rectangle(2, 2); + * R.hasIn('width', square); //=> true + * R.hasIn('area', square); //=> true + */ + var hasIn = _curry2(function hasIn(prop, obj) { + return prop in obj; + }); + + /** + * Returns true if its arguments are identical, false otherwise. Values are + * identical if they reference the same memory. `NaN` is identical to `NaN`; + * `0` and `-0` are not identical. + * + * @func + * @memberOf R + * @since v0.15.0 + * @category Relation + * @sig a -> a -> Boolean + * @param {*} a + * @param {*} b + * @return {Boolean} + * @example + * + * var o = {}; + * R.identical(o, o); //=> true + * R.identical(1, 1); //=> true + * R.identical(1, '1'); //=> false + * R.identical([], []); //=> false + * R.identical(0, -0); //=> false + * R.identical(NaN, NaN); //=> true + */ + // SameValue algorithm + // Steps 1-5, 7-10 + // Steps 6.b-6.e: +0 != -0 + // Step 6.a: NaN == NaN + var identical = _curry2(function identical(a, b) { + // SameValue algorithm + if (a === b) { + // Steps 1-5, 7-10 + // Steps 6.b-6.e: +0 != -0 + return a !== 0 || 1 / a === 1 / b; + } else { + // Step 6.a: NaN == NaN + return a !== a && b !== b; + } + }); + + /** + * A function that does nothing but return the parameter supplied to it. Good + * as a default or placeholder function. + * + * @func + * @memberOf R + * @since v0.1.0 + * @category Function + * @sig a -> a + * @param {*} x The value to return. + * @return {*} The input value, `x`. + * @example + * + * R.identity(1); //=> 1 + * + * var obj = {}; + * R.identity(obj) === obj; //=> true + */ + var identity = _curry1(_identity); + + /** + * Creates a function that will process either the `onTrue` or the `onFalse` + * function depending upon the result of the `condition` predicate. + * + * @func + * @memberOf R + * @since v0.8.0 + * @category Logic + * @sig (*... -> Boolean) -> (*... -> *) -> (*... -> *) -> (*... -> *) + * @param {Function} condition A predicate function + * @param {Function} onTrue A function to invoke when the `condition` evaluates to a truthy value. + * @param {Function} onFalse A function to invoke when the `condition` evaluates to a falsy value. + * @return {Function} A new unary function that will process either the `onTrue` or the `onFalse` + * function depending upon the result of the `condition` predicate. + * @see R.unless, R.when + * @example + * + * var incCount = R.ifElse( + * R.has('count'), + * R.over(R.lensProp('count'), R.inc), + * R.assoc('count', 1) + * ); + * incCount({}); //=> { count: 1 } + * incCount({ count: 1 }); //=> { count: 2 } + */ + var ifElse = _curry3(function ifElse(condition, onTrue, onFalse) { + return curryN(Math.max(condition.length, onTrue.length, onFalse.length), function _ifElse() { + return condition.apply(this, arguments) ? onTrue.apply(this, arguments) : onFalse.apply(this, arguments); + }); + }); + + /** + * Increments its argument. + * + * @func + * @memberOf R + * @since v0.9.0 + * @category Math + * @sig Number -> Number + * @param {Number} n + * @return {Number} + * @see R.dec + * @example + * + * R.inc(42); //=> 43 + */ + var inc = add(1); + + /** + * Inserts the supplied element into the list, at index `index`. _Note that + * this is not destructive_: it returns a copy of the list with the changes. + * No lists have been harmed in the application of this function. + * + * @func + * @memberOf R + * @since v0.2.2 + * @category List + * @sig Number -> a -> [a] -> [a] + * @param {Number} index The position to insert the element + * @param {*} elt The element to insert into the Array + * @param {Array} list The list to insert into + * @return {Array} A new Array with `elt` inserted at `index`. + * @example + * + * R.insert(2, 'x', [1,2,3,4]); //=> [1,2,'x',3,4] + */ + var insert = _curry3(function insert(idx, elt, list) { + idx = idx < list.length && idx >= 0 ? idx : list.length; + var result = _slice(list); + result.splice(idx, 0, elt); + return result; + }); + + /** + * Inserts the sub-list into the list, at index `index`. _Note that this is not + * destructive_: it returns a copy of the list with the changes. + * No lists have been harmed in the application of this function. + * + * @func + * @memberOf R + * @since v0.9.0 + * @category List + * @sig Number -> [a] -> [a] -> [a] + * @param {Number} index The position to insert the sub-list + * @param {Array} elts The sub-list to insert into the Array + * @param {Array} list The list to insert the sub-list into + * @return {Array} A new Array with `elts` inserted starting at `index`. + * @example + * + * R.insertAll(2, ['x','y','z'], [1,2,3,4]); //=> [1,2,'x','y','z',3,4] + */ + var insertAll = _curry3(function insertAll(idx, elts, list) { + idx = idx < list.length && idx >= 0 ? idx : list.length; + return _concat(_concat(_slice(list, 0, idx), elts), _slice(list, idx)); + }); + + /** + * Creates a new list with the separator interposed between elements. + * + * Dispatches to the `intersperse` method of the second argument, if present. + * + * @func + * @memberOf R + * @since v0.14.0 + * @category List + * @sig a -> [a] -> [a] + * @param {*} separator The element to add to the list. + * @param {Array} list The list to be interposed. + * @return {Array} The new list. + * @example + * + * R.intersperse('n', ['ba', 'a', 'a']); //=> ['ba', 'n', 'a', 'n', 'a'] + */ + var intersperse = _curry2(_checkForMethod('intersperse', function intersperse(separator, list) { + var out = []; + var idx = 0; + var length = list.length; + while (idx < length) { + if (idx === length - 1) { + out.push(list[idx]); + } else { + out.push(list[idx], separator); + } + idx += 1; + } + return out; + })); + + /** + * See if an object (`val`) is an instance of the supplied constructor. This + * function will check up the inheritance chain, if any. + * + * @func + * @memberOf R + * @since v0.3.0 + * @category Type + * @sig (* -> {*}) -> a -> Boolean + * @param {Object} ctor A constructor + * @param {*} val The value to test + * @return {Boolean} + * @example + * + * R.is(Object, {}); //=> true + * R.is(Number, 1); //=> true + * R.is(Object, 1); //=> false + * R.is(String, 's'); //=> true + * R.is(String, new String('')); //=> true + * R.is(Object, new String('')); //=> true + * R.is(Object, 's'); //=> false + * R.is(Number, {}); //=> false + */ + var is = _curry2(function is(Ctor, val) { + return val != null && val.constructor === Ctor || val instanceof Ctor; + }); + + /** + * Tests whether or not an object is similar to an array. + * + * @func + * @memberOf R + * @since v0.5.0 + * @category Type + * @category List + * @sig * -> Boolean + * @param {*} x The object to test. + * @return {Boolean} `true` if `x` has a numeric length property and extreme indices defined; `false` otherwise. + * @example + * + * R.isArrayLike([]); //=> true + * R.isArrayLike(true); //=> false + * R.isArrayLike({}); //=> false + * R.isArrayLike({length: 10}); //=> false + * R.isArrayLike({0: 'zero', 9: 'nine', length: 10}); //=> true + */ + var isArrayLike = _curry1(function isArrayLike(x) { + if (_isArray(x)) { + return true; + } + if (!x) { + return false; + } + if (typeof x !== 'object') { + return false; + } + if (_isString(x)) { + return false; + } + if (x.nodeType === 1) { + return !!x.length; + } + if (x.length === 0) { + return true; + } + if (x.length > 0) { + return x.hasOwnProperty(0) && x.hasOwnProperty(x.length - 1); + } + return false; + }); + + /** + * Checks if the input value is `null` or `undefined`. + * + * @func + * @memberOf R + * @since v0.9.0 + * @category Type + * @sig * -> Boolean + * @param {*} x The value to test. + * @return {Boolean} `true` if `x` is `undefined` or `null`, otherwise `false`. + * @example + * + * R.isNil(null); //=> true + * R.isNil(undefined); //=> true + * R.isNil(0); //=> false + * R.isNil([]); //=> false + */ + var isNil = _curry1(function isNil(x) { + return x == null; + }); + + /** + * Returns a list containing the names of all the enumerable own properties of + * the supplied object. + * Note that the order of the output array is not guaranteed to be consistent + * across different JS platforms. + * + * @func + * @memberOf R + * @since v0.1.0 + * @category Object + * @sig {k: v} -> [k] + * @param {Object} obj The object to extract properties from + * @return {Array} An array of the object's own properties. + * @example + * + * R.keys({a: 1, b: 2, c: 3}); //=> ['a', 'b', 'c'] + */ + // cover IE < 9 keys issues + // Safari bug + var keys = function () { + // cover IE < 9 keys issues + var hasEnumBug = !{ toString: null }.propertyIsEnumerable('toString'); + var nonEnumerableProps = [ + 'constructor', + 'valueOf', + 'isPrototypeOf', + 'toString', + 'propertyIsEnumerable', + 'hasOwnProperty', + 'toLocaleString' + ]; + // Safari bug + var hasArgsEnumBug = function () { + 'use strict'; + return arguments.propertyIsEnumerable('length'); + }(); + var contains = function contains(list, item) { + var idx = 0; + while (idx < list.length) { + if (list[idx] === item) { + return true; + } + idx += 1; + } + return false; + }; + return typeof Object.keys === 'function' && !hasArgsEnumBug ? _curry1(function keys(obj) { + return Object(obj) !== obj ? [] : Object.keys(obj); + }) : _curry1(function keys(obj) { + if (Object(obj) !== obj) { + return []; + } + var prop, nIdx; + var ks = []; + var checkArgsLength = hasArgsEnumBug && _isArguments(obj); + for (prop in obj) { + if (_has(prop, obj) && (!checkArgsLength || prop !== 'length')) { + ks[ks.length] = prop; + } + } + if (hasEnumBug) { + nIdx = nonEnumerableProps.length - 1; + while (nIdx >= 0) { + prop = nonEnumerableProps[nIdx]; + if (_has(prop, obj) && !contains(ks, prop)) { + ks[ks.length] = prop; + } + nIdx -= 1; + } + } + return ks; + }); + }(); + + /** + * Returns a list containing the names of all the properties of the supplied + * object, including prototype properties. + * Note that the order of the output array is not guaranteed to be consistent + * across different JS platforms. + * + * @func + * @memberOf R + * @since v0.2.0 + * @category Object + * @sig {k: v} -> [k] + * @param {Object} obj The object to extract properties from + * @return {Array} An array of the object's own and prototype properties. + * @example + * + * var F = function() { this.x = 'X'; }; + * F.prototype.y = 'Y'; + * var f = new F(); + * R.keysIn(f); //=> ['x', 'y'] + */ + var keysIn = _curry1(function keysIn(obj) { + var prop; + var ks = []; + for (prop in obj) { + ks[ks.length] = prop; + } + return ks; + }); + + /** + * Returns the number of elements in the array by returning `list.length`. + * + * @func + * @memberOf R + * @since v0.3.0 + * @category List + * @sig [a] -> Number + * @param {Array} list The array to inspect. + * @return {Number} The length of the array. + * @example + * + * R.length([]); //=> 0 + * R.length([1, 2, 3]); //=> 3 + */ + var length = _curry1(function length(list) { + return list != null && _isNumber(list.length) ? list.length : NaN; + }); + + /** + * Returns `true` if the first argument is less than the second; `false` + * otherwise. + * + * @func + * @memberOf R + * @since v0.1.0 + * @category Relation + * @sig Ord a => a -> a -> Boolean + * @param {*} a + * @param {*} b + * @return {Boolean} + * @see R.gt + * @example + * + * R.lt(2, 1); //=> false + * R.lt(2, 2); //=> false + * R.lt(2, 3); //=> true + * R.lt('a', 'z'); //=> true + * R.lt('z', 'a'); //=> false + */ + var lt = _curry2(function lt(a, b) { + return a < b; + }); + + /** + * Returns `true` if the first argument is less than or equal to the second; + * `false` otherwise. + * + * @func + * @memberOf R + * @since v0.1.0 + * @category Relation + * @sig Ord a => a -> a -> Boolean + * @param {Number} a + * @param {Number} b + * @return {Boolean} + * @see R.gte + * @example + * + * R.lte(2, 1); //=> false + * R.lte(2, 2); //=> true + * R.lte(2, 3); //=> true + * R.lte('a', 'z'); //=> true + * R.lte('z', 'a'); //=> false + */ + var lte = _curry2(function lte(a, b) { + return a <= b; + }); + + /** + * The mapAccum function behaves like a combination of map and reduce; it + * applies a function to each element of a list, passing an accumulating + * parameter from left to right, and returning a final value of this + * accumulator together with the new list. + * + * The iterator function receives two arguments, *acc* and *value*, and should + * return a tuple *[acc, value]*. + * + * @func + * @memberOf R + * @since v0.10.0 + * @category List + * @sig (acc -> x -> (acc, y)) -> acc -> [x] -> (acc, [y]) + * @param {Function} fn The function to be called on every element of the input `list`. + * @param {*} acc The accumulator value. + * @param {Array} list The list to iterate over. + * @return {*} The final, accumulated value. + * @see R.addIndex + * @example + * + * var digits = ['1', '2', '3', '4']; + * var appender = (a, b) => [a + b, a + b]; + * + * R.mapAccum(appender, 0, digits); //=> ['01234', ['01', '012', '0123', '01234']] + */ + var mapAccum = _curry3(function mapAccum(fn, acc, list) { + var idx = 0; + var len = list.length; + var result = []; + var tuple = [acc]; + while (idx < len) { + tuple = fn(tuple[0], list[idx]); + result[idx] = tuple[1]; + idx += 1; + } + return [ + tuple[0], + result + ]; + }); + + /** + * The mapAccumRight function behaves like a combination of map and reduce; it + * applies a function to each element of a list, passing an accumulating + * parameter from right to left, and returning a final value of this + * accumulator together with the new list. + * + * Similar to `mapAccum`, except moves through the input list from the right to + * the left. + * + * The iterator function receives two arguments, *acc* and *value*, and should + * return a tuple *[acc, value]*. + * + * @func + * @memberOf R + * @since v0.10.0 + * @category List + * @sig (acc -> x -> (acc, y)) -> acc -> [x] -> (acc, [y]) + * @param {Function} fn The function to be called on every element of the input `list`. + * @param {*} acc The accumulator value. + * @param {Array} list The list to iterate over. + * @return {*} The final, accumulated value. + * @see R.addIndex + * @example + * + * var digits = ['1', '2', '3', '4']; + * var append = (a, b) => [a + b, a + b]; + * + * R.mapAccumRight(append, 0, digits); //=> ['04321', ['04321', '0432', '043', '04']] + */ + var mapAccumRight = _curry3(function mapAccumRight(fn, acc, list) { + var idx = list.length - 1; + var result = []; + var tuple = [acc]; + while (idx >= 0) { + tuple = fn(tuple[0], list[idx]); + result[idx] = tuple[1]; + idx -= 1; + } + return [ + tuple[0], + result + ]; + }); + + /** + * Tests a regular expression against a String. Note that this function will + * return an empty array when there are no matches. This differs from + * [`String.prototype.match`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/match) + * which returns `null` when there are no matches. + * + * @func + * @memberOf R + * @since v0.1.0 + * @category String + * @sig RegExp -> String -> [String | Undefined] + * @param {RegExp} rx A regular expression. + * @param {String} str The string to match against + * @return {Array} The list of matches or empty array. + * @see R.test + * @example + * + * R.match(/([a-z]a)/g, 'bananas'); //=> ['ba', 'na', 'na'] + * R.match(/a/, 'b'); //=> [] + * R.match(/a/, null); //=> TypeError: null does not have a method named "match" + */ + var match = _curry2(function match(rx, str) { + return str.match(rx) || []; + }); + + /** + * mathMod behaves like the modulo operator should mathematically, unlike the + * `%` operator (and by extension, R.modulo). So while "-17 % 5" is -2, + * mathMod(-17, 5) is 3. mathMod requires Integer arguments, and returns NaN + * when the modulus is zero or negative. + * + * @func + * @memberOf R + * @since v0.3.0 + * @category Math + * @sig Number -> Number -> Number + * @param {Number} m The dividend. + * @param {Number} p the modulus. + * @return {Number} The result of `b mod a`. + * @example + * + * R.mathMod(-17, 5); //=> 3 + * R.mathMod(17, 5); //=> 2 + * R.mathMod(17, -5); //=> NaN + * R.mathMod(17, 0); //=> NaN + * R.mathMod(17.2, 5); //=> NaN + * R.mathMod(17, 5.3); //=> NaN + * + * var clock = R.mathMod(R.__, 12); + * clock(15); //=> 3 + * clock(24); //=> 0 + * + * var seventeenMod = R.mathMod(17); + * seventeenMod(3); //=> 2 + * seventeenMod(4); //=> 1 + * seventeenMod(10); //=> 7 + */ + var mathMod = _curry2(function mathMod(m, p) { + if (!_isInteger(m)) { + return NaN; + } + if (!_isInteger(p) || p < 1) { + return NaN; + } + return (m % p + p) % p; + }); + + /** + * Returns the larger of its two arguments. + * + * @func + * @memberOf R + * @since v0.1.0 + * @category Relation + * @sig Ord a => a -> a -> a + * @param {*} a + * @param {*} b + * @return {*} + * @see R.maxBy, R.min + * @example + * + * R.max(789, 123); //=> 789 + * R.max('a', 'b'); //=> 'b' + */ + var max = _curry2(function max(a, b) { + return b > a ? b : a; + }); + + /** + * Takes a function and two values, and returns whichever value produces the + * larger result when passed to the provided function. + * + * @func + * @memberOf R + * @since v0.8.0 + * @category Relation + * @sig Ord b => (a -> b) -> a -> a -> a + * @param {Function} f + * @param {*} a + * @param {*} b + * @return {*} + * @see R.max, R.minBy + * @example + * + * // square :: Number -> Number + * var square = n => n * n; + * + * R.maxBy(square, -3, 2); //=> -3 + * + * R.reduce(R.maxBy(square), 0, [3, -5, 4, 1, -2]); //=> -5 + * R.reduce(R.maxBy(square), 0, []); //=> 0 + */ + var maxBy = _curry3(function maxBy(f, a, b) { + return f(b) > f(a) ? b : a; + }); + + /** + * Create a new object with the own properties of the first object merged with + * the own properties of the second object. If a key exists in both objects, + * the value from the second object will be used. + * + * @func + * @memberOf R + * @since v0.1.0 + * @category Object + * @sig {k: v} -> {k: v} -> {k: v} + * @param {Object} l + * @param {Object} r + * @return {Object} + * @see R.mergeWith, R.mergeWithKey + * @example + * + * R.merge({ 'name': 'fred', 'age': 10 }, { 'age': 40 }); + * //=> { 'name': 'fred', 'age': 40 } + * + * var resetToDefault = R.merge(R.__, {x: 0}); + * resetToDefault({x: 5, y: 2}); //=> {x: 0, y: 2} + */ + var merge = _curry2(function merge(l, r) { + return _assign({}, l, r); + }); + + /** + * Merges a list of objects together into one object. + * + * @func + * @memberOf R + * @since v0.10.0 + * @category List + * @sig [{k: v}] -> {k: v} + * @param {Array} list An array of objects + * @return {Object} A merged object. + * @see R.reduce + * @example + * + * R.mergeAll([{foo:1},{bar:2},{baz:3}]); //=> {foo:1,bar:2,baz:3} + * R.mergeAll([{foo:1},{foo:2},{bar:2}]); //=> {foo:2,bar:2} + */ + var mergeAll = _curry1(function mergeAll(list) { + return _assign.apply(null, [{}].concat(list)); + }); + + /** + * Creates a new object with the own properties of the two provided objects. If + * a key exists in both objects, the provided function is applied to the key + * and the values associated with the key in each object, with the result being + * used as the value associated with the key in the returned object. The key + * will be excluded from the returned object if the resulting value is + * `undefined`. + * + * @func + * @memberOf R + * @since v0.19.0 + * @category Object + * @sig (String -> a -> a -> a) -> {a} -> {a} -> {a} + * @param {Function} fn + * @param {Object} l + * @param {Object} r + * @return {Object} + * @see R.merge, R.mergeWith + * @example + * + * let concatValues = (k, l, r) => k == 'values' ? R.concat(l, r) : r + * R.mergeWithKey(concatValues, + * { a: true, thing: 'foo', values: [10, 20] }, + * { b: true, thing: 'bar', values: [15, 35] }); + * //=> { a: true, b: true, thing: 'bar', values: [10, 20, 15, 35] } + */ + var mergeWithKey = _curry3(function mergeWithKey(fn, l, r) { + var result = {}; + var k; + for (k in l) { + if (_has(k, l)) { + result[k] = _has(k, r) ? fn(k, l[k], r[k]) : l[k]; + } + } + for (k in r) { + if (_has(k, r) && !_has(k, result)) { + result[k] = r[k]; + } + } + return result; + }); + + /** + * Returns the smaller of its two arguments. + * + * @func + * @memberOf R + * @since v0.1.0 + * @category Relation + * @sig Ord a => a -> a -> a + * @param {*} a + * @param {*} b + * @return {*} + * @see R.minBy, R.max + * @example + * + * R.min(789, 123); //=> 123 + * R.min('a', 'b'); //=> 'a' + */ + var min = _curry2(function min(a, b) { + return b < a ? b : a; + }); + + /** + * Takes a function and two values, and returns whichever value produces the + * smaller result when passed to the provided function. + * + * @func + * @memberOf R + * @since v0.8.0 + * @category Relation + * @sig Ord b => (a -> b) -> a -> a -> a + * @param {Function} f + * @param {*} a + * @param {*} b + * @return {*} + * @see R.min, R.maxBy + * @example + * + * // square :: Number -> Number + * var square = n => n * n; + * + * R.minBy(square, -3, 2); //=> 2 + * + * R.reduce(R.minBy(square), Infinity, [3, -5, 4, 1, -2]); //=> 1 + * R.reduce(R.minBy(square), Infinity, []); //=> Infinity + */ + var minBy = _curry3(function minBy(f, a, b) { + return f(b) < f(a) ? b : a; + }); + + /** + * Divides the first parameter by the second and returns the remainder. Note + * that this function preserves the JavaScript-style behavior for modulo. For + * mathematical modulo see `mathMod`. + * + * @func + * @memberOf R + * @since v0.1.1 + * @category Math + * @sig Number -> Number -> Number + * @param {Number} a The value to the divide. + * @param {Number} b The pseudo-modulus + * @return {Number} The result of `b % a`. + * @see R.mathMod + * @example + * + * R.modulo(17, 3); //=> 2 + * // JS behavior: + * R.modulo(-17, 3); //=> -2 + * R.modulo(17, -3); //=> 2 + * + * var isOdd = R.modulo(R.__, 2); + * isOdd(42); //=> 0 + * isOdd(21); //=> 1 + */ + var modulo = _curry2(function modulo(a, b) { + return a % b; + }); + + /** + * Multiplies two numbers. Equivalent to `a * b` but curried. + * + * @func + * @memberOf R + * @since v0.1.0 + * @category Math + * @sig Number -> Number -> Number + * @param {Number} a The first value. + * @param {Number} b The second value. + * @return {Number} The result of `a * b`. + * @see R.divide + * @example + * + * var double = R.multiply(2); + * var triple = R.multiply(3); + * double(3); //=> 6 + * triple(4); //=> 12 + * R.multiply(2, 5); //=> 10 + */ + var multiply = _curry2(function multiply(a, b) { + return a * b; + }); + + /** + * Wraps a function of any arity (including nullary) in a function that accepts + * exactly `n` parameters. Any extraneous parameters will not be passed to the + * supplied function. + * + * @func + * @memberOf R + * @since v0.1.0 + * @category Function + * @sig Number -> (* -> a) -> (* -> a) + * @param {Number} n The desired arity of the new function. + * @param {Function} fn The function to wrap. + * @return {Function} A new function wrapping `fn`. The new function is guaranteed to be of + * arity `n`. + * @example + * + * var takesTwoArgs = (a, b) => [a, b]; + * + * takesTwoArgs.length; //=> 2 + * takesTwoArgs(1, 2); //=> [1, 2] + * + * var takesOneArg = R.nAry(1, takesTwoArgs); + * takesOneArg.length; //=> 1 + * // Only `n` arguments are passed to the wrapped function + * takesOneArg(1, 2); //=> [1, undefined] + */ + var nAry = _curry2(function nAry(n, fn) { + switch (n) { + case 0: + return function () { + return fn.call(this); + }; + case 1: + return function (a0) { + return fn.call(this, a0); + }; + case 2: + return function (a0, a1) { + return fn.call(this, a0, a1); + }; + case 3: + return function (a0, a1, a2) { + return fn.call(this, a0, a1, a2); + }; + case 4: + return function (a0, a1, a2, a3) { + return fn.call(this, a0, a1, a2, a3); + }; + case 5: + return function (a0, a1, a2, a3, a4) { + return fn.call(this, a0, a1, a2, a3, a4); + }; + case 6: + return function (a0, a1, a2, a3, a4, a5) { + return fn.call(this, a0, a1, a2, a3, a4, a5); + }; + case 7: + return function (a0, a1, a2, a3, a4, a5, a6) { + return fn.call(this, a0, a1, a2, a3, a4, a5, a6); + }; + case 8: + return function (a0, a1, a2, a3, a4, a5, a6, a7) { + return fn.call(this, a0, a1, a2, a3, a4, a5, a6, a7); + }; + case 9: + return function (a0, a1, a2, a3, a4, a5, a6, a7, a8) { + return fn.call(this, a0, a1, a2, a3, a4, a5, a6, a7, a8); + }; + case 10: + return function (a0, a1, a2, a3, a4, a5, a6, a7, a8, a9) { + return fn.call(this, a0, a1, a2, a3, a4, a5, a6, a7, a8, a9); + }; + default: + throw new Error('First argument to nAry must be a non-negative integer no greater than ten'); + } + }); + + /** + * Negates its argument. + * + * @func + * @memberOf R + * @since v0.9.0 + * @category Math + * @sig Number -> Number + * @param {Number} n + * @return {Number} + * @example + * + * R.negate(42); //=> -42 + */ + var negate = _curry1(function negate(n) { + return -n; + }); + + /** + * Returns `true` if no elements of the list match the predicate, `false` + * otherwise. + * + * Dispatches to the `any` method of the second argument, if present. + * + * @func + * @memberOf R + * @since v0.12.0 + * @category List + * @sig (a -> Boolean) -> [a] -> Boolean + * @param {Function} fn The predicate function. + * @param {Array} list The array to consider. + * @return {Boolean} `true` if the predicate is not satisfied by every element, `false` otherwise. + * @see R.all, R.any + * @example + * + * var isEven = n => n % 2 === 0; + * + * R.none(isEven, [1, 3, 5, 7, 9, 11]); //=> true + * R.none(isEven, [1, 3, 5, 7, 8, 11]); //=> false + */ + var none = _curry2(_complement(_dispatchable('any', _xany, any))); + + /** + * A function that returns the `!` of its argument. It will return `true` when + * passed false-y value, and `false` when passed a truth-y one. + * + * @func + * @memberOf R + * @since v0.1.0 + * @category Logic + * @sig * -> Boolean + * @param {*} a any value + * @return {Boolean} the logical inverse of passed argument. + * @see R.complement + * @example + * + * R.not(true); //=> false + * R.not(false); //=> true + * R.not(0); //=> true + * R.not(1); //=> false + */ + var not = _curry1(function not(a) { + return !a; + }); + + /** + * Returns the nth element of the given list or string. If n is negative the + * element at index length + n is returned. + * + * @func + * @memberOf R + * @since v0.1.0 + * @category List + * @sig Number -> [a] -> a | Undefined + * @sig Number -> String -> String + * @param {Number} offset + * @param {*} list + * @return {*} + * @example + * + * var list = ['foo', 'bar', 'baz', 'quux']; + * R.nth(1, list); //=> 'bar' + * R.nth(-1, list); //=> 'quux' + * R.nth(-99, list); //=> undefined + * + * R.nth(2, 'abc'); //=> 'c' + * R.nth(3, 'abc'); //=> '' + */ + var nth = _curry2(function nth(offset, list) { + var idx = offset < 0 ? list.length + offset : offset; + return _isString(list) ? list.charAt(idx) : list[idx]; + }); + + /** + * Returns a function which returns its nth argument. + * + * @func + * @memberOf R + * @since v0.9.0 + * @category Function + * @sig Number -> *... -> * + * @param {Number} n + * @return {Function} + * @example + * + * R.nthArg(1)('a', 'b', 'c'); //=> 'b' + * R.nthArg(-1)('a', 'b', 'c'); //=> 'c' + */ + var nthArg = _curry1(function nthArg(n) { + var arity = n < 0 ? 1 : n + 1; + return curryN(arity, function () { + return nth(n, arguments); + }); + }); + + /** + * Creates an object containing a single key:value pair. + * + * @func + * @memberOf R + * @since v0.18.0 + * @category Object + * @sig String -> a -> {String:a} + * @param {String} key + * @param {*} val + * @return {Object} + * @see R.pair + * @example + * + * var matchPhrases = R.compose( + * R.objOf('must'), + * R.map(R.objOf('match_phrase')) + * ); + * matchPhrases(['foo', 'bar', 'baz']); //=> {must: [{match_phrase: 'foo'}, {match_phrase: 'bar'}, {match_phrase: 'baz'}]} + */ + var objOf = _curry2(function objOf(key, val) { + var obj = {}; + obj[key] = val; + return obj; + }); + + /** + * Returns a singleton array containing the value provided. + * + * Note this `of` is different from the ES6 `of`; See + * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/of + * + * @func + * @memberOf R + * @since v0.3.0 + * @category Function + * @sig a -> [a] + * @param {*} x any value + * @return {Array} An array wrapping `x`. + * @example + * + * R.of(null); //=> [null] + * R.of([42]); //=> [[42]] + */ + var of = _curry1(_of); + + /** + * Accepts a function `fn` and returns a function that guards invocation of + * `fn` such that `fn` can only ever be called once, no matter how many times + * the returned function is invoked. The first value calculated is returned in + * subsequent invocations. + * + * @func + * @memberOf R + * @since v0.1.0 + * @category Function + * @sig (a... -> b) -> (a... -> b) + * @param {Function} fn The function to wrap in a call-only-once wrapper. + * @return {Function} The wrapped function. + * @example + * + * var addOneOnce = R.once(x => x + 1); + * addOneOnce(10); //=> 11 + * addOneOnce(addOneOnce(50)); //=> 11 + */ + var once = _curry1(function once(fn) { + var called = false; + var result; + return _arity(fn.length, function () { + if (called) { + return result; + } + called = true; + result = fn.apply(this, arguments); + return result; + }); + }); + + /** + * Returns `true` if one or both of its arguments are `true`. Returns `false` + * if both arguments are `false`. + * + * @func + * @memberOf R + * @since v0.1.0 + * @category Logic + * @sig * -> * -> * + * @param {Boolean} a A boolean value + * @param {Boolean} b A boolean value + * @return {Boolean} `true` if one or both arguments are `true`, `false` otherwise + * @see R.either + * @example + * + * R.or(true, true); //=> true + * R.or(true, false); //=> true + * R.or(false, true); //=> true + * R.or(false, false); //=> false + */ + var or = _curry2(function or(a, b) { + return a || b; + }); + + /** + * Returns the result of "setting" the portion of the given data structure + * focused by the given lens to the result of applying the given function to + * the focused value. + * + * @func + * @memberOf R + * @since v0.16.0 + * @category Object + * @typedefn Lens s a = Functor f => (a -> f a) -> s -> f s + * @sig Lens s a -> (a -> a) -> s -> s + * @param {Lens} lens + * @param {*} v + * @param {*} x + * @return {*} + * @see R.prop, R.lensIndex, R.lensProp + * @example + * + * var headLens = R.lensIndex(0); + * + * R.over(headLens, R.toUpper, ['foo', 'bar', 'baz']); //=> ['FOO', 'bar', 'baz'] + */ + // `Identity` is a functor that holds a single value, where `map` simply + // transforms the held value with the provided function. + // The value returned by the getter function is first transformed with `f`, + // then set as the value of an `Identity`. This is then mapped over with the + // setter function of the lens. + var over = function () { + // `Identity` is a functor that holds a single value, where `map` simply + // transforms the held value with the provided function. + var Identity = function (x) { + return { + value: x, + map: function (f) { + return Identity(f(x)); + } + }; + }; + return _curry3(function over(lens, f, x) { + // The value returned by the getter function is first transformed with `f`, + // then set as the value of an `Identity`. This is then mapped over with the + // setter function of the lens. + return lens(function (y) { + return Identity(f(y)); + })(x).value; + }); + }(); + + /** + * Takes two arguments, `fst` and `snd`, and returns `[fst, snd]`. + * + * @func + * @memberOf R + * @since v0.18.0 + * @category List + * @sig a -> b -> (a,b) + * @param {*} fst + * @param {*} snd + * @return {Array} + * @see R.objOf, R.of + * @example + * + * R.pair('foo', 'bar'); //=> ['foo', 'bar'] + */ + var pair = _curry2(function pair(fst, snd) { + return [ + fst, + snd + ]; + }); + + /** + * Retrieve the value at a given path. + * + * @func + * @memberOf R + * @since v0.2.0 + * @category Object + * @sig [String] -> {k: v} -> v | Undefined + * @param {Array} path The path to use. + * @param {Object} obj The object to retrieve the nested property from. + * @return {*} The data at `path`. + * @see R.prop + * @example + * + * R.path(['a', 'b'], {a: {b: 2}}); //=> 2 + * R.path(['a', 'b'], {c: {b: 2}}); //=> undefined + */ + var path = _curry2(function path(paths, obj) { + var val = obj; + var idx = 0; + while (idx < paths.length) { + if (val == null) { + return; + } + val = val[paths[idx]]; + idx += 1; + } + return val; + }); + + /** + * If the given, non-null object has a value at the given path, returns the + * value at that path. Otherwise returns the provided default value. + * + * @func + * @memberOf R + * @since v0.18.0 + * @category Object + * @sig a -> [String] -> Object -> a + * @param {*} d The default value. + * @param {Array} p The path to use. + * @param {Object} obj The object to retrieve the nested property from. + * @return {*} The data at `path` of the supplied object or the default value. + * @example + * + * R.pathOr('N/A', ['a', 'b'], {a: {b: 2}}); //=> 2 + * R.pathOr('N/A', ['a', 'b'], {c: {b: 2}}); //=> "N/A" + */ + var pathOr = _curry3(function pathOr(d, p, obj) { + return defaultTo(d, path(p, obj)); + }); + + /** + * Returns `true` if the specified object property at given path satisfies the + * given predicate; `false` otherwise. + * + * @func + * @memberOf R + * @since v0.19.0 + * @category Logic + * @sig (a -> Boolean) -> [String] -> Object -> Boolean + * @param {Function} pred + * @param {Array} propPath + * @param {*} obj + * @return {Boolean} + * @see R.propSatisfies, R.path + * @example + * + * R.pathSatisfies(y => y > 0, ['x', 'y'], {x: {y: 2}}); //=> true + */ + var pathSatisfies = _curry3(function pathSatisfies(pred, propPath, obj) { + return propPath.length > 0 && pred(path(propPath, obj)); + }); + + /** + * Returns a partial copy of an object containing only the keys specified. If + * the key does not exist, the property is ignored. + * + * @func + * @memberOf R + * @since v0.1.0 + * @category Object + * @sig [k] -> {k: v} -> {k: v} + * @param {Array} names an array of String property names to copy onto a new object + * @param {Object} obj The object to copy from + * @return {Object} A new object with only properties from `names` on it. + * @see R.omit, R.props + * @example + * + * R.pick(['a', 'd'], {a: 1, b: 2, c: 3, d: 4}); //=> {a: 1, d: 4} + * R.pick(['a', 'e', 'f'], {a: 1, b: 2, c: 3, d: 4}); //=> {a: 1} + */ + var pick = _curry2(function pick(names, obj) { + var result = {}; + var idx = 0; + while (idx < names.length) { + if (names[idx] in obj) { + result[names[idx]] = obj[names[idx]]; + } + idx += 1; + } + return result; + }); + + /** + * Similar to `pick` except that this one includes a `key: undefined` pair for + * properties that don't exist. + * + * @func + * @memberOf R + * @since v0.1.0 + * @category Object + * @sig [k] -> {k: v} -> {k: v} + * @param {Array} names an array of String property names to copy onto a new object + * @param {Object} obj The object to copy from + * @return {Object} A new object with only properties from `names` on it. + * @see R.pick + * @example + * + * R.pickAll(['a', 'd'], {a: 1, b: 2, c: 3, d: 4}); //=> {a: 1, d: 4} + * R.pickAll(['a', 'e', 'f'], {a: 1, b: 2, c: 3, d: 4}); //=> {a: 1, e: undefined, f: undefined} + */ + var pickAll = _curry2(function pickAll(names, obj) { + var result = {}; + var idx = 0; + var len = names.length; + while (idx < len) { + var name = names[idx]; + result[name] = obj[name]; + idx += 1; + } + return result; + }); + + /** + * Returns a partial copy of an object containing only the keys that satisfy + * the supplied predicate. + * + * @func + * @memberOf R + * @since v0.8.0 + * @category Object + * @sig (v, k -> Boolean) -> {k: v} -> {k: v} + * @param {Function} pred A predicate to determine whether or not a key + * should be included on the output object. + * @param {Object} obj The object to copy from + * @return {Object} A new object with only properties that satisfy `pred` + * on it. + * @see R.pick, R.filter + * @example + * + * var isUpperCase = (val, key) => key.toUpperCase() === key; + * R.pickBy(isUpperCase, {a: 1, b: 2, A: 3, B: 4}); //=> {A: 3, B: 4} + */ + var pickBy = _curry2(function pickBy(test, obj) { + var result = {}; + for (var prop in obj) { + if (test(obj[prop], prop, obj)) { + result[prop] = obj[prop]; + } + } + return result; + }); + + /** + * Returns a new list with the given element at the front, followed by the + * contents of the list. + * + * @func + * @memberOf R + * @since v0.1.0 + * @category List + * @sig a -> [a] -> [a] + * @param {*} el The item to add to the head of the output list. + * @param {Array} list The array to add to the tail of the output list. + * @return {Array} A new array. + * @see R.append + * @example + * + * R.prepend('fee', ['fi', 'fo', 'fum']); //=> ['fee', 'fi', 'fo', 'fum'] + */ + var prepend = _curry2(function prepend(el, list) { + return _concat([el], list); + }); + + /** + * Returns a function that when supplied an object returns the indicated + * property of that object, if it exists. + * + * @func + * @memberOf R + * @since v0.1.0 + * @category Object + * @sig s -> {s: a} -> a | Undefined + * @param {String} p The property name + * @param {Object} obj The object to query + * @return {*} The value at `obj.p`. + * @see R.path + * @example + * + * R.prop('x', {x: 100}); //=> 100 + * R.prop('x', {}); //=> undefined + */ + var prop = _curry2(function prop(p, obj) { + return obj[p]; + }); + + /** + * Returns `true` if the specified object property is of the given type; + * `false` otherwise. + * + * @func + * @memberOf R + * @since v0.16.0 + * @category Type + * @sig Type -> String -> Object -> Boolean + * @param {Function} type + * @param {String} name + * @param {*} obj + * @return {Boolean} + * @see R.is, R.propSatisfies + * @example + * + * R.propIs(Number, 'x', {x: 1, y: 2}); //=> true + * R.propIs(Number, 'x', {x: 'foo'}); //=> false + * R.propIs(Number, 'x', {}); //=> false + */ + var propIs = _curry3(function propIs(type, name, obj) { + return is(type, obj[name]); + }); + + /** + * If the given, non-null object has an own property with the specified name, + * returns the value of that property. Otherwise returns the provided default + * value. + * + * @func + * @memberOf R + * @since v0.6.0 + * @category Object + * @sig a -> String -> Object -> a + * @param {*} val The default value. + * @param {String} p The name of the property to return. + * @param {Object} obj The object to query. + * @return {*} The value of given property of the supplied object or the default value. + * @example + * + * var alice = { + * name: 'ALICE', + * age: 101 + * }; + * var favorite = R.prop('favoriteLibrary'); + * var favoriteWithDefault = R.propOr('Ramda', 'favoriteLibrary'); + * + * favorite(alice); //=> undefined + * favoriteWithDefault(alice); //=> 'Ramda' + */ + var propOr = _curry3(function propOr(val, p, obj) { + return obj != null && _has(p, obj) ? obj[p] : val; + }); + + /** + * Returns `true` if the specified object property satisfies the given + * predicate; `false` otherwise. + * + * @func + * @memberOf R + * @since v0.16.0 + * @category Logic + * @sig (a -> Boolean) -> String -> {String: a} -> Boolean + * @param {Function} pred + * @param {String} name + * @param {*} obj + * @return {Boolean} + * @see R.propEq, R.propIs + * @example + * + * R.propSatisfies(x => x > 0, 'x', {x: 1, y: 2}); //=> true + */ + var propSatisfies = _curry3(function propSatisfies(pred, name, obj) { + return pred(obj[name]); + }); + + /** + * Acts as multiple `prop`: array of keys in, array of values out. Preserves + * order. + * + * @func + * @memberOf R + * @since v0.1.0 + * @category Object + * @sig [k] -> {k: v} -> [v] + * @param {Array} ps The property names to fetch + * @param {Object} obj The object to query + * @return {Array} The corresponding values or partially applied function. + * @example + * + * R.props(['x', 'y'], {x: 1, y: 2}); //=> [1, 2] + * R.props(['c', 'a', 'b'], {b: 2, a: 1}); //=> [undefined, 1, 2] + * + * var fullName = R.compose(R.join(' '), R.props(['first', 'last'])); + * fullName({last: 'Bullet-Tooth', age: 33, first: 'Tony'}); //=> 'Tony Bullet-Tooth' + */ + var props = _curry2(function props(ps, obj) { + var len = ps.length; + var out = []; + var idx = 0; + while (idx < len) { + out[idx] = obj[ps[idx]]; + idx += 1; + } + return out; + }); + + /** + * Returns a list of numbers from `from` (inclusive) to `to` (exclusive). + * + * @func + * @memberOf R + * @since v0.1.0 + * @category List + * @sig Number -> Number -> [Number] + * @param {Number} from The first number in the list. + * @param {Number} to One more than the last number in the list. + * @return {Array} The list of numbers in tthe set `[a, b)`. + * @example + * + * R.range(1, 5); //=> [1, 2, 3, 4] + * R.range(50, 53); //=> [50, 51, 52] + */ + var range = _curry2(function range(from, to) { + if (!(_isNumber(from) && _isNumber(to))) { + throw new TypeError('Both arguments to range must be numbers'); + } + var result = []; + var n = from; + while (n < to) { + result.push(n); + n += 1; + } + return result; + }); + + /** + * Returns a single item by iterating through the list, successively calling + * the iterator function and passing it an accumulator value and the current + * value from the array, and then passing the result to the next call. + * + * Similar to `reduce`, except moves through the input list from the right to + * the left. + * + * The iterator function receives two values: *(acc, value)* + * + * Note: `R.reduceRight` does not skip deleted or unassigned indices (sparse + * arrays), unlike the native `Array.prototype.reduce` method. For more details + * on this behavior, see: + * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduceRight#Description + * + * @func + * @memberOf R + * @since v0.1.0 + * @category List + * @sig (a,b -> a) -> a -> [b] -> a + * @param {Function} fn The iterator function. Receives two values, the accumulator and the + * current element from the array. + * @param {*} acc The accumulator value. + * @param {Array} list The list to iterate over. + * @return {*} The final, accumulated value. + * @see R.addIndex + * @example + * + * var pairs = [ ['a', 1], ['b', 2], ['c', 3] ]; + * var flattenPairs = (acc, pair) => acc.concat(pair); + * + * R.reduceRight(flattenPairs, [], pairs); //=> [ 'c', 3, 'b', 2, 'a', 1 ] + */ + var reduceRight = _curry3(function reduceRight(fn, acc, list) { + var idx = list.length - 1; + while (idx >= 0) { + acc = fn(acc, list[idx]); + idx -= 1; + } + return acc; + }); + + /** + * Returns a value wrapped to indicate that it is the final value of the reduce + * and transduce functions. The returned value should be considered a black + * box: the internal structure is not guaranteed to be stable. + * + * Note: this optimization is unavailable to functions not explicitly listed + * above. For instance, it is not currently supported by reduceRight. + * + * @func + * @memberOf R + * @since v0.15.0 + * @category List + * @sig a -> * + * @param {*} x The final value of the reduce. + * @return {*} The wrapped value. + * @see R.reduce, R.transduce + * @example + * + * R.reduce( + * R.pipe(R.add, R.when(R.gte(R.__, 10), R.reduced)), + * 0, + * [1, 2, 3, 4, 5]) // 10 + */ + var reduced = _curry1(_reduced); + + /** + * Removes the sub-list of `list` starting at index `start` and containing + * `count` elements. _Note that this is not destructive_: it returns a copy of + * the list with the changes. + * No lists have been harmed in the application of this function. + * + * @func + * @memberOf R + * @since v0.2.2 + * @category List + * @sig Number -> Number -> [a] -> [a] + * @param {Number} start The position to start removing elements + * @param {Number} count The number of elements to remove + * @param {Array} list The list to remove from + * @return {Array} A new Array with `count` elements from `start` removed. + * @example + * + * R.remove(2, 3, [1,2,3,4,5,6,7,8]); //=> [1,2,6,7,8] + */ + var remove = _curry3(function remove(start, count, list) { + return _concat(_slice(list, 0, Math.min(start, list.length)), _slice(list, Math.min(list.length, start + count))); + }); + + /** + * Replace a substring or regex match in a string with a replacement. + * + * @func + * @memberOf R + * @since v0.7.0 + * @category String + * @sig RegExp|String -> String -> String -> String + * @param {RegExp|String} pattern A regular expression or a substring to match. + * @param {String} replacement The string to replace the matches with. + * @param {String} str The String to do the search and replacement in. + * @return {String} The result. + * @example + * + * R.replace('foo', 'bar', 'foo foo foo'); //=> 'bar foo foo' + * R.replace(/foo/, 'bar', 'foo foo foo'); //=> 'bar foo foo' + * + * // Use the "g" (global) flag to replace all occurrences: + * R.replace(/foo/g, 'bar', 'foo foo foo'); //=> 'bar bar bar' + */ + var replace = _curry3(function replace(regex, replacement, str) { + return str.replace(regex, replacement); + }); + + /** + * Returns a new list or string with the elements or characters in reverse + * order. + * + * @func + * @memberOf R + * @since v0.1.0 + * @category List + * @sig [a] -> [a] + * @sig String -> String + * @param {Array|String} list + * @return {Array|String} + * @example + * + * R.reverse([1, 2, 3]); //=> [3, 2, 1] + * R.reverse([1, 2]); //=> [2, 1] + * R.reverse([1]); //=> [1] + * R.reverse([]); //=> [] + * + * R.reverse('abc'); //=> 'cba' + * R.reverse('ab'); //=> 'ba' + * R.reverse('a'); //=> 'a' + * R.reverse(''); //=> '' + */ + var reverse = _curry1(function reverse(list) { + return _isString(list) ? list.split('').reverse().join('') : _slice(list).reverse(); + }); + + /** + * Scan is similar to reduce, but returns a list of successively reduced values + * from the left + * + * @func + * @memberOf R + * @since v0.10.0 + * @category List + * @sig (a,b -> a) -> a -> [b] -> [a] + * @param {Function} fn The iterator function. Receives two values, the accumulator and the + * current element from the array + * @param {*} acc The accumulator value. + * @param {Array} list The list to iterate over. + * @return {Array} A list of all intermediately reduced values. + * @example + * + * var numbers = [1, 2, 3, 4]; + * var factorials = R.scan(R.multiply, 1, numbers); //=> [1, 1, 2, 6, 24] + */ + var scan = _curry3(function scan(fn, acc, list) { + var idx = 0; + var len = list.length; + var result = [acc]; + while (idx < len) { + acc = fn(acc, list[idx]); + result[idx + 1] = acc; + idx += 1; + } + return result; + }); + + /** + * Returns the result of "setting" the portion of the given data structure + * focused by the given lens to the given value. + * + * @func + * @memberOf R + * @since v0.16.0 + * @category Object + * @typedefn Lens s a = Functor f => (a -> f a) -> s -> f s + * @sig Lens s a -> a -> s -> s + * @param {Lens} lens + * @param {*} v + * @param {*} x + * @return {*} + * @see R.prop, R.lensIndex, R.lensProp + * @example + * + * var xLens = R.lensProp('x'); + * + * R.set(xLens, 4, {x: 1, y: 2}); //=> {x: 4, y: 2} + * R.set(xLens, 8, {x: 1, y: 2}); //=> {x: 8, y: 2} + */ + var set = _curry3(function set(lens, v, x) { + return over(lens, always(v), x); + }); + + /** + * Returns the elements of the given list or string (or object with a `slice` + * method) from `fromIndex` (inclusive) to `toIndex` (exclusive). + * + * Dispatches to the `slice` method of the third argument, if present. + * + * @func + * @memberOf R + * @since v0.1.4 + * @category List + * @sig Number -> Number -> [a] -> [a] + * @sig Number -> Number -> String -> String + * @param {Number} fromIndex The start index (inclusive). + * @param {Number} toIndex The end index (exclusive). + * @param {*} list + * @return {*} + * @example + * + * R.slice(1, 3, ['a', 'b', 'c', 'd']); //=> ['b', 'c'] + * R.slice(1, Infinity, ['a', 'b', 'c', 'd']); //=> ['b', 'c', 'd'] + * R.slice(0, -1, ['a', 'b', 'c', 'd']); //=> ['a', 'b', 'c'] + * R.slice(-3, -1, ['a', 'b', 'c', 'd']); //=> ['b', 'c'] + * R.slice(0, 3, 'ramda'); //=> 'ram' + */ + var slice = _curry3(_checkForMethod('slice', function slice(fromIndex, toIndex, list) { + return Array.prototype.slice.call(list, fromIndex, toIndex); + })); + + /** + * Returns a copy of the list, sorted according to the comparator function, + * which should accept two values at a time and return a negative number if the + * first value is smaller, a positive number if it's larger, and zero if they + * are equal. Please note that this is a **copy** of the list. It does not + * modify the original. + * + * @func + * @memberOf R + * @since v0.1.0 + * @category List + * @sig (a,a -> Number) -> [a] -> [a] + * @param {Function} comparator A sorting function :: a -> b -> Int + * @param {Array} list The list to sort + * @return {Array} a new array with its elements sorted by the comparator function. + * @example + * + * var diff = function(a, b) { return a - b; }; + * R.sort(diff, [4,2,7,5]); //=> [2, 4, 5, 7] + */ + var sort = _curry2(function sort(comparator, list) { + return _slice(list).sort(comparator); + }); + + /** + * Sorts the list according to the supplied function. + * + * @func + * @memberOf R + * @since v0.1.0 + * @category Relation + * @sig Ord b => (a -> b) -> [a] -> [a] + * @param {Function} fn + * @param {Array} list The list to sort. + * @return {Array} A new list sorted by the keys generated by `fn`. + * @example + * + * var sortByFirstItem = R.sortBy(R.prop(0)); + * var sortByNameCaseInsensitive = R.sortBy(R.compose(R.toLower, R.prop('name'))); + * var pairs = [[-1, 1], [-2, 2], [-3, 3]]; + * sortByFirstItem(pairs); //=> [[-3, 3], [-2, 2], [-1, 1]] + * var alice = { + * name: 'ALICE', + * age: 101 + * }; + * var bob = { + * name: 'Bob', + * age: -10 + * }; + * var clara = { + * name: 'clara', + * age: 314.159 + * }; + * var people = [clara, bob, alice]; + * sortByNameCaseInsensitive(people); //=> [alice, bob, clara] + */ + var sortBy = _curry2(function sortBy(fn, list) { + return _slice(list).sort(function (a, b) { + var aa = fn(a); + var bb = fn(b); + return aa < bb ? -1 : aa > bb ? 1 : 0; + }); + }); + + /** + * Splits a given list or string at a given index. + * + * @func + * @memberOf R + * @since v0.19.0 + * @category List + * @sig Number -> [a] -> [[a], [a]] + * @sig Number -> String -> [String, String] + * @param {Number} index The index where the array/string is split. + * @param {Array|String} array The array/string to be split. + * @return {Array} + * @example + * + * R.splitAt(1, [1, 2, 3]); //=> [[1], [2, 3]] + * R.splitAt(5, 'hello world'); //=> ['hello', ' world'] + * R.splitAt(-1, 'foobar'); //=> ['fooba', 'r'] + */ + var splitAt = _curry2(function splitAt(index, array) { + return [ + slice(0, index, array), + slice(index, length(array), array) + ]; + }); + + /** + * Splits a collection into slices of the specified length. + * + * @func + * @memberOf R + * @since v0.16.0 + * @category List + * @sig Number -> [a] -> [[a]] + * @sig Number -> String -> [String] + * @param {Number} n + * @param {Array} list + * @return {Array} + * @example + * + * R.splitEvery(3, [1, 2, 3, 4, 5, 6, 7]); //=> [[1, 2, 3], [4, 5, 6], [7]] + * R.splitEvery(3, 'foobarbaz'); //=> ['foo', 'bar', 'baz'] + */ + var splitEvery = _curry2(function splitEvery(n, list) { + if (n <= 0) { + throw new Error('First argument to splitEvery must be a positive integer'); + } + var result = []; + var idx = 0; + while (idx < list.length) { + result.push(slice(idx, idx += n, list)); + } + return result; + }); + + /** + * Takes a list and a predicate and returns a pair of lists with the following properties: + * + * - the result of concatenating the two output lists is equivalent to the input list; + * - none of the elements of the first output list satisfies the predicate; and + * - if the second output list is non-empty, its first element satisfies the predicate. + * + * @func + * @memberOf R + * @since v0.19.0 + * @category List + * @sig (a -> Boolean) -> [a] -> [[a], [a]] + * @param {Function} pred The predicate that determines where the array is split. + * @param {Array} list The array to be split. + * @return {Array} + * @example + * + * R.splitWhen(R.equals(2), [1, 2, 3, 1, 2, 3]); //=> [[1], [2, 3, 1, 2, 3]] + */ + var splitWhen = _curry2(function splitWhen(pred, list) { + var idx = 0; + var len = list.length; + var prefix = []; + while (idx < len && !pred(list[idx])) { + prefix.push(list[idx]); + idx += 1; + } + return [ + prefix, + _slice(list, idx) + ]; + }); + + /** + * Subtracts its second argument from its first argument. + * + * @func + * @memberOf R + * @since v0.1.0 + * @category Math + * @sig Number -> Number -> Number + * @param {Number} a The first value. + * @param {Number} b The second value. + * @return {Number} The result of `a - b`. + * @see R.add + * @example + * + * R.subtract(10, 8); //=> 2 + * + * var minus5 = R.subtract(R.__, 5); + * minus5(17); //=> 12 + * + * var complementaryAngle = R.subtract(90); + * complementaryAngle(30); //=> 60 + * complementaryAngle(72); //=> 18 + */ + var subtract = _curry2(function subtract(a, b) { + return Number(a) - Number(b); + }); + + /** + * Returns all but the first element of the given list or string (or object + * with a `tail` method). + * + * Dispatches to the `slice` method of the first argument, if present. + * + * @func + * @memberOf R + * @since v0.1.0 + * @category List + * @sig [a] -> [a] + * @sig String -> String + * @param {*} list + * @return {*} + * @see R.head, R.init, R.last + * @example + * + * R.tail([1, 2, 3]); //=> [2, 3] + * R.tail([1, 2]); //=> [2] + * R.tail([1]); //=> [] + * R.tail([]); //=> [] + * + * R.tail('abc'); //=> 'bc' + * R.tail('ab'); //=> 'b' + * R.tail('a'); //=> '' + * R.tail(''); //=> '' + */ + var tail = _checkForMethod('tail', slice(1, Infinity)); + + /** + * Returns the first `n` elements of the given list, string, or + * transducer/transformer (or object with a `take` method). + * + * Dispatches to the `take` method of the second argument, if present. + * + * @func + * @memberOf R + * @since v0.1.0 + * @category List + * @sig Number -> [a] -> [a] + * @sig Number -> String -> String + * @param {Number} n + * @param {*} list + * @return {*} + * @see R.drop + * @example + * + * R.take(1, ['foo', 'bar', 'baz']); //=> ['foo'] + * R.take(2, ['foo', 'bar', 'baz']); //=> ['foo', 'bar'] + * R.take(3, ['foo', 'bar', 'baz']); //=> ['foo', 'bar', 'baz'] + * R.take(4, ['foo', 'bar', 'baz']); //=> ['foo', 'bar', 'baz'] + * R.take(3, 'ramda'); //=> 'ram' + * + * var personnel = [ + * 'Dave Brubeck', + * 'Paul Desmond', + * 'Eugene Wright', + * 'Joe Morello', + * 'Gerry Mulligan', + * 'Bob Bates', + * 'Joe Dodge', + * 'Ron Crotty' + * ]; + * + * var takeFive = R.take(5); + * takeFive(personnel); + * //=> ['Dave Brubeck', 'Paul Desmond', 'Eugene Wright', 'Joe Morello', 'Gerry Mulligan'] + */ + var take = _curry2(_dispatchable('take', _xtake, function take(n, xs) { + return slice(0, n < 0 ? Infinity : n, xs); + })); + + /** + * Returns a new list containing the last `n` elements of a given list, passing + * each value to the supplied predicate function, and terminating when the + * predicate function returns `false`. Excludes the element that caused the + * predicate function to fail. The predicate function is passed one argument: + * *(value)*. + * + * @func + * @memberOf R + * @since v0.16.0 + * @category List + * @sig (a -> Boolean) -> [a] -> [a] + * @param {Function} fn The function called per iteration. + * @param {Array} list The collection to iterate over. + * @return {Array} A new array. + * @see R.dropLastWhile, R.addIndex + * @example + * + * var isNotOne = x => x !== 1; + * + * R.takeLastWhile(isNotOne, [1, 2, 3, 4]); //=> [2, 3, 4] + */ + var takeLastWhile = _curry2(function takeLastWhile(fn, list) { + var idx = list.length - 1; + while (idx >= 0 && fn(list[idx])) { + idx -= 1; + } + return _slice(list, idx + 1, Infinity); + }); + + /** + * Returns a new list containing the first `n` elements of a given list, + * passing each value to the supplied predicate function, and terminating when + * the predicate function returns `false`. Excludes the element that caused the + * predicate function to fail. The predicate function is passed one argument: + * *(value)*. + * + * Dispatches to the `takeWhile` method of the second argument, if present. + * + * Acts as a transducer if a transformer is given in list position. + * + * @func + * @memberOf R + * @since v0.1.0 + * @category List + * @sig (a -> Boolean) -> [a] -> [a] + * @param {Function} fn The function called per iteration. + * @param {Array} list The collection to iterate over. + * @return {Array} A new array. + * @see R.dropWhile, R.transduce, R.addIndex + * @example + * + * var isNotFour = x => x !== 4; + * + * R.takeWhile(isNotFour, [1, 2, 3, 4, 3, 2, 1]); //=> [1, 2, 3] + */ + var takeWhile = _curry2(_dispatchable('takeWhile', _xtakeWhile, function takeWhile(fn, list) { + var idx = 0; + var len = list.length; + while (idx < len && fn(list[idx])) { + idx += 1; + } + return _slice(list, 0, idx); + })); + + /** + * Runs the given function with the supplied object, then returns the object. + * + * @func + * @memberOf R + * @since v0.1.0 + * @category Function + * @sig (a -> *) -> a -> a + * @param {Function} fn The function to call with `x`. The return value of `fn` will be thrown away. + * @param {*} x + * @return {*} `x`. + * @example + * + * var sayX = x => console.log('x is ' + x); + * R.tap(sayX, 100); //=> 100 + * // logs 'x is 100' + */ + var tap = _curry2(function tap(fn, x) { + fn(x); + return x; + }); + + /** + * Calls an input function `n` times, returning an array containing the results + * of those function calls. + * + * `fn` is passed one argument: The current value of `n`, which begins at `0` + * and is gradually incremented to `n - 1`. + * + * @func + * @memberOf R + * @since v0.2.3 + * @category List + * @sig (Number -> a) -> Number -> [a] + * @param {Function} fn The function to invoke. Passed one argument, the current value of `n`. + * @param {Number} n A value between `0` and `n - 1`. Increments after each function call. + * @return {Array} An array containing the return values of all calls to `fn`. + * @example + * + * R.times(R.identity, 5); //=> [0, 1, 2, 3, 4] + */ + var times = _curry2(function times(fn, n) { + var len = Number(n); + var idx = 0; + var list; + if (len < 0 || isNaN(len)) { + throw new RangeError('n must be a non-negative number'); + } + list = new Array(len); + while (idx < len) { + list[idx] = fn(idx); + idx += 1; + } + return list; + }); + + /** + * Converts an object into an array of key, value arrays. Only the object's + * own properties are used. + * Note that the order of the output array is not guaranteed to be consistent + * across different JS platforms. + * + * @func + * @memberOf R + * @since v0.4.0 + * @category Object + * @sig {String: *} -> [[String,*]] + * @param {Object} obj The object to extract from + * @return {Array} An array of key, value arrays from the object's own properties. + * @see R.fromPairs + * @example + * + * R.toPairs({a: 1, b: 2, c: 3}); //=> [['a', 1], ['b', 2], ['c', 3]] + */ + var toPairs = _curry1(function toPairs(obj) { + var pairs = []; + for (var prop in obj) { + if (_has(prop, obj)) { + pairs[pairs.length] = [ + prop, + obj[prop] + ]; + } + } + return pairs; + }); + + /** + * Converts an object into an array of key, value arrays. The object's own + * properties and prototype properties are used. Note that the order of the + * output array is not guaranteed to be consistent across different JS + * platforms. + * + * @func + * @memberOf R + * @since v0.4.0 + * @category Object + * @sig {String: *} -> [[String,*]] + * @param {Object} obj The object to extract from + * @return {Array} An array of key, value arrays from the object's own + * and prototype properties. + * @example + * + * var F = function() { this.x = 'X'; }; + * F.prototype.y = 'Y'; + * var f = new F(); + * R.toPairsIn(f); //=> [['x','X'], ['y','Y']] + */ + var toPairsIn = _curry1(function toPairsIn(obj) { + var pairs = []; + for (var prop in obj) { + pairs[pairs.length] = [ + prop, + obj[prop] + ]; + } + return pairs; + }); + + /** + * Transposes the rows and columns of a 2D list. + * When passed a list of `n` lists of length `x`, + * returns a list of `x` lists of length `n`. + * + * + * @func + * @memberOf R + * @since v0.19.0 + * @category List + * @sig [[a]] -> [[a]] + * @param {Array} list A 2D list + * @return {Array} A 2D list + * @example + * + * R.transpose([[1, 'a'], [2, 'b'], [3, 'c']]) //=> [[1, 2, 3], ['a', 'b', 'c']] + * R.transpose([[1, 2, 3], ['a', 'b', 'c']]) //=> [[1, 'a'], [2, 'b'], [3, 'c']] + * + * If some of the rows are shorter than the following rows, their elements are skipped: + * + * R.transpose([[10, 11], [20], [], [30, 31, 32]]) //=> [[10, 20, 30], [11, 31], [32]] + */ + var transpose = _curry1(function transpose(outerlist) { + var i = 0; + var result = []; + while (i < outerlist.length) { + var innerlist = outerlist[i]; + var j = 0; + while (j < innerlist.length) { + if (typeof result[j] === 'undefined') { + result[j] = []; + } + result[j].push(innerlist[j]); + j += 1; + } + i += 1; + } + return result; + }); + + /** + * Removes (strips) whitespace from both ends of the string. + * + * @func + * @memberOf R + * @since v0.6.0 + * @category String + * @sig String -> String + * @param {String} str The string to trim. + * @return {String} Trimmed version of `str`. + * @example + * + * R.trim(' xyz '); //=> 'xyz' + * R.map(R.trim, R.split(',', 'x, y, z')); //=> ['x', 'y', 'z'] + */ + var trim = function () { + var ws = '\t\n\x0B\f\r \xA0\u1680\u180E\u2000\u2001\u2002\u2003' + '\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028' + '\u2029\uFEFF'; + var zeroWidth = '\u200B'; + var hasProtoTrim = typeof String.prototype.trim === 'function'; + if (!hasProtoTrim || (ws.trim() || !zeroWidth.trim())) { + return _curry1(function trim(str) { + var beginRx = new RegExp('^[' + ws + '][' + ws + ']*'); + var endRx = new RegExp('[' + ws + '][' + ws + ']*$'); + return str.replace(beginRx, '').replace(endRx, ''); + }); + } else { + return _curry1(function trim(str) { + return str.trim(); + }); + } + }(); + + /** + * `tryCatch` takes two functions, a `tryer` and a `catcher`. The returned + * function evaluates the `tryer`; if it does not throw, it simply returns the + * result. If the `tryer` *does* throw, the returned function evaluates the + * `catcher` function and returns its result. Note that for effective + * composition with this function, both the `tryer` and `catcher` functions + * must return the same type of results. + * + * @func + * @memberOf R + * @since v0.20.0 + * @category Function + * @sig (...x -> a) -> ((e, ...x) -> a) -> (...x -> a) + * @param {Function} tryer The function that may throw. + * @param {Function} catcher The function that will be evaluated if `tryer` throws. + * @return {Function} A new function that will catch exceptions and send then to the catcher. + * @example + * + * R.tryCatch(R.prop('x'), R.F)({x: true}); //=> true + * R.tryCatch(R.prop('x'), R.F)(null); //=> false + */ + var tryCatch = _curry2(function _tryCatch(tryer, catcher) { + return _arity(tryer.length, function () { + try { + return tryer.apply(this, arguments); + } catch (e) { + return catcher.apply(this, _concat([e], arguments)); + } + }); + }); + + /** + * Gives a single-word string description of the (native) type of a value, + * returning such answers as 'Object', 'Number', 'Array', or 'Null'. Does not + * attempt to distinguish user Object types any further, reporting them all as + * 'Object'. + * + * @func + * @memberOf R + * @since v0.8.0 + * @category Type + * @sig (* -> {*}) -> String + * @param {*} val The value to test + * @return {String} + * @example + * + * R.type({}); //=> "Object" + * R.type(1); //=> "Number" + * R.type(false); //=> "Boolean" + * R.type('s'); //=> "String" + * R.type(null); //=> "Null" + * R.type([]); //=> "Array" + * R.type(/[A-z]/); //=> "RegExp" + */ + var type = _curry1(function type(val) { + return val === null ? 'Null' : val === undefined ? 'Undefined' : Object.prototype.toString.call(val).slice(8, -1); + }); + + /** + * Takes a function `fn`, which takes a single array argument, and returns a + * function which: + * + * - takes any number of positional arguments; + * - passes these arguments to `fn` as an array; and + * - returns the result. + * + * In other words, R.unapply derives a variadic function from a function which + * takes an array. R.unapply is the inverse of R.apply. + * + * @func + * @memberOf R + * @since v0.8.0 + * @category Function + * @sig ([*...] -> a) -> (*... -> a) + * @param {Function} fn + * @return {Function} + * @see R.apply + * @example + * + * R.unapply(JSON.stringify)(1, 2, 3); //=> '[1,2,3]' + */ + var unapply = _curry1(function unapply(fn) { + return function () { + return fn(_slice(arguments)); + }; + }); + + /** + * Wraps a function of any arity (including nullary) in a function that accepts + * exactly 1 parameter. Any extraneous parameters will not be passed to the + * supplied function. + * + * @func + * @memberOf R + * @since v0.2.0 + * @category Function + * @sig (* -> b) -> (a -> b) + * @param {Function} fn The function to wrap. + * @return {Function} A new function wrapping `fn`. The new function is guaranteed to be of + * arity 1. + * @example + * + * var takesTwoArgs = function(a, b) { + * return [a, b]; + * }; + * takesTwoArgs.length; //=> 2 + * takesTwoArgs(1, 2); //=> [1, 2] + * + * var takesOneArg = R.unary(takesTwoArgs); + * takesOneArg.length; //=> 1 + * // Only 1 argument is passed to the wrapped function + * takesOneArg(1, 2); //=> [1, undefined] + */ + var unary = _curry1(function unary(fn) { + return nAry(1, fn); + }); + + /** + * Returns a function of arity `n` from a (manually) curried function. + * + * @func + * @memberOf R + * @since v0.14.0 + * @category Function + * @sig Number -> (a -> b) -> (a -> c) + * @param {Number} length The arity for the returned function. + * @param {Function} fn The function to uncurry. + * @return {Function} A new function. + * @see R.curry + * @example + * + * var addFour = a => b => c => d => a + b + c + d; + * + * var uncurriedAddFour = R.uncurryN(4, addFour); + * uncurriedAddFour(1, 2, 3, 4); //=> 10 + */ + var uncurryN = _curry2(function uncurryN(depth, fn) { + return curryN(depth, function () { + var currentDepth = 1; + var value = fn; + var idx = 0; + var endIdx; + while (currentDepth <= depth && typeof value === 'function') { + endIdx = currentDepth === depth ? arguments.length : idx + value.length; + value = value.apply(this, _slice(arguments, idx, endIdx)); + currentDepth += 1; + idx = endIdx; + } + return value; + }); + }); + + /** + * Builds a list from a seed value. Accepts an iterator function, which returns + * either false to stop iteration or an array of length 2 containing the value + * to add to the resulting list and the seed to be used in the next call to the + * iterator function. + * + * The iterator function receives one argument: *(seed)*. + * + * @func + * @memberOf R + * @since v0.10.0 + * @category List + * @sig (a -> [b]) -> * -> [b] + * @param {Function} fn The iterator function. receives one argument, `seed`, and returns + * either false to quit iteration or an array of length two to proceed. The element + * at index 0 of this array will be added to the resulting array, and the element + * at index 1 will be passed to the next call to `fn`. + * @param {*} seed The seed value. + * @return {Array} The final list. + * @example + * + * var f = n => n > 50 ? false : [-n, n + 10]; + * R.unfold(f, 10); //=> [-10, -20, -30, -40, -50] + */ + var unfold = _curry2(function unfold(fn, seed) { + var pair = fn(seed); + var result = []; + while (pair && pair.length) { + result[result.length] = pair[0]; + pair = fn(pair[1]); + } + return result; + }); + + /** + * Returns a new list containing only one copy of each element in the original + * list, based upon the value returned by applying the supplied predicate to + * two list elements. Prefers the first item if two items compare equal based + * on the predicate. + * + * @func + * @memberOf R + * @since v0.2.0 + * @category List + * @sig (a, a -> Boolean) -> [a] -> [a] + * @param {Function} pred A predicate used to test whether two items are equal. + * @param {Array} list The array to consider. + * @return {Array} The list of unique items. + * @example + * + * var strEq = R.eqBy(String); + * R.uniqWith(strEq)([1, '1', 2, 1]); //=> [1, 2] + * R.uniqWith(strEq)([{}, {}]); //=> [{}] + * R.uniqWith(strEq)([1, '1', 1]); //=> [1] + * R.uniqWith(strEq)(['1', 1, 1]); //=> ['1'] + */ + var uniqWith = _curry2(function uniqWith(pred, list) { + var idx = 0; + var len = list.length; + var result = []; + var item; + while (idx < len) { + item = list[idx]; + if (!_containsWith(pred, item, result)) { + result[result.length] = item; + } + idx += 1; + } + return result; + }); + + /** + * Tests the final argument by passing it to the given predicate function. If + * the predicate is not satisfied, the function will return the result of + * calling the `whenFalseFn` function with the same argument. If the predicate + * is satisfied, the argument is returned as is. + * + * @func + * @memberOf R + * @since v0.18.0 + * @category Logic + * @sig (a -> Boolean) -> (a -> a) -> a -> a + * @param {Function} pred A predicate function + * @param {Function} whenFalseFn A function to invoke when the `pred` evaluates + * to a falsy value. + * @param {*} x An object to test with the `pred` function and + * pass to `whenFalseFn` if necessary. + * @return {*} Either `x` or the result of applying `x` to `whenFalseFn`. + * @see R.ifElse, R.when + * @example + * + * // coerceArray :: (a|[a]) -> [a] + * var coerceArray = R.unless(R.isArrayLike, R.of); + * coerceArray([1, 2, 3]); //=> [1, 2, 3] + * coerceArray(1); //=> [1] + */ + var unless = _curry3(function unless(pred, whenFalseFn, x) { + return pred(x) ? x : whenFalseFn(x); + }); + + /** + * Takes a predicate, a transformation function, and an initial value, + * and returns a value of the same type as the initial value. + * It does so by applying the transformation until the predicate is satisfied, + * at which point it returns the satisfactory value. + * + * @func + * @memberOf R + * @since v0.20.0 + * @category Logic + * @sig (a -> Boolean) -> (a -> a) -> a -> a + * @param {Function} pred A predicate function + * @param {Function} fn The iterator function + * @param {*} init Initial value + * @return {*} Final value that satisfies predicate + * @example + * + * R.until(R.gt(R.__, 100), R.multiply(2))(1) // => 128 + */ + var until = _curry3(function until(pred, fn, init) { + var val = init; + while (!pred(val)) { + val = fn(val); + } + return val; + }); + + /** + * Returns a new copy of the array with the element at the provided index + * replaced with the given value. + * + * @func + * @memberOf R + * @since v0.14.0 + * @category List + * @sig Number -> a -> [a] -> [a] + * @param {Number} idx The index to update. + * @param {*} x The value to exist at the given index of the returned array. + * @param {Array|Arguments} list The source array-like object to be updated. + * @return {Array} A copy of `list` with the value at index `idx` replaced with `x`. + * @see R.adjust + * @example + * + * R.update(1, 11, [0, 1, 2]); //=> [0, 11, 2] + * R.update(1)(11)([0, 1, 2]); //=> [0, 11, 2] + */ + var update = _curry3(function update(idx, x, list) { + return adjust(always(x), idx, list); + }); + + /** + * Accepts a function `fn` and a list of transformer functions and returns a + * new curried function. When the new function is invoked, it calls the + * function `fn` with parameters consisting of the result of calling each + * supplied handler on successive arguments to the new function. + * + * If more arguments are passed to the returned function than transformer + * functions, those arguments are passed directly to `fn` as additional + * parameters. If you expect additional arguments that don't need to be + * transformed, although you can ignore them, it's best to pass an identity + * function so that the new function reports the correct arity. + * + * @func + * @memberOf R + * @since v0.1.0 + * @category Function + * @sig (x1 -> x2 -> ... -> z) -> [(a -> x1), (b -> x2), ...] -> (a -> b -> ... -> z) + * @param {Function} fn The function to wrap. + * @param {Array} transformers A list of transformer functions + * @return {Function} The wrapped function. + * @example + * + * R.useWith(Math.pow, [R.identity, R.identity])(3, 4); //=> 81 + * R.useWith(Math.pow, [R.identity, R.identity])(3)(4); //=> 81 + * R.useWith(Math.pow, [R.dec, R.inc])(3, 4); //=> 32 + * R.useWith(Math.pow, [R.dec, R.inc])(3)(4); //=> 32 + */ + var useWith = _curry2(function useWith(fn, transformers) { + return curryN(transformers.length, function () { + var args = []; + var idx = 0; + while (idx < transformers.length) { + args.push(transformers[idx].call(this, arguments[idx])); + idx += 1; + } + return fn.apply(this, args.concat(_slice(arguments, transformers.length))); + }); + }); + + /** + * Returns a list of all the enumerable own properties of the supplied object. + * Note that the order of the output array is not guaranteed across different + * JS platforms. + * + * @func + * @memberOf R + * @since v0.1.0 + * @category Object + * @sig {k: v} -> [v] + * @param {Object} obj The object to extract values from + * @return {Array} An array of the values of the object's own properties. + * @example + * + * R.values({a: 1, b: 2, c: 3}); //=> [1, 2, 3] + */ + var values = _curry1(function values(obj) { + var props = keys(obj); + var len = props.length; + var vals = []; + var idx = 0; + while (idx < len) { + vals[idx] = obj[props[idx]]; + idx += 1; + } + return vals; + }); + + /** + * Returns a list of all the properties, including prototype properties, of the + * supplied object. + * Note that the order of the output array is not guaranteed to be consistent + * across different JS platforms. + * + * @func + * @memberOf R + * @since v0.2.0 + * @category Object + * @sig {k: v} -> [v] + * @param {Object} obj The object to extract values from + * @return {Array} An array of the values of the object's own and prototype properties. + * @example + * + * var F = function() { this.x = 'X'; }; + * F.prototype.y = 'Y'; + * var f = new F(); + * R.valuesIn(f); //=> ['X', 'Y'] + */ + var valuesIn = _curry1(function valuesIn(obj) { + var prop; + var vs = []; + for (prop in obj) { + vs[vs.length] = obj[prop]; + } + return vs; + }); + + /** + * Returns a "view" of the given data structure, determined by the given lens. + * The lens's focus determines which portion of the data structure is visible. + * + * @func + * @memberOf R + * @since v0.16.0 + * @category Object + * @typedefn Lens s a = Functor f => (a -> f a) -> s -> f s + * @sig Lens s a -> s -> a + * @param {Lens} lens + * @param {*} x + * @return {*} + * @see R.prop, R.lensIndex, R.lensProp + * @example + * + * var xLens = R.lensProp('x'); + * + * R.view(xLens, {x: 1, y: 2}); //=> 1 + * R.view(xLens, {x: 4, y: 2}); //=> 4 + */ + // `Const` is a functor that effectively ignores the function given to `map`. + // Using `Const` effectively ignores the setter function of the `lens`, + // leaving the value returned by the getter function unmodified. + var view = function () { + // `Const` is a functor that effectively ignores the function given to `map`. + var Const = function (x) { + return { + value: x, + map: function () { + return this; + } + }; + }; + return _curry2(function view(lens, x) { + // Using `Const` effectively ignores the setter function of the `lens`, + // leaving the value returned by the getter function unmodified. + return lens(Const)(x).value; + }); + }(); + + /** + * Tests the final argument by passing it to the given predicate function. If + * the predicate is satisfied, the function will return the result of calling + * the `whenTrueFn` function with the same argument. If the predicate is not + * satisfied, the argument is returned as is. + * + * @func + * @memberOf R + * @since v0.18.0 + * @category Logic + * @sig (a -> Boolean) -> (a -> a) -> a -> a + * @param {Function} pred A predicate function + * @param {Function} whenTrueFn A function to invoke when the `condition` + * evaluates to a truthy value. + * @param {*} x An object to test with the `pred` function and + * pass to `whenTrueFn` if necessary. + * @return {*} Either `x` or the result of applying `x` to `whenTrueFn`. + * @see R.ifElse, R.unless + * @example + * + * // truncate :: String -> String + * var truncate = R.when( + * R.propSatisfies(R.gt(R.__, 10), 'length'), + * R.pipe(R.take(10), R.append('…'), R.join('')) + * ); + * truncate('12345'); //=> '12345' + * truncate('0123456789ABC'); //=> '0123456789…' + */ + var when = _curry3(function when(pred, whenTrueFn, x) { + return pred(x) ? whenTrueFn(x) : x; + }); + + /** + * Takes a spec object and a test object; returns true if the test satisfies + * the spec. Each of the spec's own properties must be a predicate function. + * Each predicate is applied to the value of the corresponding property of the + * test object. `where` returns true if all the predicates return true, false + * otherwise. + * + * `where` is well suited to declaratively expressing constraints for other + * functions such as `filter` and `find`. + * + * @func + * @memberOf R + * @since v0.1.1 + * @category Object + * @sig {String: (* -> Boolean)} -> {String: *} -> Boolean + * @param {Object} spec + * @param {Object} testObj + * @return {Boolean} + * @example + * + * // pred :: Object -> Boolean + * var pred = where({ + * a: equals('foo'), + * b: complement(equals('bar')), + * x: gt(__, 10), + * y: lt(__, 20) + * }); + * + * pred({a: 'foo', b: 'xxx', x: 11, y: 19}); //=> true + * pred({a: 'xxx', b: 'xxx', x: 11, y: 19}); //=> false + * pred({a: 'foo', b: 'bar', x: 11, y: 19}); //=> false + * pred({a: 'foo', b: 'xxx', x: 10, y: 19}); //=> false + * pred({a: 'foo', b: 'xxx', x: 11, y: 20}); //=> false + */ + var where = _curry2(function where(spec, testObj) { + for (var prop in spec) { + if (_has(prop, spec) && !spec[prop](testObj[prop])) { + return false; + } + } + return true; + }); + + /** + * Wrap a function inside another to allow you to make adjustments to the + * parameters, or do other processing either before the internal function is + * called or with its results. + * + * @func + * @memberOf R + * @since v0.1.0 + * @category Function + * @sig (a... -> b) -> ((a... -> b) -> a... -> c) -> (a... -> c) + * @param {Function} fn The function to wrap. + * @param {Function} wrapper The wrapper function. + * @return {Function} The wrapped function. + * @deprecated since v0.22.0 + * @example + * + * var greet = name => 'Hello ' + name; + * + * var shoutedGreet = R.wrap(greet, (gr, name) => gr(name).toUpperCase()); + * + * shoutedGreet("Kathy"); //=> "HELLO KATHY" + * + * var shortenedGreet = R.wrap(greet, function(gr, name) { + * return gr(name.substring(0, 3)); + * }); + * shortenedGreet("Robert"); //=> "Hello Rob" + */ + var wrap = _curry2(function wrap(fn, wrapper) { + return curryN(fn.length, function () { + return wrapper.apply(this, _concat([fn], arguments)); + }); + }); + + /** + * Creates a new list out of the two supplied by creating each possible pair + * from the lists. + * + * @func + * @memberOf R + * @since v0.1.0 + * @category List + * @sig [a] -> [b] -> [[a,b]] + * @param {Array} as The first list. + * @param {Array} bs The second list. + * @return {Array} The list made by combining each possible pair from + * `as` and `bs` into pairs (`[a, b]`). + * @example + * + * R.xprod([1, 2], ['a', 'b']); //=> [[1, 'a'], [1, 'b'], [2, 'a'], [2, 'b']] + */ + // = xprodWith(prepend); (takes about 3 times as long...) + var xprod = _curry2(function xprod(a, b) { + // = xprodWith(prepend); (takes about 3 times as long...) + var idx = 0; + var ilen = a.length; + var j; + var jlen = b.length; + var result = []; + while (idx < ilen) { + j = 0; + while (j < jlen) { + result[result.length] = [ + a[idx], + b[j] + ]; + j += 1; + } + idx += 1; + } + return result; + }); + + /** + * Creates a new list out of the two supplied by pairing up equally-positioned + * items from both lists. The returned list is truncated to the length of the + * shorter of the two input lists. + * Note: `zip` is equivalent to `zipWith(function(a, b) { return [a, b] })`. + * + * @func + * @memberOf R + * @since v0.1.0 + * @category List + * @sig [a] -> [b] -> [[a,b]] + * @param {Array} list1 The first array to consider. + * @param {Array} list2 The second array to consider. + * @return {Array} The list made by pairing up same-indexed elements of `list1` and `list2`. + * @example + * + * R.zip([1, 2, 3], ['a', 'b', 'c']); //=> [[1, 'a'], [2, 'b'], [3, 'c']] + */ + var zip = _curry2(function zip(a, b) { + var rv = []; + var idx = 0; + var len = Math.min(a.length, b.length); + while (idx < len) { + rv[idx] = [ + a[idx], + b[idx] + ]; + idx += 1; + } + return rv; + }); + + /** + * Creates a new object out of a list of keys and a list of values. + * Key/value pairing is truncated to the length of the shorter of the two lists. + * Note: `zipObj` is equivalent to `pipe(zipWith(pair), fromPairs)`. + * + * @func + * @memberOf R + * @since v0.3.0 + * @category List + * @sig [String] -> [*] -> {String: *} + * @param {Array} keys The array that will be properties on the output object. + * @param {Array} values The list of values on the output object. + * @return {Object} The object made by pairing up same-indexed elements of `keys` and `values`. + * @example + * + * R.zipObj(['a', 'b', 'c'], [1, 2, 3]); //=> {a: 1, b: 2, c: 3} + */ + var zipObj = _curry2(function zipObj(keys, values) { + var idx = 0; + var len = Math.min(keys.length, values.length); + var out = {}; + while (idx < len) { + out[keys[idx]] = values[idx]; + idx += 1; + } + return out; + }); + + /** + * Creates a new list out of the two supplied by applying the function to each + * equally-positioned pair in the lists. The returned list is truncated to the + * length of the shorter of the two input lists. + * + * @function + * @memberOf R + * @since v0.1.0 + * @category List + * @sig (a,b -> c) -> [a] -> [b] -> [c] + * @param {Function} fn The function used to combine the two elements into one value. + * @param {Array} list1 The first array to consider. + * @param {Array} list2 The second array to consider. + * @return {Array} The list made by combining same-indexed elements of `list1` and `list2` + * using `fn`. + * @example + * + * var f = (x, y) => { + * // ... + * }; + * R.zipWith(f, [1, 2, 3], ['a', 'b', 'c']); + * //=> [f(1, 'a'), f(2, 'b'), f(3, 'c')] + */ + var zipWith = _curry3(function zipWith(fn, a, b) { + var rv = []; + var idx = 0; + var len = Math.min(a.length, b.length); + while (idx < len) { + rv[idx] = fn(a[idx], b[idx]); + idx += 1; + } + return rv; + }); + + /** + * A function that always returns `false`. Any passed in parameters are ignored. + * + * @func + * @memberOf R + * @since v0.9.0 + * @category Function + * @sig * -> Boolean + * @param {*} + * @return {Boolean} + * @see R.always, R.T + * @example + * + * R.F(); //=> false + */ + var F = always(false); + + /** + * A function that always returns `true`. Any passed in parameters are ignored. + * + * @func + * @memberOf R + * @since v0.9.0 + * @category Function + * @sig * -> Boolean + * @param {*} + * @return {Boolean} + * @see R.always, R.F + * @example + * + * R.T(); //=> true + */ + var T = always(true); + + /** + * Copies an object. + * + * @private + * @param {*} value The value to be copied + * @param {Array} refFrom Array containing the source references + * @param {Array} refTo Array containing the copied source references + * @param {Boolean} deep Whether or not to perform deep cloning. + * @return {*} The copied value. + */ + var _clone = function _clone(value, refFrom, refTo, deep) { + var copy = function copy(copiedValue) { + var len = refFrom.length; + var idx = 0; + while (idx < len) { + if (value === refFrom[idx]) { + return refTo[idx]; + } + idx += 1; + } + refFrom[idx + 1] = value; + refTo[idx + 1] = copiedValue; + for (var key in value) { + copiedValue[key] = deep ? _clone(value[key], refFrom, refTo, true) : value[key]; + } + return copiedValue; + }; + switch (type(value)) { + case 'Object': + return copy({}); + case 'Array': + return copy([]); + case 'Date': + return new Date(value.valueOf()); + case 'RegExp': + return _cloneRegExp(value); + default: + return value; + } + }; + + var _createPartialApplicator = function _createPartialApplicator(concat) { + return _curry2(function (fn, args) { + return _arity(Math.max(0, fn.length - args.length), function () { + return fn.apply(this, concat(args, arguments)); + }); + }); + }; + + var _dropLast = function dropLast(n, xs) { + return take(n < xs.length ? xs.length - n : 0, xs); + }; + + // Values of other types are only equal if identical. + var _equals = function _equals(a, b, stackA, stackB) { + if (identical(a, b)) { + return true; + } + if (type(a) !== type(b)) { + return false; + } + if (a == null || b == null) { + return false; + } + if (typeof a.equals === 'function' || typeof b.equals === 'function') { + return typeof a.equals === 'function' && a.equals(b) && typeof b.equals === 'function' && b.equals(a); + } + switch (type(a)) { + case 'Arguments': + case 'Array': + case 'Object': + if (typeof a.constructor === 'function' && _functionName(a.constructor) === 'Promise') { + return a === b; + } + break; + case 'Boolean': + case 'Number': + case 'String': + if (!(typeof a === typeof b && identical(a.valueOf(), b.valueOf()))) { + return false; + } + break; + case 'Date': + if (!identical(a.valueOf(), b.valueOf())) { + return false; + } + break; + case 'Error': + return a.name === b.name && a.message === b.message; + case 'RegExp': + if (!(a.source === b.source && a.global === b.global && a.ignoreCase === b.ignoreCase && a.multiline === b.multiline && a.sticky === b.sticky && a.unicode === b.unicode)) { + return false; + } + break; + case 'Map': + case 'Set': + if (!_equals(_arrayFromIterator(a.entries()), _arrayFromIterator(b.entries()), stackA, stackB)) { + return false; + } + break; + case 'Int8Array': + case 'Uint8Array': + case 'Uint8ClampedArray': + case 'Int16Array': + case 'Uint16Array': + case 'Int32Array': + case 'Uint32Array': + case 'Float32Array': + case 'Float64Array': + break; + case 'ArrayBuffer': + break; + default: + // Values of other types are only equal if identical. + return false; + } + var keysA = keys(a); + if (keysA.length !== keys(b).length) { + return false; + } + var idx = stackA.length - 1; + while (idx >= 0) { + if (stackA[idx] === a) { + return stackB[idx] === b; + } + idx -= 1; + } + stackA.push(a); + stackB.push(b); + idx = keysA.length - 1; + while (idx >= 0) { + var key = keysA[idx]; + if (!(_has(key, b) && _equals(b[key], a[key], stackA, stackB))) { + return false; + } + idx -= 1; + } + stackA.pop(); + stackB.pop(); + return true; + }; + + /** + * `_makeFlat` is a helper function that returns a one-level or fully recursive + * function based on the flag passed in. + * + * @private + */ + var _makeFlat = function _makeFlat(recursive) { + return function flatt(list) { + var value, jlen, j; + var result = []; + var idx = 0; + var ilen = list.length; + while (idx < ilen) { + if (isArrayLike(list[idx])) { + value = recursive ? flatt(list[idx]) : list[idx]; + j = 0; + jlen = value.length; + while (j < jlen) { + result[result.length] = value[j]; + j += 1; + } + } else { + result[result.length] = list[idx]; + } + idx += 1; + } + return result; + }; + }; + + var _reduce = function () { + function _arrayReduce(xf, acc, list) { + var idx = 0; + var len = list.length; + while (idx < len) { + acc = xf['@@transducer/step'](acc, list[idx]); + if (acc && acc['@@transducer/reduced']) { + acc = acc['@@transducer/value']; + break; + } + idx += 1; + } + return xf['@@transducer/result'](acc); + } + function _iterableReduce(xf, acc, iter) { + var step = iter.next(); + while (!step.done) { + acc = xf['@@transducer/step'](acc, step.value); + if (acc && acc['@@transducer/reduced']) { + acc = acc['@@transducer/value']; + break; + } + step = iter.next(); + } + return xf['@@transducer/result'](acc); + } + function _methodReduce(xf, acc, obj) { + return xf['@@transducer/result'](obj.reduce(bind(xf['@@transducer/step'], xf), acc)); + } + var symIterator = typeof Symbol !== 'undefined' ? Symbol.iterator : '@@iterator'; + return function _reduce(fn, acc, list) { + if (typeof fn === 'function') { + fn = _xwrap(fn); + } + if (isArrayLike(list)) { + return _arrayReduce(fn, acc, list); + } + if (typeof list.reduce === 'function') { + return _methodReduce(fn, acc, list); + } + if (list[symIterator] != null) { + return _iterableReduce(fn, acc, list[symIterator]()); + } + if (typeof list.next === 'function') { + return _iterableReduce(fn, acc, list); + } + throw new TypeError('reduce: list must be array or iterable'); + }; + }(); + + var _stepCat = function () { + var _stepCatArray = { + '@@transducer/init': Array, + '@@transducer/step': function (xs, x) { + xs.push(x); + return xs; + }, + '@@transducer/result': _identity + }; + var _stepCatString = { + '@@transducer/init': String, + '@@transducer/step': function (a, b) { + return a + b; + }, + '@@transducer/result': _identity + }; + var _stepCatObject = { + '@@transducer/init': Object, + '@@transducer/step': function (result, input) { + return _assign(result, isArrayLike(input) ? objOf(input[0], input[1]) : input); + }, + '@@transducer/result': _identity + }; + return function _stepCat(obj) { + if (_isTransformer(obj)) { + return obj; + } + if (isArrayLike(obj)) { + return _stepCatArray; + } + if (typeof obj === 'string') { + return _stepCatString; + } + if (typeof obj === 'object') { + return _stepCatObject; + } + throw new Error('Cannot create transformer for ' + obj); + }; + }(); + + var _xdropLastWhile = function () { + function XDropLastWhile(fn, xf) { + this.f = fn; + this.retained = []; + this.xf = xf; + } + XDropLastWhile.prototype['@@transducer/init'] = _xfBase.init; + XDropLastWhile.prototype['@@transducer/result'] = function (result) { + this.retained = null; + return this.xf['@@transducer/result'](result); + }; + XDropLastWhile.prototype['@@transducer/step'] = function (result, input) { + return this.f(input) ? this.retain(result, input) : this.flush(result, input); + }; + XDropLastWhile.prototype.flush = function (result, input) { + result = _reduce(this.xf['@@transducer/step'], result, this.retained); + this.retained = []; + return this.xf['@@transducer/step'](result, input); + }; + XDropLastWhile.prototype.retain = function (result, input) { + this.retained.push(input); + return result; + }; + return _curry2(function _xdropLastWhile(fn, xf) { + return new XDropLastWhile(fn, xf); + }); + }(); + + /** + * Creates a new list iteration function from an existing one by adding two new + * parameters to its callback function: the current index, and the entire list. + * + * This would turn, for instance, Ramda's simple `map` function into one that + * more closely resembles `Array.prototype.map`. Note that this will only work + * for functions in which the iteration callback function is the first + * parameter, and where the list is the last parameter. (This latter might be + * unimportant if the list parameter is not used.) + * + * @func + * @memberOf R + * @since v0.15.0 + * @category Function + * @category List + * @sig ((a ... -> b) ... -> [a] -> *) -> (a ..., Int, [a] -> b) ... -> [a] -> *) + * @param {Function} fn A list iteration function that does not pass index or list to its callback + * @return {Function} An altered list iteration function that passes (item, index, list) to its callback + * @example + * + * var mapIndexed = R.addIndex(R.map); + * mapIndexed((val, idx) => idx + '-' + val, ['f', 'o', 'o', 'b', 'a', 'r']); + * //=> ['0-f', '1-o', '2-o', '3-b', '4-a', '5-r'] + */ + var addIndex = _curry1(function addIndex(fn) { + return curryN(fn.length, function () { + var idx = 0; + var origFn = arguments[0]; + var list = arguments[arguments.length - 1]; + var args = _slice(arguments); + args[0] = function () { + var result = origFn.apply(this, _concat(arguments, [ + idx, + list + ])); + idx += 1; + return result; + }; + return fn.apply(this, args); + }); + }); + + /** + * Wraps a function of any arity (including nullary) in a function that accepts + * exactly 2 parameters. Any extraneous parameters will not be passed to the + * supplied function. + * + * @func + * @memberOf R + * @since v0.2.0 + * @category Function + * @sig (* -> c) -> (a, b -> c) + * @param {Function} fn The function to wrap. + * @return {Function} A new function wrapping `fn`. The new function is guaranteed to be of + * arity 2. + * @example + * + * var takesThreeArgs = function(a, b, c) { + * return [a, b, c]; + * }; + * takesThreeArgs.length; //=> 3 + * takesThreeArgs(1, 2, 3); //=> [1, 2, 3] + * + * var takesTwoArgs = R.binary(takesThreeArgs); + * takesTwoArgs.length; //=> 2 + * // Only 2 arguments are passed to the wrapped function + * takesTwoArgs(1, 2, 3); //=> [1, 2, undefined] + */ + var binary = _curry1(function binary(fn) { + return nAry(2, fn); + }); + + /** + * Creates a deep copy of the value which may contain (nested) `Array`s and + * `Object`s, `Number`s, `String`s, `Boolean`s and `Date`s. `Function`s are not + * copied, but assigned by their reference. + * + * Dispatches to a `clone` method if present. + * + * @func + * @memberOf R + * @since v0.1.0 + * @category Object + * @sig {*} -> {*} + * @param {*} value The object or array to clone + * @return {*} A new object or array. + * @example + * + * var objects = [{}, {}, {}]; + * var objectsClone = R.clone(objects); + * objects[0] === objectsClone[0]; //=> false + */ + var clone = _curry1(function clone(value) { + return value != null && typeof value.clone === 'function' ? value.clone() : _clone(value, [], [], true); + }); + + /** + * Returns a curried equivalent of the provided function. The curried function + * has two unusual capabilities. First, its arguments needn't be provided one + * at a time. If `f` is a ternary function and `g` is `R.curry(f)`, the + * following are equivalent: + * + * - `g(1)(2)(3)` + * - `g(1)(2, 3)` + * - `g(1, 2)(3)` + * - `g(1, 2, 3)` + * + * Secondly, the special placeholder value `R.__` may be used to specify + * "gaps", allowing partial application of any combination of arguments, + * regardless of their positions. If `g` is as above and `_` is `R.__`, the + * following are equivalent: + * + * - `g(1, 2, 3)` + * - `g(_, 2, 3)(1)` + * - `g(_, _, 3)(1)(2)` + * - `g(_, _, 3)(1, 2)` + * - `g(_, 2)(1)(3)` + * - `g(_, 2)(1, 3)` + * - `g(_, 2)(_, 3)(1)` + * + * @func + * @memberOf R + * @since v0.1.0 + * @category Function + * @sig (* -> a) -> (* -> a) + * @param {Function} fn The function to curry. + * @return {Function} A new, curried function. + * @see R.curryN + * @example + * + * var addFourNumbers = (a, b, c, d) => a + b + c + d; + * + * var curriedAddFourNumbers = R.curry(addFourNumbers); + * var f = curriedAddFourNumbers(1, 2); + * var g = f(3); + * g(4); //=> 10 + */ + var curry = _curry1(function curry(fn) { + return curryN(fn.length, fn); + }); + + /** + * Returns all but the first `n` elements of the given list, string, or + * transducer/transformer (or object with a `drop` method). + * + * Dispatches to the `drop` method of the second argument, if present. + * + * @func + * @memberOf R + * @since v0.1.0 + * @category List + * @sig Number -> [a] -> [a] + * @sig Number -> String -> String + * @param {Number} n + * @param {*} list + * @return {*} + * @see R.take, R.transduce + * @example + * + * R.drop(1, ['foo', 'bar', 'baz']); //=> ['bar', 'baz'] + * R.drop(2, ['foo', 'bar', 'baz']); //=> ['baz'] + * R.drop(3, ['foo', 'bar', 'baz']); //=> [] + * R.drop(4, ['foo', 'bar', 'baz']); //=> [] + * R.drop(3, 'ramda'); //=> 'da' + */ + var drop = _curry2(_dispatchable('drop', _xdrop, function drop(n, xs) { + return slice(Math.max(0, n), Infinity, xs); + })); + + /** + * Returns a list containing all but the last `n` elements of the given `list`. + * + * @func + * @memberOf R + * @since v0.16.0 + * @category List + * @sig Number -> [a] -> [a] + * @sig Number -> String -> String + * @param {Number} n The number of elements of `xs` to skip. + * @param {Array} xs The collection to consider. + * @return {Array} + * @see R.takeLast + * @example + * + * R.dropLast(1, ['foo', 'bar', 'baz']); //=> ['foo', 'bar'] + * R.dropLast(2, ['foo', 'bar', 'baz']); //=> ['foo'] + * R.dropLast(3, ['foo', 'bar', 'baz']); //=> [] + * R.dropLast(4, ['foo', 'bar', 'baz']); //=> [] + * R.dropLast(3, 'ramda'); //=> 'ra' + */ + var dropLast = _curry2(_dispatchable('dropLast', _xdropLast, _dropLast)); + + /** + * Returns a new list excluding all the tailing elements of a given list which + * satisfy the supplied predicate function. It passes each value from the right + * to the supplied predicate function, skipping elements while the predicate + * function returns `true`. The predicate function is applied to one argument: + * *(value)*. + * + * @func + * @memberOf R + * @since v0.16.0 + * @category List + * @sig (a -> Boolean) -> [a] -> [a] + * @param {Function} fn The function called per iteration. + * @param {Array} list The collection to iterate over. + * @return {Array} A new array. + * @see R.takeLastWhile, R.addIndex + * @example + * + * var lteThree = x => x <= 3; + * + * R.dropLastWhile(lteThree, [1, 2, 3, 4, 3, 2, 1]); //=> [1, 2, 3, 4] + */ + var dropLastWhile = _curry2(_dispatchable('dropLastWhile', _xdropLastWhile, _dropLastWhile)); + + /** + * Returns `true` if its arguments are equivalent, `false` otherwise. Handles + * cyclical data structures. + * + * Dispatches symmetrically to the `equals` methods of both arguments, if + * present. + * + * @func + * @memberOf R + * @since v0.15.0 + * @category Relation + * @sig a -> b -> Boolean + * @param {*} a + * @param {*} b + * @return {Boolean} + * @example + * + * R.equals(1, 1); //=> true + * R.equals(1, '1'); //=> false + * R.equals([1, 2, 3], [1, 2, 3]); //=> true + * + * var a = {}; a.v = a; + * var b = {}; b.v = b; + * R.equals(a, b); //=> true + */ + var equals = _curry2(function equals(a, b) { + return _equals(a, b, [], []); + }); + + /** + * Takes a predicate and a "filterable", and returns a new filterable of the + * same type containing the members of the given filterable which satisfy the + * given predicate. + * + * Dispatches to the `filter` method of the second argument, if present. + * + * Acts as a transducer if a transformer is given in list position. + * + * @func + * @memberOf R + * @since v0.1.0 + * @category List + * @sig Filterable f => (a -> Boolean) -> f a -> f a + * @param {Function} pred + * @param {Array} filterable + * @return {Array} + * @see R.reject, R.transduce, R.addIndex + * @example + * + * var isEven = n => n % 2 === 0; + * + * R.filter(isEven, [1, 2, 3, 4]); //=> [2, 4] + * + * R.filter(isEven, {a: 1, b: 2, c: 3, d: 4}); //=> {b: 2, d: 4} + */ + // else + var filter = _curry2(_dispatchable('filter', _xfilter, function (pred, filterable) { + return _isObject(filterable) ? _reduce(function (acc, key) { + if (pred(filterable[key])) { + acc[key] = filterable[key]; + } + return acc; + }, {}, keys(filterable)) : // else + _filter(pred, filterable); + })); + + /** + * Returns a new list by pulling every item out of it (and all its sub-arrays) + * and putting them in a new array, depth-first. + * + * @func + * @memberOf R + * @since v0.1.0 + * @category List + * @sig [a] -> [b] + * @param {Array} list The array to consider. + * @return {Array} The flattened list. + * @see R.unnest + * @example + * + * R.flatten([1, 2, [3, 4], 5, [6, [7, 8, [9, [10, 11], 12]]]]); + * //=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] + */ + var flatten = _curry1(_makeFlat(true)); + + /** + * Returns a new function much like the supplied one, except that the first two + * arguments' order is reversed. + * + * @func + * @memberOf R + * @since v0.1.0 + * @category Function + * @sig (a -> b -> c -> ... -> z) -> (b -> a -> c -> ... -> z) + * @param {Function} fn The function to invoke with its first two parameters reversed. + * @return {*} The result of invoking `fn` with its first two parameters' order reversed. + * @example + * + * var mergeThree = (a, b, c) => [].concat(a, b, c); + * + * mergeThree(1, 2, 3); //=> [1, 2, 3] + * + * R.flip(mergeThree)(1, 2, 3); //=> [2, 1, 3] + */ + var flip = _curry1(function flip(fn) { + return curry(function (a, b) { + var args = _slice(arguments); + args[0] = b; + args[1] = a; + return fn.apply(this, args); + }); + }); + + /** + * Returns the first element of the given list or string. In some libraries + * this function is named `first`. + * + * @func + * @memberOf R + * @since v0.1.0 + * @category List + * @sig [a] -> a | Undefined + * @sig String -> String + * @param {Array|String} list + * @return {*} + * @see R.tail, R.init, R.last + * @example + * + * R.head(['fi', 'fo', 'fum']); //=> 'fi' + * R.head([]); //=> undefined + * + * R.head('abc'); //=> 'a' + * R.head(''); //=> '' + */ + var head = nth(0); + + /** + * Returns all but the last element of the given list or string. + * + * @func + * @memberOf R + * @since v0.9.0 + * @category List + * @sig [a] -> [a] + * @sig String -> String + * @param {*} list + * @return {*} + * @see R.last, R.head, R.tail + * @example + * + * R.init([1, 2, 3]); //=> [1, 2] + * R.init([1, 2]); //=> [1] + * R.init([1]); //=> [] + * R.init([]); //=> [] + * + * R.init('abc'); //=> 'ab' + * R.init('ab'); //=> 'a' + * R.init('a'); //=> '' + * R.init(''); //=> '' + */ + var init = slice(0, -1); + + /** + * Combines two lists into a set (i.e. no duplicates) composed of those + * elements common to both lists. Duplication is determined according to the + * value returned by applying the supplied predicate to two list elements. + * + * @func + * @memberOf R + * @since v0.1.0 + * @category Relation + * @sig (a -> a -> Boolean) -> [*] -> [*] -> [*] + * @param {Function} pred A predicate function that determines whether + * the two supplied elements are equal. + * @param {Array} list1 One list of items to compare + * @param {Array} list2 A second list of items to compare + * @return {Array} A new list containing those elements common to both lists. + * @see R.intersection + * @example + * + * var buffaloSpringfield = [ + * {id: 824, name: 'Richie Furay'}, + * {id: 956, name: 'Dewey Martin'}, + * {id: 313, name: 'Bruce Palmer'}, + * {id: 456, name: 'Stephen Stills'}, + * {id: 177, name: 'Neil Young'} + * ]; + * var csny = [ + * {id: 204, name: 'David Crosby'}, + * {id: 456, name: 'Stephen Stills'}, + * {id: 539, name: 'Graham Nash'}, + * {id: 177, name: 'Neil Young'} + * ]; + * + * R.intersectionWith(R.eqBy(R.prop('id')), buffaloSpringfield, csny); + * //=> [{id: 456, name: 'Stephen Stills'}, {id: 177, name: 'Neil Young'}] + */ + var intersectionWith = _curry3(function intersectionWith(pred, list1, list2) { + var lookupList, filteredList; + if (list1.length > list2.length) { + lookupList = list1; + filteredList = list2; + } else { + lookupList = list2; + filteredList = list1; + } + var results = []; + var idx = 0; + while (idx < filteredList.length) { + if (_containsWith(pred, filteredList[idx], lookupList)) { + results[results.length] = filteredList[idx]; + } + idx += 1; + } + return uniqWith(pred, results); + }); + + /** + * Transforms the items of the list with the transducer and appends the + * transformed items to the accumulator using an appropriate iterator function + * based on the accumulator type. + * + * The accumulator can be an array, string, object or a transformer. Iterated + * items will be appended to arrays and concatenated to strings. Objects will + * be merged directly or 2-item arrays will be merged as key, value pairs. + * + * The accumulator can also be a transformer object that provides a 2-arity + * reducing iterator function, step, 0-arity initial value function, init, and + * 1-arity result extraction function result. The step function is used as the + * iterator function in reduce. The result function is used to convert the + * final accumulator into the return type and in most cases is R.identity. The + * init function is used to provide the initial accumulator. + * + * The iteration is performed with R.reduce after initializing the transducer. + * + * @func + * @memberOf R + * @since v0.12.0 + * @category List + * @sig a -> (b -> b) -> [c] -> a + * @param {*} acc The initial accumulator value. + * @param {Function} xf The transducer function. Receives a transformer and returns a transformer. + * @param {Array} list The list to iterate over. + * @return {*} The final, accumulated value. + * @example + * + * var numbers = [1, 2, 3, 4]; + * var transducer = R.compose(R.map(R.add(1)), R.take(2)); + * + * R.into([], transducer, numbers); //=> [2, 3] + * + * var intoArray = R.into([]); + * intoArray(transducer, numbers); //=> [2, 3] + */ + var into = _curry3(function into(acc, xf, list) { + return _isTransformer(acc) ? _reduce(xf(acc), acc['@@transducer/init'](), list) : _reduce(xf(_stepCat(acc)), _clone(acc, [], [], false), list); + }); + + /** + * Same as R.invertObj, however this accounts for objects with duplicate values + * by putting the values into an array. + * + * @func + * @memberOf R + * @since v0.9.0 + * @category Object + * @sig {s: x} -> {x: [ s, ... ]} + * @param {Object} obj The object or array to invert + * @return {Object} out A new object with keys + * in an array. + * @example + * + * var raceResultsByFirstName = { + * first: 'alice', + * second: 'jake', + * third: 'alice', + * }; + * R.invert(raceResultsByFirstName); + * //=> { 'alice': ['first', 'third'], 'jake':['second'] } + */ + var invert = _curry1(function invert(obj) { + var props = keys(obj); + var len = props.length; + var idx = 0; + var out = {}; + while (idx < len) { + var key = props[idx]; + var val = obj[key]; + var list = _has(val, out) ? out[val] : out[val] = []; + list[list.length] = key; + idx += 1; + } + return out; + }); + + /** + * Returns a new object with the keys of the given object as values, and the + * values of the given object, which are coerced to strings, as keys. Note + * that the last key found is preferred when handling the same value. + * + * @func + * @memberOf R + * @since v0.9.0 + * @category Object + * @sig {s: x} -> {x: s} + * @param {Object} obj The object or array to invert + * @return {Object} out A new object + * @example + * + * var raceResults = { + * first: 'alice', + * second: 'jake' + * }; + * R.invertObj(raceResults); + * //=> { 'alice': 'first', 'jake':'second' } + * + * // Alternatively: + * var raceResults = ['alice', 'jake']; + * R.invertObj(raceResults); + * //=> { 'alice': '0', 'jake':'1' } + */ + var invertObj = _curry1(function invertObj(obj) { + var props = keys(obj); + var len = props.length; + var idx = 0; + var out = {}; + while (idx < len) { + var key = props[idx]; + out[obj[key]] = key; + idx += 1; + } + return out; + }); + + /** + * Returns `true` if the given value is its type's empty value; `false` + * otherwise. + * + * @func + * @memberOf R + * @since v0.1.0 + * @category Logic + * @sig a -> Boolean + * @param {*} x + * @return {Boolean} + * @see R.empty + * @example + * + * R.isEmpty([1, 2, 3]); //=> false + * R.isEmpty([]); //=> true + * R.isEmpty(''); //=> true + * R.isEmpty(null); //=> false + * R.isEmpty({}); //=> true + * R.isEmpty({length: 0}); //=> false + */ + var isEmpty = _curry1(function isEmpty(x) { + return x != null && equals(x, empty(x)); + }); + + /** + * Returns the last element of the given list or string. + * + * @func + * @memberOf R + * @since v0.1.4 + * @category List + * @sig [a] -> a | Undefined + * @sig String -> String + * @param {*} list + * @return {*} + * @see R.init, R.head, R.tail + * @example + * + * R.last(['fi', 'fo', 'fum']); //=> 'fum' + * R.last([]); //=> undefined + * + * R.last('abc'); //=> 'c' + * R.last(''); //=> '' + */ + var last = nth(-1); + + /** + * Returns the position of the last occurrence of an item in an array, or -1 if + * the item is not included in the array. `R.equals` is used to determine + * equality. + * + * @func + * @memberOf R + * @since v0.1.0 + * @category List + * @sig a -> [a] -> Number + * @param {*} target The item to find. + * @param {Array} xs The array to search in. + * @return {Number} the index of the target, or -1 if the target is not found. + * @see R.indexOf + * @example + * + * R.lastIndexOf(3, [-1,3,3,0,1,2,3,4]); //=> 6 + * R.lastIndexOf(10, [1,2,3,4]); //=> -1 + */ + var lastIndexOf = _curry2(function lastIndexOf(target, xs) { + if (typeof xs.lastIndexOf === 'function' && !_isArray(xs)) { + return xs.lastIndexOf(target); + } else { + var idx = xs.length - 1; + while (idx >= 0) { + if (equals(xs[idx], target)) { + return idx; + } + idx -= 1; + } + return -1; + } + }); + + /** + * Takes a function and + * a [functor](https://github.com/fantasyland/fantasy-land#functor), + * applies the function to each of the functor's values, and returns + * a functor of the same shape. + * + * Ramda provides suitable `map` implementations for `Array` and `Object`, + * so this function may be applied to `[1, 2, 3]` or `{x: 1, y: 2, z: 3}`. + * + * Dispatches to the `map` method of the second argument, if present. + * + * Acts as a transducer if a transformer is given in list position. + * + * Also treats functions as functors and will compose them together. + * + * @func + * @memberOf R + * @since v0.1.0 + * @category List + * @sig Functor f => (a -> b) -> f a -> f b + * @param {Function} fn The function to be called on every element of the input `list`. + * @param {Array} list The list to be iterated over. + * @return {Array} The new list. + * @see R.transduce, R.addIndex + * @example + * + * var double = x => x * 2; + * + * R.map(double, [1, 2, 3]); //=> [2, 4, 6] + * + * R.map(double, {x: 1, y: 2, z: 3}); //=> {x: 2, y: 4, z: 6} + */ + var map = _curry2(_dispatchable('map', _xmap, function map(fn, functor) { + switch (Object.prototype.toString.call(functor)) { + case '[object Function]': + return curryN(functor.length, function () { + return fn.call(this, functor.apply(this, arguments)); + }); + case '[object Object]': + return _reduce(function (acc, key) { + acc[key] = fn(functor[key]); + return acc; + }, {}, keys(functor)); + default: + return _map(fn, functor); + } + })); + + /** + * An Object-specific version of `map`. The function is applied to three + * arguments: *(value, key, obj)*. If only the value is significant, use + * `map` instead. + * + * @func + * @memberOf R + * @since v0.9.0 + * @category Object + * @sig ((*, String, Object) -> *) -> Object -> Object + * @param {Function} fn + * @param {Object} obj + * @return {Object} + * @see R.map + * @example + * + * var values = { x: 1, y: 2, z: 3 }; + * var prependKeyAndDouble = (num, key, obj) => key + (num * 2); + * + * R.mapObjIndexed(prependKeyAndDouble, values); //=> { x: 'x2', y: 'y4', z: 'z6' } + */ + var mapObjIndexed = _curry2(function mapObjIndexed(fn, obj) { + return _reduce(function (acc, key) { + acc[key] = fn(obj[key], key, obj); + return acc; + }, {}, keys(obj)); + }); + + /** + * Creates a new object with the own properties of the two provided objects. If + * a key exists in both objects, the provided function is applied to the values + * associated with the key in each object, with the result being used as the + * value associated with the key in the returned object. The key will be + * excluded from the returned object if the resulting value is `undefined`. + * + * @func + * @memberOf R + * @since v0.19.0 + * @category Object + * @sig (a -> a -> a) -> {a} -> {a} -> {a} + * @param {Function} fn + * @param {Object} l + * @param {Object} r + * @return {Object} + * @see R.merge, R.mergeWithKey + * @example + * + * R.mergeWith(R.concat, + * { a: true, values: [10, 20] }, + * { b: true, values: [15, 35] }); + * //=> { a: true, b: true, values: [10, 20, 15, 35] } + */ + var mergeWith = _curry3(function mergeWith(fn, l, r) { + return mergeWithKey(function (_, _l, _r) { + return fn(_l, _r); + }, l, r); + }); + + /** + * Takes a function `f` and a list of arguments, and returns a function `g`. + * When applied, `g` returns the result of applying `f` to the arguments + * provided initially followed by the arguments provided to `g`. + * + * @func + * @memberOf R + * @since v0.10.0 + * @category Function + * @sig ((a, b, c, ..., n) -> x) -> [a, b, c, ...] -> ((d, e, f, ..., n) -> x) + * @param {Function} f + * @param {Array} args + * @return {Function} + * @see R.partialRight + * @example + * + * var multiply = (a, b) => a * b; + * var double = R.partial(multiply, [2]); + * double(2); //=> 4 + * + * var greet = (salutation, title, firstName, lastName) => + * salutation + ', ' + title + ' ' + firstName + ' ' + lastName + '!'; + * + * var sayHello = R.partial(greet, ['Hello']); + * var sayHelloToMs = R.partial(sayHello, ['Ms.']); + * sayHelloToMs('Jane', 'Jones'); //=> 'Hello, Ms. Jane Jones!' + */ + var partial = _createPartialApplicator(_concat); + + /** + * Takes a function `f` and a list of arguments, and returns a function `g`. + * When applied, `g` returns the result of applying `f` to the arguments + * provided to `g` followed by the arguments provided initially. + * + * @func + * @memberOf R + * @since v0.10.0 + * @category Function + * @sig ((a, b, c, ..., n) -> x) -> [d, e, f, ..., n] -> ((a, b, c, ...) -> x) + * @param {Function} f + * @param {Array} args + * @return {Function} + * @see R.partial + * @example + * + * var greet = (salutation, title, firstName, lastName) => + * salutation + ', ' + title + ' ' + firstName + ' ' + lastName + '!'; + * + * var greetMsJaneJones = R.partialRight(greet, ['Ms.', 'Jane', 'Jones']); + * + * greetMsJaneJones('Hello'); //=> 'Hello, Ms. Jane Jones!' + */ + var partialRight = _createPartialApplicator(flip(_concat)); + + /** + * Determines whether a nested path on an object has a specific value, in + * `R.equals` terms. Most likely used to filter a list. + * + * @func + * @memberOf R + * @since v0.7.0 + * @category Relation + * @sig [String] -> * -> {String: *} -> Boolean + * @param {Array} path The path of the nested property to use + * @param {*} val The value to compare the nested property with + * @param {Object} obj The object to check the nested property in + * @return {Boolean} `true` if the value equals the nested object property, + * `false` otherwise. + * @example + * + * var user1 = { address: { zipCode: 90210 } }; + * var user2 = { address: { zipCode: 55555 } }; + * var user3 = { name: 'Bob' }; + * var users = [ user1, user2, user3 ]; + * var isFamous = R.pathEq(['address', 'zipCode'], 90210); + * R.filter(isFamous, users); //=> [ user1 ] + */ + var pathEq = _curry3(function pathEq(_path, val, obj) { + return equals(path(_path, obj), val); + }); + + /** + * Returns a new list by plucking the same named property off all objects in + * the list supplied. + * + * @func + * @memberOf R + * @since v0.1.0 + * @category List + * @sig k -> [{k: v}] -> [v] + * @param {Number|String} key The key name to pluck off of each object. + * @param {Array} list The array to consider. + * @return {Array} The list of values for the given key. + * @see R.props + * @example + * + * R.pluck('a')([{a: 1}, {a: 2}]); //=> [1, 2] + * R.pluck(0)([[1, 2], [3, 4]]); //=> [1, 3] + */ + var pluck = _curry2(function pluck(p, list) { + return map(prop(p), list); + }); + + /** + * Reasonable analog to SQL `select` statement. + * + * @func + * @memberOf R + * @since v0.1.0 + * @category Object + * @category Relation + * @sig [k] -> [{k: v}] -> [{k: v}] + * @param {Array} props The property names to project + * @param {Array} objs The objects to query + * @return {Array} An array of objects with just the `props` properties. + * @example + * + * var abby = {name: 'Abby', age: 7, hair: 'blond', grade: 2}; + * var fred = {name: 'Fred', age: 12, hair: 'brown', grade: 7}; + * var kids = [abby, fred]; + * R.project(['name', 'grade'], kids); //=> [{name: 'Abby', grade: 2}, {name: 'Fred', grade: 7}] + */ + // passing `identity` gives correct arity + var project = useWith(_map, [ + pickAll, + identity + ]); + + /** + * Returns `true` if the specified object property is equal, in `R.equals` + * terms, to the given value; `false` otherwise. + * + * @func + * @memberOf R + * @since v0.1.0 + * @category Relation + * @sig String -> a -> Object -> Boolean + * @param {String} name + * @param {*} val + * @param {*} obj + * @return {Boolean} + * @see R.equals, R.propSatisfies + * @example + * + * var abby = {name: 'Abby', age: 7, hair: 'blond'}; + * var fred = {name: 'Fred', age: 12, hair: 'brown'}; + * var rusty = {name: 'Rusty', age: 10, hair: 'brown'}; + * var alois = {name: 'Alois', age: 15, disposition: 'surly'}; + * var kids = [abby, fred, rusty, alois]; + * var hasBrownHair = R.propEq('hair', 'brown'); + * R.filter(hasBrownHair, kids); //=> [fred, rusty] + */ + var propEq = _curry3(function propEq(name, val, obj) { + return equals(val, obj[name]); + }); + + /** + * Returns a single item by iterating through the list, successively calling + * the iterator function and passing it an accumulator value and the current + * value from the array, and then passing the result to the next call. + * + * The iterator function receives two values: *(acc, value)*. It may use + * `R.reduced` to shortcut the iteration. + * + * Note: `R.reduce` does not skip deleted or unassigned indices (sparse + * arrays), unlike the native `Array.prototype.reduce` method. For more details + * on this behavior, see: + * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce#Description + * + * Dispatches to the `reduce` method of the third argument, if present. + * + * @func + * @memberOf R + * @since v0.1.0 + * @category List + * @sig ((a, b) -> a) -> a -> [b] -> a + * @param {Function} fn The iterator function. Receives two values, the accumulator and the + * current element from the array. + * @param {*} acc The accumulator value. + * @param {Array} list The list to iterate over. + * @return {*} The final, accumulated value. + * @see R.reduced, R.addIndex + * @example + * + * var numbers = [1, 2, 3]; + * var plus = (a, b) => a + b; + * + * R.reduce(plus, 10, numbers); //=> 16 + */ + var reduce = _curry3(_reduce); + + /** + * Groups the elements of the list according to the result of calling + * the String-returning function `keyFn` on each element and reduces the elements + * of each group to a single value via the reducer function `valueFn`. + * + * This function is basically a more general `groupBy` function. + * + * Acts as a transducer if a transformer is given in list position. + * + * @func + * @memberOf R + * @since v0.20.0 + * @category List + * @sig ((a, b) -> a) -> a -> (b -> String) -> [b] -> {String: a} + * @param {Function} valueFn The function that reduces the elements of each group to a single + * value. Receives two values, accumulator for a particular group and the current element. + * @param {*} acc The (initial) accumulator value for each group. + * @param {Function} keyFn The function that maps the list's element into a key. + * @param {Array} list The array to group. + * @return {Object} An object with the output of `keyFn` for keys, mapped to the output of + * `valueFn` for elements which produced that key when passed to `keyFn`. + * @see R.groupBy, R.reduce + * @example + * + * var reduceToNamesBy = R.reduceBy((acc, student) => acc.concat(student.name), []); + * var namesByGrade = reduceToNamesBy(function(student) { + * var score = student.score; + * return score < 65 ? 'F' : + * score < 70 ? 'D' : + * score < 80 ? 'C' : + * score < 90 ? 'B' : 'A'; + * }); + * var students = [{name: 'Lucy', score: 92}, + * {name: 'Drew', score: 85}, + * // ... + * {name: 'Bart', score: 62}]; + * namesByGrade(students); + * // { + * // 'A': ['Lucy'], + * // 'B': ['Drew'] + * // // ..., + * // 'F': ['Bart'] + * // } + */ + var reduceBy = _curryN(4, [], _dispatchable('reduceBy', _xreduceBy, function reduceBy(valueFn, valueAcc, keyFn, list) { + return _reduce(function (acc, elt) { + var key = keyFn(elt); + acc[key] = valueFn(_has(key, acc) ? acc[key] : valueAcc, elt); + return acc; + }, {}, list); + })); + + /** + * Like `reduce`, `reduceWhile` returns a single item by iterating through + * the list, successively calling the iterator function. `reduceWhile` also + * takes a predicate that is evaluated before each step. If the predicate returns + * `false`, it "short-circuits" the iteration and returns the current value + * of the accumulator. + * + * @func + * @memberOf R + * @since v0.22.0 + * @category List + * @sig ((a, b) -> Boolean) -> ((a, b) -> a) -> a -> [b] -> a + * @param {Function} pred The predicate. It is passed the accumulator and the + * current element. + * @param {Function} fn The iterator function. Receives two values, the + * accumulator and the current element. + * @param {*} a The accumulator value. + * @param {Array} list The list to iterate over. + * @return {*} The final, accumulated value. + * @see R.reduce, R.reduced + * @example + * + * var isOdd = (acc, x) => x % 2 === 1; + * var xs = [1, 3, 5, 60, 777, 800]; + * R.reduceWhile(isOdd, R.add, 0, xs); //=> 9 + * + * var ys = [2, 4, 6] + * R.reduceWhile(isOdd, R.add, 111, ys); //=> 111 + */ + var reduceWhile = _curryN(4, [], function _reduceWhile(pred, fn, a, list) { + return _reduce(function (acc, x) { + return pred(acc, x) ? fn(acc, x) : _reduced(acc); + }, a, list); + }); + + /** + * The complement of `filter`. + * + * Acts as a transducer if a transformer is given in list position. + * + * @func + * @memberOf R + * @since v0.1.0 + * @category List + * @sig Filterable f => (a -> Boolean) -> f a -> f a + * @param {Function} pred + * @param {Array} filterable + * @return {Array} + * @see R.filter, R.transduce, R.addIndex + * @example + * + * var isOdd = (n) => n % 2 === 1; + * + * R.reject(isOdd, [1, 2, 3, 4]); //=> [2, 4] + * + * R.reject(isOdd, {a: 1, b: 2, c: 3, d: 4}); //=> {b: 2, d: 4} + */ + var reject = _curry2(function reject(pred, filterable) { + return filter(_complement(pred), filterable); + }); + + /** + * Returns a fixed list of size `n` containing a specified identical value. + * + * @func + * @memberOf R + * @since v0.1.1 + * @category List + * @sig a -> n -> [a] + * @param {*} value The value to repeat. + * @param {Number} n The desired size of the output list. + * @return {Array} A new array containing `n` `value`s. + * @example + * + * R.repeat('hi', 5); //=> ['hi', 'hi', 'hi', 'hi', 'hi'] + * + * var obj = {}; + * var repeatedObjs = R.repeat(obj, 5); //=> [{}, {}, {}, {}, {}] + * repeatedObjs[0] === repeatedObjs[1]; //=> true + */ + var repeat = _curry2(function repeat(value, n) { + return times(always(value), n); + }); + + /** + * Adds together all the elements of a list. + * + * @func + * @memberOf R + * @since v0.1.0 + * @category Math + * @sig [Number] -> Number + * @param {Array} list An array of numbers + * @return {Number} The sum of all the numbers in the list. + * @see R.reduce + * @example + * + * R.sum([2,4,6,8,100,1]); //=> 121 + */ + var sum = reduce(add, 0); + + /** + * Returns a new list containing the last `n` elements of the given list. + * If `n > list.length`, returns a list of `list.length` elements. + * + * @func + * @memberOf R + * @since v0.16.0 + * @category List + * @sig Number -> [a] -> [a] + * @sig Number -> String -> String + * @param {Number} n The number of elements to return. + * @param {Array} xs The collection to consider. + * @return {Array} + * @see R.dropLast + * @example + * + * R.takeLast(1, ['foo', 'bar', 'baz']); //=> ['baz'] + * R.takeLast(2, ['foo', 'bar', 'baz']); //=> ['bar', 'baz'] + * R.takeLast(3, ['foo', 'bar', 'baz']); //=> ['foo', 'bar', 'baz'] + * R.takeLast(4, ['foo', 'bar', 'baz']); //=> ['foo', 'bar', 'baz'] + * R.takeLast(3, 'ramda'); //=> 'mda' + */ + var takeLast = _curry2(function takeLast(n, xs) { + return drop(n >= 0 ? xs.length - n : 0, xs); + }); + + /** + * Initializes a transducer using supplied iterator function. Returns a single + * item by iterating through the list, successively calling the transformed + * iterator function and passing it an accumulator value and the current value + * from the array, and then passing the result to the next call. + * + * The iterator function receives two values: *(acc, value)*. It will be + * wrapped as a transformer to initialize the transducer. A transformer can be + * passed directly in place of an iterator function. In both cases, iteration + * may be stopped early with the `R.reduced` function. + * + * A transducer is a function that accepts a transformer and returns a + * transformer and can be composed directly. + * + * A transformer is an an object that provides a 2-arity reducing iterator + * function, step, 0-arity initial value function, init, and 1-arity result + * extraction function, result. The step function is used as the iterator + * function in reduce. The result function is used to convert the final + * accumulator into the return type and in most cases is R.identity. The init + * function can be used to provide an initial accumulator, but is ignored by + * transduce. + * + * The iteration is performed with R.reduce after initializing the transducer. + * + * @func + * @memberOf R + * @since v0.12.0 + * @category List + * @sig (c -> c) -> (a,b -> a) -> a -> [b] -> a + * @param {Function} xf The transducer function. Receives a transformer and returns a transformer. + * @param {Function} fn The iterator function. Receives two values, the accumulator and the + * current element from the array. Wrapped as transformer, if necessary, and used to + * initialize the transducer + * @param {*} acc The initial accumulator value. + * @param {Array} list The list to iterate over. + * @return {*} The final, accumulated value. + * @see R.reduce, R.reduced, R.into + * @example + * + * var numbers = [1, 2, 3, 4]; + * var transducer = R.compose(R.map(R.add(1)), R.take(2)); + * + * R.transduce(transducer, R.flip(R.append), [], numbers); //=> [2, 3] + */ + var transduce = curryN(4, function transduce(xf, fn, acc, list) { + return _reduce(xf(typeof fn === 'function' ? _xwrap(fn) : fn), acc, list); + }); + + /** + * Combines two lists into a set (i.e. no duplicates) composed of the elements + * of each list. Duplication is determined according to the value returned by + * applying the supplied predicate to two list elements. + * + * @func + * @memberOf R + * @since v0.1.0 + * @category Relation + * @sig (a -> a -> Boolean) -> [*] -> [*] -> [*] + * @param {Function} pred A predicate used to test whether two items are equal. + * @param {Array} list1 The first list. + * @param {Array} list2 The second list. + * @return {Array} The first and second lists concatenated, with + * duplicates removed. + * @see R.union + * @example + * + * var l1 = [{a: 1}, {a: 2}]; + * var l2 = [{a: 1}, {a: 4}]; + * R.unionWith(R.eqBy(R.prop('a')), l1, l2); //=> [{a: 1}, {a: 2}, {a: 4}] + */ + var unionWith = _curry3(function unionWith(pred, list1, list2) { + return uniqWith(pred, _concat(list1, list2)); + }); + + /** + * Takes a spec object and a test object; returns true if the test satisfies + * the spec, false otherwise. An object satisfies the spec if, for each of the + * spec's own properties, accessing that property of the object gives the same + * value (in `R.equals` terms) as accessing that property of the spec. + * + * `whereEq` is a specialization of [`where`](#where). + * + * @func + * @memberOf R + * @since v0.14.0 + * @category Object + * @sig {String: *} -> {String: *} -> Boolean + * @param {Object} spec + * @param {Object} testObj + * @return {Boolean} + * @see R.where + * @example + * + * // pred :: Object -> Boolean + * var pred = R.whereEq({a: 1, b: 2}); + * + * pred({a: 1}); //=> false + * pred({a: 1, b: 2}); //=> true + * pred({a: 1, b: 2, c: 3}); //=> true + * pred({a: 1, b: 1}); //=> false + */ + var whereEq = _curry2(function whereEq(spec, testObj) { + return where(map(equals, spec), testObj); + }); + + var _flatCat = function () { + var preservingReduced = function (xf) { + return { + '@@transducer/init': _xfBase.init, + '@@transducer/result': function (result) { + return xf['@@transducer/result'](result); + }, + '@@transducer/step': function (result, input) { + var ret = xf['@@transducer/step'](result, input); + return ret['@@transducer/reduced'] ? _forceReduced(ret) : ret; + } + }; + }; + return function _xcat(xf) { + var rxf = preservingReduced(xf); + return { + '@@transducer/init': _xfBase.init, + '@@transducer/result': function (result) { + return rxf['@@transducer/result'](result); + }, + '@@transducer/step': function (result, input) { + return !isArrayLike(input) ? _reduce(rxf, result, [input]) : _reduce(rxf, result, input); + } + }; + }; + }(); + + // Array.prototype.indexOf doesn't exist below IE9 + // manually crawl the list to distinguish between +0 and -0 + // NaN + // non-zero numbers can utilise Set + // all these types can utilise Set + // null can utilise Set + // anything else not covered above, defer to R.equals + var _indexOf = function _indexOf(list, a, idx) { + var inf, item; + // Array.prototype.indexOf doesn't exist below IE9 + if (typeof list.indexOf === 'function') { + switch (typeof a) { + case 'number': + if (a === 0) { + // manually crawl the list to distinguish between +0 and -0 + inf = 1 / a; + while (idx < list.length) { + item = list[idx]; + if (item === 0 && 1 / item === inf) { + return idx; + } + idx += 1; + } + return -1; + } else if (a !== a) { + // NaN + while (idx < list.length) { + item = list[idx]; + if (typeof item === 'number' && item !== item) { + return idx; + } + idx += 1; + } + return -1; + } + // non-zero numbers can utilise Set + return list.indexOf(a, idx); + // all these types can utilise Set + case 'string': + case 'boolean': + case 'function': + case 'undefined': + return list.indexOf(a, idx); + case 'object': + if (a === null) { + // null can utilise Set + return list.indexOf(a, idx); + } + } + } + // anything else not covered above, defer to R.equals + while (idx < list.length) { + if (equals(list[idx], a)) { + return idx; + } + idx += 1; + } + return -1; + }; + + var _xchain = _curry2(function _xchain(f, xf) { + return map(f, _flatCat(xf)); + }); + + /** + * Takes a list of predicates and returns a predicate that returns true for a + * given list of arguments if every one of the provided predicates is satisfied + * by those arguments. + * + * The function returned is a curried function whose arity matches that of the + * highest-arity predicate. + * + * @func + * @memberOf R + * @since v0.9.0 + * @category Logic + * @sig [(*... -> Boolean)] -> (*... -> Boolean) + * @param {Array} preds + * @return {Function} + * @see R.anyPass + * @example + * + * var isQueen = R.propEq('rank', 'Q'); + * var isSpade = R.propEq('suit', '♠︎'); + * var isQueenOfSpades = R.allPass([isQueen, isSpade]); + * + * isQueenOfSpades({rank: 'Q', suit: '♣︎'}); //=> false + * isQueenOfSpades({rank: 'Q', suit: '♠︎'}); //=> true + */ + var allPass = _curry1(function allPass(preds) { + return curryN(reduce(max, 0, pluck('length', preds)), function () { + var idx = 0; + var len = preds.length; + while (idx < len) { + if (!preds[idx].apply(this, arguments)) { + return false; + } + idx += 1; + } + return true; + }); + }); + + /** + * Takes a list of predicates and returns a predicate that returns true for a + * given list of arguments if at least one of the provided predicates is + * satisfied by those arguments. + * + * The function returned is a curried function whose arity matches that of the + * highest-arity predicate. + * + * @func + * @memberOf R + * @since v0.9.0 + * @category Logic + * @sig [(*... -> Boolean)] -> (*... -> Boolean) + * @param {Array} preds + * @return {Function} + * @see R.allPass + * @example + * + * var gte = R.anyPass([R.gt, R.equals]); + * + * gte(3, 2); //=> true + * gte(2, 2); //=> true + * gte(2, 3); //=> false + */ + var anyPass = _curry1(function anyPass(preds) { + return curryN(reduce(max, 0, pluck('length', preds)), function () { + var idx = 0; + var len = preds.length; + while (idx < len) { + if (preds[idx].apply(this, arguments)) { + return true; + } + idx += 1; + } + return false; + }); + }); + + /** + * ap applies a list of functions to a list of values. + * + * Dispatches to the `ap` method of the second argument, if present. Also + * treats curried functions as applicatives. + * + * @func + * @memberOf R + * @since v0.3.0 + * @category Function + * @sig [a -> b] -> [a] -> [b] + * @sig Apply f => f (a -> b) -> f a -> f b + * @param {Array} fns An array of functions + * @param {Array} vs An array of values + * @return {Array} An array of results of applying each of `fns` to all of `vs` in turn. + * @example + * + * R.ap([R.multiply(2), R.add(3)], [1,2,3]); //=> [2, 4, 6, 4, 5, 6] + */ + // else + var ap = _curry2(function ap(applicative, fn) { + return typeof applicative.ap === 'function' ? applicative.ap(fn) : typeof applicative === 'function' ? function (x) { + return applicative(x)(fn(x)); + } : // else + _reduce(function (acc, f) { + return _concat(acc, map(f, fn)); + }, [], applicative); + }); + + /** + * Given a spec object recursively mapping properties to functions, creates a + * function producing an object of the same structure, by mapping each property + * to the result of calling its associated function with the supplied arguments. + * + * @func + * @memberOf R + * @since v0.20.0 + * @category Function + * @sig {k: ((a, b, ..., m) -> v)} -> ((a, b, ..., m) -> {k: v}) + * @param {Object} spec an object recursively mapping properties to functions for + * producing the values for these properties. + * @return {Function} A function that returns an object of the same structure + * as `spec', with each property set to the value returned by calling its + * associated function with the supplied arguments. + * @see R.converge, R.juxt + * @example + * + * var getMetrics = R.applySpec({ + * sum: R.add, + * nested: { mul: R.multiply } + * }); + * getMetrics(2, 4); // => { sum: 6, nested: { mul: 8 } } + */ + var applySpec = _curry1(function applySpec(spec) { + spec = map(function (v) { + return typeof v == 'function' ? v : applySpec(v); + }, spec); + return curryN(reduce(max, 0, pluck('length', values(spec))), function () { + var args = arguments; + return map(function (f) { + return apply(f, args); + }, spec); + }); + }); + + /** + * Returns the result of calling its first argument with the remaining + * arguments. This is occasionally useful as a converging function for + * `R.converge`: the left branch can produce a function while the right branch + * produces a value to be passed to that function as an argument. + * + * @func + * @memberOf R + * @since v0.9.0 + * @category Function + * @sig (*... -> a),*... -> a + * @param {Function} fn The function to apply to the remaining arguments. + * @param {...*} args Any number of positional arguments. + * @return {*} + * @see R.apply + * @example + * + * var indentN = R.pipe(R.times(R.always(' ')), + * R.join(''), + * R.replace(/^(?!$)/gm)); + * + * var format = R.converge(R.call, [ + * R.pipe(R.prop('indent'), indentN), + * R.prop('value') + * ]); + * + * format({indent: 2, value: 'foo\nbar\nbaz\n'}); //=> ' foo\n bar\n baz\n' + */ + var call = curry(function call(fn) { + return fn.apply(this, _slice(arguments, 1)); + }); + + /** + * `chain` maps a function over a list and concatenates the results. `chain` + * is also known as `flatMap` in some libraries + * + * Dispatches to the `chain` method of the second argument, if present, + * according to the [FantasyLand Chain spec](https://github.com/fantasyland/fantasy-land#chain). + * + * @func + * @memberOf R + * @since v0.3.0 + * @category List + * @sig Chain m => (a -> m b) -> m a -> m b + * @param {Function} fn + * @param {Array} list + * @return {Array} + * @example + * + * var duplicate = n => [n, n]; + * R.chain(duplicate, [1, 2, 3]); //=> [1, 1, 2, 2, 3, 3] + */ + var chain = _curry2(_dispatchable('chain', _xchain, function chain(fn, monad) { + if (typeof monad === 'function') { + return function () { + return monad.call(this, fn.apply(this, arguments)).apply(this, arguments); + }; + } + return _makeFlat(false)(map(fn, monad)); + })); + + /** + * Returns a function, `fn`, which encapsulates if/else-if/else logic. + * `R.cond` takes a list of [predicate, transform] pairs. All of the arguments + * to `fn` are applied to each of the predicates in turn until one returns a + * "truthy" value, at which point `fn` returns the result of applying its + * arguments to the corresponding transformer. If none of the predicates + * matches, `fn` returns undefined. + * + * @func + * @memberOf R + * @since v0.6.0 + * @category Logic + * @sig [[(*... -> Boolean),(*... -> *)]] -> (*... -> *) + * @param {Array} pairs + * @return {Function} + * @example + * + * var fn = R.cond([ + * [R.equals(0), R.always('water freezes at 0°C')], + * [R.equals(100), R.always('water boils at 100°C')], + * [R.T, temp => 'nothing special happens at ' + temp + '°C'] + * ]); + * fn(0); //=> 'water freezes at 0°C' + * fn(50); //=> 'nothing special happens at 50°C' + * fn(100); //=> 'water boils at 100°C' + */ + var cond = _curry1(function cond(pairs) { + var arity = reduce(max, 0, map(function (pair) { + return pair[0].length; + }, pairs)); + return _arity(arity, function () { + var idx = 0; + while (idx < pairs.length) { + if (pairs[idx][0].apply(this, arguments)) { + return pairs[idx][1].apply(this, arguments); + } + idx += 1; + } + }); + }); + + /** + * Wraps a constructor function inside a curried function that can be called + * with the same arguments and returns the same type. The arity of the function + * returned is specified to allow using variadic constructor functions. + * + * @func + * @memberOf R + * @since v0.4.0 + * @category Function + * @sig Number -> (* -> {*}) -> (* -> {*}) + * @param {Number} n The arity of the constructor function. + * @param {Function} Fn The constructor function to wrap. + * @return {Function} A wrapped, curried constructor function. + * @example + * + * // Variadic constructor function + * var Widget = () => { + * this.children = Array.prototype.slice.call(arguments); + * // ... + * }; + * Widget.prototype = { + * // ... + * }; + * var allConfigs = [ + * // ... + * ]; + * R.map(R.constructN(1, Widget), allConfigs); // a list of Widgets + */ + var constructN = _curry2(function constructN(n, Fn) { + if (n > 10) { + throw new Error('Constructor with greater than ten arguments'); + } + if (n === 0) { + return function () { + return new Fn(); + }; + } + return curry(nAry(n, function ($0, $1, $2, $3, $4, $5, $6, $7, $8, $9) { + switch (arguments.length) { + case 1: + return new Fn($0); + case 2: + return new Fn($0, $1); + case 3: + return new Fn($0, $1, $2); + case 4: + return new Fn($0, $1, $2, $3); + case 5: + return new Fn($0, $1, $2, $3, $4); + case 6: + return new Fn($0, $1, $2, $3, $4, $5); + case 7: + return new Fn($0, $1, $2, $3, $4, $5, $6); + case 8: + return new Fn($0, $1, $2, $3, $4, $5, $6, $7); + case 9: + return new Fn($0, $1, $2, $3, $4, $5, $6, $7, $8); + case 10: + return new Fn($0, $1, $2, $3, $4, $5, $6, $7, $8, $9); + } + })); + }); + + /** + * Accepts a converging function and a list of branching functions and returns + * a new function. When invoked, this new function is applied to some + * arguments, each branching function is applied to those same arguments. The + * results of each branching function are passed as arguments to the converging + * function to produce the return value. + * + * @func + * @memberOf R + * @since v0.4.2 + * @category Function + * @sig (x1 -> x2 -> ... -> z) -> [(a -> b -> ... -> x1), (a -> b -> ... -> x2), ...] -> (a -> b -> ... -> z) + * @param {Function} after A function. `after` will be invoked with the return values of + * `fn1` and `fn2` as its arguments. + * @param {Array} functions A list of functions. + * @return {Function} A new function. + * @example + * + * var add = (a, b) => a + b; + * var multiply = (a, b) => a * b; + * var subtract = (a, b) => a - b; + * + * //≅ multiply( add(1, 2), subtract(1, 2) ); + * R.converge(multiply, [add, subtract])(1, 2); //=> -3 + * + * var add3 = (a, b, c) => a + b + c; + * R.converge(add3, [multiply, add, subtract])(1, 2); //=> 4 + */ + var converge = _curry2(function converge(after, fns) { + return curryN(reduce(max, 0, pluck('length', fns)), function () { + var args = arguments; + var context = this; + return after.apply(context, _map(function (fn) { + return fn.apply(context, args); + }, fns)); + }); + }); + + /** + * Counts the elements of a list according to how many match each value of a + * key generated by the supplied function. Returns an object mapping the keys + * produced by `fn` to the number of occurrences in the list. Note that all + * keys are coerced to strings because of how JavaScript objects work. + * + * Acts as a transducer if a transformer is given in list position. + * + * @func + * @memberOf R + * @since v0.1.0 + * @category Relation + * @sig (a -> String) -> [a] -> {*} + * @param {Function} fn The function used to map values to keys. + * @param {Array} list The list to count elements from. + * @return {Object} An object mapping keys to number of occurrences in the list. + * @example + * + * var numbers = [1.0, 1.1, 1.2, 2.0, 3.0, 2.2]; + * var letters = R.split('', 'abcABCaaaBBc'); + * R.countBy(Math.floor)(numbers); //=> {'1': 3, '2': 2, '3': 1} + * R.countBy(R.toLower)(letters); //=> {'a': 5, 'b': 4, 'c': 3} + */ + var countBy = reduceBy(function (acc, elem) { + return acc + 1; + }, 0); + + /** + * Returns a new list without any consecutively repeating elements. Equality is + * determined by applying the supplied predicate two consecutive elements. The + * first element in a series of equal element is the one being preserved. + * + * Dispatches to the `dropRepeatsWith` method of the second argument, if present. + * + * Acts as a transducer if a transformer is given in list position. + * + * @func + * @memberOf R + * @since v0.14.0 + * @category List + * @sig (a, a -> Boolean) -> [a] -> [a] + * @param {Function} pred A predicate used to test whether two items are equal. + * @param {Array} list The array to consider. + * @return {Array} `list` without repeating elements. + * @see R.transduce + * @example + * + * var l = [1, -1, 1, 3, 4, -4, -4, -5, 5, 3, 3]; + * R.dropRepeatsWith(R.eqBy(Math.abs), l); //=> [1, 3, 4, -5, 3] + */ + var dropRepeatsWith = _curry2(_dispatchable('dropRepeatsWith', _xdropRepeatsWith, function dropRepeatsWith(pred, list) { + var result = []; + var idx = 1; + var len = list.length; + if (len !== 0) { + result[0] = list[0]; + while (idx < len) { + if (!pred(last(result), list[idx])) { + result[result.length] = list[idx]; + } + idx += 1; + } + } + return result; + })); + + /** + * Takes a function and two values in its domain and returns `true` if the + * values map to the same value in the codomain; `false` otherwise. + * + * @func + * @memberOf R + * @since v0.18.0 + * @category Relation + * @sig (a -> b) -> a -> a -> Boolean + * @param {Function} f + * @param {*} x + * @param {*} y + * @return {Boolean} + * @example + * + * R.eqBy(Math.abs, 5, -5); //=> true + */ + var eqBy = _curry3(function eqBy(f, x, y) { + return equals(f(x), f(y)); + }); + + /** + * Reports whether two objects have the same value, in `R.equals` terms, for + * the specified property. Useful as a curried predicate. + * + * @func + * @memberOf R + * @since v0.1.0 + * @category Object + * @sig k -> {k: v} -> {k: v} -> Boolean + * @param {String} prop The name of the property to compare + * @param {Object} obj1 + * @param {Object} obj2 + * @return {Boolean} + * + * @example + * + * var o1 = { a: 1, b: 2, c: 3, d: 4 }; + * var o2 = { a: 10, b: 20, c: 3, d: 40 }; + * R.eqProps('a', o1, o2); //=> false + * R.eqProps('c', o1, o2); //=> true + */ + var eqProps = _curry3(function eqProps(prop, obj1, obj2) { + return equals(obj1[prop], obj2[prop]); + }); + + /** + * Splits a list into sub-lists stored in an object, based on the result of + * calling a String-returning function on each element, and grouping the + * results according to values returned. + * + * Dispatches to the `groupBy` method of the second argument, if present. + * + * Acts as a transducer if a transformer is given in list position. + * + * @func + * @memberOf R + * @since v0.1.0 + * @category List + * @sig (a -> String) -> [a] -> {String: [a]} + * @param {Function} fn Function :: a -> String + * @param {Array} list The array to group + * @return {Object} An object with the output of `fn` for keys, mapped to arrays of elements + * that produced that key when passed to `fn`. + * @see R.transduce + * @example + * + * var byGrade = R.groupBy(function(student) { + * var score = student.score; + * return score < 65 ? 'F' : + * score < 70 ? 'D' : + * score < 80 ? 'C' : + * score < 90 ? 'B' : 'A'; + * }); + * var students = [{name: 'Abby', score: 84}, + * {name: 'Eddy', score: 58}, + * // ... + * {name: 'Jack', score: 69}]; + * byGrade(students); + * // { + * // 'A': [{name: 'Dianne', score: 99}], + * // 'B': [{name: 'Abby', score: 84}] + * // // ..., + * // 'F': [{name: 'Eddy', score: 58}] + * // } + */ + var groupBy = _curry2(_checkForMethod('groupBy', reduceBy(function (acc, item) { + if (acc == null) { + acc = []; + } + acc.push(item); + return acc; + }, null))); + + /** + * Given a function that generates a key, turns a list of objects into an + * object indexing the objects by the given key. Note that if multiple + * objects generate the same value for the indexing key only the last value + * will be included in the generated object. + * + * Acts as a transducer if a transformer is given in list position. + * + * @func + * @memberOf R + * @since v0.19.0 + * @category List + * @sig (a -> String) -> [{k: v}] -> {k: {k: v}} + * @param {Function} fn Function :: a -> String + * @param {Array} array The array of objects to index + * @return {Object} An object indexing each array element by the given property. + * @example + * + * var list = [{id: 'xyz', title: 'A'}, {id: 'abc', title: 'B'}]; + * R.indexBy(R.prop('id'), list); + * //=> {abc: {id: 'abc', title: 'B'}, xyz: {id: 'xyz', title: 'A'}} + */ + var indexBy = reduceBy(function (acc, elem) { + return elem; + }, null); + + /** + * Returns the position of the first occurrence of an item in an array, or -1 + * if the item is not included in the array. `R.equals` is used to determine + * equality. + * + * @func + * @memberOf R + * @since v0.1.0 + * @category List + * @sig a -> [a] -> Number + * @param {*} target The item to find. + * @param {Array} xs The array to search in. + * @return {Number} the index of the target, or -1 if the target is not found. + * @see R.lastIndexOf + * @example + * + * R.indexOf(3, [1,2,3,4]); //=> 2 + * R.indexOf(10, [1,2,3,4]); //=> -1 + */ + var indexOf = _curry2(function indexOf(target, xs) { + return typeof xs.indexOf === 'function' && !_isArray(xs) ? xs.indexOf(target) : _indexOf(xs, target, 0); + }); + + /** + * juxt applies a list of functions to a list of values. + * + * @func + * @memberOf R + * @since v0.19.0 + * @category Function + * @sig [(a, b, ..., m) -> n] -> ((a, b, ..., m) -> [n]) + * @param {Array} fns An array of functions + * @return {Function} A function that returns a list of values after applying each of the original `fns` to its parameters. + * @see R.applySpec + * @example + * + * var getRange = R.juxt([Math.min, Math.max]); + * getRange(3, 4, 9, -3); //=> [-3, 9] + */ + var juxt = _curry1(function juxt(fns) { + return converge(_arrayOf, fns); + }); + + /** + * Returns a lens for the given getter and setter functions. The getter "gets" + * the value of the focus; the setter "sets" the value of the focus. The setter + * should not mutate the data structure. + * + * @func + * @memberOf R + * @since v0.8.0 + * @category Object + * @typedefn Lens s a = Functor f => (a -> f a) -> s -> f s + * @sig (s -> a) -> ((a, s) -> s) -> Lens s a + * @param {Function} getter + * @param {Function} setter + * @return {Lens} + * @see R.view, R.set, R.over, R.lensIndex, R.lensProp + * @example + * + * var xLens = R.lens(R.prop('x'), R.assoc('x')); + * + * R.view(xLens, {x: 1, y: 2}); //=> 1 + * R.set(xLens, 4, {x: 1, y: 2}); //=> {x: 4, y: 2} + * R.over(xLens, R.negate, {x: 1, y: 2}); //=> {x: -1, y: 2} + */ + var lens = _curry2(function lens(getter, setter) { + return function (toFunctorFn) { + return function (target) { + return map(function (focus) { + return setter(focus, target); + }, toFunctorFn(getter(target))); + }; + }; + }); + + /** + * Returns a lens whose focus is the specified index. + * + * @func + * @memberOf R + * @since v0.14.0 + * @category Object + * @typedefn Lens s a = Functor f => (a -> f a) -> s -> f s + * @sig Number -> Lens s a + * @param {Number} n + * @return {Lens} + * @see R.view, R.set, R.over + * @example + * + * var headLens = R.lensIndex(0); + * + * R.view(headLens, ['a', 'b', 'c']); //=> 'a' + * R.set(headLens, 'x', ['a', 'b', 'c']); //=> ['x', 'b', 'c'] + * R.over(headLens, R.toUpper, ['a', 'b', 'c']); //=> ['A', 'b', 'c'] + */ + var lensIndex = _curry1(function lensIndex(n) { + return lens(nth(n), update(n)); + }); + + /** + * Returns a lens whose focus is the specified path. + * + * @func + * @memberOf R + * @since v0.19.0 + * @category Object + * @typedefn Lens s a = Functor f => (a -> f a) -> s -> f s + * @sig [String] -> Lens s a + * @param {Array} path The path to use. + * @return {Lens} + * @see R.view, R.set, R.over + * @example + * + * var xyLens = R.lensPath(['x', 'y']); + * + * R.view(xyLens, {x: {y: 2, z: 3}}); //=> 2 + * R.set(xyLens, 4, {x: {y: 2, z: 3}}); //=> {x: {y: 4, z: 3}} + * R.over(xyLens, R.negate, {x: {y: 2, z: 3}}); //=> {x: {y: -2, z: 3}} + */ + var lensPath = _curry1(function lensPath(p) { + return lens(path(p), assocPath(p)); + }); + + /** + * Returns a lens whose focus is the specified property. + * + * @func + * @memberOf R + * @since v0.14.0 + * @category Object + * @typedefn Lens s a = Functor f => (a -> f a) -> s -> f s + * @sig String -> Lens s a + * @param {String} k + * @return {Lens} + * @see R.view, R.set, R.over + * @example + * + * var xLens = R.lensProp('x'); + * + * R.view(xLens, {x: 1, y: 2}); //=> 1 + * R.set(xLens, 4, {x: 1, y: 2}); //=> {x: 4, y: 2} + * R.over(xLens, R.negate, {x: 1, y: 2}); //=> {x: -1, y: 2} + */ + var lensProp = _curry1(function lensProp(k) { + return lens(prop(k), assoc(k)); + }); + + /** + * "lifts" a function to be the specified arity, so that it may "map over" that + * many lists, Functions or other objects that satisfy the [FantasyLand Apply spec](https://github.com/fantasyland/fantasy-land#apply). + * + * @func + * @memberOf R + * @since v0.7.0 + * @category Function + * @sig Number -> (*... -> *) -> ([*]... -> [*]) + * @param {Function} fn The function to lift into higher context + * @return {Function} The lifted function. + * @see R.lift, R.ap + * @example + * + * var madd3 = R.liftN(3, R.curryN(3, (...args) => R.sum(args))); + * madd3([1,2,3], [1,2,3], [1]); //=> [3, 4, 5, 4, 5, 6, 5, 6, 7] + */ + var liftN = _curry2(function liftN(arity, fn) { + var lifted = curryN(arity, fn); + return curryN(arity, function () { + return _reduce(ap, map(lifted, arguments[0]), _slice(arguments, 1)); + }); + }); + + /** + * Returns the mean of the given list of numbers. + * + * @func + * @memberOf R + * @since v0.14.0 + * @category Math + * @sig [Number] -> Number + * @param {Array} list + * @return {Number} + * @example + * + * R.mean([2, 7, 9]); //=> 6 + * R.mean([]); //=> NaN + */ + var mean = _curry1(function mean(list) { + return sum(list) / list.length; + }); + + /** + * Returns the median of the given list of numbers. + * + * @func + * @memberOf R + * @since v0.14.0 + * @category Math + * @sig [Number] -> Number + * @param {Array} list + * @return {Number} + * @example + * + * R.median([2, 9, 7]); //=> 7 + * R.median([7, 2, 10, 9]); //=> 8 + * R.median([]); //=> NaN + */ + var median = _curry1(function median(list) { + var len = list.length; + if (len === 0) { + return NaN; + } + var width = 2 - len % 2; + var idx = (len - width) / 2; + return mean(_slice(list).sort(function (a, b) { + return a < b ? -1 : a > b ? 1 : 0; + }).slice(idx, idx + width)); + }); + + /** + * Takes a predicate and a list or other "filterable" object and returns the + * pair of filterable objects of the same type of elements which do and do not + * satisfy, the predicate, respectively. + * + * @func + * @memberOf R + * @since v0.1.4 + * @category List + * @sig Filterable f => (a -> Boolean) -> f a -> [f a, f a] + * @param {Function} pred A predicate to determine which side the element belongs to. + * @param {Array} filterable the list (or other filterable) to partition. + * @return {Array} An array, containing first the subset of elements that satisfy the + * predicate, and second the subset of elements that do not satisfy. + * @see R.filter, R.reject + * @example + * + * R.partition(R.contains('s'), ['sss', 'ttt', 'foo', 'bars']); + * // => [ [ 'sss', 'bars' ], [ 'ttt', 'foo' ] ] + * + * R.partition(R.contains('s'), { a: 'sss', b: 'ttt', foo: 'bars' }); + * // => [ { a: 'sss', foo: 'bars' }, { b: 'ttt' } ] + */ + var partition = juxt([ + filter, + reject + ]); + + /** + * Performs left-to-right function composition. The leftmost function may have + * any arity; the remaining functions must be unary. + * + * In some libraries this function is named `sequence`. + * + * **Note:** The result of pipe is not automatically curried. + * + * @func + * @memberOf R + * @since v0.1.0 + * @category Function + * @sig (((a, b, ..., n) -> o), (o -> p), ..., (x -> y), (y -> z)) -> ((a, b, ..., n) -> z) + * @param {...Function} functions + * @return {Function} + * @see R.compose + * @example + * + * var f = R.pipe(Math.pow, R.negate, R.inc); + * + * f(3, 4); // -(3^4) + 1 + */ + var pipe = function pipe() { + if (arguments.length === 0) { + throw new Error('pipe requires at least one argument'); + } + return _arity(arguments[0].length, reduce(_pipe, arguments[0], tail(arguments))); + }; + + /** + * Performs left-to-right composition of one or more Promise-returning + * functions. The leftmost function may have any arity; the remaining functions + * must be unary. + * + * @func + * @memberOf R + * @since v0.10.0 + * @category Function + * @sig ((a -> Promise b), (b -> Promise c), ..., (y -> Promise z)) -> (a -> Promise z) + * @param {...Function} functions + * @return {Function} + * @see R.composeP + * @example + * + * // followersForUser :: String -> Promise [User] + * var followersForUser = R.pipeP(db.getUserById, db.getFollowers); + */ + var pipeP = function pipeP() { + if (arguments.length === 0) { + throw new Error('pipeP requires at least one argument'); + } + return _arity(arguments[0].length, reduce(_pipeP, arguments[0], tail(arguments))); + }; + + /** + * Multiplies together all the elements of a list. + * + * @func + * @memberOf R + * @since v0.1.0 + * @category Math + * @sig [Number] -> Number + * @param {Array} list An array of numbers + * @return {Number} The product of all the numbers in the list. + * @see R.reduce + * @example + * + * R.product([2,4,6,8,100,1]); //=> 38400 + */ + var product = reduce(multiply, 1); + + /** + * Transforms a [Traversable](https://github.com/fantasyland/fantasy-land#traversable) + * of [Applicative](https://github.com/fantasyland/fantasy-land#applicative) into an + * Applicative of Traversable. + * + * Dispatches to the `sequence` method of the second argument, if present. + * + * @func + * @memberOf R + * @since v0.19.0 + * @category List + * @sig (Applicative f, Traversable t) => (a -> f a) -> t (f a) -> f (t a) + * @param {Function} of + * @param {*} traversable + * @return {*} + * @see R.traverse + * @example + * + * R.sequence(Maybe.of, [Just(1), Just(2), Just(3)]); //=> Just([1, 2, 3]) + * R.sequence(Maybe.of, [Just(1), Just(2), Nothing()]); //=> Nothing() + * + * R.sequence(R.of, Just([1, 2, 3])); //=> [Just(1), Just(2), Just(3)] + * R.sequence(R.of, Nothing()); //=> [Nothing()] + */ + var sequence = _curry2(function sequence(of, traversable) { + return typeof traversable.sequence === 'function' ? traversable.sequence(of) : reduceRight(function (acc, x) { + return ap(map(prepend, x), acc); + }, of([]), traversable); + }); + + /** + * Maps an [Applicative](https://github.com/fantasyland/fantasy-land#applicative)-returning + * function over a [Traversable](https://github.com/fantasyland/fantasy-land#traversable), + * then uses [`sequence`](#sequence) to transform the resulting Traversable of Applicative + * into an Applicative of Traversable. + * + * Dispatches to the `sequence` method of the third argument, if present. + * + * @func + * @memberOf R + * @since v0.19.0 + * @category List + * @sig (Applicative f, Traversable t) => (a -> f a) -> (a -> f b) -> t a -> f (t b) + * @param {Function} of + * @param {Function} f + * @param {*} traversable + * @return {*} + * @see R.sequence + * @example + * + * // Returns `Nothing` if the given divisor is `0` + * safeDiv = n => d => d === 0 ? Nothing() : Just(n / d) + * + * R.traverse(Maybe.of, safeDiv(10), [2, 4, 5]); //=> Just([5, 2.5, 2]) + * R.traverse(Maybe.of, safeDiv(10), [2, 0, 5]); //=> Nothing + */ + var traverse = _curry3(function traverse(of, f, traversable) { + return sequence(of, map(f, traversable)); + }); + + /** + * Shorthand for `R.chain(R.identity)`, which removes one level of nesting from + * any [Chain](https://github.com/fantasyland/fantasy-land#chain). + * + * @func + * @memberOf R + * @since v0.3.0 + * @category List + * @sig Chain c => c (c a) -> c a + * @param {*} list + * @return {*} + * @see R.flatten, R.chain + * @example + * + * R.unnest([1, [2], [[3]]]); //=> [1, 2, [3]] + * R.unnest([[1, 2], [3, 4], [5, 6]]); //=> [1, 2, 3, 4, 5, 6] + */ + var unnest = chain(_identity); + + var _contains = function _contains(a, list) { + return _indexOf(list, a, 0) >= 0; + }; + + // mapPairs :: (Object, [String]) -> [String] + var _toString = function _toString(x, seen) { + var recur = function recur(y) { + var xs = seen.concat([x]); + return _contains(y, xs) ? '' : _toString(y, xs); + }; + // mapPairs :: (Object, [String]) -> [String] + var mapPairs = function (obj, keys) { + return _map(function (k) { + return _quote(k) + ': ' + recur(obj[k]); + }, keys.slice().sort()); + }; + switch (Object.prototype.toString.call(x)) { + case '[object Arguments]': + return '(function() { return arguments; }(' + _map(recur, x).join(', ') + '))'; + case '[object Array]': + return '[' + _map(recur, x).concat(mapPairs(x, reject(function (k) { + return /^\d+$/.test(k); + }, keys(x)))).join(', ') + ']'; + case '[object Boolean]': + return typeof x === 'object' ? 'new Boolean(' + recur(x.valueOf()) + ')' : x.toString(); + case '[object Date]': + return 'new Date(' + (isNaN(x.valueOf()) ? recur(NaN) : _quote(_toISOString(x))) + ')'; + case '[object Null]': + return 'null'; + case '[object Number]': + return typeof x === 'object' ? 'new Number(' + recur(x.valueOf()) + ')' : 1 / x === -Infinity ? '-0' : x.toString(10); + case '[object String]': + return typeof x === 'object' ? 'new String(' + recur(x.valueOf()) + ')' : _quote(x); + case '[object Undefined]': + return 'undefined'; + default: + if (typeof x.toString === 'function') { + var repr = x.toString(); + if (repr !== '[object Object]') { + return repr; + } + } + return '{' + mapPairs(x, keys(x)).join(', ') + '}'; + } + }; + + /** + * Performs right-to-left function composition. The rightmost function may have + * any arity; the remaining functions must be unary. + * + * **Note:** The result of compose is not automatically curried. + * + * @func + * @memberOf R + * @since v0.1.0 + * @category Function + * @sig ((y -> z), (x -> y), ..., (o -> p), ((a, b, ..., n) -> o)) -> ((a, b, ..., n) -> z) + * @param {...Function} functions + * @return {Function} + * @see R.pipe + * @example + * + * var f = R.compose(R.inc, R.negate, Math.pow); + * + * f(3, 4); // -(3^4) + 1 + */ + var compose = function compose() { + if (arguments.length === 0) { + throw new Error('compose requires at least one argument'); + } + return pipe.apply(this, reverse(arguments)); + }; + + /** + * Returns the right-to-left Kleisli composition of the provided functions, + * each of which must return a value of a type supported by [`chain`](#chain). + * + * `R.composeK(h, g, f)` is equivalent to `R.compose(R.chain(h), R.chain(g), R.chain(f))`. + * + * @func + * @memberOf R + * @since v0.16.0 + * @category Function + * @sig Chain m => ((y -> m z), (x -> m y), ..., (a -> m b)) -> (m a -> m z) + * @param {...Function} + * @return {Function} + * @see R.pipeK + * @example + * + * // parseJson :: String -> Maybe * + * // get :: String -> Object -> Maybe * + * + * // getStateCode :: Maybe String -> Maybe String + * var getStateCode = R.composeK( + * R.compose(Maybe.of, R.toUpper), + * get('state'), + * get('address'), + * get('user'), + * parseJson + * ); + * + * getStateCode(Maybe.of('{"user":{"address":{"state":"ny"}}}')); + * //=> Just('NY') + * getStateCode(Maybe.of('[Invalid JSON]')); + * //=> Nothing() + */ + var composeK = function composeK() { + return compose.apply(this, prepend(identity, map(chain, arguments))); + }; + + /** + * Performs right-to-left composition of one or more Promise-returning + * functions. The rightmost function may have any arity; the remaining + * functions must be unary. + * + * @func + * @memberOf R + * @since v0.10.0 + * @category Function + * @sig ((y -> Promise z), (x -> Promise y), ..., (a -> Promise b)) -> (a -> Promise z) + * @param {...Function} functions + * @return {Function} + * @see R.pipeP + * @example + * + * // followersForUser :: String -> Promise [User] + * var followersForUser = R.composeP(db.getFollowers, db.getUserById); + */ + var composeP = function composeP() { + if (arguments.length === 0) { + throw new Error('composeP requires at least one argument'); + } + return pipeP.apply(this, reverse(arguments)); + }; + + /** + * Wraps a constructor function inside a curried function that can be called + * with the same arguments and returns the same type. + * + * @func + * @memberOf R + * @since v0.1.0 + * @category Function + * @sig (* -> {*}) -> (* -> {*}) + * @param {Function} Fn The constructor function to wrap. + * @return {Function} A wrapped, curried constructor function. + * @example + * + * // Constructor function + * var Widget = config => { + * // ... + * }; + * Widget.prototype = { + * // ... + * }; + * var allConfigs = [ + * // ... + * ]; + * R.map(R.construct(Widget), allConfigs); // a list of Widgets + */ + var construct = _curry1(function construct(Fn) { + return constructN(Fn.length, Fn); + }); + + /** + * Returns `true` if the specified value is equal, in `R.equals` terms, to at + * least one element of the given list; `false` otherwise. + * + * @func + * @memberOf R + * @since v0.1.0 + * @category List + * @sig a -> [a] -> Boolean + * @param {Object} a The item to compare against. + * @param {Array} list The array to consider. + * @return {Boolean} `true` if the item is in the list, `false` otherwise. + * @see R.any + * @example + * + * R.contains(3, [1, 2, 3]); //=> true + * R.contains(4, [1, 2, 3]); //=> false + * R.contains([42], [[42]]); //=> true + */ + var contains = _curry2(_contains); + + /** + * Finds the set (i.e. no duplicates) of all elements in the first list not + * contained in the second list. + * + * @func + * @memberOf R + * @since v0.1.0 + * @category Relation + * @sig [*] -> [*] -> [*] + * @param {Array} list1 The first list. + * @param {Array} list2 The second list. + * @return {Array} The elements in `list1` that are not in `list2`. + * @see R.differenceWith, R.symmetricDifference, R.symmetricDifferenceWith + * @example + * + * R.difference([1,2,3,4], [7,6,5,4,3]); //=> [1,2] + * R.difference([7,6,5,4,3], [1,2,3,4]); //=> [7,6,5] + */ + var difference = _curry2(function difference(first, second) { + var out = []; + var idx = 0; + var firstLen = first.length; + while (idx < firstLen) { + if (!_contains(first[idx], second) && !_contains(first[idx], out)) { + out[out.length] = first[idx]; + } + idx += 1; + } + return out; + }); + + /** + * Returns a new list without any consecutively repeating elements. `R.equals` + * is used to determine equality. + * + * Dispatches to the `dropRepeats` method of the first argument, if present. + * + * Acts as a transducer if a transformer is given in list position. + * + * @func + * @memberOf R + * @since v0.14.0 + * @category List + * @sig [a] -> [a] + * @param {Array} list The array to consider. + * @return {Array} `list` without repeating elements. + * @see R.transduce + * @example + * + * R.dropRepeats([1, 1, 1, 2, 3, 4, 4, 2, 2]); //=> [1, 2, 3, 4, 2] + */ + var dropRepeats = _curry1(_dispatchable('dropRepeats', _xdropRepeatsWith(equals), dropRepeatsWith(equals))); + + /** + * "lifts" a function of arity > 1 so that it may "map over" a list, Function or other + * object that satisfies the [FantasyLand Apply spec](https://github.com/fantasyland/fantasy-land#apply). + * + * @func + * @memberOf R + * @since v0.7.0 + * @category Function + * @sig (*... -> *) -> ([*]... -> [*]) + * @param {Function} fn The function to lift into higher context + * @return {Function} The lifted function. + * @see R.liftN + * @example + * + * var madd3 = R.lift(R.curry((a, b, c) => a + b + c)); + * + * madd3([1,2,3], [1,2,3], [1]); //=> [3, 4, 5, 4, 5, 6, 5, 6, 7] + * + * var madd5 = R.lift(R.curry((a, b, c, d, e) => a + b + c + d + e)); + * + * madd5([1,2], [3], [4, 5], [6], [7, 8]); //=> [21, 22, 22, 23, 22, 23, 23, 24] + */ + var lift = _curry1(function lift(fn) { + return liftN(fn.length, fn); + }); + + /** + * Returns a partial copy of an object omitting the keys specified. + * + * @func + * @memberOf R + * @since v0.1.0 + * @category Object + * @sig [String] -> {String: *} -> {String: *} + * @param {Array} names an array of String property names to omit from the new object + * @param {Object} obj The object to copy from + * @return {Object} A new object with properties from `names` not on it. + * @see R.pick + * @example + * + * R.omit(['a', 'd'], {a: 1, b: 2, c: 3, d: 4}); //=> {b: 2, c: 3} + */ + var omit = _curry2(function omit(names, obj) { + var result = {}; + for (var prop in obj) { + if (!_contains(prop, names)) { + result[prop] = obj[prop]; + } + } + return result; + }); + + /** + * Returns the left-to-right Kleisli composition of the provided functions, + * each of which must return a value of a type supported by [`chain`](#chain). + * + * `R.pipeK(f, g, h)` is equivalent to `R.pipe(R.chain(f), R.chain(g), R.chain(h))`. + * + * @func + * @memberOf R + * @since v0.16.0 + * @category Function + * @sig Chain m => ((a -> m b), (b -> m c), ..., (y -> m z)) -> (m a -> m z) + * @param {...Function} + * @return {Function} + * @see R.composeK + * @example + * + * // parseJson :: String -> Maybe * + * // get :: String -> Object -> Maybe * + * + * // getStateCode :: Maybe String -> Maybe String + * var getStateCode = R.pipeK( + * parseJson, + * get('user'), + * get('address'), + * get('state'), + * R.compose(Maybe.of, R.toUpper) + * ); + * + * getStateCode(Maybe.of('{"user":{"address":{"state":"ny"}}}')); + * //=> Just('NY') + * getStateCode(Maybe.of('[Invalid JSON]')); + * //=> Nothing() + */ + var pipeK = function pipeK() { + return composeK.apply(this, reverse(arguments)); + }; + + /** + * Returns the string representation of the given value. `eval`'ing the output + * should result in a value equivalent to the input value. Many of the built-in + * `toString` methods do not satisfy this requirement. + * + * If the given value is an `[object Object]` with a `toString` method other + * than `Object.prototype.toString`, this method is invoked with no arguments + * to produce the return value. This means user-defined constructor functions + * can provide a suitable `toString` method. For example: + * + * function Point(x, y) { + * this.x = x; + * this.y = y; + * } + * + * Point.prototype.toString = function() { + * return 'new Point(' + this.x + ', ' + this.y + ')'; + * }; + * + * R.toString(new Point(1, 2)); //=> 'new Point(1, 2)' + * + * @func + * @memberOf R + * @since v0.14.0 + * @category String + * @sig * -> String + * @param {*} val + * @return {String} + * @example + * + * R.toString(42); //=> '42' + * R.toString('abc'); //=> '"abc"' + * R.toString([1, 2, 3]); //=> '[1, 2, 3]' + * R.toString({foo: 1, bar: 2, baz: 3}); //=> '{"bar": 2, "baz": 3, "foo": 1}' + * R.toString(new Date('2001-02-03T04:05:06Z')); //=> 'new Date("2001-02-03T04:05:06.000Z")' + */ + var toString = _curry1(function toString(val) { + return _toString(val, []); + }); + + /** + * Returns a new list without values in the first argument. + * `R.equals` is used to determine equality. + * + * Acts as a transducer if a transformer is given in list position. + * + * @func + * @memberOf R + * @since v0.19.0 + * @category List + * @sig [a] -> [a] -> [a] + * @param {Array} list1 The values to be removed from `list2`. + * @param {Array} list2 The array to remove values from. + * @return {Array} The new array without values in `list1`. + * @see R.transduce + * @example + * + * R.without([1, 2], [1, 2, 1, 3, 4]); //=> [3, 4] + */ + var without = _curry2(function (xs, list) { + return reject(flip(_contains)(xs), list); + }); + + // A simple Set type that honours R.equals semantics + /* globals Set */ + // until we figure out why jsdoc chokes on this + // @param item The item to add to the Set + // @returns {boolean} true if the item did not exist prior, otherwise false + // + // + // @param item The item to check for existence in the Set + // @returns {boolean} true if the item exists in the Set, otherwise false + // + // + // Combines the logic for checking whether an item is a member of the set and + // for adding a new item to the set. + // + // @param item The item to check or add to the Set instance. + // @param shouldAdd If true, the item will be added to the set if it doesn't + // already exist. + // @param set The set instance to check or add to. + // @return {boolean} true if the item already existed, otherwise false. + // + // distinguish between +0 and -0 + // these types can all utilise the native Set + // set._items['boolean'] holds a two element array + // representing [ falseExists, trueExists ] + // compare functions for reference equality + /* falls through */ + // reduce the search size of heterogeneous sets by creating buckets + // for each type. + // scan through all previously applied items + var _Set = function () { + function _Set() { + /* globals Set */ + this._nativeSet = typeof Set === 'function' ? new Set() : null; + this._items = {}; + } + // until we figure out why jsdoc chokes on this + // @param item The item to add to the Set + // @returns {boolean} true if the item did not exist prior, otherwise false + // + _Set.prototype.add = function (item) { + return !hasOrAdd(item, true, this); + }; + // + // @param item The item to check for existence in the Set + // @returns {boolean} true if the item exists in the Set, otherwise false + // + _Set.prototype.has = function (item) { + return hasOrAdd(item, false, this); + }; + // + // Combines the logic for checking whether an item is a member of the set and + // for adding a new item to the set. + // + // @param item The item to check or add to the Set instance. + // @param shouldAdd If true, the item will be added to the set if it doesn't + // already exist. + // @param set The set instance to check or add to. + // @return {boolean} true if the item already existed, otherwise false. + // + function hasOrAdd(item, shouldAdd, set) { + var type = typeof item; + var prevSize, newSize; + switch (type) { + case 'string': + case 'number': + // distinguish between +0 and -0 + if (item === 0 && 1 / item === -Infinity) { + if (set._items['-0']) { + return true; + } else { + if (shouldAdd) { + set._items['-0'] = true; + } + return false; + } + } + // these types can all utilise the native Set + if (set._nativeSet !== null) { + if (shouldAdd) { + prevSize = set._nativeSet.size; + set._nativeSet.add(item); + newSize = set._nativeSet.size; + return newSize === prevSize; + } else { + return set._nativeSet.has(item); + } + } else { + if (!(type in set._items)) { + if (shouldAdd) { + set._items[type] = {}; + set._items[type][item] = true; + } + return false; + } else if (item in set._items[type]) { + return true; + } else { + if (shouldAdd) { + set._items[type][item] = true; + } + return false; + } + } + case 'boolean': + // set._items['boolean'] holds a two element array + // representing [ falseExists, trueExists ] + if (type in set._items) { + var bIdx = item ? 1 : 0; + if (set._items[type][bIdx]) { + return true; + } else { + if (shouldAdd) { + set._items[type][bIdx] = true; + } + return false; + } + } else { + if (shouldAdd) { + set._items[type] = item ? [ + false, + true + ] : [ + true, + false + ]; + } + return false; + } + case 'function': + // compare functions for reference equality + if (set._nativeSet !== null) { + if (shouldAdd) { + prevSize = set._nativeSet.size; + set._nativeSet.add(item); + newSize = set._nativeSet.size; + return newSize > prevSize; + } else { + return set._nativeSet.has(item); + } + } else { + if (!(type in set._items)) { + if (shouldAdd) { + set._items[type] = [item]; + } + return false; + } + if (!_contains(item, set._items[type])) { + if (shouldAdd) { + set._items[type].push(item); + } + return false; + } + return true; + } + case 'undefined': + if (set._items[type]) { + return true; + } else { + if (shouldAdd) { + set._items[type] = true; + } + return false; + } + case 'object': + if (item === null) { + if (!set._items['null']) { + if (shouldAdd) { + set._items['null'] = true; + } + return false; + } + return true; + } + /* falls through */ + default: + // reduce the search size of heterogeneous sets by creating buckets + // for each type. + type = Object.prototype.toString.call(item); + if (!(type in set._items)) { + if (shouldAdd) { + set._items[type] = [item]; + } + return false; + } + // scan through all previously applied items + if (!_contains(item, set._items[type])) { + if (shouldAdd) { + set._items[type].push(item); + } + return false; + } + return true; + } + } + return _Set; + }(); + + /** + * A function wrapping calls to the two functions in an `&&` operation, + * returning the result of the first function if it is false-y and the result + * of the second function otherwise. Note that this is short-circuited, + * meaning that the second function will not be invoked if the first returns a + * false-y value. + * + * In addition to functions, `R.both` also accepts any fantasy-land compatible + * applicative functor. + * + * @func + * @memberOf R + * @since v0.12.0 + * @category Logic + * @sig (*... -> Boolean) -> (*... -> Boolean) -> (*... -> Boolean) + * @param {Function} f a predicate + * @param {Function} g another predicate + * @return {Function} a function that applies its arguments to `f` and `g` and `&&`s their outputs together. + * @see R.and + * @example + * + * var gt10 = x => x > 10; + * var even = x => x % 2 === 0; + * var f = R.both(gt10, even); + * f(100); //=> true + * f(101); //=> false + */ + var both = _curry2(function both(f, g) { + return _isFunction(f) ? function _both() { + return f.apply(this, arguments) && g.apply(this, arguments); + } : lift(and)(f, g); + }); + + /** + * Takes a function `f` and returns a function `g` such that: + * + * - applying `g` to zero or more arguments will give __true__ if applying + * the same arguments to `f` gives a logical __false__ value; and + * + * - applying `g` to zero or more arguments will give __false__ if applying + * the same arguments to `f` gives a logical __true__ value. + * + * `R.complement` will work on all other functors as well. + * + * @func + * @memberOf R + * @since v0.12.0 + * @category Logic + * @sig (*... -> *) -> (*... -> Boolean) + * @param {Function} f + * @return {Function} + * @see R.not + * @example + * + * var isEven = n => n % 2 === 0; + * var isOdd = R.complement(isEven); + * isOdd(21); //=> true + * isOdd(42); //=> false + */ + var complement = lift(not); + + /** + * Returns the result of concatenating the given lists or strings. + * + * Note: `R.concat` expects both arguments to be of the same type, + * unlike the native `Array.prototype.concat` method. It will throw + * an error if you `concat` an Array with a non-Array value. + * + * Dispatches to the `concat` method of the first argument, if present. + * + * @func + * @memberOf R + * @since v0.1.0 + * @category List + * @sig [a] -> [a] -> [a] + * @sig String -> String -> String + * @param {Array|String} a + * @param {Array|String} b + * @return {Array|String} + * + * @example + * + * R.concat([], []); //=> [] + * R.concat([4, 5, 6], [1, 2, 3]); //=> [4, 5, 6, 1, 2, 3] + * R.concat('ABC', 'DEF'); // 'ABCDEF' + */ + var concat = _curry2(function concat(a, b) { + if (a == null || !_isFunction(a.concat)) { + throw new TypeError(toString(a) + ' does not have a method named "concat"'); + } + if (_isArray(a) && !_isArray(b)) { + throw new TypeError(toString(b) + ' is not an array'); + } + return a.concat(b); + }); + + /** + * A function wrapping calls to the two functions in an `||` operation, + * returning the result of the first function if it is truth-y and the result + * of the second function otherwise. Note that this is short-circuited, + * meaning that the second function will not be invoked if the first returns a + * truth-y value. + * + * In addition to functions, `R.either` also accepts any fantasy-land compatible + * applicative functor. + * + * @func + * @memberOf R + * @since v0.12.0 + * @category Logic + * @sig (*... -> Boolean) -> (*... -> Boolean) -> (*... -> Boolean) + * @param {Function} f a predicate + * @param {Function} g another predicate + * @return {Function} a function that applies its arguments to `f` and `g` and `||`s their outputs together. + * @see R.or + * @example + * + * var gt10 = x => x > 10; + * var even = x => x % 2 === 0; + * var f = R.either(gt10, even); + * f(101); //=> true + * f(8); //=> true + */ + var either = _curry2(function either(f, g) { + return _isFunction(f) ? function _either() { + return f.apply(this, arguments) || g.apply(this, arguments); + } : lift(or)(f, g); + }); + + /** + * Turns a named method with a specified arity into a function that can be + * called directly supplied with arguments and a target object. + * + * The returned function is curried and accepts `arity + 1` parameters where + * the final parameter is the target object. + * + * @func + * @memberOf R + * @since v0.1.0 + * @category Function + * @sig Number -> String -> (a -> b -> ... -> n -> Object -> *) + * @param {Number} arity Number of arguments the returned function should take + * before the target object. + * @param {String} method Name of the method to call. + * @return {Function} A new curried function. + * @example + * + * var sliceFrom = R.invoker(1, 'slice'); + * sliceFrom(6, 'abcdefghijklm'); //=> 'ghijklm' + * var sliceFrom6 = R.invoker(2, 'slice')(6); + * sliceFrom6(8, 'abcdefghijklm'); //=> 'gh' + */ + var invoker = _curry2(function invoker(arity, method) { + return curryN(arity + 1, function () { + var target = arguments[arity]; + if (target != null && _isFunction(target[method])) { + return target[method].apply(target, _slice(arguments, 0, arity)); + } + throw new TypeError(toString(target) + ' does not have a method named "' + method + '"'); + }); + }); + + /** + * Returns a string made by inserting the `separator` between each element and + * concatenating all the elements into a single string. + * + * @func + * @memberOf R + * @since v0.1.0 + * @category List + * @sig String -> [a] -> String + * @param {Number|String} separator The string used to separate the elements. + * @param {Array} xs The elements to join into a string. + * @return {String} str The string made by concatenating `xs` with `separator`. + * @see R.split + * @example + * + * var spacer = R.join(' '); + * spacer(['a', 2, 3.4]); //=> 'a 2 3.4' + * R.join('|', [1, 2, 3]); //=> '1|2|3' + */ + var join = invoker(1, 'join'); + + /** + * Creates a new function that, when invoked, caches the result of calling `fn` + * for a given argument set and returns the result. Subsequent calls to the + * memoized `fn` with the same argument set will not result in an additional + * call to `fn`; instead, the cached result for that set of arguments will be + * returned. + * + * @func + * @memberOf R + * @since v0.1.0 + * @category Function + * @sig (*... -> a) -> (*... -> a) + * @param {Function} fn The function to memoize. + * @return {Function} Memoized version of `fn`. + * @example + * + * var count = 0; + * var factorial = R.memoize(n => { + * count += 1; + * return R.product(R.range(1, n + 1)); + * }); + * factorial(5); //=> 120 + * factorial(5); //=> 120 + * factorial(5); //=> 120 + * count; //=> 1 + */ + var memoize = _curry1(function memoize(fn) { + var cache = {}; + return _arity(fn.length, function () { + var key = toString(arguments); + if (!_has(key, cache)) { + cache[key] = fn.apply(this, arguments); + } + return cache[key]; + }); + }); + + /** + * Splits a string into an array of strings based on the given + * separator. + * + * @func + * @memberOf R + * @since v0.1.0 + * @category String + * @sig (String | RegExp) -> String -> [String] + * @param {String|RegExp} sep The pattern. + * @param {String} str The string to separate into an array. + * @return {Array} The array of strings from `str` separated by `str`. + * @see R.join + * @example + * + * var pathComponents = R.split('/'); + * R.tail(pathComponents('/usr/local/bin/node')); //=> ['usr', 'local', 'bin', 'node'] + * + * R.split('.', 'a.b.c.xyz.d'); //=> ['a', 'b', 'c', 'xyz', 'd'] + */ + var split = invoker(1, 'split'); + + /** + * Finds the set (i.e. no duplicates) of all elements contained in the first or + * second list, but not both. + * + * @func + * @memberOf R + * @since v0.19.0 + * @category Relation + * @sig [*] -> [*] -> [*] + * @param {Array} list1 The first list. + * @param {Array} list2 The second list. + * @return {Array} The elements in `list1` or `list2`, but not both. + * @see R.symmetricDifferenceWith, R.difference, R.differenceWith + * @example + * + * R.symmetricDifference([1,2,3,4], [7,6,5,4,3]); //=> [1,2,7,6,5] + * R.symmetricDifference([7,6,5,4,3], [1,2,3,4]); //=> [7,6,5,1,2] + */ + var symmetricDifference = _curry2(function symmetricDifference(list1, list2) { + return concat(difference(list1, list2), difference(list2, list1)); + }); + + /** + * Finds the set (i.e. no duplicates) of all elements contained in the first or + * second list, but not both. Duplication is determined according to the value + * returned by applying the supplied predicate to two list elements. + * + * @func + * @memberOf R + * @since v0.19.0 + * @category Relation + * @sig (a -> a -> Boolean) -> [a] -> [a] -> [a] + * @param {Function} pred A predicate used to test whether two items are equal. + * @param {Array} list1 The first list. + * @param {Array} list2 The second list. + * @return {Array} The elements in `list1` or `list2`, but not both. + * @see R.symmetricDifference, R.difference, R.differenceWith + * @example + * + * var eqA = R.eqBy(R.prop('a')); + * var l1 = [{a: 1}, {a: 2}, {a: 3}, {a: 4}]; + * var l2 = [{a: 3}, {a: 4}, {a: 5}, {a: 6}]; + * R.symmetricDifferenceWith(eqA, l1, l2); //=> [{a: 1}, {a: 2}, {a: 5}, {a: 6}] + */ + var symmetricDifferenceWith = _curry3(function symmetricDifferenceWith(pred, list1, list2) { + return concat(differenceWith(pred, list1, list2), differenceWith(pred, list2, list1)); + }); + + /** + * Determines whether a given string matches a given regular expression. + * + * @func + * @memberOf R + * @since v0.12.0 + * @category String + * @sig RegExp -> String -> Boolean + * @param {RegExp} pattern + * @param {String} str + * @return {Boolean} + * @see R.match + * @example + * + * R.test(/^x/, 'xyz'); //=> true + * R.test(/^y/, 'xyz'); //=> false + */ + var test = _curry2(function test(pattern, str) { + if (!_isRegExp(pattern)) { + throw new TypeError('\u2018test\u2019 requires a value of type RegExp as its first argument; received ' + toString(pattern)); + } + return _cloneRegExp(pattern).test(str); + }); + + /** + * The lower case version of a string. + * + * @func + * @memberOf R + * @since v0.9.0 + * @category String + * @sig String -> String + * @param {String} str The string to lower case. + * @return {String} The lower case version of `str`. + * @see R.toUpper + * @example + * + * R.toLower('XYZ'); //=> 'xyz' + */ + var toLower = invoker(0, 'toLowerCase'); + + /** + * The upper case version of a string. + * + * @func + * @memberOf R + * @since v0.9.0 + * @category String + * @sig String -> String + * @param {String} str The string to upper case. + * @return {String} The upper case version of `str`. + * @see R.toLower + * @example + * + * R.toUpper('abc'); //=> 'ABC' + */ + var toUpper = invoker(0, 'toUpperCase'); + + /** + * Returns a new list containing only one copy of each element in the original + * list, based upon the value returned by applying the supplied function to + * each list element. Prefers the first item if the supplied function produces + * the same value on two items. `R.equals` is used for comparison. + * + * @func + * @memberOf R + * @since v0.16.0 + * @category List + * @sig (a -> b) -> [a] -> [a] + * @param {Function} fn A function used to produce a value to use during comparisons. + * @param {Array} list The array to consider. + * @return {Array} The list of unique items. + * @example + * + * R.uniqBy(Math.abs, [-1, -5, 2, 10, 1, 2]); //=> [-1, -5, 2, 10] + */ + var uniqBy = _curry2(function uniqBy(fn, list) { + var set = new _Set(); + var result = []; + var idx = 0; + var appliedItem, item; + while (idx < list.length) { + item = list[idx]; + appliedItem = fn(item); + if (set.add(appliedItem)) { + result.push(item); + } + idx += 1; + } + return result; + }); + + /** + * Returns a new list containing only one copy of each element in the original + * list. `R.equals` is used to determine equality. + * + * @func + * @memberOf R + * @since v0.1.0 + * @category List + * @sig [a] -> [a] + * @param {Array} list The array to consider. + * @return {Array} The list of unique items. + * @example + * + * R.uniq([1, 1, 2, 1]); //=> [1, 2] + * R.uniq([1, '1']); //=> [1, '1'] + * R.uniq([[42], [42]]); //=> [[42]] + */ + var uniq = uniqBy(identity); + + /** + * Combines two lists into a set (i.e. no duplicates) composed of those + * elements common to both lists. + * + * @func + * @memberOf R + * @since v0.1.0 + * @category Relation + * @sig [*] -> [*] -> [*] + * @param {Array} list1 The first list. + * @param {Array} list2 The second list. + * @return {Array} The list of elements found in both `list1` and `list2`. + * @see R.intersectionWith + * @example + * + * R.intersection([1,2,3,4], [7,6,5,4,3]); //=> [4, 3] + */ + var intersection = _curry2(function intersection(list1, list2) { + var lookupList, filteredList; + if (list1.length > list2.length) { + lookupList = list1; + filteredList = list2; + } else { + lookupList = list2; + filteredList = list1; + } + return uniq(_filter(flip(_contains)(lookupList), filteredList)); + }); + + /** + * Combines two lists into a set (i.e. no duplicates) composed of the elements + * of each list. + * + * @func + * @memberOf R + * @since v0.1.0 + * @category Relation + * @sig [*] -> [*] -> [*] + * @param {Array} as The first list. + * @param {Array} bs The second list. + * @return {Array} The first and second lists concatenated, with + * duplicates removed. + * @example + * + * R.union([1, 2, 3], [2, 3, 4]); //=> [1, 2, 3, 4] + */ + var union = _curry2(compose(uniq, _concat)); + + var R = { + F: F, + T: T, + __: __, + add: add, + addIndex: addIndex, + adjust: adjust, + all: all, + allPass: allPass, + always: always, + and: and, + any: any, + anyPass: anyPass, + ap: ap, + aperture: aperture, + append: append, + apply: apply, + applySpec: applySpec, + assoc: assoc, + assocPath: assocPath, + binary: binary, + bind: bind, + both: both, + call: call, + chain: chain, + clamp: clamp, + clone: clone, + comparator: comparator, + complement: complement, + compose: compose, + composeK: composeK, + composeP: composeP, + concat: concat, + cond: cond, + construct: construct, + constructN: constructN, + contains: contains, + converge: converge, + countBy: countBy, + curry: curry, + curryN: curryN, + dec: dec, + defaultTo: defaultTo, + difference: difference, + differenceWith: differenceWith, + dissoc: dissoc, + dissocPath: dissocPath, + divide: divide, + drop: drop, + dropLast: dropLast, + dropLastWhile: dropLastWhile, + dropRepeats: dropRepeats, + dropRepeatsWith: dropRepeatsWith, + dropWhile: dropWhile, + either: either, + empty: empty, + eqBy: eqBy, + eqProps: eqProps, + equals: equals, + evolve: evolve, + filter: filter, + find: find, + findIndex: findIndex, + findLast: findLast, + findLastIndex: findLastIndex, + flatten: flatten, + flip: flip, + forEach: forEach, + fromPairs: fromPairs, + groupBy: groupBy, + groupWith: groupWith, + gt: gt, + gte: gte, + has: has, + hasIn: hasIn, + head: head, + identical: identical, + identity: identity, + ifElse: ifElse, + inc: inc, + indexBy: indexBy, + indexOf: indexOf, + init: init, + insert: insert, + insertAll: insertAll, + intersection: intersection, + intersectionWith: intersectionWith, + intersperse: intersperse, + into: into, + invert: invert, + invertObj: invertObj, + invoker: invoker, + is: is, + isArrayLike: isArrayLike, + isEmpty: isEmpty, + isNil: isNil, + join: join, + juxt: juxt, + keys: keys, + keysIn: keysIn, + last: last, + lastIndexOf: lastIndexOf, + length: length, + lens: lens, + lensIndex: lensIndex, + lensPath: lensPath, + lensProp: lensProp, + lift: lift, + liftN: liftN, + lt: lt, + lte: lte, + map: map, + mapAccum: mapAccum, + mapAccumRight: mapAccumRight, + mapObjIndexed: mapObjIndexed, + match: match, + mathMod: mathMod, + max: max, + maxBy: maxBy, + mean: mean, + median: median, + memoize: memoize, + merge: merge, + mergeAll: mergeAll, + mergeWith: mergeWith, + mergeWithKey: mergeWithKey, + min: min, + minBy: minBy, + modulo: modulo, + multiply: multiply, + nAry: nAry, + negate: negate, + none: none, + not: not, + nth: nth, + nthArg: nthArg, + objOf: objOf, + of: of, + omit: omit, + once: once, + or: or, + over: over, + pair: pair, + partial: partial, + partialRight: partialRight, + partition: partition, + path: path, + pathEq: pathEq, + pathOr: pathOr, + pathSatisfies: pathSatisfies, + pick: pick, + pickAll: pickAll, + pickBy: pickBy, + pipe: pipe, + pipeK: pipeK, + pipeP: pipeP, + pluck: pluck, + prepend: prepend, + product: product, + project: project, + prop: prop, + propEq: propEq, + propIs: propIs, + propOr: propOr, + propSatisfies: propSatisfies, + props: props, + range: range, + reduce: reduce, + reduceBy: reduceBy, + reduceRight: reduceRight, + reduceWhile: reduceWhile, + reduced: reduced, + reject: reject, + remove: remove, + repeat: repeat, + replace: replace, + reverse: reverse, + scan: scan, + sequence: sequence, + set: set, + slice: slice, + sort: sort, + sortBy: sortBy, + split: split, + splitAt: splitAt, + splitEvery: splitEvery, + splitWhen: splitWhen, + subtract: subtract, + sum: sum, + symmetricDifference: symmetricDifference, + symmetricDifferenceWith: symmetricDifferenceWith, + tail: tail, + take: take, + takeLast: takeLast, + takeLastWhile: takeLastWhile, + takeWhile: takeWhile, + tap: tap, + test: test, + times: times, + toLower: toLower, + toPairs: toPairs, + toPairsIn: toPairsIn, + toString: toString, + toUpper: toUpper, + transduce: transduce, + transpose: transpose, + traverse: traverse, + trim: trim, + tryCatch: tryCatch, + type: type, + unapply: unapply, + unary: unary, + uncurryN: uncurryN, + unfold: unfold, + union: union, + unionWith: unionWith, + uniq: uniq, + uniqBy: uniqBy, + uniqWith: uniqWith, + unless: unless, + unnest: unnest, + until: until, + update: update, + useWith: useWith, + values: values, + valuesIn: valuesIn, + view: view, + when: when, + where: where, + whereEq: whereEq, + without: without, + wrap: wrap, + xprod: xprod, + zip: zip, + zipObj: zipObj, + zipWith: zipWith + }; + /* eslint-env amd */ + + /* TEST_ENTRY_POINT */ + + if (typeof exports === 'object') { + module.exports = R; + } else if (typeof define === 'function' && define.amd) { + define(function() { return R; }); + } else { + this.R = R; + } + +}.call(this)); + +},{}],608:[function(require,module,exports){ +var _curry1 = require('./internal/_curry1'); + + +/** + * Returns a function that always returns the given value. Note that for + * non-primitives the value returned is a reference to the original value. + * + * This function is known as `const`, `constant`, or `K` (for K combinator) in + * other languages and libraries. + * + * @func + * @memberOf R + * @since v0.1.0 + * @category Function + * @sig a -> (* -> a) + * @param {*} val The value to wrap in a function + * @return {Function} A Function :: * -> val. + * @example + * + * var t = R.always('Tee'); + * t(); //=> 'Tee' + */ +module.exports = _curry1(function always(val) { + return function() { + return val; + }; +}); + +},{"./internal/_curry1":623}],609:[function(require,module,exports){ +var _arity = require('./internal/_arity'); +var _curry2 = require('./internal/_curry2'); + + +/** + * Creates a function that is bound to a context. + * Note: `R.bind` does not provide the additional argument-binding capabilities of + * [Function.prototype.bind](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind). + * + * @func + * @memberOf R + * @since v0.6.0 + * @category Function + * @category Object + * @sig (* -> *) -> {*} -> (* -> *) + * @param {Function} fn The function to bind to context + * @param {Object} thisObj The context to bind `fn` to + * @return {Function} A function that will execute in the context of `thisObj`. + * @see R.partial + * @example + * + * var log = R.bind(console.log, console); + * R.pipe(R.assoc('a', 2), R.tap(log), R.assoc('a', 3))({a: 1}); //=> {a: 3} + * // logs {a: 2} + */ +module.exports = _curry2(function bind(fn, thisObj) { + return _arity(fn.length, function() { + return fn.apply(thisObj, arguments); + }); +}); + +},{"./internal/_arity":618,"./internal/_curry2":624}],610:[function(require,module,exports){ +var pipe = require('./pipe'); +var reverse = require('./reverse'); + + +/** + * Performs right-to-left function composition. The rightmost function may have + * any arity; the remaining functions must be unary. + * + * **Note:** The result of compose is not automatically curried. + * + * @func + * @memberOf R + * @since v0.1.0 + * @category Function + * @sig ((y -> z), (x -> y), ..., (o -> p), ((a, b, ..., n) -> o)) -> ((a, b, ..., n) -> z) + * @param {...Function} functions + * @return {Function} + * @see R.pipe + * @example + * + * var f = R.compose(R.inc, R.negate, Math.pow); + * + * f(3, 4); // -(3^4) + 1 + */ +module.exports = function compose() { + if (arguments.length === 0) { + throw new Error('compose requires at least one argument'); + } + return pipe.apply(this, reverse(arguments)); +}; + +},{"./pipe":653,"./reverse":656}],611:[function(require,module,exports){ +var _curry1 = require('./internal/_curry1'); +var curryN = require('./curryN'); + + +/** + * Returns a curried equivalent of the provided function. The curried function + * has two unusual capabilities. First, its arguments needn't be provided one + * at a time. If `f` is a ternary function and `g` is `R.curry(f)`, the + * following are equivalent: + * + * - `g(1)(2)(3)` + * - `g(1)(2, 3)` + * - `g(1, 2)(3)` + * - `g(1, 2, 3)` + * + * Secondly, the special placeholder value `R.__` may be used to specify + * "gaps", allowing partial application of any combination of arguments, + * regardless of their positions. If `g` is as above and `_` is `R.__`, the + * following are equivalent: + * + * - `g(1, 2, 3)` + * - `g(_, 2, 3)(1)` + * - `g(_, _, 3)(1)(2)` + * - `g(_, _, 3)(1, 2)` + * - `g(_, 2)(1)(3)` + * - `g(_, 2)(1, 3)` + * - `g(_, 2)(_, 3)(1)` + * + * @func + * @memberOf R + * @since v0.1.0 + * @category Function + * @sig (* -> a) -> (* -> a) + * @param {Function} fn The function to curry. + * @return {Function} A new, curried function. + * @see R.curryN + * @example + * + * var addFourNumbers = (a, b, c, d) => a + b + c + d; + * + * var curriedAddFourNumbers = R.curry(addFourNumbers); + * var f = curriedAddFourNumbers(1, 2); + * var g = f(3); + * g(4); //=> 10 + */ +module.exports = _curry1(function curry(fn) { + return curryN(fn.length, fn); +}); + +},{"./curryN":612,"./internal/_curry1":623}],612:[function(require,module,exports){ +var _arity = require('./internal/_arity'); +var _curry1 = require('./internal/_curry1'); +var _curry2 = require('./internal/_curry2'); +var _curryN = require('./internal/_curryN'); + + +/** + * Returns a curried equivalent of the provided function, with the specified + * arity. The curried function has two unusual capabilities. First, its + * arguments needn't be provided one at a time. If `g` is `R.curryN(3, f)`, the + * following are equivalent: + * + * - `g(1)(2)(3)` + * - `g(1)(2, 3)` + * - `g(1, 2)(3)` + * - `g(1, 2, 3)` + * + * Secondly, the special placeholder value `R.__` may be used to specify + * "gaps", allowing partial application of any combination of arguments, + * regardless of their positions. If `g` is as above and `_` is `R.__`, the + * following are equivalent: + * + * - `g(1, 2, 3)` + * - `g(_, 2, 3)(1)` + * - `g(_, _, 3)(1)(2)` + * - `g(_, _, 3)(1, 2)` + * - `g(_, 2)(1)(3)` + * - `g(_, 2)(1, 3)` + * - `g(_, 2)(_, 3)(1)` + * + * @func + * @memberOf R + * @since v0.5.0 + * @category Function + * @sig Number -> (* -> a) -> (* -> a) + * @param {Number} length The arity for the returned function. + * @param {Function} fn The function to curry. + * @return {Function} A new, curried function. + * @see R.curry + * @example + * + * var sumArgs = (...args) => R.sum(args); + * + * var curriedAddFourNumbers = R.curryN(4, sumArgs); + * var f = curriedAddFourNumbers(1, 2); + * var g = f(3); + * g(4); //=> 10 + */ +module.exports = _curry2(function curryN(length, fn) { + if (length === 1) { + return _curry1(fn); + } + return _arity(length, _curryN(length, [], fn)); +}); + +},{"./internal/_arity":618,"./internal/_curry1":623,"./internal/_curry2":624,"./internal/_curryN":626}],613:[function(require,module,exports){ +var _curry2 = require('./internal/_curry2'); +var _equals = require('./internal/_equals'); + + +/** + * Returns `true` if its arguments are equivalent, `false` otherwise. Handles + * cyclical data structures. + * + * Dispatches symmetrically to the `equals` methods of both arguments, if + * present. + * + * @func + * @memberOf R + * @since v0.15.0 + * @category Relation + * @sig a -> b -> Boolean + * @param {*} a + * @param {*} b + * @return {Boolean} + * @example + * + * R.equals(1, 1); //=> true + * R.equals(1, '1'); //=> false + * R.equals([1, 2, 3], [1, 2, 3]); //=> true + * + * var a = {}; a.v = a; + * var b = {}; b.v = b; + * R.equals(a, b); //=> true + */ +module.exports = _curry2(function equals(a, b) { + return _equals(a, b, [], []); +}); + +},{"./internal/_curry2":624,"./internal/_equals":628}],614:[function(require,module,exports){ +var _curry2 = require('./internal/_curry2'); +var _dispatchable = require('./internal/_dispatchable'); +var _filter = require('./internal/_filter'); +var _isObject = require('./internal/_isObject'); +var _reduce = require('./internal/_reduce'); +var _xfilter = require('./internal/_xfilter'); +var keys = require('./keys'); + + +/** + * Takes a predicate and a "filterable", and returns a new filterable of the + * same type containing the members of the given filterable which satisfy the + * given predicate. + * + * Dispatches to the `filter` method of the second argument, if present. + * + * Acts as a transducer if a transformer is given in list position. + * + * @func + * @memberOf R + * @since v0.1.0 + * @category List + * @sig Filterable f => (a -> Boolean) -> f a -> f a + * @param {Function} pred + * @param {Array} filterable + * @return {Array} + * @see R.reject, R.transduce, R.addIndex + * @example + * + * var isEven = n => n % 2 === 0; + * + * R.filter(isEven, [1, 2, 3, 4]); //=> [2, 4] + * + * R.filter(isEven, {a: 1, b: 2, c: 3, d: 4}); //=> {b: 2, d: 4} + */ +module.exports = _curry2(_dispatchable('filter', _xfilter, function(pred, filterable) { + return ( + _isObject(filterable) ? + _reduce(function(acc, key) { + if (pred(filterable[key])) { + acc[key] = filterable[key]; + } + return acc; + }, {}, keys(filterable)) : + // else + _filter(pred, filterable) + ); +})); + +},{"./internal/_curry2":624,"./internal/_dispatchable":627,"./internal/_filter":629,"./internal/_isObject":636,"./internal/_reduce":643,"./internal/_xfilter":648,"./keys":651}],615:[function(require,module,exports){ +var _checkForMethod = require('./internal/_checkForMethod'); +var _curry2 = require('./internal/_curry2'); + + +/** + * Iterate over an input `list`, calling a provided function `fn` for each + * element in the list. + * + * `fn` receives one argument: *(value)*. + * + * Note: `R.forEach` does not skip deleted or unassigned indices (sparse + * arrays), unlike the native `Array.prototype.forEach` method. For more + * details on this behavior, see: + * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach#Description + * + * Also note that, unlike `Array.prototype.forEach`, Ramda's `forEach` returns + * the original array. In some libraries this function is named `each`. + * + * Dispatches to the `forEach` method of the second argument, if present. + * + * @func + * @memberOf R + * @since v0.1.1 + * @category List + * @sig (a -> *) -> [a] -> [a] + * @param {Function} fn The function to invoke. Receives one argument, `value`. + * @param {Array} list The list to iterate over. + * @return {Array} The original list. + * @see R.addIndex + * @example + * + * var printXPlusFive = x => console.log(x + 5); + * R.forEach(printXPlusFive, [1, 2, 3]); //=> [1, 2, 3] + * // logs 6 + * // logs 7 + * // logs 8 + */ +module.exports = _curry2(_checkForMethod('forEach', function forEach(fn, list) { + var len = list.length; + var idx = 0; + while (idx < len) { + fn(list[idx]); + idx += 1; + } + return list; +})); + +},{"./internal/_checkForMethod":620,"./internal/_curry2":624}],616:[function(require,module,exports){ +var _curry2 = require('./internal/_curry2'); + + +/** + * Returns true if its arguments are identical, false otherwise. Values are + * identical if they reference the same memory. `NaN` is identical to `NaN`; + * `0` and `-0` are not identical. + * + * @func + * @memberOf R + * @since v0.15.0 + * @category Relation + * @sig a -> a -> Boolean + * @param {*} a + * @param {*} b + * @return {Boolean} + * @example + * + * var o = {}; + * R.identical(o, o); //=> true + * R.identical(1, 1); //=> true + * R.identical(1, '1'); //=> false + * R.identical([], []); //=> false + * R.identical(0, -0); //=> false + * R.identical(NaN, NaN); //=> true + */ +module.exports = _curry2(function identical(a, b) { + // SameValue algorithm + if (a === b) { // Steps 1-5, 7-10 + // Steps 6.b-6.e: +0 != -0 + return a !== 0 || 1 / a === 1 / b; + } else { + // Step 6.a: NaN == NaN + return a !== a && b !== b; + } +}); + +},{"./internal/_curry2":624}],617:[function(require,module,exports){ +var _curry1 = require('./internal/_curry1'); +var _identity = require('./internal/_identity'); + + +/** + * A function that does nothing but return the parameter supplied to it. Good + * as a default or placeholder function. + * + * @func + * @memberOf R + * @since v0.1.0 + * @category Function + * @sig a -> a + * @param {*} x The value to return. + * @return {*} The input value, `x`. + * @example + * + * R.identity(1); //=> 1 + * + * var obj = {}; + * R.identity(obj) === obj; //=> true + */ +module.exports = _curry1(_identity); + +},{"./internal/_curry1":623,"./internal/_identity":632}],618:[function(require,module,exports){ +module.exports = function _arity(n, fn) { + /* eslint-disable no-unused-vars */ + switch (n) { + case 0: return function() { return fn.apply(this, arguments); }; + case 1: return function(a0) { return fn.apply(this, arguments); }; + case 2: return function(a0, a1) { return fn.apply(this, arguments); }; + case 3: return function(a0, a1, a2) { return fn.apply(this, arguments); }; + case 4: return function(a0, a1, a2, a3) { return fn.apply(this, arguments); }; + case 5: return function(a0, a1, a2, a3, a4) { return fn.apply(this, arguments); }; + case 6: return function(a0, a1, a2, a3, a4, a5) { return fn.apply(this, arguments); }; + case 7: return function(a0, a1, a2, a3, a4, a5, a6) { return fn.apply(this, arguments); }; + case 8: return function(a0, a1, a2, a3, a4, a5, a6, a7) { return fn.apply(this, arguments); }; + case 9: return function(a0, a1, a2, a3, a4, a5, a6, a7, a8) { return fn.apply(this, arguments); }; + case 10: return function(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9) { return fn.apply(this, arguments); }; + default: throw new Error('First argument to _arity must be a non-negative integer no greater than ten'); + } +}; + +},{}],619:[function(require,module,exports){ +module.exports = function _arrayFromIterator(iter) { + var list = []; + var next; + while (!(next = iter.next()).done) { + list.push(next.value); + } + return list; +}; + +},{}],620:[function(require,module,exports){ +var _isArray = require('./_isArray'); +var _slice = require('./_slice'); + + +/** + * Similar to hasMethod, this checks whether a function has a [methodname] + * function. If it isn't an array it will execute that function otherwise it + * will default to the ramda implementation. + * + * @private + * @param {Function} fn ramda implemtation + * @param {String} methodname property to check for a custom implementation + * @return {Object} Whatever the return value of the method is. + */ +module.exports = function _checkForMethod(methodname, fn) { + return function() { + var length = arguments.length; + if (length === 0) { + return fn(); + } + var obj = arguments[length - 1]; + return (_isArray(obj) || typeof obj[methodname] !== 'function') ? + fn.apply(this, arguments) : + obj[methodname].apply(obj, _slice(arguments, 0, length - 1)); + }; +}; + +},{"./_isArray":635,"./_slice":644}],621:[function(require,module,exports){ +module.exports = function _complement(f) { + return function() { + return !f.apply(this, arguments); + }; +}; + +},{}],622:[function(require,module,exports){ +var _indexOf = require('./_indexOf'); + + +module.exports = function _contains(a, list) { + return _indexOf(list, a, 0) >= 0; +}; + +},{"./_indexOf":633}],623:[function(require,module,exports){ +var _isPlaceholder = require('./_isPlaceholder'); + + +/** + * Optimized internal one-arity curry function. + * + * @private + * @category Function + * @param {Function} fn The function to curry. + * @return {Function} The curried function. + */ +module.exports = function _curry1(fn) { + return function f1(a) { + if (arguments.length === 0 || _isPlaceholder(a)) { + return f1; + } else { + return fn.apply(this, arguments); + } + }; +}; + +},{"./_isPlaceholder":637}],624:[function(require,module,exports){ +var _curry1 = require('./_curry1'); +var _isPlaceholder = require('./_isPlaceholder'); + + +/** + * Optimized internal two-arity curry function. + * + * @private + * @category Function + * @param {Function} fn The function to curry. + * @return {Function} The curried function. + */ +module.exports = function _curry2(fn) { + return function f2(a, b) { + switch (arguments.length) { + case 0: + return f2; + case 1: + return _isPlaceholder(a) ? f2 + : _curry1(function(_b) { return fn(a, _b); }); + default: + return _isPlaceholder(a) && _isPlaceholder(b) ? f2 + : _isPlaceholder(a) ? _curry1(function(_a) { return fn(_a, b); }) + : _isPlaceholder(b) ? _curry1(function(_b) { return fn(a, _b); }) + : fn(a, b); + } + }; +}; + +},{"./_curry1":623,"./_isPlaceholder":637}],625:[function(require,module,exports){ +var _curry1 = require('./_curry1'); +var _curry2 = require('./_curry2'); +var _isPlaceholder = require('./_isPlaceholder'); + + +/** + * Optimized internal three-arity curry function. + * + * @private + * @category Function + * @param {Function} fn The function to curry. + * @return {Function} The curried function. + */ +module.exports = function _curry3(fn) { + return function f3(a, b, c) { + switch (arguments.length) { + case 0: + return f3; + case 1: + return _isPlaceholder(a) ? f3 + : _curry2(function(_b, _c) { return fn(a, _b, _c); }); + case 2: + return _isPlaceholder(a) && _isPlaceholder(b) ? f3 + : _isPlaceholder(a) ? _curry2(function(_a, _c) { return fn(_a, b, _c); }) + : _isPlaceholder(b) ? _curry2(function(_b, _c) { return fn(a, _b, _c); }) + : _curry1(function(_c) { return fn(a, b, _c); }); + default: + return _isPlaceholder(a) && _isPlaceholder(b) && _isPlaceholder(c) ? f3 + : _isPlaceholder(a) && _isPlaceholder(b) ? _curry2(function(_a, _b) { return fn(_a, _b, c); }) + : _isPlaceholder(a) && _isPlaceholder(c) ? _curry2(function(_a, _c) { return fn(_a, b, _c); }) + : _isPlaceholder(b) && _isPlaceholder(c) ? _curry2(function(_b, _c) { return fn(a, _b, _c); }) + : _isPlaceholder(a) ? _curry1(function(_a) { return fn(_a, b, c); }) + : _isPlaceholder(b) ? _curry1(function(_b) { return fn(a, _b, c); }) + : _isPlaceholder(c) ? _curry1(function(_c) { return fn(a, b, _c); }) + : fn(a, b, c); + } + }; +}; + +},{"./_curry1":623,"./_curry2":624,"./_isPlaceholder":637}],626:[function(require,module,exports){ +var _arity = require('./_arity'); +var _isPlaceholder = require('./_isPlaceholder'); + + +/** + * Internal curryN function. + * + * @private + * @category Function + * @param {Number} length The arity of the curried function. + * @param {Array} received An array of arguments received thus far. + * @param {Function} fn The function to curry. + * @return {Function} The curried function. + */ +module.exports = function _curryN(length, received, fn) { + return function() { + var combined = []; + var argsIdx = 0; + var left = length; + var combinedIdx = 0; + while (combinedIdx < received.length || argsIdx < arguments.length) { + var result; + if (combinedIdx < received.length && + (!_isPlaceholder(received[combinedIdx]) || + argsIdx >= arguments.length)) { + result = received[combinedIdx]; + } else { + result = arguments[argsIdx]; + argsIdx += 1; + } + combined[combinedIdx] = result; + if (!_isPlaceholder(result)) { + left -= 1; + } + combinedIdx += 1; + } + return left <= 0 ? fn.apply(this, combined) + : _arity(left, _curryN(length, combined, fn)); + }; +}; + +},{"./_arity":618,"./_isPlaceholder":637}],627:[function(require,module,exports){ +var _isArray = require('./_isArray'); +var _isTransformer = require('./_isTransformer'); +var _slice = require('./_slice'); + + +/** + * Returns a function that dispatches with different strategies based on the + * object in list position (last argument). If it is an array, executes [fn]. + * Otherwise, if it has a function with [methodname], it will execute that + * function (functor case). Otherwise, if it is a transformer, uses transducer + * [xf] to return a new transformer (transducer case). Otherwise, it will + * default to executing [fn]. + * + * @private + * @param {String} methodname property to check for a custom implementation + * @param {Function} xf transducer to initialize if object is transformer + * @param {Function} fn default ramda implementation + * @return {Function} A function that dispatches on object in list position + */ +module.exports = function _dispatchable(methodname, xf, fn) { + return function() { + var length = arguments.length; + if (length === 0) { + return fn(); + } + var obj = arguments[length - 1]; + if (!_isArray(obj)) { + var args = _slice(arguments, 0, length - 1); + if (typeof obj[methodname] === 'function') { + return obj[methodname].apply(obj, args); + } + if (_isTransformer(obj)) { + var transducer = xf.apply(null, args); + return transducer(obj); + } + } + return fn.apply(this, arguments); + }; +}; + +},{"./_isArray":635,"./_isTransformer":639,"./_slice":644}],628:[function(require,module,exports){ +var _arrayFromIterator = require('./_arrayFromIterator'); +var _functionName = require('./_functionName'); +var _has = require('./_has'); +var identical = require('../identical'); +var keys = require('../keys'); +var type = require('../type'); + + +module.exports = function _equals(a, b, stackA, stackB) { + if (identical(a, b)) { + return true; + } + + if (type(a) !== type(b)) { + return false; + } + + if (a == null || b == null) { + return false; + } + + if (typeof a.equals === 'function' || typeof b.equals === 'function') { + return typeof a.equals === 'function' && a.equals(b) && + typeof b.equals === 'function' && b.equals(a); + } + + switch (type(a)) { + case 'Arguments': + case 'Array': + case 'Object': + if (typeof a.constructor === 'function' && + _functionName(a.constructor) === 'Promise') { + return a === b; + } + break; + case 'Boolean': + case 'Number': + case 'String': + if (!(typeof a === typeof b && identical(a.valueOf(), b.valueOf()))) { + return false; + } + break; + case 'Date': + if (!identical(a.valueOf(), b.valueOf())) { + return false; + } + break; + case 'Error': + return a.name === b.name && a.message === b.message; + case 'RegExp': + if (!(a.source === b.source && + a.global === b.global && + a.ignoreCase === b.ignoreCase && + a.multiline === b.multiline && + a.sticky === b.sticky && + a.unicode === b.unicode)) { + return false; + } + break; + case 'Map': + case 'Set': + if (!_equals(_arrayFromIterator(a.entries()), _arrayFromIterator(b.entries()), stackA, stackB)) { + return false; + } + break; + case 'Int8Array': + case 'Uint8Array': + case 'Uint8ClampedArray': + case 'Int16Array': + case 'Uint16Array': + case 'Int32Array': + case 'Uint32Array': + case 'Float32Array': + case 'Float64Array': + break; + case 'ArrayBuffer': + break; + default: + // Values of other types are only equal if identical. + return false; + } + + var keysA = keys(a); + if (keysA.length !== keys(b).length) { + return false; + } + + var idx = stackA.length - 1; + while (idx >= 0) { + if (stackA[idx] === a) { + return stackB[idx] === b; + } + idx -= 1; + } + + stackA.push(a); + stackB.push(b); + idx = keysA.length - 1; + while (idx >= 0) { + var key = keysA[idx]; + if (!(_has(key, b) && _equals(b[key], a[key], stackA, stackB))) { + return false; + } + idx -= 1; + } + stackA.pop(); + stackB.pop(); + return true; +}; + +},{"../identical":616,"../keys":651,"../type":660,"./_arrayFromIterator":619,"./_functionName":630,"./_has":631}],629:[function(require,module,exports){ +module.exports = function _filter(fn, list) { + var idx = 0; + var len = list.length; + var result = []; + + while (idx < len) { + if (fn(list[idx])) { + result[result.length] = list[idx]; + } + idx += 1; + } + return result; +}; + +},{}],630:[function(require,module,exports){ +module.exports = function _functionName(f) { + // String(x => x) evaluates to "x => x", so the pattern may not match. + var match = String(f).match(/^function (\w*)/); + return match == null ? '' : match[1]; +}; + +},{}],631:[function(require,module,exports){ +module.exports = function _has(prop, obj) { + return Object.prototype.hasOwnProperty.call(obj, prop); +}; + +},{}],632:[function(require,module,exports){ +module.exports = function _identity(x) { return x; }; + +},{}],633:[function(require,module,exports){ +var equals = require('../equals'); + + +module.exports = function _indexOf(list, a, idx) { + var inf, item; + // Array.prototype.indexOf doesn't exist below IE9 + if (typeof list.indexOf === 'function') { + switch (typeof a) { + case 'number': + if (a === 0) { + // manually crawl the list to distinguish between +0 and -0 + inf = 1 / a; + while (idx < list.length) { + item = list[idx]; + if (item === 0 && 1 / item === inf) { + return idx; + } + idx += 1; + } + return -1; + } else if (a !== a) { + // NaN + while (idx < list.length) { + item = list[idx]; + if (typeof item === 'number' && item !== item) { + return idx; + } + idx += 1; + } + return -1; + } + // non-zero numbers can utilise Set + return list.indexOf(a, idx); + + // all these types can utilise Set + case 'string': + case 'boolean': + case 'function': + case 'undefined': + return list.indexOf(a, idx); + + case 'object': + if (a === null) { + // null can utilise Set + return list.indexOf(a, idx); + } + } + } + // anything else not covered above, defer to R.equals + while (idx < list.length) { + if (equals(list[idx], a)) { + return idx; + } + idx += 1; + } + return -1; +}; + +},{"../equals":613}],634:[function(require,module,exports){ +var _has = require('./_has'); + + +module.exports = (function() { + var toString = Object.prototype.toString; + return toString.call(arguments) === '[object Arguments]' ? + function _isArguments(x) { return toString.call(x) === '[object Arguments]'; } : + function _isArguments(x) { return _has('callee', x); }; +}()); + +},{"./_has":631}],635:[function(require,module,exports){ +/** + * Tests whether or not an object is an array. + * + * @private + * @param {*} val The object to test. + * @return {Boolean} `true` if `val` is an array, `false` otherwise. + * @example + * + * _isArray([]); //=> true + * _isArray(null); //=> false + * _isArray({}); //=> false + */ +module.exports = Array.isArray || function _isArray(val) { + return (val != null && + val.length >= 0 && + Object.prototype.toString.call(val) === '[object Array]'); +}; + +},{}],636:[function(require,module,exports){ +module.exports = function _isObject(x) { + return Object.prototype.toString.call(x) === '[object Object]'; +}; + +},{}],637:[function(require,module,exports){ +module.exports = function _isPlaceholder(a) { + return a != null && + typeof a === 'object' && + a['@@functional/placeholder'] === true; +}; + +},{}],638:[function(require,module,exports){ +module.exports = function _isString(x) { + return Object.prototype.toString.call(x) === '[object String]'; +}; + +},{}],639:[function(require,module,exports){ +module.exports = function _isTransformer(obj) { + return typeof obj['@@transducer/step'] === 'function'; +}; + +},{}],640:[function(require,module,exports){ +module.exports = function _map(fn, functor) { + var idx = 0; + var len = functor.length; + var result = Array(len); + while (idx < len) { + result[idx] = fn(functor[idx]); + idx += 1; + } + return result; +}; + +},{}],641:[function(require,module,exports){ +module.exports = function _pipe(f, g) { + return function() { + return g.call(this, f.apply(this, arguments)); + }; +}; + +},{}],642:[function(require,module,exports){ +module.exports = function _quote(s) { + var escaped = s + .replace(/\\/g, '\\\\') + .replace(/[\b]/g, '\\b') // \b matches word boundary; [\b] matches backspace + .replace(/\f/g, '\\f') + .replace(/\n/g, '\\n') + .replace(/\r/g, '\\r') + .replace(/\t/g, '\\t') + .replace(/\v/g, '\\v') + .replace(/\0/g, '\\0'); + + return '"' + escaped.replace(/"/g, '\\"') + '"'; +}; + +},{}],643:[function(require,module,exports){ +var _xwrap = require('./_xwrap'); +var bind = require('../bind'); +var isArrayLike = require('../isArrayLike'); + + +module.exports = (function() { + function _arrayReduce(xf, acc, list) { + var idx = 0; + var len = list.length; + while (idx < len) { + acc = xf['@@transducer/step'](acc, list[idx]); + if (acc && acc['@@transducer/reduced']) { + acc = acc['@@transducer/value']; + break; + } + idx += 1; + } + return xf['@@transducer/result'](acc); + } + + function _iterableReduce(xf, acc, iter) { + var step = iter.next(); + while (!step.done) { + acc = xf['@@transducer/step'](acc, step.value); + if (acc && acc['@@transducer/reduced']) { + acc = acc['@@transducer/value']; + break; + } + step = iter.next(); + } + return xf['@@transducer/result'](acc); + } + + function _methodReduce(xf, acc, obj) { + return xf['@@transducer/result'](obj.reduce(bind(xf['@@transducer/step'], xf), acc)); + } + + var symIterator = (typeof Symbol !== 'undefined') ? Symbol.iterator : '@@iterator'; + return function _reduce(fn, acc, list) { + if (typeof fn === 'function') { + fn = _xwrap(fn); + } + if (isArrayLike(list)) { + return _arrayReduce(fn, acc, list); + } + if (typeof list.reduce === 'function') { + return _methodReduce(fn, acc, list); + } + if (list[symIterator] != null) { + return _iterableReduce(fn, acc, list[symIterator]()); + } + if (typeof list.next === 'function') { + return _iterableReduce(fn, acc, list); + } + throw new TypeError('reduce: list must be array or iterable'); + }; +}()); + +},{"../bind":609,"../isArrayLike":650,"./_xwrap":649}],644:[function(require,module,exports){ +/** + * An optimized, private array `slice` implementation. + * + * @private + * @param {Arguments|Array} args The array or arguments object to consider. + * @param {Number} [from=0] The array index to slice from, inclusive. + * @param {Number} [to=args.length] The array index to slice to, exclusive. + * @return {Array} A new, sliced array. + * @example + * + * _slice([1, 2, 3, 4, 5], 1, 3); //=> [2, 3] + * + * var firstThreeArgs = function(a, b, c, d) { + * return _slice(arguments, 0, 3); + * }; + * firstThreeArgs(1, 2, 3, 4); //=> [1, 2, 3] + */ +module.exports = function _slice(args, from, to) { + switch (arguments.length) { + case 1: return _slice(args, 0, args.length); + case 2: return _slice(args, from, args.length); + default: + var list = []; + var idx = 0; + var len = Math.max(0, Math.min(args.length, to) - from); + while (idx < len) { + list[idx] = args[from + idx]; + idx += 1; + } + return list; + } +}; + +},{}],645:[function(require,module,exports){ +/** + * Polyfill from . + */ +module.exports = (function() { + var pad = function pad(n) { return (n < 10 ? '0' : '') + n; }; + + return typeof Date.prototype.toISOString === 'function' ? + function _toISOString(d) { + return d.toISOString(); + } : + function _toISOString(d) { + return ( + d.getUTCFullYear() + '-' + + pad(d.getUTCMonth() + 1) + '-' + + pad(d.getUTCDate()) + 'T' + + pad(d.getUTCHours()) + ':' + + pad(d.getUTCMinutes()) + ':' + + pad(d.getUTCSeconds()) + '.' + + (d.getUTCMilliseconds() / 1000).toFixed(3).slice(2, 5) + 'Z' + ); + }; +}()); + +},{}],646:[function(require,module,exports){ +var _contains = require('./_contains'); +var _map = require('./_map'); +var _quote = require('./_quote'); +var _toISOString = require('./_toISOString'); +var keys = require('../keys'); +var reject = require('../reject'); + + +module.exports = function _toString(x, seen) { + var recur = function recur(y) { + var xs = seen.concat([x]); + return _contains(y, xs) ? '' : _toString(y, xs); + }; + + // mapPairs :: (Object, [String]) -> [String] + var mapPairs = function(obj, keys) { + return _map(function(k) { return _quote(k) + ': ' + recur(obj[k]); }, keys.slice().sort()); + }; + + switch (Object.prototype.toString.call(x)) { + case '[object Arguments]': + return '(function() { return arguments; }(' + _map(recur, x).join(', ') + '))'; + case '[object Array]': + return '[' + _map(recur, x).concat(mapPairs(x, reject(function(k) { return /^\d+$/.test(k); }, keys(x)))).join(', ') + ']'; + case '[object Boolean]': + return typeof x === 'object' ? 'new Boolean(' + recur(x.valueOf()) + ')' : x.toString(); + case '[object Date]': + return 'new Date(' + (isNaN(x.valueOf()) ? recur(NaN) : _quote(_toISOString(x))) + ')'; + case '[object Null]': + return 'null'; + case '[object Number]': + return typeof x === 'object' ? 'new Number(' + recur(x.valueOf()) + ')' : 1 / x === -Infinity ? '-0' : x.toString(10); + case '[object String]': + return typeof x === 'object' ? 'new String(' + recur(x.valueOf()) + ')' : _quote(x); + case '[object Undefined]': + return 'undefined'; + default: + if (typeof x.toString === 'function') { + var repr = x.toString(); + if (repr !== '[object Object]') { + return repr; + } + } + return '{' + mapPairs(x, keys(x)).join(', ') + '}'; + } +}; + +},{"../keys":651,"../reject":655,"./_contains":622,"./_map":640,"./_quote":642,"./_toISOString":645}],647:[function(require,module,exports){ +module.exports = { + init: function() { + return this.xf['@@transducer/init'](); + }, + result: function(result) { + return this.xf['@@transducer/result'](result); + } +}; + +},{}],648:[function(require,module,exports){ +var _curry2 = require('./_curry2'); +var _xfBase = require('./_xfBase'); + + +module.exports = (function() { + function XFilter(f, xf) { + this.xf = xf; + this.f = f; + } + XFilter.prototype['@@transducer/init'] = _xfBase.init; + XFilter.prototype['@@transducer/result'] = _xfBase.result; + XFilter.prototype['@@transducer/step'] = function(result, input) { + return this.f(input) ? this.xf['@@transducer/step'](result, input) : result; + }; + + return _curry2(function _xfilter(f, xf) { return new XFilter(f, xf); }); +}()); + +},{"./_curry2":624,"./_xfBase":647}],649:[function(require,module,exports){ +module.exports = (function() { + function XWrap(fn) { + this.f = fn; + } + XWrap.prototype['@@transducer/init'] = function() { + throw new Error('init not implemented on XWrap'); + }; + XWrap.prototype['@@transducer/result'] = function(acc) { return acc; }; + XWrap.prototype['@@transducer/step'] = function(acc, x) { + return this.f(acc, x); + }; + + return function _xwrap(fn) { return new XWrap(fn); }; +}()); + +},{}],650:[function(require,module,exports){ +var _curry1 = require('./internal/_curry1'); +var _isArray = require('./internal/_isArray'); +var _isString = require('./internal/_isString'); + + +/** + * Tests whether or not an object is similar to an array. + * + * @func + * @memberOf R + * @since v0.5.0 + * @category Type + * @category List + * @sig * -> Boolean + * @param {*} x The object to test. + * @return {Boolean} `true` if `x` has a numeric length property and extreme indices defined; `false` otherwise. + * @example + * + * R.isArrayLike([]); //=> true + * R.isArrayLike(true); //=> false + * R.isArrayLike({}); //=> false + * R.isArrayLike({length: 10}); //=> false + * R.isArrayLike({0: 'zero', 9: 'nine', length: 10}); //=> true + */ +module.exports = _curry1(function isArrayLike(x) { + if (_isArray(x)) { return true; } + if (!x) { return false; } + if (typeof x !== 'object') { return false; } + if (_isString(x)) { return false; } + if (x.nodeType === 1) { return !!x.length; } + if (x.length === 0) { return true; } + if (x.length > 0) { + return x.hasOwnProperty(0) && x.hasOwnProperty(x.length - 1); + } + return false; +}); + +},{"./internal/_curry1":623,"./internal/_isArray":635,"./internal/_isString":638}],651:[function(require,module,exports){ +var _curry1 = require('./internal/_curry1'); +var _has = require('./internal/_has'); +var _isArguments = require('./internal/_isArguments'); + + +/** + * Returns a list containing the names of all the enumerable own properties of + * the supplied object. + * Note that the order of the output array is not guaranteed to be consistent + * across different JS platforms. + * + * @func + * @memberOf R + * @since v0.1.0 + * @category Object + * @sig {k: v} -> [k] + * @param {Object} obj The object to extract properties from + * @return {Array} An array of the object's own properties. + * @example + * + * R.keys({a: 1, b: 2, c: 3}); //=> ['a', 'b', 'c'] + */ +module.exports = (function() { + // cover IE < 9 keys issues + var hasEnumBug = !({toString: null}).propertyIsEnumerable('toString'); + var nonEnumerableProps = ['constructor', 'valueOf', 'isPrototypeOf', 'toString', + 'propertyIsEnumerable', 'hasOwnProperty', 'toLocaleString']; + // Safari bug + var hasArgsEnumBug = (function() { + 'use strict'; + return arguments.propertyIsEnumerable('length'); + }()); + + var contains = function contains(list, item) { + var idx = 0; + while (idx < list.length) { + if (list[idx] === item) { + return true; + } + idx += 1; + } + return false; + }; + + return typeof Object.keys === 'function' && !hasArgsEnumBug ? + _curry1(function keys(obj) { + return Object(obj) !== obj ? [] : Object.keys(obj); + }) : + _curry1(function keys(obj) { + if (Object(obj) !== obj) { + return []; + } + var prop, nIdx; + var ks = []; + var checkArgsLength = hasArgsEnumBug && _isArguments(obj); + for (prop in obj) { + if (_has(prop, obj) && (!checkArgsLength || prop !== 'length')) { + ks[ks.length] = prop; + } + } + if (hasEnumBug) { + nIdx = nonEnumerableProps.length - 1; + while (nIdx >= 0) { + prop = nonEnumerableProps[nIdx]; + if (_has(prop, obj) && !contains(ks, prop)) { + ks[ks.length] = prop; + } + nIdx -= 1; + } + } + return ks; + }); +}()); + +},{"./internal/_curry1":623,"./internal/_has":631,"./internal/_isArguments":634}],652:[function(require,module,exports){ +var _arity = require('./internal/_arity'); +var _curry1 = require('./internal/_curry1'); + + +/** + * Accepts a function `fn` and returns a function that guards invocation of + * `fn` such that `fn` can only ever be called once, no matter how many times + * the returned function is invoked. The first value calculated is returned in + * subsequent invocations. + * + * @func + * @memberOf R + * @since v0.1.0 + * @category Function + * @sig (a... -> b) -> (a... -> b) + * @param {Function} fn The function to wrap in a call-only-once wrapper. + * @return {Function} The wrapped function. + * @example + * + * var addOneOnce = R.once(x => x + 1); + * addOneOnce(10); //=> 11 + * addOneOnce(addOneOnce(50)); //=> 11 + */ +module.exports = _curry1(function once(fn) { + var called = false; + var result; + return _arity(fn.length, function() { + if (called) { + return result; + } + called = true; + result = fn.apply(this, arguments); + return result; + }); +}); + +},{"./internal/_arity":618,"./internal/_curry1":623}],653:[function(require,module,exports){ +var _arity = require('./internal/_arity'); +var _pipe = require('./internal/_pipe'); +var reduce = require('./reduce'); +var tail = require('./tail'); + + +/** + * Performs left-to-right function composition. The leftmost function may have + * any arity; the remaining functions must be unary. + * + * In some libraries this function is named `sequence`. + * + * **Note:** The result of pipe is not automatically curried. + * + * @func + * @memberOf R + * @since v0.1.0 + * @category Function + * @sig (((a, b, ..., n) -> o), (o -> p), ..., (x -> y), (y -> z)) -> ((a, b, ..., n) -> z) + * @param {...Function} functions + * @return {Function} + * @see R.compose + * @example + * + * var f = R.pipe(Math.pow, R.negate, R.inc); + * + * f(3, 4); // -(3^4) + 1 + */ +module.exports = function pipe() { + if (arguments.length === 0) { + throw new Error('pipe requires at least one argument'); + } + return _arity(arguments[0].length, + reduce(_pipe, arguments[0], tail(arguments))); +}; + +},{"./internal/_arity":618,"./internal/_pipe":641,"./reduce":654,"./tail":658}],654:[function(require,module,exports){ +var _curry3 = require('./internal/_curry3'); +var _reduce = require('./internal/_reduce'); + + +/** + * Returns a single item by iterating through the list, successively calling + * the iterator function and passing it an accumulator value and the current + * value from the array, and then passing the result to the next call. + * + * The iterator function receives two values: *(acc, value)*. It may use + * `R.reduced` to shortcut the iteration. + * + * Note: `R.reduce` does not skip deleted or unassigned indices (sparse + * arrays), unlike the native `Array.prototype.reduce` method. For more details + * on this behavior, see: + * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce#Description + * + * Dispatches to the `reduce` method of the third argument, if present. + * + * @func + * @memberOf R + * @since v0.1.0 + * @category List + * @sig ((a, b) -> a) -> a -> [b] -> a + * @param {Function} fn The iterator function. Receives two values, the accumulator and the + * current element from the array. + * @param {*} acc The accumulator value. + * @param {Array} list The list to iterate over. + * @return {*} The final, accumulated value. + * @see R.reduced, R.addIndex + * @example + * + * var numbers = [1, 2, 3]; + * var plus = (a, b) => a + b; + * + * R.reduce(plus, 10, numbers); //=> 16 + */ +module.exports = _curry3(_reduce); + +},{"./internal/_curry3":625,"./internal/_reduce":643}],655:[function(require,module,exports){ +var _complement = require('./internal/_complement'); +var _curry2 = require('./internal/_curry2'); +var filter = require('./filter'); + + +/** + * The complement of `filter`. + * + * Acts as a transducer if a transformer is given in list position. + * + * @func + * @memberOf R + * @since v0.1.0 + * @category List + * @sig Filterable f => (a -> Boolean) -> f a -> f a + * @param {Function} pred + * @param {Array} filterable + * @return {Array} + * @see R.filter, R.transduce, R.addIndex + * @example + * + * var isOdd = (n) => n % 2 === 1; + * + * R.reject(isOdd, [1, 2, 3, 4]); //=> [2, 4] + * + * R.reject(isOdd, {a: 1, b: 2, c: 3, d: 4}); //=> {b: 2, d: 4} + */ +module.exports = _curry2(function reject(pred, filterable) { + return filter(_complement(pred), filterable); +}); + +},{"./filter":614,"./internal/_complement":621,"./internal/_curry2":624}],656:[function(require,module,exports){ +var _curry1 = require('./internal/_curry1'); +var _isString = require('./internal/_isString'); +var _slice = require('./internal/_slice'); + + +/** + * Returns a new list or string with the elements or characters in reverse + * order. + * + * @func + * @memberOf R + * @since v0.1.0 + * @category List + * @sig [a] -> [a] + * @sig String -> String + * @param {Array|String} list + * @return {Array|String} + * @example + * + * R.reverse([1, 2, 3]); //=> [3, 2, 1] + * R.reverse([1, 2]); //=> [2, 1] + * R.reverse([1]); //=> [1] + * R.reverse([]); //=> [] + * + * R.reverse('abc'); //=> 'cba' + * R.reverse('ab'); //=> 'ba' + * R.reverse('a'); //=> 'a' + * R.reverse(''); //=> '' + */ +module.exports = _curry1(function reverse(list) { + return _isString(list) ? list.split('').reverse().join('') : + _slice(list).reverse(); +}); + +},{"./internal/_curry1":623,"./internal/_isString":638,"./internal/_slice":644}],657:[function(require,module,exports){ +var _checkForMethod = require('./internal/_checkForMethod'); +var _curry3 = require('./internal/_curry3'); + + +/** + * Returns the elements of the given list or string (or object with a `slice` + * method) from `fromIndex` (inclusive) to `toIndex` (exclusive). + * + * Dispatches to the `slice` method of the third argument, if present. + * + * @func + * @memberOf R + * @since v0.1.4 + * @category List + * @sig Number -> Number -> [a] -> [a] + * @sig Number -> Number -> String -> String + * @param {Number} fromIndex The start index (inclusive). + * @param {Number} toIndex The end index (exclusive). + * @param {*} list + * @return {*} + * @example + * + * R.slice(1, 3, ['a', 'b', 'c', 'd']); //=> ['b', 'c'] + * R.slice(1, Infinity, ['a', 'b', 'c', 'd']); //=> ['b', 'c', 'd'] + * R.slice(0, -1, ['a', 'b', 'c', 'd']); //=> ['a', 'b', 'c'] + * R.slice(-3, -1, ['a', 'b', 'c', 'd']); //=> ['b', 'c'] + * R.slice(0, 3, 'ramda'); //=> 'ram' + */ +module.exports = _curry3(_checkForMethod('slice', function slice(fromIndex, toIndex, list) { + return Array.prototype.slice.call(list, fromIndex, toIndex); +})); + +},{"./internal/_checkForMethod":620,"./internal/_curry3":625}],658:[function(require,module,exports){ +var _checkForMethod = require('./internal/_checkForMethod'); +var slice = require('./slice'); + + +/** + * Returns all but the first element of the given list or string (or object + * with a `tail` method). + * + * Dispatches to the `slice` method of the first argument, if present. + * + * @func + * @memberOf R + * @since v0.1.0 + * @category List + * @sig [a] -> [a] + * @sig String -> String + * @param {*} list + * @return {*} + * @see R.head, R.init, R.last + * @example + * + * R.tail([1, 2, 3]); //=> [2, 3] + * R.tail([1, 2]); //=> [2] + * R.tail([1]); //=> [] + * R.tail([]); //=> [] + * + * R.tail('abc'); //=> 'bc' + * R.tail('ab'); //=> 'b' + * R.tail('a'); //=> '' + * R.tail(''); //=> '' + */ +module.exports = _checkForMethod('tail', slice(1, Infinity)); + +},{"./internal/_checkForMethod":620,"./slice":657}],659:[function(require,module,exports){ +var _curry1 = require('./internal/_curry1'); +var _toString = require('./internal/_toString'); + + +/** + * Returns the string representation of the given value. `eval`'ing the output + * should result in a value equivalent to the input value. Many of the built-in + * `toString` methods do not satisfy this requirement. + * + * If the given value is an `[object Object]` with a `toString` method other + * than `Object.prototype.toString`, this method is invoked with no arguments + * to produce the return value. This means user-defined constructor functions + * can provide a suitable `toString` method. For example: + * + * function Point(x, y) { + * this.x = x; + * this.y = y; + * } + * + * Point.prototype.toString = function() { + * return 'new Point(' + this.x + ', ' + this.y + ')'; + * }; + * + * R.toString(new Point(1, 2)); //=> 'new Point(1, 2)' + * + * @func + * @memberOf R + * @since v0.14.0 + * @category String + * @sig * -> String + * @param {*} val + * @return {String} + * @example + * + * R.toString(42); //=> '42' + * R.toString('abc'); //=> '"abc"' + * R.toString([1, 2, 3]); //=> '[1, 2, 3]' + * R.toString({foo: 1, bar: 2, baz: 3}); //=> '{"bar": 2, "baz": 3, "foo": 1}' + * R.toString(new Date('2001-02-03T04:05:06Z')); //=> 'new Date("2001-02-03T04:05:06.000Z")' + */ +module.exports = _curry1(function toString(val) { return _toString(val, []); }); + +},{"./internal/_curry1":623,"./internal/_toString":646}],660:[function(require,module,exports){ +var _curry1 = require('./internal/_curry1'); + + +/** + * Gives a single-word string description of the (native) type of a value, + * returning such answers as 'Object', 'Number', 'Array', or 'Null'. Does not + * attempt to distinguish user Object types any further, reporting them all as + * 'Object'. + * + * @func + * @memberOf R + * @since v0.8.0 + * @category Type + * @sig (* -> {*}) -> String + * @param {*} val The value to test + * @return {String} + * @example + * + * R.type({}); //=> "Object" + * R.type(1); //=> "Number" + * R.type(false); //=> "Boolean" + * R.type('s'); //=> "String" + * R.type(null); //=> "Null" + * R.type([]); //=> "Array" + * R.type(/[A-z]/); //=> "RegExp" + */ +module.exports = _curry1(function type(val) { + return val === null ? 'Null' : + val === undefined ? 'Undefined' : + Object.prototype.toString.call(val).slice(8, -1); +}); + +},{"./internal/_curry1":623}],661:[function(require,module,exports){ +(function (global){ +(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.rdom = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o -1; +} + +function cfgElem(elem, attrs) { + var prop; + for (prop in attrs) { + if (attrs.hasOwnProperty(prop)) { + if (isElProp(prop)) { + elem[prop] = attrs[prop]; + } else { + elem.setAttribute(prop, attrs[prop]); + } + } + } + return elem; +} + +function mkChildren(elem, children) { + return children.reduce(function(elm, child) { + if (typeof child === 'string') { + elm.appendChild(document.createTextNode(child)); + } else { + elm.appendChild(child); + } + return elm; + }, elem); +} + +function rdom(tag, config, children) { + switch (arguments.length) { + case 0: + return rdom; + case 1: + return function _el1(conf, kids) { + switch (arguments.length) { + case 0: return _el1; + case 1: return function _el1_1(ks) { + var elem = document.createElement(tag); + return mkChildren(cfgElem(elem, conf), ks); + }; + default: + var elem = document.createElement(tag); + return mkChildren(cfgElem(elem, conf), kids); + } + }; + case 2: + return function _el2(cs) { + if (arguments.length === 0) { return _el2; } + var elem = document.createElement(tag); + return mkChildren(cfgElem(elem, config), cs); + }; + default: + var elem = document.createElement(tag); + return mkChildren(cfgElem(elem, config), children); + } +} + +rdom.addTags = function _rdomAddTags(ts, dest) { + return ts.reduce(function(acc, tagName) { + acc[tagName] = rdom(tagName); + return acc; + }, dest); +}; + +rdom.addTags(tags, rdom); + +module.exports = rdom; + +},{"./tags":1}]},{},[])("/src/rdom") +}); +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{}],662:[function(require,module,exports){ +(function (global){ +/*! https://mths.be/regenerate v1.3.1 by @mathias | MIT license */ +;(function(root) { + + // Detect free variables `exports`. + var freeExports = typeof exports == 'object' && exports; + + // Detect free variable `module`. + var freeModule = typeof module == 'object' && module && + module.exports == freeExports && module; + + // Detect free variable `global`, from Node.js/io.js or Browserified code, + // and use it as `root`. + var freeGlobal = typeof global == 'object' && global; + if (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal) { + root = freeGlobal; + } + + /*--------------------------------------------------------------------------*/ + + var ERRORS = { + 'rangeOrder': 'A range\u2019s `stop` value must be greater than or equal ' + + 'to the `start` value.', + 'codePointRange': 'Invalid code point value. Code points range from ' + + 'U+000000 to U+10FFFF.' + }; + + // https://mathiasbynens.be/notes/javascript-encoding#surrogate-pairs + var HIGH_SURROGATE_MIN = 0xD800; + var HIGH_SURROGATE_MAX = 0xDBFF; + var LOW_SURROGATE_MIN = 0xDC00; + var LOW_SURROGATE_MAX = 0xDFFF; + + // In Regenerate output, `\0` is never preceded by `\` because we sort by + // code point value, so let’s keep this regular expression simple. + var regexNull = /\\x00([^0123456789]|$)/g; + + var object = {}; + var hasOwnProperty = object.hasOwnProperty; + var extend = function(destination, source) { + var key; + for (key in source) { + if (hasOwnProperty.call(source, key)) { + destination[key] = source[key]; + } + } + return destination; + }; + + var forEach = function(array, callback) { + var index = -1; + var length = array.length; + while (++index < length) { + callback(array[index], index); + } + }; + + var toString = object.toString; + var isArray = function(value) { + return toString.call(value) == '[object Array]'; + }; + var isNumber = function(value) { + return typeof value == 'number' || + toString.call(value) == '[object Number]'; + }; + + // This assumes that `number` is a positive integer that `toString()`s nicely + // (which is the case for all code point values). + var zeroes = '0000'; + var pad = function(number, totalCharacters) { + var string = String(number); + return string.length < totalCharacters + ? (zeroes + string).slice(-totalCharacters) + : string; + }; + + var hex = function(number) { + return Number(number).toString(16).toUpperCase(); + }; + + var slice = [].slice; + + /*--------------------------------------------------------------------------*/ + + var dataFromCodePoints = function(codePoints) { + var index = -1; + var length = codePoints.length; + var max = length - 1; + var result = []; + var isStart = true; + var tmp; + var previous = 0; + while (++index < length) { + tmp = codePoints[index]; + if (isStart) { + result.push(tmp); + previous = tmp; + isStart = false; + } else { + if (tmp == previous + 1) { + if (index != max) { + previous = tmp; + continue; + } else { + isStart = true; + result.push(tmp + 1); + } + } else { + // End the previous range and start a new one. + result.push(previous + 1, tmp); + previous = tmp; + } + } + } + if (!isStart) { + result.push(tmp + 1); + } + return result; + }; + + var dataRemove = function(data, codePoint) { + // Iterate over the data per `(start, end)` pair. + var index = 0; + var start; + var end; + var length = data.length; + while (index < length) { + start = data[index]; + end = data[index + 1]; + if (codePoint >= start && codePoint < end) { + // Modify this pair. + if (codePoint == start) { + if (end == start + 1) { + // Just remove `start` and `end`. + data.splice(index, 2); + return data; + } else { + // Just replace `start` with a new value. + data[index] = codePoint + 1; + return data; + } + } else if (codePoint == end - 1) { + // Just replace `end` with a new value. + data[index + 1] = codePoint; + return data; + } else { + // Replace `[start, end]` with `[startA, endA, startB, endB]`. + data.splice(index, 2, start, codePoint, codePoint + 1, end); + return data; + } + } + index += 2; + } + return data; + }; + + var dataRemoveRange = function(data, rangeStart, rangeEnd) { + if (rangeEnd < rangeStart) { + throw Error(ERRORS.rangeOrder); + } + // Iterate over the data per `(start, end)` pair. + var index = 0; + var start; + var end; + while (index < data.length) { + start = data[index]; + end = data[index + 1] - 1; // Note: the `- 1` makes `end` inclusive. + + // Exit as soon as no more matching pairs can be found. + if (start > rangeEnd) { + return data; + } + + // Check if this range pair is equal to, or forms a subset of, the range + // to be removed. + // E.g. we have `[0, 11, 40, 51]` and want to remove 0-10 → `[40, 51]`. + // E.g. we have `[40, 51]` and want to remove 0-100 → `[]`. + if (rangeStart <= start && rangeEnd >= end) { + // Remove this pair. + data.splice(index, 2); + continue; + } + + // Check if both `rangeStart` and `rangeEnd` are within the bounds of + // this pair. + // E.g. we have `[0, 11]` and want to remove 4-6 → `[0, 4, 7, 11]`. + if (rangeStart >= start && rangeEnd < end) { + if (rangeStart == start) { + // Replace `[start, end]` with `[startB, endB]`. + data[index] = rangeEnd + 1; + data[index + 1] = end + 1; + return data; + } + // Replace `[start, end]` with `[startA, endA, startB, endB]`. + data.splice(index, 2, start, rangeStart, rangeEnd + 1, end + 1); + return data; + } + + // Check if only `rangeStart` is within the bounds of this pair. + // E.g. we have `[0, 11]` and want to remove 4-20 → `[0, 4]`. + if (rangeStart >= start && rangeStart <= end) { + // Replace `end` with `rangeStart`. + data[index + 1] = rangeStart; + // Note: we cannot `return` just yet, in case any following pairs still + // contain matching code points. + // E.g. we have `[0, 11, 14, 31]` and want to remove 4-20 + // → `[0, 4, 21, 31]`. + } + + // Check if only `rangeEnd` is within the bounds of this pair. + // E.g. we have `[14, 31]` and want to remove 4-20 → `[21, 31]`. + else if (rangeEnd >= start && rangeEnd <= end) { + // Just replace `start`. + data[index] = rangeEnd + 1; + return data; + } + + index += 2; + } + return data; + }; + + var dataAdd = function(data, codePoint) { + // Iterate over the data per `(start, end)` pair. + var index = 0; + var start; + var end; + var lastIndex = null; + var length = data.length; + if (codePoint < 0x0 || codePoint > 0x10FFFF) { + throw RangeError(ERRORS.codePointRange); + } + while (index < length) { + start = data[index]; + end = data[index + 1]; + + // Check if the code point is already in the set. + if (codePoint >= start && codePoint < end) { + return data; + } + + if (codePoint == start - 1) { + // Just replace `start` with a new value. + data[index] = codePoint; + return data; + } + + // At this point, if `start` is `greater` than `codePoint`, insert a new + // `[start, end]` pair before the current pair, or after the current pair + // if there is a known `lastIndex`. + if (start > codePoint) { + data.splice( + lastIndex != null ? lastIndex + 2 : 0, + 0, + codePoint, + codePoint + 1 + ); + return data; + } + + if (codePoint == end) { + // Check if adding this code point causes two separate ranges to become + // a single range, e.g. `dataAdd([0, 4, 5, 10], 4)` → `[0, 10]`. + if (codePoint + 1 == data[index + 2]) { + data.splice(index, 4, start, data[index + 3]); + return data; + } + // Else, just replace `end` with a new value. + data[index + 1] = codePoint + 1; + return data; + } + lastIndex = index; + index += 2; + } + // The loop has finished; add the new pair to the end of the data set. + data.push(codePoint, codePoint + 1); + return data; + }; + + var dataAddData = function(dataA, dataB) { + // Iterate over the data per `(start, end)` pair. + var index = 0; + var start; + var end; + var data = dataA.slice(); + var length = dataB.length; + while (index < length) { + start = dataB[index]; + end = dataB[index + 1] - 1; + if (start == end) { + data = dataAdd(data, start); + } else { + data = dataAddRange(data, start, end); + } + index += 2; + } + return data; + }; + + var dataRemoveData = function(dataA, dataB) { + // Iterate over the data per `(start, end)` pair. + var index = 0; + var start; + var end; + var data = dataA.slice(); + var length = dataB.length; + while (index < length) { + start = dataB[index]; + end = dataB[index + 1] - 1; + if (start == end) { + data = dataRemove(data, start); + } else { + data = dataRemoveRange(data, start, end); + } + index += 2; + } + return data; + }; + + var dataAddRange = function(data, rangeStart, rangeEnd) { + if (rangeEnd < rangeStart) { + throw Error(ERRORS.rangeOrder); + } + if ( + rangeStart < 0x0 || rangeStart > 0x10FFFF || + rangeEnd < 0x0 || rangeEnd > 0x10FFFF + ) { + throw RangeError(ERRORS.codePointRange); + } + // Iterate over the data per `(start, end)` pair. + var index = 0; + var start; + var end; + var added = false; + var length = data.length; + while (index < length) { + start = data[index]; + end = data[index + 1]; + + if (added) { + // The range has already been added to the set; at this point, we just + // need to get rid of the following ranges in case they overlap. + + // Check if this range can be combined with the previous range. + if (start == rangeEnd + 1) { + data.splice(index - 1, 2); + return data; + } + + // Exit as soon as no more possibly overlapping pairs can be found. + if (start > rangeEnd) { + return data; + } + + // E.g. `[0, 11, 12, 16]` and we’ve added 5-15, so we now have + // `[0, 16, 12, 16]`. Remove the `12,16` part, as it lies within the + // `0,16` range that was previously added. + if (start >= rangeStart && start <= rangeEnd) { + // `start` lies within the range that was previously added. + + if (end > rangeStart && end - 1 <= rangeEnd) { + // `end` lies within the range that was previously added as well, + // so remove this pair. + data.splice(index, 2); + index -= 2; + // Note: we cannot `return` just yet, as there may still be other + // overlapping pairs. + } else { + // `start` lies within the range that was previously added, but + // `end` doesn’t. E.g. `[0, 11, 12, 31]` and we’ve added 5-15, so + // now we have `[0, 16, 12, 31]`. This must be written as `[0, 31]`. + // Remove the previously added `end` and the current `start`. + data.splice(index - 1, 2); + index -= 2; + } + + // Note: we cannot return yet. + } + + } + + else if (start == rangeEnd + 1) { + data[index] = rangeStart; + return data; + } + + // Check if a new pair must be inserted *before* the current one. + else if (start > rangeEnd) { + data.splice(index, 0, rangeStart, rangeEnd + 1); + return data; + } + + else if (rangeStart >= start && rangeStart < end && rangeEnd + 1 <= end) { + // The new range lies entirely within an existing range pair. No action + // needed. + return data; + } + + else if ( + // E.g. `[0, 11]` and you add 5-15 → `[0, 16]`. + (rangeStart >= start && rangeStart < end) || + // E.g. `[0, 3]` and you add 3-6 → `[0, 7]`. + end == rangeStart + ) { + // Replace `end` with the new value. + data[index + 1] = rangeEnd + 1; + // Make sure the next range pair doesn’t overlap, e.g. `[0, 11, 12, 14]` + // and you add 5-15 → `[0, 16]`, i.e. remove the `12,14` part. + added = true; + // Note: we cannot `return` just yet. + } + + else if (rangeStart <= start && rangeEnd + 1 >= end) { + // The new range is a superset of the old range. + data[index] = rangeStart; + data[index + 1] = rangeEnd + 1; + added = true; + } + + index += 2; + } + // The loop has finished without doing anything; add the new pair to the end + // of the data set. + if (!added) { + data.push(rangeStart, rangeEnd + 1); + } + return data; + }; + + var dataContains = function(data, codePoint) { + var index = 0; + var length = data.length; + // Exit early if `codePoint` is not within `data`’s overall range. + var start = data[index]; + var end = data[length - 1]; + if (length >= 2) { + if (codePoint < start || codePoint > end) { + return false; + } + } + // Iterate over the data per `(start, end)` pair. + while (index < length) { + start = data[index]; + end = data[index + 1]; + if (codePoint >= start && codePoint < end) { + return true; + } + index += 2; + } + return false; + }; + + var dataIntersection = function(data, codePoints) { + var index = 0; + var length = codePoints.length; + var codePoint; + var result = []; + while (index < length) { + codePoint = codePoints[index]; + if (dataContains(data, codePoint)) { + result.push(codePoint); + } + ++index; + } + return dataFromCodePoints(result); + }; + + var dataIsEmpty = function(data) { + return !data.length; + }; + + var dataIsSingleton = function(data) { + // Check if the set only represents a single code point. + return data.length == 2 && data[0] + 1 == data[1]; + }; + + var dataToArray = function(data) { + // Iterate over the data per `(start, end)` pair. + var index = 0; + var start; + var end; + var result = []; + var length = data.length; + while (index < length) { + start = data[index]; + end = data[index + 1]; + while (start < end) { + result.push(start); + ++start; + } + index += 2; + } + return result; + }; + + /*--------------------------------------------------------------------------*/ + + // https://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae + var floor = Math.floor; + var highSurrogate = function(codePoint) { + return parseInt( + floor((codePoint - 0x10000) / 0x400) + HIGH_SURROGATE_MIN, + 10 + ); + }; + + var lowSurrogate = function(codePoint) { + return parseInt( + (codePoint - 0x10000) % 0x400 + LOW_SURROGATE_MIN, + 10 + ); + }; + + var stringFromCharCode = String.fromCharCode; + var codePointToString = function(codePoint) { + var string; + // https://mathiasbynens.be/notes/javascript-escapes#single + // Note: the `\b` escape sequence for U+0008 BACKSPACE in strings has a + // different meaning in regular expressions (word boundary), so it cannot + // be used here. + if (codePoint == 0x09) { + string = '\\t'; + } + // Note: IE < 9 treats `'\v'` as `'v'`, so avoid using it. + // else if (codePoint == 0x0B) { + // string = '\\v'; + // } + else if (codePoint == 0x0A) { + string = '\\n'; + } + else if (codePoint == 0x0C) { + string = '\\f'; + } + else if (codePoint == 0x0D) { + string = '\\r'; + } + else if (codePoint == 0x5C) { + string = '\\\\'; + } + else if ( + codePoint == 0x24 || + (codePoint >= 0x28 && codePoint <= 0x2B) || + codePoint == 0x2D || codePoint == 0x2E || codePoint == 0x3F || + (codePoint >= 0x5B && codePoint <= 0x5E) || + (codePoint >= 0x7B && codePoint <= 0x7D) + ) { + // The code point maps to an unsafe printable ASCII character; + // backslash-escape it. Here’s the list of those symbols: + // + // $()*+-.?[\]^{|} + // + // See #7 for more info. + string = '\\' + stringFromCharCode(codePoint); + } + else if (codePoint >= 0x20 && codePoint <= 0x7E) { + // The code point maps to one of these printable ASCII symbols + // (including the space character): + // + // !"#%&',/0123456789:;<=>@ABCDEFGHIJKLMNO + // PQRSTUVWXYZ_`abcdefghijklmnopqrstuvwxyz~ + // + // These can safely be used directly. + string = stringFromCharCode(codePoint); + } + else if (codePoint <= 0xFF) { + // https://mathiasbynens.be/notes/javascript-escapes#hexadecimal + string = '\\x' + pad(hex(codePoint), 2); + } + else { // `codePoint <= 0xFFFF` holds true. + // https://mathiasbynens.be/notes/javascript-escapes#unicode + string = '\\u' + pad(hex(codePoint), 4); + } + + // There’s no need to account for astral symbols / surrogate pairs here, + // since `codePointToString` is private and only used for BMP code points. + // But if that’s what you need, just add an `else` block with this code: + // + // string = '\\u' + pad(hex(highSurrogate(codePoint)), 4) + // + '\\u' + pad(hex(lowSurrogate(codePoint)), 4); + + return string; + }; + + var codePointToStringUnicode = function(codePoint) { + if (codePoint <= 0xFFFF) { + return codePointToString(codePoint); + } + return '\\u{' + codePoint.toString(16).toUpperCase() + '}'; + }; + + var symbolToCodePoint = function(symbol) { + var length = symbol.length; + var first = symbol.charCodeAt(0); + var second; + if ( + first >= HIGH_SURROGATE_MIN && first <= HIGH_SURROGATE_MAX && + length > 1 // There is a next code unit. + ) { + // `first` is a high surrogate, and there is a next character. Assume + // it’s a low surrogate (else it’s invalid usage of Regenerate anyway). + second = symbol.charCodeAt(1); + // https://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae + return (first - HIGH_SURROGATE_MIN) * 0x400 + + second - LOW_SURROGATE_MIN + 0x10000; + } + return first; + }; + + var createBMPCharacterClasses = function(data) { + // Iterate over the data per `(start, end)` pair. + var result = ''; + var index = 0; + var start; + var end; + var length = data.length; + if (dataIsSingleton(data)) { + return codePointToString(data[0]); + } + while (index < length) { + start = data[index]; + end = data[index + 1] - 1; // Note: the `- 1` makes `end` inclusive. + if (start == end) { + result += codePointToString(start); + } else if (start + 1 == end) { + result += codePointToString(start) + codePointToString(end); + } else { + result += codePointToString(start) + '-' + codePointToString(end); + } + index += 2; + } + return '[' + result + ']'; + }; + + var createUnicodeCharacterClasses = function(data) { + // Iterate over the data per `(start, end)` pair. + var result = ''; + var index = 0; + var start; + var end; + var length = data.length; + if (dataIsSingleton(data)) { + return codePointToStringUnicode(data[0]); + } + while (index < length) { + start = data[index]; + end = data[index + 1] - 1; // Note: the `- 1` makes `end` inclusive. + if (start == end) { + result += codePointToStringUnicode(start); + } else if (start + 1 == end) { + result += codePointToStringUnicode(start) + codePointToStringUnicode(end); + } else { + result += codePointToStringUnicode(start) + '-' + codePointToStringUnicode(end); + } + index += 2; + } + return '[' + result + ']'; + }; + + var splitAtBMP = function(data) { + // Iterate over the data per `(start, end)` pair. + var loneHighSurrogates = []; + var loneLowSurrogates = []; + var bmp = []; + var astral = []; + var index = 0; + var start; + var end; + var length = data.length; + while (index < length) { + start = data[index]; + end = data[index + 1] - 1; // Note: the `- 1` makes `end` inclusive. + + if (start < HIGH_SURROGATE_MIN) { + + // The range starts and ends before the high surrogate range. + // E.g. (0, 0x10). + if (end < HIGH_SURROGATE_MIN) { + bmp.push(start, end + 1); + } + + // The range starts before the high surrogate range and ends within it. + // E.g. (0, 0xD855). + if (end >= HIGH_SURROGATE_MIN && end <= HIGH_SURROGATE_MAX) { + bmp.push(start, HIGH_SURROGATE_MIN); + loneHighSurrogates.push(HIGH_SURROGATE_MIN, end + 1); + } + + // The range starts before the high surrogate range and ends in the low + // surrogate range. E.g. (0, 0xDCFF). + if (end >= LOW_SURROGATE_MIN && end <= LOW_SURROGATE_MAX) { + bmp.push(start, HIGH_SURROGATE_MIN); + loneHighSurrogates.push(HIGH_SURROGATE_MIN, HIGH_SURROGATE_MAX + 1); + loneLowSurrogates.push(LOW_SURROGATE_MIN, end + 1); + } + + // The range starts before the high surrogate range and ends after the + // low surrogate range. E.g. (0, 0x10FFFF). + if (end > LOW_SURROGATE_MAX) { + bmp.push(start, HIGH_SURROGATE_MIN); + loneHighSurrogates.push(HIGH_SURROGATE_MIN, HIGH_SURROGATE_MAX + 1); + loneLowSurrogates.push(LOW_SURROGATE_MIN, LOW_SURROGATE_MAX + 1); + if (end <= 0xFFFF) { + bmp.push(LOW_SURROGATE_MAX + 1, end + 1); + } else { + bmp.push(LOW_SURROGATE_MAX + 1, 0xFFFF + 1); + astral.push(0xFFFF + 1, end + 1); + } + } + + } else if (start >= HIGH_SURROGATE_MIN && start <= HIGH_SURROGATE_MAX) { + + // The range starts and ends in the high surrogate range. + // E.g. (0xD855, 0xD866). + if (end >= HIGH_SURROGATE_MIN && end <= HIGH_SURROGATE_MAX) { + loneHighSurrogates.push(start, end + 1); + } + + // The range starts in the high surrogate range and ends in the low + // surrogate range. E.g. (0xD855, 0xDCFF). + if (end >= LOW_SURROGATE_MIN && end <= LOW_SURROGATE_MAX) { + loneHighSurrogates.push(start, HIGH_SURROGATE_MAX + 1); + loneLowSurrogates.push(LOW_SURROGATE_MIN, end + 1); + } + + // The range starts in the high surrogate range and ends after the low + // surrogate range. E.g. (0xD855, 0x10FFFF). + if (end > LOW_SURROGATE_MAX) { + loneHighSurrogates.push(start, HIGH_SURROGATE_MAX + 1); + loneLowSurrogates.push(LOW_SURROGATE_MIN, LOW_SURROGATE_MAX + 1); + if (end <= 0xFFFF) { + bmp.push(LOW_SURROGATE_MAX + 1, end + 1); + } else { + bmp.push(LOW_SURROGATE_MAX + 1, 0xFFFF + 1); + astral.push(0xFFFF + 1, end + 1); + } + } + + } else if (start >= LOW_SURROGATE_MIN && start <= LOW_SURROGATE_MAX) { + + // The range starts and ends in the low surrogate range. + // E.g. (0xDCFF, 0xDDFF). + if (end >= LOW_SURROGATE_MIN && end <= LOW_SURROGATE_MAX) { + loneLowSurrogates.push(start, end + 1); + } + + // The range starts in the low surrogate range and ends after the low + // surrogate range. E.g. (0xDCFF, 0x10FFFF). + if (end > LOW_SURROGATE_MAX) { + loneLowSurrogates.push(start, LOW_SURROGATE_MAX + 1); + if (end <= 0xFFFF) { + bmp.push(LOW_SURROGATE_MAX + 1, end + 1); + } else { + bmp.push(LOW_SURROGATE_MAX + 1, 0xFFFF + 1); + astral.push(0xFFFF + 1, end + 1); + } + } + + } else if (start > LOW_SURROGATE_MAX && start <= 0xFFFF) { + + // The range starts and ends after the low surrogate range. + // E.g. (0xFFAA, 0x10FFFF). + if (end <= 0xFFFF) { + bmp.push(start, end + 1); + } else { + bmp.push(start, 0xFFFF + 1); + astral.push(0xFFFF + 1, end + 1); + } + + } else { + + // The range starts and ends in the astral range. + astral.push(start, end + 1); + + } + + index += 2; + } + return { + 'loneHighSurrogates': loneHighSurrogates, + 'loneLowSurrogates': loneLowSurrogates, + 'bmp': bmp, + 'astral': astral + }; + }; + + var optimizeSurrogateMappings = function(surrogateMappings) { + var result = []; + var tmpLow = []; + var addLow = false; + var mapping; + var nextMapping; + var highSurrogates; + var lowSurrogates; + var nextHighSurrogates; + var nextLowSurrogates; + var index = -1; + var length = surrogateMappings.length; + while (++index < length) { + mapping = surrogateMappings[index]; + nextMapping = surrogateMappings[index + 1]; + if (!nextMapping) { + result.push(mapping); + continue; + } + highSurrogates = mapping[0]; + lowSurrogates = mapping[1]; + nextHighSurrogates = nextMapping[0]; + nextLowSurrogates = nextMapping[1]; + + // Check for identical high surrogate ranges. + tmpLow = lowSurrogates; + while ( + nextHighSurrogates && + highSurrogates[0] == nextHighSurrogates[0] && + highSurrogates[1] == nextHighSurrogates[1] + ) { + // Merge with the next item. + if (dataIsSingleton(nextLowSurrogates)) { + tmpLow = dataAdd(tmpLow, nextLowSurrogates[0]); + } else { + tmpLow = dataAddRange( + tmpLow, + nextLowSurrogates[0], + nextLowSurrogates[1] - 1 + ); + } + ++index; + mapping = surrogateMappings[index]; + highSurrogates = mapping[0]; + lowSurrogates = mapping[1]; + nextMapping = surrogateMappings[index + 1]; + nextHighSurrogates = nextMapping && nextMapping[0]; + nextLowSurrogates = nextMapping && nextMapping[1]; + addLow = true; + } + result.push([ + highSurrogates, + addLow ? tmpLow : lowSurrogates + ]); + addLow = false; + } + return optimizeByLowSurrogates(result); + }; + + var optimizeByLowSurrogates = function(surrogateMappings) { + if (surrogateMappings.length == 1) { + return surrogateMappings; + } + var index = -1; + var innerIndex = -1; + while (++index < surrogateMappings.length) { + var mapping = surrogateMappings[index]; + var lowSurrogates = mapping[1]; + var lowSurrogateStart = lowSurrogates[0]; + var lowSurrogateEnd = lowSurrogates[1]; + innerIndex = index; // Note: the loop starts at the next index. + while (++innerIndex < surrogateMappings.length) { + var otherMapping = surrogateMappings[innerIndex]; + var otherLowSurrogates = otherMapping[1]; + var otherLowSurrogateStart = otherLowSurrogates[0]; + var otherLowSurrogateEnd = otherLowSurrogates[1]; + if ( + lowSurrogateStart == otherLowSurrogateStart && + lowSurrogateEnd == otherLowSurrogateEnd + ) { + // Add the code points in the other item to this one. + if (dataIsSingleton(otherMapping[0])) { + mapping[0] = dataAdd(mapping[0], otherMapping[0][0]); + } else { + mapping[0] = dataAddRange( + mapping[0], + otherMapping[0][0], + otherMapping[0][1] - 1 + ); + } + // Remove the other, now redundant, item. + surrogateMappings.splice(innerIndex, 1); + --innerIndex; + } + } + } + return surrogateMappings; + }; + + var surrogateSet = function(data) { + // Exit early if `data` is an empty set. + if (!data.length) { + return []; + } + + // Iterate over the data per `(start, end)` pair. + var index = 0; + var start; + var end; + var startHigh; + var startLow; + var prevStartHigh = 0; + var prevEndHigh = 0; + var tmpLow = []; + var endHigh; + var endLow; + var surrogateMappings = []; + var length = data.length; + var dataHigh = []; + while (index < length) { + start = data[index]; + end = data[index + 1] - 1; + + startHigh = highSurrogate(start); + startLow = lowSurrogate(start); + endHigh = highSurrogate(end); + endLow = lowSurrogate(end); + + var startsWithLowestLowSurrogate = startLow == LOW_SURROGATE_MIN; + var endsWithHighestLowSurrogate = endLow == LOW_SURROGATE_MAX; + var complete = false; + + // Append the previous high-surrogate-to-low-surrogate mappings. + // Step 1: `(startHigh, startLow)` to `(startHigh, LOW_SURROGATE_MAX)`. + if ( + startHigh == endHigh || + startsWithLowestLowSurrogate && endsWithHighestLowSurrogate + ) { + surrogateMappings.push([ + [startHigh, endHigh + 1], + [startLow, endLow + 1] + ]); + complete = true; + } else { + surrogateMappings.push([ + [startHigh, startHigh + 1], + [startLow, LOW_SURROGATE_MAX + 1] + ]); + } + + // Step 2: `(startHigh + 1, LOW_SURROGATE_MIN)` to + // `(endHigh - 1, LOW_SURROGATE_MAX)`. + if (!complete && startHigh + 1 < endHigh) { + if (endsWithHighestLowSurrogate) { + // Combine step 2 and step 3. + surrogateMappings.push([ + [startHigh + 1, endHigh + 1], + [LOW_SURROGATE_MIN, endLow + 1] + ]); + complete = true; + } else { + surrogateMappings.push([ + [startHigh + 1, endHigh], + [LOW_SURROGATE_MIN, LOW_SURROGATE_MAX + 1] + ]); + } + } + + // Step 3. `(endHigh, LOW_SURROGATE_MIN)` to `(endHigh, endLow)`. + if (!complete) { + surrogateMappings.push([ + [endHigh, endHigh + 1], + [LOW_SURROGATE_MIN, endLow + 1] + ]); + } + + prevStartHigh = startHigh; + prevEndHigh = endHigh; + + index += 2; + } + + // The format of `surrogateMappings` is as follows: + // + // [ surrogateMapping1, surrogateMapping2 ] + // + // i.e.: + // + // [ + // [ highSurrogates1, lowSurrogates1 ], + // [ highSurrogates2, lowSurrogates2 ] + // ] + return optimizeSurrogateMappings(surrogateMappings); + }; + + var createSurrogateCharacterClasses = function(surrogateMappings) { + var result = []; + forEach(surrogateMappings, function(surrogateMapping) { + var highSurrogates = surrogateMapping[0]; + var lowSurrogates = surrogateMapping[1]; + result.push( + createBMPCharacterClasses(highSurrogates) + + createBMPCharacterClasses(lowSurrogates) + ); + }); + return result.join('|'); + }; + + var createCharacterClassesFromData = function(data, bmpOnly, hasUnicodeFlag) { + if (hasUnicodeFlag) { + return createUnicodeCharacterClasses(data); + } + var result = []; + + var parts = splitAtBMP(data); + var loneHighSurrogates = parts.loneHighSurrogates; + var loneLowSurrogates = parts.loneLowSurrogates; + var bmp = parts.bmp; + var astral = parts.astral; + var hasAstral = !dataIsEmpty(parts.astral); + var hasLoneHighSurrogates = !dataIsEmpty(loneHighSurrogates); + var hasLoneLowSurrogates = !dataIsEmpty(loneLowSurrogates); + + var surrogateMappings = surrogateSet(astral); + + if (bmpOnly) { + bmp = dataAddData(bmp, loneHighSurrogates); + hasLoneHighSurrogates = false; + bmp = dataAddData(bmp, loneLowSurrogates); + hasLoneLowSurrogates = false; + } + + if (!dataIsEmpty(bmp)) { + // The data set contains BMP code points that are not high surrogates + // needed for astral code points in the set. + result.push(createBMPCharacterClasses(bmp)); + } + if (surrogateMappings.length) { + // The data set contains astral code points; append character classes + // based on their surrogate pairs. + result.push(createSurrogateCharacterClasses(surrogateMappings)); + } + // https://gist.github.com/mathiasbynens/bbe7f870208abcfec860 + if (hasLoneHighSurrogates) { + result.push( + createBMPCharacterClasses(loneHighSurrogates) + + // Make sure the high surrogates aren’t part of a surrogate pair. + '(?![\\uDC00-\\uDFFF])' + ); + } + if (hasLoneLowSurrogates) { + result.push( + // It is not possible to accurately assert the low surrogates aren’t + // part of a surrogate pair, since JavaScript regular expressions do + // not support lookbehind. + '(?:[^\\uD800-\\uDBFF]|^)' + + createBMPCharacterClasses(loneLowSurrogates) + ); + } + return result.join('|'); + }; + + /*--------------------------------------------------------------------------*/ + + // `regenerate` can be used as a constructor (and new methods can be added to + // its prototype) but also as a regular function, the latter of which is the + // documented and most common usage. For that reason, it’s not capitalized. + var regenerate = function(value) { + if (arguments.length > 1) { + value = slice.call(arguments); + } + if (this instanceof regenerate) { + this.data = []; + return value ? this.add(value) : this; + } + return (new regenerate).add(value); + }; + + regenerate.version = '1.3.1'; + + var proto = regenerate.prototype; + extend(proto, { + 'add': function(value) { + var $this = this; + if (value == null) { + return $this; + } + if (value instanceof regenerate) { + // Allow passing other Regenerate instances. + $this.data = dataAddData($this.data, value.data); + return $this; + } + if (arguments.length > 1) { + value = slice.call(arguments); + } + if (isArray(value)) { + forEach(value, function(item) { + $this.add(item); + }); + return $this; + } + $this.data = dataAdd( + $this.data, + isNumber(value) ? value : symbolToCodePoint(value) + ); + return $this; + }, + 'remove': function(value) { + var $this = this; + if (value == null) { + return $this; + } + if (value instanceof regenerate) { + // Allow passing other Regenerate instances. + $this.data = dataRemoveData($this.data, value.data); + return $this; + } + if (arguments.length > 1) { + value = slice.call(arguments); + } + if (isArray(value)) { + forEach(value, function(item) { + $this.remove(item); + }); + return $this; + } + $this.data = dataRemove( + $this.data, + isNumber(value) ? value : symbolToCodePoint(value) + ); + return $this; + }, + 'addRange': function(start, end) { + var $this = this; + $this.data = dataAddRange($this.data, + isNumber(start) ? start : symbolToCodePoint(start), + isNumber(end) ? end : symbolToCodePoint(end) + ); + return $this; + }, + 'removeRange': function(start, end) { + var $this = this; + var startCodePoint = isNumber(start) ? start : symbolToCodePoint(start); + var endCodePoint = isNumber(end) ? end : symbolToCodePoint(end); + $this.data = dataRemoveRange( + $this.data, + startCodePoint, + endCodePoint + ); + return $this; + }, + 'intersection': function(argument) { + var $this = this; + // Allow passing other Regenerate instances. + // TODO: Optimize this by writing and using `dataIntersectionData()`. + var array = argument instanceof regenerate ? + dataToArray(argument.data) : + argument; + $this.data = dataIntersection($this.data, array); + return $this; + }, + 'contains': function(codePoint) { + return dataContains( + this.data, + isNumber(codePoint) ? codePoint : symbolToCodePoint(codePoint) + ); + }, + 'clone': function() { + var set = new regenerate; + set.data = this.data.slice(0); + return set; + }, + 'toString': function(options) { + var result = createCharacterClassesFromData( + this.data, + options ? options.bmpOnly : false, + options ? options.hasUnicodeFlag : false + ); + if (!result) { + // For an empty set, return something that can be inserted `/here/` to + // form a valid regular expression. Avoid `(?:)` since that matches the + // empty string. + return '[]'; + } + // Use `\0` instead of `\x00` where possible. + return result.replace(regexNull, '\\0$1'); + }, + 'toRegExp': function(flags) { + var pattern = this.toString( + flags && flags.indexOf('u') != -1 ? + { 'hasUnicodeFlag': true } : + null + ); + return RegExp(pattern, flags || ''); + }, + 'valueOf': function() { // Note: `valueOf` is aliased as `toArray`. + return dataToArray(this.data); + } + }); + + proto.toArray = proto.valueOf; + + // Some AMD build optimizers, like r.js, check for specific condition patterns + // like the following: + if ( + typeof define == 'function' && + typeof define.amd == 'object' && + define.amd + ) { + define(function() { + return regenerate; + }); + } else if (freeExports && !freeExports.nodeType) { + if (freeModule) { // in Node.js, io.js, or RingoJS v0.8.0+ + freeModule.exports = regenerate; + } else { // in Narwhal or RingoJS v0.7.0- + freeExports.regenerate = regenerate; + } + } else { // in Rhino or a web browser + root.regenerate = regenerate; + } + +}(this)); + +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{}],663:[function(require,module,exports){ +// Generated by `/scripts/character-class-escape-sets.js`. Do not edit. +var regenerate = require('regenerate'); + +exports.REGULAR = { + 'd': regenerate() + .addRange(0x30, 0x39), + 'D': regenerate() + .addRange(0x0, 0x2F) + .addRange(0x3A, 0xFFFF), + 's': regenerate(0x20, 0xA0, 0x1680, 0x202F, 0x205F, 0x3000, 0xFEFF) + .addRange(0x9, 0xD) + .addRange(0x2000, 0x200A) + .addRange(0x2028, 0x2029), + 'S': regenerate() + .addRange(0x0, 0x8) + .addRange(0xE, 0x1F) + .addRange(0x21, 0x9F) + .addRange(0xA1, 0x167F) + .addRange(0x1681, 0x1FFF) + .addRange(0x200B, 0x2027) + .addRange(0x202A, 0x202E) + .addRange(0x2030, 0x205E) + .addRange(0x2060, 0x2FFF) + .addRange(0x3001, 0xFEFE) + .addRange(0xFF00, 0xFFFF), + 'w': regenerate(0x5F) + .addRange(0x30, 0x39) + .addRange(0x41, 0x5A) + .addRange(0x61, 0x7A), + 'W': regenerate(0x60) + .addRange(0x0, 0x2F) + .addRange(0x3A, 0x40) + .addRange(0x5B, 0x5E) + .addRange(0x7B, 0xFFFF) +}; + +exports.UNICODE = { + 'd': regenerate() + .addRange(0x30, 0x39), + 'D': regenerate() + .addRange(0x0, 0x2F) + .addRange(0x3A, 0x10FFFF), + 's': regenerate(0x20, 0xA0, 0x1680, 0x202F, 0x205F, 0x3000, 0xFEFF) + .addRange(0x9, 0xD) + .addRange(0x2000, 0x200A) + .addRange(0x2028, 0x2029), + 'S': regenerate() + .addRange(0x0, 0x8) + .addRange(0xE, 0x1F) + .addRange(0x21, 0x9F) + .addRange(0xA1, 0x167F) + .addRange(0x1681, 0x1FFF) + .addRange(0x200B, 0x2027) + .addRange(0x202A, 0x202E) + .addRange(0x2030, 0x205E) + .addRange(0x2060, 0x2FFF) + .addRange(0x3001, 0xFEFE) + .addRange(0xFF00, 0x10FFFF), + 'w': regenerate(0x5F) + .addRange(0x30, 0x39) + .addRange(0x41, 0x5A) + .addRange(0x61, 0x7A), + 'W': regenerate(0x60) + .addRange(0x0, 0x2F) + .addRange(0x3A, 0x40) + .addRange(0x5B, 0x5E) + .addRange(0x7B, 0x10FFFF) +}; + +exports.UNICODE_IGNORE_CASE = { + 'd': regenerate() + .addRange(0x30, 0x39), + 'D': regenerate() + .addRange(0x0, 0x2F) + .addRange(0x3A, 0x10FFFF), + 's': regenerate(0x20, 0xA0, 0x1680, 0x202F, 0x205F, 0x3000, 0xFEFF) + .addRange(0x9, 0xD) + .addRange(0x2000, 0x200A) + .addRange(0x2028, 0x2029), + 'S': regenerate() + .addRange(0x0, 0x8) + .addRange(0xE, 0x1F) + .addRange(0x21, 0x9F) + .addRange(0xA1, 0x167F) + .addRange(0x1681, 0x1FFF) + .addRange(0x200B, 0x2027) + .addRange(0x202A, 0x202E) + .addRange(0x2030, 0x205E) + .addRange(0x2060, 0x2FFF) + .addRange(0x3001, 0xFEFE) + .addRange(0xFF00, 0x10FFFF), + 'w': regenerate(0x5F, 0x17F, 0x212A) + .addRange(0x30, 0x39) + .addRange(0x41, 0x5A) + .addRange(0x61, 0x7A), + 'W': regenerate(0x4B, 0x53, 0x60) + .addRange(0x0, 0x2F) + .addRange(0x3A, 0x40) + .addRange(0x5B, 0x5E) + .addRange(0x7B, 0x10FFFF) +}; + +},{"regenerate":662}],664:[function(require,module,exports){ +module.exports={ + "75": 8490, + "83": 383, + "107": 8490, + "115": 383, + "181": 924, + "197": 8491, + "383": 83, + "452": 453, + "453": 452, + "455": 456, + "456": 455, + "458": 459, + "459": 458, + "497": 498, + "498": 497, + "837": 8126, + "914": 976, + "917": 1013, + "920": 1012, + "921": 8126, + "922": 1008, + "924": 181, + "928": 982, + "929": 1009, + "931": 962, + "934": 981, + "937": 8486, + "962": 931, + "976": 914, + "977": 1012, + "981": 934, + "982": 928, + "1008": 922, + "1009": 929, + "1012": [ + 920, + 977 + ], + "1013": 917, + "7776": 7835, + "7835": 7776, + "8126": [ + 837, + 921 + ], + "8486": 937, + "8490": 75, + "8491": 197, + "66560": 66600, + "66561": 66601, + "66562": 66602, + "66563": 66603, + "66564": 66604, + "66565": 66605, + "66566": 66606, + "66567": 66607, + "66568": 66608, + "66569": 66609, + "66570": 66610, + "66571": 66611, + "66572": 66612, + "66573": 66613, + "66574": 66614, + "66575": 66615, + "66576": 66616, + "66577": 66617, + "66578": 66618, + "66579": 66619, + "66580": 66620, + "66581": 66621, + "66582": 66622, + "66583": 66623, + "66584": 66624, + "66585": 66625, + "66586": 66626, + "66587": 66627, + "66588": 66628, + "66589": 66629, + "66590": 66630, + "66591": 66631, + "66592": 66632, + "66593": 66633, + "66594": 66634, + "66595": 66635, + "66596": 66636, + "66597": 66637, + "66598": 66638, + "66599": 66639, + "66600": 66560, + "66601": 66561, + "66602": 66562, + "66603": 66563, + "66604": 66564, + "66605": 66565, + "66606": 66566, + "66607": 66567, + "66608": 66568, + "66609": 66569, + "66610": 66570, + "66611": 66571, + "66612": 66572, + "66613": 66573, + "66614": 66574, + "66615": 66575, + "66616": 66576, + "66617": 66577, + "66618": 66578, + "66619": 66579, + "66620": 66580, + "66621": 66581, + "66622": 66582, + "66623": 66583, + "66624": 66584, + "66625": 66585, + "66626": 66586, + "66627": 66587, + "66628": 66588, + "66629": 66589, + "66630": 66590, + "66631": 66591, + "66632": 66592, + "66633": 66593, + "66634": 66594, + "66635": 66595, + "66636": 66596, + "66637": 66597, + "66638": 66598, + "66639": 66599, + "68736": 68800, + "68737": 68801, + "68738": 68802, + "68739": 68803, + "68740": 68804, + "68741": 68805, + "68742": 68806, + "68743": 68807, + "68744": 68808, + "68745": 68809, + "68746": 68810, + "68747": 68811, + "68748": 68812, + "68749": 68813, + "68750": 68814, + "68751": 68815, + "68752": 68816, + "68753": 68817, + "68754": 68818, + "68755": 68819, + "68756": 68820, + "68757": 68821, + "68758": 68822, + "68759": 68823, + "68760": 68824, + "68761": 68825, + "68762": 68826, + "68763": 68827, + "68764": 68828, + "68765": 68829, + "68766": 68830, + "68767": 68831, + "68768": 68832, + "68769": 68833, + "68770": 68834, + "68771": 68835, + "68772": 68836, + "68773": 68837, + "68774": 68838, + "68775": 68839, + "68776": 68840, + "68777": 68841, + "68778": 68842, + "68779": 68843, + "68780": 68844, + "68781": 68845, + "68782": 68846, + "68783": 68847, + "68784": 68848, + "68785": 68849, + "68786": 68850, + "68800": 68736, + "68801": 68737, + "68802": 68738, + "68803": 68739, + "68804": 68740, + "68805": 68741, + "68806": 68742, + "68807": 68743, + "68808": 68744, + "68809": 68745, + "68810": 68746, + "68811": 68747, + "68812": 68748, + "68813": 68749, + "68814": 68750, + "68815": 68751, + "68816": 68752, + "68817": 68753, + "68818": 68754, + "68819": 68755, + "68820": 68756, + "68821": 68757, + "68822": 68758, + "68823": 68759, + "68824": 68760, + "68825": 68761, + "68826": 68762, + "68827": 68763, + "68828": 68764, + "68829": 68765, + "68830": 68766, + "68831": 68767, + "68832": 68768, + "68833": 68769, + "68834": 68770, + "68835": 68771, + "68836": 68772, + "68837": 68773, + "68838": 68774, + "68839": 68775, + "68840": 68776, + "68841": 68777, + "68842": 68778, + "68843": 68779, + "68844": 68780, + "68845": 68781, + "68846": 68782, + "68847": 68783, + "68848": 68784, + "68849": 68785, + "68850": 68786, + "71840": 71872, + "71841": 71873, + "71842": 71874, + "71843": 71875, + "71844": 71876, + "71845": 71877, + "71846": 71878, + "71847": 71879, + "71848": 71880, + "71849": 71881, + "71850": 71882, + "71851": 71883, + "71852": 71884, + "71853": 71885, + "71854": 71886, + "71855": 71887, + "71856": 71888, + "71857": 71889, + "71858": 71890, + "71859": 71891, + "71860": 71892, + "71861": 71893, + "71862": 71894, + "71863": 71895, + "71864": 71896, + "71865": 71897, + "71866": 71898, + "71867": 71899, + "71868": 71900, + "71869": 71901, + "71870": 71902, + "71871": 71903, + "71872": 71840, + "71873": 71841, + "71874": 71842, + "71875": 71843, + "71876": 71844, + "71877": 71845, + "71878": 71846, + "71879": 71847, + "71880": 71848, + "71881": 71849, + "71882": 71850, + "71883": 71851, + "71884": 71852, + "71885": 71853, + "71886": 71854, + "71887": 71855, + "71888": 71856, + "71889": 71857, + "71890": 71858, + "71891": 71859, + "71892": 71860, + "71893": 71861, + "71894": 71862, + "71895": 71863, + "71896": 71864, + "71897": 71865, + "71898": 71866, + "71899": 71867, + "71900": 71868, + "71901": 71869, + "71902": 71870, + "71903": 71871 +} + +},{}],665:[function(require,module,exports){ +var generate = require('regjsgen').generate; +var parse = require('regjsparser').parse; +var regenerate = require('regenerate'); +var iuMappings = require('./data/iu-mappings.json'); +var ESCAPE_SETS = require('./data/character-class-escape-sets.js'); + +function getCharacterClassEscapeSet(character) { + if (unicode) { + if (ignoreCase) { + return ESCAPE_SETS.UNICODE_IGNORE_CASE[character]; + } + return ESCAPE_SETS.UNICODE[character]; + } + return ESCAPE_SETS.REGULAR[character]; +} + +var object = {}; +var hasOwnProperty = object.hasOwnProperty; +function has(object, property) { + return hasOwnProperty.call(object, property); +} + +// Prepare a Regenerate set containing all code points, used for negative +// character classes (if any). +var UNICODE_SET = regenerate().addRange(0x0, 0x10FFFF); +// Without the `u` flag, the range stops at 0xFFFF. +// https://mths.be/es6#sec-pattern-semantics +var BMP_SET = regenerate().addRange(0x0, 0xFFFF); + +// Prepare a Regenerate set containing all code points that are supposed to be +// matched by `/./u`. https://mths.be/es6#sec-atom +var DOT_SET_UNICODE = UNICODE_SET.clone() // all Unicode code points + .remove( + // minus `LineTerminator`s (https://mths.be/es6#sec-line-terminators): + 0x000A, // Line Feed + 0x000D, // Carriage Return + 0x2028, // Line Separator + 0x2029 // Paragraph Separator + ); +// Prepare a Regenerate set containing all code points that are supposed to be +// matched by `/./` (only BMP code points). +var DOT_SET = DOT_SET_UNICODE.clone() + .intersection(BMP_SET); + +// Add a range of code points + any case-folded code points in that range to a +// set. +regenerate.prototype.iuAddRange = function(min, max) { + var $this = this; + do { + var folded = caseFold(min); + if (folded) { + $this.add(folded); + } + } while (++min <= max); + return $this; +}; + +function assign(target, source) { + for (var key in source) { + // Note: `hasOwnProperty` is not needed here. + target[key] = source[key]; + } +} + +function update(item, pattern) { + // TODO: Test if memoizing `pattern` here is worth the effort. + if (!pattern) { + return; + } + var tree = parse(pattern, ''); + switch (tree.type) { + case 'characterClass': + case 'group': + case 'value': + // No wrapping needed. + break; + default: + // Wrap the pattern in a non-capturing group. + tree = wrap(tree, pattern); + } + assign(item, tree); +} + +function wrap(tree, pattern) { + // Wrap the pattern in a non-capturing group. + return { + 'type': 'group', + 'behavior': 'ignore', + 'body': [tree], + 'raw': '(?:' + pattern + ')' + }; +} + +function caseFold(codePoint) { + return has(iuMappings, codePoint) ? iuMappings[codePoint] : false; +} + +var ignoreCase = false; +var unicode = false; +function processCharacterClass(characterClassItem) { + var set = regenerate(); + var body = characterClassItem.body.forEach(function(item) { + switch (item.type) { + case 'value': + set.add(item.codePoint); + if (ignoreCase && unicode) { + var folded = caseFold(item.codePoint); + if (folded) { + set.add(folded); + } + } + break; + case 'characterClassRange': + var min = item.min.codePoint; + var max = item.max.codePoint; + set.addRange(min, max); + if (ignoreCase && unicode) { + set.iuAddRange(min, max); + } + break; + case 'characterClassEscape': + set.add(getCharacterClassEscapeSet(item.value)); + break; + // The `default` clause is only here as a safeguard; it should never be + // reached. Code coverage tools should ignore it. + /* istanbul ignore next */ + default: + throw Error('Unknown term type: ' + item.type); + } + }); + if (characterClassItem.negative) { + set = (unicode ? UNICODE_SET : BMP_SET).clone().remove(set); + } + update(characterClassItem, set.toString()); + return characterClassItem; +} + +function processTerm(item) { + switch (item.type) { + case 'dot': + update( + item, + (unicode ? DOT_SET_UNICODE : DOT_SET).toString() + ); + break; + case 'characterClass': + item = processCharacterClass(item); + break; + case 'characterClassEscape': + update( + item, + getCharacterClassEscapeSet(item.value).toString() + ); + break; + case 'alternative': + case 'disjunction': + case 'group': + case 'quantifier': + item.body = item.body.map(processTerm); + break; + case 'value': + var codePoint = item.codePoint; + var set = regenerate(codePoint); + if (ignoreCase && unicode) { + var folded = caseFold(codePoint); + if (folded) { + set.add(folded); + } + } + update(item, set.toString()); + break; + case 'anchor': + case 'empty': + case 'group': + case 'reference': + // Nothing to do here. + break; + // The `default` clause is only here as a safeguard; it should never be + // reached. Code coverage tools should ignore it. + /* istanbul ignore next */ + default: + throw Error('Unknown term type: ' + item.type); + } + return item; +}; + +module.exports = function(pattern, flags) { + var tree = parse(pattern, flags); + ignoreCase = flags ? flags.indexOf('i') > -1 : false; + unicode = flags ? flags.indexOf('u') > -1 : false; + assign(tree, processTerm(tree)); + return generate(tree); +}; + +},{"./data/character-class-escape-sets.js":663,"./data/iu-mappings.json":664,"regenerate":662,"regjsgen":666,"regjsparser":667}],666:[function(require,module,exports){ +(function (global){ +/*! + * RegJSGen + * Copyright 2014 Benjamin Tan + * Available under MIT license + */ +;(function() { + 'use strict'; + + /** Used to determine if values are of the language type `Object` */ + var objectTypes = { + 'function': true, + 'object': true + }; + + /** Used as a reference to the global object */ + var root = (objectTypes[typeof window] && window) || this; + + /** Backup possible global object */ + var oldRoot = root; + + /** Detect free variable `exports` */ + var freeExports = objectTypes[typeof exports] && exports; + + /** Detect free variable `module` */ + var freeModule = objectTypes[typeof module] && module && !module.nodeType && module; + + /** Detect free variable `global` from Node.js or Browserified code and use it as `root` */ + var freeGlobal = freeExports && freeModule && typeof global == 'object' && global; + if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal || freeGlobal.self === freeGlobal)) { + root = freeGlobal; + } + + /*--------------------------------------------------------------------------*/ + + /*! Based on https://mths.be/fromcodepoint v0.2.0 by @mathias */ + + var stringFromCharCode = String.fromCharCode; + var floor = Math.floor; + function fromCodePoint() { + var MAX_SIZE = 0x4000; + var codeUnits = []; + var highSurrogate; + var lowSurrogate; + var index = -1; + var length = arguments.length; + if (!length) { + return ''; + } + var result = ''; + while (++index < length) { + var codePoint = Number(arguments[index]); + if ( + !isFinite(codePoint) || // `NaN`, `+Infinity`, or `-Infinity` + codePoint < 0 || // not a valid Unicode code point + codePoint > 0x10FFFF || // not a valid Unicode code point + floor(codePoint) != codePoint // not an integer + ) { + throw RangeError('Invalid code point: ' + codePoint); + } + if (codePoint <= 0xFFFF) { + // BMP code point + codeUnits.push(codePoint); + } else { + // Astral code point; split in surrogate halves + // http://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae + codePoint -= 0x10000; + highSurrogate = (codePoint >> 10) + 0xD800; + lowSurrogate = (codePoint % 0x400) + 0xDC00; + codeUnits.push(highSurrogate, lowSurrogate); + } + if (index + 1 == length || codeUnits.length > MAX_SIZE) { + result += stringFromCharCode.apply(null, codeUnits); + codeUnits.length = 0; + } + } + return result; + } + + function assertType(type, expected) { + if (expected.indexOf('|') == -1) { + if (type == expected) { + return; + } + + throw Error('Invalid node type: ' + type); + } + + expected = assertType.hasOwnProperty(expected) + ? assertType[expected] + : (assertType[expected] = RegExp('^(?:' + expected + ')$')); + + if (expected.test(type)) { + return; + } + + throw Error('Invalid node type: ' + type); + } + + /*--------------------------------------------------------------------------*/ + + function generate(node) { + var type = node.type; + + if (generate.hasOwnProperty(type) && typeof generate[type] == 'function') { + return generate[type](node); + } + + throw Error('Invalid node type: ' + type); + } + + /*--------------------------------------------------------------------------*/ + + function generateAlternative(node) { + assertType(node.type, 'alternative'); + + var terms = node.body, + length = terms ? terms.length : 0; + + if (length == 1) { + return generateTerm(terms[0]); + } else { + var i = -1, + result = ''; + + while (++i < length) { + result += generateTerm(terms[i]); + } + + return result; + } + } + + function generateAnchor(node) { + assertType(node.type, 'anchor'); + + switch (node.kind) { + case 'start': + return '^'; + case 'end': + return '$'; + case 'boundary': + return '\\b'; + case 'not-boundary': + return '\\B'; + default: + throw Error('Invalid assertion'); + } + } + + function generateAtom(node) { + assertType(node.type, 'anchor|characterClass|characterClassEscape|dot|group|reference|value'); + + return generate(node); + } + + function generateCharacterClass(node) { + assertType(node.type, 'characterClass'); + + var classRanges = node.body, + length = classRanges ? classRanges.length : 0; + + var i = -1, + result = '['; + + if (node.negative) { + result += '^'; + } + + while (++i < length) { + result += generateClassAtom(classRanges[i]); + } + + result += ']'; + + return result; + } + + function generateCharacterClassEscape(node) { + assertType(node.type, 'characterClassEscape'); + + return '\\' + node.value; + } + + function generateCharacterClassRange(node) { + assertType(node.type, 'characterClassRange'); + + var min = node.min, + max = node.max; + + if (min.type == 'characterClassRange' || max.type == 'characterClassRange') { + throw Error('Invalid character class range'); + } + + return generateClassAtom(min) + '-' + generateClassAtom(max); + } + + function generateClassAtom(node) { + assertType(node.type, 'anchor|characterClassEscape|characterClassRange|dot|value'); + + return generate(node); + } + + function generateDisjunction(node) { + assertType(node.type, 'disjunction'); + + var body = node.body, + length = body ? body.length : 0; + + if (length == 0) { + throw Error('No body'); + } else if (length == 1) { + return generate(body[0]); + } else { + var i = -1, + result = ''; + + while (++i < length) { + if (i != 0) { + result += '|'; + } + result += generate(body[i]); + } + + return result; + } + } + + function generateDot(node) { + assertType(node.type, 'dot'); + + return '.'; + } + + function generateGroup(node) { + assertType(node.type, 'group'); + + var result = '('; + + switch (node.behavior) { + case 'normal': + break; + case 'ignore': + result += '?:'; + break; + case 'lookahead': + result += '?='; + break; + case 'negativeLookahead': + result += '?!'; + break; + default: + throw Error('Invalid behaviour: ' + node.behaviour); + } + + var body = node.body, + length = body ? body.length : 0; + + if (length == 1) { + result += generate(body[0]); + } else { + var i = -1; + + while (++i < length) { + result += generate(body[i]); + } + } + + result += ')'; + + return result; + } + + function generateQuantifier(node) { + assertType(node.type, 'quantifier'); + + var quantifier = '', + min = node.min, + max = node.max; + + switch (max) { + case undefined: + case null: + switch (min) { + case 0: + quantifier = '*' + break; + case 1: + quantifier = '+'; + break; + default: + quantifier = '{' + min + ',}'; + break; + } + break; + default: + if (min == max) { + quantifier = '{' + min + '}'; + } + else if (min == 0 && max == 1) { + quantifier = '?'; + } else { + quantifier = '{' + min + ',' + max + '}'; + } + break; + } + + if (!node.greedy) { + quantifier += '?'; + } + + return generateAtom(node.body[0]) + quantifier; + } + + function generateReference(node) { + assertType(node.type, 'reference'); + + return '\\' + node.matchIndex; + } + + function generateTerm(node) { + assertType(node.type, 'anchor|characterClass|characterClassEscape|empty|group|quantifier|reference|value'); + + return generate(node); + } + + function generateValue(node) { + assertType(node.type, 'value'); + + var kind = node.kind, + codePoint = node.codePoint; + + switch (kind) { + case 'controlLetter': + return '\\c' + fromCodePoint(codePoint + 64); + case 'hexadecimalEscape': + return '\\x' + ('00' + codePoint.toString(16).toUpperCase()).slice(-2); + case 'identifier': + return '\\' + fromCodePoint(codePoint); + case 'null': + return '\\' + codePoint; + case 'octal': + return '\\' + codePoint.toString(8); + case 'singleEscape': + switch (codePoint) { + case 0x0008: + return '\\b'; + case 0x009: + return '\\t'; + case 0x00A: + return '\\n'; + case 0x00B: + return '\\v'; + case 0x00C: + return '\\f'; + case 0x00D: + return '\\r'; + default: + throw Error('Invalid codepoint: ' + codePoint); + } + case 'symbol': + return fromCodePoint(codePoint); + case 'unicodeEscape': + return '\\u' + ('0000' + codePoint.toString(16).toUpperCase()).slice(-4); + case 'unicodeCodePointEscape': + return '\\u{' + codePoint.toString(16).toUpperCase() + '}'; + default: + throw Error('Unsupported node kind: ' + kind); + } + } + + /*--------------------------------------------------------------------------*/ + + generate.alternative = generateAlternative; + generate.anchor = generateAnchor; + generate.characterClass = generateCharacterClass; + generate.characterClassEscape = generateCharacterClassEscape; + generate.characterClassRange = generateCharacterClassRange; + generate.disjunction = generateDisjunction; + generate.dot = generateDot; + generate.group = generateGroup; + generate.quantifier = generateQuantifier; + generate.reference = generateReference; + generate.value = generateValue; + + /*--------------------------------------------------------------------------*/ + + // export regjsgen + // some AMD build optimizers, like r.js, check for condition patterns like the following: + if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) { + // define as an anonymous module so, through path mapping, it can be aliased + define(function() { + return { + 'generate': generate + }; + }); + } + // check for `exports` after `define` in case a build optimizer adds an `exports` object + else if (freeExports && freeModule) { + // in Narwhal, Node.js, Rhino -require, or RingoJS + freeExports.generate = generate; + } + // in a browser or Rhino + else { + root.regjsgen = { + 'generate': generate + }; + } +}.call(this)); + +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{}],667:[function(require,module,exports){ +// regjsparser +// +// ================================================================== +// +// See ECMA-262 Standard: 15.10.1 +// +// NOTE: The ECMA-262 standard uses the term "Assertion" for /^/. Here the +// term "Anchor" is used. +// +// Pattern :: +// Disjunction +// +// Disjunction :: +// Alternative +// Alternative | Disjunction +// +// Alternative :: +// [empty] +// Alternative Term +// +// Term :: +// Anchor +// Atom +// Atom Quantifier +// +// Anchor :: +// ^ +// $ +// \ b +// \ B +// ( ? = Disjunction ) +// ( ? ! Disjunction ) +// +// Quantifier :: +// QuantifierPrefix +// QuantifierPrefix ? +// +// QuantifierPrefix :: +// * +// + +// ? +// { DecimalDigits } +// { DecimalDigits , } +// { DecimalDigits , DecimalDigits } +// +// Atom :: +// PatternCharacter +// . +// \ AtomEscape +// CharacterClass +// ( Disjunction ) +// ( ? : Disjunction ) +// +// PatternCharacter :: +// SourceCharacter but not any of: ^ $ \ . * + ? ( ) [ ] { } | +// +// AtomEscape :: +// DecimalEscape +// CharacterEscape +// CharacterClassEscape +// +// CharacterEscape[U] :: +// ControlEscape +// c ControlLetter +// HexEscapeSequence +// RegExpUnicodeEscapeSequence[?U] (ES6) +// IdentityEscape[?U] +// +// ControlEscape :: +// one of f n r t v +// ControlLetter :: +// one of +// a b c d e f g h i j k l m n o p q r s t u v w x y z +// A B C D E F G H I J K L M N O P Q R S T U V W X Y Z +// +// IdentityEscape :: +// SourceCharacter but not IdentifierPart +// +// +// +// DecimalEscape :: +// DecimalIntegerLiteral [lookahead ∉ DecimalDigit] +// +// CharacterClassEscape :: +// one of d D s S w W +// +// CharacterClass :: +// [ [lookahead ∉ {^}] ClassRanges ] +// [ ^ ClassRanges ] +// +// ClassRanges :: +// [empty] +// NonemptyClassRanges +// +// NonemptyClassRanges :: +// ClassAtom +// ClassAtom NonemptyClassRangesNoDash +// ClassAtom - ClassAtom ClassRanges +// +// NonemptyClassRangesNoDash :: +// ClassAtom +// ClassAtomNoDash NonemptyClassRangesNoDash +// ClassAtomNoDash - ClassAtom ClassRanges +// +// ClassAtom :: +// - +// ClassAtomNoDash +// +// ClassAtomNoDash :: +// SourceCharacter but not one of \ or ] or - +// \ ClassEscape +// +// ClassEscape :: +// DecimalEscape +// b +// CharacterEscape +// CharacterClassEscape + +(function() { + + function parse(str, flags) { + function addRaw(node) { + node.raw = str.substring(node.range[0], node.range[1]); + return node; + } + + function updateRawStart(node, start) { + node.range[0] = start; + return addRaw(node); + } + + function createAnchor(kind, rawLength) { + return addRaw({ + type: 'anchor', + kind: kind, + range: [ + pos - rawLength, + pos + ] + }); + } + + function createValue(kind, codePoint, from, to) { + return addRaw({ + type: 'value', + kind: kind, + codePoint: codePoint, + range: [from, to] + }); + } + + function createEscaped(kind, codePoint, value, fromOffset) { + fromOffset = fromOffset || 0; + return createValue(kind, codePoint, pos - (value.length + fromOffset), pos); + } + + function createCharacter(matches) { + var _char = matches[0]; + var first = _char.charCodeAt(0); + if (hasUnicodeFlag) { + var second; + if (_char.length === 1 && first >= 0xD800 && first <= 0xDBFF) { + second = lookahead().charCodeAt(0); + if (second >= 0xDC00 && second <= 0xDFFF) { + // Unicode surrogate pair + pos++; + return createValue( + 'symbol', + (first - 0xD800) * 0x400 + second - 0xDC00 + 0x10000, + pos - 2, pos); + } + } + } + return createValue('symbol', first, pos - 1, pos); + } + + function createDisjunction(alternatives, from, to) { + return addRaw({ + type: 'disjunction', + body: alternatives, + range: [ + from, + to + ] + }); + } + + function createDot() { + return addRaw({ + type: 'dot', + range: [ + pos - 1, + pos + ] + }); + } + + function createCharacterClassEscape(value) { + return addRaw({ + type: 'characterClassEscape', + value: value, + range: [ + pos - 2, + pos + ] + }); + } + + function createReference(matchIndex) { + return addRaw({ + type: 'reference', + matchIndex: parseInt(matchIndex, 10), + range: [ + pos - 1 - matchIndex.length, + pos + ] + }); + } + + function createGroup(behavior, disjunction, from, to) { + return addRaw({ + type: 'group', + behavior: behavior, + body: disjunction, + range: [ + from, + to + ] + }); + } + + function createQuantifier(min, max, from, to) { + if (to == null) { + from = pos - 1; + to = pos; + } + + return addRaw({ + type: 'quantifier', + min: min, + max: max, + greedy: true, + body: null, // set later on + range: [ + from, + to + ] + }); + } + + function createAlternative(terms, from, to) { + return addRaw({ + type: 'alternative', + body: terms, + range: [ + from, + to + ] + }); + } + + function createCharacterClass(classRanges, negative, from, to) { + return addRaw({ + type: 'characterClass', + body: classRanges, + negative: negative, + range: [ + from, + to + ] + }); + } + + function createClassRange(min, max, from, to) { + // See 15.10.2.15: + if (min.codePoint > max.codePoint) { + bail('invalid range in character class', min.raw + '-' + max.raw, from, to); + } + + return addRaw({ + type: 'characterClassRange', + min: min, + max: max, + range: [ + from, + to + ] + }); + } + + function flattenBody(body) { + if (body.type === 'alternative') { + return body.body; + } else { + return [body]; + } + } + + function isEmpty(obj) { + return obj.type === 'empty'; + } + + function incr(amount) { + amount = (amount || 1); + var res = str.substring(pos, pos + amount); + pos += (amount || 1); + return res; + } + + function skip(value) { + if (!match(value)) { + bail('character', value); + } + } + + function match(value) { + if (str.indexOf(value, pos) === pos) { + return incr(value.length); + } + } + + function lookahead() { + return str[pos]; + } + + function current(value) { + return str.indexOf(value, pos) === pos; + } + + function next(value) { + return str[pos + 1] === value; + } + + function matchReg(regExp) { + var subStr = str.substring(pos); + var res = subStr.match(regExp); + if (res) { + res.range = []; + res.range[0] = pos; + incr(res[0].length); + res.range[1] = pos; + } + return res; + } + + function parseDisjunction() { + // Disjunction :: + // Alternative + // Alternative | Disjunction + var res = [], from = pos; + res.push(parseAlternative()); + + while (match('|')) { + res.push(parseAlternative()); + } + + if (res.length === 1) { + return res[0]; + } + + return createDisjunction(res, from, pos); + } + + function parseAlternative() { + var res = [], from = pos; + var term; + + // Alternative :: + // [empty] + // Alternative Term + while (term = parseTerm()) { + res.push(term); + } + + if (res.length === 1) { + return res[0]; + } + + return createAlternative(res, from, pos); + } + + function parseTerm() { + // Term :: + // Anchor + // Atom + // Atom Quantifier + + if (pos >= str.length || current('|') || current(')')) { + return null; /* Means: The term is empty */ + } + + var anchor = parseAnchor(); + + if (anchor) { + return anchor; + } + + var atom = parseAtom(); + if (!atom) { + bail('Expected atom'); + } + var quantifier = parseQuantifier() || false; + if (quantifier) { + quantifier.body = flattenBody(atom); + // The quantifier contains the atom. Therefore, the beginning of the + // quantifier range is given by the beginning of the atom. + updateRawStart(quantifier, atom.range[0]); + return quantifier; + } + return atom; + } + + function parseGroup(matchA, typeA, matchB, typeB) { + var type = null, from = pos; + + if (match(matchA)) { + type = typeA; + } else if (match(matchB)) { + type = typeB; + } else { + return false; + } + + var body = parseDisjunction(); + if (!body) { + bail('Expected disjunction'); + } + skip(')'); + var group = createGroup(type, flattenBody(body), from, pos); + + if (type == 'normal') { + // Keep track of the number of closed groups. This is required for + // parseDecimalEscape(). In case the string is parsed a second time the + // value already holds the total count and no incrementation is required. + if (firstIteration) { + closedCaptureCounter++; + } + } + return group; + } + + function parseAnchor() { + // Anchor :: + // ^ + // $ + // \ b + // \ B + // ( ? = Disjunction ) + // ( ? ! Disjunction ) + var res, from = pos; + + if (match('^')) { + return createAnchor('start', 1 /* rawLength */); + } else if (match('$')) { + return createAnchor('end', 1 /* rawLength */); + } else if (match('\\b')) { + return createAnchor('boundary', 2 /* rawLength */); + } else if (match('\\B')) { + return createAnchor('not-boundary', 2 /* rawLength */); + } else { + return parseGroup('(?=', 'lookahead', '(?!', 'negativeLookahead'); + } + } + + function parseQuantifier() { + // Quantifier :: + // QuantifierPrefix + // QuantifierPrefix ? + // + // QuantifierPrefix :: + // * + // + + // ? + // { DecimalDigits } + // { DecimalDigits , } + // { DecimalDigits , DecimalDigits } + + var res, from = pos; + var quantifier; + var min, max; + + if (match('*')) { + quantifier = createQuantifier(0); + } + else if (match('+')) { + quantifier = createQuantifier(1); + } + else if (match('?')) { + quantifier = createQuantifier(0, 1); + } + else if (res = matchReg(/^\{([0-9]+)\}/)) { + min = parseInt(res[1], 10); + quantifier = createQuantifier(min, min, res.range[0], res.range[1]); + } + else if (res = matchReg(/^\{([0-9]+),\}/)) { + min = parseInt(res[1], 10); + quantifier = createQuantifier(min, undefined, res.range[0], res.range[1]); + } + else if (res = matchReg(/^\{([0-9]+),([0-9]+)\}/)) { + min = parseInt(res[1], 10); + max = parseInt(res[2], 10); + if (min > max) { + bail('numbers out of order in {} quantifier', '', from, pos); + } + quantifier = createQuantifier(min, max, res.range[0], res.range[1]); + } + + if (quantifier) { + if (match('?')) { + quantifier.greedy = false; + quantifier.range[1] += 1; + } + } + + return quantifier; + } + + function parseAtom() { + // Atom :: + // PatternCharacter + // . + // \ AtomEscape + // CharacterClass + // ( Disjunction ) + // ( ? : Disjunction ) + + var res; + + // jviereck: allow ']', '}' here as well to be compatible with browser's + // implementations: ']'.match(/]/); + // if (res = matchReg(/^[^^$\\.*+?()[\]{}|]/)) { + if (res = matchReg(/^[^^$\\.*+?(){[|]/)) { + // PatternCharacter + return createCharacter(res); + } + else if (match('.')) { + // . + return createDot(); + } + else if (match('\\')) { + // \ AtomEscape + res = parseAtomEscape(); + if (!res) { + bail('atomEscape'); + } + return res; + } + else if (res = parseCharacterClass()) { + return res; + } + else { + // ( Disjunction ) + // ( ? : Disjunction ) + return parseGroup('(?:', 'ignore', '(', 'normal'); + } + } + + function parseUnicodeSurrogatePairEscape(firstEscape) { + if (hasUnicodeFlag) { + var first, second; + if (firstEscape.kind == 'unicodeEscape' && + (first = firstEscape.codePoint) >= 0xD800 && first <= 0xDBFF && + current('\\') && next('u') ) { + var prevPos = pos; + pos++; + var secondEscape = parseClassEscape(); + if (secondEscape.kind == 'unicodeEscape' && + (second = secondEscape.codePoint) >= 0xDC00 && second <= 0xDFFF) { + // Unicode surrogate pair + firstEscape.range[1] = secondEscape.range[1]; + firstEscape.codePoint = (first - 0xD800) * 0x400 + second - 0xDC00 + 0x10000; + firstEscape.type = 'value'; + firstEscape.kind = 'unicodeCodePointEscape'; + addRaw(firstEscape); + } + else { + pos = prevPos; + } + } + } + return firstEscape; + } + + function parseClassEscape() { + return parseAtomEscape(true); + } + + function parseAtomEscape(insideCharacterClass) { + // AtomEscape :: + // DecimalEscape + // CharacterEscape + // CharacterClassEscape + + var res, from = pos; + + res = parseDecimalEscape(); + if (res) { + return res; + } + + // For ClassEscape + if (insideCharacterClass) { + if (match('b')) { + // 15.10.2.19 + // The production ClassEscape :: b evaluates by returning the + // CharSet containing the one character (Unicode value 0008). + return createEscaped('singleEscape', 0x0008, '\\b'); + } else if (match('B')) { + bail('\\B not possible inside of CharacterClass', '', from); + } + } + + res = parseCharacterEscape(); + + return res; + } + + + function parseDecimalEscape() { + // DecimalEscape :: + // DecimalIntegerLiteral [lookahead ∉ DecimalDigit] + // CharacterClassEscape :: one of d D s S w W + + var res, match; + + if (res = matchReg(/^(?!0)\d+/)) { + match = res[0]; + var refIdx = parseInt(res[0], 10); + if (refIdx <= closedCaptureCounter) { + // If the number is smaller than the normal-groups found so + // far, then it is a reference... + return createReference(res[0]); + } else { + // ... otherwise it needs to be interpreted as a octal (if the + // number is in an octal format). If it is NOT octal format, + // then the slash is ignored and the number is matched later + // as normal characters. + + // Recall the negative decision to decide if the input must be parsed + // a second time with the total normal-groups. + backrefDenied.push(refIdx); + + // Reset the position again, as maybe only parts of the previous + // matched numbers are actual octal numbers. E.g. in '019' only + // the '01' should be matched. + incr(-res[0].length); + if (res = matchReg(/^[0-7]{1,3}/)) { + return createEscaped('octal', parseInt(res[0], 8), res[0], 1); + } else { + // If we end up here, we have a case like /\91/. Then the + // first slash is to be ignored and the 9 & 1 to be treated + // like ordinary characters. Create a character for the + // first number only here - other number-characters + // (if available) will be matched later. + res = createCharacter(matchReg(/^[89]/)); + return updateRawStart(res, res.range[0] - 1); + } + } + } + // Only allow octal numbers in the following. All matched numbers start + // with a zero (if the do not, the previous if-branch is executed). + // If the number is not octal format and starts with zero (e.g. `091`) + // then only the zeros `0` is treated here and the `91` are ordinary + // characters. + // Example: + // /\091/.exec('\091')[0].length === 3 + else if (res = matchReg(/^[0-7]{1,3}/)) { + match = res[0]; + if (/^0{1,3}$/.test(match)) { + // If they are all zeros, then only take the first one. + return createEscaped('null', 0x0000, '0', match.length + 1); + } else { + return createEscaped('octal', parseInt(match, 8), match, 1); + } + } else if (res = matchReg(/^[dDsSwW]/)) { + return createCharacterClassEscape(res[0]); + } + return false; + } + + function parseCharacterEscape() { + // CharacterEscape :: + // ControlEscape + // c ControlLetter + // HexEscapeSequence + // UnicodeEscapeSequence + // IdentityEscape + + var res; + if (res = matchReg(/^[fnrtv]/)) { + // ControlEscape + var codePoint = 0; + switch (res[0]) { + case 't': codePoint = 0x009; break; + case 'n': codePoint = 0x00A; break; + case 'v': codePoint = 0x00B; break; + case 'f': codePoint = 0x00C; break; + case 'r': codePoint = 0x00D; break; + } + return createEscaped('singleEscape', codePoint, '\\' + res[0]); + } else if (res = matchReg(/^c([a-zA-Z])/)) { + // c ControlLetter + return createEscaped('controlLetter', res[1].charCodeAt(0) % 32, res[1], 2); + } else if (res = matchReg(/^x([0-9a-fA-F]{2})/)) { + // HexEscapeSequence + return createEscaped('hexadecimalEscape', parseInt(res[1], 16), res[1], 2); + } else if (res = matchReg(/^u([0-9a-fA-F]{4})/)) { + // UnicodeEscapeSequence + return parseUnicodeSurrogatePairEscape( + createEscaped('unicodeEscape', parseInt(res[1], 16), res[1], 2) + ); + } else if (hasUnicodeFlag && (res = matchReg(/^u\{([0-9a-fA-F]+)\}/))) { + // RegExpUnicodeEscapeSequence (ES6 Unicode code point escape) + return createEscaped('unicodeCodePointEscape', parseInt(res[1], 16), res[1], 4); + } else { + // IdentityEscape + return parseIdentityEscape(); + } + } + + // Taken from the Esprima parser. + function isIdentifierPart(ch) { + // Generated by `tools/generate-identifier-regex.js`. + var NonAsciiIdentifierPart = new RegExp('[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u08A0-\u08B2\u08E4-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58\u0C59\u0C60-\u0C63\u0C66-\u0C6F\u0C81-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D01-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D57\u0D60-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u135F\u1380-\u138F\u13A0-\u13F4\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19D9\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1CD0-\u1CD2\u1CD4-\u1CF6\u1CF8\u1CF9\u1D00-\u1DF5\u1DFC-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u200C\u200D\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u2E2F\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099\u309A\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FCC\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA69D\uA69F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA78E\uA790-\uA7AD\uA7B0\uA7B1\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C4\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB5F\uAB64\uAB65\uABC0-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE2D\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]'); + + return (ch === 36) || (ch === 95) || // $ (dollar) and _ (underscore) + (ch >= 65 && ch <= 90) || // A..Z + (ch >= 97 && ch <= 122) || // a..z + (ch >= 48 && ch <= 57) || // 0..9 + (ch === 92) || // \ (backslash) + ((ch >= 0x80) && NonAsciiIdentifierPart.test(String.fromCharCode(ch))); + } + + function parseIdentityEscape() { + // IdentityEscape :: + // SourceCharacter but not IdentifierPart + // + // + + var ZWJ = '\u200C'; + var ZWNJ = '\u200D'; + + var tmp; + + if (!isIdentifierPart(lookahead())) { + tmp = incr(); + return createEscaped('identifier', tmp.charCodeAt(0), tmp, 1); + } + + if (match(ZWJ)) { + // + return createEscaped('identifier', 0x200C, ZWJ); + } else if (match(ZWNJ)) { + // + return createEscaped('identifier', 0x200D, ZWNJ); + } + + return null; + } + + function parseCharacterClass() { + // CharacterClass :: + // [ [lookahead ∉ {^}] ClassRanges ] + // [ ^ ClassRanges ] + + var res, from = pos; + if (res = matchReg(/^\[\^/)) { + res = parseClassRanges(); + skip(']'); + return createCharacterClass(res, true, from, pos); + } else if (match('[')) { + res = parseClassRanges(); + skip(']'); + return createCharacterClass(res, false, from, pos); + } + + return null; + } + + function parseClassRanges() { + // ClassRanges :: + // [empty] + // NonemptyClassRanges + + var res; + if (current(']')) { + // Empty array means nothing insinde of the ClassRange. + return []; + } else { + res = parseNonemptyClassRanges(); + if (!res) { + bail('nonEmptyClassRanges'); + } + return res; + } + } + + function parseHelperClassRanges(atom) { + var from, to, res; + if (current('-') && !next(']')) { + // ClassAtom - ClassAtom ClassRanges + skip('-'); + + res = parseClassAtom(); + if (!res) { + bail('classAtom'); + } + to = pos; + var classRanges = parseClassRanges(); + if (!classRanges) { + bail('classRanges'); + } + from = atom.range[0]; + if (classRanges.type === 'empty') { + return [createClassRange(atom, res, from, to)]; + } + return [createClassRange(atom, res, from, to)].concat(classRanges); + } + + res = parseNonemptyClassRangesNoDash(); + if (!res) { + bail('nonEmptyClassRangesNoDash'); + } + + return [atom].concat(res); + } + + function parseNonemptyClassRanges() { + // NonemptyClassRanges :: + // ClassAtom + // ClassAtom NonemptyClassRangesNoDash + // ClassAtom - ClassAtom ClassRanges + + var atom = parseClassAtom(); + if (!atom) { + bail('classAtom'); + } + + if (current(']')) { + // ClassAtom + return [atom]; + } + + // ClassAtom NonemptyClassRangesNoDash + // ClassAtom - ClassAtom ClassRanges + return parseHelperClassRanges(atom); + } + + function parseNonemptyClassRangesNoDash() { + // NonemptyClassRangesNoDash :: + // ClassAtom + // ClassAtomNoDash NonemptyClassRangesNoDash + // ClassAtomNoDash - ClassAtom ClassRanges + + var res = parseClassAtom(); + if (!res) { + bail('classAtom'); + } + if (current(']')) { + // ClassAtom + return res; + } + + // ClassAtomNoDash NonemptyClassRangesNoDash + // ClassAtomNoDash - ClassAtom ClassRanges + return parseHelperClassRanges(res); + } + + function parseClassAtom() { + // ClassAtom :: + // - + // ClassAtomNoDash + if (match('-')) { + return createCharacter('-'); + } else { + return parseClassAtomNoDash(); + } + } + + function parseClassAtomNoDash() { + // ClassAtomNoDash :: + // SourceCharacter but not one of \ or ] or - + // \ ClassEscape + + var res; + if (res = matchReg(/^[^\\\]-]/)) { + return createCharacter(res[0]); + } else if (match('\\')) { + res = parseClassEscape(); + if (!res) { + bail('classEscape'); + } + + return parseUnicodeSurrogatePairEscape(res); + } + } + + function bail(message, details, from, to) { + from = from == null ? pos : from; + to = to == null ? from : to; + + var contextStart = Math.max(0, from - 10); + var contextEnd = Math.min(to + 10, str.length); + + // Output a bit of context and a line pointing to where our error is. + // + // We are assuming that there are no actual newlines in the content as this is a regular expression. + var context = ' ' + str.substring(contextStart, contextEnd); + var pointer = ' ' + new Array(from - contextStart + 1).join(' ') + '^'; + + throw SyntaxError(message + ' at position ' + from + (details ? ': ' + details : '') + '\n' + context + '\n' + pointer); + } + + var backrefDenied = []; + var closedCaptureCounter = 0; + var firstIteration = true; + var hasUnicodeFlag = (flags || "").indexOf("u") !== -1; + var pos = 0; + + // Convert the input to a string and treat the empty string special. + str = String(str); + if (str === '') { + str = '(?:)'; + } + + var result = parseDisjunction(); + + if (result.range[1] !== str.length) { + bail('Could not parse entire input - got stuck', '', result.range[1]); + } + + // The spec requires to interpret the `\2` in `/\2()()/` as backreference. + // As the parser collects the number of capture groups as the string is + // parsed it is impossible to make these decisions at the point when the + // `\2` is handled. In case the local decision turns out to be wrong after + // the parsing has finished, the input string is parsed a second time with + // the total number of capture groups set. + // + // SEE: https://github.com/jviereck/regjsparser/issues/70 + for (var i = 0; i < backrefDenied.length; i++) { + if (backrefDenied[i] <= closedCaptureCounter) { + // Parse the input a second time. + pos = 0; + firstIteration = false; + return parseDisjunction(); + } + } + + return result; + } + + var regjsparser = { + parse: parse + }; + + if (typeof module !== 'undefined' && module.exports) { + module.exports = regjsparser; + } else { + window.regjsparser = regjsparser; + } + +}()); + +},{}],668:[function(require,module,exports){ +'use strict'; +var isFinite = require('is-finite'); + +module.exports = function (str, n) { + if (typeof str !== 'string') { + throw new TypeError('Expected a string as the first argument'); + } + + if (n < 0 || !isFinite(n)) { + throw new TypeError('Expected a finite positive number'); + } + + var ret = ''; + + do { + if (n & 1) { + ret += str; + } + + str += str; + } while (n = n >> 1); + + return ret; +}; + +},{"is-finite":354}],669:[function(require,module,exports){ +(function(f) { + + 'use strict'; + + /* istanbul ignore else */ + if (typeof module === 'object' && typeof module.exports === 'object') { + module.exports = f(); + } else if (typeof define === 'function' && define.amd != null) { + define([], f); + } else { + self.sanctuaryDef = f(); + } + +}(function() { + + 'use strict'; + + var $ = {}; + + var MAX_SAFE_INTEGER = Math.pow(2, 53) - 1; + var MIN_SAFE_INTEGER = -MAX_SAFE_INTEGER; + + var LEFT_SINGLE_QUOTATION_MARK = '\u2018'; + var RIGHT_SINGLE_QUOTATION_MARK = '\u2019'; + + var push = Array.prototype.push; + var hasOwnProperty = Object.prototype.hasOwnProperty; + var toString = Object.prototype.toString; + + // Left :: a -> Either a b + var Left = function Left(x) { + return { + '@@type': 'sanctuary-def/Either', + isLeft: true, + isRight: false, + chain: function(f) { return Left(x); }, + map: function(f) { return Left(x); }, + value: x + }; + }; + + // Right :: b -> Either a b + var Right = function Right(x) { + return { + '@@type': 'sanctuary-def/Either', + isLeft: false, + isRight: true, + chain: function(f) { return f(x); }, + map: function(f) { return Right(f(x)); }, + value: x + }; + }; + + // K :: a -> b -> a + var K = function(x) { return function(y) { return x; }; }; + + // all :: ([a], (a -> Boolean)) -> Boolean + var all = function(xs, pred) { + for (var idx = 0; idx < xs.length; idx += 1) { + if (!pred(xs[idx])) return false; + } + return true; + }; + + // always :: a -> (-> a) + var always = function(x) { return function() { return x; }; }; + + // assoc :: (String, a, StrMap a) -> StrMap a + var assoc = function(key, value, strMap) { + var result = {}; + for (var k in strMap) { + result[k] = strMap[k]; + } + result[key] = value; + return result; + }; + + // chain :: ([a], (a -> [b])) -> [b] + var chain = function(xs, f) { + var result = []; + for (var idx = 0; idx < xs.length; idx += 1) { + push.apply(result, f(xs[idx])); + } + return result; + }; + + // filter :: ([a], (a -> Boolean)) -> [a] + var filter = function(xs, pred) { + var result = []; + for (var idx = 0; idx < xs.length; idx += 1) { + if (pred(xs[idx])) { + result.push(xs[idx]); + } + } + return result; + }; + + // has :: (String, Object) -> Boolean + var has = function(key, obj) { return hasOwnProperty.call(obj, key); }; + + // id :: a -> a + var id = function(x) { return x; }; + + // isEmpty :: [a] -> Boolean + var isEmpty = function(xs) { return xs.length === 0; }; + + // keys :: Object -> [String] + var keys = function(obj) { + var result = []; + for (var key in obj) if (has(key, obj)) result.push(key); + return result.sort(); + }; + + // last :: [a] -> a + var last = function(xs) { return xs[xs.length - 1]; }; + + // map :: ([a], (a -> b)) -> [b] + var map = function(xs, f) { + var result = []; + for (var idx = 0; idx < xs.length; idx += 1) result.push(f(xs[idx])); + return result; + }; + + // or :: ([a], [a]) -> [a] + var or = function(xs, ys) { return isEmpty(xs) ? ys : xs; }; + + // prefix :: String -> String -> String + var prefix = function(x) { + return function(y) { + return x + y; + }; + }; + + // quote :: String -> String + var quote = function(s) { + var escaped = s + .replace(/\\/g, '\\\\') + // \b matches word boundary; [\b] matches backspace + .replace(/[\b]/g, '\\b') + .replace(/\f/g, '\\f') + .replace(/\n/g, '\\n') + .replace(/\r/g, '\\r') + .replace(/\t/g, '\\t') + .replace(/\v/g, '\\v') + .replace(/\0/g, '\\0'); + + return '"' + escaped.replace(/"/g, '\\"') + '"'; + }; + + // range :: (Number, Number) -> [Number] + var range = function(start, stop) { + var result = []; + for (var n = start; n < stop; n += 1) result.push(n); + return result; + }; + + // reduce :: ([a], b, (b, a) -> b) -> b + var reduce = function(xs, y, f) { + var result = y; + for (var idx = 0; idx < xs.length; idx += 1) result = f(result, xs[idx]); + return result; + }; + + // strRepeat :: (String, Integer) -> String + var strRepeat = function(s, times) { + return Array(times + 1).join(s); + }; + + // r :: Char -> String -> String + var r = function(c) { + return function(s) { + return strRepeat(c, s.length); + }; + }; + + // _ :: String -> String + var _ = r(' '); + + // toPairs :: StrMap a -> [Pair String a] + var toPairs = function(obj) { + return map(keys(obj), function(k) { return [k, obj[k]]; }); + }; + + // trimTrailingSpaces :: String -> String + var trimTrailingSpaces = function(s) { + return s.replace(/[ ]+$/gm, ''); + }; + + // unlines :: [String] -> String + var unlines = function(lines) { + var s = ''; + for (var idx = 0; idx < lines.length; idx += 1) s += lines[idx] + '\n'; + return s; + }; + + // when :: (Boolean, (a -> a), a) -> a + var when = function(bool, f, x) { + return bool ? f(x) : x; + }; + + // stripNamespace :: String -> String + var stripNamespace = function(s) { return s.slice(s.indexOf('/') + 1); }; + + // typeOf :: a -> String + var typeOf = function(x) { + return toString.call(x).slice('[object '.length, -']'.length); + }; + + var _show = function show(x, seen) { + var recur = function(y) { + var xs = seen.concat([x]); + return xs.indexOf(y) >= 0 ? '' : show(y, xs); + }; + + // formatKeyVal :: Object -> String -> String + var formatKeyVal = function(obj) { + return function(key) { + return quote(key) + ': ' + recur(obj[key]); + }; + }; + + switch (typeOf(x)) { + case 'Arguments': + return '(function() { return arguments; }(' + + map(x, recur).join(', ') + '))'; + case 'Array': + var reprs = map(x, recur).concat(chain(keys(x), function(k) { + return /^\d+$/.test(k) ? [] : [formatKeyVal(x)(k)]; + })); + return '[' + reprs.join(', ') + ']'; + case 'Boolean': + return typeof x === 'object' ? + 'new Boolean(' + recur(x.valueOf()) + ')' : + x.toString(); + case 'Date': + return 'new Date(' + + (isNaN(x.valueOf()) ? recur(NaN) : quote(x.toISOString())) + + ')'; + case 'Null': + return 'null'; + case 'Number': + return typeof x === 'object' ? + 'new Number(' + recur(x.valueOf()) + ')' : + 1 / x === -Infinity ? '-0' : x.toString(10); + case 'String': + return typeof x === 'object' ? + 'new String(' + recur(x.valueOf()) + ')' : + quote(x); + case 'Undefined': + return 'undefined'; + default: + if (typeof x.toString === 'function') { + var repr = x.toString(); + if (repr !== '[object Object]') return repr; + } + return '{' + map(keys(x), formatKeyVal(x)).join(', ') + '}'; + } + }; + + // show :: a -> String + var show = function(x) { return _show(x, []); }; + + // TypeClass :: (String, (a -> Boolean)) -> TypeClass + $.TypeClass = function(name, test) { + return { + '@@type': 'sanctuary-def/TypeClass', + name: name, + _test: test, + toString: always(stripNamespace(name)) + }; + }; + + // testFrom :: (a -> Result) -> a -> Boolean + var testFrom = function(validate) { + return function(x) { + return validate(x).isRight; + }; + }; + + // Unknown :: Type + var Unknown = { + '@@type': 'sanctuary-def/Type', + type: 'UNKNOWN', + validate: Right, + _test: K(true), + toString: always('???') + }; + + // Inconsistent :: Type + var Inconsistent = { + '@@type': 'sanctuary-def/Type', + type: 'INCONSISTENT', + toString: always('???') + }; + + // TypeVariable :: String -> Type + $.TypeVariable = function(name) { + return { + '@@type': 'sanctuary-def/Type', + type: 'VARIABLE', + name: name, + validate: Right, + _test: K(true), + toString: always(name) + }; + }; + + // NullaryType :: (String, (x -> Boolean)) -> Type + var NullaryType = $.NullaryType = function(name, test) { + var t = { + '@@type': 'sanctuary-def/Type', + type: 'NULLARY', + name: name, + validate: function(x) { + return test(x) ? Right(x) + : Left({value: x, typePath: [t], propPath: []}); + }, + _test: test, + toString: always(stripNamespace(name)) + }; + return t; + }; + + // UnaryType :: (String, (x -> Boolean), (t a -> [a])) -> Type -> Type + var UnaryType = $.UnaryType = function(name, test, _1) { + return function($1) { + var format = function(f, f$1) { + return f('(' + stripNamespace(name) + ' ') + f$1(String($1)) + f(')'); + }; + var validate = function(x) { + if (!test(x)) { + return Left({value: x, typePath: [t], propPath: []}); + } + for (var idx = 0, xs = _1(x); idx < xs.length; idx += 1) { + var result = $1.validate(xs[idx]); + if (result.isLeft) { + return Left({value: result.value.value, + typePath: [t].concat(result.value.typePath), + propPath: ['$1'].concat(result.value.propPath)}); + } + } + return Right(x); + }; + var t = { + '@@type': 'sanctuary-def/Type', + type: 'UNARY', + name: name, + validate: validate, + _test: testFrom(validate), + format: format, + toString: always(format(id, id)), + _1: _1, + $1: $1 + }; + return t; + }; + }; + + // UnaryType.from :: Type -> (Type -> Type) + UnaryType.from = function(t) { + return UnaryType(t.name, t._test, t._1); + }; + + // BinaryType :: (String, (x -> Boolean), (t a b -> [a]), (t a b -> [b])) -> + // (Type, Type) -> Type + var BinaryType = $.BinaryType = function(name, test, _1, _2) { + return function($1, $2) { + var format = function(f, f$1, f$2) { + return f('(' + stripNamespace(name) + ' ') + + f$1(String($1)) + f(' ') + f$2(String($2)) + f(')'); + }; + var validate = function(x) { + if (!test(x)) { + return Left({value: x, typePath: [t], propPath: []}); + } + for (var n = 1; n <= 2; n += 1) { + var _ = '_' + String(n); + var $ = '$' + String(n); + for (var idx = 0, xs = t[_](x); idx < xs.length; idx += 1) { + var result = t[$].validate(xs[idx]); + if (result.isLeft) { + return Left({value: result.value.value, + typePath: [t].concat(result.value.typePath), + propPath: [$].concat(result.value.propPath)}); + } + } + } + return Right(x); + }; + var t = { + '@@type': 'sanctuary-def/Type', + type: 'BINARY', + name: name, + validate: validate, + _test: testFrom(validate), + format: format, + toString: always(format(id, id, id)), + _1: _1, + _2: _2, + $1: $1, + $2: $2 + }; + return t; + }; + }; + + // BinaryType.from :: Type -> ((Type, Type) -> Type) + BinaryType.from = function(t) { + return BinaryType(t.name, t._test, t._1, t._2); + }; + + // BinaryType.xprod :: (Type, [Type], [Type]) -> [Type] + BinaryType.xprod = function(t, $1s, $2s) { + var specialize = BinaryType.from(t); + return chain($1s, function($1) { + return map($2s, function($2) { + return specialize($1, $2); + }); + }); + }; + + // EnumType :: [Any] -> Type + var EnumType = $.EnumType = function(members) { + var types = map(members, $$type); + var reprs = map(members, show); + var validate = function(x) { + // We use `show` to perform value-based equality checks (since we + // don't have access to `R.equals` and don't want to implement it). + // We avoid a lot of unnecessary work by checking the type of `x` + // before determining its string representation. Only if `x` is of + // the same type as one or more of the `members` do we incur the + // cost of determining its string representation. + return types.indexOf($$type(x)) >= 0 && reprs.indexOf(show(x)) >= 0 ? + Right(x) : + Left({value: x, typePath: [t], propPath: []}); + }; + var t = { + '@@type': 'sanctuary-def/Type', + type: 'ENUM', + validate: validate, + _test: testFrom(validate), + toString: always('(' + reprs.join(' | ') + ')') + }; + return t; + }; + + // RecordType :: {Type} -> Type + var RecordType = $.RecordType = function(fields) { + var names = keys(fields); + + // invalidMappings :: [String] + var invalidMappings = chain(names, function(name) { + return $$type(fields[name]) === 'sanctuary-def/Type' ? + [] : + [show(name) + ': ' + show(fields[name])]; + }); + + if (!isEmpty(invalidMappings)) { + throw new TypeError(trimTrailingSpaces(unlines([ + 'Invalid values', + '', + 'The argument to ‘RecordType’ must be an object ' + + 'mapping field name to type.', + '', + 'The following mappings are invalid:', + '', + map(invalidMappings, prefix(' - ')).join('\n') + ]))); + } + + var format = function(f, kv) { + var s = f('{'); + for (var idx = 0; idx < names.length; idx += 1) { + var name = names[idx]; + s += f(idx === 0 ? ' ' : ', '); + s += f(name + ' :: ') + kv(name)(showType(fields[name])); + if (idx === names.length - 1) s += f(' '); + } + return s + f('}'); + }; + + var validate = function(x) { + if (x == null) { + return Left({value: x, typePath: [t], propPath: []}); + } + for (var idx = 0; idx < names.length; idx += 1) { + var name = names[idx]; + if (!has(name, x)) { + return Left({value: x, typePath: [t], propPath: []}); + } + var result = fields[name].validate(x[name]); + if (result.isLeft) { + return Left({value: result.value.value, + typePath: [t].concat(result.value.typePath), + propPath: [name].concat(result.value.propPath)}); + } + } + return Right(x); + }; + + var t = { + '@@type': 'sanctuary-def/Type', + type: 'RECORD', + validate: validate, + _test: testFrom(validate), + format: format, + toString: always(format(id, K(id))), + fields: fields + }; + return t; + }; + + // Nullable :: Type -> Type + $.Nullable = UnaryType( + 'sanctuary-def/Nullable', + K(true), + function(nullable) { return nullable === null ? [] : [nullable]; } + ); + + // StrMap :: Type -> Type + var StrMap = UnaryType( + 'sanctuary-def/StrMap', + function(x) { return $.Object._test(x); }, + function(strMap) { + return map(keys(strMap), function(k) { return strMap[k]; }); + } + ); + + // $$type :: a -> String + var $$type = function(x) { + return x != null && typeOf(x['@@type']) === 'String' ? + x['@@type'] : + typeOf(x); + }; + + // $$typeEq :: String -> a -> Boolean + var $$typeEq = function(name) { + return function(x) { + return $$type(x) === name; + }; + }; + + // type0 :: String -> Type + var type0 = function(name) { + return NullaryType(name, $$typeEq(name)); + }; + + // type1 :: (String, (t a -> [a])) -> Type -> Type + var type1 = function(name, _1) { + return UnaryType(name, $$typeEq(name), _1); + }; + + // applyParameterizedTypes :: [Type] -> [Type] + var applyParameterizedTypes = function(types) { + return map(types, function(x) { + return typeof x === 'function' ? + x.apply(null, map(range(0, x.length), K(Unknown))) : + x; + }); + }; + + // defaultEnv :: [Type] + var defaultEnv = $.env = applyParameterizedTypes([ + $.Array = type1('Array', id), + $.Boolean = type0('Boolean'), + $.Date = type0('Date'), + $.Error = type0('Error'), + $.Function = type0('Function'), + $.Null = type0('Null'), + $.Number = type0('Number'), + $.Object = type0('Object'), + $.RegExp = type0('RegExp'), + $.StrMap = StrMap, + $.String = type0('String'), + $.Undefined = type0('Undefined') + ]); + + // Any :: Type + $.Any = NullaryType( + 'sanctuary-def/Any', + K(true) + ); + + // Pair :: (Type, Type) -> Type + $.Pair = $.BinaryType( + 'sanctuary-def/Pair', + function(x) { return $$typeEq('Array')(x) && x.length === 2; }, + function(pair) { return [pair[0]]; }, + function(pair) { return [pair[1]]; } + ); + + // ValidDate :: Type + $.ValidDate = NullaryType( + 'sanctuary-def/ValidDate', + function(x) { return $.Date._test(x) && !isNaN(x.valueOf()); } + ); + + // PositiveNumber :: Type + $.PositiveNumber = NullaryType( + 'sanctuary-def/PositiveNumber', + function(x) { return $.Number._test(x) && x > 0; } + ); + + // NegativeNumber :: Type + $.NegativeNumber = NullaryType( + 'sanctuary-def/NegativeNumber', + function(x) { return $.Number._test(x) && x < 0; } + ); + + // ValidNumber :: Type + var ValidNumber = $.ValidNumber = NullaryType( + 'sanctuary-def/ValidNumber', + function(x) { return $.Number._test(x) && !isNaN(x); } + ); + + // NonZeroValidNumber :: Type + $.NonZeroValidNumber = NullaryType( + 'sanctuary-def/NonZeroValidNumber', + function(x) { + return ValidNumber._test(x) && + /* eslint-disable eqeqeq */ + x != 0; + /* eslint-enable eqeqeq */ + } + ); + + // FiniteNumber :: Type + var FiniteNumber = $.FiniteNumber = NullaryType( + 'sanctuary-def/FiniteNumber', + function(x) { return ValidNumber._test(x) && isFinite(x); } + ); + + // PositiveFiniteNumber :: Type + $.PositiveFiniteNumber = NullaryType( + 'sanctuary-def/PositiveFiniteNumber', + function(x) { return FiniteNumber._test(x) && x > 0; } + ); + + // NegativeFiniteNumber :: Type + $.NegativeFiniteNumber = NullaryType( + 'sanctuary-def/NegativeFiniteNumber', + function(x) { return FiniteNumber._test(x) && x < 0; } + ); + + // NonZeroFiniteNumber :: Type + $.NonZeroFiniteNumber = NullaryType( + 'sanctuary-def/NonZeroFiniteNumber', + function(x) { + return FiniteNumber._test(x) && + /* eslint-disable eqeqeq */ + x != 0; + /* eslint-enable eqeqeq */ + } + ); + + // Integer :: Type + var Integer = $.Integer = NullaryType( + 'sanctuary-def/Integer', + function(x) { + return ValidNumber._test(x) && + /* eslint-disable eqeqeq */ + Math.floor(x) == x && + /* eslint-enable eqeqeq */ + x >= MIN_SAFE_INTEGER && + x <= MAX_SAFE_INTEGER; + } + ); + + // PositiveInteger :: Type + $.PositiveInteger = NullaryType( + 'sanctuary-def/PositiveInteger', + function(x) { return Integer._test(x) && x > 0; } + ); + + // NegativeInteger :: Type + $.NegativeInteger = NullaryType( + 'sanctuary-def/NegativeInteger', + function(x) { return Integer._test(x) && x < 0; } + ); + + // NonZeroInteger :: Type + $.NonZeroInteger = NullaryType( + 'sanctuary-def/NonZeroInteger', + function(x) { + return Integer._test(x) && + /* eslint-disable eqeqeq */ + x != 0; + /* eslint-enable eqeqeq */ + } + ); + + // RegexFlags :: Type + $.RegexFlags = EnumType(['', 'g', 'i', 'm', 'gi', 'gm', 'im', 'gim']); + + // Type :: Type + var Type = type0('sanctuary-def/Type'); + + // TypeClass :: Type + var TypeClass = type0('sanctuary-def/TypeClass'); + + // arity :: (Number, Function) -> Function + var arity = function(n, f) { + return ( + n === 0 ? + function() { + return f.apply(this, arguments); + } : + n === 1 ? + function($1) { + return f.apply(this, arguments); + } : + n === 2 ? + function($1, $2) { + return f.apply(this, arguments); + } : + n === 3 ? + function($1, $2, $3) { + return f.apply(this, arguments); + } : + n === 4 ? + function($1, $2, $3, $4) { + return f.apply(this, arguments); + } : + n === 5 ? + function($1, $2, $3, $4, $5) { + return f.apply(this, arguments); + } : + n === 6 ? + function($1, $2, $3, $4, $5, $6) { + return f.apply(this, arguments); + } : + n === 7 ? + function($1, $2, $3, $4, $5, $6, $7) { + return f.apply(this, arguments); + } : + n === 8 ? + function($1, $2, $3, $4, $5, $6, $7, $8) { + return f.apply(this, arguments); + } : + // else + function($1, $2, $3, $4, $5, $6, $7, $8, $9) { + return f.apply(this, arguments); + } + ); + }; + + // numArgs :: Number -> String + var numArgs = function(n) { + switch (n) { + case 0: return 'zero arguments'; + case 1: return 'one argument'; + case 2: return 'two arguments'; + case 3: return 'three arguments'; + case 4: return 'four arguments'; + case 5: return 'five arguments'; + case 6: return 'six arguments'; + case 7: return 'seven arguments'; + case 8: return 'eight arguments'; + case 9: return 'nine arguments'; + default: return n + ' arguments'; + } + }; + + // unexpectedType :: Any -> TypeError + var unexpectedType = /* istanbul ignore next */ function(x) { + return new TypeError( + 'Unexpected type ' + + LEFT_SINGLE_QUOTATION_MARK + x + RIGHT_SINGLE_QUOTATION_MARK + ); + }; + + // equalTypes :: (Type, Type, Boolean) -> Boolean + var equalTypes = function equalTypes(t1, t2, loose) { + if (t1.type === 'INCONSISTENT' || t2.type === 'INCONSISTENT') return loose; + if (t1.type === 'UNKNOWN' || t2.type === 'UNKNOWN') return true; + switch (t1.type) { + case 'NULLARY': + return t1.type === t2.type && t1.name === t2.name; + case 'UNARY': + return t1.type === t2.type && t1.name === t2.name && + equalTypes(t1.$1, t2.$1, loose); + case 'BINARY': + return t1.type === t2.type && t1.name === t2.name && + equalTypes(t1.$1, t2.$1, loose) && + equalTypes(t1.$2, t2.$2, loose); + case 'ENUM': + return t1.type === t2.type && show(t1) === show(t2); + case 'RECORD': + return t1.type === t2.type && show(t1) === show(t2); + /* istanbul ignore next */ + default: + throw unexpectedType(t1.type); + } + }; + + // chooseType :: (Type, Type) -> Type + var chooseType = function(t1, t2) { + return t1.type === 'UNKNOWN' ? t2 : t1; + }; + + // mergeTypes :: (Type, Type) -> Type + // + // Either String ??? `mergeTypes` Either ??? Number = Either String Number + var mergeTypes = function(t1, t2) { + return ( + t1.type === 'UNARY' ? + UnaryType.from(t1)(chooseType(t1.$1, t2.$1)) : + t1.type === 'BINARY' ? + BinaryType.from(t1)(chooseType(t1.$1, t2.$1), + chooseType(t1.$2, t2.$2)) : + // else + chooseType(t1, t2) + ); + }; + + // commonTypes :: ([[Type]], Boolean) -> [Type] + // + // [[String, RegexFlags], [String, RegexFlags]] ---> [String, RegexFlags] + // + // [[Boolean], [Boolean], [Boolean], [Number]] ---> [] + // + // [[Array ???], [Array String], [Array ???]] ---> [Array String] + // + // [[Either String ???], [Either ??? Number]] ---> [Either String Number] + var commonTypes = function(typeses, loose) { + return reduce(typeses[0], [], function(types, t) { + var st = reduce(typeses, {ok: true, type: t}, function(st, types) { + var st$ = reduce(types, {ok: false, type: st.type}, function(st, t) { + var equal = equalTypes(st.type, t, loose); + return {ok: equal || st.ok, + type: equal ? mergeTypes(st.type, t) : st.type}; + }); + return {type: st$.type, ok: st.ok && st$.ok}; + }); + return st.ok ? types.concat([st.type]) : types; + }); + }; + + // _determineActualTypes :: (Boolean, [Type], [Object], [Any]) -> [Type] + var _determineActualTypes = function recur(loose, env, seen, values) { + if (isEmpty(values)) return [Unknown]; + // typeses :: [[Type]] + var typeses = map(values, function(value) { + var seen$; + if (typeof value === 'object' && value != null || + typeof value === 'function') { + // Abort if a circular reference is encountered; add the current + // object to the list of seen objects otherwise. + if (seen.indexOf(value) >= 0) return []; + seen$ = seen.concat([value]); + } else { + seen$ = seen; + } + return chain(env, function(t) { + return ( + t.name === 'sanctuary-def/Nullable' || !t._test(value) ? + [] : + t.type === 'UNARY' ? + map(recur(loose, env, seen$, t._1(value)), UnaryType.from(t)) : + t.type === 'BINARY' ? + BinaryType.xprod(t, + recur(loose, env, seen$, t._1(value)), + recur(loose, env, seen$, t._2(value))) : + // else + [t] + ); + }); + }); + // common :: [Type] + var common = commonTypes(typeses, loose); + if (!isEmpty(common)) return common; + // If none of the values is a member of a type in the environment, + // and all the values have the same type identifier, the values are + // members of a "foreign" type. + if (isEmpty(filterTypesByValues(env, values)) && + all(values.slice(1), $$typeEq($$type(values[0])))) { + // Create a nullary type for the foreign type. + return [type0($$type(values[0]))]; + } + return [Inconsistent]; + }; + + // rejectInconsistent :: [Type] -> [Type] + var rejectInconsistent = function(types) { + return filter(types, function(t) { + return t.type !== 'INCONSISTENT' && t.type !== 'UNKNOWN'; + }); + }; + + // determineActualTypesStrict :: ([Type], [Any]) -> [Type] + var determineActualTypesStrict = function(env, values) { + return rejectInconsistent(_determineActualTypes(false, env, [], values)); + }; + + // determineActualTypesLoose :: ([Type], [Any]) -> [Type] + var determineActualTypesLoose = function(env, values) { + return rejectInconsistent(_determineActualTypes(true, env, [], values)); + }; + + // valuesToPairs :: ([Type], [Any]) -> [Pair Any [Type]] + var valuesToPairs = function(env, values) { + return map(values, function(x) { + return [x, determineActualTypesLoose(env, [x])]; + }); + }; + + // _satisfactoryTypes :: + // ... -> Either Error { typeVarMap :: StrMap { info :: Info + // , types :: [Type] } + // , types :: [Type] } + var _satisfactoryTypes = function( + env, // :: [Type] + name, // :: String + constraints, // :: StrMap [TypeClass] + expTypes, // :: [Type] + index // :: Integer + ) { + return function recur( + typeVarMap, // :: StrMap { info :: Info, types :: [Type] } + expType, // :: Type + values, // :: [Any] + typePath, // :: [Type] + propPath // :: [String] + ) { + var idx, okTypes; + if (!all(values, expType._test)) { + return Left(new TypeError('Invalid value')); + } + switch (expType.type) { + + case 'VARIABLE': + var typeVarName = expType.name; + if (has(typeVarName, constraints)) { + var typeClasses = constraints[typeVarName]; + for (idx = 0; idx < values.length; idx += 1) { + for (var idx2 = 0; idx2 < typeClasses.length; idx2 += 1) { + if (!typeClasses[idx2]._test(values[idx])) { + return Left(typeClassConstraintViolation( + name, + constraints, + expTypes, + typeClasses[idx2], + Info(env, + [values[idx]], + typePath.concat([expType]), + propPath, + index) + )); + } + } + } + } + if (has(typeVarName, typeVarMap)) { + okTypes = filterTypesByValues(typeVarMap[typeVarName].types, + values); + if (isEmpty(okTypes)) { + return Left(typeVarConstraintViolation2( + name, + constraints, + expTypes, + Info(env, + values, + typePath.concat([expType]), + propPath, + index), + typeVarMap[typeVarName].info + )); + } + } else { + okTypes = determineActualTypesStrict(env, values); + if (isEmpty(okTypes) && !isEmpty(values)) { + return Left(typeVarConstraintViolation( + name, + constraints, + expTypes, + Info(env, + values, + typePath.concat([expType]), + propPath, + index) + )); + } + } + return Right({ + typeVarMap: isEmpty(okTypes) ? typeVarMap : assoc( + typeVarName, + {types: okTypes, + info: Info(env, + values, + typePath.concat([expType]), + propPath, + index)}, + typeVarMap + ), + types: okTypes + }); + + case 'UNARY': + return recur( + typeVarMap, + expType.$1, + chain(values, expType._1), + typePath.concat([expType]), + propPath.concat(['$1']) + ) + .map(function(result) { + return { + typeVarMap: result.typeVarMap, + types: map(or(result.types, [expType.$1]), + UnaryType.from(expType)) + }; + }); + + case 'BINARY': + return recur( + typeVarMap, + expType.$1, + chain(values, expType._1), + typePath.concat([expType]), + propPath.concat(['$1']) + ) + .chain(function(result) { + var $1s = result.types; + return recur( + result.typeVarMap, + expType.$2, + chain(values, expType._2), + typePath.concat([expType]), + propPath.concat(['$2']) + ) + .map(function(result) { + var $2s = result.types; + return { + typeVarMap: result.typeVarMap, + types: BinaryType.xprod(expType, + or($1s, [expType.$1]), + or($2s, [expType.$2])) + }; + }); + }); + + default: + return Right({typeVarMap: typeVarMap, + types: determineActualTypesStrict(env, values)}); + } + }; + }; + + // satisfactoryTypes :: ... -> Either Error [Type] + var satisfactoryTypes = function( + env, // :: [Type] + name, // :: String + constraints, // :: StrMap [TypeClass] + expTypes, // :: [Type] + typeVarMap, // :: StrMap { info :: Info, types :: [Type] } + value, // :: Any + index // :: Integer + ) { + var result = expTypes[index].validate(value); + return result.isLeft ? + Left(invalidValue(name, + constraints, + expTypes, + Info(env, + [result.value.value], + result.value.typePath, + result.value.propPath, + index))) : + result.chain(function(value) { + var f = _satisfactoryTypes(env, name, constraints, expTypes, index); + return f(typeVarMap, expTypes[index], [value], [], []); + }); + }; + + // test :: ([Type], Type, Any) -> Boolean + var test = $.test = function(_env, t, x) { + var env = applyParameterizedTypes(_env); + var f = _satisfactoryTypes(env, 'name', {}, [t], 0); + return f({}, t, [x], [], []).isRight; + }; + + // filterTypesByValues :: ([Type], [Any]) -> [Type] + var filterTypesByValues = function(env, values) { + return filter(env, function(t) { + return all(values, function(x) { + return test(env, t, x); + }); + }); + }; + + // invalidArgumentsLength :: (String, Integer, Integer) -> Error + var invalidArgumentsLength = function(name, expectedLength, actualLength) { + return new TypeError( + LEFT_SINGLE_QUOTATION_MARK + name + RIGHT_SINGLE_QUOTATION_MARK + + ' requires ' + numArgs(expectedLength) + ';' + + ' received ' + numArgs(actualLength) + ); + }; + + // constraintsRepr :: StrMap [TypeClass] -> String + var constraintsRepr = function(constraints) { + var reprs = chain(toPairs(constraints), function(pair) { + return map(pair[1], function(typeClass) { + return stripNamespace(typeClass.name) + ' ' + pair[0]; + }); + }); + return when(reprs.length > 0, + function(s) { return s + ' => '; }, + when(reprs.length > 1, + function(s) { return '(' + s + ')'; }, + reprs.join(', '))); + }; + + // label :: String -> String -> String + var label = function(label) { + return function(s) { + var delta = s.length - label.length; + return strRepeat(' ', Math.floor(delta / 2)) + label + + strRepeat(' ', Math.ceil(delta / 2)); + }; + }; + + // arrowJoin :: [String] -> String + var arrowJoin = function(xs) { + return xs.join(' -> '); + }; + + // isParameterizedType :: Object -> Boolean + var isParameterizedType = function(t) { + return t.type === 'UNARY' || t.type === 'BINARY'; + }; + + // showType :: Type -> String + var showType = function(t) { + var s = String(t); + return isParameterizedType(t) ? s.slice(1, -1) : s; + }; + + // showTypeQuoted :: Type -> String + var showTypeQuoted = function(t) { + return LEFT_SINGLE_QUOTATION_MARK + + showType(t) + + RIGHT_SINGLE_QUOTATION_MARK; + }; + + // showTypeSig :: [Type] -> String + var showTypeSig = function(types) { + return arrowJoin(map(types, showType)); + }; + + // showTypeSig_ :: [Type] -> String + var showTypeSig_ = function(types) { + return arrowJoin(map(types, showType).concat([''])); + }; + + // _showTypeSig :: [Type] -> String + var _showTypeSig = function(types) { + return arrowJoin([''].concat(map(types, showType))); + }; + + // _showTypeSig_ :: [Type] -> String + var _showTypeSig_ = function(types) { + return arrowJoin([''].concat(map(types, showType)).concat([''])); + }; + + // showValueAndType :: Pair Any [Type] -> String + var showValueAndType = function(pair) { + return show(pair[0]) + ' :: ' + map(pair[1], showType).join(', '); + }; + + // underline :: Type -> [String] -> (String -> String) -> String + var underline = function(type) { + return function(propPath) { + return function(f) { + var t = type; + var types = [t]; + for (var idx = 0; idx < propPath.length; idx += 1) { + types.push(t = (t.type === 'RECORD' ? t.fields : t)[propPath[idx]]); + } + + var s = f(String(last(types))); + for (idx = types.length - 2; idx >= 0; idx -= 1) { + var k = propPath[idx]; + t = types[idx]; + s = t.type === 'UNARY' ? + t.format(_, K(s)) : + t.type === 'BINARY' && k === '$1' ? + t.format(_, K(s), _) : + t.type === 'BINARY' && k === '$2' ? + t.format(_, _, K(s)) : + // else + t.format(_, function(k$) { return k$ === k ? K(s) : _; }); + } + + return isParameterizedType(type) ? s.slice(1, -1) : s; + }; + }; + }; + + // Info = { index :: Integer + // , pairs :: [Pair Any [Type]] + // , propPath :: [String] + // , typePath :: [Type] } + + // Info :: ([Type], [Any], [Type], [String], Integer) -> Info + var Info = function(env, values, typePath, propPath, index) { + return {index: index, + pairs: valuesToPairs(env, values), + propPath: propPath, + typePath: typePath}; + }; + + // typeClassConstraintViolation :: ... -> Error + var typeClassConstraintViolation = function( + name, // :: String + constraints, // :: StrMap [TypeClass] + expTypes, // :: [Type] + typeClass, // :: TypeClass + info // :: Info + ) { + var typeVarName = last(info.typePath).name; + var reprs = chain(toPairs(constraints), function(pair) { + return map(pair[1], function(tc) { + var match = tc.name === typeClass.name && pair[0] === typeVarName; + return r(match ? '^' : ' ')(stripNamespace(tc.name) + ' ' + pair[0]); + }); + }); + + var carets = when(reprs.length > 1, + function(s) { return _('(') + s + _(')'); }, + reprs.join(_(', '))); + + var padding = _(showTypeSig_(expTypes.slice(0, info.index))); + var f = underline(info.typePath[0])(info.propPath); + + return new TypeError(trimTrailingSpaces(unlines([ + 'Type-class constraint violation', + '', + name + ' :: ' + constraintsRepr(constraints) + showTypeSig(expTypes), + _(name + ' :: ') + carets + _(' => ') + padding + f(r('^')), + _(name + ' :: ' + carets + ' => ') + padding + f(label('1')), + '', + '1) ' + map(info.pairs, showValueAndType).join('\n '), + '', + LEFT_SINGLE_QUOTATION_MARK + name + RIGHT_SINGLE_QUOTATION_MARK + + ' requires ' + LEFT_SINGLE_QUOTATION_MARK + + typeVarName + RIGHT_SINGLE_QUOTATION_MARK + + ' to satisfy the ' + typeClass + ' type-class constraint;' + + ' the value at position 1 does not.' + ]))); + }; + + // annotateSig :: ... -> String + var annotateSig = function( + types, // :: [Type] + fst, // :: Info + snd, // :: Info + f, // :: String -> String + g // :: String -> String + ) { + return _(_showTypeSig(types.slice(0, fst.index))) + + underline(fst.typePath[0])(fst.propPath)(f) + + _(_showTypeSig_(types.slice(fst.index + 1, snd.index))) + + underline(snd.typePath[0])(snd.propPath)(g); + }; + + // _typeVarConstraintViolation :: ... -> Error + var _typeVarConstraintViolation = function( + name, // :: String + constraints, // :: StrMap [TypeClass] + expTypes, // :: [Type] + carets, // :: String + numbers, // :: String + pairss // :: [[Pair Any [Type]]] + ) { + var nameAndConstraints = name + ' :: ' + constraintsRepr(constraints); + var lines = []; + lines.push('Type-variable constraint violation'); + lines.push(''); + lines.push(nameAndConstraints + showTypeSig(expTypes)); + lines.push(_(nameAndConstraints) + carets); + lines.push(_(nameAndConstraints) + numbers); + for (var idx = 0; idx < pairss.length; idx += 1) { + lines.push(''); + lines.push(String(idx + 1) + ') ' + + map(pairss[idx], showValueAndType).join('\n ')); + } + lines.push(''); + lines.push('Since there is no type of which all the above values are ' + + 'members, the type-variable constraint has been violated.'); + return new TypeError(trimTrailingSpaces(unlines(lines))); + }; + + // typeVarConstraintViolation :: ... -> Error + var typeVarConstraintViolation = function( + name, // :: String + constraints, // :: StrMap [TypeClass] + expTypes, // :: [Type] + info // :: Info + ) { + var padding = _(_showTypeSig(expTypes.slice(0, info.index))); + var f = underline(expTypes[info.index])(info.propPath); + return _typeVarConstraintViolation( + name, + constraints, + expTypes, + padding + f(r('^')), + padding + f(label('1')), + [info.pairs] + ); + }; + + // typeVarConstraintViolation2 :: ... -> Error + var typeVarConstraintViolation2 = function( + name, // :: String + constraints, // :: StrMap [TypeClass] + expTypes, // :: [Type] + _fst, // :: Info + _snd // :: Info + ) { + var fst = _fst.index < _snd.index ? _fst : _snd; + var snd = _fst.index < _snd.index ? _snd : _fst; + return _typeVarConstraintViolation( + name, + constraints, + expTypes, + annotateSig(expTypes, fst, snd, r('^'), r('^')), + annotateSig(expTypes, fst, snd, label('1'), label('2')), + [fst.pairs, snd.pairs] + ); + }; + + // invalidValue :: ... -> Error + var invalidValue = function( + name, // :: String + constraints, // :: StrMap [TypeClass] + expTypes, // :: [Type] + info // :: Info + ) { + var nameAndConstraints = name + ' :: ' + constraintsRepr(constraints); + var padding = _(_showTypeSig(expTypes.slice(0, info.index))); + var f = underline(info.typePath[0])(info.propPath); + + return new TypeError(trimTrailingSpaces(unlines([ + 'Invalid value', + '', + nameAndConstraints + showTypeSig(expTypes), + _(nameAndConstraints) + padding + f(r('^')), + _(nameAndConstraints) + padding + f(label('1')), + '', + '1) ' + map(info.pairs, showValueAndType).join('\n '), + '', + 'The value at position 1 is not a member of ' + + showTypeQuoted(last(info.typePath)) + '.' + ]))); + }; + + // assertRight :: Either a b -> Undefined ! + var assertRight = function(either) { + if (either.isLeft) throw either.value; + }; + + // Options :: Type + var Options = RecordType({checkTypes: $.Boolean, env: $.Array($.Any)}); + + // create :: Options -> Function + $.create = function(opts) { + assertRight(satisfactoryTypes(defaultEnv, + 'create', + {}, + [Options, $.Function], + {}, + opts, + 0)); + + // checkTypes :: Boolean + var checkTypes = opts.checkTypes; + + // env :: [Type] + var env = applyParameterizedTypes(opts.env); + + // curry :: ... -> Function + var curry = function( + name, // :: String + constraints, // :: StrMap [TypeClass] + expTypes, // :: [Type] + _typeVarMap, // :: StrMap { info :: Info, types :: [Type] } + _values, // :: [Any] + _indexes, // :: [Integer] + impl // :: Function + ) { + return arity(_indexes.length, function() { + if (checkTypes) { + var delta = _indexes.length - arguments.length; + if (delta < 0) { + throw invalidArgumentsLength(name, + expTypes.length - 1, + expTypes.length - 1 - delta); + } + } + var typeVarMap = _typeVarMap; + var values = _values.slice(); + var indexes = []; + for (var idx = 0; idx < _indexes.length; idx += 1) { + var index = _indexes[idx]; + + if (idx < arguments.length && + !(typeof arguments[idx] === 'object' && + arguments[idx] != null && + arguments[idx]['@@functional/placeholder'] === true)) { + + var value = arguments[idx]; + if (checkTypes) { + var result = satisfactoryTypes(env, + name, + constraints, + expTypes, + typeVarMap, + value, + index); + assertRight(result); + typeVarMap = result.value.typeVarMap; + } + values[index] = value; + } else { + indexes.push(index); + } + } + if (isEmpty(indexes)) { + var returnValue = impl.apply(this, values); + if (checkTypes) { + assertRight(satisfactoryTypes(env, + name, + constraints, + expTypes, + typeVarMap, + returnValue, + expTypes.length - 1)); + } + return returnValue; + } else { + return curry(name, + constraints, + expTypes, + typeVarMap, + values, + indexes, + impl); + } + }); + }; + + return function def(name, constraints, expTypes, impl) { + if (checkTypes) { + if (arguments.length !== def.length) { + throw invalidArgumentsLength('def', def.length, arguments.length); + } + + var types = [$.String, + StrMap($.Array(TypeClass)), + $.Array(Type), + $.Function, + $.Function]; + for (var idx = 0; idx < types.length - 1; idx += 1) { + assertRight(satisfactoryTypes(defaultEnv, + 'def', + {}, + types, + {}, + arguments[idx], + idx)); + } + } + + var arity = expTypes.length - 1; + if (arity > 9) { + throw new RangeError( + LEFT_SINGLE_QUOTATION_MARK + 'def' + RIGHT_SINGLE_QUOTATION_MARK + + ' cannot define a function with arity greater than nine' + ); + } + + return curry(name, + constraints, + expTypes, + {}, + new Array(arity), + range(0, arity), + impl); + }; + }; + + return $; + +})); + +},{}],670:[function(require,module,exports){ +/* ####### + #### #### + #### ### #### +##### ########### sanctuary +######## ######## noun +########### ##### 1 [ mass noun ] refuge from unsafe JavaScript + #### ### #### + #### #### + ####### */ + +//. # Sanctuary +//. +//. Sanctuary is a functional programming library inspired by Haskell and +//. PureScript. It depends on and works nicely with [Ramda][]. Sanctuary +//. makes it possible to write safe code without null checks. +//. +//. In JavaScript it's trivial to introduce a possible run-time type error: +//. +//. words[0].toUpperCase() +//. +//. If `words` is `[]` we'll get a familiar error at run-time: +//. +//. TypeError: Cannot read property 'toUpperCase' of undefined +//. +//. Sanctuary gives us a fighting chance of avoiding such errors. We might +//. write: +//. +//. R.map(S.toUpper, S.head(words)) +//. +//. Sanctuary is designed to work in Node.js and in ES5-compatible browsers. +//. +//. ## Types +//. +//. Sanctuary uses Haskell-like type signatures to describe the types of +//. values, including functions. `'foo'`, for example, has type `String`; +//. `[1, 2, 3]` has type `Array Number`. The arrow (`->`) is used to express +//. a function's type. `Math.abs`, for example, has type `Number -> Number`. +//. That is, it takes an argument of type `Number` and returns a value of +//. type `Number`. +//. +//. [`R.map`][R.map] has type `(a -> b) -> Array a -> Array b`. That is, +//. it takes an argument of type `a -> b` and returns a value of type +//. `Array a -> Array b`. `a` and `b` are type variables: applying `R.map` +//. to a value of type `String -> Number` will result in a value of type +//. `Array String -> Array Number`. +//. +//. Sanctuary embraces types. JavaScript doesn't support algebraic data types, +//. but these can be simulated by providing a group of data constructors which +//. return values with the same set of methods. A value of the Maybe type, for +//. example, is created via the Nothing constructor or the Just constructor. +//. +//. It's necessary to extend Haskell's notation to describe implicit arguments +//. to the *methods* provided by Sanctuary's types. In `x.map(y)`, for example, +//. the `map` method takes an implicit argument `x` in addition to the explicit +//. argument `y`. The type of the value upon which a method is invoked appears +//. at the beginning of the signature, separated from the arguments and return +//. value by a squiggly arrow (`~>`). The type of the `map` method of the Maybe +//. type is written `Maybe a ~> (a -> b) -> Maybe b`. One could read this as: +//. +//. _When the `map` method is invoked on a value of type `Maybe a` +//. (for any type `a`) with an argument of type `a -> b` (for any type `b`), +//. it returns a value of type `Maybe b`._ +//. +//. Sanctuary supports type classes: constraints on type variables. Whereas +//. `a -> a` implicitly supports every type, `Functor f => (a -> b) -> f a -> +//. f b` requires that `f` be a type which satisfies the requirements of the +//. Functor type class. Type-class constraints appear at the beginning of a +//. type signature, separated from the rest of the signature by a fat arrow +//. (`=>`). +//. +//. ### Accessible pseudotype +//. +//. What is the type of values which support property access? In other words, +//. what is the type of which every value except `null` and `undefined` is a +//. member? Object is close, but `Object.create(null)` produces a value which +//. supports property access but which is not a member of the Object type. +//. +//. Sanctuary uses the Accessible pseudotype to represent the set of values +//. which support property access. +//. +//. ### Integer pseudotype +//. +//. The Integer pseudotype represents integers in the range (-2^53 .. 2^53). +//. It is a pseudotype because each Integer is represented by a Number value. +//. Sanctuary's run-time type checking asserts that a valid Number value is +//. provided wherever an Integer value is required. +//. +//. ### Type representatives +//. +//. What is the type of `Number`? One answer is `a -> Number`, since it's a +//. function which takes an argument of any type and returns a Number value. +//. When provided as the first argument to [`is`](#is), though, `Number` is +//. really the value-level representative of the Number type. +//. +//. Sanctuary uses the TypeRep pseudotype to describe type representatives. +//. For example: +//. +//. Number :: TypeRep Number +//. +//. `Number` is the sole inhabitant of the TypeRep Number type. +//. +//. ## Type checking +//. +//. Sanctuary functions are defined via [sanctuary-def][] to provide run-time +//. type checking. This is tremendously useful during development: type errors +//. are reported immediately, avoiding circuitous stack traces (at best) and +//. silent failures due to type coercion (at worst). For example: +//. +//. ```javascript +//. S.inc('XXX'); +//. // ! TypeError: Invalid value +//. // +//. // inc :: FiniteNumber -> FiniteNumber +//. // ^^^^^^^^^^^^ +//. // 1 +//. // +//. // 1) "XXX" :: String +//. // +//. // The value at position 1 is not a member of ‘FiniteNumber’. +//. ``` +//. +//. Compare this to the behaviour of Ramda's unchecked equivalent: +//. +//. ```javascript +//. R.inc('XXX'); +//. // => NaN +//. ``` +//. +//. There is a performance cost to run-time type checking. One may wish to +//. disable type checking in certain contexts to avoid paying this cost. +//. [`create`](#create) facilitates the creation of a Sanctuary module which +//. does not perform type checking. +//. +//. In Node, one could use an environment variable to determine whether to +//. perform type checking: +//. +//. ```javascript +//. const {create, env} = require('sanctuary'); +//. +//. const checkTypes = process.env.NODE_ENV !== 'production'; +//. const S = create({checkTypes: checkTypes, env: env}); +//. ``` +//. +//. ## API + +(function(f) { + + 'use strict'; + + /* istanbul ignore else */ + if (typeof module === 'object' && typeof module.exports === 'object') { + module.exports = f(require('ramda'), require('sanctuary-def')); + } else if (typeof define === 'function' && define.amd != null) { + define(['ramda', 'sanctuary-def'], f); + } else { + self.sanctuary = f(self.R, self.sanctuaryDef); + } + +}(function(R, $) { + + 'use strict'; + + var _ = R.__; + + var sentinel = {}; + + // _type :: a -> String + var _type = function(x) { + return x != null && R.type(x['@@type']) === 'String' ? x['@@type'] + : R.type(x); + }; + + // compose2 :: ((b -> c), (a -> b)) -> a -> c + var compose2 = function(f, g) { + return function(x) { + return f(g(x)); + }; + }; + + // compose3 :: ((b -> c), (a -> b), a) -> c + var compose3 = function(f, g, x) { + return f(g(x)); + }; + + // filter :: (Monad m, Monoid m) => ((a -> Boolean), m a) -> m a + var filter = function(pred, m) { + return m.chain(function(x) { + return pred(x) ? m.of(x) : m.empty(); + }); + }; + + // hasMethod :: String -> Any -> Boolean + var hasMethod = function(name) { + return function(x) { + return x != null && typeof x[name] === 'function'; + }; + }; + + // inspect :: -> String + var inspect = /* istanbul ignore next */ function() { + return this.toString(); + }; + + // negativeZero :: a -> Boolean + var negativeZero = R.either(R.equals(-0), R.equals(new Number(-0))); + + // Accessible :: TypeClass + var Accessible = $.TypeClass( + 'sanctuary/Accessible', + function(x) { return x != null; } + ); + + // Applicative :: TypeClass + var Applicative = $.TypeClass( + 'sanctuary/Applicative', + function(x) { + return _type(x) === 'Array' || + Apply._test(x) && (hasMethod('of')(x) || + hasMethod('of')(x.constructor)); + } + ); + + // Apply :: TypeClass + var Apply = $.TypeClass( + 'sanctuary/Apply', + function(x) { + return R.contains(_type(x), ['Array', 'Function']) || + Functor._test(x) && hasMethod('ap')(x); + } + ); + + // Foldable :: TypeClass + var Foldable = $.TypeClass( + 'sanctuary/Foldable', + function(x) { + return _type(x) === 'Array' || hasMethod('reduce')(x); + } + ); + + // Functor :: TypeClass + var Functor = $.TypeClass( + 'sanctuary/Functor', + function(x) { + return R.contains(_type(x), ['Array', 'Function']) || + hasMethod('map')(x); + } + ); + + // Monoid :: TypeClass + var Monoid = $.TypeClass( + 'sanctuary/Monoid', + function(x) { + return R.contains(_type(x), ['Array', 'Boolean', 'Object', 'String']) || + hasMethod('empty')(x); + } + ); + + // Ord :: TypeClass + var Ord = $.TypeClass( + 'sanctuary/Ord', + R.anyPass([$.String._test, $.ValidDate._test, $.ValidNumber._test]) + ); + + // Semigroup :: TypeClass + var Semigroup = $.TypeClass( + 'sanctuary/Semigroup', + hasMethod('concat') + ); + + var a = $.TypeVariable('a'); + var b = $.TypeVariable('b'); + var c = $.TypeVariable('c'); + var d = $.TypeVariable('d'); + var f = $.TypeVariable('f'); + var l = $.TypeVariable('l'); + var r = $.TypeVariable('r'); + + // $Either :: Type -> Type -> Type + var $Either = $.BinaryType( + 'sanctuary/Either', + function(x) { return x != null && x['@@type'] === 'sanctuary/Either'; }, + function(either) { return either.isLeft ? [either.value] : []; }, + function(either) { return either.isRight ? [either.value] : []; } + ); + + // List :: Type -> Type + var List = $.UnaryType( + 'sanctuary/List', + function(x) { + return x != null && + R.type(x) !== 'Function' && + $.Integer._test(x.length) && + x.length >= 0; + }, + function(list) { + return list.length > 0 && R.type(list) !== 'String' ? [list[0]] : []; + } + ); + + // $Maybe :: Type -> Type + var $Maybe = $.UnaryType( + 'sanctuary/Maybe', + function(x) { return x != null && x['@@type'] === 'sanctuary/Maybe'; }, + function(maybe) { return maybe.isJust ? [maybe.value] : []; } + ); + + // TypeRep :: Type + var TypeRep = $.NullaryType( + 'sanctuary/TypeRep', + function(x) { + return R.type(x) === 'Function' || + (x != null && + R.type(x.name) === 'String' && + R.type(x.test) === 'Function'); + } + ); + + // defaultEnv :: Array Type + var defaultEnv = $.env.concat([ + $.FiniteNumber, + $.NonZeroFiniteNumber, + $Either, + $.Integer, + $Maybe, + $.Pair, + $.RegexFlags, + TypeRep, + $.ValidDate, + $.ValidNumber + ]); + + // Options :: Type + var Options = $.RecordType({checkTypes: $.Boolean, env: $.Array($.Any)}); + + // createSanctuary :: Options -> Module + var createSanctuary = function createSanctuary(opts) { + + /* eslint-disable indent */ + + var S = {EitherType: $Either, MaybeType: $Maybe}; + + //# create :: { checkTypes :: Boolean, env :: Array Type } -> Module + //. + //. Takes an options record and returns a Sanctuary module. `checkTypes` + //. specifies whether to enable type checking. The module's polymorphic + //. functions (such as [`I`](#I)) require each value associated with a + //. type variable to be a member of at least one type in the environment. + //. + //. A well-typed application of a Sanctuary function will produce the same + //. result regardless of whether type checking is enabled. If type checking + //. is enabled, a badly typed application will produce an exception with a + //. descriptive error message. + //. + //. The following snippet demonstrates defining a custom type and using + //. `create` to produce a Sanctuary module which is aware of that type: + //. + //. ```javascript + //. const {create, env} = require('sanctuary'); + //. const $ = require('sanctuary-def'); + //. + //. // identityTypeName :: String + //. const identityTypeName = 'my-package/Identity'; + //. + //. // Identity :: a -> Identity a + //. const Identity = function Identity(x) { + //. return { + //. '@@type': identityTypeName, + //. map: f => Identity(f(x)), + //. chain: f => f(x), + //. // ... + //. value: x, + //. }; + //. }; + //. + //. // isIdentity :: a -> Boolean + //. const isIdentity = x => x != null && x['@@type'] === identityTypeName; + //. + //. // identityToArray :: Identity a -> Array a + //. const identityToArray = identity => [identity.value]; + //. + //. // IdentityType :: Type + //. const IdentityType = + //. $.UnaryType(identityTypeName, isIdentity, identityToArray); + //. + //. const S = create({ + //. checkTypes: process.env.NODE_ENV !== 'production', + //. env: env.concat([IdentityType]), + //. }); + //. ``` + //. + //. See also [`env`](#env). + S.create = + $.create({checkTypes: opts.checkTypes, env: defaultEnv})('create', + {}, + [Options, $.Object], + createSanctuary); + + //# env :: Array Type + //. + //. The default environment, which may be used as is or as the basis of a + //. custom environment in conjunction with [`create`](#create). + S.env = defaultEnv; + + var def = $.create(opts); + + // Note: Type checking of method arguments takes place once all arguments + // have been provided (whereas function arguments are checked as early as + // possible). This is not ideal, but provides two benefits: + // + // - accurate type signatures in error messages (though "->" appears in + // place of "~>"); and + // + // - intuitive ordering (`a.m(b, c)` is checked in a-b-c order rather + // than b-c-a order). + var method = function(name, constraints, types, _f) { + var f = def(name, constraints, types, _f); + return def(name, + constraints, + R.repeat($.Any, types.length - 1), + function() { return R.apply(f, R.prepend(this, arguments)); }); + }; + + // prop :: Accessible a => String -> a -> b + var prop = + def('prop', + {a: [Accessible]}, + [$.String, a, b], + function(key, obj) { + var boxed = Object(obj); + if (key in boxed) { + return boxed[key]; + } else { + throw new TypeError('‘prop’ expected object to have a property ' + + 'named ‘' + key + '’; ' + + R.toString(obj) + ' does not'); + } + }); + + //. ### Classify + + //# type :: a -> String + //. + //. Takes a value, `x`, of any type and returns its type identifier. If + //. `x` has a `'@@type'` property whose value is a string, `x['@@type']` + //. is the type identifier. Otherwise, the type identifier is the result + //. of applying [`R.type`][R.type] to `x`. + //. + //. `'@@type'` properties should use the form `'/'`, + //. where `` is the name of the npm package in which the type + //. is defined. + //. + //. ```javascript + //. > S.type(S.Just(42)) + //. 'sanctuary/Maybe' + //. + //. > S.type([1, 2, 3]) + //. 'Array' + //. ``` + S.type = + def('type', + {}, + [$.Any, $.String], + _type); + + //# is :: TypeRep a -> b -> Boolean + //. + //. Takes a [type representative](#type-representatives) and a value of + //. any type and returns `true` if the given value is of the specified + //. type; `false` otherwise. Subtyping is not respected. + //. + //. ```javascript + //. > S.is(Number, 42) + //. true + //. + //. > S.is(Object, 42) + //. false + //. + //. > S.is(String, 42) + //. false + //. ``` + var is = S.is = + def('is', + {}, + [TypeRep, $.Any, $.Boolean], + function(type, x) { + return x != null && ( + R.type(type.prototype['@@type']) === 'String' ? + x['@@type'] === type.prototype['@@type'] : + R.type(x) === R.nth(1, R.match(/function (\w*)/, String(type))) + ); + }); + + //. ### Combinator + + //# I :: a -> a + //. + //. The I combinator. Returns its argument. Equivalent to Haskell's `id` + //. function. + //. + //. ```javascript + //. > S.I('foo') + //. 'foo' + //. ``` + var I = S.I = + def('I', + {}, + [a, a], + function(x) { return x; }); + + //# K :: a -> b -> a + //. + //. The K combinator. Takes two values and returns the first. Equivalent to + //. Haskell's `const` function. + //. + //. ```javascript + //. > S.K('foo', 'bar') + //. 'foo' + //. + //. > R.map(S.K(42), R.range(0, 5)) + //. [42, 42, 42, 42, 42] + //. ``` + S.K = + def('K', + {}, + [a, b, a], + function(x, y) { return x; }); + + //# A :: (a -> b) -> a -> b + //. + //. The A combinator. Takes a function and a value, and returns the result + //. of applying the function to the value. Equivalent to Haskell's `($)` + //. function. + //. + //. ```javascript + //. > S.A(S.inc, 42) + //. 43 + //. + //. > R.map(S.A(R.__, 100), [S.inc, Math.sqrt]) + //. [101, 10] + //. ``` + S.A = + def('A', + {}, + [$.Function, a, b], + function(f, x) { return f(x); }); + + //# T :: a -> (a -> b) -> b + //. + //. The T ([thrush][]) combinator. Takes a value and a function, and returns + //. the result of applying the function to the value. Equivalent to Haskell's + //. `(&)` function. + //. + //. ```javascript + //. > S.T(42, S.inc) + //. 43 + //. + //. > R.map(S.T(100), [S.inc, Math.sqrt]) + //. [101, 10] + //. ``` + S.T = + def('T', + {}, + [a, $.Function, b], + function(x, f) { return f(x); }); + + //# C :: (a -> b -> c) -> b -> a -> c + //. + //. The C combinator. Takes a curried binary function and two values, and + //. returns the result of applying the function to the values in reverse. + //. Equivalent to Haskell's `flip` function. + //. + //. This function is very similar to [`flip`](#flip), except that its first + //. argument must be curried. This allows it to work with manually curried + //. functions. + //. + //. ```javascript + //. > S.C(S.concat, 'foo', 'bar') + //. 'barfoo' + //. + //. > R.filter(S.C(R.gt, 0), [-1, -2, 3, -4, 4, 2]) + //. [3, 4, 2] + //. ``` + S.C = + def('C', + {}, + [$.Function, b, a, c], + function(f, x, y) { return f(y)(x); }); + + //# B :: (b -> c) -> (a -> b) -> a -> c + //. + //. The B combinator. Takes two functions and a value, and returns the + //. result of applying the first function to the result of applying the + //. second to the value. Equivalent to [`compose`](#compose) and Haskell's + //. `(.)` function. + //. + //. ```javascript + //. > S.B(Math.sqrt, S.inc, 99) + //. 10 + //. ``` + S.B = + def('B', + {}, + [$.Function, $.Function, a, c], + compose3); + + //# S :: (a -> b -> c) -> (a -> b) -> a -> c + //. + //. The S combinator. Takes a curried binary function, a unary function, + //. and a value, and returns the result of applying the binary function to: + //. + //. - the value; and + //. - the result of applying the unary function to the value. + //. + //. ```javascript + //. > S.S(S.add, Math.sqrt, 100) + //. 110 + //. ``` + S.S = + def('S', + {}, + [$.Function, $.Function, a, c], + function(f, g, x) { return f(x)(g(x)); }); + + //. ### Function + + //# flip :: ((a, b) -> c) -> b -> a -> c + //. + //. Takes a binary function and two values and returns the result of + //. applying the function - with its argument order reversed - to the + //. values. `flip` may also be applied to a Ramda-style curried + //. function with arity greater than two. + //. + //. See also [`C`](#C). + //. + //. ```javascript + //. > R.map(S.flip(Math.pow)(2), [1, 2, 3, 4, 5]) + //. [1, 4, 9, 16, 25] + //. ``` + S.flip = + def('flip', + {}, + [$.Function, b, a, c], + function(f, x, y) { return f(y, x); }); + + //# lift :: Functor f => (a -> b) -> f a -> f b + //. + //. Promotes a unary function to a function which operates on a [Functor][]. + //. + //. ```javascript + //. > S.lift(S.inc, S.Just(2)) + //. Just(3) + //. + //. > S.lift(S.inc, S.Nothing()) + //. Nothing() + //. ``` + S.lift = + def('lift', + {a: [Functor], b: [Functor]}, + [$.Function, a, b], + R.map); + + //# lift2 :: Apply f => (a -> b -> c) -> f a -> f b -> f c + //. + //. Promotes a binary function to a function which operates on two + //. [Apply][]s. + //. + //. ```javascript + //. > S.lift2(S.add, S.Just(2), S.Just(3)) + //. Just(5) + //. + //. > S.lift2(S.add, S.Just(2), S.Nothing()) + //. Nothing() + //. + //. > S.lift2(S.and, S.Just(true), S.Just(true)) + //. Just(true) + //. + //. > S.lift2(S.and, S.Just(true), S.Just(false)) + //. Just(false) + //. ``` + S.lift2 = + def('lift2', + {a: [Apply], b: [Apply], c: [Apply]}, + [$.Function, a, b, c], + function(f, x, y) { return R.ap(R.map(f, x), y); }); + + //# lift3 :: Apply f => (a -> b -> c -> d) -> f a -> f b -> f c -> f d + //. + //. Promotes a ternary function to a function which operates on three + //. [Apply][]s. + //. + //. ```javascript + //. > S.lift3(S.reduce, S.Just(S.add), S.Just(0), S.Just([1, 2, 3])) + //. Just(6) + //. + //. > S.lift3(S.reduce, S.Just(S.add), S.Just(0), S.Nothing()) + //. Nothing() + //. ``` + S.lift3 = + def('lift3', + {a: [Apply], b: [Apply], c: [Apply], d: [Apply]}, + [$.Function, a, b, c, d], + function(f, x, y, z) { return R.ap(R.ap(R.map(f, x), y), z); }); + + //. ### Composition + + //# compose :: (b -> c) -> (a -> b) -> a -> c + //. + //. Takes two functions assumed to be unary and a value of any type, + //. and returns the result of applying the first function to the result + //. of applying the second function to the given value. + //. + //. In general terms, `compose` performs right-to-left composition of two + //. unary functions. + //. + //. See also [`B`](#B) and [`pipe`](#pipe). + //. + //. ```javascript + //. > S.compose(Math.sqrt, S.inc)(99) + //. 10 + //. ``` + var compose = S.compose = + def('compose', + {}, + [$.Function, $.Function, a, c], + compose3); + + //# pipe :: [(a -> b), (b -> c), ..., (m -> n)] -> a -> n + //. + //. Takes an array of functions assumed to be unary and a value of any type, + //. and returns the result of applying the sequence of transformations to + //. the initial value. + //. + //. In general terms, `pipe` performs left-to-right composition of an array + //. of functions. `pipe([f, g, h], x)` is equivalent to `h(g(f(x)))`. + //. + //. See also [`meld`](#meld). + //. + //. ```javascript + //. > S.pipe([S.inc, Math.sqrt, S.dec])(99) + //. 9 + //. ``` + S.pipe = + def('pipe', + {}, + [$.Array($.Function), a, b], + function(fs, x) { return R.reduceRight(compose2, I, fs)(x); }); + + //# meld :: [** -> *] -> (* -> * -> ... -> *) + //. + //. Takes an array of non-nullary functions and returns a curried function + //. whose arity is one greater than the sum of the arities of the given + //. functions less the number of functions. + //. + //. The behaviour of `meld` is best conveyed diagrammatically. The following + //. diagram depicts the "melding" of binary functions `f` and `g`: + //. + //. +-------+ + //. --- a --->| | + //. | f | +-------+ + //. --- b --->| |--- f(a, b) --->| | + //. +-------+ | g | + //. --- c ---------------------------->| |--- g(f(a, b), c) ---> + //. +-------+ + //. + //. See also [`pipe`](#pipe). + //. + //. ```javascript + //. > S.meld([Math.pow, S.sub])(3, 4, 5) + //. 76 + //. + //. > S.meld([Math.pow, S.sub])(3)(4)(5) + //. 76 + //. ``` + S.meld = + def('meld', + {}, + [$.Array($.Function), $.Function], + function(fs) { + var n = 1 + sum(R.map(R.length, fs)) - fs.length; + return R.curryN(n, function() { + var args = Array.prototype.slice.call(arguments); + for (var idx = 0; idx < fs.length; idx += 1) { + args.unshift(fs[idx].apply(this, args.splice(0, fs[idx].length))); + } + return args[0]; + }); + }); + + //. ### Maybe type + //. + //. The Maybe type represents optional values: a value of type `Maybe a` is + //. either a Just whose value is of type `a` or a Nothing (with no value). + //. + //. The Maybe type satisfies the [Monoid][], [Monad][], [Traversable][], + //. and [Extend][] specifications. + + //# MaybeType :: Type -> Type + //. + //. A [`UnaryType`][UnaryType] for use with [sanctuary-def][]. + + //# Maybe :: TypeRep Maybe + //. + //. The [type representative](#type-representatives) for the Maybe type. + var Maybe = S.Maybe = function Maybe() { + if (arguments[0] !== sentinel) { + throw new Error('Cannot instantiate Maybe'); + } + }; + + //# Maybe.empty :: -> Maybe a + //. + //. Returns a Nothing. + //. + //. ```javascript + //. > S.Maybe.empty() + //. Nothing() + //. ``` + Maybe.empty = + def('Maybe.empty', + {}, + [$Maybe(a)], + function() { return Nothing(); }); + + //# Maybe.of :: a -> Maybe a + //. + //. Takes a value of any type and returns a Just with the given value. + //. + //. ```javascript + //. > S.Maybe.of(42) + //. Just(42) + //. ``` + Maybe.of = + def('Maybe.of', + {}, + [a, $Maybe(a)], + function(x) { return Just(x); }); + + //# Maybe#@@type :: String + //. + //. Maybe type identifier, `'sanctuary/Maybe'`. + Maybe.prototype['@@type'] = 'sanctuary/Maybe'; + + //# Maybe#isNothing :: Boolean + //. + //. `true` if `this` is a Nothing; `false` if `this` is a Just. + //. + //. ```javascript + //. > S.Nothing().isNothing + //. true + //. + //. > S.Just(42).isNothing + //. false + //. ``` + + //# Maybe#isJust :: Boolean + //. + //. `true` if `this` is a Just; `false` if `this` is a Nothing. + //. + //. ```javascript + //. > S.Just(42).isJust + //. true + //. + //. > S.Nothing().isJust + //. false + //. ``` + + //# Maybe#ap :: Maybe (a -> b) ~> Maybe a -> Maybe b + //. + //. Takes a value of type `Maybe a` and returns a Nothing unless `this` + //. is a Just *and* the argument is a Just, in which case it returns a + //. Just whose value is the result of of applying this Just's value to + //. the given Just's value. + //. + //. ```javascript + //. > S.Nothing().ap(S.Just(42)) + //. Nothing() + //. + //. > S.Just(S.inc).ap(S.Nothing()) + //. Nothing() + //. + //. > S.Just(S.inc).ap(S.Just(42)) + //. Just(43) + //. ``` + Maybe.prototype.ap = + method('Maybe#ap', + {}, + [$Maybe($.Function), $Maybe(a), $Maybe(b)], + function(mf, mx) { return mf.isJust ? mx.map(mf.value) : mf; }); + + //# Maybe#chain :: Maybe a ~> (a -> Maybe b) -> Maybe b + //. + //. Takes a function and returns `this` if `this` is a Nothing; otherwise + //. it returns the result of applying the function to this Just's value. + //. + //. ```javascript + //. > S.Nothing().chain(S.parseFloat) + //. Nothing() + //. + //. > S.Just('xxx').chain(S.parseFloat) + //. Nothing() + //. + //. > S.Just('12.34').chain(S.parseFloat) + //. Just(12.34) + //. ``` + Maybe.prototype.chain = + method('Maybe#chain', + {}, + [$Maybe(a), $.Function, $Maybe(b)], + function(maybe, f) { return maybe.isJust ? f(maybe.value) : maybe; }); + + //# Maybe#concat :: Semigroup a => Maybe a ~> Maybe a -> Maybe a + //. + //. Returns the result of concatenating two Maybe values of the same type. + //. `a` must have a [Semigroup][] (indicated by the presence of a `concat` + //. method). + //. + //. If `this` is a Nothing and the argument is a Nothing, this method returns + //. a Nothing. + //. + //. If `this` is a Just and the argument is a Just, this method returns a + //. Just whose value is the result of concatenating this Just's value and + //. the given Just's value. + //. + //. Otherwise, this method returns the Just. + //. + //. ```javascript + //. > S.Nothing().concat(S.Nothing()) + //. Nothing() + //. + //. > S.Just([1, 2, 3]).concat(S.Just([4, 5, 6])) + //. Just([1, 2, 3, 4, 5, 6]) + //. + //. > S.Nothing().concat(S.Just([1, 2, 3])) + //. Just([1, 2, 3]) + //. + //. > S.Just([1, 2, 3]).concat(S.Nothing()) + //. Just([1, 2, 3]) + //. ``` + Maybe.prototype.concat = + method('Maybe#concat', + {a: [Semigroup]}, + [$Maybe(a), $Maybe(a), $Maybe(a)], + function(mx, my) { + return mx.isNothing ? my : + my.isNothing ? mx : Just(mx.value.concat(my.value)); + }); + + //# Maybe#empty :: Maybe a ~> Maybe a + //. + //. Returns a Nothing. + //. + //. ```javascript + //. > S.Just(42).empty() + //. Nothing() + //. ``` + Maybe.prototype.empty = + def('Maybe#empty', + {}, + [$Maybe(a)], + Maybe.empty); + + //# Maybe#equals :: Maybe a ~> b -> Boolean + //. + //. Takes a value of any type and returns `true` if: + //. + //. - it is a Nothing and `this` is a Nothing; or + //. + //. - it is a Just and `this` is a Just, and their values are equal + //. according to [`R.equals`][R.equals]. + //. + //. ```javascript + //. > S.Nothing().equals(S.Nothing()) + //. true + //. + //. > S.Nothing().equals(null) + //. false + //. + //. > S.Just([1, 2, 3]).equals(S.Just([1, 2, 3])) + //. true + //. + //. > S.Just([1, 2, 3]).equals(S.Just([3, 2, 1])) + //. false + //. + //. > S.Just([1, 2, 3]).equals(S.Nothing()) + //. false + //. ``` + Maybe.prototype.equals = + method('Maybe#equals', + {}, + [$Maybe(a), b, $.Boolean], + function(maybe, x) { + return _type(x) === 'sanctuary/Maybe' && + (maybe.isNothing && x.isNothing || + maybe.isJust && x.isJust && R.eqProps('value', maybe, x)); + }); + + //# Maybe#extend :: Maybe a ~> (Maybe a -> a) -> Maybe a + //. + //. Takes a function and returns `this` if `this` is a Nothing; otherwise + //. it returns a Just whose value is the result of applying the function to + //. `this`. + //. + //. ```javascript + //. > S.Nothing().extend(x => x.value + 1) + //. Nothing() + //. + //. > S.Just(42).extend(x => x.value + 1) + //. Just(43) + //. ``` + Maybe.prototype.extend = + method('Maybe#extend', + {}, + [$Maybe(a), $.Function, $Maybe(a)], + function(maybe, f) { return maybe.isJust ? Just(f(maybe)) : maybe; }); + + //# Maybe#filter :: Maybe a ~> (a -> Boolean) -> Maybe a + //. + //. Takes a predicate and returns `this` if `this` is a Just whose value + //. satisfies the predicate; Nothing otherwise. + //. + //. ```javascript + //. > S.Just(42).filter(n => n % 2 === 0) + //. Just(42) + //. + //. > S.Just(43).filter(n => n % 2 === 0) + //. Nothing() + //. ``` + Maybe.prototype.filter = + method('Maybe#filter', + {}, + [$Maybe(a), $.Function, $Maybe(a)], + function(maybe, pred) { return filter(pred, maybe); }); + + //# Maybe#map :: Maybe a ~> (a -> b) -> Maybe b + //. + //. Takes a function and returns `this` if `this` is a Nothing; otherwise + //. it returns a Just whose value is the result of applying the function to + //. this Just's value. + //. + //. ```javascript + //. > S.Nothing().map(S.inc) + //. Nothing() + //. + //. > S.Just([1, 2, 3]).map(S.sum) + //. Just(6) + //. ``` + Maybe.prototype.map = + method('Maybe#map', + {}, + [$Maybe(a), $.Function, $Maybe(b)], + function(maybe, f) { + return maybe.isJust ? Just(f(maybe.value)) : maybe; + }); + + //# Maybe#of :: Maybe a ~> b -> Maybe b + //. + //. Takes a value of any type and returns a Just with the given value. + //. + //. ```javascript + //. > S.Nothing().of(42) + //. Just(42) + //. ``` + Maybe.prototype.of = + def('Maybe#of', + {}, + [b, $Maybe(b)], + Maybe.of); + + //# Maybe#reduce :: Maybe a ~> ((b, a) -> b) -> b -> b + //. + //. Takes a function and an initial value of any type, and returns: + //. + //. - the initial value if `this` is a Nothing; otherwise + //. + //. - the result of applying the function to the initial value and this + //. Just's value. + //. + //. ```javascript + //. > S.Nothing().reduce(S.add, 10) + //. 10 + //. + //. > S.Just(5).reduce(S.add, 10) + //. 15 + //. ``` + Maybe.prototype.reduce = + method('Maybe#reduce', + {}, + [$Maybe(a), $.Function, b, b], + function(maybe, f, x) { + return maybe.isJust ? f(x, maybe.value) : x; + }); + + //# Maybe#sequence :: Applicative f => Maybe (f a) ~> (a -> f a) -> f (Maybe a) + //. + //. Evaluates an applicative action contained within the Maybe, resulting in: + //. + //. - a pure applicative of a Nothing if `this` is a Nothing; otherwise + //. + //. - an applicative of Just the value of the evaluated action. + //. + //. ```javascript + //. > S.Nothing().sequence(S.Either.of) + //. Right(Nothing()) + //. + //. > S.Just(S.Right(42)).sequence(S.Either.of) + //. Right(Just(42)) + //. + //. > S.Just(S.Left('Cannot divide by zero')).sequence(S.Either.of) + //. Left('Cannot divide by zero') + //. ``` + Maybe.prototype.sequence = + method('Maybe#sequence', + {a: [Applicative], b: [Applicative]}, + [$Maybe(a), $.Function, b], + function(maybe, of) { + return maybe.isJust ? R.map(Just, maybe.value) : of(maybe); + }); + + //# Maybe#toBoolean :: Maybe a ~> Boolean + //. + //. Returns `false` if `this` is a Nothing; `true` if `this` is a Just. + //. + //. ```javascript + //. > S.Nothing().toBoolean() + //. false + //. + //. > S.Just(42).toBoolean() + //. true + //. ``` + Maybe.prototype.toBoolean = + method('Maybe#toBoolean', + {}, + [$Maybe(a), $.Boolean], + prop('isJust')); + + //# Maybe#toString :: Maybe a ~> String + //. + //. Returns the string representation of the Maybe. + //. + //. ```javascript + //. > S.Nothing().toString() + //. 'Nothing()' + //. + //. > S.Just([1, 2, 3]).toString() + //. 'Just([1, 2, 3])' + //. ``` + Maybe.prototype.toString = + method('Maybe#toString', + {}, + [$Maybe(a), $.String], + function(maybe) { + return maybe.isJust ? 'Just(' + R.toString(maybe.value) + ')' + : 'Nothing()'; + }); + + //# Maybe#inspect :: Maybe a ~> String + //. + //. Returns the string representation of the Maybe. This method is used by + //. `util.inspect` and the REPL to format a Maybe for display. + //. + //. See also [`Maybe#toString`](#Maybe.prototype.toString). + //. + //. ```javascript + //. > S.Nothing().inspect() + //. 'Nothing()' + //. + //. > S.Just([1, 2, 3]).inspect() + //. 'Just([1, 2, 3])' + //. ``` + Maybe.prototype.inspect = inspect; + + //# Nothing :: -> Maybe a + //. + //. Returns a Nothing. + //. + //. ```javascript + //. > S.Nothing() + //. Nothing() + //. ``` + var Nothing = S.Nothing = function() { + var nothing = new Maybe(sentinel); + nothing.isNothing = true; + nothing.isJust = false; + return nothing; + }; + + //# Just :: a -> Maybe a + //. + //. Takes a value of any type and returns a Just with the given value. + //. + //. ```javascript + //. > S.Just(42) + //. Just(42) + //. ``` + var Just = S.Just = function(value) { + var just = new Maybe(sentinel); + just.isNothing = false; + just.isJust = true; + just.value = value; + return just; + }; + + //# isNothing :: Maybe a -> Boolean + //. + //. Returns `true` if the given Maybe is a Nothing; `false` if it is a Just. + //. + //. ```javascript + //. > S.isNothing(S.Nothing()) + //. true + //. + //. > S.isNothing(S.Just(42)) + //. false + //. ``` + S.isNothing = + def('isNothing', + {}, + [$Maybe(a), $.Boolean], + prop('isNothing')); + + //# isJust :: Maybe a -> Boolean + //. + //. Returns `true` if the given Maybe is a Just; `false` if it is a Nothing. + //. + //. ```javascript + //. > S.isJust(S.Just(42)) + //. true + //. + //. > S.isJust(S.Nothing()) + //. false + //. ``` + S.isJust = + def('isJust', + {}, + [$Maybe(a), $.Boolean], + prop('isJust')); + + //# fromMaybe :: a -> Maybe a -> a + //. + //. Takes a default value and a Maybe, and returns the Maybe's value + //. if the Maybe is a Just; the default value otherwise. + //. + //. See also [`maybeToNullable`](#maybeToNullable). + //. + //. ```javascript + //. > S.fromMaybe(0, S.Just(42)) + //. 42 + //. + //. > S.fromMaybe(0, S.Nothing()) + //. 0 + //. ``` + var fromMaybe = S.fromMaybe = + def('fromMaybe', + {}, + [a, $Maybe(a), a], + function(x, maybe) { return maybe.isJust ? maybe.value : x; }); + + //# maybeToNullable :: Maybe a -> Nullable a + //. + //. Returns the given Maybe's value if the Maybe is a Just; `null` otherwise. + //. [Nullable][] is defined in sanctuary-def. + //. + //. See also [`fromMaybe`](#fromMaybe). + //. + //. ```javascript + //. > S.maybeToNullable(S.Just(42)) + //. 42 + //. + //. > S.maybeToNullable(S.Nothing()) + //. null + //. ``` + S.maybeToNullable = + def('maybeToNullable', + {}, + [$Maybe(a), $.Nullable(a)], + function(maybe) { return maybe.isJust ? maybe.value : null; }); + + //# toMaybe :: a? -> Maybe a + //. + //. Takes a value and returns Nothing if the value is null or undefined; + //. Just the value otherwise. + //. + //. ```javascript + //. > S.toMaybe(null) + //. Nothing() + //. + //. > S.toMaybe(42) + //. Just(42) + //. ``` + var toMaybe = S.toMaybe = + def('toMaybe', + {}, + [a, $Maybe(a)], + function(x) { return x == null ? Nothing() : Just(x); }); + + //# maybe :: b -> (a -> b) -> Maybe a -> b + //. + //. Takes a value of any type, a function, and a Maybe. If the Maybe is + //. a Just, the return value is the result of applying the function to + //. the Just's value. Otherwise, the first argument is returned. + //. + //. ```javascript + //. > S.maybe(0, R.length, S.Just('refuge')) + //. 6 + //. + //. > S.maybe(0, R.length, S.Nothing()) + //. 0 + //. ``` + var maybe = S.maybe = + def('maybe', + {}, + [b, $.Function, $Maybe(a), b], + function(x, f, maybe) { return fromMaybe(x, maybe.map(f)); }); + + //# justs :: Array (Maybe a) -> Array a + //. + //. Takes an array of Maybes and returns an array containing each Just's + //. value. Equivalent to Haskell's `catMaybes` function. + //. + //. See also [`lefts`](#lefts) and [`rights`](#rights). + //. + //. ```javascript + //. > S.justs([S.Just('foo'), S.Nothing(), S.Just('baz')]) + //. ['foo', 'baz'] + //. ``` + var justs = S.justs = + def('justs', + {}, + [$.Array($Maybe(a)), $.Array(a)], + R.chain(maybe([], R.of))); + + //# mapMaybe :: (a -> Maybe b) -> Array a -> Array b + //. + //. Takes a function and an array, applies the function to each element of + //. the array, and returns an array of "successful" results. If the result of + //. applying the function to an element of the array is a Nothing, the result + //. is discarded; if the result is a Just, the Just's value is included in + //. the output array. + //. + //. In general terms, `mapMaybe` filters an array while mapping over it. + //. + //. ```javascript + //. > S.mapMaybe(S.head, [[], [1, 2, 3], [], [4, 5, 6], []]) + //. [1, 4] + //. ``` + S.mapMaybe = + def('mapMaybe', + {}, + [$.Function, $.Array(a), $.Array(b)], + function(f, xs) { return justs(R.map(f, xs)); }); + + //# encase :: (a -> b) -> a -> Maybe b + //. + //. Takes a unary function `f` which may throw and a value `x` of any type, + //. and applies `f` to `x` inside a `try` block. If an exception is caught, + //. the return value is a Nothing; otherwise the return value is Just the + //. result of applying `f` to `x`. + //. + //. See also [`encaseEither`](#encaseEither). + //. + //. ```javascript + //. > S.encase(eval, '1 + 1') + //. Just(2) + //. + //. > S.encase(eval, '1 +') + //. Nothing() + //. ``` + var encase = S.encase = + def('encase', + {}, + [$.Function, a, $Maybe(b)], + function(f, x) { + try { + return Just(f(x)); + } catch (err) { + return Nothing(); + } + }); + + //# encase2 :: (a -> b -> c) -> a -> b -> Maybe c + //. + //. Binary version of [`encase`](#encase). + //. + //. See also [`encase2_`](#encase2_). + var encase2 = S.encase2 = + def('encase2', + {}, + [$.Function, a, b, $Maybe(c)], + function(f, x, y) { + try { + return Just(f(x)(y)); + } catch (err) { + return Nothing(); + } + }); + + //# encase2_ :: ((a, b) -> c) -> a -> b -> Maybe c + //. + //. Version of [`encase2`](#encase2) accepting uncurried functions. + S.encase2_ = + def('encase2_', + {}, + [$.Function, a, b, $Maybe(c)], + function(f_, x, y) { + var f = function(x) { + return function(y) { + return f_(x, y); + }; + }; + return encase2(f, x, y); + }); + + //# encase3 :: (a -> b -> c -> d) -> a -> b -> c -> Maybe d + //. + //. Ternary version of [`encase`](#encase). + //. + //. See also [`encase3_`](#encase3_). + var encase3 = S.encase3 = + def('encase3', + {}, + [$.Function, a, b, c, $Maybe(d)], + function(f, x, y, z) { + try { + return Just(f(x)(y)(z)); + } catch (err) { + return Nothing(); + } + }); + + //# encase3_ :: ((a, b, c) -> d) -> a -> b -> c -> Maybe d + //. + //. Version of [`encase3`](#encase3) accepting uncurried functions. + S.encase3_ = + def('encase3_', + {}, + [$.Function, a, b, c, $Maybe(d)], + function(f_, x, y, z) { + var f = function(x) { + return function(y) { + return function(z) { + return f_(x, y, z); + }; + }; + }; + return encase3(f, x, y, z); + }); + + //# maybeToEither :: a -> Maybe b -> Either a b + //. + //. Converts a Maybe to an Either. A Nothing becomes a Left (containing the + //. first argument); a Just becomes a Right. + //. + //. See also [`eitherToMaybe`](#eitherToMaybe). + //. + //. ```javascript + //. > S.maybeToEither('Expecting an integer', S.parseInt(10, 'xyz')) + //. Left('Expecting an integer') + //. + //. > S.maybeToEither('Expecting an integer', S.parseInt(10, '42')) + //. Right(42) + //. ``` + S.maybeToEither = + def('maybeToEither', + {}, + [a, $Maybe(b), $Either(a, b)], + function(x, maybe) { + return maybe.isNothing ? Left(x) : Right(maybe.value); + }); + + //. ### Either type + //. + //. The Either type represents values with two possibilities: a value of type + //. `Either a b` is either a Left whose value is of type `a` or a Right whose + //. value is of type `b`. + //. + //. The Either type satisfies the [Semigroup][], [Monad][], [Traversable][], + //. and [Extend][] specifications. + + //# EitherType :: Type -> Type -> Type + //. + //. A [`BinaryType`][BinaryType] for use with [sanctuary-def][]. + + //# Either :: TypeRep Either + //. + //. The [type representative](#type-representatives) for the Either type. + var Either = S.Either = function Either() { + if (arguments[0] !== sentinel) { + throw new Error('Cannot instantiate Either'); + } + }; + + //# Either.of :: b -> Either a b + //. + //. Takes a value of any type and returns a Right with the given value. + //. + //. ```javascript + //. > S.Either.of(42) + //. Right(42) + //. ``` + Either.of = + def('Either.of', + {}, + [b, $Either(a, b)], + function(x) { return Right(x); }); + + //# Either#@@type :: String + //. + //. Either type identifier, `'sanctuary/Either'`. + Either.prototype['@@type'] = 'sanctuary/Either'; + + //# Either#isLeft :: Boolean + //. + //. `true` if `this` is a Left; `false` if `this` is a Right. + //. + //. ```javascript + //. > S.Left('Cannot divide by zero').isLeft + //. true + //. + //. > S.Right(42).isLeft + //. false + //. ``` + + //# Either#isRight :: Boolean + //. + //. `true` if `this` is a Right; `false` if `this` is a Left. + //. + //. ```javascript + //. > S.Right(42).isRight + //. true + //. + //. > S.Left('Cannot divide by zero').isRight + //. false + //. ``` + + //# Either#ap :: Either a (b -> c) ~> Either a b -> Either a c + //. + //. Takes a value of type `Either a b` and returns a Left unless `this` + //. is a Right *and* the argument is a Right, in which case it returns + //. a Right whose value is the result of applying this Right's value to + //. the given Right's value. + //. + //. ```javascript + //. > S.Left('Cannot divide by zero').ap(S.Right(42)) + //. Left('Cannot divide by zero') + //. + //. > S.Right(S.inc).ap(S.Left('Cannot divide by zero')) + //. Left('Cannot divide by zero') + //. + //. > S.Right(S.inc).ap(S.Right(42)) + //. Right(43) + //. ``` + Either.prototype.ap = + method('Either#ap', + {}, + [$Either(a, $.Function), $Either(a, b), $Either(a, c)], + function(ef, ex) { return ef.isRight ? ex.map(ef.value) : ef; }); + + //# Either#chain :: Either a b ~> (b -> Either a c) -> Either a c + //. + //. Takes a function and returns `this` if `this` is a Left; otherwise + //. it returns the result of applying the function to this Right's value. + //. + //. ```javascript + //. > global.sqrt = n => + //. . n < 0 ? S.Left('Cannot represent square root of negative number') + //. . : S.Right(Math.sqrt(n)) + //. sqrt + //. + //. > S.Left('Cannot divide by zero').chain(sqrt) + //. Left('Cannot divide by zero') + //. + //. > S.Right(-1).chain(sqrt) + //. Left('Cannot represent square root of negative number') + //. + //. > S.Right(25).chain(sqrt) + //. Right(5) + //. ``` + Either.prototype.chain = + method('Either#chain', + {}, + [$Either(a, b), $.Function, $Either(a, c)], + function(either, f) { + return either.isRight ? f(either.value) : either; + }); + + //# Either#concat :: (Semigroup a, Semigroup b) => Either a b ~> Either a b -> Either a b + //. + //. Returns the result of concatenating two Either values of the same type. + //. `a` must have a [Semigroup][] (indicated by the presence of a `concat` + //. method), as must `b`. + //. + //. If `this` is a Left and the argument is a Left, this method returns a + //. Left whose value is the result of concatenating this Left's value and + //. the given Left's value. + //. + //. If `this` is a Right and the argument is a Right, this method returns a + //. Right whose value is the result of concatenating this Right's value and + //. the given Right's value. + //. + //. Otherwise, this method returns the Right. + //. + //. ```javascript + //. > S.Left('abc').concat(S.Left('def')) + //. Left('abcdef') + //. + //. > S.Right([1, 2, 3]).concat(S.Right([4, 5, 6])) + //. Right([1, 2, 3, 4, 5, 6]) + //. + //. > S.Left('abc').concat(S.Right([1, 2, 3])) + //. Right([1, 2, 3]) + //. + //. > S.Right([1, 2, 3]).concat(S.Left('abc')) + //. Right([1, 2, 3]) + //. ``` + Either.prototype.concat = + method('Either#concat', + {a: [Semigroup], b: [Semigroup]}, + [$Either(a, b), $Either(a, b), $Either(a, b)], + function(ex, ey) { + return ex.isLeft && ey.isLeft ? Left(ex.value.concat(ey.value)) : + ex.isRight && ey.isRight ? Right(ex.value.concat(ey.value)) : + ex.isRight ? ex : ey; + }); + + //# Either#equals :: Either a b ~> c -> Boolean + //. + //. Takes a value of any type and returns `true` if: + //. + //. - it is a Left and `this` is a Left, and their values are equal + //. according to [`R.equals`][R.equals]; or + //. + //. - it is a Right and `this` is a Right, and their values are equal + //. according to [`R.equals`][R.equals]. + //. + //. ```javascript + //. > S.Right([1, 2, 3]).equals(S.Right([1, 2, 3])) + //. true + //. + //. > S.Right([1, 2, 3]).equals(S.Left([1, 2, 3])) + //. false + //. + //. > S.Right(42).equals(42) + //. false + //. ``` + Either.prototype.equals = + method('Either#equals', + {}, + [$Either(a, b), c, $.Boolean], + function(either, x) { + return _type(x) === 'sanctuary/Either' && + either.isLeft === x.isLeft && R.eqProps('value', either, x); + }); + + //# Either#extend :: Either a b ~> (Either a b -> b) -> Either a b + //. + //. Takes a function and returns `this` if `this` is a Left; otherwise it + //. returns a Right whose value is the result of applying the function to + //. `this`. + //. + //. ```javascript + //. > S.Left('Cannot divide by zero').extend(x => x.value + 1) + //. Left('Cannot divide by zero') + //. + //. > S.Right(42).extend(x => x.value + 1) + //. Right(43) + //. ``` + Either.prototype.extend = + method('Either#extend', + {}, + [$Either(a, b), $.Function, $Either(a, b)], + function(either, f) { + return either.isLeft ? either : Right(f(either)); + }); + + //# Either#map :: Either a b ~> (b -> c) -> Either a c + //. + //. Takes a function and returns `this` if `this` is a Left; otherwise it + //. returns a Right whose value is the result of applying the function to + //. this Right's value. + //. + //. ```javascript + //. > S.Left('Cannot divide by zero').map(S.inc) + //. Left('Cannot divide by zero') + //. + //. > S.Right([1, 2, 3]).map(S.sum) + //. Right(6) + //. ``` + Either.prototype.map = + method('Either#map', + {}, + [$Either(a, b), $.Function, $Either(a, c)], + function(either, f) { + return either.isRight ? Right(f(either.value)) : either; + }); + + //# Either#of :: Either a b ~> c -> Either a c + //. + //. Takes a value of any type and returns a Right with the given value. + //. + //. ```javascript + //. > S.Left('Cannot divide by zero').of(42) + //. Right(42) + //. ``` + Either.prototype.of = + def('Either#of', + {}, + [c, $Either(a, c)], + Either.of); + + //# Either#reduce :: Either a b ~> ((c, b) -> c) -> c -> c + //. + //. Takes a function and an initial value of any type, and returns: + //. + //. - the initial value if `this` is a Left; otherwise + //. + //. - the result of applying the function to the initial value and this + //. Right's value. + //. + //. ```javascript + //. > S.Left('Cannot divide by zero').reduce((xs, x) => xs.concat([x]), [42]) + //. [42] + //. + //. > S.Right(5).reduce((xs, x) => xs.concat([x]), [42]) + //. [42, 5] + //. ``` + Either.prototype.reduce = + method('Either#reduce', + {}, + [$Either(a, b), $.Function, c, c], + function(either, f, x) { + return either.isRight ? f(x, either.value) : x; + }); + + //# Either#sequence :: Applicative f => Either a (f b) ~> (b -> f b) -> f (Either a b) + //. + //. Evaluates an applicative action contained within the Either, + //. resulting in: + //. + //. - a pure applicative of a Left if `this` is a Left; otherwise + //. + //. - an applicative of a Right of the evaluated action. + //. + //. ```javascript + //. > S.Left('Cannot divide by zero').sequence(S.Maybe.of) + //. Just(Left('Cannot divide by zero')) + //. + //. > S.Right(S.Just(42)).sequence(S.Maybe.of) + //. Just(Right(42)) + //. + //. > S.Right(S.Nothing()).sequence(S.Maybe.of) + //. Nothing() + //. ``` + Either.prototype.sequence = + method('Either#sequence', + {b: [Applicative], c: [Applicative]}, + [$Either(a, b), $.Function, c], + function(either, of) { + return either.isRight ? R.map(Right, either.value) : of(either); + }); + + //# Either#toBoolean :: Either a b ~> Boolean + //. + //. Returns `false` if `this` is a Left; `true` if `this` is a Right. + //. + //. ```javascript + //. > S.Left(42).toBoolean() + //. false + //. + //. > S.Right(42).toBoolean() + //. true + //. ``` + Either.prototype.toBoolean = + method('Either#toBoolean', + {}, + [$Either(a, b), $.Boolean], + prop('isRight')); + + //# Either#toString :: Either a b ~> String + //. + //. Returns the string representation of the Either. + //. + //. ```javascript + //. > S.Left('Cannot divide by zero').toString() + //. 'Left("Cannot divide by zero")' + //. + //. > S.Right([1, 2, 3]).toString() + //. 'Right([1, 2, 3])' + //. ``` + Either.prototype.toString = + method('Either#toString', + {}, + [$Either(a, b), $.String], + function(either) { + return (either.isLeft ? 'Left' : 'Right') + + '(' + R.toString(either.value) + ')'; + }); + + //# Either#inspect :: Either a b ~> String + //. + //. Returns the string representation of the Either. This method is used by + //. `util.inspect` and the REPL to format a Either for display. + //. + //. See also [`Either#toString`](#Either.prototype.toString). + //. + //. ```javascript + //. > S.Left('Cannot divide by zero').inspect() + //. 'Left("Cannot divide by zero")' + //. + //. > S.Right([1, 2, 3]).inspect() + //. 'Right([1, 2, 3])' + //. ``` + Either.prototype.inspect = inspect; + + //# Left :: a -> Either a b + //. + //. Takes a value of any type and returns a Left with the given value. + //. + //. ```javascript + //. > S.Left('Cannot divide by zero') + //. Left('Cannot divide by zero') + //. ``` + var Left = S.Left = function(value) { + var left = new Either(sentinel); + left.isLeft = true; + left.isRight = false; + left.value = value; + return left; + }; + + //# Right :: b -> Either a b + //. + //. Takes a value of any type and returns a Right with the given value. + //. + //. ```javascript + //. > S.Right(42) + //. Right(42) + //. ``` + var Right = S.Right = function(value) { + var right = new Either(sentinel); + right.isLeft = false; + right.isRight = true; + right.value = value; + return right; + }; + + //# isLeft :: Either a b -> Boolean + //. + //. Returns `true` if the given Either is a Left; `false` if it is a Right. + //. + //. ```javascript + //. > S.isLeft(S.Left('Cannot divide by zero')) + //. true + //. + //. > S.isLeft(S.Right(42)) + //. false + //. ``` + S.isLeft = + def('isLeft', + {}, + [$Either(a, b), $.Boolean], + prop('isLeft')); + + //# isRight :: Either a b -> Boolean + //. + //. Returns `true` if the given Either is a Right; `false` if it is a Left. + //. + //. ```javascript + //. > S.isRight(S.Right(42)) + //. true + //. + //. > S.isRight(S.Left('Cannot divide by zero')) + //. false + //. ``` + S.isRight = + def('isRight', + {}, + [$Either(a, b), $.Boolean], + prop('isRight')); + + //# either :: (a -> c) -> (b -> c) -> Either a b -> c + //. + //. Takes two functions and an Either, and returns the result of + //. applying the first function to the Left's value, if the Either + //. is a Left, or the result of applying the second function to the + //. Right's value, if the Either is a Right. + //. + //. ```javascript + //. > S.either(S.toUpper, R.toString, S.Left('Cannot divide by zero')) + //. 'CANNOT DIVIDE BY ZERO' + //. + //. > S.either(S.toUpper, R.toString, S.Right(42)) + //. '42' + //. ``` + S.either = + def('either', + {}, + [$.Function, $.Function, $Either(a, b), c], + function(l, r, either) { + return either.isLeft ? l(either.value) : r(either.value); + }); + + //# lefts :: Array (Either a b) -> Array a + //. + //. Takes an array of Eithers and returns an array containing each Left's + //. value. + //. + //. See also [`rights`](#rights). + //. + //. ```javascript + //. > S.lefts([S.Right(20), S.Left('foo'), S.Right(10), S.Left('bar')]) + //. ['foo', 'bar'] + //. ``` + S.lefts = + def('lefts', + {}, + [$.Array($Either(a, b)), $.Array(a)], + R.chain(function(either) { + return either.isLeft ? [either.value] : []; + })); + + //# rights :: Array (Either a b) -> Array b + //. + //. Takes an array of Eithers and returns an array containing each Right's + //. value. + //. + //. See also [`lefts`](#lefts). + //. + //. ```javascript + //. > S.rights([S.Right(20), S.Left('foo'), S.Right(10), S.Left('bar')]) + //. [20, 10] + //. ``` + S.rights = + def('rights', + {}, + [$.Array($Either(a, b)), $.Array(b)], + R.chain(function(either) { + return either.isRight ? [either.value] : []; + })); + + //# encaseEither :: (Error -> l) -> (a -> r) -> a -> Either l r + //. + //. Takes two unary functions, `f` and `g`, the second of which may throw, + //. and a value `x` of any type. Applies `g` to `x` inside a `try` block. + //. If an exception is caught, the return value is a Left containing the + //. result of applying `f` to the caught Error object; otherwise the return + //. value is a Right containing the result of applying `g` to `x`. + //. + //. See also [`encase`](#encase). + //. + //. ```javascript + //. > S.encaseEither(S.I, JSON.parse, '["foo","bar","baz"]') + //. Right(['foo', 'bar', 'baz']) + //. + //. > S.encaseEither(S.I, JSON.parse, '[') + //. Left(new SyntaxError('Unexpected end of input')) + //. + //. > S.encaseEither(S.prop('message'), JSON.parse, '[') + //. Left('Unexpected end of input') + //. ``` + S.encaseEither = + def('encaseEither', + {}, + [$.Function, $.Function, a, $Either(l, r)], + function(f, g, x) { + try { + return Right(g(x)); + } catch (err) { + return Left(f(err)); + } + }); + + //# encaseEither2 :: (Error -> l) -> (a -> b -> r) -> a -> b -> Either l r + //. + //. Binary version of [`encaseEither`](#encaseEither). + //. + //. See also [`encaseEither2_`](#encaseEither2_). + var encaseEither2 = S.encaseEither2 = + def('encaseEither2', + {}, + [$.Function, $.Function, a, b, $Either(l, r)], + function(f, g, x, y) { + try { + return Right(g(x)(y)); + } catch (err) { + return Left(f(err)); + } + }); + + //# encaseEither2_ :: (Error -> l) -> ((a, b) -> r) -> a -> b -> Either l r + //. + //. Version of [`encaseEither2`](#encaseEither2) accepting uncurried + //. functions. + S.encaseEither2_ = + def('encaseEither2_', + {}, + [$.Function, $.Function, a, b, $Either(l, r)], + function(f, g_, x, y) { + var g = function(x) { + return function(y) { + return g_(x, y); + }; + }; + return encaseEither2(f, g, x, y); + }); + + //# encaseEither3 :: (Error -> l) -> (a -> b -> c -> r) -> a -> b -> c -> Either l r + //. + //. Ternary version of [`encaseEither`](#encaseEither). + //. + //. See also [`encaseEither3_`](#encaseEither3_). + var encaseEither3 = S.encaseEither3 = + def('encaseEither3', + {}, + [$.Function, $.Function, a, b, c, $Either(l, r)], + function(f, g, x, y, z) { + try { + return Right(g(x)(y)(z)); + } catch (err) { + return Left(f(err)); + } + }); + + //# encaseEither3_ :: (Error -> l) -> ((a, b, c) -> r) -> a -> b -> c -> Either l r + //. + //. Version of [`encaseEither3`](#encaseEither3) accepting uncurried + //. functions. + S.encaseEither3_ = + def('encaseEither3', + {}, + [$.Function, $.Function, a, b, c, $Either(l, r)], + function(f, g_, x, y, z) { + var g = function(x) { + return function(y) { + return function(z) { + return g_(x, y, z); + }; + }; + }; + return encaseEither3(f, g, x, y, z); + }); + + //# eitherToMaybe :: Either a b -> Maybe b + //. + //. Converts an Either to a Maybe. A Left becomes a Nothing; a Right becomes + //. a Just. + //. + //. See also [`maybeToEither`](#maybeToEither). + //. + //. ```javascript + //. > S.eitherToMaybe(S.Left('Cannot divide by zero')) + //. Nothing() + //. + //. > S.eitherToMaybe(S.Right(42)) + //. Just(42) + //. ``` + S.eitherToMaybe = + def('eitherToMaybe', + {}, + [$Either(a, b), $Maybe(b)], + function(either) { + return either.isLeft ? Nothing() : Just(either.value); + }); + + //. ### Alternative + + // Alternative :: TypeClass + var Alternative = $.TypeClass( + 'Alternative', + function(x) { + return R.contains(R.type(x), ['Array', 'Boolean']) || + hasMethod('toBoolean')(x); + } + ); + + // toBoolean :: Alternative a => a -> Boolean + var toBoolean = function(x) { + switch (R.type(x)) { + case 'Array': return x.length > 0; + case 'Boolean': return x.valueOf(); + default: return x.toBoolean(); + } + }; + + // empty :: Monoid a => a -> a + var empty = function(x) { + switch (R.type(x)) { + case 'Array': return []; + case 'Boolean': return false; + default: return x.empty(); + } + }; + + //# and :: Alternative a => a -> a -> a + //. + //. Takes two values of the same type and returns the second value + //. if the first is "true"; the first value otherwise. An array is + //. considered "true" if its length is greater than zero. The Boolean + //. value `true` is also considered "true". Other types must provide + //. a `toBoolean` method. + //. + //. ```javascript + //. > S.and(S.Just(1), S.Just(2)) + //. Just(2) + //. + //. > S.and(S.Nothing(), S.Just(3)) + //. Nothing() + //. ``` + S.and = + def('and', + {a: [Alternative]}, + [a, a, a], + function(x, y) { return toBoolean(x) ? y : x; }); + + //# or :: Alternative a => a -> a -> a + //. + //. Takes two values of the same type and returns the first value if it + //. is "true"; the second value otherwise. An array is considered "true" + //. if its length is greater than zero. The Boolean value `true` is also + //. considered "true". Other types must provide a `toBoolean` method. + //. + //. ```javascript + //. > S.or(S.Just(1), S.Just(2)) + //. Just(1) + //. + //. > S.or(S.Nothing(), S.Just(3)) + //. Just(3) + //. ``` + var or = S.or = + def('or', + {a: [Alternative]}, + [a, a, a], + function(x, y) { return toBoolean(x) ? x : y; }); + + //# xor :: (Alternative a, Monoid a) => a -> a -> a + //. + //. Takes two values of the same type and returns the "true" value + //. if one value is "true" and the other is "false"; otherwise it + //. returns the type's "false" value. An array is considered "true" + //. if its length is greater than zero. The Boolean value `true` is + //. also considered "true". Other types must provide `toBoolean` and + //. `empty` methods. + //. + //. ```javascript + //. > S.xor(S.Nothing(), S.Just(1)) + //. Just(1) + //. + //. > S.xor(S.Just(2), S.Just(3)) + //. Nothing() + //. ``` + S.xor = + def('xor', + {a: [Alternative, Monoid]}, + [a, a, a], + function(x, y) { + return toBoolean(x) === toBoolean(y) ? empty(x) : or(x, y); + }); + + //. ### Logic + + //# not :: Boolean -> Boolean + //. + //. Takes a Boolean and returns the negation of that value + //. (`false` for `true`; `true` for `false`). + //. + //. ```javascript + //. > S.not(true) + //. false + //. + //. > S.not(false) + //. true + //. ``` + S.not = + def('not', + {}, + [$.Boolean, $.Boolean], + function(x) { return !x.valueOf(); }); + + //# ifElse :: (a -> Boolean) -> (a -> b) -> (a -> b) -> a -> b + //. + //. Takes a unary predicate, a unary "if" function, a unary "else" + //. function, and a value of any type, and returns the result of + //. applying the "if" function to the value if the value satisfies + //. the predicate; the result of applying the "else" function to the + //. value otherwise. + //. + //. ```javascript + //. > S.ifElse(x => x < 0, Math.abs, Math.sqrt, -1) + //. 1 + //. + //. > S.ifElse(x => x < 0, Math.abs, Math.sqrt, 16) + //. 4 + //. ``` + S.ifElse = + def('ifElse', + {}, + [$.Function, $.Function, $.Function, a, b], + function(pred, f, g, x) { return pred(x) ? f(x) : g(x); }); + + //# allPass :: Array (a -> Boolean) -> a -> Boolean + //. + //. Takes an array of unary predicates and a value of any type + //. and returns `true` if all the predicates pass; `false` otherwise. + //. None of the subsequent predicates will be evaluated after the + //. first failed predicate. + //. + //. ```javascript + //. > S.allPass([S.test(/q/), S.test(/u/), S.test(/i/)], 'quiessence') + //. true + //. + //. > S.allPass([S.test(/q/), S.test(/u/), S.test(/i/)], 'fissiparous') + //. false + //. ``` + S.allPass = + def('allPass', + {}, + [$.Array($.Function), a, $.Boolean], + function(preds, x) { + for (var idx = 0; idx < preds.length; idx += 1) { + if (!preds[idx](x)) return false; + } + return true; + }); + + //# anyPass :: Array (a -> Boolean) -> a -> Boolean + //. + //. Takes an array of unary predicates and a value of any type + //. and returns `true` if any of the predicates pass; `false` otherwise. + //. None of the subsequent predicates will be evaluated after the + //. first passed predicate. + //. + //. ```javascript + //. > S.anyPass([S.test(/q/), S.test(/u/), S.test(/i/)], 'incandescent') + //. true + //. + //. > S.anyPass([S.test(/q/), S.test(/u/), S.test(/i/)], 'empathy') + //. false + //. ``` + S.anyPass = + def('anyPass', + {}, + [$.Array($.Function), a, $.Boolean], + function(preds, x) { + for (var idx = 0; idx < preds.length; idx += 1) { + if (preds[idx](x)) return true; + } + return false; + }); + + //. ### List + //. + //. The List type represents non-Function values with integer `length` + //. properties greater than or equal to zero, such as `[1, 2, 3]` and + //. `'foo'`. + //. + //. `[a]` is the notation used to represent a List of values of type `a`. + + //# concat :: Semigroup a => a -> a -> a + //. + //. Concatenates two (homogeneous) arrays, two strings, or two values of any + //. other type which satisfies the [Semigroup][] specification. + //. + //. ```javascript + //. > S.concat([1, 2, 3], [4, 5, 6]) + //. [1, 2, 3, 4, 5, 6] + //. + //. > S.concat('foo', 'bar') + //. 'foobar' + //. + //. > S.concat(S.Just('foo'), S.Just('bar')) + //. S.Just('foobar') + //. ``` + var concat = S.concat = + def('concat', + {a: [Semigroup]}, + [a, a, a], + function(x, y) { return x.concat(y); }); + + //# slice :: Integer -> Integer -> [a] -> Maybe [a] + //. + //. Returns Just a list containing the elements from the supplied list + //. from a beginning index (inclusive) to an end index (exclusive). + //. Returns Nothing unless the start interval is less than or equal to + //. the end interval, and the list contains both (half-open) intervals. + //. Accepts negative indices, which indicate an offset from the end of + //. the list. + //. + //. Dispatches to its third argument's `slice` method if present. As a + //. result, one may replace `[a]` with `String` in the type signature. + //. + //. ```javascript + //. > S.slice(1, 3, ['a', 'b', 'c', 'd', 'e']) + //. Just(['b', 'c']) + //. + //. > S.slice(-2, -0, ['a', 'b', 'c', 'd', 'e']) + //. Just(['d', 'e']) + //. + //. > S.slice(2, -0, ['a', 'b', 'c', 'd', 'e']) + //. Just(['c', 'd', 'e']) + //. + //. > S.slice(1, 6, ['a', 'b', 'c', 'd', 'e']) + //. Nothing() + //. + //. > S.slice(2, 6, 'banana') + //. Just('nana') + //. ``` + var slice = S.slice = + def('slice', + {}, + [$.Integer, $.Integer, List(a), $Maybe(List(a))], + function(start, end, xs) { + var len = xs.length; + var A = negativeZero(start) ? len : start < 0 ? start + len : start; + var Z = negativeZero(end) ? len : end < 0 ? end + len : end; + + return Math.abs(start) <= len && Math.abs(end) <= len && A <= Z ? + Just(R.slice(A, Z, xs)) : + Nothing(); + }); + + //# at :: Integer -> [a] -> Maybe a + //. + //. Takes an index and a list and returns Just the element of the list at + //. the index if the index is within the list's bounds; Nothing otherwise. + //. A negative index represents an offset from the length of the list. + //. + //. ```javascript + //. > S.at(2, ['a', 'b', 'c', 'd', 'e']) + //. Just('c') + //. + //. > S.at(5, ['a', 'b', 'c', 'd', 'e']) + //. Nothing() + //. + //. > S.at(-2, ['a', 'b', 'c', 'd', 'e']) + //. Just('d') + //. ``` + var at = S.at = + def('at', + {}, + [$.Integer, List(a), $Maybe(a)], + function(n, xs) { + return R.map(R.head, slice(n, n === -1 ? -0 : n + 1, xs)); + }); + + //# head :: [a] -> Maybe a + //. + //. Takes a list and returns Just the first element of the list if the + //. list contains at least one element; Nothing if the list is empty. + //. + //. ```javascript + //. > S.head([1, 2, 3]) + //. Just(1) + //. + //. > S.head([]) + //. Nothing() + //. ``` + S.head = + def('head', + {}, + [List(a), $Maybe(a)], + at(0)); + + //# last :: [a] -> Maybe a + //. + //. Takes a list and returns Just the last element of the list if the + //. list contains at least one element; Nothing if the list is empty. + //. + //. ```javascript + //. > S.last([1, 2, 3]) + //. Just(3) + //. + //. > S.last([]) + //. Nothing() + //. ``` + S.last = + def('last', + {}, + [List(a), $Maybe(a)], + at(-1)); + + //# tail :: [a] -> Maybe [a] + //. + //. Takes a list and returns Just a list containing all but the first + //. of the list's elements if the list contains at least one element; + //. Nothing if the list is empty. + //. + //. ```javascript + //. > S.tail([1, 2, 3]) + //. Just([2, 3]) + //. + //. > S.tail([]) + //. Nothing() + //. ``` + S.tail = + def('tail', + {}, + [List(a), $Maybe(List(a))], + slice(1, -0)); + + //# init :: [a] -> Maybe [a] + //. + //. Takes a list and returns Just a list containing all but the last + //. of the list's elements if the list contains at least one element; + //. Nothing if the list is empty. + //. + //. ```javascript + //. > S.init([1, 2, 3]) + //. Just([1, 2]) + //. + //. > S.init([]) + //. Nothing() + //. ``` + S.init = + def('init', + {}, + [List(a), $Maybe(List(a))], + slice(0, -1)); + + //# take :: Integer -> [a] -> Maybe [a] + //. + //. Returns Just the first N elements of the given collection if N is + //. greater than or equal to zero and less than or equal to the length + //. of the collection; Nothing otherwise. Supports Array, String, and + //. any other collection type which provides a `slice` method. + //. + //. ```javascript + //. > S.take(2, ['a', 'b', 'c', 'd', 'e']) + //. Just(['a', 'b']) + //. + //. > S.take(4, 'abcdefg') + //. Just('abcd') + //. + //. > S.take(4, ['a', 'b', 'c']) + //. Nothing() + //. ``` + S.take = + def('take', + {}, + [$.Integer, List(a), $Maybe(List(a))], + function(n, xs) { + return n < 0 || negativeZero(n) ? Nothing() : slice(0, n, xs); + }); + + //# takeLast :: Integer -> [a] -> Maybe [a] + //. + //. Returns Just the last N elements of the given collection if N is + //. greater than or equal to zero and less than or equal to the length + //. of the collection; Nothing otherwise. Supports Array, String, and + //. any other collection type which provides a `slice` method. + //. + //. ```javascript + //. > S.takeLast(2, ['a', 'b', 'c', 'd', 'e']) + //. Just(['d', 'e']) + //. + //. > S.takeLast(4, 'abcdefg') + //. Just('defg') + //. + //. > S.takeLast(4, ['a', 'b', 'c']) + //. Nothing() + //. ``` + S.takeLast = + def('takeLast', + {}, + [$.Integer, List(a), $Maybe(List(a))], + function(n, xs) { + return n < 0 || negativeZero(n) ? Nothing() : slice(-n, -0, xs); + }); + + //# drop :: Integer -> [a] -> Maybe [a] + //. + //. Returns Just all but the first N elements of the given collection + //. if N is greater than or equal to zero and less than or equal to the + //. length of the collection; Nothing otherwise. Supports Array, String, + //. and any other collection type which provides a `slice` method. + //. + //. ```javascript + //. > S.drop(2, ['a', 'b', 'c', 'd', 'e']) + //. Just(['c', 'd', 'e']) + //. + //. > S.drop(4, 'abcdefg') + //. Just('efg') + //. + //. > S.drop(4, 'abc') + //. Nothing() + //. ``` + S.drop = + def('drop', + {}, + [$.Integer, List(a), $Maybe(List(a))], + function(n, xs) { + return n < 0 || negativeZero(n) ? Nothing() : slice(n, -0, xs); + }); + + //# dropLast :: Integer -> [a] -> Maybe [a] + //. + //. Returns Just all but the last N elements of the given collection + //. if N is greater than or equal to zero and less than or equal to the + //. length of the collection; Nothing otherwise. Supports Array, String, + //. and any other collection type which provides a `slice` method. + //. + //. ```javascript + //. > S.dropLast(2, ['a', 'b', 'c', 'd', 'e']) + //. Just(['a', 'b', 'c']) + //. + //. > S.dropLast(4, 'abcdefg') + //. Just('abc') + //. + //. > S.dropLast(4, 'abc') + //. Nothing() + //. ``` + S.dropLast = + def('dropLast', + {}, + [$.Integer, List(a), $Maybe(List(a))], + function(n, xs) { + return n < 0 || negativeZero(n) ? Nothing() : slice(0, -n, xs); + }); + + //# reverse :: [a] -> [a] + //. + //. Returns the elements of the given list in reverse order. + //. + //. ```javascript + //. > S.reverse([1, 2, 3]) + //. [3, 2, 1] + //. + //. > S.reverse('abc') + //. 'cba' + //. ``` + S.reverse = + def('reverse', + {}, + [List(a), List(a)], + function reverse(xs) { + if (_type(xs) === 'String') return reverse(xs.split('')).join(''); + var result = []; + for (var idx = xs.length - 1; idx >= 0; idx -= 1) result.push(xs[idx]); + return result; + }); + + // ArrayLike :: TypeClass + var ArrayLike = $.TypeClass( + 'ArrayLike', + function(x) { + return x != null && + typeof x !== 'function' && + $.Integer._test(x.length) && + x.length >= 0; + } + ); + + var sanctifyIndexOf = function(name) { + return def(name, + {b: [ArrayLike]}, + [a, b, $Maybe($.Integer)], + R.pipe(R[name], Just, R.filter(R.gte(_, 0)))); + }; + + //# indexOf :: a -> [a] -> Maybe Integer + //. + //. Takes a value of any type and a list, and returns Just the index + //. of the first occurrence of the value in the list, if applicable; + //. Nothing otherwise. + //. + //. Dispatches to its second argument's `indexOf` method if present. + //. As a result, `String -> String -> Maybe Integer` is an alternative + //. type signature. + //. + //. ```javascript + //. > S.indexOf('a', ['b', 'a', 'n', 'a', 'n', 'a']) + //. Just(1) + //. + //. > S.indexOf('x', ['b', 'a', 'n', 'a', 'n', 'a']) + //. Nothing() + //. + //. > S.indexOf('an', 'banana') + //. Just(1) + //. + //. > S.indexOf('ax', 'banana') + //. Nothing() + //. ``` + S.indexOf = sanctifyIndexOf('indexOf'); + + //# lastIndexOf :: a -> [a] -> Maybe Integer + //. + //. Takes a value of any type and a list, and returns Just the index + //. of the last occurrence of the value in the list, if applicable; + //. Nothing otherwise. + //. + //. Dispatches to its second argument's `lastIndexOf` method if present. + //. As a result, `String -> String -> Maybe Integer` is an alternative + //. type signature. + //. + //. ```javascript + //. > S.lastIndexOf('a', ['b', 'a', 'n', 'a', 'n', 'a']) + //. Just(5) + //. + //. > S.lastIndexOf('x', ['b', 'a', 'n', 'a', 'n', 'a']) + //. Nothing() + //. + //. > S.lastIndexOf('an', 'banana') + //. Just(3) + //. + //. > S.lastIndexOf('ax', 'banana') + //. Nothing() + //. ``` + S.lastIndexOf = sanctifyIndexOf('lastIndexOf'); + + //. ### Array + + //# append :: a -> Array a -> Array a + //. + //. Takes a value of any type and an array of values of that type, and + //. returns the result of appending the value to the array. + //. + //. See also [`prepend`](#prepend). + //. + //. ```javascript + //. > S.append(3, [1, 2]) + //. [1, 2, 3] + //. ``` + S.append = + def('append', + {}, + [a, $.Array(a), $.Array(a)], + function(x, xs) { return xs.concat([x]); }); + + //# prepend :: a -> Array a -> Array a + //. + //. Takes a value of any type and an array of values of that type, and + //. returns the result of prepending the value to the array. + //. + //. See also [`append`](#append). + //. + //. ```javascript + //. > S.prepend(1, [2, 3]) + //. [1, 2, 3] + //. ``` + S.prepend = + def('prepend', + {}, + [a, $.Array(a), $.Array(a)], + function(x, xs) { return [x].concat(xs); }); + + //# find :: (a -> Boolean) -> Array a -> Maybe a + //. + //. Takes a predicate and an array and returns Just the leftmost element of + //. the array which satisfies the predicate; Nothing if none of the array's + //. elements satisfies the predicate. + //. + //. ```javascript + //. > S.find(n => n < 0, [1, -2, 3, -4, 5]) + //. Just(-2) + //. + //. > S.find(n => n < 0, [1, 2, 3, 4, 5]) + //. Nothing() + //. ``` + S.find = + def('find', + {}, + [$.Function, $.Array(a), $Maybe(a)], + function(pred, xs) { + for (var idx = 0, len = xs.length; idx < len; idx += 1) { + if (pred(xs[idx])) { + return Just(xs[idx]); + } + } + return Nothing(); + }); + + //# pluck :: Accessible a => TypeRep b -> String -> Array a -> Array (Maybe b) + //. + //. Takes a [type representative](#type-representatives), a property name, + //. and an array of objects and returns an array of equal length. Each + //. element of the output array is Just the value of the specified property + //. of the corresponding object if the value is of the specified type + //. (according to [`is`](#is)); Nothing otherwise. + //. + //. See also [`get`](#get). + //. + //. ```javascript + //. > S.pluck(Number, 'x', [{x: 1}, {x: 2}, {x: '3'}, {x: null}, {}]) + //. [Just(1), Just(2), Nothing(), Nothing(), Nothing()] + //. ``` + S.pluck = + def('pluck', + {a: [Accessible]}, + [TypeRep, $.String, $.Array(a), $.Array($Maybe(b))], + function(type, key, xs) { return R.map(get(type, key), xs); }); + + //# reduce :: Foldable f => (a -> b -> a) -> a -> f b -> a + //. + //. Takes a curried binary function, an initial value, and a [Foldable][], + //. and applies the function to the initial value and the Foldable's first + //. value, then applies the function to the result of the previous + //. application and the Foldable's second value. Repeats this process + //. until each of the Foldable's values has been used. Returns the initial + //. value if the Foldable is empty; the result of the final application + //. otherwise. + //. + //. See also [`reduce_`](#reduce_). + //. + //. ```javascript + //. > S.reduce(S.add, 0, [1, 2, 3, 4, 5]) + //. 15 + //. + //. > S.reduce(xs => x => [x].concat(xs), [], [1, 2, 3, 4, 5]) + //. [5, 4, 3, 2, 1] + //. ``` + var reduce = S.reduce = + def('reduce', + {b: [Foldable]}, + [$.Function, a, b, a], + function(f_, initial, foldable) { + var f = function(a, b) { + return f_(a)(b); + }; + return reduce_(f, initial, foldable); + }); + + //# reduce_ :: Foldable f => ((a, b) -> a) -> a -> f b -> a + //. + //. Version of [`reduce`](#reduce) accepting uncurried functions. + var reduce_ = S.reduce_ = + def('reduce_', + {b: [Foldable]}, + [$.Function, a, b, a], + function(f, initial, foldable) { + if (_type(foldable) === 'Array') { + var acc = initial; + for (var idx = 0; idx < foldable.length; idx += 1) { + acc = f(acc, foldable[idx]); + } + return acc; + } else { + return foldable.reduce(f, initial); + } + }); + + //# unfoldr :: (b -> Maybe (Pair a b)) -> b -> Array a + //. + //. Takes a function and a seed value, and returns an array generated by + //. applying the function repeatedly. The array is initially empty. The + //. function is initially applied to the seed value. Each application + //. of the function should result in either: + //. + //. - a Nothing, in which case the array is returned; or + //. + //. - Just a pair, in which case the first element is appended to + //. the array and the function is applied to the second element. + //. + //. ```javascript + //. > S.unfoldr(n => n < 5 ? S.Just([n, n + 1]) : S.Nothing(), 1) + //. [1, 2, 3, 4] + //. ``` + S.unfoldr = + def('unfoldr', + {}, + [$.Function, b, $.Array(a)], + function(f, x) { + var result = []; + var m = f(x); + while (m.isJust) { + result.push(m.value[0]); + m = f(m.value[1]); + } + return result; + }); + + //# range :: Integer -> Integer -> Array Integer + //. + //. Returns an array of consecutive integers starting with the first argument + //. and ending with the second argument minus one. Returns `[]` if the second + //. argument is less than or equal to the first argument. + //. + //. ```javascript + //. > S.range(0, 10) + //. [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] + //. + //. > S.range(-5, 0) + //. [-5, -4, -3, -2, -1] + //. + //. > S.range(0, -5) + //. [] + //. ``` + S.range = + def('range', + {}, + [$.Integer, $.Integer, $.Array($.Integer)], + function(from, to) { + var result = []; + for (var n = from; n < to; n += 1) result.push(n); + return result; + }); + + //. ### Object + + //# prop :: Accessible a => String -> a -> b + //. + //. Takes a property name and an object with known properties and returns + //. the value of the specified property. If for some reason the object + //. lacks the specified property, a type error is thrown. + //. + //. For accessing properties of uncertain objects, use [`get`](#get) instead. + //. + //. ```javascript + //. > S.prop('a', {a: 1, b: 2}) + //. 1 + //. ``` + S.prop = prop; + + //# get :: Accessible a => TypeRep b -> String -> a -> Maybe b + //. + //. Takes a [type representative](#type-representatives), a property + //. name, and an object and returns Just the value of the specified object + //. property if it is of the specified type (according to [`is`](#is)); + //. Nothing otherwise. + //. + //. The `Object` type representative may be used as a catch-all since most + //. values have `Object.prototype` in their prototype chains. + //. + //. See also [`gets`](#gets) and [`prop`](#prop). + //. + //. ```javascript + //. > S.get(Number, 'x', {x: 1, y: 2}) + //. Just(1) + //. + //. > S.get(Number, 'x', {x: '1', y: '2'}) + //. Nothing() + //. + //. > S.get(Number, 'x', {}) + //. Nothing() + //. ``` + var get = S.get = + def('get', + {a: [Accessible]}, + [TypeRep, $.String, a, $Maybe(b)], + function(type, key, obj) { return filter(is(type), Just(obj[key])); }); + + //# gets :: Accessible a => TypeRep b -> Array String -> a -> Maybe b + //. + //. Takes a [type representative](#type-representatives), an array of + //. property names, and an object and returns Just the value at the path + //. specified by the array of property names if such a path exists and + //. the value is of the specified type; Nothing otherwise. + //. + //. See also [`get`](#get). + //. + //. ```javascript + //. > S.gets(Number, ['a', 'b', 'c'], {a: {b: {c: 42}}}) + //. Just(42) + //. + //. > S.gets(Number, ['a', 'b', 'c'], {a: {b: {c: '42'}}}) + //. Nothing() + //. + //. > S.gets(Number, ['a', 'b', 'c'], {}) + //. Nothing() + //. ``` + S.gets = + def('gets', + {a: [Accessible]}, + [TypeRep, $.Array($.String), a, $Maybe(b)], + function(type, keys, obj) { + var x = obj; + for (var idx = 0; idx < keys.length; idx += 1) { + if (x == null) { + return Nothing(); + } + x = x[keys[idx]]; + } + return filter(is(type), Just(x)); + }); + + //# keys :: StrMap a -> Array String + //. + //. Returns the keys of the given string map, in arbitrary order. + //. + //. ```javascript + //. > S.keys({b: 2, c: 3, a: 1}).sort() + //. ['a', 'b', 'c'] + //. ``` + S.keys = + def('keys', + {}, + [$.StrMap(a), $.Array($.String)], + Object.keys); + + //# values :: StrMap a -> Array a + //. + //. Returns the values of the given string map, in arbitrary order. + //. + //. ```javascript + //. > S.values({a: 1, c: 3, b: 2}).sort() + //. [1, 2, 3] + //. ``` + S.values = + def('values', + {}, + [$.StrMap(a), $.Array(a)], + function(strMap) { + return Object.keys(strMap).map(function(key) { return strMap[key]; }); + }); + + //# pairs :: StrMap a -> Array (Pair String a) + //. + //. Returns the key–value pairs of the given string map, in arbitrary order. + //. + //. ```javascript + //. > S.pairs({b: 2, a: 1, c: 3}).sort() + //. [['a', 1], ['b', 2], ['c', 3]] + //. ``` + S.pairs = + def('pairs', + {}, + [$.StrMap(a), $.Array($.Pair($.String, a))], + function(strMap) { + return Object.keys(strMap).map(function(k) { return [k, strMap[k]]; }); + }); + + //. ### Number + + //# negate :: ValidNumber -> ValidNumber + //. + //. Negates its argument. + //. + //. ```javascript + //. > S.negate(12.5) + //. -12.5 + //. + //. > S.negate(-42) + //. 42 + //. ``` + S.negate = + def('negate', + {}, + [$.ValidNumber, $.ValidNumber], + function(n) { return -n; }); + + //# add :: FiniteNumber -> FiniteNumber -> FiniteNumber + //. + //. Returns the sum of two (finite) numbers. + //. + //. ```javascript + //. > S.add(1, 1) + //. 2 + //. ``` + S.add = + def('add', + {}, + [$.FiniteNumber, $.FiniteNumber, $.FiniteNumber], + function(a, b) { return a + b; }); + + //# sum :: Foldable f => f FiniteNumber -> FiniteNumber + //. + //. Returns the sum of the given array of (finite) numbers. + //. + //. ```javascript + //. > S.sum([1, 2, 3, 4, 5]) + //. 15 + //. + //. > S.sum([]) + //. 0 + //. + //. > S.sum(S.Just(42)) + //. 42 + //. + //. > S.sum(S.Nothing()) + //. 0 + //. ``` + var sum = S.sum = + def('sum', + {f: [Foldable]}, + [f, $.FiniteNumber], + reduce(function(a) { return function(b) { return a + b; }; }, 0)); + + //# sub :: FiniteNumber -> FiniteNumber -> FiniteNumber + //. + //. Returns the difference between two (finite) numbers. + //. + //. ```javascript + //. > S.sub(4, 2) + //. 2 + //. ``` + S.sub = + def('sub', + {}, + [$.FiniteNumber, $.FiniteNumber, $.FiniteNumber], + function(a, b) { return a - b; }); + + //# inc :: FiniteNumber -> FiniteNumber + //. + //. Increments a (finite) number by one. + //. + //. ```javascript + //. > S.inc(1) + //. 2 + //. ``` + S.inc = + def('inc', + {}, + [$.FiniteNumber, $.FiniteNumber], + function(a) { return a + 1; }); + + //# dec :: FiniteNumber -> FiniteNumber + //. + //. Decrements a (finite) number by one. + //. + //. ```javascript + //. > S.dec(2) + //. 1 + //. ``` + S.dec = + def('dec', + {}, + [$.FiniteNumber, $.FiniteNumber], + function(a) { return a - 1; }); + + //# mult :: FiniteNumber -> FiniteNumber -> FiniteNumber + //. + //. Returns the product of two (finite) numbers. + //. + //. ```javascript + //. > S.mult(4, 2) + //. 8 + //. ``` + S.mult = + def('mult', + {}, + [$.FiniteNumber, $.FiniteNumber, $.FiniteNumber], + function(a, b) { return a * b; }); + + //# product :: Foldable f => f FiniteNumber -> FiniteNumber + //. + //. Returns the product of the given array of (finite) numbers. + //. + //. ```javascript + //. > S.product([1, 2, 3, 4, 5]) + //. 120 + //. + //. > S.product([]) + //. 1 + //. + //. > S.product(S.Just(42)) + //. 42 + //. + //. > S.product(S.Nothing()) + //. 1 + //. ``` + S.product = + def('product', + {f: [Foldable]}, + [f, $.FiniteNumber], + reduce(function(a) { return function(b) { return a * b; }; }, 1)); + + //# div :: FiniteNumber -> NonZeroFiniteNumber -> FiniteNumber + //. + //. Returns the result of dividing its first argument (a finite number) by + //. its second argument (a non-zero finite number). + //. + //. ```javascript + //. > S.div(7, 2) + //. 3.5 + //. ``` + S.div = + def('div', + {}, + [$.FiniteNumber, $.NonZeroFiniteNumber, $.FiniteNumber], + function(a, b) { return a / b; }); + + //# min :: Ord a => a -> a -> a + //. + //. Returns the smaller of its two arguments. + //. + //. Strings are compared lexicographically. Specifically, the Unicode + //. code point value of each character in the first string is compared + //. to the value of the corresponding character in the second string. + //. + //. See also [`max`](#max). + //. + //. ```javascript + //. > S.min(10, 2) + //. 2 + //. + //. > S.min(new Date('1999-12-31'), new Date('2000-01-01')) + //. new Date('1999-12-31') + //. + //. > S.min('10', '2') + //. '10' + //. ``` + S.min = + def('min', + {a: [Ord]}, + [a, a, a], + function(x, y) { return x < y ? x : y; }); + + //# max :: Ord a => a -> a -> a + //. + //. Returns the larger of its two arguments. + //. + //. Strings are compared lexicographically. Specifically, the Unicode + //. code point value of each character in the first string is compared + //. to the value of the corresponding character in the second string. + //. + //. See also [`min`](#min). + //. + //. ```javascript + //. > S.max(10, 2) + //. 10 + //. + //. > S.max(new Date('1999-12-31'), new Date('2000-01-01')) + //. new Date('2000-01-01') + //. + //. > S.max('10', '2') + //. '2' + //. ``` + S.max = + def('max', + {a: [Ord]}, + [a, a, a], + function(x, y) { return x > y ? x : y; }); + + //. ### Integer + + //# even :: Integer -> Boolean + //. + //. Returns `true` if the given integer is even; `false` if it is odd. + //. + //. ```javascript + //. > S.even(42) + //. true + //. + //. > S.even(99) + //. false + //. ``` + S.even = + def('even', + {}, + [$.Integer, $.Boolean], + function(n) { return n % 2 === 0; }); + + //# odd :: Integer -> Boolean + //. + //. Returns `true` if the given integer is odd; `false` if it is even. + //. + //. ```javascript + //. > S.odd(99) + //. true + //. + //. > S.odd(42) + //. false + //. ``` + S.odd = + def('odd', + {}, + [$.Integer, $.Boolean], + function(n) { return n % 2 !== 0; }); + + //. ### Parse + + //# parseDate :: String -> Maybe Date + //. + //. Takes a string and returns Just the date represented by the string + //. if it does in fact represent a date; Nothing otherwise. + //. + //. ```javascript + //. > S.parseDate('2011-01-19T17:40:00Z') + //. Just(new Date('2011-01-19T17:40:00.000Z')) + //. + //. > S.parseDate('today') + //. Nothing() + //. ``` + S.parseDate = + def('parseDate', + {}, + [$.String, $Maybe($.Date)], + function(s) { + var d = new Date(s); + return d.valueOf() === d.valueOf() ? Just(d) : Nothing(); + }); + + // requiredNonCapturingGroup :: Array String -> String + var requiredNonCapturingGroup = function(xs) { + return '(?:' + xs.join('|') + ')'; + }; + + // optionalNonCapturingGroup :: Array String -> String + var optionalNonCapturingGroup = function(xs) { + return requiredNonCapturingGroup(xs) + '?'; + }; + + // validFloatRepr :: String -> Boolean + var validFloatRepr = R.test(new RegExp( + '^' + // start-of-string anchor + '\\s*' + // any number of leading whitespace characters + '[+-]?' + // optional sign + requiredNonCapturingGroup([ + 'Infinity', // "Infinity" + 'NaN', // "NaN" + requiredNonCapturingGroup([ + '[0-9]+', // number + '[0-9]+[.][0-9]+', // number with interior decimal point + '[0-9]+[.]', // number with trailing decimal point + '[.][0-9]+' // number with leading decimal point + ]) + + optionalNonCapturingGroup([ + '[Ee]' + // "E" or "e" + '[+-]?' + // optional sign + '[0-9]+' // exponent + ]) + ]) + + '\\s*' + // any number of trailing whitespace characters + '$' // end-of-string anchor + )); + + //# parseFloat :: String -> Maybe Number + //. + //. Takes a string and returns Just the number represented by the string + //. if it does in fact represent a number; Nothing otherwise. + //. + //. ```javascript + //. > S.parseFloat('-123.45') + //. Just(-123.45) + //. + //. > S.parseFloat('foo.bar') + //. Nothing() + //. ``` + S.parseFloat = + def('parseFloat', + {}, + [$.String, $Maybe($.Number)], + R.pipe(Just, R.filter(validFloatRepr), R.map(parseFloat))); + + //# parseInt :: Integer -> String -> Maybe Integer + //. + //. Takes a radix (an integer between 2 and 36 inclusive) and a string, + //. and returns Just the number represented by the string if it does in + //. fact represent a number in the base specified by the radix; Nothing + //. otherwise. + //. + //. This function is stricter than [`parseInt`][parseInt]: a string + //. is considered to represent an integer only if all its non-prefix + //. characters are members of the character set specified by the radix. + //. + //. ```javascript + //. > S.parseInt(10, '-42') + //. Just(-42) + //. + //. > S.parseInt(16, '0xFF') + //. Just(255) + //. + //. > S.parseInt(16, '0xGG') + //. Nothing() + //. ``` + S.parseInt = + def('parseInt', + {}, + [$.Integer, $.String, $Maybe($.Integer)], + function(radix, s) { + if (radix < 2 || radix > 36) { + throw new RangeError('Radix not in [2 .. 36]'); + } + + var charset = R.take(radix, '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'); + + return R.pipe( + Just, + R.filter(R.pipe(R.replace(/^[+-]/, ''), + radix === 16 ? R.replace(/^0x/i, '') : I, + R.split(''), + R.all(R.pipe(toUpper, + R.indexOf(_, charset), + R.gte(_, 0))))), + R.map(R.partialRight(parseInt, [radix])), + R.filter($.Integer._test) + )(s); + }); + + //# parseJson :: TypeRep a -> String -> Maybe a + //. + //. Takes a [type representative](#type-representatives) and a string which + //. may or may not be valid JSON, and returns Just the result of applying + //. `JSON.parse` to the string *if* the result is of the specified type + //. (according to [`is`](#is)); Nothing otherwise. + //. + //. ```javascript + //. > S.parseJson(Array, '["foo","bar","baz"]') + //. Just(['foo', 'bar', 'baz']) + //. + //. > S.parseJson(Array, '[') + //. Nothing() + //. + //. > S.parseJson(Object, '["foo","bar","baz"]') + //. Nothing() + //. ``` + S.parseJson = + def('parseJson', + {}, + [TypeRep, $.String, $Maybe(a)], + function(type, s) { return filter(is(type), encase(JSON.parse, s)); }); + + //. ### RegExp + + //# regex :: RegexFlags -> String -> RegExp + //. + //. Takes a [RegexFlags][] and a pattern, and returns a RegExp. + //. + //. ```javascript + //. > S.regex('g', ':\\d+:') + //. /:\d+:/g + //. ``` + S.regex = + def('regex', + {}, + [$.RegexFlags, $.String, $.RegExp], + function(flags, source) { return new RegExp(source, flags); }); + + //# regexEscape :: String -> String + //. + //. Takes a string which may contain regular expression metacharacters, + //. and returns a string with those metacharacters escaped. + //. + //. Properties: + //. + //. - `forall s :: String. S.test(S.regex('', S.regexEscape(s)), s) = true` + //. + //. ```javascript + //. > S.regexEscape('-=*{XYZ}*=-') + //. '\\-=\\*\\{XYZ\\}\\*=\\-' + //. ``` + S.regexEscape = + def('regexEscape', + {}, + [$.String, $.String], + function(s) { return s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&'); }); + + //# test :: RegExp -> String -> Boolean + //. + //. Takes a pattern and a string, and returns `true` if the pattern + //. matches the string; `false` otherwise. + //. + //. ```javascript + //. > S.test(/^a/, 'abacus') + //. true + //. + //. > S.test(/^a/, 'banana') + //. false + //. ``` + S.test = + def('test', + {}, + [$.RegExp, $.String, $.Boolean], + function(pattern, s) { + var lastIndex = pattern.lastIndex; + var result = pattern.test(s); + pattern.lastIndex = lastIndex; + return result; + }); + + //# match :: RegExp -> String -> Maybe (Array (Maybe String)) + //. + //. Takes a pattern and a string, and returns Just an array of matches + //. if the pattern matches the string; Nothing otherwise. Each match has + //. type `Maybe String`, where a Nothing represents an unmatched optional + //. capturing group. + //. + //. ```javascript + //. > S.match(/(good)?bye/, 'goodbye') + //. Just([Just('goodbye'), Just('good')]) + //. + //. > S.match(/(good)?bye/, 'bye') + //. Just([Just('bye'), Nothing()]) + //. ``` + S.match = + def('match', + {}, + [$.RegExp, $.String, $Maybe($.Array($Maybe($.String)))], + function(pattern, s) { + var match = s.match(pattern); + return match == null ? Nothing() : Just(R.map(toMaybe, match)); + }); + + //. ### String + + //# toUpper :: String -> String + //. + //. Returns the upper-case equivalent of its argument. + //. + //. See also [`toLower`](#toLower). + //. + //. ```javascript + //. > S.toUpper('ABC def 123') + //. 'ABC DEF 123' + //. ``` + var toUpper = S.toUpper = + def('toUpper', + {}, + [$.String, $.String], + function(s) { return s.toUpperCase(); }); + + //# toLower :: String -> String + //. + //. Returns the lower-case equivalent of its argument. + //. + //. See also [`toUpper`](#toUpper). + //. + //. ```javascript + //. > S.toLower('ABC def 123') + //. 'abc def 123' + //. ``` + S.toLower = + def('toLower', + {}, + [$.String, $.String], + function(s) { return s.toLowerCase(); }); + + //# trim :: String -> String + //. + //. Strips leading and trailing whitespace characters. + //. + //. ```javascript + //. > S.trim('\t\t foo bar \n') + //. 'foo bar' + //. ``` + S.trim = + def('trim', + {}, + [$.String, $.String], + function(s) { return s.trim(); }); + + //# words :: String -> Array String + //. + //. Takes a string and returns the array of words the string contains + //. (words are delimited by whitespace characters). + //. + //. See also [`unwords`](#unwords). + //. + //. ```javascript + //. > S.words(' foo bar baz ') + //. ['foo', 'bar', 'baz'] + //. ``` + S.words = + def('words', + {}, + [$.String, $.Array($.String)], + compose(R.reject(R.isEmpty), R.split(/\s+/))); + + //# unwords :: Array String -> String + //. + //. Takes an array of words and returns the result of joining the words + //. with separating spaces. + //. + //. See also [`words`](#words). + //. + //. ```javascript + //. > S.unwords(['foo', 'bar', 'baz']) + //. 'foo bar baz' + //. ``` + S.unwords = + def('unwords', + {}, + [$.Array($.String), $.String], + function(xs) { return xs.join(' '); }); + + //# lines :: String -> Array String + //. + //. Takes a string and returns the array of lines the string contains + //. (lines are delimited by newlines: `'\n'` or `'\r\n'` or `'\r'`). + //. The resulting strings do not contain newlines. + //. + //. See also [`unlines`](#unlines). + //. + //. ```javascript + //. > S.lines('foo\nbar\nbaz\n') + //. ['foo', 'bar', 'baz'] + //. ``` + S.lines = + def('lines', + {}, + [$.String, $.Array($.String)], + compose(R.match(/^(?=[\s\S]).*/gm), R.replace(/\r\n?/g, '\n'))); + + //# unlines :: Array String -> String + //. + //. Takes an array of lines and returns the result of joining the lines + //. after appending a terminating line feed (`'\n'`) to each. + //. + //. See also [`lines`](#lines). + //. + //. ```javascript + //. > S.unlines(['foo', 'bar', 'baz']) + //. 'foo\nbar\nbaz\n' + //. ``` + S.unlines = + def('unlines', + {}, + [$.Array($.String), $.String], + compose(R.join(''), R.map(concat(_, '\n')))); + + return S; + + /* eslint-enable indent */ + + }; + + return createSanctuary({checkTypes: true, env: defaultEnv}); + +})); + +//. [Apply]: https://github.com/fantasyland/fantasy-land#apply +//. [BinaryType]: https://github.com/sanctuary-js/sanctuary-def#binarytype +//. [Extend]: https://github.com/fantasyland/fantasy-land#extend +//. [Foldable]: https://github.com/fantasyland/fantasy-land#foldable +//. [Functor]: https://github.com/fantasyland/fantasy-land#functor +//. [Monad]: https://github.com/fantasyland/fantasy-land#monad +//. [Monoid]: https://github.com/fantasyland/fantasy-land#monoid +//. [Nullable]: https://github.com/sanctuary-js/sanctuary-def#nullable +//. [R.equals]: http://ramdajs.com/docs/#equals +//. [R.map]: http://ramdajs.com/docs/#map +//. [R.type]: http://ramdajs.com/docs/#type +//. [Ramda]: http://ramdajs.com/ +//. [RegExp]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp +//. [RegexFlags]: https://github.com/sanctuary-js/sanctuary-def#regexflags +//. [Semigroup]: https://github.com/fantasyland/fantasy-land#semigroup +//. [Traversable]: https://github.com/fantasyland/fantasy-land#traversable +//. [UnaryType]: https://github.com/sanctuary-js/sanctuary-def#unarytype +//. [parseInt]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt +//. [sanctuary-def]: https://github.com/sanctuary-js/sanctuary-def +//. [thrush]: https://github.com/raganwald-deprecated/homoiconic/blob/master/2008-10-30/thrush.markdown + +},{"ramda":671,"sanctuary-def":669}],671:[function(require,module,exports){ +// Ramda v0.21.0 +// https://github.com/ramda/ramda +// (c) 2013-2016 Scott Sauyet, Michael Hurley, and David Chambers +// Ramda may be freely distributed under the MIT license. + +;(function() { + + 'use strict'; + + /** + * A special placeholder value used to specify "gaps" within curried functions, + * allowing partial application of any combination of arguments, regardless of + * their positions. + * + * If `g` is a curried ternary function and `_` is `R.__`, the following are + * equivalent: + * + * - `g(1, 2, 3)` + * - `g(_, 2, 3)(1)` + * - `g(_, _, 3)(1)(2)` + * - `g(_, _, 3)(1, 2)` + * - `g(_, 2, _)(1, 3)` + * - `g(_, 2)(1)(3)` + * - `g(_, 2)(1, 3)` + * - `g(_, 2)(_, 3)(1)` + * + * @constant + * @memberOf R + * @since v0.6.0 + * @category Function + * @example + * + * var greet = R.replace('{name}', R.__, 'Hello, {name}!'); + * greet('Alice'); //=> 'Hello, Alice!' + */ + var __ = { '@@functional/placeholder': true }; + + /* eslint-disable no-unused-vars */ + var _arity = function _arity(n, fn) { + /* eslint-disable no-unused-vars */ + switch (n) { + case 0: + return function () { + return fn.apply(this, arguments); + }; + case 1: + return function (a0) { + return fn.apply(this, arguments); + }; + case 2: + return function (a0, a1) { + return fn.apply(this, arguments); + }; + case 3: + return function (a0, a1, a2) { + return fn.apply(this, arguments); + }; + case 4: + return function (a0, a1, a2, a3) { + return fn.apply(this, arguments); + }; + case 5: + return function (a0, a1, a2, a3, a4) { + return fn.apply(this, arguments); + }; + case 6: + return function (a0, a1, a2, a3, a4, a5) { + return fn.apply(this, arguments); + }; + case 7: + return function (a0, a1, a2, a3, a4, a5, a6) { + return fn.apply(this, arguments); + }; + case 8: + return function (a0, a1, a2, a3, a4, a5, a6, a7) { + return fn.apply(this, arguments); + }; + case 9: + return function (a0, a1, a2, a3, a4, a5, a6, a7, a8) { + return fn.apply(this, arguments); + }; + case 10: + return function (a0, a1, a2, a3, a4, a5, a6, a7, a8, a9) { + return fn.apply(this, arguments); + }; + default: + throw new Error('First argument to _arity must be a non-negative integer no greater than ten'); + } + }; + + var _arrayFromIterator = function _arrayFromIterator(iter) { + var list = []; + var next; + while (!(next = iter.next()).done) { + list.push(next.value); + } + return list; + }; + + var _arrayOf = function _arrayOf() { + return Array.prototype.slice.call(arguments); + }; + + var _cloneRegExp = function _cloneRegExp(pattern) { + return new RegExp(pattern.source, (pattern.global ? 'g' : '') + (pattern.ignoreCase ? 'i' : '') + (pattern.multiline ? 'm' : '') + (pattern.sticky ? 'y' : '') + (pattern.unicode ? 'u' : '')); + }; + + var _complement = function _complement(f) { + return function () { + return !f.apply(this, arguments); + }; + }; + + /** + * Private `concat` function to merge two array-like objects. + * + * @private + * @param {Array|Arguments} [set1=[]] An array-like object. + * @param {Array|Arguments} [set2=[]] An array-like object. + * @return {Array} A new, merged array. + * @example + * + * _concat([4, 5, 6], [1, 2, 3]); //=> [4, 5, 6, 1, 2, 3] + */ + var _concat = function _concat(set1, set2) { + set1 = set1 || []; + set2 = set2 || []; + var idx; + var len1 = set1.length; + var len2 = set2.length; + var result = []; + idx = 0; + while (idx < len1) { + result[result.length] = set1[idx]; + idx += 1; + } + idx = 0; + while (idx < len2) { + result[result.length] = set2[idx]; + idx += 1; + } + return result; + }; + + var _containsWith = function _containsWith(pred, x, list) { + var idx = 0; + var len = list.length; + while (idx < len) { + if (pred(x, list[idx])) { + return true; + } + idx += 1; + } + return false; + }; + + var _filter = function _filter(fn, list) { + var idx = 0; + var len = list.length; + var result = []; + while (idx < len) { + if (fn(list[idx])) { + result[result.length] = list[idx]; + } + idx += 1; + } + return result; + }; + + var _forceReduced = function _forceReduced(x) { + return { + '@@transducer/value': x, + '@@transducer/reduced': true + }; + }; + + // String(x => x) evaluates to "x => x", so the pattern may not match. + var _functionName = function _functionName(f) { + // String(x => x) evaluates to "x => x", so the pattern may not match. + var match = String(f).match(/^function (\w*)/); + return match == null ? '' : match[1]; + }; + + var _has = function _has(prop, obj) { + return Object.prototype.hasOwnProperty.call(obj, prop); + }; + + var _identity = function _identity(x) { + return x; + }; + + var _isArguments = function () { + var toString = Object.prototype.toString; + return toString.call(arguments) === '[object Arguments]' ? function _isArguments(x) { + return toString.call(x) === '[object Arguments]'; + } : function _isArguments(x) { + return _has('callee', x); + }; + }(); + + /** + * Tests whether or not an object is an array. + * + * @private + * @param {*} val The object to test. + * @return {Boolean} `true` if `val` is an array, `false` otherwise. + * @example + * + * _isArray([]); //=> true + * _isArray(null); //=> false + * _isArray({}); //=> false + */ + var _isArray = Array.isArray || function _isArray(val) { + return val != null && val.length >= 0 && Object.prototype.toString.call(val) === '[object Array]'; + }; + + var _isFunction = function _isNumber(x) { + return Object.prototype.toString.call(x) === '[object Function]'; + }; + + /** + * Determine if the passed argument is an integer. + * + * @private + * @param {*} n + * @category Type + * @return {Boolean} + */ + var _isInteger = Number.isInteger || function _isInteger(n) { + return n << 0 === n; + }; + + var _isNumber = function _isNumber(x) { + return Object.prototype.toString.call(x) === '[object Number]'; + }; + + var _isObject = function _isObject(x) { + return Object.prototype.toString.call(x) === '[object Object]'; + }; + + var _isPlaceholder = function _isPlaceholder(a) { + return a != null && typeof a === 'object' && a['@@functional/placeholder'] === true; + }; + + var _isRegExp = function _isRegExp(x) { + return Object.prototype.toString.call(x) === '[object RegExp]'; + }; + + var _isString = function _isString(x) { + return Object.prototype.toString.call(x) === '[object String]'; + }; + + var _isTransformer = function _isTransformer(obj) { + return typeof obj['@@transducer/step'] === 'function'; + }; + + var _map = function _map(fn, functor) { + var idx = 0; + var len = functor.length; + var result = Array(len); + while (idx < len) { + result[idx] = fn(functor[idx]); + idx += 1; + } + return result; + }; + + // Based on https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/assign + var _objectAssign = function _objectAssign(target) { + if (target == null) { + throw new TypeError('Cannot convert undefined or null to object'); + } + var output = Object(target); + var idx = 1; + var length = arguments.length; + while (idx < length) { + var source = arguments[idx]; + if (source != null) { + for (var nextKey in source) { + if (_has(nextKey, source)) { + output[nextKey] = source[nextKey]; + } + } + } + idx += 1; + } + return output; + }; + + var _of = function _of(x) { + return [x]; + }; + + var _pipe = function _pipe(f, g) { + return function () { + return g.call(this, f.apply(this, arguments)); + }; + }; + + var _pipeP = function _pipeP(f, g) { + return function () { + var ctx = this; + return f.apply(ctx, arguments).then(function (x) { + return g.call(ctx, x); + }); + }; + }; + + // \b matches word boundary; [\b] matches backspace + var _quote = function _quote(s) { + var escaped = s.replace(/\\/g, '\\\\').replace(/[\b]/g, '\\b') // \b matches word boundary; [\b] matches backspace + .replace(/\f/g, '\\f').replace(/\n/g, '\\n').replace(/\r/g, '\\r').replace(/\t/g, '\\t').replace(/\v/g, '\\v').replace(/\0/g, '\\0'); + return '"' + escaped.replace(/"/g, '\\"') + '"'; + }; + + var _reduced = function _reduced(x) { + return x && x['@@transducer/reduced'] ? x : { + '@@transducer/value': x, + '@@transducer/reduced': true + }; + }; + + /** + * An optimized, private array `slice` implementation. + * + * @private + * @param {Arguments|Array} args The array or arguments object to consider. + * @param {Number} [from=0] The array index to slice from, inclusive. + * @param {Number} [to=args.length] The array index to slice to, exclusive. + * @return {Array} A new, sliced array. + * @example + * + * _slice([1, 2, 3, 4, 5], 1, 3); //=> [2, 3] + * + * var firstThreeArgs = function(a, b, c, d) { + * return _slice(arguments, 0, 3); + * }; + * firstThreeArgs(1, 2, 3, 4); //=> [1, 2, 3] + */ + var _slice = function _slice(args, from, to) { + switch (arguments.length) { + case 1: + return _slice(args, 0, args.length); + case 2: + return _slice(args, from, args.length); + default: + var list = []; + var idx = 0; + var len = Math.max(0, Math.min(args.length, to) - from); + while (idx < len) { + list[idx] = args[from + idx]; + idx += 1; + } + return list; + } + }; + + /** + * Polyfill from . + */ + var _toISOString = function () { + var pad = function pad(n) { + return (n < 10 ? '0' : '') + n; + }; + return typeof Date.prototype.toISOString === 'function' ? function _toISOString(d) { + return d.toISOString(); + } : function _toISOString(d) { + return d.getUTCFullYear() + '-' + pad(d.getUTCMonth() + 1) + '-' + pad(d.getUTCDate()) + 'T' + pad(d.getUTCHours()) + ':' + pad(d.getUTCMinutes()) + ':' + pad(d.getUTCSeconds()) + '.' + (d.getUTCMilliseconds() / 1000).toFixed(3).slice(2, 5) + 'Z'; + }; + }(); + + var _xfBase = { + init: function () { + return this.xf['@@transducer/init'](); + }, + result: function (result) { + return this.xf['@@transducer/result'](result); + } + }; + + var _xwrap = function () { + function XWrap(fn) { + this.f = fn; + } + XWrap.prototype['@@transducer/init'] = function () { + throw new Error('init not implemented on XWrap'); + }; + XWrap.prototype['@@transducer/result'] = function (acc) { + return acc; + }; + XWrap.prototype['@@transducer/step'] = function (acc, x) { + return this.f(acc, x); + }; + return function _xwrap(fn) { + return new XWrap(fn); + }; + }(); + + var _aperture = function _aperture(n, list) { + var idx = 0; + var limit = list.length - (n - 1); + var acc = new Array(limit >= 0 ? limit : 0); + while (idx < limit) { + acc[idx] = _slice(list, idx, idx + n); + idx += 1; + } + return acc; + }; + + var _assign = typeof Object.assign === 'function' ? Object.assign : _objectAssign; + + /** + * Similar to hasMethod, this checks whether a function has a [methodname] + * function. If it isn't an array it will execute that function otherwise it + * will default to the ramda implementation. + * + * @private + * @param {Function} fn ramda implemtation + * @param {String} methodname property to check for a custom implementation + * @return {Object} Whatever the return value of the method is. + */ + var _checkForMethod = function _checkForMethod(methodname, fn) { + return function () { + var length = arguments.length; + if (length === 0) { + return fn(); + } + var obj = arguments[length - 1]; + return _isArray(obj) || typeof obj[methodname] !== 'function' ? fn.apply(this, arguments) : obj[methodname].apply(obj, _slice(arguments, 0, length - 1)); + }; + }; + + /** + * Optimized internal one-arity curry function. + * + * @private + * @category Function + * @param {Function} fn The function to curry. + * @return {Function} The curried function. + */ + var _curry1 = function _curry1(fn) { + return function f1(a) { + if (arguments.length === 0 || _isPlaceholder(a)) { + return f1; + } else { + return fn.apply(this, arguments); + } + }; + }; + + /** + * Optimized internal two-arity curry function. + * + * @private + * @category Function + * @param {Function} fn The function to curry. + * @return {Function} The curried function. + */ + var _curry2 = function _curry2(fn) { + return function f2(a, b) { + switch (arguments.length) { + case 0: + return f2; + case 1: + return _isPlaceholder(a) ? f2 : _curry1(function (_b) { + return fn(a, _b); + }); + default: + return _isPlaceholder(a) && _isPlaceholder(b) ? f2 : _isPlaceholder(a) ? _curry1(function (_a) { + return fn(_a, b); + }) : _isPlaceholder(b) ? _curry1(function (_b) { + return fn(a, _b); + }) : fn(a, b); + } + }; + }; + + /** + * Optimized internal three-arity curry function. + * + * @private + * @category Function + * @param {Function} fn The function to curry. + * @return {Function} The curried function. + */ + var _curry3 = function _curry3(fn) { + return function f3(a, b, c) { + switch (arguments.length) { + case 0: + return f3; + case 1: + return _isPlaceholder(a) ? f3 : _curry2(function (_b, _c) { + return fn(a, _b, _c); + }); + case 2: + return _isPlaceholder(a) && _isPlaceholder(b) ? f3 : _isPlaceholder(a) ? _curry2(function (_a, _c) { + return fn(_a, b, _c); + }) : _isPlaceholder(b) ? _curry2(function (_b, _c) { + return fn(a, _b, _c); + }) : _curry1(function (_c) { + return fn(a, b, _c); + }); + default: + return _isPlaceholder(a) && _isPlaceholder(b) && _isPlaceholder(c) ? f3 : _isPlaceholder(a) && _isPlaceholder(b) ? _curry2(function (_a, _b) { + return fn(_a, _b, c); + }) : _isPlaceholder(a) && _isPlaceholder(c) ? _curry2(function (_a, _c) { + return fn(_a, b, _c); + }) : _isPlaceholder(b) && _isPlaceholder(c) ? _curry2(function (_b, _c) { + return fn(a, _b, _c); + }) : _isPlaceholder(a) ? _curry1(function (_a) { + return fn(_a, b, c); + }) : _isPlaceholder(b) ? _curry1(function (_b) { + return fn(a, _b, c); + }) : _isPlaceholder(c) ? _curry1(function (_c) { + return fn(a, b, _c); + }) : fn(a, b, c); + } + }; + }; + + /** + * Internal curryN function. + * + * @private + * @category Function + * @param {Number} length The arity of the curried function. + * @param {Array} received An array of arguments received thus far. + * @param {Function} fn The function to curry. + * @return {Function} The curried function. + */ + var _curryN = function _curryN(length, received, fn) { + return function () { + var combined = []; + var argsIdx = 0; + var left = length; + var combinedIdx = 0; + while (combinedIdx < received.length || argsIdx < arguments.length) { + var result; + if (combinedIdx < received.length && (!_isPlaceholder(received[combinedIdx]) || argsIdx >= arguments.length)) { + result = received[combinedIdx]; + } else { + result = arguments[argsIdx]; + argsIdx += 1; + } + combined[combinedIdx] = result; + if (!_isPlaceholder(result)) { + left -= 1; + } + combinedIdx += 1; + } + return left <= 0 ? fn.apply(this, combined) : _arity(left, _curryN(length, combined, fn)); + }; + }; + + /** + * Returns a function that dispatches with different strategies based on the + * object in list position (last argument). If it is an array, executes [fn]. + * Otherwise, if it has a function with [methodname], it will execute that + * function (functor case). Otherwise, if it is a transformer, uses transducer + * [xf] to return a new transformer (transducer case). Otherwise, it will + * default to executing [fn]. + * + * @private + * @param {String} methodname property to check for a custom implementation + * @param {Function} xf transducer to initialize if object is transformer + * @param {Function} fn default ramda implementation + * @return {Function} A function that dispatches on object in list position + */ + var _dispatchable = function _dispatchable(methodname, xf, fn) { + return function () { + var length = arguments.length; + if (length === 0) { + return fn(); + } + var obj = arguments[length - 1]; + if (!_isArray(obj)) { + var args = _slice(arguments, 0, length - 1); + if (typeof obj[methodname] === 'function') { + return obj[methodname].apply(obj, args); + } + if (_isTransformer(obj)) { + var transducer = xf.apply(null, args); + return transducer(obj); + } + } + return fn.apply(this, arguments); + }; + }; + + var _dropLastWhile = function dropLastWhile(pred, list) { + var idx = list.length - 1; + while (idx >= 0 && pred(list[idx])) { + idx -= 1; + } + return _slice(list, 0, idx + 1); + }; + + var _xall = function () { + function XAll(f, xf) { + this.xf = xf; + this.f = f; + this.all = true; + } + XAll.prototype['@@transducer/init'] = _xfBase.init; + XAll.prototype['@@transducer/result'] = function (result) { + if (this.all) { + result = this.xf['@@transducer/step'](result, true); + } + return this.xf['@@transducer/result'](result); + }; + XAll.prototype['@@transducer/step'] = function (result, input) { + if (!this.f(input)) { + this.all = false; + result = _reduced(this.xf['@@transducer/step'](result, false)); + } + return result; + }; + return _curry2(function _xall(f, xf) { + return new XAll(f, xf); + }); + }(); + + var _xany = function () { + function XAny(f, xf) { + this.xf = xf; + this.f = f; + this.any = false; + } + XAny.prototype['@@transducer/init'] = _xfBase.init; + XAny.prototype['@@transducer/result'] = function (result) { + if (!this.any) { + result = this.xf['@@transducer/step'](result, false); + } + return this.xf['@@transducer/result'](result); + }; + XAny.prototype['@@transducer/step'] = function (result, input) { + if (this.f(input)) { + this.any = true; + result = _reduced(this.xf['@@transducer/step'](result, true)); + } + return result; + }; + return _curry2(function _xany(f, xf) { + return new XAny(f, xf); + }); + }(); + + var _xaperture = function () { + function XAperture(n, xf) { + this.xf = xf; + this.pos = 0; + this.full = false; + this.acc = new Array(n); + } + XAperture.prototype['@@transducer/init'] = _xfBase.init; + XAperture.prototype['@@transducer/result'] = function (result) { + this.acc = null; + return this.xf['@@transducer/result'](result); + }; + XAperture.prototype['@@transducer/step'] = function (result, input) { + this.store(input); + return this.full ? this.xf['@@transducer/step'](result, this.getCopy()) : result; + }; + XAperture.prototype.store = function (input) { + this.acc[this.pos] = input; + this.pos += 1; + if (this.pos === this.acc.length) { + this.pos = 0; + this.full = true; + } + }; + XAperture.prototype.getCopy = function () { + return _concat(_slice(this.acc, this.pos), _slice(this.acc, 0, this.pos)); + }; + return _curry2(function _xaperture(n, xf) { + return new XAperture(n, xf); + }); + }(); + + var _xdrop = function () { + function XDrop(n, xf) { + this.xf = xf; + this.n = n; + } + XDrop.prototype['@@transducer/init'] = _xfBase.init; + XDrop.prototype['@@transducer/result'] = _xfBase.result; + XDrop.prototype['@@transducer/step'] = function (result, input) { + if (this.n > 0) { + this.n -= 1; + return result; + } + return this.xf['@@transducer/step'](result, input); + }; + return _curry2(function _xdrop(n, xf) { + return new XDrop(n, xf); + }); + }(); + + var _xdropLast = function () { + function XDropLast(n, xf) { + this.xf = xf; + this.pos = 0; + this.full = false; + this.acc = new Array(n); + } + XDropLast.prototype['@@transducer/init'] = _xfBase.init; + XDropLast.prototype['@@transducer/result'] = function (result) { + this.acc = null; + return this.xf['@@transducer/result'](result); + }; + XDropLast.prototype['@@transducer/step'] = function (result, input) { + if (this.full) { + result = this.xf['@@transducer/step'](result, this.acc[this.pos]); + } + this.store(input); + return result; + }; + XDropLast.prototype.store = function (input) { + this.acc[this.pos] = input; + this.pos += 1; + if (this.pos === this.acc.length) { + this.pos = 0; + this.full = true; + } + }; + return _curry2(function _xdropLast(n, xf) { + return new XDropLast(n, xf); + }); + }(); + + var _xdropRepeatsWith = function () { + function XDropRepeatsWith(pred, xf) { + this.xf = xf; + this.pred = pred; + this.lastValue = undefined; + this.seenFirstValue = false; + } + XDropRepeatsWith.prototype['@@transducer/init'] = function () { + return this.xf['@@transducer/init'](); + }; + XDropRepeatsWith.prototype['@@transducer/result'] = function (result) { + return this.xf['@@transducer/result'](result); + }; + XDropRepeatsWith.prototype['@@transducer/step'] = function (result, input) { + var sameAsLast = false; + if (!this.seenFirstValue) { + this.seenFirstValue = true; + } else if (this.pred(this.lastValue, input)) { + sameAsLast = true; + } + this.lastValue = input; + return sameAsLast ? result : this.xf['@@transducer/step'](result, input); + }; + return _curry2(function _xdropRepeatsWith(pred, xf) { + return new XDropRepeatsWith(pred, xf); + }); + }(); + + var _xdropWhile = function () { + function XDropWhile(f, xf) { + this.xf = xf; + this.f = f; + } + XDropWhile.prototype['@@transducer/init'] = _xfBase.init; + XDropWhile.prototype['@@transducer/result'] = _xfBase.result; + XDropWhile.prototype['@@transducer/step'] = function (result, input) { + if (this.f) { + if (this.f(input)) { + return result; + } + this.f = null; + } + return this.xf['@@transducer/step'](result, input); + }; + return _curry2(function _xdropWhile(f, xf) { + return new XDropWhile(f, xf); + }); + }(); + + var _xfilter = function () { + function XFilter(f, xf) { + this.xf = xf; + this.f = f; + } + XFilter.prototype['@@transducer/init'] = _xfBase.init; + XFilter.prototype['@@transducer/result'] = _xfBase.result; + XFilter.prototype['@@transducer/step'] = function (result, input) { + return this.f(input) ? this.xf['@@transducer/step'](result, input) : result; + }; + return _curry2(function _xfilter(f, xf) { + return new XFilter(f, xf); + }); + }(); + + var _xfind = function () { + function XFind(f, xf) { + this.xf = xf; + this.f = f; + this.found = false; + } + XFind.prototype['@@transducer/init'] = _xfBase.init; + XFind.prototype['@@transducer/result'] = function (result) { + if (!this.found) { + result = this.xf['@@transducer/step'](result, void 0); + } + return this.xf['@@transducer/result'](result); + }; + XFind.prototype['@@transducer/step'] = function (result, input) { + if (this.f(input)) { + this.found = true; + result = _reduced(this.xf['@@transducer/step'](result, input)); + } + return result; + }; + return _curry2(function _xfind(f, xf) { + return new XFind(f, xf); + }); + }(); + + var _xfindIndex = function () { + function XFindIndex(f, xf) { + this.xf = xf; + this.f = f; + this.idx = -1; + this.found = false; + } + XFindIndex.prototype['@@transducer/init'] = _xfBase.init; + XFindIndex.prototype['@@transducer/result'] = function (result) { + if (!this.found) { + result = this.xf['@@transducer/step'](result, -1); + } + return this.xf['@@transducer/result'](result); + }; + XFindIndex.prototype['@@transducer/step'] = function (result, input) { + this.idx += 1; + if (this.f(input)) { + this.found = true; + result = _reduced(this.xf['@@transducer/step'](result, this.idx)); + } + return result; + }; + return _curry2(function _xfindIndex(f, xf) { + return new XFindIndex(f, xf); + }); + }(); + + var _xfindLast = function () { + function XFindLast(f, xf) { + this.xf = xf; + this.f = f; + } + XFindLast.prototype['@@transducer/init'] = _xfBase.init; + XFindLast.prototype['@@transducer/result'] = function (result) { + return this.xf['@@transducer/result'](this.xf['@@transducer/step'](result, this.last)); + }; + XFindLast.prototype['@@transducer/step'] = function (result, input) { + if (this.f(input)) { + this.last = input; + } + return result; + }; + return _curry2(function _xfindLast(f, xf) { + return new XFindLast(f, xf); + }); + }(); + + var _xfindLastIndex = function () { + function XFindLastIndex(f, xf) { + this.xf = xf; + this.f = f; + this.idx = -1; + this.lastIdx = -1; + } + XFindLastIndex.prototype['@@transducer/init'] = _xfBase.init; + XFindLastIndex.prototype['@@transducer/result'] = function (result) { + return this.xf['@@transducer/result'](this.xf['@@transducer/step'](result, this.lastIdx)); + }; + XFindLastIndex.prototype['@@transducer/step'] = function (result, input) { + this.idx += 1; + if (this.f(input)) { + this.lastIdx = this.idx; + } + return result; + }; + return _curry2(function _xfindLastIndex(f, xf) { + return new XFindLastIndex(f, xf); + }); + }(); + + var _xmap = function () { + function XMap(f, xf) { + this.xf = xf; + this.f = f; + } + XMap.prototype['@@transducer/init'] = _xfBase.init; + XMap.prototype['@@transducer/result'] = _xfBase.result; + XMap.prototype['@@transducer/step'] = function (result, input) { + return this.xf['@@transducer/step'](result, this.f(input)); + }; + return _curry2(function _xmap(f, xf) { + return new XMap(f, xf); + }); + }(); + + var _xtake = function () { + function XTake(n, xf) { + this.xf = xf; + this.n = n; + } + XTake.prototype['@@transducer/init'] = _xfBase.init; + XTake.prototype['@@transducer/result'] = _xfBase.result; + XTake.prototype['@@transducer/step'] = function (result, input) { + if (this.n === 0) { + return _reduced(result); + } else { + this.n -= 1; + return this.xf['@@transducer/step'](result, input); + } + }; + return _curry2(function _xtake(n, xf) { + return new XTake(n, xf); + }); + }(); + + var _xtakeWhile = function () { + function XTakeWhile(f, xf) { + this.xf = xf; + this.f = f; + } + XTakeWhile.prototype['@@transducer/init'] = _xfBase.init; + XTakeWhile.prototype['@@transducer/result'] = _xfBase.result; + XTakeWhile.prototype['@@transducer/step'] = function (result, input) { + return this.f(input) ? this.xf['@@transducer/step'](result, input) : _reduced(result); + }; + return _curry2(function _xtakeWhile(f, xf) { + return new XTakeWhile(f, xf); + }); + }(); + + /** + * Adds two values. + * + * @func + * @memberOf R + * @since v0.1.0 + * @category Math + * @sig Number -> Number -> Number + * @param {Number} a + * @param {Number} b + * @return {Number} + * @see R.subtract + * @example + * + * R.add(2, 3); //=> 5 + * R.add(7)(10); //=> 17 + */ + var add = _curry2(function add(a, b) { + return Number(a) + Number(b); + }); + + /** + * Applies a function to the value at the given index of an array, returning a + * new copy of the array with the element at the given index replaced with the + * result of the function application. + * + * @func + * @memberOf R + * @since v0.14.0 + * @category List + * @sig (a -> a) -> Number -> [a] -> [a] + * @param {Function} fn The function to apply. + * @param {Number} idx The index. + * @param {Array|Arguments} list An array-like object whose value + * at the supplied index will be replaced. + * @return {Array} A copy of the supplied array-like object with + * the element at index `idx` replaced with the value + * returned by applying `fn` to the existing element. + * @see R.update + * @example + * + * R.adjust(R.add(10), 1, [0, 1, 2]); //=> [0, 11, 2] + * R.adjust(R.add(10))(1)([0, 1, 2]); //=> [0, 11, 2] + */ + var adjust = _curry3(function adjust(fn, idx, list) { + if (idx >= list.length || idx < -list.length) { + return list; + } + var start = idx < 0 ? list.length : 0; + var _idx = start + idx; + var _list = _concat(list); + _list[_idx] = fn(list[_idx]); + return _list; + }); + + /** + * Returns `true` if all elements of the list match the predicate, `false` if + * there are any that don't. + * + * Dispatches to the `all` method of the second argument, if present. + * + * Acts as a transducer if a transformer is given in list position. + * + * @func + * @memberOf R + * @since v0.1.0 + * @category List + * @sig (a -> Boolean) -> [a] -> Boolean + * @param {Function} fn The predicate function. + * @param {Array} list The array to consider. + * @return {Boolean} `true` if the predicate is satisfied by every element, `false` + * otherwise. + * @see R.any, R.none, R.transduce + * @example + * + * var lessThan2 = R.flip(R.lt)(2); + * var lessThan3 = R.flip(R.lt)(3); + * R.all(lessThan2)([1, 2]); //=> false + * R.all(lessThan3)([1, 2]); //=> true + */ + var all = _curry2(_dispatchable('all', _xall, function all(fn, list) { + var idx = 0; + while (idx < list.length) { + if (!fn(list[idx])) { + return false; + } + idx += 1; + } + return true; + })); + + /** + * Returns a function that always returns the given value. Note that for + * non-primitives the value returned is a reference to the original value. + * + * This function is known as `const`, `constant`, or `K` (for K combinator) in + * other languages and libraries. + * + * @func + * @memberOf R + * @since v0.1.0 + * @category Function + * @sig a -> (* -> a) + * @param {*} val The value to wrap in a function + * @return {Function} A Function :: * -> val. + * @example + * + * var t = R.always('Tee'); + * t(); //=> 'Tee' + */ + var always = _curry1(function always(val) { + return function () { + return val; + }; + }); + + /** + * Returns `true` if both arguments are `true`; `false` otherwise. + * + * @func + * @memberOf R + * @since v0.1.0 + * @category Logic + * @sig * -> * -> * + * @param {Boolean} a A boolean value + * @param {Boolean} b A boolean value + * @return {Boolean} `true` if both arguments are `true`, `false` otherwise + * @see R.both + * @example + * + * R.and(true, true); //=> true + * R.and(true, false); //=> false + * R.and(false, true); //=> false + * R.and(false, false); //=> false + */ + var and = _curry2(function and(a, b) { + return a && b; + }); + + /** + * Returns `true` if at least one of elements of the list match the predicate, + * `false` otherwise. + * + * Dispatches to the `any` method of the second argument, if present. + * + * Acts as a transducer if a transformer is given in list position. + * + * @func + * @memberOf R + * @since v0.1.0 + * @category List + * @sig (a -> Boolean) -> [a] -> Boolean + * @param {Function} fn The predicate function. + * @param {Array} list The array to consider. + * @return {Boolean} `true` if the predicate is satisfied by at least one element, `false` + * otherwise. + * @see R.all, R.none, R.transduce + * @example + * + * var lessThan0 = R.flip(R.lt)(0); + * var lessThan2 = R.flip(R.lt)(2); + * R.any(lessThan0)([1, 2]); //=> false + * R.any(lessThan2)([1, 2]); //=> true + */ + var any = _curry2(_dispatchable('any', _xany, function any(fn, list) { + var idx = 0; + while (idx < list.length) { + if (fn(list[idx])) { + return true; + } + idx += 1; + } + return false; + })); + + /** + * Returns a new list, composed of n-tuples of consecutive elements If `n` is + * greater than the length of the list, an empty list is returned. + * + * Dispatches to the `aperture` method of the second argument, if present. + * + * Acts as a transducer if a transformer is given in list position. + * + * @func + * @memberOf R + * @since v0.12.0 + * @category List + * @sig Number -> [a] -> [[a]] + * @param {Number} n The size of the tuples to create + * @param {Array} list The list to split into `n`-tuples + * @return {Array} The new list. + * @see R.transduce + * @example + * + * R.aperture(2, [1, 2, 3, 4, 5]); //=> [[1, 2], [2, 3], [3, 4], [4, 5]] + * R.aperture(3, [1, 2, 3, 4, 5]); //=> [[1, 2, 3], [2, 3, 4], [3, 4, 5]] + * R.aperture(7, [1, 2, 3, 4, 5]); //=> [] + */ + var aperture = _curry2(_dispatchable('aperture', _xaperture, _aperture)); + + /** + * Returns a new list containing the contents of the given list, followed by + * the given element. + * + * @func + * @memberOf R + * @since v0.1.0 + * @category List + * @sig a -> [a] -> [a] + * @param {*} el The element to add to the end of the new list. + * @param {Array} list The list whose contents will be added to the beginning of the output + * list. + * @return {Array} A new list containing the contents of the old list followed by `el`. + * @see R.prepend + * @example + * + * R.append('tests', ['write', 'more']); //=> ['write', 'more', 'tests'] + * R.append('tests', []); //=> ['tests'] + * R.append(['tests'], ['write', 'more']); //=> ['write', 'more', ['tests']] + */ + var append = _curry2(function append(el, list) { + return _concat(list, [el]); + }); + + /** + * Applies function `fn` to the argument list `args`. This is useful for + * creating a fixed-arity function from a variadic function. `fn` should be a + * bound function if context is significant. + * + * @func + * @memberOf R + * @since v0.7.0 + * @category Function + * @sig (*... -> a) -> [*] -> a + * @param {Function} fn + * @param {Array} args + * @return {*} + * @see R.call, R.unapply + * @example + * + * var nums = [1, 2, 3, -99, 42, 6, 7]; + * R.apply(Math.max, nums); //=> 42 + */ + var apply = _curry2(function apply(fn, args) { + return fn.apply(this, args); + }); + + /** + * Makes a shallow clone of an object, setting or overriding the specified + * property with the given value. Note that this copies and flattens prototype + * properties onto the new object as well. All non-primitive properties are + * copied by reference. + * + * @func + * @memberOf R + * @since v0.8.0 + * @category Object + * @sig String -> a -> {k: v} -> {k: v} + * @param {String} prop the property name to set + * @param {*} val the new value + * @param {Object} obj the object to clone + * @return {Object} a new object similar to the original except for the specified property. + * @see R.dissoc + * @example + * + * R.assoc('c', 3, {a: 1, b: 2}); //=> {a: 1, b: 2, c: 3} + */ + var assoc = _curry3(function assoc(prop, val, obj) { + var result = {}; + for (var p in obj) { + result[p] = obj[p]; + } + result[prop] = val; + return result; + }); + + /** + * Makes a shallow clone of an object, setting or overriding the nodes required + * to create the given path, and placing the specific value at the tail end of + * that path. Note that this copies and flattens prototype properties onto the + * new object as well. All non-primitive properties are copied by reference. + * + * @func + * @memberOf R + * @since v0.8.0 + * @category Object + * @sig [String] -> a -> {k: v} -> {k: v} + * @param {Array} path the path to set + * @param {*} val the new value + * @param {Object} obj the object to clone + * @return {Object} a new object similar to the original except along the specified path. + * @see R.dissocPath + * @example + * + * R.assocPath(['a', 'b', 'c'], 42, {a: {b: {c: 0}}}); //=> {a: {b: {c: 42}}} + */ + var assocPath = _curry3(function assocPath(path, val, obj) { + switch (path.length) { + case 0: + return val; + case 1: + return assoc(path[0], val, obj); + default: + return assoc(path[0], assocPath(_slice(path, 1), val, Object(obj[path[0]])), obj); + } + }); + + /** + * Creates a function that is bound to a context. + * Note: `R.bind` does not provide the additional argument-binding capabilities of + * [Function.prototype.bind](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind). + * + * @func + * @memberOf R + * @since v0.6.0 + * @category Function + * @category Object + * @sig (* -> *) -> {*} -> (* -> *) + * @param {Function} fn The function to bind to context + * @param {Object} thisObj The context to bind `fn` to + * @return {Function} A function that will execute in the context of `thisObj`. + * @see R.partial + */ + var bind = _curry2(function bind(fn, thisObj) { + return _arity(fn.length, function () { + return fn.apply(thisObj, arguments); + }); + }); + + /** + * Restricts a number to be within a range. + * + * Also works for other ordered types such as Strings and Dates. + * + * @func + * @memberOf R + * @since v0.20.0 + * @category Relation + * @sig Ord a => a -> a -> a -> a + * @param {Number} minimum number + * @param {Number} maximum number + * @param {Number} value to be clamped + * @return {Number} Returns the clamped value + * @example + * + * R.clamp(1, 10, -1) // => 1 + * R.clamp(1, 10, 11) // => 10 + * R.clamp(1, 10, 4) // => 4 + */ + var clamp = _curry3(function clamp(min, max, value) { + if (min > max) { + throw new Error('min must not be greater than max in clamp(min, max, value)'); + } + return value < min ? min : value > max ? max : value; + }); + + /** + * Makes a comparator function out of a function that reports whether the first + * element is less than the second. + * + * @func + * @memberOf R + * @since v0.1.0 + * @category Function + * @sig (a, b -> Boolean) -> (a, b -> Number) + * @param {Function} pred A predicate function of arity two. + * @return {Function} A Function :: a -> b -> Int that returns `-1` if a < b, `1` if b < a, otherwise `0`. + * @example + * + * var cmp = R.comparator((a, b) => a.age < b.age); + * var people = [ + * // ... + * ]; + * R.sort(cmp, people); + */ + var comparator = _curry1(function comparator(pred) { + return function (a, b) { + return pred(a, b) ? -1 : pred(b, a) ? 1 : 0; + }; + }); + + /** + * Returns a curried equivalent of the provided function, with the specified + * arity. The curried function has two unusual capabilities. First, its + * arguments needn't be provided one at a time. If `g` is `R.curryN(3, f)`, the + * following are equivalent: + * + * - `g(1)(2)(3)` + * - `g(1)(2, 3)` + * - `g(1, 2)(3)` + * - `g(1, 2, 3)` + * + * Secondly, the special placeholder value `R.__` may be used to specify + * "gaps", allowing partial application of any combination of arguments, + * regardless of their positions. If `g` is as above and `_` is `R.__`, the + * following are equivalent: + * + * - `g(1, 2, 3)` + * - `g(_, 2, 3)(1)` + * - `g(_, _, 3)(1)(2)` + * - `g(_, _, 3)(1, 2)` + * - `g(_, 2)(1)(3)` + * - `g(_, 2)(1, 3)` + * - `g(_, 2)(_, 3)(1)` + * + * @func + * @memberOf R + * @since v0.5.0 + * @category Function + * @sig Number -> (* -> a) -> (* -> a) + * @param {Number} length The arity for the returned function. + * @param {Function} fn The function to curry. + * @return {Function} A new, curried function. + * @see R.curry + * @example + * + * var sumArgs = (...args) => R.sum(args); + * + * var curriedAddFourNumbers = R.curryN(4, sumArgs); + * var f = curriedAddFourNumbers(1, 2); + * var g = f(3); + * g(4); //=> 10 + */ + var curryN = _curry2(function curryN(length, fn) { + if (length === 1) { + return _curry1(fn); + } + return _arity(length, _curryN(length, [], fn)); + }); + + /** + * Decrements its argument. + * + * @func + * @memberOf R + * @since v0.9.0 + * @category Math + * @sig Number -> Number + * @param {Number} n + * @return {Number} + * @see R.inc + * @example + * + * R.dec(42); //=> 41 + */ + var dec = add(-1); + + /** + * Returns the second argument if it is not `null`, `undefined` or `NaN` + * otherwise the first argument is returned. + * + * @func + * @memberOf R + * @since v0.10.0 + * @category Logic + * @sig a -> b -> a | b + * @param {a} val The default value. + * @param {b} val The value to return if it is not null or undefined + * @return {*} The the second value or the default value + * @example + * + * var defaultTo42 = R.defaultTo(42); + * + * defaultTo42(null); //=> 42 + * defaultTo42(undefined); //=> 42 + * defaultTo42('Ramda'); //=> 'Ramda' + * defaultTo42(parseInt('string')); //=> 42 + */ + var defaultTo = _curry2(function defaultTo(d, v) { + return v == null || v !== v ? d : v; + }); + + /** + * Finds the set (i.e. no duplicates) of all elements in the first list not + * contained in the second list. Duplication is determined according to the + * value returned by applying the supplied predicate to two list elements. + * + * @func + * @memberOf R + * @since v0.1.0 + * @category Relation + * @sig (a -> a -> Boolean) -> [*] -> [*] -> [*] + * @param {Function} pred A predicate used to test whether two items are equal. + * @param {Array} list1 The first list. + * @param {Array} list2 The second list. + * @return {Array} The elements in `list1` that are not in `list2`. + * @see R.difference + * @example + * + * var cmp = (x, y) => x.a === y.a; + * var l1 = [{a: 1}, {a: 2}, {a: 3}]; + * var l2 = [{a: 3}, {a: 4}]; + * R.differenceWith(cmp, l1, l2); //=> [{a: 1}, {a: 2}] + */ + var differenceWith = _curry3(function differenceWith(pred, first, second) { + var out = []; + var idx = 0; + var firstLen = first.length; + while (idx < firstLen) { + if (!_containsWith(pred, first[idx], second) && !_containsWith(pred, first[idx], out)) { + out.push(first[idx]); + } + idx += 1; + } + return out; + }); + + /** + * Returns a new object that does not contain a `prop` property. + * + * @func + * @memberOf R + * @since v0.10.0 + * @category Object + * @sig String -> {k: v} -> {k: v} + * @param {String} prop the name of the property to dissociate + * @param {Object} obj the object to clone + * @return {Object} a new object similar to the original but without the specified property + * @see R.assoc + * @example + * + * R.dissoc('b', {a: 1, b: 2, c: 3}); //=> {a: 1, c: 3} + */ + var dissoc = _curry2(function dissoc(prop, obj) { + var result = {}; + for (var p in obj) { + if (p !== prop) { + result[p] = obj[p]; + } + } + return result; + }); + + /** + * Makes a shallow clone of an object, omitting the property at the given path. + * Note that this copies and flattens prototype properties onto the new object + * as well. All non-primitive properties are copied by reference. + * + * @func + * @memberOf R + * @since v0.11.0 + * @category Object + * @sig [String] -> {k: v} -> {k: v} + * @param {Array} path the path to set + * @param {Object} obj the object to clone + * @return {Object} a new object without the property at path + * @see R.assocPath + * @example + * + * R.dissocPath(['a', 'b', 'c'], {a: {b: {c: 42}}}); //=> {a: {b: {}}} + */ + var dissocPath = _curry2(function dissocPath(path, obj) { + switch (path.length) { + case 0: + return obj; + case 1: + return dissoc(path[0], obj); + default: + var head = path[0]; + var tail = _slice(path, 1); + return obj[head] == null ? obj : assoc(head, dissocPath(tail, obj[head]), obj); + } + }); + + /** + * Divides two numbers. Equivalent to `a / b`. + * + * @func + * @memberOf R + * @since v0.1.0 + * @category Math + * @sig Number -> Number -> Number + * @param {Number} a The first value. + * @param {Number} b The second value. + * @return {Number} The result of `a / b`. + * @see R.multiply + * @example + * + * R.divide(71, 100); //=> 0.71 + * + * var half = R.divide(R.__, 2); + * half(42); //=> 21 + * + * var reciprocal = R.divide(1); + * reciprocal(4); //=> 0.25 + */ + var divide = _curry2(function divide(a, b) { + return a / b; + }); + + /** + * Returns a new list containing the last `n` elements of a given list, passing + * each value to the supplied predicate function, skipping elements while the + * predicate function returns `true`. The predicate function is passed one + * argument: *(value)*. + * + * Dispatches to the `dropWhile` method of the second argument, if present. + * + * Acts as a transducer if a transformer is given in list position. + * + * @func + * @memberOf R + * @since v0.9.0 + * @category List + * @sig (a -> Boolean) -> [a] -> [a] + * @param {Function} fn The function called per iteration. + * @param {Array} list The collection to iterate over. + * @return {Array} A new array. + * @see R.takeWhile, R.transduce, R.addIndex + * @example + * + * var lteTwo = x => x <= 2; + * + * R.dropWhile(lteTwo, [1, 2, 3, 4, 3, 2, 1]); //=> [3, 4, 3, 2, 1] + */ + var dropWhile = _curry2(_dispatchable('dropWhile', _xdropWhile, function dropWhile(pred, list) { + var idx = 0; + var len = list.length; + while (idx < len && pred(list[idx])) { + idx += 1; + } + return _slice(list, idx); + })); + + /** + * Returns the empty value of its argument's type. Ramda defines the empty + * value of Array (`[]`), Object (`{}`), String (`''`), and Arguments. Other + * types are supported if they define `.empty` and/or + * `.prototype.empty`. + * + * Dispatches to the `empty` method of the first argument, if present. + * + * @func + * @memberOf R + * @since v0.3.0 + * @category Function + * @sig a -> a + * @param {*} x + * @return {*} + * @example + * + * R.empty(Just(42)); //=> Nothing() + * R.empty([1, 2, 3]); //=> [] + * R.empty('unicorns'); //=> '' + * R.empty({x: 1, y: 2}); //=> {} + */ + // else + var empty = _curry1(function empty(x) { + return x != null && typeof x.empty === 'function' ? x.empty() : x != null && x.constructor != null && typeof x.constructor.empty === 'function' ? x.constructor.empty() : _isArray(x) ? [] : _isString(x) ? '' : _isObject(x) ? {} : _isArguments(x) ? function () { + return arguments; + }() : // else + void 0; + }); + + /** + * Creates a new object by recursively evolving a shallow copy of `object`, + * according to the `transformation` functions. All non-primitive properties + * are copied by reference. + * + * A `transformation` function will not be invoked if its corresponding key + * does not exist in the evolved object. + * + * @func + * @memberOf R + * @since v0.9.0 + * @category Object + * @sig {k: (v -> v)} -> {k: v} -> {k: v} + * @param {Object} transformations The object specifying transformation functions to apply + * to the object. + * @param {Object} object The object to be transformed. + * @return {Object} The transformed object. + * @example + * + * var tomato = {firstName: ' Tomato ', data: {elapsed: 100, remaining: 1400}, id:123}; + * var transformations = { + * firstName: R.trim, + * lastName: R.trim, // Will not get invoked. + * data: {elapsed: R.add(1), remaining: R.add(-1)} + * }; + * R.evolve(transformations, tomato); //=> {firstName: 'Tomato', data: {elapsed: 101, remaining: 1399}, id:123} + */ + var evolve = _curry2(function evolve(transformations, object) { + var result = {}; + var transformation, key, type; + for (key in object) { + transformation = transformations[key]; + type = typeof transformation; + result[key] = type === 'function' ? transformation(object[key]) : type === 'object' ? evolve(transformations[key], object[key]) : object[key]; + } + return result; + }); + + /** + * Returns the first element of the list which matches the predicate, or + * `undefined` if no element matches. + * + * Dispatches to the `find` method of the second argument, if present. + * + * Acts as a transducer if a transformer is given in list position. + * + * @func + * @memberOf R + * @since v0.1.0 + * @category List + * @sig (a -> Boolean) -> [a] -> a | undefined + * @param {Function} fn The predicate function used to determine if the element is the + * desired one. + * @param {Array} list The array to consider. + * @return {Object} The element found, or `undefined`. + * @see R.transduce + * @example + * + * var xs = [{a: 1}, {a: 2}, {a: 3}]; + * R.find(R.propEq('a', 2))(xs); //=> {a: 2} + * R.find(R.propEq('a', 4))(xs); //=> undefined + */ + var find = _curry2(_dispatchable('find', _xfind, function find(fn, list) { + var idx = 0; + var len = list.length; + while (idx < len) { + if (fn(list[idx])) { + return list[idx]; + } + idx += 1; + } + })); + + /** + * Returns the index of the first element of the list which matches the + * predicate, or `-1` if no element matches. + * + * Dispatches to the `findIndex` method of the second argument, if present. + * + * Acts as a transducer if a transformer is given in list position. + * + * @func + * @memberOf R + * @since v0.1.1 + * @category List + * @sig (a -> Boolean) -> [a] -> Number + * @param {Function} fn The predicate function used to determine if the element is the + * desired one. + * @param {Array} list The array to consider. + * @return {Number} The index of the element found, or `-1`. + * @see R.transduce + * @example + * + * var xs = [{a: 1}, {a: 2}, {a: 3}]; + * R.findIndex(R.propEq('a', 2))(xs); //=> 1 + * R.findIndex(R.propEq('a', 4))(xs); //=> -1 + */ + var findIndex = _curry2(_dispatchable('findIndex', _xfindIndex, function findIndex(fn, list) { + var idx = 0; + var len = list.length; + while (idx < len) { + if (fn(list[idx])) { + return idx; + } + idx += 1; + } + return -1; + })); + + /** + * Returns the last element of the list which matches the predicate, or + * `undefined` if no element matches. + * + * Dispatches to the `findLast` method of the second argument, if present. + * + * Acts as a transducer if a transformer is given in list position. + * + * @func + * @memberOf R + * @since v0.1.1 + * @category List + * @sig (a -> Boolean) -> [a] -> a | undefined + * @param {Function} fn The predicate function used to determine if the element is the + * desired one. + * @param {Array} list The array to consider. + * @return {Object} The element found, or `undefined`. + * @see R.transduce + * @example + * + * var xs = [{a: 1, b: 0}, {a:1, b: 1}]; + * R.findLast(R.propEq('a', 1))(xs); //=> {a: 1, b: 1} + * R.findLast(R.propEq('a', 4))(xs); //=> undefined + */ + var findLast = _curry2(_dispatchable('findLast', _xfindLast, function findLast(fn, list) { + var idx = list.length - 1; + while (idx >= 0) { + if (fn(list[idx])) { + return list[idx]; + } + idx -= 1; + } + })); + + /** + * Returns the index of the last element of the list which matches the + * predicate, or `-1` if no element matches. + * + * Dispatches to the `findLastIndex` method of the second argument, if present. + * + * Acts as a transducer if a transformer is given in list position. + * + * @func + * @memberOf R + * @since v0.1.1 + * @category List + * @sig (a -> Boolean) -> [a] -> Number + * @param {Function} fn The predicate function used to determine if the element is the + * desired one. + * @param {Array} list The array to consider. + * @return {Number} The index of the element found, or `-1`. + * @see R.transduce + * @example + * + * var xs = [{a: 1, b: 0}, {a:1, b: 1}]; + * R.findLastIndex(R.propEq('a', 1))(xs); //=> 1 + * R.findLastIndex(R.propEq('a', 4))(xs); //=> -1 + */ + var findLastIndex = _curry2(_dispatchable('findLastIndex', _xfindLastIndex, function findLastIndex(fn, list) { + var idx = list.length - 1; + while (idx >= 0) { + if (fn(list[idx])) { + return idx; + } + idx -= 1; + } + return -1; + })); + + /** + * Iterate over an input `list`, calling a provided function `fn` for each + * element in the list. + * + * `fn` receives one argument: *(value)*. + * + * Note: `R.forEach` does not skip deleted or unassigned indices (sparse + * arrays), unlike the native `Array.prototype.forEach` method. For more + * details on this behavior, see: + * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach#Description + * + * Also note that, unlike `Array.prototype.forEach`, Ramda's `forEach` returns + * the original array. In some libraries this function is named `each`. + * + * Dispatches to the `forEach` method of the second argument, if present. + * + * @func + * @memberOf R + * @since v0.1.1 + * @category List + * @sig (a -> *) -> [a] -> [a] + * @param {Function} fn The function to invoke. Receives one argument, `value`. + * @param {Array} list The list to iterate over. + * @return {Array} The original list. + * @see R.addIndex + * @example + * + * var printXPlusFive = x => console.log(x + 5); + * R.forEach(printXPlusFive, [1, 2, 3]); //=> [1, 2, 3] + * //-> 6 + * //-> 7 + * //-> 8 + */ + var forEach = _curry2(_checkForMethod('forEach', function forEach(fn, list) { + var len = list.length; + var idx = 0; + while (idx < len) { + fn(list[idx]); + idx += 1; + } + return list; + })); + + /** + * Creates a new object out of a list key-value pairs. + * + * @func + * @memberOf R + * @since v0.3.0 + * @category List + * @sig [[k,v]] -> {k: v} + * @param {Array} pairs An array of two-element arrays that will be the keys and values of the output object. + * @return {Object} The object made by pairing up `keys` and `values`. + * @see R.toPairs, R.pair + * @example + * + * R.fromPairs([['a', 1], ['b', 2], ['c', 3]]); //=> {a: 1, b: 2, c: 3} + */ + var fromPairs = _curry1(function fromPairs(pairs) { + var idx = 0; + var len = pairs.length; + var out = {}; + while (idx < len) { + if (_isArray(pairs[idx]) && pairs[idx].length) { + out[pairs[idx][0]] = pairs[idx][1]; + } + idx += 1; + } + return out; + }); + + /** + * Takes a list and returns a list of lists where each sublist's elements are + * all "equal" according to the provided equality function. + * + * @func + * @memberOf R + * @since v0.21.0 + * @category List + * @sig (a, a -> Boolean) -> [a] -> [[a]] + * @param {Function} fn Function for determining whether two given (adjacent) + * elements should be in the same group + * @param {Array} list The array to group. Also accepts a string, which will be + * treated as a list of characters. + * @return {List} A list that contains sublists of equal elements, + * whose concatenations is equal to the original list. + * @example + * + * groupWith(R.equals, [0, 1, 1, 2, 3, 5, 8, 13, 21]) + * // [[0], [1, 1], [2, 3, 5, 8, 13, 21]] + * + * groupWith((a, b) => a % 2 === b % 2, [0, 1, 1, 2, 3, 5, 8, 13, 21]) + * // [[0], [1, 1], [2], [3, 5], [8], [13, 21]] + * + * R.groupWith(R.eqBy(isVowel), 'aestiou') + * // ['ae', 'st', 'iou'] + */ + var groupWith = _curry2(function (fn, list) { + var res = []; + var idx = 0; + var len = list.length; + while (idx < len) { + var nextidx = idx + 1; + while (nextidx < len && fn(list[idx], list[nextidx])) { + nextidx += 1; + } + res.push(list.slice(idx, nextidx)); + idx = nextidx; + } + return res; + }); + + /** + * Returns `true` if the first argument is greater than the second; `false` + * otherwise. + * + * @func + * @memberOf R + * @since v0.1.0 + * @category Relation + * @sig Ord a => a -> a -> Boolean + * @param {*} a + * @param {*} b + * @return {Boolean} + * @see R.lt + * @example + * + * R.gt(2, 1); //=> true + * R.gt(2, 2); //=> false + * R.gt(2, 3); //=> false + * R.gt('a', 'z'); //=> false + * R.gt('z', 'a'); //=> true + */ + var gt = _curry2(function gt(a, b) { + return a > b; + }); + + /** + * Returns `true` if the first argument is greater than or equal to the second; + * `false` otherwise. + * + * @func + * @memberOf R + * @since v0.1.0 + * @category Relation + * @sig Ord a => a -> a -> Boolean + * @param {Number} a + * @param {Number} b + * @return {Boolean} + * @see R.lte + * @example + * + * R.gte(2, 1); //=> true + * R.gte(2, 2); //=> true + * R.gte(2, 3); //=> false + * R.gte('a', 'z'); //=> false + * R.gte('z', 'a'); //=> true + */ + var gte = _curry2(function gte(a, b) { + return a >= b; + }); + + /** + * Returns whether or not an object has an own property with the specified name + * + * @func + * @memberOf R + * @since v0.7.0 + * @category Object + * @sig s -> {s: x} -> Boolean + * @param {String} prop The name of the property to check for. + * @param {Object} obj The object to query. + * @return {Boolean} Whether the property exists. + * @example + * + * var hasName = R.has('name'); + * hasName({name: 'alice'}); //=> true + * hasName({name: 'bob'}); //=> true + * hasName({}); //=> false + * + * var point = {x: 0, y: 0}; + * var pointHas = R.has(R.__, point); + * pointHas('x'); //=> true + * pointHas('y'); //=> true + * pointHas('z'); //=> false + */ + var has = _curry2(_has); + + /** + * Returns whether or not an object or its prototype chain has a property with + * the specified name + * + * @func + * @memberOf R + * @since v0.7.0 + * @category Object + * @sig s -> {s: x} -> Boolean + * @param {String} prop The name of the property to check for. + * @param {Object} obj The object to query. + * @return {Boolean} Whether the property exists. + * @example + * + * function Rectangle(width, height) { + * this.width = width; + * this.height = height; + * } + * Rectangle.prototype.area = function() { + * return this.width * this.height; + * }; + * + * var square = new Rectangle(2, 2); + * R.hasIn('width', square); //=> true + * R.hasIn('area', square); //=> true + */ + var hasIn = _curry2(function hasIn(prop, obj) { + return prop in obj; + }); + + /** + * Returns true if its arguments are identical, false otherwise. Values are + * identical if they reference the same memory. `NaN` is identical to `NaN`; + * `0` and `-0` are not identical. + * + * @func + * @memberOf R + * @since v0.15.0 + * @category Relation + * @sig a -> a -> Boolean + * @param {*} a + * @param {*} b + * @return {Boolean} + * @example + * + * var o = {}; + * R.identical(o, o); //=> true + * R.identical(1, 1); //=> true + * R.identical(1, '1'); //=> false + * R.identical([], []); //=> false + * R.identical(0, -0); //=> false + * R.identical(NaN, NaN); //=> true + */ + // SameValue algorithm + // Steps 1-5, 7-10 + // Steps 6.b-6.e: +0 != -0 + // Step 6.a: NaN == NaN + var identical = _curry2(function identical(a, b) { + // SameValue algorithm + if (a === b) { + // Steps 1-5, 7-10 + // Steps 6.b-6.e: +0 != -0 + return a !== 0 || 1 / a === 1 / b; + } else { + // Step 6.a: NaN == NaN + return a !== a && b !== b; + } + }); + + /** + * A function that does nothing but return the parameter supplied to it. Good + * as a default or placeholder function. + * + * @func + * @memberOf R + * @since v0.1.0 + * @category Function + * @sig a -> a + * @param {*} x The value to return. + * @return {*} The input value, `x`. + * @example + * + * R.identity(1); //=> 1 + * + * var obj = {}; + * R.identity(obj) === obj; //=> true + */ + var identity = _curry1(_identity); + + /** + * Creates a function that will process either the `onTrue` or the `onFalse` + * function depending upon the result of the `condition` predicate. + * + * @func + * @memberOf R + * @since v0.8.0 + * @category Logic + * @sig (*... -> Boolean) -> (*... -> *) -> (*... -> *) -> (*... -> *) + * @param {Function} condition A predicate function + * @param {Function} onTrue A function to invoke when the `condition` evaluates to a truthy value. + * @param {Function} onFalse A function to invoke when the `condition` evaluates to a falsy value. + * @return {Function} A new unary function that will process either the `onTrue` or the `onFalse` + * function depending upon the result of the `condition` predicate. + * @see R.unless, R.when + * @example + * + * var incCount = R.ifElse( + * R.has('count'), + * R.over(R.lensProp('count'), R.inc), + * R.assoc('count', 1) + * ); + * incCount({}); //=> { count: 1 } + * incCount({ count: 1 }); //=> { count: 2 } + */ + var ifElse = _curry3(function ifElse(condition, onTrue, onFalse) { + return curryN(Math.max(condition.length, onTrue.length, onFalse.length), function _ifElse() { + return condition.apply(this, arguments) ? onTrue.apply(this, arguments) : onFalse.apply(this, arguments); + }); + }); + + /** + * Increments its argument. + * + * @func + * @memberOf R + * @since v0.9.0 + * @category Math + * @sig Number -> Number + * @param {Number} n + * @return {Number} + * @see R.dec + * @example + * + * R.inc(42); //=> 43 + */ + var inc = add(1); + + /** + * Inserts the supplied element into the list, at index `index`. _Note that + * this is not destructive_: it returns a copy of the list with the changes. + * No lists have been harmed in the application of this function. + * + * @func + * @memberOf R + * @since v0.2.2 + * @category List + * @sig Number -> a -> [a] -> [a] + * @param {Number} index The position to insert the element + * @param {*} elt The element to insert into the Array + * @param {Array} list The list to insert into + * @return {Array} A new Array with `elt` inserted at `index`. + * @example + * + * R.insert(2, 'x', [1,2,3,4]); //=> [1,2,'x',3,4] + */ + var insert = _curry3(function insert(idx, elt, list) { + idx = idx < list.length && idx >= 0 ? idx : list.length; + var result = _slice(list); + result.splice(idx, 0, elt); + return result; + }); + + /** + * Inserts the sub-list into the list, at index `index`. _Note that this is not + * destructive_: it returns a copy of the list with the changes. + * No lists have been harmed in the application of this function. + * + * @func + * @memberOf R + * @since v0.9.0 + * @category List + * @sig Number -> [a] -> [a] -> [a] + * @param {Number} index The position to insert the sub-list + * @param {Array} elts The sub-list to insert into the Array + * @param {Array} list The list to insert the sub-list into + * @return {Array} A new Array with `elts` inserted starting at `index`. + * @example + * + * R.insertAll(2, ['x','y','z'], [1,2,3,4]); //=> [1,2,'x','y','z',3,4] + */ + var insertAll = _curry3(function insertAll(idx, elts, list) { + idx = idx < list.length && idx >= 0 ? idx : list.length; + return _concat(_concat(_slice(list, 0, idx), elts), _slice(list, idx)); + }); + + /** + * Creates a new list with the separator interposed between elements. + * + * Dispatches to the `intersperse` method of the second argument, if present. + * + * @func + * @memberOf R + * @since v0.14.0 + * @category List + * @sig a -> [a] -> [a] + * @param {*} separator The element to add to the list. + * @param {Array} list The list to be interposed. + * @return {Array} The new list. + * @example + * + * R.intersperse('n', ['ba', 'a', 'a']); //=> ['ba', 'n', 'a', 'n', 'a'] + */ + var intersperse = _curry2(_checkForMethod('intersperse', function intersperse(separator, list) { + var out = []; + var idx = 0; + var length = list.length; + while (idx < length) { + if (idx === length - 1) { + out.push(list[idx]); + } else { + out.push(list[idx], separator); + } + idx += 1; + } + return out; + })); + + /** + * See if an object (`val`) is an instance of the supplied constructor. This + * function will check up the inheritance chain, if any. + * + * @func + * @memberOf R + * @since v0.3.0 + * @category Type + * @sig (* -> {*}) -> a -> Boolean + * @param {Object} ctor A constructor + * @param {*} val The value to test + * @return {Boolean} + * @example + * + * R.is(Object, {}); //=> true + * R.is(Number, 1); //=> true + * R.is(Object, 1); //=> false + * R.is(String, 's'); //=> true + * R.is(String, new String('')); //=> true + * R.is(Object, new String('')); //=> true + * R.is(Object, 's'); //=> false + * R.is(Number, {}); //=> false + */ + var is = _curry2(function is(Ctor, val) { + return val != null && val.constructor === Ctor || val instanceof Ctor; + }); + + /** + * Tests whether or not an object is similar to an array. + * + * @func + * @memberOf R + * @since v0.5.0 + * @category Type + * @category List + * @sig * -> Boolean + * @param {*} x The object to test. + * @return {Boolean} `true` if `x` has a numeric length property and extreme indices defined; `false` otherwise. + * @example + * + * R.isArrayLike([]); //=> true + * R.isArrayLike(true); //=> false + * R.isArrayLike({}); //=> false + * R.isArrayLike({length: 10}); //=> false + * R.isArrayLike({0: 'zero', 9: 'nine', length: 10}); //=> true + */ + var isArrayLike = _curry1(function isArrayLike(x) { + if (_isArray(x)) { + return true; + } + if (!x) { + return false; + } + if (typeof x !== 'object') { + return false; + } + if (x instanceof String) { + return false; + } + if (x.nodeType === 1) { + return !!x.length; + } + if (x.length === 0) { + return true; + } + if (x.length > 0) { + return x.hasOwnProperty(0) && x.hasOwnProperty(x.length - 1); + } + return false; + }); + + /** + * Checks if the input value is `null` or `undefined`. + * + * @func + * @memberOf R + * @since v0.9.0 + * @category Type + * @sig * -> Boolean + * @param {*} x The value to test. + * @return {Boolean} `true` if `x` is `undefined` or `null`, otherwise `false`. + * @example + * + * R.isNil(null); //=> true + * R.isNil(undefined); //=> true + * R.isNil(0); //=> false + * R.isNil([]); //=> false + */ + var isNil = _curry1(function isNil(x) { + return x == null; + }); + + /** + * Returns a list containing the names of all the enumerable own properties of + * the supplied object. + * Note that the order of the output array is not guaranteed to be consistent + * across different JS platforms. + * + * @func + * @memberOf R + * @since v0.1.0 + * @category Object + * @sig {k: v} -> [k] + * @param {Object} obj The object to extract properties from + * @return {Array} An array of the object's own properties. + * @example + * + * R.keys({a: 1, b: 2, c: 3}); //=> ['a', 'b', 'c'] + */ + // cover IE < 9 keys issues + // Safari bug + var keys = function () { + // cover IE < 9 keys issues + var hasEnumBug = !{ toString: null }.propertyIsEnumerable('toString'); + var nonEnumerableProps = [ + 'constructor', + 'valueOf', + 'isPrototypeOf', + 'toString', + 'propertyIsEnumerable', + 'hasOwnProperty', + 'toLocaleString' + ]; + // Safari bug + var hasArgsEnumBug = function () { + 'use strict'; + return arguments.propertyIsEnumerable('length'); + }(); + var contains = function contains(list, item) { + var idx = 0; + while (idx < list.length) { + if (list[idx] === item) { + return true; + } + idx += 1; + } + return false; + }; + return typeof Object.keys === 'function' && !hasArgsEnumBug ? _curry1(function keys(obj) { + return Object(obj) !== obj ? [] : Object.keys(obj); + }) : _curry1(function keys(obj) { + if (Object(obj) !== obj) { + return []; + } + var prop, nIdx; + var ks = []; + var checkArgsLength = hasArgsEnumBug && _isArguments(obj); + for (prop in obj) { + if (_has(prop, obj) && (!checkArgsLength || prop !== 'length')) { + ks[ks.length] = prop; + } + } + if (hasEnumBug) { + nIdx = nonEnumerableProps.length - 1; + while (nIdx >= 0) { + prop = nonEnumerableProps[nIdx]; + if (_has(prop, obj) && !contains(ks, prop)) { + ks[ks.length] = prop; + } + nIdx -= 1; + } + } + return ks; + }); + }(); + + /** + * Returns a list containing the names of all the properties of the supplied + * object, including prototype properties. + * Note that the order of the output array is not guaranteed to be consistent + * across different JS platforms. + * + * @func + * @memberOf R + * @since v0.2.0 + * @category Object + * @sig {k: v} -> [k] + * @param {Object} obj The object to extract properties from + * @return {Array} An array of the object's own and prototype properties. + * @example + * + * var F = function() { this.x = 'X'; }; + * F.prototype.y = 'Y'; + * var f = new F(); + * R.keysIn(f); //=> ['x', 'y'] + */ + var keysIn = _curry1(function keysIn(obj) { + var prop; + var ks = []; + for (prop in obj) { + ks[ks.length] = prop; + } + return ks; + }); + + /** + * Returns the number of elements in the array by returning `list.length`. + * + * @func + * @memberOf R + * @since v0.3.0 + * @category List + * @sig [a] -> Number + * @param {Array} list The array to inspect. + * @return {Number} The length of the array. + * @example + * + * R.length([]); //=> 0 + * R.length([1, 2, 3]); //=> 3 + */ + var length = _curry1(function length(list) { + return list != null && is(Number, list.length) ? list.length : NaN; + }); + + /** + * Returns `true` if the first argument is less than the second; `false` + * otherwise. + * + * @func + * @memberOf R + * @since v0.1.0 + * @category Relation + * @sig Ord a => a -> a -> Boolean + * @param {*} a + * @param {*} b + * @return {Boolean} + * @see R.gt + * @example + * + * R.lt(2, 1); //=> false + * R.lt(2, 2); //=> false + * R.lt(2, 3); //=> true + * R.lt('a', 'z'); //=> true + * R.lt('z', 'a'); //=> false + */ + var lt = _curry2(function lt(a, b) { + return a < b; + }); + + /** + * Returns `true` if the first argument is less than or equal to the second; + * `false` otherwise. + * + * @func + * @memberOf R + * @since v0.1.0 + * @category Relation + * @sig Ord a => a -> a -> Boolean + * @param {Number} a + * @param {Number} b + * @return {Boolean} + * @see R.gte + * @example + * + * R.lte(2, 1); //=> false + * R.lte(2, 2); //=> true + * R.lte(2, 3); //=> true + * R.lte('a', 'z'); //=> true + * R.lte('z', 'a'); //=> false + */ + var lte = _curry2(function lte(a, b) { + return a <= b; + }); + + /** + * The mapAccum function behaves like a combination of map and reduce; it + * applies a function to each element of a list, passing an accumulating + * parameter from left to right, and returning a final value of this + * accumulator together with the new list. + * + * The iterator function receives two arguments, *acc* and *value*, and should + * return a tuple *[acc, value]*. + * + * @func + * @memberOf R + * @since v0.10.0 + * @category List + * @sig (acc -> x -> (acc, y)) -> acc -> [x] -> (acc, [y]) + * @param {Function} fn The function to be called on every element of the input `list`. + * @param {*} acc The accumulator value. + * @param {Array} list The list to iterate over. + * @return {*} The final, accumulated value. + * @see R.addIndex + * @example + * + * var digits = ['1', '2', '3', '4']; + * var appender = (a, b) => [a + b, a + b]; + * + * R.mapAccum(appender, 0, digits); //=> ['01234', ['01', '012', '0123', '01234']] + */ + var mapAccum = _curry3(function mapAccum(fn, acc, list) { + var idx = 0; + var len = list.length; + var result = []; + var tuple = [acc]; + while (idx < len) { + tuple = fn(tuple[0], list[idx]); + result[idx] = tuple[1]; + idx += 1; + } + return [ + tuple[0], + result + ]; + }); + + /** + * The mapAccumRight function behaves like a combination of map and reduce; it + * applies a function to each element of a list, passing an accumulating + * parameter from right to left, and returning a final value of this + * accumulator together with the new list. + * + * Similar to `mapAccum`, except moves through the input list from the right to + * the left. + * + * The iterator function receives two arguments, *acc* and *value*, and should + * return a tuple *[acc, value]*. + * + * @func + * @memberOf R + * @since v0.10.0 + * @category List + * @sig (acc -> x -> (acc, y)) -> acc -> [x] -> (acc, [y]) + * @param {Function} fn The function to be called on every element of the input `list`. + * @param {*} acc The accumulator value. + * @param {Array} list The list to iterate over. + * @return {*} The final, accumulated value. + * @see R.addIndex + * @example + * + * var digits = ['1', '2', '3', '4']; + * var append = (a, b) => [a + b, a + b]; + * + * R.mapAccumRight(append, 0, digits); //=> ['04321', ['04321', '0432', '043', '04']] + */ + var mapAccumRight = _curry3(function mapAccumRight(fn, acc, list) { + var idx = list.length - 1; + var result = []; + var tuple = [acc]; + while (idx >= 0) { + tuple = fn(tuple[0], list[idx]); + result[idx] = tuple[1]; + idx -= 1; + } + return [ + tuple[0], + result + ]; + }); + + /** + * Tests a regular expression against a String. Note that this function will + * return an empty array when there are no matches. This differs from + * [`String.prototype.match`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/match) + * which returns `null` when there are no matches. + * + * @func + * @memberOf R + * @since v0.1.0 + * @category String + * @sig RegExp -> String -> [String | Undefined] + * @param {RegExp} rx A regular expression. + * @param {String} str The string to match against + * @return {Array} The list of matches or empty array. + * @see R.test + * @example + * + * R.match(/([a-z]a)/g, 'bananas'); //=> ['ba', 'na', 'na'] + * R.match(/a/, 'b'); //=> [] + * R.match(/a/, null); //=> TypeError: null does not have a method named "match" + */ + var match = _curry2(function match(rx, str) { + return str.match(rx) || []; + }); + + /** + * mathMod behaves like the modulo operator should mathematically, unlike the + * `%` operator (and by extension, R.modulo). So while "-17 % 5" is -2, + * mathMod(-17, 5) is 3. mathMod requires Integer arguments, and returns NaN + * when the modulus is zero or negative. + * + * @func + * @memberOf R + * @since v0.3.0 + * @category Math + * @sig Number -> Number -> Number + * @param {Number} m The dividend. + * @param {Number} p the modulus. + * @return {Number} The result of `b mod a`. + * @example + * + * R.mathMod(-17, 5); //=> 3 + * R.mathMod(17, 5); //=> 2 + * R.mathMod(17, -5); //=> NaN + * R.mathMod(17, 0); //=> NaN + * R.mathMod(17.2, 5); //=> NaN + * R.mathMod(17, 5.3); //=> NaN + * + * var clock = R.mathMod(R.__, 12); + * clock(15); //=> 3 + * clock(24); //=> 0 + * + * var seventeenMod = R.mathMod(17); + * seventeenMod(3); //=> 2 + * seventeenMod(4); //=> 1 + * seventeenMod(10); //=> 7 + */ + var mathMod = _curry2(function mathMod(m, p) { + if (!_isInteger(m)) { + return NaN; + } + if (!_isInteger(p) || p < 1) { + return NaN; + } + return (m % p + p) % p; + }); + + /** + * Returns the larger of its two arguments. + * + * @func + * @memberOf R + * @since v0.1.0 + * @category Relation + * @sig Ord a => a -> a -> a + * @param {*} a + * @param {*} b + * @return {*} + * @see R.maxBy, R.min + * @example + * + * R.max(789, 123); //=> 789 + * R.max('a', 'b'); //=> 'b' + */ + var max = _curry2(function max(a, b) { + return b > a ? b : a; + }); + + /** + * Takes a function and two values, and returns whichever value produces the + * larger result when passed to the provided function. + * + * @func + * @memberOf R + * @since v0.8.0 + * @category Relation + * @sig Ord b => (a -> b) -> a -> a -> a + * @param {Function} f + * @param {*} a + * @param {*} b + * @return {*} + * @see R.max, R.minBy + * @example + * + * // square :: Number -> Number + * var square = n => n * n; + * + * R.maxBy(square, -3, 2); //=> -3 + * + * R.reduce(R.maxBy(square), 0, [3, -5, 4, 1, -2]); //=> -5 + * R.reduce(R.maxBy(square), 0, []); //=> 0 + */ + var maxBy = _curry3(function maxBy(f, a, b) { + return f(b) > f(a) ? b : a; + }); + + /** + * Create a new object with the own properties of the first object merged with + * the own properties of the second object. If a key exists in both objects, + * the value from the second object will be used. + * + * @func + * @memberOf R + * @since v0.1.0 + * @category Object + * @sig {k: v} -> {k: v} -> {k: v} + * @param {Object} l + * @param {Object} r + * @return {Object} + * @see R.mergeWith, R.mergeWithKey + * @example + * + * R.merge({ 'name': 'fred', 'age': 10 }, { 'age': 40 }); + * //=> { 'name': 'fred', 'age': 40 } + * + * var resetToDefault = R.merge(R.__, {x: 0}); + * resetToDefault({x: 5, y: 2}); //=> {x: 0, y: 2} + */ + var merge = _curry2(function merge(l, r) { + return _assign({}, l, r); + }); + + /** + * Merges a list of objects together into one object. + * + * @func + * @memberOf R + * @since v0.10.0 + * @category List + * @sig [{k: v}] -> {k: v} + * @param {Array} list An array of objects + * @return {Object} A merged object. + * @see R.reduce + * @example + * + * R.mergeAll([{foo:1},{bar:2},{baz:3}]); //=> {foo:1,bar:2,baz:3} + * R.mergeAll([{foo:1},{foo:2},{bar:2}]); //=> {foo:2,bar:2} + */ + var mergeAll = _curry1(function mergeAll(list) { + return _assign.apply(null, [{}].concat(list)); + }); + + /** + * Creates a new object with the own properties of the two provided objects. If + * a key exists in both objects, the provided function is applied to the key + * and the values associated with the key in each object, with the result being + * used as the value associated with the key in the returned object. The key + * will be excluded from the returned object if the resulting value is + * `undefined`. + * + * @func + * @memberOf R + * @since v0.19.0 + * @category Object + * @sig (String -> a -> a -> a) -> {a} -> {a} -> {a} + * @param {Function} fn + * @param {Object} l + * @param {Object} r + * @return {Object} + * @see R.merge, R.mergeWith + * @example + * + * let concatValues = (k, l, r) => k == 'values' ? R.concat(l, r) : r + * R.mergeWithKey(concatValues, + * { a: true, thing: 'foo', values: [10, 20] }, + * { b: true, thing: 'bar', values: [15, 35] }); + * //=> { a: true, b: true, thing: 'bar', values: [10, 20, 15, 35] } + */ + var mergeWithKey = _curry3(function mergeWithKey(fn, l, r) { + var result = {}; + var k; + for (k in l) { + if (_has(k, l)) { + result[k] = _has(k, r) ? fn(k, l[k], r[k]) : l[k]; + } + } + for (k in r) { + if (_has(k, r) && !_has(k, result)) { + result[k] = r[k]; + } + } + return result; + }); + + /** + * Returns the smaller of its two arguments. + * + * @func + * @memberOf R + * @since v0.1.0 + * @category Relation + * @sig Ord a => a -> a -> a + * @param {*} a + * @param {*} b + * @return {*} + * @see R.minBy, R.max + * @example + * + * R.min(789, 123); //=> 123 + * R.min('a', 'b'); //=> 'a' + */ + var min = _curry2(function min(a, b) { + return b < a ? b : a; + }); + + /** + * Takes a function and two values, and returns whichever value produces the + * smaller result when passed to the provided function. + * + * @func + * @memberOf R + * @since v0.8.0 + * @category Relation + * @sig Ord b => (a -> b) -> a -> a -> a + * @param {Function} f + * @param {*} a + * @param {*} b + * @return {*} + * @see R.min, R.maxBy + * @example + * + * // square :: Number -> Number + * var square = n => n * n; + * + * R.minBy(square, -3, 2); //=> 2 + * + * R.reduce(R.minBy(square), Infinity, [3, -5, 4, 1, -2]); //=> 1 + * R.reduce(R.minBy(square), Infinity, []); //=> Infinity + */ + var minBy = _curry3(function minBy(f, a, b) { + return f(b) < f(a) ? b : a; + }); + + /** + * Divides the second parameter by the first and returns the remainder. Note + * that this function preserves the JavaScript-style behavior for modulo. For + * mathematical modulo see `mathMod`. + * + * @func + * @memberOf R + * @since v0.1.1 + * @category Math + * @sig Number -> Number -> Number + * @param {Number} a The value to the divide. + * @param {Number} b The pseudo-modulus + * @return {Number} The result of `b % a`. + * @see R.mathMod + * @example + * + * R.modulo(17, 3); //=> 2 + * // JS behavior: + * R.modulo(-17, 3); //=> -2 + * R.modulo(17, -3); //=> 2 + * + * var isOdd = R.modulo(R.__, 2); + * isOdd(42); //=> 0 + * isOdd(21); //=> 1 + */ + var modulo = _curry2(function modulo(a, b) { + return a % b; + }); + + /** + * Multiplies two numbers. Equivalent to `a * b` but curried. + * + * @func + * @memberOf R + * @since v0.1.0 + * @category Math + * @sig Number -> Number -> Number + * @param {Number} a The first value. + * @param {Number} b The second value. + * @return {Number} The result of `a * b`. + * @see R.divide + * @example + * + * var double = R.multiply(2); + * var triple = R.multiply(3); + * double(3); //=> 6 + * triple(4); //=> 12 + * R.multiply(2, 5); //=> 10 + */ + var multiply = _curry2(function multiply(a, b) { + return a * b; + }); + + /** + * Wraps a function of any arity (including nullary) in a function that accepts + * exactly `n` parameters. Any extraneous parameters will not be passed to the + * supplied function. + * + * @func + * @memberOf R + * @since v0.1.0 + * @category Function + * @sig Number -> (* -> a) -> (* -> a) + * @param {Number} n The desired arity of the new function. + * @param {Function} fn The function to wrap. + * @return {Function} A new function wrapping `fn`. The new function is guaranteed to be of + * arity `n`. + * @example + * + * var takesTwoArgs = (a, b) => [a, b]; + * + * takesTwoArgs.length; //=> 2 + * takesTwoArgs(1, 2); //=> [1, 2] + * + * var takesOneArg = R.nAry(1, takesTwoArgs); + * takesOneArg.length; //=> 1 + * // Only `n` arguments are passed to the wrapped function + * takesOneArg(1, 2); //=> [1, undefined] + */ + var nAry = _curry2(function nAry(n, fn) { + switch (n) { + case 0: + return function () { + return fn.call(this); + }; + case 1: + return function (a0) { + return fn.call(this, a0); + }; + case 2: + return function (a0, a1) { + return fn.call(this, a0, a1); + }; + case 3: + return function (a0, a1, a2) { + return fn.call(this, a0, a1, a2); + }; + case 4: + return function (a0, a1, a2, a3) { + return fn.call(this, a0, a1, a2, a3); + }; + case 5: + return function (a0, a1, a2, a3, a4) { + return fn.call(this, a0, a1, a2, a3, a4); + }; + case 6: + return function (a0, a1, a2, a3, a4, a5) { + return fn.call(this, a0, a1, a2, a3, a4, a5); + }; + case 7: + return function (a0, a1, a2, a3, a4, a5, a6) { + return fn.call(this, a0, a1, a2, a3, a4, a5, a6); + }; + case 8: + return function (a0, a1, a2, a3, a4, a5, a6, a7) { + return fn.call(this, a0, a1, a2, a3, a4, a5, a6, a7); + }; + case 9: + return function (a0, a1, a2, a3, a4, a5, a6, a7, a8) { + return fn.call(this, a0, a1, a2, a3, a4, a5, a6, a7, a8); + }; + case 10: + return function (a0, a1, a2, a3, a4, a5, a6, a7, a8, a9) { + return fn.call(this, a0, a1, a2, a3, a4, a5, a6, a7, a8, a9); + }; + default: + throw new Error('First argument to nAry must be a non-negative integer no greater than ten'); + } + }); + + /** + * Negates its argument. + * + * @func + * @memberOf R + * @since v0.9.0 + * @category Math + * @sig Number -> Number + * @param {Number} n + * @return {Number} + * @example + * + * R.negate(42); //=> -42 + */ + var negate = _curry1(function negate(n) { + return -n; + }); + + /** + * Returns `true` if no elements of the list match the predicate, `false` + * otherwise. + * + * Dispatches to the `any` method of the second argument, if present. + * + * @func + * @memberOf R + * @since v0.12.0 + * @category List + * @sig (a -> Boolean) -> [a] -> Boolean + * @param {Function} fn The predicate function. + * @param {Array} list The array to consider. + * @return {Boolean} `true` if the predicate is not satisfied by every element, `false` otherwise. + * @see R.all, R.any + * @example + * + * var isEven = n => n % 2 === 0; + * + * R.none(isEven, [1, 3, 5, 7, 9, 11]); //=> true + * R.none(isEven, [1, 3, 5, 7, 8, 11]); //=> false + */ + var none = _curry2(_complement(_dispatchable('any', _xany, any))); + + /** + * A function that returns the `!` of its argument. It will return `true` when + * passed false-y value, and `false` when passed a truth-y one. + * + * @func + * @memberOf R + * @since v0.1.0 + * @category Logic + * @sig * -> Boolean + * @param {*} a any value + * @return {Boolean} the logical inverse of passed argument. + * @see R.complement + * @example + * + * R.not(true); //=> false + * R.not(false); //=> true + * R.not(0); => true + * R.not(1); => false + */ + var not = _curry1(function not(a) { + return !a; + }); + + /** + * Returns the nth element of the given list or string. If n is negative the + * element at index length + n is returned. + * + * @func + * @memberOf R + * @since v0.1.0 + * @category List + * @sig Number -> [a] -> a | Undefined + * @sig Number -> String -> String + * @param {Number} offset + * @param {*} list + * @return {*} + * @example + * + * var list = ['foo', 'bar', 'baz', 'quux']; + * R.nth(1, list); //=> 'bar' + * R.nth(-1, list); //=> 'quux' + * R.nth(-99, list); //=> undefined + * + * R.nth(2, 'abc'); //=> 'c' + * R.nth(3, 'abc'); //=> '' + */ + var nth = _curry2(function nth(offset, list) { + var idx = offset < 0 ? list.length + offset : offset; + return _isString(list) ? list.charAt(idx) : list[idx]; + }); + + /** + * Returns a function which returns its nth argument. + * + * @func + * @memberOf R + * @since v0.9.0 + * @category Function + * @sig Number -> *... -> * + * @param {Number} n + * @return {Function} + * @example + * + * R.nthArg(1)('a', 'b', 'c'); //=> 'b' + * R.nthArg(-1)('a', 'b', 'c'); //=> 'c' + */ + var nthArg = _curry1(function nthArg(n) { + return function () { + return nth(n, arguments); + }; + }); + + /** + * Creates an object containing a single key:value pair. + * + * @func + * @memberOf R + * @since v0.18.0 + * @category Object + * @sig String -> a -> {String:a} + * @param {String} key + * @param {*} val + * @return {Object} + * @see R.pair + * @example + * + * var matchPhrases = R.compose( + * R.objOf('must'), + * R.map(R.objOf('match_phrase')) + * ); + * matchPhrases(['foo', 'bar', 'baz']); //=> {must: [{match_phrase: 'foo'}, {match_phrase: 'bar'}, {match_phrase: 'baz'}]} + */ + var objOf = _curry2(function objOf(key, val) { + var obj = {}; + obj[key] = val; + return obj; + }); + + /** + * Returns a singleton array containing the value provided. + * + * Note this `of` is different from the ES6 `of`; See + * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/of + * + * @func + * @memberOf R + * @since v0.3.0 + * @category Function + * @sig a -> [a] + * @param {*} x any value + * @return {Array} An array wrapping `x`. + * @example + * + * R.of(null); //=> [null] + * R.of([42]); //=> [[42]] + */ + var of = _curry1(_of); + + /** + * Accepts a function `fn` and returns a function that guards invocation of + * `fn` such that `fn` can only ever be called once, no matter how many times + * the returned function is invoked. The first value calculated is returned in + * subsequent invocations. + * + * @func + * @memberOf R + * @since v0.1.0 + * @category Function + * @sig (a... -> b) -> (a... -> b) + * @param {Function} fn The function to wrap in a call-only-once wrapper. + * @return {Function} The wrapped function. + * @example + * + * var addOneOnce = R.once(x => x + 1); + * addOneOnce(10); //=> 11 + * addOneOnce(addOneOnce(50)); //=> 11 + */ + var once = _curry1(function once(fn) { + var called = false; + var result; + return _arity(fn.length, function () { + if (called) { + return result; + } + called = true; + result = fn.apply(this, arguments); + return result; + }); + }); + + /** + * Returns `true` if one or both of its arguments are `true`. Returns `false` + * if both arguments are `false`. + * + * @func + * @memberOf R + * @since v0.1.0 + * @category Logic + * @sig * -> * -> * + * @param {Boolean} a A boolean value + * @param {Boolean} b A boolean value + * @return {Boolean} `true` if one or both arguments are `true`, `false` otherwise + * @see R.either + * @example + * + * R.or(true, true); //=> true + * R.or(true, false); //=> true + * R.or(false, true); //=> true + * R.or(false, false); //=> false + */ + var or = _curry2(function or(a, b) { + return a || b; + }); + + /** + * Returns the result of "setting" the portion of the given data structure + * focused by the given lens to the result of applying the given function to + * the focused value. + * + * @func + * @memberOf R + * @since v0.16.0 + * @category Object + * @typedefn Lens s a = Functor f => (a -> f a) -> s -> f s + * @sig Lens s a -> (a -> a) -> s -> s + * @param {Lens} lens + * @param {*} v + * @param {*} x + * @return {*} + * @see R.prop, R.lensIndex, R.lensProp + * @example + * + * var headLens = R.lensIndex(0); + * + * R.over(headLens, R.toUpper, ['foo', 'bar', 'baz']); //=> ['FOO', 'bar', 'baz'] + */ + // `Identity` is a functor that holds a single value, where `map` simply + // transforms the held value with the provided function. + // The value returned by the getter function is first transformed with `f`, + // then set as the value of an `Identity`. This is then mapped over with the + // setter function of the lens. + var over = function () { + // `Identity` is a functor that holds a single value, where `map` simply + // transforms the held value with the provided function. + var Identity = function (x) { + return { + value: x, + map: function (f) { + return Identity(f(x)); + } + }; + }; + return _curry3(function over(lens, f, x) { + // The value returned by the getter function is first transformed with `f`, + // then set as the value of an `Identity`. This is then mapped over with the + // setter function of the lens. + return lens(function (y) { + return Identity(f(y)); + })(x).value; + }); + }(); + + /** + * Takes two arguments, `fst` and `snd`, and returns `[fst, snd]`. + * + * @func + * @memberOf R + * @since v0.18.0 + * @category List + * @sig a -> b -> (a,b) + * @param {*} fst + * @param {*} snd + * @return {Array} + * @see R.objOf, R.of + * @example + * + * R.pair('foo', 'bar'); //=> ['foo', 'bar'] + */ + var pair = _curry2(function pair(fst, snd) { + return [ + fst, + snd + ]; + }); + + /** + * Retrieve the value at a given path. + * + * @func + * @memberOf R + * @since v0.2.0 + * @category Object + * @sig [String] -> {k: v} -> v | Undefined + * @param {Array} path The path to use. + * @param {Object} obj The object to retrieve the nested property from. + * @return {*} The data at `path`. + * @example + * + * R.path(['a', 'b'], {a: {b: 2}}); //=> 2 + * R.path(['a', 'b'], {c: {b: 2}}); //=> undefined + */ + var path = _curry2(function path(paths, obj) { + var val = obj; + var idx = 0; + while (idx < paths.length) { + if (val == null) { + return; + } + val = val[paths[idx]]; + idx += 1; + } + return val; + }); + + /** + * If the given, non-null object has a value at the given path, returns the + * value at that path. Otherwise returns the provided default value. + * + * @func + * @memberOf R + * @since v0.18.0 + * @category Object + * @sig a -> [String] -> Object -> a + * @param {*} d The default value. + * @param {Array} p The path to use. + * @param {Object} obj The object to retrieve the nested property from. + * @return {*} The data at `path` of the supplied object or the default value. + * @example + * + * R.pathOr('N/A', ['a', 'b'], {a: {b: 2}}); //=> 2 + * R.pathOr('N/A', ['a', 'b'], {c: {b: 2}}); //=> "N/A" + */ + var pathOr = _curry3(function pathOr(d, p, obj) { + return defaultTo(d, path(p, obj)); + }); + + /** + * Returns `true` if the specified object property at given path satisfies the + * given predicate; `false` otherwise. + * + * @func + * @memberOf R + * @since v0.19.0 + * @category Logic + * @sig (a -> Boolean) -> [String] -> Object -> Boolean + * @param {Function} pred + * @param {Array} propPath + * @param {*} obj + * @return {Boolean} + * @see R.propSatisfies, R.path + * @example + * + * R.pathSatisfies(y => y > 0, ['x', 'y'], {x: {y: 2}}); //=> true + */ + var pathSatisfies = _curry3(function pathSatisfies(pred, propPath, obj) { + return propPath.length > 0 && pred(path(propPath, obj)); + }); + + /** + * Returns a partial copy of an object containing only the keys specified. If + * the key does not exist, the property is ignored. + * + * @func + * @memberOf R + * @since v0.1.0 + * @category Object + * @sig [k] -> {k: v} -> {k: v} + * @param {Array} names an array of String property names to copy onto a new object + * @param {Object} obj The object to copy from + * @return {Object} A new object with only properties from `names` on it. + * @see R.omit, R.props + * @example + * + * R.pick(['a', 'd'], {a: 1, b: 2, c: 3, d: 4}); //=> {a: 1, d: 4} + * R.pick(['a', 'e', 'f'], {a: 1, b: 2, c: 3, d: 4}); //=> {a: 1} + */ + var pick = _curry2(function pick(names, obj) { + var result = {}; + var idx = 0; + while (idx < names.length) { + if (names[idx] in obj) { + result[names[idx]] = obj[names[idx]]; + } + idx += 1; + } + return result; + }); + + /** + * Similar to `pick` except that this one includes a `key: undefined` pair for + * properties that don't exist. + * + * @func + * @memberOf R + * @since v0.1.0 + * @category Object + * @sig [k] -> {k: v} -> {k: v} + * @param {Array} names an array of String property names to copy onto a new object + * @param {Object} obj The object to copy from + * @return {Object} A new object with only properties from `names` on it. + * @see R.pick + * @example + * + * R.pickAll(['a', 'd'], {a: 1, b: 2, c: 3, d: 4}); //=> {a: 1, d: 4} + * R.pickAll(['a', 'e', 'f'], {a: 1, b: 2, c: 3, d: 4}); //=> {a: 1, e: undefined, f: undefined} + */ + var pickAll = _curry2(function pickAll(names, obj) { + var result = {}; + var idx = 0; + var len = names.length; + while (idx < len) { + var name = names[idx]; + result[name] = obj[name]; + idx += 1; + } + return result; + }); + + /** + * Returns a partial copy of an object containing only the keys that satisfy + * the supplied predicate. + * + * @func + * @memberOf R + * @since v0.8.0 + * @category Object + * @sig (v, k -> Boolean) -> {k: v} -> {k: v} + * @param {Function} pred A predicate to determine whether or not a key + * should be included on the output object. + * @param {Object} obj The object to copy from + * @return {Object} A new object with only properties that satisfy `pred` + * on it. + * @see R.pick, R.filter + * @example + * + * var isUpperCase = (val, key) => key.toUpperCase() === key; + * R.pickBy(isUpperCase, {a: 1, b: 2, A: 3, B: 4}); //=> {A: 3, B: 4} + */ + var pickBy = _curry2(function pickBy(test, obj) { + var result = {}; + for (var prop in obj) { + if (test(obj[prop], prop, obj)) { + result[prop] = obj[prop]; + } + } + return result; + }); + + /** + * Returns a new list with the given element at the front, followed by the + * contents of the list. + * + * @func + * @memberOf R + * @since v0.1.0 + * @category List + * @sig a -> [a] -> [a] + * @param {*} el The item to add to the head of the output list. + * @param {Array} list The array to add to the tail of the output list. + * @return {Array} A new array. + * @see R.append + * @example + * + * R.prepend('fee', ['fi', 'fo', 'fum']); //=> ['fee', 'fi', 'fo', 'fum'] + */ + var prepend = _curry2(function prepend(el, list) { + return _concat([el], list); + }); + + /** + * Returns a function that when supplied an object returns the indicated + * property of that object, if it exists. + * + * @func + * @memberOf R + * @since v0.1.0 + * @category Object + * @sig s -> {s: a} -> a | Undefined + * @param {String} p The property name + * @param {Object} obj The object to query + * @return {*} The value at `obj.p`. + * @example + * + * R.prop('x', {x: 100}); //=> 100 + * R.prop('x', {}); //=> undefined + */ + var prop = _curry2(function prop(p, obj) { + return obj[p]; + }); + + /** + * If the given, non-null object has an own property with the specified name, + * returns the value of that property. Otherwise returns the provided default + * value. + * + * @func + * @memberOf R + * @since v0.6.0 + * @category Object + * @sig a -> String -> Object -> a + * @param {*} val The default value. + * @param {String} p The name of the property to return. + * @param {Object} obj The object to query. + * @return {*} The value of given property of the supplied object or the default value. + * @example + * + * var alice = { + * name: 'ALICE', + * age: 101 + * }; + * var favorite = R.prop('favoriteLibrary'); + * var favoriteWithDefault = R.propOr('Ramda', 'favoriteLibrary'); + * + * favorite(alice); //=> undefined + * favoriteWithDefault(alice); //=> 'Ramda' + */ + var propOr = _curry3(function propOr(val, p, obj) { + return obj != null && _has(p, obj) ? obj[p] : val; + }); + + /** + * Returns `true` if the specified object property satisfies the given + * predicate; `false` otherwise. + * + * @func + * @memberOf R + * @since v0.16.0 + * @category Logic + * @sig (a -> Boolean) -> String -> {String: a} -> Boolean + * @param {Function} pred + * @param {String} name + * @param {*} obj + * @return {Boolean} + * @see R.propEq, R.propIs + * @example + * + * R.propSatisfies(x => x > 0, 'x', {x: 1, y: 2}); //=> true + */ + var propSatisfies = _curry3(function propSatisfies(pred, name, obj) { + return pred(obj[name]); + }); + + /** + * Acts as multiple `prop`: array of keys in, array of values out. Preserves + * order. + * + * @func + * @memberOf R + * @since v0.1.0 + * @category Object + * @sig [k] -> {k: v} -> [v] + * @param {Array} ps The property names to fetch + * @param {Object} obj The object to query + * @return {Array} The corresponding values or partially applied function. + * @example + * + * R.props(['x', 'y'], {x: 1, y: 2}); //=> [1, 2] + * R.props(['c', 'a', 'b'], {b: 2, a: 1}); //=> [undefined, 1, 2] + * + * var fullName = R.compose(R.join(' '), R.props(['first', 'last'])); + * fullName({last: 'Bullet-Tooth', age: 33, first: 'Tony'}); //=> 'Tony Bullet-Tooth' + */ + var props = _curry2(function props(ps, obj) { + var len = ps.length; + var out = []; + var idx = 0; + while (idx < len) { + out[idx] = obj[ps[idx]]; + idx += 1; + } + return out; + }); + + /** + * Returns a list of numbers from `from` (inclusive) to `to` (exclusive). + * + * @func + * @memberOf R + * @since v0.1.0 + * @category List + * @sig Number -> Number -> [Number] + * @param {Number} from The first number in the list. + * @param {Number} to One more than the last number in the list. + * @return {Array} The list of numbers in tthe set `[a, b)`. + * @example + * + * R.range(1, 5); //=> [1, 2, 3, 4] + * R.range(50, 53); //=> [50, 51, 52] + */ + var range = _curry2(function range(from, to) { + if (!(_isNumber(from) && _isNumber(to))) { + throw new TypeError('Both arguments to range must be numbers'); + } + var result = []; + var n = from; + while (n < to) { + result.push(n); + n += 1; + } + return result; + }); + + /** + * Returns a single item by iterating through the list, successively calling + * the iterator function and passing it an accumulator value and the current + * value from the array, and then passing the result to the next call. + * + * Similar to `reduce`, except moves through the input list from the right to + * the left. + * + * The iterator function receives two values: *(acc, value)* + * + * Note: `R.reduceRight` does not skip deleted or unassigned indices (sparse + * arrays), unlike the native `Array.prototype.reduce` method. For more details + * on this behavior, see: + * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduceRight#Description + * + * @func + * @memberOf R + * @since v0.1.0 + * @category List + * @sig (a,b -> a) -> a -> [b] -> a + * @param {Function} fn The iterator function. Receives two values, the accumulator and the + * current element from the array. + * @param {*} acc The accumulator value. + * @param {Array} list The list to iterate over. + * @return {*} The final, accumulated value. + * @see R.addIndex + * @example + * + * var pairs = [ ['a', 1], ['b', 2], ['c', 3] ]; + * var flattenPairs = (acc, pair) => acc.concat(pair); + * + * R.reduceRight(flattenPairs, [], pairs); //=> [ 'c', 3, 'b', 2, 'a', 1 ] + */ + var reduceRight = _curry3(function reduceRight(fn, acc, list) { + var idx = list.length - 1; + while (idx >= 0) { + acc = fn(acc, list[idx]); + idx -= 1; + } + return acc; + }); + + /** + * Returns a value wrapped to indicate that it is the final value of the reduce + * and transduce functions. The returned value should be considered a black + * box: the internal structure is not guaranteed to be stable. + * + * Note: this optimization is unavailable to functions not explicitly listed + * above. For instance, it is not currently supported by reduceRight. + * + * @func + * @memberOf R + * @since v0.15.0 + * @category List + * @sig a -> * + * @param {*} x The final value of the reduce. + * @return {*} The wrapped value. + * @see R.reduce, R.transduce + * @example + * + * R.reduce( + * R.pipe(R.add, R.when(R.gte(R.__, 10), R.reduced)), + * 0, + * [1, 2, 3, 4, 5]) // 10 + */ + var reduced = _curry1(_reduced); + + /** + * Removes the sub-list of `list` starting at index `start` and containing + * `count` elements. _Note that this is not destructive_: it returns a copy of + * the list with the changes. + * No lists have been harmed in the application of this function. + * + * @func + * @memberOf R + * @since v0.2.2 + * @category List + * @sig Number -> Number -> [a] -> [a] + * @param {Number} start The position to start removing elements + * @param {Number} count The number of elements to remove + * @param {Array} list The list to remove from + * @return {Array} A new Array with `count` elements from `start` removed. + * @example + * + * R.remove(2, 3, [1,2,3,4,5,6,7,8]); //=> [1,2,6,7,8] + */ + var remove = _curry3(function remove(start, count, list) { + return _concat(_slice(list, 0, Math.min(start, list.length)), _slice(list, Math.min(list.length, start + count))); + }); + + /** + * Replace a substring or regex match in a string with a replacement. + * + * @func + * @memberOf R + * @since v0.7.0 + * @category String + * @sig RegExp|String -> String -> String -> String + * @param {RegExp|String} pattern A regular expression or a substring to match. + * @param {String} replacement The string to replace the matches with. + * @param {String} str The String to do the search and replacement in. + * @return {String} The result. + * @example + * + * R.replace('foo', 'bar', 'foo foo foo'); //=> 'bar foo foo' + * R.replace(/foo/, 'bar', 'foo foo foo'); //=> 'bar foo foo' + * + * // Use the "g" (global) flag to replace all occurrences: + * R.replace(/foo/g, 'bar', 'foo foo foo'); //=> 'bar bar bar' + */ + var replace = _curry3(function replace(regex, replacement, str) { + return str.replace(regex, replacement); + }); + + /** + * Returns a new list or string with the elements or characters in reverse + * order. + * + * @func + * @memberOf R + * @since v0.1.0 + * @category List + * @sig [a] -> [a] + * @sig String -> String + * @param {Array|String} list + * @return {Array|String} + * @example + * + * R.reverse([1, 2, 3]); //=> [3, 2, 1] + * R.reverse([1, 2]); //=> [2, 1] + * R.reverse([1]); //=> [1] + * R.reverse([]); //=> [] + * + * R.reverse('abc'); //=> 'cba' + * R.reverse('ab'); //=> 'ba' + * R.reverse('a'); //=> 'a' + * R.reverse(''); //=> '' + */ + var reverse = _curry1(function reverse(list) { + return _isString(list) ? list.split('').reverse().join('') : _slice(list).reverse(); + }); + + /** + * Scan is similar to reduce, but returns a list of successively reduced values + * from the left + * + * @func + * @memberOf R + * @since v0.10.0 + * @category List + * @sig (a,b -> a) -> a -> [b] -> [a] + * @param {Function} fn The iterator function. Receives two values, the accumulator and the + * current element from the array + * @param {*} acc The accumulator value. + * @param {Array} list The list to iterate over. + * @return {Array} A list of all intermediately reduced values. + * @example + * + * var numbers = [1, 2, 3, 4]; + * var factorials = R.scan(R.multiply, 1, numbers); //=> [1, 1, 2, 6, 24] + */ + var scan = _curry3(function scan(fn, acc, list) { + var idx = 0; + var len = list.length; + var result = [acc]; + while (idx < len) { + acc = fn(acc, list[idx]); + result[idx + 1] = acc; + idx += 1; + } + return result; + }); + + /** + * Returns the result of "setting" the portion of the given data structure + * focused by the given lens to the given value. + * + * @func + * @memberOf R + * @since v0.16.0 + * @category Object + * @typedefn Lens s a = Functor f => (a -> f a) -> s -> f s + * @sig Lens s a -> a -> s -> s + * @param {Lens} lens + * @param {*} v + * @param {*} x + * @return {*} + * @see R.prop, R.lensIndex, R.lensProp + * @example + * + * var xLens = R.lensProp('x'); + * + * R.set(xLens, 4, {x: 1, y: 2}); //=> {x: 4, y: 2} + * R.set(xLens, 8, {x: 1, y: 2}); //=> {x: 8, y: 2} + */ + var set = _curry3(function set(lens, v, x) { + return over(lens, always(v), x); + }); + + /** + * Returns the elements of the given list or string (or object with a `slice` + * method) from `fromIndex` (inclusive) to `toIndex` (exclusive). + * + * Dispatches to the `slice` method of the third argument, if present. + * + * @func + * @memberOf R + * @since v0.1.4 + * @category List + * @sig Number -> Number -> [a] -> [a] + * @sig Number -> Number -> String -> String + * @param {Number} fromIndex The start index (inclusive). + * @param {Number} toIndex The end index (exclusive). + * @param {*} list + * @return {*} + * @example + * + * R.slice(1, 3, ['a', 'b', 'c', 'd']); //=> ['b', 'c'] + * R.slice(1, Infinity, ['a', 'b', 'c', 'd']); //=> ['b', 'c', 'd'] + * R.slice(0, -1, ['a', 'b', 'c', 'd']); //=> ['a', 'b', 'c'] + * R.slice(-3, -1, ['a', 'b', 'c', 'd']); //=> ['b', 'c'] + * R.slice(0, 3, 'ramda'); //=> 'ram' + */ + var slice = _curry3(_checkForMethod('slice', function slice(fromIndex, toIndex, list) { + return Array.prototype.slice.call(list, fromIndex, toIndex); + })); + + /** + * Returns a copy of the list, sorted according to the comparator function, + * which should accept two values at a time and return a negative number if the + * first value is smaller, a positive number if it's larger, and zero if they + * are equal. Please note that this is a **copy** of the list. It does not + * modify the original. + * + * @func + * @memberOf R + * @since v0.1.0 + * @category List + * @sig (a,a -> Number) -> [a] -> [a] + * @param {Function} comparator A sorting function :: a -> b -> Int + * @param {Array} list The list to sort + * @return {Array} a new array with its elements sorted by the comparator function. + * @example + * + * var diff = function(a, b) { return a - b; }; + * R.sort(diff, [4,2,7,5]); //=> [2, 4, 5, 7] + */ + var sort = _curry2(function sort(comparator, list) { + return _slice(list).sort(comparator); + }); + + /** + * Sorts the list according to the supplied function. + * + * @func + * @memberOf R + * @since v0.1.0 + * @category Relation + * @sig Ord b => (a -> b) -> [a] -> [a] + * @param {Function} fn + * @param {Array} list The list to sort. + * @return {Array} A new list sorted by the keys generated by `fn`. + * @example + * + * var sortByFirstItem = R.sortBy(R.prop(0)); + * var sortByNameCaseInsensitive = R.sortBy(R.compose(R.toLower, R.prop('name'))); + * var pairs = [[-1, 1], [-2, 2], [-3, 3]]; + * sortByFirstItem(pairs); //=> [[-3, 3], [-2, 2], [-1, 1]] + * var alice = { + * name: 'ALICE', + * age: 101 + * }; + * var bob = { + * name: 'Bob', + * age: -10 + * }; + * var clara = { + * name: 'clara', + * age: 314.159 + * }; + * var people = [clara, bob, alice]; + * sortByNameCaseInsensitive(people); //=> [alice, bob, clara] + */ + var sortBy = _curry2(function sortBy(fn, list) { + return _slice(list).sort(function (a, b) { + var aa = fn(a); + var bb = fn(b); + return aa < bb ? -1 : aa > bb ? 1 : 0; + }); + }); + + /** + * Splits a given list or string at a given index. + * + * @func + * @memberOf R + * @since v0.19.0 + * @category List + * @sig Number -> [a] -> [[a], [a]] + * @sig Number -> String -> [String, String] + * @param {Number} index The index where the array/string is split. + * @param {Array|String} array The array/string to be split. + * @return {Array} + * @example + * + * R.splitAt(1, [1, 2, 3]); //=> [[1], [2, 3]] + * R.splitAt(5, 'hello world'); //=> ['hello', ' world'] + * R.splitAt(-1, 'foobar'); //=> ['fooba', 'r'] + */ + var splitAt = _curry2(function splitAt(index, array) { + return [ + slice(0, index, array), + slice(index, length(array), array) + ]; + }); + + /** + * Splits a collection into slices of the specified length. + * + * @func + * @memberOf R + * @since v0.16.0 + * @category List + * @sig Number -> [a] -> [[a]] + * @sig Number -> String -> [String] + * @param {Number} n + * @param {Array} list + * @return {Array} + * @example + * + * R.splitEvery(3, [1, 2, 3, 4, 5, 6, 7]); //=> [[1, 2, 3], [4, 5, 6], [7]] + * R.splitEvery(3, 'foobarbaz'); //=> ['foo', 'bar', 'baz'] + */ + var splitEvery = _curry2(function splitEvery(n, list) { + if (n <= 0) { + throw new Error('First argument to splitEvery must be a positive integer'); + } + var result = []; + var idx = 0; + while (idx < list.length) { + result.push(slice(idx, idx += n, list)); + } + return result; + }); + + /** + * Takes a list and a predicate and returns a pair of lists with the following properties: + * + * - the result of concatenating the two output lists is equivalent to the input list; + * - none of the elements of the first output list satisfies the predicate; and + * - if the second output list is non-empty, its first element satisfies the predicate. + * + * @func + * @memberOf R + * @since v0.19.0 + * @category List + * @sig (a -> Boolean) -> [a] -> [[a], [a]] + * @param {Function} pred The predicate that determines where the array is split. + * @param {Array} list The array to be split. + * @return {Array} + * @example + * + * R.splitWhen(R.equals(2), [1, 2, 3, 1, 2, 3]); //=> [[1], [2, 3, 1, 2, 3]] + */ + var splitWhen = _curry2(function splitWhen(pred, list) { + var idx = 0; + var len = list.length; + var prefix = []; + while (idx < len && !pred(list[idx])) { + prefix.push(list[idx]); + idx += 1; + } + return [ + prefix, + _slice(list, idx) + ]; + }); + + /** + * Subtracts its second argument from its first argument. + * + * @func + * @memberOf R + * @since v0.1.0 + * @category Math + * @sig Number -> Number -> Number + * @param {Number} a The first value. + * @param {Number} b The second value. + * @return {Number} The result of `a - b`. + * @see R.add + * @example + * + * R.subtract(10, 8); //=> 2 + * + * var minus5 = R.subtract(R.__, 5); + * minus5(17); //=> 12 + * + * var complementaryAngle = R.subtract(90); + * complementaryAngle(30); //=> 60 + * complementaryAngle(72); //=> 18 + */ + var subtract = _curry2(function subtract(a, b) { + return Number(a) - Number(b); + }); + + /** + * Returns all but the first element of the given list or string (or object + * with a `tail` method). + * + * Dispatches to the `slice` method of the first argument, if present. + * + * @func + * @memberOf R + * @since v0.1.0 + * @category List + * @sig [a] -> [a] + * @sig String -> String + * @param {*} list + * @return {*} + * @see R.head, R.init, R.last + * @example + * + * R.tail([1, 2, 3]); //=> [2, 3] + * R.tail([1, 2]); //=> [2] + * R.tail([1]); //=> [] + * R.tail([]); //=> [] + * + * R.tail('abc'); //=> 'bc' + * R.tail('ab'); //=> 'b' + * R.tail('a'); //=> '' + * R.tail(''); //=> '' + */ + var tail = _checkForMethod('tail', slice(1, Infinity)); + + /** + * Returns the first `n` elements of the given list, string, or + * transducer/transformer (or object with a `take` method). + * + * Dispatches to the `take` method of the second argument, if present. + * + * @func + * @memberOf R + * @since v0.1.0 + * @category List + * @sig Number -> [a] -> [a] + * @sig Number -> String -> String + * @param {Number} n + * @param {*} list + * @return {*} + * @see R.drop + * @example + * + * R.take(1, ['foo', 'bar', 'baz']); //=> ['foo'] + * R.take(2, ['foo', 'bar', 'baz']); //=> ['foo', 'bar'] + * R.take(3, ['foo', 'bar', 'baz']); //=> ['foo', 'bar', 'baz'] + * R.take(4, ['foo', 'bar', 'baz']); //=> ['foo', 'bar', 'baz'] + * R.take(3, 'ramda'); //=> 'ram' + * + * var personnel = [ + * 'Dave Brubeck', + * 'Paul Desmond', + * 'Eugene Wright', + * 'Joe Morello', + * 'Gerry Mulligan', + * 'Bob Bates', + * 'Joe Dodge', + * 'Ron Crotty' + * ]; + * + * var takeFive = R.take(5); + * takeFive(personnel); + * //=> ['Dave Brubeck', 'Paul Desmond', 'Eugene Wright', 'Joe Morello', 'Gerry Mulligan'] + */ + var take = _curry2(_dispatchable('take', _xtake, function take(n, xs) { + return slice(0, n < 0 ? Infinity : n, xs); + })); + + /** + * Returns a new list containing the last `n` elements of a given list, passing + * each value to the supplied predicate function, and terminating when the + * predicate function returns `false`. Excludes the element that caused the + * predicate function to fail. The predicate function is passed one argument: + * *(value)*. + * + * @func + * @memberOf R + * @since v0.16.0 + * @category List + * @sig (a -> Boolean) -> [a] -> [a] + * @param {Function} fn The function called per iteration. + * @param {Array} list The collection to iterate over. + * @return {Array} A new array. + * @see R.dropLastWhile, R.addIndex + * @example + * + * var isNotOne = x => x !== 1; + * + * R.takeLastWhile(isNotOne, [1, 2, 3, 4]); //=> [2, 3, 4] + */ + var takeLastWhile = _curry2(function takeLastWhile(fn, list) { + var idx = list.length - 1; + while (idx >= 0 && fn(list[idx])) { + idx -= 1; + } + return _slice(list, idx + 1, Infinity); + }); + + /** + * Returns a new list containing the first `n` elements of a given list, + * passing each value to the supplied predicate function, and terminating when + * the predicate function returns `false`. Excludes the element that caused the + * predicate function to fail. The predicate function is passed one argument: + * *(value)*. + * + * Dispatches to the `takeWhile` method of the second argument, if present. + * + * Acts as a transducer if a transformer is given in list position. + * + * @func + * @memberOf R + * @since v0.1.0 + * @category List + * @sig (a -> Boolean) -> [a] -> [a] + * @param {Function} fn The function called per iteration. + * @param {Array} list The collection to iterate over. + * @return {Array} A new array. + * @see R.dropWhile, R.transduce, R.addIndex + * @example + * + * var isNotFour = x => x !== 4; + * + * R.takeWhile(isNotFour, [1, 2, 3, 4, 3, 2, 1]); //=> [1, 2, 3] + */ + var takeWhile = _curry2(_dispatchable('takeWhile', _xtakeWhile, function takeWhile(fn, list) { + var idx = 0; + var len = list.length; + while (idx < len && fn(list[idx])) { + idx += 1; + } + return _slice(list, 0, idx); + })); + + /** + * Runs the given function with the supplied object, then returns the object. + * + * @func + * @memberOf R + * @since v0.1.0 + * @category Function + * @sig (a -> *) -> a -> a + * @param {Function} fn The function to call with `x`. The return value of `fn` will be thrown away. + * @param {*} x + * @return {*} `x`. + * @example + * + * var sayX = x => console.log('x is ' + x); + * R.tap(sayX, 100); //=> 100 + * //-> 'x is 100' + */ + var tap = _curry2(function tap(fn, x) { + fn(x); + return x; + }); + + /** + * Calls an input function `n` times, returning an array containing the results + * of those function calls. + * + * `fn` is passed one argument: The current value of `n`, which begins at `0` + * and is gradually incremented to `n - 1`. + * + * @func + * @memberOf R + * @since v0.2.3 + * @category List + * @sig (Number -> a) -> Number -> [a] + * @param {Function} fn The function to invoke. Passed one argument, the current value of `n`. + * @param {Number} n A value between `0` and `n - 1`. Increments after each function call. + * @return {Array} An array containing the return values of all calls to `fn`. + * @example + * + * R.times(R.identity, 5); //=> [0, 1, 2, 3, 4] + */ + var times = _curry2(function times(fn, n) { + var len = Number(n); + var idx = 0; + var list; + if (len < 0 || isNaN(len)) { + throw new RangeError('n must be a non-negative number'); + } + list = new Array(len); + while (idx < len) { + list[idx] = fn(idx); + idx += 1; + } + return list; + }); + + /** + * Converts an object into an array of key, value arrays. Only the object's + * own properties are used. + * Note that the order of the output array is not guaranteed to be consistent + * across different JS platforms. + * + * @func + * @memberOf R + * @since v0.4.0 + * @category Object + * @sig {String: *} -> [[String,*]] + * @param {Object} obj The object to extract from + * @return {Array} An array of key, value arrays from the object's own properties. + * @see R.fromPairs + * @example + * + * R.toPairs({a: 1, b: 2, c: 3}); //=> [['a', 1], ['b', 2], ['c', 3]] + */ + var toPairs = _curry1(function toPairs(obj) { + var pairs = []; + for (var prop in obj) { + if (_has(prop, obj)) { + pairs[pairs.length] = [ + prop, + obj[prop] + ]; + } + } + return pairs; + }); + + /** + * Converts an object into an array of key, value arrays. The object's own + * properties and prototype properties are used. Note that the order of the + * output array is not guaranteed to be consistent across different JS + * platforms. + * + * @func + * @memberOf R + * @since v0.4.0 + * @category Object + * @sig {String: *} -> [[String,*]] + * @param {Object} obj The object to extract from + * @return {Array} An array of key, value arrays from the object's own + * and prototype properties. + * @example + * + * var F = function() { this.x = 'X'; }; + * F.prototype.y = 'Y'; + * var f = new F(); + * R.toPairsIn(f); //=> [['x','X'], ['y','Y']] + */ + var toPairsIn = _curry1(function toPairsIn(obj) { + var pairs = []; + for (var prop in obj) { + pairs[pairs.length] = [ + prop, + obj[prop] + ]; + } + return pairs; + }); + + /** + * Transposes the rows and columns of a 2D list. + * When passed a list of `n` lists of length `x`, + * returns a list of `x` lists of length `n`. + * + * + * @func + * @memberOf R + * @since v0.19.0 + * @category List + * @sig [[a]] -> [[a]] + * @param {Array} list A 2D list + * @return {Array} A 2D list + * @example + * + * R.transpose([[1, 'a'], [2, 'b'], [3, 'c']]) //=> [[1, 2, 3], ['a', 'b', 'c']] + * R.transpose([[1, 2, 3], ['a', 'b', 'c']]) //=> [[1, 'a'], [2, 'b'], [3, 'c']] + * + * If some of the rows are shorter than the following rows, their elements are skipped: + * + * R.transpose([[10, 11], [20], [], [30, 31, 32]]) //=> [[10, 20, 30], [11, 31], [32]] + */ + var transpose = _curry1(function transpose(outerlist) { + var i = 0; + var result = []; + while (i < outerlist.length) { + var innerlist = outerlist[i]; + var j = 0; + while (j < innerlist.length) { + if (typeof result[j] === 'undefined') { + result[j] = []; + } + result[j].push(innerlist[j]); + j += 1; + } + i += 1; + } + return result; + }); + + /** + * Removes (strips) whitespace from both ends of the string. + * + * @func + * @memberOf R + * @since v0.6.0 + * @category String + * @sig String -> String + * @param {String} str The string to trim. + * @return {String} Trimmed version of `str`. + * @example + * + * R.trim(' xyz '); //=> 'xyz' + * R.map(R.trim, R.split(',', 'x, y, z')); //=> ['x', 'y', 'z'] + */ + var trim = function () { + var ws = '\t\n\x0B\f\r \xA0\u1680\u180E\u2000\u2001\u2002\u2003' + '\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028' + '\u2029\uFEFF'; + var zeroWidth = '\u200B'; + var hasProtoTrim = typeof String.prototype.trim === 'function'; + if (!hasProtoTrim || (ws.trim() || !zeroWidth.trim())) { + return _curry1(function trim(str) { + var beginRx = new RegExp('^[' + ws + '][' + ws + ']*'); + var endRx = new RegExp('[' + ws + '][' + ws + ']*$'); + return str.replace(beginRx, '').replace(endRx, ''); + }); + } else { + return _curry1(function trim(str) { + return str.trim(); + }); + } + }(); + + /** + * `tryCatch` takes two functions, a `tryer` and a `catcher`. The returned + * function evaluates the `tryer`; if it does not throw, it simply returns the + * result. If the `tryer` *does* throw, the returned function evaluates the + * `catcher` function and returns its result. Note that for effective + * composition with this function, both the `tryer` and `catcher` functions + * must return the same type of results. + * + * @func + * @memberOf R + * @since v0.20.0 + * @category Function + * @sig (...x -> a) -> ((e, ...x) -> a) -> (...x -> a) + * @param {Function} tryer The function that may throw. + * @param {Function} catcher The function that will be evaluated if `tryer` throws. + * @return {Function} A new function that will catch exceptions and send then to the catcher. + * @example + * + * R.tryCatch(R.prop('x'), R.F, {x: true}); //=> true + * R.tryCatch(R.prop('x'), R.F, null); //=> false + */ + var tryCatch = _curry2(function _tryCatch(tryer, catcher) { + return _arity(tryer.length, function () { + try { + return tryer.apply(this, arguments); + } catch (e) { + return catcher.apply(this, _concat([e], arguments)); + } + }); + }); + + /** + * Gives a single-word string description of the (native) type of a value, + * returning such answers as 'Object', 'Number', 'Array', or 'Null'. Does not + * attempt to distinguish user Object types any further, reporting them all as + * 'Object'. + * + * @func + * @memberOf R + * @since v0.8.0 + * @category Type + * @sig (* -> {*}) -> String + * @param {*} val The value to test + * @return {String} + * @example + * + * R.type({}); //=> "Object" + * R.type(1); //=> "Number" + * R.type(false); //=> "Boolean" + * R.type('s'); //=> "String" + * R.type(null); //=> "Null" + * R.type([]); //=> "Array" + * R.type(/[A-z]/); //=> "RegExp" + */ + var type = _curry1(function type(val) { + return val === null ? 'Null' : val === undefined ? 'Undefined' : Object.prototype.toString.call(val).slice(8, -1); + }); + + /** + * Takes a function `fn`, which takes a single array argument, and returns a + * function which: + * + * - takes any number of positional arguments; + * - passes these arguments to `fn` as an array; and + * - returns the result. + * + * In other words, R.unapply derives a variadic function from a function which + * takes an array. R.unapply is the inverse of R.apply. + * + * @func + * @memberOf R + * @since v0.8.0 + * @category Function + * @sig ([*...] -> a) -> (*... -> a) + * @param {Function} fn + * @return {Function} + * @see R.apply + * @example + * + * R.unapply(JSON.stringify)(1, 2, 3); //=> '[1,2,3]' + */ + var unapply = _curry1(function unapply(fn) { + return function () { + return fn(_slice(arguments)); + }; + }); + + /** + * Wraps a function of any arity (including nullary) in a function that accepts + * exactly 1 parameter. Any extraneous parameters will not be passed to the + * supplied function. + * + * @func + * @memberOf R + * @since v0.2.0 + * @category Function + * @sig (* -> b) -> (a -> b) + * @param {Function} fn The function to wrap. + * @return {Function} A new function wrapping `fn`. The new function is guaranteed to be of + * arity 1. + * @example + * + * var takesTwoArgs = function(a, b) { + * return [a, b]; + * }; + * takesTwoArgs.length; //=> 2 + * takesTwoArgs(1, 2); //=> [1, 2] + * + * var takesOneArg = R.unary(takesTwoArgs); + * takesOneArg.length; //=> 1 + * // Only 1 argument is passed to the wrapped function + * takesOneArg(1, 2); //=> [1, undefined] + */ + var unary = _curry1(function unary(fn) { + return nAry(1, fn); + }); + + /** + * Returns a function of arity `n` from a (manually) curried function. + * + * @func + * @memberOf R + * @since v0.14.0 + * @category Function + * @sig Number -> (a -> b) -> (a -> c) + * @param {Number} length The arity for the returned function. + * @param {Function} fn The function to uncurry. + * @return {Function} A new function. + * @see R.curry + * @example + * + * var addFour = a => b => c => d => a + b + c + d; + * + * var uncurriedAddFour = R.uncurryN(4, addFour); + * uncurriedAddFour(1, 2, 3, 4); //=> 10 + */ + var uncurryN = _curry2(function uncurryN(depth, fn) { + return curryN(depth, function () { + var currentDepth = 1; + var value = fn; + var idx = 0; + var endIdx; + while (currentDepth <= depth && typeof value === 'function') { + endIdx = currentDepth === depth ? arguments.length : idx + value.length; + value = value.apply(this, _slice(arguments, idx, endIdx)); + currentDepth += 1; + idx = endIdx; + } + return value; + }); + }); + + /** + * Builds a list from a seed value. Accepts an iterator function, which returns + * either false to stop iteration or an array of length 2 containing the value + * to add to the resulting list and the seed to be used in the next call to the + * iterator function. + * + * The iterator function receives one argument: *(seed)*. + * + * @func + * @memberOf R + * @since v0.10.0 + * @category List + * @sig (a -> [b]) -> * -> [b] + * @param {Function} fn The iterator function. receives one argument, `seed`, and returns + * either false to quit iteration or an array of length two to proceed. The element + * at index 0 of this array will be added to the resulting array, and the element + * at index 1 will be passed to the next call to `fn`. + * @param {*} seed The seed value. + * @return {Array} The final list. + * @example + * + * var f = n => n > 50 ? false : [-n, n + 10]; + * R.unfold(f, 10); //=> [-10, -20, -30, -40, -50] + */ + var unfold = _curry2(function unfold(fn, seed) { + var pair = fn(seed); + var result = []; + while (pair && pair.length) { + result[result.length] = pair[0]; + pair = fn(pair[1]); + } + return result; + }); + + /** + * Returns a new list containing only one copy of each element in the original + * list, based upon the value returned by applying the supplied predicate to + * two list elements. Prefers the first item if two items compare equal based + * on the predicate. + * + * @func + * @memberOf R + * @since v0.2.0 + * @category List + * @sig (a, a -> Boolean) -> [a] -> [a] + * @param {Function} pred A predicate used to test whether two items are equal. + * @param {Array} list The array to consider. + * @return {Array} The list of unique items. + * @example + * + * var strEq = R.eqBy(String); + * R.uniqWith(strEq)([1, '1', 2, 1]); //=> [1, 2] + * R.uniqWith(strEq)([{}, {}]); //=> [{}] + * R.uniqWith(strEq)([1, '1', 1]); //=> [1] + * R.uniqWith(strEq)(['1', 1, 1]); //=> ['1'] + */ + var uniqWith = _curry2(function uniqWith(pred, list) { + var idx = 0; + var len = list.length; + var result = []; + var item; + while (idx < len) { + item = list[idx]; + if (!_containsWith(pred, item, result)) { + result[result.length] = item; + } + idx += 1; + } + return result; + }); + + /** + * Tests the final argument by passing it to the given predicate function. If + * the predicate is not satisfied, the function will return the result of + * calling the `whenFalseFn` function with the same argument. If the predicate + * is satisfied, the argument is returned as is. + * + * @func + * @memberOf R + * @since v0.18.0 + * @category Logic + * @sig (a -> Boolean) -> (a -> a) -> a -> a + * @param {Function} pred A predicate function + * @param {Function} whenFalseFn A function to invoke when the `pred` evaluates + * to a falsy value. + * @param {*} x An object to test with the `pred` function and + * pass to `whenFalseFn` if necessary. + * @return {*} Either `x` or the result of applying `x` to `whenFalseFn`. + * @see R.ifElse, R.when + * @example + * + * // coerceArray :: (a|[a]) -> [a] + * var coerceArray = R.unless(R.isArrayLike, R.of); + * coerceArray([1, 2, 3]); //=> [1, 2, 3] + * coerceArray(1); //=> [1] + */ + var unless = _curry3(function unless(pred, whenFalseFn, x) { + return pred(x) ? x : whenFalseFn(x); + }); + + /** + * Takes a predicate, a transformation function, and an initial value, + * and returns a value of the same type as the initial value. + * It does so by applying the transformation until the predicate is satisfied, + * at which point it returns the satisfactory value. + * + * @func + * @memberOf R + * @since v0.20.0 + * @category Logic + * @sig (a -> Boolean) -> (a -> a) -> a -> a + * @param {Function} pred A predicate function + * @param {Function} fn The iterator function + * @param {*} init Initial value + * @return {*} Final value that satisfies predicate + * @example + * + * R.until(R.gt(R.__, 100), R.multiply(2))(1) // => 128 + */ + var until = _curry3(function until(pred, fn, init) { + var val = init; + while (!pred(val)) { + val = fn(val); + } + return val; + }); + + /** + * Returns a new copy of the array with the element at the provided index + * replaced with the given value. + * + * @func + * @memberOf R + * @since v0.14.0 + * @category List + * @sig Number -> a -> [a] -> [a] + * @param {Number} idx The index to update. + * @param {*} x The value to exist at the given index of the returned array. + * @param {Array|Arguments} list The source array-like object to be updated. + * @return {Array} A copy of `list` with the value at index `idx` replaced with `x`. + * @see R.adjust + * @example + * + * R.update(1, 11, [0, 1, 2]); //=> [0, 11, 2] + * R.update(1)(11)([0, 1, 2]); //=> [0, 11, 2] + */ + var update = _curry3(function update(idx, x, list) { + return adjust(always(x), idx, list); + }); + + /** + * Accepts a function `fn` and a list of transformer functions and returns a + * new curried function. When the new function is invoked, it calls the + * function `fn` with parameters consisting of the result of calling each + * supplied handler on successive arguments to the new function. + * + * If more arguments are passed to the returned function than transformer + * functions, those arguments are passed directly to `fn` as additional + * parameters. If you expect additional arguments that don't need to be + * transformed, although you can ignore them, it's best to pass an identity + * function so that the new function reports the correct arity. + * + * @func + * @memberOf R + * @since v0.1.0 + * @category Function + * @sig (x1 -> x2 -> ... -> z) -> [(a -> x1), (b -> x2), ...] -> (a -> b -> ... -> z) + * @param {Function} fn The function to wrap. + * @param {Array} transformers A list of transformer functions + * @return {Function} The wrapped function. + * @example + * + * R.useWith(Math.pow, [R.identity, R.identity])(3, 4); //=> 81 + * R.useWith(Math.pow, [R.identity, R.identity])(3)(4); //=> 81 + * R.useWith(Math.pow, [R.dec, R.inc])(3, 4); //=> 32 + * R.useWith(Math.pow, [R.dec, R.inc])(3)(4); //=> 32 + */ + var useWith = _curry2(function useWith(fn, transformers) { + return curryN(transformers.length, function () { + var args = []; + var idx = 0; + while (idx < transformers.length) { + args.push(transformers[idx].call(this, arguments[idx])); + idx += 1; + } + return fn.apply(this, args.concat(_slice(arguments, transformers.length))); + }); + }); + + /** + * Returns a list of all the enumerable own properties of the supplied object. + * Note that the order of the output array is not guaranteed across different + * JS platforms. + * + * @func + * @memberOf R + * @since v0.1.0 + * @category Object + * @sig {k: v} -> [v] + * @param {Object} obj The object to extract values from + * @return {Array} An array of the values of the object's own properties. + * @example + * + * R.values({a: 1, b: 2, c: 3}); //=> [1, 2, 3] + */ + var values = _curry1(function values(obj) { + var props = keys(obj); + var len = props.length; + var vals = []; + var idx = 0; + while (idx < len) { + vals[idx] = obj[props[idx]]; + idx += 1; + } + return vals; + }); + + /** + * Returns a list of all the properties, including prototype properties, of the + * supplied object. + * Note that the order of the output array is not guaranteed to be consistent + * across different JS platforms. + * + * @func + * @memberOf R + * @since v0.2.0 + * @category Object + * @sig {k: v} -> [v] + * @param {Object} obj The object to extract values from + * @return {Array} An array of the values of the object's own and prototype properties. + * @example + * + * var F = function() { this.x = 'X'; }; + * F.prototype.y = 'Y'; + * var f = new F(); + * R.valuesIn(f); //=> ['X', 'Y'] + */ + var valuesIn = _curry1(function valuesIn(obj) { + var prop; + var vs = []; + for (prop in obj) { + vs[vs.length] = obj[prop]; + } + return vs; + }); + + /** + * Returns a "view" of the given data structure, determined by the given lens. + * The lens's focus determines which portion of the data structure is visible. + * + * @func + * @memberOf R + * @since v0.16.0 + * @category Object + * @typedefn Lens s a = Functor f => (a -> f a) -> s -> f s + * @sig Lens s a -> s -> a + * @param {Lens} lens + * @param {*} x + * @return {*} + * @see R.prop, R.lensIndex, R.lensProp + * @example + * + * var xLens = R.lensProp('x'); + * + * R.view(xLens, {x: 1, y: 2}); //=> 1 + * R.view(xLens, {x: 4, y: 2}); //=> 4 + */ + // `Const` is a functor that effectively ignores the function given to `map`. + // Using `Const` effectively ignores the setter function of the `lens`, + // leaving the value returned by the getter function unmodified. + var view = function () { + // `Const` is a functor that effectively ignores the function given to `map`. + var Const = function (x) { + return { + value: x, + map: function () { + return this; + } + }; + }; + return _curry2(function view(lens, x) { + // Using `Const` effectively ignores the setter function of the `lens`, + // leaving the value returned by the getter function unmodified. + return lens(Const)(x).value; + }); + }(); + + /** + * Tests the final argument by passing it to the given predicate function. If + * the predicate is satisfied, the function will return the result of calling + * the `whenTrueFn` function with the same argument. If the predicate is not + * satisfied, the argument is returned as is. + * + * @func + * @memberOf R + * @since v0.18.0 + * @category Logic + * @sig (a -> Boolean) -> (a -> a) -> a -> a + * @param {Function} pred A predicate function + * @param {Function} whenTrueFn A function to invoke when the `condition` + * evaluates to a truthy value. + * @param {*} x An object to test with the `pred` function and + * pass to `whenTrueFn` if necessary. + * @return {*} Either `x` or the result of applying `x` to `whenTrueFn`. + * @see R.ifElse, R.unless + * @example + * + * // truncate :: String -> String + * var truncate = R.when( + * R.propSatisfies(R.gt(R.__, 10), 'length'), + * R.pipe(R.take(10), R.append('…'), R.join('')) + * ); + * truncate('12345'); //=> '12345' + * truncate('0123456789ABC'); //=> '0123456789…' + */ + var when = _curry3(function when(pred, whenTrueFn, x) { + return pred(x) ? whenTrueFn(x) : x; + }); + + /** + * Takes a spec object and a test object; returns true if the test satisfies + * the spec. Each of the spec's own properties must be a predicate function. + * Each predicate is applied to the value of the corresponding property of the + * test object. `where` returns true if all the predicates return true, false + * otherwise. + * + * `where` is well suited to declaratively expressing constraints for other + * functions such as `filter` and `find`. + * + * @func + * @memberOf R + * @since v0.1.1 + * @category Object + * @sig {String: (* -> Boolean)} -> {String: *} -> Boolean + * @param {Object} spec + * @param {Object} testObj + * @return {Boolean} + * @example + * + * // pred :: Object -> Boolean + * var pred = R.where({ + * a: R.equals('foo'), + * b: R.complement(R.equals('bar')), + * x: R.gt(_, 10), + * y: R.lt(_, 20) + * }); + * + * pred({a: 'foo', b: 'xxx', x: 11, y: 19}); //=> true + * pred({a: 'xxx', b: 'xxx', x: 11, y: 19}); //=> false + * pred({a: 'foo', b: 'bar', x: 11, y: 19}); //=> false + * pred({a: 'foo', b: 'xxx', x: 10, y: 19}); //=> false + * pred({a: 'foo', b: 'xxx', x: 11, y: 20}); //=> false + */ + var where = _curry2(function where(spec, testObj) { + for (var prop in spec) { + if (_has(prop, spec) && !spec[prop](testObj[prop])) { + return false; + } + } + return true; + }); + + /** + * Wrap a function inside another to allow you to make adjustments to the + * parameters, or do other processing either before the internal function is + * called or with its results. + * + * @func + * @memberOf R + * @since v0.1.0 + * @category Function + * @sig (a... -> b) -> ((a... -> b) -> a... -> c) -> (a... -> c) + * @param {Function} fn The function to wrap. + * @param {Function} wrapper The wrapper function. + * @return {Function} The wrapped function. + * @example + * + * var greet = name => 'Hello ' + name; + * + * var shoutedGreet = R.wrap(greet, (gr, name) => gr(name).toUpperCase()); + * + * shoutedGreet("Kathy"); //=> "HELLO KATHY" + * + * var shortenedGreet = R.wrap(greet, function(gr, name) { + * return gr(name.substring(0, 3)); + * }); + * shortenedGreet("Robert"); //=> "Hello Rob" + */ + var wrap = _curry2(function wrap(fn, wrapper) { + return curryN(fn.length, function () { + return wrapper.apply(this, _concat([fn], arguments)); + }); + }); + + /** + * Creates a new list out of the two supplied by creating each possible pair + * from the lists. + * + * @func + * @memberOf R + * @since v0.1.0 + * @category List + * @sig [a] -> [b] -> [[a,b]] + * @param {Array} as The first list. + * @param {Array} bs The second list. + * @return {Array} The list made by combining each possible pair from + * `as` and `bs` into pairs (`[a, b]`). + * @example + * + * R.xprod([1, 2], ['a', 'b']); //=> [[1, 'a'], [1, 'b'], [2, 'a'], [2, 'b']] + */ + // = xprodWith(prepend); (takes about 3 times as long...) + var xprod = _curry2(function xprod(a, b) { + // = xprodWith(prepend); (takes about 3 times as long...) + var idx = 0; + var ilen = a.length; + var j; + var jlen = b.length; + var result = []; + while (idx < ilen) { + j = 0; + while (j < jlen) { + result[result.length] = [ + a[idx], + b[j] + ]; + j += 1; + } + idx += 1; + } + return result; + }); + + /** + * Creates a new list out of the two supplied by pairing up equally-positioned + * items from both lists. The returned list is truncated to the length of the + * shorter of the two input lists. + * Note: `zip` is equivalent to `zipWith(function(a, b) { return [a, b] })`. + * + * @func + * @memberOf R + * @since v0.1.0 + * @category List + * @sig [a] -> [b] -> [[a,b]] + * @param {Array} list1 The first array to consider. + * @param {Array} list2 The second array to consider. + * @return {Array} The list made by pairing up same-indexed elements of `list1` and `list2`. + * @example + * + * R.zip([1, 2, 3], ['a', 'b', 'c']); //=> [[1, 'a'], [2, 'b'], [3, 'c']] + */ + var zip = _curry2(function zip(a, b) { + var rv = []; + var idx = 0; + var len = Math.min(a.length, b.length); + while (idx < len) { + rv[idx] = [ + a[idx], + b[idx] + ]; + idx += 1; + } + return rv; + }); + + /** + * Creates a new object out of a list of keys and a list of values. + * Key/value pairing is truncated to the length of the shorter of the two lists. + * Note: `zipObj` is equivalent to `pipe(zipWith(pair), fromPairs)`. + * + * @func + * @memberOf R + * @since v0.3.0 + * @category List + * @sig [String] -> [*] -> {String: *} + * @param {Array} keys The array that will be properties on the output object. + * @param {Array} values The list of values on the output object. + * @return {Object} The object made by pairing up same-indexed elements of `keys` and `values`. + * @example + * + * R.zipObj(['a', 'b', 'c'], [1, 2, 3]); //=> {a: 1, b: 2, c: 3} + */ + var zipObj = _curry2(function zipObj(keys, values) { + var idx = 0; + var len = Math.min(keys.length, values.length); + var out = {}; + while (idx < len) { + out[keys[idx]] = values[idx]; + idx += 1; + } + return out; + }); + + /** + * Creates a new list out of the two supplied by applying the function to each + * equally-positioned pair in the lists. The returned list is truncated to the + * length of the shorter of the two input lists. + * + * @function + * @memberOf R + * @since v0.1.0 + * @category List + * @sig (a,b -> c) -> [a] -> [b] -> [c] + * @param {Function} fn The function used to combine the two elements into one value. + * @param {Array} list1 The first array to consider. + * @param {Array} list2 The second array to consider. + * @return {Array} The list made by combining same-indexed elements of `list1` and `list2` + * using `fn`. + * @example + * + * var f = (x, y) => { + * // ... + * }; + * R.zipWith(f, [1, 2, 3], ['a', 'b', 'c']); + * //=> [f(1, 'a'), f(2, 'b'), f(3, 'c')] + */ + var zipWith = _curry3(function zipWith(fn, a, b) { + var rv = []; + var idx = 0; + var len = Math.min(a.length, b.length); + while (idx < len) { + rv[idx] = fn(a[idx], b[idx]); + idx += 1; + } + return rv; + }); + + /** + * A function that always returns `false`. Any passed in parameters are ignored. + * + * @func + * @memberOf R + * @since v0.9.0 + * @category Function + * @sig * -> Boolean + * @param {*} + * @return {Boolean} + * @see R.always, R.T + * @example + * + * R.F(); //=> false + */ + var F = always(false); + + /** + * A function that always returns `true`. Any passed in parameters are ignored. + * + * @func + * @memberOf R + * @since v0.9.0 + * @category Function + * @sig * -> Boolean + * @param {*} + * @return {Boolean} + * @see R.always, R.F + * @example + * + * R.T(); //=> true + */ + var T = always(true); + + /** + * Copies an object. + * + * @private + * @param {*} value The value to be copied + * @param {Array} refFrom Array containing the source references + * @param {Array} refTo Array containing the copied source references + * @param {Boolean} deep Whether or not to perform deep cloning. + * @return {*} The copied value. + */ + var _clone = function _clone(value, refFrom, refTo, deep) { + var copy = function copy(copiedValue) { + var len = refFrom.length; + var idx = 0; + while (idx < len) { + if (value === refFrom[idx]) { + return refTo[idx]; + } + idx += 1; + } + refFrom[idx + 1] = value; + refTo[idx + 1] = copiedValue; + for (var key in value) { + copiedValue[key] = deep ? _clone(value[key], refFrom, refTo, true) : value[key]; + } + return copiedValue; + }; + switch (type(value)) { + case 'Object': + return copy({}); + case 'Array': + return copy([]); + case 'Date': + return new Date(value.valueOf()); + case 'RegExp': + return _cloneRegExp(value); + default: + return value; + } + }; + + var _createPartialApplicator = function _createPartialApplicator(concat) { + return _curry2(function (fn, args) { + return _arity(Math.max(0, fn.length - args.length), function () { + return fn.apply(this, concat(args, arguments)); + }); + }); + }; + + var _dropLast = function dropLast(n, xs) { + return take(n < xs.length ? xs.length - n : 0, xs); + }; + + // Values of other types are only equal if identical. + var _equals = function _equals(a, b, stackA, stackB) { + if (identical(a, b)) { + return true; + } + if (type(a) !== type(b)) { + return false; + } + if (a == null || b == null) { + return false; + } + if (typeof a.equals === 'function' || typeof b.equals === 'function') { + return typeof a.equals === 'function' && a.equals(b) && typeof b.equals === 'function' && b.equals(a); + } + switch (type(a)) { + case 'Arguments': + case 'Array': + case 'Object': + if (typeof a.constructor === 'function' && _functionName(a.constructor) === 'Promise') { + return a === b; + } + break; + case 'Boolean': + case 'Number': + case 'String': + if (!(typeof a === typeof b && identical(a.valueOf(), b.valueOf()))) { + return false; + } + break; + case 'Date': + if (!identical(a.valueOf(), b.valueOf())) { + return false; + } + break; + case 'Error': + return a.name === b.name && a.message === b.message; + case 'RegExp': + if (!(a.source === b.source && a.global === b.global && a.ignoreCase === b.ignoreCase && a.multiline === b.multiline && a.sticky === b.sticky && a.unicode === b.unicode)) { + return false; + } + break; + case 'Map': + case 'Set': + if (!_equals(_arrayFromIterator(a.entries()), _arrayFromIterator(b.entries()), stackA, stackB)) { + return false; + } + break; + case 'Int8Array': + case 'Uint8Array': + case 'Uint8ClampedArray': + case 'Int16Array': + case 'Uint16Array': + case 'Int32Array': + case 'Uint32Array': + case 'Float32Array': + case 'Float64Array': + break; + case 'ArrayBuffer': + break; + default: + // Values of other types are only equal if identical. + return false; + } + var keysA = keys(a); + if (keysA.length !== keys(b).length) { + return false; + } + var idx = stackA.length - 1; + while (idx >= 0) { + if (stackA[idx] === a) { + return stackB[idx] === b; + } + idx -= 1; + } + stackA.push(a); + stackB.push(b); + idx = keysA.length - 1; + while (idx >= 0) { + var key = keysA[idx]; + if (!(_has(key, b) && _equals(b[key], a[key], stackA, stackB))) { + return false; + } + idx -= 1; + } + stackA.pop(); + stackB.pop(); + return true; + }; + + /** + * `_makeFlat` is a helper function that returns a one-level or fully recursive + * function based on the flag passed in. + * + * @private + */ + var _makeFlat = function _makeFlat(recursive) { + return function flatt(list) { + var value, jlen, j; + var result = []; + var idx = 0; + var ilen = list.length; + while (idx < ilen) { + if (isArrayLike(list[idx])) { + value = recursive ? flatt(list[idx]) : list[idx]; + j = 0; + jlen = value.length; + while (j < jlen) { + result[result.length] = value[j]; + j += 1; + } + } else { + result[result.length] = list[idx]; + } + idx += 1; + } + return result; + }; + }; + + var _reduce = function () { + function _arrayReduce(xf, acc, list) { + var idx = 0; + var len = list.length; + while (idx < len) { + acc = xf['@@transducer/step'](acc, list[idx]); + if (acc && acc['@@transducer/reduced']) { + acc = acc['@@transducer/value']; + break; + } + idx += 1; + } + return xf['@@transducer/result'](acc); + } + function _iterableReduce(xf, acc, iter) { + var step = iter.next(); + while (!step.done) { + acc = xf['@@transducer/step'](acc, step.value); + if (acc && acc['@@transducer/reduced']) { + acc = acc['@@transducer/value']; + break; + } + step = iter.next(); + } + return xf['@@transducer/result'](acc); + } + function _methodReduce(xf, acc, obj) { + return xf['@@transducer/result'](obj.reduce(bind(xf['@@transducer/step'], xf), acc)); + } + var symIterator = typeof Symbol !== 'undefined' ? Symbol.iterator : '@@iterator'; + return function _reduce(fn, acc, list) { + if (typeof fn === 'function') { + fn = _xwrap(fn); + } + if (isArrayLike(list)) { + return _arrayReduce(fn, acc, list); + } + if (typeof list.reduce === 'function') { + return _methodReduce(fn, acc, list); + } + if (list[symIterator] != null) { + return _iterableReduce(fn, acc, list[symIterator]()); + } + if (typeof list.next === 'function') { + return _iterableReduce(fn, acc, list); + } + throw new TypeError('reduce: list must be array or iterable'); + }; + }(); + + var _stepCat = function () { + var _stepCatArray = { + '@@transducer/init': Array, + '@@transducer/step': function (xs, x) { + xs.push(x); + return xs; + }, + '@@transducer/result': _identity + }; + var _stepCatString = { + '@@transducer/init': String, + '@@transducer/step': function (a, b) { + return a + b; + }, + '@@transducer/result': _identity + }; + var _stepCatObject = { + '@@transducer/init': Object, + '@@transducer/step': function (result, input) { + return _assign(result, isArrayLike(input) ? objOf(input[0], input[1]) : input); + }, + '@@transducer/result': _identity + }; + return function _stepCat(obj) { + if (_isTransformer(obj)) { + return obj; + } + if (isArrayLike(obj)) { + return _stepCatArray; + } + if (typeof obj === 'string') { + return _stepCatString; + } + if (typeof obj === 'object') { + return _stepCatObject; + } + throw new Error('Cannot create transformer for ' + obj); + }; + }(); + + var _xdropLastWhile = function () { + function XDropLastWhile(fn, xf) { + this.f = fn; + this.retained = []; + this.xf = xf; + } + XDropLastWhile.prototype['@@transducer/init'] = _xfBase.init; + XDropLastWhile.prototype['@@transducer/result'] = function (result) { + this.retained = null; + return this.xf['@@transducer/result'](result); + }; + XDropLastWhile.prototype['@@transducer/step'] = function (result, input) { + return this.f(input) ? this.retain(result, input) : this.flush(result, input); + }; + XDropLastWhile.prototype.flush = function (result, input) { + result = _reduce(this.xf['@@transducer/step'], result, this.retained); + this.retained = []; + return this.xf['@@transducer/step'](result, input); + }; + XDropLastWhile.prototype.retain = function (result, input) { + this.retained.push(input); + return result; + }; + return _curry2(function _xdropLastWhile(fn, xf) { + return new XDropLastWhile(fn, xf); + }); + }(); + + var _xgroupBy = function () { + function XGroupBy(f, xf) { + this.xf = xf; + this.f = f; + this.inputs = {}; + } + XGroupBy.prototype['@@transducer/init'] = _xfBase.init; + XGroupBy.prototype['@@transducer/result'] = function (result) { + var key; + for (key in this.inputs) { + if (_has(key, this.inputs)) { + result = this.xf['@@transducer/step'](result, this.inputs[key]); + if (result['@@transducer/reduced']) { + result = result['@@transducer/value']; + break; + } + } + } + this.inputs = null; + return this.xf['@@transducer/result'](result); + }; + XGroupBy.prototype['@@transducer/step'] = function (result, input) { + var key = this.f(input); + this.inputs[key] = this.inputs[key] || [ + key, + [] + ]; + this.inputs[key][1] = append(input, this.inputs[key][1]); + return result; + }; + return _curry2(function _xgroupBy(f, xf) { + return new XGroupBy(f, xf); + }); + }(); + + /** + * Creates a new list iteration function from an existing one by adding two new + * parameters to its callback function: the current index, and the entire list. + * + * This would turn, for instance, Ramda's simple `map` function into one that + * more closely resembles `Array.prototype.map`. Note that this will only work + * for functions in which the iteration callback function is the first + * parameter, and where the list is the last parameter. (This latter might be + * unimportant if the list parameter is not used.) + * + * @func + * @memberOf R + * @since v0.15.0 + * @category Function + * @category List + * @sig ((a ... -> b) ... -> [a] -> *) -> (a ..., Int, [a] -> b) ... -> [a] -> *) + * @param {Function} fn A list iteration function that does not pass index or list to its callback + * @return {Function} An altered list iteration function that passes (item, index, list) to its callback + * @example + * + * var mapIndexed = R.addIndex(R.map); + * mapIndexed((val, idx) => idx + '-' + val, ['f', 'o', 'o', 'b', 'a', 'r']); + * //=> ['0-f', '1-o', '2-o', '3-b', '4-a', '5-r'] + */ + var addIndex = _curry1(function addIndex(fn) { + return curryN(fn.length, function () { + var idx = 0; + var origFn = arguments[0]; + var list = arguments[arguments.length - 1]; + var args = _slice(arguments); + args[0] = function () { + var result = origFn.apply(this, _concat(arguments, [ + idx, + list + ])); + idx += 1; + return result; + }; + return fn.apply(this, args); + }); + }); + + /** + * Wraps a function of any arity (including nullary) in a function that accepts + * exactly 2 parameters. Any extraneous parameters will not be passed to the + * supplied function. + * + * @func + * @memberOf R + * @since v0.2.0 + * @category Function + * @sig (* -> c) -> (a, b -> c) + * @param {Function} fn The function to wrap. + * @return {Function} A new function wrapping `fn`. The new function is guaranteed to be of + * arity 2. + * @example + * + * var takesThreeArgs = function(a, b, c) { + * return [a, b, c]; + * }; + * takesThreeArgs.length; //=> 3 + * takesThreeArgs(1, 2, 3); //=> [1, 2, 3] + * + * var takesTwoArgs = R.binary(takesThreeArgs); + * takesTwoArgs.length; //=> 2 + * // Only 2 arguments are passed to the wrapped function + * takesTwoArgs(1, 2, 3); //=> [1, 2, undefined] + */ + var binary = _curry1(function binary(fn) { + return nAry(2, fn); + }); + + /** + * Creates a deep copy of the value which may contain (nested) `Array`s and + * `Object`s, `Number`s, `String`s, `Boolean`s and `Date`s. `Function`s are not + * copied, but assigned by their reference. + * + * Dispatches to a `clone` method if present. + * + * @func + * @memberOf R + * @since v0.1.0 + * @category Object + * @sig {*} -> {*} + * @param {*} value The object or array to clone + * @return {*} A new object or array. + * @example + * + * var objects = [{}, {}, {}]; + * var objectsClone = R.clone(objects); + * objects[0] === objectsClone[0]; //=> false + */ + var clone = _curry1(function clone(value) { + return value != null && typeof value.clone === 'function' ? value.clone() : _clone(value, [], [], true); + }); + + /** + * Returns a curried equivalent of the provided function. The curried function + * has two unusual capabilities. First, its arguments needn't be provided one + * at a time. If `f` is a ternary function and `g` is `R.curry(f)`, the + * following are equivalent: + * + * - `g(1)(2)(3)` + * - `g(1)(2, 3)` + * - `g(1, 2)(3)` + * - `g(1, 2, 3)` + * + * Secondly, the special placeholder value `R.__` may be used to specify + * "gaps", allowing partial application of any combination of arguments, + * regardless of their positions. If `g` is as above and `_` is `R.__`, the + * following are equivalent: + * + * - `g(1, 2, 3)` + * - `g(_, 2, 3)(1)` + * - `g(_, _, 3)(1)(2)` + * - `g(_, _, 3)(1, 2)` + * - `g(_, 2)(1)(3)` + * - `g(_, 2)(1, 3)` + * - `g(_, 2)(_, 3)(1)` + * + * @func + * @memberOf R + * @since v0.1.0 + * @category Function + * @sig (* -> a) -> (* -> a) + * @param {Function} fn The function to curry. + * @return {Function} A new, curried function. + * @see R.curryN + * @example + * + * var addFourNumbers = (a, b, c, d) => a + b + c + d; + * + * var curriedAddFourNumbers = R.curry(addFourNumbers); + * var f = curriedAddFourNumbers(1, 2); + * var g = f(3); + * g(4); //=> 10 + */ + var curry = _curry1(function curry(fn) { + return curryN(fn.length, fn); + }); + + /** + * Returns all but the first `n` elements of the given list, string, or + * transducer/transformer (or object with a `drop` method). + * + * Dispatches to the `drop` method of the second argument, if present. + * + * @func + * @memberOf R + * @since v0.1.0 + * @category List + * @sig Number -> [a] -> [a] + * @sig Number -> String -> String + * @param {Number} n + * @param {*} list + * @return {*} + * @see R.take, R.transduce + * @example + * + * R.drop(1, ['foo', 'bar', 'baz']); //=> ['bar', 'baz'] + * R.drop(2, ['foo', 'bar', 'baz']); //=> ['baz'] + * R.drop(3, ['foo', 'bar', 'baz']); //=> [] + * R.drop(4, ['foo', 'bar', 'baz']); //=> [] + * R.drop(3, 'ramda'); //=> 'da' + */ + var drop = _curry2(_dispatchable('drop', _xdrop, function drop(n, xs) { + return slice(Math.max(0, n), Infinity, xs); + })); + + /** + * Returns a list containing all but the last `n` elements of the given `list`. + * + * @func + * @memberOf R + * @since v0.16.0 + * @category List + * @sig Number -> [a] -> [a] + * @sig Number -> String -> String + * @param {Number} n The number of elements of `xs` to skip. + * @param {Array} xs The collection to consider. + * @return {Array} + * @see R.takeLast + * @example + * + * R.dropLast(1, ['foo', 'bar', 'baz']); //=> ['foo', 'bar'] + * R.dropLast(2, ['foo', 'bar', 'baz']); //=> ['foo'] + * R.dropLast(3, ['foo', 'bar', 'baz']); //=> [] + * R.dropLast(4, ['foo', 'bar', 'baz']); //=> [] + * R.dropLast(3, 'ramda'); //=> 'ra' + */ + var dropLast = _curry2(_dispatchable('dropLast', _xdropLast, _dropLast)); + + /** + * Returns a new list containing all but last the`n` elements of a given list, + * passing each value from the right to the supplied predicate function, + * skipping elements while the predicate function returns `true`. The predicate + * function is passed one argument: (value)*. + * + * @func + * @memberOf R + * @since v0.16.0 + * @category List + * @sig (a -> Boolean) -> [a] -> [a] + * @param {Function} fn The function called per iteration. + * @param {Array} list The collection to iterate over. + * @return {Array} A new array. + * @see R.takeLastWhile, R.addIndex + * @example + * + * var lteThree = x => x <= 3; + * + * R.dropLastWhile(lteThree, [1, 2, 3, 4, 3, 2, 1]); //=> [1, 2, 3, 4] + */ + var dropLastWhile = _curry2(_dispatchable('dropLastWhile', _xdropLastWhile, _dropLastWhile)); + + /** + * Returns `true` if its arguments are equivalent, `false` otherwise. Handles + * cyclical data structures. + * + * Dispatches symmetrically to the `equals` methods of both arguments, if + * present. + * + * @func + * @memberOf R + * @since v0.15.0 + * @category Relation + * @sig a -> b -> Boolean + * @param {*} a + * @param {*} b + * @return {Boolean} + * @example + * + * R.equals(1, 1); //=> true + * R.equals(1, '1'); //=> false + * R.equals([1, 2, 3], [1, 2, 3]); //=> true + * + * var a = {}; a.v = a; + * var b = {}; b.v = b; + * R.equals(a, b); //=> true + */ + var equals = _curry2(function equals(a, b) { + return _equals(a, b, [], []); + }); + + /** + * Takes a predicate and a "filterable", and returns a new filterable of the + * same type containing the members of the given filterable which satisfy the + * given predicate. + * + * Dispatches to the `filter` method of the second argument, if present. + * + * Acts as a transducer if a transformer is given in list position. + * + * @func + * @memberOf R + * @since v0.1.0 + * @category List + * @sig Filterable f => (a -> Boolean) -> f a -> f a + * @param {Function} pred + * @param {Array} filterable + * @return {Array} + * @see R.reject, R.transduce, R.addIndex + * @example + * + * var isEven = n => n % 2 === 0; + * + * R.filter(isEven, [1, 2, 3, 4]); //=> [2, 4] + * + * R.filter(isEven, {a: 1, b: 2, c: 3, d: 4}); //=> {b: 2, d: 4} + */ + // else + var filter = _curry2(_dispatchable('filter', _xfilter, function (pred, filterable) { + return _isObject(filterable) ? _reduce(function (acc, key) { + if (pred(filterable[key])) { + acc[key] = filterable[key]; + } + return acc; + }, {}, keys(filterable)) : // else + _filter(pred, filterable); + })); + + /** + * Returns a new list by pulling every item out of it (and all its sub-arrays) + * and putting them in a new array, depth-first. + * + * @func + * @memberOf R + * @since v0.1.0 + * @category List + * @sig [a] -> [b] + * @param {Array} list The array to consider. + * @return {Array} The flattened list. + * @see R.unnest + * @example + * + * R.flatten([1, 2, [3, 4], 5, [6, [7, 8, [9, [10, 11], 12]]]]); + * //=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] + */ + var flatten = _curry1(_makeFlat(true)); + + /** + * Returns a new function much like the supplied one, except that the first two + * arguments' order is reversed. + * + * @func + * @memberOf R + * @since v0.1.0 + * @category Function + * @sig (a -> b -> c -> ... -> z) -> (b -> a -> c -> ... -> z) + * @param {Function} fn The function to invoke with its first two parameters reversed. + * @return {*} The result of invoking `fn` with its first two parameters' order reversed. + * @example + * + * var mergeThree = (a, b, c) => [].concat(a, b, c); + * + * mergeThree(1, 2, 3); //=> [1, 2, 3] + * + * R.flip(mergeThree)(1, 2, 3); //=> [2, 1, 3] + */ + var flip = _curry1(function flip(fn) { + return curry(function (a, b) { + var args = _slice(arguments); + args[0] = b; + args[1] = a; + return fn.apply(this, args); + }); + }); + + /** + * Returns the first element of the given list or string. In some libraries + * this function is named `first`. + * + * @func + * @memberOf R + * @since v0.1.0 + * @category List + * @sig [a] -> a | Undefined + * @sig String -> String + * @param {Array|String} list + * @return {*} + * @see R.tail, R.init, R.last + * @example + * + * R.head(['fi', 'fo', 'fum']); //=> 'fi' + * R.head([]); //=> undefined + * + * R.head('abc'); //=> 'a' + * R.head(''); //=> '' + */ + var head = nth(0); + + /** + * Returns all but the last element of the given list or string. + * + * @func + * @memberOf R + * @since v0.9.0 + * @category List + * @sig [a] -> [a] + * @sig String -> String + * @param {*} list + * @return {*} + * @see R.last, R.head, R.tail + * @example + * + * R.init([1, 2, 3]); //=> [1, 2] + * R.init([1, 2]); //=> [1] + * R.init([1]); //=> [] + * R.init([]); //=> [] + * + * R.init('abc'); //=> 'ab' + * R.init('ab'); //=> 'a' + * R.init('a'); //=> '' + * R.init(''); //=> '' + */ + var init = slice(0, -1); + + /** + * Combines two lists into a set (i.e. no duplicates) composed of those + * elements common to both lists. Duplication is determined according to the + * value returned by applying the supplied predicate to two list elements. + * + * @func + * @memberOf R + * @since v0.1.0 + * @category Relation + * @sig (a -> a -> Boolean) -> [*] -> [*] -> [*] + * @param {Function} pred A predicate function that determines whether + * the two supplied elements are equal. + * @param {Array} list1 One list of items to compare + * @param {Array} list2 A second list of items to compare + * @return {Array} A new list containing those elements common to both lists. + * @see R.intersection + * @example + * + * var buffaloSpringfield = [ + * {id: 824, name: 'Richie Furay'}, + * {id: 956, name: 'Dewey Martin'}, + * {id: 313, name: 'Bruce Palmer'}, + * {id: 456, name: 'Stephen Stills'}, + * {id: 177, name: 'Neil Young'} + * ]; + * var csny = [ + * {id: 204, name: 'David Crosby'}, + * {id: 456, name: 'Stephen Stills'}, + * {id: 539, name: 'Graham Nash'}, + * {id: 177, name: 'Neil Young'} + * ]; + * + * R.intersectionWith(R.eqBy(R.prop('id')), buffaloSpringfield, csny); + * //=> [{id: 456, name: 'Stephen Stills'}, {id: 177, name: 'Neil Young'}] + */ + var intersectionWith = _curry3(function intersectionWith(pred, list1, list2) { + var lookupList, filteredList; + if (list1.length > list2.length) { + lookupList = list1; + filteredList = list2; + } else { + lookupList = list2; + filteredList = list1; + } + var results = []; + var idx = 0; + while (idx < filteredList.length) { + if (_containsWith(pred, filteredList[idx], lookupList)) { + results[results.length] = filteredList[idx]; + } + idx += 1; + } + return uniqWith(pred, results); + }); + + /** + * Transforms the items of the list with the transducer and appends the + * transformed items to the accumulator using an appropriate iterator function + * based on the accumulator type. + * + * The accumulator can be an array, string, object or a transformer. Iterated + * items will be appended to arrays and concatenated to strings. Objects will + * be merged directly or 2-item arrays will be merged as key, value pairs. + * + * The accumulator can also be a transformer object that provides a 2-arity + * reducing iterator function, step, 0-arity initial value function, init, and + * 1-arity result extraction function result. The step function is used as the + * iterator function in reduce. The result function is used to convert the + * final accumulator into the return type and in most cases is R.identity. The + * init function is used to provide the initial accumulator. + * + * The iteration is performed with R.reduce after initializing the transducer. + * + * @func + * @memberOf R + * @since v0.12.0 + * @category List + * @sig a -> (b -> b) -> [c] -> a + * @param {*} acc The initial accumulator value. + * @param {Function} xf The transducer function. Receives a transformer and returns a transformer. + * @param {Array} list The list to iterate over. + * @return {*} The final, accumulated value. + * @example + * + * var numbers = [1, 2, 3, 4]; + * var transducer = R.compose(R.map(R.add(1)), R.take(2)); + * + * R.into([], transducer, numbers); //=> [2, 3] + * + * var intoArray = R.into([]); + * intoArray(transducer, numbers); //=> [2, 3] + */ + var into = _curry3(function into(acc, xf, list) { + return _isTransformer(acc) ? _reduce(xf(acc), acc['@@transducer/init'](), list) : _reduce(xf(_stepCat(acc)), _clone(acc, [], [], false), list); + }); + + /** + * Same as R.invertObj, however this accounts for objects with duplicate values + * by putting the values into an array. + * + * @func + * @memberOf R + * @since v0.9.0 + * @category Object + * @sig {s: x} -> {x: [ s, ... ]} + * @param {Object} obj The object or array to invert + * @return {Object} out A new object with keys + * in an array. + * @example + * + * var raceResultsByFirstName = { + * first: 'alice', + * second: 'jake', + * third: 'alice', + * }; + * R.invert(raceResultsByFirstName); + * //=> { 'alice': ['first', 'third'], 'jake':['second'] } + */ + var invert = _curry1(function invert(obj) { + var props = keys(obj); + var len = props.length; + var idx = 0; + var out = {}; + while (idx < len) { + var key = props[idx]; + var val = obj[key]; + var list = _has(val, out) ? out[val] : out[val] = []; + list[list.length] = key; + idx += 1; + } + return out; + }); + + /** + * Returns a new object with the keys of the given object as values, and the + * values of the given object, which are coerced to strings, as keys. Note + * that the last key found is preferred when handling the same value. + * + * @func + * @memberOf R + * @since v0.9.0 + * @category Object + * @sig {s: x} -> {x: s} + * @param {Object} obj The object or array to invert + * @return {Object} out A new object + * @example + * + * var raceResults = { + * first: 'alice', + * second: 'jake' + * }; + * R.invertObj(raceResults); + * //=> { 'alice': 'first', 'jake':'second' } + * + * // Alternatively: + * var raceResults = ['alice', 'jake']; + * R.invertObj(raceResults); + * //=> { 'alice': '0', 'jake':'1' } + */ + var invertObj = _curry1(function invertObj(obj) { + var props = keys(obj); + var len = props.length; + var idx = 0; + var out = {}; + while (idx < len) { + var key = props[idx]; + out[obj[key]] = key; + idx += 1; + } + return out; + }); + + /** + * Returns `true` if the given value is its type's empty value; `false` + * otherwise. + * + * @func + * @memberOf R + * @since v0.1.0 + * @category Logic + * @sig a -> Boolean + * @param {*} x + * @return {Boolean} + * @see R.empty + * @example + * + * R.isEmpty([1, 2, 3]); //=> false + * R.isEmpty([]); //=> true + * R.isEmpty(''); //=> true + * R.isEmpty(null); //=> false + * R.isEmpty({}); //=> true + * R.isEmpty({length: 0}); //=> false + */ + var isEmpty = _curry1(function isEmpty(x) { + return x != null && equals(x, empty(x)); + }); + + /** + * Returns the last element of the given list or string. + * + * @func + * @memberOf R + * @since v0.1.4 + * @category List + * @sig [a] -> a | Undefined + * @sig String -> String + * @param {*} list + * @return {*} + * @see R.init, R.head, R.tail + * @example + * + * R.last(['fi', 'fo', 'fum']); //=> 'fum' + * R.last([]); //=> undefined + * + * R.last('abc'); //=> 'c' + * R.last(''); //=> '' + */ + var last = nth(-1); + + /** + * Returns the position of the last occurrence of an item in an array, or -1 if + * the item is not included in the array. `R.equals` is used to determine + * equality. + * + * @func + * @memberOf R + * @since v0.1.0 + * @category List + * @sig a -> [a] -> Number + * @param {*} target The item to find. + * @param {Array} xs The array to search in. + * @return {Number} the index of the target, or -1 if the target is not found. + * @see R.indexOf + * @example + * + * R.lastIndexOf(3, [-1,3,3,0,1,2,3,4]); //=> 6 + * R.lastIndexOf(10, [1,2,3,4]); //=> -1 + */ + var lastIndexOf = _curry2(function lastIndexOf(target, xs) { + if (typeof xs.lastIndexOf === 'function' && !_isArray(xs)) { + return xs.lastIndexOf(target); + } else { + var idx = xs.length - 1; + while (idx >= 0) { + if (equals(xs[idx], target)) { + return idx; + } + idx -= 1; + } + return -1; + } + }); + + /** + * Takes a function and + * a [functor](https://github.com/fantasyland/fantasy-land#functor), + * applies the function to each of the functor's values, and returns + * a functor of the same shape. + * + * Ramda provides suitable `map` implementations for `Array` and `Object`, + * so this function may be applied to `[1, 2, 3]` or `{x: 1, y: 2, z: 3}`. + * + * Dispatches to the `map` method of the second argument, if present. + * + * Acts as a transducer if a transformer is given in list position. + * + * Also treats functions as functors and will compose them together. + * + * @func + * @memberOf R + * @since v0.1.0 + * @category List + * @sig Functor f => (a -> b) -> f a -> f b + * @param {Function} fn The function to be called on every element of the input `list`. + * @param {Array} list The list to be iterated over. + * @return {Array} The new list. + * @see R.transduce, R.addIndex + * @example + * + * var double = x => x * 2; + * + * R.map(double, [1, 2, 3]); //=> [2, 4, 6] + * + * R.map(double, {x: 1, y: 2, z: 3}); //=> {x: 2, y: 4, z: 6} + */ + var map = _curry2(_dispatchable('map', _xmap, function map(fn, functor) { + switch (Object.prototype.toString.call(functor)) { + case '[object Function]': + return curryN(functor.length, function () { + return fn.call(this, functor.apply(this, arguments)); + }); + case '[object Object]': + return _reduce(function (acc, key) { + acc[key] = fn(functor[key]); + return acc; + }, {}, keys(functor)); + default: + return _map(fn, functor); + } + })); + + /** + * An Object-specific version of `map`. The function is applied to three + * arguments: *(value, key, obj)*. If only the value is significant, use + * `map` instead. + * + * @func + * @memberOf R + * @since v0.9.0 + * @category Object + * @sig ((*, String, Object) -> *) -> Object -> Object + * @param {Function} fn + * @param {Object} obj + * @return {Object} + * @see R.map + * @example + * + * var values = { x: 1, y: 2, z: 3 }; + * var prependKeyAndDouble = (num, key, obj) => key + (num * 2); + * + * R.mapObjIndexed(prependKeyAndDouble, values); //=> { x: 'x2', y: 'y4', z: 'z6' } + */ + var mapObjIndexed = _curry2(function mapObjIndexed(fn, obj) { + return _reduce(function (acc, key) { + acc[key] = fn(obj[key], key, obj); + return acc; + }, {}, keys(obj)); + }); + + /** + * Creates a new object with the own properties of the two provided objects. If + * a key exists in both objects, the provided function is applied to the values + * associated with the key in each object, with the result being used as the + * value associated with the key in the returned object. The key will be + * excluded from the returned object if the resulting value is `undefined`. + * + * @func + * @memberOf R + * @since v0.19.0 + * @category Object + * @sig (a -> a -> a) -> {a} -> {a} -> {a} + * @param {Function} fn + * @param {Object} l + * @param {Object} r + * @return {Object} + * @see R.merge, R.mergeWithKey + * @example + * + * R.mergeWith(R.concat, + * { a: true, values: [10, 20] }, + * { b: true, values: [15, 35] }); + * //=> { a: true, b: true, values: [10, 20, 15, 35] } + */ + var mergeWith = _curry3(function mergeWith(fn, l, r) { + return mergeWithKey(function (_, _l, _r) { + return fn(_l, _r); + }, l, r); + }); + + /** + * Takes a function `f` and a list of arguments, and returns a function `g`. + * When applied, `g` returns the result of applying `f` to the arguments + * provided initially followed by the arguments provided to `g`. + * + * @func + * @memberOf R + * @since v0.10.0 + * @category Function + * @sig ((a, b, c, ..., n) -> x) -> [a, b, c, ...] -> ((d, e, f, ..., n) -> x) + * @param {Function} f + * @param {Array} args + * @return {Function} + * @see R.partialRight + * @example + * + * var multiply = (a, b) => a * b; + * var double = R.partial(multiply, [2]); + * double(2); //=> 4 + * + * var greet = (salutation, title, firstName, lastName) => + * salutation + ', ' + title + ' ' + firstName + ' ' + lastName + '!'; + * + * var sayHello = R.partial(greet, ['Hello']); + * var sayHelloToMs = R.partial(sayHello, ['Ms.']); + * sayHelloToMs('Jane', 'Jones'); //=> 'Hello, Ms. Jane Jones!' + */ + var partial = _createPartialApplicator(_concat); + + /** + * Takes a function `f` and a list of arguments, and returns a function `g`. + * When applied, `g` returns the result of applying `f` to the arguments + * provided to `g` followed by the arguments provided initially. + * + * @func + * @memberOf R + * @since v0.10.0 + * @category Function + * @sig ((a, b, c, ..., n) -> x) -> [d, e, f, ..., n] -> ((a, b, c, ...) -> x) + * @param {Function} f + * @param {Array} args + * @return {Function} + * @see R.partial + * @example + * + * var greet = (salutation, title, firstName, lastName) => + * salutation + ', ' + title + ' ' + firstName + ' ' + lastName + '!'; + * + * var greetMsJaneJones = R.partialRight(greet, ['Ms.', 'Jane', 'Jones']); + * + * greetMsJaneJones('Hello'); //=> 'Hello, Ms. Jane Jones!' + */ + var partialRight = _createPartialApplicator(flip(_concat)); + + /** + * Determines whether a nested path on an object has a specific value, in + * `R.equals` terms. Most likely used to filter a list. + * + * @func + * @memberOf R + * @since v0.7.0 + * @category Relation + * @sig [String] -> * -> {String: *} -> Boolean + * @param {Array} path The path of the nested property to use + * @param {*} val The value to compare the nested property with + * @param {Object} obj The object to check the nested property in + * @return {Boolean} `true` if the value equals the nested object property, + * `false` otherwise. + * @example + * + * var user1 = { address: { zipCode: 90210 } }; + * var user2 = { address: { zipCode: 55555 } }; + * var user3 = { name: 'Bob' }; + * var users = [ user1, user2, user3 ]; + * var isFamous = R.pathEq(['address', 'zipCode'], 90210); + * R.filter(isFamous, users); //=> [ user1 ] + */ + var pathEq = _curry3(function pathEq(_path, val, obj) { + return equals(path(_path, obj), val); + }); + + /** + * Returns a new list by plucking the same named property off all objects in + * the list supplied. + * + * @func + * @memberOf R + * @since v0.1.0 + * @category List + * @sig k -> [{k: v}] -> [v] + * @param {Number|String} key The key name to pluck off of each object. + * @param {Array} list The array to consider. + * @return {Array} The list of values for the given key. + * @see R.props + * @example + * + * R.pluck('a')([{a: 1}, {a: 2}]); //=> [1, 2] + * R.pluck(0)([[1, 2], [3, 4]]); //=> [1, 3] + */ + var pluck = _curry2(function pluck(p, list) { + return map(prop(p), list); + }); + + /** + * Reasonable analog to SQL `select` statement. + * + * @func + * @memberOf R + * @since v0.1.0 + * @category Object + * @category Relation + * @sig [k] -> [{k: v}] -> [{k: v}] + * @param {Array} props The property names to project + * @param {Array} objs The objects to query + * @return {Array} An array of objects with just the `props` properties. + * @example + * + * var abby = {name: 'Abby', age: 7, hair: 'blond', grade: 2}; + * var fred = {name: 'Fred', age: 12, hair: 'brown', grade: 7}; + * var kids = [abby, fred]; + * R.project(['name', 'grade'], kids); //=> [{name: 'Abby', grade: 2}, {name: 'Fred', grade: 7}] + */ + // passing `identity` gives correct arity + var project = useWith(_map, [ + pickAll, + identity + ]); + + /** + * Returns `true` if the specified object property is equal, in `R.equals` + * terms, to the given value; `false` otherwise. + * + * @func + * @memberOf R + * @since v0.1.0 + * @category Relation + * @sig String -> a -> Object -> Boolean + * @param {String} name + * @param {*} val + * @param {*} obj + * @return {Boolean} + * @see R.equals, R.propSatisfies + * @example + * + * var abby = {name: 'Abby', age: 7, hair: 'blond'}; + * var fred = {name: 'Fred', age: 12, hair: 'brown'}; + * var rusty = {name: 'Rusty', age: 10, hair: 'brown'}; + * var alois = {name: 'Alois', age: 15, disposition: 'surly'}; + * var kids = [abby, fred, rusty, alois]; + * var hasBrownHair = R.propEq('hair', 'brown'); + * R.filter(hasBrownHair, kids); //=> [fred, rusty] + */ + var propEq = _curry3(function propEq(name, val, obj) { + return propSatisfies(equals(val), name, obj); + }); + + /** + * Returns `true` if the specified object property is of the given type; + * `false` otherwise. + * + * @func + * @memberOf R + * @since v0.16.0 + * @category Type + * @sig Type -> String -> Object -> Boolean + * @param {Function} type + * @param {String} name + * @param {*} obj + * @return {Boolean} + * @see R.is, R.propSatisfies + * @example + * + * R.propIs(Number, 'x', {x: 1, y: 2}); //=> true + * R.propIs(Number, 'x', {x: 'foo'}); //=> false + * R.propIs(Number, 'x', {}); //=> false + */ + var propIs = _curry3(function propIs(type, name, obj) { + return propSatisfies(is(type), name, obj); + }); + + /** + * Returns a single item by iterating through the list, successively calling + * the iterator function and passing it an accumulator value and the current + * value from the array, and then passing the result to the next call. + * + * The iterator function receives two values: *(acc, value)*. It may use + * `R.reduced` to shortcut the iteration. + * + * Note: `R.reduce` does not skip deleted or unassigned indices (sparse + * arrays), unlike the native `Array.prototype.reduce` method. For more details + * on this behavior, see: + * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce#Description + * + * Dispatches to the `reduce` method of the third argument, if present. + * + * @func + * @memberOf R + * @since v0.1.0 + * @category List + * @sig ((a, b) -> a) -> a -> [b] -> a + * @param {Function} fn The iterator function. Receives two values, the accumulator and the + * current element from the array. + * @param {*} acc The accumulator value. + * @param {Array} list The list to iterate over. + * @return {*} The final, accumulated value. + * @see R.reduced, R.addIndex + * @example + * + * var numbers = [1, 2, 3]; + * var add = (a, b) => a + b; + * + * R.reduce(add, 10, numbers); //=> 16 + */ + var reduce = _curry3(_reduce); + + /** + * Groups the elements of the list according to the result of calling + * the String-returning function `keyFn` on each element and reduces the elements + * of each group to a single value via the reducer function `valueFn`. + * + * This function is basically a more general `groupBy` function. + * + * @func + * @memberOf R + * @since v0.20.0 + * @category List + * @sig ((a, b) -> a) -> a -> (b -> String) -> [b] -> {String: a} + * @param {Function} valueFn The function that reduces the elements of each group to a single + * value. Receives two values, accumulator for a particular group and the current element. + * @param {*} acc The (initial) accumulator value for each group. + * @param {Function} keyFn The function that maps the list's element into a key. + * @param {Array} list The array to group. + * @return {Object} An object with the output of `keyFn` for keys, mapped to the output of + * `valueFn` for elements which produced that key when passed to `keyFn`. + * @see R.groupBy, R.reduce + * @example + * + * var reduceToNamesBy = R.reduceBy((acc, student) => acc.concat(student.name), []); + * var namesByGrade = reduceToNamesBy(function(student) { + * var score = student.score; + * return score < 65 ? 'F' : + * score < 70 ? 'D' : + * score < 80 ? 'C' : + * score < 90 ? 'B' : 'A'; + * }); + * var students = [{name: 'Lucy', score: 92}, + * {name: 'Drew', score: 85}, + * // ... + * {name: 'Bart', score: 62}]; + * namesByGrade(students); + * // { + * // 'A': ['Lucy'], + * // 'B': ['Drew'] + * // // ..., + * // 'F': ['Bart'] + * // } + */ + var reduceBy = _curryN(4, [], function reduceBy(valueFn, valueAcc, keyFn, list) { + return _reduce(function (acc, elt) { + var key = keyFn(elt); + acc[key] = valueFn(_has(key, acc) ? acc[key] : valueAcc, elt); + return acc; + }, {}, list); + }); + + /** + * The complement of `filter`. + * + * Acts as a transducer if a transformer is given in list position. + * + * @func + * @memberOf R + * @since v0.1.0 + * @category List + * @sig Filterable f => (a -> Boolean) -> f a -> f a + * @param {Function} pred + * @param {Array} filterable + * @return {Array} + * @see R.filter, R.transduce, R.addIndex + * @example + * + * var isOdd = (n) => n % 2 === 1; + * + * R.reject(isOdd, [1, 2, 3, 4]); //=> [2, 4] + * + * R.reject(isOdd, {a: 1, b: 2, c: 3, d: 4}); //=> {b: 2, d: 4} + */ + var reject = _curry2(function reject(pred, filterable) { + return filter(_complement(pred), filterable); + }); + + /** + * Returns a fixed list of size `n` containing a specified identical value. + * + * @func + * @memberOf R + * @since v0.1.1 + * @category List + * @sig a -> n -> [a] + * @param {*} value The value to repeat. + * @param {Number} n The desired size of the output list. + * @return {Array} A new array containing `n` `value`s. + * @example + * + * R.repeat('hi', 5); //=> ['hi', 'hi', 'hi', 'hi', 'hi'] + * + * var obj = {}; + * var repeatedObjs = R.repeat(obj, 5); //=> [{}, {}, {}, {}, {}] + * repeatedObjs[0] === repeatedObjs[1]; //=> true + */ + var repeat = _curry2(function repeat(value, n) { + return times(always(value), n); + }); + + /** + * Adds together all the elements of a list. + * + * @func + * @memberOf R + * @since v0.1.0 + * @category Math + * @sig [Number] -> Number + * @param {Array} list An array of numbers + * @return {Number} The sum of all the numbers in the list. + * @see R.reduce + * @example + * + * R.sum([2,4,6,8,100,1]); //=> 121 + */ + var sum = reduce(add, 0); + + /** + * Returns a new list containing the last `n` elements of the given list. + * If `n > list.length`, returns a list of `list.length` elements. + * + * @func + * @memberOf R + * @since v0.16.0 + * @category List + * @sig Number -> [a] -> [a] + * @sig Number -> String -> String + * @param {Number} n The number of elements to return. + * @param {Array} xs The collection to consider. + * @return {Array} + * @see R.dropLast + * @example + * + * R.takeLast(1, ['foo', 'bar', 'baz']); //=> ['baz'] + * R.takeLast(2, ['foo', 'bar', 'baz']); //=> ['bar', 'baz'] + * R.takeLast(3, ['foo', 'bar', 'baz']); //=> ['foo', 'bar', 'baz'] + * R.takeLast(4, ['foo', 'bar', 'baz']); //=> ['foo', 'bar', 'baz'] + * R.takeLast(3, 'ramda'); //=> 'mda' + */ + var takeLast = _curry2(function takeLast(n, xs) { + return drop(n >= 0 ? xs.length - n : 0, xs); + }); + + /** + * Initializes a transducer using supplied iterator function. Returns a single + * item by iterating through the list, successively calling the transformed + * iterator function and passing it an accumulator value and the current value + * from the array, and then passing the result to the next call. + * + * The iterator function receives two values: *(acc, value)*. It will be + * wrapped as a transformer to initialize the transducer. A transformer can be + * passed directly in place of an iterator function. In both cases, iteration + * may be stopped early with the `R.reduced` function. + * + * A transducer is a function that accepts a transformer and returns a + * transformer and can be composed directly. + * + * A transformer is an an object that provides a 2-arity reducing iterator + * function, step, 0-arity initial value function, init, and 1-arity result + * extraction function, result. The step function is used as the iterator + * function in reduce. The result function is used to convert the final + * accumulator into the return type and in most cases is R.identity. The init + * function can be used to provide an initial accumulator, but is ignored by + * transduce. + * + * The iteration is performed with R.reduce after initializing the transducer. + * + * @func + * @memberOf R + * @since v0.12.0 + * @category List + * @sig (c -> c) -> (a,b -> a) -> a -> [b] -> a + * @param {Function} xf The transducer function. Receives a transformer and returns a transformer. + * @param {Function} fn The iterator function. Receives two values, the accumulator and the + * current element from the array. Wrapped as transformer, if necessary, and used to + * initialize the transducer + * @param {*} acc The initial accumulator value. + * @param {Array} list The list to iterate over. + * @return {*} The final, accumulated value. + * @see R.reduce, R.reduced, R.into + * @example + * + * var numbers = [1, 2, 3, 4]; + * var transducer = R.compose(R.map(R.add(1)), R.take(2)); + * + * R.transduce(transducer, R.flip(R.append), [], numbers); //=> [2, 3] + */ + var transduce = curryN(4, function transduce(xf, fn, acc, list) { + return _reduce(xf(typeof fn === 'function' ? _xwrap(fn) : fn), acc, list); + }); + + /** + * Combines two lists into a set (i.e. no duplicates) composed of the elements + * of each list. Duplication is determined according to the value returned by + * applying the supplied predicate to two list elements. + * + * @func + * @memberOf R + * @since v0.1.0 + * @category Relation + * @sig (a -> a -> Boolean) -> [*] -> [*] -> [*] + * @param {Function} pred A predicate used to test whether two items are equal. + * @param {Array} list1 The first list. + * @param {Array} list2 The second list. + * @return {Array} The first and second lists concatenated, with + * duplicates removed. + * @see R.union + * @example + * + * var l1 = [{a: 1}, {a: 2}]; + * var l2 = [{a: 1}, {a: 4}]; + * R.unionWith(R.eqBy(R.prop('a')), l1, l2); //=> [{a: 1}, {a: 2}, {a: 4}] + */ + var unionWith = _curry3(function unionWith(pred, list1, list2) { + return uniqWith(pred, _concat(list1, list2)); + }); + + /** + * Takes a spec object and a test object; returns true if the test satisfies + * the spec, false otherwise. An object satisfies the spec if, for each of the + * spec's own properties, accessing that property of the object gives the same + * value (in `R.equals` terms) as accessing that property of the spec. + * + * `whereEq` is a specialization of [`where`](#where). + * + * @func + * @memberOf R + * @since v0.14.0 + * @category Object + * @sig {String: *} -> {String: *} -> Boolean + * @param {Object} spec + * @param {Object} testObj + * @return {Boolean} + * @see R.where + * @example + * + * // pred :: Object -> Boolean + * var pred = R.whereEq({a: 1, b: 2}); + * + * pred({a: 1}); //=> false + * pred({a: 1, b: 2}); //=> true + * pred({a: 1, b: 2, c: 3}); //=> true + * pred({a: 1, b: 1}); //=> false + */ + var whereEq = _curry2(function whereEq(spec, testObj) { + return where(map(equals, spec), testObj); + }); + + var _flatCat = function () { + var preservingReduced = function (xf) { + return { + '@@transducer/init': _xfBase.init, + '@@transducer/result': function (result) { + return xf['@@transducer/result'](result); + }, + '@@transducer/step': function (result, input) { + var ret = xf['@@transducer/step'](result, input); + return ret['@@transducer/reduced'] ? _forceReduced(ret) : ret; + } + }; + }; + return function _xcat(xf) { + var rxf = preservingReduced(xf); + return { + '@@transducer/init': _xfBase.init, + '@@transducer/result': function (result) { + return rxf['@@transducer/result'](result); + }, + '@@transducer/step': function (result, input) { + return !isArrayLike(input) ? _reduce(rxf, result, [input]) : _reduce(rxf, result, input); + } + }; + }; + }(); + + // Array.prototype.indexOf doesn't exist below IE9 + // manually crawl the list to distinguish between +0 and -0 + // NaN + // non-zero numbers can utilise Set + // all these types can utilise Set + // null can utilise Set + // anything else not covered above, defer to R.equals + var _indexOf = function _indexOf(list, a, idx) { + var inf, item; + // Array.prototype.indexOf doesn't exist below IE9 + if (typeof list.indexOf === 'function') { + switch (typeof a) { + case 'number': + if (a === 0) { + // manually crawl the list to distinguish between +0 and -0 + inf = 1 / a; + while (idx < list.length) { + item = list[idx]; + if (item === 0 && 1 / item === inf) { + return idx; + } + idx += 1; + } + return -1; + } else if (a !== a) { + // NaN + while (idx < list.length) { + item = list[idx]; + if (typeof item === 'number' && item !== item) { + return idx; + } + idx += 1; + } + return -1; + } + // non-zero numbers can utilise Set + return list.indexOf(a, idx); + // all these types can utilise Set + case 'string': + case 'boolean': + case 'function': + case 'undefined': + return list.indexOf(a, idx); + case 'object': + if (a === null) { + // null can utilise Set + return list.indexOf(a, idx); + } + } + } + // anything else not covered above, defer to R.equals + while (idx < list.length) { + if (equals(list[idx], a)) { + return idx; + } + idx += 1; + } + return -1; + }; + + var _xchain = _curry2(function _xchain(f, xf) { + return map(f, _flatCat(xf)); + }); + + /** + * Takes a list of predicates and returns a predicate that returns true for a + * given list of arguments if every one of the provided predicates is satisfied + * by those arguments. + * + * The function returned is a curried function whose arity matches that of the + * highest-arity predicate. + * + * @func + * @memberOf R + * @since v0.9.0 + * @category Logic + * @sig [(*... -> Boolean)] -> (*... -> Boolean) + * @param {Array} preds + * @return {Function} + * @see R.anyPass + * @example + * + * var isQueen = R.propEq('rank', 'Q'); + * var isSpade = R.propEq('suit', '♠︎'); + * var isQueenOfSpades = R.allPass([isQueen, isSpade]); + * + * isQueenOfSpades({rank: 'Q', suit: '♣︎'}); //=> false + * isQueenOfSpades({rank: 'Q', suit: '♠︎'}); //=> true + */ + var allPass = _curry1(function allPass(preds) { + return curryN(reduce(max, 0, pluck('length', preds)), function () { + var idx = 0; + var len = preds.length; + while (idx < len) { + if (!preds[idx].apply(this, arguments)) { + return false; + } + idx += 1; + } + return true; + }); + }); + + /** + * Returns `true` if all elements are unique, in `R.equals` terms, otherwise + * `false`. + * + * @func + * @memberOf R + * @since v0.18.0 + * @category List + * @sig [a] -> Boolean + * @param {Array} list The array to consider. + * @return {Boolean} `true` if all elements are unique, else `false`. + * @deprecated since v0.20.0 + * @example + * + * R.allUniq(['1', 1]); //=> true + * R.allUniq([1, 1]); //=> false + * R.allUniq([[42], [42]]); //=> false + */ + var allUniq = _curry1(function allUniq(list) { + var len = list.length; + var idx = 0; + while (idx < len) { + if (_indexOf(list, list[idx], idx + 1) >= 0) { + return false; + } + idx += 1; + } + return true; + }); + + /** + * Takes a list of predicates and returns a predicate that returns true for a + * given list of arguments if at least one of the provided predicates is + * satisfied by those arguments. + * + * The function returned is a curried function whose arity matches that of the + * highest-arity predicate. + * + * @func + * @memberOf R + * @since v0.9.0 + * @category Logic + * @sig [(*... -> Boolean)] -> (*... -> Boolean) + * @param {Array} preds + * @return {Function} + * @see R.allPass + * @example + * + * var gte = R.anyPass([R.gt, R.equals]); + * + * gte(3, 2); //=> true + * gte(2, 2); //=> true + * gte(2, 3); //=> false + */ + var anyPass = _curry1(function anyPass(preds) { + return curryN(reduce(max, 0, pluck('length', preds)), function () { + var idx = 0; + var len = preds.length; + while (idx < len) { + if (preds[idx].apply(this, arguments)) { + return true; + } + idx += 1; + } + return false; + }); + }); + + /** + * ap applies a list of functions to a list of values. + * + * Dispatches to the `ap` method of the second argument, if present. Also + * treats functions as applicatives. + * + * @func + * @memberOf R + * @since v0.3.0 + * @category Function + * @sig [f] -> [a] -> [f a] + * @param {Array} fns An array of functions + * @param {Array} vs An array of values + * @return {Array} An array of results of applying each of `fns` to all of `vs` in turn. + * @example + * + * R.ap([R.multiply(2), R.add(3)], [1,2,3]); //=> [2, 4, 6, 4, 5, 6] + */ + // else + var ap = _curry2(function ap(applicative, fn) { + return typeof applicative.ap === 'function' ? applicative.ap(fn) : typeof applicative === 'function' ? curryN(Math.max(applicative.length, fn.length), function () { + return applicative.apply(this, arguments)(fn.apply(this, arguments)); + }) : // else + _reduce(function (acc, f) { + return _concat(acc, map(f, fn)); + }, [], applicative); + }); + + /** + * Given a spec object recursively mapping properties to functions, creates a + * function producing an object of the same structure, by mapping each property + * to the result of calling its associated function with the supplied arguments. + * + * @func + * @memberOf R + * @since v0.20.0 + * @category Function + * @sig {k: ((a, b, ..., m) -> v)} -> ((a, b, ..., m) -> {k: v}) + * @param {Object} spec an object recursively mapping properties to functions for + * producing the values for these properties. + * @return {Function} A function that returns an object of the same structure + * as `spec', with each property set to the value returned by calling its + * associated function with the supplied arguments. + * @see R.juxt + * @example + * + * var getMetrics = R.applySpec({ + * sum: R.add, + * nested: { mul: R.multiply } + * }); + * getMetrics(2, 4); // => { sum: 6, nested: { mul: 8 } } + */ + var applySpec = _curry1(function applySpec(spec) { + spec = map(function (v) { + return typeof v == 'function' ? v : applySpec(v); + }, spec); + return curryN(reduce(max, 0, pluck('length', values(spec))), function () { + var args = arguments; + return map(function (f) { + return apply(f, args); + }, spec); + }); + }); + + /** + * Returns the result of calling its first argument with the remaining + * arguments. This is occasionally useful as a converging function for + * `R.converge`: the left branch can produce a function while the right branch + * produces a value to be passed to that function as an argument. + * + * @func + * @memberOf R + * @since v0.9.0 + * @category Function + * @sig (*... -> a),*... -> a + * @param {Function} fn The function to apply to the remaining arguments. + * @param {...*} args Any number of positional arguments. + * @return {*} + * @see R.apply + * @example + * + * var indentN = R.pipe(R.times(R.always(' ')), + * R.join(''), + * R.replace(/^(?!$)/gm)); + * + * var format = R.converge(R.call, [ + * R.pipe(R.prop('indent'), indentN), + * R.prop('value') + * ]); + * + * format({indent: 2, value: 'foo\nbar\nbaz\n'}); //=> ' foo\n bar\n baz\n' + */ + var call = curry(function call(fn) { + return fn.apply(this, _slice(arguments, 1)); + }); + + /** + * `chain` maps a function over a list and concatenates the results. `chain` + * is also known as `flatMap` in some libraries + * + * Dispatches to the `chain` method of the second argument, if present. + * + * @func + * @memberOf R + * @since v0.3.0 + * @category List + * @sig (a -> [b]) -> [a] -> [b] + * @param {Function} fn + * @param {Array} list + * @return {Array} + * @example + * + * var duplicate = n => [n, n]; + * R.chain(duplicate, [1, 2, 3]); //=> [1, 1, 2, 2, 3, 3] + */ + var chain = _curry2(_dispatchable('chain', _xchain, function chain(fn, monad) { + if (typeof monad === 'function') { + return function () { + return monad.call(this, fn.apply(this, arguments)).apply(this, arguments); + }; + } + return _makeFlat(false)(map(fn, monad)); + })); + + /** + * Returns a function, `fn`, which encapsulates if/else-if/else logic. + * `R.cond` takes a list of [predicate, transform] pairs. All of the arguments + * to `fn` are applied to each of the predicates in turn until one returns a + * "truthy" value, at which point `fn` returns the result of applying its + * arguments to the corresponding transformer. If none of the predicates + * matches, `fn` returns undefined. + * + * @func + * @memberOf R + * @since v0.6.0 + * @category Logic + * @sig [[(*... -> Boolean),(*... -> *)]] -> (*... -> *) + * @param {Array} pairs + * @return {Function} + * @example + * + * var fn = R.cond([ + * [R.equals(0), R.always('water freezes at 0°C')], + * [R.equals(100), R.always('water boils at 100°C')], + * [R.T, temp => 'nothing special happens at ' + temp + '°C'] + * ]); + * fn(0); //=> 'water freezes at 0°C' + * fn(50); //=> 'nothing special happens at 50°C' + * fn(100); //=> 'water boils at 100°C' + */ + var cond = _curry1(function cond(pairs) { + var arity = reduce(max, 0, map(function (pair) { + return pair[0].length; + }, pairs)); + return _arity(arity, function () { + var idx = 0; + while (idx < pairs.length) { + if (pairs[idx][0].apply(this, arguments)) { + return pairs[idx][1].apply(this, arguments); + } + idx += 1; + } + }); + }); + + /** + * Wraps a constructor function inside a curried function that can be called + * with the same arguments and returns the same type. The arity of the function + * returned is specified to allow using variadic constructor functions. + * + * @func + * @memberOf R + * @since v0.4.0 + * @category Function + * @sig Number -> (* -> {*}) -> (* -> {*}) + * @param {Number} n The arity of the constructor function. + * @param {Function} Fn The constructor function to wrap. + * @return {Function} A wrapped, curried constructor function. + * @example + * + * // Variadic constructor function + * var Widget = () => { + * this.children = Array.prototype.slice.call(arguments); + * // ... + * }; + * Widget.prototype = { + * // ... + * }; + * var allConfigs = [ + * // ... + * ]; + * R.map(R.constructN(1, Widget), allConfigs); // a list of Widgets + */ + var constructN = _curry2(function constructN(n, Fn) { + if (n > 10) { + throw new Error('Constructor with greater than ten arguments'); + } + if (n === 0) { + return function () { + return new Fn(); + }; + } + return curry(nAry(n, function ($0, $1, $2, $3, $4, $5, $6, $7, $8, $9) { + switch (arguments.length) { + case 1: + return new Fn($0); + case 2: + return new Fn($0, $1); + case 3: + return new Fn($0, $1, $2); + case 4: + return new Fn($0, $1, $2, $3); + case 5: + return new Fn($0, $1, $2, $3, $4); + case 6: + return new Fn($0, $1, $2, $3, $4, $5); + case 7: + return new Fn($0, $1, $2, $3, $4, $5, $6); + case 8: + return new Fn($0, $1, $2, $3, $4, $5, $6, $7); + case 9: + return new Fn($0, $1, $2, $3, $4, $5, $6, $7, $8); + case 10: + return new Fn($0, $1, $2, $3, $4, $5, $6, $7, $8, $9); + } + })); + }); + + /** + * Accepts a converging function and a list of branching functions and returns + * a new function. When invoked, this new function is applied to some + * arguments, each branching function is applied to those same arguments. The + * results of each branching function are passed as arguments to the converging + * function to produce the return value. + * + * @func + * @memberOf R + * @since v0.4.2 + * @category Function + * @sig (x1 -> x2 -> ... -> z) -> [(a -> b -> ... -> x1), (a -> b -> ... -> x2), ...] -> (a -> b -> ... -> z) + * @param {Function} after A function. `after` will be invoked with the return values of + * `fn1` and `fn2` as its arguments. + * @param {Array} functions A list of functions. + * @return {Function} A new function. + * @example + * + * var add = (a, b) => a + b; + * var multiply = (a, b) => a * b; + * var subtract = (a, b) => a - b; + * + * //≅ multiply( add(1, 2), subtract(1, 2) ); + * R.converge(multiply, [add, subtract])(1, 2); //=> -3 + * + * var add3 = (a, b, c) => a + b + c; + * R.converge(add3, [multiply, add, subtract])(1, 2); //=> 4 + */ + var converge = _curry2(function converge(after, fns) { + return curryN(reduce(max, 0, pluck('length', fns)), function () { + var args = arguments; + var context = this; + return after.apply(context, _map(function (fn) { + return fn.apply(context, args); + }, fns)); + }); + }); + + /** + * Counts the elements of a list according to how many match each value of a + * key generated by the supplied function. Returns an object mapping the keys + * produced by `fn` to the number of occurrences in the list. Note that all + * keys are coerced to strings because of how JavaScript objects work. + * + * @func + * @memberOf R + * @since v0.1.0 + * @category Relation + * @sig (a -> String) -> [a] -> {*} + * @param {Function} fn The function used to map values to keys. + * @param {Array} list The list to count elements from. + * @return {Object} An object mapping keys to number of occurrences in the list. + * @example + * + * var numbers = [1.0, 1.1, 1.2, 2.0, 3.0, 2.2]; + * var letters = R.split('', 'abcABCaaaBBc'); + * R.countBy(Math.floor)(numbers); //=> {'1': 3, '2': 2, '3': 1} + * R.countBy(R.toLower)(letters); //=> {'a': 5, 'b': 4, 'c': 3} + */ + var countBy = reduceBy(function (acc, elem) { + return acc + 1; + }, 0); + + /** + * Returns a new list without any consecutively repeating elements. Equality is + * determined by applying the supplied predicate two consecutive elements. The + * first element in a series of equal element is the one being preserved. + * + * Dispatches to the `dropRepeatsWith` method of the second argument, if present. + * + * Acts as a transducer if a transformer is given in list position. + * + * @func + * @memberOf R + * @since v0.14.0 + * @category List + * @sig (a, a -> Boolean) -> [a] -> [a] + * @param {Function} pred A predicate used to test whether two items are equal. + * @param {Array} list The array to consider. + * @return {Array} `list` without repeating elements. + * @see R.transduce + * @example + * + * var l = [1, -1, 1, 3, 4, -4, -4, -5, 5, 3, 3]; + * R.dropRepeatsWith(R.eqBy(Math.abs), l); //=> [1, 3, 4, -5, 3] + */ + var dropRepeatsWith = _curry2(_dispatchable('dropRepeatsWith', _xdropRepeatsWith, function dropRepeatsWith(pred, list) { + var result = []; + var idx = 1; + var len = list.length; + if (len !== 0) { + result[0] = list[0]; + while (idx < len) { + if (!pred(last(result), list[idx])) { + result[result.length] = list[idx]; + } + idx += 1; + } + } + return result; + })); + + /** + * Takes a function and two values in its domain and returns `true` if the + * values map to the same value in the codomain; `false` otherwise. + * + * @func + * @memberOf R + * @since v0.18.0 + * @category Relation + * @sig (a -> b) -> a -> a -> Boolean + * @param {Function} f + * @param {*} x + * @param {*} y + * @return {Boolean} + * @example + * + * R.eqBy(Math.abs, 5, -5); //=> true + */ + var eqBy = _curry3(function eqBy(f, x, y) { + return equals(f(x), f(y)); + }); + + /** + * Reports whether two objects have the same value, in `R.equals` terms, for + * the specified property. Useful as a curried predicate. + * + * @func + * @memberOf R + * @since v0.1.0 + * @category Object + * @sig k -> {k: v} -> {k: v} -> Boolean + * @param {String} prop The name of the property to compare + * @param {Object} obj1 + * @param {Object} obj2 + * @return {Boolean} + * + * @example + * + * var o1 = { a: 1, b: 2, c: 3, d: 4 }; + * var o2 = { a: 10, b: 20, c: 3, d: 40 }; + * R.eqProps('a', o1, o2); //=> false + * R.eqProps('c', o1, o2); //=> true + */ + var eqProps = _curry3(function eqProps(prop, obj1, obj2) { + return equals(obj1[prop], obj2[prop]); + }); + + /** + * Splits a list into sub-lists stored in an object, based on the result of + * calling a String-returning function on each element, and grouping the + * results according to values returned. + * + * Dispatches to the `groupBy` method of the second argument, if present. + * + * Acts as a transducer if a transformer is given in list position. + * + * @func + * @memberOf R + * @since v0.1.0 + * @category List + * @sig (a -> String) -> [a] -> {String: [a]} + * @param {Function} fn Function :: a -> String + * @param {Array} list The array to group + * @return {Object} An object with the output of `fn` for keys, mapped to arrays of elements + * that produced that key when passed to `fn`. + * @see R.transduce + * @example + * + * var byGrade = R.groupBy(function(student) { + * var score = student.score; + * return score < 65 ? 'F' : + * score < 70 ? 'D' : + * score < 80 ? 'C' : + * score < 90 ? 'B' : 'A'; + * }); + * var students = [{name: 'Abby', score: 84}, + * {name: 'Eddy', score: 58}, + * // ... + * {name: 'Jack', score: 69}]; + * byGrade(students); + * // { + * // 'A': [{name: 'Dianne', score: 99}], + * // 'B': [{name: 'Abby', score: 84}] + * // // ..., + * // 'F': [{name: 'Eddy', score: 58}] + * // } + */ + var groupBy = _curry2(_dispatchable('groupBy', _xgroupBy, reduceBy(function (acc, item) { + if (acc == null) { + acc = []; + } + acc.push(item); + return acc; + }, null))); + + /** + * Given a function that generates a key, turns a list of objects into an + * object indexing the objects by the given key. Note that if multiple + * objects generate the same value for the indexing key only the last value + * will be included in the generated object. + * + * @func + * @memberOf R + * @since v0.19.0 + * @category List + * @sig (a -> String) -> [{k: v}] -> {k: {k: v}} + * @param {Function} fn Function :: a -> String + * @param {Array} array The array of objects to index + * @return {Object} An object indexing each array element by the given property. + * @example + * + * var list = [{id: 'xyz', title: 'A'}, {id: 'abc', title: 'B'}]; + * R.indexBy(R.prop('id'), list); + * //=> {abc: {id: 'abc', title: 'B'}, xyz: {id: 'xyz', title: 'A'}} + */ + var indexBy = reduceBy(function (acc, elem) { + return elem; + }, null); + + /** + * Returns the position of the first occurrence of an item in an array, or -1 + * if the item is not included in the array. `R.equals` is used to determine + * equality. + * + * @func + * @memberOf R + * @since v0.1.0 + * @category List + * @sig a -> [a] -> Number + * @param {*} target The item to find. + * @param {Array} xs The array to search in. + * @return {Number} the index of the target, or -1 if the target is not found. + * @see R.lastIndexOf + * @example + * + * R.indexOf(3, [1,2,3,4]); //=> 2 + * R.indexOf(10, [1,2,3,4]); //=> -1 + */ + var indexOf = _curry2(function indexOf(target, xs) { + return typeof xs.indexOf === 'function' && !_isArray(xs) ? xs.indexOf(target) : _indexOf(xs, target, 0); + }); + + /** + * juxt applies a list of functions to a list of values. + * + * @func + * @memberOf R + * @since v0.19.0 + * @category Function + * @sig [(a, b, ..., m) -> n] -> ((a, b, ..., m) -> [n]) + * @param {Array} fns An array of functions + * @return {Function} A function that returns a list of values after applying each of the original `fns` to its parameters. + * @see R.applySpec + * @example + * + * var range = R.juxt([Math.min, Math.max]); + * range(3, 4, 9, -3); //=> [-3, 9] + */ + var juxt = _curry1(function juxt(fns) { + return converge(_arrayOf, fns); + }); + + /** + * Returns a lens for the given getter and setter functions. The getter "gets" + * the value of the focus; the setter "sets" the value of the focus. The setter + * should not mutate the data structure. + * + * @func + * @memberOf R + * @since v0.8.0 + * @category Object + * @typedefn Lens s a = Functor f => (a -> f a) -> s -> f s + * @sig (s -> a) -> ((a, s) -> s) -> Lens s a + * @param {Function} getter + * @param {Function} setter + * @return {Lens} + * @see R.view, R.set, R.over, R.lensIndex, R.lensProp + * @example + * + * var xLens = R.lens(R.prop('x'), R.assoc('x')); + * + * R.view(xLens, {x: 1, y: 2}); //=> 1 + * R.set(xLens, 4, {x: 1, y: 2}); //=> {x: 4, y: 2} + * R.over(xLens, R.negate, {x: 1, y: 2}); //=> {x: -1, y: 2} + */ + var lens = _curry2(function lens(getter, setter) { + return function (toFunctorFn) { + return function (target) { + return map(function (focus) { + return setter(focus, target); + }, toFunctorFn(getter(target))); + }; + }; + }); + + /** + * Returns a lens whose focus is the specified index. + * + * @func + * @memberOf R + * @since v0.14.0 + * @category Object + * @typedefn Lens s a = Functor f => (a -> f a) -> s -> f s + * @sig Number -> Lens s a + * @param {Number} n + * @return {Lens} + * @see R.view, R.set, R.over + * @example + * + * var headLens = R.lensIndex(0); + * + * R.view(headLens, ['a', 'b', 'c']); //=> 'a' + * R.set(headLens, 'x', ['a', 'b', 'c']); //=> ['x', 'b', 'c'] + * R.over(headLens, R.toUpper, ['a', 'b', 'c']); //=> ['A', 'b', 'c'] + */ + var lensIndex = _curry1(function lensIndex(n) { + return lens(nth(n), update(n)); + }); + + /** + * Returns a lens whose focus is the specified path. + * + * @func + * @memberOf R + * @since v0.19.0 + * @category Object + * @typedefn Lens s a = Functor f => (a -> f a) -> s -> f s + * @sig [String] -> Lens s a + * @param {Array} path The path to use. + * @return {Lens} + * @see R.view, R.set, R.over + * @example + * + * var xyLens = R.lensPath(['x', 'y']); + * + * R.view(xyLens, {x: {y: 2, z: 3}}); //=> 2 + * R.set(xyLens, 4, {x: {y: 2, z: 3}}); //=> {x: {y: 4, z: 3}} + * R.over(xyLens, R.negate, {x: {y: 2, z: 3}}); //=> {x: {y: -2, z: 3}} + */ + var lensPath = _curry1(function lensPath(p) { + return lens(path(p), assocPath(p)); + }); + + /** + * Returns a lens whose focus is the specified property. + * + * @func + * @memberOf R + * @since v0.14.0 + * @category Object + * @typedefn Lens s a = Functor f => (a -> f a) -> s -> f s + * @sig String -> Lens s a + * @param {String} k + * @return {Lens} + * @see R.view, R.set, R.over + * @example + * + * var xLens = R.lensProp('x'); + * + * R.view(xLens, {x: 1, y: 2}); //=> 1 + * R.set(xLens, 4, {x: 1, y: 2}); //=> {x: 4, y: 2} + * R.over(xLens, R.negate, {x: 1, y: 2}); //=> {x: -1, y: 2} + */ + var lensProp = _curry1(function lensProp(k) { + return lens(prop(k), assoc(k)); + }); + + /** + * "lifts" a function to be the specified arity, so that it may "map over" that + * many lists, Functions or other objects that satisfy the [FantasyLand Apply spec](https://github.com/fantasyland/fantasy-land#apply). + * + * @func + * @memberOf R + * @since v0.7.0 + * @category Function + * @sig Number -> (*... -> *) -> ([*]... -> [*]) + * @param {Function} fn The function to lift into higher context + * @return {Function} The lifted function. + * @see R.lift, R.ap + * @example + * + * var madd3 = R.liftN(3, R.curryN(3, (...args) => R.sum(args))); + * madd3([1,2,3], [1,2,3], [1]); //=> [3, 4, 5, 4, 5, 6, 5, 6, 7] + */ + var liftN = _curry2(function liftN(arity, fn) { + var lifted = curryN(arity, fn); + return curryN(arity, function () { + return _reduce(ap, map(lifted, arguments[0]), _slice(arguments, 1)); + }); + }); + + /** + * Returns the mean of the given list of numbers. + * + * @func + * @memberOf R + * @since v0.14.0 + * @category Math + * @sig [Number] -> Number + * @param {Array} list + * @return {Number} + * @example + * + * R.mean([2, 7, 9]); //=> 6 + * R.mean([]); //=> NaN + */ + var mean = _curry1(function mean(list) { + return sum(list) / list.length; + }); + + /** + * Returns the median of the given list of numbers. + * + * @func + * @memberOf R + * @since v0.14.0 + * @category Math + * @sig [Number] -> Number + * @param {Array} list + * @return {Number} + * @example + * + * R.median([2, 9, 7]); //=> 7 + * R.median([7, 2, 10, 9]); //=> 8 + * R.median([]); //=> NaN + */ + var median = _curry1(function median(list) { + var len = list.length; + if (len === 0) { + return NaN; + } + var width = 2 - len % 2; + var idx = (len - width) / 2; + return mean(_slice(list).sort(function (a, b) { + return a < b ? -1 : a > b ? 1 : 0; + }).slice(idx, idx + width)); + }); + + /** + * Takes a predicate and a list or other "filterable" object and returns the + * pair of filterable objects of the same type of elements which do and do not + * satisfy, the predicate, respectively. + * + * @func + * @memberOf R + * @since v0.1.4 + * @category List + * @sig Filterable f => (a -> Boolean) -> f a -> [f a, f a] + * @param {Function} pred A predicate to determine which side the element belongs to. + * @param {Array} filterable the list (or other filterable) to partition. + * @return {Array} An array, containing first the subset of elements that satisfy the + * predicate, and second the subset of elements that do not satisfy. + * @see R.filter, R.reject + * @example + * + * R.partition(R.contains('s'), ['sss', 'ttt', 'foo', 'bars']); + * // => [ [ 'sss', 'bars' ], [ 'ttt', 'foo' ] ] + * + * R.partition(R.contains('s'), { a: 'sss', b: 'ttt', foo: 'bars' }); + * // => [ { a: 'sss', foo: 'bars' }, { b: 'ttt' } ] + */ + var partition = juxt([ + filter, + reject + ]); + + /** + * Performs left-to-right function composition. The leftmost function may have + * any arity; the remaining functions must be unary. + * + * In some libraries this function is named `sequence`. + * + * **Note:** The result of pipe is not automatically curried. + * + * @func + * @memberOf R + * @since v0.1.0 + * @category Function + * @sig (((a, b, ..., n) -> o), (o -> p), ..., (x -> y), (y -> z)) -> ((a, b, ..., n) -> z) + * @param {...Function} functions + * @return {Function} + * @see R.compose + * @example + * + * var f = R.pipe(Math.pow, R.negate, R.inc); + * + * f(3, 4); // -(3^4) + 1 + */ + var pipe = function pipe() { + if (arguments.length === 0) { + throw new Error('pipe requires at least one argument'); + } + return _arity(arguments[0].length, reduce(_pipe, arguments[0], tail(arguments))); + }; + + /** + * Performs left-to-right composition of one or more Promise-returning + * functions. The leftmost function may have any arity; the remaining functions + * must be unary. + * + * @func + * @memberOf R + * @since v0.10.0 + * @category Function + * @sig ((a -> Promise b), (b -> Promise c), ..., (y -> Promise z)) -> (a -> Promise z) + * @param {...Function} functions + * @return {Function} + * @see R.composeP + * @example + * + * // followersForUser :: String -> Promise [User] + * var followersForUser = R.pipeP(db.getUserById, db.getFollowers); + */ + var pipeP = function pipeP() { + if (arguments.length === 0) { + throw new Error('pipeP requires at least one argument'); + } + return _arity(arguments[0].length, reduce(_pipeP, arguments[0], tail(arguments))); + }; + + /** + * Multiplies together all the elements of a list. + * + * @func + * @memberOf R + * @since v0.1.0 + * @category Math + * @sig [Number] -> Number + * @param {Array} list An array of numbers + * @return {Number} The product of all the numbers in the list. + * @see R.reduce + * @example + * + * R.product([2,4,6,8,100,1]); //=> 38400 + */ + var product = reduce(multiply, 1); + + /** + * Transforms a [Traversable](https://github.com/fantasyland/fantasy-land#traversable) + * of [Applicative](https://github.com/fantasyland/fantasy-land#applicative) into an + * Applicative of Traversable. + * + * Dispatches to the `sequence` method of the second argument, if present. + * + * @func + * @memberOf R + * @since v0.19.0 + * @category List + * @sig (Applicative f, Traversable t) => (a -> f a) -> t (f a) -> f (t a) + * @param {Function} of + * @param {*} traversable + * @return {*} + * @see R.traverse + * @example + * + * R.sequence(Maybe.of, [Just(1), Just(2), Just(3)]); //=> Just([1, 2, 3]) + * R.sequence(Maybe.of, [Just(1), Just(2), Nothing()]); //=> Nothing() + * + * R.sequence(R.of, Just([1, 2, 3])); //=> [Just(1), Just(2), Just(3)] + * R.sequence(R.of, Nothing()); //=> [Nothing()] + */ + var sequence = _curry2(function sequence(of, traversable) { + return typeof traversable.sequence === 'function' ? traversable.sequence(of) : reduceRight(function (acc, x) { + return ap(map(prepend, x), acc); + }, of([]), traversable); + }); + + /** + * Maps an [Applicative](https://github.com/fantasyland/fantasy-land#applicative)-returning + * function over a [Traversable](https://github.com/fantasyland/fantasy-land#traversable), + * then uses [`sequence`](#sequence) to transform the resulting Traversable of Applicative + * into an Applicative of Traversable. + * + * Dispatches to the `sequence` method of the third argument, if present. + * + * @func + * @memberOf R + * @since v0.19.0 + * @category List + * @sig (Applicative f, Traversable t) => (a -> f a) -> (a -> f b) -> t a -> f (t b) + * @param {Function} of + * @param {Function} f + * @param {*} traversable + * @return {*} + * @see R.sequence + * @example + * + * // Returns `Nothing` if the given divisor is `0` + * safeDiv = n => d => d === 0 ? Nothing() : Just(n / d) + * + * R.traverse(Maybe.of, safeDiv(10), [2, 4, 5]); //=> Just([5, 2.5, 2]) + * R.traverse(Maybe.of, safeDiv(10), [2, 0, 5]); //=> Nothing + */ + var traverse = _curry3(function traverse(of, f, traversable) { + return sequence(of, map(f, traversable)); + }); + + /** + * Shorthand for `R.chain(R.identity)`, which removes one level of nesting from + * any [Chain](https://github.com/fantasyland/fantasy-land#chain). + * + * @func + * @memberOf R + * @since v0.3.0 + * @category List + * @sig Chain c => c (c a) -> c a + * @param {*} list + * @return {*} + * @see R.flatten, R.chain + * @example + * + * R.unnest([1, [2], [[3]]]); //=> [1, 2, [3]] + * R.unnest([[1, 2], [3, 4], [5, 6]]); //=> [1, 2, 3, 4, 5, 6] + */ + var unnest = chain(_identity); + + var _contains = function _contains(a, list) { + return _indexOf(list, a, 0) >= 0; + }; + + // mapPairs :: (Object, [String]) -> [String] + var _toString = function _toString(x, seen) { + var recur = function recur(y) { + var xs = seen.concat([x]); + return _contains(y, xs) ? '' : _toString(y, xs); + }; + // mapPairs :: (Object, [String]) -> [String] + var mapPairs = function (obj, keys) { + return _map(function (k) { + return _quote(k) + ': ' + recur(obj[k]); + }, keys.slice().sort()); + }; + switch (Object.prototype.toString.call(x)) { + case '[object Arguments]': + return '(function() { return arguments; }(' + _map(recur, x).join(', ') + '))'; + case '[object Array]': + return '[' + _map(recur, x).concat(mapPairs(x, reject(function (k) { + return /^\d+$/.test(k); + }, keys(x)))).join(', ') + ']'; + case '[object Boolean]': + return typeof x === 'object' ? 'new Boolean(' + recur(x.valueOf()) + ')' : x.toString(); + case '[object Date]': + return 'new Date(' + (isNaN(x.valueOf()) ? recur(NaN) : _quote(_toISOString(x))) + ')'; + case '[object Null]': + return 'null'; + case '[object Number]': + return typeof x === 'object' ? 'new Number(' + recur(x.valueOf()) + ')' : 1 / x === -Infinity ? '-0' : x.toString(10); + case '[object String]': + return typeof x === 'object' ? 'new String(' + recur(x.valueOf()) + ')' : _quote(x); + case '[object Undefined]': + return 'undefined'; + default: + if (typeof x.toString === 'function') { + var repr = x.toString(); + if (repr !== '[object Object]') { + return repr; + } + } + return '{' + mapPairs(x, keys(x)).join(', ') + '}'; + } + }; + + /** + * Performs right-to-left function composition. The rightmost function may have + * any arity; the remaining functions must be unary. + * + * **Note:** The result of compose is not automatically curried. + * + * @func + * @memberOf R + * @since v0.1.0 + * @category Function + * @sig ((y -> z), (x -> y), ..., (o -> p), ((a, b, ..., n) -> o)) -> ((a, b, ..., n) -> z) + * @param {...Function} functions + * @return {Function} + * @see R.pipe + * @example + * + * var f = R.compose(R.inc, R.negate, Math.pow); + * + * f(3, 4); // -(3^4) + 1 + */ + var compose = function compose() { + if (arguments.length === 0) { + throw new Error('compose requires at least one argument'); + } + return pipe.apply(this, reverse(arguments)); + }; + + /** + * Returns the right-to-left Kleisli composition of the provided functions, + * each of which must return a value of a type supported by [`chain`](#chain). + * + * `R.composeK(h, g, f)` is equivalent to `R.compose(R.chain(h), R.chain(g), R.chain(f))`. + * + * @func + * @memberOf R + * @since v0.16.0 + * @category Function + * @sig Chain m => ((y -> m z), (x -> m y), ..., (a -> m b)) -> (m a -> m z) + * @param {...Function} + * @return {Function} + * @see R.pipeK + * @example + * + * // parseJson :: String -> Maybe * + * // get :: String -> Object -> Maybe * + * + * // getStateCode :: Maybe String -> Maybe String + * var getStateCode = R.composeK( + * R.compose(Maybe.of, R.toUpper), + * get('state'), + * get('address'), + * get('user'), + * parseJson + * ); + * + * getStateCode(Maybe.of('{"user":{"address":{"state":"ny"}}}')); + * //=> Just('NY') + * getStateCode(Maybe.of('[Invalid JSON]')); + * //=> Nothing() + */ + var composeK = function composeK() { + return compose.apply(this, prepend(identity, map(chain, arguments))); + }; + + /** + * Performs right-to-left composition of one or more Promise-returning + * functions. The rightmost function may have any arity; the remaining + * functions must be unary. + * + * @func + * @memberOf R + * @since v0.10.0 + * @category Function + * @sig ((y -> Promise z), (x -> Promise y), ..., (a -> Promise b)) -> (a -> Promise z) + * @param {...Function} functions + * @return {Function} + * @see R.pipeP + * @example + * + * // followersForUser :: String -> Promise [User] + * var followersForUser = R.composeP(db.getFollowers, db.getUserById); + */ + var composeP = function composeP() { + if (arguments.length === 0) { + throw new Error('composeP requires at least one argument'); + } + return pipeP.apply(this, reverse(arguments)); + }; + + /** + * Wraps a constructor function inside a curried function that can be called + * with the same arguments and returns the same type. + * + * @func + * @memberOf R + * @since v0.1.0 + * @category Function + * @sig (* -> {*}) -> (* -> {*}) + * @param {Function} Fn The constructor function to wrap. + * @return {Function} A wrapped, curried constructor function. + * @example + * + * // Constructor function + * var Widget = config => { + * // ... + * }; + * Widget.prototype = { + * // ... + * }; + * var allConfigs = [ + * // ... + * ]; + * R.map(R.construct(Widget), allConfigs); // a list of Widgets + */ + var construct = _curry1(function construct(Fn) { + return constructN(Fn.length, Fn); + }); + + /** + * Returns `true` if the specified value is equal, in `R.equals` terms, to at + * least one element of the given list; `false` otherwise. + * + * @func + * @memberOf R + * @since v0.1.0 + * @category List + * @sig a -> [a] -> Boolean + * @param {Object} a The item to compare against. + * @param {Array} list The array to consider. + * @return {Boolean} `true` if the item is in the list, `false` otherwise. + * @see R.any + * @example + * + * R.contains(3, [1, 2, 3]); //=> true + * R.contains(4, [1, 2, 3]); //=> false + * R.contains([42], [[42]]); //=> true + */ + var contains = _curry2(_contains); + + /** + * Finds the set (i.e. no duplicates) of all elements in the first list not + * contained in the second list. + * + * @func + * @memberOf R + * @since v0.1.0 + * @category Relation + * @sig [*] -> [*] -> [*] + * @param {Array} list1 The first list. + * @param {Array} list2 The second list. + * @return {Array} The elements in `list1` that are not in `list2`. + * @see R.differenceWith + * @example + * + * R.difference([1,2,3,4], [7,6,5,4,3]); //=> [1,2] + * R.difference([7,6,5,4,3], [1,2,3,4]); //=> [7,6,5] + */ + var difference = _curry2(function difference(first, second) { + var out = []; + var idx = 0; + var firstLen = first.length; + while (idx < firstLen) { + if (!_contains(first[idx], second) && !_contains(first[idx], out)) { + out[out.length] = first[idx]; + } + idx += 1; + } + return out; + }); + + /** + * Returns a new list without any consecutively repeating elements. `R.equals` + * is used to determine equality. + * + * Dispatches to the `dropRepeats` method of the first argument, if present. + * + * Acts as a transducer if a transformer is given in list position. + * + * @func + * @memberOf R + * @since v0.14.0 + * @category List + * @sig [a] -> [a] + * @param {Array} list The array to consider. + * @return {Array} `list` without repeating elements. + * @see R.transduce + * @example + * + * R.dropRepeats([1, 1, 1, 2, 3, 4, 4, 2, 2]); //=> [1, 2, 3, 4, 2] + */ + var dropRepeats = _curry1(_dispatchable('dropRepeats', _xdropRepeatsWith(equals), dropRepeatsWith(equals))); + + /** + * "lifts" a function of arity > 1 so that it may "map over" a list, Function or other + * object that satisfies the [FantasyLand Apply spec](https://github.com/fantasyland/fantasy-land#apply). + * + * @func + * @memberOf R + * @since v0.7.0 + * @category Function + * @sig (*... -> *) -> ([*]... -> [*]) + * @param {Function} fn The function to lift into higher context + * @return {Function} The lifted function. + * @see R.liftN + * @example + * + * var madd3 = R.lift(R.curry((a, b, c) => a + b + c)); + * + * madd3([1,2,3], [1,2,3], [1]); //=> [3, 4, 5, 4, 5, 6, 5, 6, 7] + * + * var madd5 = R.lift(R.curry((a, b, c, d, e) => a + b + c + d + e)); + * + * madd5([1,2], [3], [4, 5], [6], [7, 8]); //=> [21, 22, 22, 23, 22, 23, 23, 24] + */ + var lift = _curry1(function lift(fn) { + return liftN(fn.length, fn); + }); + + /** + * Returns a partial copy of an object omitting the keys specified. + * + * @func + * @memberOf R + * @since v0.1.0 + * @category Object + * @sig [String] -> {String: *} -> {String: *} + * @param {Array} names an array of String property names to omit from the new object + * @param {Object} obj The object to copy from + * @return {Object} A new object with properties from `names` not on it. + * @see R.pick + * @example + * + * R.omit(['a', 'd'], {a: 1, b: 2, c: 3, d: 4}); //=> {b: 2, c: 3} + */ + var omit = _curry2(function omit(names, obj) { + var result = {}; + for (var prop in obj) { + if (!_contains(prop, names)) { + result[prop] = obj[prop]; + } + } + return result; + }); + + /** + * Returns the left-to-right Kleisli composition of the provided functions, + * each of which must return a value of a type supported by [`chain`](#chain). + * + * `R.pipeK(f, g, h)` is equivalent to `R.pipe(R.chain(f), R.chain(g), R.chain(h))`. + * + * @func + * @memberOf R + * @since v0.16.0 + * @category Function + * @sig Chain m => ((a -> m b), (b -> m c), ..., (y -> m z)) -> (m a -> m z) + * @param {...Function} + * @return {Function} + * @see R.composeK + * @example + * + * // parseJson :: String -> Maybe * + * // get :: String -> Object -> Maybe * + * + * // getStateCode :: Maybe String -> Maybe String + * var getStateCode = R.pipeK( + * parseJson, + * get('user'), + * get('address'), + * get('state'), + * R.compose(Maybe.of, R.toUpper) + * ); + * + * getStateCode(Maybe.of('{"user":{"address":{"state":"ny"}}}')); + * //=> Just('NY') + * getStateCode(Maybe.of('[Invalid JSON]')); + * //=> Nothing() + */ + var pipeK = function pipeK() { + return composeK.apply(this, reverse(arguments)); + }; + + /** + * Returns the string representation of the given value. `eval`'ing the output + * should result in a value equivalent to the input value. Many of the built-in + * `toString` methods do not satisfy this requirement. + * + * If the given value is an `[object Object]` with a `toString` method other + * than `Object.prototype.toString`, this method is invoked with no arguments + * to produce the return value. This means user-defined constructor functions + * can provide a suitable `toString` method. For example: + * + * function Point(x, y) { + * this.x = x; + * this.y = y; + * } + * + * Point.prototype.toString = function() { + * return 'new Point(' + this.x + ', ' + this.y + ')'; + * }; + * + * R.toString(new Point(1, 2)); //=> 'new Point(1, 2)' + * + * @func + * @memberOf R + * @since v0.14.0 + * @category String + * @sig * -> String + * @param {*} val + * @return {String} + * @example + * + * R.toString(42); //=> '42' + * R.toString('abc'); //=> '"abc"' + * R.toString([1, 2, 3]); //=> '[1, 2, 3]' + * R.toString({foo: 1, bar: 2, baz: 3}); //=> '{"bar": 2, "baz": 3, "foo": 1}' + * R.toString(new Date('2001-02-03T04:05:06Z')); //=> 'new Date("2001-02-03T04:05:06.000Z")' + */ + var toString = _curry1(function toString(val) { + return _toString(val, []); + }); + + /** + * Returns a new list without values in the first argument. + * `R.equals` is used to determine equality. + * + * Acts as a transducer if a transformer is given in list position. + * + * @func + * @memberOf R + * @since v0.19.0 + * @category List + * @sig [a] -> [a] -> [a] + * @param {Array} list1 The values to be removed from `list2`. + * @param {Array} list2 The array to remove values from. + * @return {Array} The new array without values in `list1`. + * @see R.transduce + * @example + * + * R.without([1, 2], [1, 2, 1, 3, 4]); //=> [3, 4] + */ + var without = _curry2(function (xs, list) { + return reject(flip(_contains)(xs), list); + }); + + // A simple Set type that honours R.equals semantics + /* globals Set */ + /** + * Combines the logic for checking whether an item is a member of the set and + * for adding a new item to the set. + * + * @param item The item to check or add to the Set instance. + * @param shouldAdd If true, the item will be added to the set if it doesn't + * already exist. + * @param set The set instance to check or add to. + * @return {boolean} When shouldAdd is true, this will return true when a new + * item was added otherwise false. When shouldAdd is false, + * this will return true if the item already exists, otherwise + * false. + */ + // distinguish between +0 and -0 + // these types can all utilise Set + // set._items['boolean'] holds a two element array + // representing [ falseExists, trueExists ] + // compare functions for reference equality + /* falls through */ + // reduce the search size of heterogeneous sets by creating buckets + // for each type. + // scan through all previously applied items + var _Set = function () { + function _Set() { + /* globals Set */ + this._nativeSet = typeof Set === 'function' ? new Set() : null; + this._items = {}; + } + _Set.prototype.add = function (item) { + return hasOrAdd(item, true, this); + }; + _Set.prototype.has = function (item) { + return hasOrAdd(item, false, this); + }; + /** + * Combines the logic for checking whether an item is a member of the set and + * for adding a new item to the set. + * + * @param item The item to check or add to the Set instance. + * @param shouldAdd If true, the item will be added to the set if it doesn't + * already exist. + * @param set The set instance to check or add to. + * @return {boolean} When shouldAdd is true, this will return true when a new + * item was added otherwise false. When shouldAdd is false, + * this will return true if the item already exists, otherwise + * false. + */ + function hasOrAdd(item, shouldAdd, set) { + var type = typeof item; + var prevSize, newSize; + switch (type) { + case 'string': + case 'number': + // distinguish between +0 and -0 + if (item === 0 && !set._items['-0'] && 1 / item === -Infinity) { + if (shouldAdd) { + set._items['-0'] = true; + } + return shouldAdd; + } + // these types can all utilise Set + if (set._nativeSet !== null) { + if (shouldAdd) { + prevSize = set._nativeSet.size; + set._nativeSet.add(item); + newSize = set._nativeSet.size; + return newSize > prevSize; + } else { + return set._nativeSet.has(item); + } + } else { + if (!(type in set._items)) { + if (shouldAdd) { + set._items[type] = {}; + set._items[type][item] = true; + } + return shouldAdd; + } else if (item in set._items[type]) { + return !shouldAdd; + } else { + if (shouldAdd) { + set._items[type][item] = true; + } + return shouldAdd; + } + } + case 'boolean': + // set._items['boolean'] holds a two element array + // representing [ falseExists, trueExists ] + if (type in set._items) { + var bIdx = item ? 1 : 0; + if (set._items[type][bIdx]) { + return !shouldAdd; + } else { + if (shouldAdd) { + set._items[type][bIdx] = true; + } + return shouldAdd; + } + } else { + if (shouldAdd) { + set._items[type] = item ? [ + false, + true + ] : [ + true, + false + ]; + } + return shouldAdd; + } + case 'function': + // compare functions for reference equality + if (set._nativeSet !== null) { + if (shouldAdd) { + prevSize = set._nativeSet.size; + set._nativeSet.add(item); + newSize = set._nativeSet.size; + return newSize > prevSize; + } else { + return set._nativeSet.has(item); + } + } else { + if (!(type in set._items)) { + if (shouldAdd) { + set._items[type] = [item]; + } + return shouldAdd; + } + if (!_contains(item, set._items[type])) { + if (shouldAdd) { + set._items[type].push(item); + } + return shouldAdd; + } + } + return !shouldAdd; + case 'undefined': + if (set._items[type]) { + return !shouldAdd; + } else { + if (shouldAdd) { + set._items[type] = true; + } + return shouldAdd; + } + case 'object': + if (item === null) { + if (!set._items['null']) { + if (shouldAdd) { + set._items['null'] = true; + } + return shouldAdd; + } + return !shouldAdd; + } + /* falls through */ + default: + // reduce the search size of heterogeneous sets by creating buckets + // for each type. + type = Object.prototype.toString.call(item); + if (!(type in set._items)) { + if (shouldAdd) { + set._items[type] = [item]; + } + return shouldAdd; + } + // scan through all previously applied items + if (!_contains(item, set._items[type])) { + if (shouldAdd) { + set._items[type].push(item); + } + return shouldAdd; + } + return !shouldAdd; + } + } + return _Set; + }(); + + /** + * A function wrapping calls to the two functions in an `&&` operation, + * returning the result of the first function if it is false-y and the result + * of the second function otherwise. Note that this is short-circuited, + * meaning that the second function will not be invoked if the first returns a + * false-y value. + * + * In addition to functions, `R.both` also accepts any fantasy-land compatible + * applicative functor. + * + * @func + * @memberOf R + * @since v0.12.0 + * @category Logic + * @sig (*... -> Boolean) -> (*... -> Boolean) -> (*... -> Boolean) + * @param {Function} f a predicate + * @param {Function} g another predicate + * @return {Function} a function that applies its arguments to `f` and `g` and `&&`s their outputs together. + * @see R.and + * @example + * + * var gt10 = x => x > 10; + * var even = x => x % 2 === 0; + * var f = R.both(gt10, even); + * f(100); //=> true + * f(101); //=> false + */ + var both = _curry2(function both(f, g) { + return _isFunction(f) ? function _both() { + return f.apply(this, arguments) && g.apply(this, arguments); + } : lift(and)(f, g); + }); + + /** + * Takes a function `f` and returns a function `g` such that: + * + * - applying `g` to zero or more arguments will give __true__ if applying + * the same arguments to `f` gives a logical __false__ value; and + * + * - applying `g` to zero or more arguments will give __false__ if applying + * the same arguments to `f` gives a logical __true__ value. + * + * `R.complement` will work on all other functors as well. + * + * @func + * @memberOf R + * @since v0.12.0 + * @category Logic + * @sig (*... -> *) -> (*... -> Boolean) + * @param {Function} f + * @return {Function} + * @see R.not + * @example + * + * var isEven = n => n % 2 === 0; + * var isOdd = R.complement(isEven); + * isOdd(21); //=> true + * isOdd(42); //=> false + */ + var complement = lift(not); + + /** + * A function wrapping calls to the two functions in an `||` operation, + * returning the result of the first function if it is truth-y and the result + * of the second function otherwise. Note that this is short-circuited, + * meaning that the second function will not be invoked if the first returns a + * truth-y value. + * + * In addition to functions, `R.either` also accepts any fantasy-land compatible + * applicative functor. + * + * @func + * @memberOf R + * @since v0.12.0 + * @category Logic + * @sig (*... -> Boolean) -> (*... -> Boolean) -> (*... -> Boolean) + * @param {Function} f a predicate + * @param {Function} g another predicate + * @return {Function} a function that applies its arguments to `f` and `g` and `||`s their outputs together. + * @see R.or + * @example + * + * var gt10 = x => x > 10; + * var even = x => x % 2 === 0; + * var f = R.either(gt10, even); + * f(101); //=> true + * f(8); //=> true + */ + var either = _curry2(function either(f, g) { + return _isFunction(f) ? function _either() { + return f.apply(this, arguments) || g.apply(this, arguments); + } : lift(or)(f, g); + }); + + /** + * Turns a named method with a specified arity into a function that can be + * called directly supplied with arguments and a target object. + * + * The returned function is curried and accepts `arity + 1` parameters where + * the final parameter is the target object. + * + * @func + * @memberOf R + * @since v0.1.0 + * @category Function + * @sig Number -> String -> (a -> b -> ... -> n -> Object -> *) + * @param {Number} arity Number of arguments the returned function should take + * before the target object. + * @param {String} method Name of the method to call. + * @return {Function} A new curried function. + * @example + * + * var sliceFrom = R.invoker(1, 'slice'); + * sliceFrom(6, 'abcdefghijklm'); //=> 'ghijklm' + * var sliceFrom6 = R.invoker(2, 'slice')(6); + * sliceFrom6(8, 'abcdefghijklm'); //=> 'gh' + */ + var invoker = _curry2(function invoker(arity, method) { + return curryN(arity + 1, function () { + var target = arguments[arity]; + if (target != null && is(Function, target[method])) { + return target[method].apply(target, _slice(arguments, 0, arity)); + } + throw new TypeError(toString(target) + ' does not have a method named "' + method + '"'); + }); + }); + + /** + * Returns a string made by inserting the `separator` between each element and + * concatenating all the elements into a single string. + * + * @func + * @memberOf R + * @since v0.1.0 + * @category List + * @sig String -> [a] -> String + * @param {Number|String} separator The string used to separate the elements. + * @param {Array} xs The elements to join into a string. + * @return {String} str The string made by concatenating `xs` with `separator`. + * @see R.split + * @example + * + * var spacer = R.join(' '); + * spacer(['a', 2, 3.4]); //=> 'a 2 3.4' + * R.join('|', [1, 2, 3]); //=> '1|2|3' + */ + var join = invoker(1, 'join'); + + /** + * Creates a new function that, when invoked, caches the result of calling `fn` + * for a given argument set and returns the result. Subsequent calls to the + * memoized `fn` with the same argument set will not result in an additional + * call to `fn`; instead, the cached result for that set of arguments will be + * returned. + * + * @func + * @memberOf R + * @since v0.1.0 + * @category Function + * @sig (*... -> a) -> (*... -> a) + * @param {Function} fn The function to memoize. + * @return {Function} Memoized version of `fn`. + * @example + * + * var count = 0; + * var factorial = R.memoize(n => { + * count += 1; + * return R.product(R.range(1, n + 1)); + * }); + * factorial(5); //=> 120 + * factorial(5); //=> 120 + * factorial(5); //=> 120 + * count; //=> 1 + */ + var memoize = _curry1(function memoize(fn) { + var cache = {}; + return _arity(fn.length, function () { + var key = toString(arguments); + if (!_has(key, cache)) { + cache[key] = fn.apply(this, arguments); + } + return cache[key]; + }); + }); + + /** + * Splits a string into an array of strings based on the given + * separator. + * + * @func + * @memberOf R + * @since v0.1.0 + * @category String + * @sig (String | RegExp) -> String -> [String] + * @param {String|RegExp} sep The pattern. + * @param {String} str The string to separate into an array. + * @return {Array} The array of strings from `str` separated by `str`. + * @see R.join + * @example + * + * var pathComponents = R.split('/'); + * R.tail(pathComponents('/usr/local/bin/node')); //=> ['usr', 'local', 'bin', 'node'] + * + * R.split('.', 'a.b.c.xyz.d'); //=> ['a', 'b', 'c', 'xyz', 'd'] + */ + var split = invoker(1, 'split'); + + /** + * Determines whether a given string matches a given regular expression. + * + * @func + * @memberOf R + * @since v0.12.0 + * @category String + * @sig RegExp -> String -> Boolean + * @param {RegExp} pattern + * @param {String} str + * @return {Boolean} + * @see R.match + * @example + * + * R.test(/^x/, 'xyz'); //=> true + * R.test(/^y/, 'xyz'); //=> false + */ + var test = _curry2(function test(pattern, str) { + if (!_isRegExp(pattern)) { + throw new TypeError('\u2018test\u2019 requires a value of type RegExp as its first argument; received ' + toString(pattern)); + } + return _cloneRegExp(pattern).test(str); + }); + + /** + * The lower case version of a string. + * + * @func + * @memberOf R + * @since v0.9.0 + * @category String + * @sig String -> String + * @param {String} str The string to lower case. + * @return {String} The lower case version of `str`. + * @see R.toUpper + * @example + * + * R.toLower('XYZ'); //=> 'xyz' + */ + var toLower = invoker(0, 'toLowerCase'); + + /** + * The upper case version of a string. + * + * @func + * @memberOf R + * @since v0.9.0 + * @category String + * @sig String -> String + * @param {String} str The string to upper case. + * @return {String} The upper case version of `str`. + * @see R.toLower + * @example + * + * R.toUpper('abc'); //=> 'ABC' + */ + var toUpper = invoker(0, 'toUpperCase'); + + /** + * Returns a new list containing only one copy of each element in the original + * list, based upon the value returned by applying the supplied function to + * each list element. Prefers the first item if the supplied function produces + * the same value on two items. `R.equals` is used for comparison. + * + * @func + * @memberOf R + * @since v0.16.0 + * @category List + * @sig (a -> b) -> [a] -> [a] + * @param {Function} fn A function used to produce a value to use during comparisons. + * @param {Array} list The array to consider. + * @return {Array} The list of unique items. + * @example + * + * R.uniqBy(Math.abs, [-1, -5, 2, 10, 1, 2]); //=> [-1, -5, 2, 10] + */ + var uniqBy = _curry2(function uniqBy(fn, list) { + var set = new _Set(); + var result = []; + var idx = 0; + var appliedItem, item; + while (idx < list.length) { + item = list[idx]; + appliedItem = fn(item); + if (set.add(appliedItem)) { + result.push(item); + } + idx += 1; + } + return result; + }); + + /** + * Returns the result of concatenating the given lists or strings. + * + * Dispatches to the `concat` method of the first argument, if present. + * + * @func + * @memberOf R + * @since v0.1.0 + * @category List + * @sig [a] -> [a] -> [a] + * @sig String -> String -> String + * @param {Array|String} a + * @param {Array|String} b + * @return {Array|String} + * + * @example + * + * R.concat([], []); //=> [] + * R.concat([4, 5, 6], [1, 2, 3]); //=> [4, 5, 6, 1, 2, 3] + * R.concat('ABC', 'DEF'); // 'ABCDEF' + */ + var concat = flip(invoker(1, 'concat')); + + /** + * Finds the set (i.e. no duplicates) of all elements contained in the first or + * second list, but not both. + * + * @func + * @memberOf R + * @since v0.19.0 + * @category Relation + * @sig [*] -> [*] -> [*] + * @param {Array} list1 The first list. + * @param {Array} list2 The second list. + * @return {Array} The elements in `list1` or `list2`, but not both. + * @see R.symmetricDifferenceWith + * @example + * + * R.symmetricDifference([1,2,3,4], [7,6,5,4,3]); //=> [1,2,7,6,5] + * R.symmetricDifference([7,6,5,4,3], [1,2,3,4]); //=> [7,6,5,1,2] + */ + var symmetricDifference = _curry2(function symmetricDifference(list1, list2) { + return concat(difference(list1, list2), difference(list2, list1)); + }); + + /** + * Finds the set (i.e. no duplicates) of all elements contained in the first or + * second list, but not both. Duplication is determined according to the value + * returned by applying the supplied predicate to two list elements. + * + * @func + * @memberOf R + * @since v0.19.0 + * @category Relation + * @sig (a -> a -> Boolean) -> [a] -> [a] -> [a] + * @param {Function} pred A predicate used to test whether two items are equal. + * @param {Array} list1 The first list. + * @param {Array} list2 The second list. + * @return {Array} The elements in `list1` or `list2`, but not both. + * @see R.symmetricDifference + * @example + * + * var eqA = R.eqBy(R.prop('a')); + * var l1 = [{a: 1}, {a: 2}, {a: 3}, {a: 4}]; + * var l2 = [{a: 3}, {a: 4}, {a: 5}, {a: 6}]; + * R.symmetricDifferenceWith(eqA, l1, l2); //=> [{a: 1}, {a: 2}, {a: 5}, {a: 6}] + */ + var symmetricDifferenceWith = _curry3(function symmetricDifferenceWith(pred, list1, list2) { + return concat(differenceWith(pred, list1, list2), differenceWith(pred, list2, list1)); + }); + + /** + * Returns a new list containing only one copy of each element in the original + * list. `R.equals` is used to determine equality. + * + * @func + * @memberOf R + * @since v0.1.0 + * @category List + * @sig [a] -> [a] + * @param {Array} list The array to consider. + * @return {Array} The list of unique items. + * @example + * + * R.uniq([1, 1, 2, 1]); //=> [1, 2] + * R.uniq([1, '1']); //=> [1, '1'] + * R.uniq([[42], [42]]); //=> [[42]] + */ + var uniq = uniqBy(identity); + + /** + * Combines two lists into a set (i.e. no duplicates) composed of those + * elements common to both lists. + * + * @func + * @memberOf R + * @since v0.1.0 + * @category Relation + * @sig [*] -> [*] -> [*] + * @param {Array} list1 The first list. + * @param {Array} list2 The second list. + * @return {Array} The list of elements found in both `list1` and `list2`. + * @see R.intersectionWith + * @example + * + * R.intersection([1,2,3,4], [7,6,5,4,3]); //=> [4, 3] + */ + var intersection = _curry2(function intersection(list1, list2) { + var lookupList, filteredList; + if (list1.length > list2.length) { + lookupList = list1; + filteredList = list2; + } else { + lookupList = list2; + filteredList = list1; + } + return uniq(_filter(flip(_contains)(lookupList), filteredList)); + }); + + /** + * Combines two lists into a set (i.e. no duplicates) composed of the elements + * of each list. + * + * @func + * @memberOf R + * @since v0.1.0 + * @category Relation + * @sig [*] -> [*] -> [*] + * @param {Array} as The first list. + * @param {Array} bs The second list. + * @return {Array} The first and second lists concatenated, with + * duplicates removed. + * @example + * + * R.union([1, 2, 3], [2, 3, 4]); //=> [1, 2, 3, 4] + */ + var union = _curry2(compose(uniq, _concat)); + + var R = { + F: F, + T: T, + __: __, + add: add, + addIndex: addIndex, + adjust: adjust, + all: all, + allPass: allPass, + allUniq: allUniq, + always: always, + and: and, + any: any, + anyPass: anyPass, + ap: ap, + aperture: aperture, + append: append, + apply: apply, + applySpec: applySpec, + assoc: assoc, + assocPath: assocPath, + binary: binary, + bind: bind, + both: both, + call: call, + chain: chain, + clamp: clamp, + clone: clone, + comparator: comparator, + complement: complement, + compose: compose, + composeK: composeK, + composeP: composeP, + concat: concat, + cond: cond, + construct: construct, + constructN: constructN, + contains: contains, + converge: converge, + countBy: countBy, + curry: curry, + curryN: curryN, + dec: dec, + defaultTo: defaultTo, + difference: difference, + differenceWith: differenceWith, + dissoc: dissoc, + dissocPath: dissocPath, + divide: divide, + drop: drop, + dropLast: dropLast, + dropLastWhile: dropLastWhile, + dropRepeats: dropRepeats, + dropRepeatsWith: dropRepeatsWith, + dropWhile: dropWhile, + either: either, + empty: empty, + eqBy: eqBy, + eqProps: eqProps, + equals: equals, + evolve: evolve, + filter: filter, + find: find, + findIndex: findIndex, + findLast: findLast, + findLastIndex: findLastIndex, + flatten: flatten, + flip: flip, + forEach: forEach, + fromPairs: fromPairs, + groupBy: groupBy, + groupWith: groupWith, + gt: gt, + gte: gte, + has: has, + hasIn: hasIn, + head: head, + identical: identical, + identity: identity, + ifElse: ifElse, + inc: inc, + indexBy: indexBy, + indexOf: indexOf, + init: init, + insert: insert, + insertAll: insertAll, + intersection: intersection, + intersectionWith: intersectionWith, + intersperse: intersperse, + into: into, + invert: invert, + invertObj: invertObj, + invoker: invoker, + is: is, + isArrayLike: isArrayLike, + isEmpty: isEmpty, + isNil: isNil, + join: join, + juxt: juxt, + keys: keys, + keysIn: keysIn, + last: last, + lastIndexOf: lastIndexOf, + length: length, + lens: lens, + lensIndex: lensIndex, + lensPath: lensPath, + lensProp: lensProp, + lift: lift, + liftN: liftN, + lt: lt, + lte: lte, + map: map, + mapAccum: mapAccum, + mapAccumRight: mapAccumRight, + mapObjIndexed: mapObjIndexed, + match: match, + mathMod: mathMod, + max: max, + maxBy: maxBy, + mean: mean, + median: median, + memoize: memoize, + merge: merge, + mergeAll: mergeAll, + mergeWith: mergeWith, + mergeWithKey: mergeWithKey, + min: min, + minBy: minBy, + modulo: modulo, + multiply: multiply, + nAry: nAry, + negate: negate, + none: none, + not: not, + nth: nth, + nthArg: nthArg, + objOf: objOf, + of: of, + omit: omit, + once: once, + or: or, + over: over, + pair: pair, + partial: partial, + partialRight: partialRight, + partition: partition, + path: path, + pathEq: pathEq, + pathOr: pathOr, + pathSatisfies: pathSatisfies, + pick: pick, + pickAll: pickAll, + pickBy: pickBy, + pipe: pipe, + pipeK: pipeK, + pipeP: pipeP, + pluck: pluck, + prepend: prepend, + product: product, + project: project, + prop: prop, + propEq: propEq, + propIs: propIs, + propOr: propOr, + propSatisfies: propSatisfies, + props: props, + range: range, + reduce: reduce, + reduceBy: reduceBy, + reduceRight: reduceRight, + reduced: reduced, + reject: reject, + remove: remove, + repeat: repeat, + replace: replace, + reverse: reverse, + scan: scan, + sequence: sequence, + set: set, + slice: slice, + sort: sort, + sortBy: sortBy, + split: split, + splitAt: splitAt, + splitEvery: splitEvery, + splitWhen: splitWhen, + subtract: subtract, + sum: sum, + symmetricDifference: symmetricDifference, + symmetricDifferenceWith: symmetricDifferenceWith, + tail: tail, + take: take, + takeLast: takeLast, + takeLastWhile: takeLastWhile, + takeWhile: takeWhile, + tap: tap, + test: test, + times: times, + toLower: toLower, + toPairs: toPairs, + toPairsIn: toPairsIn, + toString: toString, + toUpper: toUpper, + transduce: transduce, + transpose: transpose, + traverse: traverse, + trim: trim, + tryCatch: tryCatch, + type: type, + unapply: unapply, + unary: unary, + uncurryN: uncurryN, + unfold: unfold, + union: union, + unionWith: unionWith, + uniq: uniq, + uniqBy: uniqBy, + uniqWith: uniqWith, + unless: unless, + unnest: unnest, + until: until, + update: update, + useWith: useWith, + values: values, + valuesIn: valuesIn, + view: view, + when: when, + where: where, + whereEq: whereEq, + without: without, + wrap: wrap, + xprod: xprod, + zip: zip, + zipObj: zipObj, + zipWith: zipWith + }; + /* eslint-env amd */ + + /* TEST_ENTRY_POINT */ + + if (typeof exports === 'object') { + module.exports = R; + } else if (typeof define === 'function' && define.amd) { + define(function() { return R; }); + } else { + this.R = R; + } + +}.call(this)); + +},{}],672:[function(require,module,exports){ +'use strict'; +module.exports = /^#!.*/; + +},{}],673:[function(require,module,exports){ +'use strict'; +module.exports = function (str) { + var isExtendedLengthPath = /^\\\\\?\\/.test(str); + var hasNonAscii = /[^\x00-\x80]+/.test(str); + + if (isExtendedLengthPath || hasNonAscii) { + return str; + } + + return str.replace(/\\/g, '/'); +}; + +},{}],674:[function(require,module,exports){ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +var util = require('./util'); +var has = Object.prototype.hasOwnProperty; + +/** + * A data structure which is a combination of an array and a set. Adding a new + * member is O(1), testing for membership is O(1), and finding the index of an + * element is O(1). Removing elements from the set is not supported. Only + * strings are supported for membership. + */ +function ArraySet() { + this._array = []; + this._set = Object.create(null); +} + +/** + * Static method for creating ArraySet instances from an existing array. + */ +ArraySet.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) { + var set = new ArraySet(); + for (var i = 0, len = aArray.length; i < len; i++) { + set.add(aArray[i], aAllowDuplicates); + } + return set; +}; + +/** + * Return how many unique items are in this ArraySet. If duplicates have been + * added, than those do not count towards the size. + * + * @returns Number + */ +ArraySet.prototype.size = function ArraySet_size() { + return Object.getOwnPropertyNames(this._set).length; +}; + +/** + * Add the given string to this set. + * + * @param String aStr + */ +ArraySet.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) { + var sStr = util.toSetString(aStr); + var isDuplicate = has.call(this._set, sStr); + var idx = this._array.length; + if (!isDuplicate || aAllowDuplicates) { + this._array.push(aStr); + } + if (!isDuplicate) { + this._set[sStr] = idx; + } +}; + +/** + * Is the given string a member of this set? + * + * @param String aStr + */ +ArraySet.prototype.has = function ArraySet_has(aStr) { + var sStr = util.toSetString(aStr); + return has.call(this._set, sStr); +}; + +/** + * What is the index of the given string in the array? + * + * @param String aStr + */ +ArraySet.prototype.indexOf = function ArraySet_indexOf(aStr) { + var sStr = util.toSetString(aStr); + if (has.call(this._set, sStr)) { + return this._set[sStr]; + } + throw new Error('"' + aStr + '" is not in the set.'); +}; + +/** + * What is the element at the given index? + * + * @param Number aIdx + */ +ArraySet.prototype.at = function ArraySet_at(aIdx) { + if (aIdx >= 0 && aIdx < this._array.length) { + return this._array[aIdx]; + } + throw new Error('No element indexed by ' + aIdx); +}; + +/** + * Returns the array representation of this set (which has the proper indices + * indicated by indexOf). Note that this is a copy of the internal array used + * for storing the members so that no one can mess with internal state. + */ +ArraySet.prototype.toArray = function ArraySet_toArray() { + return this._array.slice(); +}; + +exports.ArraySet = ArraySet; + +},{"./util":683}],675:[function(require,module,exports){ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + * + * Based on the Base 64 VLQ implementation in Closure Compiler: + * https://code.google.com/p/closure-compiler/source/browse/trunk/src/com/google/debugging/sourcemap/Base64VLQ.java + * + * Copyright 2011 The Closure Compiler Authors. 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 Google Inc. 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. + */ + +var base64 = require('./base64'); + +// A single base 64 digit can contain 6 bits of data. For the base 64 variable +// length quantities we use in the source map spec, the first bit is the sign, +// the next four bits are the actual value, and the 6th bit is the +// continuation bit. The continuation bit tells us whether there are more +// digits in this value following this digit. +// +// Continuation +// | Sign +// | | +// V V +// 101011 + +var VLQ_BASE_SHIFT = 5; + +// binary: 100000 +var VLQ_BASE = 1 << VLQ_BASE_SHIFT; + +// binary: 011111 +var VLQ_BASE_MASK = VLQ_BASE - 1; + +// binary: 100000 +var VLQ_CONTINUATION_BIT = VLQ_BASE; + +/** + * Converts from a two-complement value to a value where the sign bit is + * placed in the least significant bit. For example, as decimals: + * 1 becomes 2 (10 binary), -1 becomes 3 (11 binary) + * 2 becomes 4 (100 binary), -2 becomes 5 (101 binary) + */ +function toVLQSigned(aValue) { + return aValue < 0 + ? ((-aValue) << 1) + 1 + : (aValue << 1) + 0; +} + +/** + * Converts to a two-complement value from a value where the sign bit is + * placed in the least significant bit. For example, as decimals: + * 2 (10 binary) becomes 1, 3 (11 binary) becomes -1 + * 4 (100 binary) becomes 2, 5 (101 binary) becomes -2 + */ +function fromVLQSigned(aValue) { + var isNegative = (aValue & 1) === 1; + var shifted = aValue >> 1; + return isNegative + ? -shifted + : shifted; +} + +/** + * Returns the base 64 VLQ encoded value. + */ +exports.encode = function base64VLQ_encode(aValue) { + var encoded = ""; + var digit; + + var vlq = toVLQSigned(aValue); + + do { + digit = vlq & VLQ_BASE_MASK; + vlq >>>= VLQ_BASE_SHIFT; + if (vlq > 0) { + // There are still more digits in this value, so we must make sure the + // continuation bit is marked. + digit |= VLQ_CONTINUATION_BIT; + } + encoded += base64.encode(digit); + } while (vlq > 0); + + return encoded; +}; + +/** + * Decodes the next base 64 VLQ value from the given string and returns the + * value and the rest of the string via the out parameter. + */ +exports.decode = function base64VLQ_decode(aStr, aIndex, aOutParam) { + var strLen = aStr.length; + var result = 0; + var shift = 0; + var continuation, digit; + + do { + if (aIndex >= strLen) { + throw new Error("Expected more digits in base 64 VLQ value."); + } + + digit = base64.decode(aStr.charCodeAt(aIndex++)); + if (digit === -1) { + throw new Error("Invalid base64 digit: " + aStr.charAt(aIndex - 1)); + } + + continuation = !!(digit & VLQ_CONTINUATION_BIT); + digit &= VLQ_BASE_MASK; + result = result + (digit << shift); + shift += VLQ_BASE_SHIFT; + } while (continuation); + + aOutParam.value = fromVLQSigned(result); + aOutParam.rest = aIndex; +}; + +},{"./base64":676}],676:[function(require,module,exports){ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +var intToCharMap = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split(''); + +/** + * Encode an integer in the range of 0 to 63 to a single base 64 digit. + */ +exports.encode = function (number) { + if (0 <= number && number < intToCharMap.length) { + return intToCharMap[number]; + } + throw new TypeError("Must be between 0 and 63: " + number); +}; + +/** + * Decode a single base 64 character code digit to an integer. Returns -1 on + * failure. + */ +exports.decode = function (charCode) { + var bigA = 65; // 'A' + var bigZ = 90; // 'Z' + + var littleA = 97; // 'a' + var littleZ = 122; // 'z' + + var zero = 48; // '0' + var nine = 57; // '9' + + var plus = 43; // '+' + var slash = 47; // '/' + + var littleOffset = 26; + var numberOffset = 52; + + // 0 - 25: ABCDEFGHIJKLMNOPQRSTUVWXYZ + if (bigA <= charCode && charCode <= bigZ) { + return (charCode - bigA); + } + + // 26 - 51: abcdefghijklmnopqrstuvwxyz + if (littleA <= charCode && charCode <= littleZ) { + return (charCode - littleA + littleOffset); + } + + // 52 - 61: 0123456789 + if (zero <= charCode && charCode <= nine) { + return (charCode - zero + numberOffset); + } + + // 62: + + if (charCode == plus) { + return 62; + } + + // 63: / + if (charCode == slash) { + return 63; + } + + // Invalid base64 digit. + return -1; +}; + +},{}],677:[function(require,module,exports){ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +exports.GREATEST_LOWER_BOUND = 1; +exports.LEAST_UPPER_BOUND = 2; + +/** + * Recursive implementation of binary search. + * + * @param aLow Indices here and lower do not contain the needle. + * @param aHigh Indices here and higher do not contain the needle. + * @param aNeedle The element being searched for. + * @param aHaystack The non-empty array being searched. + * @param aCompare Function which takes two elements and returns -1, 0, or 1. + * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or + * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the + * closest element that is smaller than or greater than the one we are + * searching for, respectively, if the exact element cannot be found. + */ +function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare, aBias) { + // This function terminates when one of the following is true: + // + // 1. We find the exact element we are looking for. + // + // 2. We did not find the exact element, but we can return the index of + // the next-closest element. + // + // 3. We did not find the exact element, and there is no next-closest + // element than the one we are searching for, so we return -1. + var mid = Math.floor((aHigh - aLow) / 2) + aLow; + var cmp = aCompare(aNeedle, aHaystack[mid], true); + if (cmp === 0) { + // Found the element we are looking for. + return mid; + } + else if (cmp > 0) { + // Our needle is greater than aHaystack[mid]. + if (aHigh - mid > 1) { + // The element is in the upper half. + return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare, aBias); + } + + // The exact needle element was not found in this haystack. Determine if + // we are in termination case (3) or (2) and return the appropriate thing. + if (aBias == exports.LEAST_UPPER_BOUND) { + return aHigh < aHaystack.length ? aHigh : -1; + } else { + return mid; + } + } + else { + // Our needle is less than aHaystack[mid]. + if (mid - aLow > 1) { + // The element is in the lower half. + return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare, aBias); + } + + // we are in termination case (3) or (2) and return the appropriate thing. + if (aBias == exports.LEAST_UPPER_BOUND) { + return mid; + } else { + return aLow < 0 ? -1 : aLow; + } + } +} + +/** + * This is an implementation of binary search which will always try and return + * the index of the closest element if there is no exact hit. This is because + * mappings between original and generated line/col pairs are single points, + * and there is an implicit region between each of them, so a miss just means + * that you aren't on the very start of a region. + * + * @param aNeedle The element you are looking for. + * @param aHaystack The array that is being searched. + * @param aCompare A function which takes the needle and an element in the + * array and returns -1, 0, or 1 depending on whether the needle is less + * than, equal to, or greater than the element, respectively. + * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or + * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the + * closest element that is smaller than or greater than the one we are + * searching for, respectively, if the exact element cannot be found. + * Defaults to 'binarySearch.GREATEST_LOWER_BOUND'. + */ +exports.search = function search(aNeedle, aHaystack, aCompare, aBias) { + if (aHaystack.length === 0) { + return -1; + } + + var index = recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack, + aCompare, aBias || exports.GREATEST_LOWER_BOUND); + if (index < 0) { + return -1; + } + + // We have found either the exact element, or the next-closest element than + // the one we are searching for. However, there may be more than one such + // element. Make sure we always return the smallest of these. + while (index - 1 >= 0) { + if (aCompare(aHaystack[index], aHaystack[index - 1], true) !== 0) { + break; + } + --index; + } + + return index; +}; + +},{}],678:[function(require,module,exports){ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2014 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +var util = require('./util'); + +/** + * Determine whether mappingB is after mappingA with respect to generated + * position. + */ +function generatedPositionAfter(mappingA, mappingB) { + // Optimized for most common case + var lineA = mappingA.generatedLine; + var lineB = mappingB.generatedLine; + var columnA = mappingA.generatedColumn; + var columnB = mappingB.generatedColumn; + return lineB > lineA || lineB == lineA && columnB >= columnA || + util.compareByGeneratedPositionsInflated(mappingA, mappingB) <= 0; +} + +/** + * A data structure to provide a sorted view of accumulated mappings in a + * performance conscious manner. It trades a neglibable overhead in general + * case for a large speedup in case of mappings being added in order. + */ +function MappingList() { + this._array = []; + this._sorted = true; + // Serves as infimum + this._last = {generatedLine: -1, generatedColumn: 0}; +} + +/** + * Iterate through internal items. This method takes the same arguments that + * `Array.prototype.forEach` takes. + * + * NOTE: The order of the mappings is NOT guaranteed. + */ +MappingList.prototype.unsortedForEach = + function MappingList_forEach(aCallback, aThisArg) { + this._array.forEach(aCallback, aThisArg); + }; + +/** + * Add the given source mapping. + * + * @param Object aMapping + */ +MappingList.prototype.add = function MappingList_add(aMapping) { + if (generatedPositionAfter(this._last, aMapping)) { + this._last = aMapping; + this._array.push(aMapping); + } else { + this._sorted = false; + this._array.push(aMapping); + } +}; + +/** + * Returns the flat, sorted array of mappings. The mappings are sorted by + * generated position. + * + * WARNING: This method returns internal data without copying, for + * performance. The return value must NOT be mutated, and should be treated as + * an immutable borrow. If you want to take ownership, you must make your own + * copy. + */ +MappingList.prototype.toArray = function MappingList_toArray() { + if (!this._sorted) { + this._array.sort(util.compareByGeneratedPositionsInflated); + this._sorted = true; + } + return this._array; +}; + +exports.MappingList = MappingList; + +},{"./util":683}],679:[function(require,module,exports){ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +// It turns out that some (most?) JavaScript engines don't self-host +// `Array.prototype.sort`. This makes sense because C++ will likely remain +// faster than JS when doing raw CPU-intensive sorting. However, when using a +// custom comparator function, calling back and forth between the VM's C++ and +// JIT'd JS is rather slow *and* loses JIT type information, resulting in +// worse generated code for the comparator function than would be optimal. In +// fact, when sorting with a comparator, these costs outweigh the benefits of +// sorting in C++. By using our own JS-implemented Quick Sort (below), we get +// a ~3500ms mean speed-up in `bench/bench.html`. + +/** + * Swap the elements indexed by `x` and `y` in the array `ary`. + * + * @param {Array} ary + * The array. + * @param {Number} x + * The index of the first item. + * @param {Number} y + * The index of the second item. + */ +function swap(ary, x, y) { + var temp = ary[x]; + ary[x] = ary[y]; + ary[y] = temp; +} + +/** + * Returns a random integer within the range `low .. high` inclusive. + * + * @param {Number} low + * The lower bound on the range. + * @param {Number} high + * The upper bound on the range. + */ +function randomIntInRange(low, high) { + return Math.round(low + (Math.random() * (high - low))); +} + +/** + * The Quick Sort algorithm. + * + * @param {Array} ary + * An array to sort. + * @param {function} comparator + * Function to use to compare two items. + * @param {Number} p + * Start index of the array + * @param {Number} r + * End index of the array + */ +function doQuickSort(ary, comparator, p, r) { + // If our lower bound is less than our upper bound, we (1) partition the + // array into two pieces and (2) recurse on each half. If it is not, this is + // the empty array and our base case. + + if (p < r) { + // (1) Partitioning. + // + // The partitioning chooses a pivot between `p` and `r` and moves all + // elements that are less than or equal to the pivot to the before it, and + // all the elements that are greater than it after it. The effect is that + // once partition is done, the pivot is in the exact place it will be when + // the array is put in sorted order, and it will not need to be moved + // again. This runs in O(n) time. + + // Always choose a random pivot so that an input array which is reverse + // sorted does not cause O(n^2) running time. + var pivotIndex = randomIntInRange(p, r); + var i = p - 1; + + swap(ary, pivotIndex, r); + var pivot = ary[r]; + + // Immediately after `j` is incremented in this loop, the following hold + // true: + // + // * Every element in `ary[p .. i]` is less than or equal to the pivot. + // + // * Every element in `ary[i+1 .. j-1]` is greater than the pivot. + for (var j = p; j < r; j++) { + if (comparator(ary[j], pivot) <= 0) { + i += 1; + swap(ary, i, j); + } + } + + swap(ary, i + 1, j); + var q = i + 1; + + // (2) Recurse on each half. + + doQuickSort(ary, comparator, p, q - 1); + doQuickSort(ary, comparator, q + 1, r); + } +} + +/** + * Sort the given array in-place with the given comparator function. + * + * @param {Array} ary + * An array to sort. + * @param {function} comparator + * Function to use to compare two items. + */ +exports.quickSort = function (ary, comparator) { + doQuickSort(ary, comparator, 0, ary.length - 1); +}; + +},{}],680:[function(require,module,exports){ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +var util = require('./util'); +var binarySearch = require('./binary-search'); +var ArraySet = require('./array-set').ArraySet; +var base64VLQ = require('./base64-vlq'); +var quickSort = require('./quick-sort').quickSort; + +function SourceMapConsumer(aSourceMap) { + var sourceMap = aSourceMap; + if (typeof aSourceMap === 'string') { + sourceMap = JSON.parse(aSourceMap.replace(/^\)\]\}'/, '')); + } + + return sourceMap.sections != null + ? new IndexedSourceMapConsumer(sourceMap) + : new BasicSourceMapConsumer(sourceMap); +} + +SourceMapConsumer.fromSourceMap = function(aSourceMap) { + return BasicSourceMapConsumer.fromSourceMap(aSourceMap); +} + +/** + * The version of the source mapping spec that we are consuming. + */ +SourceMapConsumer.prototype._version = 3; + +// `__generatedMappings` and `__originalMappings` are arrays that hold the +// parsed mapping coordinates from the source map's "mappings" attribute. They +// are lazily instantiated, accessed via the `_generatedMappings` and +// `_originalMappings` getters respectively, and we only parse the mappings +// and create these arrays once queried for a source location. We jump through +// these hoops because there can be many thousands of mappings, and parsing +// them is expensive, so we only want to do it if we must. +// +// Each object in the arrays is of the form: +// +// { +// generatedLine: The line number in the generated code, +// generatedColumn: The column number in the generated code, +// source: The path to the original source file that generated this +// chunk of code, +// originalLine: The line number in the original source that +// corresponds to this chunk of generated code, +// originalColumn: The column number in the original source that +// corresponds to this chunk of generated code, +// name: The name of the original symbol which generated this chunk of +// code. +// } +// +// All properties except for `generatedLine` and `generatedColumn` can be +// `null`. +// +// `_generatedMappings` is ordered by the generated positions. +// +// `_originalMappings` is ordered by the original positions. + +SourceMapConsumer.prototype.__generatedMappings = null; +Object.defineProperty(SourceMapConsumer.prototype, '_generatedMappings', { + get: function () { + if (!this.__generatedMappings) { + this._parseMappings(this._mappings, this.sourceRoot); + } + + return this.__generatedMappings; + } +}); + +SourceMapConsumer.prototype.__originalMappings = null; +Object.defineProperty(SourceMapConsumer.prototype, '_originalMappings', { + get: function () { + if (!this.__originalMappings) { + this._parseMappings(this._mappings, this.sourceRoot); + } + + return this.__originalMappings; + } +}); + +SourceMapConsumer.prototype._charIsMappingSeparator = + function SourceMapConsumer_charIsMappingSeparator(aStr, index) { + var c = aStr.charAt(index); + return c === ";" || c === ","; + }; + +/** + * Parse the mappings in a string in to a data structure which we can easily + * query (the ordered arrays in the `this.__generatedMappings` and + * `this.__originalMappings` properties). + */ +SourceMapConsumer.prototype._parseMappings = + function SourceMapConsumer_parseMappings(aStr, aSourceRoot) { + throw new Error("Subclasses must implement _parseMappings"); + }; + +SourceMapConsumer.GENERATED_ORDER = 1; +SourceMapConsumer.ORIGINAL_ORDER = 2; + +SourceMapConsumer.GREATEST_LOWER_BOUND = 1; +SourceMapConsumer.LEAST_UPPER_BOUND = 2; + +/** + * Iterate over each mapping between an original source/line/column and a + * generated line/column in this source map. + * + * @param Function aCallback + * The function that is called with each mapping. + * @param Object aContext + * Optional. If specified, this object will be the value of `this` every + * time that `aCallback` is called. + * @param aOrder + * Either `SourceMapConsumer.GENERATED_ORDER` or + * `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to + * iterate over the mappings sorted by the generated file's line/column + * order or the original's source/line/column order, respectively. Defaults to + * `SourceMapConsumer.GENERATED_ORDER`. + */ +SourceMapConsumer.prototype.eachMapping = + function SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) { + var context = aContext || null; + var order = aOrder || SourceMapConsumer.GENERATED_ORDER; + + var mappings; + switch (order) { + case SourceMapConsumer.GENERATED_ORDER: + mappings = this._generatedMappings; + break; + case SourceMapConsumer.ORIGINAL_ORDER: + mappings = this._originalMappings; + break; + default: + throw new Error("Unknown order of iteration."); + } + + var sourceRoot = this.sourceRoot; + mappings.map(function (mapping) { + var source = mapping.source === null ? null : this._sources.at(mapping.source); + if (source != null && sourceRoot != null) { + source = util.join(sourceRoot, source); + } + return { + source: source, + generatedLine: mapping.generatedLine, + generatedColumn: mapping.generatedColumn, + originalLine: mapping.originalLine, + originalColumn: mapping.originalColumn, + name: mapping.name === null ? null : this._names.at(mapping.name) + }; + }, this).forEach(aCallback, context); + }; + +/** + * Returns all generated line and column information for the original source, + * line, and column provided. If no column is provided, returns all mappings + * corresponding to a either the line we are searching for or the next + * closest line that has any mappings. Otherwise, returns all mappings + * corresponding to the given line and either the column we are searching for + * or the next closest column that has any offsets. + * + * The only argument is an object with the following properties: + * + * - source: The filename of the original source. + * - line: The line number in the original source. + * - column: Optional. the column number in the original source. + * + * and an array of objects is returned, each with the following properties: + * + * - line: The line number in the generated source, or null. + * - column: The column number in the generated source, or null. + */ +SourceMapConsumer.prototype.allGeneratedPositionsFor = + function SourceMapConsumer_allGeneratedPositionsFor(aArgs) { + var line = util.getArg(aArgs, 'line'); + + // When there is no exact match, BasicSourceMapConsumer.prototype._findMapping + // returns the index of the closest mapping less than the needle. By + // setting needle.originalColumn to 0, we thus find the last mapping for + // the given line, provided such a mapping exists. + var needle = { + source: util.getArg(aArgs, 'source'), + originalLine: line, + originalColumn: util.getArg(aArgs, 'column', 0) + }; + + if (this.sourceRoot != null) { + needle.source = util.relative(this.sourceRoot, needle.source); + } + if (!this._sources.has(needle.source)) { + return []; + } + needle.source = this._sources.indexOf(needle.source); + + var mappings = []; + + var index = this._findMapping(needle, + this._originalMappings, + "originalLine", + "originalColumn", + util.compareByOriginalPositions, + binarySearch.LEAST_UPPER_BOUND); + if (index >= 0) { + var mapping = this._originalMappings[index]; + + if (aArgs.column === undefined) { + var originalLine = mapping.originalLine; + + // Iterate until either we run out of mappings, or we run into + // a mapping for a different line than the one we found. Since + // mappings are sorted, this is guaranteed to find all mappings for + // the line we found. + while (mapping && mapping.originalLine === originalLine) { + mappings.push({ + line: util.getArg(mapping, 'generatedLine', null), + column: util.getArg(mapping, 'generatedColumn', null), + lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null) + }); + + mapping = this._originalMappings[++index]; + } + } else { + var originalColumn = mapping.originalColumn; + + // Iterate until either we run out of mappings, or we run into + // a mapping for a different line than the one we were searching for. + // Since mappings are sorted, this is guaranteed to find all mappings for + // the line we are searching for. + while (mapping && + mapping.originalLine === line && + mapping.originalColumn == originalColumn) { + mappings.push({ + line: util.getArg(mapping, 'generatedLine', null), + column: util.getArg(mapping, 'generatedColumn', null), + lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null) + }); + + mapping = this._originalMappings[++index]; + } + } + } + + return mappings; + }; + +exports.SourceMapConsumer = SourceMapConsumer; + +/** + * A BasicSourceMapConsumer instance represents a parsed source map which we can + * query for information about the original file positions by giving it a file + * position in the generated source. + * + * The only parameter is the raw source map (either as a JSON string, or + * already parsed to an object). According to the spec, source maps have the + * following attributes: + * + * - version: Which version of the source map spec this map is following. + * - sources: An array of URLs to the original source files. + * - names: An array of identifiers which can be referrenced by individual mappings. + * - sourceRoot: Optional. The URL root from which all sources are relative. + * - sourcesContent: Optional. An array of contents of the original source files. + * - mappings: A string of base64 VLQs which contain the actual mappings. + * - file: Optional. The generated file this source map is associated with. + * + * Here is an example source map, taken from the source map spec[0]: + * + * { + * version : 3, + * file: "out.js", + * sourceRoot : "", + * sources: ["foo.js", "bar.js"], + * names: ["src", "maps", "are", "fun"], + * mappings: "AA,AB;;ABCDE;" + * } + * + * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?pli=1# + */ +function BasicSourceMapConsumer(aSourceMap) { + var sourceMap = aSourceMap; + if (typeof aSourceMap === 'string') { + sourceMap = JSON.parse(aSourceMap.replace(/^\)\]\}'/, '')); + } + + var version = util.getArg(sourceMap, 'version'); + var sources = util.getArg(sourceMap, 'sources'); + // Sass 3.3 leaves out the 'names' array, so we deviate from the spec (which + // requires the array) to play nice here. + var names = util.getArg(sourceMap, 'names', []); + var sourceRoot = util.getArg(sourceMap, 'sourceRoot', null); + var sourcesContent = util.getArg(sourceMap, 'sourcesContent', null); + var mappings = util.getArg(sourceMap, 'mappings'); + var file = util.getArg(sourceMap, 'file', null); + + // Once again, Sass deviates from the spec and supplies the version as a + // string rather than a number, so we use loose equality checking here. + if (version != this._version) { + throw new Error('Unsupported version: ' + version); + } + + sources = sources + .map(String) + // Some source maps produce relative source paths like "./foo.js" instead of + // "foo.js". Normalize these first so that future comparisons will succeed. + // See bugzil.la/1090768. + .map(util.normalize) + // Always ensure that absolute sources are internally stored relative to + // the source root, if the source root is absolute. Not doing this would + // be particularly problematic when the source root is a prefix of the + // source (valid, but why??). See github issue #199 and bugzil.la/1188982. + .map(function (source) { + return sourceRoot && util.isAbsolute(sourceRoot) && util.isAbsolute(source) + ? util.relative(sourceRoot, source) + : source; + }); + + // Pass `true` below to allow duplicate names and sources. While source maps + // are intended to be compressed and deduplicated, the TypeScript compiler + // sometimes generates source maps with duplicates in them. See Github issue + // #72 and bugzil.la/889492. + this._names = ArraySet.fromArray(names.map(String), true); + this._sources = ArraySet.fromArray(sources, true); + + this.sourceRoot = sourceRoot; + this.sourcesContent = sourcesContent; + this._mappings = mappings; + this.file = file; +} + +BasicSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype); +BasicSourceMapConsumer.prototype.consumer = SourceMapConsumer; + +/** + * Create a BasicSourceMapConsumer from a SourceMapGenerator. + * + * @param SourceMapGenerator aSourceMap + * The source map that will be consumed. + * @returns BasicSourceMapConsumer + */ +BasicSourceMapConsumer.fromSourceMap = + function SourceMapConsumer_fromSourceMap(aSourceMap) { + var smc = Object.create(BasicSourceMapConsumer.prototype); + + var names = smc._names = ArraySet.fromArray(aSourceMap._names.toArray(), true); + var sources = smc._sources = ArraySet.fromArray(aSourceMap._sources.toArray(), true); + smc.sourceRoot = aSourceMap._sourceRoot; + smc.sourcesContent = aSourceMap._generateSourcesContent(smc._sources.toArray(), + smc.sourceRoot); + smc.file = aSourceMap._file; + + // Because we are modifying the entries (by converting string sources and + // names to indices into the sources and names ArraySets), we have to make + // a copy of the entry or else bad things happen. Shared mutable state + // strikes again! See github issue #191. + + var generatedMappings = aSourceMap._mappings.toArray().slice(); + var destGeneratedMappings = smc.__generatedMappings = []; + var destOriginalMappings = smc.__originalMappings = []; + + for (var i = 0, length = generatedMappings.length; i < length; i++) { + var srcMapping = generatedMappings[i]; + var destMapping = new Mapping; + destMapping.generatedLine = srcMapping.generatedLine; + destMapping.generatedColumn = srcMapping.generatedColumn; + + if (srcMapping.source) { + destMapping.source = sources.indexOf(srcMapping.source); + destMapping.originalLine = srcMapping.originalLine; + destMapping.originalColumn = srcMapping.originalColumn; + + if (srcMapping.name) { + destMapping.name = names.indexOf(srcMapping.name); + } + + destOriginalMappings.push(destMapping); + } + + destGeneratedMappings.push(destMapping); + } + + quickSort(smc.__originalMappings, util.compareByOriginalPositions); + + return smc; + }; + +/** + * The version of the source mapping spec that we are consuming. + */ +BasicSourceMapConsumer.prototype._version = 3; + +/** + * The list of original sources. + */ +Object.defineProperty(BasicSourceMapConsumer.prototype, 'sources', { + get: function () { + return this._sources.toArray().map(function (s) { + return this.sourceRoot != null ? util.join(this.sourceRoot, s) : s; + }, this); + } +}); + +/** + * Provide the JIT with a nice shape / hidden class. + */ +function Mapping() { + this.generatedLine = 0; + this.generatedColumn = 0; + this.source = null; + this.originalLine = null; + this.originalColumn = null; + this.name = null; +} + +/** + * Parse the mappings in a string in to a data structure which we can easily + * query (the ordered arrays in the `this.__generatedMappings` and + * `this.__originalMappings` properties). + */ +BasicSourceMapConsumer.prototype._parseMappings = + function SourceMapConsumer_parseMappings(aStr, aSourceRoot) { + var generatedLine = 1; + var previousGeneratedColumn = 0; + var previousOriginalLine = 0; + var previousOriginalColumn = 0; + var previousSource = 0; + var previousName = 0; + var length = aStr.length; + var index = 0; + var cachedSegments = {}; + var temp = {}; + var originalMappings = []; + var generatedMappings = []; + var mapping, str, segment, end, value; + + while (index < length) { + if (aStr.charAt(index) === ';') { + generatedLine++; + index++; + previousGeneratedColumn = 0; + } + else if (aStr.charAt(index) === ',') { + index++; + } + else { + mapping = new Mapping(); + mapping.generatedLine = generatedLine; + + // Because each offset is encoded relative to the previous one, + // many segments often have the same encoding. We can exploit this + // fact by caching the parsed variable length fields of each segment, + // allowing us to avoid a second parse if we encounter the same + // segment again. + for (end = index; end < length; end++) { + if (this._charIsMappingSeparator(aStr, end)) { + break; + } + } + str = aStr.slice(index, end); + + segment = cachedSegments[str]; + if (segment) { + index += str.length; + } else { + segment = []; + while (index < end) { + base64VLQ.decode(aStr, index, temp); + value = temp.value; + index = temp.rest; + segment.push(value); + } + + if (segment.length === 2) { + throw new Error('Found a source, but no line and column'); + } + + if (segment.length === 3) { + throw new Error('Found a source and line, but no column'); + } + + cachedSegments[str] = segment; + } + + // Generated column. + mapping.generatedColumn = previousGeneratedColumn + segment[0]; + previousGeneratedColumn = mapping.generatedColumn; + + if (segment.length > 1) { + // Original source. + mapping.source = previousSource + segment[1]; + previousSource += segment[1]; + + // Original line. + mapping.originalLine = previousOriginalLine + segment[2]; + previousOriginalLine = mapping.originalLine; + // Lines are stored 0-based + mapping.originalLine += 1; + + // Original column. + mapping.originalColumn = previousOriginalColumn + segment[3]; + previousOriginalColumn = mapping.originalColumn; + + if (segment.length > 4) { + // Original name. + mapping.name = previousName + segment[4]; + previousName += segment[4]; + } + } + + generatedMappings.push(mapping); + if (typeof mapping.originalLine === 'number') { + originalMappings.push(mapping); + } + } + } + + quickSort(generatedMappings, util.compareByGeneratedPositionsDeflated); + this.__generatedMappings = generatedMappings; + + quickSort(originalMappings, util.compareByOriginalPositions); + this.__originalMappings = originalMappings; + }; + +/** + * Find the mapping that best matches the hypothetical "needle" mapping that + * we are searching for in the given "haystack" of mappings. + */ +BasicSourceMapConsumer.prototype._findMapping = + function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName, + aColumnName, aComparator, aBias) { + // To return the position we are searching for, we must first find the + // mapping for the given position and then return the opposite position it + // points to. Because the mappings are sorted, we can use binary search to + // find the best mapping. + + if (aNeedle[aLineName] <= 0) { + throw new TypeError('Line must be greater than or equal to 1, got ' + + aNeedle[aLineName]); + } + if (aNeedle[aColumnName] < 0) { + throw new TypeError('Column must be greater than or equal to 0, got ' + + aNeedle[aColumnName]); + } + + return binarySearch.search(aNeedle, aMappings, aComparator, aBias); + }; + +/** + * Compute the last column for each generated mapping. The last column is + * inclusive. + */ +BasicSourceMapConsumer.prototype.computeColumnSpans = + function SourceMapConsumer_computeColumnSpans() { + for (var index = 0; index < this._generatedMappings.length; ++index) { + var mapping = this._generatedMappings[index]; + + // Mappings do not contain a field for the last generated columnt. We + // can come up with an optimistic estimate, however, by assuming that + // mappings are contiguous (i.e. given two consecutive mappings, the + // first mapping ends where the second one starts). + if (index + 1 < this._generatedMappings.length) { + var nextMapping = this._generatedMappings[index + 1]; + + if (mapping.generatedLine === nextMapping.generatedLine) { + mapping.lastGeneratedColumn = nextMapping.generatedColumn - 1; + continue; + } + } + + // The last mapping for each line spans the entire line. + mapping.lastGeneratedColumn = Infinity; + } + }; + +/** + * Returns the original source, line, and column information for the generated + * source's line and column positions provided. The only argument is an object + * with the following properties: + * + * - line: The line number in the generated source. + * - column: The column number in the generated source. + * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or + * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the + * closest element that is smaller than or greater than the one we are + * searching for, respectively, if the exact element cannot be found. + * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'. + * + * and an object is returned with the following properties: + * + * - source: The original source file, or null. + * - line: The line number in the original source, or null. + * - column: The column number in the original source, or null. + * - name: The original identifier, or null. + */ +BasicSourceMapConsumer.prototype.originalPositionFor = + function SourceMapConsumer_originalPositionFor(aArgs) { + var needle = { + generatedLine: util.getArg(aArgs, 'line'), + generatedColumn: util.getArg(aArgs, 'column') + }; + + var index = this._findMapping( + needle, + this._generatedMappings, + "generatedLine", + "generatedColumn", + util.compareByGeneratedPositionsDeflated, + util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND) + ); + + if (index >= 0) { + var mapping = this._generatedMappings[index]; + + if (mapping.generatedLine === needle.generatedLine) { + var source = util.getArg(mapping, 'source', null); + if (source !== null) { + source = this._sources.at(source); + if (this.sourceRoot != null) { + source = util.join(this.sourceRoot, source); + } + } + var name = util.getArg(mapping, 'name', null); + if (name !== null) { + name = this._names.at(name); + } + return { + source: source, + line: util.getArg(mapping, 'originalLine', null), + column: util.getArg(mapping, 'originalColumn', null), + name: name + }; + } + } + + return { + source: null, + line: null, + column: null, + name: null + }; + }; + +/** + * Return true if we have the source content for every source in the source + * map, false otherwise. + */ +BasicSourceMapConsumer.prototype.hasContentsOfAllSources = + function BasicSourceMapConsumer_hasContentsOfAllSources() { + if (!this.sourcesContent) { + return false; + } + return this.sourcesContent.length >= this._sources.size() && + !this.sourcesContent.some(function (sc) { return sc == null; }); + }; + +/** + * Returns the original source content. The only argument is the url of the + * original source file. Returns null if no original source content is + * available. + */ +BasicSourceMapConsumer.prototype.sourceContentFor = + function SourceMapConsumer_sourceContentFor(aSource, nullOnMissing) { + if (!this.sourcesContent) { + return null; + } + + if (this.sourceRoot != null) { + aSource = util.relative(this.sourceRoot, aSource); + } + + if (this._sources.has(aSource)) { + return this.sourcesContent[this._sources.indexOf(aSource)]; + } + + var url; + if (this.sourceRoot != null + && (url = util.urlParse(this.sourceRoot))) { + // XXX: file:// URIs and absolute paths lead to unexpected behavior for + // many users. We can help them out when they expect file:// URIs to + // behave like it would if they were running a local HTTP server. See + // https://bugzilla.mozilla.org/show_bug.cgi?id=885597. + var fileUriAbsPath = aSource.replace(/^file:\/\//, ""); + if (url.scheme == "file" + && this._sources.has(fileUriAbsPath)) { + return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)] + } + + if ((!url.path || url.path == "/") + && this._sources.has("/" + aSource)) { + return this.sourcesContent[this._sources.indexOf("/" + aSource)]; + } + } + + // This function is used recursively from + // IndexedSourceMapConsumer.prototype.sourceContentFor. In that case, we + // don't want to throw if we can't find the source - we just want to + // return null, so we provide a flag to exit gracefully. + if (nullOnMissing) { + return null; + } + else { + throw new Error('"' + aSource + '" is not in the SourceMap.'); + } + }; + +/** + * Returns the generated line and column information for the original source, + * line, and column positions provided. The only argument is an object with + * the following properties: + * + * - source: The filename of the original source. + * - line: The line number in the original source. + * - column: The column number in the original source. + * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or + * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the + * closest element that is smaller than or greater than the one we are + * searching for, respectively, if the exact element cannot be found. + * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'. + * + * and an object is returned with the following properties: + * + * - line: The line number in the generated source, or null. + * - column: The column number in the generated source, or null. + */ +BasicSourceMapConsumer.prototype.generatedPositionFor = + function SourceMapConsumer_generatedPositionFor(aArgs) { + var source = util.getArg(aArgs, 'source'); + if (this.sourceRoot != null) { + source = util.relative(this.sourceRoot, source); + } + if (!this._sources.has(source)) { + return { + line: null, + column: null, + lastColumn: null + }; + } + source = this._sources.indexOf(source); + + var needle = { + source: source, + originalLine: util.getArg(aArgs, 'line'), + originalColumn: util.getArg(aArgs, 'column') + }; + + var index = this._findMapping( + needle, + this._originalMappings, + "originalLine", + "originalColumn", + util.compareByOriginalPositions, + util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND) + ); + + if (index >= 0) { + var mapping = this._originalMappings[index]; + + if (mapping.source === needle.source) { + return { + line: util.getArg(mapping, 'generatedLine', null), + column: util.getArg(mapping, 'generatedColumn', null), + lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null) + }; + } + } + + return { + line: null, + column: null, + lastColumn: null + }; + }; + +exports.BasicSourceMapConsumer = BasicSourceMapConsumer; + +/** + * An IndexedSourceMapConsumer instance represents a parsed source map which + * we can query for information. It differs from BasicSourceMapConsumer in + * that it takes "indexed" source maps (i.e. ones with a "sections" field) as + * input. + * + * The only parameter is a raw source map (either as a JSON string, or already + * parsed to an object). According to the spec for indexed source maps, they + * have the following attributes: + * + * - version: Which version of the source map spec this map is following. + * - file: Optional. The generated file this source map is associated with. + * - sections: A list of section definitions. + * + * Each value under the "sections" field has two fields: + * - offset: The offset into the original specified at which this section + * begins to apply, defined as an object with a "line" and "column" + * field. + * - map: A source map definition. This source map could also be indexed, + * but doesn't have to be. + * + * Instead of the "map" field, it's also possible to have a "url" field + * specifying a URL to retrieve a source map from, but that's currently + * unsupported. + * + * Here's an example source map, taken from the source map spec[0], but + * modified to omit a section which uses the "url" field. + * + * { + * version : 3, + * file: "app.js", + * sections: [{ + * offset: {line:100, column:10}, + * map: { + * version : 3, + * file: "section.js", + * sources: ["foo.js", "bar.js"], + * names: ["src", "maps", "are", "fun"], + * mappings: "AAAA,E;;ABCDE;" + * } + * }], + * } + * + * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit#heading=h.535es3xeprgt + */ +function IndexedSourceMapConsumer(aSourceMap) { + var sourceMap = aSourceMap; + if (typeof aSourceMap === 'string') { + sourceMap = JSON.parse(aSourceMap.replace(/^\)\]\}'/, '')); + } + + var version = util.getArg(sourceMap, 'version'); + var sections = util.getArg(sourceMap, 'sections'); + + if (version != this._version) { + throw new Error('Unsupported version: ' + version); + } + + this._sources = new ArraySet(); + this._names = new ArraySet(); + + var lastOffset = { + line: -1, + column: 0 + }; + this._sections = sections.map(function (s) { + if (s.url) { + // The url field will require support for asynchronicity. + // See https://github.com/mozilla/source-map/issues/16 + throw new Error('Support for url field in sections not implemented.'); + } + var offset = util.getArg(s, 'offset'); + var offsetLine = util.getArg(offset, 'line'); + var offsetColumn = util.getArg(offset, 'column'); + + if (offsetLine < lastOffset.line || + (offsetLine === lastOffset.line && offsetColumn < lastOffset.column)) { + throw new Error('Section offsets must be ordered and non-overlapping.'); + } + lastOffset = offset; + + return { + generatedOffset: { + // The offset fields are 0-based, but we use 1-based indices when + // encoding/decoding from VLQ. + generatedLine: offsetLine + 1, + generatedColumn: offsetColumn + 1 + }, + consumer: new SourceMapConsumer(util.getArg(s, 'map')) + } + }); +} + +IndexedSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype); +IndexedSourceMapConsumer.prototype.constructor = SourceMapConsumer; + +/** + * The version of the source mapping spec that we are consuming. + */ +IndexedSourceMapConsumer.prototype._version = 3; + +/** + * The list of original sources. + */ +Object.defineProperty(IndexedSourceMapConsumer.prototype, 'sources', { + get: function () { + var sources = []; + for (var i = 0; i < this._sections.length; i++) { + for (var j = 0; j < this._sections[i].consumer.sources.length; j++) { + sources.push(this._sections[i].consumer.sources[j]); + } + } + return sources; + } +}); + +/** + * Returns the original source, line, and column information for the generated + * source's line and column positions provided. The only argument is an object + * with the following properties: + * + * - line: The line number in the generated source. + * - column: The column number in the generated source. + * + * and an object is returned with the following properties: + * + * - source: The original source file, or null. + * - line: The line number in the original source, or null. + * - column: The column number in the original source, or null. + * - name: The original identifier, or null. + */ +IndexedSourceMapConsumer.prototype.originalPositionFor = + function IndexedSourceMapConsumer_originalPositionFor(aArgs) { + var needle = { + generatedLine: util.getArg(aArgs, 'line'), + generatedColumn: util.getArg(aArgs, 'column') + }; + + // Find the section containing the generated position we're trying to map + // to an original position. + var sectionIndex = binarySearch.search(needle, this._sections, + function(needle, section) { + var cmp = needle.generatedLine - section.generatedOffset.generatedLine; + if (cmp) { + return cmp; + } + + return (needle.generatedColumn - + section.generatedOffset.generatedColumn); + }); + var section = this._sections[sectionIndex]; + + if (!section) { + return { + source: null, + line: null, + column: null, + name: null + }; + } + + return section.consumer.originalPositionFor({ + line: needle.generatedLine - + (section.generatedOffset.generatedLine - 1), + column: needle.generatedColumn - + (section.generatedOffset.generatedLine === needle.generatedLine + ? section.generatedOffset.generatedColumn - 1 + : 0), + bias: aArgs.bias + }); + }; + +/** + * Return true if we have the source content for every source in the source + * map, false otherwise. + */ +IndexedSourceMapConsumer.prototype.hasContentsOfAllSources = + function IndexedSourceMapConsumer_hasContentsOfAllSources() { + return this._sections.every(function (s) { + return s.consumer.hasContentsOfAllSources(); + }); + }; + +/** + * Returns the original source content. The only argument is the url of the + * original source file. Returns null if no original source content is + * available. + */ +IndexedSourceMapConsumer.prototype.sourceContentFor = + function IndexedSourceMapConsumer_sourceContentFor(aSource, nullOnMissing) { + for (var i = 0; i < this._sections.length; i++) { + var section = this._sections[i]; + + var content = section.consumer.sourceContentFor(aSource, true); + if (content) { + return content; + } + } + if (nullOnMissing) { + return null; + } + else { + throw new Error('"' + aSource + '" is not in the SourceMap.'); + } + }; + +/** + * Returns the generated line and column information for the original source, + * line, and column positions provided. The only argument is an object with + * the following properties: + * + * - source: The filename of the original source. + * - line: The line number in the original source. + * - column: The column number in the original source. + * + * and an object is returned with the following properties: + * + * - line: The line number in the generated source, or null. + * - column: The column number in the generated source, or null. + */ +IndexedSourceMapConsumer.prototype.generatedPositionFor = + function IndexedSourceMapConsumer_generatedPositionFor(aArgs) { + for (var i = 0; i < this._sections.length; i++) { + var section = this._sections[i]; + + // Only consider this section if the requested source is in the list of + // sources of the consumer. + if (section.consumer.sources.indexOf(util.getArg(aArgs, 'source')) === -1) { + continue; + } + var generatedPosition = section.consumer.generatedPositionFor(aArgs); + if (generatedPosition) { + var ret = { + line: generatedPosition.line + + (section.generatedOffset.generatedLine - 1), + column: generatedPosition.column + + (section.generatedOffset.generatedLine === generatedPosition.line + ? section.generatedOffset.generatedColumn - 1 + : 0) + }; + return ret; + } + } + + return { + line: null, + column: null + }; + }; + +/** + * Parse the mappings in a string in to a data structure which we can easily + * query (the ordered arrays in the `this.__generatedMappings` and + * `this.__originalMappings` properties). + */ +IndexedSourceMapConsumer.prototype._parseMappings = + function IndexedSourceMapConsumer_parseMappings(aStr, aSourceRoot) { + this.__generatedMappings = []; + this.__originalMappings = []; + for (var i = 0; i < this._sections.length; i++) { + var section = this._sections[i]; + var sectionMappings = section.consumer._generatedMappings; + for (var j = 0; j < sectionMappings.length; j++) { + var mapping = sectionMappings[j]; + + var source = section.consumer._sources.at(mapping.source); + if (section.consumer.sourceRoot !== null) { + source = util.join(section.consumer.sourceRoot, source); + } + this._sources.add(source); + source = this._sources.indexOf(source); + + var name = section.consumer._names.at(mapping.name); + this._names.add(name); + name = this._names.indexOf(name); + + // The mappings coming from the consumer for the section have + // generated positions relative to the start of the section, so we + // need to offset them to be relative to the start of the concatenated + // generated file. + var adjustedMapping = { + source: source, + generatedLine: mapping.generatedLine + + (section.generatedOffset.generatedLine - 1), + generatedColumn: mapping.generatedColumn + + (section.generatedOffset.generatedLine === mapping.generatedLine + ? section.generatedOffset.generatedColumn - 1 + : 0), + originalLine: mapping.originalLine, + originalColumn: mapping.originalColumn, + name: name + }; + + this.__generatedMappings.push(adjustedMapping); + if (typeof adjustedMapping.originalLine === 'number') { + this.__originalMappings.push(adjustedMapping); + } + } + } + + quickSort(this.__generatedMappings, util.compareByGeneratedPositionsDeflated); + quickSort(this.__originalMappings, util.compareByOriginalPositions); + }; + +exports.IndexedSourceMapConsumer = IndexedSourceMapConsumer; + +},{"./array-set":674,"./base64-vlq":675,"./binary-search":677,"./quick-sort":679,"./util":683}],681:[function(require,module,exports){ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +var base64VLQ = require('./base64-vlq'); +var util = require('./util'); +var ArraySet = require('./array-set').ArraySet; +var MappingList = require('./mapping-list').MappingList; + +/** + * An instance of the SourceMapGenerator represents a source map which is + * being built incrementally. You may pass an object with the following + * properties: + * + * - file: The filename of the generated source. + * - sourceRoot: A root for all relative URLs in this source map. + */ +function SourceMapGenerator(aArgs) { + if (!aArgs) { + aArgs = {}; + } + this._file = util.getArg(aArgs, 'file', null); + this._sourceRoot = util.getArg(aArgs, 'sourceRoot', null); + this._skipValidation = util.getArg(aArgs, 'skipValidation', false); + this._sources = new ArraySet(); + this._names = new ArraySet(); + this._mappings = new MappingList(); + this._sourcesContents = null; +} + +SourceMapGenerator.prototype._version = 3; + +/** + * Creates a new SourceMapGenerator based on a SourceMapConsumer + * + * @param aSourceMapConsumer The SourceMap. + */ +SourceMapGenerator.fromSourceMap = + function SourceMapGenerator_fromSourceMap(aSourceMapConsumer) { + var sourceRoot = aSourceMapConsumer.sourceRoot; + var generator = new SourceMapGenerator({ + file: aSourceMapConsumer.file, + sourceRoot: sourceRoot + }); + aSourceMapConsumer.eachMapping(function (mapping) { + var newMapping = { + generated: { + line: mapping.generatedLine, + column: mapping.generatedColumn + } + }; + + if (mapping.source != null) { + newMapping.source = mapping.source; + if (sourceRoot != null) { + newMapping.source = util.relative(sourceRoot, newMapping.source); + } + + newMapping.original = { + line: mapping.originalLine, + column: mapping.originalColumn + }; + + if (mapping.name != null) { + newMapping.name = mapping.name; + } + } + + generator.addMapping(newMapping); + }); + aSourceMapConsumer.sources.forEach(function (sourceFile) { + var content = aSourceMapConsumer.sourceContentFor(sourceFile); + if (content != null) { + generator.setSourceContent(sourceFile, content); + } + }); + return generator; + }; + +/** + * Add a single mapping from original source line and column to the generated + * source's line and column for this source map being created. The mapping + * object should have the following properties: + * + * - generated: An object with the generated line and column positions. + * - original: An object with the original line and column positions. + * - source: The original source file (relative to the sourceRoot). + * - name: An optional original token name for this mapping. + */ +SourceMapGenerator.prototype.addMapping = + function SourceMapGenerator_addMapping(aArgs) { + var generated = util.getArg(aArgs, 'generated'); + var original = util.getArg(aArgs, 'original', null); + var source = util.getArg(aArgs, 'source', null); + var name = util.getArg(aArgs, 'name', null); + + if (!this._skipValidation) { + this._validateMapping(generated, original, source, name); + } + + if (source != null) { + source = String(source); + if (!this._sources.has(source)) { + this._sources.add(source); + } + } + + if (name != null) { + name = String(name); + if (!this._names.has(name)) { + this._names.add(name); + } + } + + this._mappings.add({ + generatedLine: generated.line, + generatedColumn: generated.column, + originalLine: original != null && original.line, + originalColumn: original != null && original.column, + source: source, + name: name + }); + }; + +/** + * Set the source content for a source file. + */ +SourceMapGenerator.prototype.setSourceContent = + function SourceMapGenerator_setSourceContent(aSourceFile, aSourceContent) { + var source = aSourceFile; + if (this._sourceRoot != null) { + source = util.relative(this._sourceRoot, source); + } + + if (aSourceContent != null) { + // Add the source content to the _sourcesContents map. + // Create a new _sourcesContents map if the property is null. + if (!this._sourcesContents) { + this._sourcesContents = Object.create(null); + } + this._sourcesContents[util.toSetString(source)] = aSourceContent; + } else if (this._sourcesContents) { + // Remove the source file from the _sourcesContents map. + // If the _sourcesContents map is empty, set the property to null. + delete this._sourcesContents[util.toSetString(source)]; + if (Object.keys(this._sourcesContents).length === 0) { + this._sourcesContents = null; + } + } + }; + +/** + * Applies the mappings of a sub-source-map for a specific source file to the + * source map being generated. Each mapping to the supplied source file is + * rewritten using the supplied source map. Note: The resolution for the + * resulting mappings is the minimium of this map and the supplied map. + * + * @param aSourceMapConsumer The source map to be applied. + * @param aSourceFile Optional. The filename of the source file. + * If omitted, SourceMapConsumer's file property will be used. + * @param aSourceMapPath Optional. The dirname of the path to the source map + * to be applied. If relative, it is relative to the SourceMapConsumer. + * This parameter is needed when the two source maps aren't in the same + * directory, and the source map to be applied contains relative source + * paths. If so, those relative source paths need to be rewritten + * relative to the SourceMapGenerator. + */ +SourceMapGenerator.prototype.applySourceMap = + function SourceMapGenerator_applySourceMap(aSourceMapConsumer, aSourceFile, aSourceMapPath) { + var sourceFile = aSourceFile; + // If aSourceFile is omitted, we will use the file property of the SourceMap + if (aSourceFile == null) { + if (aSourceMapConsumer.file == null) { + throw new Error( + 'SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, ' + + 'or the source map\'s "file" property. Both were omitted.' + ); + } + sourceFile = aSourceMapConsumer.file; + } + var sourceRoot = this._sourceRoot; + // Make "sourceFile" relative if an absolute Url is passed. + if (sourceRoot != null) { + sourceFile = util.relative(sourceRoot, sourceFile); + } + // Applying the SourceMap can add and remove items from the sources and + // the names array. + var newSources = new ArraySet(); + var newNames = new ArraySet(); + + // Find mappings for the "sourceFile" + this._mappings.unsortedForEach(function (mapping) { + if (mapping.source === sourceFile && mapping.originalLine != null) { + // Check if it can be mapped by the source map, then update the mapping. + var original = aSourceMapConsumer.originalPositionFor({ + line: mapping.originalLine, + column: mapping.originalColumn + }); + if (original.source != null) { + // Copy mapping + mapping.source = original.source; + if (aSourceMapPath != null) { + mapping.source = util.join(aSourceMapPath, mapping.source) + } + if (sourceRoot != null) { + mapping.source = util.relative(sourceRoot, mapping.source); + } + mapping.originalLine = original.line; + mapping.originalColumn = original.column; + if (original.name != null) { + mapping.name = original.name; + } + } + } + + var source = mapping.source; + if (source != null && !newSources.has(source)) { + newSources.add(source); + } + + var name = mapping.name; + if (name != null && !newNames.has(name)) { + newNames.add(name); + } + + }, this); + this._sources = newSources; + this._names = newNames; + + // Copy sourcesContents of applied map. + aSourceMapConsumer.sources.forEach(function (sourceFile) { + var content = aSourceMapConsumer.sourceContentFor(sourceFile); + if (content != null) { + if (aSourceMapPath != null) { + sourceFile = util.join(aSourceMapPath, sourceFile); + } + if (sourceRoot != null) { + sourceFile = util.relative(sourceRoot, sourceFile); + } + this.setSourceContent(sourceFile, content); + } + }, this); + }; + +/** + * A mapping can have one of the three levels of data: + * + * 1. Just the generated position. + * 2. The Generated position, original position, and original source. + * 3. Generated and original position, original source, as well as a name + * token. + * + * To maintain consistency, we validate that any new mapping being added falls + * in to one of these categories. + */ +SourceMapGenerator.prototype._validateMapping = + function SourceMapGenerator_validateMapping(aGenerated, aOriginal, aSource, + aName) { + if (aGenerated && 'line' in aGenerated && 'column' in aGenerated + && aGenerated.line > 0 && aGenerated.column >= 0 + && !aOriginal && !aSource && !aName) { + // Case 1. + return; + } + else if (aGenerated && 'line' in aGenerated && 'column' in aGenerated + && aOriginal && 'line' in aOriginal && 'column' in aOriginal + && aGenerated.line > 0 && aGenerated.column >= 0 + && aOriginal.line > 0 && aOriginal.column >= 0 + && aSource) { + // Cases 2 and 3. + return; + } + else { + throw new Error('Invalid mapping: ' + JSON.stringify({ + generated: aGenerated, + source: aSource, + original: aOriginal, + name: aName + })); + } + }; + +/** + * Serialize the accumulated mappings in to the stream of base 64 VLQs + * specified by the source map format. + */ +SourceMapGenerator.prototype._serializeMappings = + function SourceMapGenerator_serializeMappings() { + var previousGeneratedColumn = 0; + var previousGeneratedLine = 1; + var previousOriginalColumn = 0; + var previousOriginalLine = 0; + var previousName = 0; + var previousSource = 0; + var result = ''; + var next; + var mapping; + var nameIdx; + var sourceIdx; + + var mappings = this._mappings.toArray(); + for (var i = 0, len = mappings.length; i < len; i++) { + mapping = mappings[i]; + next = '' + + if (mapping.generatedLine !== previousGeneratedLine) { + previousGeneratedColumn = 0; + while (mapping.generatedLine !== previousGeneratedLine) { + next += ';'; + previousGeneratedLine++; + } + } + else { + if (i > 0) { + if (!util.compareByGeneratedPositionsInflated(mapping, mappings[i - 1])) { + continue; + } + next += ','; + } + } + + next += base64VLQ.encode(mapping.generatedColumn + - previousGeneratedColumn); + previousGeneratedColumn = mapping.generatedColumn; + + if (mapping.source != null) { + sourceIdx = this._sources.indexOf(mapping.source); + next += base64VLQ.encode(sourceIdx - previousSource); + previousSource = sourceIdx; + + // lines are stored 0-based in SourceMap spec version 3 + next += base64VLQ.encode(mapping.originalLine - 1 + - previousOriginalLine); + previousOriginalLine = mapping.originalLine - 1; + + next += base64VLQ.encode(mapping.originalColumn + - previousOriginalColumn); + previousOriginalColumn = mapping.originalColumn; + + if (mapping.name != null) { + nameIdx = this._names.indexOf(mapping.name); + next += base64VLQ.encode(nameIdx - previousName); + previousName = nameIdx; + } + } + + result += next; + } + + return result; + }; + +SourceMapGenerator.prototype._generateSourcesContent = + function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) { + return aSources.map(function (source) { + if (!this._sourcesContents) { + return null; + } + if (aSourceRoot != null) { + source = util.relative(aSourceRoot, source); + } + var key = util.toSetString(source); + return Object.prototype.hasOwnProperty.call(this._sourcesContents, key) + ? this._sourcesContents[key] + : null; + }, this); + }; + +/** + * Externalize the source map. + */ +SourceMapGenerator.prototype.toJSON = + function SourceMapGenerator_toJSON() { + var map = { + version: this._version, + sources: this._sources.toArray(), + names: this._names.toArray(), + mappings: this._serializeMappings() + }; + if (this._file != null) { + map.file = this._file; + } + if (this._sourceRoot != null) { + map.sourceRoot = this._sourceRoot; + } + if (this._sourcesContents) { + map.sourcesContent = this._generateSourcesContent(map.sources, map.sourceRoot); + } + + return map; + }; + +/** + * Render the source map being generated to a string. + */ +SourceMapGenerator.prototype.toString = + function SourceMapGenerator_toString() { + return JSON.stringify(this.toJSON()); + }; + +exports.SourceMapGenerator = SourceMapGenerator; + +},{"./array-set":674,"./base64-vlq":675,"./mapping-list":678,"./util":683}],682:[function(require,module,exports){ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +var SourceMapGenerator = require('./source-map-generator').SourceMapGenerator; +var util = require('./util'); + +// Matches a Windows-style `\r\n` newline or a `\n` newline used by all other +// operating systems these days (capturing the result). +var REGEX_NEWLINE = /(\r?\n)/; + +// Newline character code for charCodeAt() comparisons +var NEWLINE_CODE = 10; + +// Private symbol for identifying `SourceNode`s when multiple versions of +// the source-map library are loaded. This MUST NOT CHANGE across +// versions! +var isSourceNode = "$$$isSourceNode$$$"; + +/** + * SourceNodes provide a way to abstract over interpolating/concatenating + * snippets of generated JavaScript source code while maintaining the line and + * column information associated with the original source code. + * + * @param aLine The original line number. + * @param aColumn The original column number. + * @param aSource The original source's filename. + * @param aChunks Optional. An array of strings which are snippets of + * generated JS, or other SourceNodes. + * @param aName The original identifier. + */ +function SourceNode(aLine, aColumn, aSource, aChunks, aName) { + this.children = []; + this.sourceContents = {}; + this.line = aLine == null ? null : aLine; + this.column = aColumn == null ? null : aColumn; + this.source = aSource == null ? null : aSource; + this.name = aName == null ? null : aName; + this[isSourceNode] = true; + if (aChunks != null) this.add(aChunks); +} + +/** + * Creates a SourceNode from generated code and a SourceMapConsumer. + * + * @param aGeneratedCode The generated code + * @param aSourceMapConsumer The SourceMap for the generated code + * @param aRelativePath Optional. The path that relative sources in the + * SourceMapConsumer should be relative to. + */ +SourceNode.fromStringWithSourceMap = + function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer, aRelativePath) { + // The SourceNode we want to fill with the generated code + // and the SourceMap + var node = new SourceNode(); + + // All even indices of this array are one line of the generated code, + // while all odd indices are the newlines between two adjacent lines + // (since `REGEX_NEWLINE` captures its match). + // Processed fragments are removed from this array, by calling `shiftNextLine`. + var remainingLines = aGeneratedCode.split(REGEX_NEWLINE); + var shiftNextLine = function() { + var lineContents = remainingLines.shift(); + // The last line of a file might not have a newline. + var newLine = remainingLines.shift() || ""; + return lineContents + newLine; + }; + + // We need to remember the position of "remainingLines" + var lastGeneratedLine = 1, lastGeneratedColumn = 0; + + // The generate SourceNodes we need a code range. + // To extract it current and last mapping is used. + // Here we store the last mapping. + var lastMapping = null; + + aSourceMapConsumer.eachMapping(function (mapping) { + if (lastMapping !== null) { + // We add the code from "lastMapping" to "mapping": + // First check if there is a new line in between. + if (lastGeneratedLine < mapping.generatedLine) { + // Associate first line with "lastMapping" + addMappingWithCode(lastMapping, shiftNextLine()); + lastGeneratedLine++; + lastGeneratedColumn = 0; + // The remaining code is added without mapping + } else { + // There is no new line in between. + // Associate the code between "lastGeneratedColumn" and + // "mapping.generatedColumn" with "lastMapping" + var nextLine = remainingLines[0]; + var code = nextLine.substr(0, mapping.generatedColumn - + lastGeneratedColumn); + remainingLines[0] = nextLine.substr(mapping.generatedColumn - + lastGeneratedColumn); + lastGeneratedColumn = mapping.generatedColumn; + addMappingWithCode(lastMapping, code); + // No more remaining code, continue + lastMapping = mapping; + return; + } + } + // We add the generated code until the first mapping + // to the SourceNode without any mapping. + // Each line is added as separate string. + while (lastGeneratedLine < mapping.generatedLine) { + node.add(shiftNextLine()); + lastGeneratedLine++; + } + if (lastGeneratedColumn < mapping.generatedColumn) { + var nextLine = remainingLines[0]; + node.add(nextLine.substr(0, mapping.generatedColumn)); + remainingLines[0] = nextLine.substr(mapping.generatedColumn); + lastGeneratedColumn = mapping.generatedColumn; + } + lastMapping = mapping; + }, this); + // We have processed all mappings. + if (remainingLines.length > 0) { + if (lastMapping) { + // Associate the remaining code in the current line with "lastMapping" + addMappingWithCode(lastMapping, shiftNextLine()); + } + // and add the remaining lines without any mapping + node.add(remainingLines.join("")); + } + + // Copy sourcesContent into SourceNode + aSourceMapConsumer.sources.forEach(function (sourceFile) { + var content = aSourceMapConsumer.sourceContentFor(sourceFile); + if (content != null) { + if (aRelativePath != null) { + sourceFile = util.join(aRelativePath, sourceFile); + } + node.setSourceContent(sourceFile, content); + } + }); + + return node; + + function addMappingWithCode(mapping, code) { + if (mapping === null || mapping.source === undefined) { + node.add(code); + } else { + var source = aRelativePath + ? util.join(aRelativePath, mapping.source) + : mapping.source; + node.add(new SourceNode(mapping.originalLine, + mapping.originalColumn, + source, + code, + mapping.name)); + } + } + }; + +/** + * Add a chunk of generated JS to this source node. + * + * @param aChunk A string snippet of generated JS code, another instance of + * SourceNode, or an array where each member is one of those things. + */ +SourceNode.prototype.add = function SourceNode_add(aChunk) { + if (Array.isArray(aChunk)) { + aChunk.forEach(function (chunk) { + this.add(chunk); + }, this); + } + else if (aChunk[isSourceNode] || typeof aChunk === "string") { + if (aChunk) { + this.children.push(aChunk); + } + } + else { + throw new TypeError( + "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk + ); + } + return this; +}; + +/** + * Add a chunk of generated JS to the beginning of this source node. + * + * @param aChunk A string snippet of generated JS code, another instance of + * SourceNode, or an array where each member is one of those things. + */ +SourceNode.prototype.prepend = function SourceNode_prepend(aChunk) { + if (Array.isArray(aChunk)) { + for (var i = aChunk.length-1; i >= 0; i--) { + this.prepend(aChunk[i]); + } + } + else if (aChunk[isSourceNode] || typeof aChunk === "string") { + this.children.unshift(aChunk); + } + else { + throw new TypeError( + "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk + ); + } + return this; +}; + +/** + * Walk over the tree of JS snippets in this node and its children. The + * walking function is called once for each snippet of JS and is passed that + * snippet and the its original associated source's line/column location. + * + * @param aFn The traversal function. + */ +SourceNode.prototype.walk = function SourceNode_walk(aFn) { + var chunk; + for (var i = 0, len = this.children.length; i < len; i++) { + chunk = this.children[i]; + if (chunk[isSourceNode]) { + chunk.walk(aFn); + } + else { + if (chunk !== '') { + aFn(chunk, { source: this.source, + line: this.line, + column: this.column, + name: this.name }); + } + } + } +}; + +/** + * Like `String.prototype.join` except for SourceNodes. Inserts `aStr` between + * each of `this.children`. + * + * @param aSep The separator. + */ +SourceNode.prototype.join = function SourceNode_join(aSep) { + var newChildren; + var i; + var len = this.children.length; + if (len > 0) { + newChildren = []; + for (i = 0; i < len-1; i++) { + newChildren.push(this.children[i]); + newChildren.push(aSep); + } + newChildren.push(this.children[i]); + this.children = newChildren; + } + return this; +}; + +/** + * Call String.prototype.replace on the very right-most source snippet. Useful + * for trimming whitespace from the end of a source node, etc. + * + * @param aPattern The pattern to replace. + * @param aReplacement The thing to replace the pattern with. + */ +SourceNode.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) { + var lastChild = this.children[this.children.length - 1]; + if (lastChild[isSourceNode]) { + lastChild.replaceRight(aPattern, aReplacement); + } + else if (typeof lastChild === 'string') { + this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement); + } + else { + this.children.push(''.replace(aPattern, aReplacement)); + } + return this; +}; + +/** + * Set the source content for a source file. This will be added to the SourceMapGenerator + * in the sourcesContent field. + * + * @param aSourceFile The filename of the source file + * @param aSourceContent The content of the source file + */ +SourceNode.prototype.setSourceContent = + function SourceNode_setSourceContent(aSourceFile, aSourceContent) { + this.sourceContents[util.toSetString(aSourceFile)] = aSourceContent; + }; + +/** + * Walk over the tree of SourceNodes. The walking function is called for each + * source file content and is passed the filename and source content. + * + * @param aFn The traversal function. + */ +SourceNode.prototype.walkSourceContents = + function SourceNode_walkSourceContents(aFn) { + for (var i = 0, len = this.children.length; i < len; i++) { + if (this.children[i][isSourceNode]) { + this.children[i].walkSourceContents(aFn); + } + } + + var sources = Object.keys(this.sourceContents); + for (var i = 0, len = sources.length; i < len; i++) { + aFn(util.fromSetString(sources[i]), this.sourceContents[sources[i]]); + } + }; + +/** + * Return the string representation of this source node. Walks over the tree + * and concatenates all the various snippets together to one string. + */ +SourceNode.prototype.toString = function SourceNode_toString() { + var str = ""; + this.walk(function (chunk) { + str += chunk; + }); + return str; +}; + +/** + * Returns the string representation of this source node along with a source + * map. + */ +SourceNode.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) { + var generated = { + code: "", + line: 1, + column: 0 + }; + var map = new SourceMapGenerator(aArgs); + var sourceMappingActive = false; + var lastOriginalSource = null; + var lastOriginalLine = null; + var lastOriginalColumn = null; + var lastOriginalName = null; + this.walk(function (chunk, original) { + generated.code += chunk; + if (original.source !== null + && original.line !== null + && original.column !== null) { + if(lastOriginalSource !== original.source + || lastOriginalLine !== original.line + || lastOriginalColumn !== original.column + || lastOriginalName !== original.name) { + map.addMapping({ + source: original.source, + original: { + line: original.line, + column: original.column + }, + generated: { + line: generated.line, + column: generated.column + }, + name: original.name + }); + } + lastOriginalSource = original.source; + lastOriginalLine = original.line; + lastOriginalColumn = original.column; + lastOriginalName = original.name; + sourceMappingActive = true; + } else if (sourceMappingActive) { + map.addMapping({ + generated: { + line: generated.line, + column: generated.column + } + }); + lastOriginalSource = null; + sourceMappingActive = false; + } + for (var idx = 0, length = chunk.length; idx < length; idx++) { + if (chunk.charCodeAt(idx) === NEWLINE_CODE) { + generated.line++; + generated.column = 0; + // Mappings end at eol + if (idx + 1 === length) { + lastOriginalSource = null; + sourceMappingActive = false; + } else if (sourceMappingActive) { + map.addMapping({ + source: original.source, + original: { + line: original.line, + column: original.column + }, + generated: { + line: generated.line, + column: generated.column + }, + name: original.name + }); + } + } else { + generated.column++; + } + } + }); + this.walkSourceContents(function (sourceFile, sourceContent) { + map.setSourceContent(sourceFile, sourceContent); + }); + + return { code: generated.code, map: map }; +}; + +exports.SourceNode = SourceNode; + +},{"./source-map-generator":681,"./util":683}],683:[function(require,module,exports){ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +/** + * This is a helper function for getting values from parameter/options + * objects. + * + * @param args The object we are extracting values from + * @param name The name of the property we are getting. + * @param defaultValue An optional value to return if the property is missing + * from the object. If this is not specified and the property is missing, an + * error will be thrown. + */ +function getArg(aArgs, aName, aDefaultValue) { + if (aName in aArgs) { + return aArgs[aName]; + } else if (arguments.length === 3) { + return aDefaultValue; + } else { + throw new Error('"' + aName + '" is a required argument.'); + } +} +exports.getArg = getArg; + +var urlRegexp = /^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.]*)(?::(\d+))?(\S*)$/; +var dataUrlRegexp = /^data:.+\,.+$/; + +function urlParse(aUrl) { + var match = aUrl.match(urlRegexp); + if (!match) { + return null; + } + return { + scheme: match[1], + auth: match[2], + host: match[3], + port: match[4], + path: match[5] + }; +} +exports.urlParse = urlParse; + +function urlGenerate(aParsedUrl) { + var url = ''; + if (aParsedUrl.scheme) { + url += aParsedUrl.scheme + ':'; + } + url += '//'; + if (aParsedUrl.auth) { + url += aParsedUrl.auth + '@'; + } + if (aParsedUrl.host) { + url += aParsedUrl.host; + } + if (aParsedUrl.port) { + url += ":" + aParsedUrl.port + } + if (aParsedUrl.path) { + url += aParsedUrl.path; + } + return url; +} +exports.urlGenerate = urlGenerate; + +/** + * Normalizes a path, or the path portion of a URL: + * + * - Replaces consecutive slashes with one slash. + * - Removes unnecessary '.' parts. + * - Removes unnecessary '/..' parts. + * + * Based on code in the Node.js 'path' core module. + * + * @param aPath The path or url to normalize. + */ +function normalize(aPath) { + var path = aPath; + var url = urlParse(aPath); + if (url) { + if (!url.path) { + return aPath; + } + path = url.path; + } + var isAbsolute = exports.isAbsolute(path); + + var parts = path.split(/\/+/); + for (var part, up = 0, i = parts.length - 1; i >= 0; i--) { + part = parts[i]; + if (part === '.') { + parts.splice(i, 1); + } else if (part === '..') { + up++; + } else if (up > 0) { + if (part === '') { + // The first part is blank if the path is absolute. Trying to go + // above the root is a no-op. Therefore we can remove all '..' parts + // directly after the root. + parts.splice(i + 1, up); + up = 0; + } else { + parts.splice(i, 2); + up--; + } + } + } + path = parts.join('/'); + + if (path === '') { + path = isAbsolute ? '/' : '.'; + } + + if (url) { + url.path = path; + return urlGenerate(url); + } + return path; +} +exports.normalize = normalize; + +/** + * Joins two paths/URLs. + * + * @param aRoot The root path or URL. + * @param aPath The path or URL to be joined with the root. + * + * - If aPath is a URL or a data URI, aPath is returned, unless aPath is a + * scheme-relative URL: Then the scheme of aRoot, if any, is prepended + * first. + * - Otherwise aPath is a path. If aRoot is a URL, then its path portion + * is updated with the result and aRoot is returned. Otherwise the result + * is returned. + * - If aPath is absolute, the result is aPath. + * - Otherwise the two paths are joined with a slash. + * - Joining for example 'http://' and 'www.example.com' is also supported. + */ +function join(aRoot, aPath) { + if (aRoot === "") { + aRoot = "."; + } + if (aPath === "") { + aPath = "."; + } + var aPathUrl = urlParse(aPath); + var aRootUrl = urlParse(aRoot); + if (aRootUrl) { + aRoot = aRootUrl.path || '/'; + } + + // `join(foo, '//www.example.org')` + if (aPathUrl && !aPathUrl.scheme) { + if (aRootUrl) { + aPathUrl.scheme = aRootUrl.scheme; + } + return urlGenerate(aPathUrl); + } + + if (aPathUrl || aPath.match(dataUrlRegexp)) { + return aPath; + } + + // `join('http://', 'www.example.com')` + if (aRootUrl && !aRootUrl.host && !aRootUrl.path) { + aRootUrl.host = aPath; + return urlGenerate(aRootUrl); + } + + var joined = aPath.charAt(0) === '/' + ? aPath + : normalize(aRoot.replace(/\/+$/, '') + '/' + aPath); + + if (aRootUrl) { + aRootUrl.path = joined; + return urlGenerate(aRootUrl); + } + return joined; +} +exports.join = join; + +exports.isAbsolute = function (aPath) { + return aPath.charAt(0) === '/' || !!aPath.match(urlRegexp); +}; + +/** + * Make a path relative to a URL or another path. + * + * @param aRoot The root path or URL. + * @param aPath The path or URL to be made relative to aRoot. + */ +function relative(aRoot, aPath) { + if (aRoot === "") { + aRoot = "."; + } + + aRoot = aRoot.replace(/\/$/, ''); + + // It is possible for the path to be above the root. In this case, simply + // checking whether the root is a prefix of the path won't work. Instead, we + // need to remove components from the root one by one, until either we find + // a prefix that fits, or we run out of components to remove. + var level = 0; + while (aPath.indexOf(aRoot + '/') !== 0) { + var index = aRoot.lastIndexOf("/"); + if (index < 0) { + return aPath; + } + + // If the only part of the root that is left is the scheme (i.e. http://, + // file:///, etc.), one or more slashes (/), or simply nothing at all, we + // have exhausted all components, so the path is not relative to the root. + aRoot = aRoot.slice(0, index); + if (aRoot.match(/^([^\/]+:\/)?\/*$/)) { + return aPath; + } + + ++level; + } + + // Make sure we add a "../" for each component we removed from the root. + return Array(level + 1).join("../") + aPath.substr(aRoot.length + 1); +} +exports.relative = relative; + +var supportsNullProto = (function () { + var obj = Object.create(null); + return !('__proto__' in obj); +}()); + +function identity (s) { + return s; +} + +/** + * Because behavior goes wacky when you set `__proto__` on objects, we + * have to prefix all the strings in our set with an arbitrary character. + * + * See https://github.com/mozilla/source-map/pull/31 and + * https://github.com/mozilla/source-map/issues/30 + * + * @param String aStr + */ +function toSetString(aStr) { + if (isProtoString(aStr)) { + return '$' + aStr; + } + + return aStr; +} +exports.toSetString = supportsNullProto ? identity : toSetString; + +function fromSetString(aStr) { + if (isProtoString(aStr)) { + return aStr.slice(1); + } + + return aStr; +} +exports.fromSetString = supportsNullProto ? identity : fromSetString; + +function isProtoString(s) { + if (!s) { + return false; + } + + var length = s.length; + + if (length < 9 /* "__proto__".length */) { + return false; + } + + if (s.charCodeAt(length - 1) !== 95 /* '_' */ || + s.charCodeAt(length - 2) !== 95 /* '_' */ || + s.charCodeAt(length - 3) !== 111 /* 'o' */ || + s.charCodeAt(length - 4) !== 116 /* 't' */ || + s.charCodeAt(length - 5) !== 111 /* 'o' */ || + s.charCodeAt(length - 6) !== 114 /* 'r' */ || + s.charCodeAt(length - 7) !== 112 /* 'p' */ || + s.charCodeAt(length - 8) !== 95 /* '_' */ || + s.charCodeAt(length - 9) !== 95 /* '_' */) { + return false; + } + + for (var i = length - 10; i >= 0; i--) { + if (s.charCodeAt(i) !== 36 /* '$' */) { + return false; + } + } + + return true; +} + +/** + * Comparator between two mappings where the original positions are compared. + * + * Optionally pass in `true` as `onlyCompareGenerated` to consider two + * mappings with the same original source/line/column, but different generated + * line and column the same. Useful when searching for a mapping with a + * stubbed out mapping. + */ +function compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) { + var cmp = mappingA.source - mappingB.source; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalLine - mappingB.originalLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalColumn - mappingB.originalColumn; + if (cmp !== 0 || onlyCompareOriginal) { + return cmp; + } + + cmp = mappingA.generatedColumn - mappingB.generatedColumn; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.generatedLine - mappingB.generatedLine; + if (cmp !== 0) { + return cmp; + } + + return mappingA.name - mappingB.name; +} +exports.compareByOriginalPositions = compareByOriginalPositions; + +/** + * Comparator between two mappings with deflated source and name indices where + * the generated positions are compared. + * + * Optionally pass in `true` as `onlyCompareGenerated` to consider two + * mappings with the same generated line and column, but different + * source/name/original line and column the same. Useful when searching for a + * mapping with a stubbed out mapping. + */ +function compareByGeneratedPositionsDeflated(mappingA, mappingB, onlyCompareGenerated) { + var cmp = mappingA.generatedLine - mappingB.generatedLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.generatedColumn - mappingB.generatedColumn; + if (cmp !== 0 || onlyCompareGenerated) { + return cmp; + } + + cmp = mappingA.source - mappingB.source; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalLine - mappingB.originalLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalColumn - mappingB.originalColumn; + if (cmp !== 0) { + return cmp; + } + + return mappingA.name - mappingB.name; +} +exports.compareByGeneratedPositionsDeflated = compareByGeneratedPositionsDeflated; + +function strcmp(aStr1, aStr2) { + if (aStr1 === aStr2) { + return 0; + } + + if (aStr1 > aStr2) { + return 1; + } + + return -1; +} + +/** + * Comparator between two mappings with inflated source and name strings where + * the generated positions are compared. + */ +function compareByGeneratedPositionsInflated(mappingA, mappingB) { + var cmp = mappingA.generatedLine - mappingB.generatedLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.generatedColumn - mappingB.generatedColumn; + if (cmp !== 0) { + return cmp; + } + + cmp = strcmp(mappingA.source, mappingB.source); + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalLine - mappingB.originalLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalColumn - mappingB.originalColumn; + if (cmp !== 0) { + return cmp; + } + + return strcmp(mappingA.name, mappingB.name); +} +exports.compareByGeneratedPositionsInflated = compareByGeneratedPositionsInflated; + +},{}],684:[function(require,module,exports){ +/* + * Copyright 2009-2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE.txt or: + * http://opensource.org/licenses/BSD-3-Clause + */ +exports.SourceMapGenerator = require('./lib/source-map-generator').SourceMapGenerator; +exports.SourceMapConsumer = require('./lib/source-map-consumer').SourceMapConsumer; +exports.SourceNode = require('./lib/source-node').SourceNode; + +},{"./lib/source-map-consumer":680,"./lib/source-map-generator":681,"./lib/source-node":682}],685:[function(require,module,exports){ +'use strict'; +var ansiRegex = require('ansi-regex')(); + +module.exports = function (str) { + return typeof str === 'string' ? str.replace(ansiRegex, '') : str; +}; + +},{"ansi-regex":15}],686:[function(require,module,exports){ +(function (process){ +'use strict'; +var argv = process.argv; + +var terminator = argv.indexOf('--'); +var hasFlag = function (flag) { + flag = '--' + flag; + var pos = argv.indexOf(flag); + return pos !== -1 && (terminator !== -1 ? pos < terminator : true); +}; + +module.exports = (function () { + if ('FORCE_COLOR' in process.env) { + return true; + } + + if (hasFlag('no-color') || + hasFlag('no-colors') || + hasFlag('color=false')) { + return false; + } + + if (hasFlag('color') || + hasFlag('colors') || + hasFlag('color=true') || + hasFlag('color=always')) { + return true; + } + + if (process.stdout && !process.stdout.isTTY) { + return false; + } + + if (process.platform === 'win32') { + return true; + } + + if ('COLORTERM' in process.env) { + return true; + } + + if (process.env.TERM === 'dumb') { + return false; + } + + if (/^screen|^xterm|^vt100|color|ansi|cygwin|linux/i.test(process.env.TERM)) { + return true; + } + + return false; +})(); + +}).call(this,require('_process')) +},{"_process":594}],687:[function(require,module,exports){ +'use strict'; +module.exports = function toFastProperties(obj) { + function f() {} + f.prototype = obj; + new f(); + return; + eval(obj); +}; + +},{}],688:[function(require,module,exports){ +exports.isatty = function () { return false; }; + +function ReadStream() { + throw new Error('tty.ReadStream is not implemented'); +} +exports.ReadStream = ReadStream; + +function WriteStream() { + throw new Error('tty.ReadStream is not implemented'); +} +exports.WriteStream = WriteStream; + +},{}],689:[function(require,module,exports){ +if (typeof Object.create === 'function') { + // implementation from standard node.js 'util' module + module.exports = function inherits(ctor, superCtor) { + ctor.super_ = superCtor + ctor.prototype = Object.create(superCtor.prototype, { + constructor: { + value: ctor, + enumerable: false, + writable: true, + configurable: true + } + }); + }; +} else { + // old school shim for old browsers + module.exports = function inherits(ctor, superCtor) { + ctor.super_ = superCtor + var TempCtor = function () {} + TempCtor.prototype = superCtor.prototype + ctor.prototype = new TempCtor() + ctor.prototype.constructor = ctor + } +} + +},{}],690:[function(require,module,exports){ +module.exports = function isBuffer(arg) { + return arg && typeof arg === 'object' + && typeof arg.copy === 'function' + && typeof arg.fill === 'function' + && typeof arg.readUInt8 === 'function'; +} +},{}],691:[function(require,module,exports){ +(function (process,global){ +// Copyright Joyent, Inc. and other Node contributors. +// +// 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. + +var formatRegExp = /%[sdj%]/g; +exports.format = function(f) { + if (!isString(f)) { + var objects = []; + for (var i = 0; i < arguments.length; i++) { + objects.push(inspect(arguments[i])); + } + return objects.join(' '); + } + + var i = 1; + var args = arguments; + var len = args.length; + var str = String(f).replace(formatRegExp, function(x) { + if (x === '%%') return '%'; + if (i >= len) return x; + switch (x) { + case '%s': return String(args[i++]); + case '%d': return Number(args[i++]); + case '%j': + try { + return JSON.stringify(args[i++]); + } catch (_) { + return '[Circular]'; + } + default: + return x; + } + }); + for (var x = args[i]; i < len; x = args[++i]) { + if (isNull(x) || !isObject(x)) { + str += ' ' + x; + } else { + str += ' ' + inspect(x); + } + } + return str; +}; + + +// Mark that a method should not be used. +// Returns a modified function which warns once by default. +// If --no-deprecation is set, then it is a no-op. +exports.deprecate = function(fn, msg) { + // Allow for deprecating things in the process of starting up. + if (isUndefined(global.process)) { + return function() { + return exports.deprecate(fn, msg).apply(this, arguments); + }; + } + + if (process.noDeprecation === true) { + return fn; + } + + var warned = false; + function deprecated() { + if (!warned) { + if (process.throwDeprecation) { + throw new Error(msg); + } else if (process.traceDeprecation) { + console.trace(msg); + } else { + console.error(msg); + } + warned = true; + } + return fn.apply(this, arguments); + } + + return deprecated; +}; + + +var debugs = {}; +var debugEnviron; +exports.debuglog = function(set) { + if (isUndefined(debugEnviron)) + debugEnviron = process.env.NODE_DEBUG || ''; + set = set.toUpperCase(); + if (!debugs[set]) { + if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) { + var pid = process.pid; + debugs[set] = function() { + var msg = exports.format.apply(exports, arguments); + console.error('%s %d: %s', set, pid, msg); + }; + } else { + debugs[set] = function() {}; + } + } + return debugs[set]; +}; + + +/** + * Echos the value of a value. Trys to print the value out + * in the best way possible given the different types. + * + * @param {Object} obj The object to print out. + * @param {Object} opts Optional options object that alters the output. + */ +/* legacy: obj, showHidden, depth, colors*/ +function inspect(obj, opts) { + // default options + var ctx = { + seen: [], + stylize: stylizeNoColor + }; + // legacy... + if (arguments.length >= 3) ctx.depth = arguments[2]; + if (arguments.length >= 4) ctx.colors = arguments[3]; + if (isBoolean(opts)) { + // legacy... + ctx.showHidden = opts; + } else if (opts) { + // got an "options" object + exports._extend(ctx, opts); + } + // set default options + if (isUndefined(ctx.showHidden)) ctx.showHidden = false; + if (isUndefined(ctx.depth)) ctx.depth = 2; + if (isUndefined(ctx.colors)) ctx.colors = false; + if (isUndefined(ctx.customInspect)) ctx.customInspect = true; + if (ctx.colors) ctx.stylize = stylizeWithColor; + return formatValue(ctx, obj, ctx.depth); +} +exports.inspect = inspect; + + +// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics +inspect.colors = { + 'bold' : [1, 22], + 'italic' : [3, 23], + 'underline' : [4, 24], + 'inverse' : [7, 27], + 'white' : [37, 39], + 'grey' : [90, 39], + 'black' : [30, 39], + 'blue' : [34, 39], + 'cyan' : [36, 39], + 'green' : [32, 39], + 'magenta' : [35, 39], + 'red' : [31, 39], + 'yellow' : [33, 39] +}; + +// Don't use 'blue' not visible on cmd.exe +inspect.styles = { + 'special': 'cyan', + 'number': 'yellow', + 'boolean': 'yellow', + 'undefined': 'grey', + 'null': 'bold', + 'string': 'green', + 'date': 'magenta', + // "name": intentionally not styling + 'regexp': 'red' +}; + + +function stylizeWithColor(str, styleType) { + var style = inspect.styles[styleType]; + + if (style) { + return '\u001b[' + inspect.colors[style][0] + 'm' + str + + '\u001b[' + inspect.colors[style][1] + 'm'; + } else { + return str; + } +} + + +function stylizeNoColor(str, styleType) { + return str; +} + + +function arrayToHash(array) { + var hash = {}; + + array.forEach(function(val, idx) { + hash[val] = true; + }); + + return hash; +} + + +function formatValue(ctx, value, recurseTimes) { + // Provide a hook for user-specified inspect functions. + // Check that value is an object with an inspect function on it + if (ctx.customInspect && + value && + isFunction(value.inspect) && + // Filter out the util module, it's inspect function is special + value.inspect !== exports.inspect && + // Also filter out any prototype objects using the circular check. + !(value.constructor && value.constructor.prototype === value)) { + var ret = value.inspect(recurseTimes, ctx); + if (!isString(ret)) { + ret = formatValue(ctx, ret, recurseTimes); + } + return ret; + } + + // Primitive types cannot have properties + var primitive = formatPrimitive(ctx, value); + if (primitive) { + return primitive; + } + + // Look up the keys of the object. + var keys = Object.keys(value); + var visibleKeys = arrayToHash(keys); + + if (ctx.showHidden) { + keys = Object.getOwnPropertyNames(value); + } + + // IE doesn't make error fields non-enumerable + // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx + if (isError(value) + && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) { + return formatError(value); + } + + // Some type of object without properties can be shortcutted. + if (keys.length === 0) { + if (isFunction(value)) { + var name = value.name ? ': ' + value.name : ''; + return ctx.stylize('[Function' + name + ']', 'special'); + } + if (isRegExp(value)) { + return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); + } + if (isDate(value)) { + return ctx.stylize(Date.prototype.toString.call(value), 'date'); + } + if (isError(value)) { + return formatError(value); + } + } + + var base = '', array = false, braces = ['{', '}']; + + // Make Array say that they are Array + if (isArray(value)) { + array = true; + braces = ['[', ']']; + } + + // Make functions say that they are functions + if (isFunction(value)) { + var n = value.name ? ': ' + value.name : ''; + base = ' [Function' + n + ']'; + } + + // Make RegExps say that they are RegExps + if (isRegExp(value)) { + base = ' ' + RegExp.prototype.toString.call(value); + } + + // Make dates with properties first say the date + if (isDate(value)) { + base = ' ' + Date.prototype.toUTCString.call(value); + } + + // Make error with message first say the error + if (isError(value)) { + base = ' ' + formatError(value); + } + + if (keys.length === 0 && (!array || value.length == 0)) { + return braces[0] + base + braces[1]; + } + + if (recurseTimes < 0) { + if (isRegExp(value)) { + return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); + } else { + return ctx.stylize('[Object]', 'special'); + } + } + + ctx.seen.push(value); + + var output; + if (array) { + output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); + } else { + output = keys.map(function(key) { + return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); + }); + } + + ctx.seen.pop(); + + return reduceToSingleString(output, base, braces); +} + + +function formatPrimitive(ctx, value) { + if (isUndefined(value)) + return ctx.stylize('undefined', 'undefined'); + if (isString(value)) { + var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') + .replace(/'/g, "\\'") + .replace(/\\"/g, '"') + '\''; + return ctx.stylize(simple, 'string'); + } + if (isNumber(value)) + return ctx.stylize('' + value, 'number'); + if (isBoolean(value)) + return ctx.stylize('' + value, 'boolean'); + // For some reason typeof null is "object", so special case here. + if (isNull(value)) + return ctx.stylize('null', 'null'); +} + + +function formatError(value) { + return '[' + Error.prototype.toString.call(value) + ']'; +} + + +function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { + var output = []; + for (var i = 0, l = value.length; i < l; ++i) { + if (hasOwnProperty(value, String(i))) { + output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, + String(i), true)); + } else { + output.push(''); + } + } + keys.forEach(function(key) { + if (!key.match(/^\d+$/)) { + output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, + key, true)); + } + }); + return output; +} + + +function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { + var name, str, desc; + desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] }; + if (desc.get) { + if (desc.set) { + str = ctx.stylize('[Getter/Setter]', 'special'); + } else { + str = ctx.stylize('[Getter]', 'special'); + } + } else { + if (desc.set) { + str = ctx.stylize('[Setter]', 'special'); + } + } + if (!hasOwnProperty(visibleKeys, key)) { + name = '[' + key + ']'; + } + if (!str) { + if (ctx.seen.indexOf(desc.value) < 0) { + if (isNull(recurseTimes)) { + str = formatValue(ctx, desc.value, null); + } else { + str = formatValue(ctx, desc.value, recurseTimes - 1); + } + if (str.indexOf('\n') > -1) { + if (array) { + str = str.split('\n').map(function(line) { + return ' ' + line; + }).join('\n').substr(2); + } else { + str = '\n' + str.split('\n').map(function(line) { + return ' ' + line; + }).join('\n'); + } + } + } else { + str = ctx.stylize('[Circular]', 'special'); + } + } + if (isUndefined(name)) { + if (array && key.match(/^\d+$/)) { + return str; + } + name = JSON.stringify('' + key); + if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { + name = name.substr(1, name.length - 2); + name = ctx.stylize(name, 'name'); + } else { + name = name.replace(/'/g, "\\'") + .replace(/\\"/g, '"') + .replace(/(^"|"$)/g, "'"); + name = ctx.stylize(name, 'string'); + } + } + + return name + ': ' + str; +} + + +function reduceToSingleString(output, base, braces) { + var numLinesEst = 0; + var length = output.reduce(function(prev, cur) { + numLinesEst++; + if (cur.indexOf('\n') >= 0) numLinesEst++; + return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; + }, 0); + + if (length > 60) { + return braces[0] + + (base === '' ? '' : base + '\n ') + + ' ' + + output.join(',\n ') + + ' ' + + braces[1]; + } + + return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; +} + + +// NOTE: These type checking functions intentionally don't use `instanceof` +// because it is fragile and can be easily faked with `Object.create()`. +function isArray(ar) { + return Array.isArray(ar); +} +exports.isArray = isArray; + +function isBoolean(arg) { + return typeof arg === 'boolean'; +} +exports.isBoolean = isBoolean; + +function isNull(arg) { + return arg === null; +} +exports.isNull = isNull; + +function isNullOrUndefined(arg) { + return arg == null; +} +exports.isNullOrUndefined = isNullOrUndefined; + +function isNumber(arg) { + return typeof arg === 'number'; +} +exports.isNumber = isNumber; + +function isString(arg) { + return typeof arg === 'string'; +} +exports.isString = isString; + +function isSymbol(arg) { + return typeof arg === 'symbol'; +} +exports.isSymbol = isSymbol; + +function isUndefined(arg) { + return arg === void 0; +} +exports.isUndefined = isUndefined; + +function isRegExp(re) { + return isObject(re) && objectToString(re) === '[object RegExp]'; +} +exports.isRegExp = isRegExp; + +function isObject(arg) { + return typeof arg === 'object' && arg !== null; +} +exports.isObject = isObject; + +function isDate(d) { + return isObject(d) && objectToString(d) === '[object Date]'; +} +exports.isDate = isDate; + +function isError(e) { + return isObject(e) && + (objectToString(e) === '[object Error]' || e instanceof Error); +} +exports.isError = isError; + +function isFunction(arg) { + return typeof arg === 'function'; +} +exports.isFunction = isFunction; + +function isPrimitive(arg) { + return arg === null || + typeof arg === 'boolean' || + typeof arg === 'number' || + typeof arg === 'string' || + typeof arg === 'symbol' || // ES6 symbol + typeof arg === 'undefined'; +} +exports.isPrimitive = isPrimitive; + +exports.isBuffer = require('./support/isBuffer'); + +function objectToString(o) { + return Object.prototype.toString.call(o); +} + + +function pad(n) { + return n < 10 ? '0' + n.toString(10) : n.toString(10); +} + + +var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', + 'Oct', 'Nov', 'Dec']; + +// 26 Feb 16:19:34 +function timestamp() { + var d = new Date(); + var time = [pad(d.getHours()), + pad(d.getMinutes()), + pad(d.getSeconds())].join(':'); + return [d.getDate(), months[d.getMonth()], time].join(' '); +} + + +// log is just a thin wrapper to console.log that prepends a timestamp +exports.log = function() { + console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments)); +}; + + +/** + * Inherit the prototype methods from one constructor into another. + * + * The Function.prototype.inherits from lang.js rewritten as a standalone + * function (not on Function.prototype). NOTE: If this file is to be loaded + * during bootstrapping this function needs to be rewritten using some native + * functions as prototype setup using normal JavaScript does not work as + * expected during bootstrapping (see mirror.js in r114903). + * + * @param {function} ctor Constructor function which needs to inherit the + * prototype. + * @param {function} superCtor Constructor function to inherit prototype from. + */ +exports.inherits = require('inherits'); + +exports._extend = function(origin, add) { + // Don't do anything if add isn't an object + if (!add || !isObject(add)) return origin; + + var keys = Object.keys(add); + var i = keys.length; + while (i--) { + origin[keys[i]] = add[keys[i]]; + } + return origin; +}; + +function hasOwnProperty(obj, prop) { + return Object.prototype.hasOwnProperty.call(obj, prop); +} + +}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"./support/isBuffer":690,"_process":594,"inherits":689}]},{},[10]); diff --git a/dist/bundle.js b/dist/ramdaRepl.min.js similarity index 94% rename from dist/bundle.js rename to dist/ramdaRepl.min.js index 40c2d03..99340b5 100644 --- a/dist/bundle.js +++ b/dist/ramdaRepl.min.js @@ -1,9 +1,9 @@ (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o1&&arguments[1]!==undefined?arguments[1]:{};targetEl.style.display="none";targetEl.parentNode.insertBefore(_replDOM2.default,targetEl);if(!config.initialValue){config.initialValue=targetEl.value||targetEl.textContent}(0,_loadScripts2.default)(config).fork(function(err){onLoadEnd(_replDOM2.default);_replDOM2.default.querySelector(".js-error").textContent=err},function(){onLoadEnd(_replDOM2.default);bindBehaviour(_replDOM2.default,config)})}},{"./clear":1,"./dom/replDOM":4,"./googl":6,"./input-panel":7,"./load-scripts":8,"./logger":9,"./output-panel":11,"./pretty":12,"./reset":14}],14:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.default=bindResetButton;function bindResetButton(options){options.btnReset.addEventListener("click",function(){options.window.location="."})}},{}],15:[function(require,module,exports){"use strict";module.exports=function(){return/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g}},{}],16:[function(require,module,exports){"use strict";function assembleStyles(){var styles={modifiers:{reset:[0,0],bold:[1,22],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]}};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:"["+style[0]+"m",close:"["+style[1]+"m"}});Object.defineProperty(styles,groupName,{value:group,enumerable:false})});return styles}Object.defineProperty(module,"exports",{enumerable:true,get:assembleStyles})},{}],17:[function(require,module,exports){var util=require("util/");var pSlice=Array.prototype.slice;var hasOwn=Object.prototype.hasOwnProperty;var assert=module.exports=ok;assert.AssertionError=function AssertionError(options){this.name="AssertionError";this.actual=options.actual;this.expected=options.expected;this.operator=options.operator;if(options.message){this.message=options.message;this.generatedMessage=false}else{this.message=getMessage(this);this.generatedMessage=true}var stackStartFunction=options.stackStartFunction||fail;if(Error.captureStackTrace){Error.captureStackTrace(this,stackStartFunction)}else{var err=new Error;if(err.stack){var out=err.stack;var fn_name=stackStartFunction.name;var idx=out.indexOf("\n"+fn_name);if(idx>=0){var next_line=out.indexOf("\n",idx+1);out=out.substring(next_line+1)}this.stack=out}}};util.inherits(assert.AssertionError,Error);function replacer(key,value){if(util.isUndefined(value)){return""+value}if(util.isNumber(value)&&!isFinite(value)){return value.toString()}if(util.isFunction(value)||util.isRegExp(value)){return value.toString()}return value}function truncate(s,n){if(util.isString(s)){return s.length=0;i--){if(ka[i]!=kb[i])return false}for(i=ka.length-1;i>=0;i--){key=ka[i];if(!_deepEqual(a[key],b[key]))return false}return true}assert.notDeepEqual=function notDeepEqual(actual,expected,message){if(_deepEqual(actual,expected)){fail(actual,expected,message,"notDeepEqual",assert.notDeepEqual)}};assert.strictEqual=function strictEqual(actual,expected,message){if(actual!==expected){fail(actual,expected,message,"===",assert.strictEqual)}};assert.notStrictEqual=function notStrictEqual(actual,expected,message){if(actual===expected){fail(actual,expected,message,"!==",assert.notStrictEqual)}};function expectedException(actual,expected){if(!actual||!expected){return false}if(Object.prototype.toString.call(expected)=="[object RegExp]"){return expected.test(actual)}else if(actual instanceof expected){return true}else if(expected.call({},actual)===true){return true}return false}function _throws(shouldThrow,block,expected,message){var actual;if(util.isString(expected)){message=expected;expected=null}try{block()}catch(e){actual=e}message=(expected&&expected.name?" ("+expected.name+").":".")+(message?" "+message:".");if(shouldThrow&&!actual){fail(actual,expected,"Missing expected exception"+message)}if(!shouldThrow&&expectedException(actual,expected)){fail(actual,expected,"Got unwanted exception"+message)}if(shouldThrow&&actual&&expected&&!expectedException(actual,expected)||!shouldThrow&&actual){throw actual}}assert.throws=function(block,error,message){_throws.apply(this,[true].concat(pSlice.call(arguments)))};assert.doesNotThrow=function(block,message){_throws.apply(this,[false].concat(pSlice.call(arguments)))};assert.ifError=function(err){if(err){throw err}};var objectKeys=Object.keys||function(obj){var keys=[];for(var key in obj){if(hasOwn.call(obj,key))keys.push(key)}return keys}},{"util/":691}],18:[function(require,module,exports){"use strict";exports.__esModule=true;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;var maybeHighlight=function maybeHighlight(chalkFn,string){return highlighted?chalkFn(string):string};if(highlighted)rawLines=highlight(rawLines);var linesAbove=opts.linesAbove||2;var linesBelow=opts.linesBelow||3;var lines=rawLines.split(NEWLINE);var start=Math.max(lineNumber-(linesAbove+1),0);var end=Math.min(lines.length,lineNumber+linesBelow);if(!lineNumber&&!colNumber){start=0;end=lines.length}var numberMaxWidth=String(end).length;var frame=lines.slice(start,end).map(function(line,index){var number=start+1+index;var paddedNumber=(" "+number).slice(-numberMaxWidth);var gutter=" "+paddedNumber+" | ";if(number===lineNumber){var markerLine="";if(colNumber){var markerSpacing=line.slice(0,colNumber-1).replace(/[^\t]/g," ");markerLine=["\n ",maybeHighlight(defs.gutter,gutter.replace(/\d/g," ")),markerSpacing,maybeHighlight(defs.marker,"^")].join("")}return[maybeHighlight(defs.marker,">"),maybeHighlight(defs.gutter,gutter),line,markerLine].join("")}else{return" "+maybeHighlight(defs.gutter,gutter)+line}}).join("\n");if(highlighted){return _chalk2.default.reset(frame)}else{return frame}};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 _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}var defs={keyword:_chalk2.default.cyan,capitalized:_chalk2.default.yellow,jsx_tag:_chalk2.default.yellow,punctuator:_chalk2.default.yellow,number:_chalk2.default.magenta,string:_chalk2.default.green,regex:_chalk2.default.magenta,comment:_chalk2.default.grey,invalid:_chalk2.default.white.bgRed.bold,gutter:_chalk2.default.grey,marker:_chalk2.default.red.bold};var NEWLINE=/\r\n|[\n\r\u2028\u2029]/;var JSX_TAG=/^[a-z][\w-]*$/i;var BRACKET=/^[()\[\]{}]$/;function getTokenType(match){var _match$slice=match.slice(-2);var offset=_match$slice[0];var text=_match$slice[1];var token=_jsTokens2.default.matchToToken(match);if(token.type==="name"){if(_esutils2.default.keyword.isReservedWordES6(token.value)){return"keyword"}if(JSX_TAG.test(token.value)&&(text[offset-1]==="<"||text.substr(offset-2,2)=="=_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}})};var _mergeWith=require("lodash/mergeWith");var _mergeWith2=_interopRequireDefault(_mergeWith);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}module.exports=exports["default"]},{"babel-runtime/core-js/get-iterator":138,"lodash/mergeWith":568}],22:[function(require,module,exports){"use strict";exports.__esModule=true;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?")};var _babelTypes=require("babel-types");var t=_interopRequireWildcard(_babelTypes);function _interopRequireWildcard(obj){if(obj&&obj.__esModule){return obj}else{var newObj={};if(obj!=null){for(var key in obj){if(Object.prototype.hasOwnProperty.call(obj,key))newObj[key]=obj[key]}}newObj.default=obj;return newObj}}module.exports=exports["default"]},{"babel-types":193}],23:[function(require,module,exports){(function(process){"use strict";exports.__esModule=true;var _typeof2=require("babel-runtime/helpers/typeof");var _typeof3=_interopRequireDefault(_typeof2);exports.default=function(loc){var relative=arguments.length<=1||arguments[1]===undefined?process.cwd():arguments[1];if((typeof _module2.default==="undefined"?"undefined":(0,_typeof3.default)(_module2.default))==="object")return null;var relativeMod=relativeModules[relative];if(!relativeMod){relativeMod=new _module2.default;var filename=_path2.default.join(relative,".babelrc");relativeMod.id=filename;relativeMod.filename=filename;relativeMod.paths=_module2.default._nodeModulePaths(relative);relativeModules[relative]=relativeMod}try{return _module2.default._resolveFilename(loc,relativeMod)}catch(err){return null}};var _module=require("module");var _module2=_interopRequireDefault(_module);var _path=require("path");var _path2=_interopRequireDefault(_path);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}var relativeModules={};module.exports=exports["default"]}).call(this,require("_process"))},{_process:594,"babel-runtime/helpers/typeof":155,module:220,path:589}],24:[function(require,module,exports){"use strict";exports.__esModule=true;var _map=require("babel-runtime/core-js/map");var _map2=_interopRequireDefault(_map);var _classCallCheck2=require("babel-runtime/helpers/classCallCheck");var _classCallCheck3=_interopRequireDefault(_classCallCheck2);var _possibleConstructorReturn2=require("babel-runtime/helpers/possibleConstructorReturn");var _possibleConstructorReturn3=_interopRequireDefault(_possibleConstructorReturn2);var _inherits2=require("babel-runtime/helpers/inherits");var _inherits3=_interopRequireDefault(_inherits2);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}var Store=function(_Map){ (0,_inherits3.default)(Store,_Map);function Store(){(0,_classCallCheck3.default)(this,Store);var _this=(0,_possibleConstructorReturn3.default)(this,_Map.call(this));_this.dynamicData={};return _this}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.default);exports.default=Store;module.exports=exports["default"]},{"babel-runtime/core-js/map":140,"babel-runtime/helpers/classCallCheck":152,"babel-runtime/helpers/inherits":153,"babel-runtime/helpers/possibleConstructorReturn":154}],25:[function(require,module,exports){"use strict";exports.__esModule=true;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=void 0;var build={global:buildGlobal,umd:buildUmd,var:buildVar}[outputType];if(build){tree=build(namespace,builder)}else{throw new Error(messages.get("unsupportedOutputType",outputType))}return(0,_babelGenerator2.default)(tree).code};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 _each=require("lodash/each");var _each2=_interopRequireDefault(_each);var _babelTypes=require("babel-types");var t=_interopRequireWildcard(_babelTypes);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function _interopRequireWildcard(obj){if(obj&&obj.__esModule){return obj}else{var newObj={};if(obj!=null){for(var key in obj){if(Object.prototype.hasOwnProperty.call(obj,key))newObj[key]=obj[key]}}newObj.default=obj;return newObj}}var buildUmdWrapper=(0,_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){(0,_each2.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))))})}module.exports=exports["default"]},{"babel-generator":53,"babel-helpers":75,"babel-messages":76,"babel-template":156,"babel-types":193,"lodash/each":533}],26:[function(require,module,exports){(function(process){"use strict";exports.__esModule=true;exports.File=undefined;var _typeof2=require("babel-runtime/helpers/typeof");var _typeof3=_interopRequireDefault(_typeof2);var _getIterator2=require("babel-runtime/core-js/get-iterator");var _getIterator3=_interopRequireDefault(_getIterator2);var _create=require("babel-runtime/core-js/object/create");var _create2=_interopRequireDefault(_create);var _assign=require("babel-runtime/core-js/object/assign");var _assign2=_interopRequireDefault(_assign);var _classCallCheck2=require("babel-runtime/helpers/classCallCheck");var _classCallCheck3=_interopRequireDefault(_classCallCheck2);var _possibleConstructorReturn2=require("babel-runtime/helpers/possibleConstructorReturn");var _possibleConstructorReturn3=_interopRequireDefault(_possibleConstructorReturn2);var _inherits2=require("babel-runtime/helpers/inherits");var _inherits3=_interopRequireDefault(_inherits2);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 _optionManager=require("./options/option-manager");var _optionManager2=_interopRequireDefault(_optionManager);var _pluginPass=require("../plugin-pass");var _pluginPass2=_interopRequireDefault(_pluginPass);var _shebangRegex=require("shebang-regex");var _shebangRegex2=_interopRequireDefault(_shebangRegex);var _babelTraverse=require("babel-traverse");var _babelTraverse2=_interopRequireDefault(_babelTraverse);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 _defaults=require("lodash/defaults");var _defaults2=_interopRequireDefault(_defaults);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 _resolve=require("../../helpers/resolve");var _resolve2=_interopRequireDefault(_resolve);var _blockHoist=require("../internal-plugins/block-hoist");var _blockHoist2=_interopRequireDefault(_blockHoist);var _shadowFunctions=require("../internal-plugins/shadow-functions");var _shadowFunctions2=_interopRequireDefault(_shadowFunctions);function _interopRequireWildcard(obj){if(obj&&obj.__esModule){return obj}else{var newObj={};if(obj!=null){for(var key in obj){if(Object.prototype.hasOwnProperty.call(obj,key))newObj[key]=obj[key]}}newObj.default=obj;return newObj}}function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}var INTERNAL_PLUGINS=[[_blockHoist2.default],[_shadowFunctions2.default]];var errorVisitor={enter:function enter(path,state){var loc=path.node.loc;if(loc){state.loc=loc;path.stop()}}};var File=function(_Store){(0,_inherits3.default)(File,_Store);function File(){var opts=arguments.length<=0||arguments[0]===undefined?{}:arguments[0];var pipeline=arguments[1];(0,_classCallCheck3.default)(this,File);var _this=(0,_possibleConstructorReturn3.default)(this,_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,sourceFileName:_this.opts.filename,plugins:[]};_this.pluginVisitors=[];_this.pluginPasses=[];_this.buildPluginsForOptions(_this.opts);if(_this.opts.passPerPreset){_this.perPresetOpts=[];_this.opts.presets.forEach(function(presetOpts){var perPresetOpts=(0,_assign2.default)((0,_create2.default)(_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);return _this}File.prototype.getMetadata=function getMetadata(){var has=false;for(var _iterator=this.ast.program.body,_isArray=Array.isArray(_iterator),_i=0,_iterator=_isArray?_iterator:(0,_getIterator3.default)(_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 node=_ref;if(t.isModuleDeclaration(node)){has=true;break}}if(has){this.path.traverse(metadataVisitor,this)}};File.prototype.initOptions=function initOptions(opts){opts=new _optionManager2.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);(0,_defaults2.default)(opts,{moduleRoot:opts.sourceRoot});(0,_defaults2.default)(opts,{sourceRoot:opts.moduleRoot});(0,_defaults2.default)(opts,{filenameRelative:opts.filename});var basenameRelative=_path2.default.basename(opts.filenameRelative);(0,_defaults2.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=[];for(var _iterator2=plugins,_isArray2=Array.isArray(_iterator2),_i2=0,_iterator2=_isArray2?_iterator2:(0,_getIterator3.default)(_iterator2);;){var _ref2;if(_isArray2){if(_i2>=_iterator2.length)break;_ref2=_iterator2[_i2++]}else{_i2=_iterator2.next();if(_i2.done)break;_ref2=_i2.value}var ref=_ref2;var plugin=ref[0];var pluginOpts=ref[1];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}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){var sourceRootRegEx=new RegExp("^"+opts.sourceRoot+"/?");filenameRelative=filenameRelative.replace(sourceRootRegEx,"")}filenameRelative=filenameRelative.replace(/\.(\w*?)$/,"");moduleName+=filenameRelative;moduleName=moduleName.replace(/\\/g,"/");if(opts.getModuleId){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];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};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=(0,_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){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});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{(0,_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});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:mapping.source==null?null:{line:mapping.originalLine,column:mapping.originalColumn},generated:generatedPosition})}});var mergedMap=mergedGenerator.toJSON();inputMap.mappings=mergedMap.mappings;return{v:inputMap}}();if((typeof _ret==="undefined"?"undefined":(0,_typeof3.default)(_ret))==="object")return _ret.v}else{return map}};File.prototype.parse=function parse(code){var parseCode=_babylon.parse;var parserOpts=this.opts.parserOpts;if(parserOpts){parserOpts=(0,_assign2.default)({},this.parserOpts,parserOpts);if(parserOpts.parser){if(typeof parserOpts.parser==="string"){var dirname=_path2.default.dirname(this.opts.filename)||process.cwd();var parser=(0,_resolve2.default)(parserOpts.parser,dirname);if(parser){parseCode=require(parser).parse}else{throw new Error("Couldn't find parser "+parserOpts.parser+' with "parse" method relative to directory '+dirname)}}else{parseCode=parserOpts.parser}parserOpts.parser={parse:function parse(source){return(0,_babylon.parse)(source,parserOpts)}}}}this.log.debug("Parse start");var ast=parseCode(code,parserOpts||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(){for(var i=0;i=_iterator3.length)break;_ref3=_iterator3[_i3++]}else{_i3=_iterator3.next();if(_i3.done)break;_ref3=_i3.value}var pass=_ref3;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(_ref4){var code=_ref4.code;var map=_ref4.map;var ast=_ref4.ast;var ignored=_ref4.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);var gen=_babelGenerator2.default;if(opts.generatorOpts.generator){gen=opts.generatorOpts.generator;if(typeof gen==="string"){var dirname=_path2.default.dirname(this.opts.filename)||process.cwd();var generator=(0,_resolve2.default)(gen,dirname);if(generator){gen=require(generator).print}else{throw new Error("Couldn't find generator "+gen+' with "print" method relative to directory '+dirname)}}}this.log.debug("Generation start");var _result=gen(ast,opts.generatorOpts?(0,_assign2.default)(opts,opts.generatorOpts):opts,this.code);result.code=_result.code;result.map=_result.map;this.log.debug("Generation end");if(this.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}).call(this,require("_process"))},{"../../helpers/resolve":23,"../../store":24,"../../util":40,"../internal-plugins/block-hoist":35,"../internal-plugins/shadow-functions":36,"../plugin-pass":38,"./logger":27,"./metadata":28,"./options/option-manager":32,_process:594,"babel-code-frame":18,"babel-generator":53,"babel-helpers":75,"babel-runtime/core-js/get-iterator":138,"babel-runtime/core-js/object/assign":142,"babel-runtime/core-js/object/create":143,"babel-runtime/helpers/classCallCheck":152,"babel-runtime/helpers/inherits":153,"babel-runtime/helpers/possibleConstructorReturn":154,"babel-runtime/helpers/typeof":155,"babel-traverse":160,"babel-types":193,babylon:197,"convert-source-map":231,"lodash/defaults":532,path:589,"shebang-regex":672,"source-map":684}],27:[function(require,module,exports){"use strict";exports.__esModule=true;var _classCallCheck2=require("babel-runtime/helpers/classCallCheck");var _classCallCheck3=_interopRequireDefault(_classCallCheck2);var _node=require("debug/node");var _node2=_interopRequireDefault(_node);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}var verboseDebug=(0,_node2.default)("babel:verbose");var generalDebug=(0,_node2.default)("babel");var seenDeprecatedMessages=[];var Logger=function(){function Logger(file,filename){(0,_classCallCheck3.default)(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);if(seenDeprecatedMessages.indexOf(msg)>=0)return;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"]},{"babel-runtime/helpers/classCallCheck":152,"debug/node":342}],28:[function(require,module,exports){"use strict";exports.__esModule=true;exports.ImportDeclaration=exports.ModuleDeclaration=undefined;var _getIterator2=require("babel-runtime/core-js/get-iterator");var _getIterator3=_interopRequireDefault(_getIterator2);exports.ExportDeclaration=ExportDeclaration;exports.Scope=Scope;var _babelTypes=require("babel-types");var t=_interopRequireWildcard(_babelTypes);function _interopRequireWildcard(obj){if(obj&&obj.__esModule){return obj}else{var newObj={};if(obj!=null){for(var key in obj){if(Object.prototype.hasOwnProperty.call(obj,key))newObj[key]=obj[key]}}newObj.default=obj;return newObj}}function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}var ModuleDeclaration=exports.ModuleDeclaration={enter:function enter(path,file){var node=path.node;if(node.source){node.source.value=file.resolveModuleSource(node.source.value)}}};var ImportDeclaration=exports.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});for(var _iterator=path.get("specifiers"),_isArray=Array.isArray(_iterator),_i=0,_iterator=_isArray?_iterator:(0,_getIterator3.default)(_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 specifier=_ref;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})}}}};function ExportDeclaration(path,file){var node=path.node;var source=node.source?node.source.value:null;var exports=file.metadata.modules.exports;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){for(var _iterator2=node.specifiers,_isArray2=Array.isArray(_iterator2),_i2=0,_iterator2=_isArray2?_iterator2:(0,_getIterator3.default)(_iterator2);;){var _ref2;if(_isArray2){if(_i2>=_iterator2.length)break;_ref2=_iterator2[_i2++]}else{_i2=_iterator2.next();if(_i2.done)break;_ref2=_i2.value}var specifier=_ref2;var exported=specifier.exported.name;exports.exported.push(exported);if(t.isExportDefaultSpecifier(specifier)){exports.specifiers.push({kind:"external",local:exported,exported:exported,source:source})}if(t.isExportNamespaceSpecifier(specifier)){exports.specifiers.push({kind:"external-namespace",exported:exported,source:source})}var local=specifier.local;if(!local)continue;if(source){exports.specifiers.push({kind:"external",local:local.name,exported:exported,source:source})}if(!source){exports.specifiers.push({kind:"local",local:local.name,exported:exported})}}}if(path.isExportAllDeclaration()){exports.specifiers.push({kind:"external-all",source:source})}}function Scope(path){path.skip()}},{"babel-runtime/core-js/get-iterator":138,"babel-types":193}],29:[function(require,module,exports){(function(process){"use strict";exports.__esModule=true;var _assign=require("babel-runtime/core-js/object/assign");var _assign2=_interopRequireDefault(_assign);var _classCallCheck2=require("babel-runtime/helpers/classCallCheck");var _classCallCheck3=_interopRequireDefault(_classCallCheck2);exports.default=buildConfigChain;var _resolve=require("../../../helpers/resolve");var _resolve2=_interopRequireDefault(_resolve);var _json=require("json5");var _json2=_interopRequireDefault(_json);var _pathIsAbsolute=require("path-is-absolute");var _pathIsAbsolute2=_interopRequireDefault(_pathIsAbsolute);var _pathExists=require("path-exists");var _pathExists2=_interopRequireDefault(_pathExists);var _path=require("path");var _path2=_interopRequireDefault(_path);var _fs=require("fs");var _fs2=_interopRequireDefault(_fs);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}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}}function buildConfigChain(){var opts=arguments.length<=0||arguments[0]===undefined?{}:arguments[0];var log=arguments[1];var filename=opts.filename;var builder=new ConfigChainBuilder(log);if(opts.babelrc!==false){builder.findConfigs(filename)}builder.mergeConfig({options:opts,alias:"base",dirname:filename&&_path2.default.dirname(filename)});return builder.configs}var ConfigChainBuilder=function(){function ConfigChainBuilder(log){(0,_classCallCheck3.default)(this,ConfigChainBuilder);this.resolvedConfigs=[];this.configs=[];this.log=log}ConfigChainBuilder.prototype.findConfigs=function findConfigs(loc){if(!loc)return;if(!(0,_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}};ConfigChainBuilder.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});if(lines.length){this.mergeConfig({options:{ignore:lines},alias:loc,dirname:_path2.default.dirname(loc)})}};ConfigChainBuilder.prototype.addConfig=function addConfig(loc,key){var json=arguments.length<=2||arguments[2]===undefined?_json2.default:arguments[2];if(this.resolvedConfigs.indexOf(loc)>=0){return false}this.resolvedConfigs.push(loc);var content=_fs2.default.readFileSync(loc,"utf8");var options=void 0;try{options=jsonCache[content]=jsonCache[content]||json.parse(content);if(key)options=options[key]}catch(err){err.message=loc+": Error while parsing JSON - "+err.message;throw err}this.mergeConfig({options:options,alias:loc,dirname:_path2.default.dirname(loc)});return!!options};ConfigChainBuilder.prototype.mergeConfig=function mergeConfig(_ref){var options=_ref.options;var alias=_ref.alias;var loc=_ref.loc;var dirname=_ref.dirname;if(!options){return false}options=(0,_assign2.default)({},options);dirname=dirname||process.cwd();loc=loc||alias;if(options.extends){var extendsLoc=(0,_resolve2.default)(options.extends,dirname);if(extendsLoc){this.addConfig(extendsLoc)}else{if(this.log)this.log.error("Couldn't resolve extends clause of "+options.extends+" in "+alias)}delete options.extends}this.configs.push({options:options,alias:alias,loc:loc,dirname:dirname});var envOpts=void 0;var envKey=process.env.BABEL_ENV||process.env.NODE_ENV||"development";if(options.env){envOpts=options.env[envKey];delete options.env}this.mergeConfig({options:envOpts,alias:alias+".env."+envKey,dirname:dirname})};return ConfigChainBuilder}();module.exports=exports["default"]}).call(this,require("_process"))},{"../../../helpers/resolve":23,_process:594,"babel-runtime/core-js/object/assign":142,"babel-runtime/helpers/classCallCheck":152,fs:220,json5:358,path:589,"path-exists":590,"path-is-absolute":591}],30:[function(require,module,exports){"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"},wrapPluginVisitorMethod:{hidden:true,description:"optional callback to wrap all visitor methods"},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},parserOpts:{description:"Options to pass into the parser, or to change parsers (parserOpts.parser)",default:false},generatorOpts:{description:"Options to pass into the generator, or to change generators (generatorOpts.generator)",default:false}}},{}],31:[function(require,module,exports){"use strict";exports.__esModule=true;exports.config=undefined;exports.normaliseOptions=normaliseOptions;var _parsers=require("./parsers");var parsers=_interopRequireWildcard(_parsers);var _config=require("./config");var _config2=_interopRequireDefault(_config);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function _interopRequireWildcard(obj){if(obj&&obj.__esModule){return obj}else{var newObj={};if(obj!=null){for(var key in obj){if(Object.prototype.hasOwnProperty.call(obj,key))newObj[key]=obj[key]}}newObj.default=obj;return newObj}}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}},{"./config":30,"./parsers":33}],32:[function(require,module,exports){(function(process){"use strict";exports.__esModule=true;var _stringify=require("babel-runtime/core-js/json/stringify");var _stringify2=_interopRequireDefault(_stringify);var _assign=require("babel-runtime/core-js/object/assign");var _assign2=_interopRequireDefault(_assign);var _getIterator2=require("babel-runtime/core-js/get-iterator");var _getIterator3=_interopRequireDefault(_getIterator2);var _typeof2=require("babel-runtime/helpers/typeof");var _typeof3=_interopRequireDefault(_typeof2);var _classCallCheck2=require("babel-runtime/helpers/classCallCheck");var _classCallCheck3=_interopRequireDefault(_classCallCheck2);var _node=require("../../../api/node");var context=_interopRequireWildcard(_node);var _plugin2=require("../../plugin");var _plugin3=_interopRequireDefault(_plugin2);var _babelMessages=require("babel-messages");var messages=_interopRequireWildcard(_babelMessages);var _index=require("./index");var _resolve=require("../../../helpers/resolve");var _resolve2=_interopRequireDefault(_resolve);var _cloneDeepWith=require("lodash/cloneDeepWith");var _cloneDeepWith2=_interopRequireDefault(_cloneDeepWith);var _clone=require("lodash/clone");var _clone2=_interopRequireDefault(_clone);var _merge=require("../../../helpers/merge");var _merge2=_interopRequireDefault(_merge);var _config2=require("./config");var _config3=_interopRequireDefault(_config2);var _removed=require("./removed");var _removed2=_interopRequireDefault(_removed);var _buildConfigChain=require("./build-config-chain");var _buildConfigChain2=_interopRequireDefault(_buildConfigChain);var _path=require("path");var _path2=_interopRequireDefault(_path);function _interopRequireWildcard(obj){if(obj&&obj.__esModule){return obj}else{var newObj={};if(obj!=null){for(var key in obj){if(Object.prototype.hasOwnProperty.call(obj,key))newObj[key]=obj[key]}}newObj.default=obj;return newObj}}function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}var OptionManager=function(){function OptionManager(log){(0,_classCallCheck3.default)(this,OptionManager);this.resolvedConfigs=[];this.options=OptionManager.createBareOptions();this.log=log}OptionManager.memoisePluginContainer=function memoisePluginContainer(fn,loc,i,alias){for(var _iterator=OptionManager.memoisedPlugins,_isArray=Array.isArray(_iterator),_i=0,_iterator=_isArray?_iterator:(0,_getIterator3.default)(_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 cache=_ref;if(cache.container===fn)return cache.plugin}var obj=void 0;if(typeof fn==="function"){obj=fn(context)}else{obj=fn}if((typeof obj==="undefined"?"undefined":(0,_typeof3.default)(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==="undefined"?"undefined":(0,_typeof3.default)(obj))+loc+i)}};OptionManager.createBareOptions=function createBareOptions(){var opts={};for(var _key in _config3.default){var opt=_config3.default[_key];opts[_key]=(0,_clone2.default)(opt.default)}return opts};OptionManager.normalisePlugin=function normalisePlugin(plugin,loc,i,alias){plugin=plugin.__esModule?plugin.default:plugin;if(!(plugin instanceof _plugin3.default)){if(typeof plugin==="function"||(typeof plugin==="undefined"?"undefined":(0,_typeof3.default)(plugin))==="object"){plugin=OptionManager.memoisePluginContainer(plugin,loc,i,alias)}else{throw new TypeError(messages.get("pluginNotFunction",loc,i,typeof plugin==="undefined"?"undefined":(0,_typeof3.default)(plugin)))}}plugin.init(loc,i);return plugin};OptionManager.normalisePlugins=function normalisePlugins(loc,dirname,plugins){return plugins.map(function(val,i){var plugin=void 0,options=void 0;if(!val){throw new TypeError("Falsy value found in plugins")}if(Array.isArray(val)){plugin=val[0];options=val[1]}else{plugin=val}var alias=typeof plugin==="string"?plugin:loc+"$"+i;if(typeof plugin==="string"){var pluginLoc=(0,_resolve2.default)("babel-plugin-"+plugin,dirname)||(0,_resolve2.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.mergeOptions=function mergeOptions(_ref2){var _this=this;var rawOpts=_ref2.options;var extendingOpts=_ref2.extending;var alias=_ref2.alias;var loc=_ref2.loc;var dirname=_ref2.dirname;alias=alias||"foreign";if(!rawOpts)return;if((typeof rawOpts==="undefined"?"undefined":(0,_typeof3.default)(rawOpts))!=="object"||Array.isArray(rawOpts)){this.log.error("Invalid options type for "+alias,TypeError)}var opts=(0,_cloneDeepWith2.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=_config3.default[_key2];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)}}}(0,_index.normaliseOptions)(opts);if(opts.plugins){opts.plugins=OptionManager.normalisePlugins(loc,dirname,opts.plugins)}if(opts.presets){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{this.mergePresets(opts.presets,dirname);delete opts.presets}}if(rawOpts===extendingOpts){(0,_assign2.default)(extendingOpts,opts)}else{(0,_merge2.default)(extendingOpts||this.options,opts)}};OptionManager.prototype.mergePresets=function mergePresets(presets,dirname){var _this2=this;this.resolvePresets(presets,dirname,function(presetOpts,presetLoc){_this2.mergeOptions({options:presetOpts,alias:presetLoc,loc:presetLoc,dirname:_path2.default.dirname(presetLoc||"")})})};OptionManager.prototype.resolvePresets=function resolvePresets(presets,dirname,onResolve){return presets.map(function(val){var options=void 0;if(Array.isArray(val)){if(val.length>2){throw new Error("Unexpected extra options "+(0,_stringify2.default)(val.slice(2))+" passed to preset.")}var _val=val;val=_val[0];options=_val[1]}var presetLoc=void 0;try{if(typeof val==="string"){presetLoc=(0,_resolve2.default)("babel-preset-"+val,dirname)||(0,_resolve2.default)(val,dirname);if(!presetLoc){var matches=val.match(/^(@[^\/]+)\/(.+)$/);if(matches){var orgName=matches[1];var presetPath=matches[2];val=orgName+"/babel-preset-"+presetPath;presetLoc=(0,_resolve2.default)(val,dirname)}}if(!presetLoc){throw new Error("Couldn't find preset "+(0,_stringify2.default)(val)+" relative to directory "+(0,_stringify2.default)(dirname))}val=require(presetLoc)}if((typeof val==="undefined"?"undefined":(0,_typeof3.default)(val))==="object"&&val.__esModule)val=val.default;if((typeof val==="undefined"?"undefined":(0,_typeof3.default)(val))==="object"&&val.buildPreset)val=val.buildPreset;if(typeof val!=="function"&&options!==undefined){throw new Error("Options "+(0,_stringify2.default)(options)+" passed to "+(presetLoc||"a preset")+" which does not accept options.")}if(typeof val==="function")val=val(context,options);if((typeof val==="undefined"?"undefined":(0,_typeof3.default)(val))!=="object"){throw new Error("Unsupported preset format: "+val+".")}onResolve&&onResolve(val,presetLoc)}catch(e){if(presetLoc){e.message+=" (While processing preset: "+(0,_stringify2.default)(presetLoc)+")"}throw e}return val})};OptionManager.prototype.normaliseOptions=function normaliseOptions(){var opts=this.options;for(var _key3 in _config3.default){var option=_config3.default[_key3];var val=opts[_key3];if(!val&&option.optional)continue;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];for(var _iterator2=(0,_buildConfigChain2.default)(opts,this.log),_isArray2=Array.isArray(_iterator2),_i2=0,_iterator2=_isArray2?_iterator2:(0,_getIterator3.default)(_iterator2);;){var _ref3;if(_isArray2){if(_i2>=_iterator2.length)break;_ref3=_iterator2[_i2++]}else{_i2=_iterator2.next();if(_i2.done)break;_ref3=_i2.value}var _config=_ref3;this.mergeOptions(_config)}this.normaliseOptions(opts);return this.options};return OptionManager}();exports.default=OptionManager;OptionManager.memoisedPlugins=[];module.exports=exports["default"]}).call(this,require("_process"))},{"../../../api/node":20,"../../../helpers/merge":21,"../../../helpers/resolve":23,"../../plugin":39,"./build-config-chain":29,"./config":30,"./index":31,"./removed":34,_process:594,"babel-messages":76,"babel-runtime/core-js/get-iterator":138,"babel-runtime/core-js/json/stringify":139,"babel-runtime/core-js/object/assign":142,"babel-runtime/helpers/classCallCheck":152,"babel-runtime/helpers/typeof":155,"lodash/clone":527,"lodash/cloneDeepWith":529,path:589}],33:[function(require,module,exports){"use strict";exports.__esModule=true;exports.filename=undefined;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);function _interopRequireWildcard(obj){if(obj&&obj.__esModule){return obj}else{var newObj={};if(obj!=null){for(var key in obj){if(Object.prototype.hasOwnProperty.call(obj,key))newObj[key]=obj[key]}}newObj.default=obj;return newObj}}function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}var filename=exports.filename=_slash2.default;function boolean(val){return!!val}function booleanString(val){return util.booleanify(val)}function list(val){return util.list(val)}},{"../../../util":40,slash:673}],34:[function(require,module,exports){"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/"},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"}}},{}],35:[function(require,module,exports){"use strict";exports.__esModule=true;var _plugin=require("../plugin");var _plugin2=_interopRequireDefault(_plugin);var _sortBy=require("lodash/sortBy");var _sortBy2=_interopRequireDefault(_sortBy);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}exports.default=new _plugin2.default({name:"internal.blockHoist",visitor:{Block:{exit:function exit(_ref){var node=_ref.node;var hasChange=false;for(var i=0;i=_iterator.length)break;_ref=_iterator[_i++]}else{_i=_iterator.next();if(_i.done)break;_ref=_i.value}var fn=_ref;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=_optionManager2.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])};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 _iterator2=GLOBAL_VISITOR_PROPS,_isArray2=Array.isArray(_iterator2),_i2=0,_iterator2=_isArray2?_iterator2:(0,_getIterator3.default)(_iterator2);;){var _ref2;if(_isArray2){if(_i2>=_iterator2.length)break;_ref2=_iterator2[_i2++]}else{_i2=_iterator2.next();if(_i2.done)break;_ref2=_i2.value}var key=_ref2;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"]},{"../store":24,"./file/options/option-manager":32,"babel-messages":76,"babel-runtime/core-js/get-iterator":138,"babel-runtime/helpers/classCallCheck":152,"babel-runtime/helpers/inherits":153,"babel-runtime/helpers/possibleConstructorReturn":154,"babel-traverse":160,"lodash/assign":524,"lodash/clone":527}],40:[function(require,module,exports){"use strict";exports.__esModule=true;exports.inspect=exports.inherits=undefined;var _getIterator2=require("babel-runtime/core-js/get-iterator");var _getIterator3=_interopRequireDefault(_getIterator2);var _util=require("util");Object.defineProperty(exports,"inherits",{enumerable:true,get:function get(){return _util.inherits}});Object.defineProperty(exports,"inspect",{enumerable:true,get:function get(){return _util.inspect}});exports.canCompile=canCompile;exports.list=list;exports.regexify=regexify;exports.arrayify=arrayify;exports.booleanify=booleanify;exports.shouldIgnore=shouldIgnore;var _escapeRegExp=require("lodash/escapeRegExp");var _escapeRegExp2=_interopRequireDefault(_escapeRegExp);var _startsWith=require("lodash/startsWith");var _startsWith2=_interopRequireDefault(_startsWith);var _isBoolean=require("lodash/isBoolean");var _isBoolean2=_interopRequireDefault(_isBoolean);var _minimatch=require("minimatch");var _minimatch2=_interopRequireDefault(_minimatch);var _includes=require("lodash/includes");var _includes2=_interopRequireDefault(_includes);var _isString=require("lodash/isString");var _isString2=_interopRequireDefault(_isString);var _isRegExp=require("lodash/isRegExp");var _isRegExp2=_interopRequireDefault(_isRegExp);var _path=require("path");var _path2=_interopRequireDefault(_path);var _slash=require("slash");var _slash2=_interopRequireDefault(_slash);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function canCompile(filename,altExts){var exts=altExts||canCompile.EXTENSIONS;var ext=_path2.default.extname(filename);return(0,_includes2.default)(exts,ext)}canCompile.EXTENSIONS=[".js",".jsx",".es6",".es"];function list(val){if(!val){return[]}else if(Array.isArray(val)){return val}else if(typeof val==="string"){return val.split(",")}else{return[val]}}function regexify(val){if(!val){return new RegExp(/.^/)}if(Array.isArray(val)){val=new RegExp(val.map(_escapeRegExp2.default).join("|"),"i")}if(typeof val==="string"){val=(0,_slash2.default)(val);if((0,_startsWith2.default)(val,"./")||(0,_startsWith2.default)(val,"*/"))val=val.slice(2);if((0,_startsWith2.default)(val,"**/"))val=val.slice(3);var regex=_minimatch2.default.makeRe(val,{nocase:true});return new RegExp(regex.source.slice(1,-1),"i")}if((0,_isRegExp2.default)(val)){return val}throw new TypeError("illegal type for regexify")}function arrayify(val,mapFn){if(!val)return[];if((0,_isBoolean2.default)(val))return arrayify([val],mapFn);if((0,_isString2.default)(val))return arrayify(list(val),mapFn);if(Array.isArray(val)){if(mapFn)val=val.map(mapFn);return val}return[val]}function booleanify(val){if(val==="true"||val==1){return true}if(val==="false"||val==0||!val){return false}return val}function shouldIgnore(filename){var ignore=arguments.length<=1||arguments[1]===undefined?[]:arguments[1];var only=arguments[2];filename=(0,_slash2.default)(filename);if(only){for(var _iterator=only,_isArray=Array.isArray(_iterator),_i=0,_iterator=_isArray?_iterator:(0,_getIterator3.default)(_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 pattern=_ref;if(_shouldIgnore(pattern,filename))return false}return true}else if(ignore.length){for(var _iterator2=ignore,_isArray2=Array.isArray(_iterator2),_i2=0,_iterator2=_isArray2?_iterator2:(0,_getIterator3.default)(_iterator2);;){var _ref2;if(_isArray2){if(_i2>=_iterator2.length)break;_ref2=_iterator2[_i2++]}else{_i2=_iterator2.next();if(_i2.done)break;_ref2=_i2.value}var _pattern=_ref2;if(_shouldIgnore(_pattern,filename))return true}}return false}function _shouldIgnore(pattern,filename){if(typeof pattern==="function"){return pattern(filename)}else{return pattern.test(filename)}}},{"babel-runtime/core-js/get-iterator":138,"lodash/escapeRegExp":535,"lodash/includes":546,"lodash/isBoolean":551,"lodash/isRegExp":560,"lodash/isString":561,"lodash/startsWith":575,minimatch:586,path:589,slash:673,util:691}],41:[function(require,module,exports){module.exports={_args:[["babel-core@6.16.0","/home/decoy/dev/ramda-repl"]],_from:"babel-core@6.16.0",_id:"babel-core@6.16.0",_inCache:true,_installable:true,_location:"/babel-core",_nodeVersion:"5.11.1",_npmOperationalInternal:{host:"packages-16-east.internal.npmjs.com",tmp:"tmp/babel-core-6.16.0.tgz_1475091527641_0.820686154300347"},_npmUser:{email:"hi@henryzoo.com",name:"hzoo"},_npmVersion:"3.10.8",_phantomChildren:{},_requested:{name:"babel-core",raw:"babel-core@6.16.0",rawSpec:"6.16.0",scope:null,spec:"6.16.0",type:"version"},_requiredBy:["/","/babel-register","/babelify","/systemjs-builder"],_resolved:"https://registry.npmjs.org/babel-core/-/babel-core-6.16.0.tgz",_shasum:"cf8bbfdf0097c4146195d80d9ec96d73acf387d5",_shrinkwrap:null,_spec:"babel-core@6.16.0",_where:"/home/decoy/dev/ramda-repl",author:{email:"sebmck@gmail.com",name:"Sebastian McKenzie"},dependencies:{"babel-code-frame":"^6.16.0","babel-generator":"^6.16.0","babel-helpers":"^6.16.0","babel-messages":"^6.8.0","babel-register":"^6.16.0","babel-runtime":"^6.9.1","babel-template":"^6.16.0","babel-traverse":"^6.16.0","babel-types":"^6.16.0",babylon:"^6.11.0","convert-source-map":"^1.1.0",debug:"^2.1.1",json5:"^0.4.0",lodash:"^4.2.0",minimatch:"^3.0.2","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.9.0","babel-helper-transform-fixture-test-runner":"^6.16.0","babel-polyfill":"^6.16.0"},directories:{},dist:{shasum:"cf8bbfdf0097c4146195d80d9ec96d73acf387d5",tarball:"https://registry.npmjs.org/babel-core/-/babel-core-6.16.0.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.16.0"}},{}],42:[function(require,module,exports){"use strict";exports.__esModule=true;var _classCallCheck2=require("babel-runtime/helpers/classCallCheck");var _classCallCheck3=_interopRequireDefault(_classCallCheck2);var _trimEnd=require("lodash/trimEnd");var _trimEnd2=_interopRequireDefault(_trimEnd);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}var SPACES_RE=/^[ \t]+$/;var Buffer=function(){function Buffer(map){(0,_classCallCheck3.default)(this,Buffer);this._map=null;this._buf=[];this._last="";this._queue=[];this._position={line:1,column:0};this._sourcePosition={identifierName:null,line:null,column:null,filename:null};this._map=map}Buffer.prototype.get=function get(){this._flush();return{code:(0,_trimEnd2.default)(this._buf.join("")),map:this._map?this._map.get():null}};Buffer.prototype.append=function append(str){this._flush();var _sourcePosition=this._sourcePosition;var line=_sourcePosition.line;var column=_sourcePosition.column;var filename=_sourcePosition.filename;var identifierName=_sourcePosition.identifierName;this._append(str,line,column,identifierName,filename)};Buffer.prototype.queue=function queue(str){if(str==="\n")while(this._queue.length>0&&SPACES_RE.test(this._queue[0][0])){this._queue.shift()}var _sourcePosition2=this._sourcePosition;var line=_sourcePosition2.line;var column=_sourcePosition2.column;var filename=_sourcePosition2.filename;var identifierName=_sourcePosition2.identifierName;this._queue.unshift([str,line,column,identifierName,filename])};Buffer.prototype._flush=function _flush(){var item=void 0;while(item=this._queue.pop()){this._append.apply(this,item)}};Buffer.prototype._append=function _append(str,line,column,identifierName,filename){if(this._map&&str[0]!=="\n"){this._map.mark(this._position.line,this._position.column,line,column,identifierName,filename)}this._buf.push(str);this._last=str[str.length-1];for(var i=0;i0&&this._queue[0][0]==="\n")this._queue.shift()};Buffer.prototype.removeLastSemicolon=function removeLastSemicolon(){if(this._queue.length>0&&this._queue[0][0]===";")this._queue.shift()};Buffer.prototype.endsWith=function endsWith(suffix){if(suffix.length===1){var last=void 0;if(this._queue.length>0){var str=this._queue[0][0];last=str[str.length-1]}else{last=this._last}return last===suffix}var end=this._last+this._queue.reduce(function(acc,item){return item[0]+acc},"");if(suffix.length<=end.length){return end.slice(-suffix.length)===suffix}return false};Buffer.prototype.hasContent=function hasContent(){return this._queue.length>0||!!this._last};Buffer.prototype.source=function source(prop,loc){if(prop&&!loc)return;var pos=loc?loc[prop]:null;this._sourcePosition.identifierName=loc&&loc.identifierName||null;this._sourcePosition.line=pos?pos.line:null;this._sourcePosition.column=pos?pos.column:null;this._sourcePosition.filename=loc&&loc.filename||null};Buffer.prototype.withSource=function withSource(prop,loc,cb){if(!this._map)return cb();var originalLine=this._sourcePosition.line;var originalColumn=this._sourcePosition.column;var originalFilename=this._sourcePosition.filename;var originalIdentifierName=this._sourcePosition.identifierName;this.source(prop,loc);cb();this._sourcePosition.line=originalLine;this._sourcePosition.column=originalColumn;this._sourcePosition.filename=originalFilename;this._sourcePosition.identifierName=originalIdentifierName};Buffer.prototype.getCurrentColumn=function getCurrentColumn(){var extra=this._queue.reduce(function(acc,item){return item[0]+acc},"");var lastIndex=extra.lastIndexOf("\n");return lastIndex===-1?this._position.column+extra.length:extra.length-1-lastIndex};Buffer.prototype.getCurrentLine=function getCurrentLine(){var extra=this._queue.reduce(function(acc,item){return item[0]+acc},"");var count=0;for(var i=0;i")}this.space();this.print(node.returnType,node)}function FunctionTypeParam(node){this.print(node.name,node);if(node.optional)this.token("?");this.token(":");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.space();this.word("extends");this.space();this.printList(node.extends,node)}if(node.mixins&&node.mixins.length){this.space();this.word("mixins");this.space();this.printList(node.mixins,node)}this.space();this.print(node.body,node)}function InterfaceDeclaration(node){this.word("interface");this.space();this._interfaceish(node)}function andSeparator(){this.space();this.token("&");this.space()}function IntersectionTypeAnnotation(node){this.printJoin(node.types,node,{separator:andSeparator})}function MixedTypeAnnotation(){this.word("mixed")}function NullableTypeAnnotation(node){this.token("?");this.print(node.typeAnnotation,node)}function NumberTypeAnnotation(){this.word("number")}function StringTypeAnnotation(){this.word("string")}function ThisTypeAnnotation(){this.word("this")}function TupleTypeAnnotation(node){this.token("[");this.printList(node.types,node);this.token("]")}function TypeofTypeAnnotation(node){this.word("typeof");this.space();this.print(node.argument,node)}function TypeAlias(node){this.word("type");this.space();this.print(node.id,node);this.print(node.typeParameters,node);this.space();this.token("=");this.space();this.print(node.right,node);this.semicolon()}function TypeAnnotation(node){this.token(":");this.space();if(node.optional)this.token("?");this.print(node.typeAnnotation,node)}function TypeParameter(node){if(node.variance==="plus"){this.token("+")}else if(node.variance==="minus"){this.token("-")}this.word(node.name);if(node.bound){this.print(node.bound,node)}if(node.default){this.space();this.token("=");this.space();this.print(node.default,node)}}function TypeParameterInstantiation(node){this.token("<");this.printList(node.params,node,{});this.token(">")}exports.TypeParameterDeclaration=TypeParameterInstantiation;function ObjectTypeAnnotation(node){var _this=this;if(node.exact){this.token("{|")}else{this.token("{")}var props=node.properties.concat(node.callProperties,node.indexers);if(props.length){this.space();this.printJoin(props,node,{indent:true,statement:true,iterator:function iterator(){if(props.length!==1){_this.semicolon();_this.space()}}});this.space()}if(node.exact){this.token("|}")}else{this.token("}")}}function ObjectTypeCallProperty(node){if(node.static){this.word("static");this.space()}this.print(node.value,node)}function ObjectTypeIndexer(node){if(node.static){this.word("static");this.space()}this.token("[");this.print(node.id,node);this.token(":");this.space();this.print(node.key,node);this.token("]");this.token(":");this.space();this.print(node.value,node)}function ObjectTypeProperty(node){if(node.static){this.word("static");this.space()}this.print(node.key,node);if(node.optional)this.token("?");this.token(":");this.space();this.print(node.value,node)}function QualifiedTypeIdentifier(node){this.print(node.qualification,node);this.token(".");this.print(node.id,node)}function orSeparator(){this.space();this.token("|");this.space()}function UnionTypeAnnotation(node){this.printJoin(node.types,node,{separator:orSeparator})}function TypeCastExpression(node){this.token("(");this.print(node.expression,node);this.print(node.typeAnnotation,node);this.token(")")}function VoidTypeAnnotation(){this.word("void")}},{"./types":52}],47:[function(require,module,exports){"use strict";exports.__esModule=true;var _getIterator2=require("babel-runtime/core-js/get-iterator");var _getIterator3=_interopRequireDefault(_getIterator2);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 _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function JSXAttribute(node){this.print(node.name,node);if(node.value){this.token("=");this.print(node.value,node)}}function JSXIdentifier(node){this.word(node.name)}function JSXNamespacedName(node){this.print(node.namespace,node);this.token(":");this.print(node.name,node)}function JSXMemberExpression(node){this.print(node.object,node);this.token(".");this.print(node.property,node)}function JSXSpreadAttribute(node){this.token("{");this.token("...");this.print(node.argument,node);this.token("}")}function JSXExpressionContainer(node){this.token("{");this.print(node.expression,node);this.token("}")}function JSXText(node){this.token(node.value)}function JSXElement(node){var open=node.openingElement;this.print(open,node);if(open.selfClosing)return;this.indent();for(var _iterator=node.children,_isArray=Array.isArray(_iterator),_i=0,_iterator=_isArray?_iterator:(0,_getIterator3.default)(_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 child=_ref;this.print(child,node)}this.dedent();this.print(node.closingElement,node)}function spaceSeparator(){this.space()}function JSXOpeningElement(node){this.token("<");this.print(node.name,node);if(node.attributes.length>0){this.space();this.printJoin(node.attributes,node,{separator:spaceSeparator})}if(node.selfClosing){this.space();this.token("/>")}else{this.token(">")}}function JSXClosingElement(node){this.token("")}function JSXEmptyExpression(){}},{"babel-runtime/core-js/get-iterator":138}],48:[function(require,module,exports){"use strict";exports.__esModule=true;exports.FunctionDeclaration=undefined;exports._params=_params;exports._method=_method;exports.FunctionExpression=FunctionExpression;exports.ArrowFunctionExpression=ArrowFunctionExpression;var _babelTypes=require("babel-types");var t=_interopRequireWildcard(_babelTypes);function _interopRequireWildcard(obj){if(obj&&obj.__esModule){return obj}else{var newObj={};if(obj!=null){for(var key in obj){if(Object.prototype.hasOwnProperty.call(obj,key))newObj[key]=obj[key]}}newObj.default=obj;return newObj}}function _params(node){var _this=this;this.print(node.typeParameters,node);this.token("(");this.printList(node.params,node,{iterator:function iterator(node){if(node.optional)_this.token("?");_this.print(node.typeAnnotation,node)}});this.token(")");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.token("*")}}if(kind==="get"||kind==="set"){this.word(kind);this.space()}if(node.async){this.word("async");this.space()}if(node.computed){this.token("[");this.print(key,node);this.token("]")}else{this.print(key,node)}this._params(node);this.space();this.print(node.body,node)}function FunctionExpression(node){if(node.async){this.word("async");this.space()}this.word("function");if(node.generator)this.token("*");if(node.id){this.space();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.word("async");this.space()}var firstParam=node.params[0];if(node.params.length===1&&t.isIdentifier(firstParam)&&!hasTypes(node,firstParam)){this.print(firstParam,node)}else{this._params(node)}this.space();this.token("=>");this.space();this.print(node.body,node)}function hasTypes(node,param){return node.typeParameters||node.returnType||param.typeAnnotation||param.optional||param.trailingComments}},{"babel-types":193}],49:[function(require,module,exports){"use strict";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 _interopRequireWildcard(obj){if(obj&&obj.__esModule){return obj}else{var newObj={};if(obj!=null){for(var key in obj){if(Object.prototype.hasOwnProperty.call(obj,key))newObj[key]=obj[key]}}newObj.default=obj;return newObj}}function ImportSpecifier(node){this.print(node.imported,node);if(node.local&&node.local.name!==node.imported.name){this.space();this.word("as");this.space();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.space();this.word("as");this.space();this.print(node.exported,node)}}function ExportNamespaceSpecifier(node){this.token("*");this.space();this.word("as");this.space();this.print(node.exported,node)}function ExportAllDeclaration(node){this.word("export");this.space();this.token("*");if(node.exported){this.space();this.word("as");this.space();this.print(node.exported,node)}this.space();this.word("from");this.space();this.print(node.source,node);this.semicolon()}function ExportNamedDeclaration(){this.word("export");this.space();ExportDeclaration.apply(this,arguments)}function ExportDefaultDeclaration(){this.word("export");this.space();this.word("default");this.space();ExportDeclaration.apply(this,arguments)}function ExportDeclaration(node){if(node.declaration){var declar=node.declaration;this.print(declar,node);if(!t.isStatement(declar))this.semicolon()}else{if(node.exportKind==="type"){this.word("type");this.space()}var specifiers=node.specifiers.slice(0);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.token(",");this.space()}}else{break}}if(specifiers.length||!specifiers.length&&!hasSpecial){this.token("{");if(specifiers.length){this.space();this.printList(specifiers,node);this.space()}this.token("}")}if(node.source){this.space();this.word("from");this.space();this.print(node.source,node)}this.semicolon()}}function ImportDeclaration(node){this.word("import");this.space();if(node.importKind==="type"||node.importKind==="typeof"){this.word(node.importKind);this.space()}var specifiers=node.specifiers.slice(0);if(specifiers&&specifiers.length){while(true){var first=specifiers[0];if(t.isImportDefaultSpecifier(first)||t.isImportNamespaceSpecifier(first)){this.print(specifiers.shift(),node);if(specifiers.length){this.token(",");this.space()}}else{break}}if(specifiers.length){this.token("{");this.space();this.printList(specifiers,node);this.space();this.token("}")}this.space();this.word("from");this.space()}this.print(node.source,node);this.semicolon()}function ImportNamespaceSpecifier(node){this.token("*");this.space();this.word("as");this.space();this.print(node.local,node)}},{"babel-types":193}],50:[function(require,module,exports){"use strict";exports.__esModule=true;exports.ThrowStatement=exports.BreakStatement=exports.ReturnStatement=exports.ContinueStatement=exports.ForAwaitStatement=exports.ForOfStatement=exports.ForInStatement=undefined;var _getIterator2=require("babel-runtime/core-js/get-iterator");var _getIterator3=_interopRequireDefault(_getIterator2);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 _babelTypes=require("babel-types");var t=_interopRequireWildcard(_babelTypes);function _interopRequireWildcard(obj){if(obj&&obj.__esModule){return obj}else{var newObj={};if(obj!=null){for(var key in obj){if(Object.prototype.hasOwnProperty.call(obj,key))newObj[key]=obj[key]}}newObj.default=obj;return newObj}}function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function WithStatement(node){this.word("with");this.space();this.token("(");this.print(node.object,node);this.token(")");this.printBlock(node)}function IfStatement(node){this.word("if");this.space();this.token("(");this.print(node.test,node);this.token(")");this.space();var needsBlock=node.alternate&&t.isIfStatement(getLastStatement(node.consequent));if(needsBlock){this.token("{");this.newline();this.indent()}this.printAndIndentOnComments(node.consequent,node);if(needsBlock){this.dedent();this.newline();this.token("}")}if(node.alternate){if(this.endsWith("}"))this.space();this.word("else");this.space();this.printAndIndentOnComments(node.alternate,node)}}function getLastStatement(statement){if(!t.isStatement(statement.body))return statement;return getLastStatement(statement.body)}function ForStatement(node){this.word("for");this.space();this.token("(");this.inForStatementInitCounter++;this.print(node.init,node);this.inForStatementInitCounter--;this.token(";");if(node.test){this.space();this.print(node.test,node)}this.token(";");if(node.update){this.space();this.print(node.update,node)}this.token(")");this.printBlock(node)}function WhileStatement(node){this.word("while");this.space();this.token("(");this.print(node.test,node);this.token(")");this.printBlock(node)}var buildForXStatement=function buildForXStatement(op){return function(node){this.word("for");this.space();if(op==="await"){this.word("await");this.space();op="of"}this.token("(");this.print(node.left,node);this.space();this.word(op);this.space();this.print(node.right,node);this.token(")");this.printBlock(node)}};var ForInStatement=exports.ForInStatement=buildForXStatement("in");var ForOfStatement=exports.ForOfStatement=buildForXStatement("of");var ForAwaitStatement=exports.ForAwaitStatement=buildForXStatement("await");function DoWhileStatement(node){this.word("do");this.space();this.print(node.body,node);this.space();this.word("while");this.space();this.token("(");this.print(node.test,node);this.token(")");this.semicolon()}function buildLabelStatement(prefix){var key=arguments.length<=1||arguments[1]===undefined?"label":arguments[1];return function(node){this.word(prefix);var label=node[key];if(label){this.space(); -var terminatorState=this.startTerminatorless();this.print(label,node);this.endTerminatorless(terminatorState)}this.semicolon()}}var ContinueStatement=exports.ContinueStatement=buildLabelStatement("continue");var ReturnStatement=exports.ReturnStatement=buildLabelStatement("return","argument");var BreakStatement=exports.BreakStatement=buildLabelStatement("break");var ThrowStatement=exports.ThrowStatement=buildLabelStatement("throw","argument");function LabeledStatement(node){this.print(node.label,node);this.token(":");this.space();this.print(node.body,node)}function TryStatement(node){this.word("try");this.space();this.print(node.block,node);this.space();if(node.handlers){this.print(node.handlers[0],node)}else{this.print(node.handler,node)}if(node.finalizer){this.space();this.word("finally");this.space();this.print(node.finalizer,node)}}function CatchClause(node){this.word("catch");this.space();this.token("(");this.print(node.param,node);this.token(")");this.space();this.print(node.body,node)}function SwitchStatement(node){this.word("switch");this.space();this.token("(");this.print(node.discriminant,node);this.token(")");this.space();this.token("{");this.printSequence(node.cases,node,{indent:true,addNewlines:function addNewlines(leading,cas){if(!leading&&node.cases[node.cases.length-1]===cas)return-1}});this.token("}")}function SwitchCase(node){if(node.test){this.word("case");this.space();this.print(node.test,node);this.token(":")}else{this.word("default");this.token(":")}if(node.consequent.length){this.newline();this.printSequence(node.consequent,node,{indent:true})}}function DebuggerStatement(){this.word("debugger");this.semicolon()}function variableDeclarationIdent(){this.token(",");this.newline();if(this.endsWith("\n"))for(var i=0;i<4;i++){this.space(true)}}function constDeclarationIdent(){this.token(",");this.newline();if(this.endsWith("\n"))for(var i=0;i<6;i++){this.space(true)}}function VariableDeclaration(node,parent){this.word(node.kind);this.space();var hasInits=false;if(!t.isFor(parent)){for(var _iterator=node.declarations,_isArray=Array.isArray(_iterator),_i=0,_iterator=_isArray?_iterator:(0,_getIterator3.default)(_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 declar=_ref;if(declar.init){hasInits=true}}}var separator=void 0;if(hasInits){separator=node.kind==="const"?constDeclarationIdent:variableDeclarationIdent}this.printList(node.declarations,node,{separator:separator});if(t.isFor(parent)){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.token("=");this.space();this.print(node.init,node)}}},{"babel-runtime/core-js/get-iterator":138,"babel-types":193}],51:[function(require,module,exports){"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,parent){var isFirst=parent.quasis[0]===node;var isLast=parent.quasis[parent.quasis.length-1]===node;var value=(isFirst?"`":"}")+node.value.raw+(isLast?"`":"${");if(!isFirst)this.space();this.token(value);if(!isLast)this.space()}function TemplateLiteral(node){var quasis=node.quasis;for(var i=0;i0)this.space();this.print(elem,node);if(i=0||value.indexOf("@preserve")>=0}}if(format.compact==="auto"){format.compact=code.length>1e5;if(format.compact){console.error("[BABEL] "+messages.get("codeGeneratorDeopt",opts.filename,"100KB"))}}if(format.compact){format.indent.adjustMultilineComment=false}return format}function findCommonStringDelimiter(code,tokens){var DEFAULT_STRING_DELIMITER="double";if(!code){return DEFAULT_STRING_DELIMITER}var occurences={single:0,double:0};var checked=0;for(var i=0;i=3)break}if(occurences.single>occurences.double){return"single"}else{return"double"}}var CodeGenerator=exports.CodeGenerator=function(){function CodeGenerator(ast,opts,code){(0,_classCallCheck3.default)(this,CodeGenerator);this._generator=new Generator(ast,opts,code)}CodeGenerator.prototype.generate=function generate(){return this._generator.generate()};return CodeGenerator}()},{"./printer":57,"./source-map":58,"babel-messages":76,"babel-runtime/helpers/classCallCheck":152,"babel-runtime/helpers/inherits":153,"babel-runtime/helpers/possibleConstructorReturn":154,"detect-indent":343}],54:[function(require,module,exports){"use strict";exports.__esModule=true;var _getIterator2=require("babel-runtime/core-js/get-iterator");var _getIterator3=_interopRequireDefault(_getIterator2);var _keys=require("babel-runtime/core-js/object/keys");var _keys2=_interopRequireDefault(_keys);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 _interopRequireWildcard(obj){if(obj&&obj.__esModule){return obj}else{var newObj={};if(obj!=null){for(var key in obj){if(Object.prototype.hasOwnProperty.call(obj,key))newObj[key]=obj[key]}}newObj.default=obj;return newObj}}function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function expandAliases(obj){var newObj={};function add(type,func){var fn=newObj[type];newObj[type]=fn?function(node,parent,stack){var result=fn(node,parent,stack);return result==null?func(node,parent,stack):result}:func}for(var _iterator=(0,_keys2.default)(obj),_isArray=Array.isArray(_iterator),_i=0,_iterator=_isArray?_iterator:(0,_getIterator3.default)(_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 type=_ref;var aliases=t.FLIPPED_ALIAS_KEYS[type];if(aliases){for(var _iterator2=aliases,_isArray2=Array.isArray(_iterator2),_i2=0,_iterator2=_isArray2?_iterator2:(0,_getIterator3.default)(_iterator2);;){var _ref2;if(_isArray2){if(_i2>=_iterator2.length)break;_ref2=_iterator2[_i2++]}else{_i2=_iterator2.next();if(_i2.done)break;_ref2=_i2.value}var alias=_ref2;add(alias,obj[type])}}else{add(type,obj[type])}}return newObj}var expandedParens=expandAliases(parens);var expandedWhitespaceNodes=expandAliases(_whitespace2.default.nodes);var expandedWhitespaceList=expandAliases(_whitespace2.default.list);function find(obj,node,parent,printStack){var fn=obj[node.type];return fn?fn(node,parent,printStack):null}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 needsWhitespace(node,parent,type){if(!node)return 0;if(t.isExpressionStatement(node)){node=node.expression}var linesInfo=find(expandedWhitespaceNodes,node,parent);if(!linesInfo){var items=find(expandedWhitespaceList,node,parent);if(items){for(var i=0;i":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){return true}return false}function ObjectExpression(node,parent,printStack){return isFirstInStatement(printStack,{considerArrow: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}if(parentPos===nodePos&&parent.right===node&&!t.isLogicalExpression(parent)){return true}}return false}function BinaryExpression(node,parent){if(node.operator==="in"){if(t.isVariableDeclarator(parent)){return true}if(t.isFor(parent)){return true}}return false}function SequenceExpression(node,parent){if(t.isForStatement(parent)){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}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,printStack){return isFirstInStatement(printStack,{considerDefaultExports:true})}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){return isFirstInStatement(printStack,{considerDefaultExports:true})}function ArrowFunctionExpression(node,parent){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)}}function isFirstInStatement(printStack){var _ref=arguments.length<=1||arguments[1]===undefined?{}:arguments[1];var _ref$considerArrow=_ref.considerArrow;var considerArrow=_ref$considerArrow===undefined?false:_ref$considerArrow;var _ref$considerDefaultE=_ref.considerDefaultExports;var considerDefaultExports=_ref$considerDefaultE===undefined?false:_ref$considerDefaultE;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(considerDefaultExports&&t.isExportDefaultDeclaration(parent,{declaration: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}},{"babel-types":193}],56:[function(require,module,exports){"use strict";var _isBoolean=require("lodash/isBoolean");var _isBoolean2=_interopRequireDefault(_isBoolean);var _each=require("lodash/each");var _each2=_interopRequireDefault(_each);var _map=require("lodash/map");var _map2=_interopRequireDefault(_map);var _babelTypes=require("babel-types");var t=_interopRequireWildcard(_babelTypes);function _interopRequireWildcard(obj){if(obj&&obj.__esModule){return obj}else{var newObj={};if(obj!=null){for(var key in obj){if(Object.prototype.hasOwnProperty.call(obj,key))newObj[key]=obj[key]}}newObj.default=obj;return newObj}}function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}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}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)}exports.nodes={AssignmentExpression:function AssignmentExpression(node){var state=crawl(node.right);if(state.hasCall&&state.hasHelper||state.hasFunction){return{before:state.hasFunction,after:true}}},SwitchCase:function SwitchCase(node,parent){return{before:node.consequent.length||parent.cases[0]===node}},LogicalExpression:function LogicalExpression(node){if(t.isFunction(node.left)||t.isFunction(node.right)){return{after:true}}},Literal:function Literal(node){if(node.value==="use strict"){return{after:true}}},CallExpression:function CallExpression(node){if(t.isFunction(node.callee)||isHelper(node)){return{before:true,after:true}}},VariableDeclaration:function VariableDeclaration(node){for(var i=0;i0?new _whitespace2.default(tokens):null}Printer.prototype.generate=function generate(ast){this.print(ast);this._maybeAddAuxComment();return this._buf.get()};Printer.prototype.indent=function indent(){if(this.format.compact||this.format.concise)return;this._indent++};Printer.prototype.dedent=function dedent(){if(this.format.compact||this.format.concise)return;this._indent--};Printer.prototype.semicolon=function semicolon(){var force=arguments.length<=0||arguments[0]===undefined?false:arguments[0];this._maybeAddAuxComment();this._append(";",!force)};Printer.prototype.rightBrace=function rightBrace(){if(this.format.minified){this._buf.removeLastSemicolon()}this.token("}")};Printer.prototype.space=function space(){var force=arguments.length<=0||arguments[0]===undefined?false:arguments[0];if(this.format.compact)return;if(this._buf.hasContent()&&!this.endsWith(" ")&&!this.endsWith("\n")||force){this._space()}};Printer.prototype.word=function word(str){if(this._endsWithWord)this._space();this._maybeAddAuxComment();this._append(str);this._endsWithWord=true};Printer.prototype.number=function number(str){this.word(str);this._endsWithInteger=(0,_isInteger2.default)(+str)&&!NON_DECIMAL_LITERAL.test(str)&&!SCIENTIFIC_NOTATION.test(str)&&!ZERO_DECIMAL_INTEGER.test(str)&&str[str.length-1]!=="."};Printer.prototype.token=function token(str){if(str==="--"&&this.endsWith("!")||str[0]==="+"&&this.endsWith("+")||str[0]==="-"&&this.endsWith("-")||str[0]==="."&&this._endsWithInteger){this._space()}this._maybeAddAuxComment();this._append(str)};Printer.prototype.newline=function newline(i){if(this.format.retainLines||this.format.compact)return;if(this.format.concise){this.space();return}if(this.endsWith("\n\n"))return;if(typeof i!=="number")i=1;i=Math.min(2,i);if(this.endsWith("{\n")||this.endsWith(":\n"))i--;if(i<=0)return;for(var j=0;j=_iterator.length)break;_ref=_iterator[_i++]}else{_i=_iterator.next();if(_i.done)break;_ref=_i.value}var _comment3=_ref;this._printComment(_comment3)}};return Printer}();exports.default=Printer;function commaSeparator(){this.token(",");this.space()}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];(0,_assign2.default)(Printer.prototype,generator)}module.exports=exports["default"]},{"./buffer":42,"./generators/base":43,"./generators/classes":44,"./generators/expressions":45,"./generators/flow":46,"./generators/jsx":47,"./generators/methods":48,"./generators/modules":49,"./generators/statements":50,"./generators/template-literals":51,"./generators/types":52,"./node":54,"./whitespace":59,"babel-runtime/core-js/get-iterator":138,"babel-runtime/core-js/json/stringify":139,"babel-runtime/core-js/object/assign":142,"babel-runtime/core-js/weak-set":151,"babel-runtime/helpers/classCallCheck":152,"babel-types":193,"lodash/find":537,"lodash/findLast":539,"lodash/isInteger":554,"lodash/repeat":573}],58:[function(require,module,exports){"use strict";exports.__esModule=true;var _keys=require("babel-runtime/core-js/object/keys");var _keys2=_interopRequireDefault(_keys);var _typeof2=require("babel-runtime/helpers/typeof");var _typeof3=_interopRequireDefault(_typeof2);var _classCallCheck2=require("babel-runtime/helpers/classCallCheck");var _classCallCheck3=_interopRequireDefault(_classCallCheck2);var _sourceMap=require("source-map");var _sourceMap2=_interopRequireDefault(_sourceMap);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}var SourceMap=function(){function SourceMap(opts,code){var _this=this;(0,_classCallCheck3.default)(this,SourceMap);this._opts=opts;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==="undefined"?"undefined":(0,_typeof3.default)(code))==="object"){(0,_keys2.default)(code).forEach(function(sourceFileName){_this._map.setSourceContent(sourceFileName,code[sourceFileName])})}}SourceMap.prototype.get=function get(){return this._map.toJSON()};SourceMap.prototype.mark=function mark(generatedLine,generatedColumn,line,column,identifierName,filename){if(this._lastGenLine!==generatedLine&&line===null)return;if(this._lastGenLine===generatedLine&&this._lastSourceLine===line&&this._lastSourceColumn===column){return}this._lastGenLine=generatedLine;this._lastSourceLine=line;this._lastSourceColumn=column;this._map.addMapping({name:identifierName,generated:{line:generatedLine,column:generatedColumn},source:line==null?null:filename||this._opts.sourceFileName,original:line==null?null:{line:line,column:column}})};return SourceMap}();exports.default=SourceMap;module.exports=exports["default"]},{"babel-runtime/core-js/object/keys":145,"babel-runtime/helpers/classCallCheck":152,"babel-runtime/helpers/typeof":155,"source-map":684}],59:[function(require,module,exports){"use strict";exports.__esModule=true;var _classCallCheck2=require("babel-runtime/helpers/classCallCheck");var _classCallCheck3=_interopRequireDefault(_classCallCheck2);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}var Whitespace=function(){function Whitespace(tokens){(0,_classCallCheck3.default)(this,Whitespace);this.tokens=tokens;this.used={}}Whitespace.prototype.getNewlinesBefore=function getNewlinesBefore(node){var startToken=void 0;var endToken=void 0;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)};Whitespace.prototype.getNewlinesAfter=function getNewlinesAfter(node){var startToken=void 0;var endToken=void 0;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{return this._getNewlinesBetween(startToken,endToken)}};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)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"]},{"babel-runtime/helpers/classCallCheck":152}],60:[function(require,module,exports){"use strict";exports.__esModule=true;var _getIterator2=require("babel-runtime/core-js/get-iterator");var _getIterator3=_interopRequireDefault(_getIterator2);exports.default=bindifyDecorators;var _babelTypes=require("babel-types");var t=_interopRequireWildcard(_babelTypes);function _interopRequireWildcard(obj){if(obj&&obj.__esModule){return obj}else{var newObj={};if(obj!=null){for(var key in obj){if(Object.prototype.hasOwnProperty.call(obj,key))newObj[key]=obj[key]}}newObj.default=obj;return newObj}}function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function bindifyDecorators(decorators){for(var _iterator=decorators,_isArray=Array.isArray(_iterator),_i=0,_iterator=_isArray?_iterator:(0,_getIterator3.default)(_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 decoratorPath=_ref;var decorator=decoratorPath.node;var expression=decorator.expression;if(!t.isMemberExpression(expression))continue;var temp=decoratorPath.scope.maybeGenerateMemoised(expression.object);var ref=void 0;var nodes=[];if(temp){ref=temp;nodes.push(t.assignmentExpression("=",temp,expression.object))}else{ref=expression.object}nodes.push(t.callExpression(t.memberExpression(t.memberExpression(ref,expression.property,expression.computed),t.identifier("bind")),[ref]));if(nodes.length===1){decorator.expression=nodes[0]}else{decorator.expression=t.sequenceExpression(nodes)}}}module.exports=exports["default"]},{"babel-runtime/core-js/get-iterator":138,"babel-types":193}],61:[function(require,module,exports){"use strict";exports.__esModule=true;exports.default=function(opts){var visitor={};function isAssignment(node){return node&&node.operator===opts.operator+"="}function buildAssignment(left,right){return t.assignmentExpression("=",left,right)}visitor.ExpressionStatement=function(path,file){if(path.isCompletionRecord())return;var expr=path.node.expression;if(!isAssignment(expr))return;var nodes=[];var exploded=(0,_babelHelperExplodeAssignableExpression2.default)(expr.left,nodes,file,path.scope,true);nodes.push(t.expressionStatement(buildAssignment(exploded.ref,opts.build(exploded.uid,expr.right))));path.replaceWithMultiple(nodes)};visitor.AssignmentExpression=function(path,file){var node=path.node;var scope=path.scope;if(!isAssignment(node))return;var nodes=[];var exploded=(0,_babelHelperExplodeAssignableExpression2.default)(node.left,nodes,file,scope);nodes.push(buildAssignment(exploded.ref,opts.build(exploded.uid,node.right)));path.replaceWithMultiple(nodes)};visitor.BinaryExpression=function(path){var node=path.node;if(node.operator===opts.operator){path.replaceWith(opts.build(node.left,node.right))}};return visitor};var _babelHelperExplodeAssignableExpression=require("babel-helper-explode-assignable-expression");var _babelHelperExplodeAssignableExpression2=_interopRequireDefault(_babelHelperExplodeAssignableExpression);var _babelTypes=require("babel-types");var t=_interopRequireWildcard(_babelTypes);function _interopRequireWildcard(obj){if(obj&&obj.__esModule){return obj}else{var newObj={};if(obj!=null){for(var key in obj){if(Object.prototype.hasOwnProperty.call(obj,key))newObj[key]=obj[key]}}newObj.default=obj;return newObj}}function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}module.exports=exports["default"]},{"babel-helper-explode-assignable-expression":64,"babel-types":193}],62:[function(require,module,exports){"use strict";exports.__esModule=true;exports.default=function(path){var scope=arguments.length<=1||arguments[1]===undefined?path.scope:arguments[1];var node=path.node;var container=t.functionExpression(null,[],node.body,node.generator,node.async);var callee=container;var args=[];(0,_babelHelperHoistVariables2.default)(path,function(id){return scope.push({id:id})});var state={foundThis:false,foundArguments:false};path.traverse(visitor,state);if(state.foundArguments){callee=t.memberExpression(container,t.identifier("apply"));args=[];if(state.foundThis){args.push(t.thisExpression())}if(state.foundArguments){if(!state.foundThis)args.push(t.nullLiteral());args.push(t.identifier("arguments"))}}var call=t.callExpression(callee,args);if(node.generator)call=t.yieldExpression(call,true);return t.returnStatement(call)};var _babelHelperHoistVariables=require("babel-helper-hoist-variables");var _babelHelperHoistVariables2=_interopRequireDefault(_babelHelperHoistVariables);var _babelTypes=require("babel-types");var t=_interopRequireWildcard(_babelTypes);function _interopRequireWildcard(obj){if(obj&&obj.__esModule){return obj}else{var newObj={};if(obj!=null){for(var key in obj){if(Object.prototype.hasOwnProperty.call(obj,key))newObj[key]=obj[key]}}newObj.default=obj;return newObj}}function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}var visitor={enter:function enter(path,state){if(path.isThisExpression()){state.foundThis=true}if(path.isReferencedIdentifier({name:"arguments"})){state.foundArguments=true}},Function:function Function(path){path.skip()}};module.exports=exports["default"]},{"babel-helper-hoist-variables":68,"babel-types":193}],63:[function(require,module,exports){"use strict";exports.__esModule=true;exports.push=push;exports.hasComputed=hasComputed;exports.toComputedObjectFromClass=toComputedObjectFromClass;exports.toClassObject=toClassObject;exports.toDefineObject=toDefineObject;var _babelHelperFunctionName=require("babel-helper-function-name");var _babelHelperFunctionName2=_interopRequireDefault(_babelHelperFunctionName);var _each=require("lodash/each");var _each2=_interopRequireDefault(_each);var _has=require("lodash/has");var _has2=_interopRequireDefault(_has);var _babelTypes=require("babel-types");var t=_interopRequireWildcard(_babelTypes);function _interopRequireWildcard(obj){if(obj&&obj.__esModule){return obj}else{var newObj={};if(obj!=null){for(var key in obj){if(Object.prototype.hasOwnProperty.call(obj,key))newObj[key]=obj[key]}}newObj.default=obj;return newObj}}function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function toKind(node){if(t.isClassMethod(node)||t.isObjectMethod(node)){if(node.kind==="get"||node.kind==="set"){return node.kind}}return"value"}function push(mutatorMap,node,kind,file,scope){var alias=t.toKeyAlias(node);var map={};if((0,_has2.default)(mutatorMap,alias))map=mutatorMap[alias];mutatorMap[alias]=map;map._inherits=map._inherits||[];map._inherits.push(node);map._key=node.key;if(node.computed){map._computed=true}if(node.decorators){var decorators=map.decorators=map.decorators||t.arrayExpression([]);decorators.elements=decorators.elements.concat(node.decorators.map(function(dec){return dec.expression}).reverse())}if(map.value||map.initializer){throw file.buildCodeFrameError(node,"Key conflict with sibling node")}var key=void 0,value=void 0;if(t.isObjectProperty(node)||t.isObjectMethod(node)||t.isClassMethod(node)){key=t.toComputedKey(node,node.key)}if(t.isObjectProperty(node)||t.isClassProperty(node)){value=node.value}else if(t.isObjectMethod(node)||t.isClassMethod(node)){value=t.functionExpression(null,node.params,node.body,node.generator,node.async)}var inheritedKind=toKind(node);if(!kind||inheritedKind!=="value"){kind=inheritedKind}if(scope&&t.isStringLiteral(key)&&(kind==="value"||kind==="initializer")&&t.isFunctionExpression(value)){value=(0,_babelHelperFunctionName2.default)({id:key,node:value,scope:scope})}if(value){t.inheritsComments(value,node);map[kind]=value}return map}function hasComputed(mutatorMap){for(var key in mutatorMap){if(mutatorMap[key]._computed){return true}}return false}function toComputedObjectFromClass(obj){var objExpr=t.arrayExpression([]);for(var i=0;i=_iterator.length)break;_ref=_iterator[_i++]}else{_i=_iterator.next();if(_i.done)break;_ref=_i.value}var path=_ref;maybeMemoise(path)}}maybeMemoise(classPath.get("superClass"));memoiseDecorators(classPath.get("decorators"),true);var methods=classPath.get("body.body");for(var _iterator2=methods,_isArray2=Array.isArray(_iterator2),_i2=0,_iterator2=_isArray2?_iterator2:(0,_getIterator3.default)(_iterator2);;){var _ref2;if(_isArray2){if(_i2>=_iterator2.length)break;_ref2=_iterator2[_i2++]}else{_i2=_iterator2.next();if(_i2.done)break;_ref2=_i2.value}var methodPath=_ref2;if(methodPath.is("computed")){maybeMemoise(methodPath.get("key"))}if(methodPath.has("decorators")){memoiseDecorators(classPath.get("decorators"))}}if(memoisedExpressions){classPath.insertBefore(memoisedExpressions.map(function(expr){return t.expressionStatement(expr)}))}};var _babelHelperBindifyDecorators=require("babel-helper-bindify-decorators");var _babelHelperBindifyDecorators2=_interopRequireDefault(_babelHelperBindifyDecorators);var _babelTypes=require("babel-types");var t=_interopRequireWildcard(_babelTypes);function _interopRequireWildcard(obj){if(obj&&obj.__esModule){return obj}else{var newObj={};if(obj!=null){for(var key in obj){if(Object.prototype.hasOwnProperty.call(obj,key))newObj[key]=obj[key]}}newObj.default=obj;return newObj}}function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}module.exports=exports["default"]},{"babel-helper-bindify-decorators":60,"babel-runtime/core-js/get-iterator":138,"babel-types":193}],66:[function(require,module,exports){"use strict";exports.__esModule=true;exports.default=function(_ref){var node=_ref.node;var parent=_ref.parent;var scope=_ref.scope;var id=_ref.id;if(node.id)return;if((t.isObjectProperty(parent)||t.isObjectMethod(parent,{kind:"method"}))&&(!parent.computed||t.isLiteral(parent.key))){id=parent.key}else if(t.isVariableDeclarator(parent)){id=parent.id;if(t.isIdentifier(id)){var binding=scope.parent.getBinding(id.name);if(binding&&binding.constant&&scope.getBinding(id.name)===binding){node.id=id;node.id[t.NOT_LOCAL_BINDING]=true;return}}}else if(t.isAssignmentExpression(parent)){id=parent.left}else if(!id){return}var name=void 0;if(id&&t.isLiteral(id)){name=id.value}else if(id&&t.isIdentifier(id)){name=id.name}else{return}name=t.toBindingIdentifierName(name);id=t.identifier(name);id[t.NOT_LOCAL_BINDING]=true;var state=visit(node,name,scope);return wrap(state,node,id,scope)||node};var _babelHelperGetFunctionArity=require("babel-helper-get-function-arity");var _babelHelperGetFunctionArity2=_interopRequireDefault(_babelHelperGetFunctionArity);var _babelTemplate=require("babel-template");var _babelTemplate2=_interopRequireDefault(_babelTemplate);var _babelTypes=require("babel-types");var t=_interopRequireWildcard(_babelTypes);function _interopRequireWildcard(obj){if(obj&&obj.__esModule){return obj}else{var newObj={};if(obj!=null){for(var key in obj){if(Object.prototype.hasOwnProperty.call(obj,key))newObj[key]=obj[key]}}newObj.default=obj;return newObj}}function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}var buildPropertyMethodAssignmentWrapper=(0,_babelTemplate2.default)("\n (function (FUNCTION_KEY) {\n function FUNCTION_ID() {\n return FUNCTION_KEY.apply(this, arguments);\n }\n\n FUNCTION_ID.toString = function () {\n return FUNCTION_KEY.toString();\n }\n\n return FUNCTION_ID;\n })(FUNCTION)\n");var buildGeneratorPropertyMethodAssignmentWrapper=(0,_babelTemplate2.default)("\n (function (FUNCTION_KEY) {\n function* FUNCTION_ID() {\n return yield* FUNCTION_KEY.apply(this, arguments);\n }\n\n FUNCTION_ID.toString = function () {\n return FUNCTION_KEY.toString();\n };\n\n return FUNCTION_ID;\n })(FUNCTION)\n");var visitor={"ReferencedIdentifier|BindingIdentifier":function ReferencedIdentifierBindingIdentifier(path,state){if(path.node.name!==state.name)return;var localDeclar=path.scope.getBindingIdentifier(state.name);if(localDeclar!==state.outerDeclar)return;state.selfReference=true;path.stop()}};function wrap(state,method,id,scope){if(state.selfReference){if(scope.hasBinding(id.name)&&!scope.hasGlobal(id.name)){scope.rename(id.name)}else{if(!t.isFunction(method))return;var build=buildPropertyMethodAssignmentWrapper;if(method.generator)build=buildGeneratorPropertyMethodAssignmentWrapper;var _template=build({FUNCTION:method,FUNCTION_ID:id,FUNCTION_KEY:scope.generateUidIdentifier(id.name)}).expression;_template.callee._skipModulesRemap=true;var params=_template.callee.body.body[0].params;for(var i=0,len=(0,_babelHelperGetFunctionArity2.default)(method);i=_iterator.length)break;_ref=_iterator[_i++]}else{_i=_iterator.next();if(_i.done)break;_ref=_i.value}var declar=_ref;firstId=declar.node.id;if(declar.node.init){nodes.push(t.expressionStatement(t.assignmentExpression("=",declar.node.id,declar.node.init)))}for(var name in declar.getBindingIdentifiers()){state.emit(t.identifier(name),name)}}if(path.parentPath.isFor({left:path.node})){path.replaceWith(firstId)}else{path.replaceWithMultiple(nodes)}}};module.exports=exports["default"]},{"babel-runtime/core-js/get-iterator":138,"babel-types":193}],69:[function(require,module,exports){"use strict";exports.__esModule=true;exports.default=function(callee,thisNode,args){if(args.length===1&&t.isSpreadElement(args[0])&&t.isIdentifier(args[0].argument,{name:"arguments"})){return t.callExpression(t.memberExpression(callee,t.identifier("apply")),[thisNode,args[0].argument])}else{return t.callExpression(t.memberExpression(callee,t.identifier("call")),[thisNode].concat(args))}};var _babelTypes=require("babel-types");var t=_interopRequireWildcard(_babelTypes);function _interopRequireWildcard(obj){if(obj&&obj.__esModule){return obj}else{var newObj={};if(obj!=null){for(var key in obj){if(Object.prototype.hasOwnProperty.call(obj,key))newObj[key]=obj[key]}}newObj.default=obj;return newObj}}module.exports=exports["default"]},{"babel-types":193}],70:[function(require,module,exports){"use strict";exports.__esModule=true;exports.is=is;exports.pullFlag=pullFlag;var _pull=require("lodash/pull");var _pull2=_interopRequireDefault(_pull);var _babelTypes=require("babel-types");var t=_interopRequireWildcard(_babelTypes);function _interopRequireWildcard(obj){if(obj&&obj.__esModule){return obj}else{var newObj={};if(obj!=null){for(var key in obj){if(Object.prototype.hasOwnProperty.call(obj,key))newObj[key]=obj[key]}}newObj.default=obj;return newObj}}function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function is(node,flag){return t.isRegExpLiteral(node)&&node.flags.indexOf(flag)>=0}function pullFlag(node,flag){var flags=node.flags.split("");if(node.flags.indexOf(flag)<0)return;(0,_pull2.default)(flags,flag);node.flags=flags.join("")}},{"babel-types":193,"lodash/pull":571}],71:[function(require,module,exports){"use strict";exports.__esModule=true;exports.default=function(path,helpers){var node=path.node;var scope=path.scope;var parent=path.parent;var stepKey=scope.generateUidIdentifier("step");var stepValue=scope.generateUidIdentifier("value");var left=node.left;var declar=void 0;if(t.isIdentifier(left)||t.isPattern(left)||t.isMemberExpression(left)){declar=t.expressionStatement(t.assignmentExpression("=",left,stepValue))}else if(t.isVariableDeclaration(left)){declar=t.variableDeclaration(left.kind,[t.variableDeclarator(left.declarations[0].id,stepValue)])}var template=buildForAwait();(0,_babelTraverse2.default)(template,forAwaitVisitor,null,{ITERATOR_HAD_ERROR_KEY:scope.generateUidIdentifier("didIteratorError"),ITERATOR_COMPLETION:scope.generateUidIdentifier("iteratorNormalCompletion"),ITERATOR_ERROR_KEY:scope.generateUidIdentifier("iteratorError"),ITERATOR_KEY:scope.generateUidIdentifier("iterator"),GET_ITERATOR:helpers.getAsyncIterator,OBJECT:node.right,STEP_VALUE:stepValue,STEP_KEY:stepKey,AWAIT:helpers.wrapAwait});template=template.body.body;var isLabeledParent=t.isLabeledStatement(parent);var tryBody=template[3].block.body;var loop=tryBody[0];if(isLabeledParent){tryBody[0]=t.labeledStatement(parent.label,loop)}return{replaceParent:isLabeledParent,node:template,declar:declar,loop:loop}};var _babelTypes=require("babel-types");var t=_interopRequireWildcard(_babelTypes);var _babelTemplate=require("babel-template");var _babelTemplate2=_interopRequireDefault(_babelTemplate);var _babelTraverse=require("babel-traverse");var _babelTraverse2=_interopRequireDefault(_babelTraverse);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function _interopRequireWildcard(obj){if(obj&&obj.__esModule){return obj}else{var newObj={};if(obj!=null){for(var key in obj){if(Object.prototype.hasOwnProperty.call(obj,key))newObj[key]=obj[key]}}newObj.default=obj;return newObj}}var buildForAwait=(0,_babelTemplate2.default)("\n function* wrapper() {\n var ITERATOR_COMPLETION = true;\n var ITERATOR_HAD_ERROR_KEY = false;\n var ITERATOR_ERROR_KEY = undefined;\n try {\n for (\n var ITERATOR_KEY = GET_ITERATOR(OBJECT), STEP_KEY, STEP_VALUE;\n (\n STEP_KEY = yield AWAIT(ITERATOR_KEY.next()),\n ITERATOR_COMPLETION = STEP_KEY.done,\n STEP_VALUE = yield AWAIT(STEP_KEY.value),\n !ITERATOR_COMPLETION\n );\n ITERATOR_COMPLETION = true) {\n }\n } catch (err) {\n ITERATOR_HAD_ERROR_KEY = true;\n ITERATOR_ERROR_KEY = err;\n } finally {\n try {\n if (!ITERATOR_COMPLETION && ITERATOR_KEY.return) {\n yield AWAIT(ITERATOR_KEY.return());\n }\n } finally {\n if (ITERATOR_HAD_ERROR_KEY) {\n throw ITERATOR_ERROR_KEY;\n }\n }\n }\n }\n"); +hidden:true,description:"optional callback to control whether a comment should be inserted, when this is used the comments option is ignored"},wrapPluginVisitorMethod:{hidden:true,description:"optional callback to wrap all visitor methods"},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},parserOpts:{description:"Options to pass into the parser, or to change parsers (parserOpts.parser)",default:false},generatorOpts:{description:"Options to pass into the generator, or to change generators (generatorOpts.generator)",default:false}}},{}],31:[function(require,module,exports){"use strict";exports.__esModule=true;exports.config=undefined;exports.normaliseOptions=normaliseOptions;var _parsers=require("./parsers");var parsers=_interopRequireWildcard(_parsers);var _config=require("./config");var _config2=_interopRequireDefault(_config);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function _interopRequireWildcard(obj){if(obj&&obj.__esModule){return obj}else{var newObj={};if(obj!=null){for(var key in obj){if(Object.prototype.hasOwnProperty.call(obj,key))newObj[key]=obj[key]}}newObj.default=obj;return newObj}}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}},{"./config":30,"./parsers":33}],32:[function(require,module,exports){(function(process){"use strict";exports.__esModule=true;var _stringify=require("babel-runtime/core-js/json/stringify");var _stringify2=_interopRequireDefault(_stringify);var _assign=require("babel-runtime/core-js/object/assign");var _assign2=_interopRequireDefault(_assign);var _getIterator2=require("babel-runtime/core-js/get-iterator");var _getIterator3=_interopRequireDefault(_getIterator2);var _typeof2=require("babel-runtime/helpers/typeof");var _typeof3=_interopRequireDefault(_typeof2);var _classCallCheck2=require("babel-runtime/helpers/classCallCheck");var _classCallCheck3=_interopRequireDefault(_classCallCheck2);var _node=require("../../../api/node");var context=_interopRequireWildcard(_node);var _plugin2=require("../../plugin");var _plugin3=_interopRequireDefault(_plugin2);var _babelMessages=require("babel-messages");var messages=_interopRequireWildcard(_babelMessages);var _index=require("./index");var _resolve=require("../../../helpers/resolve");var _resolve2=_interopRequireDefault(_resolve);var _cloneDeepWith=require("lodash/cloneDeepWith");var _cloneDeepWith2=_interopRequireDefault(_cloneDeepWith);var _clone=require("lodash/clone");var _clone2=_interopRequireDefault(_clone);var _merge=require("../../../helpers/merge");var _merge2=_interopRequireDefault(_merge);var _config2=require("./config");var _config3=_interopRequireDefault(_config2);var _removed=require("./removed");var _removed2=_interopRequireDefault(_removed);var _buildConfigChain=require("./build-config-chain");var _buildConfigChain2=_interopRequireDefault(_buildConfigChain);var _path=require("path");var _path2=_interopRequireDefault(_path);function _interopRequireWildcard(obj){if(obj&&obj.__esModule){return obj}else{var newObj={};if(obj!=null){for(var key in obj){if(Object.prototype.hasOwnProperty.call(obj,key))newObj[key]=obj[key]}}newObj.default=obj;return newObj}}function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}var OptionManager=function(){function OptionManager(log){(0,_classCallCheck3.default)(this,OptionManager);this.resolvedConfigs=[];this.options=OptionManager.createBareOptions();this.log=log}OptionManager.memoisePluginContainer=function memoisePluginContainer(fn,loc,i,alias){for(var _iterator=OptionManager.memoisedPlugins,_isArray=Array.isArray(_iterator),_i=0,_iterator=_isArray?_iterator:(0,_getIterator3.default)(_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 cache=_ref;if(cache.container===fn)return cache.plugin}var obj=void 0;if(typeof fn==="function"){obj=fn(context)}else{obj=fn}if((typeof obj==="undefined"?"undefined":(0,_typeof3.default)(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==="undefined"?"undefined":(0,_typeof3.default)(obj))+loc+i)}};OptionManager.createBareOptions=function createBareOptions(){var opts={};for(var _key in _config3.default){var opt=_config3.default[_key];opts[_key]=(0,_clone2.default)(opt.default)}return opts};OptionManager.normalisePlugin=function normalisePlugin(plugin,loc,i,alias){plugin=plugin.__esModule?plugin.default:plugin;if(!(plugin instanceof _plugin3.default)){if(typeof plugin==="function"||(typeof plugin==="undefined"?"undefined":(0,_typeof3.default)(plugin))==="object"){plugin=OptionManager.memoisePluginContainer(plugin,loc,i,alias)}else{throw new TypeError(messages.get("pluginNotFunction",loc,i,typeof plugin==="undefined"?"undefined":(0,_typeof3.default)(plugin)))}}plugin.init(loc,i);return plugin};OptionManager.normalisePlugins=function normalisePlugins(loc,dirname,plugins){return plugins.map(function(val,i){var plugin=void 0,options=void 0;if(!val){throw new TypeError("Falsy value found in plugins")}if(Array.isArray(val)){plugin=val[0];options=val[1]}else{plugin=val}var alias=typeof plugin==="string"?plugin:loc+"$"+i;if(typeof plugin==="string"){var pluginLoc=(0,_resolve2.default)("babel-plugin-"+plugin,dirname)||(0,_resolve2.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.mergeOptions=function mergeOptions(_ref2){var _this=this;var rawOpts=_ref2.options;var extendingOpts=_ref2.extending;var alias=_ref2.alias;var loc=_ref2.loc;var dirname=_ref2.dirname;alias=alias||"foreign";if(!rawOpts)return;if((typeof rawOpts==="undefined"?"undefined":(0,_typeof3.default)(rawOpts))!=="object"||Array.isArray(rawOpts)){this.log.error("Invalid options type for "+alias,TypeError)}var opts=(0,_cloneDeepWith2.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=_config3.default[_key2];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)}}}(0,_index.normaliseOptions)(opts);if(opts.plugins){opts.plugins=OptionManager.normalisePlugins(loc,dirname,opts.plugins)}if(opts.presets){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{this.mergePresets(opts.presets,dirname);delete opts.presets}}if(rawOpts===extendingOpts){(0,_assign2.default)(extendingOpts,opts)}else{(0,_merge2.default)(extendingOpts||this.options,opts)}};OptionManager.prototype.mergePresets=function mergePresets(presets,dirname){var _this2=this;this.resolvePresets(presets,dirname,function(presetOpts,presetLoc){_this2.mergeOptions({options:presetOpts,alias:presetLoc,loc:presetLoc,dirname:_path2.default.dirname(presetLoc||"")})})};OptionManager.prototype.resolvePresets=function resolvePresets(presets,dirname,onResolve){return presets.map(function(val){var options=void 0;if(Array.isArray(val)){if(val.length>2){throw new Error("Unexpected extra options "+(0,_stringify2.default)(val.slice(2))+" passed to preset.")}var _val=val;val=_val[0];options=_val[1]}var presetLoc=void 0;try{if(typeof val==="string"){presetLoc=(0,_resolve2.default)("babel-preset-"+val,dirname)||(0,_resolve2.default)(val,dirname);if(!presetLoc){var matches=val.match(/^(@[^\/]+)\/(.+)$/);if(matches){var orgName=matches[1];var presetPath=matches[2];val=orgName+"/babel-preset-"+presetPath;presetLoc=(0,_resolve2.default)(val,dirname)}}if(!presetLoc){throw new Error("Couldn't find preset "+(0,_stringify2.default)(val)+" relative to directory "+(0,_stringify2.default)(dirname))}val=require(presetLoc)}if((typeof val==="undefined"?"undefined":(0,_typeof3.default)(val))==="object"&&val.__esModule)val=val.default;if((typeof val==="undefined"?"undefined":(0,_typeof3.default)(val))==="object"&&val.buildPreset)val=val.buildPreset;if(typeof val!=="function"&&options!==undefined){throw new Error("Options "+(0,_stringify2.default)(options)+" passed to "+(presetLoc||"a preset")+" which does not accept options.")}if(typeof val==="function")val=val(context,options);if((typeof val==="undefined"?"undefined":(0,_typeof3.default)(val))!=="object"){throw new Error("Unsupported preset format: "+val+".")}onResolve&&onResolve(val,presetLoc)}catch(e){if(presetLoc){e.message+=" (While processing preset: "+(0,_stringify2.default)(presetLoc)+")"}throw e}return val})};OptionManager.prototype.normaliseOptions=function normaliseOptions(){var opts=this.options;for(var _key3 in _config3.default){var option=_config3.default[_key3];var val=opts[_key3];if(!val&&option.optional)continue;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];for(var _iterator2=(0,_buildConfigChain2.default)(opts,this.log),_isArray2=Array.isArray(_iterator2),_i2=0,_iterator2=_isArray2?_iterator2:(0,_getIterator3.default)(_iterator2);;){var _ref3;if(_isArray2){if(_i2>=_iterator2.length)break;_ref3=_iterator2[_i2++]}else{_i2=_iterator2.next();if(_i2.done)break;_ref3=_i2.value}var _config=_ref3;this.mergeOptions(_config)}this.normaliseOptions(opts);return this.options};return OptionManager}();exports.default=OptionManager;OptionManager.memoisedPlugins=[];module.exports=exports["default"]}).call(this,require("_process"))},{"../../../api/node":20,"../../../helpers/merge":21,"../../../helpers/resolve":23,"../../plugin":39,"./build-config-chain":29,"./config":30,"./index":31,"./removed":34,_process:594,"babel-messages":76,"babel-runtime/core-js/get-iterator":138,"babel-runtime/core-js/json/stringify":139,"babel-runtime/core-js/object/assign":142,"babel-runtime/helpers/classCallCheck":152,"babel-runtime/helpers/typeof":155,"lodash/clone":527,"lodash/cloneDeepWith":529,path:589}],33:[function(require,module,exports){"use strict";exports.__esModule=true;exports.filename=undefined;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);function _interopRequireWildcard(obj){if(obj&&obj.__esModule){return obj}else{var newObj={};if(obj!=null){for(var key in obj){if(Object.prototype.hasOwnProperty.call(obj,key))newObj[key]=obj[key]}}newObj.default=obj;return newObj}}function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}var filename=exports.filename=_slash2.default;function boolean(val){return!!val}function booleanString(val){return util.booleanify(val)}function list(val){return util.list(val)}},{"../../../util":40,slash:673}],34:[function(require,module,exports){"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/"},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"}}},{}],35:[function(require,module,exports){"use strict";exports.__esModule=true;var _plugin=require("../plugin");var _plugin2=_interopRequireDefault(_plugin);var _sortBy=require("lodash/sortBy");var _sortBy2=_interopRequireDefault(_sortBy);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}exports.default=new _plugin2.default({name:"internal.blockHoist",visitor:{Block:{exit:function exit(_ref){var node=_ref.node;var hasChange=false;for(var i=0;i=_iterator.length)break;_ref=_iterator[_i++]}else{_i=_iterator.next();if(_i.done)break;_ref=_i.value}var fn=_ref;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=_optionManager2.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])};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 _iterator2=GLOBAL_VISITOR_PROPS,_isArray2=Array.isArray(_iterator2),_i2=0,_iterator2=_isArray2?_iterator2:(0,_getIterator3.default)(_iterator2);;){var _ref2;if(_isArray2){if(_i2>=_iterator2.length)break;_ref2=_iterator2[_i2++]}else{_i2=_iterator2.next();if(_i2.done)break;_ref2=_i2.value}var key=_ref2;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"]},{"../store":24,"./file/options/option-manager":32,"babel-messages":76,"babel-runtime/core-js/get-iterator":138,"babel-runtime/helpers/classCallCheck":152,"babel-runtime/helpers/inherits":153,"babel-runtime/helpers/possibleConstructorReturn":154,"babel-traverse":160,"lodash/assign":524,"lodash/clone":527}],40:[function(require,module,exports){"use strict";exports.__esModule=true;exports.inspect=exports.inherits=undefined;var _getIterator2=require("babel-runtime/core-js/get-iterator");var _getIterator3=_interopRequireDefault(_getIterator2);var _util=require("util");Object.defineProperty(exports,"inherits",{enumerable:true,get:function get(){return _util.inherits}});Object.defineProperty(exports,"inspect",{enumerable:true,get:function get(){return _util.inspect}});exports.canCompile=canCompile;exports.list=list;exports.regexify=regexify;exports.arrayify=arrayify;exports.booleanify=booleanify;exports.shouldIgnore=shouldIgnore;var _escapeRegExp=require("lodash/escapeRegExp");var _escapeRegExp2=_interopRequireDefault(_escapeRegExp);var _startsWith=require("lodash/startsWith");var _startsWith2=_interopRequireDefault(_startsWith);var _isBoolean=require("lodash/isBoolean");var _isBoolean2=_interopRequireDefault(_isBoolean);var _minimatch=require("minimatch");var _minimatch2=_interopRequireDefault(_minimatch);var _includes=require("lodash/includes");var _includes2=_interopRequireDefault(_includes);var _isString=require("lodash/isString");var _isString2=_interopRequireDefault(_isString);var _isRegExp=require("lodash/isRegExp");var _isRegExp2=_interopRequireDefault(_isRegExp);var _path=require("path");var _path2=_interopRequireDefault(_path);var _slash=require("slash");var _slash2=_interopRequireDefault(_slash);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function canCompile(filename,altExts){var exts=altExts||canCompile.EXTENSIONS;var ext=_path2.default.extname(filename);return(0,_includes2.default)(exts,ext)}canCompile.EXTENSIONS=[".js",".jsx",".es6",".es"];function list(val){if(!val){return[]}else if(Array.isArray(val)){return val}else if(typeof val==="string"){return val.split(",")}else{return[val]}}function regexify(val){if(!val){return new RegExp(/.^/)}if(Array.isArray(val)){val=new RegExp(val.map(_escapeRegExp2.default).join("|"),"i")}if(typeof val==="string"){val=(0,_slash2.default)(val);if((0,_startsWith2.default)(val,"./")||(0,_startsWith2.default)(val,"*/"))val=val.slice(2);if((0,_startsWith2.default)(val,"**/"))val=val.slice(3);var regex=_minimatch2.default.makeRe(val,{nocase:true});return new RegExp(regex.source.slice(1,-1),"i")}if((0,_isRegExp2.default)(val)){return val}throw new TypeError("illegal type for regexify")}function arrayify(val,mapFn){if(!val)return[];if((0,_isBoolean2.default)(val))return arrayify([val],mapFn);if((0,_isString2.default)(val))return arrayify(list(val),mapFn);if(Array.isArray(val)){if(mapFn)val=val.map(mapFn);return val}return[val]}function booleanify(val){if(val==="true"||val==1){return true}if(val==="false"||val==0||!val){return false}return val}function shouldIgnore(filename){var ignore=arguments.length<=1||arguments[1]===undefined?[]:arguments[1];var only=arguments[2];filename=(0,_slash2.default)(filename);if(only){for(var _iterator=only,_isArray=Array.isArray(_iterator),_i=0,_iterator=_isArray?_iterator:(0,_getIterator3.default)(_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 pattern=_ref;if(_shouldIgnore(pattern,filename))return false}return true}else if(ignore.length){for(var _iterator2=ignore,_isArray2=Array.isArray(_iterator2),_i2=0,_iterator2=_isArray2?_iterator2:(0,_getIterator3.default)(_iterator2);;){var _ref2;if(_isArray2){if(_i2>=_iterator2.length)break;_ref2=_iterator2[_i2++]}else{_i2=_iterator2.next();if(_i2.done)break;_ref2=_i2.value}var _pattern=_ref2;if(_shouldIgnore(_pattern,filename))return true}}return false}function _shouldIgnore(pattern,filename){if(typeof pattern==="function"){return pattern(filename)}else{return pattern.test(filename)}}},{"babel-runtime/core-js/get-iterator":138,"lodash/escapeRegExp":535,"lodash/includes":546,"lodash/isBoolean":551,"lodash/isRegExp":560,"lodash/isString":561,"lodash/startsWith":575,minimatch:586,path:589,slash:673,util:691}],41:[function(require,module,exports){module.exports={_args:[[{raw:"babel-core@https://registry.npmjs.org/babel-core/-/babel-core-6.16.0.tgz",scope:null,escapedName:"babel-core",name:"babel-core",rawSpec:"https://registry.npmjs.org/babel-core/-/babel-core-6.16.0.tgz",spec:"https://registry.npmjs.org/babel-core/-/babel-core-6.16.0.tgz",type:"remote"},"/home/mike/dev/repl"]],_from:"babel-core@6.16.0",_id:"babel-core@6.16.0",_inCache:true,_location:"/babel-core",_phantomChildren:{},_requested:{raw:"babel-core@https://registry.npmjs.org/babel-core/-/babel-core-6.16.0.tgz",scope:null,escapedName:"babel-core",name:"babel-core",rawSpec:"https://registry.npmjs.org/babel-core/-/babel-core-6.16.0.tgz",spec:"https://registry.npmjs.org/babel-core/-/babel-core-6.16.0.tgz",type:"remote"},_requiredBy:["/","/babel-register","/babelify","/systemjs-builder"],_resolved:"https://registry.npmjs.org/babel-core/-/babel-core-6.16.0.tgz",_shasum:"cf8bbfdf0097c4146195d80d9ec96d73acf387d5",_shrinkwrap:null,_spec:"babel-core@https://registry.npmjs.org/babel-core/-/babel-core-6.16.0.tgz",_where:"/home/mike/dev/repl",author:{name:"Sebastian McKenzie",email:"sebmck@gmail.com"},dependencies:{"babel-code-frame":"^6.16.0","babel-generator":"^6.16.0","babel-helpers":"^6.16.0","babel-messages":"^6.8.0","babel-register":"^6.16.0","babel-runtime":"^6.9.1","babel-template":"^6.16.0","babel-traverse":"^6.16.0","babel-types":"^6.16.0",babylon:"^6.11.0","convert-source-map":"^1.1.0", +debug:"^2.1.1",json5:"^0.4.0",lodash:"^4.2.0",minimatch:"^3.0.2","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.9.0","babel-helper-transform-fixture-test-runner":"^6.16.0","babel-polyfill":"^6.16.0"},homepage:"https://babeljs.io/",keywords:["6to5","babel","classes","const","es6","harmony","let","modules","transpile","transpiler","var"],license:"MIT",name:"babel-core",optionalDependencies:{},readme:"# babel-core\n\n> Babel compiler core.\n\n## Install\n\n```\n$ npm install babel-core\n```\n\n## Usage\n\n```js\nimport babel from 'babel-core';\n\nconst code = `class Example {}`;\nconst result = babel.transform(code, { /* options */ });\n\nresult.code; // Generated code\nresult.map; // Sourcemap\nresult.ast; // AST\n```\n\nFor more in depth documentation see: http://babeljs.io/docs/usage/api/\n",readmeFilename:"README.md",repository:{type:"git",url:"https://github.com/babel/babel/tree/master/packages/babel-core"},scripts:{bench:"make bench",test:"make test"},version:"6.16.0"}},{}],42:[function(require,module,exports){"use strict";exports.__esModule=true;var _classCallCheck2=require("babel-runtime/helpers/classCallCheck");var _classCallCheck3=_interopRequireDefault(_classCallCheck2);var _trimEnd=require("lodash/trimEnd");var _trimEnd2=_interopRequireDefault(_trimEnd);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}var SPACES_RE=/^[ \t]+$/;var Buffer=function(){function Buffer(map){(0,_classCallCheck3.default)(this,Buffer);this._map=null;this._buf=[];this._last="";this._queue=[];this._position={line:1,column:0};this._sourcePosition={identifierName:null,line:null,column:null,filename:null};this._map=map}Buffer.prototype.get=function get(){this._flush();return{code:(0,_trimEnd2.default)(this._buf.join("")),map:this._map?this._map.get():null}};Buffer.prototype.append=function append(str){this._flush();var _sourcePosition=this._sourcePosition;var line=_sourcePosition.line;var column=_sourcePosition.column;var filename=_sourcePosition.filename;var identifierName=_sourcePosition.identifierName;this._append(str,line,column,identifierName,filename)};Buffer.prototype.queue=function queue(str){if(str==="\n")while(this._queue.length>0&&SPACES_RE.test(this._queue[0][0])){this._queue.shift()}var _sourcePosition2=this._sourcePosition;var line=_sourcePosition2.line;var column=_sourcePosition2.column;var filename=_sourcePosition2.filename;var identifierName=_sourcePosition2.identifierName;this._queue.unshift([str,line,column,identifierName,filename])};Buffer.prototype._flush=function _flush(){var item=void 0;while(item=this._queue.pop()){this._append.apply(this,item)}};Buffer.prototype._append=function _append(str,line,column,identifierName,filename){if(this._map&&str[0]!=="\n"){this._map.mark(this._position.line,this._position.column,line,column,identifierName,filename)}this._buf.push(str);this._last=str[str.length-1];for(var i=0;i0&&this._queue[0][0]==="\n")this._queue.shift()};Buffer.prototype.removeLastSemicolon=function removeLastSemicolon(){if(this._queue.length>0&&this._queue[0][0]===";")this._queue.shift()};Buffer.prototype.endsWith=function endsWith(suffix){if(suffix.length===1){var last=void 0;if(this._queue.length>0){var str=this._queue[0][0];last=str[str.length-1]}else{last=this._last}return last===suffix}var end=this._last+this._queue.reduce(function(acc,item){return item[0]+acc},"");if(suffix.length<=end.length){return end.slice(-suffix.length)===suffix}return false};Buffer.prototype.hasContent=function hasContent(){return this._queue.length>0||!!this._last};Buffer.prototype.source=function source(prop,loc){if(prop&&!loc)return;var pos=loc?loc[prop]:null;this._sourcePosition.identifierName=loc&&loc.identifierName||null;this._sourcePosition.line=pos?pos.line:null;this._sourcePosition.column=pos?pos.column:null;this._sourcePosition.filename=loc&&loc.filename||null};Buffer.prototype.withSource=function withSource(prop,loc,cb){if(!this._map)return cb();var originalLine=this._sourcePosition.line;var originalColumn=this._sourcePosition.column;var originalFilename=this._sourcePosition.filename;var originalIdentifierName=this._sourcePosition.identifierName;this.source(prop,loc);cb();this._sourcePosition.line=originalLine;this._sourcePosition.column=originalColumn;this._sourcePosition.filename=originalFilename;this._sourcePosition.identifierName=originalIdentifierName};Buffer.prototype.getCurrentColumn=function getCurrentColumn(){var extra=this._queue.reduce(function(acc,item){return item[0]+acc},"");var lastIndex=extra.lastIndexOf("\n");return lastIndex===-1?this._position.column+extra.length:extra.length-1-lastIndex};Buffer.prototype.getCurrentLine=function getCurrentLine(){var extra=this._queue.reduce(function(acc,item){return item[0]+acc},"");var count=0;for(var i=0;i")}this.space();this.print(node.returnType,node)}function FunctionTypeParam(node){this.print(node.name,node);if(node.optional)this.token("?");this.token(":");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.space();this.word("extends");this.space();this.printList(node.extends,node)}if(node.mixins&&node.mixins.length){this.space();this.word("mixins");this.space();this.printList(node.mixins,node)}this.space();this.print(node.body,node)}function InterfaceDeclaration(node){this.word("interface");this.space();this._interfaceish(node)}function andSeparator(){this.space();this.token("&");this.space()}function IntersectionTypeAnnotation(node){this.printJoin(node.types,node,{separator:andSeparator})}function MixedTypeAnnotation(){this.word("mixed")}function NullableTypeAnnotation(node){this.token("?");this.print(node.typeAnnotation,node)}function NumberTypeAnnotation(){this.word("number")}function StringTypeAnnotation(){this.word("string")}function ThisTypeAnnotation(){this.word("this")}function TupleTypeAnnotation(node){this.token("[");this.printList(node.types,node);this.token("]")}function TypeofTypeAnnotation(node){this.word("typeof");this.space();this.print(node.argument,node)}function TypeAlias(node){this.word("type");this.space();this.print(node.id,node);this.print(node.typeParameters,node);this.space();this.token("=");this.space();this.print(node.right,node);this.semicolon()}function TypeAnnotation(node){this.token(":");this.space();if(node.optional)this.token("?");this.print(node.typeAnnotation,node)}function TypeParameter(node){if(node.variance==="plus"){this.token("+")}else if(node.variance==="minus"){this.token("-")}this.word(node.name);if(node.bound){this.print(node.bound,node)}if(node.default){this.space();this.token("=");this.space();this.print(node.default,node)}}function TypeParameterInstantiation(node){this.token("<");this.printList(node.params,node,{});this.token(">")}exports.TypeParameterDeclaration=TypeParameterInstantiation;function ObjectTypeAnnotation(node){var _this=this;if(node.exact){this.token("{|")}else{this.token("{")}var props=node.properties.concat(node.callProperties,node.indexers);if(props.length){this.space();this.printJoin(props,node,{indent:true,statement:true,iterator:function iterator(){if(props.length!==1){_this.semicolon();_this.space()}}});this.space()}if(node.exact){this.token("|}")}else{this.token("}")}}function ObjectTypeCallProperty(node){if(node.static){this.word("static");this.space()}this.print(node.value,node)}function ObjectTypeIndexer(node){if(node.static){this.word("static");this.space()}this.token("[");this.print(node.id,node);this.token(":");this.space();this.print(node.key,node);this.token("]");this.token(":");this.space();this.print(node.value,node)}function ObjectTypeProperty(node){if(node.static){this.word("static");this.space()}this.print(node.key,node);if(node.optional)this.token("?");this.token(":");this.space();this.print(node.value,node)}function QualifiedTypeIdentifier(node){this.print(node.qualification,node);this.token(".");this.print(node.id,node)}function orSeparator(){this.space();this.token("|");this.space()}function UnionTypeAnnotation(node){this.printJoin(node.types,node,{separator:orSeparator})}function TypeCastExpression(node){this.token("(");this.print(node.expression,node);this.print(node.typeAnnotation,node);this.token(")")}function VoidTypeAnnotation(){this.word("void")}},{"./types":52}],47:[function(require,module,exports){"use strict";exports.__esModule=true;var _getIterator2=require("babel-runtime/core-js/get-iterator");var _getIterator3=_interopRequireDefault(_getIterator2);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 _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function JSXAttribute(node){this.print(node.name,node);if(node.value){this.token("=");this.print(node.value,node)}}function JSXIdentifier(node){this.word(node.name)}function JSXNamespacedName(node){this.print(node.namespace,node);this.token(":");this.print(node.name,node)}function JSXMemberExpression(node){this.print(node.object,node);this.token(".");this.print(node.property,node)}function JSXSpreadAttribute(node){this.token("{");this.token("...");this.print(node.argument,node);this.token("}")}function JSXExpressionContainer(node){this.token("{");this.print(node.expression,node);this.token("}")}function JSXText(node){this.token(node.value)}function JSXElement(node){var open=node.openingElement;this.print(open,node);if(open.selfClosing)return;this.indent();for(var _iterator=node.children,_isArray=Array.isArray(_iterator),_i=0,_iterator=_isArray?_iterator:(0,_getIterator3.default)(_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 child=_ref;this.print(child,node)}this.dedent();this.print(node.closingElement,node)}function spaceSeparator(){this.space()}function JSXOpeningElement(node){this.token("<");this.print(node.name,node);if(node.attributes.length>0){this.space();this.printJoin(node.attributes,node,{separator:spaceSeparator})}if(node.selfClosing){this.space();this.token("/>")}else{this.token(">")}}function JSXClosingElement(node){this.token("")}function JSXEmptyExpression(){}},{"babel-runtime/core-js/get-iterator":138}],48:[function(require,module,exports){"use strict";exports.__esModule=true;exports.FunctionDeclaration=undefined;exports._params=_params;exports._method=_method;exports.FunctionExpression=FunctionExpression;exports.ArrowFunctionExpression=ArrowFunctionExpression;var _babelTypes=require("babel-types");var t=_interopRequireWildcard(_babelTypes);function _interopRequireWildcard(obj){if(obj&&obj.__esModule){return obj}else{var newObj={};if(obj!=null){for(var key in obj){if(Object.prototype.hasOwnProperty.call(obj,key))newObj[key]=obj[key]}}newObj.default=obj;return newObj}}function _params(node){var _this=this;this.print(node.typeParameters,node);this.token("(");this.printList(node.params,node,{iterator:function iterator(node){if(node.optional)_this.token("?");_this.print(node.typeAnnotation,node)}});this.token(")");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.token("*")}}if(kind==="get"||kind==="set"){this.word(kind);this.space()}if(node.async){this.word("async");this.space()}if(node.computed){this.token("[");this.print(key,node);this.token("]")}else{this.print(key,node)}this._params(node);this.space();this.print(node.body,node)}function FunctionExpression(node){if(node.async){this.word("async");this.space()}this.word("function");if(node.generator)this.token("*");if(node.id){this.space();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.word("async");this.space()}var firstParam=node.params[0];if(node.params.length===1&&t.isIdentifier(firstParam)&&!hasTypes(node,firstParam)){this.print(firstParam,node)}else{this._params(node)}this.space();this.token("=>");this.space();this.print(node.body,node)}function hasTypes(node,param){return node.typeParameters||node.returnType||param.typeAnnotation||param.optional||param.trailingComments}},{"babel-types":193}],49:[function(require,module,exports){"use strict";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 _interopRequireWildcard(obj){if(obj&&obj.__esModule){return obj}else{var newObj={};if(obj!=null){for(var key in obj){if(Object.prototype.hasOwnProperty.call(obj,key))newObj[key]=obj[key]}}newObj.default=obj;return newObj}}function ImportSpecifier(node){this.print(node.imported,node);if(node.local&&node.local.name!==node.imported.name){this.space();this.word("as");this.space();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.space();this.word("as");this.space();this.print(node.exported,node)}}function ExportNamespaceSpecifier(node){this.token("*");this.space();this.word("as");this.space();this.print(node.exported,node)}function ExportAllDeclaration(node){this.word("export");this.space();this.token("*");if(node.exported){this.space();this.word("as");this.space();this.print(node.exported,node)}this.space();this.word("from");this.space();this.print(node.source,node);this.semicolon()}function ExportNamedDeclaration(){this.word("export");this.space();ExportDeclaration.apply(this,arguments)}function ExportDefaultDeclaration(){this.word("export");this.space();this.word("default");this.space();ExportDeclaration.apply(this,arguments)}function ExportDeclaration(node){if(node.declaration){var declar=node.declaration;this.print(declar,node);if(!t.isStatement(declar))this.semicolon()}else{if(node.exportKind==="type"){this.word("type");this.space()}var specifiers=node.specifiers.slice(0);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.token(",");this.space()}}else{break}}if(specifiers.length||!specifiers.length&&!hasSpecial){this.token("{");if(specifiers.length){this.space();this.printList(specifiers,node);this.space()}this.token("}")}if(node.source){this.space();this.word("from");this.space();this.print(node.source,node)}this.semicolon()}}function ImportDeclaration(node){this.word("import");this.space();if(node.importKind==="type"||node.importKind==="typeof"){this.word(node.importKind);this.space()}var specifiers=node.specifiers.slice(0);if(specifiers&&specifiers.length){while(true){var first=specifiers[0];if(t.isImportDefaultSpecifier(first)||t.isImportNamespaceSpecifier(first)){this.print(specifiers.shift(),node);if(specifiers.length){this.token(",");this.space()}}else{break}}if(specifiers.length){this.token("{");this.space();this.printList(specifiers,node);this.space();this.token("}")}this.space();this.word("from");this.space()}this.print(node.source,node);this.semicolon()}function ImportNamespaceSpecifier(node){this.token("*");this.space();this.word("as");this.space();this.print(node.local,node)}},{"babel-types":193}],50:[function(require,module,exports){"use strict";exports.__esModule=true;exports.ThrowStatement=exports.BreakStatement=exports.ReturnStatement=exports.ContinueStatement=exports.ForAwaitStatement=exports.ForOfStatement=exports.ForInStatement=undefined;var _getIterator2=require("babel-runtime/core-js/get-iterator");var _getIterator3=_interopRequireDefault(_getIterator2);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 _babelTypes=require("babel-types");var t=_interopRequireWildcard(_babelTypes);function _interopRequireWildcard(obj){if(obj&&obj.__esModule){return obj}else{var newObj={};if(obj!=null){for(var key in obj){if(Object.prototype.hasOwnProperty.call(obj,key))newObj[key]=obj[key]}}newObj.default=obj;return newObj}}function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function WithStatement(node){this.word("with");this.space();this.token("(");this.print(node.object,node);this.token(")");this.printBlock(node)}function IfStatement(node){this.word("if");this.space();this.token("(");this.print(node.test,node);this.token(")");this.space();var needsBlock=node.alternate&&t.isIfStatement(getLastStatement(node.consequent));if(needsBlock){this.token("{");this.newline();this.indent()}this.printAndIndentOnComments(node.consequent,node);if(needsBlock){this.dedent();this.newline();this.token("}")}if(node.alternate){if(this.endsWith("}"))this.space();this.word("else");this.space();this.printAndIndentOnComments(node.alternate,node)}}function getLastStatement(statement){if(!t.isStatement(statement.body))return statement;return getLastStatement(statement.body)}function ForStatement(node){this.word("for");this.space();this.token("(");this.inForStatementInitCounter++;this.print(node.init,node);this.inForStatementInitCounter--;this.token(";");if(node.test){this.space();this.print(node.test,node)}this.token(";");if(node.update){this.space();this.print(node.update,node)}this.token(")");this.printBlock(node)}function WhileStatement(node){this.word("while");this.space();this.token("(");this.print(node.test,node);this.token(")");this.printBlock(node)}var buildForXStatement=function buildForXStatement(op){return function(node){this.word("for");this.space();if(op==="await"){this.word("await");this.space();op="of"}this.token("(");this.print(node.left,node);this.space();this.word(op);this.space();this.print(node.right,node);this.token(")");this.printBlock(node)}};var ForInStatement=exports.ForInStatement=buildForXStatement("in");var ForOfStatement=exports.ForOfStatement=buildForXStatement("of");var ForAwaitStatement=exports.ForAwaitStatement=buildForXStatement("await");function DoWhileStatement(node){this.word("do");this.space();this.print(node.body,node);this.space();this.word("while");this.space();this.token("(");this.print(node.test,node);this.token(")"); +this.semicolon()}function buildLabelStatement(prefix){var key=arguments.length<=1||arguments[1]===undefined?"label":arguments[1];return function(node){this.word(prefix);var label=node[key];if(label){this.space();var terminatorState=this.startTerminatorless();this.print(label,node);this.endTerminatorless(terminatorState)}this.semicolon()}}var ContinueStatement=exports.ContinueStatement=buildLabelStatement("continue");var ReturnStatement=exports.ReturnStatement=buildLabelStatement("return","argument");var BreakStatement=exports.BreakStatement=buildLabelStatement("break");var ThrowStatement=exports.ThrowStatement=buildLabelStatement("throw","argument");function LabeledStatement(node){this.print(node.label,node);this.token(":");this.space();this.print(node.body,node)}function TryStatement(node){this.word("try");this.space();this.print(node.block,node);this.space();if(node.handlers){this.print(node.handlers[0],node)}else{this.print(node.handler,node)}if(node.finalizer){this.space();this.word("finally");this.space();this.print(node.finalizer,node)}}function CatchClause(node){this.word("catch");this.space();this.token("(");this.print(node.param,node);this.token(")");this.space();this.print(node.body,node)}function SwitchStatement(node){this.word("switch");this.space();this.token("(");this.print(node.discriminant,node);this.token(")");this.space();this.token("{");this.printSequence(node.cases,node,{indent:true,addNewlines:function addNewlines(leading,cas){if(!leading&&node.cases[node.cases.length-1]===cas)return-1}});this.token("}")}function SwitchCase(node){if(node.test){this.word("case");this.space();this.print(node.test,node);this.token(":")}else{this.word("default");this.token(":")}if(node.consequent.length){this.newline();this.printSequence(node.consequent,node,{indent:true})}}function DebuggerStatement(){this.word("debugger");this.semicolon()}function variableDeclarationIdent(){this.token(",");this.newline();if(this.endsWith("\n"))for(var i=0;i<4;i++){this.space(true)}}function constDeclarationIdent(){this.token(",");this.newline();if(this.endsWith("\n"))for(var i=0;i<6;i++){this.space(true)}}function VariableDeclaration(node,parent){this.word(node.kind);this.space();var hasInits=false;if(!t.isFor(parent)){for(var _iterator=node.declarations,_isArray=Array.isArray(_iterator),_i=0,_iterator=_isArray?_iterator:(0,_getIterator3.default)(_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 declar=_ref;if(declar.init){hasInits=true}}}var separator=void 0;if(hasInits){separator=node.kind==="const"?constDeclarationIdent:variableDeclarationIdent}this.printList(node.declarations,node,{separator:separator});if(t.isFor(parent)){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.token("=");this.space();this.print(node.init,node)}}},{"babel-runtime/core-js/get-iterator":138,"babel-types":193}],51:[function(require,module,exports){"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,parent){var isFirst=parent.quasis[0]===node;var isLast=parent.quasis[parent.quasis.length-1]===node;var value=(isFirst?"`":"}")+node.value.raw+(isLast?"`":"${");if(!isFirst)this.space();this.token(value);if(!isLast)this.space()}function TemplateLiteral(node){var quasis=node.quasis;for(var i=0;i0)this.space();this.print(elem,node);if(i=0||value.indexOf("@preserve")>=0}}if(format.compact==="auto"){format.compact=code.length>1e5;if(format.compact){console.error("[BABEL] "+messages.get("codeGeneratorDeopt",opts.filename,"100KB"))}}if(format.compact){format.indent.adjustMultilineComment=false}return format}function findCommonStringDelimiter(code,tokens){var DEFAULT_STRING_DELIMITER="double";if(!code){return DEFAULT_STRING_DELIMITER}var occurences={single:0,double:0};var checked=0;for(var i=0;i=3)break}if(occurences.single>occurences.double){return"single"}else{return"double"}}var CodeGenerator=exports.CodeGenerator=function(){function CodeGenerator(ast,opts,code){(0,_classCallCheck3.default)(this,CodeGenerator);this._generator=new Generator(ast,opts,code)}CodeGenerator.prototype.generate=function generate(){return this._generator.generate()};return CodeGenerator}()},{"./printer":57,"./source-map":58,"babel-messages":76,"babel-runtime/helpers/classCallCheck":152,"babel-runtime/helpers/inherits":153,"babel-runtime/helpers/possibleConstructorReturn":154,"detect-indent":343}],54:[function(require,module,exports){"use strict";exports.__esModule=true;var _getIterator2=require("babel-runtime/core-js/get-iterator");var _getIterator3=_interopRequireDefault(_getIterator2);var _keys=require("babel-runtime/core-js/object/keys");var _keys2=_interopRequireDefault(_keys);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 _interopRequireWildcard(obj){if(obj&&obj.__esModule){return obj}else{var newObj={};if(obj!=null){for(var key in obj){if(Object.prototype.hasOwnProperty.call(obj,key))newObj[key]=obj[key]}}newObj.default=obj;return newObj}}function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function expandAliases(obj){var newObj={};function add(type,func){var fn=newObj[type];newObj[type]=fn?function(node,parent,stack){var result=fn(node,parent,stack);return result==null?func(node,parent,stack):result}:func}for(var _iterator=(0,_keys2.default)(obj),_isArray=Array.isArray(_iterator),_i=0,_iterator=_isArray?_iterator:(0,_getIterator3.default)(_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 type=_ref;var aliases=t.FLIPPED_ALIAS_KEYS[type];if(aliases){for(var _iterator2=aliases,_isArray2=Array.isArray(_iterator2),_i2=0,_iterator2=_isArray2?_iterator2:(0,_getIterator3.default)(_iterator2);;){var _ref2;if(_isArray2){if(_i2>=_iterator2.length)break;_ref2=_iterator2[_i2++]}else{_i2=_iterator2.next();if(_i2.done)break;_ref2=_i2.value}var alias=_ref2;add(alias,obj[type])}}else{add(type,obj[type])}}return newObj}var expandedParens=expandAliases(parens);var expandedWhitespaceNodes=expandAliases(_whitespace2.default.nodes);var expandedWhitespaceList=expandAliases(_whitespace2.default.list);function find(obj,node,parent,printStack){var fn=obj[node.type];return fn?fn(node,parent,printStack):null}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 needsWhitespace(node,parent,type){if(!node)return 0;if(t.isExpressionStatement(node)){node=node.expression}var linesInfo=find(expandedWhitespaceNodes,node,parent);if(!linesInfo){var items=find(expandedWhitespaceList,node,parent);if(items){for(var i=0;i":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){return true}return false}function ObjectExpression(node,parent,printStack){return isFirstInStatement(printStack,{considerArrow: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}if(parentPos===nodePos&&parent.right===node&&!t.isLogicalExpression(parent)){return true}}return false}function BinaryExpression(node,parent){if(node.operator==="in"){if(t.isVariableDeclarator(parent)){return true}if(t.isFor(parent)){return true}}return false}function SequenceExpression(node,parent){if(t.isForStatement(parent)){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}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,printStack){return isFirstInStatement(printStack,{considerDefaultExports:true})}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){return isFirstInStatement(printStack,{considerDefaultExports:true})}function ArrowFunctionExpression(node,parent){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)}}function isFirstInStatement(printStack){var _ref=arguments.length<=1||arguments[1]===undefined?{}:arguments[1];var _ref$considerArrow=_ref.considerArrow;var considerArrow=_ref$considerArrow===undefined?false:_ref$considerArrow;var _ref$considerDefaultE=_ref.considerDefaultExports;var considerDefaultExports=_ref$considerDefaultE===undefined?false:_ref$considerDefaultE;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(considerDefaultExports&&t.isExportDefaultDeclaration(parent,{declaration: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}},{"babel-types":193}],56:[function(require,module,exports){"use strict";var _isBoolean=require("lodash/isBoolean");var _isBoolean2=_interopRequireDefault(_isBoolean);var _each=require("lodash/each");var _each2=_interopRequireDefault(_each);var _map=require("lodash/map");var _map2=_interopRequireDefault(_map);var _babelTypes=require("babel-types");var t=_interopRequireWildcard(_babelTypes);function _interopRequireWildcard(obj){if(obj&&obj.__esModule){return obj}else{var newObj={};if(obj!=null){for(var key in obj){if(Object.prototype.hasOwnProperty.call(obj,key))newObj[key]=obj[key]}}newObj.default=obj;return newObj}}function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}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}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)}exports.nodes={AssignmentExpression:function AssignmentExpression(node){var state=crawl(node.right);if(state.hasCall&&state.hasHelper||state.hasFunction){return{before:state.hasFunction,after:true}}},SwitchCase:function SwitchCase(node,parent){return{before:node.consequent.length||parent.cases[0]===node}},LogicalExpression:function LogicalExpression(node){if(t.isFunction(node.left)||t.isFunction(node.right)){return{after:true}}},Literal:function Literal(node){if(node.value==="use strict"){return{after:true}}},CallExpression:function CallExpression(node){if(t.isFunction(node.callee)||isHelper(node)){return{before:true,after:true}}},VariableDeclaration:function VariableDeclaration(node){for(var i=0;i0?new _whitespace2.default(tokens):null}Printer.prototype.generate=function generate(ast){this.print(ast);this._maybeAddAuxComment();return this._buf.get()};Printer.prototype.indent=function indent(){if(this.format.compact||this.format.concise)return;this._indent++};Printer.prototype.dedent=function dedent(){if(this.format.compact||this.format.concise)return;this._indent--};Printer.prototype.semicolon=function semicolon(){var force=arguments.length<=0||arguments[0]===undefined?false:arguments[0];this._maybeAddAuxComment();this._append(";",!force)};Printer.prototype.rightBrace=function rightBrace(){if(this.format.minified){this._buf.removeLastSemicolon()}this.token("}")};Printer.prototype.space=function space(){var force=arguments.length<=0||arguments[0]===undefined?false:arguments[0];if(this.format.compact)return;if(this._buf.hasContent()&&!this.endsWith(" ")&&!this.endsWith("\n")||force){this._space()}};Printer.prototype.word=function word(str){if(this._endsWithWord)this._space();this._maybeAddAuxComment();this._append(str);this._endsWithWord=true};Printer.prototype.number=function number(str){this.word(str);this._endsWithInteger=(0,_isInteger2.default)(+str)&&!NON_DECIMAL_LITERAL.test(str)&&!SCIENTIFIC_NOTATION.test(str)&&!ZERO_DECIMAL_INTEGER.test(str)&&str[str.length-1]!=="."};Printer.prototype.token=function token(str){if(str==="--"&&this.endsWith("!")||str[0]==="+"&&this.endsWith("+")||str[0]==="-"&&this.endsWith("-")||str[0]==="."&&this._endsWithInteger){this._space()}this._maybeAddAuxComment();this._append(str)};Printer.prototype.newline=function newline(i){if(this.format.retainLines||this.format.compact)return;if(this.format.concise){this.space();return}if(this.endsWith("\n\n"))return;if(typeof i!=="number")i=1;i=Math.min(2,i);if(this.endsWith("{\n")||this.endsWith(":\n"))i--;if(i<=0)return;for(var j=0;j=_iterator.length)break;_ref=_iterator[_i++]}else{_i=_iterator.next();if(_i.done)break;_ref=_i.value}var _comment3=_ref;this._printComment(_comment3)}};return Printer}();exports.default=Printer;function commaSeparator(){this.token(",");this.space()}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];(0,_assign2.default)(Printer.prototype,generator)}module.exports=exports["default"]},{"./buffer":42,"./generators/base":43,"./generators/classes":44,"./generators/expressions":45,"./generators/flow":46,"./generators/jsx":47,"./generators/methods":48,"./generators/modules":49,"./generators/statements":50,"./generators/template-literals":51,"./generators/types":52,"./node":54,"./whitespace":59,"babel-runtime/core-js/get-iterator":138,"babel-runtime/core-js/json/stringify":139,"babel-runtime/core-js/object/assign":142,"babel-runtime/core-js/weak-set":151,"babel-runtime/helpers/classCallCheck":152,"babel-types":193,"lodash/find":537,"lodash/findLast":539,"lodash/isInteger":554,"lodash/repeat":573}],58:[function(require,module,exports){"use strict";exports.__esModule=true;var _keys=require("babel-runtime/core-js/object/keys");var _keys2=_interopRequireDefault(_keys);var _typeof2=require("babel-runtime/helpers/typeof");var _typeof3=_interopRequireDefault(_typeof2);var _classCallCheck2=require("babel-runtime/helpers/classCallCheck");var _classCallCheck3=_interopRequireDefault(_classCallCheck2);var _sourceMap=require("source-map");var _sourceMap2=_interopRequireDefault(_sourceMap);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}var SourceMap=function(){function SourceMap(opts,code){var _this=this;(0,_classCallCheck3.default)(this,SourceMap);this._opts=opts;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==="undefined"?"undefined":(0,_typeof3.default)(code))==="object"){(0,_keys2.default)(code).forEach(function(sourceFileName){_this._map.setSourceContent(sourceFileName,code[sourceFileName])})}}SourceMap.prototype.get=function get(){return this._map.toJSON()};SourceMap.prototype.mark=function mark(generatedLine,generatedColumn,line,column,identifierName,filename){if(this._lastGenLine!==generatedLine&&line===null)return;if(this._lastGenLine===generatedLine&&this._lastSourceLine===line&&this._lastSourceColumn===column){return}this._lastGenLine=generatedLine;this._lastSourceLine=line;this._lastSourceColumn=column;this._map.addMapping({name:identifierName,generated:{line:generatedLine,column:generatedColumn},source:line==null?null:filename||this._opts.sourceFileName,original:line==null?null:{line:line,column:column}})};return SourceMap}();exports.default=SourceMap;module.exports=exports["default"]},{"babel-runtime/core-js/object/keys":145,"babel-runtime/helpers/classCallCheck":152,"babel-runtime/helpers/typeof":155,"source-map":684}],59:[function(require,module,exports){"use strict";exports.__esModule=true;var _classCallCheck2=require("babel-runtime/helpers/classCallCheck");var _classCallCheck3=_interopRequireDefault(_classCallCheck2);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}var Whitespace=function(){function Whitespace(tokens){(0,_classCallCheck3.default)(this,Whitespace);this.tokens=tokens;this.used={}}Whitespace.prototype.getNewlinesBefore=function getNewlinesBefore(node){var startToken=void 0;var endToken=void 0;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)};Whitespace.prototype.getNewlinesAfter=function getNewlinesAfter(node){var startToken=void 0;var endToken=void 0;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{return this._getNewlinesBetween(startToken,endToken)}};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)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"]},{"babel-runtime/helpers/classCallCheck":152}],60:[function(require,module,exports){"use strict";exports.__esModule=true;var _getIterator2=require("babel-runtime/core-js/get-iterator");var _getIterator3=_interopRequireDefault(_getIterator2);exports.default=bindifyDecorators;var _babelTypes=require("babel-types");var t=_interopRequireWildcard(_babelTypes);function _interopRequireWildcard(obj){if(obj&&obj.__esModule){return obj}else{var newObj={};if(obj!=null){for(var key in obj){if(Object.prototype.hasOwnProperty.call(obj,key))newObj[key]=obj[key]}}newObj.default=obj;return newObj}}function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function bindifyDecorators(decorators){for(var _iterator=decorators,_isArray=Array.isArray(_iterator),_i=0,_iterator=_isArray?_iterator:(0,_getIterator3.default)(_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 decoratorPath=_ref;var decorator=decoratorPath.node;var expression=decorator.expression;if(!t.isMemberExpression(expression))continue;var temp=decoratorPath.scope.maybeGenerateMemoised(expression.object);var ref=void 0;var nodes=[];if(temp){ref=temp;nodes.push(t.assignmentExpression("=",temp,expression.object))}else{ref=expression.object}nodes.push(t.callExpression(t.memberExpression(t.memberExpression(ref,expression.property,expression.computed),t.identifier("bind")),[ref]));if(nodes.length===1){decorator.expression=nodes[0]}else{decorator.expression=t.sequenceExpression(nodes)}}}module.exports=exports["default"]},{"babel-runtime/core-js/get-iterator":138,"babel-types":193}],61:[function(require,module,exports){"use strict";exports.__esModule=true;exports.default=function(opts){var visitor={};function isAssignment(node){return node&&node.operator===opts.operator+"="}function buildAssignment(left,right){return t.assignmentExpression("=",left,right)}visitor.ExpressionStatement=function(path,file){if(path.isCompletionRecord())return;var expr=path.node.expression;if(!isAssignment(expr))return;var nodes=[];var exploded=(0,_babelHelperExplodeAssignableExpression2.default)(expr.left,nodes,file,path.scope,true);nodes.push(t.expressionStatement(buildAssignment(exploded.ref,opts.build(exploded.uid,expr.right))));path.replaceWithMultiple(nodes)};visitor.AssignmentExpression=function(path,file){var node=path.node;var scope=path.scope;if(!isAssignment(node))return;var nodes=[];var exploded=(0,_babelHelperExplodeAssignableExpression2.default)(node.left,nodes,file,scope);nodes.push(buildAssignment(exploded.ref,opts.build(exploded.uid,node.right)));path.replaceWithMultiple(nodes)};visitor.BinaryExpression=function(path){var node=path.node;if(node.operator===opts.operator){path.replaceWith(opts.build(node.left,node.right))}};return visitor};var _babelHelperExplodeAssignableExpression=require("babel-helper-explode-assignable-expression");var _babelHelperExplodeAssignableExpression2=_interopRequireDefault(_babelHelperExplodeAssignableExpression);var _babelTypes=require("babel-types");var t=_interopRequireWildcard(_babelTypes);function _interopRequireWildcard(obj){if(obj&&obj.__esModule){return obj}else{var newObj={};if(obj!=null){for(var key in obj){if(Object.prototype.hasOwnProperty.call(obj,key))newObj[key]=obj[key]}}newObj.default=obj;return newObj}}function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}module.exports=exports["default"]},{"babel-helper-explode-assignable-expression":64,"babel-types":193}],62:[function(require,module,exports){"use strict";exports.__esModule=true;exports.default=function(path){var scope=arguments.length<=1||arguments[1]===undefined?path.scope:arguments[1];var node=path.node;var container=t.functionExpression(null,[],node.body,node.generator,node.async);var callee=container;var args=[];(0,_babelHelperHoistVariables2.default)(path,function(id){return scope.push({id:id})});var state={foundThis:false,foundArguments:false};path.traverse(visitor,state);if(state.foundArguments){callee=t.memberExpression(container,t.identifier("apply"));args=[];if(state.foundThis){args.push(t.thisExpression())}if(state.foundArguments){if(!state.foundThis)args.push(t.nullLiteral());args.push(t.identifier("arguments"))}}var call=t.callExpression(callee,args);if(node.generator)call=t.yieldExpression(call,true);return t.returnStatement(call)};var _babelHelperHoistVariables=require("babel-helper-hoist-variables");var _babelHelperHoistVariables2=_interopRequireDefault(_babelHelperHoistVariables);var _babelTypes=require("babel-types");var t=_interopRequireWildcard(_babelTypes);function _interopRequireWildcard(obj){if(obj&&obj.__esModule){return obj}else{var newObj={};if(obj!=null){for(var key in obj){if(Object.prototype.hasOwnProperty.call(obj,key))newObj[key]=obj[key]}}newObj.default=obj;return newObj}}function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}var visitor={enter:function enter(path,state){if(path.isThisExpression()){state.foundThis=true}if(path.isReferencedIdentifier({name:"arguments"})){state.foundArguments=true}},Function:function Function(path){path.skip()}};module.exports=exports["default"]},{"babel-helper-hoist-variables":68,"babel-types":193}],63:[function(require,module,exports){"use strict";exports.__esModule=true;exports.push=push;exports.hasComputed=hasComputed;exports.toComputedObjectFromClass=toComputedObjectFromClass;exports.toClassObject=toClassObject;exports.toDefineObject=toDefineObject;var _babelHelperFunctionName=require("babel-helper-function-name");var _babelHelperFunctionName2=_interopRequireDefault(_babelHelperFunctionName);var _each=require("lodash/each");var _each2=_interopRequireDefault(_each);var _has=require("lodash/has");var _has2=_interopRequireDefault(_has);var _babelTypes=require("babel-types");var t=_interopRequireWildcard(_babelTypes);function _interopRequireWildcard(obj){if(obj&&obj.__esModule){return obj}else{var newObj={};if(obj!=null){for(var key in obj){if(Object.prototype.hasOwnProperty.call(obj,key))newObj[key]=obj[key]}}newObj.default=obj;return newObj}}function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function toKind(node){if(t.isClassMethod(node)||t.isObjectMethod(node)){if(node.kind==="get"||node.kind==="set"){return node.kind}}return"value"}function push(mutatorMap,node,kind,file,scope){var alias=t.toKeyAlias(node);var map={};if((0,_has2.default)(mutatorMap,alias))map=mutatorMap[alias];mutatorMap[alias]=map;map._inherits=map._inherits||[];map._inherits.push(node);map._key=node.key;if(node.computed){map._computed=true}if(node.decorators){var decorators=map.decorators=map.decorators||t.arrayExpression([]);decorators.elements=decorators.elements.concat(node.decorators.map(function(dec){return dec.expression}).reverse())}if(map.value||map.initializer){throw file.buildCodeFrameError(node,"Key conflict with sibling node")}var key=void 0,value=void 0;if(t.isObjectProperty(node)||t.isObjectMethod(node)||t.isClassMethod(node)){key=t.toComputedKey(node,node.key)}if(t.isObjectProperty(node)||t.isClassProperty(node)){value=node.value}else if(t.isObjectMethod(node)||t.isClassMethod(node)){value=t.functionExpression(null,node.params,node.body,node.generator,node.async)}var inheritedKind=toKind(node);if(!kind||inheritedKind!=="value"){kind=inheritedKind}if(scope&&t.isStringLiteral(key)&&(kind==="value"||kind==="initializer")&&t.isFunctionExpression(value)){value=(0,_babelHelperFunctionName2.default)({id:key,node:value,scope:scope})}if(value){t.inheritsComments(value,node);map[kind]=value}return map}function hasComputed(mutatorMap){for(var key in mutatorMap){if(mutatorMap[key]._computed){return true}}return false}function toComputedObjectFromClass(obj){var objExpr=t.arrayExpression([]);for(var i=0;i=_iterator.length)break;_ref=_iterator[_i++]}else{_i=_iterator.next();if(_i.done)break;_ref=_i.value}var path=_ref;maybeMemoise(path)}}maybeMemoise(classPath.get("superClass"));memoiseDecorators(classPath.get("decorators"),true);var methods=classPath.get("body.body");for(var _iterator2=methods,_isArray2=Array.isArray(_iterator2),_i2=0,_iterator2=_isArray2?_iterator2:(0,_getIterator3.default)(_iterator2);;){var _ref2;if(_isArray2){if(_i2>=_iterator2.length)break;_ref2=_iterator2[_i2++]}else{_i2=_iterator2.next();if(_i2.done)break;_ref2=_i2.value}var methodPath=_ref2;if(methodPath.is("computed")){maybeMemoise(methodPath.get("key"))}if(methodPath.has("decorators")){memoiseDecorators(classPath.get("decorators"))}}if(memoisedExpressions){classPath.insertBefore(memoisedExpressions.map(function(expr){return t.expressionStatement(expr)}))}};var _babelHelperBindifyDecorators=require("babel-helper-bindify-decorators");var _babelHelperBindifyDecorators2=_interopRequireDefault(_babelHelperBindifyDecorators);var _babelTypes=require("babel-types");var t=_interopRequireWildcard(_babelTypes);function _interopRequireWildcard(obj){if(obj&&obj.__esModule){return obj}else{var newObj={};if(obj!=null){for(var key in obj){if(Object.prototype.hasOwnProperty.call(obj,key))newObj[key]=obj[key]}}newObj.default=obj;return newObj}}function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}module.exports=exports["default"]},{"babel-helper-bindify-decorators":60,"babel-runtime/core-js/get-iterator":138,"babel-types":193}],66:[function(require,module,exports){"use strict";exports.__esModule=true;exports.default=function(_ref){var node=_ref.node;var parent=_ref.parent;var scope=_ref.scope;var id=_ref.id;if(node.id)return;if((t.isObjectProperty(parent)||t.isObjectMethod(parent,{kind:"method"}))&&(!parent.computed||t.isLiteral(parent.key))){id=parent.key}else if(t.isVariableDeclarator(parent)){id=parent.id;if(t.isIdentifier(id)){var binding=scope.parent.getBinding(id.name);if(binding&&binding.constant&&scope.getBinding(id.name)===binding){node.id=id;node.id[t.NOT_LOCAL_BINDING]=true;return}}}else if(t.isAssignmentExpression(parent)){id=parent.left}else if(!id){return}var name=void 0;if(id&&t.isLiteral(id)){name=id.value}else if(id&&t.isIdentifier(id)){name=id.name}else{return}name=t.toBindingIdentifierName(name);id=t.identifier(name);id[t.NOT_LOCAL_BINDING]=true;var state=visit(node,name,scope);return wrap(state,node,id,scope)||node};var _babelHelperGetFunctionArity=require("babel-helper-get-function-arity");var _babelHelperGetFunctionArity2=_interopRequireDefault(_babelHelperGetFunctionArity);var _babelTemplate=require("babel-template");var _babelTemplate2=_interopRequireDefault(_babelTemplate);var _babelTypes=require("babel-types");var t=_interopRequireWildcard(_babelTypes);function _interopRequireWildcard(obj){if(obj&&obj.__esModule){return obj}else{var newObj={};if(obj!=null){for(var key in obj){if(Object.prototype.hasOwnProperty.call(obj,key))newObj[key]=obj[key]}}newObj.default=obj;return newObj}}function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}var buildPropertyMethodAssignmentWrapper=(0,_babelTemplate2.default)("\n (function (FUNCTION_KEY) {\n function FUNCTION_ID() {\n return FUNCTION_KEY.apply(this, arguments);\n }\n\n FUNCTION_ID.toString = function () {\n return FUNCTION_KEY.toString();\n }\n\n return FUNCTION_ID;\n })(FUNCTION)\n");var buildGeneratorPropertyMethodAssignmentWrapper=(0,_babelTemplate2.default)("\n (function (FUNCTION_KEY) {\n function* FUNCTION_ID() {\n return yield* FUNCTION_KEY.apply(this, arguments);\n }\n\n FUNCTION_ID.toString = function () {\n return FUNCTION_KEY.toString();\n };\n\n return FUNCTION_ID;\n })(FUNCTION)\n");var visitor={"ReferencedIdentifier|BindingIdentifier":function ReferencedIdentifierBindingIdentifier(path,state){if(path.node.name!==state.name)return;var localDeclar=path.scope.getBindingIdentifier(state.name);if(localDeclar!==state.outerDeclar)return;state.selfReference=true;path.stop()}};function wrap(state,method,id,scope){if(state.selfReference){if(scope.hasBinding(id.name)&&!scope.hasGlobal(id.name)){scope.rename(id.name)}else{if(!t.isFunction(method))return;var build=buildPropertyMethodAssignmentWrapper;if(method.generator)build=buildGeneratorPropertyMethodAssignmentWrapper;var _template=build({FUNCTION:method,FUNCTION_ID:id,FUNCTION_KEY:scope.generateUidIdentifier(id.name)}).expression;_template.callee._skipModulesRemap=true;var params=_template.callee.body.body[0].params;for(var i=0,len=(0,_babelHelperGetFunctionArity2.default)(method);i=_iterator.length)break;_ref=_iterator[_i++]}else{_i=_iterator.next();if(_i.done)break;_ref=_i.value}var declar=_ref;firstId=declar.node.id;if(declar.node.init){nodes.push(t.expressionStatement(t.assignmentExpression("=",declar.node.id,declar.node.init)))}for(var name in declar.getBindingIdentifiers()){state.emit(t.identifier(name),name)}}if(path.parentPath.isFor({left:path.node})){path.replaceWith(firstId)}else{path.replaceWithMultiple(nodes)}}};module.exports=exports["default"]},{"babel-runtime/core-js/get-iterator":138,"babel-types":193}],69:[function(require,module,exports){"use strict";exports.__esModule=true;exports.default=function(callee,thisNode,args){if(args.length===1&&t.isSpreadElement(args[0])&&t.isIdentifier(args[0].argument,{name:"arguments"})){return t.callExpression(t.memberExpression(callee,t.identifier("apply")),[thisNode,args[0].argument])}else{return t.callExpression(t.memberExpression(callee,t.identifier("call")),[thisNode].concat(args))}};var _babelTypes=require("babel-types");var t=_interopRequireWildcard(_babelTypes);function _interopRequireWildcard(obj){if(obj&&obj.__esModule){return obj}else{var newObj={};if(obj!=null){for(var key in obj){if(Object.prototype.hasOwnProperty.call(obj,key))newObj[key]=obj[key]}}newObj.default=obj;return newObj}}module.exports=exports["default"]},{"babel-types":193}],70:[function(require,module,exports){"use strict";exports.__esModule=true;exports.is=is;exports.pullFlag=pullFlag;var _pull=require("lodash/pull");var _pull2=_interopRequireDefault(_pull);var _babelTypes=require("babel-types");var t=_interopRequireWildcard(_babelTypes);function _interopRequireWildcard(obj){if(obj&&obj.__esModule){return obj}else{var newObj={};if(obj!=null){for(var key in obj){if(Object.prototype.hasOwnProperty.call(obj,key))newObj[key]=obj[key]}}newObj.default=obj;return newObj}}function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function is(node,flag){return t.isRegExpLiteral(node)&&node.flags.indexOf(flag)>=0}function pullFlag(node,flag){var flags=node.flags.split("");if(node.flags.indexOf(flag)<0)return;(0,_pull2.default)(flags,flag);node.flags=flags.join("")}},{"babel-types":193,"lodash/pull":571}],71:[function(require,module,exports){"use strict";exports.__esModule=true;exports.default=function(path,helpers){var node=path.node;var scope=path.scope;var parent=path.parent;var stepKey=scope.generateUidIdentifier("step");var stepValue=scope.generateUidIdentifier("value");var left=node.left;var declar=void 0;if(t.isIdentifier(left)||t.isPattern(left)||t.isMemberExpression(left)){declar=t.expressionStatement(t.assignmentExpression("=",left,stepValue))}else if(t.isVariableDeclaration(left)){declar=t.variableDeclaration(left.kind,[t.variableDeclarator(left.declarations[0].id,stepValue)])}var template=buildForAwait();(0,_babelTraverse2.default)(template,forAwaitVisitor,null,{ITERATOR_HAD_ERROR_KEY:scope.generateUidIdentifier("didIteratorError"),ITERATOR_COMPLETION:scope.generateUidIdentifier("iteratorNormalCompletion"),ITERATOR_ERROR_KEY:scope.generateUidIdentifier("iteratorError"),ITERATOR_KEY:scope.generateUidIdentifier("iterator"),GET_ITERATOR:helpers.getAsyncIterator,OBJECT:node.right,STEP_VALUE:stepValue,STEP_KEY:stepKey,AWAIT:helpers.wrapAwait});template=template.body.body;var isLabeledParent=t.isLabeledStatement(parent);var tryBody=template[3].block.body;var loop=tryBody[0];if(isLabeledParent){tryBody[0]=t.labeledStatement(parent.label,loop)}return{replaceParent:isLabeledParent,node:template,declar:declar,loop:loop}};var _babelTypes=require("babel-types");var t=_interopRequireWildcard(_babelTypes);var _babelTemplate=require("babel-template");var _babelTemplate2=_interopRequireDefault(_babelTemplate);var _babelTraverse=require("babel-traverse");var _babelTraverse2=_interopRequireDefault(_babelTraverse);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function _interopRequireWildcard(obj){if(obj&&obj.__esModule){return obj}else{var newObj={};if(obj!=null){for(var key in obj){if(Object.prototype.hasOwnProperty.call(obj,key))newObj[key]=obj[key]}}newObj.default=obj;return newObj}}var buildForAwait=(0,_babelTemplate2.default)("\n function* wrapper() {\n var ITERATOR_COMPLETION = true;\n var ITERATOR_HAD_ERROR_KEY = false;\n var ITERATOR_ERROR_KEY = undefined;\n try {\n for (\n var ITERATOR_KEY = GET_ITERATOR(OBJECT), STEP_KEY, STEP_VALUE;\n (\n STEP_KEY = yield AWAIT(ITERATOR_KEY.next()),\n ITERATOR_COMPLETION = STEP_KEY.done,\n STEP_VALUE = yield AWAIT(STEP_KEY.value),\n !ITERATOR_COMPLETION\n );\n ITERATOR_COMPLETION = true) {\n }\n } catch (err) {\n ITERATOR_HAD_ERROR_KEY = true;\n ITERATOR_ERROR_KEY = err;\n } finally {\n try {\n if (!ITERATOR_COMPLETION && ITERATOR_KEY.return) {\n yield AWAIT(ITERATOR_KEY.return());\n }\n } finally {\n if (ITERATOR_HAD_ERROR_KEY) {\n throw ITERATOR_ERROR_KEY;\n }\n }\n }\n }\n"); var forAwaitVisitor={noScope:true,Identifier:function Identifier(path,replacements){if(path.node.name in replacements){path.replaceInline(replacements[path.node.name])}},CallExpression:function CallExpression(path,replacements){var callee=path.node.callee;if(t.isIdentifier(callee)&&callee.name==="AWAIT"&&!replacements.AWAIT){path.replaceWith(path.node.arguments[0])}}};module.exports=exports["default"]},{"babel-template":156,"babel-traverse":160,"babel-types":193}],72:[function(require,module,exports){"use strict";exports.__esModule=true;exports.default=function(path,file,helpers){if(!helpers){helpers={wrapAsync:file};file=null}path.traverse(awaitVisitor,{file:file,wrapAwait:helpers.wrapAwait});if(path.isClassMethod()||path.isObjectMethod()){classOrObjectMethod(path,helpers.wrapAsync)}else{plainFunction(path,helpers.wrapAsync)}};var _babelHelperFunctionName=require("babel-helper-function-name");var _babelHelperFunctionName2=_interopRequireDefault(_babelHelperFunctionName);var _babelTemplate=require("babel-template");var _babelTemplate2=_interopRequireDefault(_babelTemplate);var _babelTypes=require("babel-types");var t=_interopRequireWildcard(_babelTypes);var _forAwait=require("./for-await");var _forAwait2=_interopRequireDefault(_forAwait);function _interopRequireWildcard(obj){if(obj&&obj.__esModule){return obj}else{var newObj={};if(obj!=null){for(var key in obj){if(Object.prototype.hasOwnProperty.call(obj,key))newObj[key]=obj[key]}}newObj.default=obj;return newObj}}function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}var buildWrapper=(0,_babelTemplate2.default)("\n (() => {\n var REF = FUNCTION;\n return function NAME(PARAMS) {\n return REF.apply(this, arguments);\n };\n })\n");var namedBuildWrapper=(0,_babelTemplate2.default)("\n (() => {\n var REF = FUNCTION;\n function NAME(PARAMS) {\n return REF.apply(this, arguments);\n }\n return NAME;\n })\n");var awaitVisitor={Function:function Function(path){if(path.isArrowFunctionExpression()&&!path.node.async){path.arrowFunctionToShadowed();return}path.skip()},AwaitExpression:function AwaitExpression(_ref,_ref2){var node=_ref.node;var wrapAwait=_ref2.wrapAwait;node.type="YieldExpression";if(wrapAwait){node.argument=t.callExpression(wrapAwait,[node.argument])}},ForAwaitStatement:function ForAwaitStatement(path,_ref3){var file=_ref3.file;var wrapAwait=_ref3.wrapAwait;var node=path.node;var build=(0,_forAwait2.default)(path,{getAsyncIterator:file.addHelper("asyncIterator"),wrapAwait:wrapAwait});var declar=build.declar;var loop=build.loop;var block=loop.body;path.ensureBlock();if(declar){block.body.push(declar)}block.body=block.body.concat(node.body.body);t.inherits(loop,node);t.inherits(loop.body,node.body);if(build.replaceParent){path.parentPath.replaceWithMultiple(build.node);path.remove()}else{path.replaceWithMultiple(build.node)}}};function classOrObjectMethod(path,callId){var node=path.node;var body=node.body;node.async=false;var container=t.functionExpression(null,[],t.blockStatement(body.body),true);container.shadow=true;body.body=[t.returnStatement(t.callExpression(t.callExpression(callId,[container]),[]))]}function plainFunction(path,callId){var node=path.node;var isDeclaration=path.isFunctionDeclaration();var asyncFnId=node.id;var wrapper=buildWrapper;if(path.isArrowFunctionExpression()){path.arrowFunctionToShadowed()}else if(!isDeclaration&&asyncFnId){wrapper=namedBuildWrapper}node.async=false;node.generator=true;node.id=null;if(isDeclaration){node.type="FunctionExpression"}var built=t.callExpression(callId,[node]);var container=wrapper({NAME:asyncFnId,REF:path.scope.generateUidIdentifier("ref"),FUNCTION:built,PARAMS:node.params.map(function(){return path.scope.generateUidIdentifier("x")})}).expression;if(isDeclaration){var declar=t.variableDeclaration("let",[t.variableDeclarator(t.identifier(asyncFnId.name),t.callExpression(container,[]))]);declar._blockHoist=true;path.replaceWith(declar)}else{var retFunction=container.body.body[1].argument;if(!asyncFnId){(0,_babelHelperFunctionName2.default)({node:retFunction,parent:path.parent,scope:path.scope})}if(!retFunction||retFunction.id||node.params.length){path.replaceWith(t.callExpression(container,[]))}else{path.replaceWith(built)}}}module.exports=exports["default"]},{"./for-await":71,"babel-helper-function-name":66,"babel-template":156,"babel-types":193}],73:[function(require,module,exports){"use strict";exports.__esModule=true;var _classCallCheck2=require("babel-runtime/helpers/classCallCheck");var _classCallCheck3=_interopRequireDefault(_classCallCheck2);var _symbol=require("babel-runtime/core-js/symbol");var _symbol2=_interopRequireDefault(_symbol);var _babelHelperOptimiseCallExpression=require("babel-helper-optimise-call-expression");var _babelHelperOptimiseCallExpression2=_interopRequireDefault(_babelHelperOptimiseCallExpression);var _babelMessages=require("babel-messages");var messages=_interopRequireWildcard(_babelMessages);var _babelTypes=require("babel-types");var t=_interopRequireWildcard(_babelTypes);function _interopRequireWildcard(obj){if(obj&&obj.__esModule){return obj}else{var newObj={};if(obj!=null){for(var key in obj){if(Object.prototype.hasOwnProperty.call(obj,key))newObj[key]=obj[key]}}newObj.default=obj;return newObj}}function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}var HARDCORE_THIS_REF=(0,_symbol2.default)();function isIllegalBareSuper(node,parent){if(!t.isSuper(node))return false;if(t.isMemberExpression(parent,{computed:false}))return false;if(t.isCallExpression(parent,{callee:node}))return false;return true}function isMemberExpressionSuper(node){return t.isMemberExpression(node)&&t.isSuper(node.object)}function getPrototypeOfExpression(objectRef,isStatic){var targetRef=isStatic?objectRef:t.memberExpression(objectRef,t.identifier("prototype"));return t.logicalExpression("||",t.memberExpression(targetRef,t.identifier("__proto__")),t.callExpression(t.memberExpression(t.identifier("Object"),t.identifier("getPrototypeOf")),[targetRef]))}var visitor={Function:function Function(path){if(!path.inShadow("this")){path.skip()}},ReturnStatement:function ReturnStatement(path,state){if(!path.inShadow("this")){state.returns.push(path)}},ThisExpression:function ThisExpression(path,state){if(!path.node[HARDCORE_THIS_REF]){state.thises.push(path)}},enter:function enter(path,state){var callback=state.specHandle;if(state.isLoose)callback=state.looseHandle;var isBareSuper=path.isCallExpression()&&path.get("callee").isSuper();var result=callback.call(state,path);if(result){state.hasSuper=true}if(isBareSuper){state.bareSupers.push(path)}if(result===true){path.requeue()}if(result!==true&&result){if(Array.isArray(result)){path.replaceWithMultiple(result)}else{path.replaceWith(result)}}}};var ReplaceSupers=function(){function ReplaceSupers(opts){var inClass=arguments.length<=1||arguments[1]===undefined?false:arguments[1];(0,_classCallCheck3.default)(this,ReplaceSupers);this.forceSuperMemoisation=opts.forceSuperMemoisation;this.methodPath=opts.methodPath;this.methodNode=opts.methodNode;this.superRef=opts.superRef;this.isStatic=opts.isStatic;this.hasSuper=false;this.inClass=inClass;this.isLoose=opts.isLoose;this.scope=this.methodPath.scope;this.file=opts.file;this.opts=opts;this.bareSupers=[];this.returns=[];this.thises=[]}ReplaceSupers.prototype.getObjectRef=function getObjectRef(){return this.opts.objectRef||this.opts.getObjectRef()};ReplaceSupers.prototype.setSuperProperty=function setSuperProperty(property,value,isComputed){return t.callExpression(this.file.addHelper("set"),[getPrototypeOfExpression(this.getObjectRef(),this.isStatic),isComputed?property:t.stringLiteral(property.name),value,t.thisExpression()])};ReplaceSupers.prototype.getSuperProperty=function getSuperProperty(property,isComputed){return t.callExpression(this.file.addHelper("get"),[getPrototypeOfExpression(this.getObjectRef(),this.isStatic),isComputed?property:t.stringLiteral(property.name),t.thisExpression()])};ReplaceSupers.prototype.replace=function replace(){this.methodPath.traverse(visitor,this)};ReplaceSupers.prototype.getLooseSuperProperty=function getLooseSuperProperty(id,parent){var methodNode=this.methodNode;var superRef=this.superRef||t.identifier("Function");if(parent.property===id){return}else if(t.isCallExpression(parent,{callee:id})){return}else if(t.isMemberExpression(parent)&&!methodNode.static){return t.memberExpression(superRef,t.identifier("prototype"))}else{return superRef}};ReplaceSupers.prototype.looseHandle=function looseHandle(path){var node=path.node;if(path.isSuper()){return this.getLooseSuperProperty(node,path.parent)}else if(path.isCallExpression()){var callee=node.callee;if(!t.isMemberExpression(callee))return;if(!t.isSuper(callee.object))return;t.appendToMemberExpression(callee,t.identifier("call"));node.arguments.unshift(t.thisExpression());return true}};ReplaceSupers.prototype.specHandleAssignmentExpression=function specHandleAssignmentExpression(ref,path,node){if(node.operator==="="){return this.setSuperProperty(node.left.property,node.right,node.left.computed)}else{ref=ref||path.scope.generateUidIdentifier("ref");return[t.variableDeclaration("var",[t.variableDeclarator(ref,node.left)]),t.expressionStatement(t.assignmentExpression("=",node.left,t.binaryExpression(node.operator[0],ref,node.right)))]}};ReplaceSupers.prototype.specHandle=function specHandle(path){var property=void 0;var computed=void 0;var args=void 0;var parent=path.parent;var node=path.node;if(isIllegalBareSuper(node,parent)){throw path.buildCodeFrameError(messages.get("classesIllegalBareSuper"))}if(t.isCallExpression(node)){var callee=node.callee;if(t.isSuper(callee)){return}else if(isMemberExpressionSuper(callee)){property=callee.property;computed=callee.computed;args=node.arguments}}else if(t.isMemberExpression(node)&&t.isSuper(node.object)){property=node.property;computed=node.computed}else if(t.isUpdateExpression(node)&&isMemberExpressionSuper(node.argument)){var binary=t.binaryExpression(node.operator[0],node.argument,t.numericLiteral(1));if(node.prefix){return this.specHandleAssignmentExpression(null,path,binary)}else{var ref=path.scope.generateUidIdentifier("ref");return this.specHandleAssignmentExpression(ref,path,binary).concat(t.expressionStatement(ref))}}else if(t.isAssignmentExpression(node)&&isMemberExpressionSuper(node.left)){return this.specHandleAssignmentExpression(null,path,node)}if(!property)return;var superProperty=this.getSuperProperty(property,computed);if(args){return this.optimiseCall(superProperty,args)}else{return superProperty}};ReplaceSupers.prototype.optimiseCall=function optimiseCall(callee,args){var thisNode=t.thisExpression();thisNode[HARDCORE_THIS_REF]=true;return(0,_babelHelperOptimiseCallExpression2.default)(callee,thisNode,args)};return ReplaceSupers}();exports.default=ReplaceSupers;module.exports=exports["default"]},{"babel-helper-optimise-call-expression":69,"babel-messages":76,"babel-runtime/core-js/symbol":147,"babel-runtime/helpers/classCallCheck":152,"babel-types":193}],74:[function(require,module,exports){"use strict";exports.__esModule=true;var _babelTemplate=require("babel-template");var _babelTemplate2=_interopRequireDefault(_babelTemplate);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}var helpers={};exports.default=helpers;helpers.typeof=(0,_babelTemplate2.default)('\n (typeof Symbol === "function" && typeof Symbol.iterator === "symbol")\n ? function (obj) { return typeof obj; }\n : function (obj) {\n return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype\n ? "symbol"\n : typeof obj;\n };\n');helpers.jsx=(0,_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.asyncIterator=(0,_babelTemplate2.default)('\n (function (iterable) {\n if (typeof Symbol === "function") {\n if (Symbol.asyncIterator) {\n var method = iterable[Symbol.asyncIterator];\n if (method != null) return method.call(iterable);\n }\n if (Symbol.iterator) {\n return iterable[Symbol.iterator]();\n }\n }\n throw new TypeError("Object is not async iterable");\n })\n');helpers.asyncGenerator=(0,_babelTemplate2.default)('\n (function () {\n function AwaitValue(value) {\n this.value = value;\n }\n\n function AsyncGenerator(gen) {\n var front, back;\n\n function send(key, arg) {\n return new Promise(function (resolve, reject) {\n var request = {\n key: key,\n arg: arg,\n resolve: resolve,\n reject: reject,\n next: null\n };\n\n if (back) {\n back = back.next = request;\n } else {\n front = back = request;\n resume(key, arg);\n }\n });\n }\n\n function resume(key, arg) {\n try {\n var result = gen[key](arg)\n var value = result.value;\n if (value instanceof AwaitValue) {\n Promise.resolve(value.value).then(\n function (arg) { resume("next", arg); },\n function (arg) { resume("throw", arg); });\n } else {\n settle(result.done ? "return" : "normal", result.value);\n }\n } catch (err) {\n settle("throw", err);\n }\n }\n\n function settle(type, value) {\n switch (type) {\n case "return":\n front.resolve({ value: value, done: true });\n break;\n case "throw":\n front.reject(value);\n break;\n default:\n front.resolve({ value: value, done: false });\n break;\n }\n\n front = front.next;\n if (front) {\n resume(front.key, front.arg);\n } else {\n back = null;\n }\n }\n\n this._invoke = send;\n\n // Hide "return" method if generator return is not supported\n if (typeof gen.return !== "function") {\n this.return = undefined;\n }\n }\n\n if (typeof Symbol === "function" && Symbol.asyncIterator) {\n AsyncGenerator.prototype[Symbol.asyncIterator] = function () { return this; };\n }\n\n AsyncGenerator.prototype.next = function (arg) { return this._invoke("next", arg); };\n AsyncGenerator.prototype.throw = function (arg) { return this._invoke("throw", arg); };\n AsyncGenerator.prototype.return = function (arg) { return this._invoke("return", arg); };\n\n return {\n wrap: function (fn) {\n return function () {\n return new AsyncGenerator(fn.apply(this, arguments));\n };\n },\n await: function (value) {\n return new AwaitValue(value);\n }\n };\n\n })()\n');helpers.asyncGeneratorDelegate=(0,_babelTemplate2.default)('\n (function (inner, awaitWrap) {\n var iter = {}, waiting = false;\n\n function pump(key, value) {\n waiting = true;\n value = new Promise(function (resolve) { resolve(inner[key](value)); });\n return { done: false, value: awaitWrap(value) };\n };\n\n if (typeof Symbol === "function" && Symbol.iterator) {\n iter[Symbol.iterator] = function () { return this; };\n }\n\n iter.next = function (value) {\n if (waiting) {\n waiting = false;\n return value;\n }\n return pump("next", value);\n };\n\n if (typeof inner.throw === "function") {\n iter.throw = function (value) {\n if (waiting) {\n waiting = false;\n throw value;\n }\n return pump("throw", value);\n };\n }\n\n if (typeof inner.return === "function") {\n iter.return = function (value) {\n return pump("return", value);\n };\n }\n\n return iter;\n })\n');helpers.asyncToGenerator=(0,_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 step("next", value);\n }, function (err) {\n step("throw", err);\n });\n }\n }\n\n return step("next");\n });\n };\n })\n');helpers.classCallCheck=(0,_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=(0,_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=(0,_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=(0,_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=(0,_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=(0,_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=(0,_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=(0,_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=(0,_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=(0,_babelTemplate2.default)("\n (function (obj) {\n return obj && obj.__esModule ? obj : { default: obj };\n })\n");helpers.interopRequireWildcard=(0,_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=(0,_babelTemplate2.default)('\n (function (innerThis, boundThis) {\n if (innerThis !== boundThis) {\n throw new TypeError("Cannot instantiate an arrow function");\n }\n });\n');helpers.objectDestructuringEmpty=(0,_babelTemplate2.default)('\n (function (obj) {\n if (obj == null) throw new TypeError("Cannot destructure undefined");\n });\n');helpers.objectWithoutProperties=(0,_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=(0,_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=(0,_babelTemplate2.default)('\n typeof global === "undefined" ? self : global\n');helpers.set=(0,_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=(0,_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=(0,_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=(0,_babelTemplate2.default)("\n (function (strings, raw) {\n return Object.freeze(Object.defineProperties(strings, {\n raw: { value: Object.freeze(raw) }\n }));\n });\n");helpers.taggedTemplateLiteralLoose=(0,_babelTemplate2.default)("\n (function (strings, raw) {\n strings.raw = raw;\n return strings;\n });\n");helpers.temporalRef=(0,_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=(0,_babelTemplate2.default)("\n ({})\n");helpers.toArray=(0,_babelTemplate2.default)("\n (function (arr) {\n return Array.isArray(arr) ? arr : Array.from(arr);\n });\n");helpers.toConsumableArray=(0,_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"]},{"babel-template":156}],75:[function(require,module,exports){"use strict";exports.__esModule=true;exports.list=undefined;var _keys=require("babel-runtime/core-js/object/keys");var _keys2=_interopRequireDefault(_keys);exports.get=get;var _helpers=require("./helpers");var _helpers2=_interopRequireDefault(_helpers);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function get(name){var fn=_helpers2.default[name];if(!fn)throw new ReferenceError("Unknown helper "+name);return fn().expression}var list=exports.list=(0,_keys2.default)(_helpers2.default).map(function(name){return name[0]==="_"?name.slice(1):name}).filter(function(name){return name!=="__esModule"});exports.default=get},{"./helpers":74,"babel-runtime/core-js/object/keys":145}],76:[function(require,module,exports){"use strict";exports.__esModule=true;exports.MESSAGES=undefined;var _stringify=require("babel-runtime/core-js/json/stringify");var _stringify2=_interopRequireDefault(_stringify);exports.get=get;exports.parseArgs=parseArgs;var _util=require("util");var util=_interopRequireWildcard(_util);function _interopRequireWildcard(obj){if(obj&&obj.__esModule){return obj}else{var newObj={};if(obj!=null){for(var key in obj){if(Object.prototype.hasOwnProperty.call(obj,key))newObj[key]=obj[key]}}newObj.default=obj;return newObj}}function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}var MESSAGES=exports.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"};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 "+(0,_stringify2.default)(key));args=parseArgs(args);return msg.replace(/\$(\d+)/g,function(str,i){return args[i-1]})}function parseArgs(args){return args.map(function(val){ if(val!=null&&val.inspect){return val.inspect()}else{try{return(0,_stringify2.default)(val)||val+""}catch(e){return util.inspect(val)}}})}},{"babel-runtime/core-js/json/stringify":139,util:691}],77:[function(require,module,exports){"use strict";exports.__esModule=true;var _getIterator2=require("babel-runtime/core-js/get-iterator");var _getIterator3=_interopRequireDefault(_getIterator2);exports.default=function(_ref){var messages=_ref.messages;return{visitor:{Scope:function Scope(_ref2){var scope=_ref2.scope;for(var name in scope.bindings){var binding=scope.bindings[name];if(binding.kind!=="const"&&binding.kind!=="module")continue;for(var _iterator=binding.constantViolations,_isArray=Array.isArray(_iterator),_i=0,_iterator=_isArray?_iterator:(0,_getIterator3.default)(_iterator);;){var _ref3;if(_isArray){if(_i>=_iterator.length)break;_ref3=_iterator[_i++]}else{_i=_iterator.next();if(_i.done)break;_ref3=_i.value}var violation=_ref3;throw violation.buildCodeFrameError(messages.get("readOnly",name))}}}}}};function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}module.exports=exports["default"]},{"babel-runtime/core-js/get-iterator":138}],78:[function(require,module,exports){"use strict";exports.__esModule=true;exports.default=function(){return{manipulateOptions:function manipulateOptions(opts,parserOpts){parserOpts.plugins.push("asyncFunctions")}}};module.exports=exports["default"]},{}],79:[function(require,module,exports){"use strict";exports.__esModule=true;exports.default=function(){return{manipulateOptions:function manipulateOptions(opts,parserOpts){parserOpts.plugins.push("classConstructorCall")}}};module.exports=exports["default"]},{}],80:[function(require,module,exports){"use strict";exports.__esModule=true;exports.default=function(){return{manipulateOptions:function manipulateOptions(opts,parserOpts){parserOpts.plugins.push("classProperties")}}};module.exports=exports["default"]},{}],81:[function(require,module,exports){"use strict";exports.__esModule=true;exports.default=function(){return{manipulateOptions:function manipulateOptions(opts,parserOpts){parserOpts.plugins.push("decorators")}}};module.exports=exports["default"]},{}],82:[function(require,module,exports){"use strict";exports.__esModule=true;exports.default=function(){return{manipulateOptions:function manipulateOptions(opts,parserOpts){parserOpts.plugins.push("doExpressions")}}};module.exports=exports["default"]},{}],83:[function(require,module,exports){"use strict";exports.__esModule=true;exports.default=function(){return{manipulateOptions:function manipulateOptions(opts,parserOpts){parserOpts.plugins.push("exponentiationOperator")}}};module.exports=exports["default"]},{}],84:[function(require,module,exports){"use strict";exports.__esModule=true;exports.default=function(){return{manipulateOptions:function manipulateOptions(opts,parserOpts){parserOpts.plugins.push("exportExtensions")}}};module.exports=exports["default"]},{}],85:[function(require,module,exports){"use strict";exports.__esModule=true;exports.default=function(){return{manipulateOptions:function manipulateOptions(opts,parserOpts){parserOpts.plugins.push("functionBind")}}};module.exports=exports["default"]},{}],86:[function(require,module,exports){"use strict";exports.__esModule=true;exports.default=function(){return{manipulateOptions:function manipulateOptions(opts,parserOpts){parserOpts.plugins.push("objectRestSpread")}}};module.exports=exports["default"]},{}],87:[function(require,module,exports){"use strict";exports.__esModule=true;exports.default=function(){return{manipulateOptions:function manipulateOptions(opts,parserOpts){parserOpts.plugins.push("trailingFunctionCommas")}}};module.exports=exports["default"]},{}],88:[function(require,module,exports){"use strict";exports.__esModule=true;exports.default=function(){return{inherits:require("babel-plugin-syntax-async-functions"),visitor:{Function:function Function(path,state){if(!path.node.async||path.node.generator)return;(0,_babelHelperRemapAsyncToGenerator2.default)(path,state.file,{wrapAsync:state.addHelper("asyncToGenerator")})}}}};var _babelHelperRemapAsyncToGenerator=require("babel-helper-remap-async-to-generator");var _babelHelperRemapAsyncToGenerator2=_interopRequireDefault(_babelHelperRemapAsyncToGenerator);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}module.exports=exports["default"]},{"babel-helper-remap-async-to-generator":72,"babel-plugin-syntax-async-functions":78}],89:[function(require,module,exports){"use strict";exports.__esModule=true;var _getIterator2=require("babel-runtime/core-js/get-iterator");var _getIterator3=_interopRequireDefault(_getIterator2);var _symbol=require("babel-runtime/core-js/symbol");var _symbol2=_interopRequireDefault(_symbol);exports.default=function(_ref){var t=_ref.types;var ALREADY_VISITED=(0,_symbol2.default)();function findConstructorCall(path){var methods=path.get("body.body");for(var _iterator=methods,_isArray=Array.isArray(_iterator),_i=0,_iterator=_isArray?_iterator:(0,_getIterator3.default)(_iterator);;){var _ref2;if(_isArray){if(_i>=_iterator.length)break;_ref2=_iterator[_i++]}else{_i=_iterator.next();if(_i.done)break;_ref2=_i.value}var method=_ref2;if(method.node.kind==="constructorCall"){return method}}return null}function handleClassWithCall(constructorCall,classPath){var _classPath=classPath;var node=_classPath.node;var ref=node.id||classPath.scope.generateUidIdentifier("class");if(classPath.parentPath.isExportDefaultDeclaration()){classPath=classPath.parentPath;classPath.insertAfter(t.exportDefaultDeclaration(ref))}classPath.replaceWithMultiple(buildWrapper({CLASS_REF:classPath.scope.generateUidIdentifier(ref.name),CALL_REF:classPath.scope.generateUidIdentifier(ref.name+"Call"),CALL:t.functionExpression(null,constructorCall.node.params,constructorCall.node.body),CLASS:t.toExpression(node),WRAPPER_REF:ref}));constructorCall.remove()}return{inherits:require("babel-plugin-syntax-class-constructor-call"),visitor:{Class:function Class(path){if(path.node[ALREADY_VISITED])return;path.node[ALREADY_VISITED]=true;var constructorCall=findConstructorCall(path);if(constructorCall){handleClassWithCall(constructorCall,path)}else{return}}}}};var _babelTemplate=require("babel-template");var _babelTemplate2=_interopRequireDefault(_babelTemplate);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}var buildWrapper=(0,_babelTemplate2.default)("\n let CLASS_REF = CLASS;\n var CALL_REF = CALL;\n var WRAPPER_REF = function (...args) {\n if (this instanceof WRAPPER_REF) {\n return Reflect.construct(CLASS_REF, args);\n } else {\n return CALL_REF.apply(this, args);\n }\n };\n WRAPPER_REF.__proto__ = CLASS_REF;\n WRAPPER_REF;\n");module.exports=exports["default"]},{"babel-plugin-syntax-class-constructor-call":79,"babel-runtime/core-js/get-iterator":138,"babel-runtime/core-js/symbol":147,"babel-template":156}],90:[function(require,module,exports){"use strict";exports.__esModule=true;var _getIterator2=require("babel-runtime/core-js/get-iterator");var _getIterator3=_interopRequireDefault(_getIterator2);exports.default=function(_ref){var t=_ref.types;var findBareSupers={Super:function Super(path){if(path.parentPath.isCallExpression({callee:path.node})){this.push(path.parentPath)}}};var referenceVisitor={ReferencedIdentifier:function ReferencedIdentifier(path){if(this.scope.hasOwnBinding(path.node.name)){this.collision=true;path.skip()}}};return{inherits:require("babel-plugin-syntax-class-properties"),visitor:{Class:function Class(path){var isDerived=!!path.node.superClass;var constructor=void 0;var props=[];var body=path.get("body");for(var _iterator=body.get("body"),_isArray=Array.isArray(_iterator),_i=0,_iterator=_isArray?_iterator:(0,_getIterator3.default)(_iterator);;){var _ref2;if(_isArray){if(_i>=_iterator.length)break;_ref2=_iterator[_i++]}else{_i=_iterator.next();if(_i.done)break;_ref2=_i.value}var _path=_ref2;if(_path.isClassProperty()){props.push(_path)}else if(_path.isClassMethod({kind:"constructor"})){constructor=_path}}if(!props.length)return;var nodes=[];var ref=void 0;if(path.isClassExpression()||!path.node.id){(0,_babelHelperFunctionName2.default)(path);ref=path.scope.generateUidIdentifier("class")}else{ref=path.node.id}var instanceBody=[];for(var _iterator2=props,_isArray2=Array.isArray(_iterator2),_i2=0,_iterator2=_isArray2?_iterator2:(0,_getIterator3.default)(_iterator2);;){var _ref3;if(_isArray2){if(_i2>=_iterator2.length)break;_ref3=_iterator2[_i2++]}else{_i2=_iterator2.next();if(_i2.done)break;_ref3=_i2.value}var _prop=_ref3;var propNode=_prop.node;if(propNode.decorators&&propNode.decorators.length>0)continue;if(!propNode.value)continue;var isStatic=propNode.static;var isComputed=propNode.computed||t.isLiteral(_prop.key);if(isStatic){nodes.push(t.expressionStatement(t.assignmentExpression("=",t.memberExpression(ref,propNode.key,isComputed),propNode.value)))}else{instanceBody.push(t.expressionStatement(t.assignmentExpression("=",t.memberExpression(t.thisExpression(),propNode.key,isComputed),propNode.value)))}}if(instanceBody.length){if(!constructor){var newConstructor=t.classMethod("constructor",t.identifier("constructor"),[],t.blockStatement([]));if(isDerived){newConstructor.params=[t.restElement(t.identifier("args"))];newConstructor.body.body.push(t.returnStatement(t.callExpression(t.super(),[t.spreadElement(t.identifier("args"))])))}var _body$unshiftContaine=body.unshiftContainer("body",newConstructor);constructor=_body$unshiftContaine[0]}var collisionState={collision:false,scope:constructor.scope};for(var _iterator3=props,_isArray3=Array.isArray(_iterator3),_i3=0,_iterator3=_isArray3?_iterator3:(0,_getIterator3.default)(_iterator3);;){var _ref4;if(_isArray3){if(_i3>=_iterator3.length)break;_ref4=_iterator3[_i3++]}else{_i3=_iterator3.next();if(_i3.done)break;_ref4=_i3.value}var prop=_ref4;prop.traverse(referenceVisitor,collisionState);if(collisionState.collision)break}if(collisionState.collision){var initialisePropsRef=path.scope.generateUidIdentifier("initialiseProps");nodes.push(t.variableDeclaration("var",[t.variableDeclarator(initialisePropsRef,t.functionExpression(null,[],t.blockStatement(instanceBody)))]));instanceBody=[t.expressionStatement(t.callExpression(t.memberExpression(initialisePropsRef,t.identifier("call")),[t.thisExpression()]))]}if(isDerived){var bareSupers=[];constructor.traverse(findBareSupers,bareSupers);for(var _iterator4=bareSupers,_isArray4=Array.isArray(_iterator4),_i4=0,_iterator4=_isArray4?_iterator4:(0,_getIterator3.default)(_iterator4);;){var _ref5;if(_isArray4){if(_i4>=_iterator4.length)break;_ref5=_iterator4[_i4++]}else{_i4=_iterator4.next();if(_i4.done)break;_ref5=_i4.value}var bareSuper=_ref5;bareSuper.insertAfter(instanceBody)}}else{constructor.get("body").unshiftContainer("body",instanceBody)}}for(var _iterator5=props,_isArray5=Array.isArray(_iterator5),_i5=0,_iterator5=_isArray5?_iterator5:(0,_getIterator3.default)(_iterator5);;){var _ref6;if(_isArray5){if(_i5>=_iterator5.length)break;_ref6=_iterator5[_i5++]}else{_i5=_iterator5.next();if(_i5.done)break;_ref6=_i5.value}var _prop2=_ref6;_prop2.remove()}if(!nodes.length)return;if(path.isClassExpression()){path.scope.push({id:ref});path.replaceWith(t.assignmentExpression("=",ref,path.node))}else{if(!path.node.id){path.node.id=ref}if(path.parentPath.isExportDeclaration()){path=path.parentPath}}path.insertAfter(nodes)},ArrowFunctionExpression:function ArrowFunctionExpression(path){var classExp=path.get("body");if(!classExp.isClassExpression())return;var body=classExp.get("body");var members=body.get("body");if(members.some(function(member){return member.isClassProperty()})){path.ensureBlock()}}}}};var _babelHelperFunctionName=require("babel-helper-function-name");var _babelHelperFunctionName2=_interopRequireDefault(_babelHelperFunctionName);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}module.exports=exports["default"]},{"babel-helper-function-name":66,"babel-plugin-syntax-class-properties":80,"babel-runtime/core-js/get-iterator":138}],91:[function(require,module,exports){"use strict";exports.__esModule=true;var _create=require("babel-runtime/core-js/object/create");var _create2=_interopRequireDefault(_create);var _getIterator2=require("babel-runtime/core-js/get-iterator");var _getIterator3=_interopRequireDefault(_getIterator2);exports.default=function(_ref){var t=_ref.types;function cleanDecorators(decorators){return decorators.reverse().map(function(dec){return dec.expression})}function transformClass(path,ref,state){var nodes=[];state;var classDecorators=path.node.decorators;if(classDecorators){path.node.decorators=null;classDecorators=cleanDecorators(classDecorators);for(var _iterator=classDecorators,_isArray=Array.isArray(_iterator),_i=0,_iterator=_isArray?_iterator:(0,_getIterator3.default)(_iterator);;){var _ref2;if(_isArray){if(_i>=_iterator.length)break;_ref2=_iterator[_i++]}else{_i=_iterator.next();if(_i.done)break;_ref2=_i.value}var decorator=_ref2;nodes.push(buildClassDecorator({CLASS_REF:ref,DECORATOR:decorator}))}}var map=(0,_create2.default)(null);for(var _iterator2=path.get("body.body"),_isArray2=Array.isArray(_iterator2),_i2=0,_iterator2=_isArray2?_iterator2:(0,_getIterator3.default)(_iterator2);;){var _ref3;if(_isArray2){if(_i2>=_iterator2.length)break;_ref3=_iterator2[_i2++]}else{_i2=_iterator2.next();if(_i2.done)break;_ref3=_i2.value}var method=_ref3;var decorators=method.node.decorators;if(!decorators)continue;var _alias=t.toKeyAlias(method.node);map[_alias]=map[_alias]||[];map[_alias].push(method.node);method.remove()}for(var alias in map){var items=map[alias];items}return nodes}function hasDecorators(path){if(path.isClass()){if(path.node.decorators)return true;for(var _iterator3=path.node.body.body,_isArray3=Array.isArray(_iterator3),_i3=0,_iterator3=_isArray3?_iterator3:(0,_getIterator3.default)(_iterator3);;){var _ref4;if(_isArray3){if(_i3>=_iterator3.length)break;_ref4=_iterator3[_i3++]}else{_i3=_iterator3.next();if(_i3.done)break;_ref4=_i3.value}var method=_ref4;if(method.decorators){return true}}}else if(path.isObjectExpression()){for(var _iterator4=path.node.properties,_isArray4=Array.isArray(_iterator4),_i4=0,_iterator4=_isArray4?_iterator4:(0,_getIterator3.default)(_iterator4);;){var _ref5;if(_isArray4){if(_i4>=_iterator4.length)break;_ref5=_iterator4[_i4++]}else{_i4=_iterator4.next();if(_i4.done)break;_ref5=_i4.value}var prop=_ref5;if(prop.decorators){return true}}}return false}function doError(path){throw path.buildCodeFrameError('Decorators are not officially supported yet in 6.x pending a proposal update.\nHowever, if you need to use them you can install the legacy decorators transform with:\n\nnpm install babel-plugin-transform-decorators-legacy --save-dev\n\nand add the following line to your .babelrc file:\n\n{\n "plugins": ["transform-decorators-legacy"]\n}\n\nThe repo url is: https://github.com/loganfsmyth/babel-plugin-transform-decorators-legacy.\n ')}return{inherits:require("babel-plugin-syntax-decorators"),visitor:{ClassExpression:function ClassExpression(path){if(!hasDecorators(path))return;doError(path);(0,_babelHelperExplodeClass2.default)(path);var ref=path.scope.generateDeclaredUidIdentifier("ref");var nodes=[];nodes.push(t.assignmentExpression("=",ref,path.node));nodes=nodes.concat(transformClass(path,ref,this));nodes.push(ref);path.replaceWith(t.sequenceExpression(nodes))},ClassDeclaration:function ClassDeclaration(path){if(!hasDecorators(path))return;doError(path);(0,_babelHelperExplodeClass2.default)(path);var ref=path.node.id;var nodes=[];nodes=nodes.concat(transformClass(path,ref,this).map(function(expr){return t.expressionStatement(expr)}));nodes.push(t.expressionStatement(ref));path.insertAfter(nodes)},ObjectExpression:function ObjectExpression(path){if(!hasDecorators(path))return;doError(path)}}}};var _babelTemplate=require("babel-template");var _babelTemplate2=_interopRequireDefault(_babelTemplate);var _babelHelperExplodeClass=require("babel-helper-explode-class");var _babelHelperExplodeClass2=_interopRequireDefault(_babelHelperExplodeClass);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}var buildClassDecorator=(0,_babelTemplate2.default)("\n CLASS_REF = DECORATOR(CLASS_REF) || CLASS_REF;\n");module.exports=exports["default"]},{"babel-helper-explode-class":65,"babel-plugin-syntax-decorators":81,"babel-runtime/core-js/get-iterator":138,"babel-runtime/core-js/object/create":143,"babel-template":156}],92:[function(require,module,exports){"use strict";exports.__esModule=true;exports.default=function(){return{inherits:require("babel-plugin-syntax-do-expressions"),visitor:{DoExpression:function DoExpression(path){var body=path.node.body.body;if(body.length){path.replaceWithMultiple(body)}else{path.replaceWith(path.scope.buildUndefinedNode())}}}}};module.exports=exports["default"]},{"babel-plugin-syntax-do-expressions":82}],93:[function(require,module,exports){"use strict";exports.__esModule=true;exports.default=function(_ref){var t=_ref.types;return{visitor:{ArrowFunctionExpression:function ArrowFunctionExpression(path,state){if(state.opts.spec){var node=path.node;if(node.shadow)return;node.shadow={this:false};node.type="FunctionExpression";var boundThis=t.thisExpression();boundThis._forceShadow=path;path.ensureBlock();path.get("body").unshiftContainer("body",t.expressionStatement(t.callExpression(state.addHelper("newArrowCheck"),[t.thisExpression(),boundThis])));path.replaceWith(t.callExpression(t.memberExpression(node,t.identifier("bind")),[t.thisExpression()]))}else{path.arrowFunctionToShadowed()}}}}};module.exports=exports["default"]},{}],94:[function(require,module,exports){"use strict";exports.__esModule=true;var _getIterator2=require("babel-runtime/core-js/get-iterator");var _getIterator3=_interopRequireDefault(_getIterator2);exports.default=function(_ref){var t=_ref.types;function statementList(key,path){var paths=path.get(key);for(var _iterator=paths,_isArray=Array.isArray(_iterator),_i=0,_iterator=_isArray?_iterator:(0,_getIterator3.default)(_iterator);;){var _ref2;if(_isArray){if(_i>=_iterator.length)break;_ref2=_iterator[_i++]}else{_i=_iterator.next();if(_i.done)break;_ref2=_i.value}var _path=_ref2;var func=_path.node;if(!_path.isFunctionDeclaration())continue;var declar=t.variableDeclaration("let",[t.variableDeclarator(func.id,t.toExpression(func))]);declar._blockHoist=2;func.id=null;_path.replaceWith(declar)}}return{visitor:{BlockStatement:function BlockStatement(path){var node=path.node;var parent=path.parent;if(t.isFunction(parent,{body:node})||t.isExportDeclaration(parent)){return}statementList("body",path)},SwitchCase:function SwitchCase(path){statementList("consequent",path)}}}};function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}module.exports=exports["default"]},{"babel-runtime/core-js/get-iterator":138}],95:[function(require,module,exports){"use strict";exports.__esModule=true;var _symbol=require("babel-runtime/core-js/symbol");var _symbol2=_interopRequireDefault(_symbol);var _create=require("babel-runtime/core-js/object/create");var _create2=_interopRequireDefault(_create);var _classCallCheck2=require("babel-runtime/helpers/classCallCheck");var _classCallCheck3=_interopRequireDefault(_classCallCheck2);exports.default=function(){return{visitor:{VariableDeclaration:function VariableDeclaration(path,file){var node=path.node;var parent=path.parent;var scope=path.scope;if(!isBlockScoped(node))return;convertBlockScopedToVar(path,null,parent,scope,true);if(node._tdzThis){var nodes=[node];for(var i=0;i=0){return}loopText=loopText+"|"+node.label.name}else{if(state.ignoreLabeless)return;if(state.inSwitchCase)return;if(t.isBreakStatement(node)&&t.isSwitchCase(parent))return}state.hasBreakContinue=true;state.map[loopText]=node;replace=t.stringLiteral(loopText)}if(path.isReturnStatement()){state.hasReturn=true;replace=t.objectExpression([t.objectProperty(t.identifier("v"),node.argument||scope.buildUndefinedNode())])}if(replace){replace=t.returnStatement(replace);replace[this.LOOP_IGNORE]=true;path.skip();path.replaceWith(t.inherits(replace,node))}}};var BlockScoping=function(){function BlockScoping(loopPath,blockPath,parent,scope,file){(0,_classCallCheck3.default)(this,BlockScoping);this.parent=parent;this.scope=scope;this.file=file;this.blockPath=blockPath;this.block=blockPath.node;this.outsideLetReferences=(0,_create2.default)(null);this.hasLetReferences=false;this.letReferences=(0,_create2.default)(null);this.body=[];if(loopPath){this.loopParent=loopPath.parent;this.loopLabel=t.isLabeledStatement(this.loopParent)&&this.loopParent.label;this.loopPath=loopPath;this.loop=loopPath.node}}BlockScoping.prototype.run=function run(){var block=this.block;if(block._letDone)return;block._letDone=true;var needsClosure=this.getLetReferences();if(t.isFunction(this.parent)||t.isProgram(this.block)){this.updateScopeInfo();return}if(!this.hasLetReferences)return;if(needsClosure){this.wrapClosure()}else{this.remap()}this.updateScopeInfo();if(this.loopLabel&&!t.isLabeledStatement(this.loopParent)){return t.labeledStatement(this.loopLabel,this.loop)}};BlockScoping.prototype.updateScopeInfo=function updateScopeInfo(){var scope=this.scope;var parentScope=scope.getFunctionParent();var letRefs=this.letReferences;for(var key in letRefs){var ref=letRefs[key];var binding=scope.getBinding(ref.name);if(!binding)continue;if(binding.kind==="let"||binding.kind==="const"){binding.kind="var";scope.moveBindingTo(ref.name,parentScope)}}};BlockScoping.prototype.remap=function remap(){var letRefs=this.letReferences;var scope=this.scope;for(var key in letRefs){var ref=letRefs[key];if(scope.parentHasBinding(key)||scope.hasGlobal(key)){if(scope.hasOwnBinding(key))scope.rename(ref.name);if(this.blockPath.scope.hasOwnBinding(key))this.blockPath.scope.rename(ref.name)}}};BlockScoping.prototype.wrapClosure=function wrapClosure(){var block=this.block;var outsideRefs=this.outsideLetReferences;if(this.loop){for(var name in outsideRefs){var id=outsideRefs[name];if(this.scope.hasGlobal(id.name)||this.scope.parentHasBinding(id.name)){delete outsideRefs[id.name];delete this.letReferences[id.name];this.scope.rename(id.name);this.letReferences[id.name]=id;outsideRefs[id.name]=id}}}this.has=this.checkLoop();this.hoistVarDeclarations();var params=(0,_values2.default)(outsideRefs);var args=(0,_values2.default)(outsideRefs);var isSwitch=this.blockPath.isSwitchStatement();var fn=t.functionExpression(null,params,t.blockStatement(isSwitch?[block]:block.body));fn.shadow=true;this.addContinuations(fn);var ref=fn;if(this.loop){ref=this.scope.generateUidIdentifier("loop");this.loopPath.insertBefore(t.variableDeclaration("var",[t.variableDeclarator(ref,fn)]))}var call=t.callExpression(ref,args);var ret=this.scope.generateUidIdentifier("ret");var hasYield=_babelTraverse2.default.hasType(fn.body,this.scope,"YieldExpression",t.FUNCTION_TYPES);if(hasYield){fn.generator=true;call=t.yieldExpression(call,true)}var hasAsync=_babelTraverse2.default.hasType(fn.body,this.scope,"AwaitExpression",t.FUNCTION_TYPES);if(hasAsync){fn.async=true;call=t.awaitExpression(call)}this.buildClosure(ret,call);if(isSwitch)this.blockPath.replaceWithMultiple(this.body);else block.body=this.body};BlockScoping.prototype.buildClosure=function buildClosure(ret,call){var has=this.has;if(has.hasReturn||has.hasBreakContinue){this.buildHas(ret,call)}else{this.body.push(t.expressionStatement(call))}};BlockScoping.prototype.addContinuations=function addContinuations(fn){var state={reassignments:{},outsideReferences:this.outsideLetReferences};this.scope.traverse(fn,continuationVisitor,state);for(var i=0;i=_iterator.length)break;_ref=_iterator[_i++]}else{_i=_iterator.next();if(_i.done)break;_ref=_i.value}var path=_ref;hasConstructor=path.equals("kind","constructor");if(hasConstructor)break}if(hasConstructor)return;var params=void 0,body=void 0;if(this.isDerived){var _constructor=buildDerivedConstructor().expression;params=_constructor.params;body=_constructor.body}else{params=[];body=t.blockStatement([])}this.path.get("body").unshiftContainer("body",t.classMethod("constructor",t.identifier("constructor"),params,body))};ClassTransformer.prototype.buildBody=function buildBody(){this.constructorMeMaybe();this.pushBody();this.verifyConstructor();if(this.userConstructor){var constructorBody=this.constructorBody;constructorBody.body=constructorBody.body.concat(this.userConstructor.body.body);t.inherits(this.constructor,this.userConstructor);t.inherits(constructorBody,this.userConstructor.body)}this.pushDescriptors()};ClassTransformer.prototype.pushBody=function pushBody(){var classBodyPaths=this.path.get("body.body");for(var _iterator2=classBodyPaths,_isArray2=Array.isArray(_iterator2),_i2=0,_iterator2=_isArray2?_iterator2:(0,_getIterator3.default)(_iterator2);;){var _ref2;if(_isArray2){if(_i2>=_iterator2.length)break;_ref2=_iterator2[_i2++]}else{_i2=_iterator2.next();if(_i2.done)break;_ref2=_i2.value}var path=_ref2;var node=path.node;if(path.isClassProperty()){throw path.buildCodeFrameError("Missing class properties transform.")}if(node.decorators){throw path.buildCodeFrameError("Method has decorators, put the decorator plugin before the classes one.")}if(t.isClassMethod(node)){var isConstructor=node.kind==="constructor";if(isConstructor){path.traverse(verifyConstructorVisitor,this);if(!this.hasBareSuper&&this.isDerived){throw path.buildCodeFrameError("missing super() call in constructor")}}var replaceSupers=new _babelHelperReplaceSupers2.default({forceSuperMemoisation:isConstructor,methodPath:path,methodNode:node,objectRef:this.classRef,superRef:this.superName,isStatic:node.static,isLoose:this.isLoose,scope:this.scope,file:this.file},true);replaceSupers.replace();if(isConstructor){this.pushConstructor(replaceSupers,node,path)}else{this.pushMethod(node,path)}}}};ClassTransformer.prototype.clearDescriptors=function clearDescriptors(){this.hasInstanceDescriptors=false;this.hasStaticDescriptors=false;this.instanceMutatorMap={};this.staticMutatorMap={}};ClassTransformer.prototype.pushDescriptors=function pushDescriptors(){this.pushInherits();var body=this.body;var instanceProps=void 0;var staticProps=void 0;if(this.hasInstanceDescriptors){instanceProps=defineMap.toClassObject(this.instanceMutatorMap)}if(this.hasStaticDescriptors){staticProps=defineMap.toClassObject(this.staticMutatorMap)}if(instanceProps||staticProps){if(instanceProps)instanceProps=defineMap.toComputedObjectFromClass(instanceProps);if(staticProps)staticProps=defineMap.toComputedObjectFromClass(staticProps);var nullNode=t.nullLiteral();var args=[this.classRef,nullNode,nullNode,nullNode,nullNode];if(instanceProps)args[1]=instanceProps;if(staticProps)args[2]=staticProps;if(this.instanceInitializersId){args[3]=this.instanceInitializersId;body.unshift(this.buildObjectAssignment(this.instanceInitializersId))}if(this.staticInitializersId){args[4]=this.staticInitializersId;body.unshift(this.buildObjectAssignment(this.staticInitializersId))}var lastNonNullIndex=0;for(var i=0;i=_iterator3.length)break;_ref3=_iterator3[_i3++]}else{_i3=_iterator3.next();if(_i3.done)break;_ref3=_i3.value}var bareSuper=_ref3;this.wrapSuperCall(bareSuper,superRef,thisRef,body);if(guaranteedSuperBeforeFinish){bareSuper.find(function(parentPath){if(parentPath===path){return true}if(parentPath.isLoop()||parentPath.isConditional()){guaranteedSuperBeforeFinish=false;return true}})}}for(var _iterator4=this.superThises,_isArray4=Array.isArray(_iterator4),_i4=0,_iterator4=_isArray4?_iterator4:(0,_getIterator3.default)(_iterator4);;){var _ref4;if(_isArray4){if(_i4>=_iterator4.length)break;_ref4=_iterator4[_i4++]}else{_i4=_iterator4.next();if(_i4.done)break;_ref4=_i4.value}var thisPath=_ref4;thisPath.replaceWith(thisRef)}var wrapReturn=function wrapReturn(returnArg){return t.callExpression(_this2.file.addHelper("possibleConstructorReturn"),[thisRef].concat(returnArg||[]))};var bodyPaths=body.get("body");if(bodyPaths.length&&!bodyPaths.pop().isReturnStatement()){body.pushContainer("body",t.returnStatement(guaranteedSuperBeforeFinish?thisRef:wrapReturn()))}for(var _iterator5=this.superReturns,_isArray5=Array.isArray(_iterator5),_i5=0,_iterator5=_isArray5?_iterator5:(0,_getIterator3.default)(_iterator5);;){var _ref5;if(_isArray5){if(_i5>=_iterator5.length)break;_ref5=_iterator5[_i5++]}else{_i5=_iterator5.next();if(_i5.done)break;_ref5=_i5.value}var returnPath=_ref5;if(returnPath.node.argument){var ref=returnPath.scope.generateDeclaredUidIdentifier("ret");returnPath.get("argument").replaceWithMultiple([t.assignmentExpression("=",ref,returnPath.node.argument),wrapReturn(ref)])}else{returnPath.get("argument").replaceWith(wrapReturn())}}};ClassTransformer.prototype.pushMethod=function pushMethod(node,path){var scope=path?path.scope:this.scope;if(node.kind==="method"){if(this._processMethod(node,scope))return}this.pushToMap(node,false,null,scope)};ClassTransformer.prototype._processMethod=function _processMethod(){return false};ClassTransformer.prototype.pushConstructor=function pushConstructor(replaceSupers,method,path){this.bareSupers=replaceSupers.bareSupers;this.superReturns=replaceSupers.returns;if(path.scope.hasOwnBinding(this.classRef.name)){path.scope.rename(this.classRef.name)}var construct=this.constructor;this.userConstructorPath=path;this.userConstructor=method;this.hasConstructor=true;t.inheritsComments(construct,method);construct._ignoreUserWhitespace=true;construct.params=method.params;t.inherits(construct.body,method.body);construct.body.directives=method.body.directives;this._pushConstructor()};ClassTransformer.prototype._pushConstructor=function _pushConstructor(){if(this.pushedConstructor)return;this.pushedConstructor=true;if(this.hasInstanceDescriptors||this.hasStaticDescriptors){this.pushDescriptors()}this.body.push(this.constructor);this.pushInherits()};ClassTransformer.prototype.pushInherits=function pushInherits(){if(!this.isDerived||this.pushedInherits)return;this.pushedInherits=true;this.body.unshift(t.expressionStatement(t.callExpression(this.file.addHelper("inherits"),[this.classRef,this.superName])))};return ClassTransformer}();exports.default=ClassTransformer;module.exports=exports["default"]},{"babel-helper-define-map":63,"babel-helper-optimise-call-expression":69,"babel-helper-replace-supers":73,"babel-runtime/core-js/get-iterator":138,"babel-runtime/helpers/classCallCheck":152,"babel-template":156,"babel-traverse":160,"babel-types":193}],100:[function(require,module,exports){"use strict";exports.__esModule=true;var _getIterator2=require("babel-runtime/core-js/get-iterator");var _getIterator3=_interopRequireDefault(_getIterator2);exports.default=function(_ref){var t=_ref.types;var template=_ref.template;var buildMutatorMapAssign=template("\n MUTATOR_MAP_REF[KEY] = MUTATOR_MAP_REF[KEY] || {};\n MUTATOR_MAP_REF[KEY].KIND = VALUE;\n ");function getValue(prop){if(t.isObjectProperty(prop)){return prop.value}else if(t.isObjectMethod(prop)){return t.functionExpression(null,prop.params,prop.body,prop.generator,prop.async)}}function pushAssign(objId,prop,body){if(prop.kind==="get"&&prop.kind==="set"){pushMutatorDefine(objId,prop,body)}else{body.push(t.expressionStatement(t.assignmentExpression("=",t.memberExpression(objId,prop.key,prop.computed||t.isLiteral(prop.key)),getValue(prop))))}}function pushMutatorDefine(_ref2,prop){var objId=_ref2.objId;var body=_ref2.body;var getMutatorId=_ref2.getMutatorId;var scope=_ref2.scope;var key=!prop.computed&&t.isIdentifier(prop.key)?t.stringLiteral(prop.key.name):prop.key;var maybeMemoise=scope.maybeGenerateMemoised(key);if(maybeMemoise){body.push(t.expressionStatement(t.assignmentExpression("=",maybeMemoise,key)));key=maybeMemoise}body.push.apply(body,buildMutatorMapAssign({MUTATOR_MAP_REF:getMutatorId(),KEY:key,VALUE:getValue(prop),KIND:t.identifier(prop.kind)}))}function loose(info){for(var _iterator=info.computedProps,_isArray=Array.isArray(_iterator),_i=0,_iterator=_isArray?_iterator:(0,_getIterator3.default)(_iterator);;){var _ref3;if(_isArray){if(_i>=_iterator.length)break;_ref3=_iterator[_i++]}else{_i=_iterator.next();if(_i.done)break;_ref3=_i.value}var prop=_ref3;if(prop.kind==="get"||prop.kind==="set"){pushMutatorDefine(info,prop)}else{pushAssign(info.objId,prop,info.body)}}}function spec(info){var objId=info.objId;var body=info.body;var computedProps=info.computedProps;var state=info.state;for(var _iterator2=computedProps,_isArray2=Array.isArray(_iterator2),_i2=0,_iterator2=_isArray2?_iterator2:(0,_getIterator3.default)(_iterator2);;){var _ref4;if(_isArray2){if(_i2>=_iterator2.length)break;_ref4=_iterator2[_i2++]}else{_i2=_iterator2.next();if(_i2.done)break;_ref4=_i2.value}var prop=_ref4;var key=t.toComputedKey(prop);if(prop.kind==="get"||prop.kind==="set"){pushMutatorDefine(info,prop)}else if(t.isStringLiteral(key,{value:"__proto__"})){pushAssign(objId,prop,body)}else{if(computedProps.length===1){return t.callExpression(state.addHelper("defineProperty"),[info.initPropExpression,key,getValue(prop)])}else{body.push(t.expressionStatement(t.callExpression(state.addHelper("defineProperty"),[objId,key,getValue(prop)])))}}}}return{visitor:{ObjectExpression:{exit:function exit(path,state){var node=path.node;var parent=path.parent;var scope=path.scope;var hasComputed=false;for(var _iterator3=node.properties,_isArray3=Array.isArray(_iterator3),_i3=0,_iterator3=_isArray3?_iterator3:(0,_getIterator3.default)(_iterator3);;){var _ref5;if(_isArray3){if(_i3>=_iterator3.length)break;_ref5=_iterator3[_i3++]}else{_i3=_iterator3.next();if(_i3.done)break;_ref5=_i3.value}var prop=_ref5;hasComputed=prop.computed===true;if(hasComputed)break}if(!hasComputed)return;var initProps=[];var computedProps=[];var foundComputed=false;for(var _iterator4=node.properties,_isArray4=Array.isArray(_iterator4),_i4=0,_iterator4=_isArray4?_iterator4:(0,_getIterator3.default)(_iterator4);;){var _ref6;if(_isArray4){if(_i4>=_iterator4.length)break;_ref6=_iterator4[_i4++]}else{_i4=_iterator4.next();if(_i4.done)break;_ref6=_i4.value}var _prop=_ref6;if(_prop.computed){foundComputed=true}if(foundComputed){computedProps.push(_prop)}else{initProps.push(_prop)}}var objId=scope.generateUidIdentifierBasedOnNode(parent);var initPropExpression=t.objectExpression(initProps);var body=[];body.push(t.variableDeclaration("var",[t.variableDeclarator(objId,initPropExpression)]));var callback=spec;if(state.opts.loose)callback=loose;var mutatorRef=void 0;var getMutatorId=function getMutatorId(){if(!mutatorRef){mutatorRef=scope.generateUidIdentifier("mutatorMap");body.push(t.variableDeclaration("var",[t.variableDeclarator(mutatorRef,t.objectExpression([]))]))}return mutatorRef};var single=callback({scope:scope,objId:objId,body:body,computedProps:computedProps,initPropExpression:initPropExpression,getMutatorId:getMutatorId,state:state});if(mutatorRef){body.push(t.expressionStatement(t.callExpression(state.addHelper("defineEnumerableProperties"),[objId,mutatorRef])))}if(single){path.replaceWith(single)}else{body.push(t.expressionStatement(objId));path.replaceWithMultiple(body)}}}}}};function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}module.exports=exports["default"]},{"babel-runtime/core-js/get-iterator":138}],101:[function(require,module,exports){"use strict";exports.__esModule=true;var _classCallCheck2=require("babel-runtime/helpers/classCallCheck");var _classCallCheck3=_interopRequireDefault(_classCallCheck2);var _getIterator2=require("babel-runtime/core-js/get-iterator");var _getIterator3=_interopRequireDefault(_getIterator2);exports.default=function(_ref){var t=_ref.types;function variableDeclarationHasPattern(node){for(var _iterator=node.declarations,_isArray=Array.isArray(_iterator),_i=0,_iterator=_isArray?_iterator:(0,_getIterator3.default)(_iterator);;){var _ref2;if(_isArray){if(_i>=_iterator.length)break;_ref2=_iterator[_i++]}else{_i=_iterator.next();if(_i.done)break;_ref2=_i.value}var declar=_ref2;if(t.isPattern(declar.id)){return true}}return false}function hasRest(pattern){for(var _iterator2=pattern.elements,_isArray2=Array.isArray(_iterator2),_i2=0,_iterator2=_isArray2?_iterator2:(0,_getIterator3.default)(_iterator2);;){var _ref3;if(_isArray2){if(_i2>=_iterator2.length)break;_ref3=_iterator2[_i2++]}else{_i2=_iterator2.next();if(_i2.done)break;_ref3=_i2.value}var elem=_ref3;if(t.isRestElement(elem)){return true}}return false}var arrayUnpackVisitor={ReferencedIdentifier:function ReferencedIdentifier(path,state){if(state.bindings[path.node.name]){state.deopt=true;path.stop()}}};var DestructuringTransformer=function(){function DestructuringTransformer(opts){(0,_classCallCheck3.default)(this,DestructuringTransformer);this.blockHoist=opts.blockHoist;this.operator=opts.operator;this.arrays={};this.nodes=opts.nodes||[];this.scope=opts.scope;this.file=opts.file;this.kind=opts.kind}DestructuringTransformer.prototype.buildVariableAssignment=function buildVariableAssignment(id,init){var op=this.operator;if(t.isMemberExpression(id))op="=";var node=void 0;if(op){node=t.expressionStatement(t.assignmentExpression(op,id,init))}else{node=t.variableDeclaration(this.kind,[t.variableDeclarator(id,init)])}node._blockHoist=this.blockHoist;return node};DestructuringTransformer.prototype.buildVariableDeclaration=function buildVariableDeclaration(id,init){var declar=t.variableDeclaration("var",[t.variableDeclarator(id,init)]);declar._blockHoist=this.blockHoist;return declar};DestructuringTransformer.prototype.push=function push(id,init){if(t.isObjectPattern(id)){this.pushObjectPattern(id,init)}else if(t.isArrayPattern(id)){this.pushArrayPattern(id,init)}else if(t.isAssignmentPattern(id)){this.pushAssignmentPattern(id,init)}else{this.nodes.push(this.buildVariableAssignment(id,init))}};DestructuringTransformer.prototype.toArray=function toArray(node,count){if(this.file.opts.loose||t.isIdentifier(node)&&this.arrays[node.name]){return node}else{return this.scope.toArray(node,count)}};DestructuringTransformer.prototype.pushAssignmentPattern=function pushAssignmentPattern(pattern,valueRef){var tempValueRef=this.scope.generateUidIdentifierBasedOnNode(valueRef);var declar=t.variableDeclaration("var",[t.variableDeclarator(tempValueRef,valueRef)]);declar._blockHoist=this.blockHoist;this.nodes.push(declar);var tempConditional=t.conditionalExpression(t.binaryExpression("===",tempValueRef,t.identifier("undefined")),pattern.right,tempValueRef);var left=pattern.left;if(t.isPattern(left)){var tempValueDefault=t.expressionStatement(t.assignmentExpression("=",tempValueRef,tempConditional));tempValueDefault._blockHoist=this.blockHoist;this.nodes.push(tempValueDefault);this.push(left,tempValueRef)}else{this.nodes.push(this.buildVariableAssignment(left,tempConditional))}};DestructuringTransformer.prototype.pushObjectRest=function pushObjectRest(pattern,objRef,spreadProp,spreadPropIndex){var keys=[];for(var i=0;i=spreadPropIndex)break;if(t.isRestProperty(prop))continue;var key=prop.key;if(t.isIdentifier(key)&&!prop.computed)key=t.stringLiteral(prop.key.name);keys.push(key)}keys=t.arrayExpression(keys);var value=t.callExpression(this.file.addHelper("objectWithoutProperties"),[objRef,keys]);this.nodes.push(this.buildVariableAssignment(spreadProp.argument,value))};DestructuringTransformer.prototype.pushObjectProperty=function pushObjectProperty(prop,propRef){if(t.isLiteral(prop.key))prop.computed=true;var pattern=prop.value;var objRef=t.memberExpression(propRef,prop.key,prop.computed);if(t.isPattern(pattern)){this.push(pattern,objRef)}else{this.nodes.push(this.buildVariableAssignment(pattern,objRef))}};DestructuringTransformer.prototype.pushObjectPattern=function pushObjectPattern(pattern,objRef){if(!pattern.properties.length){this.nodes.push(t.expressionStatement(t.callExpression(this.file.addHelper("objectDestructuringEmpty"),[objRef])))}if(pattern.properties.length>1&&!this.scope.isStatic(objRef)){var temp=this.scope.generateUidIdentifierBasedOnNode(objRef);this.nodes.push(this.buildVariableDeclaration(temp,objRef));objRef=temp}for(var i=0;iarr.elements.length)return;if(pattern.elements.length - +