From 2ba1cfda746cb779071b9904df356670bc73bb6b Mon Sep 17 00:00:00 2001 From: Titus Wormer Date: Fri, 31 Jul 2015 10:52:38 +0200 Subject: [PATCH] Initial commit --- .editorconfig | 15 + .eslintignore | 6 + .eslintrc | 8 + .gitignore | 8 + .jscs.json | 146 ++ .mdastignore | 1 + .mdastrc | 13 + .travis.yml | 9 + LICENSE | 21 + bower.json | 35 + component.json | 24 + history.md | 6 + index.js | 279 ++++ package.json | 61 + readme.md | 340 +++++ test.js | 1106 +++++++++++++++ unified.js | 3469 ++++++++++++++++++++++++++++++++++++++++++++++++ unified.min.js | 1 + 18 files changed, 5548 insertions(+) create mode 100644 .editorconfig create mode 100644 .eslintignore create mode 100644 .eslintrc create mode 100644 .gitignore create mode 100644 .jscs.json create mode 100644 .mdastignore create mode 100644 .mdastrc create mode 100644 .travis.yml create mode 100644 LICENSE create mode 100644 bower.json create mode 100644 component.json create mode 100644 history.md create mode 100644 index.js create mode 100644 package.json create mode 100644 readme.md create mode 100644 test.js create mode 100644 unified.js create mode 100644 unified.min.js diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 00000000..dcd6f5ec --- /dev/null +++ b/.editorconfig @@ -0,0 +1,15 @@ +root = true + +[*] +indent_style = space +indent_size = 4 +end_of_line = lf +charset = utf-8 +trim_trailing_whitespace = true +insert_final_newline = true + +[*.{json,svg,mdastrc,eslintrc}] +indent_size = 2 + +[*.md] +trim_trailing_whitespace = false diff --git a/.eslintignore b/.eslintignore new file mode 100644 index 00000000..31fa4ea3 --- /dev/null +++ b/.eslintignore @@ -0,0 +1,6 @@ +build/ +components/ +coverage/ +build.js +unified.js +unified.min.js diff --git a/.eslintrc b/.eslintrc new file mode 100644 index 00000000..f244f524 --- /dev/null +++ b/.eslintrc @@ -0,0 +1,8 @@ +{ + "env": { + "node": true + }, + "rules": { + "quotes": [2, "single"] + } +} diff --git a/.gitignore b/.gitignore new file mode 100644 index 00000000..f41859aa --- /dev/null +++ b/.gitignore @@ -0,0 +1,8 @@ +.DS_Store +*.log +bower_components/ +build/ +components/ +coverage/ +node_modules/ +build.js diff --git a/.jscs.json b/.jscs.json new file mode 100644 index 00000000..c889e2d2 --- /dev/null +++ b/.jscs.json @@ -0,0 +1,146 @@ +{ + "excludeFiles": [ + "build/", + "components/", + "coverage/", + "node_modules/", + "build.js", + "unified.js", + "unified.min.js" + ], + "jsDoc": { + "checkAnnotations": "jsdoc3", + "checkParamNames": true, + "checkRedundantAccess": true, + "checkRedundantParams": true, + "checkRedundantReturns": true, + "checkReturnTypes": true, + "checkTypes": "strictNativeCase", + "enforceExistence": true, + "requireDescriptionCompleteSentence": true, + "requireHyphenBeforeDescription": true, + "requireNewlineAfterDescription": true, + "requireParamDescription": true, + "requireParamTypes": true, + "requireReturnTypes": true + }, + "requireCurlyBraces": [ + "if", + "else", + "for", + "while", + "do", + "try", + "catch" + ], + "requireSpaceAfterKeywords": [ + "if", + "else", + "for", + "while", + "do", + "switch", + "return", + "try", + "catch" + ], + "requireSpaceBeforeBlockStatements": true, + "requireParenthesesAroundIIFE": true, + "requireSpacesInConditionalExpression": true, + "requireSpacesInFunctionExpression": { + "beforeOpeningCurlyBrace": true + }, + "requireSpacesInAnonymousFunctionExpression": { + "beforeOpeningRoundBrace": true, + "beforeOpeningCurlyBrace": true + }, + "requireSpacesInNamedFunctionExpression": { + "beforeOpeningRoundBrace": true, + "beforeOpeningCurlyBrace": true + }, + "requireBlocksOnNewline": true, + "disallowEmptyBlocks": true, + "disallowSpacesInsideObjectBrackets": true, + "disallowSpacesInsideArrayBrackets": true, + "disallowSpacesInsideParentheses": true, + "requireSpacesInsideObjectBrackets": "all", + "disallowDanglingUnderscores": true, + "disallowSpaceAfterObjectKeys": true, + "requireCommaBeforeLineBreak": true, + "requireOperatorBeforeLineBreak": [ + "?", + "+", + "-", + "/", + "*", + "=", + "==", + "===", + "!=", + "!==", + ">", + ">=", + "<", + "<=" + ], + "requireSpaceBeforeBinaryOperators": [ + "+", + "-", + "/", + "*", + "=", + "==", + "===", + "!=", + "!==" + ], + "requireSpaceAfterBinaryOperators": [ + "+", + "-", + "/", + "*", + "=", + "==", + "===", + "!=", + "!==" + ], + "disallowSpaceAfterPrefixUnaryOperators": [ + "++", + "--", + "+", + "-", + "~", + "!" + ], + "disallowSpaceBeforePostfixUnaryOperators": [ + "++", + "--" + ], + "disallowImplicitTypeConversion": [ + "numeric", + "boolean", + "binary", + "string" + ], + "requireCamelCaseOrUpperCaseIdentifiers": true, + "disallowKeywords": [ + "with" + ], + "disallowMultipleLineStrings": true, + "disallowMultipleLineBreaks": true, + "validateLineBreaks": "LF", + "validateQuoteMarks": "'", + "disallowMixedSpacesAndTabs": true, + "disallowTrailingWhitespace": true, + "disallowTrailingComma": true, + "disallowKeywordsOnNewLine": [ + "else" + ], + "requireLineFeedAtFileEnd": true, + "maximumLineLength": 78, + "requireCapitalizedConstructors": true, + "safeContextKeyword": "self", + "requireDotNotation": true, + "disallowYodaConditions": true +} diff --git a/.mdastignore b/.mdastignore new file mode 100644 index 00000000..44be31f2 --- /dev/null +++ b/.mdastignore @@ -0,0 +1 @@ +components diff --git a/.mdastrc b/.mdastrc new file mode 100644 index 00000000..dd41d892 --- /dev/null +++ b/.mdastrc @@ -0,0 +1,13 @@ +{ + "output": true, + "plugins": [ + "lint", + "github", + "toc", + "validate-links", + "comment-config" + ], + "settings": { + "bullet": "*" + } +} diff --git a/.travis.yml b/.travis.yml new file mode 100644 index 00000000..8d459005 --- /dev/null +++ b/.travis.yml @@ -0,0 +1,9 @@ +language: node_js +script: npm run-script test-travis +node_js: +- '0.10' +- '0.11' +- '0.12' +- iojs +sudo: false +after_script: npm install codecov.io && cat ./coverage/lcov.info | codecov diff --git a/LICENSE b/LICENSE new file mode 100644 index 00000000..f3722d94 --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +(The MIT License) + +Copyright (c) 2015 Titus Wormer + +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. diff --git a/bower.json b/bower.json new file mode 100644 index 00000000..7064154f --- /dev/null +++ b/bower.json @@ -0,0 +1,35 @@ +{ + "name": "unified", + "main": "unified.js", + "description": "Text processing framework: Parse / Transform / Compile", + "license": "MIT", + "keywords": [ + "compose", + "connect", + "middleware", + "config", + "configuration" + ], + "repository": { + "type": "git", + "url": "https://github.com/wooorm/unified.git" + }, + "authors": [ + "Titus Wormer " + ], + "ignore": [ + ".*", + "*.log", + "*.md", + "*.sh", + "*.svg", + "build/", + "components/", + "coverage/", + "node_modules/", + "component.json", + "package.json", + "build.js", + "index.js" + ] +} diff --git a/component.json b/component.json new file mode 100644 index 00000000..839bd616 --- /dev/null +++ b/component.json @@ -0,0 +1,24 @@ +{ + "name": "unified", + "version": "0.0.0", + "description": "Text processing framework: Parse / Transform / Compile", + "license": "MIT", + "keywords": [ + "compose", + "connect", + "middleware", + "config", + "configuration" + ], + "dependencies": { + "segmentio/ware": "^1.0.0", + "wooorm/attach-ware": "^1.0.0", + "wooorm/bail": "^1.0.0", + "wooorm/unherit": "^1.0.4", + "wooorm/vfile": "^1.0.0" + }, + "repository": "wooorm/unified", + "scripts": [ + "index.js" + ] +} diff --git a/history.md b/history.md new file mode 100644 index 00000000..f4fbb8de --- /dev/null +++ b/history.md @@ -0,0 +1,6 @@ + + + + +0.0.0 / 2015-07-31 +================== diff --git a/index.js b/index.js new file mode 100644 index 00000000..43d8ff59 --- /dev/null +++ b/index.js @@ -0,0 +1,279 @@ +/** + * @author Titus Wormer + * @copyright 2015 Titus Wormer + * @license MIT + * @module unified + * @fileoverview Parse / Transform / Compile / Repeat. + */ + +'use strict'; + +/* + * Dependencies. + */ + +var bail = require('bail'); +var ware = require('ware'); +var AttachWare = require('attach-ware')(ware); +var VFile = require('vfile'); +var unherit = require('unherit'); + +/* + * Processing pipeline. + */ + +var pipeline = ware() + .use(function (ctx) { + ctx.tree = ctx.context.parse(ctx.file, ctx.settings); + }) + .use(function (ctx, next) { + ctx.context.run(ctx.tree, ctx.file, next); + }) + .use(function (ctx) { + ctx.result = ctx.context.stringify(ctx.tree, ctx.file, ctx.settings); + }); + +/** + * Construct a new Processor class based on the + * given options. + * + * @param {Object} options - Configuration. + * @param {string} options.name - Private storage. + * @param {string} options.type - Type of syntax tree. + * @param {Function} options.Parser - Class to turn a + * virtual file into a syntax tree. + * @param {Function} options.Compiler - Class to turn a + * syntax tree into a string. + * @return {Processor} - A new constructor. + */ +function unified(options) { + var name = options.name; + var type = options.type; + var Parser = options.Parser; + var Compiler = options.Compiler; + + /** + * Construct a Processor instance. + * + * @constructor + * @class {Processor} + */ + function Processor(processor) { + var self = this; + + if (!(self instanceof Processor)) { + return new Processor(processor); + } + + self.ware = new AttachWare(processor && processor.ware); + self.ware.context = self; + + self.Parser = unherit(Parser); + self.Compiler = unherit(Compiler); + } + + /** + * Either return `context` if its an instance + * of `Processor` or construct a new `Processor` + * instance. + * + * @private + * @param {Processor?} [context] - Context object. + * @return {Processor} - Either `context` or a new + * Processor instance. + */ + function instance(context) { + return context instanceof Processor ? context : new Processor(); + } + + /** + * Attach a plugin. + * + * @this {Processor?} - Either a Processor instance or + * the Processor constructor. + * @return {Processor} + */ + function use() { + var self = instance(this); + + self.ware.use.apply(self.ware, arguments); + + return self; + } + + /** + * Transform. + * + * @this {Processor?} - Either a Processor instance or + * the Processor constructor. + * @param {Node} [node] - Syntax tree. + * @param {VFile?} [file] - Virtual file. + * @param {Function?} [done] - Callback. + * @return {Node} - `node`. + */ + function run(node, file, done) { + var self = this; + var space; + + if (typeof file === 'function') { + done = file; + file = null; + } + + if (!file && node && !node.type) { + file = node; + node = null; + } + + file = new VFile(file); + space = file.namespace(name); + + if (!node) { + node = space[type] || node; + } else if (!space[type]) { + space[type] = node; + } + + if (!node) { + throw new Error('Expected node, got ' + node); + } + + done = typeof done === 'function' ? done : bail; + + /* + * Only run when this is an instance of Processor, + * and when there are transformers. + */ + + if (self.ware && self.ware.fns) { + self.ware.run(node, file, done); + } else { + done(null, node, file); + } + + return node; + } + + /** + * Parse a file. + * + * Patches the parsed node onto the `name` + * namespace on the `type` property. + * + * @this {Processor?} - Either a Processor instance or + * the Processor constructor. + * @param {string|VFile} value - Input to parse. + * @param {Object?} [settings] - Configuration. + * @return {Node} - `node`. + */ + function parse(value, settings) { + var file = new VFile(value); + var CustomParser = (this && this.Parser) || Parser; + var node = new CustomParser(file, settings).parse(); + + file.namespace(name)[type] = node; + + return node; + } + + /** + * Compile a file. + * + * Used the parsed node at the `name` + * namespace at `type` when no node was given. + * + * @this {Processor?} - Either a Processor instance or + * the Processor constructor. + * @param {Object} [node] - Syntax tree. + * @param {VFile} [file] - File with syntax tree. + * @param {Object?} [settings] - Configuration. + * @return {string} - Compiled `file`. + */ + function stringify(node, file, settings) { + var CustomCompiler = (this && this.Compiler) || Compiler; + var space; + + if (settings === null || settings === undefined) { + settings = file; + file = null; + } + + if (!file && node && !node.type) { + file = node; + node = null; + } + + file = new VFile(file); + space = file.namespace(name); + + if (!node) { + node = space[type] || node; + } else if (!space[type]) { + space[type] = node; + } + + if (!node) { + throw new Error('Expected node, got ' + node); + } + + return new CustomCompiler(file, settings).compile(); + } + + /** + * Parse / Transform / Compile. + * + * @this {Processor?} - Either a Processor instance or + * the Processor constructor. + * @param {string|VFile} value - Input to process. + * @param {Object?} [settings] - Configuration. + * @param {Function?} [done] - Callback. + * @return {string?} - Parsed document, when + * transformation was async. + */ + function process(value, settings, done) { + var self = instance(this); + var file = new VFile(value); + var result = null; + + if (typeof settings === 'function') { + done = settings; + settings = null; + } + + pipeline.run({ + 'context': self, + 'file': file, + 'settings': settings || {} + }, function (err, res) { + result = res && res.result; + + if (done) { + done(err, file, result); + } else if (err) { + bail(err); + } + }); + + return result; + } + + /* + * Methods / functions. + */ + + var proto = Processor.prototype; + + Processor.use = proto.use = use; + Processor.parse = proto.parse = parse; + Processor.run = proto.run = run; + Processor.stringify = proto.stringify = stringify; + Processor.process = proto.process = process; + + return Processor; +} + +/* + * Expose. + */ + +module.exports = unified; diff --git a/package.json b/package.json new file mode 100644 index 00000000..f901cde2 --- /dev/null +++ b/package.json @@ -0,0 +1,61 @@ +{ + "name": "unified", + "version": "0.0.0", + "description": "Text processing framework: Parse / Transform / Compile", + "license": "MIT", + "keywords": [ + "process", + "parse", + "transform", + "compile", + "stringify", + "retext", + "mdast" + ], + "dependencies": { + "attach-ware": "^1.0.0", + "bail": "^1.0.0", + "unherit": "^1.0.4", + "vfile": "^1.0.0", + "ware": "^1.3.0" + }, + "repository": { + "type": "git", + "url": "https://github.com/wooorm/unified.git" + }, + "author": "Titus Wormer ", + "files": [ + "index.js" + ], + "devDependencies": { + "browserify": "^11.0.0", + "eslint": "^0.24.0", + "esmangle": "^1.0.0", + "istanbul": "^0.3.0", + "jscs": "^2.0.0", + "jscs-jsdoc": "^1.0.0", + "mdast": "^0.27.1", + "mdast-comment-config": "^0.1.2", + "mdast-github": "^0.3.0", + "mdast-lint": "^0.4.0", + "mdast-man": "^0.4.0", + "mdast-toc": "^0.5.1", + "mdast-validate-links": "^0.3.0", + "mocha": "^2.0.0" + }, + "scripts": { + "test-api": "mocha --check-leaks test.js", + "test-coveralls": "istanbul cover _mocha --report lcovonly -- --check-leaks test.js", + "test-coverage": "istanbul cover _mocha -- -- test.js", + "test-travis": "npm run test-coveralls", + "test": "npm run test-api", + "lint-api": "eslint .", + "lint-style": "jscs --reporter inline .", + "lint": "npm run lint-api && npm run lint-style", + "make": "npm run lint && npm run test-coverage", + "build-md": "mdast . --quiet", + "build-bundle": "browserify index.js -s AttachWare > unified.js", + "postbuild-bundle": "esmangle unified.js > unified.min.js", + "build": "npm run build-md && npm run build-bundle" + } +} diff --git a/readme.md b/readme.md new file mode 100644 index 00000000..8bfce862 --- /dev/null +++ b/readme.md @@ -0,0 +1,340 @@ +# unified [![Build Status](https://img.shields.io/travis/wooorm/unified.svg)](https://travis-ci.org/wooorm/unified) [![Coverage Status](https://img.shields.io/codecov/c/github/wooorm/unified.svg)](https://codecov.io/github/wooorm/unified) + +Text processing framework: Parse / Transform / Compile. + +This library provides the boilerplate to make parsing and compiling pluggable. + +## Installation + +[npm](https://docs.npmjs.com/cli/install): + +```bash +npm install unified +``` + +**unified** is also available for [bower](http://bower.io/#install-packages), +[component](https://github.com/componentjs/component), and [duo](http://duojs.org/#getting-started), +and as an AMD, CommonJS, and globals module, [uncompressed](unified.js) and +[compressed](unified.min.js). + +## Usage + +From [**mdast**](https://github.com/wooorm/mdast/blob/master/index.js): + +```js +var unified = require('unified'); +var Parser = require('./lib/parse.js'); +var Compiler = require('./lib/stringify.js'); + +module.exports = unified({ + 'name': 'mdast', + 'type': 'ast', + 'Parser': Parser, + 'Compiler': Compiler +}); +``` + +## Table of Contents + +* [API](#api) + + * [unified(options)](#unifiedoptions) + + * [Processor([processor])](#processorprocessor) + + * [Processor#use(plugin[, input...])](#processoruseplugin-input) + + * [Plugin](#plugin) + + * [function attacher(processor[, input...])](#function-attacherprocessor-input) + * [function transformer(node, file[, next])](#function-transformernode-file-next) + + * [Processor#parse(file[, options])](#processorparsefile-options) + + * [Processor#run(node[, file][, done])](#processorrunnode-file-done) + + * [function done(err, node, file)](#function-doneerr-node-file) + + * [Processor#stringify(node[, file][, options])](#processorstringifynode-file-options) + + * [Processor#process(file[, options][, done])](#processorprocessfile-options-done) + + * [function done(err, doc, file)](#function-doneerr-doc-file) + +* [License](#license) + +## API + +### unified(options) + +Create a new `Processor` constructor. + +**Parameters** — `options` (`Object`): + +* `name` (`string`) — Unique namespace, e.g. `'mdast'` or `'retext'`. + +* `type` (`string`) — Type of the produced syntax tree. For example, + **mdast** uses an `'ast'` (Abstract Syntax Tree), whereas **retext** + uses a `'cst'` (Concrete Syntax Tree). + + Used to store the syntax tree after parsing on the file (at + `file.namespace(name)[type]`). + +* `Parser` (`Function`) — Constructor which transforms a virtual file + into a syntax tree. When input is parsed, this function will be + constructed with a `file` and `settings`. `Parser` instances should + have a `parse` method which returns a `node` (an object with a `type` + property). + + The string representation of a file can be accessed by executing + `file.toString();`. + +* `Compiler` (`Function`) — Constructor which transforms a node + into a string. When input is compiled, this function will be + constructed with a `file` and `settings`. `Compiler` instances should + have a `compile` method which returns a `string`. + + The syntax tree representation of a file can be accessed by executing + `file.namespace(name)[type]`. + +**Returns** — `Function` (`Processor` constructor). + +### Processor(\[processor\]) + +> Note that all methods on the instance are also available as functions on the +> constructor, which, when invoked, create a new instance. +> +> Thus, invoking `new Processor().process()` is the same as +> `Processor.process()`. + +Create a new `Processor` instance. + +**Parameters** + +* `processor` (`Processor`, optional) — Uses all plug-ins available on the + reference processor instance, on the newly constructed processor instance. + +**Returns** + +`Processor`. + +### Processor#use(plugin\[, input...\]) + +Change the way the processor works by using a plugin. + +**Signatures** + +* `unified = unified.use(plugin[, input...])`; +* `unified = unified.use(plugins)`. + +**Parameters** + +* `plugin` (`Function`) — [Plugin](#plugin). +* `plugins` (`Array.`) — List of plugins. +* `input` (`*`) — Passed to plugin. Specified by its documentation. + +**Returns** + +`Processor` — `this` (the context object). + +#### Plugin + +A **uniware** plugin changes the way the applied-on processor works. It does +two things: + +* It modifies the instance: such as changing the Parser or the Compiler; +* It transforms a syntax tree representation of a file. + +Both have their own function. The first is called an +[“attacher”](#function-attacherprocessor-input). The second is named a +[“transformer”](#function-transformernode-file-next). An “attacher” may +return a “transformer”. + +##### function attacher([processor](#processorprocessor)\[, input...\]) + +To modify the processor, create an attacher. An attacher is the thing passed to +[`use`](#processoruseplugin-input). It can +receive plugin specific options, but that’s entirely up to the third-party +developer. + +An **attacher** is invoked when the plugin is +[`use`](https://github.com/wooorm/mdast#mdastuseplugin-options)d, and can +return a transformer which will be called on subsequent +[`process()`](#processorprocessfile-options-done)s and +[`run()`](#processorrunnode-file-done)s. + +**Signatures** + +* `transformer? = attacher(processor[, input...])`. + +**Parameters** + +* `processor` (`Processor`) — Context on which the plugin was + [`use`](https://github.com/wooorm/mdast#mdastuseplugin-options)d; + +* `input` (`*`) — Passed by the user of a plug-in. + +**Returns** + +[`transformer`](#function-transformernode-file-next) (optional). + +##### function transformer(node, file\[, next\]) + +To transform a syntax tree, create a transformer. A transformer is a simple +(generator) function which is invoked each time a file is +[`process()`](#processorprocessfile-options-done)s and +[`run()`](#processorrunnode-file-done)s. A transformer should +change the syntax tree representation of a file. + +**Signatures** + +* `err? = transformer(node, file)`; +* `transformer(node, file, next)`; +* `Promise. = transformer(node, file)`; +* `transformer*(node, file)`. + +**Parameters** + +* `node` (`Node`) — Syntax tree representation of a file; + +* `file` (`VFile`) — [Virtual file](https://github.com/wooorm/vfile); + +* `next` (`function([err])`, optional) — If the signature includes both + `next`, `transformer` **may** finish asynchronous, and **must** + invoke `next()` on completion with an optional error. + +**Returns** — Optionally: + +* `Error` — Exception which will be thrown; + +* `Promise.` — Promise which must be resolved or rejected + on completion. + +### Processor#parse(file\[, options\]) + +Parse a document into a syntax tree. + +When given a file, stores the returned node on that file. + +**Signatures** + +* `node = processor.parse(file|value[, options])`. + +**Parameters** + +* `file` (`VFile`) — [Virtual file](https://github.com/wooorm/vfile). +* `value` (`string`) — String representation of a file. +* `options` (`Object`) — Configuration given to the parser. + +**Returns** + +`Node` — (`Object`). + +### Processor#run(node\[, file\]\[, done\]) + +Transform a syntax tree by applying plug-ins to it. + +Either a node or a file which was previously passed to `processor.parse()`, +must be given. + +**Signatures** + +* `node = processor.run(node[, file|value][, done])`; +* `node = processor.run(file[, done])`. + +**Parameters** + +* `node` (`Object`) — Syntax tree as returned by `parse()`; +* `file` (`VFile`) — [Virtual file](https://github.com/wooorm/vfile). +* `value` (`string`) — String representation of a file. +* `done` ([`function done(err, node, file)`](#function-doneerr-node-file)). + +**Returns** + +`Node` — The given syntax tree node. + +**Throws** + +When no `node` was given and no node was found on the file. + +#### function done(err, node, file) + +Invoked when transformation is complete. + +**Signatures** + +* `function done(err)`; +* `function done(null, node, file)`. + +**Parameters** + +* `exception` (`Error`) — Failure; +* `doc` (`string`) — Document generated by the process; +* `file` (`File`) — File object representing the input file; + +### Processor#stringify(node\[, file\]\[, options\]) + +Compile a syntax tree into a document. + +Either a node or a file which was previously passed to `processor.parse()`, +must be given. + +**Signatures** + +* `doc = processor.stringify(node[, file|value][, options])`; +* `doc = processor.stringify(file[, options])`. + +**Parameters** + +* `node` (`Object`) — Syntax tree as returned by `parse()`; +* `file` (`VFile`) — [Virtual file](https://github.com/wooorm/vfile). +* `value` (`string`) — String representation of a file. +* `options` (`Object`) — Configuration. + +**Returns** + +`doc` (`string`) — Document. + +**Throws** + +When no `node` was given and no node was found on the file. + +### Processor#process(file\[, options\]\[, done\]) + +Parse / Transform / Compile. When an async transformer is used, +`null` is returned and `done` must be given to receive the results +upon completion. + +**Signatures** + +* `doc = processor.process(file|value[, options][, done])`. + +**Parameters** + +* `file` (`File`) — [Virtual file](https://github.com/wooorm/vfile); +* `value` (`string`) — String representation of a file; +* `options` (`Object`) — Configuration. +* `done` ([`function done(err?, doc?, file?)`](#function-doneerr-doc-file)). + +**Returns** + +`string` — Document generated by the process; + +#### function done(err, doc, file) + +Invoked when processing is complete. + +**Signatures** + +* `function done(err)`; +* `function done(null, doc, file)`. + +**Parameters** + +* `exception` (`Error`) — Failure; +* `doc` (`string`) — Document generated by the process; +* `file` (`File`) — File object representing the input file; + +## License + +[MIT](LICENSE) © [Titus Wormer](http://wooorm.com) diff --git a/test.js b/test.js new file mode 100644 index 00000000..a9e7241d --- /dev/null +++ b/test.js @@ -0,0 +1,1106 @@ +'use strict'; + +/* eslint-env mocha */ + +/* + * Dependencies. + */ + +var assert = require('assert'); +var VFile = require('vfile'); +var unified = require('./'); + +/** + * No-operation. + */ +function noop() {} + +noop.compile = noop; +noop.parse = noop; + +/* + * Methods. + */ + +var equal = assert.strictEqual; +var dequal = assert.deepEqual; + +/* + * Tests. + */ + +describe('unified()', function () { + var Processor; + var proto; + + it('should create a new constructor', function () { + Processor = unified({ + 'name': 'foo', + 'type': 'bar', + 'Parser': noop, + 'Compiler': noop + }); + + equal(typeof Processor, 'function'); + + proto = Processor.prototype; + + equal(typeof proto, 'object'); + }); + + it('should expose the correct methods', function () { + equal(typeof proto.use, 'function'); + equal(typeof proto.parse, 'function'); + equal(typeof proto.run, 'function'); + equal(typeof proto.stringify, 'function'); + equal(typeof proto.process, 'function'); + }); + + it('should expose the correct functions', function () { + equal(typeof Processor.use, 'function'); + equal(typeof Processor.parse, 'function'); + equal(typeof Processor.run, 'function'); + equal(typeof Processor.stringify, 'function'); + equal(typeof Processor.process, 'function'); + }); + + describe('Processor', function () { + it('should create an instance', function () { + assert(new Processor() instanceof Processor); + }); + + it('should create an instance when without `new`', function () { + /* eslint-disable new-cap */ + assert(Processor() instanceof Processor); + /* eslint-enable new-cap */ + }); + + it('should create an instance when without `new`', function () { + /* eslint-disable new-cap */ + assert(Processor() instanceof Processor); + /* eslint-enable new-cap */ + }); + + it('should use the given processor', function () { + var p; + var q; + + /** + * Example plugin. + */ + function plugin() { + return noop; + } + + p = new Processor().use(plugin); + q = new Processor(p); + + dequal(p.ware.attachers, [plugin]); + dequal(p.ware.fns, [noop]); + dequal(q.ware.attachers, [plugin]); + dequal(q.ware.fns, [noop]); + }); + }); + + describe('Processor#use()', function () { + it('should return itself', function () { + var p = new Processor(); + + assert(p.use(noop), p); + }); + + it('should return a new instance when without context', function () { + assert(Processor.use(noop) instanceof Processor); + }); + + it('should invoke the attacher', function (done) { + var p = new Processor(); + + /** + * Example plugin. + */ + function plugin(context, one, two, three) { + assert(context, p); + assert(one, 1); + assert(two, 2); + assert(three, 3); + + done(); + } + + p.use(plugin, 1, 2, 3); + + dequal(p.ware.attachers, [plugin]); + }); + + it('should be able to return a transformer', function () { + var p = new Processor(); + + /** + * Example plugin. + */ + function plugin() { + return noop; + } + + p.use(plugin); + + dequal(p.ware.attachers, [plugin]); + dequal(p.ware.fns, [noop]); + }); + }); + + describe('Processor#parse()', function () { + it('should invoke the parser', function (done) { + var self; + var node = { + 'type': 'baz', + 'value': 'qux' + }; + + /** + * Example Parser. + */ + function Parser(file, options) { + self = this; + + equal(file.toString(), 'foo'); + equal(options, 'bar'); + } + + /** + * Example parse methods. + */ + function parse() { + equal(this, self); + + done(); + + return node; + } + + Parser.prototype.parse = parse; + + Processor.Parser = Parser; + + dequal(Processor.parse('foo', 'bar'), node); + + Processor.Parser = noop; + }); + + it('should invoke the bound parser when none is available on the ' + + 'context object', + function (done) { + /** + * Example parser. + */ + function Bound() {} + + Bound.prototype.parse = done; + + var parse = unified({ + 'name': 'foo', + 'type': 'bar', + 'Parser': Bound, + 'Compiler': noop + }).parse; + + parse(); + } + ); + }); + + describe('Processor#run()', function () { + it('should invoke a transformer', function (done) { + var tree = { + 'type': 'foo', + 'value': 'bar' + }; + + /** + * Example transformer. + */ + function transformer() { + done(); + } + + /** + * Example attacher. + */ + function attacher() { + return transformer; + } + + equal(new Processor().use(attacher).run(tree), tree); + }); + + it('should throw without node', function () { + assert.throws(function () { + new Processor().run(); + }, /Expected node, got undefined/); + }); + + it('should invoke `done`', function (done) { + var node = { + 'type': 'foo', + 'value': 'bar' + }; + + new Processor().run(node, function (err, tree, file) { + equal(err, null); + equal(tree, node); + equal(file.toString(), ''); + + done(err); + }); + }); + + it('should work with a file', function (done) { + var vfile = new VFile(); + var node = { + 'type': 'foo', + 'value': 'bar' + }; + + vfile.namespace('foo').bar = node; + + new Processor().run(vfile, function (err, tree, file) { + equal(err, null); + equal(tree, node); + equal(file, vfile); + + done(err); + }); + }); + + it('should work with a file and a node', function (done) { + var vfile = new VFile(); + var node = { + 'type': 'foo', + 'value': 'bar' + }; + + vfile.namespace('foo').bar = node; + + new Processor().run(node, vfile, function (err, tree, file) { + equal(err, null); + equal(tree, node); + equal(file, vfile); + + done(err); + }); + }); + + it('should work when used as a function', function (done) { + var node = { + 'type': 'foo', + 'value': 'bar' + }; + + Processor.run(node, function (err) { + done(err); + }); + }); + }); + + describe('Processor#stringify()', function () { + it('should invoke with node and settings', function (done) { + var self; + var node = { + 'type': 'baz', + 'value': 'qux' + }; + + /** + * Example `Compiler`. + */ + function Compiler(file, options) { + self = this; + + equal(file.namespace('foo').bar, node); + equal(options, 'bar'); + } + + /** + * Example `compile`. + */ + function compile() { + equal(this, self); + + done(); + + return 'qux'; + } + + Compiler.prototype.compile = compile; + + Processor.Compiler = Compiler; + + equal(Processor.stringify(node, 'bar'), 'qux'); + + Processor.Compiler = noop; + }); + + it('should work with a file and settings', function (done) { + var vfile = new VFile(); + var settings = { + 'qux': 'quux' + }; + var tree = { + 'type': 'foo', + 'value': 'bar' + }; + + /** + * Example `Compiler`. + */ + function Compiler(file, options) { + equal(file, vfile); + equal(options, settings); + } + + Compiler.prototype.compile = done; + + vfile.namespace('foo').bar = tree; + + Processor.Compiler = Compiler; + + Processor.stringify(vfile, settings); + + Processor.Compiler = noop; + }); + + it('should work with just a node', function (done) { + /** + * Example `Compiler`. + */ + function Compiler(file, options) { + equal(options, undefined); + } + + Compiler.prototype.compile = done; + + Processor.Compiler = Compiler; + + Processor.stringify({ + 'type': 'baz', + 'value': 'qux' + }); + + Processor.Compiler = noop; + }); + + it('should with just a node', function (done) { + var vfile = new VFile(); + var tree = { + 'type': 'foo', + 'value': 'bar' + }; + + /** + * Example `Compiler`. + */ + function Compiler(file, options) { + equal(file, vfile); + equal(options, undefined); + } + + Compiler.prototype.compile = done; + + Processor.Compiler = Compiler; + + vfile.namespace('foo').bar = tree; + + Processor.stringify(vfile); + + Processor.Compiler = noop; + }); + + it('should with all arguments', function (done) { + var vfile = new VFile(); + var settings = { + 'qux': 'quux' + }; + var tree = { + 'type': 'foo', + 'value': 'bar' + }; + + /** + * Example `Compiler`. + */ + function Compiler(file, options) { + equal(file, vfile); + equal(options, settings); + } + + Compiler.prototype.compile = done; + + Processor.Compiler = Compiler; + + vfile.namespace('foo').bar = tree; + + Processor.stringify(tree, vfile, settings); + + Processor.Compiler = noop; + }); + + it('should throw without node', function () { + assert.throws(function () { + Processor.stringify(new VFile()); + }, /Expected node, got null/); + + assert.throws(function () { + Processor.stringify(); + }, /Expected node, got undefined/); + }); + + it('should invoke the bound compiler when none is available on the ' + + 'context object', + function (done) { + /** + * Example `Processor`. + */ + function Bound() {} + + Bound.prototype.compile = done; + + var stringify = unified({ + 'name': 'foo', + 'type': 'bar', + 'Parser': noop, + 'Compiler': Bound + }).stringify; + + stringify({ + 'type': 'foo', + 'value': 'bar' + }); + } + ); + }); + + describe('Processor#process()', function () { + it('should support a value', function () { + var Processor2; + var isParsed; + var isCompiled; + + /** + * Example `Parser`. + */ + function Parser() {} + + /** + * Example `parse` function. + */ + function parse() { + isParsed = true; + return { + 'type': 'foo', + 'value': 'bar' + }; + } + + /** + * Example `Compiler`. + */ + function Compiler() {} + + /** + * Example `compile`. + */ + function compile() { + isCompiled = true; + return 'bar'; + } + + Parser.prototype.parse = parse; + Compiler.prototype.compile = compile; + + Processor2 = unified({ + 'name': 'foo', + 'type': 'bar', + 'Parser': Parser, + 'Compiler': Compiler + }); + + equal(new Processor2().process('bar'), 'bar'); + equal(isParsed, true); + equal(isCompiled, true); + }); + + it('should support a value and settings', function () { + var settings; + var Processor2; + var isParsed; + var isCompiled; + + /** + * Example `Parser`. + */ + function Parser(file, options) { + equal(file.toString(), 'bar'); + equal(options, settings); + } + + /** + * Example `parse` function. + */ + function parse() { + isParsed = true; + return { + 'type': 'foo', + 'value': 'bar' + }; + } + + /** + * Example `Compiler`. + */ + function Compiler(file, options) { + equal(file.toString(), 'bar'); + equal(options, settings); + } + + /** + * Example `compile`. + */ + function compile() { + isCompiled = true; + return 'bar'; + } + + Parser.prototype.parse = parse; + Compiler.prototype.compile = compile; + + Processor2 = unified({ + 'name': 'foo', + 'type': 'bar', + 'Parser': Parser, + 'Compiler': Compiler + }); + + settings = { + 'baz': 'qux' + }; + + equal(new Processor2().process('bar', settings), 'bar'); + equal(isParsed, true); + equal(isCompiled, true); + }); + + it('should support a value and a callback', function (done) { + var Processor2; + var isParsed; + var isCompiled; + + /** + * Example `Parser`. + */ + function Parser() {} + + /** + * Example `parse` function. + */ + function parse() { + isParsed = true; + return { + 'type': 'foo', + 'value': 'bar' + }; + } + + /** + * Example `Compiler`. + */ + function Compiler() {} + + /** + * Example `compile`. + */ + function compile() { + isCompiled = true; + return 'bar'; + } + + Parser.prototype.parse = parse; + Compiler.prototype.compile = compile; + + Processor2 = unified({ + 'name': 'foo', + 'type': 'bar', + 'Parser': Parser, + 'Compiler': Compiler + }); + + equal(new Processor2().process('bar', done), 'bar'); + equal(isParsed, true); + equal(isCompiled, true); + }); + + it('should support a file and settings', function () { + var vfile; + var settings; + var Processor2; + var isParsed; + var isCompiled; + + /** + * Example `Parser`. + */ + function Parser(file, options) { + equal(file, vfile); + equal(options, settings); + } + + /** + * Example `parse` function. + */ + function parse() { + isParsed = true; + return { + 'type': 'foo', + 'value': 'bar' + }; + } + + /** + * Example `Compiler`. + */ + function Compiler(file, options) { + equal(file, vfile); + equal(options, settings); + } + + /** + * Example `compile`. + */ + function compile() { + isCompiled = true; + return 'bar'; + } + + Parser.prototype.parse = parse; + Compiler.prototype.compile = compile; + + Processor2 = unified({ + 'name': 'foo', + 'type': 'bar', + 'Parser': Parser, + 'Compiler': Compiler + }); + + vfile = new VFile('bar'); + + settings = { + 'baz': 'qux' + }; + + equal(new Processor2().process(vfile, settings), 'bar'); + equal(isParsed, true); + equal(isCompiled, true); + }); + + it('should support a file and a callback', function (done) { + var vfile; + var Processor2; + var isParsed; + var isCompiled; + + /** + * Example `Parser`. + */ + function Parser(file) { + equal(file, vfile); + } + + /** + * Example `parse` function. + */ + function parse() { + isParsed = true; + return { + 'type': 'foo', + 'value': 'bar' + }; + } + + /** + * Example `Compiler`. + */ + function Compiler(file) { + equal(file, vfile); + } + + /** + * Example `compile`. + */ + function compile() { + isCompiled = true; + return 'bar'; + } + + Parser.prototype.parse = parse; + Compiler.prototype.compile = compile; + + Processor2 = unified({ + 'name': 'foo', + 'type': 'bar', + 'Parser': Parser, + 'Compiler': Compiler + }); + + vfile = new VFile('bar'); + + equal(new Processor2().process(vfile, done), 'bar'); + equal(isParsed, true); + equal(isCompiled, true); + }); + + it('should support a file and settings', function () { + var vfile; + var settings; + var Processor2; + var isParsed; + var isCompiled; + + /** + * Example `Parser`. + */ + function Parser(file, options) { + equal(file, vfile); + equal(options, settings); + } + + /** + * Example `parse` function. + */ + function parse() { + isParsed = true; + return { + 'type': 'foo', + 'value': 'bar' + }; + } + + /** + * Example `Compiler`. + */ + function Compiler(file, options) { + equal(file, vfile); + equal(options, settings); + } + + /** + * Example `compile`. + */ + function compile() { + isCompiled = true; + return 'bar'; + } + + Parser.prototype.parse = parse; + Compiler.prototype.compile = compile; + + Processor2 = unified({ + 'name': 'foo', + 'type': 'bar', + 'Parser': Parser, + 'Compiler': Compiler + }); + + vfile = new VFile('bar'); + + settings = { + 'baz': 'qux' + }; + + equal(new Processor2().process(vfile, settings), 'bar'); + equal(isParsed, true); + equal(isCompiled, true); + }); + + it('should support file, settings, and a callback', function (done) { + var vfile; + var settings; + var processor; + var isParsed; + var isCompiled; + + /** + * Example `Parser`. + */ + function Parser(file, options) { + equal(file, vfile); + equal(options, settings); + } + + /** + * Example `parse` function. + */ + function parse() { + isParsed = true; + return { + 'type': 'foo', + 'value': 'bar' + }; + } + + /** + * Example `Compiler`. + */ + function Compiler(file, options) { + equal(file, vfile); + equal(options, settings); + } + + /** + * Example `compile`. + */ + function compile() { + isCompiled = true; + return 'bar'; + } + + Parser.prototype.parse = parse; + Compiler.prototype.compile = compile; + + processor = unified({ + 'name': 'foo', + 'type': 'bar', + 'Parser': Parser, + 'Compiler': Compiler + }); + + vfile = new VFile('bar'); + + settings = { + 'baz': 'qux' + }; + + equal(processor.process(vfile, settings, done), 'bar'); + equal(isParsed, true); + equal(isCompiled, true); + }); + + it('should throw a sync parse error', function () { + var processor; + + /** + * Example `Parser`. + */ + function Parser(file) { + this.file = file; + } + + /** + * Example `parse` function. + */ + function parse() { + this.file.fail('Warning'); + } + + Parser.prototype.parse = parse; + + processor = unified({ + 'name': 'foo', + 'type': 'bar', + 'Parser': Parser, + 'Compiler': noop + }); + + assert.throws(function () { + processor.process('foo'); + }, /1:1: Warning/); + }); + + it('should throw a sync compile error', function () { + var processor; + + /** + * Example `Parser`. + */ + function Parser() {} + + /** + * Example `parse` function. + */ + function parse() { + return { + 'type': 'foo', + 'value': 'bar' + }; + } + + /** + * Example `Compiler`. + */ + function Compiler(file) { + this.file = file; + } + + /** + * Example `compile`. + */ + function compile() { + this.file.fail('Warning'); + } + + Parser.prototype.parse = parse; + Compiler.prototype.compile = compile; + + processor = unified({ + 'name': 'foo', + 'type': 'bar', + 'Parser': Parser, + 'Compiler': Compiler + }); + + assert.throws(function () { + processor.process('foo'); + }, /1:1: Warning/); + }); + + it('should throw a sync run error', function () { + var processor; + + /** + * Example `Parser`. + */ + function Parser() {} + + /** + * Example `parse` function. + */ + function parse() { + return { + 'type': 'foo', + 'value': 'bar' + }; + } + + Parser.prototype.parse = parse; + + processor = unified({ + 'name': 'foo', + 'type': 'bar', + 'Parser': Parser, + 'Compiler': noop + }).use(function () { + return function (ast, file) { + file.fail('Warning'); + }; + }); + + assert.throws(function () { + processor.process('foo'); + }, /1:1: Warning/); + }); + + it('should pass an async parse error', function (done) { + /** + * Example `Parser`. + */ + function Parser(file) { + this.file = file; + } + + /** + * Example `parse` function. + */ + function parse() { + this.file.fail('Warning'); + } + + Parser.prototype.parse = parse; + + unified({ + 'name': 'foo', + 'type': 'bar', + 'Parser': Parser, + 'Compiler': noop + }).process('foo', function (err) { + equal(String(err), '1:1: Warning'); + done(); + }); + }); + + it('should pass an async compile error', function (done) { + /** + * Example `Parser`. + */ + function Parser() {} + + /** + * Example `parse` function. + */ + function parse() { + return { + 'type': 'foo', + 'value': 'bar' + }; + } + + /** + * Example `Compiler`. + */ + function Compiler(file) { + this.file = file; + } + + /** + * Example `compile`. + */ + function compile() { + this.file.fail('Warning'); + } + + Parser.prototype.parse = parse; + Compiler.prototype.compile = compile; + + unified({ + 'name': 'foo', + 'type': 'bar', + 'Parser': Parser, + 'Compiler': Compiler + }).process('foo', function (err) { + equal(String(err), '1:1: Warning'); + done(); + }); + }); + + it('should pass an async run error', function (done) { + /** + * Example `Parser`. + */ + function Parser() {} + + /** + * Example `parse` function. + */ + function parse() { + return { + 'type': 'foo', + 'value': 'bar' + }; + } + + Parser.prototype.parse = parse; + + unified({ + 'name': 'foo', + 'type': 'bar', + 'Parser': Parser, + 'Compiler': noop + }).use(function () { + return function (ast, file) { + file.fail('Warning'); + }; + }).process('bar', function (err) { + equal(String(err), '1:1: Warning'); + done(); + }); + }); + }); +}); diff --git a/unified.js b/unified.js new file mode 100644 index 00000000..245e8d6d --- /dev/null +++ b/unified.js @@ -0,0 +1,3469 @@ +(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.AttachWare = 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 + * @license MIT + */ + +var base64 = require('base64-js') +var ieee754 = require('ieee754') +var isArray = require('is-array') + +exports.Buffer = Buffer +exports.SlowBuffer = SlowBuffer +exports.INSPECT_MAX_BYTES = 50 +Buffer.poolSize = 8192 // not used by this implementation + +var rootParent = {} + +/** + * If `Buffer.TYPED_ARRAY_SUPPORT`: + * === true Use Uint8Array implementation (fastest) + * === false Use Object implementation (most compatible, even IE6) + * + * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, + * Opera 11.6+, iOS 4.2+. + * + * Note: + * + * - Implementation must support adding new properties to `Uint8Array` instances. + * Firefox 4-29 lacked support, fixed in Firefox 30+. + * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438. + * + * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function. + * + * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of + * incorrect length in some situations. + * + * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they will + * get the Object implementation, which is slower but will work correctly. + */ +Buffer.TYPED_ARRAY_SUPPORT = (function () { + function Foo () {} + try { + var buf = new ArrayBuffer(0) + var arr = new Uint8Array(buf) + arr.foo = function () { return 42 } + arr.constructor = Foo + return arr.foo() === 42 && // typed array instances can be augmented + arr.constructor === Foo && // constructor can be set + typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray` + new Uint8Array(1).subarray(1, 1).byteLength === 0 // ie10 has broken `subarray` + } catch (e) { + return false + } +})() + +function kMaxLength () { + return Buffer.TYPED_ARRAY_SUPPORT + ? 0x7fffffff + : 0x3fffffff +} + +/** + * Class: Buffer + * ============= + * + * The Buffer constructor returns instances of `Uint8Array` that are augmented + * with function properties for all the node `Buffer` API functions. We use + * `Uint8Array` so that square bracket notation works as expected -- it returns + * a single octet. + * + * By augmenting the instances, we can avoid modifying the `Uint8Array` + * prototype. + */ +function Buffer (arg) { + if (!(this instanceof Buffer)) { + // Avoid going through an ArgumentsAdaptorTrampoline in the common case. + if (arguments.length > 1) return new Buffer(arg, arguments[1]) + return new Buffer(arg) + } + + this.length = 0 + this.parent = undefined + + // Common case. + if (typeof arg === 'number') { + return fromNumber(this, arg) + } + + // Slightly less common case. + if (typeof arg === 'string') { + return fromString(this, arg, arguments.length > 1 ? arguments[1] : 'utf8') + } + + // Unusual. + return fromObject(this, arg) +} + +function fromNumber (that, length) { + that = allocate(that, length < 0 ? 0 : checked(length) | 0) + if (!Buffer.TYPED_ARRAY_SUPPORT) { + for (var i = 0; i < length; i++) { + that[i] = 0 + } + } + return that +} + +function fromString (that, string, encoding) { + if (typeof encoding !== 'string' || encoding === '') encoding = 'utf8' + + // Assumption: byteLength() return value is always < kMaxLength. + var length = byteLength(string, encoding) | 0 + that = allocate(that, length) + + that.write(string, encoding) + return that +} + +function fromObject (that, object) { + if (Buffer.isBuffer(object)) return fromBuffer(that, object) + + if (isArray(object)) return fromArray(that, object) + + if (object == null) { + throw new TypeError('must start with number, buffer, array or string') + } + + if (typeof ArrayBuffer !== 'undefined' && object.buffer instanceof ArrayBuffer) { + return fromTypedArray(that, object) + } + + if (object.length) return fromArrayLike(that, object) + + return fromJsonObject(that, object) +} + +function fromBuffer (that, buffer) { + var length = checked(buffer.length) | 0 + that = allocate(that, length) + buffer.copy(that, 0, 0, length) + return that +} + +function fromArray (that, array) { + var length = checked(array.length) | 0 + that = allocate(that, length) + for (var i = 0; i < length; i += 1) { + that[i] = array[i] & 255 + } + return that +} + +// Duplicate of fromArray() to keep fromArray() monomorphic. +function fromTypedArray (that, array) { + var length = checked(array.length) | 0 + that = allocate(that, length) + // Truncating the elements is probably not what people expect from typed + // arrays with BYTES_PER_ELEMENT > 1 but it's compatible with the behavior + // of the old Buffer constructor. + for (var i = 0; i < length; i += 1) { + that[i] = array[i] & 255 + } + return that +} + +function fromArrayLike (that, array) { + var length = checked(array.length) | 0 + that = allocate(that, length) + for (var i = 0; i < length; i += 1) { + that[i] = array[i] & 255 + } + return that +} + +// Deserialize { type: 'Buffer', data: [1,2,3,...] } into a Buffer object. +// Returns a zero-length buffer for inputs that don't conform to the spec. +function fromJsonObject (that, object) { + var array + var length = 0 + + if (object.type === 'Buffer' && isArray(object.data)) { + array = object.data + length = checked(array.length) | 0 + } + that = allocate(that, length) + + for (var i = 0; i < length; i += 1) { + that[i] = array[i] & 255 + } + return that +} + +function allocate (that, length) { + if (Buffer.TYPED_ARRAY_SUPPORT) { + // Return an augmented `Uint8Array` instance, for best performance + that = Buffer._augment(new Uint8Array(length)) + } else { + // Fallback: Return an object instance of the Buffer class + that.length = length + that._isBuffer = true + } + + var fromPool = length !== 0 && length <= Buffer.poolSize >>> 1 + if (fromPool) that.parent = rootParent + + return that +} + +function checked (length) { + // Note: cannot use `length < kMaxLength` here because that fails when + // length is NaN (which is otherwise coerced to zero.) + if (length >= kMaxLength()) { + throw new RangeError('Attempt to allocate Buffer larger than maximum ' + + 'size: 0x' + kMaxLength().toString(16) + ' bytes') + } + return length | 0 +} + +function SlowBuffer (subject, encoding) { + if (!(this instanceof SlowBuffer)) return new SlowBuffer(subject, encoding) + + var buf = new Buffer(subject, encoding) + delete buf.parent + return buf +} + +Buffer.isBuffer = function isBuffer (b) { + return !!(b != null && b._isBuffer) +} + +Buffer.compare = function compare (a, b) { + if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) { + throw new TypeError('Arguments must be Buffers') + } + + if (a === b) return 0 + + var x = a.length + var y = b.length + + var i = 0 + var len = Math.min(x, y) + while (i < len) { + if (a[i] !== b[i]) break + + ++i + } + + if (i !== len) { + x = a[i] + y = b[i] + } + + if (x < y) return -1 + if (y < x) return 1 + return 0 +} + +Buffer.isEncoding = function isEncoding (encoding) { + switch (String(encoding).toLowerCase()) { + case 'hex': + case 'utf8': + case 'utf-8': + case 'ascii': + case 'binary': + case 'base64': + case 'raw': + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return true + default: + return false + } +} + +Buffer.concat = function concat (list, length) { + if (!isArray(list)) throw new TypeError('list argument must be an Array of Buffers.') + + if (list.length === 0) { + return new Buffer(0) + } else if (list.length === 1) { + return list[0] + } + + var i + if (length === undefined) { + length = 0 + for (i = 0; i < list.length; i++) { + length += list[i].length + } + } + + var buf = new Buffer(length) + var pos = 0 + for (i = 0; i < list.length; i++) { + var item = list[i] + item.copy(buf, pos) + pos += item.length + } + return buf +} + +function byteLength (string, encoding) { + if (typeof string !== 'string') string = '' + string + + var len = string.length + if (len === 0) return 0 + + // Use a for loop to avoid recursion + var loweredCase = false + for (;;) { + switch (encoding) { + case 'ascii': + case 'binary': + // Deprecated + case 'raw': + case 'raws': + return len + case 'utf8': + case 'utf-8': + return utf8ToBytes(string).length + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return len * 2 + case 'hex': + return len >>> 1 + case 'base64': + return base64ToBytes(string).length + default: + if (loweredCase) return utf8ToBytes(string).length // assume utf8 + encoding = ('' + encoding).toLowerCase() + loweredCase = true + } + } +} +Buffer.byteLength = byteLength + +// pre-set for values that may exist in the future +Buffer.prototype.length = undefined +Buffer.prototype.parent = undefined + +function slowToString (encoding, start, end) { + var loweredCase = false + + start = start | 0 + end = end === undefined || end === Infinity ? this.length : end | 0 + + if (!encoding) encoding = 'utf8' + if (start < 0) start = 0 + if (end > this.length) end = this.length + if (end <= start) return '' + + while (true) { + switch (encoding) { + case 'hex': + return hexSlice(this, start, end) + + case 'utf8': + case 'utf-8': + return utf8Slice(this, start, end) + + case 'ascii': + return asciiSlice(this, start, end) + + case 'binary': + return binarySlice(this, start, end) + + case 'base64': + return base64Slice(this, start, end) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return utf16leSlice(this, start, end) + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = (encoding + '').toLowerCase() + loweredCase = true + } + } +} + +Buffer.prototype.toString = function toString () { + var length = this.length | 0 + if (length === 0) return '' + if (arguments.length === 0) return utf8Slice(this, 0, length) + return slowToString.apply(this, arguments) +} + +Buffer.prototype.equals = function equals (b) { + if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer') + if (this === b) return true + return Buffer.compare(this, b) === 0 +} + +Buffer.prototype.inspect = function inspect () { + var str = '' + var max = exports.INSPECT_MAX_BYTES + if (this.length > 0) { + str = this.toString('hex', 0, max).match(/.{2}/g).join(' ') + if (this.length > max) str += ' ... ' + } + return '' +} + +Buffer.prototype.compare = function compare (b) { + if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer') + if (this === b) return 0 + return Buffer.compare(this, b) +} + +Buffer.prototype.indexOf = function indexOf (val, byteOffset) { + if (byteOffset > 0x7fffffff) byteOffset = 0x7fffffff + else if (byteOffset < -0x80000000) byteOffset = -0x80000000 + byteOffset >>= 0 + + if (this.length === 0) return -1 + if (byteOffset >= this.length) return -1 + + // Negative offsets start from the end of the buffer + if (byteOffset < 0) byteOffset = Math.max(this.length + byteOffset, 0) + + if (typeof val === 'string') { + if (val.length === 0) return -1 // special case: looking for empty string always fails + return String.prototype.indexOf.call(this, val, byteOffset) + } + if (Buffer.isBuffer(val)) { + return arrayIndexOf(this, val, byteOffset) + } + if (typeof val === 'number') { + if (Buffer.TYPED_ARRAY_SUPPORT && Uint8Array.prototype.indexOf === 'function') { + return Uint8Array.prototype.indexOf.call(this, val, byteOffset) + } + return arrayIndexOf(this, [ val ], byteOffset) + } + + function arrayIndexOf (arr, val, byteOffset) { + var foundIndex = -1 + for (var i = 0; byteOffset + i < arr.length; i++) { + if (arr[byteOffset + i] === val[foundIndex === -1 ? 0 : i - foundIndex]) { + if (foundIndex === -1) foundIndex = i + if (i - foundIndex + 1 === val.length) return byteOffset + foundIndex + } else { + foundIndex = -1 + } + } + return -1 + } + + throw new TypeError('val must be string, number or Buffer') +} + +// `get` will be removed in Node 0.13+ +Buffer.prototype.get = function get (offset) { + console.log('.get() is deprecated. Access using array indexes instead.') + return this.readUInt8(offset) +} + +// `set` will be removed in Node 0.13+ +Buffer.prototype.set = function set (v, offset) { + console.log('.set() is deprecated. Access using array indexes instead.') + return this.writeUInt8(v, offset) +} + +function hexWrite (buf, string, offset, length) { + offset = Number(offset) || 0 + var remaining = buf.length - offset + if (!length) { + length = remaining + } else { + length = Number(length) + if (length > remaining) { + length = remaining + } + } + + // must be an even number of digits + var strLen = string.length + if (strLen % 2 !== 0) throw new Error('Invalid hex string') + + if (length > strLen / 2) { + length = strLen / 2 + } + for (var i = 0; i < length; i++) { + var parsed = parseInt(string.substr(i * 2, 2), 16) + if (isNaN(parsed)) throw new Error('Invalid hex string') + buf[offset + i] = parsed + } + return i +} + +function utf8Write (buf, string, offset, length) { + return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) +} + +function asciiWrite (buf, string, offset, length) { + return blitBuffer(asciiToBytes(string), buf, offset, length) +} + +function binaryWrite (buf, string, offset, length) { + return asciiWrite(buf, string, offset, length) +} + +function base64Write (buf, string, offset, length) { + return blitBuffer(base64ToBytes(string), buf, offset, length) +} + +function ucs2Write (buf, string, offset, length) { + return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) +} + +Buffer.prototype.write = function write (string, offset, length, encoding) { + // Buffer#write(string) + if (offset === undefined) { + encoding = 'utf8' + length = this.length + offset = 0 + // Buffer#write(string, encoding) + } else if (length === undefined && typeof offset === 'string') { + encoding = offset + length = this.length + offset = 0 + // Buffer#write(string, offset[, length][, encoding]) + } else if (isFinite(offset)) { + offset = offset | 0 + if (isFinite(length)) { + length = length | 0 + if (encoding === undefined) encoding = 'utf8' + } else { + encoding = length + length = undefined + } + // legacy write(string, encoding, offset, length) - remove in v0.13 + } else { + var swap = encoding + encoding = offset + offset = length | 0 + length = swap + } + + var remaining = this.length - offset + if (length === undefined || length > remaining) length = remaining + + if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { + throw new RangeError('attempt to write outside buffer bounds') + } + + if (!encoding) encoding = 'utf8' + + var loweredCase = false + for (;;) { + switch (encoding) { + case 'hex': + return hexWrite(this, string, offset, length) + + case 'utf8': + case 'utf-8': + return utf8Write(this, string, offset, length) + + case 'ascii': + return asciiWrite(this, string, offset, length) + + case 'binary': + return binaryWrite(this, string, offset, length) + + case 'base64': + // Warning: maxLength not taken into account in base64Write + return base64Write(this, string, offset, length) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return ucs2Write(this, string, offset, length) + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = ('' + encoding).toLowerCase() + loweredCase = true + } + } +} + +Buffer.prototype.toJSON = function toJSON () { + return { + type: 'Buffer', + data: Array.prototype.slice.call(this._arr || this, 0) + } +} + +function base64Slice (buf, start, end) { + if (start === 0 && end === buf.length) { + return base64.fromByteArray(buf) + } else { + return base64.fromByteArray(buf.slice(start, end)) + } +} + +function utf8Slice (buf, start, end) { + var res = '' + var tmp = '' + end = Math.min(buf.length, end) + + for (var i = start; i < end; i++) { + if (buf[i] <= 0x7F) { + res += decodeUtf8Char(tmp) + String.fromCharCode(buf[i]) + tmp = '' + } else { + tmp += '%' + buf[i].toString(16) + } + } + + return res + decodeUtf8Char(tmp) +} + +function asciiSlice (buf, start, end) { + var ret = '' + end = Math.min(buf.length, end) + + for (var i = start; i < end; i++) { + ret += String.fromCharCode(buf[i] & 0x7F) + } + return ret +} + +function binarySlice (buf, start, end) { + var ret = '' + end = Math.min(buf.length, end) + + for (var i = start; i < end; i++) { + ret += String.fromCharCode(buf[i]) + } + return ret +} + +function hexSlice (buf, start, end) { + var len = buf.length + + if (!start || start < 0) start = 0 + if (!end || end < 0 || end > len) end = len + + var out = '' + for (var i = start; i < end; i++) { + out += toHex(buf[i]) + } + return out +} + +function utf16leSlice (buf, start, end) { + var bytes = buf.slice(start, end) + var res = '' + for (var i = 0; i < bytes.length; i += 2) { + res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256) + } + return res +} + +Buffer.prototype.slice = function slice (start, end) { + var len = this.length + start = ~~start + end = end === undefined ? len : ~~end + + if (start < 0) { + start += len + if (start < 0) start = 0 + } else if (start > len) { + start = len + } + + if (end < 0) { + end += len + if (end < 0) end = 0 + } else if (end > len) { + end = len + } + + if (end < start) end = start + + var newBuf + if (Buffer.TYPED_ARRAY_SUPPORT) { + newBuf = Buffer._augment(this.subarray(start, end)) + } else { + var sliceLen = end - start + newBuf = new Buffer(sliceLen, undefined) + for (var i = 0; i < sliceLen; i++) { + newBuf[i] = this[i + start] + } + } + + if (newBuf.length) newBuf.parent = this.parent || this + + return newBuf +} + +/* + * Need to make sure that buffer isn't trying to write out of bounds. + */ +function checkOffset (offset, ext, length) { + if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') + if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') +} + +Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { + offset = offset | 0 + byteLength = byteLength | 0 + if (!noAssert) checkOffset(offset, byteLength, this.length) + + var val = this[offset] + var mul = 1 + var i = 0 + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul + } + + return val +} + +Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { + offset = offset | 0 + byteLength = byteLength | 0 + if (!noAssert) { + checkOffset(offset, byteLength, this.length) + } + + var val = this[offset + --byteLength] + var mul = 1 + while (byteLength > 0 && (mul *= 0x100)) { + val += this[offset + --byteLength] * mul + } + + return val +} + +Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { + if (!noAssert) checkOffset(offset, 1, this.length) + return this[offset] +} + +Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length) + return this[offset] | (this[offset + 1] << 8) +} + +Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length) + return (this[offset] << 8) | this[offset + 1] +} + +Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) + + return ((this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16)) + + (this[offset + 3] * 0x1000000) +} + +Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) + + return (this[offset] * 0x1000000) + + ((this[offset + 1] << 16) | + (this[offset + 2] << 8) | + this[offset + 3]) +} + +Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { + offset = offset | 0 + byteLength = byteLength | 0 + if (!noAssert) checkOffset(offset, byteLength, this.length) + + var val = this[offset] + var mul = 1 + var i = 0 + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul + } + mul *= 0x80 + + if (val >= mul) val -= Math.pow(2, 8 * byteLength) + + return val +} + +Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { + offset = offset | 0 + byteLength = byteLength | 0 + if (!noAssert) checkOffset(offset, byteLength, this.length) + + var i = byteLength + var mul = 1 + var val = this[offset + --i] + while (i > 0 && (mul *= 0x100)) { + val += this[offset + --i] * mul + } + mul *= 0x80 + + if (val >= mul) val -= Math.pow(2, 8 * byteLength) + + return val +} + +Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) { + if (!noAssert) checkOffset(offset, 1, this.length) + if (!(this[offset] & 0x80)) return (this[offset]) + return ((0xff - this[offset] + 1) * -1) +} + +Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length) + var val = this[offset] | (this[offset + 1] << 8) + return (val & 0x8000) ? val | 0xFFFF0000 : val +} + +Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length) + var val = this[offset + 1] | (this[offset] << 8) + return (val & 0x8000) ? val | 0xFFFF0000 : val +} + +Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) + + return (this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16) | + (this[offset + 3] << 24) +} + +Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) + + return (this[offset] << 24) | + (this[offset + 1] << 16) | + (this[offset + 2] << 8) | + (this[offset + 3]) +} + +Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) + return ieee754.read(this, offset, true, 23, 4) +} + +Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) + return ieee754.read(this, offset, false, 23, 4) +} + +Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 8, this.length) + return ieee754.read(this, offset, true, 52, 8) +} + +Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 8, this.length) + return ieee754.read(this, offset, false, 52, 8) +} + +function checkInt (buf, value, offset, ext, max, min) { + if (!Buffer.isBuffer(buf)) throw new TypeError('buffer must be a Buffer instance') + if (value > max || value < min) throw new RangeError('value is out of bounds') + if (offset + ext > buf.length) throw new RangeError('index out of range') +} + +Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { + value = +value + offset = offset | 0 + byteLength = byteLength | 0 + if (!noAssert) checkInt(this, value, offset, byteLength, Math.pow(2, 8 * byteLength), 0) + + var mul = 1 + var i = 0 + this[offset] = value & 0xFF + while (++i < byteLength && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF + } + + return offset + byteLength +} + +Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { + value = +value + offset = offset | 0 + byteLength = byteLength | 0 + if (!noAssert) checkInt(this, value, offset, byteLength, Math.pow(2, 8 * byteLength), 0) + + var i = byteLength - 1 + var mul = 1 + this[offset + i] = value & 0xFF + while (--i >= 0 && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF + } + + return offset + byteLength +} + +Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0) + if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value) + this[offset] = value + return offset + 1 +} + +function objectWriteUInt16 (buf, value, offset, littleEndian) { + if (value < 0) value = 0xffff + value + 1 + for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; i++) { + buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>> + (littleEndian ? i : 1 - i) * 8 + } +} + +Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = value + this[offset + 1] = (value >>> 8) + } else { + objectWriteUInt16(this, value, offset, true) + } + return offset + 2 +} + +Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 8) + this[offset + 1] = value + } else { + objectWriteUInt16(this, value, offset, false) + } + return offset + 2 +} + +function objectWriteUInt32 (buf, value, offset, littleEndian) { + if (value < 0) value = 0xffffffff + value + 1 + for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; i++) { + buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff + } +} + +Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset + 3] = (value >>> 24) + this[offset + 2] = (value >>> 16) + this[offset + 1] = (value >>> 8) + this[offset] = value + } else { + objectWriteUInt32(this, value, offset, true) + } + return offset + 4 +} + +Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 24) + this[offset + 1] = (value >>> 16) + this[offset + 2] = (value >>> 8) + this[offset + 3] = value + } else { + objectWriteUInt32(this, value, offset, false) + } + return offset + 4 +} + +Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) { + var limit = Math.pow(2, 8 * byteLength - 1) + + checkInt(this, value, offset, byteLength, limit - 1, -limit) + } + + var i = 0 + var mul = 1 + var sub = value < 0 ? 1 : 0 + this[offset] = value & 0xFF + while (++i < byteLength && (mul *= 0x100)) { + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF + } + + return offset + byteLength +} + +Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) { + var limit = Math.pow(2, 8 * byteLength - 1) + + checkInt(this, value, offset, byteLength, limit - 1, -limit) + } + + var i = byteLength - 1 + var mul = 1 + var sub = value < 0 ? 1 : 0 + this[offset + i] = value & 0xFF + while (--i >= 0 && (mul *= 0x100)) { + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF + } + + return offset + byteLength +} + +Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80) + if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value) + if (value < 0) value = 0xff + value + 1 + this[offset] = value + return offset + 1 +} + +Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = value + this[offset + 1] = (value >>> 8) + } else { + objectWriteUInt16(this, value, offset, true) + } + return offset + 2 +} + +Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 8) + this[offset + 1] = value + } else { + objectWriteUInt16(this, value, offset, false) + } + return offset + 2 +} + +Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = value + this[offset + 1] = (value >>> 8) + this[offset + 2] = (value >>> 16) + this[offset + 3] = (value >>> 24) + } else { + objectWriteUInt32(this, value, offset, true) + } + return offset + 4 +} + +Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) + if (value < 0) value = 0xffffffff + value + 1 + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 24) + this[offset + 1] = (value >>> 16) + this[offset + 2] = (value >>> 8) + this[offset + 3] = value + } else { + objectWriteUInt32(this, value, offset, false) + } + return offset + 4 +} + +function checkIEEE754 (buf, value, offset, ext, max, min) { + if (value > max || value < min) throw new RangeError('value is out of bounds') + if (offset + ext > buf.length) throw new RangeError('index out of range') + if (offset < 0) throw new RangeError('index out of range') +} + +function writeFloat (buf, value, offset, littleEndian, noAssert) { + if (!noAssert) { + checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38) + } + ieee754.write(buf, value, offset, littleEndian, 23, 4) + return offset + 4 +} + +Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { + return writeFloat(this, value, offset, true, noAssert) +} + +Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { + return writeFloat(this, value, offset, false, noAssert) +} + +function writeDouble (buf, value, offset, littleEndian, noAssert) { + if (!noAssert) { + checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308) + } + ieee754.write(buf, value, offset, littleEndian, 52, 8) + return offset + 8 +} + +Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { + return writeDouble(this, value, offset, true, noAssert) +} + +Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { + return writeDouble(this, value, offset, false, noAssert) +} + +// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) +Buffer.prototype.copy = function copy (target, targetStart, start, end) { + if (!start) start = 0 + if (!end && end !== 0) end = this.length + if (targetStart >= target.length) targetStart = target.length + if (!targetStart) targetStart = 0 + if (end > 0 && end < start) end = start + + // Copy 0 bytes; we're done + if (end === start) return 0 + if (target.length === 0 || this.length === 0) return 0 + + // Fatal error conditions + if (targetStart < 0) { + throw new RangeError('targetStart out of bounds') + } + if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds') + if (end < 0) throw new RangeError('sourceEnd out of bounds') + + // Are we oob? + if (end > this.length) end = this.length + if (target.length - targetStart < end - start) { + end = target.length - targetStart + start + } + + var len = end - start + + if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) { + for (var i = 0; i < len; i++) { + target[i + targetStart] = this[i + start] + } + } else { + target._set(this.subarray(start, start + len), targetStart) + } + + return len +} + +// fill(value, start=0, end=buffer.length) +Buffer.prototype.fill = function fill (value, start, end) { + if (!value) value = 0 + if (!start) start = 0 + if (!end) end = this.length + + if (end < start) throw new RangeError('end < start') + + // Fill 0 bytes; we're done + if (end === start) return + if (this.length === 0) return + + if (start < 0 || start >= this.length) throw new RangeError('start out of bounds') + if (end < 0 || end > this.length) throw new RangeError('end out of bounds') + + var i + if (typeof value === 'number') { + for (i = start; i < end; i++) { + this[i] = value + } + } else { + var bytes = utf8ToBytes(value.toString()) + var len = bytes.length + for (i = start; i < end; i++) { + this[i] = bytes[i % len] + } + } + + return this +} + +/** + * Creates a new `ArrayBuffer` with the *copied* memory of the buffer instance. + * Added in Node 0.12. Only available in browsers that support ArrayBuffer. + */ +Buffer.prototype.toArrayBuffer = function toArrayBuffer () { + if (typeof Uint8Array !== 'undefined') { + if (Buffer.TYPED_ARRAY_SUPPORT) { + return (new Buffer(this)).buffer + } else { + var buf = new Uint8Array(this.length) + for (var i = 0, len = buf.length; i < len; i += 1) { + buf[i] = this[i] + } + return buf.buffer + } + } else { + throw new TypeError('Buffer.toArrayBuffer not supported in this browser') + } +} + +// HELPER FUNCTIONS +// ================ + +var BP = Buffer.prototype + +/** + * Augment a Uint8Array *instance* (not the Uint8Array class!) with Buffer methods + */ +Buffer._augment = function _augment (arr) { + arr.constructor = Buffer + arr._isBuffer = true + + // save reference to original Uint8Array set method before overwriting + arr._set = arr.set + + // deprecated, will be removed in node 0.13+ + arr.get = BP.get + arr.set = BP.set + + arr.write = BP.write + arr.toString = BP.toString + arr.toLocaleString = BP.toString + arr.toJSON = BP.toJSON + arr.equals = BP.equals + arr.compare = BP.compare + arr.indexOf = BP.indexOf + arr.copy = BP.copy + arr.slice = BP.slice + arr.readUIntLE = BP.readUIntLE + arr.readUIntBE = BP.readUIntBE + arr.readUInt8 = BP.readUInt8 + arr.readUInt16LE = BP.readUInt16LE + arr.readUInt16BE = BP.readUInt16BE + arr.readUInt32LE = BP.readUInt32LE + arr.readUInt32BE = BP.readUInt32BE + arr.readIntLE = BP.readIntLE + arr.readIntBE = BP.readIntBE + arr.readInt8 = BP.readInt8 + arr.readInt16LE = BP.readInt16LE + arr.readInt16BE = BP.readInt16BE + arr.readInt32LE = BP.readInt32LE + arr.readInt32BE = BP.readInt32BE + arr.readFloatLE = BP.readFloatLE + arr.readFloatBE = BP.readFloatBE + arr.readDoubleLE = BP.readDoubleLE + arr.readDoubleBE = BP.readDoubleBE + arr.writeUInt8 = BP.writeUInt8 + arr.writeUIntLE = BP.writeUIntLE + arr.writeUIntBE = BP.writeUIntBE + arr.writeUInt16LE = BP.writeUInt16LE + arr.writeUInt16BE = BP.writeUInt16BE + arr.writeUInt32LE = BP.writeUInt32LE + arr.writeUInt32BE = BP.writeUInt32BE + arr.writeIntLE = BP.writeIntLE + arr.writeIntBE = BP.writeIntBE + arr.writeInt8 = BP.writeInt8 + arr.writeInt16LE = BP.writeInt16LE + arr.writeInt16BE = BP.writeInt16BE + arr.writeInt32LE = BP.writeInt32LE + arr.writeInt32BE = BP.writeInt32BE + arr.writeFloatLE = BP.writeFloatLE + arr.writeFloatBE = BP.writeFloatBE + arr.writeDoubleLE = BP.writeDoubleLE + arr.writeDoubleBE = BP.writeDoubleBE + arr.fill = BP.fill + arr.inspect = BP.inspect + arr.toArrayBuffer = BP.toArrayBuffer + + return arr +} + +var INVALID_BASE64_RE = /[^+\/0-9A-z\-]/g + +function base64clean (str) { + // Node strips out invalid characters like \n and \t from the string, base64-js does not + str = stringtrim(str).replace(INVALID_BASE64_RE, '') + // Node converts strings with length < 2 to '' + if (str.length < 2) return '' + // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not + while (str.length % 4 !== 0) { + str = str + '=' + } + return str +} + +function stringtrim (str) { + if (str.trim) return str.trim() + return str.replace(/^\s+|\s+$/g, '') +} + +function toHex (n) { + if (n < 16) return '0' + n.toString(16) + return n.toString(16) +} + +function utf8ToBytes (string, units) { + units = units || Infinity + var codePoint + var length = string.length + var leadSurrogate = null + var bytes = [] + var i = 0 + + for (; i < length; i++) { + codePoint = string.charCodeAt(i) + + // is surrogate component + if (codePoint > 0xD7FF && codePoint < 0xE000) { + // last char was a lead + if (leadSurrogate) { + // 2 leads in a row + if (codePoint < 0xDC00) { + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + leadSurrogate = codePoint + continue + } else { + // valid surrogate pair + codePoint = leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00 | 0x10000 + leadSurrogate = null + } + } else { + // no lead yet + + if (codePoint > 0xDBFF) { + // unexpected trail + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + continue + } else if (i + 1 === length) { + // unpaired lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + continue + } else { + // valid lead + leadSurrogate = codePoint + continue + } + } + } else if (leadSurrogate) { + // valid bmp char, but last char was a lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + leadSurrogate = null + } + + // encode utf8 + if (codePoint < 0x80) { + if ((units -= 1) < 0) break + bytes.push(codePoint) + } else if (codePoint < 0x800) { + if ((units -= 2) < 0) break + bytes.push( + codePoint >> 0x6 | 0xC0, + codePoint & 0x3F | 0x80 + ) + } else if (codePoint < 0x10000) { + if ((units -= 3) < 0) break + bytes.push( + codePoint >> 0xC | 0xE0, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ) + } else if (codePoint < 0x200000) { + if ((units -= 4) < 0) break + bytes.push( + codePoint >> 0x12 | 0xF0, + codePoint >> 0xC & 0x3F | 0x80, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ) + } else { + throw new Error('Invalid code point') + } + } + + return bytes +} + +function asciiToBytes (str) { + var byteArray = [] + for (var i = 0; i < str.length; i++) { + // Node's code seems to be doing this and not & 0x7F.. + byteArray.push(str.charCodeAt(i) & 0xFF) + } + return byteArray +} + +function utf16leToBytes (str, units) { + var c, hi, lo + var byteArray = [] + for (var i = 0; i < str.length; i++) { + if ((units -= 2) < 0) break + + c = str.charCodeAt(i) + hi = c >> 8 + lo = c % 256 + byteArray.push(lo) + byteArray.push(hi) + } + + return byteArray +} + +function base64ToBytes (str) { + return base64.toByteArray(base64clean(str)) +} + +function blitBuffer (src, dst, offset, length) { + for (var i = 0; i < length; i++) { + if ((i + offset >= dst.length) || (i >= src.length)) break + dst[i + offset] = src[i] + } + return i +} + +function decodeUtf8Char (str) { + try { + return decodeURIComponent(str) + } catch (err) { + return String.fromCharCode(0xFFFD) // UTF 8 invalid char + } +} + +},{"base64-js":5,"ieee754":6,"is-array":7}],5:[function(require,module,exports){ +var lookup = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; + +;(function (exports) { + 'use strict'; + + var Arr = (typeof Uint8Array !== 'undefined') + ? Uint8Array + : Array + + var PLUS = '+'.charCodeAt(0) + var SLASH = '/'.charCodeAt(0) + var NUMBER = '0'.charCodeAt(0) + var LOWER = 'a'.charCodeAt(0) + var UPPER = 'A'.charCodeAt(0) + var PLUS_URL_SAFE = '-'.charCodeAt(0) + var SLASH_URL_SAFE = '_'.charCodeAt(0) + + function decode (elt) { + var code = elt.charCodeAt(0) + if (code === PLUS || + code === PLUS_URL_SAFE) + return 62 // '+' + if (code === SLASH || + code === SLASH_URL_SAFE) + return 63 // '/' + if (code < NUMBER) + return -1 //no match + if (code < NUMBER + 10) + return code - NUMBER + 26 + 26 + if (code < UPPER + 26) + return code - UPPER + if (code < LOWER + 26) + return code - LOWER + 26 + } + + function b64ToByteArray (b64) { + var i, j, l, tmp, placeHolders, arr + + if (b64.length % 4 > 0) { + throw new Error('Invalid string. Length must be a multiple of 4') + } + + // the number of equal signs (place holders) + // if there are two placeholders, than the two characters before it + // represent one byte + // if there is only one, then the three characters before it represent 2 bytes + // this is just a cheap hack to not do indexOf twice + var len = b64.length + placeHolders = '=' === b64.charAt(len - 2) ? 2 : '=' === b64.charAt(len - 1) ? 1 : 0 + + // base64 is 4/3 + up to two characters of the original data + arr = new Arr(b64.length * 3 / 4 - placeHolders) + + // if there are placeholders, only get up to the last complete 4 chars + l = placeHolders > 0 ? b64.length - 4 : b64.length + + var L = 0 + + function push (v) { + arr[L++] = v + } + + for (i = 0, j = 0; i < l; i += 4, j += 3) { + tmp = (decode(b64.charAt(i)) << 18) | (decode(b64.charAt(i + 1)) << 12) | (decode(b64.charAt(i + 2)) << 6) | decode(b64.charAt(i + 3)) + push((tmp & 0xFF0000) >> 16) + push((tmp & 0xFF00) >> 8) + push(tmp & 0xFF) + } + + if (placeHolders === 2) { + tmp = (decode(b64.charAt(i)) << 2) | (decode(b64.charAt(i + 1)) >> 4) + push(tmp & 0xFF) + } else if (placeHolders === 1) { + tmp = (decode(b64.charAt(i)) << 10) | (decode(b64.charAt(i + 1)) << 4) | (decode(b64.charAt(i + 2)) >> 2) + push((tmp >> 8) & 0xFF) + push(tmp & 0xFF) + } + + return arr + } + + function uint8ToBase64 (uint8) { + var i, + extraBytes = uint8.length % 3, // if we have 1 byte left, pad 2 bytes + output = "", + temp, length + + function encode (num) { + return lookup.charAt(num) + } + + function tripletToBase64 (num) { + return encode(num >> 18 & 0x3F) + encode(num >> 12 & 0x3F) + encode(num >> 6 & 0x3F) + encode(num & 0x3F) + } + + // go through the array every three bytes, we'll deal with trailing stuff later + for (i = 0, length = uint8.length - extraBytes; i < length; i += 3) { + temp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2]) + output += tripletToBase64(temp) + } + + // pad the end with zeros, but make sure to not forget the extra bytes + switch (extraBytes) { + case 1: + temp = uint8[uint8.length - 1] + output += encode(temp >> 2) + output += encode((temp << 4) & 0x3F) + output += '==' + break + case 2: + temp = (uint8[uint8.length - 2] << 8) + (uint8[uint8.length - 1]) + output += encode(temp >> 10) + output += encode((temp >> 4) & 0x3F) + output += encode((temp << 2) & 0x3F) + output += '=' + break + } + + return output + } + + exports.toByteArray = b64ToByteArray + exports.fromByteArray = uint8ToBase64 +}(typeof exports === 'undefined' ? (this.base64js = {}) : exports)) + +},{}],6:[function(require,module,exports){ +exports.read = function (buffer, offset, isLE, mLen, nBytes) { + var e, m + var eLen = nBytes * 8 - mLen - 1 + var eMax = (1 << eLen) - 1 + var eBias = eMax >> 1 + var nBits = -7 + var i = isLE ? (nBytes - 1) : 0 + var d = isLE ? -1 : 1 + var s = buffer[offset + i] + + i += d + + e = s & ((1 << (-nBits)) - 1) + s >>= (-nBits) + nBits += eLen + for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {} + + m = e & ((1 << (-nBits)) - 1) + e >>= (-nBits) + nBits += mLen + for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {} + + if (e === 0) { + e = 1 - eBias + } else if (e === eMax) { + return m ? NaN : ((s ? -1 : 1) * Infinity) + } else { + m = m + Math.pow(2, mLen) + e = e - eBias + } + return (s ? -1 : 1) * m * Math.pow(2, e - mLen) +} + +exports.write = function (buffer, value, offset, isLE, mLen, nBytes) { + var e, m, c + var eLen = nBytes * 8 - mLen - 1 + var eMax = (1 << eLen) - 1 + var eBias = eMax >> 1 + var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0) + var i = isLE ? 0 : (nBytes - 1) + var d = isLE ? 1 : -1 + var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0 + + value = Math.abs(value) + + if (isNaN(value) || value === Infinity) { + m = isNaN(value) ? 1 : 0 + e = eMax + } else { + e = Math.floor(Math.log(value) / Math.LN2) + if (value * (c = Math.pow(2, -e)) < 1) { + e-- + c *= 2 + } + if (e + eBias >= 1) { + value += rt / c + } else { + value += rt * Math.pow(2, 1 - eBias) + } + if (value * c >= 2) { + e++ + c /= 2 + } + + if (e + eBias >= eMax) { + m = 0 + e = eMax + } else if (e + eBias >= 1) { + m = (value * c - 1) * Math.pow(2, mLen) + e = e + eBias + } else { + m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen) + e = 0 + } + } + + for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} + + e = (e << mLen) | m + eLen += mLen + for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} + + buffer[offset + i - d] |= s * 128 +} + +},{}],7:[function(require,module,exports){ + +/** + * isArray + */ + +var isArray = Array.isArray; + +/** + * toString + */ + +var str = Object.prototype.toString; + +/** + * Whether or not the given `val` + * is an array. + * + * example: + * + * isArray([]); + * // > true + * isArray(arguments); + * // > false + * isArray(''); + * // > false + * + * @param {mixed} val + * @return {bool} + */ + +module.exports = isArray || function (val) { + return !! val && '[object Array]' == str.call(val); +}; + +},{}],8:[function(require,module,exports){ +/** + * @author Titus Wormer + * @copyright 2015 Titus Wormer + * @license MIT + * @module unherit + * @fileoverview Create a custom constructor which can be modified + * without affecting the original class. + * @example + * var EventEmitter = require('events').EventEmitter; + * var Emitter = unherit(EventEmitter); + * // Create a private class which acts just like + * // `EventEmitter`. + * + * Emitter.prototype.defaultMaxListeners = 0; + * // Now, all instances of `Emitter` have no maximum + * // listeners, without affecting other `EventEmitter`s. + */ + +'use strict'; + +/* + * Dependencies. + */ + +var clone = require('clone'); +var inherits = require('inherits'); + +/** + * Create a custom constructor which can be modified + * without affecting the original class. + * + * @param {Function} Super - Super-class. + * @return {Function} - Constructor acting like `Super`, + * which can be modified without affecting the original + * class. + */ +function unherit(Super) { + var base = clone(Super.prototype); + var result; + var key; + + /** + * Constructor accepting a single argument, + * which itself is an `arguments` object. + */ + function From(parameters) { + return Super.apply(this, parameters); + } + + /** + * Constructor accepting variadic arguments. + */ + function Of() { + if (!(this instanceof Of)) { + return new From(arguments); + } + + return Super.apply(this, arguments); + } + + inherits(Of, Super); + inherits(From, Of); + + /* + * Both do duplicate work. However, cloning the + * prototype ensures clonable things are cloned + * and thus used. The `inherits` call ensures + * `instanceof` still thinks an instance subclasses + * `Super`. + */ + + result = Of.prototype; + + for (key in base) { + result[key] = base[key]; + } + + return Of; +} + +/* + * Expose. + */ + +module.exports = unherit; + +},{"clone":9,"inherits":10}],9:[function(require,module,exports){ +(function (Buffer){ +var clone = (function() { +'use strict'; + +/** + * Clones (copies) an Object using deep copying. + * + * This function supports circular references by default, but if you are certain + * there are no circular references in your object, you can save some CPU time + * by calling clone(obj, false). + * + * Caution: if `circular` is false and `parent` contains circular references, + * your program may enter an infinite loop and crash. + * + * @param `parent` - the object to be cloned + * @param `circular` - set to true if the object to be cloned may contain + * circular references. (optional - true by default) + * @param `depth` - set to a number if the object is only to be cloned to + * a particular depth. (optional - defaults to Infinity) + * @param `prototype` - sets the prototype to be used when cloning an object. + * (optional - defaults to parent prototype). +*/ +function clone(parent, circular, depth, prototype) { + var filter; + if (typeof circular === 'object') { + depth = circular.depth; + prototype = circular.prototype; + filter = circular.filter; + circular = circular.circular + } + // maintain two arrays for circular references, where corresponding parents + // and children have the same index + var allParents = []; + var allChildren = []; + + var useBuffer = typeof Buffer != 'undefined'; + + if (typeof circular == 'undefined') + circular = true; + + if (typeof depth == 'undefined') + depth = Infinity; + + // recurse this function so we don't reset allParents and allChildren + function _clone(parent, depth) { + // cloning null always returns null + if (parent === null) + return null; + + if (depth == 0) + return parent; + + var child; + var proto; + if (typeof parent != 'object') { + return parent; + } + + if (clone.__isArray(parent)) { + child = []; + } else if (clone.__isRegExp(parent)) { + child = new RegExp(parent.source, __getRegExpFlags(parent)); + if (parent.lastIndex) child.lastIndex = parent.lastIndex; + } else if (clone.__isDate(parent)) { + child = new Date(parent.getTime()); + } else if (useBuffer && Buffer.isBuffer(parent)) { + child = new Buffer(parent.length); + parent.copy(child); + return child; + } else { + if (typeof prototype == 'undefined') { + proto = Object.getPrototypeOf(parent); + child = Object.create(proto); + } + else { + child = Object.create(prototype); + proto = prototype; + } + } + + if (circular) { + var index = allParents.indexOf(parent); + + if (index != -1) { + return allChildren[index]; + } + allParents.push(parent); + allChildren.push(child); + } + + for (var i in parent) { + var attrs; + if (proto) { + attrs = Object.getOwnPropertyDescriptor(proto, i); + } + + if (attrs && attrs.set == null) { + continue; + } + child[i] = _clone(parent[i], depth - 1); + } + + return child; + } + + return _clone(parent, depth); +} + +/** + * Simple flat clone using prototype, accepts only objects, usefull for property + * override on FLAT configuration object (no nested props). + * + * USE WITH CAUTION! This may not behave as you wish if you do not know how this + * works. + */ +clone.clonePrototype = function clonePrototype(parent) { + if (parent === null) + return null; + + var c = function () {}; + c.prototype = parent; + return new c(); +}; + +// private utility functions + +function __objToStr(o) { + return Object.prototype.toString.call(o); +}; +clone.__objToStr = __objToStr; + +function __isDate(o) { + return typeof o === 'object' && __objToStr(o) === '[object Date]'; +}; +clone.__isDate = __isDate; + +function __isArray(o) { + return typeof o === 'object' && __objToStr(o) === '[object Array]'; +}; +clone.__isArray = __isArray; + +function __isRegExp(o) { + return typeof o === 'object' && __objToStr(o) === '[object RegExp]'; +}; +clone.__isRegExp = __isRegExp; + +function __getRegExpFlags(re) { + var flags = ''; + if (re.global) flags += 'g'; + if (re.ignoreCase) flags += 'i'; + if (re.multiline) flags += 'm'; + return flags; +}; +clone.__getRegExpFlags = __getRegExpFlags; + +return clone; +})(); + +if (typeof module === 'object' && module.exports) { + module.exports = clone; +} + +}).call(this,require("buffer").Buffer) +},{"buffer":4}],10:[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 + } +} + +},{}],11:[function(require,module,exports){ +/** + * @author Titus Wormer + * @copyright 2015 Titus Wormer + * @license MIT + * @module vfile + * @fileoverview Virtual file format to attach additional + * information related to processed input. Similar to + * `wearefractal/vinyl`. Additionally, `VFile` can be + * passed directly to ESLint formatters to visualise + * warnings and errors relating to a file. + * @example + * var VFile = require('vfile'); + * + * var file = new VFile({ + * 'directory': '~', + * 'filename': 'example', + * 'extension': 'txt', + * 'contents': 'Foo *bar* baz' + * }); + * + * file.toString(); // 'Foo *bar* baz' + * file.filePath(); // '~/example.txt' + * + * file.move({'extension': 'md'}); + * file.filePath(); // '~/example.md' + * + * file.warn('Something went wrong', {'line': 2, 'column': 3}); + * // { [~/example.md:2:3: Something went wrong] + * // name: '~/example.md:2:3', + * // file: '~/example.md', + * // reason: 'Something went wrong', + * // line: 2, + * // column: 3, + * // fatal: false } + */ + +'use strict'; + +var SEPARATOR = '/'; + +try { + SEPARATOR = require('pa' + 'th').sep; +} catch (e) { /* empty */ } + +/** + * File-related message with location information. + * + * @typedef {Error} VFileMessage + * @property {string} name - (Starting) location of the + * message, preceded by its file-path when available, + * and joined by `:`. Used internally by the native + * `Error#toString()`. + * @property {string} file - File-path. + * @property {string} reason - Reason for message. + * @property {number?} line - Line of message, when + * available. + * @property {number?} column - Column of message, when + * available. + * @property {string?} stack - Stack of message, when + * available. + * @property {boolean?} fatal - Whether the associated file + * is still processable. + */ + +/** + * Stringify a position. + * + * @example + * stringify({'line': 1, 'column': 3}) // '1:3' + * stringify({'line': 1}) // '1:1' + * stringify({'column': 3}) // '1:3' + * stringify() // '1:1' + * + * @private + * @param {Object?} [position] - Single position, like + * those available at `node.position.start`. + * @return {string} + */ +function stringify(position) { + if (!position) { + position = {}; + } + + return (position.line || 1) + ':' + (position.column || 1); +} + +/** + * ESLint's formatter API expects `filePath` to be a + * string. This hack supports invocation as well as + * implicit coercion. + * + * @example + * var file = new VFile({ + * 'filename': 'example', + * 'extension': 'txt' + * }); + * + * filePath = filePathFactory(file); + * + * String(filePath); // 'example.txt' + * filePath(); // 'example.txt' + * + * @private + * @param {VFile} file + * @return {Function} + */ +function filePathFactory(file) { + /** + * Get the filename, with extension and directory, if applicable. + * + * @example + * var file = new VFile({ + * 'directory': '~', + * 'filename': 'example', + * 'extension': 'txt' + * }); + * + * String(file.filePath); // ~/example.txt + * file.filePath() // ~/example.txt + * + * @memberof {VFile} + * @property {Function} toString - Itself. ESLint's + * formatter API expects `filePath` to be `string`. + * This hack supports invocation as well as implicit + * coercion. + * @return {string} - If the `vFile` has a `filename`, + * it will be prefixed with the directory (slashed), + * if applicable, and suffixed with the (dotted) + * extension (if applicable). Otherwise, an empty + * string is returned. + */ + function filePath() { + var directory = file.directory; + var separator; + + if (file.filename || file.extension) { + separator = directory.charAt(directory.length - 1); + + if (separator === '/' || separator === '\\') { + directory = directory.slice(0, -1); + } + + if (directory === '.') { + directory = ''; + } + + return (directory ? directory + SEPARATOR : '') + + file.filename + + (file.extension ? '.' + file.extension : ''); + } + + return ''; + } + + filePath.toString = filePath; + + return filePath; +} + +/** + * Construct a new file. + * + * @example + * var file = new VFile({ + * 'directory': '~', + * 'filename': 'example', + * 'extension': 'txt', + * 'contents': 'Foo *bar* baz' + * }); + * + * file === VFile(file) // true + * file === new VFile(file) // true + * VFile('foo') instanceof VFile // true + * + * @constructor + * @class {VFile} + * @param {Object|VFile|string} [options] - either an + * options object, or the value of `contents` (both + * optional). When a `file` is passed in, it's + * immediately returned. + * @property {string} [contents=''] - Content of file. + * @property {string} [directory=''] - Path to parent + * directory. + * @property {string} [filename=''] - Filename. + * A file-path can still be generated when no filename + * exists. + * @property {string} [extension=''] - Extension. + * A file-path can still be generated when no extension + * exists. + * @property {boolean?} quiet - Whether an error created by + * `VFile#fail()` is returned (when truthy) or thrown + * (when falsey). Ensure all `messages` associated with + * a file are handled properly when setting this to + * `true`. + * @property {Array.} messages - List of associated + * messages. + */ +function VFile(options) { + var self = this; + + /* + * No `new` operator. + */ + + if (!(self instanceof VFile)) { + return new VFile(options); + } + + /* + * Given file. + */ + + if ( + options && + typeof options.message === 'function' && + typeof options.hasFailed === 'function' + ) { + return options; + } + + if (!options) { + options = {}; + } else if (typeof options === 'string') { + options = { + 'contents': options + }; + } + + self.contents = options.contents || ''; + self.filename = options.filename || ''; + self.directory = options.directory || ''; + self.extension = options.extension || ''; + + self.messages = []; + + /* + * Make sure eslint’s formatters stringify `filePath` + * properly. + */ + + self.filePath = filePathFactory(self); +} + +/** + * Get the value of the file. + * + * @example + * var vFile = new VFile('Foo'); + * String(vFile); // 'Foo' + * + * @this {VFile} + * @memberof {VFile} + * @return {string} - value at the `contents` property + * in context. + */ +function toString() { + return this.contents; +} + +/** + * Move a file by passing a new directory, filename, + * and extension. When these are not given, the default + * values are kept. + * + * @example + * var file = new VFile({ + * 'directory': '~', + * 'filename': 'example', + * 'extension': 'txt', + * 'contents': 'Foo *bar* baz' + * }); + * + * file.move({'directory': '/var/www'}); + * file.filePath(); // '/var/www/example.txt' + * + * file.move({'extension': 'md'}); + * file.filePath(); // '/var/www/example.md' + * + * @this {VFile} + * @memberof {VFile} + * @param {Object?} [options] + * @return {VFile} - Context object. + */ +function move(options) { + var self = this; + + if (!options) { + options = {}; + } + + self.directory = options.directory || self.directory || ''; + self.filename = options.filename || self.filename || ''; + self.extension = options.extension || self.extension || ''; + + return self; +} + +/** + * Create a message with `reason` at `position`. + * When an error is passed in as `reason`, copies the + * stack. This does not add a message to `messages`. + * + * @example + * var file = new VFile(); + * + * file.message('Something went wrong'); + * // { [1:1: Something went wrong] + * // name: '1:1', + * // file: '', + * // reason: 'Something went wrong', + * // line: null, + * // column: null } + * + * @this {VFile} + * @memberof {VFile} + * @param {string|Error} reason - Reason for message. + * @param {Node|Location|Position} [position] - Location + * of message in file. + * @return {VFileMessage} - File-related message with + * location information. + */ +function message(reason, position) { + var filePath = this.filePath(); + var location; + var err; + + /* + * Node / location / position. + */ + + if (position && position.position) { + position = position.position; + } + + if (position && position.start) { + location = stringify(position.start) + '-' + stringify(position.end); + position = position.start; + } else { + location = stringify(position); + } + + err = new Error(reason.message || reason); + + err.name = (filePath ? filePath + ':' : '') + location; + err.file = filePath; + err.reason = reason.message || reason; + err.line = position ? position.line : null; + err.column = position ? position.column : null; + + if (reason.stack) { + err.stack = reason.stack; + } + + return err; +} + +/** + * Warn. Creates a non-fatal message (see `VFile#message()`), + * and adds it to the file's `messages` list. + * + * @example + * var file = new VFile(); + * + * file.warn('Something went wrong'); + * // { [1:1: Something went wrong] + * // name: '1:1', + * // file: '', + * // reason: 'Something went wrong', + * // line: null, + * // column: null, + * // fatal: false } + * + * @see VFile#message + * @this {VFile} + * @memberof {VFile} + */ +function warn() { + var err = this.message.apply(this, arguments); + + err.fatal = false; + + this.messages.push(err); + + return err; +} + +/** + * Fail. Creates a fatal message (see `VFile#message()`), + * sets `fatal: true`, adds it to the file's + * `messages` list. + * + * If `quiet` is not `true`, throws the error. + * + * @example + * var file = new VFile(); + * + * file.fail('Something went wrong'); + * // 1:1: Something went wrong + * // at VFile.exception (vfile/index.js:296:11) + * // at VFile.fail (vfile/index.js:360:20) + * // at repl:1:6 + * + * file.quiet = true; + * file.fail('Something went wrong'); + * // { [1:1: Something went wrong] + * // name: '1:1', + * // file: '', + * // reason: 'Something went wrong', + * // line: null, + * // column: null, + * // fatal: true } + * + * @this {VFile} + * @memberof {VFile} + * @throws {VFileMessage} - When not `quiet: true`. + * @param {string|Error} reason - Reason for failure. + * @param {Node|Location|Position} [position] - Place + * of failure in file. + * @return {VFileMessage} - Unless thrown, of course. + */ +function fail(reason, position) { + var err = this.message(reason, position); + + err.fatal = true; + + this.messages.push(err); + + if (!this.quiet) { + throw err; + } + + return err; +} + +/** + * Check if a fatal message occurred making the file no + * longer processable. + * + * @example + * var file = new VFile(); + * file.quiet = true; + * + * file.hasFailed(); // false + * + * file.fail('Something went wrong'); + * file.hasFailed(); // true + * + * @this {VFile} + * @memberof {VFile} + * @return {boolean} - `true` if at least one of file's + * `messages` has a `fatal` property set to `true` + */ +function hasFailed() { + var messages = this.messages; + var index = -1; + var length = messages.length; + + while (++index < length) { + if (messages[index].fatal) { + return true; + } + } + + return false; +} + +/** + * Access private information relating to a file. + * + * @example + * var file = new VFile('Foo'); + * + * file.namespace('foo').bar = 'baz'; + * + * console.log(file.namespace('foo').bar) // 'baz'; + * + * @this {VFile} + * @memberof {VFile} + * @param {string} key - Namespace key. + * @return {Object} - Private space. + */ +function namespace(key) { + var self = this; + var space = self.data; + + if (!space) { + space = self.data = {}; + } + + if (!space[key]) { + space[key] = {}; + } + + return space[key]; +} + +/* + * Methods. + */ + +var vFilePrototype = VFile.prototype; + +vFilePrototype.move = move; +vFilePrototype.toString = toString; +vFilePrototype.message = message; +vFilePrototype.warn = warn; +vFilePrototype.fail = fail; +vFilePrototype.hasFailed = hasFailed; +vFilePrototype.namespace = namespace; + +/* + * Expose. + */ + +module.exports = VFile; + +},{}],12:[function(require,module,exports){ +/** + * Module Dependencies + */ + +var slice = [].slice; +var wrap = require('wrap-fn'); + +/** + * Expose `Ware`. + */ + +module.exports = Ware; + +/** + * Throw an error. + * + * @param {Error} error + */ + +function fail (err) { + throw err; +} + +/** + * Initialize a new `Ware` manager, with optional `fns`. + * + * @param {Function or Array or Ware} fn (optional) + */ + +function Ware (fn) { + if (!(this instanceof Ware)) return new Ware(fn); + this.fns = []; + if (fn) this.use(fn); +} + +/** + * Use a middleware `fn`. + * + * @param {Function or Array or Ware} fn + * @return {Ware} + */ + +Ware.prototype.use = function (fn) { + if (fn instanceof Ware) { + return this.use(fn.fns); + } + + if (fn instanceof Array) { + for (var i = 0, f; f = fn[i++];) this.use(f); + return this; + } + + this.fns.push(fn); + return this; +}; + +/** + * Run through the middleware with the given `args` and optional `callback`. + * + * @param {Mixed} args... + * @param {Function} callback (optional) + * @return {Ware} + */ + +Ware.prototype.run = function () { + var fns = this.fns; + var ctx = this; + var i = 0; + var last = arguments[arguments.length - 1]; + var done = 'function' == typeof last && last; + var args = done + ? slice.call(arguments, 0, arguments.length - 1) + : slice.call(arguments); + + // next step + function next (err) { + if (err) return (done || fail)(err); + var fn = fns[i++]; + var arr = slice.call(args); + + if (!fn) { + return done && done.apply(null, [null].concat(args)); + } + + wrap(fn, next).apply(ctx, arr); + } + + next(); + + return this; +}; + +},{"wrap-fn":13}],13:[function(require,module,exports){ +/** + * Module Dependencies + */ + +var noop = function(){}; +var co = require('co'); + +/** + * Export `wrap-fn` + */ + +module.exports = wrap; + +/** + * Wrap a function to support + * sync, async, and gen functions. + * + * @param {Function} fn + * @param {Function} done + * @return {Function} + * @api public + */ + +function wrap(fn, done) { + done = once(done || noop); + + return function() { + // prevents arguments leakage + // see https://github.com/petkaantonov/bluebird/wiki/Optimization-killers#3-managing-arguments + var i = arguments.length; + var args = new Array(i); + while (i--) args[i] = arguments[i]; + + var ctx = this; + + // done + if (!fn) { + return done.apply(ctx, [null].concat(args)); + } + + // async + if (fn.length > args.length) { + // NOTE: this only handles uncaught synchronous errors + try { + return fn.apply(ctx, args.concat(done)); + } catch (e) { + return done(e); + } + } + + // generator + if (generator(fn)) { + return co(fn).apply(ctx, args.concat(done)); + } + + // sync + return sync(fn, done).apply(ctx, args); + } +} + +/** + * Wrap a synchronous function execution. + * + * @param {Function} fn + * @param {Function} done + * @return {Function} + * @api private + */ + +function sync(fn, done) { + return function () { + var ret; + + try { + ret = fn.apply(this, arguments); + } catch (err) { + return done(err); + } + + if (promise(ret)) { + ret.then(function (value) { done(null, value); }, done); + } else { + ret instanceof Error ? done(ret) : done(null, ret); + } + } +} + +/** + * Is `value` a generator? + * + * @param {Mixed} value + * @return {Boolean} + * @api private + */ + +function generator(value) { + return value + && value.constructor + && 'GeneratorFunction' == value.constructor.name; +} + + +/** + * Is `value` a promise? + * + * @param {Mixed} value + * @return {Boolean} + * @api private + */ + +function promise(value) { + return value && 'function' == typeof value.then; +} + +/** + * Once + */ + +function once(fn) { + return function() { + var ret = fn.apply(this, arguments); + fn = noop; + return ret; + }; +} + +},{"co":14}],14:[function(require,module,exports){ + +/** + * slice() reference. + */ + +var slice = Array.prototype.slice; + +/** + * Expose `co`. + */ + +module.exports = co; + +/** + * Wrap the given generator `fn` and + * return a thunk. + * + * @param {Function} fn + * @return {Function} + * @api public + */ + +function co(fn) { + var isGenFun = isGeneratorFunction(fn); + + return function (done) { + var ctx = this; + + // in toThunk() below we invoke co() + // with a generator, so optimize for + // this case + var gen = fn; + + // we only need to parse the arguments + // if gen is a generator function. + if (isGenFun) { + var args = slice.call(arguments), len = args.length; + var hasCallback = len && 'function' == typeof args[len - 1]; + done = hasCallback ? args.pop() : error; + gen = fn.apply(this, args); + } else { + done = done || error; + } + + next(); + + // #92 + // wrap the callback in a setImmediate + // so that any of its errors aren't caught by `co` + function exit(err, res) { + setImmediate(function(){ + done.call(ctx, err, res); + }); + } + + function next(err, res) { + var ret; + + // multiple args + if (arguments.length > 2) res = slice.call(arguments, 1); + + // error + if (err) { + try { + ret = gen.throw(err); + } catch (e) { + return exit(e); + } + } + + // ok + if (!err) { + try { + ret = gen.next(res); + } catch (e) { + return exit(e); + } + } + + // done + if (ret.done) return exit(null, ret.value); + + // normalize + ret.value = toThunk(ret.value, ctx); + + // run + if ('function' == typeof ret.value) { + var called = false; + try { + ret.value.call(ctx, function(){ + if (called) return; + called = true; + next.apply(ctx, arguments); + }); + } catch (e) { + setImmediate(function(){ + if (called) return; + called = true; + next(e); + }); + } + return; + } + + // invalid + next(new TypeError('You may only yield a function, promise, generator, array, or object, ' + + 'but the following was passed: "' + String(ret.value) + '"')); + } + } +} + +/** + * Convert `obj` into a normalized thunk. + * + * @param {Mixed} obj + * @param {Mixed} ctx + * @return {Function} + * @api private + */ + +function toThunk(obj, ctx) { + + if (isGeneratorFunction(obj)) { + return co(obj.call(ctx)); + } + + if (isGenerator(obj)) { + return co(obj); + } + + if (isPromise(obj)) { + return promiseToThunk(obj); + } + + if ('function' == typeof obj) { + return obj; + } + + if (isObject(obj) || Array.isArray(obj)) { + return objectToThunk.call(ctx, obj); + } + + return obj; +} + +/** + * Convert an object of yieldables to a thunk. + * + * @param {Object} obj + * @return {Function} + * @api private + */ + +function objectToThunk(obj){ + var ctx = this; + var isArray = Array.isArray(obj); + + return function(done){ + var keys = Object.keys(obj); + var pending = keys.length; + var results = isArray + ? new Array(pending) // predefine the array length + : new obj.constructor(); + var finished; + + if (!pending) { + setImmediate(function(){ + done(null, results) + }); + return; + } + + // prepopulate object keys to preserve key ordering + if (!isArray) { + for (var i = 0; i < pending; i++) { + results[keys[i]] = undefined; + } + } + + for (var i = 0; i < keys.length; i++) { + run(obj[keys[i]], keys[i]); + } + + function run(fn, key) { + if (finished) return; + try { + fn = toThunk(fn, ctx); + + if ('function' != typeof fn) { + results[key] = fn; + return --pending || done(null, results); + } + + fn.call(ctx, function(err, res){ + if (finished) return; + + if (err) { + finished = true; + return done(err); + } + + results[key] = res; + --pending || done(null, results); + }); + } catch (err) { + finished = true; + done(err); + } + } + } +} + +/** + * Convert `promise` to a thunk. + * + * @param {Object} promise + * @return {Function} + * @api private + */ + +function promiseToThunk(promise) { + return function(fn){ + promise.then(function(res) { + fn(null, res); + }, fn); + } +} + +/** + * Check if `obj` is a promise. + * + * @param {Object} obj + * @return {Boolean} + * @api private + */ + +function isPromise(obj) { + return obj && 'function' == typeof obj.then; +} + +/** + * Check if `obj` is a generator. + * + * @param {Mixed} obj + * @return {Boolean} + * @api private + */ + +function isGenerator(obj) { + return obj && 'function' == typeof obj.next && 'function' == typeof obj.throw; +} + +/** + * Check if `obj` is a generator function. + * + * @param {Mixed} obj + * @return {Boolean} + * @api private + */ + +function isGeneratorFunction(obj) { + return obj && obj.constructor && 'GeneratorFunction' == obj.constructor.name; +} + +/** + * Check for plain object. + * + * @param {Mixed} val + * @return {Boolean} + * @api private + */ + +function isObject(val) { + return val && Object == val.constructor; +} + +/** + * Throw `err` in a new stack. + * + * This is used when co() is invoked + * without supplying a callback, which + * should only be for demonstrational + * purposes. + * + * @param {Error} err + * @api private + */ + +function error(err) { + if (!err) return; + setImmediate(function(){ + throw err; + }); +} + +},{}]},{},[1])(1) +}); \ No newline at end of file diff --git a/unified.min.js b/unified.min.js new file mode 100644 index 00000000..5f4df8ee --- /dev/null +++ b/unified.min.js @@ -0,0 +1 @@ +!function(b,a){typeof exports==='object'&&typeof module!=='undefined'?module.exports=b():typeof define==='function'&&define.amd?define([],b):(typeof window!=='undefined'?a=window:typeof global!=='undefined'?a=global:typeof self!=='undefined'?a=self:a=this,a.AttachWare=b())}(function(){return function a(b,c,e){function f(d,k){if(!c[d]){if(!b[d]){var i=typeof require=='function'&&require;if(!k&&i)return i(d,!0);if(g)return g(d,!0);var j=new Error("Cannot find module '"+d+"'");throw j.code='MODULE_NOT_FOUND',j}var h=c[d]={exports:{}};b[d][0].call(h.exports,function(c){var a=b[d][1][c];return f(a?a:c)},h,h.exports,a,b,c,e)}return c[d].exports}var g=typeof require=='function'&&require;for(var d=0;d1?arguments[1]:'utf8'):W(this,b)):arguments.length>1?new a(b,arguments[1]):new a(b)}function Y(b,d){if(b=e(b,d<0?0:g(d)|0),!a.TYPED_ARRAY_SUPPORT)for(var c=0;c>>1;return d&&(b.parent=y),b}function g(a){if(a>=A())throw new RangeError('Attempt to allocate Buffer larger than maximum size: 0x'+A().toString(16)+' bytes');return a|0}function p(c,d){if(!(this instanceof p))return new p(c,d);var b=new a(c,d);return delete b.parent,b}function r(a,c){typeof a!=='string'&&(a=''+a);var b=a.length;if(b===0)return 0;var d=!1;for(;;)switch(c){case'ascii':case'binary':case'raw':case'raws':return b;case'utf8':case'utf-8':return n(a).length;case'ucs2':case'ucs-2':case'utf16le':case'utf-16le':return b*2;case'hex':return b>>>1;case'base64':return w(a).length;default:if(d)return n(a).length;c=(''+c).toLowerCase();d=!0}}function L(c,b,a){var d=!1;if(b|=0,a=a===undefined||a===Infinity?this.length:a|0,c||(c='utf8'),b<0&&(b=0),a>this.length&&(a=this.length),a<=b)return'';while(!0)switch(c){case'hex':return D(this,b,a);case'utf8':case'utf-8':return q(this,b,a);case'ascii':return C(this,b,a);case'binary':return O(this,b,a);case'base64':return F(this,b,a);case'ucs2':case'ucs-2':case'utf16le':case'utf-16le':return E(this,b,a);default:if(d)throw new TypeError('Unknown encoding: '+c);c=(c+'').toLowerCase();d=!0}}function K(g,h,c,a){c=Number(c)||0;var d=g.length-c;a?(a=Number(a),a>d&&(a=d)):a=d;var e=h.length;if(e%2!==0)throw new Error('Invalid hex string');a>e/2&&(a=e/2);for(var b=0;bd)&&(a=d);var e='';for(var c=b;cc)throw new RangeError('Trying to access beyond buffer length')}function d(b,c,d,e,f,g){if(!a.isBuffer(b))throw new TypeError('buffer must be a Buffer instance');if(c>f||cb.length)throw new RangeError('index out of range')}function l(c,b,d,e){b<0&&(b=65535+b+1);for(var a=0,f=Math.min(c.length-d,2);a>>(e?a:1-a)*8}function k(c,b,d,f){b<0&&(b=4294967295+b+1);for(var a=0,e=Math.min(c.length-d,4);a>>(f?a:3-a)*8&255}function u(c,a,b,d,e,f){if(a>e||ac.length)throw new RangeError('index out of range');if(b<0)throw new RangeError('index out of range')}function t(b,c,a,d,e){return e||u(b,c,a,4,3.4028234663852886e38,-3.4028234663852886e38),f.write(b,c,a,d,23,4),a+4}function s(b,c,a,d,e){return e||u(b,c,a,8,1.7976931348623157e308,-1.7976931348623157e308),f.write(b,c,a,d,52,8),a+8}function M(a){if(a=N(a).replace(x,''),a.length<2)return'';while(a.length%4!==0)a+='=';return a}function N(a){return a.trim?a.trim():a.replace(/^\s+|\s+$/g,'')}function B(a){return a<16?'0'+a.toString(16):a.toString(16)}function n(g,b){b=b||Infinity;var a,f=g.length,d=null,c=[],e=0;for(;e55295&&a<57344)if(d)if(a<56320){(b-=3)>-1&&c.push(239,191,189),d=a;continue}else a=d-55296<<10|a-56320|65536,d=null;else if(a>56319){(b-=3)>-1&&c.push(239,191,189);continue}else if(e+1===f){(b-=3)>-1&&c.push(239,191,189);continue}else{d=a;continue}else d&&((b-=3)>-1&&c.push(239,191,189),d=null);if(a<128){if((b-=1)<0)break;c.push(a)}else if(a<2048){if((b-=2)<0)break;c.push(a>>6|192,a&63|128)}else if(a<65536){if((b-=3)<0)break;c.push(a>>12|224,a>>6&63|128,a&63|128)}else if(a<2097152){if((b-=4)<0)break;c.push(a>>18|240,a>>12&63|128,a>>6&63|128,a&63|128)}else throw new Error('Invalid code point')}return c}function Q(c){var b=[];for(var a=0;a>8,f=c%256,a.push(f),a.push(e)}return a}function w(a){return j.toByteArray(M(a))}function m(b,c,d,e){for(var a=0;a=c.length||a>=b.length)break;c[a+d]=b[a]}return a}function z(a){try{return decodeURIComponent(a)}catch(a){return String.fromCharCode(65533)}}var j=o('base64-js'),f=o('ieee754'),i=o('is-array');h.Buffer=a,h.SlowBuffer=p,h.INSPECT_MAX_BYTES=50,a.poolSize=8192;var y={};a.TYPED_ARRAY_SUPPORT=function(b,a){function c(){}try{return b=new ArrayBuffer(0),a=new Uint8Array(b),a.foo=function(){return 42},a.constructor=c,a.foo()===42&&a.constructor===c&&typeof a.subarray==='function'&&new Uint8Array(1).subarray(1,1).byteLength===0}catch(a){return!1}}(),a.isBuffer=function a(b){return!!(b!=null&&b._isBuffer)},a.compare=function b(d,e){if(!(a.isBuffer(d)&&a.isBuffer(e)))throw new TypeError('Arguments must be Buffers');if(d===e)return 0;var f=d.length,g=e.length,c=0,h=Math.min(f,g);while(c0&&(b=this.toString('hex',0,c).match(/.{2}/g).join(' '),this.length>c&&(b+=' ... ')),''},a.prototype.compare=function b(c){if(!a.isBuffer(c))throw new TypeError('Argument must be a Buffer');return this===c?0:a.compare(this,c)},a.prototype.indexOf=function b(d,c){function e(d,e,c){var a=-1;for(var b=0;c+b2147483647?c=2147483647:c<-2147483648&&(c=-2147483648),c>>=0,this.length===0)return-1;if(c>=this.length)return-1;if(c<0&&(c=Math.max(this.length+c,0)),typeof d==='string')return d.length===0?-1:String.prototype.indexOf.call(this,d,c);if(a.isBuffer(d))return e(this,d,c);if(typeof d==='number')return a.TYPED_ARRAY_SUPPORT&&Uint8Array.prototype.indexOf==='function'?Uint8Array.prototype.indexOf.call(this,d,c):e(this,[d],c);throw new TypeError('val must be string, number or Buffer')},a.prototype.get=function a(b){return console.log('.get() is deprecated. Access using array indexes instead.'),this.readUInt8(b)},a.prototype.set=function a(b,c){return console.log('.set() is deprecated. Access using array indexes instead.'),this.writeUInt8(b,c)},a.prototype.write=function a(e,c,b,d){if(c===undefined)d='utf8',b=this.length,c=0;else if(b===undefined&&typeof c==='string')d=c,b=this.length,c=0;else if(isFinite(c))c|=0,isFinite(b)?(b|=0,d===undefined&&(d='utf8')):(d=b,b=undefined);else{var h=d;d=c,c=b|0,b=h}var f=this.length-c;if((b===undefined||b>f)&&(b=f),e.length>0&&(b<0||c<0)||c>this.length)throw new RangeError('attempt to write outside buffer bounds');d||(d='utf8');var g=!1;for(;;)switch(d){case'hex':return K(this,e,c,b);case'utf8':case'utf-8':return J(this,e,c,b);case'ascii':return v(this,e,c,b);case'binary':return I(this,e,c,b);case'base64':return H(this,e,c,b);case'ucs2':case'ucs-2':case'utf16le':case'utf-16le':return G(this,e,c,b);default:if(g)throw new TypeError('Unknown encoding: '+d);d=(''+d).toLowerCase();g=!0}},a.prototype.toJSON=function a(){return{type:'Buffer',data:Array.prototype.slice.call(this._arr||this,0)}},a.prototype.slice=function b(c,d){var e=this.length;c=~~c,d=d===undefined?e:~~d,c<0?(c+=e,c<0&&(c=0)):c>e&&(c=e),d<0?(d+=e,d<0&&(d=0)):d>e&&(d=e),d0&&(f*=256))e+=this[d+--b]*f;return e},a.prototype.readUInt8=function a(b,d){return d||c(b,1,this.length),this[b]},a.prototype.readUInt16LE=function a(b,d){return d||c(b,2,this.length),this[b]|this[b+1]<<8},a.prototype.readUInt16BE=function a(b,d){return d||c(b,2,this.length),this[b]<<8|this[b+1]},a.prototype.readUInt32LE=function a(b,d){return d||c(b,4,this.length),(this[b]|this[b+1]<<8|this[b+2]<<16)+this[b+3]*16777216},a.prototype.readUInt32BE=function a(b,d){return d||c(b,4,this.length),this[b]*16777216+(this[b+1]<<16|this[b+2]<<8|this[b+3])},a.prototype.readIntLE=function a(e,f,h){e|=0,f|=0,h||c(e,f,this.length);var b=this[e],d=1,g=0;while(++g=d&&(b-=Math.pow(2,8*f)),b},a.prototype.readIntBE=function a(e,f,h){e|=0,f|=0,h||c(e,f,this.length);var g=f,b=1,d=this[e+--g];while(g>0&&(b*=256))d+=this[e+--g]*b;return b*=128,d>=b&&(d-=Math.pow(2,8*f)),d},a.prototype.readInt8=function a(b,d){return d||c(b,1,this.length),this[b]&128?(255-this[b]+1)*-1:this[b]},a.prototype.readInt16LE=function a(d,e){e||c(d,2,this.length);var b=this[d]|this[d+1]<<8;return b&32768?b|4294901760:b},a.prototype.readInt16BE=function a(d,e){e||c(d,2,this.length);var b=this[d+1]|this[d]<<8;return b&32768?b|4294901760:b},a.prototype.readInt32LE=function a(b,d){return d||c(b,4,this.length),this[b]|this[b+1]<<8|this[b+2]<<16|this[b+3]<<24},a.prototype.readInt32BE=function a(b,d){return d||c(b,4,this.length),this[b]<<24|this[b+1]<<16|this[b+2]<<8|this[b+3]},a.prototype.readFloatLE=function a(b,d){return d||c(b,4,this.length),f.read(this,b,!0,23,4)},a.prototype.readFloatBE=function a(b,d){return d||c(b,4,this.length),f.read(this,b,!1,23,4)},a.prototype.readDoubleLE=function a(b,d){return d||c(b,8,this.length),f.read(this,b,!0,52,8)},a.prototype.readDoubleBE=function a(b,d){return d||c(b,8,this.length),f.read(this,b,!1,52,8)},a.prototype.writeUIntLE=function a(b,c,e,h){b=+b,c|=0,e|=0,h||d(this,b,c,e,Math.pow(2,8*e),0);var f=1,g=0;this[c]=b&255;while(++g=0&&(g*=256))this[c+f]=b/g&255;return c+e},a.prototype.writeUInt8=function b(c,e,f){return c=+c,e|=0,f||d(this,c,e,1,255,0),a.TYPED_ARRAY_SUPPORT||(c=Math.floor(c)),this[e]=c,e+1},a.prototype.writeUInt16LE=function b(c,e,f){return c=+c,e|=0,f||d(this,c,e,2,65535,0),a.TYPED_ARRAY_SUPPORT?(this[e]=c,this[e+1]=c>>>8):l(this,c,e,!0),e+2},a.prototype.writeUInt16BE=function b(c,e,f){return c=+c,e|=0,f||d(this,c,e,2,65535,0),a.TYPED_ARRAY_SUPPORT?(this[e]=c>>>8,this[e+1]=c):l(this,c,e,!1),e+2},a.prototype.writeUInt32LE=function b(c,e,f){return c=+c,e|=0,f||d(this,c,e,4,4294967295,0),a.TYPED_ARRAY_SUPPORT?(this[e+3]=c>>>24,this[e+2]=c>>>16,this[e+1]=c>>>8,this[e]=c):k(this,c,e,!0),e+4},a.prototype.writeUInt32BE=function b(c,e,f){return c=+c,e|=0,f||d(this,c,e,4,4294967295,0),a.TYPED_ARRAY_SUPPORT?(this[e]=c>>>24,this[e+1]=c>>>16,this[e+2]=c>>>8,this[e+3]=c):k(this,c,e,!1),e+4},a.prototype.writeIntLE=function a(b,c,e,j){if(b=+b,c|=0,!j){var f=Math.pow(2,8*e-1);d(this,b,c,e,f-1,-f)}var g=0,h=1,i=b<0?1:0;this[c]=b&255;while(++g>0)-i&255;return c+e},a.prototype.writeIntBE=function a(b,c,e,j){if(b=+b,c|=0,!j){var g=Math.pow(2,8*e-1);d(this,b,c,e,g-1,-g)}var f=e-1,h=1,i=b<0?1:0;this[c+f]=b&255;while(--f>=0&&(h*=256))this[c+f]=(b/h>>0)-i&255;return c+e},a.prototype.writeInt8=function b(c,e,f){return c=+c,e|=0,f||d(this,c,e,1,127,-128),a.TYPED_ARRAY_SUPPORT||(c=Math.floor(c)),c<0&&(c=255+c+1),this[e]=c,e+1},a.prototype.writeInt16LE=function b(c,e,f){return c=+c,e|=0,f||d(this,c,e,2,32767,-32768),a.TYPED_ARRAY_SUPPORT?(this[e]=c,this[e+1]=c>>>8):l(this,c,e,!0),e+2},a.prototype.writeInt16BE=function b(c,e,f){return c=+c,e|=0,f||d(this,c,e,2,32767,-32768),a.TYPED_ARRAY_SUPPORT?(this[e]=c>>>8,this[e+1]=c):l(this,c,e,!1),e+2},a.prototype.writeInt32LE=function b(c,e,f){return c=+c,e|=0,f||d(this,c,e,4,2147483647,-2147483648),a.TYPED_ARRAY_SUPPORT?(this[e]=c,this[e+1]=c>>>8,this[e+2]=c>>>16,this[e+3]=c>>>24):k(this,c,e,!0),e+4},a.prototype.writeInt32BE=function b(c,e,f){return c=+c,e|=0,f||d(this,c,e,4,2147483647,-2147483648),c<0&&(c=4294967295+c+1),a.TYPED_ARRAY_SUPPORT?(this[e]=c>>>24,this[e+1]=c>>>16,this[e+2]=c>>>8,this[e+3]=c):k(this,c,e,!1),e+4},a.prototype.writeFloatLE=function a(b,c,d){return t(this,b,c,!0,d)},a.prototype.writeFloatBE=function a(b,c,d){return t(this,b,c,!1,d)},a.prototype.writeDoubleLE=function a(b,c,d){return s(this,b,c,!0,d)},a.prototype.writeDoubleBE=function a(b,c,d){return s(this,b,c,!1,d)},a.prototype.copy=function b(f,e,c,d){if(c||(c=0),!d&&d!==0&&(d=this.length),e>=f.length&&(e=f.length),e||(e=0),d>0&&d=this.length)throw new RangeError('sourceStart out of bounds');if(d<0)throw new RangeError('sourceEnd out of bounds');d>this.length&&(d=this.length),f.length-e=this.length)throw new RangeError('start out of bounds');if(d<0||d>this.length)throw new RangeError('end out of bounds');var b;if(typeof e==='number')for(b=c;b0)throw new Error('Invalid string. Length must be a multiple of 4');var i=b.length;g='='===b.charAt(i-2)?2:'='===b.charAt(i-1)?1:0,h=new f(b.length*3/4-g),j=g>0?b.length-4:b.length;var l=0;for(c=0,k=0;c>16),e((d&65280)>>8),e(d&255);return g===2?(d=a(b.charAt(c))<<2|a(b.charAt(c+1))>>4,e(d&255)):g===1&&(d=a(b.charAt(c))<<10|a(b.charAt(c+1))<<4|a(b.charAt(c+2))>>2,e(d>>8&255),e(d&255)),h}function l(a){function d(a){return b.charAt(a)}function i(a){return d(a>>18&63)+d(a>>12&63)+d(a>>6&63)+d(a&63)}var f,g=a.length%3,c='',e,h;for(f=0,h=a.length-g;f>2);c+=d(e<<4&63);c+='==';break;case 2:e=(a[a.length-2]<<8)+a[a.length-1];c+=d(e>>10);c+=d(e>>4&63);c+=d(e<<2&63);c+='=';break}return c}f=typeof Uint8Array!=='undefined'?Uint8Array:Array,g='+'.charCodeAt(0),h='/'.charCodeAt(0),c='0'.charCodeAt(0),d='a'.charCodeAt(0),e='A'.charCodeAt(0),j='-'.charCodeAt(0),k='_'.charCodeAt(0),i.toByteArray=m,i.fromByteArray=l}(a===void 0?this.base64js={}:a)},{}],6:[function(b,c,a){a.read=function(h,l,n,f,m){var b,d,i=m*8-f-1,j=(1<>1,a=-7,c=n?m-1:0,g=n?-1:1,e=h[l+c];for(c+=g,b=e&(1<<-a)-1,e>>=-a,a+=i;a>0;b=b*256+h[l+c],c+=g,a-=8);for(d=b&(1<<-a)-1,b>>=-a,a+=f;a>0;d=d*256+h[l+c],c+=g,a-=8);if(b===0)b=1-k;else if(b===j)return d?NaN:(e?-1:1)*Infinity;else d+=Math.pow(2,f),b-=k;return(e?-1:1)*d*Math.pow(2,b-f)},a.write=function(k,b,m,n,c,p){var a,d,f,h=p*8-c-1,i=(1<>1,l=c===23?Math.pow(2,-24)-Math.pow(2,-77):0,g=n?0:p-1,j=n?1:-1,o=b<0||b===0&&1/b<0?1:0;for(b=Math.abs(b),isNaN(b)||b===Infinity?(d=isNaN(b)?1:0,a=i):(a=Math.floor(Math.log(b)/Math.LN2),b*(f=Math.pow(2,-a))<1&&(a--,f*=2),a+e>=1?b+=l/f:b+=l*Math.pow(2,1-e),b*f>=2&&(a++,f/=2),a+e>=i?(d=0,a=i):a+e>=1?(d=(b*f-1)*Math.pow(2,c),a+=e):(d=b*Math.pow(2,e-1)*Math.pow(2,c),a=0));c>=8;k[m+g]=d&255,g+=j,d/=256,c-=8);for(a=a<0;k[m+g]=a&255,g+=j,a/=256,h-=8);k[m+g-j]|=o*128}},{}],7:[function(d,c,e){var a=Array.isArray,b=Object.prototype.toString;c.exports=a||function(a){return!!a&&'[object Array]'==b.call(a)}},{}],8:[function(b,d,f){'use strict';function e(d){function g(a){return d.apply(this,a)}function b(){return this instanceof b?d.apply(this,arguments):new g(arguments)}var e=c(d.prototype),h,f;a(b,d),a(g,b),h=b.prototype;for(f in e)h[f]=e[f];return b}var c=b('clone'),a=b('inherits');d.exports=e},{clone:9,inherits:10}],9:[function(b,a,c){(function(b){var c=function(){'use strict';function a(k,c,e,f){function i(e,p){if(e===null)return null;if(p==0)return e;var k,l;if(typeof e!='object')return e;if(a.__isArray(e))k=[];else if(a.__isRegExp(e))k=new RegExp(e.source,d(e)),e.lastIndex&&(k.lastIndex=e.lastIndex);else if(a.__isDate(e))k=new Date(e.getTime());else if(j&&b.isBuffer(e))return k=new b(e.length),e.copy(k),k;else f===void 0?(l=Object.getPrototypeOf(e),k=Object.create(l)):(k=Object.create(f),l=f);if(c){var n=g.indexOf(e);if(n!=-1)return h[n];g.push(e),h.push(k)}for(var m in e){var o;if(l&&(o=Object.getOwnPropertyDescriptor(l,m)),o&&o.set==null)continue;k[m]=i(e[m],p-1)}return k}var l;typeof c==='object'&&(e=c.depth,f=c.prototype,l=c.filter,c=c.circular);var g=[],h=[],j=b!==void 0;return c===void 0&&(c=!0),e===void 0&&(e=Infinity),i(k,e)}function c(a){return Object.prototype.toString.call(a)}function e(a){return typeof a==='object'&&c(a)==='[object Date]'}function f(a){return typeof a==='object'&&c(a)==='[object Array]'}function g(a){return typeof a==='object'&&c(a)==='[object RegExp]'}function d(b){var a='';return b.global&&(a+='g'),b.ignoreCase&&(a+='i'),b.multiline&&(a+='m'),a}return a.clonePrototype=function a(c){if(c===null)return null;var b=function(){};return b.prototype=c,new b},a.__objToStr=c,a.__isDate=e,a.__isArray=f,a.__isRegExp=g,a.__getRegExpFlags=d,a}();typeof a==='object'&&a.exports&&(a.exports=c)}.call(this,b('buffer').Buffer))},{buffer:4}],10:[function(b,a,c){typeof Object.create==='function'?a.exports=function a(b,c){b.super_=c,b.prototype=Object.create(c.prototype,{constructor:{value:b,enumerable:!1,writable:!0,configurable:!0}})}:a.exports=function a(b,d){b.super_=d;var c=function(){};c.prototype=d.prototype,b.prototype=new c,b.prototype.constructor=b}},{}],11:[function(i,e,o){'use strict';function d(a){return a||(a={}),(a.line||1)+':'+(a.column||1)}function f(a){function b(){var b=a.directory,d;return a.filename||a.extension?(d=b.charAt(b.length-1),(d==='/'||d==='\\')&&(b=b.slice(0,-1)),b==='.'&&(b=''),(b?b+c:'')+a.filename+(a.extension?'.'+a.extension:'')):''}return b.toString=b,b}function b(a){var c=this;if(!(c instanceof b))return new b(a);if(a&&typeof a.message==='function'&&typeof a.hasFailed==='function')return a;a?typeof a==='string'&&(a={contents:a}):a={},c.contents=a.contents||'',c.filename=a.filename||'',c.directory=a.directory||'',c.extension=a.extension||'',c.messages=[],c.filePath=f(c)}function h(){return this.contents}function g(b){var a=this;return b||(b={}),a.directory=b.directory||a.directory||'',a.filename=b.filename||a.filename||'',a.extension=b.extension||a.extension||'',a}function j(c,a){var e=this.filePath(),f,b;return a&&a.position&&(a=a.position),a&&a.start?(f=d(a.start)+'-'+d(a.end),a=a.start):f=d(a),b=new Error(c.message||c),b.name=(e?e+':':'')+f,b.file=e,b.reason=c.message||c,b.line=a?a.line:null,b.column=a?a.column:null,c.stack&&(b.stack=c.stack),b}function k(){var a=this.message.apply(this,arguments);return a.fatal=!1,this.messages.push(a),a}function l(b,c){var a=this.message(b,c);if(a.fatal=!0,this.messages.push(a),!this.quiet)throw a;return a}function m(){var a=this.messages,b=-1,c=a.length;while(++ba.length)try{return e.apply(h,a.concat(c))}catch(a){return c(a)}return g(e)?b(e).apply(h,a.concat(c)):d(e,c).apply(h,a)}}function d(b,a){return function(){var c;try{c=b.apply(this,arguments)}catch(b){return a(b)}h(c)?c.then(function(b){a(null,b)},a):c instanceof Error?a(c):a(null,c)}}function g(a){return a&&a.constructor&&'GeneratorFunction'==a.constructor.name}function h(a){return a&&'function'==typeof a.then}function i(b){return function(){var c=b.apply(this,arguments);return b=a,c}}var a=function(){},b=f('co');c.exports=e},{co:14}],14:[function(l,k,m){function b(b){var f=e(b);return function(h){function k(a,b){setImmediate(function(){h.call(e,a,b)})}function i(f,g){var b;if(arguments.length>2&&(g=a.call(arguments,1)),f)try{b=j.throw(f)}catch(a){return k(a)}if(!f)try{b=j.next(g)}catch(a){return k(a)}if(b.done)return k(null,b.value);if(b.value=d(b.value,e),'function'==typeof b.value){var c=!1;try{b.value.call(e,function(){if(c)return;c=!0,i.apply(e,arguments)})}catch(a){setImmediate(function(){if(c)return;c=!0,i(a)})}return}i(new TypeError('You may only yield a function, promise, generator, array, or object, but the following was passed: "'+String(b.value)+'"'))}var e=this,j=b;if(f){var g=a.call(arguments),l=g.length,m=l&&'function'==typeof g[l-1];h=m?g.pop():c,j=b.apply(this,g)}else h=h||c;i()}}function d(a,c){return e(a)?b(a.call(c)):j(a)?b(a):i(a)?f(a):'function'==typeof a?a:h(a)||Array.isArray(a)?g.call(c,a):a}function g(a){var b=this,c=Array.isArray(a);return function(i){function k(a,c){if(j)return;try{if(a=d(a,b),'function'!=typeof a)return f[c]=a,--h||i(null,f);a.call(b,function(a,b){if(j)return;if(a)return j=!0,i(a);f[c]=b,--h||i(null,f)})}catch(a){j=!0,i(a)}}var g=Object.keys(a),h=g.length,f=c?new Array(h):new a.constructor,j;if(!h){setImmediate(function(){i(null,f)});return}if(!c)for(var e=0;e