Template Upload

This commit is contained in:
SOUTHERNCO\x2mjbyrn
2017-05-17 13:45:25 -04:00
parent 415b9c25f3
commit 7efe7605b8
11476 changed files with 2170865 additions and 34 deletions

21
node_modules/typings/LICENSE generated vendored Normal file
View File

@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2015 Blake Embrey (hello@blakeembrey.com)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

82
node_modules/typings/README.md generated vendored Normal file
View File

@ -0,0 +1,82 @@
# ![Typings](https://cdn.rawgit.com/typings/typings/master/logo.svg)
[![NPM version][npm-image]][npm-url]
[![NPM downloads][downloads-image]][downloads-url]
[![Build status][travis-image]][travis-url]
[![Test coverage][coveralls-image]][coveralls-url]
[![Gitter][gitter-image]][gitter-url]
> The TypeScript Definition Manager.
**Updating from 0.6 to 0.7?** Make sure you `rm -rf typings/` and re-install them, the directory structure has changed.
## Quick Start
```sh
# Install Typings CLI utility.
npm install typings --global
# Search for definitions.
typings search tape
# Find an available definition (by name).
typings search --name react
# Install typings (DT is "ambient", make sure to enable the flag and persist the selection in `typings.json`).
typings install react --ambient --save
# Use `main.d.ts` (in `tsconfig.json` or as a `///` reference).
cat typings/main.d.ts
```
## Usage
**Typings** is the simple way to manage and install TypeScript definitions. It uses `typings.json`, which can resolve to GitHub, NPM, Bower, HTTP and local files. Packages can use type definitions from various sources and different versions, and know they will _never_ cause a conflict for users.
```sh
typings install debug --save
```
A [public registry](https://github.com/typings/registry) is maintained by the community, and is used to resolve official type definitions for JavaScript packages.
## Read More
* [Commands](docs/commands.md)
* [Coming from TSD?](docs/tsd.md)
* [Example typings](docs/examples.md)
* [Why external modules?](docs/external-modules.md)
* [About the registry](docs/registry.md)
* [FAQ](docs/faq.md)
## Contributing
```sh
# Installation
# Fork this repo (https://github.com/typings/typings)
# Clone the fork (E.g. `https://github.com/<your_username>/typings.git`)
cd typings
# Install modules
npm install
# Build
npm run build
# Test
npm run test
```
## License
MIT
[npm-image]: https://img.shields.io/npm/v/typings.svg?style=flat
[npm-url]: https://npmjs.org/package/typings
[downloads-image]: https://img.shields.io/npm/dm/typings.svg?style=flat
[downloads-url]: https://npmjs.org/package/typings
[travis-image]: https://img.shields.io/travis/typings/typings.svg?style=flat
[travis-url]: https://travis-ci.org/typings/typings
[coveralls-image]: https://img.shields.io/coveralls/typings/typings.svg?style=flat
[coveralls-url]: https://coveralls.io/r/typings/typings?branch=master
[gitter-image]: https://badges.gitter.im/typings/typings.svg
[gitter-url]: https://gitter.im/typings/typings?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge

7
node_modules/typings/dist/aliases.d.ts generated vendored Normal file
View File

@ -0,0 +1,7 @@
export interface Aliases {
[cmd: string]: {
exec(args: string[], options: Object): any;
help(): string;
};
}
export declare const aliases: Aliases;

29
node_modules/typings/dist/aliases.js generated vendored Normal file
View File

@ -0,0 +1,29 @@
"use strict";
var bundle = require('./bin-bundle');
var init = require('./bin-init');
var uninstall = require('./bin-uninstall');
var install = require('./bin-install');
var list = require('./bin-list');
var search = require('./bin-search');
var open = require('./bin-open');
var view = require('./bin-view');
exports.aliases = {
i: install,
in: install,
install: install,
r: uninstall,
rm: uninstall,
remove: uninstall,
uninstall: uninstall,
init: init,
ls: list,
ll: list,
la: list,
list: list,
bundle: bundle,
search: search,
open: open,
view: view,
info: view
};
//# sourceMappingURL=aliases.js.map

1
node_modules/typings/dist/aliases.js.map generated vendored Normal file
View File

@ -0,0 +1 @@
{"version":3,"file":"aliases.js","sourceRoot":"","sources":["../src/aliases.ts"],"names":[],"mappings":";AAAA,IAAY,MAAM,WAAM,cACxB,CAAC,CADqC;AACtC,IAAY,IAAI,WAAM,YACtB,CAAC,CADiC;AAClC,IAAY,SAAS,WAAM,iBAC3B,CAAC,CAD2C;AAC5C,IAAY,OAAO,WAAM,eACzB,CAAC,CADuC;AACxC,IAAY,IAAI,WAAM,YACtB,CAAC,CADiC;AAClC,IAAY,MAAM,WAAM,cACxB,CAAC,CADqC;AACtC,IAAY,IAAI,WAAM,YACtB,CAAC,CADiC;AAClC,IAAY,IAAI,WAAM,YAEtB,CAAC,CAFiC;AASrB,eAAO,GAAY;IAE9B,CAAC,EAAE,OAAO;IACV,EAAE,EAAE,OAAO;IACX,OAAO,EAAE,OAAO;IAEhB,CAAC,EAAE,SAAS;IACZ,EAAE,EAAE,SAAS;IACb,MAAM,EAAE,SAAS;IACjB,SAAS,EAAE,SAAS;IAEpB,IAAI,EAAE,IAAI;IAEV,EAAE,EAAE,IAAI;IACR,EAAE,EAAE,IAAI;IACR,EAAE,EAAE,IAAI;IACR,IAAI,EAAE,IAAI;IAEV,MAAM,EAAE,MAAM;IAEd,MAAM,EAAE,MAAM;IAEd,IAAI,EAAE,IAAI;IAEV,IAAI,EAAE,IAAI;IACV,IAAI,EAAE,IAAI;CACX,CAAA"}

10
node_modules/typings/dist/bin-bundle.d.ts generated vendored Normal file
View File

@ -0,0 +1,10 @@
import Promise = require('any-promise');
export declare function help(): string;
export interface Options {
cwd: string;
name: string;
out: string;
ambient: boolean;
verbose: boolean;
}
export declare function exec(args: string[], options: Options): Promise<any>;

12
node_modules/typings/dist/bin-bundle.js generated vendored Normal file
View File

@ -0,0 +1,12 @@
#!/usr/bin/env node
"use strict";
var typings_core_1 = require('typings-core');
function help() {
return "\ntypings bundle --out <directory>\n\nOptions:\n [--out|-o] <directory> The bundled output directory\n [--name] <name> Bundle module name\n [--ambient|-A] Bundle as an ambient definition\n";
}
exports.help = help;
function exec(args, options) {
return typings_core_1.bundle(options);
}
exports.exec = exec;
//# sourceMappingURL=bin-bundle.js.map

1
node_modules/typings/dist/bin-bundle.js.map generated vendored Normal file
View File

@ -0,0 +1 @@
{"version":3,"file":"bin-bundle.js","sourceRoot":"","sources":["../src/bin-bundle.ts"],"names":[],"mappings":";;AAGA,6BAAuB,cAEvB,CAAC,CAFoC;AAErC;IACE,MAAM,CAAC,gNAOR,CAAA;AACD,CAAC;AATe,YAAI,OASnB,CAAA;AAUD,cAAsB,IAAc,EAAE,OAAgB;IACpD,MAAM,CAAC,qBAAM,CAAC,OAAO,CAAC,CAAA;AACxB,CAAC;AAFe,YAAI,OAEnB,CAAA"}

8
node_modules/typings/dist/bin-init.d.ts generated vendored Normal file
View File

@ -0,0 +1,8 @@
import Promise = require('any-promise');
export declare function help(): string;
export interface Options {
verbose: boolean;
cwd: string;
upgrade: boolean;
}
export declare function exec(args: string[], options: Options): Promise<void>;

12
node_modules/typings/dist/bin-init.js generated vendored Normal file
View File

@ -0,0 +1,12 @@
#!/usr/bin/env node
"use strict";
var typings_core_1 = require('typings-core');
function help() {
return "\ntypings init\n\nOptions:\n [--upgrade] Upgrade `tsd.json` to `typings.json`\n";
}
exports.help = help;
function exec(args, options) {
return typings_core_1.init(options);
}
exports.exec = exec;
//# sourceMappingURL=bin-init.js.map

1
node_modules/typings/dist/bin-init.js.map generated vendored Normal file
View File

@ -0,0 +1 @@
{"version":3,"file":"bin-init.js","sourceRoot":"","sources":["../src/bin-init.ts"],"names":[],"mappings":";;AAGA,6BAAqB,cAErB,CAAC,CAFkC;AAEnC;IACE,MAAM,CAAC,qFAKR,CAAA;AACD,CAAC;AAPe,YAAI,OAOnB,CAAA;AAQD,cAAsB,IAAc,EAAE,OAAgB;IACpD,MAAM,CAAC,mBAAI,CAAC,OAAO,CAAC,CAAA;AACtB,CAAC;AAFe,YAAI,OAEnB,CAAA"}

13
node_modules/typings/dist/bin-install.d.ts generated vendored Normal file
View File

@ -0,0 +1,13 @@
import Promise = require('any-promise');
import { Emitter } from 'typings-core';
export declare function help(): string;
export interface Options {
cwd: string;
verbose: boolean;
save: boolean;
saveDev: boolean;
savePeer: boolean;
ambient: boolean;
emitter: Emitter;
}
export declare function exec(args: string[], options: Options): Promise<void>;

45
node_modules/typings/dist/bin-install.js generated vendored Normal file
View File

@ -0,0 +1,45 @@
#!/usr/bin/env node
"use strict";
var Promise = require('any-promise');
var typings_core_1 = require('typings-core');
var listify = require('listify');
var cli_1 = require('./support/cli');
function help() {
return "\ntypings install (with no arguments, in package directory)\ntypings install [<name>=]<location>\n\n <name> Module name of the installed definition\n <location> The location to read from (described below)\n\nValid Locations:\n [<source>!]<pkg>[@<version>][#<tag>]\n file:<path>\n github:<org>/<repo>[/<path>][#<commitish>]\n bitbucket:<org>/<repo>[/<path>][#<commitish>]\n npm:<pkg>[/<path>]\n bower:<pkg>[/<path>]\n http(s)://<host>/<path>\n\n <source> The registry mirror (E.g. \"npm\", \"bower\", \"env\", \"global\", \"dt\", ...)\n <path> Path to a `.d.ts` file or `typings.json`\n <host> A domain name (with optional port)\n <version> A semver range (E.g. \">=4.0\")\n <tag> The specific tag of a registry entry\n <commitish> A git commit, tag or branch\n\nOptions:\n [--save|-S] Persist to \"dependencies\"\n [--save-dev|-D] Persist to \"devDependencies\"\n [--save-peer|-P] Persist to \"peerDependencies\"\n [--ambient|-A] Install and persist as an ambient definition\n [-SA] Persist to \"ambientDependencies\"\n [-DA] Persist to \"ambientDevDependencies\"\n [--production] Install only production dependencies (omits dev dependencies)\n\nAliases: i, in\n";
}
exports.help = help;
function exec(args, options) {
var emitter = options.emitter;
if (args.length === 0) {
return typings_core_1.install(options)
.then(function (result) {
console.log(cli_1.archifyDependencyTree(result));
});
}
var references = [];
emitter.on('reference', function (_a) {
var reference = _a.reference, name = _a.name;
if (references.indexOf(reference) === -1) {
cli_1.logInfo("Stripped reference \"" + reference + "\" during installation from \"" + name + "\"", 'reference');
references.push(reference);
}
});
emitter.on('ambientdependencies', function (_a) {
var name = _a.name, dependencies = _a.dependencies;
var deps = Object.keys(dependencies).map(function (x) { return JSON.stringify(x); });
if (deps.length) {
cli_1.logInfo("\"" + name + "\" lists ambient dependencies on " + listify(deps) + " and should be installed", 'ambientdependencies');
}
});
return Promise.all(args.map(function (arg) {
return typings_core_1.installDependencyRaw(arg, options);
}))
.then(function (results) {
for (var _i = 0, results_1 = results; _i < results_1.length; _i++) {
var result = results_1[_i];
console.log(cli_1.archifyDependencyTree(result));
}
});
}
exports.exec = exec;
//# sourceMappingURL=bin-install.js.map

1
node_modules/typings/dist/bin-install.js.map generated vendored Normal file
View File

@ -0,0 +1 @@
{"version":3,"file":"bin-install.js","sourceRoot":"","sources":["../src/bin-install.ts"],"names":[],"mappings":";;AAEA,IAAO,OAAO,WAAW,aAAa,CAAC,CAAA;AACvC,6BAAuD,cACvD,CAAC,CADoE;AACrE,IAAO,OAAO,WAAW,SAAS,CAAC,CAAA;AACnC,oBAA+C,eAE/C,CAAC,CAF6D;AAE9D;IACE,MAAM,CAAC,ouCAiCR,CAAA;AACD,CAAC;AAnCe,YAAI,OAmCnB,CAAA;AAYD,cAAsB,IAAc,EAAE,OAAgB;IAC5C,6BAAO,CAAY;IAE3B,EAAE,CAAC,CAAC,IAAI,CAAC,MAAM,KAAK,CAAC,CAAC,CAAC,CAAC;QACtB,MAAM,CAAC,sBAAO,CAAC,OAAO,CAAC;aACpB,IAAI,CAAC,UAAC,MAAM;YACX,OAAO,CAAC,GAAG,CAAC,2BAAqB,CAAC,MAAM,CAAC,CAAC,CAAA;QAC5C,CAAC,CAAC,CAAA;IACN,CAAC;IAGD,IAAM,UAAU,GAAa,EAAE,CAAA;IAG/B,OAAO,CAAC,EAAE,CAAC,WAAW,EAAE,UAAU,EAAmB;YAAjB,wBAAS,EAAE,cAAI;QACjD,EAAE,CAAC,CAAC,UAAU,CAAC,OAAO,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC;YACzC,aAAO,CAAC,0BAAuB,SAAS,sCAA+B,IAAI,OAAG,EAAE,WAAW,CAAC,CAAA;YAE5F,UAAU,CAAC,IAAI,CAAC,SAAS,CAAC,CAAA;QAC5B,CAAC;IACH,CAAC,CAAC,CAAA;IAGF,OAAO,CAAC,EAAE,CAAC,qBAAqB,EAAE,UAAU,EAAsB;YAApB,cAAI,EAAE,8BAAY;QAC9D,IAAM,IAAI,GAAG,MAAM,CAAC,IAAI,CAAC,YAAY,CAAC,CAAC,GAAG,CAAC,UAAA,CAAC,IAAI,OAAA,IAAI,CAAC,SAAS,CAAC,CAAC,CAAC,EAAjB,CAAiB,CAAC,CAAA;QAElE,EAAE,CAAC,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,CAAC;YAChB,aAAO,CACL,OAAI,IAAI,yCAAmC,OAAO,CAAC,IAAI,CAAC,6BAA0B,EAClF,qBAAqB,CACtB,CAAA;QACH,CAAC;IACH,CAAC,CAAC,CAAA;IAEF,MAAM,CAAC,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,GAAG,CAAC,UAAA,GAAG;QAC7B,MAAM,CAAC,mCAAoB,CAAC,GAAG,EAAE,OAAO,CAAC,CAAA;IAC3C,CAAC,CAAC,CAAC;SACA,IAAI,CAAC,UAAA,OAAO;QACX,GAAG,CAAC,CAAiB,UAAO,EAAP,mBAAO,EAAP,qBAAO,EAAP,IAAO,CAAC;YAAxB,IAAM,MAAM,gBAAA;YACf,OAAO,CAAC,GAAG,CAAC,2BAAqB,CAAC,MAAM,CAAC,CAAC,CAAA;SAC3C;IACH,CAAC,CAAC,CAAA;AACN,CAAC;AA1Ce,YAAI,OA0CnB,CAAA"}

8
node_modules/typings/dist/bin-list.d.ts generated vendored Normal file
View File

@ -0,0 +1,8 @@
import Promise = require('any-promise');
export declare function help(): string;
export interface Options {
cwd: string;
dev: boolean;
verbose: boolean;
}
export declare function exec(args: string[], options: Options): Promise<void>;

16
node_modules/typings/dist/bin-list.js generated vendored Normal file
View File

@ -0,0 +1,16 @@
#!/usr/bin/env node
"use strict";
var cli_1 = require('./support/cli');
var typings_core_1 = require('typings-core');
function help() {
return "\ntypings list\n\nOptions:\n [--production] List only production dependencies (omit dev dependencies)\n\nAliases: la, ll, ls\n";
}
exports.help = help;
function exec(args, options) {
return typings_core_1.list(options)
.then(function (tree) {
console.log(cli_1.archifyDependencyTree({ tree: tree }));
});
}
exports.exec = exec;
//# sourceMappingURL=bin-list.js.map

1
node_modules/typings/dist/bin-list.js.map generated vendored Normal file
View File

@ -0,0 +1 @@
{"version":3,"file":"bin-list.js","sourceRoot":"","sources":["../src/bin-list.ts"],"names":[],"mappings":";;AAGA,oBAAsC,eACtC,CAAC,CADoD;AACrD,6BAAqB,cAErB,CAAC,CAFkC;AAEnC;IACE,MAAM,CAAC,iIAOR,CAAA;AACD,CAAC;AATe,YAAI,OASnB,CAAA;AAQD,cAAsB,IAAc,EAAE,OAAgB;IACpD,MAAM,CAAC,mBAAI,CAAC,OAAO,CAAC;SACjB,IAAI,CAAC,UAAU,IAAI;QAClB,OAAO,CAAC,GAAG,CAAC,2BAAqB,CAAC,EAAE,MAAA,IAAI,EAAE,CAAC,CAAC,CAAA;IAC9C,CAAC,CAAC,CAAA;AACN,CAAC;AALe,YAAI,OAKnB,CAAA"}

2
node_modules/typings/dist/bin-open.d.ts generated vendored Normal file
View File

@ -0,0 +1,2 @@
export declare function help(): string;
export declare function exec(args: string[]): void;

16
node_modules/typings/dist/bin-open.js generated vendored Normal file
View File

@ -0,0 +1,16 @@
"use strict";
var typings_core_1 = require('typings-core');
var cli_1 = require('./support/cli');
function help() {
return "\ntypings open <location>\n\n <location> A known Typings location with scheme (see typings install -h)\n";
}
exports.help = help;
function exec(args) {
if (args.length === 0) {
cli_1.logError(help());
return;
}
console.log(typings_core_1.open(args[0]));
}
exports.exec = exec;
//# sourceMappingURL=bin-open.js.map

1
node_modules/typings/dist/bin-open.js.map generated vendored Normal file
View File

@ -0,0 +1 @@
{"version":3,"file":"bin-open.js","sourceRoot":"","sources":["../src/bin-open.ts"],"names":[],"mappings":";AAAA,6BAAqB,cACrB,CAAC,CADkC;AACnC,oBAAyB,eAEzB,CAAC,CAFuC;AAExC;IACE,MAAM,CAAC,4GAIR,CAAA;AACD,CAAC;AANe,YAAI,OAMnB,CAAA;AAED,cAAsB,IAAc;IAClC,EAAE,CAAC,CAAC,IAAI,CAAC,MAAM,KAAK,CAAC,CAAC,CAAC,CAAC;QACtB,cAAQ,CAAC,IAAI,EAAE,CAAC,CAAA;QAChB,MAAM,CAAA;IACR,CAAC;IAED,OAAO,CAAC,GAAG,CAAC,mBAAI,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,CAAA;AAC5B,CAAC;AAPe,YAAI,OAOnB,CAAA"}

12
node_modules/typings/dist/bin-search.d.ts generated vendored Normal file
View File

@ -0,0 +1,12 @@
import Promise = require('any-promise');
export declare function help(): string;
export interface Options {
name: string;
source: string;
offset: string;
limit: string;
order: string;
sort: string;
verbose: boolean;
}
export declare function exec(args: string[], options: Options): Promise<void>;

25
node_modules/typings/dist/bin-search.js generated vendored Normal file
View File

@ -0,0 +1,25 @@
#!/usr/bin/env node
"use strict";
var columnify = require('columnify');
var typings_core_1 = require('typings-core');
function help() {
return "\ntypings search [query]\n\nOptions:\n [--name] <name> Search for definitions by exact name (E.g. only \"react\")\n [--source] <source> The registry mirror (E.g. \"npm\", \"bower\", \"env\", \"global\", \"dt\", ...)\n [--offset] <x> Skip first \"x\" results (default: 0)\n [--limit] <x> Limit to \"x\" results (default: 20, max: 100)\n [--order] <order> Direction to sort results (default: \"asc\", enum: \"asc\" or \"desc\")\n [--sort] <column> Order results by a column (E.g. \"versions\", \"name\", ...)\n";
}
exports.help = help;
function exec(args, options) {
var query = args[0];
var name = options.name, source = options.source, offset = options.offset, limit = options.limit, order = options.order, sort = options.sort;
return typings_core_1.search({ name: name, source: source, query: query, offset: offset, limit: limit, order: order, sort: sort })
.then(function (_a) {
var results = _a.results, total = _a.total;
if (total === 0) {
console.log('No results found for search');
return;
}
console.log("Viewing " + results.length + " of " + total);
console.log('');
console.log(columnify(results));
});
}
exports.exec = exec;
//# sourceMappingURL=bin-search.js.map

1
node_modules/typings/dist/bin-search.js.map generated vendored Normal file
View File

@ -0,0 +1 @@
{"version":3,"file":"bin-search.js","sourceRoot":"","sources":["../src/bin-search.ts"],"names":[],"mappings":";;AAGA,IAAO,SAAS,WAAW,WAAW,CAAC,CAAA;AACvC,6BAAuB,cAEvB,CAAC,CAFoC;AAErC;IACE,MAAM,CAAC,uhBAUR,CAAA;AACD,CAAC;AAZe,YAAI,OAYnB,CAAA;AAYD,cAAsB,IAAc,EAAE,OAAgB;IACpD,IAAM,KAAK,GAAG,IAAI,CAAC,CAAC,CAAC,CAAA;IACb,uBAAI,EAAE,uBAAM,EAAE,uBAAM,EAAE,qBAAK,EAAE,qBAAK,EAAE,mBAAI,CAAY;IAE5D,MAAM,CAAC,qBAAM,CAAC,EAAE,MAAA,IAAI,EAAE,QAAA,MAAM,EAAE,OAAA,KAAK,EAAE,QAAA,MAAM,EAAE,OAAA,KAAK,EAAE,OAAA,KAAK,EAAE,MAAA,IAAI,EAAE,CAAC;SAC/D,IAAI,CAAC,UAAU,EAAkB;YAAhB,oBAAO,EAAE,gBAAK;QAC9B,EAAE,CAAC,CAAC,KAAK,KAAK,CAAC,CAAC,CAAC,CAAC;YAChB,OAAO,CAAC,GAAG,CAAC,6BAA6B,CAAC,CAAA;YAC1C,MAAM,CAAA;QACR,CAAC;QAED,OAAO,CAAC,GAAG,CAAC,aAAW,OAAO,CAAC,MAAM,YAAO,KAAO,CAAC,CAAA;QACpD,OAAO,CAAC,GAAG,CAAC,EAAE,CAAC,CAAA;QACf,OAAO,CAAC,GAAG,CAAC,SAAS,CAAC,OAAO,CAAC,CAAC,CAAA;IACjC,CAAC,CAAC,CAAA;AACN,CAAC;AAfe,YAAI,OAenB,CAAA"}

12
node_modules/typings/dist/bin-uninstall.d.ts generated vendored Normal file
View File

@ -0,0 +1,12 @@
import Promise = require('any-promise');
export declare function help(): string;
export interface Options {
cwd: string;
save: boolean;
saveDev: boolean;
savePeer: boolean;
ambient: boolean;
verbose: boolean;
help: boolean;
}
export declare function exec(args: string[], options: Options): Promise<void[]>;

20
node_modules/typings/dist/bin-uninstall.js generated vendored Normal file
View File

@ -0,0 +1,20 @@
#!/usr/bin/env node
"use strict";
var Promise = require('any-promise');
var typings_core_1 = require('typings-core');
var cli_1 = require('./support/cli');
function help() {
return "\ntypings uninstall <name> [--save|--save-dev|--save-peer] [--ambient]\n\nOptions:\n [--save|-S] Remove from \"dependencies\"\n [--save-dev|-D] Remove from \"devDependencies\"\n [--save-peer|-P] Remove from \"peerDependencies\"\n [--ambient|-A] Remove from the ambient version of dependencies\n [-SA] Remove from \"ambientDependencies\"\n [-DA] Remove from \"ambientDevDependencies\"\n\nAliases: r, rm, remove, un\n";
}
exports.help = help;
function exec(args, options) {
if (args.length === 0) {
cli_1.logError(help());
return;
}
return Promise.all(args.map(function (name) {
return typings_core_1.uninstallDependency(name, options);
}));
}
exports.exec = exec;
//# sourceMappingURL=bin-uninstall.js.map

1
node_modules/typings/dist/bin-uninstall.js.map generated vendored Normal file
View File

@ -0,0 +1 @@
{"version":3,"file":"bin-uninstall.js","sourceRoot":"","sources":["../src/bin-uninstall.ts"],"names":[],"mappings":";;AAEA,IAAO,OAAO,WAAW,aAAa,CAAC,CAAA;AACvC,6BAAoC,cACpC,CAAC,CADiD;AAClD,oBAAyB,eAEzB,CAAC,CAFuC;AAExC;IACE,MAAM,CAAC,2cAYR,CAAA;AACD,CAAC;AAde,YAAI,OAcnB,CAAA;AAYD,cAAsB,IAAc,EAAE,OAAgB;IACpD,EAAE,CAAC,CAAC,IAAI,CAAC,MAAM,KAAK,CAAC,CAAC,CAAC,CAAC;QACtB,cAAQ,CAAC,IAAI,EAAE,CAAC,CAAA;QAChB,MAAM,CAAA;IACR,CAAC;IAED,MAAM,CAAC,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,GAAG,CAAC,UAAA,IAAI;QAC9B,MAAM,CAAC,kCAAmB,CAAC,IAAI,EAAE,OAAO,CAAC,CAAA;IAC3C,CAAC,CAAC,CAAC,CAAA;AACL,CAAC;AATe,YAAI,OASnB,CAAA"}

7
node_modules/typings/dist/bin-view.d.ts generated vendored Normal file
View File

@ -0,0 +1,7 @@
import Promise = require('any-promise');
export declare function help(): string;
export interface Options {
ambient: boolean;
versions: boolean;
}
export declare function exec(args: string[], options: Options): Promise<void>;

22
node_modules/typings/dist/bin-view.js generated vendored Normal file
View File

@ -0,0 +1,22 @@
"use strict";
var columnify = require('columnify');
var typings_core_1 = require('typings-core');
var cli_1 = require('./support/cli');
function help() {
return "\ntypings view <pkg>\n\n <pkg> A registry expression like `[<source>!]<pkg>`\n\nOptions:\n [--versions] List all package versions\n [--ambient|-A] View `<pkg>` from the default ambient source\n\nAliases: info\n";
}
exports.help = help;
function exec(args, options) {
if (args.length === 0) {
cli_1.logError(help());
return;
}
if (options.versions) {
return typings_core_1.viewVersions(args[0], options)
.then(function (versions) { return console.log(columnify(versions)); });
}
return typings_core_1.viewEntry(args[0], options)
.then(function (entry) { return console.log(columnify(entry)); });
}
exports.exec = exec;
//# sourceMappingURL=bin-view.js.map

1
node_modules/typings/dist/bin-view.js.map generated vendored Normal file
View File

@ -0,0 +1 @@
{"version":3,"file":"bin-view.js","sourceRoot":"","sources":["../src/bin-view.ts"],"names":[],"mappings":";AACA,IAAO,SAAS,WAAW,WAAW,CAAC,CAAA;AACvC,6BAAwC,cACxC,CAAC,CADqD;AACtD,oBAAyB,eAEzB,CAAC,CAFuC;AAExC;IACE,MAAM,CAAC,4NAUR,CAAA;AACD,CAAC;AAZe,YAAI,OAYnB,CAAA;AAOD,cAAsB,IAAc,EAAE,OAAgB;IACpD,EAAE,CAAC,CAAC,IAAI,CAAC,MAAM,KAAK,CAAC,CAAC,CAAC,CAAC;QACtB,cAAQ,CAAC,IAAI,EAAE,CAAC,CAAA;QAChB,MAAM,CAAA;IACR,CAAC;IAED,EAAE,CAAC,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAC,CAAC;QACrB,MAAM,CAAC,2BAAY,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,OAAO,CAAC;aAClC,IAAI,CAAC,UAAA,QAAQ,IAAI,OAAA,OAAO,CAAC,GAAG,CAAC,SAAS,CAAC,QAAQ,CAAC,CAAC,EAAhC,CAAgC,CAAC,CAAA;IACvD,CAAC;IAED,MAAM,CAAC,wBAAS,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,OAAO,CAAC;SAC/B,IAAI,CAAC,UAAA,KAAK,IAAI,OAAA,OAAO,CAAC,GAAG,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC,EAA7B,CAA6B,CAAC,CAAA;AACjD,CAAC;AAbe,YAAI,OAanB,CAAA"}

0
node_modules/typings/dist/bin.d.ts generated vendored Normal file
View File

80
node_modules/typings/dist/bin.js generated vendored Normal file
View File

@ -0,0 +1,80 @@
#!/usr/bin/env node
"use strict";
var minimist = require('minimist');
var wordwrap = require('wordwrap');
var path_1 = require('path');
var updateNotifier = require('update-notifier');
var extend = require('xtend');
var events_1 = require('events');
var cli_1 = require('./support/cli');
var aliases_1 = require('./aliases');
var pkg = require('../package.json');
var IS_PRODUCTION = process.env.NODE_ENV === 'production';
var argv = minimist(process.argv.slice(2), {
boolean: ['version', 'save', 'saveDev', 'savePeer', 'ambient', 'verbose', 'dev', 'production'],
string: ['cwd', 'out', 'name'],
alias: {
ambient: ['A'],
version: ['v'],
save: ['S'],
saveDev: ['save-dev', 'D'],
savePeer: ['savePeer', 'P'],
verbose: ['V'],
out: ['o'],
help: ['h']
}
});
var cwd = process.cwd();
var emitter = new events_1.EventEmitter();
var isDev = IS_PRODUCTION ? argv.dev : !argv.production;
var args = extend({ cwd: cwd, emitter: emitter }, argv, { dev: isDev, production: !isDev });
updateNotifier({ pkg: pkg }).notify();
exec(args);
emitter.on('enoent', function (_a) {
var path = _a.path;
cli_1.logWarning("Path \"" + path + "\" is missing", 'enoent');
});
emitter.on('hastypings', function (_a) {
var name = _a.name, typings = _a.typings;
cli_1.logWarning(("Typings for \"" + name + "\" already exist in \"" + path_1.relative(cwd, typings) + "\". You should ") +
"let TypeScript resolve the packaged typings and uninstall the copy installed by Typings", 'hastypings');
});
emitter.on('postmessage', function (_a) {
var message = _a.message, name = _a.name;
cli_1.logInfo(name + ": " + message, 'postmessage');
});
emitter.on('badlocation', function (_a) {
var raw = _a.raw;
cli_1.logWarning("\"" + raw + "\" is a mutable location and may change, consider specifying a commit hash", 'badlocation');
});
emitter.on('deprecated', function (_a) {
var date = _a.date, raw = _a.raw, parent = _a.parent;
if (parent == null) {
cli_1.logWarning(date.toLocaleString() + ": \"" + raw + "\" is deprecated (outdated or removed)", 'deprecated');
}
else if (parent.raw) {
cli_1.logWarning(date.toLocaleString() + ": \"" + raw + "\" has been deprecated (used by \"" + parent.raw + "\")", 'deprecated');
}
else {
cli_1.logWarning(date.toLocaleString() + ": \"" + raw + "\" has been deprecated", 'deprecated');
}
});
function exec(options) {
if (options._.length) {
var command = aliases_1.aliases[options._[0]];
var args_1 = options._.slice(1);
if (command != null) {
if (options.help) {
return console.log(command.help());
}
return cli_1.handle(command.exec(args_1, options), options);
}
}
else if (options.version) {
console.log(pkg.version);
return;
}
var wrap = wordwrap(4, 80);
console.log("\nUsage: typings <command>\n\nCommands:\n" + wrap(Object.keys(aliases_1.aliases).sort().join(', ')) + "\n\ntypings <command> -h Get help for <command>\ntypings <command> -V Enable verbose logging\n\ntypings --version Print the CLI version\n\ntypings@" + pkg.version + " " + path_1.join(__dirname, '..') + "\n");
}
//# sourceMappingURL=bin.js.map

1
node_modules/typings/dist/bin.js.map generated vendored Normal file
View File

@ -0,0 +1 @@
{"version":3,"file":"bin.js","sourceRoot":"","sources":["../src/bin.ts"],"names":[],"mappings":";;AAEA,IAAO,QAAQ,WAAW,UAAU,CAAC,CAAA;AACrC,IAAO,QAAQ,WAAW,UAAU,CAAC,CAAA;AACrC,qBAA+B,MAC/B,CAAC,CADoC;AACrC,IAAO,cAAc,WAAW,iBAAiB,CAAC,CAAA;AAClD,IAAO,MAAM,WAAW,OAAO,CAAC,CAAA;AAChC,uBAA6B,QAC7B,CAAC,CADoC;AACrC,oBAA4C,eAC5C,CAAC,CAD0D;AAE3D,wBAAwB,WAExB,CAAC,CAFkC;AAEnC,IAAM,GAAG,GAAG,OAAO,CAAC,iBAAiB,CAAC,CAAA;AACtC,IAAM,aAAa,GAAG,OAAO,CAAC,GAAG,CAAC,QAAQ,KAAK,YAAY,CAAA;AAoB3D,IAAM,IAAI,GAAG,QAAQ,CAAO,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE;IACjD,OAAO,EAAE,CAAC,SAAS,EAAE,MAAM,EAAE,SAAS,EAAE,UAAU,EAAE,SAAS,EAAE,SAAS,EAAE,KAAK,EAAE,YAAY,CAAC;IAC9F,MAAM,EAAE,CAAC,KAAK,EAAE,KAAK,EAAE,MAAM,CAAC;IAC9B,KAAK,EAAE;QACL,OAAO,EAAE,CAAC,GAAG,CAAC;QACd,OAAO,EAAE,CAAC,GAAG,CAAC;QACd,IAAI,EAAE,CAAC,GAAG,CAAC;QACX,OAAO,EAAE,CAAC,UAAU,EAAE,GAAG,CAAC;QAC1B,QAAQ,EAAE,CAAC,UAAU,EAAE,GAAG,CAAC;QAC3B,OAAO,EAAE,CAAC,GAAG,CAAC;QACd,GAAG,EAAE,CAAC,GAAG,CAAC;QACV,IAAI,EAAE,CAAC,GAAG,CAAC;KACZ;CACF,CAAC,CAAA;AAEF,IAAM,GAAG,GAAG,OAAO,CAAC,GAAG,EAAE,CAAA;AACzB,IAAM,OAAO,GAAY,IAAI,qBAAY,EAAE,CAAA;AAC3C,IAAM,KAAK,GAAG,aAAa,GAAG,IAAI,CAAC,GAAG,GAAG,CAAC,IAAI,CAAC,UAAU,CAAA;AACzD,IAAM,IAAI,GAAS,MAAM,CAAC,EAAE,KAAA,GAAG,EAAE,SAAA,OAAO,EAAE,EAAE,IAAI,EAAE,EAAE,GAAG,EAAE,KAAK,EAAE,UAAU,EAAE,CAAC,KAAK,EAAE,CAAC,CAAA;AAGrF,cAAc,CAAC,EAAE,KAAA,GAAG,EAAE,CAAC,CAAC,MAAM,EAAE,CAAA;AAGhC,IAAI,CAAC,IAAI,CAAC,CAAA;AAGV,OAAO,CAAC,EAAE,CAAC,QAAQ,EAAE,UAAU,EAAQ;QAAN,cAAI;IACnC,gBAAU,CAAC,YAAS,IAAI,kBAAc,EAAE,QAAQ,CAAC,CAAA;AACnD,CAAC,CAAC,CAAA;AAGF,OAAO,CAAC,EAAE,CAAC,YAAY,EAAE,UAAU,EAAiB;QAAf,cAAI,EAAE,oBAAO;IAChD,gBAAU,CACR,oBAAgB,IAAI,8BAAuB,eAAQ,CAAC,GAAG,EAAE,OAAO,CAAC,qBAAgB;QACjF,yFAAyF,EACzF,YAAY,CACb,CAAA;AACH,CAAC,CAAC,CAAA;AAGF,OAAO,CAAC,EAAE,CAAC,aAAa,EAAE,UAAU,EAAiB;QAAf,oBAAO,EAAE,cAAI;IACjD,aAAO,CAAI,IAAI,UAAK,OAAS,EAAE,aAAa,CAAC,CAAA;AAC/C,CAAC,CAAC,CAAA;AAGF,OAAO,CAAC,EAAE,CAAC,aAAa,EAAE,UAAU,EAAO;QAAL,YAAG;IACvC,gBAAU,CAAC,OAAI,GAAG,+EAA2E,EAAE,aAAa,CAAC,CAAA;AAC/G,CAAC,CAAC,CAAA;AAGF,OAAO,CAAC,EAAE,CAAC,YAAY,EAAE,UAAU,EAAqB;QAAnB,cAAI,EAAE,YAAG,EAAE,kBAAM;IACpD,EAAE,CAAC,CAAC,MAAM,IAAI,IAAI,CAAC,CAAC,CAAC;QACnB,gBAAU,CAAI,IAAI,CAAC,cAAc,EAAE,YAAM,GAAG,2CAAuC,EAAE,YAAY,CAAC,CAAA;IACpG,CAAC;IAAC,IAAI,CAAC,EAAE,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC;QACtB,gBAAU,CAAI,IAAI,CAAC,cAAc,EAAE,YAAM,GAAG,0CAAmC,MAAM,CAAC,GAAG,QAAI,EAAE,YAAY,CAAC,CAAA;IAC9G,CAAC;IAAC,IAAI,CAAC,CAAC;QACN,gBAAU,CAAI,IAAI,CAAC,cAAc,EAAE,YAAM,GAAG,2BAAuB,EAAE,YAAY,CAAC,CAAA;IACpF,CAAC;AACH,CAAC,CAAC,CAAA;AAKF,cAAe,OAAa;IAC1B,EAAE,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC;QACrB,IAAM,OAAO,GAAG,iBAAO,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAA;QACrC,IAAM,MAAI,GAAG,OAAO,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAA;QAE/B,EAAE,CAAC,CAAC,OAAO,IAAI,IAAI,CAAC,CAAC,CAAC;YACpB,EAAE,CAAC,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC;gBACjB,MAAM,CAAC,OAAO,CAAC,GAAG,CAAC,OAAO,CAAC,IAAI,EAAE,CAAC,CAAA;YACpC,CAAC;YAED,MAAM,CAAC,YAAM,CAAC,OAAO,CAAC,IAAI,CAAC,MAAI,EAAE,OAAO,CAAC,EAAE,OAAO,CAAC,CAAA;QACrD,CAAC;IACH,CAAC;IAAC,IAAI,CAAC,EAAE,CAAC,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC,CAAC;QAC3B,OAAO,CAAC,GAAG,CAAC,GAAG,CAAC,OAAO,CAAC,CAAA;QACxB,MAAM,CAAA;IACR,CAAC;IAED,IAAM,IAAI,GAAG,QAAQ,CAAC,CAAC,EAAE,EAAE,CAAC,CAAA;IAE5B,OAAO,CAAC,GAAG,CAAC,8CAIZ,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,iBAAO,CAAC,CAAC,IAAI,EAAE,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,oKAOpC,GAAG,CAAC,OAAO,SAAI,WAAI,CAAC,SAAS,EAAE,IAAI,CAAC,OAC7C,CAAC,CAAA;AACF,CAAC"}

16
node_modules/typings/dist/support/cli.d.ts generated vendored Normal file
View File

@ -0,0 +1,16 @@
import Promise = require('any-promise');
import { DependencyTree } from 'typings-core';
export interface PrintOptions {
verbose: boolean;
}
export declare function log(message: string): void;
export declare function logInfo(message: string, prefix?: string): void;
export declare function logWarning(message: string, prefix?: string): void;
export declare function logError(message: string, prefix?: string): void;
export declare function handle(promise: any, options: PrintOptions): Promise<any>;
export declare function handleError(error: Error, options: PrintOptions): any;
export interface ArchifyOptions {
name?: string;
tree: DependencyTree;
}
export declare function archifyDependencyTree(options: ArchifyOptions): string;

99
node_modules/typings/dist/support/cli.js generated vendored Normal file
View File

@ -0,0 +1,99 @@
"use strict";
var chalk = require('chalk');
var Promise = require('any-promise');
var archy = require('archy');
var os = require('os');
var pkg = require('../../package.json');
function log(message) {
console.error(message);
}
exports.log = log;
function formatLine(color, type, line, prefix) {
return chalk.bgBlack.white('typings') + " " + color(type) + " " + (prefix ? chalk.magenta(prefix + " ") : '') + line;
}
function logInfo(message, prefix) {
var output = message.split(/\r?\n/g).map(function (line) {
return formatLine(chalk.bgBlack.cyan, 'INFO', line, prefix);
}).join('\n');
log(output);
}
exports.logInfo = logInfo;
function logWarning(message, prefix) {
var output = message.split(/\r?\n/g).map(function (line) {
return formatLine(chalk.bgYellow.black, 'WARN', line, prefix);
}).join('\n');
log(output);
}
exports.logWarning = logWarning;
function logError(message, prefix) {
var output = message.split(/\r?\n/g).map(function (line) {
return formatLine(chalk.bgBlack.red, 'ERR!', line, prefix);
}).join('\n');
log(output);
}
exports.logError = logError;
function handle(promise, options) {
return Promise.resolve(promise).catch(function (err) { return handleError(err, options); });
}
exports.handle = handle;
function handleError(error, options) {
var cause = error;
logError(error.message, 'message');
while (cause = cause.cause) {
logError(cause.message, 'caused by');
}
if (options.verbose && error.stack) {
log('');
logError(error.stack, 'stack');
}
log('');
logError(process.cwd(), 'cwd');
logError(os.type() + " " + os.release(), 'system');
logError(process.argv.map(JSON.stringify).join(' '), 'command');
logError(process.version, 'node -v');
logError(pkg.version, "typings -v");
if (error.code) {
logError(error.code, 'code');
}
log('');
logError('If you need help, you may report this error at:');
logError(" <https://github.com/typings/typings/issues>");
process.exit(1);
}
exports.handleError = handleError;
function toDependencyName(name, node, suffix) {
var fullname = node.version ? name + "@" + node.version : name;
return suffix ? fullname + " " + suffix : fullname;
}
function archifyDependencyTree(options) {
var result = {
label: options.name ? toDependencyName(options.name, options.tree) : '',
nodes: []
};
function children(nodes, dependencies, suffix) {
for (var _i = 0, _a = Object.keys(dependencies).sort(); _i < _a.length; _i++) {
var name_1 = _a[_i];
var tree = dependencies[name_1];
nodes.push(traverse({
label: toDependencyName(name_1, tree, suffix),
nodes: []
}, tree));
}
}
function traverse(result, tree) {
var nodes = result.nodes;
children(nodes, tree.dependencies);
children(nodes, tree.devDependencies, chalk.gray('(dev)'));
children(nodes, tree.peerDependencies, chalk.gray('(peer)'));
children(nodes, tree.ambientDependencies, chalk.gray('(ambient)'));
children(nodes, tree.ambientDevDependencies, chalk.gray('(ambient dev)'));
return result;
}
var archyTree = traverse(result, options.tree);
if (archyTree.nodes.length === 0) {
archyTree.nodes.push(chalk.gray('(No dependencies)'));
}
return archy(archyTree);
}
exports.archifyDependencyTree = archifyDependencyTree;
//# sourceMappingURL=cli.js.map

1
node_modules/typings/dist/support/cli.js.map generated vendored Normal file
View File

@ -0,0 +1 @@
{"version":3,"file":"cli.js","sourceRoot":"","sources":["../../src/support/cli.ts"],"names":[],"mappings":";AAAA,IAAO,KAAK,WAAW,OAAO,CAAC,CAAA;AAC/B,IAAO,OAAO,WAAW,aAAa,CAAC,CAAA;AACvC,IAAO,KAAK,WAAW,OAAO,CAAC,CAAA;AAC/B,IAAY,EAAE,WAAM,IACpB,CAAC,CADuB;AAGxB,IAAM,GAAG,GAAG,OAAO,CAAC,oBAAoB,CAAC,CAAA;AAYzC,aAAqB,OAAe;IAClC,OAAO,CAAC,KAAK,CAAC,OAAO,CAAC,CAAA;AACxB,CAAC;AAFe,WAAG,MAElB,CAAA;AAKD,oBAAqB,KAAe,EAAE,IAAY,EAAE,IAAY,EAAE,MAAe;IAC/E,MAAM,CAAI,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,SAAS,CAAC,SAAI,KAAK,CAAC,IAAI,CAAC,UAAI,MAAM,GAAG,KAAK,CAAC,OAAO,CAAI,MAAM,MAAG,CAAC,GAAG,EAAE,IAAG,IAAM,CAAA;AAC/G,CAAC;AAKD,iBAAyB,OAAe,EAAE,MAAe;IACvD,IAAM,MAAM,GAAG,OAAO,CAAC,KAAK,CAAC,QAAQ,CAAC,CAAC,GAAG,CAAC,UAAA,IAAI;QAC7C,MAAM,CAAC,UAAU,CAAC,KAAK,CAAC,OAAO,CAAC,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,CAAC,CAAA;IAC7D,CAAC,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAA;IAEb,GAAG,CAAC,MAAM,CAAC,CAAA;AACb,CAAC;AANe,eAAO,UAMtB,CAAA;AAKD,oBAA4B,OAAe,EAAE,MAAe;IAC1D,IAAM,MAAM,GAAG,OAAO,CAAC,KAAK,CAAC,QAAQ,CAAC,CAAC,GAAG,CAAC,UAAA,IAAI;QAC7C,MAAM,CAAC,UAAU,CAAC,KAAK,CAAC,QAAQ,CAAC,KAAK,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,CAAC,CAAA;IAC/D,CAAC,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAA;IAEb,GAAG,CAAC,MAAM,CAAC,CAAA;AACb,CAAC;AANe,kBAAU,aAMzB,CAAA;AAKD,kBAA0B,OAAe,EAAE,MAAe;IACxD,IAAM,MAAM,GAAG,OAAO,CAAC,KAAK,CAAC,QAAQ,CAAC,CAAC,GAAG,CAAC,UAAA,IAAI;QAC7C,MAAM,CAAC,UAAU,CAAC,KAAK,CAAC,OAAO,CAAC,GAAG,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,CAAC,CAAA;IAC5D,CAAC,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAA;IAEb,GAAG,CAAC,MAAM,CAAC,CAAA;AACb,CAAC;AANe,gBAAQ,WAMvB,CAAA;AAKD,gBAAwB,OAAY,EAAE,OAAqB;IACzD,MAAM,CAAC,OAAO,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC,KAAK,CAAC,UAAA,GAAG,IAAI,OAAA,WAAW,CAAC,GAAG,EAAE,OAAO,CAAC,EAAzB,CAAyB,CAAC,CAAA;AACzE,CAAC;AAFe,cAAM,SAErB,CAAA;AAKD,qBAA6B,KAAY,EAAE,OAAqB;IAC9D,IAAI,KAAK,GAAG,KAAK,CAAA;IAEjB,QAAQ,CAAC,KAAK,CAAC,OAAO,EAAE,SAAS,CAAC,CAAA;IAElC,OAAO,KAAK,GAAI,KAAa,CAAC,KAAK,EAAE,CAAC;QACpC,QAAQ,CAAC,KAAK,CAAC,OAAO,EAAE,WAAW,CAAC,CAAA;IACtC,CAAC;IAED,EAAE,CAAC,CAAC,OAAO,CAAC,OAAO,IAAI,KAAK,CAAC,KAAK,CAAC,CAAC,CAAC;QACnC,GAAG,CAAC,EAAE,CAAC,CAAA;QACP,QAAQ,CAAC,KAAK,CAAC,KAAK,EAAE,OAAO,CAAC,CAAA;IAChC,CAAC;IAED,GAAG,CAAC,EAAE,CAAC,CAAA;IACP,QAAQ,CAAC,OAAO,CAAC,GAAG,EAAE,EAAE,KAAK,CAAC,CAAA;IAC9B,QAAQ,CAAI,EAAE,CAAC,IAAI,EAAE,SAAI,EAAE,CAAC,OAAO,EAAI,EAAE,QAAQ,CAAC,CAAA;IAClD,QAAQ,CAAC,OAAO,CAAC,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE,SAAS,CAAC,CAAA;IAC/D,QAAQ,CAAC,OAAO,CAAC,OAAO,EAAE,SAAS,CAAC,CAAA;IACpC,QAAQ,CAAC,GAAG,CAAC,OAAO,EAAE,YAAY,CAAC,CAAA;IAEnC,EAAE,CAAC,CAAE,KAAa,CAAC,IAAI,CAAC,CAAC,CAAC;QACxB,QAAQ,CAAE,KAAa,CAAC,IAAI,EAAE,MAAM,CAAC,CAAA;IACvC,CAAC;IAED,GAAG,CAAC,EAAE,CAAC,CAAA;IACP,QAAQ,CAAC,iDAAiD,CAAC,CAAA;IAC3D,QAAQ,CAAC,+CAA+C,CAAC,CAAA;IAEzD,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAA;AACjB,CAAC;AA9Be,mBAAW,cA8B1B,CAAA;AAaD,0BAA2B,IAAY,EAAE,IAAoB,EAAE,MAAe;IAC5E,IAAM,QAAQ,GAAG,IAAI,CAAC,OAAO,GAAM,IAAI,SAAI,IAAI,CAAC,OAAS,GAAG,IAAI,CAAA;IAEhE,MAAM,CAAC,MAAM,GAAM,QAAQ,SAAI,MAAQ,GAAG,QAAQ,CAAA;AACpD,CAAC;AAKD,+BAAuC,OAAuB;IAC5D,IAAM,MAAM,GAAe;QACzB,KAAK,EAAE,OAAO,CAAC,IAAI,GAAG,gBAAgB,CAAC,OAAO,CAAC,IAAI,EAAE,OAAO,CAAC,IAAI,CAAC,GAAG,EAAE;QACvE,KAAK,EAAE,EAAE;KACV,CAAA;IAGD,kBAAmB,KAA8B,EAAE,YAA8B,EAAE,MAAe;QAChG,GAAG,CAAC,CAAe,UAAgC,EAAhC,KAAA,MAAM,CAAC,IAAI,CAAC,YAAY,CAAC,CAAC,IAAI,EAAE,EAAhC,cAAgC,EAAhC,IAAgC,CAAC;YAA/C,IAAM,MAAI,SAAA;YACb,IAAM,IAAI,GAAG,YAAY,CAAC,MAAI,CAAC,CAAA;YAE/B,KAAK,CAAC,IAAI,CAAC,QAAQ,CACjB;gBACE,KAAK,EAAE,gBAAgB,CAAC,MAAI,EAAE,IAAI,EAAE,MAAM,CAAC;gBAC3C,KAAK,EAAE,EAAE;aACV,EACD,IAAI,CACL,CAAC,CAAA;SACH;IACH,CAAC;IAGD,kBAAmB,MAAkB,EAAE,IAAoB;QACjD,wBAAK,CAAW;QAExB,QAAQ,CAAC,KAAK,EAAE,IAAI,CAAC,YAAY,CAAC,CAAA;QAClC,QAAQ,CAAC,KAAK,EAAE,IAAI,CAAC,eAAe,EAAE,KAAK,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC,CAAA;QAC1D,QAAQ,CAAC,KAAK,EAAE,IAAI,CAAC,gBAAgB,EAAE,KAAK,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC,CAAA;QAC5D,QAAQ,CAAC,KAAK,EAAE,IAAI,CAAC,mBAAmB,EAAE,KAAK,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC,CAAA;QAClE,QAAQ,CAAC,KAAK,EAAE,IAAI,CAAC,sBAAsB,EAAE,KAAK,CAAC,IAAI,CAAC,eAAe,CAAC,CAAC,CAAA;QAEzE,MAAM,CAAC,MAAM,CAAA;IACf,CAAC;IAED,IAAM,SAAS,GAAG,QAAQ,CAAC,MAAM,EAAE,OAAO,CAAC,IAAI,CAAC,CAAA;IAGhD,EAAE,CAAC,CAAC,SAAS,CAAC,KAAK,CAAC,MAAM,KAAK,CAAC,CAAC,CAAC,CAAC;QACjC,SAAS,CAAC,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,mBAAmB,CAAC,CAAC,CAAA;IACvD,CAAC;IAED,MAAM,CAAC,KAAK,CAAC,SAAS,CAAC,CAAA;AACzB,CAAC;AA1Ce,6BAAqB,wBA0CpC,CAAA"}

1
node_modules/typings/dist/typings.d.ts generated vendored Normal file
View File

@ -0,0 +1 @@
export * from 'typings-core';

6
node_modules/typings/dist/typings.js generated vendored Normal file
View File

@ -0,0 +1,6 @@
"use strict";
function __export(m) {
for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
}
__export(require('typings-core'));
//# sourceMappingURL=typings.js.map

1
node_modules/typings/dist/typings.js.map generated vendored Normal file
View File

@ -0,0 +1 @@
{"version":3,"file":"typings.js","sourceRoot":"","sources":["../src/typings.ts"],"names":[],"mappings":";;;;AAAA,iBAAc,cACd,CAAC,EAD2B"}

View File

@ -0,0 +1,4 @@
'use strict';
module.exports = function () {
return /[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-PRZcf-nqry=><]/g;
};

21
node_modules/typings/node_modules/ansi-regex/license generated vendored Normal file
View File

@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

View File

@ -0,0 +1,123 @@
{
"_args": [
[
"ansi-regex@^2.0.0",
"C:\\Users\\x2mjbyrn\\Source\\Repos\\Skeleton\\node_modules\\typings\\node_modules\\has-ansi"
]
],
"_from": "ansi-regex@>=2.0.0-0 <3.0.0-0",
"_id": "ansi-regex@2.1.1",
"_inCache": true,
"_location": "/typings/ansi-regex",
"_nodeVersion": "0.10.32",
"_npmOperationalInternal": {
"host": "packages-18-east.internal.npmjs.com",
"tmp": "tmp/ansi-regex-2.1.1.tgz_1484363378013_0.4482989883981645"
},
"_npmUser": {
"email": "i.am.qix@gmail.com",
"name": "qix"
},
"_npmVersion": "2.14.2",
"_phantomChildren": {},
"_requested": {
"name": "ansi-regex",
"raw": "ansi-regex@^2.0.0",
"rawSpec": "^2.0.0",
"scope": null,
"spec": ">=2.0.0-0 <3.0.0-0",
"type": "range"
},
"_requiredBy": [
"/typings/has-ansi",
"/typings/strip-ansi"
],
"_resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-2.1.1.tgz",
"_shasum": "c3b33ab5ee360d86e0e628f0468ae7ef27d654df",
"_shrinkwrap": null,
"_spec": "ansi-regex@^2.0.0",
"_where": "C:\\Users\\x2mjbyrn\\Source\\Repos\\Skeleton\\node_modules\\typings\\node_modules\\has-ansi",
"author": {
"email": "sindresorhus@gmail.com",
"name": "Sindre Sorhus",
"url": "sindresorhus.com"
},
"bugs": {
"url": "https://github.com/chalk/ansi-regex/issues"
},
"dependencies": {},
"description": "Regular expression for matching ANSI escape codes",
"devDependencies": {
"ava": "0.17.0",
"xo": "0.16.0"
},
"directories": {},
"dist": {
"shasum": "c3b33ab5ee360d86e0e628f0468ae7ef27d654df",
"tarball": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-2.1.1.tgz"
},
"engines": {
"node": ">=0.10.0"
},
"files": [
"index.js"
],
"gitHead": "7c908e7b4eb6cd82bfe1295e33fdf6d166c7ed85",
"homepage": "https://github.com/chalk/ansi-regex#readme",
"installable": true,
"keywords": [
"256",
"ansi",
"cli",
"color",
"colors",
"colour",
"command-line",
"console",
"escape",
"find",
"formatting",
"match",
"pattern",
"re",
"regex",
"regexp",
"rgb",
"shell",
"string",
"styles",
"terminal",
"test",
"text",
"tty",
"xterm"
],
"license": "MIT",
"maintainers": [
{
"name": "qix",
"email": "i.am.qix@gmail.com"
},
{
"name": "sindresorhus",
"email": "sindresorhus@gmail.com"
}
],
"name": "ansi-regex",
"optionalDependencies": {},
"repository": {
"type": "git",
"url": "git+https://github.com/chalk/ansi-regex.git"
},
"scripts": {
"test": "xo && ava --verbose",
"view-supported": "node fixtures/view-codes.js"
},
"version": "2.1.1",
"xo": {
"rules": {
"guard-for-in": 0,
"no-loop-func": 0
}
}
}

39
node_modules/typings/node_modules/ansi-regex/readme.md generated vendored Normal file
View File

@ -0,0 +1,39 @@
# ansi-regex [![Build Status](https://travis-ci.org/chalk/ansi-regex.svg?branch=master)](https://travis-ci.org/chalk/ansi-regex)
> Regular expression for matching [ANSI escape codes](http://en.wikipedia.org/wiki/ANSI_escape_code)
## Install
```
$ npm install --save ansi-regex
```
## Usage
```js
const ansiRegex = require('ansi-regex');
ansiRegex().test('\u001b[4mcake\u001b[0m');
//=> true
ansiRegex().test('cake');
//=> false
'\u001b[4mcake\u001b[0m'.match(ansiRegex());
//=> ['\u001b[4m', '\u001b[0m']
```
## FAQ
### Why do you test for codes not in the ECMA 48 standard?
Some of the codes we run as a test are codes that we acquired finding various lists of non-standard or manufacturer specific codes. If I recall correctly, we test for both standard and non-standard codes, as most of them follow the same or similar format and can be safely matched in strings without the risk of removing actual string content. There are a few non-standard control codes that do not follow the traditional format (i.e. they end in numbers) thus forcing us to exclude them from the test because we cannot reliably match them.
On the historical side, those ECMA standards were established in the early 90's whereas the VT100, for example, was designed in the mid/late 70's. At that point in time, control codes were still pretty ungoverned and engineers used them for a multitude of things, namely to activate hardware ports that may have been proprietary. Somewhere else you see a similar 'anarchy' of codes is in the x86 architecture for processors; there are a ton of "interrupts" that can mean different things on certain brands of processors, most of which have been phased out.
## License
MIT © [Sindre Sorhus](http://sindresorhus.com)

65
node_modules/typings/node_modules/ansi-styles/index.js generated vendored Normal file
View File

@ -0,0 +1,65 @@
'use strict';
function assembleStyles () {
var styles = {
modifiers: {
reset: [0, 0],
bold: [1, 22], // 21 isn't widely supported and 22 does the same thing
dim: [2, 22],
italic: [3, 23],
underline: [4, 24],
inverse: [7, 27],
hidden: [8, 28],
strikethrough: [9, 29]
},
colors: {
black: [30, 39],
red: [31, 39],
green: [32, 39],
yellow: [33, 39],
blue: [34, 39],
magenta: [35, 39],
cyan: [36, 39],
white: [37, 39],
gray: [90, 39]
},
bgColors: {
bgBlack: [40, 49],
bgRed: [41, 49],
bgGreen: [42, 49],
bgYellow: [43, 49],
bgBlue: [44, 49],
bgMagenta: [45, 49],
bgCyan: [46, 49],
bgWhite: [47, 49]
}
};
// fix humans
styles.colors.grey = styles.colors.gray;
Object.keys(styles).forEach(function (groupName) {
var group = styles[groupName];
Object.keys(group).forEach(function (styleName) {
var style = group[styleName];
styles[styleName] = group[styleName] = {
open: '\u001b[' + style[0] + 'm',
close: '\u001b[' + style[1] + 'm'
};
});
Object.defineProperty(styles, groupName, {
value: group,
enumerable: false
});
});
return styles;
}
Object.defineProperty(module, 'exports', {
enumerable: true,
get: assembleStyles
});

21
node_modules/typings/node_modules/ansi-styles/license generated vendored Normal file
View File

@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

View File

@ -0,0 +1,105 @@
{
"_args": [
[
"ansi-styles@^2.2.1",
"C:\\Users\\x2mjbyrn\\Source\\Repos\\Skeleton\\node_modules\\typings\\node_modules\\chalk"
]
],
"_from": "ansi-styles@>=2.2.1-0 <3.0.0-0",
"_id": "ansi-styles@2.2.1",
"_inCache": true,
"_location": "/typings/ansi-styles",
"_nodeVersion": "4.3.0",
"_npmOperationalInternal": {
"host": "packages-12-west.internal.npmjs.com",
"tmp": "tmp/ansi-styles-2.2.1.tgz_1459197317833_0.9694824463222176"
},
"_npmUser": {
"email": "sindresorhus@gmail.com",
"name": "sindresorhus"
},
"_npmVersion": "3.8.3",
"_phantomChildren": {},
"_requested": {
"name": "ansi-styles",
"raw": "ansi-styles@^2.2.1",
"rawSpec": "^2.2.1",
"scope": null,
"spec": ">=2.2.1-0 <3.0.0-0",
"type": "range"
},
"_requiredBy": [
"/typings/chalk"
],
"_resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-2.2.1.tgz",
"_shasum": "b432dd3358b634cf75e1e4664368240533c1ddbe",
"_shrinkwrap": null,
"_spec": "ansi-styles@^2.2.1",
"_where": "C:\\Users\\x2mjbyrn\\Source\\Repos\\Skeleton\\node_modules\\typings\\node_modules\\chalk",
"author": {
"email": "sindresorhus@gmail.com",
"name": "Sindre Sorhus",
"url": "sindresorhus.com"
},
"bugs": {
"url": "https://github.com/chalk/ansi-styles/issues"
},
"dependencies": {},
"description": "ANSI escape codes for styling strings in the terminal",
"devDependencies": {
"mocha": "*"
},
"directories": {},
"dist": {
"shasum": "b432dd3358b634cf75e1e4664368240533c1ddbe",
"tarball": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-2.2.1.tgz"
},
"engines": {
"node": ">=0.10.0"
},
"files": [
"index.js"
],
"gitHead": "95c59b23be760108b6530ca1c89477c21b258032",
"homepage": "https://github.com/chalk/ansi-styles#readme",
"installable": true,
"keywords": [
"256",
"ansi",
"cli",
"color",
"colors",
"colour",
"command-line",
"console",
"escape",
"formatting",
"log",
"logging",
"rgb",
"shell",
"string",
"styles",
"terminal",
"text",
"tty",
"xterm"
],
"license": "MIT",
"maintainers": [
{
"name": "sindresorhus",
"email": "sindresorhus@gmail.com"
}
],
"name": "ansi-styles",
"optionalDependencies": {},
"repository": {
"type": "git",
"url": "git+https://github.com/chalk/ansi-styles.git"
},
"scripts": {
"test": "mocha"
},
"version": "2.2.1"
}

View File

@ -0,0 +1,86 @@
# ansi-styles [![Build Status](https://travis-ci.org/chalk/ansi-styles.svg?branch=master)](https://travis-ci.org/chalk/ansi-styles)
> [ANSI escape codes](http://en.wikipedia.org/wiki/ANSI_escape_code#Colors_and_Styles) for styling strings in the terminal
You probably want the higher-level [chalk](https://github.com/chalk/chalk) module for styling your strings.
![](screenshot.png)
## Install
```
$ npm install --save ansi-styles
```
## Usage
```js
var ansi = require('ansi-styles');
console.log(ansi.green.open + 'Hello world!' + ansi.green.close);
```
## API
Each style has an `open` and `close` property.
## Styles
### Modifiers
- `reset`
- `bold`
- `dim`
- `italic` *(not widely supported)*
- `underline`
- `inverse`
- `hidden`
- `strikethrough` *(not widely supported)*
### Colors
- `black`
- `red`
- `green`
- `yellow`
- `blue`
- `magenta`
- `cyan`
- `white`
- `gray`
### Background colors
- `bgBlack`
- `bgRed`
- `bgGreen`
- `bgYellow`
- `bgBlue`
- `bgMagenta`
- `bgCyan`
- `bgWhite`
## Advanced usage
By default you get a map of styles, but the styles are also available as groups. They are non-enumerable so they don't show up unless you access them explicitly. This makes it easier to expose only a subset in a higher-level module.
- `ansi.modifiers`
- `ansi.colors`
- `ansi.bgColors`
###### Example
```js
console.log(ansi.colors.green.open);
```
## License
MIT © [Sindre Sorhus](http://sindresorhus.com)

21
node_modules/typings/node_modules/bluebird/LICENSE generated vendored Normal file
View File

@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2013-2017 Petka Antonov
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.

51
node_modules/typings/node_modules/bluebird/README.md generated vendored Normal file
View File

@ -0,0 +1,51 @@
<a href="http://promisesaplus.com/">
<img src="http://promisesaplus.com/assets/logo-small.png" alt="Promises/A+ logo"
title="Promises/A+ 1.1 compliant" align="right" />
</a>
[![Build Status](https://travis-ci.org/petkaantonov/bluebird.svg?branch=master)](https://travis-ci.org/petkaantonov/bluebird)
[![coverage-98%](http://img.shields.io/badge/coverage-98%-brightgreen.svg?style=flat)](http://petkaantonov.github.io/bluebird/coverage/debug/index.html)
**Got a question?** Join us on [stackoverflow](http://stackoverflow.com/questions/tagged/bluebird), the [mailing list](https://groups.google.com/forum/#!forum/bluebird-js) or chat on [IRC](https://webchat.freenode.net/?channels=#promises)
# Introduction
Bluebird is a fully featured promise library with focus on innovative features and performance
See the [**bluebird website**](http://bluebirdjs.com/docs/getting-started.html) for further documentation, references and instructions. See the [**API reference**](http://bluebirdjs.com/docs/api-reference.html) here.
For bluebird 2.x documentation and files, see the [2.x tree](https://github.com/petkaantonov/bluebird/tree/2.x).
# Questions and issues
The [github issue tracker](https://github.com/petkaantonov/bluebird/issues) is **_only_** for bug reports and feature requests. Anything else, such as questions for help in using the library, should be posted in [StackOverflow](http://stackoverflow.com/questions/tagged/bluebird) under tags `promise` and `bluebird`.
## Thanks
Thanks to BrowserStack for providing us with a free account which lets us support old browsers like IE8.
# License
The MIT License (MIT)
Copyright (c) 2013-2017 Petka Antonov
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.

View File

@ -0,0 +1 @@
[http://bluebirdjs.com/docs/changelog.html](http://bluebirdjs.com/docs/changelog.html)

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,21 @@
"use strict";
module.exports = function(Promise) {
var SomePromiseArray = Promise._SomePromiseArray;
function any(promises) {
var ret = new SomePromiseArray(promises);
var promise = ret.promise();
ret.setHowMany(1);
ret.setUnwrap();
ret.init();
return promise;
}
Promise.any = function (promises) {
return any(promises);
};
Promise.prototype.any = function () {
return any(this);
};
};

View File

@ -0,0 +1,55 @@
"use strict";
module.exports = (function(){
var AssertionError = (function() {
function AssertionError(a) {
this.constructor$(a);
this.message = a;
this.name = "AssertionError";
}
AssertionError.prototype = new Error();
AssertionError.prototype.constructor = AssertionError;
AssertionError.prototype.constructor$ = Error;
return AssertionError;
})();
function getParams(args) {
var params = [];
for (var i = 0; i < args.length; ++i) params.push("arg" + i);
return params;
}
function nativeAssert(callName, args, expect) {
try {
var params = getParams(args);
var constructorArgs = params;
constructorArgs.push("return " +
callName + "("+ params.join(",") + ");");
var fn = Function.apply(null, constructorArgs);
return fn.apply(null, args);
} catch (e) {
if (!(e instanceof SyntaxError)) {
throw e;
} else {
return expect;
}
}
}
return function assert(boolExpr, message) {
if (boolExpr === true) return;
if (typeof boolExpr === "string" &&
boolExpr.charAt(0) === "%") {
var nativeCallName = boolExpr;
var $_len = arguments.length;var args = new Array(Math.max($_len - 2, 0)); for(var $_i = 2; $_i < $_len; ++$_i) {args[$_i - 2] = arguments[$_i];};
if (nativeAssert(nativeCallName, args, message) === message) return;
message = (nativeCallName + " !== " + message);
}
var ret = new AssertionError(message);
if (Error.captureStackTrace) {
Error.captureStackTrace(ret, assert);
}
throw ret;
};
})();

View File

@ -0,0 +1,161 @@
"use strict";
var firstLineError;
try {throw new Error(); } catch (e) {firstLineError = e;}
var schedule = require("./schedule");
var Queue = require("./queue");
var util = require("./util");
function Async() {
this._customScheduler = false;
this._isTickUsed = false;
this._lateQueue = new Queue(16);
this._normalQueue = new Queue(16);
this._haveDrainedQueues = false;
this._trampolineEnabled = true;
var self = this;
this.drainQueues = function () {
self._drainQueues();
};
this._schedule = schedule;
}
Async.prototype.setScheduler = function(fn) {
var prev = this._schedule;
this._schedule = fn;
this._customScheduler = true;
return prev;
};
Async.prototype.hasCustomScheduler = function() {
return this._customScheduler;
};
Async.prototype.enableTrampoline = function() {
this._trampolineEnabled = true;
};
Async.prototype.disableTrampolineIfNecessary = function() {
if (util.hasDevTools) {
this._trampolineEnabled = false;
}
};
Async.prototype.haveItemsQueued = function () {
return this._isTickUsed || this._haveDrainedQueues;
};
Async.prototype.fatalError = function(e, isNode) {
if (isNode) {
process.stderr.write("Fatal " + (e instanceof Error ? e.stack : e) +
"\n");
process.exit(2);
} else {
this.throwLater(e);
}
};
Async.prototype.throwLater = function(fn, arg) {
if (arguments.length === 1) {
arg = fn;
fn = function () { throw arg; };
}
if (typeof setTimeout !== "undefined") {
setTimeout(function() {
fn(arg);
}, 0);
} else try {
this._schedule(function() {
fn(arg);
});
} catch (e) {
throw new Error("No async scheduler available\u000a\u000a See http://goo.gl/MqrFmX\u000a");
}
};
function AsyncInvokeLater(fn, receiver, arg) {
this._lateQueue.push(fn, receiver, arg);
this._queueTick();
}
function AsyncInvoke(fn, receiver, arg) {
this._normalQueue.push(fn, receiver, arg);
this._queueTick();
}
function AsyncSettlePromises(promise) {
this._normalQueue._pushOne(promise);
this._queueTick();
}
if (!util.hasDevTools) {
Async.prototype.invokeLater = AsyncInvokeLater;
Async.prototype.invoke = AsyncInvoke;
Async.prototype.settlePromises = AsyncSettlePromises;
} else {
Async.prototype.invokeLater = function (fn, receiver, arg) {
if (this._trampolineEnabled) {
AsyncInvokeLater.call(this, fn, receiver, arg);
} else {
this._schedule(function() {
setTimeout(function() {
fn.call(receiver, arg);
}, 100);
});
}
};
Async.prototype.invoke = function (fn, receiver, arg) {
if (this._trampolineEnabled) {
AsyncInvoke.call(this, fn, receiver, arg);
} else {
this._schedule(function() {
fn.call(receiver, arg);
});
}
};
Async.prototype.settlePromises = function(promise) {
if (this._trampolineEnabled) {
AsyncSettlePromises.call(this, promise);
} else {
this._schedule(function() {
promise._settlePromises();
});
}
};
}
Async.prototype._drainQueue = function(queue) {
while (queue.length() > 0) {
var fn = queue.shift();
if (typeof fn !== "function") {
fn._settlePromises();
continue;
}
var receiver = queue.shift();
var arg = queue.shift();
fn.call(receiver, arg);
}
};
Async.prototype._drainQueues = function () {
this._drainQueue(this._normalQueue);
this._reset();
this._haveDrainedQueues = true;
this._drainQueue(this._lateQueue);
};
Async.prototype._queueTick = function () {
if (!this._isTickUsed) {
this._isTickUsed = true;
this._schedule(this.drainQueues);
}
};
Async.prototype._reset = function () {
this._isTickUsed = false;
};
module.exports = Async;
module.exports.firstLineError = firstLineError;

View File

@ -0,0 +1,67 @@
"use strict";
module.exports = function(Promise, INTERNAL, tryConvertToPromise, debug) {
var calledBind = false;
var rejectThis = function(_, e) {
this._reject(e);
};
var targetRejected = function(e, context) {
context.promiseRejectionQueued = true;
context.bindingPromise._then(rejectThis, rejectThis, null, this, e);
};
var bindingResolved = function(thisArg, context) {
if (((this._bitField & 50397184) === 0)) {
this._resolveCallback(context.target);
}
};
var bindingRejected = function(e, context) {
if (!context.promiseRejectionQueued) this._reject(e);
};
Promise.prototype.bind = function (thisArg) {
if (!calledBind) {
calledBind = true;
Promise.prototype._propagateFrom = debug.propagateFromFunction();
Promise.prototype._boundValue = debug.boundValueFunction();
}
var maybePromise = tryConvertToPromise(thisArg);
var ret = new Promise(INTERNAL);
ret._propagateFrom(this, 1);
var target = this._target();
ret._setBoundTo(maybePromise);
if (maybePromise instanceof Promise) {
var context = {
promiseRejectionQueued: false,
promise: ret,
target: target,
bindingPromise: maybePromise
};
target._then(INTERNAL, targetRejected, undefined, ret, context);
maybePromise._then(
bindingResolved, bindingRejected, undefined, ret, context);
ret._setOnCancel(maybePromise);
} else {
ret._resolveCallback(target);
}
return ret;
};
Promise.prototype._setBoundTo = function (obj) {
if (obj !== undefined) {
this._bitField = this._bitField | 2097152;
this._boundTo = obj;
} else {
this._bitField = this._bitField & (~2097152);
}
};
Promise.prototype._isBound = function () {
return (this._bitField & 2097152) === 2097152;
};
Promise.bind = function (thisArg, value) {
return Promise.resolve(value).bind(thisArg);
};
};

View File

@ -0,0 +1,11 @@
"use strict";
var old;
if (typeof Promise !== "undefined") old = Promise;
function noConflict() {
try { if (Promise === bluebird) Promise = old; }
catch (e) {}
return bluebird;
}
var bluebird = require("./promise")();
bluebird.noConflict = noConflict;
module.exports = bluebird;

View File

@ -0,0 +1,123 @@
"use strict";
var cr = Object.create;
if (cr) {
var callerCache = cr(null);
var getterCache = cr(null);
callerCache[" size"] = getterCache[" size"] = 0;
}
module.exports = function(Promise) {
var util = require("./util");
var canEvaluate = util.canEvaluate;
var isIdentifier = util.isIdentifier;
var getMethodCaller;
var getGetter;
if (!false) {
var makeMethodCaller = function (methodName) {
return new Function("ensureMethod", " \n\
return function(obj) { \n\
'use strict' \n\
var len = this.length; \n\
ensureMethod(obj, 'methodName'); \n\
switch(len) { \n\
case 1: return obj.methodName(this[0]); \n\
case 2: return obj.methodName(this[0], this[1]); \n\
case 3: return obj.methodName(this[0], this[1], this[2]); \n\
case 0: return obj.methodName(); \n\
default: \n\
return obj.methodName.apply(obj, this); \n\
} \n\
}; \n\
".replace(/methodName/g, methodName))(ensureMethod);
};
var makeGetter = function (propertyName) {
return new Function("obj", " \n\
'use strict'; \n\
return obj.propertyName; \n\
".replace("propertyName", propertyName));
};
var getCompiled = function(name, compiler, cache) {
var ret = cache[name];
if (typeof ret !== "function") {
if (!isIdentifier(name)) {
return null;
}
ret = compiler(name);
cache[name] = ret;
cache[" size"]++;
if (cache[" size"] > 512) {
var keys = Object.keys(cache);
for (var i = 0; i < 256; ++i) delete cache[keys[i]];
cache[" size"] = keys.length - 256;
}
}
return ret;
};
getMethodCaller = function(name) {
return getCompiled(name, makeMethodCaller, callerCache);
};
getGetter = function(name) {
return getCompiled(name, makeGetter, getterCache);
};
}
function ensureMethod(obj, methodName) {
var fn;
if (obj != null) fn = obj[methodName];
if (typeof fn !== "function") {
var message = "Object " + util.classString(obj) + " has no method '" +
util.toString(methodName) + "'";
throw new Promise.TypeError(message);
}
return fn;
}
function caller(obj) {
var methodName = this.pop();
var fn = ensureMethod(obj, methodName);
return fn.apply(obj, this);
}
Promise.prototype.call = function (methodName) {
var $_len = arguments.length;var args = new Array(Math.max($_len - 1, 0)); for(var $_i = 1; $_i < $_len; ++$_i) {args[$_i - 1] = arguments[$_i];};
if (!false) {
if (canEvaluate) {
var maybeCaller = getMethodCaller(methodName);
if (maybeCaller !== null) {
return this._then(
maybeCaller, undefined, undefined, args, undefined);
}
}
}
args.push(methodName);
return this._then(caller, undefined, undefined, args, undefined);
};
function namedGetter(obj) {
return obj[this];
}
function indexedGetter(obj) {
var index = +this;
if (index < 0) index = Math.max(0, index + obj.length);
return obj[index];
}
Promise.prototype.get = function (propertyName) {
var isIndex = (typeof propertyName === "number");
var getter;
if (!isIndex) {
if (canEvaluate) {
var maybeGetter = getGetter(propertyName);
getter = maybeGetter !== null ? maybeGetter : namedGetter;
} else {
getter = namedGetter;
}
} else {
getter = indexedGetter;
}
return this._then(getter, undefined, undefined, propertyName, undefined);
};
};

View File

@ -0,0 +1,129 @@
"use strict";
module.exports = function(Promise, PromiseArray, apiRejection, debug) {
var util = require("./util");
var tryCatch = util.tryCatch;
var errorObj = util.errorObj;
var async = Promise._async;
Promise.prototype["break"] = Promise.prototype.cancel = function() {
if (!debug.cancellation()) return this._warn("cancellation is disabled");
var promise = this;
var child = promise;
while (promise._isCancellable()) {
if (!promise._cancelBy(child)) {
if (child._isFollowing()) {
child._followee().cancel();
} else {
child._cancelBranched();
}
break;
}
var parent = promise._cancellationParent;
if (parent == null || !parent._isCancellable()) {
if (promise._isFollowing()) {
promise._followee().cancel();
} else {
promise._cancelBranched();
}
break;
} else {
if (promise._isFollowing()) promise._followee().cancel();
promise._setWillBeCancelled();
child = promise;
promise = parent;
}
}
};
Promise.prototype._branchHasCancelled = function() {
this._branchesRemainingToCancel--;
};
Promise.prototype._enoughBranchesHaveCancelled = function() {
return this._branchesRemainingToCancel === undefined ||
this._branchesRemainingToCancel <= 0;
};
Promise.prototype._cancelBy = function(canceller) {
if (canceller === this) {
this._branchesRemainingToCancel = 0;
this._invokeOnCancel();
return true;
} else {
this._branchHasCancelled();
if (this._enoughBranchesHaveCancelled()) {
this._invokeOnCancel();
return true;
}
}
return false;
};
Promise.prototype._cancelBranched = function() {
if (this._enoughBranchesHaveCancelled()) {
this._cancel();
}
};
Promise.prototype._cancel = function() {
if (!this._isCancellable()) return;
this._setCancelled();
async.invoke(this._cancelPromises, this, undefined);
};
Promise.prototype._cancelPromises = function() {
if (this._length() > 0) this._settlePromises();
};
Promise.prototype._unsetOnCancel = function() {
this._onCancelField = undefined;
};
Promise.prototype._isCancellable = function() {
return this.isPending() && !this._isCancelled();
};
Promise.prototype.isCancellable = function() {
return this.isPending() && !this.isCancelled();
};
Promise.prototype._doInvokeOnCancel = function(onCancelCallback, internalOnly) {
if (util.isArray(onCancelCallback)) {
for (var i = 0; i < onCancelCallback.length; ++i) {
this._doInvokeOnCancel(onCancelCallback[i], internalOnly);
}
} else if (onCancelCallback !== undefined) {
if (typeof onCancelCallback === "function") {
if (!internalOnly) {
var e = tryCatch(onCancelCallback).call(this._boundValue());
if (e === errorObj) {
this._attachExtraTrace(e.e);
async.throwLater(e.e);
}
}
} else {
onCancelCallback._resultCancelled(this);
}
}
};
Promise.prototype._invokeOnCancel = function() {
var onCancelCallback = this._onCancel();
this._unsetOnCancel();
async.invoke(this._doInvokeOnCancel, this, onCancelCallback);
};
Promise.prototype._invokeInternalOnCancel = function() {
if (this._isCancellable()) {
this._doInvokeOnCancel(this._onCancel(), true);
this._unsetOnCancel();
}
};
Promise.prototype._resultCancelled = function() {
this.cancel();
};
};

View File

@ -0,0 +1,42 @@
"use strict";
module.exports = function(NEXT_FILTER) {
var util = require("./util");
var getKeys = require("./es5").keys;
var tryCatch = util.tryCatch;
var errorObj = util.errorObj;
function catchFilter(instances, cb, promise) {
return function(e) {
var boundTo = promise._boundValue();
predicateLoop: for (var i = 0; i < instances.length; ++i) {
var item = instances[i];
if (item === Error ||
(item != null && item.prototype instanceof Error)) {
if (e instanceof item) {
return tryCatch(cb).call(boundTo, e);
}
} else if (typeof item === "function") {
var matchesPredicate = tryCatch(item).call(boundTo, e);
if (matchesPredicate === errorObj) {
return matchesPredicate;
} else if (matchesPredicate) {
return tryCatch(cb).call(boundTo, e);
}
} else if (util.isObject(e)) {
var keys = getKeys(item);
for (var j = 0; j < keys.length; ++j) {
var key = keys[j];
if (item[key] != e[key]) {
continue predicateLoop;
}
}
return tryCatch(cb).call(boundTo, e);
}
}
return NEXT_FILTER;
};
}
return catchFilter;
};

View File

@ -0,0 +1,69 @@
"use strict";
module.exports = function(Promise) {
var longStackTraces = false;
var contextStack = [];
Promise.prototype._promiseCreated = function() {};
Promise.prototype._pushContext = function() {};
Promise.prototype._popContext = function() {return null;};
Promise._peekContext = Promise.prototype._peekContext = function() {};
function Context() {
this._trace = new Context.CapturedTrace(peekContext());
}
Context.prototype._pushContext = function () {
if (this._trace !== undefined) {
this._trace._promiseCreated = null;
contextStack.push(this._trace);
}
};
Context.prototype._popContext = function () {
if (this._trace !== undefined) {
var trace = contextStack.pop();
var ret = trace._promiseCreated;
trace._promiseCreated = null;
return ret;
}
return null;
};
function createContext() {
if (longStackTraces) return new Context();
}
function peekContext() {
var lastIndex = contextStack.length - 1;
if (lastIndex >= 0) {
return contextStack[lastIndex];
}
return undefined;
}
Context.CapturedTrace = null;
Context.create = createContext;
Context.deactivateLongStackTraces = function() {};
Context.activateLongStackTraces = function() {
var Promise_pushContext = Promise.prototype._pushContext;
var Promise_popContext = Promise.prototype._popContext;
var Promise_PeekContext = Promise._peekContext;
var Promise_peekContext = Promise.prototype._peekContext;
var Promise_promiseCreated = Promise.prototype._promiseCreated;
Context.deactivateLongStackTraces = function() {
Promise.prototype._pushContext = Promise_pushContext;
Promise.prototype._popContext = Promise_popContext;
Promise._peekContext = Promise_PeekContext;
Promise.prototype._peekContext = Promise_peekContext;
Promise.prototype._promiseCreated = Promise_promiseCreated;
longStackTraces = false;
};
longStackTraces = true;
Promise.prototype._pushContext = Context.prototype._pushContext;
Promise.prototype._popContext = Context.prototype._popContext;
Promise._peekContext = Promise.prototype._peekContext = peekContext;
Promise.prototype._promiseCreated = function() {
var ctx = this._peekContext();
if (ctx && ctx._promiseCreated == null) ctx._promiseCreated = this;
};
};
return Context;
};

View File

@ -0,0 +1,916 @@
"use strict";
module.exports = function(Promise, Context) {
var getDomain = Promise._getDomain;
var async = Promise._async;
var Warning = require("./errors").Warning;
var util = require("./util");
var canAttachTrace = util.canAttachTrace;
var unhandledRejectionHandled;
var possiblyUnhandledRejection;
var bluebirdFramePattern =
/[\\\/]bluebird[\\\/]js[\\\/](release|debug|instrumented)/;
var nodeFramePattern = /\((?:timers\.js):\d+:\d+\)/;
var parseLinePattern = /[\/<\(](.+?):(\d+):(\d+)\)?\s*$/;
var stackFramePattern = null;
var formatStack = null;
var indentStackFrames = false;
var printWarning;
var debugging = !!(util.env("BLUEBIRD_DEBUG") != 0 &&
(false ||
util.env("BLUEBIRD_DEBUG") ||
util.env("NODE_ENV") === "development"));
var warnings = !!(util.env("BLUEBIRD_WARNINGS") != 0 &&
(debugging || util.env("BLUEBIRD_WARNINGS")));
var longStackTraces = !!(util.env("BLUEBIRD_LONG_STACK_TRACES") != 0 &&
(debugging || util.env("BLUEBIRD_LONG_STACK_TRACES")));
var wForgottenReturn = util.env("BLUEBIRD_W_FORGOTTEN_RETURN") != 0 &&
(warnings || !!util.env("BLUEBIRD_W_FORGOTTEN_RETURN"));
Promise.prototype.suppressUnhandledRejections = function() {
var target = this._target();
target._bitField = ((target._bitField & (~1048576)) |
524288);
};
Promise.prototype._ensurePossibleRejectionHandled = function () {
if ((this._bitField & 524288) !== 0) return;
this._setRejectionIsUnhandled();
async.invokeLater(this._notifyUnhandledRejection, this, undefined);
};
Promise.prototype._notifyUnhandledRejectionIsHandled = function () {
fireRejectionEvent("rejectionHandled",
unhandledRejectionHandled, undefined, this);
};
Promise.prototype._setReturnedNonUndefined = function() {
this._bitField = this._bitField | 268435456;
};
Promise.prototype._returnedNonUndefined = function() {
return (this._bitField & 268435456) !== 0;
};
Promise.prototype._notifyUnhandledRejection = function () {
if (this._isRejectionUnhandled()) {
var reason = this._settledValue();
this._setUnhandledRejectionIsNotified();
fireRejectionEvent("unhandledRejection",
possiblyUnhandledRejection, reason, this);
}
};
Promise.prototype._setUnhandledRejectionIsNotified = function () {
this._bitField = this._bitField | 262144;
};
Promise.prototype._unsetUnhandledRejectionIsNotified = function () {
this._bitField = this._bitField & (~262144);
};
Promise.prototype._isUnhandledRejectionNotified = function () {
return (this._bitField & 262144) > 0;
};
Promise.prototype._setRejectionIsUnhandled = function () {
this._bitField = this._bitField | 1048576;
};
Promise.prototype._unsetRejectionIsUnhandled = function () {
this._bitField = this._bitField & (~1048576);
if (this._isUnhandledRejectionNotified()) {
this._unsetUnhandledRejectionIsNotified();
this._notifyUnhandledRejectionIsHandled();
}
};
Promise.prototype._isRejectionUnhandled = function () {
return (this._bitField & 1048576) > 0;
};
Promise.prototype._warn = function(message, shouldUseOwnTrace, promise) {
return warn(message, shouldUseOwnTrace, promise || this);
};
Promise.onPossiblyUnhandledRejection = function (fn) {
var domain = getDomain();
possiblyUnhandledRejection =
typeof fn === "function" ? (domain === null ?
fn : util.domainBind(domain, fn))
: undefined;
};
Promise.onUnhandledRejectionHandled = function (fn) {
var domain = getDomain();
unhandledRejectionHandled =
typeof fn === "function" ? (domain === null ?
fn : util.domainBind(domain, fn))
: undefined;
};
var disableLongStackTraces = function() {};
Promise.longStackTraces = function () {
if (async.haveItemsQueued() && !config.longStackTraces) {
throw new Error("cannot enable long stack traces after promises have been created\u000a\u000a See http://goo.gl/MqrFmX\u000a");
}
if (!config.longStackTraces && longStackTracesIsSupported()) {
var Promise_captureStackTrace = Promise.prototype._captureStackTrace;
var Promise_attachExtraTrace = Promise.prototype._attachExtraTrace;
config.longStackTraces = true;
disableLongStackTraces = function() {
if (async.haveItemsQueued() && !config.longStackTraces) {
throw new Error("cannot enable long stack traces after promises have been created\u000a\u000a See http://goo.gl/MqrFmX\u000a");
}
Promise.prototype._captureStackTrace = Promise_captureStackTrace;
Promise.prototype._attachExtraTrace = Promise_attachExtraTrace;
Context.deactivateLongStackTraces();
async.enableTrampoline();
config.longStackTraces = false;
};
Promise.prototype._captureStackTrace = longStackTracesCaptureStackTrace;
Promise.prototype._attachExtraTrace = longStackTracesAttachExtraTrace;
Context.activateLongStackTraces();
async.disableTrampolineIfNecessary();
}
};
Promise.hasLongStackTraces = function () {
return config.longStackTraces && longStackTracesIsSupported();
};
var fireDomEvent = (function() {
try {
if (typeof CustomEvent === "function") {
var event = new CustomEvent("CustomEvent");
util.global.dispatchEvent(event);
return function(name, event) {
var domEvent = new CustomEvent(name.toLowerCase(), {
detail: event,
cancelable: true
});
return !util.global.dispatchEvent(domEvent);
};
} else if (typeof Event === "function") {
var event = new Event("CustomEvent");
util.global.dispatchEvent(event);
return function(name, event) {
var domEvent = new Event(name.toLowerCase(), {
cancelable: true
});
domEvent.detail = event;
return !util.global.dispatchEvent(domEvent);
};
} else {
var event = document.createEvent("CustomEvent");
event.initCustomEvent("testingtheevent", false, true, {});
util.global.dispatchEvent(event);
return function(name, event) {
var domEvent = document.createEvent("CustomEvent");
domEvent.initCustomEvent(name.toLowerCase(), false, true,
event);
return !util.global.dispatchEvent(domEvent);
};
}
} catch (e) {}
return function() {
return false;
};
})();
var fireGlobalEvent = (function() {
if (util.isNode) {
return function() {
return process.emit.apply(process, arguments);
};
} else {
if (!util.global) {
return function() {
return false;
};
}
return function(name) {
var methodName = "on" + name.toLowerCase();
var method = util.global[methodName];
if (!method) return false;
method.apply(util.global, [].slice.call(arguments, 1));
return true;
};
}
})();
function generatePromiseLifecycleEventObject(name, promise) {
return {promise: promise};
}
var eventToObjectGenerator = {
promiseCreated: generatePromiseLifecycleEventObject,
promiseFulfilled: generatePromiseLifecycleEventObject,
promiseRejected: generatePromiseLifecycleEventObject,
promiseResolved: generatePromiseLifecycleEventObject,
promiseCancelled: generatePromiseLifecycleEventObject,
promiseChained: function(name, promise, child) {
return {promise: promise, child: child};
},
warning: function(name, warning) {
return {warning: warning};
},
unhandledRejection: function (name, reason, promise) {
return {reason: reason, promise: promise};
},
rejectionHandled: generatePromiseLifecycleEventObject
};
var activeFireEvent = function (name) {
var globalEventFired = false;
try {
globalEventFired = fireGlobalEvent.apply(null, arguments);
} catch (e) {
async.throwLater(e);
globalEventFired = true;
}
var domEventFired = false;
try {
domEventFired = fireDomEvent(name,
eventToObjectGenerator[name].apply(null, arguments));
} catch (e) {
async.throwLater(e);
domEventFired = true;
}
return domEventFired || globalEventFired;
};
Promise.config = function(opts) {
opts = Object(opts);
if ("longStackTraces" in opts) {
if (opts.longStackTraces) {
Promise.longStackTraces();
} else if (!opts.longStackTraces && Promise.hasLongStackTraces()) {
disableLongStackTraces();
}
}
if ("warnings" in opts) {
var warningsOption = opts.warnings;
config.warnings = !!warningsOption;
wForgottenReturn = config.warnings;
if (util.isObject(warningsOption)) {
if ("wForgottenReturn" in warningsOption) {
wForgottenReturn = !!warningsOption.wForgottenReturn;
}
}
}
if ("cancellation" in opts && opts.cancellation && !config.cancellation) {
if (async.haveItemsQueued()) {
throw new Error(
"cannot enable cancellation after promises are in use");
}
Promise.prototype._clearCancellationData =
cancellationClearCancellationData;
Promise.prototype._propagateFrom = cancellationPropagateFrom;
Promise.prototype._onCancel = cancellationOnCancel;
Promise.prototype._setOnCancel = cancellationSetOnCancel;
Promise.prototype._attachCancellationCallback =
cancellationAttachCancellationCallback;
Promise.prototype._execute = cancellationExecute;
propagateFromFunction = cancellationPropagateFrom;
config.cancellation = true;
}
if ("monitoring" in opts) {
if (opts.monitoring && !config.monitoring) {
config.monitoring = true;
Promise.prototype._fireEvent = activeFireEvent;
} else if (!opts.monitoring && config.monitoring) {
config.monitoring = false;
Promise.prototype._fireEvent = defaultFireEvent;
}
}
return Promise;
};
function defaultFireEvent() { return false; }
Promise.prototype._fireEvent = defaultFireEvent;
Promise.prototype._execute = function(executor, resolve, reject) {
try {
executor(resolve, reject);
} catch (e) {
return e;
}
};
Promise.prototype._onCancel = function () {};
Promise.prototype._setOnCancel = function (handler) { ; };
Promise.prototype._attachCancellationCallback = function(onCancel) {
;
};
Promise.prototype._captureStackTrace = function () {};
Promise.prototype._attachExtraTrace = function () {};
Promise.prototype._clearCancellationData = function() {};
Promise.prototype._propagateFrom = function (parent, flags) {
;
;
};
function cancellationExecute(executor, resolve, reject) {
var promise = this;
try {
executor(resolve, reject, function(onCancel) {
if (typeof onCancel !== "function") {
throw new TypeError("onCancel must be a function, got: " +
util.toString(onCancel));
}
promise._attachCancellationCallback(onCancel);
});
} catch (e) {
return e;
}
}
function cancellationAttachCancellationCallback(onCancel) {
if (!this._isCancellable()) return this;
var previousOnCancel = this._onCancel();
if (previousOnCancel !== undefined) {
if (util.isArray(previousOnCancel)) {
previousOnCancel.push(onCancel);
} else {
this._setOnCancel([previousOnCancel, onCancel]);
}
} else {
this._setOnCancel(onCancel);
}
}
function cancellationOnCancel() {
return this._onCancelField;
}
function cancellationSetOnCancel(onCancel) {
this._onCancelField = onCancel;
}
function cancellationClearCancellationData() {
this._cancellationParent = undefined;
this._onCancelField = undefined;
}
function cancellationPropagateFrom(parent, flags) {
if ((flags & 1) !== 0) {
this._cancellationParent = parent;
var branchesRemainingToCancel = parent._branchesRemainingToCancel;
if (branchesRemainingToCancel === undefined) {
branchesRemainingToCancel = 0;
}
parent._branchesRemainingToCancel = branchesRemainingToCancel + 1;
}
if ((flags & 2) !== 0 && parent._isBound()) {
this._setBoundTo(parent._boundTo);
}
}
function bindingPropagateFrom(parent, flags) {
if ((flags & 2) !== 0 && parent._isBound()) {
this._setBoundTo(parent._boundTo);
}
}
var propagateFromFunction = bindingPropagateFrom;
function boundValueFunction() {
var ret = this._boundTo;
if (ret !== undefined) {
if (ret instanceof Promise) {
if (ret.isFulfilled()) {
return ret.value();
} else {
return undefined;
}
}
}
return ret;
}
function longStackTracesCaptureStackTrace() {
this._trace = new CapturedTrace(this._peekContext());
}
function longStackTracesAttachExtraTrace(error, ignoreSelf) {
if (canAttachTrace(error)) {
var trace = this._trace;
if (trace !== undefined) {
if (ignoreSelf) trace = trace._parent;
}
if (trace !== undefined) {
trace.attachExtraTrace(error);
} else if (!error.__stackCleaned__) {
var parsed = parseStackAndMessage(error);
util.notEnumerableProp(error, "stack",
parsed.message + "\n" + parsed.stack.join("\n"));
util.notEnumerableProp(error, "__stackCleaned__", true);
}
}
}
function checkForgottenReturns(returnValue, promiseCreated, name, promise,
parent) {
if (returnValue === undefined && promiseCreated !== null &&
wForgottenReturn) {
if (parent !== undefined && parent._returnedNonUndefined()) return;
if ((promise._bitField & 65535) === 0) return;
if (name) name = name + " ";
var handlerLine = "";
var creatorLine = "";
if (promiseCreated._trace) {
var traceLines = promiseCreated._trace.stack.split("\n");
var stack = cleanStack(traceLines);
for (var i = stack.length - 1; i >= 0; --i) {
var line = stack[i];
if (!nodeFramePattern.test(line)) {
var lineMatches = line.match(parseLinePattern);
if (lineMatches) {
handlerLine = "at " + lineMatches[1] +
":" + lineMatches[2] + ":" + lineMatches[3] + " ";
}
break;
}
}
if (stack.length > 0) {
var firstUserLine = stack[0];
for (var i = 0; i < traceLines.length; ++i) {
if (traceLines[i] === firstUserLine) {
if (i > 0) {
creatorLine = "\n" + traceLines[i - 1];
}
break;
}
}
}
}
var msg = "a promise was created in a " + name +
"handler " + handlerLine + "but was not returned from it, " +
"see http://goo.gl/rRqMUw" +
creatorLine;
promise._warn(msg, true, promiseCreated);
}
}
function deprecated(name, replacement) {
var message = name +
" is deprecated and will be removed in a future version.";
if (replacement) message += " Use " + replacement + " instead.";
return warn(message);
}
function warn(message, shouldUseOwnTrace, promise) {
if (!config.warnings) return;
var warning = new Warning(message);
var ctx;
if (shouldUseOwnTrace) {
promise._attachExtraTrace(warning);
} else if (config.longStackTraces && (ctx = Promise._peekContext())) {
ctx.attachExtraTrace(warning);
} else {
var parsed = parseStackAndMessage(warning);
warning.stack = parsed.message + "\n" + parsed.stack.join("\n");
}
if (!activeFireEvent("warning", warning)) {
formatAndLogError(warning, "", true);
}
}
function reconstructStack(message, stacks) {
for (var i = 0; i < stacks.length - 1; ++i) {
stacks[i].push("From previous event:");
stacks[i] = stacks[i].join("\n");
}
if (i < stacks.length) {
stacks[i] = stacks[i].join("\n");
}
return message + "\n" + stacks.join("\n");
}
function removeDuplicateOrEmptyJumps(stacks) {
for (var i = 0; i < stacks.length; ++i) {
if (stacks[i].length === 0 ||
((i + 1 < stacks.length) && stacks[i][0] === stacks[i+1][0])) {
stacks.splice(i, 1);
i--;
}
}
}
function removeCommonRoots(stacks) {
var current = stacks[0];
for (var i = 1; i < stacks.length; ++i) {
var prev = stacks[i];
var currentLastIndex = current.length - 1;
var currentLastLine = current[currentLastIndex];
var commonRootMeetPoint = -1;
for (var j = prev.length - 1; j >= 0; --j) {
if (prev[j] === currentLastLine) {
commonRootMeetPoint = j;
break;
}
}
for (var j = commonRootMeetPoint; j >= 0; --j) {
var line = prev[j];
if (current[currentLastIndex] === line) {
current.pop();
currentLastIndex--;
} else {
break;
}
}
current = prev;
}
}
function cleanStack(stack) {
var ret = [];
for (var i = 0; i < stack.length; ++i) {
var line = stack[i];
var isTraceLine = " (No stack trace)" === line ||
stackFramePattern.test(line);
var isInternalFrame = isTraceLine && shouldIgnore(line);
if (isTraceLine && !isInternalFrame) {
if (indentStackFrames && line.charAt(0) !== " ") {
line = " " + line;
}
ret.push(line);
}
}
return ret;
}
function stackFramesAsArray(error) {
var stack = error.stack.replace(/\s+$/g, "").split("\n");
for (var i = 0; i < stack.length; ++i) {
var line = stack[i];
if (" (No stack trace)" === line || stackFramePattern.test(line)) {
break;
}
}
if (i > 0 && error.name != "SyntaxError") {
stack = stack.slice(i);
}
return stack;
}
function parseStackAndMessage(error) {
var stack = error.stack;
var message = error.toString();
stack = typeof stack === "string" && stack.length > 0
? stackFramesAsArray(error) : [" (No stack trace)"];
return {
message: message,
stack: error.name == "SyntaxError" ? stack : cleanStack(stack)
};
}
function formatAndLogError(error, title, isSoft) {
if (typeof console !== "undefined") {
var message;
if (util.isObject(error)) {
var stack = error.stack;
message = title + formatStack(stack, error);
} else {
message = title + String(error);
}
if (typeof printWarning === "function") {
printWarning(message, isSoft);
} else if (typeof console.log === "function" ||
typeof console.log === "object") {
console.log(message);
}
}
}
function fireRejectionEvent(name, localHandler, reason, promise) {
var localEventFired = false;
try {
if (typeof localHandler === "function") {
localEventFired = true;
if (name === "rejectionHandled") {
localHandler(promise);
} else {
localHandler(reason, promise);
}
}
} catch (e) {
async.throwLater(e);
}
if (name === "unhandledRejection") {
if (!activeFireEvent(name, reason, promise) && !localEventFired) {
formatAndLogError(reason, "Unhandled rejection ");
}
} else {
activeFireEvent(name, promise);
}
}
function formatNonError(obj) {
var str;
if (typeof obj === "function") {
str = "[function " +
(obj.name || "anonymous") +
"]";
} else {
str = obj && typeof obj.toString === "function"
? obj.toString() : util.toString(obj);
var ruselessToString = /\[object [a-zA-Z0-9$_]+\]/;
if (ruselessToString.test(str)) {
try {
var newStr = JSON.stringify(obj);
str = newStr;
}
catch(e) {
}
}
if (str.length === 0) {
str = "(empty array)";
}
}
return ("(<" + snip(str) + ">, no stack trace)");
}
function snip(str) {
var maxChars = 41;
if (str.length < maxChars) {
return str;
}
return str.substr(0, maxChars - 3) + "...";
}
function longStackTracesIsSupported() {
return typeof captureStackTrace === "function";
}
var shouldIgnore = function() { return false; };
var parseLineInfoRegex = /[\/<\(]([^:\/]+):(\d+):(?:\d+)\)?\s*$/;
function parseLineInfo(line) {
var matches = line.match(parseLineInfoRegex);
if (matches) {
return {
fileName: matches[1],
line: parseInt(matches[2], 10)
};
}
}
function setBounds(firstLineError, lastLineError) {
if (!longStackTracesIsSupported()) return;
var firstStackLines = firstLineError.stack.split("\n");
var lastStackLines = lastLineError.stack.split("\n");
var firstIndex = -1;
var lastIndex = -1;
var firstFileName;
var lastFileName;
for (var i = 0; i < firstStackLines.length; ++i) {
var result = parseLineInfo(firstStackLines[i]);
if (result) {
firstFileName = result.fileName;
firstIndex = result.line;
break;
}
}
for (var i = 0; i < lastStackLines.length; ++i) {
var result = parseLineInfo(lastStackLines[i]);
if (result) {
lastFileName = result.fileName;
lastIndex = result.line;
break;
}
}
if (firstIndex < 0 || lastIndex < 0 || !firstFileName || !lastFileName ||
firstFileName !== lastFileName || firstIndex >= lastIndex) {
return;
}
shouldIgnore = function(line) {
if (bluebirdFramePattern.test(line)) return true;
var info = parseLineInfo(line);
if (info) {
if (info.fileName === firstFileName &&
(firstIndex <= info.line && info.line <= lastIndex)) {
return true;
}
}
return false;
};
}
function CapturedTrace(parent) {
this._parent = parent;
this._promisesCreated = 0;
var length = this._length = 1 + (parent === undefined ? 0 : parent._length);
captureStackTrace(this, CapturedTrace);
if (length > 32) this.uncycle();
}
util.inherits(CapturedTrace, Error);
Context.CapturedTrace = CapturedTrace;
CapturedTrace.prototype.uncycle = function() {
var length = this._length;
if (length < 2) return;
var nodes = [];
var stackToIndex = {};
for (var i = 0, node = this; node !== undefined; ++i) {
nodes.push(node);
node = node._parent;
}
length = this._length = i;
for (var i = length - 1; i >= 0; --i) {
var stack = nodes[i].stack;
if (stackToIndex[stack] === undefined) {
stackToIndex[stack] = i;
}
}
for (var i = 0; i < length; ++i) {
var currentStack = nodes[i].stack;
var index = stackToIndex[currentStack];
if (index !== undefined && index !== i) {
if (index > 0) {
nodes[index - 1]._parent = undefined;
nodes[index - 1]._length = 1;
}
nodes[i]._parent = undefined;
nodes[i]._length = 1;
var cycleEdgeNode = i > 0 ? nodes[i - 1] : this;
if (index < length - 1) {
cycleEdgeNode._parent = nodes[index + 1];
cycleEdgeNode._parent.uncycle();
cycleEdgeNode._length =
cycleEdgeNode._parent._length + 1;
} else {
cycleEdgeNode._parent = undefined;
cycleEdgeNode._length = 1;
}
var currentChildLength = cycleEdgeNode._length + 1;
for (var j = i - 2; j >= 0; --j) {
nodes[j]._length = currentChildLength;
currentChildLength++;
}
return;
}
}
};
CapturedTrace.prototype.attachExtraTrace = function(error) {
if (error.__stackCleaned__) return;
this.uncycle();
var parsed = parseStackAndMessage(error);
var message = parsed.message;
var stacks = [parsed.stack];
var trace = this;
while (trace !== undefined) {
stacks.push(cleanStack(trace.stack.split("\n")));
trace = trace._parent;
}
removeCommonRoots(stacks);
removeDuplicateOrEmptyJumps(stacks);
util.notEnumerableProp(error, "stack", reconstructStack(message, stacks));
util.notEnumerableProp(error, "__stackCleaned__", true);
};
var captureStackTrace = (function stackDetection() {
var v8stackFramePattern = /^\s*at\s*/;
var v8stackFormatter = function(stack, error) {
if (typeof stack === "string") return stack;
if (error.name !== undefined &&
error.message !== undefined) {
return error.toString();
}
return formatNonError(error);
};
if (typeof Error.stackTraceLimit === "number" &&
typeof Error.captureStackTrace === "function") {
Error.stackTraceLimit += 6;
stackFramePattern = v8stackFramePattern;
formatStack = v8stackFormatter;
var captureStackTrace = Error.captureStackTrace;
shouldIgnore = function(line) {
return bluebirdFramePattern.test(line);
};
return function(receiver, ignoreUntil) {
Error.stackTraceLimit += 6;
captureStackTrace(receiver, ignoreUntil);
Error.stackTraceLimit -= 6;
};
}
var err = new Error();
if (typeof err.stack === "string" &&
err.stack.split("\n")[0].indexOf("stackDetection@") >= 0) {
stackFramePattern = /@/;
formatStack = v8stackFormatter;
indentStackFrames = true;
return function captureStackTrace(o) {
o.stack = new Error().stack;
};
}
var hasStackAfterThrow;
try { throw new Error(); }
catch(e) {
hasStackAfterThrow = ("stack" in e);
}
if (!("stack" in err) && hasStackAfterThrow &&
typeof Error.stackTraceLimit === "number") {
stackFramePattern = v8stackFramePattern;
formatStack = v8stackFormatter;
return function captureStackTrace(o) {
Error.stackTraceLimit += 6;
try { throw new Error(); }
catch(e) { o.stack = e.stack; }
Error.stackTraceLimit -= 6;
};
}
formatStack = function(stack, error) {
if (typeof stack === "string") return stack;
if ((typeof error === "object" ||
typeof error === "function") &&
error.name !== undefined &&
error.message !== undefined) {
return error.toString();
}
return formatNonError(error);
};
return null;
})([]);
if (typeof console !== "undefined" && typeof console.warn !== "undefined") {
printWarning = function (message) {
console.warn(message);
};
if (util.isNode && process.stderr.isTTY) {
printWarning = function(message, isSoft) {
var color = isSoft ? "\u001b[33m" : "\u001b[31m";
console.warn(color + message + "\u001b[0m\n");
};
} else if (!util.isNode && typeof (new Error().stack) === "string") {
printWarning = function(message, isSoft) {
console.warn("%c" + message,
isSoft ? "color: darkorange" : "color: red");
};
}
}
var config = {
warnings: warnings,
longStackTraces: false,
cancellation: false,
monitoring: false
};
if (longStackTraces) Promise.longStackTraces();
return {
longStackTraces: function() {
return config.longStackTraces;
},
warnings: function() {
return config.warnings;
},
cancellation: function() {
return config.cancellation;
},
monitoring: function() {
return config.monitoring;
},
propagateFromFunction: function() {
return propagateFromFunction;
},
boundValueFunction: function() {
return boundValueFunction;
},
checkForgottenReturns: checkForgottenReturns,
setBounds: setBounds,
warn: warn,
deprecated: deprecated,
CapturedTrace: CapturedTrace,
fireDomEvent: fireDomEvent,
fireGlobalEvent: fireGlobalEvent
};
};

View File

@ -0,0 +1,46 @@
"use strict";
module.exports = function(Promise) {
function returner() {
return this.value;
}
function thrower() {
throw this.reason;
}
Promise.prototype["return"] =
Promise.prototype.thenReturn = function (value) {
if (value instanceof Promise) value.suppressUnhandledRejections();
return this._then(
returner, undefined, undefined, {value: value}, undefined);
};
Promise.prototype["throw"] =
Promise.prototype.thenThrow = function (reason) {
return this._then(
thrower, undefined, undefined, {reason: reason}, undefined);
};
Promise.prototype.catchThrow = function (reason) {
if (arguments.length <= 1) {
return this._then(
undefined, thrower, undefined, {reason: reason}, undefined);
} else {
var _reason = arguments[1];
var handler = function() {throw _reason;};
return this.caught(reason, handler);
}
};
Promise.prototype.catchReturn = function (value) {
if (arguments.length <= 1) {
if (value instanceof Promise) value.suppressUnhandledRejections();
return this._then(
undefined, returner, undefined, {value: value}, undefined);
} else {
var _value = arguments[1];
if (_value instanceof Promise) _value.suppressUnhandledRejections();
var handler = function() {return _value;};
return this.caught(value, handler);
}
};
};

View File

@ -0,0 +1,30 @@
"use strict";
module.exports = function(Promise, INTERNAL) {
var PromiseReduce = Promise.reduce;
var PromiseAll = Promise.all;
function promiseAllThis() {
return PromiseAll(this);
}
function PromiseMapSeries(promises, fn) {
return PromiseReduce(promises, fn, INTERNAL, INTERNAL);
}
Promise.prototype.each = function (fn) {
return PromiseReduce(this, fn, INTERNAL, 0)
._then(promiseAllThis, undefined, undefined, this, undefined);
};
Promise.prototype.mapSeries = function (fn) {
return PromiseReduce(this, fn, INTERNAL, INTERNAL);
};
Promise.each = function (promises, fn) {
return PromiseReduce(promises, fn, INTERNAL, 0)
._then(promiseAllThis, undefined, undefined, promises, undefined);
};
Promise.mapSeries = PromiseMapSeries;
};

View File

@ -0,0 +1,116 @@
"use strict";
var es5 = require("./es5");
var Objectfreeze = es5.freeze;
var util = require("./util");
var inherits = util.inherits;
var notEnumerableProp = util.notEnumerableProp;
function subError(nameProperty, defaultMessage) {
function SubError(message) {
if (!(this instanceof SubError)) return new SubError(message);
notEnumerableProp(this, "message",
typeof message === "string" ? message : defaultMessage);
notEnumerableProp(this, "name", nameProperty);
if (Error.captureStackTrace) {
Error.captureStackTrace(this, this.constructor);
} else {
Error.call(this);
}
}
inherits(SubError, Error);
return SubError;
}
var _TypeError, _RangeError;
var Warning = subError("Warning", "warning");
var CancellationError = subError("CancellationError", "cancellation error");
var TimeoutError = subError("TimeoutError", "timeout error");
var AggregateError = subError("AggregateError", "aggregate error");
try {
_TypeError = TypeError;
_RangeError = RangeError;
} catch(e) {
_TypeError = subError("TypeError", "type error");
_RangeError = subError("RangeError", "range error");
}
var methods = ("join pop push shift unshift slice filter forEach some " +
"every map indexOf lastIndexOf reduce reduceRight sort reverse").split(" ");
for (var i = 0; i < methods.length; ++i) {
if (typeof Array.prototype[methods[i]] === "function") {
AggregateError.prototype[methods[i]] = Array.prototype[methods[i]];
}
}
es5.defineProperty(AggregateError.prototype, "length", {
value: 0,
configurable: false,
writable: true,
enumerable: true
});
AggregateError.prototype["isOperational"] = true;
var level = 0;
AggregateError.prototype.toString = function() {
var indent = Array(level * 4 + 1).join(" ");
var ret = "\n" + indent + "AggregateError of:" + "\n";
level++;
indent = Array(level * 4 + 1).join(" ");
for (var i = 0; i < this.length; ++i) {
var str = this[i] === this ? "[Circular AggregateError]" : this[i] + "";
var lines = str.split("\n");
for (var j = 0; j < lines.length; ++j) {
lines[j] = indent + lines[j];
}
str = lines.join("\n");
ret += str + "\n";
}
level--;
return ret;
};
function OperationalError(message) {
if (!(this instanceof OperationalError))
return new OperationalError(message);
notEnumerableProp(this, "name", "OperationalError");
notEnumerableProp(this, "message", message);
this.cause = message;
this["isOperational"] = true;
if (message instanceof Error) {
notEnumerableProp(this, "message", message.message);
notEnumerableProp(this, "stack", message.stack);
} else if (Error.captureStackTrace) {
Error.captureStackTrace(this, this.constructor);
}
}
inherits(OperationalError, Error);
var errorTypes = Error["__BluebirdErrorTypes__"];
if (!errorTypes) {
errorTypes = Objectfreeze({
CancellationError: CancellationError,
TimeoutError: TimeoutError,
OperationalError: OperationalError,
RejectionError: OperationalError,
AggregateError: AggregateError
});
es5.defineProperty(Error, "__BluebirdErrorTypes__", {
value: errorTypes,
writable: false,
enumerable: false,
configurable: false
});
}
module.exports = {
Error: Error,
TypeError: _TypeError,
RangeError: _RangeError,
CancellationError: errorTypes.CancellationError,
OperationalError: errorTypes.OperationalError,
TimeoutError: errorTypes.TimeoutError,
AggregateError: errorTypes.AggregateError,
Warning: Warning
};

View File

@ -0,0 +1,80 @@
var isES5 = (function(){
"use strict";
return this === undefined;
})();
if (isES5) {
module.exports = {
freeze: Object.freeze,
defineProperty: Object.defineProperty,
getDescriptor: Object.getOwnPropertyDescriptor,
keys: Object.keys,
names: Object.getOwnPropertyNames,
getPrototypeOf: Object.getPrototypeOf,
isArray: Array.isArray,
isES5: isES5,
propertyIsWritable: function(obj, prop) {
var descriptor = Object.getOwnPropertyDescriptor(obj, prop);
return !!(!descriptor || descriptor.writable || descriptor.set);
}
};
} else {
var has = {}.hasOwnProperty;
var str = {}.toString;
var proto = {}.constructor.prototype;
var ObjectKeys = function (o) {
var ret = [];
for (var key in o) {
if (has.call(o, key)) {
ret.push(key);
}
}
return ret;
};
var ObjectGetDescriptor = function(o, key) {
return {value: o[key]};
};
var ObjectDefineProperty = function (o, key, desc) {
o[key] = desc.value;
return o;
};
var ObjectFreeze = function (obj) {
return obj;
};
var ObjectGetPrototypeOf = function (obj) {
try {
return Object(obj).constructor.prototype;
}
catch (e) {
return proto;
}
};
var ArrayIsArray = function (obj) {
try {
return str.call(obj) === "[object Array]";
}
catch(e) {
return false;
}
};
module.exports = {
isArray: ArrayIsArray,
keys: ObjectKeys,
names: ObjectKeys,
defineProperty: ObjectDefineProperty,
getDescriptor: ObjectGetDescriptor,
freeze: ObjectFreeze,
getPrototypeOf: ObjectGetPrototypeOf,
isES5: isES5,
propertyIsWritable: function() {
return true;
}
};
}

View File

@ -0,0 +1,12 @@
"use strict";
module.exports = function(Promise, INTERNAL) {
var PromiseMap = Promise.map;
Promise.prototype.filter = function (fn, options) {
return PromiseMap(this, fn, options, INTERNAL);
};
Promise.filter = function (promises, fn, options) {
return PromiseMap(promises, fn, options, INTERNAL);
};
};

View File

@ -0,0 +1,146 @@
"use strict";
module.exports = function(Promise, tryConvertToPromise, NEXT_FILTER) {
var util = require("./util");
var CancellationError = Promise.CancellationError;
var errorObj = util.errorObj;
var catchFilter = require("./catch_filter")(NEXT_FILTER);
function PassThroughHandlerContext(promise, type, handler) {
this.promise = promise;
this.type = type;
this.handler = handler;
this.called = false;
this.cancelPromise = null;
}
PassThroughHandlerContext.prototype.isFinallyHandler = function() {
return this.type === 0;
};
function FinallyHandlerCancelReaction(finallyHandler) {
this.finallyHandler = finallyHandler;
}
FinallyHandlerCancelReaction.prototype._resultCancelled = function() {
checkCancel(this.finallyHandler);
};
function checkCancel(ctx, reason) {
if (ctx.cancelPromise != null) {
if (arguments.length > 1) {
ctx.cancelPromise._reject(reason);
} else {
ctx.cancelPromise._cancel();
}
ctx.cancelPromise = null;
return true;
}
return false;
}
function succeed() {
return finallyHandler.call(this, this.promise._target()._settledValue());
}
function fail(reason) {
if (checkCancel(this, reason)) return;
errorObj.e = reason;
return errorObj;
}
function finallyHandler(reasonOrValue) {
var promise = this.promise;
var handler = this.handler;
if (!this.called) {
this.called = true;
var ret = this.isFinallyHandler()
? handler.call(promise._boundValue())
: handler.call(promise._boundValue(), reasonOrValue);
if (ret === NEXT_FILTER) {
return ret;
} else if (ret !== undefined) {
promise._setReturnedNonUndefined();
var maybePromise = tryConvertToPromise(ret, promise);
if (maybePromise instanceof Promise) {
if (this.cancelPromise != null) {
if (maybePromise._isCancelled()) {
var reason =
new CancellationError("late cancellation observer");
promise._attachExtraTrace(reason);
errorObj.e = reason;
return errorObj;
} else if (maybePromise.isPending()) {
maybePromise._attachCancellationCallback(
new FinallyHandlerCancelReaction(this));
}
}
return maybePromise._then(
succeed, fail, undefined, this, undefined);
}
}
}
if (promise.isRejected()) {
checkCancel(this);
errorObj.e = reasonOrValue;
return errorObj;
} else {
checkCancel(this);
return reasonOrValue;
}
}
Promise.prototype._passThrough = function(handler, type, success, fail) {
if (typeof handler !== "function") return this.then();
return this._then(success,
fail,
undefined,
new PassThroughHandlerContext(this, type, handler),
undefined);
};
Promise.prototype.lastly =
Promise.prototype["finally"] = function (handler) {
return this._passThrough(handler,
0,
finallyHandler,
finallyHandler);
};
Promise.prototype.tap = function (handler) {
return this._passThrough(handler, 1, finallyHandler);
};
Promise.prototype.tapCatch = function (handlerOrPredicate) {
var len = arguments.length;
if(len === 1) {
return this._passThrough(handlerOrPredicate,
1,
undefined,
finallyHandler);
} else {
var catchInstances = new Array(len - 1),
j = 0, i;
for (i = 0; i < len - 1; ++i) {
var item = arguments[i];
if (util.isObject(item)) {
catchInstances[j++] = item;
} else {
return Promise.reject(new TypeError(
"tapCatch statement predicate: "
+ "expecting an object but got " + util.classString(item)
));
}
}
catchInstances.length = j;
var handler = arguments[i];
return this._passThrough(catchFilter(catchInstances, handler, this),
1,
undefined,
finallyHandler);
}
};
return PassThroughHandlerContext;
};

View File

@ -0,0 +1,223 @@
"use strict";
module.exports = function(Promise,
apiRejection,
INTERNAL,
tryConvertToPromise,
Proxyable,
debug) {
var errors = require("./errors");
var TypeError = errors.TypeError;
var util = require("./util");
var errorObj = util.errorObj;
var tryCatch = util.tryCatch;
var yieldHandlers = [];
function promiseFromYieldHandler(value, yieldHandlers, traceParent) {
for (var i = 0; i < yieldHandlers.length; ++i) {
traceParent._pushContext();
var result = tryCatch(yieldHandlers[i])(value);
traceParent._popContext();
if (result === errorObj) {
traceParent._pushContext();
var ret = Promise.reject(errorObj.e);
traceParent._popContext();
return ret;
}
var maybePromise = tryConvertToPromise(result, traceParent);
if (maybePromise instanceof Promise) return maybePromise;
}
return null;
}
function PromiseSpawn(generatorFunction, receiver, yieldHandler, stack) {
if (debug.cancellation()) {
var internal = new Promise(INTERNAL);
var _finallyPromise = this._finallyPromise = new Promise(INTERNAL);
this._promise = internal.lastly(function() {
return _finallyPromise;
});
internal._captureStackTrace();
internal._setOnCancel(this);
} else {
var promise = this._promise = new Promise(INTERNAL);
promise._captureStackTrace();
}
this._stack = stack;
this._generatorFunction = generatorFunction;
this._receiver = receiver;
this._generator = undefined;
this._yieldHandlers = typeof yieldHandler === "function"
? [yieldHandler].concat(yieldHandlers)
: yieldHandlers;
this._yieldedPromise = null;
this._cancellationPhase = false;
}
util.inherits(PromiseSpawn, Proxyable);
PromiseSpawn.prototype._isResolved = function() {
return this._promise === null;
};
PromiseSpawn.prototype._cleanup = function() {
this._promise = this._generator = null;
if (debug.cancellation() && this._finallyPromise !== null) {
this._finallyPromise._fulfill();
this._finallyPromise = null;
}
};
PromiseSpawn.prototype._promiseCancelled = function() {
if (this._isResolved()) return;
var implementsReturn = typeof this._generator["return"] !== "undefined";
var result;
if (!implementsReturn) {
var reason = new Promise.CancellationError(
"generator .return() sentinel");
Promise.coroutine.returnSentinel = reason;
this._promise._attachExtraTrace(reason);
this._promise._pushContext();
result = tryCatch(this._generator["throw"]).call(this._generator,
reason);
this._promise._popContext();
} else {
this._promise._pushContext();
result = tryCatch(this._generator["return"]).call(this._generator,
undefined);
this._promise._popContext();
}
this._cancellationPhase = true;
this._yieldedPromise = null;
this._continue(result);
};
PromiseSpawn.prototype._promiseFulfilled = function(value) {
this._yieldedPromise = null;
this._promise._pushContext();
var result = tryCatch(this._generator.next).call(this._generator, value);
this._promise._popContext();
this._continue(result);
};
PromiseSpawn.prototype._promiseRejected = function(reason) {
this._yieldedPromise = null;
this._promise._attachExtraTrace(reason);
this._promise._pushContext();
var result = tryCatch(this._generator["throw"])
.call(this._generator, reason);
this._promise._popContext();
this._continue(result);
};
PromiseSpawn.prototype._resultCancelled = function() {
if (this._yieldedPromise instanceof Promise) {
var promise = this._yieldedPromise;
this._yieldedPromise = null;
promise.cancel();
}
};
PromiseSpawn.prototype.promise = function () {
return this._promise;
};
PromiseSpawn.prototype._run = function () {
this._generator = this._generatorFunction.call(this._receiver);
this._receiver =
this._generatorFunction = undefined;
this._promiseFulfilled(undefined);
};
PromiseSpawn.prototype._continue = function (result) {
var promise = this._promise;
if (result === errorObj) {
this._cleanup();
if (this._cancellationPhase) {
return promise.cancel();
} else {
return promise._rejectCallback(result.e, false);
}
}
var value = result.value;
if (result.done === true) {
this._cleanup();
if (this._cancellationPhase) {
return promise.cancel();
} else {
return promise._resolveCallback(value);
}
} else {
var maybePromise = tryConvertToPromise(value, this._promise);
if (!(maybePromise instanceof Promise)) {
maybePromise =
promiseFromYieldHandler(maybePromise,
this._yieldHandlers,
this._promise);
if (maybePromise === null) {
this._promiseRejected(
new TypeError(
"A value %s was yielded that could not be treated as a promise\u000a\u000a See http://goo.gl/MqrFmX\u000a\u000a".replace("%s", String(value)) +
"From coroutine:\u000a" +
this._stack.split("\n").slice(1, -7).join("\n")
)
);
return;
}
}
maybePromise = maybePromise._target();
var bitField = maybePromise._bitField;
;
if (((bitField & 50397184) === 0)) {
this._yieldedPromise = maybePromise;
maybePromise._proxy(this, null);
} else if (((bitField & 33554432) !== 0)) {
Promise._async.invoke(
this._promiseFulfilled, this, maybePromise._value()
);
} else if (((bitField & 16777216) !== 0)) {
Promise._async.invoke(
this._promiseRejected, this, maybePromise._reason()
);
} else {
this._promiseCancelled();
}
}
};
Promise.coroutine = function (generatorFunction, options) {
if (typeof generatorFunction !== "function") {
throw new TypeError("generatorFunction must be a function\u000a\u000a See http://goo.gl/MqrFmX\u000a");
}
var yieldHandler = Object(options).yieldHandler;
var PromiseSpawn$ = PromiseSpawn;
var stack = new Error().stack;
return function () {
var generator = generatorFunction.apply(this, arguments);
var spawn = new PromiseSpawn$(undefined, undefined, yieldHandler,
stack);
var ret = spawn.promise();
spawn._generator = generator;
spawn._promiseFulfilled(undefined);
return ret;
};
};
Promise.coroutine.addYieldHandler = function(fn) {
if (typeof fn !== "function") {
throw new TypeError("expecting a function but got " + util.classString(fn));
}
yieldHandlers.push(fn);
};
Promise.spawn = function (generatorFunction) {
debug.deprecated("Promise.spawn()", "Promise.coroutine()");
if (typeof generatorFunction !== "function") {
return apiRejection("generatorFunction must be a function\u000a\u000a See http://goo.gl/MqrFmX\u000a");
}
var spawn = new PromiseSpawn(generatorFunction, this);
var ret = spawn.promise();
spawn._run(Promise.spawn);
return ret;
};
};

View File

@ -0,0 +1,168 @@
"use strict";
module.exports =
function(Promise, PromiseArray, tryConvertToPromise, INTERNAL, async,
getDomain) {
var util = require("./util");
var canEvaluate = util.canEvaluate;
var tryCatch = util.tryCatch;
var errorObj = util.errorObj;
var reject;
if (!false) {
if (canEvaluate) {
var thenCallback = function(i) {
return new Function("value", "holder", " \n\
'use strict'; \n\
holder.pIndex = value; \n\
holder.checkFulfillment(this); \n\
".replace(/Index/g, i));
};
var promiseSetter = function(i) {
return new Function("promise", "holder", " \n\
'use strict'; \n\
holder.pIndex = promise; \n\
".replace(/Index/g, i));
};
var generateHolderClass = function(total) {
var props = new Array(total);
for (var i = 0; i < props.length; ++i) {
props[i] = "this.p" + (i+1);
}
var assignment = props.join(" = ") + " = null;";
var cancellationCode= "var promise;\n" + props.map(function(prop) {
return " \n\
promise = " + prop + "; \n\
if (promise instanceof Promise) { \n\
promise.cancel(); \n\
} \n\
";
}).join("\n");
var passedArguments = props.join(", ");
var name = "Holder$" + total;
var code = "return function(tryCatch, errorObj, Promise, async) { \n\
'use strict'; \n\
function [TheName](fn) { \n\
[TheProperties] \n\
this.fn = fn; \n\
this.asyncNeeded = true; \n\
this.now = 0; \n\
} \n\
\n\
[TheName].prototype._callFunction = function(promise) { \n\
promise._pushContext(); \n\
var ret = tryCatch(this.fn)([ThePassedArguments]); \n\
promise._popContext(); \n\
if (ret === errorObj) { \n\
promise._rejectCallback(ret.e, false); \n\
} else { \n\
promise._resolveCallback(ret); \n\
} \n\
}; \n\
\n\
[TheName].prototype.checkFulfillment = function(promise) { \n\
var now = ++this.now; \n\
if (now === [TheTotal]) { \n\
if (this.asyncNeeded) { \n\
async.invoke(this._callFunction, this, promise); \n\
} else { \n\
this._callFunction(promise); \n\
} \n\
\n\
} \n\
}; \n\
\n\
[TheName].prototype._resultCancelled = function() { \n\
[CancellationCode] \n\
}; \n\
\n\
return [TheName]; \n\
}(tryCatch, errorObj, Promise, async); \n\
";
code = code.replace(/\[TheName\]/g, name)
.replace(/\[TheTotal\]/g, total)
.replace(/\[ThePassedArguments\]/g, passedArguments)
.replace(/\[TheProperties\]/g, assignment)
.replace(/\[CancellationCode\]/g, cancellationCode);
return new Function("tryCatch", "errorObj", "Promise", "async", code)
(tryCatch, errorObj, Promise, async);
};
var holderClasses = [];
var thenCallbacks = [];
var promiseSetters = [];
for (var i = 0; i < 8; ++i) {
holderClasses.push(generateHolderClass(i + 1));
thenCallbacks.push(thenCallback(i + 1));
promiseSetters.push(promiseSetter(i + 1));
}
reject = function (reason) {
this._reject(reason);
};
}}
Promise.join = function () {
var last = arguments.length - 1;
var fn;
if (last > 0 && typeof arguments[last] === "function") {
fn = arguments[last];
if (!false) {
if (last <= 8 && canEvaluate) {
var ret = new Promise(INTERNAL);
ret._captureStackTrace();
var HolderClass = holderClasses[last - 1];
var holder = new HolderClass(fn);
var callbacks = thenCallbacks;
for (var i = 0; i < last; ++i) {
var maybePromise = tryConvertToPromise(arguments[i], ret);
if (maybePromise instanceof Promise) {
maybePromise = maybePromise._target();
var bitField = maybePromise._bitField;
;
if (((bitField & 50397184) === 0)) {
maybePromise._then(callbacks[i], reject,
undefined, ret, holder);
promiseSetters[i](maybePromise, holder);
holder.asyncNeeded = false;
} else if (((bitField & 33554432) !== 0)) {
callbacks[i].call(ret,
maybePromise._value(), holder);
} else if (((bitField & 16777216) !== 0)) {
ret._reject(maybePromise._reason());
} else {
ret._cancel();
}
} else {
callbacks[i].call(ret, maybePromise, holder);
}
}
if (!ret._isFateSealed()) {
if (holder.asyncNeeded) {
var domain = getDomain();
if (domain !== null) {
holder.fn = util.domainBind(domain, holder.fn);
}
}
ret._setAsyncGuaranteed();
ret._setOnCancel(holder);
}
return ret;
}
}
}
var $_len = arguments.length;var args = new Array($_len); for(var $_i = 0; $_i < $_len; ++$_i) {args[$_i] = arguments[$_i];};
if (fn) args.pop();
var ret = new PromiseArray(args).promise();
return fn !== undefined ? ret.spread(fn) : ret;
};
};

View File

@ -0,0 +1,168 @@
"use strict";
module.exports = function(Promise,
PromiseArray,
apiRejection,
tryConvertToPromise,
INTERNAL,
debug) {
var getDomain = Promise._getDomain;
var util = require("./util");
var tryCatch = util.tryCatch;
var errorObj = util.errorObj;
var async = Promise._async;
function MappingPromiseArray(promises, fn, limit, _filter) {
this.constructor$(promises);
this._promise._captureStackTrace();
var domain = getDomain();
this._callback = domain === null ? fn : util.domainBind(domain, fn);
this._preservedValues = _filter === INTERNAL
? new Array(this.length())
: null;
this._limit = limit;
this._inFlight = 0;
this._queue = [];
async.invoke(this._asyncInit, this, undefined);
}
util.inherits(MappingPromiseArray, PromiseArray);
MappingPromiseArray.prototype._asyncInit = function() {
this._init$(undefined, -2);
};
MappingPromiseArray.prototype._init = function () {};
MappingPromiseArray.prototype._promiseFulfilled = function (value, index) {
var values = this._values;
var length = this.length();
var preservedValues = this._preservedValues;
var limit = this._limit;
if (index < 0) {
index = (index * -1) - 1;
values[index] = value;
if (limit >= 1) {
this._inFlight--;
this._drainQueue();
if (this._isResolved()) return true;
}
} else {
if (limit >= 1 && this._inFlight >= limit) {
values[index] = value;
this._queue.push(index);
return false;
}
if (preservedValues !== null) preservedValues[index] = value;
var promise = this._promise;
var callback = this._callback;
var receiver = promise._boundValue();
promise._pushContext();
var ret = tryCatch(callback).call(receiver, value, index, length);
var promiseCreated = promise._popContext();
debug.checkForgottenReturns(
ret,
promiseCreated,
preservedValues !== null ? "Promise.filter" : "Promise.map",
promise
);
if (ret === errorObj) {
this._reject(ret.e);
return true;
}
var maybePromise = tryConvertToPromise(ret, this._promise);
if (maybePromise instanceof Promise) {
maybePromise = maybePromise._target();
var bitField = maybePromise._bitField;
;
if (((bitField & 50397184) === 0)) {
if (limit >= 1) this._inFlight++;
values[index] = maybePromise;
maybePromise._proxy(this, (index + 1) * -1);
return false;
} else if (((bitField & 33554432) !== 0)) {
ret = maybePromise._value();
} else if (((bitField & 16777216) !== 0)) {
this._reject(maybePromise._reason());
return true;
} else {
this._cancel();
return true;
}
}
values[index] = ret;
}
var totalResolved = ++this._totalResolved;
if (totalResolved >= length) {
if (preservedValues !== null) {
this._filter(values, preservedValues);
} else {
this._resolve(values);
}
return true;
}
return false;
};
MappingPromiseArray.prototype._drainQueue = function () {
var queue = this._queue;
var limit = this._limit;
var values = this._values;
while (queue.length > 0 && this._inFlight < limit) {
if (this._isResolved()) return;
var index = queue.pop();
this._promiseFulfilled(values[index], index);
}
};
MappingPromiseArray.prototype._filter = function (booleans, values) {
var len = values.length;
var ret = new Array(len);
var j = 0;
for (var i = 0; i < len; ++i) {
if (booleans[i]) ret[j++] = values[i];
}
ret.length = j;
this._resolve(ret);
};
MappingPromiseArray.prototype.preservedValues = function () {
return this._preservedValues;
};
function map(promises, fn, options, _filter) {
if (typeof fn !== "function") {
return apiRejection("expecting a function but got " + util.classString(fn));
}
var limit = 0;
if (options !== undefined) {
if (typeof options === "object" && options !== null) {
if (typeof options.concurrency !== "number") {
return Promise.reject(
new TypeError("'concurrency' must be a number but it is " +
util.classString(options.concurrency)));
}
limit = options.concurrency;
} else {
return Promise.reject(new TypeError(
"options argument must be an object but it is " +
util.classString(options)));
}
}
limit = typeof limit === "number" &&
isFinite(limit) && limit >= 1 ? limit : 0;
return new MappingPromiseArray(promises, fn, limit, _filter).promise();
}
Promise.prototype.map = function (fn, options) {
return map(this, fn, options, null);
};
Promise.map = function (promises, fn, options, _filter) {
return map(promises, fn, options, _filter);
};
};

View File

@ -0,0 +1,55 @@
"use strict";
module.exports =
function(Promise, INTERNAL, tryConvertToPromise, apiRejection, debug) {
var util = require("./util");
var tryCatch = util.tryCatch;
Promise.method = function (fn) {
if (typeof fn !== "function") {
throw new Promise.TypeError("expecting a function but got " + util.classString(fn));
}
return function () {
var ret = new Promise(INTERNAL);
ret._captureStackTrace();
ret._pushContext();
var value = tryCatch(fn).apply(this, arguments);
var promiseCreated = ret._popContext();
debug.checkForgottenReturns(
value, promiseCreated, "Promise.method", ret);
ret._resolveFromSyncValue(value);
return ret;
};
};
Promise.attempt = Promise["try"] = function (fn) {
if (typeof fn !== "function") {
return apiRejection("expecting a function but got " + util.classString(fn));
}
var ret = new Promise(INTERNAL);
ret._captureStackTrace();
ret._pushContext();
var value;
if (arguments.length > 1) {
debug.deprecated("calling Promise.try with more than 1 argument");
var arg = arguments[1];
var ctx = arguments[2];
value = util.isArray(arg) ? tryCatch(fn).apply(ctx, arg)
: tryCatch(fn).call(ctx, arg);
} else {
value = tryCatch(fn)();
}
var promiseCreated = ret._popContext();
debug.checkForgottenReturns(
value, promiseCreated, "Promise.try", ret);
ret._resolveFromSyncValue(value);
return ret;
};
Promise.prototype._resolveFromSyncValue = function (value) {
if (value === util.errorObj) {
this._rejectCallback(value.e, false);
} else {
this._resolveCallback(value, true);
}
};
};

View File

@ -0,0 +1,51 @@
"use strict";
var util = require("./util");
var maybeWrapAsError = util.maybeWrapAsError;
var errors = require("./errors");
var OperationalError = errors.OperationalError;
var es5 = require("./es5");
function isUntypedError(obj) {
return obj instanceof Error &&
es5.getPrototypeOf(obj) === Error.prototype;
}
var rErrorKey = /^(?:name|message|stack|cause)$/;
function wrapAsOperationalError(obj) {
var ret;
if (isUntypedError(obj)) {
ret = new OperationalError(obj);
ret.name = obj.name;
ret.message = obj.message;
ret.stack = obj.stack;
var keys = es5.keys(obj);
for (var i = 0; i < keys.length; ++i) {
var key = keys[i];
if (!rErrorKey.test(key)) {
ret[key] = obj[key];
}
}
return ret;
}
util.markAsOriginatingFromRejection(obj);
return obj;
}
function nodebackForPromise(promise, multiArgs) {
return function(err, value) {
if (promise === null) return;
if (err) {
var wrapped = wrapAsOperationalError(maybeWrapAsError(err));
promise._attachExtraTrace(wrapped);
promise._reject(wrapped);
} else if (!multiArgs) {
promise._fulfill(value);
} else {
var $_len = arguments.length;var args = new Array(Math.max($_len - 1, 0)); for(var $_i = 1; $_i < $_len; ++$_i) {args[$_i - 1] = arguments[$_i];};
promise._fulfill(args);
}
promise = null;
};
}
module.exports = nodebackForPromise;

View File

@ -0,0 +1,58 @@
"use strict";
module.exports = function(Promise) {
var util = require("./util");
var async = Promise._async;
var tryCatch = util.tryCatch;
var errorObj = util.errorObj;
function spreadAdapter(val, nodeback) {
var promise = this;
if (!util.isArray(val)) return successAdapter.call(promise, val, nodeback);
var ret =
tryCatch(nodeback).apply(promise._boundValue(), [null].concat(val));
if (ret === errorObj) {
async.throwLater(ret.e);
}
}
function successAdapter(val, nodeback) {
var promise = this;
var receiver = promise._boundValue();
var ret = val === undefined
? tryCatch(nodeback).call(receiver, null)
: tryCatch(nodeback).call(receiver, null, val);
if (ret === errorObj) {
async.throwLater(ret.e);
}
}
function errorAdapter(reason, nodeback) {
var promise = this;
if (!reason) {
var newReason = new Error(reason + "");
newReason.cause = reason;
reason = newReason;
}
var ret = tryCatch(nodeback).call(promise._boundValue(), reason);
if (ret === errorObj) {
async.throwLater(ret.e);
}
}
Promise.prototype.asCallback = Promise.prototype.nodeify = function (nodeback,
options) {
if (typeof nodeback == "function") {
var adapter = successAdapter;
if (options !== undefined && Object(options).spread) {
adapter = spreadAdapter;
}
this._then(
adapter,
errorAdapter,
undefined,
this,
nodeback
);
}
return this;
};
};

View File

@ -0,0 +1,775 @@
"use strict";
module.exports = function() {
var makeSelfResolutionError = function () {
return new TypeError("circular promise resolution chain\u000a\u000a See http://goo.gl/MqrFmX\u000a");
};
var reflectHandler = function() {
return new Promise.PromiseInspection(this._target());
};
var apiRejection = function(msg) {
return Promise.reject(new TypeError(msg));
};
function Proxyable() {}
var UNDEFINED_BINDING = {};
var util = require("./util");
var getDomain;
if (util.isNode) {
getDomain = function() {
var ret = process.domain;
if (ret === undefined) ret = null;
return ret;
};
} else {
getDomain = function() {
return null;
};
}
util.notEnumerableProp(Promise, "_getDomain", getDomain);
var es5 = require("./es5");
var Async = require("./async");
var async = new Async();
es5.defineProperty(Promise, "_async", {value: async});
var errors = require("./errors");
var TypeError = Promise.TypeError = errors.TypeError;
Promise.RangeError = errors.RangeError;
var CancellationError = Promise.CancellationError = errors.CancellationError;
Promise.TimeoutError = errors.TimeoutError;
Promise.OperationalError = errors.OperationalError;
Promise.RejectionError = errors.OperationalError;
Promise.AggregateError = errors.AggregateError;
var INTERNAL = function(){};
var APPLY = {};
var NEXT_FILTER = {};
var tryConvertToPromise = require("./thenables")(Promise, INTERNAL);
var PromiseArray =
require("./promise_array")(Promise, INTERNAL,
tryConvertToPromise, apiRejection, Proxyable);
var Context = require("./context")(Promise);
/*jshint unused:false*/
var createContext = Context.create;
var debug = require("./debuggability")(Promise, Context);
var CapturedTrace = debug.CapturedTrace;
var PassThroughHandlerContext =
require("./finally")(Promise, tryConvertToPromise, NEXT_FILTER);
var catchFilter = require("./catch_filter")(NEXT_FILTER);
var nodebackForPromise = require("./nodeback");
var errorObj = util.errorObj;
var tryCatch = util.tryCatch;
function check(self, executor) {
if (self == null || self.constructor !== Promise) {
throw new TypeError("the promise constructor cannot be invoked directly\u000a\u000a See http://goo.gl/MqrFmX\u000a");
}
if (typeof executor !== "function") {
throw new TypeError("expecting a function but got " + util.classString(executor));
}
}
function Promise(executor) {
if (executor !== INTERNAL) {
check(this, executor);
}
this._bitField = 0;
this._fulfillmentHandler0 = undefined;
this._rejectionHandler0 = undefined;
this._promise0 = undefined;
this._receiver0 = undefined;
this._resolveFromExecutor(executor);
this._promiseCreated();
this._fireEvent("promiseCreated", this);
}
Promise.prototype.toString = function () {
return "[object Promise]";
};
Promise.prototype.caught = Promise.prototype["catch"] = function (fn) {
var len = arguments.length;
if (len > 1) {
var catchInstances = new Array(len - 1),
j = 0, i;
for (i = 0; i < len - 1; ++i) {
var item = arguments[i];
if (util.isObject(item)) {
catchInstances[j++] = item;
} else {
return apiRejection("Catch statement predicate: " +
"expecting an object but got " + util.classString(item));
}
}
catchInstances.length = j;
fn = arguments[i];
return this.then(undefined, catchFilter(catchInstances, fn, this));
}
return this.then(undefined, fn);
};
Promise.prototype.reflect = function () {
return this._then(reflectHandler,
reflectHandler, undefined, this, undefined);
};
Promise.prototype.then = function (didFulfill, didReject) {
if (debug.warnings() && arguments.length > 0 &&
typeof didFulfill !== "function" &&
typeof didReject !== "function") {
var msg = ".then() only accepts functions but was passed: " +
util.classString(didFulfill);
if (arguments.length > 1) {
msg += ", " + util.classString(didReject);
}
this._warn(msg);
}
return this._then(didFulfill, didReject, undefined, undefined, undefined);
};
Promise.prototype.done = function (didFulfill, didReject) {
var promise =
this._then(didFulfill, didReject, undefined, undefined, undefined);
promise._setIsFinal();
};
Promise.prototype.spread = function (fn) {
if (typeof fn !== "function") {
return apiRejection("expecting a function but got " + util.classString(fn));
}
return this.all()._then(fn, undefined, undefined, APPLY, undefined);
};
Promise.prototype.toJSON = function () {
var ret = {
isFulfilled: false,
isRejected: false,
fulfillmentValue: undefined,
rejectionReason: undefined
};
if (this.isFulfilled()) {
ret.fulfillmentValue = this.value();
ret.isFulfilled = true;
} else if (this.isRejected()) {
ret.rejectionReason = this.reason();
ret.isRejected = true;
}
return ret;
};
Promise.prototype.all = function () {
if (arguments.length > 0) {
this._warn(".all() was passed arguments but it does not take any");
}
return new PromiseArray(this).promise();
};
Promise.prototype.error = function (fn) {
return this.caught(util.originatesFromRejection, fn);
};
Promise.getNewLibraryCopy = module.exports;
Promise.is = function (val) {
return val instanceof Promise;
};
Promise.fromNode = Promise.fromCallback = function(fn) {
var ret = new Promise(INTERNAL);
ret._captureStackTrace();
var multiArgs = arguments.length > 1 ? !!Object(arguments[1]).multiArgs
: false;
var result = tryCatch(fn)(nodebackForPromise(ret, multiArgs));
if (result === errorObj) {
ret._rejectCallback(result.e, true);
}
if (!ret._isFateSealed()) ret._setAsyncGuaranteed();
return ret;
};
Promise.all = function (promises) {
return new PromiseArray(promises).promise();
};
Promise.cast = function (obj) {
var ret = tryConvertToPromise(obj);
if (!(ret instanceof Promise)) {
ret = new Promise(INTERNAL);
ret._captureStackTrace();
ret._setFulfilled();
ret._rejectionHandler0 = obj;
}
return ret;
};
Promise.resolve = Promise.fulfilled = Promise.cast;
Promise.reject = Promise.rejected = function (reason) {
var ret = new Promise(INTERNAL);
ret._captureStackTrace();
ret._rejectCallback(reason, true);
return ret;
};
Promise.setScheduler = function(fn) {
if (typeof fn !== "function") {
throw new TypeError("expecting a function but got " + util.classString(fn));
}
return async.setScheduler(fn);
};
Promise.prototype._then = function (
didFulfill,
didReject,
_, receiver,
internalData
) {
var haveInternalData = internalData !== undefined;
var promise = haveInternalData ? internalData : new Promise(INTERNAL);
var target = this._target();
var bitField = target._bitField;
if (!haveInternalData) {
promise._propagateFrom(this, 3);
promise._captureStackTrace();
if (receiver === undefined &&
((this._bitField & 2097152) !== 0)) {
if (!((bitField & 50397184) === 0)) {
receiver = this._boundValue();
} else {
receiver = target === this ? undefined : this._boundTo;
}
}
this._fireEvent("promiseChained", this, promise);
}
var domain = getDomain();
if (!((bitField & 50397184) === 0)) {
var handler, value, settler = target._settlePromiseCtx;
if (((bitField & 33554432) !== 0)) {
value = target._rejectionHandler0;
handler = didFulfill;
} else if (((bitField & 16777216) !== 0)) {
value = target._fulfillmentHandler0;
handler = didReject;
target._unsetRejectionIsUnhandled();
} else {
settler = target._settlePromiseLateCancellationObserver;
value = new CancellationError("late cancellation observer");
target._attachExtraTrace(value);
handler = didReject;
}
async.invoke(settler, target, {
handler: domain === null ? handler
: (typeof handler === "function" &&
util.domainBind(domain, handler)),
promise: promise,
receiver: receiver,
value: value
});
} else {
target._addCallbacks(didFulfill, didReject, promise, receiver, domain);
}
return promise;
};
Promise.prototype._length = function () {
return this._bitField & 65535;
};
Promise.prototype._isFateSealed = function () {
return (this._bitField & 117506048) !== 0;
};
Promise.prototype._isFollowing = function () {
return (this._bitField & 67108864) === 67108864;
};
Promise.prototype._setLength = function (len) {
this._bitField = (this._bitField & -65536) |
(len & 65535);
};
Promise.prototype._setFulfilled = function () {
this._bitField = this._bitField | 33554432;
this._fireEvent("promiseFulfilled", this);
};
Promise.prototype._setRejected = function () {
this._bitField = this._bitField | 16777216;
this._fireEvent("promiseRejected", this);
};
Promise.prototype._setFollowing = function () {
this._bitField = this._bitField | 67108864;
this._fireEvent("promiseResolved", this);
};
Promise.prototype._setIsFinal = function () {
this._bitField = this._bitField | 4194304;
};
Promise.prototype._isFinal = function () {
return (this._bitField & 4194304) > 0;
};
Promise.prototype._unsetCancelled = function() {
this._bitField = this._bitField & (~65536);
};
Promise.prototype._setCancelled = function() {
this._bitField = this._bitField | 65536;
this._fireEvent("promiseCancelled", this);
};
Promise.prototype._setWillBeCancelled = function() {
this._bitField = this._bitField | 8388608;
};
Promise.prototype._setAsyncGuaranteed = function() {
if (async.hasCustomScheduler()) return;
this._bitField = this._bitField | 134217728;
};
Promise.prototype._receiverAt = function (index) {
var ret = index === 0 ? this._receiver0 : this[
index * 4 - 4 + 3];
if (ret === UNDEFINED_BINDING) {
return undefined;
} else if (ret === undefined && this._isBound()) {
return this._boundValue();
}
return ret;
};
Promise.prototype._promiseAt = function (index) {
return this[
index * 4 - 4 + 2];
};
Promise.prototype._fulfillmentHandlerAt = function (index) {
return this[
index * 4 - 4 + 0];
};
Promise.prototype._rejectionHandlerAt = function (index) {
return this[
index * 4 - 4 + 1];
};
Promise.prototype._boundValue = function() {};
Promise.prototype._migrateCallback0 = function (follower) {
var bitField = follower._bitField;
var fulfill = follower._fulfillmentHandler0;
var reject = follower._rejectionHandler0;
var promise = follower._promise0;
var receiver = follower._receiverAt(0);
if (receiver === undefined) receiver = UNDEFINED_BINDING;
this._addCallbacks(fulfill, reject, promise, receiver, null);
};
Promise.prototype._migrateCallbackAt = function (follower, index) {
var fulfill = follower._fulfillmentHandlerAt(index);
var reject = follower._rejectionHandlerAt(index);
var promise = follower._promiseAt(index);
var receiver = follower._receiverAt(index);
if (receiver === undefined) receiver = UNDEFINED_BINDING;
this._addCallbacks(fulfill, reject, promise, receiver, null);
};
Promise.prototype._addCallbacks = function (
fulfill,
reject,
promise,
receiver,
domain
) {
var index = this._length();
if (index >= 65535 - 4) {
index = 0;
this._setLength(0);
}
if (index === 0) {
this._promise0 = promise;
this._receiver0 = receiver;
if (typeof fulfill === "function") {
this._fulfillmentHandler0 =
domain === null ? fulfill : util.domainBind(domain, fulfill);
}
if (typeof reject === "function") {
this._rejectionHandler0 =
domain === null ? reject : util.domainBind(domain, reject);
}
} else {
var base = index * 4 - 4;
this[base + 2] = promise;
this[base + 3] = receiver;
if (typeof fulfill === "function") {
this[base + 0] =
domain === null ? fulfill : util.domainBind(domain, fulfill);
}
if (typeof reject === "function") {
this[base + 1] =
domain === null ? reject : util.domainBind(domain, reject);
}
}
this._setLength(index + 1);
return index;
};
Promise.prototype._proxy = function (proxyable, arg) {
this._addCallbacks(undefined, undefined, arg, proxyable, null);
};
Promise.prototype._resolveCallback = function(value, shouldBind) {
if (((this._bitField & 117506048) !== 0)) return;
if (value === this)
return this._rejectCallback(makeSelfResolutionError(), false);
var maybePromise = tryConvertToPromise(value, this);
if (!(maybePromise instanceof Promise)) return this._fulfill(value);
if (shouldBind) this._propagateFrom(maybePromise, 2);
var promise = maybePromise._target();
if (promise === this) {
this._reject(makeSelfResolutionError());
return;
}
var bitField = promise._bitField;
if (((bitField & 50397184) === 0)) {
var len = this._length();
if (len > 0) promise._migrateCallback0(this);
for (var i = 1; i < len; ++i) {
promise._migrateCallbackAt(this, i);
}
this._setFollowing();
this._setLength(0);
this._setFollowee(promise);
} else if (((bitField & 33554432) !== 0)) {
this._fulfill(promise._value());
} else if (((bitField & 16777216) !== 0)) {
this._reject(promise._reason());
} else {
var reason = new CancellationError("late cancellation observer");
promise._attachExtraTrace(reason);
this._reject(reason);
}
};
Promise.prototype._rejectCallback =
function(reason, synchronous, ignoreNonErrorWarnings) {
var trace = util.ensureErrorObject(reason);
var hasStack = trace === reason;
if (!hasStack && !ignoreNonErrorWarnings && debug.warnings()) {
var message = "a promise was rejected with a non-error: " +
util.classString(reason);
this._warn(message, true);
}
this._attachExtraTrace(trace, synchronous ? hasStack : false);
this._reject(reason);
};
Promise.prototype._resolveFromExecutor = function (executor) {
if (executor === INTERNAL) return;
var promise = this;
this._captureStackTrace();
this._pushContext();
var synchronous = true;
var r = this._execute(executor, function(value) {
promise._resolveCallback(value);
}, function (reason) {
promise._rejectCallback(reason, synchronous);
});
synchronous = false;
this._popContext();
if (r !== undefined) {
promise._rejectCallback(r, true);
}
};
Promise.prototype._settlePromiseFromHandler = function (
handler, receiver, value, promise
) {
var bitField = promise._bitField;
if (((bitField & 65536) !== 0)) return;
promise._pushContext();
var x;
if (receiver === APPLY) {
if (!value || typeof value.length !== "number") {
x = errorObj;
x.e = new TypeError("cannot .spread() a non-array: " +
util.classString(value));
} else {
x = tryCatch(handler).apply(this._boundValue(), value);
}
} else {
x = tryCatch(handler).call(receiver, value);
}
var promiseCreated = promise._popContext();
bitField = promise._bitField;
if (((bitField & 65536) !== 0)) return;
if (x === NEXT_FILTER) {
promise._reject(value);
} else if (x === errorObj) {
promise._rejectCallback(x.e, false);
} else {
debug.checkForgottenReturns(x, promiseCreated, "", promise, this);
promise._resolveCallback(x);
}
};
Promise.prototype._target = function() {
var ret = this;
while (ret._isFollowing()) ret = ret._followee();
return ret;
};
Promise.prototype._followee = function() {
return this._rejectionHandler0;
};
Promise.prototype._setFollowee = function(promise) {
this._rejectionHandler0 = promise;
};
Promise.prototype._settlePromise = function(promise, handler, receiver, value) {
var isPromise = promise instanceof Promise;
var bitField = this._bitField;
var asyncGuaranteed = ((bitField & 134217728) !== 0);
if (((bitField & 65536) !== 0)) {
if (isPromise) promise._invokeInternalOnCancel();
if (receiver instanceof PassThroughHandlerContext &&
receiver.isFinallyHandler()) {
receiver.cancelPromise = promise;
if (tryCatch(handler).call(receiver, value) === errorObj) {
promise._reject(errorObj.e);
}
} else if (handler === reflectHandler) {
promise._fulfill(reflectHandler.call(receiver));
} else if (receiver instanceof Proxyable) {
receiver._promiseCancelled(promise);
} else if (isPromise || promise instanceof PromiseArray) {
promise._cancel();
} else {
receiver.cancel();
}
} else if (typeof handler === "function") {
if (!isPromise) {
handler.call(receiver, value, promise);
} else {
if (asyncGuaranteed) promise._setAsyncGuaranteed();
this._settlePromiseFromHandler(handler, receiver, value, promise);
}
} else if (receiver instanceof Proxyable) {
if (!receiver._isResolved()) {
if (((bitField & 33554432) !== 0)) {
receiver._promiseFulfilled(value, promise);
} else {
receiver._promiseRejected(value, promise);
}
}
} else if (isPromise) {
if (asyncGuaranteed) promise._setAsyncGuaranteed();
if (((bitField & 33554432) !== 0)) {
promise._fulfill(value);
} else {
promise._reject(value);
}
}
};
Promise.prototype._settlePromiseLateCancellationObserver = function(ctx) {
var handler = ctx.handler;
var promise = ctx.promise;
var receiver = ctx.receiver;
var value = ctx.value;
if (typeof handler === "function") {
if (!(promise instanceof Promise)) {
handler.call(receiver, value, promise);
} else {
this._settlePromiseFromHandler(handler, receiver, value, promise);
}
} else if (promise instanceof Promise) {
promise._reject(value);
}
};
Promise.prototype._settlePromiseCtx = function(ctx) {
this._settlePromise(ctx.promise, ctx.handler, ctx.receiver, ctx.value);
};
Promise.prototype._settlePromise0 = function(handler, value, bitField) {
var promise = this._promise0;
var receiver = this._receiverAt(0);
this._promise0 = undefined;
this._receiver0 = undefined;
this._settlePromise(promise, handler, receiver, value);
};
Promise.prototype._clearCallbackDataAtIndex = function(index) {
var base = index * 4 - 4;
this[base + 2] =
this[base + 3] =
this[base + 0] =
this[base + 1] = undefined;
};
Promise.prototype._fulfill = function (value) {
var bitField = this._bitField;
if (((bitField & 117506048) >>> 16)) return;
if (value === this) {
var err = makeSelfResolutionError();
this._attachExtraTrace(err);
return this._reject(err);
}
this._setFulfilled();
this._rejectionHandler0 = value;
if ((bitField & 65535) > 0) {
if (((bitField & 134217728) !== 0)) {
this._settlePromises();
} else {
async.settlePromises(this);
}
}
};
Promise.prototype._reject = function (reason) {
var bitField = this._bitField;
if (((bitField & 117506048) >>> 16)) return;
this._setRejected();
this._fulfillmentHandler0 = reason;
if (this._isFinal()) {
return async.fatalError(reason, util.isNode);
}
if ((bitField & 65535) > 0) {
async.settlePromises(this);
} else {
this._ensurePossibleRejectionHandled();
}
};
Promise.prototype._fulfillPromises = function (len, value) {
for (var i = 1; i < len; i++) {
var handler = this._fulfillmentHandlerAt(i);
var promise = this._promiseAt(i);
var receiver = this._receiverAt(i);
this._clearCallbackDataAtIndex(i);
this._settlePromise(promise, handler, receiver, value);
}
};
Promise.prototype._rejectPromises = function (len, reason) {
for (var i = 1; i < len; i++) {
var handler = this._rejectionHandlerAt(i);
var promise = this._promiseAt(i);
var receiver = this._receiverAt(i);
this._clearCallbackDataAtIndex(i);
this._settlePromise(promise, handler, receiver, reason);
}
};
Promise.prototype._settlePromises = function () {
var bitField = this._bitField;
var len = (bitField & 65535);
if (len > 0) {
if (((bitField & 16842752) !== 0)) {
var reason = this._fulfillmentHandler0;
this._settlePromise0(this._rejectionHandler0, reason, bitField);
this._rejectPromises(len, reason);
} else {
var value = this._rejectionHandler0;
this._settlePromise0(this._fulfillmentHandler0, value, bitField);
this._fulfillPromises(len, value);
}
this._setLength(0);
}
this._clearCancellationData();
};
Promise.prototype._settledValue = function() {
var bitField = this._bitField;
if (((bitField & 33554432) !== 0)) {
return this._rejectionHandler0;
} else if (((bitField & 16777216) !== 0)) {
return this._fulfillmentHandler0;
}
};
function deferResolve(v) {this.promise._resolveCallback(v);}
function deferReject(v) {this.promise._rejectCallback(v, false);}
Promise.defer = Promise.pending = function() {
debug.deprecated("Promise.defer", "new Promise");
var promise = new Promise(INTERNAL);
return {
promise: promise,
resolve: deferResolve,
reject: deferReject
};
};
util.notEnumerableProp(Promise,
"_makeSelfResolutionError",
makeSelfResolutionError);
require("./method")(Promise, INTERNAL, tryConvertToPromise, apiRejection,
debug);
require("./bind")(Promise, INTERNAL, tryConvertToPromise, debug);
require("./cancel")(Promise, PromiseArray, apiRejection, debug);
require("./direct_resolve")(Promise);
require("./synchronous_inspection")(Promise);
require("./join")(
Promise, PromiseArray, tryConvertToPromise, INTERNAL, async, getDomain);
Promise.Promise = Promise;
Promise.version = "3.5.0";
require('./map.js')(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL, debug);
require('./call_get.js')(Promise);
require('./using.js')(Promise, apiRejection, tryConvertToPromise, createContext, INTERNAL, debug);
require('./timers.js')(Promise, INTERNAL, debug);
require('./generators.js')(Promise, apiRejection, INTERNAL, tryConvertToPromise, Proxyable, debug);
require('./nodeify.js')(Promise);
require('./promisify.js')(Promise, INTERNAL);
require('./props.js')(Promise, PromiseArray, tryConvertToPromise, apiRejection);
require('./race.js')(Promise, INTERNAL, tryConvertToPromise, apiRejection);
require('./reduce.js')(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL, debug);
require('./settle.js')(Promise, PromiseArray, debug);
require('./some.js')(Promise, PromiseArray, apiRejection);
require('./filter.js')(Promise, INTERNAL);
require('./each.js')(Promise, INTERNAL);
require('./any.js')(Promise);
util.toFastProperties(Promise);
util.toFastProperties(Promise.prototype);
function fillTypes(value) {
var p = new Promise(INTERNAL);
p._fulfillmentHandler0 = value;
p._rejectionHandler0 = value;
p._promise0 = value;
p._receiver0 = value;
}
// Complete slack tracking, opt out of field-type tracking and
// stabilize map
fillTypes({a: 1});
fillTypes({b: 2});
fillTypes({c: 3});
fillTypes(1);
fillTypes(function(){});
fillTypes(undefined);
fillTypes(false);
fillTypes(new Promise(INTERNAL));
debug.setBounds(Async.firstLineError, util.lastLineError);
return Promise;
};

View File

@ -0,0 +1,185 @@
"use strict";
module.exports = function(Promise, INTERNAL, tryConvertToPromise,
apiRejection, Proxyable) {
var util = require("./util");
var isArray = util.isArray;
function toResolutionValue(val) {
switch(val) {
case -2: return [];
case -3: return {};
case -6: return new Map();
}
}
function PromiseArray(values) {
var promise = this._promise = new Promise(INTERNAL);
if (values instanceof Promise) {
promise._propagateFrom(values, 3);
}
promise._setOnCancel(this);
this._values = values;
this._length = 0;
this._totalResolved = 0;
this._init(undefined, -2);
}
util.inherits(PromiseArray, Proxyable);
PromiseArray.prototype.length = function () {
return this._length;
};
PromiseArray.prototype.promise = function () {
return this._promise;
};
PromiseArray.prototype._init = function init(_, resolveValueIfEmpty) {
var values = tryConvertToPromise(this._values, this._promise);
if (values instanceof Promise) {
values = values._target();
var bitField = values._bitField;
;
this._values = values;
if (((bitField & 50397184) === 0)) {
this._promise._setAsyncGuaranteed();
return values._then(
init,
this._reject,
undefined,
this,
resolveValueIfEmpty
);
} else if (((bitField & 33554432) !== 0)) {
values = values._value();
} else if (((bitField & 16777216) !== 0)) {
return this._reject(values._reason());
} else {
return this._cancel();
}
}
values = util.asArray(values);
if (values === null) {
var err = apiRejection(
"expecting an array or an iterable object but got " + util.classString(values)).reason();
this._promise._rejectCallback(err, false);
return;
}
if (values.length === 0) {
if (resolveValueIfEmpty === -5) {
this._resolveEmptyArray();
}
else {
this._resolve(toResolutionValue(resolveValueIfEmpty));
}
return;
}
this._iterate(values);
};
PromiseArray.prototype._iterate = function(values) {
var len = this.getActualLength(values.length);
this._length = len;
this._values = this.shouldCopyValues() ? new Array(len) : this._values;
var result = this._promise;
var isResolved = false;
var bitField = null;
for (var i = 0; i < len; ++i) {
var maybePromise = tryConvertToPromise(values[i], result);
if (maybePromise instanceof Promise) {
maybePromise = maybePromise._target();
bitField = maybePromise._bitField;
} else {
bitField = null;
}
if (isResolved) {
if (bitField !== null) {
maybePromise.suppressUnhandledRejections();
}
} else if (bitField !== null) {
if (((bitField & 50397184) === 0)) {
maybePromise._proxy(this, i);
this._values[i] = maybePromise;
} else if (((bitField & 33554432) !== 0)) {
isResolved = this._promiseFulfilled(maybePromise._value(), i);
} else if (((bitField & 16777216) !== 0)) {
isResolved = this._promiseRejected(maybePromise._reason(), i);
} else {
isResolved = this._promiseCancelled(i);
}
} else {
isResolved = this._promiseFulfilled(maybePromise, i);
}
}
if (!isResolved) result._setAsyncGuaranteed();
};
PromiseArray.prototype._isResolved = function () {
return this._values === null;
};
PromiseArray.prototype._resolve = function (value) {
this._values = null;
this._promise._fulfill(value);
};
PromiseArray.prototype._cancel = function() {
if (this._isResolved() || !this._promise._isCancellable()) return;
this._values = null;
this._promise._cancel();
};
PromiseArray.prototype._reject = function (reason) {
this._values = null;
this._promise._rejectCallback(reason, false);
};
PromiseArray.prototype._promiseFulfilled = function (value, index) {
this._values[index] = value;
var totalResolved = ++this._totalResolved;
if (totalResolved >= this._length) {
this._resolve(this._values);
return true;
}
return false;
};
PromiseArray.prototype._promiseCancelled = function() {
this._cancel();
return true;
};
PromiseArray.prototype._promiseRejected = function (reason) {
this._totalResolved++;
this._reject(reason);
return true;
};
PromiseArray.prototype._resultCancelled = function() {
if (this._isResolved()) return;
var values = this._values;
this._cancel();
if (values instanceof Promise) {
values.cancel();
} else {
for (var i = 0; i < values.length; ++i) {
if (values[i] instanceof Promise) {
values[i].cancel();
}
}
}
};
PromiseArray.prototype.shouldCopyValues = function () {
return true;
};
PromiseArray.prototype.getActualLength = function (len) {
return len;
};
return PromiseArray;
};

View File

@ -0,0 +1,314 @@
"use strict";
module.exports = function(Promise, INTERNAL) {
var THIS = {};
var util = require("./util");
var nodebackForPromise = require("./nodeback");
var withAppended = util.withAppended;
var maybeWrapAsError = util.maybeWrapAsError;
var canEvaluate = util.canEvaluate;
var TypeError = require("./errors").TypeError;
var defaultSuffix = "Async";
var defaultPromisified = {__isPromisified__: true};
var noCopyProps = [
"arity", "length",
"name",
"arguments",
"caller",
"callee",
"prototype",
"__isPromisified__"
];
var noCopyPropsPattern = new RegExp("^(?:" + noCopyProps.join("|") + ")$");
var defaultFilter = function(name) {
return util.isIdentifier(name) &&
name.charAt(0) !== "_" &&
name !== "constructor";
};
function propsFilter(key) {
return !noCopyPropsPattern.test(key);
}
function isPromisified(fn) {
try {
return fn.__isPromisified__ === true;
}
catch (e) {
return false;
}
}
function hasPromisified(obj, key, suffix) {
var val = util.getDataPropertyOrDefault(obj, key + suffix,
defaultPromisified);
return val ? isPromisified(val) : false;
}
function checkValid(ret, suffix, suffixRegexp) {
for (var i = 0; i < ret.length; i += 2) {
var key = ret[i];
if (suffixRegexp.test(key)) {
var keyWithoutAsyncSuffix = key.replace(suffixRegexp, "");
for (var j = 0; j < ret.length; j += 2) {
if (ret[j] === keyWithoutAsyncSuffix) {
throw new TypeError("Cannot promisify an API that has normal methods with '%s'-suffix\u000a\u000a See http://goo.gl/MqrFmX\u000a"
.replace("%s", suffix));
}
}
}
}
}
function promisifiableMethods(obj, suffix, suffixRegexp, filter) {
var keys = util.inheritedDataKeys(obj);
var ret = [];
for (var i = 0; i < keys.length; ++i) {
var key = keys[i];
var value = obj[key];
var passesDefaultFilter = filter === defaultFilter
? true : defaultFilter(key, value, obj);
if (typeof value === "function" &&
!isPromisified(value) &&
!hasPromisified(obj, key, suffix) &&
filter(key, value, obj, passesDefaultFilter)) {
ret.push(key, value);
}
}
checkValid(ret, suffix, suffixRegexp);
return ret;
}
var escapeIdentRegex = function(str) {
return str.replace(/([$])/, "\\$");
};
var makeNodePromisifiedEval;
if (!false) {
var switchCaseArgumentOrder = function(likelyArgumentCount) {
var ret = [likelyArgumentCount];
var min = Math.max(0, likelyArgumentCount - 1 - 3);
for(var i = likelyArgumentCount - 1; i >= min; --i) {
ret.push(i);
}
for(var i = likelyArgumentCount + 1; i <= 3; ++i) {
ret.push(i);
}
return ret;
};
var argumentSequence = function(argumentCount) {
return util.filledRange(argumentCount, "_arg", "");
};
var parameterDeclaration = function(parameterCount) {
return util.filledRange(
Math.max(parameterCount, 3), "_arg", "");
};
var parameterCount = function(fn) {
if (typeof fn.length === "number") {
return Math.max(Math.min(fn.length, 1023 + 1), 0);
}
return 0;
};
makeNodePromisifiedEval =
function(callback, receiver, originalName, fn, _, multiArgs) {
var newParameterCount = Math.max(0, parameterCount(fn) - 1);
var argumentOrder = switchCaseArgumentOrder(newParameterCount);
var shouldProxyThis = typeof callback === "string" || receiver === THIS;
function generateCallForArgumentCount(count) {
var args = argumentSequence(count).join(", ");
var comma = count > 0 ? ", " : "";
var ret;
if (shouldProxyThis) {
ret = "ret = callback.call(this, {{args}}, nodeback); break;\n";
} else {
ret = receiver === undefined
? "ret = callback({{args}}, nodeback); break;\n"
: "ret = callback.call(receiver, {{args}}, nodeback); break;\n";
}
return ret.replace("{{args}}", args).replace(", ", comma);
}
function generateArgumentSwitchCase() {
var ret = "";
for (var i = 0; i < argumentOrder.length; ++i) {
ret += "case " + argumentOrder[i] +":" +
generateCallForArgumentCount(argumentOrder[i]);
}
ret += " \n\
default: \n\
var args = new Array(len + 1); \n\
var i = 0; \n\
for (var i = 0; i < len; ++i) { \n\
args[i] = arguments[i]; \n\
} \n\
args[i] = nodeback; \n\
[CodeForCall] \n\
break; \n\
".replace("[CodeForCall]", (shouldProxyThis
? "ret = callback.apply(this, args);\n"
: "ret = callback.apply(receiver, args);\n"));
return ret;
}
var getFunctionCode = typeof callback === "string"
? ("this != null ? this['"+callback+"'] : fn")
: "fn";
var body = "'use strict'; \n\
var ret = function (Parameters) { \n\
'use strict'; \n\
var len = arguments.length; \n\
var promise = new Promise(INTERNAL); \n\
promise._captureStackTrace(); \n\
var nodeback = nodebackForPromise(promise, " + multiArgs + "); \n\
var ret; \n\
var callback = tryCatch([GetFunctionCode]); \n\
switch(len) { \n\
[CodeForSwitchCase] \n\
} \n\
if (ret === errorObj) { \n\
promise._rejectCallback(maybeWrapAsError(ret.e), true, true);\n\
} \n\
if (!promise._isFateSealed()) promise._setAsyncGuaranteed(); \n\
return promise; \n\
}; \n\
notEnumerableProp(ret, '__isPromisified__', true); \n\
return ret; \n\
".replace("[CodeForSwitchCase]", generateArgumentSwitchCase())
.replace("[GetFunctionCode]", getFunctionCode);
body = body.replace("Parameters", parameterDeclaration(newParameterCount));
return new Function("Promise",
"fn",
"receiver",
"withAppended",
"maybeWrapAsError",
"nodebackForPromise",
"tryCatch",
"errorObj",
"notEnumerableProp",
"INTERNAL",
body)(
Promise,
fn,
receiver,
withAppended,
maybeWrapAsError,
nodebackForPromise,
util.tryCatch,
util.errorObj,
util.notEnumerableProp,
INTERNAL);
};
}
function makeNodePromisifiedClosure(callback, receiver, _, fn, __, multiArgs) {
var defaultThis = (function() {return this;})();
var method = callback;
if (typeof method === "string") {
callback = fn;
}
function promisified() {
var _receiver = receiver;
if (receiver === THIS) _receiver = this;
var promise = new Promise(INTERNAL);
promise._captureStackTrace();
var cb = typeof method === "string" && this !== defaultThis
? this[method] : callback;
var fn = nodebackForPromise(promise, multiArgs);
try {
cb.apply(_receiver, withAppended(arguments, fn));
} catch(e) {
promise._rejectCallback(maybeWrapAsError(e), true, true);
}
if (!promise._isFateSealed()) promise._setAsyncGuaranteed();
return promise;
}
util.notEnumerableProp(promisified, "__isPromisified__", true);
return promisified;
}
var makeNodePromisified = canEvaluate
? makeNodePromisifiedEval
: makeNodePromisifiedClosure;
function promisifyAll(obj, suffix, filter, promisifier, multiArgs) {
var suffixRegexp = new RegExp(escapeIdentRegex(suffix) + "$");
var methods =
promisifiableMethods(obj, suffix, suffixRegexp, filter);
for (var i = 0, len = methods.length; i < len; i+= 2) {
var key = methods[i];
var fn = methods[i+1];
var promisifiedKey = key + suffix;
if (promisifier === makeNodePromisified) {
obj[promisifiedKey] =
makeNodePromisified(key, THIS, key, fn, suffix, multiArgs);
} else {
var promisified = promisifier(fn, function() {
return makeNodePromisified(key, THIS, key,
fn, suffix, multiArgs);
});
util.notEnumerableProp(promisified, "__isPromisified__", true);
obj[promisifiedKey] = promisified;
}
}
util.toFastProperties(obj);
return obj;
}
function promisify(callback, receiver, multiArgs) {
return makeNodePromisified(callback, receiver, undefined,
callback, null, multiArgs);
}
Promise.promisify = function (fn, options) {
if (typeof fn !== "function") {
throw new TypeError("expecting a function but got " + util.classString(fn));
}
if (isPromisified(fn)) {
return fn;
}
options = Object(options);
var receiver = options.context === undefined ? THIS : options.context;
var multiArgs = !!options.multiArgs;
var ret = promisify(fn, receiver, multiArgs);
util.copyDescriptors(fn, ret, propsFilter);
return ret;
};
Promise.promisifyAll = function (target, options) {
if (typeof target !== "function" && typeof target !== "object") {
throw new TypeError("the target of promisifyAll must be an object or a function\u000a\u000a See http://goo.gl/MqrFmX\u000a");
}
options = Object(options);
var multiArgs = !!options.multiArgs;
var suffix = options.suffix;
if (typeof suffix !== "string") suffix = defaultSuffix;
var filter = options.filter;
if (typeof filter !== "function") filter = defaultFilter;
var promisifier = options.promisifier;
if (typeof promisifier !== "function") promisifier = makeNodePromisified;
if (!util.isIdentifier(suffix)) {
throw new RangeError("suffix must be a valid identifier\u000a\u000a See http://goo.gl/MqrFmX\u000a");
}
var keys = util.inheritedDataKeys(target);
for (var i = 0; i < keys.length; ++i) {
var value = target[keys[i]];
if (keys[i] !== "constructor" &&
util.isClass(value)) {
promisifyAll(value.prototype, suffix, filter, promisifier,
multiArgs);
promisifyAll(value, suffix, filter, promisifier, multiArgs);
}
}
return promisifyAll(target, suffix, filter, promisifier, multiArgs);
};
};

View File

@ -0,0 +1,118 @@
"use strict";
module.exports = function(
Promise, PromiseArray, tryConvertToPromise, apiRejection) {
var util = require("./util");
var isObject = util.isObject;
var es5 = require("./es5");
var Es6Map;
if (typeof Map === "function") Es6Map = Map;
var mapToEntries = (function() {
var index = 0;
var size = 0;
function extractEntry(value, key) {
this[index] = value;
this[index + size] = key;
index++;
}
return function mapToEntries(map) {
size = map.size;
index = 0;
var ret = new Array(map.size * 2);
map.forEach(extractEntry, ret);
return ret;
};
})();
var entriesToMap = function(entries) {
var ret = new Es6Map();
var length = entries.length / 2 | 0;
for (var i = 0; i < length; ++i) {
var key = entries[length + i];
var value = entries[i];
ret.set(key, value);
}
return ret;
};
function PropertiesPromiseArray(obj) {
var isMap = false;
var entries;
if (Es6Map !== undefined && obj instanceof Es6Map) {
entries = mapToEntries(obj);
isMap = true;
} else {
var keys = es5.keys(obj);
var len = keys.length;
entries = new Array(len * 2);
for (var i = 0; i < len; ++i) {
var key = keys[i];
entries[i] = obj[key];
entries[i + len] = key;
}
}
this.constructor$(entries);
this._isMap = isMap;
this._init$(undefined, isMap ? -6 : -3);
}
util.inherits(PropertiesPromiseArray, PromiseArray);
PropertiesPromiseArray.prototype._init = function () {};
PropertiesPromiseArray.prototype._promiseFulfilled = function (value, index) {
this._values[index] = value;
var totalResolved = ++this._totalResolved;
if (totalResolved >= this._length) {
var val;
if (this._isMap) {
val = entriesToMap(this._values);
} else {
val = {};
var keyOffset = this.length();
for (var i = 0, len = this.length(); i < len; ++i) {
val[this._values[i + keyOffset]] = this._values[i];
}
}
this._resolve(val);
return true;
}
return false;
};
PropertiesPromiseArray.prototype.shouldCopyValues = function () {
return false;
};
PropertiesPromiseArray.prototype.getActualLength = function (len) {
return len >> 1;
};
function props(promises) {
var ret;
var castValue = tryConvertToPromise(promises);
if (!isObject(castValue)) {
return apiRejection("cannot await properties of a non-object\u000a\u000a See http://goo.gl/MqrFmX\u000a");
} else if (castValue instanceof Promise) {
ret = castValue._then(
Promise.props, undefined, undefined, undefined, undefined);
} else {
ret = new PropertiesPromiseArray(castValue).promise();
}
if (castValue instanceof Promise) {
ret._propagateFrom(castValue, 2);
}
return ret;
}
Promise.prototype.props = function () {
return props(this);
};
Promise.props = function (promises) {
return props(promises);
};
};

View File

@ -0,0 +1,73 @@
"use strict";
function arrayMove(src, srcIndex, dst, dstIndex, len) {
for (var j = 0; j < len; ++j) {
dst[j + dstIndex] = src[j + srcIndex];
src[j + srcIndex] = void 0;
}
}
function Queue(capacity) {
this._capacity = capacity;
this._length = 0;
this._front = 0;
}
Queue.prototype._willBeOverCapacity = function (size) {
return this._capacity < size;
};
Queue.prototype._pushOne = function (arg) {
var length = this.length();
this._checkCapacity(length + 1);
var i = (this._front + length) & (this._capacity - 1);
this[i] = arg;
this._length = length + 1;
};
Queue.prototype.push = function (fn, receiver, arg) {
var length = this.length() + 3;
if (this._willBeOverCapacity(length)) {
this._pushOne(fn);
this._pushOne(receiver);
this._pushOne(arg);
return;
}
var j = this._front + length - 3;
this._checkCapacity(length);
var wrapMask = this._capacity - 1;
this[(j + 0) & wrapMask] = fn;
this[(j + 1) & wrapMask] = receiver;
this[(j + 2) & wrapMask] = arg;
this._length = length;
};
Queue.prototype.shift = function () {
var front = this._front,
ret = this[front];
this[front] = undefined;
this._front = (front + 1) & (this._capacity - 1);
this._length--;
return ret;
};
Queue.prototype.length = function () {
return this._length;
};
Queue.prototype._checkCapacity = function (size) {
if (this._capacity < size) {
this._resizeTo(this._capacity << 1);
}
};
Queue.prototype._resizeTo = function (capacity) {
var oldCapacity = this._capacity;
this._capacity = capacity;
var front = this._front;
var length = this._length;
var moveItemsCount = (front + length) & (oldCapacity - 1);
arrayMove(this, 0, this, oldCapacity, moveItemsCount);
};
module.exports = Queue;

View File

@ -0,0 +1,49 @@
"use strict";
module.exports = function(
Promise, INTERNAL, tryConvertToPromise, apiRejection) {
var util = require("./util");
var raceLater = function (promise) {
return promise.then(function(array) {
return race(array, promise);
});
};
function race(promises, parent) {
var maybePromise = tryConvertToPromise(promises);
if (maybePromise instanceof Promise) {
return raceLater(maybePromise);
} else {
promises = util.asArray(promises);
if (promises === null)
return apiRejection("expecting an array or an iterable object but got " + util.classString(promises));
}
var ret = new Promise(INTERNAL);
if (parent !== undefined) {
ret._propagateFrom(parent, 3);
}
var fulfill = ret._fulfill;
var reject = ret._reject;
for (var i = 0, len = promises.length; i < len; ++i) {
var val = promises[i];
if (val === undefined && !(i in promises)) {
continue;
}
Promise.cast(val)._then(fulfill, reject, undefined, ret, null);
}
return ret;
}
Promise.race = function (promises) {
return race(promises, undefined);
};
Promise.prototype.race = function () {
return race(this, undefined);
};
};

View File

@ -0,0 +1,172 @@
"use strict";
module.exports = function(Promise,
PromiseArray,
apiRejection,
tryConvertToPromise,
INTERNAL,
debug) {
var getDomain = Promise._getDomain;
var util = require("./util");
var tryCatch = util.tryCatch;
function ReductionPromiseArray(promises, fn, initialValue, _each) {
this.constructor$(promises);
var domain = getDomain();
this._fn = domain === null ? fn : util.domainBind(domain, fn);
if (initialValue !== undefined) {
initialValue = Promise.resolve(initialValue);
initialValue._attachCancellationCallback(this);
}
this._initialValue = initialValue;
this._currentCancellable = null;
if(_each === INTERNAL) {
this._eachValues = Array(this._length);
} else if (_each === 0) {
this._eachValues = null;
} else {
this._eachValues = undefined;
}
this._promise._captureStackTrace();
this._init$(undefined, -5);
}
util.inherits(ReductionPromiseArray, PromiseArray);
ReductionPromiseArray.prototype._gotAccum = function(accum) {
if (this._eachValues !== undefined &&
this._eachValues !== null &&
accum !== INTERNAL) {
this._eachValues.push(accum);
}
};
ReductionPromiseArray.prototype._eachComplete = function(value) {
if (this._eachValues !== null) {
this._eachValues.push(value);
}
return this._eachValues;
};
ReductionPromiseArray.prototype._init = function() {};
ReductionPromiseArray.prototype._resolveEmptyArray = function() {
this._resolve(this._eachValues !== undefined ? this._eachValues
: this._initialValue);
};
ReductionPromiseArray.prototype.shouldCopyValues = function () {
return false;
};
ReductionPromiseArray.prototype._resolve = function(value) {
this._promise._resolveCallback(value);
this._values = null;
};
ReductionPromiseArray.prototype._resultCancelled = function(sender) {
if (sender === this._initialValue) return this._cancel();
if (this._isResolved()) return;
this._resultCancelled$();
if (this._currentCancellable instanceof Promise) {
this._currentCancellable.cancel();
}
if (this._initialValue instanceof Promise) {
this._initialValue.cancel();
}
};
ReductionPromiseArray.prototype._iterate = function (values) {
this._values = values;
var value;
var i;
var length = values.length;
if (this._initialValue !== undefined) {
value = this._initialValue;
i = 0;
} else {
value = Promise.resolve(values[0]);
i = 1;
}
this._currentCancellable = value;
if (!value.isRejected()) {
for (; i < length; ++i) {
var ctx = {
accum: null,
value: values[i],
index: i,
length: length,
array: this
};
value = value._then(gotAccum, undefined, undefined, ctx, undefined);
}
}
if (this._eachValues !== undefined) {
value = value
._then(this._eachComplete, undefined, undefined, this, undefined);
}
value._then(completed, completed, undefined, value, this);
};
Promise.prototype.reduce = function (fn, initialValue) {
return reduce(this, fn, initialValue, null);
};
Promise.reduce = function (promises, fn, initialValue, _each) {
return reduce(promises, fn, initialValue, _each);
};
function completed(valueOrReason, array) {
if (this.isFulfilled()) {
array._resolve(valueOrReason);
} else {
array._reject(valueOrReason);
}
}
function reduce(promises, fn, initialValue, _each) {
if (typeof fn !== "function") {
return apiRejection("expecting a function but got " + util.classString(fn));
}
var array = new ReductionPromiseArray(promises, fn, initialValue, _each);
return array.promise();
}
function gotAccum(accum) {
this.accum = accum;
this.array._gotAccum(accum);
var value = tryConvertToPromise(this.value, this.array._promise);
if (value instanceof Promise) {
this.array._currentCancellable = value;
return value._then(gotValue, undefined, undefined, this, undefined);
} else {
return gotValue.call(this, value);
}
}
function gotValue(value) {
var array = this.array;
var promise = array._promise;
var fn = tryCatch(array._fn);
promise._pushContext();
var ret;
if (array._eachValues !== undefined) {
ret = fn.call(promise._boundValue(), value, this.index, this.length);
} else {
ret = fn.call(promise._boundValue(),
this.accum, value, this.index, this.length);
}
if (ret instanceof Promise) {
array._currentCancellable = ret;
}
var promiseCreated = promise._popContext();
debug.checkForgottenReturns(
ret,
promiseCreated,
array._eachValues !== undefined ? "Promise.each" : "Promise.reduce",
promise
);
return ret;
}
};

View File

@ -0,0 +1,61 @@
"use strict";
var util = require("./util");
var schedule;
var noAsyncScheduler = function() {
throw new Error("No async scheduler available\u000a\u000a See http://goo.gl/MqrFmX\u000a");
};
var NativePromise = util.getNativePromise();
if (util.isNode && typeof MutationObserver === "undefined") {
var GlobalSetImmediate = global.setImmediate;
var ProcessNextTick = process.nextTick;
schedule = util.isRecentNode
? function(fn) { GlobalSetImmediate.call(global, fn); }
: function(fn) { ProcessNextTick.call(process, fn); };
} else if (typeof NativePromise === "function" &&
typeof NativePromise.resolve === "function") {
var nativePromise = NativePromise.resolve();
schedule = function(fn) {
nativePromise.then(fn);
};
} else if ((typeof MutationObserver !== "undefined") &&
!(typeof window !== "undefined" &&
window.navigator &&
(window.navigator.standalone || window.cordova))) {
schedule = (function() {
var div = document.createElement("div");
var opts = {attributes: true};
var toggleScheduled = false;
var div2 = document.createElement("div");
var o2 = new MutationObserver(function() {
div.classList.toggle("foo");
toggleScheduled = false;
});
o2.observe(div2, opts);
var scheduleToggle = function() {
if (toggleScheduled) return;
toggleScheduled = true;
div2.classList.toggle("foo");
};
return function schedule(fn) {
var o = new MutationObserver(function() {
o.disconnect();
fn();
});
o.observe(div, opts);
scheduleToggle();
};
})();
} else if (typeof setImmediate !== "undefined") {
schedule = function (fn) {
setImmediate(fn);
};
} else if (typeof setTimeout !== "undefined") {
schedule = function (fn) {
setTimeout(fn, 0);
};
} else {
schedule = noAsyncScheduler;
}
module.exports = schedule;

View File

@ -0,0 +1,43 @@
"use strict";
module.exports =
function(Promise, PromiseArray, debug) {
var PromiseInspection = Promise.PromiseInspection;
var util = require("./util");
function SettledPromiseArray(values) {
this.constructor$(values);
}
util.inherits(SettledPromiseArray, PromiseArray);
SettledPromiseArray.prototype._promiseResolved = function (index, inspection) {
this._values[index] = inspection;
var totalResolved = ++this._totalResolved;
if (totalResolved >= this._length) {
this._resolve(this._values);
return true;
}
return false;
};
SettledPromiseArray.prototype._promiseFulfilled = function (value, index) {
var ret = new PromiseInspection();
ret._bitField = 33554432;
ret._settledValueField = value;
return this._promiseResolved(index, ret);
};
SettledPromiseArray.prototype._promiseRejected = function (reason, index) {
var ret = new PromiseInspection();
ret._bitField = 16777216;
ret._settledValueField = reason;
return this._promiseResolved(index, ret);
};
Promise.settle = function (promises) {
debug.deprecated(".settle()", ".reflect()");
return new SettledPromiseArray(promises).promise();
};
Promise.prototype.settle = function () {
return Promise.settle(this);
};
};

View File

@ -0,0 +1,148 @@
"use strict";
module.exports =
function(Promise, PromiseArray, apiRejection) {
var util = require("./util");
var RangeError = require("./errors").RangeError;
var AggregateError = require("./errors").AggregateError;
var isArray = util.isArray;
var CANCELLATION = {};
function SomePromiseArray(values) {
this.constructor$(values);
this._howMany = 0;
this._unwrap = false;
this._initialized = false;
}
util.inherits(SomePromiseArray, PromiseArray);
SomePromiseArray.prototype._init = function () {
if (!this._initialized) {
return;
}
if (this._howMany === 0) {
this._resolve([]);
return;
}
this._init$(undefined, -5);
var isArrayResolved = isArray(this._values);
if (!this._isResolved() &&
isArrayResolved &&
this._howMany > this._canPossiblyFulfill()) {
this._reject(this._getRangeError(this.length()));
}
};
SomePromiseArray.prototype.init = function () {
this._initialized = true;
this._init();
};
SomePromiseArray.prototype.setUnwrap = function () {
this._unwrap = true;
};
SomePromiseArray.prototype.howMany = function () {
return this._howMany;
};
SomePromiseArray.prototype.setHowMany = function (count) {
this._howMany = count;
};
SomePromiseArray.prototype._promiseFulfilled = function (value) {
this._addFulfilled(value);
if (this._fulfilled() === this.howMany()) {
this._values.length = this.howMany();
if (this.howMany() === 1 && this._unwrap) {
this._resolve(this._values[0]);
} else {
this._resolve(this._values);
}
return true;
}
return false;
};
SomePromiseArray.prototype._promiseRejected = function (reason) {
this._addRejected(reason);
return this._checkOutcome();
};
SomePromiseArray.prototype._promiseCancelled = function () {
if (this._values instanceof Promise || this._values == null) {
return this._cancel();
}
this._addRejected(CANCELLATION);
return this._checkOutcome();
};
SomePromiseArray.prototype._checkOutcome = function() {
if (this.howMany() > this._canPossiblyFulfill()) {
var e = new AggregateError();
for (var i = this.length(); i < this._values.length; ++i) {
if (this._values[i] !== CANCELLATION) {
e.push(this._values[i]);
}
}
if (e.length > 0) {
this._reject(e);
} else {
this._cancel();
}
return true;
}
return false;
};
SomePromiseArray.prototype._fulfilled = function () {
return this._totalResolved;
};
SomePromiseArray.prototype._rejected = function () {
return this._values.length - this.length();
};
SomePromiseArray.prototype._addRejected = function (reason) {
this._values.push(reason);
};
SomePromiseArray.prototype._addFulfilled = function (value) {
this._values[this._totalResolved++] = value;
};
SomePromiseArray.prototype._canPossiblyFulfill = function () {
return this.length() - this._rejected();
};
SomePromiseArray.prototype._getRangeError = function (count) {
var message = "Input array must contain at least " +
this._howMany + " items but contains only " + count + " items";
return new RangeError(message);
};
SomePromiseArray.prototype._resolveEmptyArray = function () {
this._reject(this._getRangeError(0));
};
function some(promises, howMany) {
if ((howMany | 0) !== howMany || howMany < 0) {
return apiRejection("expecting a positive integer\u000a\u000a See http://goo.gl/MqrFmX\u000a");
}
var ret = new SomePromiseArray(promises);
var promise = ret.promise();
ret.setHowMany(howMany);
ret.init();
return promise;
}
Promise.some = function (promises, howMany) {
return some(promises, howMany);
};
Promise.prototype.some = function (howMany) {
return some(this, howMany);
};
Promise._SomePromiseArray = SomePromiseArray;
};

View File

@ -0,0 +1,103 @@
"use strict";
module.exports = function(Promise) {
function PromiseInspection(promise) {
if (promise !== undefined) {
promise = promise._target();
this._bitField = promise._bitField;
this._settledValueField = promise._isFateSealed()
? promise._settledValue() : undefined;
}
else {
this._bitField = 0;
this._settledValueField = undefined;
}
}
PromiseInspection.prototype._settledValue = function() {
return this._settledValueField;
};
var value = PromiseInspection.prototype.value = function () {
if (!this.isFulfilled()) {
throw new TypeError("cannot get fulfillment value of a non-fulfilled promise\u000a\u000a See http://goo.gl/MqrFmX\u000a");
}
return this._settledValue();
};
var reason = PromiseInspection.prototype.error =
PromiseInspection.prototype.reason = function () {
if (!this.isRejected()) {
throw new TypeError("cannot get rejection reason of a non-rejected promise\u000a\u000a See http://goo.gl/MqrFmX\u000a");
}
return this._settledValue();
};
var isFulfilled = PromiseInspection.prototype.isFulfilled = function() {
return (this._bitField & 33554432) !== 0;
};
var isRejected = PromiseInspection.prototype.isRejected = function () {
return (this._bitField & 16777216) !== 0;
};
var isPending = PromiseInspection.prototype.isPending = function () {
return (this._bitField & 50397184) === 0;
};
var isResolved = PromiseInspection.prototype.isResolved = function () {
return (this._bitField & 50331648) !== 0;
};
PromiseInspection.prototype.isCancelled = function() {
return (this._bitField & 8454144) !== 0;
};
Promise.prototype.__isCancelled = function() {
return (this._bitField & 65536) === 65536;
};
Promise.prototype._isCancelled = function() {
return this._target().__isCancelled();
};
Promise.prototype.isCancelled = function() {
return (this._target()._bitField & 8454144) !== 0;
};
Promise.prototype.isPending = function() {
return isPending.call(this._target());
};
Promise.prototype.isRejected = function() {
return isRejected.call(this._target());
};
Promise.prototype.isFulfilled = function() {
return isFulfilled.call(this._target());
};
Promise.prototype.isResolved = function() {
return isResolved.call(this._target());
};
Promise.prototype.value = function() {
return value.call(this._target());
};
Promise.prototype.reason = function() {
var target = this._target();
target._unsetRejectionIsUnhandled();
return reason.call(target);
};
Promise.prototype._value = function() {
return this._settledValue();
};
Promise.prototype._reason = function() {
this._unsetRejectionIsUnhandled();
return this._settledValue();
};
Promise.PromiseInspection = PromiseInspection;
};

View File

@ -0,0 +1,86 @@
"use strict";
module.exports = function(Promise, INTERNAL) {
var util = require("./util");
var errorObj = util.errorObj;
var isObject = util.isObject;
function tryConvertToPromise(obj, context) {
if (isObject(obj)) {
if (obj instanceof Promise) return obj;
var then = getThen(obj);
if (then === errorObj) {
if (context) context._pushContext();
var ret = Promise.reject(then.e);
if (context) context._popContext();
return ret;
} else if (typeof then === "function") {
if (isAnyBluebirdPromise(obj)) {
var ret = new Promise(INTERNAL);
obj._then(
ret._fulfill,
ret._reject,
undefined,
ret,
null
);
return ret;
}
return doThenable(obj, then, context);
}
}
return obj;
}
function doGetThen(obj) {
return obj.then;
}
function getThen(obj) {
try {
return doGetThen(obj);
} catch (e) {
errorObj.e = e;
return errorObj;
}
}
var hasProp = {}.hasOwnProperty;
function isAnyBluebirdPromise(obj) {
try {
return hasProp.call(obj, "_promise0");
} catch (e) {
return false;
}
}
function doThenable(x, then, context) {
var promise = new Promise(INTERNAL);
var ret = promise;
if (context) context._pushContext();
promise._captureStackTrace();
if (context) context._popContext();
var synchronous = true;
var result = util.tryCatch(then).call(x, resolve, reject);
synchronous = false;
if (promise && result === errorObj) {
promise._rejectCallback(result.e, true, true);
promise = null;
}
function resolve(value) {
if (!promise) return;
promise._resolveCallback(value);
promise = null;
}
function reject(reason) {
if (!promise) return;
promise._rejectCallback(reason, synchronous, true);
promise = null;
}
return ret;
}
return tryConvertToPromise;
};

View File

@ -0,0 +1,93 @@
"use strict";
module.exports = function(Promise, INTERNAL, debug) {
var util = require("./util");
var TimeoutError = Promise.TimeoutError;
function HandleWrapper(handle) {
this.handle = handle;
}
HandleWrapper.prototype._resultCancelled = function() {
clearTimeout(this.handle);
};
var afterValue = function(value) { return delay(+this).thenReturn(value); };
var delay = Promise.delay = function (ms, value) {
var ret;
var handle;
if (value !== undefined) {
ret = Promise.resolve(value)
._then(afterValue, null, null, ms, undefined);
if (debug.cancellation() && value instanceof Promise) {
ret._setOnCancel(value);
}
} else {
ret = new Promise(INTERNAL);
handle = setTimeout(function() { ret._fulfill(); }, +ms);
if (debug.cancellation()) {
ret._setOnCancel(new HandleWrapper(handle));
}
ret._captureStackTrace();
}
ret._setAsyncGuaranteed();
return ret;
};
Promise.prototype.delay = function (ms) {
return delay(ms, this);
};
var afterTimeout = function (promise, message, parent) {
var err;
if (typeof message !== "string") {
if (message instanceof Error) {
err = message;
} else {
err = new TimeoutError("operation timed out");
}
} else {
err = new TimeoutError(message);
}
util.markAsOriginatingFromRejection(err);
promise._attachExtraTrace(err);
promise._reject(err);
if (parent != null) {
parent.cancel();
}
};
function successClear(value) {
clearTimeout(this.handle);
return value;
}
function failureClear(reason) {
clearTimeout(this.handle);
throw reason;
}
Promise.prototype.timeout = function (ms, message) {
ms = +ms;
var ret, parent;
var handleWrapper = new HandleWrapper(setTimeout(function timeoutTimeout() {
if (ret.isPending()) {
afterTimeout(ret, message, parent);
}
}, ms));
if (debug.cancellation()) {
parent = this.then();
ret = parent._then(successClear, failureClear,
undefined, handleWrapper, undefined);
ret._setOnCancel(handleWrapper);
} else {
ret = this._then(successClear, failureClear,
undefined, handleWrapper, undefined);
}
return ret;
};
};

View File

@ -0,0 +1,226 @@
"use strict";
module.exports = function (Promise, apiRejection, tryConvertToPromise,
createContext, INTERNAL, debug) {
var util = require("./util");
var TypeError = require("./errors").TypeError;
var inherits = require("./util").inherits;
var errorObj = util.errorObj;
var tryCatch = util.tryCatch;
var NULL = {};
function thrower(e) {
setTimeout(function(){throw e;}, 0);
}
function castPreservingDisposable(thenable) {
var maybePromise = tryConvertToPromise(thenable);
if (maybePromise !== thenable &&
typeof thenable._isDisposable === "function" &&
typeof thenable._getDisposer === "function" &&
thenable._isDisposable()) {
maybePromise._setDisposable(thenable._getDisposer());
}
return maybePromise;
}
function dispose(resources, inspection) {
var i = 0;
var len = resources.length;
var ret = new Promise(INTERNAL);
function iterator() {
if (i >= len) return ret._fulfill();
var maybePromise = castPreservingDisposable(resources[i++]);
if (maybePromise instanceof Promise &&
maybePromise._isDisposable()) {
try {
maybePromise = tryConvertToPromise(
maybePromise._getDisposer().tryDispose(inspection),
resources.promise);
} catch (e) {
return thrower(e);
}
if (maybePromise instanceof Promise) {
return maybePromise._then(iterator, thrower,
null, null, null);
}
}
iterator();
}
iterator();
return ret;
}
function Disposer(data, promise, context) {
this._data = data;
this._promise = promise;
this._context = context;
}
Disposer.prototype.data = function () {
return this._data;
};
Disposer.prototype.promise = function () {
return this._promise;
};
Disposer.prototype.resource = function () {
if (this.promise().isFulfilled()) {
return this.promise().value();
}
return NULL;
};
Disposer.prototype.tryDispose = function(inspection) {
var resource = this.resource();
var context = this._context;
if (context !== undefined) context._pushContext();
var ret = resource !== NULL
? this.doDispose(resource, inspection) : null;
if (context !== undefined) context._popContext();
this._promise._unsetDisposable();
this._data = null;
return ret;
};
Disposer.isDisposer = function (d) {
return (d != null &&
typeof d.resource === "function" &&
typeof d.tryDispose === "function");
};
function FunctionDisposer(fn, promise, context) {
this.constructor$(fn, promise, context);
}
inherits(FunctionDisposer, Disposer);
FunctionDisposer.prototype.doDispose = function (resource, inspection) {
var fn = this.data();
return fn.call(resource, resource, inspection);
};
function maybeUnwrapDisposer(value) {
if (Disposer.isDisposer(value)) {
this.resources[this.index]._setDisposable(value);
return value.promise();
}
return value;
}
function ResourceList(length) {
this.length = length;
this.promise = null;
this[length-1] = null;
}
ResourceList.prototype._resultCancelled = function() {
var len = this.length;
for (var i = 0; i < len; ++i) {
var item = this[i];
if (item instanceof Promise) {
item.cancel();
}
}
};
Promise.using = function () {
var len = arguments.length;
if (len < 2) return apiRejection(
"you must pass at least 2 arguments to Promise.using");
var fn = arguments[len - 1];
if (typeof fn !== "function") {
return apiRejection("expecting a function but got " + util.classString(fn));
}
var input;
var spreadArgs = true;
if (len === 2 && Array.isArray(arguments[0])) {
input = arguments[0];
len = input.length;
spreadArgs = false;
} else {
input = arguments;
len--;
}
var resources = new ResourceList(len);
for (var i = 0; i < len; ++i) {
var resource = input[i];
if (Disposer.isDisposer(resource)) {
var disposer = resource;
resource = resource.promise();
resource._setDisposable(disposer);
} else {
var maybePromise = tryConvertToPromise(resource);
if (maybePromise instanceof Promise) {
resource =
maybePromise._then(maybeUnwrapDisposer, null, null, {
resources: resources,
index: i
}, undefined);
}
}
resources[i] = resource;
}
var reflectedResources = new Array(resources.length);
for (var i = 0; i < reflectedResources.length; ++i) {
reflectedResources[i] = Promise.resolve(resources[i]).reflect();
}
var resultPromise = Promise.all(reflectedResources)
.then(function(inspections) {
for (var i = 0; i < inspections.length; ++i) {
var inspection = inspections[i];
if (inspection.isRejected()) {
errorObj.e = inspection.error();
return errorObj;
} else if (!inspection.isFulfilled()) {
resultPromise.cancel();
return;
}
inspections[i] = inspection.value();
}
promise._pushContext();
fn = tryCatch(fn);
var ret = spreadArgs
? fn.apply(undefined, inspections) : fn(inspections);
var promiseCreated = promise._popContext();
debug.checkForgottenReturns(
ret, promiseCreated, "Promise.using", promise);
return ret;
});
var promise = resultPromise.lastly(function() {
var inspection = new Promise.PromiseInspection(resultPromise);
return dispose(resources, inspection);
});
resources.promise = promise;
promise._setOnCancel(resources);
return promise;
};
Promise.prototype._setDisposable = function (disposer) {
this._bitField = this._bitField | 131072;
this._disposer = disposer;
};
Promise.prototype._isDisposable = function () {
return (this._bitField & 131072) > 0;
};
Promise.prototype._getDisposer = function () {
return this._disposer;
};
Promise.prototype._unsetDisposable = function () {
this._bitField = this._bitField & (~131072);
this._disposer = undefined;
};
Promise.prototype.disposer = function (fn) {
if (typeof fn === "function") {
return new FunctionDisposer(fn, this, createContext());
}
throw new TypeError();
};
};

View File

@ -0,0 +1,379 @@
"use strict";
var es5 = require("./es5");
var canEvaluate = typeof navigator == "undefined";
var errorObj = {e: {}};
var tryCatchTarget;
var globalObject = typeof self !== "undefined" ? self :
typeof window !== "undefined" ? window :
typeof global !== "undefined" ? global :
this !== undefined ? this : null;
function tryCatcher() {
try {
var target = tryCatchTarget;
tryCatchTarget = null;
return target.apply(this, arguments);
} catch (e) {
errorObj.e = e;
return errorObj;
}
}
function tryCatch(fn) {
tryCatchTarget = fn;
return tryCatcher;
}
var inherits = function(Child, Parent) {
var hasProp = {}.hasOwnProperty;
function T() {
this.constructor = Child;
this.constructor$ = Parent;
for (var propertyName in Parent.prototype) {
if (hasProp.call(Parent.prototype, propertyName) &&
propertyName.charAt(propertyName.length-1) !== "$"
) {
this[propertyName + "$"] = Parent.prototype[propertyName];
}
}
}
T.prototype = Parent.prototype;
Child.prototype = new T();
return Child.prototype;
};
function isPrimitive(val) {
return val == null || val === true || val === false ||
typeof val === "string" || typeof val === "number";
}
function isObject(value) {
return typeof value === "function" ||
typeof value === "object" && value !== null;
}
function maybeWrapAsError(maybeError) {
if (!isPrimitive(maybeError)) return maybeError;
return new Error(safeToString(maybeError));
}
function withAppended(target, appendee) {
var len = target.length;
var ret = new Array(len + 1);
var i;
for (i = 0; i < len; ++i) {
ret[i] = target[i];
}
ret[i] = appendee;
return ret;
}
function getDataPropertyOrDefault(obj, key, defaultValue) {
if (es5.isES5) {
var desc = Object.getOwnPropertyDescriptor(obj, key);
if (desc != null) {
return desc.get == null && desc.set == null
? desc.value
: defaultValue;
}
} else {
return {}.hasOwnProperty.call(obj, key) ? obj[key] : undefined;
}
}
function notEnumerableProp(obj, name, value) {
if (isPrimitive(obj)) return obj;
var descriptor = {
value: value,
configurable: true,
enumerable: false,
writable: true
};
es5.defineProperty(obj, name, descriptor);
return obj;
}
function thrower(r) {
throw r;
}
var inheritedDataKeys = (function() {
var excludedPrototypes = [
Array.prototype,
Object.prototype,
Function.prototype
];
var isExcludedProto = function(val) {
for (var i = 0; i < excludedPrototypes.length; ++i) {
if (excludedPrototypes[i] === val) {
return true;
}
}
return false;
};
if (es5.isES5) {
var getKeys = Object.getOwnPropertyNames;
return function(obj) {
var ret = [];
var visitedKeys = Object.create(null);
while (obj != null && !isExcludedProto(obj)) {
var keys;
try {
keys = getKeys(obj);
} catch (e) {
return ret;
}
for (var i = 0; i < keys.length; ++i) {
var key = keys[i];
if (visitedKeys[key]) continue;
visitedKeys[key] = true;
var desc = Object.getOwnPropertyDescriptor(obj, key);
if (desc != null && desc.get == null && desc.set == null) {
ret.push(key);
}
}
obj = es5.getPrototypeOf(obj);
}
return ret;
};
} else {
var hasProp = {}.hasOwnProperty;
return function(obj) {
if (isExcludedProto(obj)) return [];
var ret = [];
/*jshint forin:false */
enumeration: for (var key in obj) {
if (hasProp.call(obj, key)) {
ret.push(key);
} else {
for (var i = 0; i < excludedPrototypes.length; ++i) {
if (hasProp.call(excludedPrototypes[i], key)) {
continue enumeration;
}
}
ret.push(key);
}
}
return ret;
};
}
})();
var thisAssignmentPattern = /this\s*\.\s*\S+\s*=/;
function isClass(fn) {
try {
if (typeof fn === "function") {
var keys = es5.names(fn.prototype);
var hasMethods = es5.isES5 && keys.length > 1;
var hasMethodsOtherThanConstructor = keys.length > 0 &&
!(keys.length === 1 && keys[0] === "constructor");
var hasThisAssignmentAndStaticMethods =
thisAssignmentPattern.test(fn + "") && es5.names(fn).length > 0;
if (hasMethods || hasMethodsOtherThanConstructor ||
hasThisAssignmentAndStaticMethods) {
return true;
}
}
return false;
} catch (e) {
return false;
}
}
function toFastProperties(obj) {
/*jshint -W027,-W055,-W031*/
function FakeConstructor() {}
FakeConstructor.prototype = obj;
var l = 8;
while (l--) new FakeConstructor();
return obj;
eval(obj);
}
var rident = /^[a-z$_][a-z$_0-9]*$/i;
function isIdentifier(str) {
return rident.test(str);
}
function filledRange(count, prefix, suffix) {
var ret = new Array(count);
for(var i = 0; i < count; ++i) {
ret[i] = prefix + i + suffix;
}
return ret;
}
function safeToString(obj) {
try {
return obj + "";
} catch (e) {
return "[no string representation]";
}
}
function isError(obj) {
return obj !== null &&
typeof obj === "object" &&
typeof obj.message === "string" &&
typeof obj.name === "string";
}
function markAsOriginatingFromRejection(e) {
try {
notEnumerableProp(e, "isOperational", true);
}
catch(ignore) {}
}
function originatesFromRejection(e) {
if (e == null) return false;
return ((e instanceof Error["__BluebirdErrorTypes__"].OperationalError) ||
e["isOperational"] === true);
}
function canAttachTrace(obj) {
return isError(obj) && es5.propertyIsWritable(obj, "stack");
}
var ensureErrorObject = (function() {
if (!("stack" in new Error())) {
return function(value) {
if (canAttachTrace(value)) return value;
try {throw new Error(safeToString(value));}
catch(err) {return err;}
};
} else {
return function(value) {
if (canAttachTrace(value)) return value;
return new Error(safeToString(value));
};
}
})();
function classString(obj) {
return {}.toString.call(obj);
}
function copyDescriptors(from, to, filter) {
var keys = es5.names(from);
for (var i = 0; i < keys.length; ++i) {
var key = keys[i];
if (filter(key)) {
try {
es5.defineProperty(to, key, es5.getDescriptor(from, key));
} catch (ignore) {}
}
}
}
var asArray = function(v) {
if (es5.isArray(v)) {
return v;
}
return null;
};
if (typeof Symbol !== "undefined" && Symbol.iterator) {
var ArrayFrom = typeof Array.from === "function" ? function(v) {
return Array.from(v);
} : function(v) {
var ret = [];
var it = v[Symbol.iterator]();
var itResult;
while (!((itResult = it.next()).done)) {
ret.push(itResult.value);
}
return ret;
};
asArray = function(v) {
if (es5.isArray(v)) {
return v;
} else if (v != null && typeof v[Symbol.iterator] === "function") {
return ArrayFrom(v);
}
return null;
};
}
var isNode = typeof process !== "undefined" &&
classString(process).toLowerCase() === "[object process]";
var hasEnvVariables = typeof process !== "undefined" &&
typeof process.env !== "undefined";
function env(key) {
return hasEnvVariables ? process.env[key] : undefined;
}
function getNativePromise() {
if (typeof Promise === "function") {
try {
var promise = new Promise(function(){});
if ({}.toString.call(promise) === "[object Promise]") {
return Promise;
}
} catch (e) {}
}
}
function domainBind(self, cb) {
return self.bind(cb);
}
var ret = {
isClass: isClass,
isIdentifier: isIdentifier,
inheritedDataKeys: inheritedDataKeys,
getDataPropertyOrDefault: getDataPropertyOrDefault,
thrower: thrower,
isArray: es5.isArray,
asArray: asArray,
notEnumerableProp: notEnumerableProp,
isPrimitive: isPrimitive,
isObject: isObject,
isError: isError,
canEvaluate: canEvaluate,
errorObj: errorObj,
tryCatch: tryCatch,
inherits: inherits,
withAppended: withAppended,
maybeWrapAsError: maybeWrapAsError,
toFastProperties: toFastProperties,
filledRange: filledRange,
toString: safeToString,
canAttachTrace: canAttachTrace,
ensureErrorObject: ensureErrorObject,
originatesFromRejection: originatesFromRejection,
markAsOriginatingFromRejection: markAsOriginatingFromRejection,
classString: classString,
copyDescriptors: copyDescriptors,
hasDevTools: typeof chrome !== "undefined" && chrome &&
typeof chrome.loadTimes === "function",
isNode: isNode,
hasEnvVariables: hasEnvVariables,
env: env,
global: globalObject,
getNativePromise: getNativePromise,
domainBind: domainBind
};
ret.isRecentNode = ret.isNode && (function() {
var version = process.versions.node.split(".").map(Number);
return (version[0] === 0 && version[1] > 10) || (version[0] > 0);
})();
if (ret.isNode) ret.toFastProperties(process);
try {throw new Error(); } catch (e) {ret.lastLineError = e;}
module.exports = ret;

128
node_modules/typings/node_modules/bluebird/package.json generated vendored Normal file
View File

@ -0,0 +1,128 @@
{
"_args": [
[
"bluebird@^3.1.1",
"C:\\Users\\x2mjbyrn\\Source\\Repos\\Skeleton\\node_modules\\typings"
]
],
"_from": "bluebird@>=3.1.1-0 <4.0.0-0",
"_id": "bluebird@3.5.0",
"_inCache": true,
"_location": "/typings/bluebird",
"_nodeVersion": "7.7.1",
"_npmOperationalInternal": {
"host": "packages-12-west.internal.npmjs.com",
"tmp": "tmp/bluebird-3.5.0.tgz_1488577769162_0.549377566203475"
},
"_npmUser": {
"email": "petka_antonov@hotmail.com",
"name": "esailija"
},
"_npmVersion": "4.1.2",
"_phantomChildren": {},
"_requested": {
"name": "bluebird",
"raw": "bluebird@^3.1.1",
"rawSpec": "^3.1.1",
"scope": null,
"spec": ">=3.1.1-0 <4.0.0-0",
"type": "range"
},
"_requiredBy": [
"/typings"
],
"_resolved": "https://registry.npmjs.org/bluebird/-/bluebird-3.5.0.tgz",
"_shasum": "791420d7f551eea2897453a8a77653f96606d67c",
"_shrinkwrap": null,
"_spec": "bluebird@^3.1.1",
"_where": "C:\\Users\\x2mjbyrn\\Source\\Repos\\Skeleton\\node_modules\\typings",
"author": {
"email": "petka_antonov@hotmail.com",
"name": "Petka Antonov",
"url": "http://github.com/petkaantonov/"
},
"browser": "./js/browser/bluebird.js",
"bugs": {
"url": "http://github.com/petkaantonov/bluebird/issues"
},
"dependencies": {},
"description": "Full featured Promises/A+ implementation with exceptionally good performance",
"devDependencies": {
"acorn": "~0.6.0",
"baconjs": "^0.7.43",
"bluebird": "^2.9.2",
"body-parser": "^1.10.2",
"browserify": "^8.1.1",
"cli-table": "~0.3.1",
"co": "^4.2.0",
"cross-spawn": "^0.2.3",
"glob": "^4.3.2",
"grunt-saucelabs": "~8.4.1",
"highland": "^2.3.0",
"istanbul": "^0.3.5",
"jshint": "^2.6.0",
"jshint-stylish": "~0.2.0",
"kefir": "^2.4.1",
"mkdirp": "~0.5.0",
"mocha": "~2.1",
"open": "~0.0.5",
"optimist": "~0.6.1",
"rimraf": "~2.2.6",
"rx": "^2.3.25",
"serve-static": "^1.7.1",
"sinon": "~1.7.3",
"uglify-js": "~2.4.16"
},
"directories": {},
"dist": {
"shasum": "791420d7f551eea2897453a8a77653f96606d67c",
"tarball": "https://registry.npmjs.org/bluebird/-/bluebird-3.5.0.tgz"
},
"files": [
"LICENSE",
"js/browser",
"js/release"
],
"gitHead": "0b281e6caeec9c30b8de9a409b8ff1723f973f59",
"homepage": "https://github.com/petkaantonov/bluebird",
"installable": true,
"keywords": [
"async",
"await",
"deferred",
"deferreds",
"dsl",
"flow control",
"fluent interface",
"future",
"performance",
"promise",
"promises",
"promises-a",
"promises-aplus"
],
"license": "MIT",
"main": "./js/release/bluebird.js",
"maintainers": [
{
"name": "esailija",
"email": "petka_antonov@hotmail.com"
}
],
"name": "bluebird",
"optionalDependencies": {},
"repository": {
"type": "git",
"url": "git://github.com/petkaantonov/bluebird.git"
},
"scripts": {
"generate-browser-core": "node tools/build.js --features=core --no-debug --release --zalgo --browser --minify && mv js/browser/bluebird.js js/browser/bluebird.core.js && mv js/browser/bluebird.min.js js/browser/bluebird.core.min.js",
"generate-browser-full": "node tools/build.js --no-clean --no-debug --release --browser --minify",
"istanbul": "istanbul",
"lint": "node scripts/jshint.js",
"prepublish": "npm run generate-browser-core && npm run generate-browser-full",
"test": "node tools/test.js"
},
"version": "3.5.0",
"webpack": "./js/release/bluebird.js"
}

116
node_modules/typings/node_modules/chalk/index.js generated vendored Normal file
View File

@ -0,0 +1,116 @@
'use strict';
var escapeStringRegexp = require('escape-string-regexp');
var ansiStyles = require('ansi-styles');
var stripAnsi = require('strip-ansi');
var hasAnsi = require('has-ansi');
var supportsColor = require('supports-color');
var defineProps = Object.defineProperties;
var isSimpleWindowsTerm = process.platform === 'win32' && !/^xterm/i.test(process.env.TERM);
function Chalk(options) {
// detect mode if not set manually
this.enabled = !options || options.enabled === undefined ? supportsColor : options.enabled;
}
// use bright blue on Windows as the normal blue color is illegible
if (isSimpleWindowsTerm) {
ansiStyles.blue.open = '\u001b[94m';
}
var styles = (function () {
var ret = {};
Object.keys(ansiStyles).forEach(function (key) {
ansiStyles[key].closeRe = new RegExp(escapeStringRegexp(ansiStyles[key].close), 'g');
ret[key] = {
get: function () {
return build.call(this, this._styles.concat(key));
}
};
});
return ret;
})();
var proto = defineProps(function chalk() {}, styles);
function build(_styles) {
var builder = function () {
return applyStyle.apply(builder, arguments);
};
builder._styles = _styles;
builder.enabled = this.enabled;
// __proto__ is used because we must return a function, but there is
// no way to create a function with a different prototype.
/* eslint-disable no-proto */
builder.__proto__ = proto;
return builder;
}
function applyStyle() {
// support varags, but simply cast to string in case there's only one arg
var args = arguments;
var argsLen = args.length;
var str = argsLen !== 0 && String(arguments[0]);
if (argsLen > 1) {
// don't slice `arguments`, it prevents v8 optimizations
for (var a = 1; a < argsLen; a++) {
str += ' ' + args[a];
}
}
if (!this.enabled || !str) {
return str;
}
var nestedStyles = this._styles;
var i = nestedStyles.length;
// Turns out that on Windows dimmed gray text becomes invisible in cmd.exe,
// see https://github.com/chalk/chalk/issues/58
// If we're on Windows and we're dealing with a gray color, temporarily make 'dim' a noop.
var originalDim = ansiStyles.dim.open;
if (isSimpleWindowsTerm && (nestedStyles.indexOf('gray') !== -1 || nestedStyles.indexOf('grey') !== -1)) {
ansiStyles.dim.open = '';
}
while (i--) {
var code = ansiStyles[nestedStyles[i]];
// Replace any instances already present with a re-opening code
// otherwise only the part of the string until said closing code
// will be colored, and the rest will simply be 'plain'.
str = code.open + str.replace(code.closeRe, code.open) + code.close;
}
// Reset the original 'dim' if we changed it to work around the Windows dimmed gray issue.
ansiStyles.dim.open = originalDim;
return str;
}
function init() {
var ret = {};
Object.keys(styles).forEach(function (name) {
ret[name] = {
get: function () {
return build.call(this, [name]);
}
};
});
return ret;
}
defineProps(Chalk.prototype, init());
module.exports = new Chalk();
module.exports.styles = ansiStyles;
module.exports.hasColor = hasAnsi;
module.exports.stripColor = stripAnsi;
module.exports.supportsColor = supportsColor;

21
node_modules/typings/node_modules/chalk/license generated vendored Normal file
View File

@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

131
node_modules/typings/node_modules/chalk/package.json generated vendored Normal file
View File

@ -0,0 +1,131 @@
{
"_args": [
[
"chalk@^1.0.0",
"C:\\Users\\x2mjbyrn\\Source\\Repos\\Skeleton\\node_modules\\typings"
]
],
"_from": "chalk@>=1.0.0-0 <2.0.0-0",
"_id": "chalk@1.1.3",
"_inCache": true,
"_location": "/typings/chalk",
"_nodeVersion": "0.10.32",
"_npmOperationalInternal": {
"host": "packages-12-west.internal.npmjs.com",
"tmp": "tmp/chalk-1.1.3.tgz_1459210604109_0.3892582862172276"
},
"_npmUser": {
"email": "i.am.qix@gmail.com",
"name": "qix"
},
"_npmVersion": "2.14.2",
"_phantomChildren": {},
"_requested": {
"name": "chalk",
"raw": "chalk@^1.0.0",
"rawSpec": "^1.0.0",
"scope": null,
"spec": ">=1.0.0-0 <2.0.0-0",
"type": "range"
},
"_requiredBy": [
"/typings"
],
"_resolved": "https://registry.npmjs.org/chalk/-/chalk-1.1.3.tgz",
"_shasum": "a8115c55e4a702fe4d150abd3872822a7e09fc98",
"_shrinkwrap": null,
"_spec": "chalk@^1.0.0",
"_where": "C:\\Users\\x2mjbyrn\\Source\\Repos\\Skeleton\\node_modules\\typings",
"bugs": {
"url": "https://github.com/chalk/chalk/issues"
},
"dependencies": {
"ansi-styles": "^2.2.1",
"escape-string-regexp": "^1.0.2",
"has-ansi": "^2.0.0",
"strip-ansi": "^3.0.0",
"supports-color": "^2.0.0"
},
"description": "Terminal string styling done right. Much color.",
"devDependencies": {
"coveralls": "^2.11.2",
"matcha": "^0.6.0",
"mocha": "*",
"nyc": "^3.0.0",
"require-uncached": "^1.0.2",
"resolve-from": "^1.0.0",
"semver": "^4.3.3",
"xo": "*"
},
"directories": {},
"dist": {
"shasum": "a8115c55e4a702fe4d150abd3872822a7e09fc98",
"tarball": "https://registry.npmjs.org/chalk/-/chalk-1.1.3.tgz"
},
"engines": {
"node": ">=0.10.0"
},
"files": [
"index.js"
],
"gitHead": "0d8d8c204eb87a4038219131ad4d8369c9f59d24",
"homepage": "https://github.com/chalk/chalk#readme",
"installable": true,
"keywords": [
"256",
"ansi",
"cli",
"color",
"colors",
"colour",
"command-line",
"console",
"formatting",
"log",
"logging",
"rgb",
"shell",
"str",
"string",
"style",
"styles",
"terminal",
"text",
"tty",
"xterm"
],
"license": "MIT",
"maintainers": [
{
"name": "qix",
"email": "i.am.qix@gmail.com"
},
{
"name": "sindresorhus",
"email": "sindresorhus@gmail.com"
},
{
"name": "unicorn",
"email": "sindresorhus+unicorn@gmail.com"
}
],
"name": "chalk",
"optionalDependencies": {},
"repository": {
"type": "git",
"url": "git+https://github.com/chalk/chalk.git"
},
"scripts": {
"bench": "matcha benchmark.js",
"coverage": "nyc npm test && nyc report",
"coveralls": "nyc npm test && nyc report --reporter=text-lcov | coveralls",
"test": "xo && mocha"
},
"version": "1.1.3",
"xo": {
"envs": [
"mocha",
"node"
]
}
}

213
node_modules/typings/node_modules/chalk/readme.md generated vendored Normal file
View File

@ -0,0 +1,213 @@
<h1 align="center">
<br>
<br>
<img width="360" src="https://cdn.rawgit.com/chalk/chalk/19935d6484811c5e468817f846b7b3d417d7bf4a/logo.svg" alt="chalk">
<br>
<br>
<br>
</h1>
> Terminal string styling done right
[![Build Status](https://travis-ci.org/chalk/chalk.svg?branch=master)](https://travis-ci.org/chalk/chalk)
[![Coverage Status](https://coveralls.io/repos/chalk/chalk/badge.svg?branch=master)](https://coveralls.io/r/chalk/chalk?branch=master)
[![](http://img.shields.io/badge/unicorn-approved-ff69b4.svg)](https://www.youtube.com/watch?v=9auOCbH5Ns4)
[colors.js](https://github.com/Marak/colors.js) used to be the most popular string styling module, but it has serious deficiencies like extending `String.prototype` which causes all kinds of [problems](https://github.com/yeoman/yo/issues/68). Although there are other ones, they either do too much or not enough.
**Chalk is a clean and focused alternative.**
![](https://github.com/chalk/ansi-styles/raw/master/screenshot.png)
## Why
- Highly performant
- Doesn't extend `String.prototype`
- Expressive API
- Ability to nest styles
- Clean and focused
- Auto-detects color support
- Actively maintained
- [Used by ~4500 modules](https://www.npmjs.com/browse/depended/chalk) as of July 15, 2015
## Install
```
$ npm install --save chalk
```
## Usage
Chalk comes with an easy to use composable API where you just chain and nest the styles you want.
```js
var chalk = require('chalk');
// style a string
chalk.blue('Hello world!');
// combine styled and normal strings
chalk.blue('Hello') + 'World' + chalk.red('!');
// compose multiple styles using the chainable API
chalk.blue.bgRed.bold('Hello world!');
// pass in multiple arguments
chalk.blue('Hello', 'World!', 'Foo', 'bar', 'biz', 'baz');
// nest styles
chalk.red('Hello', chalk.underline.bgBlue('world') + '!');
// nest styles of the same type even (color, underline, background)
chalk.green(
'I am a green line ' +
chalk.blue.underline.bold('with a blue substring') +
' that becomes green again!'
);
```
Easily define your own themes.
```js
var chalk = require('chalk');
var error = chalk.bold.red;
console.log(error('Error!'));
```
Take advantage of console.log [string substitution](http://nodejs.org/docs/latest/api/console.html#console_console_log_data).
```js
var name = 'Sindre';
console.log(chalk.green('Hello %s'), name);
//=> Hello Sindre
```
## API
### chalk.`<style>[.<style>...](string, [string...])`
Example: `chalk.red.bold.underline('Hello', 'world');`
Chain [styles](#styles) and call the last one as a method with a string argument. Order doesn't matter, and later styles take precedent in case of a conflict. This simply means that `Chalk.red.yellow.green` is equivalent to `Chalk.green`.
Multiple arguments will be separated by space.
### chalk.enabled
Color support is automatically detected, but you can override it by setting the `enabled` property. You should however only do this in your own code as it applies globally to all chalk consumers.
If you need to change this in a reusable module create a new instance:
```js
var ctx = new chalk.constructor({enabled: false});
```
### chalk.supportsColor
Detect whether the terminal [supports color](https://github.com/chalk/supports-color). Used internally and handled for you, but exposed for convenience.
Can be overridden by the user with the flags `--color` and `--no-color`. For situations where using `--color` is not possible, add an environment variable `FORCE_COLOR` with any value to force color. Trumps `--no-color`.
### chalk.styles
Exposes the styles as [ANSI escape codes](https://github.com/chalk/ansi-styles).
Generally not useful, but you might need just the `.open` or `.close` escape code if you're mixing externally styled strings with your own.
```js
var chalk = require('chalk');
console.log(chalk.styles.red);
//=> {open: '\u001b[31m', close: '\u001b[39m'}
console.log(chalk.styles.red.open + 'Hello' + chalk.styles.red.close);
```
### chalk.hasColor(string)
Check whether a string [has color](https://github.com/chalk/has-ansi).
### chalk.stripColor(string)
[Strip color](https://github.com/chalk/strip-ansi) from a string.
Can be useful in combination with `.supportsColor` to strip color on externally styled text when it's not supported.
Example:
```js
var chalk = require('chalk');
var styledString = getText();
if (!chalk.supportsColor) {
styledString = chalk.stripColor(styledString);
}
```
## Styles
### Modifiers
- `reset`
- `bold`
- `dim`
- `italic` *(not widely supported)*
- `underline`
- `inverse`
- `hidden`
- `strikethrough` *(not widely supported)*
### Colors
- `black`
- `red`
- `green`
- `yellow`
- `blue` *(on Windows the bright version is used as normal blue is illegible)*
- `magenta`
- `cyan`
- `white`
- `gray`
### Background colors
- `bgBlack`
- `bgRed`
- `bgGreen`
- `bgYellow`
- `bgBlue`
- `bgMagenta`
- `bgCyan`
- `bgWhite`
## 256-colors
Chalk does not support anything other than the base eight colors, which guarantees it will work on all terminals and systems. Some terminals, specifically `xterm` compliant ones, will support the full range of 8-bit colors. For this the lower level [ansi-256-colors](https://github.com/jbnicolai/ansi-256-colors) package can be used.
## Windows
If you're on Windows, do yourself a favor and use [`cmder`](http://bliker.github.io/cmder/) instead of `cmd.exe`.
## Related
- [chalk-cli](https://github.com/chalk/chalk-cli) - CLI for this module
- [ansi-styles](https://github.com/chalk/ansi-styles/) - ANSI escape codes for styling strings in the terminal
- [supports-color](https://github.com/chalk/supports-color/) - Detect whether a terminal supports color
- [strip-ansi](https://github.com/chalk/strip-ansi) - Strip ANSI escape codes
- [has-ansi](https://github.com/chalk/has-ansi) - Check if a string has ANSI escape codes
- [ansi-regex](https://github.com/chalk/ansi-regex) - Regular expression for matching ANSI escape codes
- [wrap-ansi](https://github.com/chalk/wrap-ansi) - Wordwrap a string with ANSI escape codes
## License
MIT © [Sindre Sorhus](http://sindresorhus.com)

21
node_modules/typings/node_modules/columnify/LICENSE generated vendored Normal file
View File

@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2013 Tim Oxley
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.

9
node_modules/typings/node_modules/columnify/Makefile generated vendored Normal file
View File

@ -0,0 +1,9 @@
all: columnify.js
prepublish: all
columnify.js: index.js package.json
babel index.js > columnify.js
.PHONY: all prepublish

470
node_modules/typings/node_modules/columnify/Readme.md generated vendored Normal file
View File

@ -0,0 +1,470 @@
# columnify
[![NPM](https://nodei.co/npm/columnify.png?downloads=true&downloadRank=true&stars=true&chrome)](https://nodei.co/npm-dl/columnify/)
[![NPM](https://nodei.co/npm-dl/columnify.png?months=3&height=3&chrome)](https://nodei.co/npm/columnify/)
[![Build Status](https://img.shields.io/travis/timoxley/columnify.svg?style=flat)](https://travis-ci.org/timoxley/columnify)
[![NPM Version](https://img.shields.io/npm/v/columnify.svg?style=flat)](https://npmjs.org/package/columnify)
[![License](http://img.shields.io/npm/l/columnify.svg?style=flat)](LICENSE)
[![Dependency Status](https://david-dm.org/timoxley/columnify.svg)](https://david-dm.org/timoxley/columnify)
[![devDependency Status](https://david-dm.org/timoxley/columnify/dev-status.svg)](https://david-dm.org/timoxley/columnify#info=devDependencies)
Create text-based columns suitable for console output from objects or
arrays of objects.
Columns are automatically resized to fit the content of the largest
cell. Each cell will be padded with spaces to fill the available space
and ensure column contents are left-aligned.
Designed to [handle sensible wrapping in npm search results](https://github.com/isaacs/npm/pull/2328).
`npm search` before & after integrating columnify:
![npm-tidy-search](https://f.cloud.github.com/assets/43438/1848959/ae02ad04-76a1-11e3-8255-4781debffc26.gif)
## Installation & Update
```
$ npm install --save columnify@latest
```
## Usage
```javascript
var columnify = require('columnify')
var columns = columnify(data, options)
console.log(columns)
```
## Examples
### Columnify Objects
Objects are converted to a list of key/value pairs:
```javascript
var data = {
"commander@0.6.1": 1,
"minimatch@0.2.14": 3,
"mkdirp@0.3.5": 2,
"sigmund@1.0.0": 3
}
console.log(columnify(data))
```
#### Output:
```
KEY VALUE
commander@0.6.1 1
minimatch@0.2.14 3
mkdirp@0.3.5 2
sigmund@1.0.0 3
```
### Custom Column Names
```javascript
var data = {
"commander@0.6.1": 1,
"minimatch@0.2.14": 3,
"mkdirp@0.3.5": 2,
"sigmund@1.0.0": 3
}
console.log(columnify(data, {columns: ['MODULE', 'COUNT']}))
```
#### Output:
```
MODULE COUNT
commander@0.6.1 1
minimatch@0.2.14 3
mkdirp@0.3.5 2
sigmund@1.0.0 3
```
### Columnify Arrays of Objects
Column headings are extracted from the keys in supplied objects.
```javascript
var columnify = require('columnify')
var columns = columnify([{
name: 'mod1',
version: '0.0.1'
}, {
name: 'module2',
version: '0.2.0'
}])
console.log(columns)
```
#### Output:
```
NAME VERSION
mod1 0.0.1
module2 0.2.0
```
### Filtering & Ordering Columns
By default, all properties are converted into columns, whether or not
they exist on every object or not.
To explicitly specify which columns to include, and in which order,
supply a "columns" or "include" array ("include" is just an alias).
```javascript
var data = [{
name: 'module1',
description: 'some description',
version: '0.0.1',
}, {
name: 'module2',
description: 'another description',
version: '0.2.0',
}]
var columns = columnify(data, {
columns: ['name', 'version']
})
console.log(columns)
```
#### Output:
```
NAME VERSION
module1 0.0.1
module2 0.2.0
```
## Global and Per Column Options
You can set a number of options at a global level (ie. for all columns) or on a per column basis.
Set options on a per column basis by using the `config` option to specify individual columns:
```javascript
var columns = columnify(data, {
optionName: optionValue,
config: {
columnName: {optionName: optionValue},
columnName: {optionName: optionValue},
}
})
```
### Maximum and Minimum Column Widths
As with all options, you can define the `maxWidth` and `minWidth` globally, or for specified columns. By default, wrapping will happen at word boundaries. Empty cells or those which do not fill the `minWidth` will be padded with spaces.
```javascript
var columns = columnify([{
name: 'mod1',
description: 'some description which happens to be far larger than the max',
version: '0.0.1',
}, {
name: 'module-two',
description: 'another description larger than the max',
version: '0.2.0',
}], {
minWidth: 20,
config: {
description: {maxWidth: 30}
}
})
console.log(columns)
```
#### Output:
```
NAME DESCRIPTION VERSION
mod1 some description which happens 0.0.1
to be far larger than the max
module-two another description larger 0.2.0
than the max
```
#### Maximum Line Width
You can set a hard maximum line width using the `maxLineWidth` option.
Beyond this value data is unceremoniously truncated with no truncation
marker.
This can either be a number or 'auto' to set the value to the width of
stdout.
Setting this value to 'auto' prevent TTY-imposed line-wrapping when
lines exceed the screen width.
#### Truncating Column Cells Instead of Wrapping
You can disable wrapping and instead truncate content at the maximum
column width by using the `truncate` option. Truncation respects word boundaries. A truncation marker, `…`, will appear next to the last word in any truncated line.
```javascript
var columns = columnify(data, {
truncate: true,
config: {
description: {
maxWidth: 20
}
}
})
console.log(columns)
```
#### Output:
```
NAME DESCRIPTION VERSION
mod1 some description… 0.0.1
module-two another description… 0.2.0
```
### Align Right/Center
You can set the alignment of the column data by using the `align` option.
```js
var data = {
"mocha@1.18.2": 1,
"commander@2.0.0": 1,
"debug@0.8.1": 1
}
columnify(data, {config: {value: {align: 'right'}}})
```
#### Output:
```
KEY VALUE
mocha@1.18.2 1
commander@2.0.0 1
debug@0.8.1 1
```
`align: 'center'` works in a similar way.
### Padding Character
Set a character to fill whitespace within columns with the `paddingChr` option.
```js
var data = {
"shortKey": "veryVeryVeryVeryVeryLongVal",
"veryVeryVeryVeryVeryLongKey": "shortVal"
}
columnify(data, { paddingChr: '.'})
```
#### Output:
```
KEY........................ VALUE......................
shortKey................... veryVeryVeryVeryVeryLongVal
veryVeryVeryVeryVeryLongKey shortVal...................
```
### Preserve Existing Newlines
By default, `columnify` sanitises text by replacing any occurance of 1 or more whitespace characters with a single space.
`columnify` can be configured to respect existing new line characters using the `preserveNewLines` option. Note this will still collapse all other whitespace.
```javascript
var data = [{
name: "glob@3.2.9",
paths: [
"node_modules/tap/node_modules/glob",
"node_modules/tape/node_modules/glob"
].join('\n')
}, {
name: "nopt@2.2.1",
paths: [
"node_modules/tap/node_modules/nopt"
]
}, {
name: "runforcover@0.0.2",
paths: "node_modules/tap/node_modules/runforcover"
}]
console.log(columnify(data, {preserveNewLines: true}))
```
#### Output:
```
NAME PATHS
glob@3.2.9 node_modules/tap/node_modules/glob
node_modules/tape/node_modules/glob
nopt@2.2.1 node_modules/tap/node_modules/nopt
runforcover@0.0.2 node_modules/tap/node_modules/runforcover
```
Compare this with output without `preserveNewLines`:
```javascript
console.log(columnify(data, {preserveNewLines: false}))
// or just
console.log(columnify(data))
```
```
NAME PATHS
glob@3.2.9 node_modules/tap/node_modules/glob node_modules/tape/node_modules/glob
nopt@2.2.1 node_modules/tap/node_modules/nopt
runforcover@0.0.2 node_modules/tap/node_modules/runforcover
```
### Custom Truncation Marker
You can change the truncation marker to something other than the default
`…` by using the `truncateMarker` option.
```javascript
var columns = columnify(data, {
truncate: true,
truncateMarker: '>',
widths: {
description: {
maxWidth: 20
}
}
})
console.log(columns)
```
#### Output:
```
NAME DESCRIPTION VERSION
mod1 some description> 0.0.1
module-two another description> 0.2.0
```
### Custom Column Splitter
If your columns need some bling, you can split columns with custom
characters by using the `columnSplitter` option.
```javascript
var columns = columnify(data, {
columnSplitter: ' | '
})
console.log(columns)
```
#### Output:
```
NAME | DESCRIPTION | VERSION
mod1 | some description which happens to be far larger than the max | 0.0.1
module-two | another description larger than the max | 0.2.0
```
### Control Header Display
Control whether column headers are displayed by using the `showHeaders` option.
```javascript
var columns = columnify(data, {
showHeaders: false
})
```
This also works well for hiding a single column header, like an `id` column:
```javascript
var columns = columnify(data, {
config: {
id: { showHeaders: false }
}
})
```
### Transforming Column Data and Headers
If you need to modify the presentation of column content or heading content there are two useful options for doing that: `dataTransform` and `headerTransform`. Both of these take a function and need to return a valid string.
```javascript
var columns = columnify([{
name: 'mod1',
description: 'SOME DESCRIPTION TEXT.'
}, {
name: 'module-two',
description: 'SOME SLIGHTLY LONGER DESCRIPTION TEXT.'
}], {
dataTransform: function(data) {
return data.toLowerCase()
},
config: {
name: {
headingTransform: function(heading) {
heading = "module " + heading
return "*" + heading.toUpperCase() + "*"
}
}
}
})
```
#### Output:
```
*MODULE NAME* DESCRIPTION
mod1 some description text.
module-two some slightly longer description text.
```
## Multibyte Character Support
`columnify` uses [mycoboco/wcwidth.js](https://github.com/mycoboco/wcwidth.js) to calculate length of multibyte characters:
```javascript
var data = [{
name: 'module-one',
description: 'some description',
version: '0.0.1',
}, {
name: '这是一个很长的名字的模块',
description: '这真的是一个描述的内容这个描述很长',
version: "0.3.3"
}]
console.log(columnify(data))
```
#### Without multibyte handling:
i.e. before columnify added this feature
```
NAME DESCRIPTION VERSION
module-one some description 0.0.1
这是一个很长的名字的模块 这真的是一个描述的内容这个描述很长 0.3.3
```
#### With multibyte handling:
```
NAME DESCRIPTION VERSION
module-one some description 0.0.1
这是一个很长的名字的模块 这真的是一个描述的内容这个描述很长 0.3.3
```
## Contributions
```
project : columnify
repo age : 1 year, 2 months
active : 32 days
commits : 120
files : 54
authors :
90 Tim Oxley 75.0%
8 Tim 6.7%
7 Arjun Mehta 5.8%
6 Dany 5.0%
5 Wei Gao 4.2%
2 Dany Shaanan 1.7%
1 Seth Miller 0.8%
1 Isaac Z. Schlueter 0.8%
```
## License
MIT

View File

@ -0,0 +1,308 @@
"use strict";
var wcwidth = require('./width');
var _require = require('./utils');
var padRight = _require.padRight;
var padCenter = _require.padCenter;
var padLeft = _require.padLeft;
var splitIntoLines = _require.splitIntoLines;
var splitLongWords = _require.splitLongWords;
var truncateString = _require.truncateString;
var DEFAULT_HEADING_TRANSFORM = function DEFAULT_HEADING_TRANSFORM(key) {
return key.toUpperCase();
};
var DEFAULT_DATA_TRANSFORM = function DEFAULT_DATA_TRANSFORM(cell, column, index) {
return cell;
};
var DEFAULTS = Object.freeze({
maxWidth: Infinity,
minWidth: 0,
columnSplitter: ' ',
truncate: false,
truncateMarker: '…',
preserveNewLines: false,
paddingChr: ' ',
showHeaders: true,
headingTransform: DEFAULT_HEADING_TRANSFORM,
dataTransform: DEFAULT_DATA_TRANSFORM
});
module.exports = function (items) {
var options = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
var columnConfigs = options.config || {};
delete options.config; // remove config so doesn't appear on every column.
var maxLineWidth = options.maxLineWidth || Infinity;
if (maxLineWidth === 'auto') maxLineWidth = process.stdout.columns || Infinity;
delete options.maxLineWidth; // this is a line control option, don't pass it to column
// Option defaults inheritance:
// options.config[columnName] => options => DEFAULTS
options = mixin({}, DEFAULTS, options);
options.config = options.config || Object.create(null);
options.spacing = options.spacing || '\n'; // probably useless
options.preserveNewLines = !!options.preserveNewLines;
options.showHeaders = !!options.showHeaders;
options.columns = options.columns || options.include; // alias include/columns, prefer columns if supplied
var columnNames = options.columns || []; // optional user-supplied columns to include
items = toArray(items, columnNames);
// if not suppled column names, automatically determine columns from data keys
if (!columnNames.length) {
items.forEach(function (item) {
for (var columnName in item) {
if (columnNames.indexOf(columnName) === -1) columnNames.push(columnName);
}
});
}
// initialize column defaults (each column inherits from options.config)
var columns = columnNames.reduce(function (columns, columnName) {
var column = Object.create(options);
columns[columnName] = mixin(column, columnConfigs[columnName]);
return columns;
}, Object.create(null));
// sanitize column settings
columnNames.forEach(function (columnName) {
var column = columns[columnName];
column.name = columnName;
column.maxWidth = Math.ceil(column.maxWidth);
column.minWidth = Math.ceil(column.minWidth);
column.truncate = !!column.truncate;
column.align = column.align || 'left';
});
// sanitize data
items = items.map(function (item) {
var result = Object.create(null);
columnNames.forEach(function (columnName) {
// null/undefined -> ''
result[columnName] = item[columnName] != null ? item[columnName] : '';
// toString everything
result[columnName] = '' + result[columnName];
if (columns[columnName].preserveNewLines) {
// merge non-newline whitespace chars
result[columnName] = result[columnName].replace(/[^\S\n]/gmi, ' ');
} else {
// merge all whitespace chars
result[columnName] = result[columnName].replace(/\s/gmi, ' ');
}
});
return result;
});
// transform data cells
columnNames.forEach(function (columnName) {
var column = columns[columnName];
items = items.map(function (item, index) {
var col = Object.create(column);
item[columnName] = column.dataTransform(item[columnName], col, index);
var changedKeys = Object.keys(col);
// disable default heading transform if we wrote to column.name
if (changedKeys.indexOf('name') !== -1) {
if (column.headingTransform !== DEFAULT_HEADING_TRANSFORM) return;
column.headingTransform = function (heading) {
return heading;
};
}
changedKeys.forEach(function (key) {
return column[key] = col[key];
});
return item;
});
});
// add headers
var headers = {};
if (options.showHeaders) {
columnNames.forEach(function (columnName) {
var column = columns[columnName];
if (!column.showHeaders) {
headers[columnName] = '';
return;
}
headers[columnName] = column.headingTransform(column.name);
});
items.unshift(headers);
}
// get actual max-width between min & max
// based on length of data in columns
columnNames.forEach(function (columnName) {
var column = columns[columnName];
column.width = items.map(function (item) {
return item[columnName];
}).reduce(function (min, cur) {
// if already at maxWidth don't bother testing
if (min >= column.maxWidth) return min;
return Math.max(min, Math.min(column.maxWidth, Math.max(column.minWidth, wcwidth(cur))));
}, 0);
});
// split long words so they can break onto multiple lines
columnNames.forEach(function (columnName) {
var column = columns[columnName];
items = items.map(function (item) {
item[columnName] = splitLongWords(item[columnName], column.width, column.truncateMarker);
return item;
});
});
// wrap long lines. each item is now an array of lines.
columnNames.forEach(function (columnName) {
var column = columns[columnName];
items = items.map(function (item, index) {
var cell = item[columnName];
item[columnName] = splitIntoLines(cell, column.width);
// if truncating required, only include first line + add truncation char
if (column.truncate && item[columnName].length > 1) {
item[columnName] = splitIntoLines(cell, column.width - wcwidth(column.truncateMarker));
var firstLine = item[columnName][0];
if (!endsWith(firstLine, column.truncateMarker)) item[columnName][0] += column.truncateMarker;
item[columnName] = item[columnName].slice(0, 1);
}
return item;
});
});
// recalculate column widths from truncated output/lines
columnNames.forEach(function (columnName) {
var column = columns[columnName];
column.width = items.map(function (item) {
return item[columnName].reduce(function (min, cur) {
if (min >= column.maxWidth) return min;
return Math.max(min, Math.min(column.maxWidth, Math.max(column.minWidth, wcwidth(cur))));
}, 0);
}).reduce(function (min, cur) {
if (min >= column.maxWidth) return min;
return Math.max(min, Math.min(column.maxWidth, Math.max(column.minWidth, cur)));
}, 0);
});
var rows = createRows(items, columns, columnNames, options.paddingChr); // merge lines into rows
// conceive output
return rows.reduce(function (output, row) {
return output.concat(row.reduce(function (rowOut, line) {
return rowOut.concat(line.join(options.columnSplitter));
}, []));
}, []).map(function (line) {
return truncateString(line, maxLineWidth);
}).join(options.spacing);
};
/**
* Convert wrapped lines into rows with padded values.
*
* @param Array items data to process
* @param Array columns column width settings for wrapping
* @param Array columnNames column ordering
* @return Array items wrapped in arrays, corresponding to lines
*/
function createRows(items, columns, columnNames, paddingChr) {
return items.map(function (item) {
var row = [];
var numLines = 0;
columnNames.forEach(function (columnName) {
numLines = Math.max(numLines, item[columnName].length);
});
// combine matching lines of each rows
var _loop = function _loop(i) {
row[i] = row[i] || [];
columnNames.forEach(function (columnName) {
var column = columns[columnName];
var val = item[columnName][i] || ''; // || '' ensures empty columns get padded
if (column.align === 'right') row[i].push(padLeft(val, column.width, paddingChr));else if (column.align === 'center' || column.align === 'centre') row[i].push(padCenter(val, column.width, paddingChr));else row[i].push(padRight(val, column.width, paddingChr));
});
};
for (var i = 0; i < numLines; i++) {
_loop(i);
}
return row;
});
}
/**
* Object.assign
*
* @return Object Object with properties mixed in.
*/
function mixin() {
var _Object;
if (Object.assign) return (_Object = Object).assign.apply(_Object, arguments);
return ObjectAssign.apply(undefined, arguments);
}
function ObjectAssign(target, firstSource) {
"use strict";
if (target === undefined || target === null) throw new TypeError("Cannot convert first argument to object");
var to = Object(target);
var hasPendingException = false;
var pendingException;
for (var i = 1; i < arguments.length; i++) {
var nextSource = arguments[i];
if (nextSource === undefined || nextSource === null) continue;
var keysArray = Object.keys(Object(nextSource));
for (var nextIndex = 0, len = keysArray.length; nextIndex < len; nextIndex++) {
var nextKey = keysArray[nextIndex];
try {
var desc = Object.getOwnPropertyDescriptor(nextSource, nextKey);
if (desc !== undefined && desc.enumerable) to[nextKey] = nextSource[nextKey];
} catch (e) {
if (!hasPendingException) {
hasPendingException = true;
pendingException = e;
}
}
}
if (hasPendingException) throw pendingException;
}
return to;
}
/**
* Adapted from String.prototype.endsWith polyfill.
*/
function endsWith(target, searchString, position) {
position = position || target.length;
position = position - searchString.length;
var lastIndex = target.lastIndexOf(searchString);
return lastIndex !== -1 && lastIndex === position;
}
function toArray(items, columnNames) {
if (Array.isArray(items)) return items;
var rows = [];
for (var key in items) {
var item = {};
item[columnNames[0] || 'key'] = key;
item[columnNames[1] || 'value'] = items[key];
rows.push(item);
}
return rows;
}

297
node_modules/typings/node_modules/columnify/index.js generated vendored Normal file
View File

@ -0,0 +1,297 @@
"use strict"
const wcwidth = require('./width')
const {
padRight,
padCenter,
padLeft,
splitIntoLines,
splitLongWords,
truncateString
} = require('./utils')
const DEFAULT_HEADING_TRANSFORM = key => key.toUpperCase()
const DEFAULT_DATA_TRANSFORM = (cell, column, index) => cell
const DEFAULTS = Object.freeze({
maxWidth: Infinity,
minWidth: 0,
columnSplitter: ' ',
truncate: false,
truncateMarker: '…',
preserveNewLines: false,
paddingChr: ' ',
showHeaders: true,
headingTransform: DEFAULT_HEADING_TRANSFORM,
dataTransform: DEFAULT_DATA_TRANSFORM
})
module.exports = function(items, options = {}) {
let columnConfigs = options.config || {}
delete options.config // remove config so doesn't appear on every column.
let maxLineWidth = options.maxLineWidth || Infinity
if (maxLineWidth === 'auto') maxLineWidth = process.stdout.columns || Infinity
delete options.maxLineWidth // this is a line control option, don't pass it to column
// Option defaults inheritance:
// options.config[columnName] => options => DEFAULTS
options = mixin({}, DEFAULTS, options)
options.config = options.config || Object.create(null)
options.spacing = options.spacing || '\n' // probably useless
options.preserveNewLines = !!options.preserveNewLines
options.showHeaders = !!options.showHeaders;
options.columns = options.columns || options.include // alias include/columns, prefer columns if supplied
let columnNames = options.columns || [] // optional user-supplied columns to include
items = toArray(items, columnNames)
// if not suppled column names, automatically determine columns from data keys
if (!columnNames.length) {
items.forEach(function(item) {
for (let columnName in item) {
if (columnNames.indexOf(columnName) === -1) columnNames.push(columnName)
}
})
}
// initialize column defaults (each column inherits from options.config)
let columns = columnNames.reduce((columns, columnName) => {
let column = Object.create(options)
columns[columnName] = mixin(column, columnConfigs[columnName])
return columns
}, Object.create(null))
// sanitize column settings
columnNames.forEach(columnName => {
let column = columns[columnName]
column.name = columnName
column.maxWidth = Math.ceil(column.maxWidth)
column.minWidth = Math.ceil(column.minWidth)
column.truncate = !!column.truncate
column.align = column.align || 'left'
})
// sanitize data
items = items.map(item => {
let result = Object.create(null)
columnNames.forEach(columnName => {
// null/undefined -> ''
result[columnName] = item[columnName] != null ? item[columnName] : ''
// toString everything
result[columnName] = '' + result[columnName]
if (columns[columnName].preserveNewLines) {
// merge non-newline whitespace chars
result[columnName] = result[columnName].replace(/[^\S\n]/gmi, ' ')
} else {
// merge all whitespace chars
result[columnName] = result[columnName].replace(/\s/gmi, ' ')
}
})
return result
})
// transform data cells
columnNames.forEach(columnName => {
let column = columns[columnName]
items = items.map((item, index) => {
let col = Object.create(column)
item[columnName] = column.dataTransform(item[columnName], col, index)
let changedKeys = Object.keys(col)
// disable default heading transform if we wrote to column.name
if (changedKeys.indexOf('name') !== -1) {
if (column.headingTransform !== DEFAULT_HEADING_TRANSFORM) return
column.headingTransform = heading => heading
}
changedKeys.forEach(key => column[key] = col[key])
return item
})
})
// add headers
let headers = {}
if(options.showHeaders) {
columnNames.forEach(columnName => {
let column = columns[columnName]
if(!column.showHeaders){
headers[columnName] = '';
return;
}
headers[columnName] = column.headingTransform(column.name)
})
items.unshift(headers)
}
// get actual max-width between min & max
// based on length of data in columns
columnNames.forEach(columnName => {
let column = columns[columnName]
column.width = items
.map(item => item[columnName])
.reduce((min, cur) => {
// if already at maxWidth don't bother testing
if (min >= column.maxWidth) return min
return Math.max(min, Math.min(column.maxWidth, Math.max(column.minWidth, wcwidth(cur))))
}, 0)
})
// split long words so they can break onto multiple lines
columnNames.forEach(columnName => {
let column = columns[columnName]
items = items.map(item => {
item[columnName] = splitLongWords(item[columnName], column.width, column.truncateMarker)
return item
})
})
// wrap long lines. each item is now an array of lines.
columnNames.forEach(columnName => {
let column = columns[columnName]
items = items.map((item, index) => {
let cell = item[columnName]
item[columnName] = splitIntoLines(cell, column.width)
// if truncating required, only include first line + add truncation char
if (column.truncate && item[columnName].length > 1) {
item[columnName] = splitIntoLines(cell, column.width - wcwidth(column.truncateMarker))
let firstLine = item[columnName][0]
if (!endsWith(firstLine, column.truncateMarker)) item[columnName][0] += column.truncateMarker
item[columnName] = item[columnName].slice(0, 1)
}
return item
})
})
// recalculate column widths from truncated output/lines
columnNames.forEach(columnName => {
let column = columns[columnName]
column.width = items.map(item => {
return item[columnName].reduce((min, cur) => {
if (min >= column.maxWidth) return min
return Math.max(min, Math.min(column.maxWidth, Math.max(column.minWidth, wcwidth(cur))))
}, 0)
}).reduce((min, cur) => {
if (min >= column.maxWidth) return min
return Math.max(min, Math.min(column.maxWidth, Math.max(column.minWidth, cur)))
}, 0)
})
let rows = createRows(items, columns, columnNames, options.paddingChr) // merge lines into rows
// conceive output
return rows.reduce((output, row) => {
return output.concat(row.reduce((rowOut, line) => {
return rowOut.concat(line.join(options.columnSplitter))
}, []))
}, [])
.map(line => truncateString(line, maxLineWidth))
.join(options.spacing)
}
/**
* Convert wrapped lines into rows with padded values.
*
* @param Array items data to process
* @param Array columns column width settings for wrapping
* @param Array columnNames column ordering
* @return Array items wrapped in arrays, corresponding to lines
*/
function createRows(items, columns, columnNames, paddingChr) {
return items.map(item => {
let row = []
let numLines = 0
columnNames.forEach(columnName => {
numLines = Math.max(numLines, item[columnName].length)
})
// combine matching lines of each rows
for (let i = 0; i < numLines; i++) {
row[i] = row[i] || []
columnNames.forEach(columnName => {
let column = columns[columnName]
let val = item[columnName][i] || '' // || '' ensures empty columns get padded
if (column.align === 'right') row[i].push(padLeft(val, column.width, paddingChr))
else if (column.align === 'center' || column.align === 'centre') row[i].push(padCenter(val, column.width, paddingChr))
else row[i].push(padRight(val, column.width, paddingChr))
})
}
return row
})
}
/**
* Object.assign
*
* @return Object Object with properties mixed in.
*/
function mixin(...args) {
if (Object.assign) return Object.assign(...args)
return ObjectAssign(...args)
}
function ObjectAssign(target, firstSource) {
"use strict";
if (target === undefined || target === null)
throw new TypeError("Cannot convert first argument to object");
var to = Object(target);
var hasPendingException = false;
var pendingException;
for (var i = 1; i < arguments.length; i++) {
var nextSource = arguments[i];
if (nextSource === undefined || nextSource === null)
continue;
var keysArray = Object.keys(Object(nextSource));
for (var nextIndex = 0, len = keysArray.length; nextIndex < len; nextIndex++) {
var nextKey = keysArray[nextIndex];
try {
var desc = Object.getOwnPropertyDescriptor(nextSource, nextKey);
if (desc !== undefined && desc.enumerable)
to[nextKey] = nextSource[nextKey];
} catch (e) {
if (!hasPendingException) {
hasPendingException = true;
pendingException = e;
}
}
}
if (hasPendingException)
throw pendingException;
}
return to;
}
/**
* Adapted from String.prototype.endsWith polyfill.
*/
function endsWith(target, searchString, position) {
position = position || target.length;
position = position - searchString.length;
let lastIndex = target.lastIndexOf(searchString);
return lastIndex !== -1 && lastIndex === position;
}
function toArray(items, columnNames) {
if (Array.isArray(items)) return items
let rows = []
for (let key in items) {
let item = {}
item[columnNames[0] || 'key'] = key
item[columnNames[1] || 'value'] = items[key]
rows.push(item)
}
return rows
}

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