전수민

merge with master

Showing 212 changed files with 4850 additions and 36 deletions
File mode changed
1 -var map;
2 var pos; 1 var pos;
2 +var map;
3 var infowindow; 3 var infowindow;
4 var service; 4 var service;
5 5
6 function initMap() { 6 function initMap() {
7 - map = new google.maps.Map(document.getElementById('map'), { 7 +
8 + map = new google.maps.Map(document.getElementById('map'), {
8 center: {lat: -34.397, lng: 150.644}, 9 center: {lat: -34.397, lng: 150.644},
9 zoom: 17 10 zoom: 17
10 }); 11 });
11 infowindow = new google.maps.InfoWindow(); 12 infowindow = new google.maps.InfoWindow();
12 13
13 -
14 // Try HTML5 geolocation. 14 // Try HTML5 geolocation.
15 if (navigator.geolocation) { 15 if (navigator.geolocation) {
16 navigator.geolocation.getCurrentPosition(function(position) { 16 navigator.geolocation.getCurrentPosition(function(position) {
...@@ -19,22 +19,22 @@ function initMap() { ...@@ -19,22 +19,22 @@ function initMap() {
19 lng: position.coords.longitude 19 lng: position.coords.longitude
20 }; 20 };
21 21
22 + var map = new google.maps.Map(document.getElementById('map'), {
23 + center: pos,
24 + zoom: 17
25 + });
26 + infowindow = new google.maps.InfoWindow();
27 +
22 map.setCenter(pos); 28 map.setCenter(pos);
23 29
24 service = new google.maps.places.PlacesService(map); 30 service = new google.maps.places.PlacesService(map);
25 31
26 - service.nearbySearch({
27 - location: pos,
28 - radius: 500,
29 - type: ['bakery']
30 - }, callback_foods);
31 -
32 searchPlace('bar','food'); 32 searchPlace('bar','food');
33 searchPlace('cafe','food'); 33 searchPlace('cafe','food');
34 searchPlace('meal_delivery','food'); 34 searchPlace('meal_delivery','food');
35 searchPlace('meal_takeaway','food'); 35 searchPlace('meal_takeaway','food');
36 searchPlace('restaurant','food'); 36 searchPlace('restaurant','food');
37 - 37 + searchPlace('bakery','food');
38 38
39 searchPlace('department_store','entertainment'); 39 searchPlace('department_store','entertainment');
40 searchPlace('movie_theater','entertainment'); 40 searchPlace('movie_theater','entertainment');
...@@ -44,31 +44,46 @@ function initMap() { ...@@ -44,31 +44,46 @@ function initMap() {
44 searchPlace('zoo','entertainment'); 44 searchPlace('zoo','entertainment');
45 45
46 searchPlace('lodging','room'); 46 searchPlace('lodging','room');
47 +
48 + // put data to db
49 + for (var i = 0; i < results_food.length; i++) {
50 + //putDataToDB(results_food[i], 'food')
51 + console.log(results_food[i])
52 + }
53 + for (var i = 0; i < results_entertainment.length; i++) {
54 + //putDataToDB(results_entertainment[i], 'entertainment')
55 + console.log(results_entertainment[i])
56 + }
57 + for (var i = 0; i < results_room.length; i++) {
58 + //putDataToDB(results_room[i], 'room')
59 + console.log(results_room[i])
60 + }
47 }); 61 });
48 } 62 }
49 } 63 }
50 64
65 +
51 function searchPlace(str, placeType) { 66 function searchPlace(str, placeType) {
52 switch(placeType) { 67 switch(placeType) {
53 case 'food': 68 case 'food':
54 service.nearbySearch({ 69 service.nearbySearch({
55 location: pos, 70 location: pos,
56 radius: 500, 71 radius: 500,
57 - type: ['meal_takeaway'] 72 + type: [str]
58 }, callback_foods); 73 }, callback_foods);
59 break; 74 break;
60 case 'entertainment': 75 case 'entertainment':
61 service.nearbySearch({ 76 service.nearbySearch({
62 location: pos, 77 location: pos,
63 radius: 500, 78 radius: 500,
64 - type: [str.toString()] 79 + type: [str]
65 }, callback_entertainment); 80 }, callback_entertainment);
66 break; 81 break;
67 case 'room': 82 case 'room':
68 service.nearbySearch({ 83 service.nearbySearch({
69 location: pos, 84 location: pos,
70 radius: 500, 85 radius: 500,
71 - type: ['lodging'] 86 + type: [str]
72 }, callback_rooms); 87 }, callback_rooms);
73 break; 88 break;
74 default: 89 default:
...@@ -80,7 +95,7 @@ function searchPlace(str, placeType) { ...@@ -80,7 +95,7 @@ function searchPlace(str, placeType) {
80 function callback_foods(results, status) { 95 function callback_foods(results, status) {
81 if (status === google.maps.places.PlacesServiceStatus.OK) { 96 if (status === google.maps.places.PlacesServiceStatus.OK) {
82 for (var i = 0; i < results.length; i++) { 97 for (var i = 0; i < results.length; i++) {
83 - result_food.push(results[i]); 98 + putDataToDB(results[i], 'food')
84 createMarker_foods(results[i]); 99 createMarker_foods(results[i]);
85 } 100 }
86 } 101 }
...@@ -89,7 +104,7 @@ function callback_foods(results, status) { ...@@ -89,7 +104,7 @@ function callback_foods(results, status) {
89 function callback_entertainment(results, status) { 104 function callback_entertainment(results, status) {
90 if (status === google.maps.places.PlacesServiceStatus.OK) { 105 if (status === google.maps.places.PlacesServiceStatus.OK) {
91 for (var i = 0; i < results.length; i++) { 106 for (var i = 0; i < results.length; i++) {
92 - result_entertainment.push(results[i]); 107 + putDataToDB(results[i], 'entertainment')
93 createMarker_entertainment(results[i]); 108 createMarker_entertainment(results[i]);
94 } 109 }
95 } 110 }
...@@ -98,14 +113,12 @@ function callback_entertainment(results, status) { ...@@ -98,14 +113,12 @@ function callback_entertainment(results, status) {
98 function callback_rooms(results, status) { 113 function callback_rooms(results, status) {
99 if (status === google.maps.places.PlacesServiceStatus.OK) { 114 if (status === google.maps.places.PlacesServiceStatus.OK) {
100 for (var i = 0; i < results.length; i++) { 115 for (var i = 0; i < results.length; i++) {
101 - result_room.push(results[i]); 116 + putDataToDB(results[i], 'room')
102 - createMarker_rooms(results[i]); 117 + createMarker_rooms(results[i]);
103 } 118 }
104 } 119 }
105 } 120 }
106 121
107 -
108 -
109 function createMarker_foods(place) { 122 function createMarker_foods(place) {
110 var marker = new google.maps.Marker({ 123 var marker = new google.maps.Marker({
111 map: map, 124 map: map,
...@@ -146,4 +159,82 @@ function createMarker_rooms(place) { ...@@ -146,4 +159,82 @@ function createMarker_rooms(place) {
146 infowindow.setContent(place.name); 159 infowindow.setContent(place.name);
147 infowindow.open(map, this); 160 infowindow.open(map, this);
148 }); 161 });
149 -}
...\ No newline at end of file ...\ No newline at end of file
162 +}
163 +
164 +function putDataToDB(result, category1) {
165 + const id = result['id'];
166 + const place_id =result['place_id'];
167 + const name = result['name'];
168 + const address = result['vicinity'];
169 + let category_big = category1
170 + const category_small = result.types[0];
171 + const image = "default"
172 + const rating = result.rating;
173 + const lng = result.geometry.viewport.ea.j;
174 + const lat =result.geometry.viewport.la.j;
175 +
176 + if(rating == null) {
177 + rating = 0;
178 + }
179 + const QueryCheck = () => {
180 + if (!id || !place_id || !name || !address || !category_big || !category_small || !image || !rating || !lng || !lat) {
181 + return Promise.reject({
182 + message: 'Query Error'
183 + })
184 + }
185 + return Promise.resolve()
186 + }
187 +
188 + // 2. SQL Start
189 + const SQLStart = async (pool) => {
190 + try {
191 + let data = await pool.query('INSERT INTO PLACE(ID, PLACE_ID, NAME, ADDRESS, CATEGORY_BIG, CATEGORY_SMALL, IMAGE, RATING, LNG, LAT) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?);', [id, place_id, name, address, category_big, category_small, image, rating, lng, lat])
192 + return Promise.resolve(pool)
193 + } catch(err) {
194 + return Promise.reject(err)
195 + }
196 + }
197 + // 3. Response
198 + const Response = (rows) => {
199 + return res.status(200).json(rows)
200 + }
201 +
202 + // 1. Query Check
203 + const FindQueryCheck = () => {
204 + if (!id) {
205 + return Promise.reject({
206 + message: 'Query Error'
207 + })
208 + }
209 + else return pool
210 + }
211 +
212 + // 2. SQL Start
213 + const FindSQLStart = (pool) => {
214 + return pool.query('SELECT * FROM PLACE WHERE ID LIKE '+id.toString())
215 + }
216 +
217 + // 3. Response
218 + const FindResponse = (rows) => {
219 + return res.status(200).json(rows)
220 + }
221 +
222 + if([] == FindQueryCheck()
223 + .then(FindSQLStart)
224 + .then(FindResponse)
225 + .catch(err => {
226 + if (err) {
227 + return res.status(500).json(err.message || err)
228 + }
229 + }))
230 + {
231 + QueryCheck()
232 + .then(SQLStart)
233 + .then(Response)
234 + .catch(err => {
235 + if (err) {
236 + return res.status(500).json(err.message || err)
237 + }
238 + })
239 + }
240 +}
......
1 var express = require('express'); 1 var express = require('express');
2 -var path = require('path'); 2 +var router = require('./routes/index');
3 -var cookieParser = require('cookie-parser');
4 -var logger = require('morgan');
5 -
6 -var indexRouter = require('./routes/index');
7 -var usersRouter = require('./routes/users');
8 -
9 var app = express(); 3 var app = express();
10 4
11 -app.use(logger('dev')); 5 +app.use('/', router);
12 -app.use(express.json());
13 -app.use(express.urlencoded({ extended: false }));
14 -app.use(cookieParser());
15 -app.use(express.static(path.join(__dirname, 'public')));
16 -
17 -app.use('/', indexRouter);
18 -app.use('/users', usersRouter);
19 6
20 var server = app.listen(3000); 7 var server = app.listen(3000);
......
1 -console.log("Hello World!");
...\ No newline at end of file ...\ No newline at end of file
1 +const mysql = require('promise-mysql')
2 +
3 +module.exports = mysql.createConnection({
4 + host: "52.79.82.27",
5 + user: "root",
6 + password: "oss",
7 + database: "OSS"
8 +})
1 + MIT License
2 +
3 + Copyright (c) Microsoft Corporation. All rights reserved.
4 +
5 + Permission is hereby granted, free of charge, to any person obtaining a copy
6 + of this software and associated documentation files (the "Software"), to deal
7 + in the Software without restriction, including without limitation the rights
8 + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 + copies of the Software, and to permit persons to whom the Software is
10 + furnished to do so, subject to the following conditions:
11 +
12 + The above copyright notice and this permission notice shall be included in all
13 + copies or substantial portions of the Software.
14 +
15 + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 + SOFTWARE
1 +# Installation
2 +> `npm install --save @types/bluebird`
3 +
4 +# Summary
5 +This package contains type definitions for bluebird (https://github.com/petkaantonov/bluebird).
6 +
7 +# Details
8 +Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/bluebird
9 +
10 +Additional Details
11 + * Last updated: Mon, 27 Aug 2018 22:59:40 GMT
12 + * Dependencies: none
13 + * Global values: none
14 +
15 +# Credits
16 +These definitions were written by Leonard Hecker <https://github.com/lhecker>.
This diff is collapsed. Click to expand it.
1 +{
2 + "_from": "@types/bluebird@^3.5.19",
3 + "_id": "@types/bluebird@3.5.24",
4 + "_inBundle": false,
5 + "_integrity": "sha512-YeQoDpq4Lm8ppSBqAnAeF/xy1cYp/dMTif2JFcvmAbETMRlvKHT2iLcWu+WyYiJO3b3Ivokwo7EQca/xfLVJmg==",
6 + "_location": "/@types/bluebird",
7 + "_phantomChildren": {},
8 + "_requested": {
9 + "type": "range",
10 + "registry": true,
11 + "raw": "@types/bluebird@^3.5.19",
12 + "name": "@types/bluebird",
13 + "escapedName": "@types%2fbluebird",
14 + "scope": "@types",
15 + "rawSpec": "^3.5.19",
16 + "saveSpec": null,
17 + "fetchSpec": "^3.5.19"
18 + },
19 + "_requiredBy": [
20 + "/promise-mysql"
21 + ],
22 + "_resolved": "https://registry.npmjs.org/@types/bluebird/-/bluebird-3.5.24.tgz",
23 + "_shasum": "11f76812531c14f793b8ecbf1de96f672905de8a",
24 + "_spec": "@types/bluebird@^3.5.19",
25 + "_where": "/Users/donghoon/Documents/Classroom/OpenSourceS:W/Project/node_modules/promise-mysql",
26 + "bugs": {
27 + "url": "https://github.com/DefinitelyTyped/DefinitelyTyped/issues"
28 + },
29 + "bundleDependencies": false,
30 + "contributors": [
31 + {
32 + "name": "Leonard Hecker",
33 + "url": "https://github.com/lhecker"
34 + }
35 + ],
36 + "dependencies": {},
37 + "deprecated": false,
38 + "description": "TypeScript definitions for bluebird",
39 + "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped#readme",
40 + "license": "MIT",
41 + "main": "",
42 + "name": "@types/bluebird",
43 + "repository": {
44 + "type": "git",
45 + "url": "git+https://github.com/DefinitelyTyped/DefinitelyTyped.git"
46 + },
47 + "scripts": {},
48 + "typeScriptVersion": "2.8",
49 + "typesPublisherContentHash": "886708ab10a8bb6421a5748563a83e005973395bfeff5765f04a8b35fa01a420",
50 + "version": "3.5.24"
51 +}
1 + MIT License
2 +
3 + Copyright (c) Microsoft Corporation. All rights reserved.
4 +
5 + Permission is hereby granted, free of charge, to any person obtaining a copy
6 + of this software and associated documentation files (the "Software"), to deal
7 + in the Software without restriction, including without limitation the rights
8 + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 + copies of the Software, and to permit persons to whom the Software is
10 + furnished to do so, subject to the following conditions:
11 +
12 + The above copyright notice and this permission notice shall be included in all
13 + copies or substantial portions of the Software.
14 +
15 + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 + SOFTWARE
1 +# Installation
2 +> `npm install --save @types/mysql`
3 +
4 +# Summary
5 +This package contains type definitions for mysql (https://github.com/mysqljs/mysql).
6 +
7 +# Details
8 +Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/mysql
9 +
10 +Additional Details
11 + * Last updated: Thu, 31 May 2018 20:09:03 GMT
12 + * Dependencies: stream, tls, node
13 + * Global values: none
14 +
15 +# Credits
16 +These definitions were written by William Johnston <https://github.com/wjohnsto>, Kacper Polak <https://github.com/kacepe>, Krittanan Pingclasai <https://github.com/kpping>, James Munro <https://github.com/jdmunro>.
This diff is collapsed. Click to expand it.
1 +{
2 + "_from": "@types/mysql@^2.15.2",
3 + "_id": "@types/mysql@2.15.5",
4 + "_inBundle": false,
5 + "_integrity": "sha512-4QAISTUGZbcFh7bqdndo08xRdES5OTU+JODy8VCZbe1yiXyGjqw1H83G43XjQ3IbC10wn9xlGd44A5RXJwNh0Q==",
6 + "_location": "/@types/mysql",
7 + "_phantomChildren": {},
8 + "_requested": {
9 + "type": "range",
10 + "registry": true,
11 + "raw": "@types/mysql@^2.15.2",
12 + "name": "@types/mysql",
13 + "escapedName": "@types%2fmysql",
14 + "scope": "@types",
15 + "rawSpec": "^2.15.2",
16 + "saveSpec": null,
17 + "fetchSpec": "^2.15.2"
18 + },
19 + "_requiredBy": [
20 + "/promise-mysql"
21 + ],
22 + "_resolved": "https://registry.npmjs.org/@types/mysql/-/mysql-2.15.5.tgz",
23 + "_shasum": "6d75afb5cc018c9d66b2f37a046924e397f85430",
24 + "_spec": "@types/mysql@^2.15.2",
25 + "_where": "/Users/donghoon/Documents/Classroom/OpenSourceS:W/Project/node_modules/promise-mysql",
26 + "bugs": {
27 + "url": "https://github.com/DefinitelyTyped/DefinitelyTyped/issues"
28 + },
29 + "bundleDependencies": false,
30 + "contributors": [
31 + {
32 + "name": "William Johnston",
33 + "url": "https://github.com/wjohnsto"
34 + },
35 + {
36 + "name": "Kacper Polak",
37 + "url": "https://github.com/kacepe"
38 + },
39 + {
40 + "name": "Krittanan Pingclasai",
41 + "url": "https://github.com/kpping"
42 + },
43 + {
44 + "name": "James Munro",
45 + "url": "https://github.com/jdmunro"
46 + }
47 + ],
48 + "dependencies": {
49 + "@types/node": "*"
50 + },
51 + "deprecated": false,
52 + "description": "TypeScript definitions for mysql",
53 + "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped#readme",
54 + "license": "MIT",
55 + "main": "",
56 + "name": "@types/mysql",
57 + "repository": {
58 + "type": "git",
59 + "url": "git+https://github.com/DefinitelyTyped/DefinitelyTyped.git"
60 + },
61 + "scripts": {},
62 + "typeScriptVersion": "2.1",
63 + "typesPublisherContentHash": "5ab0640250fb34af9e11026236c9009f506a78be9ddd17745a348947c3766d6f",
64 + "version": "2.15.5"
65 +}
1 + MIT License
2 +
3 + Copyright (c) Microsoft Corporation. All rights reserved.
4 +
5 + Permission is hereby granted, free of charge, to any person obtaining a copy
6 + of this software and associated documentation files (the "Software"), to deal
7 + in the Software without restriction, including without limitation the rights
8 + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 + copies of the Software, and to permit persons to whom the Software is
10 + furnished to do so, subject to the following conditions:
11 +
12 + The above copyright notice and this permission notice shall be included in all
13 + copies or substantial portions of the Software.
14 +
15 + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 + SOFTWARE
1 +# Installation
2 +> `npm install --save @types/node`
3 +
4 +# Summary
5 +This package contains type definitions for Node.js (http://nodejs.org/).
6 +
7 +# Details
8 +Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/node
9 +
10 +Additional Details
11 + * Last updated: Thu, 13 Dec 2018 19:22:44 GMT
12 + * Dependencies: none
13 + * Global values: Buffer, NodeJS, SlowBuffer, Symbol, __dirname, __filename, clearImmediate, clearInterval, clearTimeout, console, exports, global, module, process, require, setImmediate, setInterval, setTimeout
14 +
15 +# Credits
16 +These definitions were written by Microsoft TypeScript <https://github.com/Microsoft>, DefinitelyTyped <https://github.com/DefinitelyTyped>, Alberto Schiabel <https://github.com/jkomyno>, Alexander T. <https://github.com/a-tarasyuk>, Alvis HT Tang <https://github.com/alvis>, Andrew Makarov <https://github.com/r3nya>, Bruno Scheufler <https://github.com/brunoscheufler>, Chigozirim C. <https://github.com/smac89>, Christian Vaagland Tellnes <https://github.com/tellnes>, Deividas Bakanas <https://github.com/DeividasBakanas>, Eugene Y. Q. Shen <https://github.com/eyqs>, Flarna <https://github.com/Flarna>, Hannes Magnusson <https://github.com/Hannes-Magnusson-CK>, Hoàng Văn Khải <https://github.com/KSXGitHub>, Huw <https://github.com/hoo29>, Kelvin Jin <https://github.com/kjin>, Klaus Meinhardt <https://github.com/ajafff>, Lishude <https://github.com/islishude>, Mariusz Wiktorczyk <https://github.com/mwiktorczyk>, Matthieu Sieben <https://github.com/matthieusieben>, Mohsen Azimi <https://github.com/mohsen1>, Nicolas Even <https://github.com/n-e>, Nicolas Voigt <https://github.com/octo-sniffle>, Parambir Singh <https://github.com/parambirs>, Sebastian Silbermann <https://github.com/eps1lon>, Simon Schick <https://github.com/SimonSchick>, Thomas den Hollander <https://github.com/ThomasdenH>, Wilco Bakker <https://github.com/WilcoBakker>, wwwy3y3 <https://github.com/wwwy3y3>, Zane Hannan AU <https://github.com/ZaneHannanAU>, Jeremie Rodriguez <https://github.com/jeremiergz>, Samuel Ainsworth <https://github.com/samuela>.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
1 +{
2 + "_from": "@types/node@*",
3 + "_id": "@types/node@10.12.15",
4 + "_inBundle": false,
5 + "_integrity": "sha512-9kROxduaN98QghwwHmxXO2Xz3MaWf+I1sLVAA6KJDF5xix+IyXVhds0MAfdNwtcpSrzhaTsNB0/jnL86fgUhqA==",
6 + "_location": "/@types/node",
7 + "_phantomChildren": {},
8 + "_requested": {
9 + "type": "range",
10 + "registry": true,
11 + "raw": "@types/node@*",
12 + "name": "@types/node",
13 + "escapedName": "@types%2fnode",
14 + "scope": "@types",
15 + "rawSpec": "*",
16 + "saveSpec": null,
17 + "fetchSpec": "*"
18 + },
19 + "_requiredBy": [
20 + "/@types/mysql"
21 + ],
22 + "_resolved": "https://registry.npmjs.org/@types/node/-/node-10.12.15.tgz",
23 + "_shasum": "20e85651b62fd86656e57c9c9bc771ab1570bc59",
24 + "_spec": "@types/node@*",
25 + "_where": "/Users/donghoon/Documents/Classroom/OpenSourceS:W/Project/node_modules/@types/mysql",
26 + "bugs": {
27 + "url": "https://github.com/DefinitelyTyped/DefinitelyTyped/issues"
28 + },
29 + "bundleDependencies": false,
30 + "contributors": [
31 + {
32 + "name": "Microsoft TypeScript",
33 + "url": "https://github.com/Microsoft"
34 + },
35 + {
36 + "name": "DefinitelyTyped",
37 + "url": "https://github.com/DefinitelyTyped"
38 + },
39 + {
40 + "name": "Alberto Schiabel",
41 + "url": "https://github.com/jkomyno"
42 + },
43 + {
44 + "name": "Alexander T.",
45 + "url": "https://github.com/a-tarasyuk"
46 + },
47 + {
48 + "name": "Alvis HT Tang",
49 + "url": "https://github.com/alvis"
50 + },
51 + {
52 + "name": "Andrew Makarov",
53 + "url": "https://github.com/r3nya"
54 + },
55 + {
56 + "name": "Bruno Scheufler",
57 + "url": "https://github.com/brunoscheufler"
58 + },
59 + {
60 + "name": "Chigozirim C.",
61 + "url": "https://github.com/smac89"
62 + },
63 + {
64 + "name": "Christian Vaagland Tellnes",
65 + "url": "https://github.com/tellnes"
66 + },
67 + {
68 + "name": "Deividas Bakanas",
69 + "url": "https://github.com/DeividasBakanas"
70 + },
71 + {
72 + "name": "Eugene Y. Q. Shen",
73 + "url": "https://github.com/eyqs"
74 + },
75 + {
76 + "name": "Flarna",
77 + "url": "https://github.com/Flarna"
78 + },
79 + {
80 + "name": "Hannes Magnusson",
81 + "url": "https://github.com/Hannes-Magnusson-CK"
82 + },
83 + {
84 + "name": "Hoàng Văn Khải",
85 + "url": "https://github.com/KSXGitHub"
86 + },
87 + {
88 + "name": "Huw",
89 + "url": "https://github.com/hoo29"
90 + },
91 + {
92 + "name": "Kelvin Jin",
93 + "url": "https://github.com/kjin"
94 + },
95 + {
96 + "name": "Klaus Meinhardt",
97 + "url": "https://github.com/ajafff"
98 + },
99 + {
100 + "name": "Lishude",
101 + "url": "https://github.com/islishude"
102 + },
103 + {
104 + "name": "Mariusz Wiktorczyk",
105 + "url": "https://github.com/mwiktorczyk"
106 + },
107 + {
108 + "name": "Matthieu Sieben",
109 + "url": "https://github.com/matthieusieben"
110 + },
111 + {
112 + "name": "Mohsen Azimi",
113 + "url": "https://github.com/mohsen1"
114 + },
115 + {
116 + "name": "Nicolas Even",
117 + "url": "https://github.com/n-e"
118 + },
119 + {
120 + "name": "Nicolas Voigt",
121 + "url": "https://github.com/octo-sniffle"
122 + },
123 + {
124 + "name": "Parambir Singh",
125 + "url": "https://github.com/parambirs"
126 + },
127 + {
128 + "name": "Sebastian Silbermann",
129 + "url": "https://github.com/eps1lon"
130 + },
131 + {
132 + "name": "Simon Schick",
133 + "url": "https://github.com/SimonSchick"
134 + },
135 + {
136 + "name": "Thomas den Hollander",
137 + "url": "https://github.com/ThomasdenH"
138 + },
139 + {
140 + "name": "Wilco Bakker",
141 + "url": "https://github.com/WilcoBakker"
142 + },
143 + {
144 + "name": "wwwy3y3",
145 + "url": "https://github.com/wwwy3y3"
146 + },
147 + {
148 + "name": "Zane Hannan AU",
149 + "url": "https://github.com/ZaneHannanAU"
150 + },
151 + {
152 + "name": "Jeremie Rodriguez",
153 + "url": "https://github.com/jeremiergz"
154 + },
155 + {
156 + "name": "Samuel Ainsworth",
157 + "url": "https://github.com/samuela"
158 + }
159 + ],
160 + "dependencies": {},
161 + "deprecated": false,
162 + "description": "TypeScript definitions for Node.js",
163 + "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped#readme",
164 + "license": "MIT",
165 + "main": "",
166 + "name": "@types/node",
167 + "repository": {
168 + "type": "git",
169 + "url": "git+https://github.com/DefinitelyTyped/DefinitelyTyped.git"
170 + },
171 + "scripts": {},
172 + "typeScriptVersion": "2.0",
173 + "types": "index",
174 + "typesPublisherContentHash": "3cb7c377b3501067ecca235d531f2eaf3e308568e8195e87dd75e5215e13e117",
175 + "version": "10.12.15"
176 +}
1 +The MIT Licence.
2 +
3 +Copyright (c) 2017 Michael Mclaughlin
4 +
5 +Permission is hereby granted, free of charge, to any person obtaining
6 +a copy of this software and associated documentation files (the
7 +'Software'), to deal in the Software without restriction, including
8 +without limitation the rights to use, copy, modify, merge, publish,
9 +distribute, sublicense, and/or sell copies of the Software, and to
10 +permit persons to whom the Software is furnished to do so, subject to
11 +the following conditions:
12 +
13 +The above copyright notice and this permission notice shall be
14 +included in all copies or substantial portions of the Software.
15 +
16 +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
17 +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18 +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
19 +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
20 +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
21 +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
22 +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
23 +
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
1 +{
2 + "name": "bignumber.js",
3 + "main": "bignumber.js",
4 + "version": "4.1.0",
5 + "homepage": "https://github.com/MikeMcl/bignumber.js",
6 + "authors": [
7 + "Michael Mclaughlin <M8ch88l@gmail.com>"
8 + ],
9 + "description": "A library for arbitrary-precision decimal and non-decimal arithmetic",
10 + "moduleType": [
11 + "amd",
12 + "globals",
13 + "node"
14 + ],
15 + "keywords": [
16 + "arbitrary",
17 + "precision",
18 + "arithmetic",
19 + "big",
20 + "number",
21 + "decimal",
22 + "float",
23 + "biginteger",
24 + "bigdecimal",
25 + "bignumber",
26 + "bigint",
27 + "bignum"
28 + ],
29 + "license": "MIT",
30 + "ignore": [
31 + ".*",
32 + "*.json",
33 + "test"
34 + ]
35 +}
36 +
This diff is collapsed. Click to expand it.
1 +{
2 + "_from": "bignumber.js@4.1.0",
3 + "_id": "bignumber.js@4.1.0",
4 + "_inBundle": false,
5 + "_integrity": "sha512-eJzYkFYy9L4JzXsbymsFn3p54D+llV27oTQ+ziJG7WFRheJcNZilgVXMG0LoZtlQSKBsJdWtLFqOD0u+U0jZKA==",
6 + "_location": "/bignumber.js",
7 + "_phantomChildren": {},
8 + "_requested": {
9 + "type": "version",
10 + "registry": true,
11 + "raw": "bignumber.js@4.1.0",
12 + "name": "bignumber.js",
13 + "escapedName": "bignumber.js",
14 + "rawSpec": "4.1.0",
15 + "saveSpec": null,
16 + "fetchSpec": "4.1.0"
17 + },
18 + "_requiredBy": [
19 + "/mysql"
20 + ],
21 + "_resolved": "https://registry.npmjs.org/bignumber.js/-/bignumber.js-4.1.0.tgz",
22 + "_shasum": "db6f14067c140bd46624815a7916c92d9b6c24b1",
23 + "_spec": "bignumber.js@4.1.0",
24 + "_where": "/Users/donghoon/Documents/Classroom/OpenSourceS:W/Project/node_modules/mysql",
25 + "author": {
26 + "name": "Michael Mclaughlin",
27 + "email": "M8ch88l@gmail.com"
28 + },
29 + "bugs": {
30 + "url": "https://github.com/MikeMcl/bignumber.js/issues"
31 + },
32 + "bundleDependencies": false,
33 + "deprecated": false,
34 + "description": "A library for arbitrary-precision decimal and non-decimal arithmetic",
35 + "engines": {
36 + "node": "*"
37 + },
38 + "homepage": "https://github.com/MikeMcl/bignumber.js#readme",
39 + "keywords": [
40 + "arbitrary",
41 + "precision",
42 + "arithmetic",
43 + "big",
44 + "number",
45 + "decimal",
46 + "float",
47 + "biginteger",
48 + "bigdecimal",
49 + "bignumber",
50 + "bigint",
51 + "bignum"
52 + ],
53 + "license": "MIT",
54 + "main": "bignumber.js",
55 + "name": "bignumber.js",
56 + "repository": {
57 + "type": "git",
58 + "url": "git+https://github.com/MikeMcl/bignumber.js.git"
59 + },
60 + "scripts": {
61 + "build": "uglifyjs bignumber.js --source-map bignumber.js.map -c -m -o bignumber.min.js --preamble \"/* bignumber.js v4.1.0 https://github.com/MikeMcl/bignumber.js/LICENCE */\"",
62 + "test": "node ./test/every-test.js"
63 + },
64 + "types": "bignumber.d.ts",
65 + "version": "4.1.0"
66 +}
1 +The MIT License (MIT)
2 +
3 +Copyright (c) 2013-2018 Petka Antonov
4 +
5 +Permission is hereby granted, free of charge, to any person obtaining a copy
6 +of this software and associated documentation files (the "Software"), to deal
7 +in the Software without restriction, including without limitation the rights
8 +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 +copies of the Software, and to permit persons to whom the Software is
10 +furnished to do so, subject to the following conditions:
11 +
12 +The above copyright notice and this permission notice shall be included in
13 +all copies or substantial portions of the Software.
14 +
15 +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21 +THE SOFTWARE.
1 +<a href="http://promisesaplus.com/">
2 + <img src="http://promisesaplus.com/assets/logo-small.png" alt="Promises/A+ logo"
3 + title="Promises/A+ 1.1 compliant" align="right" />
4 +</a>
5 +
6 +
7 +[![Build Status](https://travis-ci.org/petkaantonov/bluebird.svg?branch=master)](https://travis-ci.org/petkaantonov/bluebird)
8 +[![coverage-98%](https://img.shields.io/badge/coverage-98%25-brightgreen.svg?style=flat)](http://petkaantonov.github.io/bluebird/coverage/debug/index.html)
9 +
10 +**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)
11 +
12 +# Introduction
13 +
14 +Bluebird is a fully featured promise library with focus on innovative features and performance
15 +
16 +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.
17 +
18 +For bluebird 2.x documentation and files, see the [2.x tree](https://github.com/petkaantonov/bluebird/tree/2.x).
19 +
20 +### Note
21 +
22 +Promises in Node.js 10 are significantly faster than before. Bluebird still includes a lot of features like cancellation, iteration methods and warnings that native promises don't. If you are using Bluebird for performance rather than for those - please consider giving native promises a shot and running the benchmarks yourself.
23 +
24 +# Questions and issues
25 +
26 +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`.
27 +
28 +
29 +
30 +## Thanks
31 +
32 +Thanks to BrowserStack for providing us with a free account which lets us support old browsers like IE8.
33 +
34 +# License
35 +
36 +The MIT License (MIT)
37 +
38 +Copyright (c) 2013-2017 Petka Antonov
39 +
40 +Permission is hereby granted, free of charge, to any person obtaining a copy
41 +of this software and associated documentation files (the "Software"), to deal
42 +in the Software without restriction, including without limitation the rights
43 +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
44 +copies of the Software, and to permit persons to whom the Software is
45 +furnished to do so, subject to the following conditions:
46 +
47 +The above copyright notice and this permission notice shall be included in
48 +all copies or substantial portions of the Software.
49 +
50 +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
51 +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
52 +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
53 +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
54 +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
55 +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
56 +THE SOFTWARE.
57 +
1 +[http://bluebirdjs.com/docs/changelog.html](http://bluebirdjs.com/docs/changelog.html)
This diff could not be displayed because it is too large.
This diff is collapsed. Click to expand it.
This diff could not be displayed because it is too large.
This diff is collapsed. Click to expand it.
1 +"use strict";
2 +module.exports = function(Promise) {
3 +var SomePromiseArray = Promise._SomePromiseArray;
4 +function any(promises) {
5 + var ret = new SomePromiseArray(promises);
6 + var promise = ret.promise();
7 + ret.setHowMany(1);
8 + ret.setUnwrap();
9 + ret.init();
10 + return promise;
11 +}
12 +
13 +Promise.any = function (promises) {
14 + return any(promises);
15 +};
16 +
17 +Promise.prototype.any = function () {
18 + return any(this);
19 +};
20 +
21 +};
1 +"use strict";
2 +module.exports = (function(){
3 +var AssertionError = (function() {
4 + function AssertionError(a) {
5 + this.constructor$(a);
6 + this.message = a;
7 + this.name = "AssertionError";
8 + }
9 + AssertionError.prototype = new Error();
10 + AssertionError.prototype.constructor = AssertionError;
11 + AssertionError.prototype.constructor$ = Error;
12 + return AssertionError;
13 +})();
14 +
15 +function getParams(args) {
16 + var params = [];
17 + for (var i = 0; i < args.length; ++i) params.push("arg" + i);
18 + return params;
19 +}
20 +
21 +function nativeAssert(callName, args, expect) {
22 + try {
23 + var params = getParams(args);
24 + var constructorArgs = params;
25 + constructorArgs.push("return " +
26 + callName + "("+ params.join(",") + ");");
27 + var fn = Function.apply(null, constructorArgs);
28 + return fn.apply(null, args);
29 + } catch (e) {
30 + if (!(e instanceof SyntaxError)) {
31 + throw e;
32 + } else {
33 + return expect;
34 + }
35 + }
36 +}
37 +
38 +return function assert(boolExpr, message) {
39 + if (boolExpr === true) return;
40 +
41 + if (typeof boolExpr === "string" &&
42 + boolExpr.charAt(0) === "%") {
43 + var nativeCallName = boolExpr;
44 + 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];};
45 + if (nativeAssert(nativeCallName, args, message) === message) return;
46 + message = (nativeCallName + " !== " + message);
47 + }
48 +
49 + var ret = new AssertionError(message);
50 + if (Error.captureStackTrace) {
51 + Error.captureStackTrace(ret, assert);
52 + }
53 + throw ret;
54 +};
55 +})();
1 +"use strict";
2 +var firstLineError;
3 +try {throw new Error(); } catch (e) {firstLineError = e;}
4 +var schedule = require("./schedule");
5 +var Queue = require("./queue");
6 +var util = require("./util");
7 +
8 +function Async() {
9 + this._customScheduler = false;
10 + this._isTickUsed = false;
11 + this._lateQueue = new Queue(16);
12 + this._normalQueue = new Queue(16);
13 + this._haveDrainedQueues = false;
14 + this._trampolineEnabled = true;
15 + var self = this;
16 + this.drainQueues = function () {
17 + self._drainQueues();
18 + };
19 + this._schedule = schedule;
20 +}
21 +
22 +Async.prototype.setScheduler = function(fn) {
23 + var prev = this._schedule;
24 + this._schedule = fn;
25 + this._customScheduler = true;
26 + return prev;
27 +};
28 +
29 +Async.prototype.hasCustomScheduler = function() {
30 + return this._customScheduler;
31 +};
32 +
33 +Async.prototype.enableTrampoline = function() {
34 + this._trampolineEnabled = true;
35 +};
36 +
37 +Async.prototype.disableTrampolineIfNecessary = function() {
38 + if (util.hasDevTools) {
39 + this._trampolineEnabled = false;
40 + }
41 +};
42 +
43 +Async.prototype.haveItemsQueued = function () {
44 + return this._isTickUsed || this._haveDrainedQueues;
45 +};
46 +
47 +
48 +Async.prototype.fatalError = function(e, isNode) {
49 + if (isNode) {
50 + process.stderr.write("Fatal " + (e instanceof Error ? e.stack : e) +
51 + "\n");
52 + process.exit(2);
53 + } else {
54 + this.throwLater(e);
55 + }
56 +};
57 +
58 +Async.prototype.throwLater = function(fn, arg) {
59 + if (arguments.length === 1) {
60 + arg = fn;
61 + fn = function () { throw arg; };
62 + }
63 + if (typeof setTimeout !== "undefined") {
64 + setTimeout(function() {
65 + fn(arg);
66 + }, 0);
67 + } else try {
68 + this._schedule(function() {
69 + fn(arg);
70 + });
71 + } catch (e) {
72 + throw new Error("No async scheduler available\u000a\u000a See http://goo.gl/MqrFmX\u000a");
73 + }
74 +};
75 +
76 +function AsyncInvokeLater(fn, receiver, arg) {
77 + this._lateQueue.push(fn, receiver, arg);
78 + this._queueTick();
79 +}
80 +
81 +function AsyncInvoke(fn, receiver, arg) {
82 + this._normalQueue.push(fn, receiver, arg);
83 + this._queueTick();
84 +}
85 +
86 +function AsyncSettlePromises(promise) {
87 + this._normalQueue._pushOne(promise);
88 + this._queueTick();
89 +}
90 +
91 +if (!util.hasDevTools) {
92 + Async.prototype.invokeLater = AsyncInvokeLater;
93 + Async.prototype.invoke = AsyncInvoke;
94 + Async.prototype.settlePromises = AsyncSettlePromises;
95 +} else {
96 + Async.prototype.invokeLater = function (fn, receiver, arg) {
97 + if (this._trampolineEnabled) {
98 + AsyncInvokeLater.call(this, fn, receiver, arg);
99 + } else {
100 + this._schedule(function() {
101 + setTimeout(function() {
102 + fn.call(receiver, arg);
103 + }, 100);
104 + });
105 + }
106 + };
107 +
108 + Async.prototype.invoke = function (fn, receiver, arg) {
109 + if (this._trampolineEnabled) {
110 + AsyncInvoke.call(this, fn, receiver, arg);
111 + } else {
112 + this._schedule(function() {
113 + fn.call(receiver, arg);
114 + });
115 + }
116 + };
117 +
118 + Async.prototype.settlePromises = function(promise) {
119 + if (this._trampolineEnabled) {
120 + AsyncSettlePromises.call(this, promise);
121 + } else {
122 + this._schedule(function() {
123 + promise._settlePromises();
124 + });
125 + }
126 + };
127 +}
128 +
129 +function _drainQueue(queue) {
130 + while (queue.length() > 0) {
131 + _drainQueueStep(queue);
132 + }
133 +}
134 +
135 +function _drainQueueStep(queue) {
136 + var fn = queue.shift();
137 + if (typeof fn !== "function") {
138 + fn._settlePromises();
139 + } else {
140 + var receiver = queue.shift();
141 + var arg = queue.shift();
142 + fn.call(receiver, arg);
143 + }
144 +}
145 +
146 +Async.prototype._drainQueues = function () {
147 + _drainQueue(this._normalQueue);
148 + this._reset();
149 + this._haveDrainedQueues = true;
150 + _drainQueue(this._lateQueue);
151 +};
152 +
153 +Async.prototype._queueTick = function () {
154 + if (!this._isTickUsed) {
155 + this._isTickUsed = true;
156 + this._schedule(this.drainQueues);
157 + }
158 +};
159 +
160 +Async.prototype._reset = function () {
161 + this._isTickUsed = false;
162 +};
163 +
164 +module.exports = Async;
165 +module.exports.firstLineError = firstLineError;
1 +"use strict";
2 +module.exports = function(Promise, INTERNAL, tryConvertToPromise, debug) {
3 +var calledBind = false;
4 +var rejectThis = function(_, e) {
5 + this._reject(e);
6 +};
7 +
8 +var targetRejected = function(e, context) {
9 + context.promiseRejectionQueued = true;
10 + context.bindingPromise._then(rejectThis, rejectThis, null, this, e);
11 +};
12 +
13 +var bindingResolved = function(thisArg, context) {
14 + if (((this._bitField & 50397184) === 0)) {
15 + this._resolveCallback(context.target);
16 + }
17 +};
18 +
19 +var bindingRejected = function(e, context) {
20 + if (!context.promiseRejectionQueued) this._reject(e);
21 +};
22 +
23 +Promise.prototype.bind = function (thisArg) {
24 + if (!calledBind) {
25 + calledBind = true;
26 + Promise.prototype._propagateFrom = debug.propagateFromFunction();
27 + Promise.prototype._boundValue = debug.boundValueFunction();
28 + }
29 + var maybePromise = tryConvertToPromise(thisArg);
30 + var ret = new Promise(INTERNAL);
31 + ret._propagateFrom(this, 1);
32 + var target = this._target();
33 + ret._setBoundTo(maybePromise);
34 + if (maybePromise instanceof Promise) {
35 + var context = {
36 + promiseRejectionQueued: false,
37 + promise: ret,
38 + target: target,
39 + bindingPromise: maybePromise
40 + };
41 + target._then(INTERNAL, targetRejected, undefined, ret, context);
42 + maybePromise._then(
43 + bindingResolved, bindingRejected, undefined, ret, context);
44 + ret._setOnCancel(maybePromise);
45 + } else {
46 + ret._resolveCallback(target);
47 + }
48 + return ret;
49 +};
50 +
51 +Promise.prototype._setBoundTo = function (obj) {
52 + if (obj !== undefined) {
53 + this._bitField = this._bitField | 2097152;
54 + this._boundTo = obj;
55 + } else {
56 + this._bitField = this._bitField & (~2097152);
57 + }
58 +};
59 +
60 +Promise.prototype._isBound = function () {
61 + return (this._bitField & 2097152) === 2097152;
62 +};
63 +
64 +Promise.bind = function (thisArg, value) {
65 + return Promise.resolve(value).bind(thisArg);
66 +};
67 +};
1 +"use strict";
2 +var old;
3 +if (typeof Promise !== "undefined") old = Promise;
4 +function noConflict() {
5 + try { if (Promise === bluebird) Promise = old; }
6 + catch (e) {}
7 + return bluebird;
8 +}
9 +var bluebird = require("./promise")();
10 +bluebird.noConflict = noConflict;
11 +module.exports = bluebird;
1 +"use strict";
2 +var cr = Object.create;
3 +if (cr) {
4 + var callerCache = cr(null);
5 + var getterCache = cr(null);
6 + callerCache[" size"] = getterCache[" size"] = 0;
7 +}
8 +
9 +module.exports = function(Promise) {
10 +var util = require("./util");
11 +var canEvaluate = util.canEvaluate;
12 +var isIdentifier = util.isIdentifier;
13 +
14 +var getMethodCaller;
15 +var getGetter;
16 +if (!false) {
17 +var makeMethodCaller = function (methodName) {
18 + return new Function("ensureMethod", " \n\
19 + return function(obj) { \n\
20 + 'use strict' \n\
21 + var len = this.length; \n\
22 + ensureMethod(obj, 'methodName'); \n\
23 + switch(len) { \n\
24 + case 1: return obj.methodName(this[0]); \n\
25 + case 2: return obj.methodName(this[0], this[1]); \n\
26 + case 3: return obj.methodName(this[0], this[1], this[2]); \n\
27 + case 0: return obj.methodName(); \n\
28 + default: \n\
29 + return obj.methodName.apply(obj, this); \n\
30 + } \n\
31 + }; \n\
32 + ".replace(/methodName/g, methodName))(ensureMethod);
33 +};
34 +
35 +var makeGetter = function (propertyName) {
36 + return new Function("obj", " \n\
37 + 'use strict'; \n\
38 + return obj.propertyName; \n\
39 + ".replace("propertyName", propertyName));
40 +};
41 +
42 +var getCompiled = function(name, compiler, cache) {
43 + var ret = cache[name];
44 + if (typeof ret !== "function") {
45 + if (!isIdentifier(name)) {
46 + return null;
47 + }
48 + ret = compiler(name);
49 + cache[name] = ret;
50 + cache[" size"]++;
51 + if (cache[" size"] > 512) {
52 + var keys = Object.keys(cache);
53 + for (var i = 0; i < 256; ++i) delete cache[keys[i]];
54 + cache[" size"] = keys.length - 256;
55 + }
56 + }
57 + return ret;
58 +};
59 +
60 +getMethodCaller = function(name) {
61 + return getCompiled(name, makeMethodCaller, callerCache);
62 +};
63 +
64 +getGetter = function(name) {
65 + return getCompiled(name, makeGetter, getterCache);
66 +};
67 +}
68 +
69 +function ensureMethod(obj, methodName) {
70 + var fn;
71 + if (obj != null) fn = obj[methodName];
72 + if (typeof fn !== "function") {
73 + var message = "Object " + util.classString(obj) + " has no method '" +
74 + util.toString(methodName) + "'";
75 + throw new Promise.TypeError(message);
76 + }
77 + return fn;
78 +}
79 +
80 +function caller(obj) {
81 + var methodName = this.pop();
82 + var fn = ensureMethod(obj, methodName);
83 + return fn.apply(obj, this);
84 +}
85 +Promise.prototype.call = function (methodName) {
86 + 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];};
87 + if (!false) {
88 + if (canEvaluate) {
89 + var maybeCaller = getMethodCaller(methodName);
90 + if (maybeCaller !== null) {
91 + return this._then(
92 + maybeCaller, undefined, undefined, args, undefined);
93 + }
94 + }
95 + }
96 + args.push(methodName);
97 + return this._then(caller, undefined, undefined, args, undefined);
98 +};
99 +
100 +function namedGetter(obj) {
101 + return obj[this];
102 +}
103 +function indexedGetter(obj) {
104 + var index = +this;
105 + if (index < 0) index = Math.max(0, index + obj.length);
106 + return obj[index];
107 +}
108 +Promise.prototype.get = function (propertyName) {
109 + var isIndex = (typeof propertyName === "number");
110 + var getter;
111 + if (!isIndex) {
112 + if (canEvaluate) {
113 + var maybeGetter = getGetter(propertyName);
114 + getter = maybeGetter !== null ? maybeGetter : namedGetter;
115 + } else {
116 + getter = namedGetter;
117 + }
118 + } else {
119 + getter = indexedGetter;
120 + }
121 + return this._then(getter, undefined, undefined, propertyName, undefined);
122 +};
123 +};
1 +"use strict";
2 +module.exports = function(Promise, PromiseArray, apiRejection, debug) {
3 +var util = require("./util");
4 +var tryCatch = util.tryCatch;
5 +var errorObj = util.errorObj;
6 +var async = Promise._async;
7 +
8 +Promise.prototype["break"] = Promise.prototype.cancel = function() {
9 + if (!debug.cancellation()) return this._warn("cancellation is disabled");
10 +
11 + var promise = this;
12 + var child = promise;
13 + while (promise._isCancellable()) {
14 + if (!promise._cancelBy(child)) {
15 + if (child._isFollowing()) {
16 + child._followee().cancel();
17 + } else {
18 + child._cancelBranched();
19 + }
20 + break;
21 + }
22 +
23 + var parent = promise._cancellationParent;
24 + if (parent == null || !parent._isCancellable()) {
25 + if (promise._isFollowing()) {
26 + promise._followee().cancel();
27 + } else {
28 + promise._cancelBranched();
29 + }
30 + break;
31 + } else {
32 + if (promise._isFollowing()) promise._followee().cancel();
33 + promise._setWillBeCancelled();
34 + child = promise;
35 + promise = parent;
36 + }
37 + }
38 +};
39 +
40 +Promise.prototype._branchHasCancelled = function() {
41 + this._branchesRemainingToCancel--;
42 +};
43 +
44 +Promise.prototype._enoughBranchesHaveCancelled = function() {
45 + return this._branchesRemainingToCancel === undefined ||
46 + this._branchesRemainingToCancel <= 0;
47 +};
48 +
49 +Promise.prototype._cancelBy = function(canceller) {
50 + if (canceller === this) {
51 + this._branchesRemainingToCancel = 0;
52 + this._invokeOnCancel();
53 + return true;
54 + } else {
55 + this._branchHasCancelled();
56 + if (this._enoughBranchesHaveCancelled()) {
57 + this._invokeOnCancel();
58 + return true;
59 + }
60 + }
61 + return false;
62 +};
63 +
64 +Promise.prototype._cancelBranched = function() {
65 + if (this._enoughBranchesHaveCancelled()) {
66 + this._cancel();
67 + }
68 +};
69 +
70 +Promise.prototype._cancel = function() {
71 + if (!this._isCancellable()) return;
72 + this._setCancelled();
73 + async.invoke(this._cancelPromises, this, undefined);
74 +};
75 +
76 +Promise.prototype._cancelPromises = function() {
77 + if (this._length() > 0) this._settlePromises();
78 +};
79 +
80 +Promise.prototype._unsetOnCancel = function() {
81 + this._onCancelField = undefined;
82 +};
83 +
84 +Promise.prototype._isCancellable = function() {
85 + return this.isPending() && !this._isCancelled();
86 +};
87 +
88 +Promise.prototype.isCancellable = function() {
89 + return this.isPending() && !this.isCancelled();
90 +};
91 +
92 +Promise.prototype._doInvokeOnCancel = function(onCancelCallback, internalOnly) {
93 + if (util.isArray(onCancelCallback)) {
94 + for (var i = 0; i < onCancelCallback.length; ++i) {
95 + this._doInvokeOnCancel(onCancelCallback[i], internalOnly);
96 + }
97 + } else if (onCancelCallback !== undefined) {
98 + if (typeof onCancelCallback === "function") {
99 + if (!internalOnly) {
100 + var e = tryCatch(onCancelCallback).call(this._boundValue());
101 + if (e === errorObj) {
102 + this._attachExtraTrace(e.e);
103 + async.throwLater(e.e);
104 + }
105 + }
106 + } else {
107 + onCancelCallback._resultCancelled(this);
108 + }
109 + }
110 +};
111 +
112 +Promise.prototype._invokeOnCancel = function() {
113 + var onCancelCallback = this._onCancel();
114 + this._unsetOnCancel();
115 + async.invoke(this._doInvokeOnCancel, this, onCancelCallback);
116 +};
117 +
118 +Promise.prototype._invokeInternalOnCancel = function() {
119 + if (this._isCancellable()) {
120 + this._doInvokeOnCancel(this._onCancel(), true);
121 + this._unsetOnCancel();
122 + }
123 +};
124 +
125 +Promise.prototype._resultCancelled = function() {
126 + this.cancel();
127 +};
128 +
129 +};
1 +"use strict";
2 +module.exports = function(NEXT_FILTER) {
3 +var util = require("./util");
4 +var getKeys = require("./es5").keys;
5 +var tryCatch = util.tryCatch;
6 +var errorObj = util.errorObj;
7 +
8 +function catchFilter(instances, cb, promise) {
9 + return function(e) {
10 + var boundTo = promise._boundValue();
11 + predicateLoop: for (var i = 0; i < instances.length; ++i) {
12 + var item = instances[i];
13 +
14 + if (item === Error ||
15 + (item != null && item.prototype instanceof Error)) {
16 + if (e instanceof item) {
17 + return tryCatch(cb).call(boundTo, e);
18 + }
19 + } else if (typeof item === "function") {
20 + var matchesPredicate = tryCatch(item).call(boundTo, e);
21 + if (matchesPredicate === errorObj) {
22 + return matchesPredicate;
23 + } else if (matchesPredicate) {
24 + return tryCatch(cb).call(boundTo, e);
25 + }
26 + } else if (util.isObject(e)) {
27 + var keys = getKeys(item);
28 + for (var j = 0; j < keys.length; ++j) {
29 + var key = keys[j];
30 + if (item[key] != e[key]) {
31 + continue predicateLoop;
32 + }
33 + }
34 + return tryCatch(cb).call(boundTo, e);
35 + }
36 + }
37 + return NEXT_FILTER;
38 + };
39 +}
40 +
41 +return catchFilter;
42 +};
1 +"use strict";
2 +module.exports = function(Promise) {
3 +var longStackTraces = false;
4 +var contextStack = [];
5 +
6 +Promise.prototype._promiseCreated = function() {};
7 +Promise.prototype._pushContext = function() {};
8 +Promise.prototype._popContext = function() {return null;};
9 +Promise._peekContext = Promise.prototype._peekContext = function() {};
10 +
11 +function Context() {
12 + this._trace = new Context.CapturedTrace(peekContext());
13 +}
14 +Context.prototype._pushContext = function () {
15 + if (this._trace !== undefined) {
16 + this._trace._promiseCreated = null;
17 + contextStack.push(this._trace);
18 + }
19 +};
20 +
21 +Context.prototype._popContext = function () {
22 + if (this._trace !== undefined) {
23 + var trace = contextStack.pop();
24 + var ret = trace._promiseCreated;
25 + trace._promiseCreated = null;
26 + return ret;
27 + }
28 + return null;
29 +};
30 +
31 +function createContext() {
32 + if (longStackTraces) return new Context();
33 +}
34 +
35 +function peekContext() {
36 + var lastIndex = contextStack.length - 1;
37 + if (lastIndex >= 0) {
38 + return contextStack[lastIndex];
39 + }
40 + return undefined;
41 +}
42 +Context.CapturedTrace = null;
43 +Context.create = createContext;
44 +Context.deactivateLongStackTraces = function() {};
45 +Context.activateLongStackTraces = function() {
46 + var Promise_pushContext = Promise.prototype._pushContext;
47 + var Promise_popContext = Promise.prototype._popContext;
48 + var Promise_PeekContext = Promise._peekContext;
49 + var Promise_peekContext = Promise.prototype._peekContext;
50 + var Promise_promiseCreated = Promise.prototype._promiseCreated;
51 + Context.deactivateLongStackTraces = function() {
52 + Promise.prototype._pushContext = Promise_pushContext;
53 + Promise.prototype._popContext = Promise_popContext;
54 + Promise._peekContext = Promise_PeekContext;
55 + Promise.prototype._peekContext = Promise_peekContext;
56 + Promise.prototype._promiseCreated = Promise_promiseCreated;
57 + longStackTraces = false;
58 + };
59 + longStackTraces = true;
60 + Promise.prototype._pushContext = Context.prototype._pushContext;
61 + Promise.prototype._popContext = Context.prototype._popContext;
62 + Promise._peekContext = Promise.prototype._peekContext = peekContext;
63 + Promise.prototype._promiseCreated = function() {
64 + var ctx = this._peekContext();
65 + if (ctx && ctx._promiseCreated == null) ctx._promiseCreated = this;
66 + };
67 +};
68 +return Context;
69 +};
This diff is collapsed. Click to expand it.
1 +"use strict";
2 +module.exports = function(Promise) {
3 +function returner() {
4 + return this.value;
5 +}
6 +function thrower() {
7 + throw this.reason;
8 +}
9 +
10 +Promise.prototype["return"] =
11 +Promise.prototype.thenReturn = function (value) {
12 + if (value instanceof Promise) value.suppressUnhandledRejections();
13 + return this._then(
14 + returner, undefined, undefined, {value: value}, undefined);
15 +};
16 +
17 +Promise.prototype["throw"] =
18 +Promise.prototype.thenThrow = function (reason) {
19 + return this._then(
20 + thrower, undefined, undefined, {reason: reason}, undefined);
21 +};
22 +
23 +Promise.prototype.catchThrow = function (reason) {
24 + if (arguments.length <= 1) {
25 + return this._then(
26 + undefined, thrower, undefined, {reason: reason}, undefined);
27 + } else {
28 + var _reason = arguments[1];
29 + var handler = function() {throw _reason;};
30 + return this.caught(reason, handler);
31 + }
32 +};
33 +
34 +Promise.prototype.catchReturn = function (value) {
35 + if (arguments.length <= 1) {
36 + if (value instanceof Promise) value.suppressUnhandledRejections();
37 + return this._then(
38 + undefined, returner, undefined, {value: value}, undefined);
39 + } else {
40 + var _value = arguments[1];
41 + if (_value instanceof Promise) _value.suppressUnhandledRejections();
42 + var handler = function() {return _value;};
43 + return this.caught(value, handler);
44 + }
45 +};
46 +};
1 +"use strict";
2 +module.exports = function(Promise, INTERNAL) {
3 +var PromiseReduce = Promise.reduce;
4 +var PromiseAll = Promise.all;
5 +
6 +function promiseAllThis() {
7 + return PromiseAll(this);
8 +}
9 +
10 +function PromiseMapSeries(promises, fn) {
11 + return PromiseReduce(promises, fn, INTERNAL, INTERNAL);
12 +}
13 +
14 +Promise.prototype.each = function (fn) {
15 + return PromiseReduce(this, fn, INTERNAL, 0)
16 + ._then(promiseAllThis, undefined, undefined, this, undefined);
17 +};
18 +
19 +Promise.prototype.mapSeries = function (fn) {
20 + return PromiseReduce(this, fn, INTERNAL, INTERNAL);
21 +};
22 +
23 +Promise.each = function (promises, fn) {
24 + return PromiseReduce(promises, fn, INTERNAL, 0)
25 + ._then(promiseAllThis, undefined, undefined, promises, undefined);
26 +};
27 +
28 +Promise.mapSeries = PromiseMapSeries;
29 +};
30 +
1 +"use strict";
2 +var es5 = require("./es5");
3 +var Objectfreeze = es5.freeze;
4 +var util = require("./util");
5 +var inherits = util.inherits;
6 +var notEnumerableProp = util.notEnumerableProp;
7 +
8 +function subError(nameProperty, defaultMessage) {
9 + function SubError(message) {
10 + if (!(this instanceof SubError)) return new SubError(message);
11 + notEnumerableProp(this, "message",
12 + typeof message === "string" ? message : defaultMessage);
13 + notEnumerableProp(this, "name", nameProperty);
14 + if (Error.captureStackTrace) {
15 + Error.captureStackTrace(this, this.constructor);
16 + } else {
17 + Error.call(this);
18 + }
19 + }
20 + inherits(SubError, Error);
21 + return SubError;
22 +}
23 +
24 +var _TypeError, _RangeError;
25 +var Warning = subError("Warning", "warning");
26 +var CancellationError = subError("CancellationError", "cancellation error");
27 +var TimeoutError = subError("TimeoutError", "timeout error");
28 +var AggregateError = subError("AggregateError", "aggregate error");
29 +try {
30 + _TypeError = TypeError;
31 + _RangeError = RangeError;
32 +} catch(e) {
33 + _TypeError = subError("TypeError", "type error");
34 + _RangeError = subError("RangeError", "range error");
35 +}
36 +
37 +var methods = ("join pop push shift unshift slice filter forEach some " +
38 + "every map indexOf lastIndexOf reduce reduceRight sort reverse").split(" ");
39 +
40 +for (var i = 0; i < methods.length; ++i) {
41 + if (typeof Array.prototype[methods[i]] === "function") {
42 + AggregateError.prototype[methods[i]] = Array.prototype[methods[i]];
43 + }
44 +}
45 +
46 +es5.defineProperty(AggregateError.prototype, "length", {
47 + value: 0,
48 + configurable: false,
49 + writable: true,
50 + enumerable: true
51 +});
52 +AggregateError.prototype["isOperational"] = true;
53 +var level = 0;
54 +AggregateError.prototype.toString = function() {
55 + var indent = Array(level * 4 + 1).join(" ");
56 + var ret = "\n" + indent + "AggregateError of:" + "\n";
57 + level++;
58 + indent = Array(level * 4 + 1).join(" ");
59 + for (var i = 0; i < this.length; ++i) {
60 + var str = this[i] === this ? "[Circular AggregateError]" : this[i] + "";
61 + var lines = str.split("\n");
62 + for (var j = 0; j < lines.length; ++j) {
63 + lines[j] = indent + lines[j];
64 + }
65 + str = lines.join("\n");
66 + ret += str + "\n";
67 + }
68 + level--;
69 + return ret;
70 +};
71 +
72 +function OperationalError(message) {
73 + if (!(this instanceof OperationalError))
74 + return new OperationalError(message);
75 + notEnumerableProp(this, "name", "OperationalError");
76 + notEnumerableProp(this, "message", message);
77 + this.cause = message;
78 + this["isOperational"] = true;
79 +
80 + if (message instanceof Error) {
81 + notEnumerableProp(this, "message", message.message);
82 + notEnumerableProp(this, "stack", message.stack);
83 + } else if (Error.captureStackTrace) {
84 + Error.captureStackTrace(this, this.constructor);
85 + }
86 +
87 +}
88 +inherits(OperationalError, Error);
89 +
90 +var errorTypes = Error["__BluebirdErrorTypes__"];
91 +if (!errorTypes) {
92 + errorTypes = Objectfreeze({
93 + CancellationError: CancellationError,
94 + TimeoutError: TimeoutError,
95 + OperationalError: OperationalError,
96 + RejectionError: OperationalError,
97 + AggregateError: AggregateError
98 + });
99 + es5.defineProperty(Error, "__BluebirdErrorTypes__", {
100 + value: errorTypes,
101 + writable: false,
102 + enumerable: false,
103 + configurable: false
104 + });
105 +}
106 +
107 +module.exports = {
108 + Error: Error,
109 + TypeError: _TypeError,
110 + RangeError: _RangeError,
111 + CancellationError: errorTypes.CancellationError,
112 + OperationalError: errorTypes.OperationalError,
113 + TimeoutError: errorTypes.TimeoutError,
114 + AggregateError: errorTypes.AggregateError,
115 + Warning: Warning
116 +};
1 +var isES5 = (function(){
2 + "use strict";
3 + return this === undefined;
4 +})();
5 +
6 +if (isES5) {
7 + module.exports = {
8 + freeze: Object.freeze,
9 + defineProperty: Object.defineProperty,
10 + getDescriptor: Object.getOwnPropertyDescriptor,
11 + keys: Object.keys,
12 + names: Object.getOwnPropertyNames,
13 + getPrototypeOf: Object.getPrototypeOf,
14 + isArray: Array.isArray,
15 + isES5: isES5,
16 + propertyIsWritable: function(obj, prop) {
17 + var descriptor = Object.getOwnPropertyDescriptor(obj, prop);
18 + return !!(!descriptor || descriptor.writable || descriptor.set);
19 + }
20 + };
21 +} else {
22 + var has = {}.hasOwnProperty;
23 + var str = {}.toString;
24 + var proto = {}.constructor.prototype;
25 +
26 + var ObjectKeys = function (o) {
27 + var ret = [];
28 + for (var key in o) {
29 + if (has.call(o, key)) {
30 + ret.push(key);
31 + }
32 + }
33 + return ret;
34 + };
35 +
36 + var ObjectGetDescriptor = function(o, key) {
37 + return {value: o[key]};
38 + };
39 +
40 + var ObjectDefineProperty = function (o, key, desc) {
41 + o[key] = desc.value;
42 + return o;
43 + };
44 +
45 + var ObjectFreeze = function (obj) {
46 + return obj;
47 + };
48 +
49 + var ObjectGetPrototypeOf = function (obj) {
50 + try {
51 + return Object(obj).constructor.prototype;
52 + }
53 + catch (e) {
54 + return proto;
55 + }
56 + };
57 +
58 + var ArrayIsArray = function (obj) {
59 + try {
60 + return str.call(obj) === "[object Array]";
61 + }
62 + catch(e) {
63 + return false;
64 + }
65 + };
66 +
67 + module.exports = {
68 + isArray: ArrayIsArray,
69 + keys: ObjectKeys,
70 + names: ObjectKeys,
71 + defineProperty: ObjectDefineProperty,
72 + getDescriptor: ObjectGetDescriptor,
73 + freeze: ObjectFreeze,
74 + getPrototypeOf: ObjectGetPrototypeOf,
75 + isES5: isES5,
76 + propertyIsWritable: function() {
77 + return true;
78 + }
79 + };
80 +}
1 +"use strict";
2 +module.exports = function(Promise, INTERNAL) {
3 +var PromiseMap = Promise.map;
4 +
5 +Promise.prototype.filter = function (fn, options) {
6 + return PromiseMap(this, fn, options, INTERNAL);
7 +};
8 +
9 +Promise.filter = function (promises, fn, options) {
10 + return PromiseMap(promises, fn, options, INTERNAL);
11 +};
12 +};
1 +"use strict";
2 +module.exports = function(Promise, tryConvertToPromise, NEXT_FILTER) {
3 +var util = require("./util");
4 +var CancellationError = Promise.CancellationError;
5 +var errorObj = util.errorObj;
6 +var catchFilter = require("./catch_filter")(NEXT_FILTER);
7 +
8 +function PassThroughHandlerContext(promise, type, handler) {
9 + this.promise = promise;
10 + this.type = type;
11 + this.handler = handler;
12 + this.called = false;
13 + this.cancelPromise = null;
14 +}
15 +
16 +PassThroughHandlerContext.prototype.isFinallyHandler = function() {
17 + return this.type === 0;
18 +};
19 +
20 +function FinallyHandlerCancelReaction(finallyHandler) {
21 + this.finallyHandler = finallyHandler;
22 +}
23 +
24 +FinallyHandlerCancelReaction.prototype._resultCancelled = function() {
25 + checkCancel(this.finallyHandler);
26 +};
27 +
28 +function checkCancel(ctx, reason) {
29 + if (ctx.cancelPromise != null) {
30 + if (arguments.length > 1) {
31 + ctx.cancelPromise._reject(reason);
32 + } else {
33 + ctx.cancelPromise._cancel();
34 + }
35 + ctx.cancelPromise = null;
36 + return true;
37 + }
38 + return false;
39 +}
40 +
41 +function succeed() {
42 + return finallyHandler.call(this, this.promise._target()._settledValue());
43 +}
44 +function fail(reason) {
45 + if (checkCancel(this, reason)) return;
46 + errorObj.e = reason;
47 + return errorObj;
48 +}
49 +function finallyHandler(reasonOrValue) {
50 + var promise = this.promise;
51 + var handler = this.handler;
52 +
53 + if (!this.called) {
54 + this.called = true;
55 + var ret = this.isFinallyHandler()
56 + ? handler.call(promise._boundValue())
57 + : handler.call(promise._boundValue(), reasonOrValue);
58 + if (ret === NEXT_FILTER) {
59 + return ret;
60 + } else if (ret !== undefined) {
61 + promise._setReturnedNonUndefined();
62 + var maybePromise = tryConvertToPromise(ret, promise);
63 + if (maybePromise instanceof Promise) {
64 + if (this.cancelPromise != null) {
65 + if (maybePromise._isCancelled()) {
66 + var reason =
67 + new CancellationError("late cancellation observer");
68 + promise._attachExtraTrace(reason);
69 + errorObj.e = reason;
70 + return errorObj;
71 + } else if (maybePromise.isPending()) {
72 + maybePromise._attachCancellationCallback(
73 + new FinallyHandlerCancelReaction(this));
74 + }
75 + }
76 + return maybePromise._then(
77 + succeed, fail, undefined, this, undefined);
78 + }
79 + }
80 + }
81 +
82 + if (promise.isRejected()) {
83 + checkCancel(this);
84 + errorObj.e = reasonOrValue;
85 + return errorObj;
86 + } else {
87 + checkCancel(this);
88 + return reasonOrValue;
89 + }
90 +}
91 +
92 +Promise.prototype._passThrough = function(handler, type, success, fail) {
93 + if (typeof handler !== "function") return this.then();
94 + return this._then(success,
95 + fail,
96 + undefined,
97 + new PassThroughHandlerContext(this, type, handler),
98 + undefined);
99 +};
100 +
101 +Promise.prototype.lastly =
102 +Promise.prototype["finally"] = function (handler) {
103 + return this._passThrough(handler,
104 + 0,
105 + finallyHandler,
106 + finallyHandler);
107 +};
108 +
109 +
110 +Promise.prototype.tap = function (handler) {
111 + return this._passThrough(handler, 1, finallyHandler);
112 +};
113 +
114 +Promise.prototype.tapCatch = function (handlerOrPredicate) {
115 + var len = arguments.length;
116 + if(len === 1) {
117 + return this._passThrough(handlerOrPredicate,
118 + 1,
119 + undefined,
120 + finallyHandler);
121 + } else {
122 + var catchInstances = new Array(len - 1),
123 + j = 0, i;
124 + for (i = 0; i < len - 1; ++i) {
125 + var item = arguments[i];
126 + if (util.isObject(item)) {
127 + catchInstances[j++] = item;
128 + } else {
129 + return Promise.reject(new TypeError(
130 + "tapCatch statement predicate: "
131 + + "expecting an object but got " + util.classString(item)
132 + ));
133 + }
134 + }
135 + catchInstances.length = j;
136 + var handler = arguments[i];
137 + return this._passThrough(catchFilter(catchInstances, handler, this),
138 + 1,
139 + undefined,
140 + finallyHandler);
141 + }
142 +
143 +};
144 +
145 +return PassThroughHandlerContext;
146 +};
1 +"use strict";
2 +module.exports = function(Promise,
3 + apiRejection,
4 + INTERNAL,
5 + tryConvertToPromise,
6 + Proxyable,
7 + debug) {
8 +var errors = require("./errors");
9 +var TypeError = errors.TypeError;
10 +var util = require("./util");
11 +var errorObj = util.errorObj;
12 +var tryCatch = util.tryCatch;
13 +var yieldHandlers = [];
14 +
15 +function promiseFromYieldHandler(value, yieldHandlers, traceParent) {
16 + for (var i = 0; i < yieldHandlers.length; ++i) {
17 + traceParent._pushContext();
18 + var result = tryCatch(yieldHandlers[i])(value);
19 + traceParent._popContext();
20 + if (result === errorObj) {
21 + traceParent._pushContext();
22 + var ret = Promise.reject(errorObj.e);
23 + traceParent._popContext();
24 + return ret;
25 + }
26 + var maybePromise = tryConvertToPromise(result, traceParent);
27 + if (maybePromise instanceof Promise) return maybePromise;
28 + }
29 + return null;
30 +}
31 +
32 +function PromiseSpawn(generatorFunction, receiver, yieldHandler, stack) {
33 + if (debug.cancellation()) {
34 + var internal = new Promise(INTERNAL);
35 + var _finallyPromise = this._finallyPromise = new Promise(INTERNAL);
36 + this._promise = internal.lastly(function() {
37 + return _finallyPromise;
38 + });
39 + internal._captureStackTrace();
40 + internal._setOnCancel(this);
41 + } else {
42 + var promise = this._promise = new Promise(INTERNAL);
43 + promise._captureStackTrace();
44 + }
45 + this._stack = stack;
46 + this._generatorFunction = generatorFunction;
47 + this._receiver = receiver;
48 + this._generator = undefined;
49 + this._yieldHandlers = typeof yieldHandler === "function"
50 + ? [yieldHandler].concat(yieldHandlers)
51 + : yieldHandlers;
52 + this._yieldedPromise = null;
53 + this._cancellationPhase = false;
54 +}
55 +util.inherits(PromiseSpawn, Proxyable);
56 +
57 +PromiseSpawn.prototype._isResolved = function() {
58 + return this._promise === null;
59 +};
60 +
61 +PromiseSpawn.prototype._cleanup = function() {
62 + this._promise = this._generator = null;
63 + if (debug.cancellation() && this._finallyPromise !== null) {
64 + this._finallyPromise._fulfill();
65 + this._finallyPromise = null;
66 + }
67 +};
68 +
69 +PromiseSpawn.prototype._promiseCancelled = function() {
70 + if (this._isResolved()) return;
71 + var implementsReturn = typeof this._generator["return"] !== "undefined";
72 +
73 + var result;
74 + if (!implementsReturn) {
75 + var reason = new Promise.CancellationError(
76 + "generator .return() sentinel");
77 + Promise.coroutine.returnSentinel = reason;
78 + this._promise._attachExtraTrace(reason);
79 + this._promise._pushContext();
80 + result = tryCatch(this._generator["throw"]).call(this._generator,
81 + reason);
82 + this._promise._popContext();
83 + } else {
84 + this._promise._pushContext();
85 + result = tryCatch(this._generator["return"]).call(this._generator,
86 + undefined);
87 + this._promise._popContext();
88 + }
89 + this._cancellationPhase = true;
90 + this._yieldedPromise = null;
91 + this._continue(result);
92 +};
93 +
94 +PromiseSpawn.prototype._promiseFulfilled = function(value) {
95 + this._yieldedPromise = null;
96 + this._promise._pushContext();
97 + var result = tryCatch(this._generator.next).call(this._generator, value);
98 + this._promise._popContext();
99 + this._continue(result);
100 +};
101 +
102 +PromiseSpawn.prototype._promiseRejected = function(reason) {
103 + this._yieldedPromise = null;
104 + this._promise._attachExtraTrace(reason);
105 + this._promise._pushContext();
106 + var result = tryCatch(this._generator["throw"])
107 + .call(this._generator, reason);
108 + this._promise._popContext();
109 + this._continue(result);
110 +};
111 +
112 +PromiseSpawn.prototype._resultCancelled = function() {
113 + if (this._yieldedPromise instanceof Promise) {
114 + var promise = this._yieldedPromise;
115 + this._yieldedPromise = null;
116 + promise.cancel();
117 + }
118 +};
119 +
120 +PromiseSpawn.prototype.promise = function () {
121 + return this._promise;
122 +};
123 +
124 +PromiseSpawn.prototype._run = function () {
125 + this._generator = this._generatorFunction.call(this._receiver);
126 + this._receiver =
127 + this._generatorFunction = undefined;
128 + this._promiseFulfilled(undefined);
129 +};
130 +
131 +PromiseSpawn.prototype._continue = function (result) {
132 + var promise = this._promise;
133 + if (result === errorObj) {
134 + this._cleanup();
135 + if (this._cancellationPhase) {
136 + return promise.cancel();
137 + } else {
138 + return promise._rejectCallback(result.e, false);
139 + }
140 + }
141 +
142 + var value = result.value;
143 + if (result.done === true) {
144 + this._cleanup();
145 + if (this._cancellationPhase) {
146 + return promise.cancel();
147 + } else {
148 + return promise._resolveCallback(value);
149 + }
150 + } else {
151 + var maybePromise = tryConvertToPromise(value, this._promise);
152 + if (!(maybePromise instanceof Promise)) {
153 + maybePromise =
154 + promiseFromYieldHandler(maybePromise,
155 + this._yieldHandlers,
156 + this._promise);
157 + if (maybePromise === null) {
158 + this._promiseRejected(
159 + new TypeError(
160 + "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)) +
161 + "From coroutine:\u000a" +
162 + this._stack.split("\n").slice(1, -7).join("\n")
163 + )
164 + );
165 + return;
166 + }
167 + }
168 + maybePromise = maybePromise._target();
169 + var bitField = maybePromise._bitField;
170 + ;
171 + if (((bitField & 50397184) === 0)) {
172 + this._yieldedPromise = maybePromise;
173 + maybePromise._proxy(this, null);
174 + } else if (((bitField & 33554432) !== 0)) {
175 + Promise._async.invoke(
176 + this._promiseFulfilled, this, maybePromise._value()
177 + );
178 + } else if (((bitField & 16777216) !== 0)) {
179 + Promise._async.invoke(
180 + this._promiseRejected, this, maybePromise._reason()
181 + );
182 + } else {
183 + this._promiseCancelled();
184 + }
185 + }
186 +};
187 +
188 +Promise.coroutine = function (generatorFunction, options) {
189 + if (typeof generatorFunction !== "function") {
190 + throw new TypeError("generatorFunction must be a function\u000a\u000a See http://goo.gl/MqrFmX\u000a");
191 + }
192 + var yieldHandler = Object(options).yieldHandler;
193 + var PromiseSpawn$ = PromiseSpawn;
194 + var stack = new Error().stack;
195 + return function () {
196 + var generator = generatorFunction.apply(this, arguments);
197 + var spawn = new PromiseSpawn$(undefined, undefined, yieldHandler,
198 + stack);
199 + var ret = spawn.promise();
200 + spawn._generator = generator;
201 + spawn._promiseFulfilled(undefined);
202 + return ret;
203 + };
204 +};
205 +
206 +Promise.coroutine.addYieldHandler = function(fn) {
207 + if (typeof fn !== "function") {
208 + throw new TypeError("expecting a function but got " + util.classString(fn));
209 + }
210 + yieldHandlers.push(fn);
211 +};
212 +
213 +Promise.spawn = function (generatorFunction) {
214 + debug.deprecated("Promise.spawn()", "Promise.coroutine()");
215 + if (typeof generatorFunction !== "function") {
216 + return apiRejection("generatorFunction must be a function\u000a\u000a See http://goo.gl/MqrFmX\u000a");
217 + }
218 + var spawn = new PromiseSpawn(generatorFunction, this);
219 + var ret = spawn.promise();
220 + spawn._run(Promise.spawn);
221 + return ret;
222 +};
223 +};
1 +"use strict";
2 +module.exports =
3 +function(Promise, PromiseArray, tryConvertToPromise, INTERNAL, async,
4 + getDomain) {
5 +var util = require("./util");
6 +var canEvaluate = util.canEvaluate;
7 +var tryCatch = util.tryCatch;
8 +var errorObj = util.errorObj;
9 +var reject;
10 +
11 +if (!false) {
12 +if (canEvaluate) {
13 + var thenCallback = function(i) {
14 + return new Function("value", "holder", " \n\
15 + 'use strict'; \n\
16 + holder.pIndex = value; \n\
17 + holder.checkFulfillment(this); \n\
18 + ".replace(/Index/g, i));
19 + };
20 +
21 + var promiseSetter = function(i) {
22 + return new Function("promise", "holder", " \n\
23 + 'use strict'; \n\
24 + holder.pIndex = promise; \n\
25 + ".replace(/Index/g, i));
26 + };
27 +
28 + var generateHolderClass = function(total) {
29 + var props = new Array(total);
30 + for (var i = 0; i < props.length; ++i) {
31 + props[i] = "this.p" + (i+1);
32 + }
33 + var assignment = props.join(" = ") + " = null;";
34 + var cancellationCode= "var promise;\n" + props.map(function(prop) {
35 + return " \n\
36 + promise = " + prop + "; \n\
37 + if (promise instanceof Promise) { \n\
38 + promise.cancel(); \n\
39 + } \n\
40 + ";
41 + }).join("\n");
42 + var passedArguments = props.join(", ");
43 + var name = "Holder$" + total;
44 +
45 +
46 + var code = "return function(tryCatch, errorObj, Promise, async) { \n\
47 + 'use strict'; \n\
48 + function [TheName](fn) { \n\
49 + [TheProperties] \n\
50 + this.fn = fn; \n\
51 + this.asyncNeeded = true; \n\
52 + this.now = 0; \n\
53 + } \n\
54 + \n\
55 + [TheName].prototype._callFunction = function(promise) { \n\
56 + promise._pushContext(); \n\
57 + var ret = tryCatch(this.fn)([ThePassedArguments]); \n\
58 + promise._popContext(); \n\
59 + if (ret === errorObj) { \n\
60 + promise._rejectCallback(ret.e, false); \n\
61 + } else { \n\
62 + promise._resolveCallback(ret); \n\
63 + } \n\
64 + }; \n\
65 + \n\
66 + [TheName].prototype.checkFulfillment = function(promise) { \n\
67 + var now = ++this.now; \n\
68 + if (now === [TheTotal]) { \n\
69 + if (this.asyncNeeded) { \n\
70 + async.invoke(this._callFunction, this, promise); \n\
71 + } else { \n\
72 + this._callFunction(promise); \n\
73 + } \n\
74 + \n\
75 + } \n\
76 + }; \n\
77 + \n\
78 + [TheName].prototype._resultCancelled = function() { \n\
79 + [CancellationCode] \n\
80 + }; \n\
81 + \n\
82 + return [TheName]; \n\
83 + }(tryCatch, errorObj, Promise, async); \n\
84 + ";
85 +
86 + code = code.replace(/\[TheName\]/g, name)
87 + .replace(/\[TheTotal\]/g, total)
88 + .replace(/\[ThePassedArguments\]/g, passedArguments)
89 + .replace(/\[TheProperties\]/g, assignment)
90 + .replace(/\[CancellationCode\]/g, cancellationCode);
91 +
92 + return new Function("tryCatch", "errorObj", "Promise", "async", code)
93 + (tryCatch, errorObj, Promise, async);
94 + };
95 +
96 + var holderClasses = [];
97 + var thenCallbacks = [];
98 + var promiseSetters = [];
99 +
100 + for (var i = 0; i < 8; ++i) {
101 + holderClasses.push(generateHolderClass(i + 1));
102 + thenCallbacks.push(thenCallback(i + 1));
103 + promiseSetters.push(promiseSetter(i + 1));
104 + }
105 +
106 + reject = function (reason) {
107 + this._reject(reason);
108 + };
109 +}}
110 +
111 +Promise.join = function () {
112 + var last = arguments.length - 1;
113 + var fn;
114 + if (last > 0 && typeof arguments[last] === "function") {
115 + fn = arguments[last];
116 + if (!false) {
117 + if (last <= 8 && canEvaluate) {
118 + var ret = new Promise(INTERNAL);
119 + ret._captureStackTrace();
120 + var HolderClass = holderClasses[last - 1];
121 + var holder = new HolderClass(fn);
122 + var callbacks = thenCallbacks;
123 +
124 + for (var i = 0; i < last; ++i) {
125 + var maybePromise = tryConvertToPromise(arguments[i], ret);
126 + if (maybePromise instanceof Promise) {
127 + maybePromise = maybePromise._target();
128 + var bitField = maybePromise._bitField;
129 + ;
130 + if (((bitField & 50397184) === 0)) {
131 + maybePromise._then(callbacks[i], reject,
132 + undefined, ret, holder);
133 + promiseSetters[i](maybePromise, holder);
134 + holder.asyncNeeded = false;
135 + } else if (((bitField & 33554432) !== 0)) {
136 + callbacks[i].call(ret,
137 + maybePromise._value(), holder);
138 + } else if (((bitField & 16777216) !== 0)) {
139 + ret._reject(maybePromise._reason());
140 + } else {
141 + ret._cancel();
142 + }
143 + } else {
144 + callbacks[i].call(ret, maybePromise, holder);
145 + }
146 + }
147 +
148 + if (!ret._isFateSealed()) {
149 + if (holder.asyncNeeded) {
150 + var domain = getDomain();
151 + if (domain !== null) {
152 + holder.fn = util.domainBind(domain, holder.fn);
153 + }
154 + }
155 + ret._setAsyncGuaranteed();
156 + ret._setOnCancel(holder);
157 + }
158 + return ret;
159 + }
160 + }
161 + }
162 + var $_len = arguments.length;var args = new Array($_len); for(var $_i = 0; $_i < $_len; ++$_i) {args[$_i] = arguments[$_i];};
163 + if (fn) args.pop();
164 + var ret = new PromiseArray(args).promise();
165 + return fn !== undefined ? ret.spread(fn) : ret;
166 +};
167 +
168 +};
1 +"use strict";
2 +module.exports = function(Promise,
3 + PromiseArray,
4 + apiRejection,
5 + tryConvertToPromise,
6 + INTERNAL,
7 + debug) {
8 +var getDomain = Promise._getDomain;
9 +var util = require("./util");
10 +var tryCatch = util.tryCatch;
11 +var errorObj = util.errorObj;
12 +var async = Promise._async;
13 +
14 +function MappingPromiseArray(promises, fn, limit, _filter) {
15 + this.constructor$(promises);
16 + this._promise._captureStackTrace();
17 + var domain = getDomain();
18 + this._callback = domain === null ? fn : util.domainBind(domain, fn);
19 + this._preservedValues = _filter === INTERNAL
20 + ? new Array(this.length())
21 + : null;
22 + this._limit = limit;
23 + this._inFlight = 0;
24 + this._queue = [];
25 + async.invoke(this._asyncInit, this, undefined);
26 +}
27 +util.inherits(MappingPromiseArray, PromiseArray);
28 +
29 +MappingPromiseArray.prototype._asyncInit = function() {
30 + this._init$(undefined, -2);
31 +};
32 +
33 +MappingPromiseArray.prototype._init = function () {};
34 +
35 +MappingPromiseArray.prototype._promiseFulfilled = function (value, index) {
36 + var values = this._values;
37 + var length = this.length();
38 + var preservedValues = this._preservedValues;
39 + var limit = this._limit;
40 +
41 + if (index < 0) {
42 + index = (index * -1) - 1;
43 + values[index] = value;
44 + if (limit >= 1) {
45 + this._inFlight--;
46 + this._drainQueue();
47 + if (this._isResolved()) return true;
48 + }
49 + } else {
50 + if (limit >= 1 && this._inFlight >= limit) {
51 + values[index] = value;
52 + this._queue.push(index);
53 + return false;
54 + }
55 + if (preservedValues !== null) preservedValues[index] = value;
56 +
57 + var promise = this._promise;
58 + var callback = this._callback;
59 + var receiver = promise._boundValue();
60 + promise._pushContext();
61 + var ret = tryCatch(callback).call(receiver, value, index, length);
62 + var promiseCreated = promise._popContext();
63 + debug.checkForgottenReturns(
64 + ret,
65 + promiseCreated,
66 + preservedValues !== null ? "Promise.filter" : "Promise.map",
67 + promise
68 + );
69 + if (ret === errorObj) {
70 + this._reject(ret.e);
71 + return true;
72 + }
73 +
74 + var maybePromise = tryConvertToPromise(ret, this._promise);
75 + if (maybePromise instanceof Promise) {
76 + maybePromise = maybePromise._target();
77 + var bitField = maybePromise._bitField;
78 + ;
79 + if (((bitField & 50397184) === 0)) {
80 + if (limit >= 1) this._inFlight++;
81 + values[index] = maybePromise;
82 + maybePromise._proxy(this, (index + 1) * -1);
83 + return false;
84 + } else if (((bitField & 33554432) !== 0)) {
85 + ret = maybePromise._value();
86 + } else if (((bitField & 16777216) !== 0)) {
87 + this._reject(maybePromise._reason());
88 + return true;
89 + } else {
90 + this._cancel();
91 + return true;
92 + }
93 + }
94 + values[index] = ret;
95 + }
96 + var totalResolved = ++this._totalResolved;
97 + if (totalResolved >= length) {
98 + if (preservedValues !== null) {
99 + this._filter(values, preservedValues);
100 + } else {
101 + this._resolve(values);
102 + }
103 + return true;
104 + }
105 + return false;
106 +};
107 +
108 +MappingPromiseArray.prototype._drainQueue = function () {
109 + var queue = this._queue;
110 + var limit = this._limit;
111 + var values = this._values;
112 + while (queue.length > 0 && this._inFlight < limit) {
113 + if (this._isResolved()) return;
114 + var index = queue.pop();
115 + this._promiseFulfilled(values[index], index);
116 + }
117 +};
118 +
119 +MappingPromiseArray.prototype._filter = function (booleans, values) {
120 + var len = values.length;
121 + var ret = new Array(len);
122 + var j = 0;
123 + for (var i = 0; i < len; ++i) {
124 + if (booleans[i]) ret[j++] = values[i];
125 + }
126 + ret.length = j;
127 + this._resolve(ret);
128 +};
129 +
130 +MappingPromiseArray.prototype.preservedValues = function () {
131 + return this._preservedValues;
132 +};
133 +
134 +function map(promises, fn, options, _filter) {
135 + if (typeof fn !== "function") {
136 + return apiRejection("expecting a function but got " + util.classString(fn));
137 + }
138 +
139 + var limit = 0;
140 + if (options !== undefined) {
141 + if (typeof options === "object" && options !== null) {
142 + if (typeof options.concurrency !== "number") {
143 + return Promise.reject(
144 + new TypeError("'concurrency' must be a number but it is " +
145 + util.classString(options.concurrency)));
146 + }
147 + limit = options.concurrency;
148 + } else {
149 + return Promise.reject(new TypeError(
150 + "options argument must be an object but it is " +
151 + util.classString(options)));
152 + }
153 + }
154 + limit = typeof limit === "number" &&
155 + isFinite(limit) && limit >= 1 ? limit : 0;
156 + return new MappingPromiseArray(promises, fn, limit, _filter).promise();
157 +}
158 +
159 +Promise.prototype.map = function (fn, options) {
160 + return map(this, fn, options, null);
161 +};
162 +
163 +Promise.map = function (promises, fn, options, _filter) {
164 + return map(promises, fn, options, _filter);
165 +};
166 +
167 +
168 +};
1 +"use strict";
2 +module.exports =
3 +function(Promise, INTERNAL, tryConvertToPromise, apiRejection, debug) {
4 +var util = require("./util");
5 +var tryCatch = util.tryCatch;
6 +
7 +Promise.method = function (fn) {
8 + if (typeof fn !== "function") {
9 + throw new Promise.TypeError("expecting a function but got " + util.classString(fn));
10 + }
11 + return function () {
12 + var ret = new Promise(INTERNAL);
13 + ret._captureStackTrace();
14 + ret._pushContext();
15 + var value = tryCatch(fn).apply(this, arguments);
16 + var promiseCreated = ret._popContext();
17 + debug.checkForgottenReturns(
18 + value, promiseCreated, "Promise.method", ret);
19 + ret._resolveFromSyncValue(value);
20 + return ret;
21 + };
22 +};
23 +
24 +Promise.attempt = Promise["try"] = function (fn) {
25 + if (typeof fn !== "function") {
26 + return apiRejection("expecting a function but got " + util.classString(fn));
27 + }
28 + var ret = new Promise(INTERNAL);
29 + ret._captureStackTrace();
30 + ret._pushContext();
31 + var value;
32 + if (arguments.length > 1) {
33 + debug.deprecated("calling Promise.try with more than 1 argument");
34 + var arg = arguments[1];
35 + var ctx = arguments[2];
36 + value = util.isArray(arg) ? tryCatch(fn).apply(ctx, arg)
37 + : tryCatch(fn).call(ctx, arg);
38 + } else {
39 + value = tryCatch(fn)();
40 + }
41 + var promiseCreated = ret._popContext();
42 + debug.checkForgottenReturns(
43 + value, promiseCreated, "Promise.try", ret);
44 + ret._resolveFromSyncValue(value);
45 + return ret;
46 +};
47 +
48 +Promise.prototype._resolveFromSyncValue = function (value) {
49 + if (value === util.errorObj) {
50 + this._rejectCallback(value.e, false);
51 + } else {
52 + this._resolveCallback(value, true);
53 + }
54 +};
55 +};
1 +"use strict";
2 +var util = require("./util");
3 +var maybeWrapAsError = util.maybeWrapAsError;
4 +var errors = require("./errors");
5 +var OperationalError = errors.OperationalError;
6 +var es5 = require("./es5");
7 +
8 +function isUntypedError(obj) {
9 + return obj instanceof Error &&
10 + es5.getPrototypeOf(obj) === Error.prototype;
11 +}
12 +
13 +var rErrorKey = /^(?:name|message|stack|cause)$/;
14 +function wrapAsOperationalError(obj) {
15 + var ret;
16 + if (isUntypedError(obj)) {
17 + ret = new OperationalError(obj);
18 + ret.name = obj.name;
19 + ret.message = obj.message;
20 + ret.stack = obj.stack;
21 + var keys = es5.keys(obj);
22 + for (var i = 0; i < keys.length; ++i) {
23 + var key = keys[i];
24 + if (!rErrorKey.test(key)) {
25 + ret[key] = obj[key];
26 + }
27 + }
28 + return ret;
29 + }
30 + util.markAsOriginatingFromRejection(obj);
31 + return obj;
32 +}
33 +
34 +function nodebackForPromise(promise, multiArgs) {
35 + return function(err, value) {
36 + if (promise === null) return;
37 + if (err) {
38 + var wrapped = wrapAsOperationalError(maybeWrapAsError(err));
39 + promise._attachExtraTrace(wrapped);
40 + promise._reject(wrapped);
41 + } else if (!multiArgs) {
42 + promise._fulfill(value);
43 + } else {
44 + 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];};
45 + promise._fulfill(args);
46 + }
47 + promise = null;
48 + };
49 +}
50 +
51 +module.exports = nodebackForPromise;
1 +"use strict";
2 +module.exports = function(Promise) {
3 +var util = require("./util");
4 +var async = Promise._async;
5 +var tryCatch = util.tryCatch;
6 +var errorObj = util.errorObj;
7 +
8 +function spreadAdapter(val, nodeback) {
9 + var promise = this;
10 + if (!util.isArray(val)) return successAdapter.call(promise, val, nodeback);
11 + var ret =
12 + tryCatch(nodeback).apply(promise._boundValue(), [null].concat(val));
13 + if (ret === errorObj) {
14 + async.throwLater(ret.e);
15 + }
16 +}
17 +
18 +function successAdapter(val, nodeback) {
19 + var promise = this;
20 + var receiver = promise._boundValue();
21 + var ret = val === undefined
22 + ? tryCatch(nodeback).call(receiver, null)
23 + : tryCatch(nodeback).call(receiver, null, val);
24 + if (ret === errorObj) {
25 + async.throwLater(ret.e);
26 + }
27 +}
28 +function errorAdapter(reason, nodeback) {
29 + var promise = this;
30 + if (!reason) {
31 + var newReason = new Error(reason + "");
32 + newReason.cause = reason;
33 + reason = newReason;
34 + }
35 + var ret = tryCatch(nodeback).call(promise._boundValue(), reason);
36 + if (ret === errorObj) {
37 + async.throwLater(ret.e);
38 + }
39 +}
40 +
41 +Promise.prototype.asCallback = Promise.prototype.nodeify = function (nodeback,
42 + options) {
43 + if (typeof nodeback == "function") {
44 + var adapter = successAdapter;
45 + if (options !== undefined && Object(options).spread) {
46 + adapter = spreadAdapter;
47 + }
48 + this._then(
49 + adapter,
50 + errorAdapter,
51 + undefined,
52 + this,
53 + nodeback
54 + );
55 + }
56 + return this;
57 +};
58 +};
This diff is collapsed. Click to expand it.
1 +"use strict";
2 +module.exports = function(Promise, INTERNAL, tryConvertToPromise,
3 + apiRejection, Proxyable) {
4 +var util = require("./util");
5 +var isArray = util.isArray;
6 +
7 +function toResolutionValue(val) {
8 + switch(val) {
9 + case -2: return [];
10 + case -3: return {};
11 + case -6: return new Map();
12 + }
13 +}
14 +
15 +function PromiseArray(values) {
16 + var promise = this._promise = new Promise(INTERNAL);
17 + if (values instanceof Promise) {
18 + promise._propagateFrom(values, 3);
19 + }
20 + promise._setOnCancel(this);
21 + this._values = values;
22 + this._length = 0;
23 + this._totalResolved = 0;
24 + this._init(undefined, -2);
25 +}
26 +util.inherits(PromiseArray, Proxyable);
27 +
28 +PromiseArray.prototype.length = function () {
29 + return this._length;
30 +};
31 +
32 +PromiseArray.prototype.promise = function () {
33 + return this._promise;
34 +};
35 +
36 +PromiseArray.prototype._init = function init(_, resolveValueIfEmpty) {
37 + var values = tryConvertToPromise(this._values, this._promise);
38 + if (values instanceof Promise) {
39 + values = values._target();
40 + var bitField = values._bitField;
41 + ;
42 + this._values = values;
43 +
44 + if (((bitField & 50397184) === 0)) {
45 + this._promise._setAsyncGuaranteed();
46 + return values._then(
47 + init,
48 + this._reject,
49 + undefined,
50 + this,
51 + resolveValueIfEmpty
52 + );
53 + } else if (((bitField & 33554432) !== 0)) {
54 + values = values._value();
55 + } else if (((bitField & 16777216) !== 0)) {
56 + return this._reject(values._reason());
57 + } else {
58 + return this._cancel();
59 + }
60 + }
61 + values = util.asArray(values);
62 + if (values === null) {
63 + var err = apiRejection(
64 + "expecting an array or an iterable object but got " + util.classString(values)).reason();
65 + this._promise._rejectCallback(err, false);
66 + return;
67 + }
68 +
69 + if (values.length === 0) {
70 + if (resolveValueIfEmpty === -5) {
71 + this._resolveEmptyArray();
72 + }
73 + else {
74 + this._resolve(toResolutionValue(resolveValueIfEmpty));
75 + }
76 + return;
77 + }
78 + this._iterate(values);
79 +};
80 +
81 +PromiseArray.prototype._iterate = function(values) {
82 + var len = this.getActualLength(values.length);
83 + this._length = len;
84 + this._values = this.shouldCopyValues() ? new Array(len) : this._values;
85 + var result = this._promise;
86 + var isResolved = false;
87 + var bitField = null;
88 + for (var i = 0; i < len; ++i) {
89 + var maybePromise = tryConvertToPromise(values[i], result);
90 +
91 + if (maybePromise instanceof Promise) {
92 + maybePromise = maybePromise._target();
93 + bitField = maybePromise._bitField;
94 + } else {
95 + bitField = null;
96 + }
97 +
98 + if (isResolved) {
99 + if (bitField !== null) {
100 + maybePromise.suppressUnhandledRejections();
101 + }
102 + } else if (bitField !== null) {
103 + if (((bitField & 50397184) === 0)) {
104 + maybePromise._proxy(this, i);
105 + this._values[i] = maybePromise;
106 + } else if (((bitField & 33554432) !== 0)) {
107 + isResolved = this._promiseFulfilled(maybePromise._value(), i);
108 + } else if (((bitField & 16777216) !== 0)) {
109 + isResolved = this._promiseRejected(maybePromise._reason(), i);
110 + } else {
111 + isResolved = this._promiseCancelled(i);
112 + }
113 + } else {
114 + isResolved = this._promiseFulfilled(maybePromise, i);
115 + }
116 + }
117 + if (!isResolved) result._setAsyncGuaranteed();
118 +};
119 +
120 +PromiseArray.prototype._isResolved = function () {
121 + return this._values === null;
122 +};
123 +
124 +PromiseArray.prototype._resolve = function (value) {
125 + this._values = null;
126 + this._promise._fulfill(value);
127 +};
128 +
129 +PromiseArray.prototype._cancel = function() {
130 + if (this._isResolved() || !this._promise._isCancellable()) return;
131 + this._values = null;
132 + this._promise._cancel();
133 +};
134 +
135 +PromiseArray.prototype._reject = function (reason) {
136 + this._values = null;
137 + this._promise._rejectCallback(reason, false);
138 +};
139 +
140 +PromiseArray.prototype._promiseFulfilled = function (value, index) {
141 + this._values[index] = value;
142 + var totalResolved = ++this._totalResolved;
143 + if (totalResolved >= this._length) {
144 + this._resolve(this._values);
145 + return true;
146 + }
147 + return false;
148 +};
149 +
150 +PromiseArray.prototype._promiseCancelled = function() {
151 + this._cancel();
152 + return true;
153 +};
154 +
155 +PromiseArray.prototype._promiseRejected = function (reason) {
156 + this._totalResolved++;
157 + this._reject(reason);
158 + return true;
159 +};
160 +
161 +PromiseArray.prototype._resultCancelled = function() {
162 + if (this._isResolved()) return;
163 + var values = this._values;
164 + this._cancel();
165 + if (values instanceof Promise) {
166 + values.cancel();
167 + } else {
168 + for (var i = 0; i < values.length; ++i) {
169 + if (values[i] instanceof Promise) {
170 + values[i].cancel();
171 + }
172 + }
173 + }
174 +};
175 +
176 +PromiseArray.prototype.shouldCopyValues = function () {
177 + return true;
178 +};
179 +
180 +PromiseArray.prototype.getActualLength = function (len) {
181 + return len;
182 +};
183 +
184 +return PromiseArray;
185 +};
This diff is collapsed. Click to expand it.
1 +"use strict";
2 +module.exports = function(
3 + Promise, PromiseArray, tryConvertToPromise, apiRejection) {
4 +var util = require("./util");
5 +var isObject = util.isObject;
6 +var es5 = require("./es5");
7 +var Es6Map;
8 +if (typeof Map === "function") Es6Map = Map;
9 +
10 +var mapToEntries = (function() {
11 + var index = 0;
12 + var size = 0;
13 +
14 + function extractEntry(value, key) {
15 + this[index] = value;
16 + this[index + size] = key;
17 + index++;
18 + }
19 +
20 + return function mapToEntries(map) {
21 + size = map.size;
22 + index = 0;
23 + var ret = new Array(map.size * 2);
24 + map.forEach(extractEntry, ret);
25 + return ret;
26 + };
27 +})();
28 +
29 +var entriesToMap = function(entries) {
30 + var ret = new Es6Map();
31 + var length = entries.length / 2 | 0;
32 + for (var i = 0; i < length; ++i) {
33 + var key = entries[length + i];
34 + var value = entries[i];
35 + ret.set(key, value);
36 + }
37 + return ret;
38 +};
39 +
40 +function PropertiesPromiseArray(obj) {
41 + var isMap = false;
42 + var entries;
43 + if (Es6Map !== undefined && obj instanceof Es6Map) {
44 + entries = mapToEntries(obj);
45 + isMap = true;
46 + } else {
47 + var keys = es5.keys(obj);
48 + var len = keys.length;
49 + entries = new Array(len * 2);
50 + for (var i = 0; i < len; ++i) {
51 + var key = keys[i];
52 + entries[i] = obj[key];
53 + entries[i + len] = key;
54 + }
55 + }
56 + this.constructor$(entries);
57 + this._isMap = isMap;
58 + this._init$(undefined, isMap ? -6 : -3);
59 +}
60 +util.inherits(PropertiesPromiseArray, PromiseArray);
61 +
62 +PropertiesPromiseArray.prototype._init = function () {};
63 +
64 +PropertiesPromiseArray.prototype._promiseFulfilled = function (value, index) {
65 + this._values[index] = value;
66 + var totalResolved = ++this._totalResolved;
67 + if (totalResolved >= this._length) {
68 + var val;
69 + if (this._isMap) {
70 + val = entriesToMap(this._values);
71 + } else {
72 + val = {};
73 + var keyOffset = this.length();
74 + for (var i = 0, len = this.length(); i < len; ++i) {
75 + val[this._values[i + keyOffset]] = this._values[i];
76 + }
77 + }
78 + this._resolve(val);
79 + return true;
80 + }
81 + return false;
82 +};
83 +
84 +PropertiesPromiseArray.prototype.shouldCopyValues = function () {
85 + return false;
86 +};
87 +
88 +PropertiesPromiseArray.prototype.getActualLength = function (len) {
89 + return len >> 1;
90 +};
91 +
92 +function props(promises) {
93 + var ret;
94 + var castValue = tryConvertToPromise(promises);
95 +
96 + if (!isObject(castValue)) {
97 + return apiRejection("cannot await properties of a non-object\u000a\u000a See http://goo.gl/MqrFmX\u000a");
98 + } else if (castValue instanceof Promise) {
99 + ret = castValue._then(
100 + Promise.props, undefined, undefined, undefined, undefined);
101 + } else {
102 + ret = new PropertiesPromiseArray(castValue).promise();
103 + }
104 +
105 + if (castValue instanceof Promise) {
106 + ret._propagateFrom(castValue, 2);
107 + }
108 + return ret;
109 +}
110 +
111 +Promise.prototype.props = function () {
112 + return props(this);
113 +};
114 +
115 +Promise.props = function (promises) {
116 + return props(promises);
117 +};
118 +};
1 +"use strict";
2 +function arrayMove(src, srcIndex, dst, dstIndex, len) {
3 + for (var j = 0; j < len; ++j) {
4 + dst[j + dstIndex] = src[j + srcIndex];
5 + src[j + srcIndex] = void 0;
6 + }
7 +}
8 +
9 +function Queue(capacity) {
10 + this._capacity = capacity;
11 + this._length = 0;
12 + this._front = 0;
13 +}
14 +
15 +Queue.prototype._willBeOverCapacity = function (size) {
16 + return this._capacity < size;
17 +};
18 +
19 +Queue.prototype._pushOne = function (arg) {
20 + var length = this.length();
21 + this._checkCapacity(length + 1);
22 + var i = (this._front + length) & (this._capacity - 1);
23 + this[i] = arg;
24 + this._length = length + 1;
25 +};
26 +
27 +Queue.prototype.push = function (fn, receiver, arg) {
28 + var length = this.length() + 3;
29 + if (this._willBeOverCapacity(length)) {
30 + this._pushOne(fn);
31 + this._pushOne(receiver);
32 + this._pushOne(arg);
33 + return;
34 + }
35 + var j = this._front + length - 3;
36 + this._checkCapacity(length);
37 + var wrapMask = this._capacity - 1;
38 + this[(j + 0) & wrapMask] = fn;
39 + this[(j + 1) & wrapMask] = receiver;
40 + this[(j + 2) & wrapMask] = arg;
41 + this._length = length;
42 +};
43 +
44 +Queue.prototype.shift = function () {
45 + var front = this._front,
46 + ret = this[front];
47 +
48 + this[front] = undefined;
49 + this._front = (front + 1) & (this._capacity - 1);
50 + this._length--;
51 + return ret;
52 +};
53 +
54 +Queue.prototype.length = function () {
55 + return this._length;
56 +};
57 +
58 +Queue.prototype._checkCapacity = function (size) {
59 + if (this._capacity < size) {
60 + this._resizeTo(this._capacity << 1);
61 + }
62 +};
63 +
64 +Queue.prototype._resizeTo = function (capacity) {
65 + var oldCapacity = this._capacity;
66 + this._capacity = capacity;
67 + var front = this._front;
68 + var length = this._length;
69 + var moveItemsCount = (front + length) & (oldCapacity - 1);
70 + arrayMove(this, 0, this, oldCapacity, moveItemsCount);
71 +};
72 +
73 +module.exports = Queue;
1 +"use strict";
2 +module.exports = function(
3 + Promise, INTERNAL, tryConvertToPromise, apiRejection) {
4 +var util = require("./util");
5 +
6 +var raceLater = function (promise) {
7 + return promise.then(function(array) {
8 + return race(array, promise);
9 + });
10 +};
11 +
12 +function race(promises, parent) {
13 + var maybePromise = tryConvertToPromise(promises);
14 +
15 + if (maybePromise instanceof Promise) {
16 + return raceLater(maybePromise);
17 + } else {
18 + promises = util.asArray(promises);
19 + if (promises === null)
20 + return apiRejection("expecting an array or an iterable object but got " + util.classString(promises));
21 + }
22 +
23 + var ret = new Promise(INTERNAL);
24 + if (parent !== undefined) {
25 + ret._propagateFrom(parent, 3);
26 + }
27 + var fulfill = ret._fulfill;
28 + var reject = ret._reject;
29 + for (var i = 0, len = promises.length; i < len; ++i) {
30 + var val = promises[i];
31 +
32 + if (val === undefined && !(i in promises)) {
33 + continue;
34 + }
35 +
36 + Promise.cast(val)._then(fulfill, reject, undefined, ret, null);
37 + }
38 + return ret;
39 +}
40 +
41 +Promise.race = function (promises) {
42 + return race(promises, undefined);
43 +};
44 +
45 +Promise.prototype.race = function () {
46 + return race(this, undefined);
47 +};
48 +
49 +};
1 +"use strict";
2 +module.exports = function(Promise,
3 + PromiseArray,
4 + apiRejection,
5 + tryConvertToPromise,
6 + INTERNAL,
7 + debug) {
8 +var getDomain = Promise._getDomain;
9 +var util = require("./util");
10 +var tryCatch = util.tryCatch;
11 +
12 +function ReductionPromiseArray(promises, fn, initialValue, _each) {
13 + this.constructor$(promises);
14 + var domain = getDomain();
15 + this._fn = domain === null ? fn : util.domainBind(domain, fn);
16 + if (initialValue !== undefined) {
17 + initialValue = Promise.resolve(initialValue);
18 + initialValue._attachCancellationCallback(this);
19 + }
20 + this._initialValue = initialValue;
21 + this._currentCancellable = null;
22 + if(_each === INTERNAL) {
23 + this._eachValues = Array(this._length);
24 + } else if (_each === 0) {
25 + this._eachValues = null;
26 + } else {
27 + this._eachValues = undefined;
28 + }
29 + this._promise._captureStackTrace();
30 + this._init$(undefined, -5);
31 +}
32 +util.inherits(ReductionPromiseArray, PromiseArray);
33 +
34 +ReductionPromiseArray.prototype._gotAccum = function(accum) {
35 + if (this._eachValues !== undefined &&
36 + this._eachValues !== null &&
37 + accum !== INTERNAL) {
38 + this._eachValues.push(accum);
39 + }
40 +};
41 +
42 +ReductionPromiseArray.prototype._eachComplete = function(value) {
43 + if (this._eachValues !== null) {
44 + this._eachValues.push(value);
45 + }
46 + return this._eachValues;
47 +};
48 +
49 +ReductionPromiseArray.prototype._init = function() {};
50 +
51 +ReductionPromiseArray.prototype._resolveEmptyArray = function() {
52 + this._resolve(this._eachValues !== undefined ? this._eachValues
53 + : this._initialValue);
54 +};
55 +
56 +ReductionPromiseArray.prototype.shouldCopyValues = function () {
57 + return false;
58 +};
59 +
60 +ReductionPromiseArray.prototype._resolve = function(value) {
61 + this._promise._resolveCallback(value);
62 + this._values = null;
63 +};
64 +
65 +ReductionPromiseArray.prototype._resultCancelled = function(sender) {
66 + if (sender === this._initialValue) return this._cancel();
67 + if (this._isResolved()) return;
68 + this._resultCancelled$();
69 + if (this._currentCancellable instanceof Promise) {
70 + this._currentCancellable.cancel();
71 + }
72 + if (this._initialValue instanceof Promise) {
73 + this._initialValue.cancel();
74 + }
75 +};
76 +
77 +ReductionPromiseArray.prototype._iterate = function (values) {
78 + this._values = values;
79 + var value;
80 + var i;
81 + var length = values.length;
82 + if (this._initialValue !== undefined) {
83 + value = this._initialValue;
84 + i = 0;
85 + } else {
86 + value = Promise.resolve(values[0]);
87 + i = 1;
88 + }
89 +
90 + this._currentCancellable = value;
91 +
92 + if (!value.isRejected()) {
93 + for (; i < length; ++i) {
94 + var ctx = {
95 + accum: null,
96 + value: values[i],
97 + index: i,
98 + length: length,
99 + array: this
100 + };
101 + value = value._then(gotAccum, undefined, undefined, ctx, undefined);
102 + }
103 + }
104 +
105 + if (this._eachValues !== undefined) {
106 + value = value
107 + ._then(this._eachComplete, undefined, undefined, this, undefined);
108 + }
109 + value._then(completed, completed, undefined, value, this);
110 +};
111 +
112 +Promise.prototype.reduce = function (fn, initialValue) {
113 + return reduce(this, fn, initialValue, null);
114 +};
115 +
116 +Promise.reduce = function (promises, fn, initialValue, _each) {
117 + return reduce(promises, fn, initialValue, _each);
118 +};
119 +
120 +function completed(valueOrReason, array) {
121 + if (this.isFulfilled()) {
122 + array._resolve(valueOrReason);
123 + } else {
124 + array._reject(valueOrReason);
125 + }
126 +}
127 +
128 +function reduce(promises, fn, initialValue, _each) {
129 + if (typeof fn !== "function") {
130 + return apiRejection("expecting a function but got " + util.classString(fn));
131 + }
132 + var array = new ReductionPromiseArray(promises, fn, initialValue, _each);
133 + return array.promise();
134 +}
135 +
136 +function gotAccum(accum) {
137 + this.accum = accum;
138 + this.array._gotAccum(accum);
139 + var value = tryConvertToPromise(this.value, this.array._promise);
140 + if (value instanceof Promise) {
141 + this.array._currentCancellable = value;
142 + return value._then(gotValue, undefined, undefined, this, undefined);
143 + } else {
144 + return gotValue.call(this, value);
145 + }
146 +}
147 +
148 +function gotValue(value) {
149 + var array = this.array;
150 + var promise = array._promise;
151 + var fn = tryCatch(array._fn);
152 + promise._pushContext();
153 + var ret;
154 + if (array._eachValues !== undefined) {
155 + ret = fn.call(promise._boundValue(), value, this.index, this.length);
156 + } else {
157 + ret = fn.call(promise._boundValue(),
158 + this.accum, value, this.index, this.length);
159 + }
160 + if (ret instanceof Promise) {
161 + array._currentCancellable = ret;
162 + }
163 + var promiseCreated = promise._popContext();
164 + debug.checkForgottenReturns(
165 + ret,
166 + promiseCreated,
167 + array._eachValues !== undefined ? "Promise.each" : "Promise.reduce",
168 + promise
169 + );
170 + return ret;
171 +}
172 +};
1 +"use strict";
2 +var util = require("./util");
3 +var schedule;
4 +var noAsyncScheduler = function() {
5 + throw new Error("No async scheduler available\u000a\u000a See http://goo.gl/MqrFmX\u000a");
6 +};
7 +var NativePromise = util.getNativePromise();
8 +if (util.isNode && typeof MutationObserver === "undefined") {
9 + var GlobalSetImmediate = global.setImmediate;
10 + var ProcessNextTick = process.nextTick;
11 + schedule = util.isRecentNode
12 + ? function(fn) { GlobalSetImmediate.call(global, fn); }
13 + : function(fn) { ProcessNextTick.call(process, fn); };
14 +} else if (typeof NativePromise === "function" &&
15 + typeof NativePromise.resolve === "function") {
16 + var nativePromise = NativePromise.resolve();
17 + schedule = function(fn) {
18 + nativePromise.then(fn);
19 + };
20 +} else if ((typeof MutationObserver !== "undefined") &&
21 + !(typeof window !== "undefined" &&
22 + window.navigator &&
23 + (window.navigator.standalone || window.cordova))) {
24 + schedule = (function() {
25 + var div = document.createElement("div");
26 + var opts = {attributes: true};
27 + var toggleScheduled = false;
28 + var div2 = document.createElement("div");
29 + var o2 = new MutationObserver(function() {
30 + div.classList.toggle("foo");
31 + toggleScheduled = false;
32 + });
33 + o2.observe(div2, opts);
34 +
35 + var scheduleToggle = function() {
36 + if (toggleScheduled) return;
37 + toggleScheduled = true;
38 + div2.classList.toggle("foo");
39 + };
40 +
41 + return function schedule(fn) {
42 + var o = new MutationObserver(function() {
43 + o.disconnect();
44 + fn();
45 + });
46 + o.observe(div, opts);
47 + scheduleToggle();
48 + };
49 + })();
50 +} else if (typeof setImmediate !== "undefined") {
51 + schedule = function (fn) {
52 + setImmediate(fn);
53 + };
54 +} else if (typeof setTimeout !== "undefined") {
55 + schedule = function (fn) {
56 + setTimeout(fn, 0);
57 + };
58 +} else {
59 + schedule = noAsyncScheduler;
60 +}
61 +module.exports = schedule;
1 +"use strict";
2 +module.exports =
3 + function(Promise, PromiseArray, debug) {
4 +var PromiseInspection = Promise.PromiseInspection;
5 +var util = require("./util");
6 +
7 +function SettledPromiseArray(values) {
8 + this.constructor$(values);
9 +}
10 +util.inherits(SettledPromiseArray, PromiseArray);
11 +
12 +SettledPromiseArray.prototype._promiseResolved = function (index, inspection) {
13 + this._values[index] = inspection;
14 + var totalResolved = ++this._totalResolved;
15 + if (totalResolved >= this._length) {
16 + this._resolve(this._values);
17 + return true;
18 + }
19 + return false;
20 +};
21 +
22 +SettledPromiseArray.prototype._promiseFulfilled = function (value, index) {
23 + var ret = new PromiseInspection();
24 + ret._bitField = 33554432;
25 + ret._settledValueField = value;
26 + return this._promiseResolved(index, ret);
27 +};
28 +SettledPromiseArray.prototype._promiseRejected = function (reason, index) {
29 + var ret = new PromiseInspection();
30 + ret._bitField = 16777216;
31 + ret._settledValueField = reason;
32 + return this._promiseResolved(index, ret);
33 +};
34 +
35 +Promise.settle = function (promises) {
36 + debug.deprecated(".settle()", ".reflect()");
37 + return new SettledPromiseArray(promises).promise();
38 +};
39 +
40 +Promise.prototype.settle = function () {
41 + return Promise.settle(this);
42 +};
43 +};
1 +"use strict";
2 +module.exports =
3 +function(Promise, PromiseArray, apiRejection) {
4 +var util = require("./util");
5 +var RangeError = require("./errors").RangeError;
6 +var AggregateError = require("./errors").AggregateError;
7 +var isArray = util.isArray;
8 +var CANCELLATION = {};
9 +
10 +
11 +function SomePromiseArray(values) {
12 + this.constructor$(values);
13 + this._howMany = 0;
14 + this._unwrap = false;
15 + this._initialized = false;
16 +}
17 +util.inherits(SomePromiseArray, PromiseArray);
18 +
19 +SomePromiseArray.prototype._init = function () {
20 + if (!this._initialized) {
21 + return;
22 + }
23 + if (this._howMany === 0) {
24 + this._resolve([]);
25 + return;
26 + }
27 + this._init$(undefined, -5);
28 + var isArrayResolved = isArray(this._values);
29 + if (!this._isResolved() &&
30 + isArrayResolved &&
31 + this._howMany > this._canPossiblyFulfill()) {
32 + this._reject(this._getRangeError(this.length()));
33 + }
34 +};
35 +
36 +SomePromiseArray.prototype.init = function () {
37 + this._initialized = true;
38 + this._init();
39 +};
40 +
41 +SomePromiseArray.prototype.setUnwrap = function () {
42 + this._unwrap = true;
43 +};
44 +
45 +SomePromiseArray.prototype.howMany = function () {
46 + return this._howMany;
47 +};
48 +
49 +SomePromiseArray.prototype.setHowMany = function (count) {
50 + this._howMany = count;
51 +};
52 +
53 +SomePromiseArray.prototype._promiseFulfilled = function (value) {
54 + this._addFulfilled(value);
55 + if (this._fulfilled() === this.howMany()) {
56 + this._values.length = this.howMany();
57 + if (this.howMany() === 1 && this._unwrap) {
58 + this._resolve(this._values[0]);
59 + } else {
60 + this._resolve(this._values);
61 + }
62 + return true;
63 + }
64 + return false;
65 +
66 +};
67 +SomePromiseArray.prototype._promiseRejected = function (reason) {
68 + this._addRejected(reason);
69 + return this._checkOutcome();
70 +};
71 +
72 +SomePromiseArray.prototype._promiseCancelled = function () {
73 + if (this._values instanceof Promise || this._values == null) {
74 + return this._cancel();
75 + }
76 + this._addRejected(CANCELLATION);
77 + return this._checkOutcome();
78 +};
79 +
80 +SomePromiseArray.prototype._checkOutcome = function() {
81 + if (this.howMany() > this._canPossiblyFulfill()) {
82 + var e = new AggregateError();
83 + for (var i = this.length(); i < this._values.length; ++i) {
84 + if (this._values[i] !== CANCELLATION) {
85 + e.push(this._values[i]);
86 + }
87 + }
88 + if (e.length > 0) {
89 + this._reject(e);
90 + } else {
91 + this._cancel();
92 + }
93 + return true;
94 + }
95 + return false;
96 +};
97 +
98 +SomePromiseArray.prototype._fulfilled = function () {
99 + return this._totalResolved;
100 +};
101 +
102 +SomePromiseArray.prototype._rejected = function () {
103 + return this._values.length - this.length();
104 +};
105 +
106 +SomePromiseArray.prototype._addRejected = function (reason) {
107 + this._values.push(reason);
108 +};
109 +
110 +SomePromiseArray.prototype._addFulfilled = function (value) {
111 + this._values[this._totalResolved++] = value;
112 +};
113 +
114 +SomePromiseArray.prototype._canPossiblyFulfill = function () {
115 + return this.length() - this._rejected();
116 +};
117 +
118 +SomePromiseArray.prototype._getRangeError = function (count) {
119 + var message = "Input array must contain at least " +
120 + this._howMany + " items but contains only " + count + " items";
121 + return new RangeError(message);
122 +};
123 +
124 +SomePromiseArray.prototype._resolveEmptyArray = function () {
125 + this._reject(this._getRangeError(0));
126 +};
127 +
128 +function some(promises, howMany) {
129 + if ((howMany | 0) !== howMany || howMany < 0) {
130 + return apiRejection("expecting a positive integer\u000a\u000a See http://goo.gl/MqrFmX\u000a");
131 + }
132 + var ret = new SomePromiseArray(promises);
133 + var promise = ret.promise();
134 + ret.setHowMany(howMany);
135 + ret.init();
136 + return promise;
137 +}
138 +
139 +Promise.some = function (promises, howMany) {
140 + return some(promises, howMany);
141 +};
142 +
143 +Promise.prototype.some = function (howMany) {
144 + return some(this, howMany);
145 +};
146 +
147 +Promise._SomePromiseArray = SomePromiseArray;
148 +};
1 +"use strict";
2 +module.exports = function(Promise) {
3 +function PromiseInspection(promise) {
4 + if (promise !== undefined) {
5 + promise = promise._target();
6 + this._bitField = promise._bitField;
7 + this._settledValueField = promise._isFateSealed()
8 + ? promise._settledValue() : undefined;
9 + }
10 + else {
11 + this._bitField = 0;
12 + this._settledValueField = undefined;
13 + }
14 +}
15 +
16 +PromiseInspection.prototype._settledValue = function() {
17 + return this._settledValueField;
18 +};
19 +
20 +var value = PromiseInspection.prototype.value = function () {
21 + if (!this.isFulfilled()) {
22 + throw new TypeError("cannot get fulfillment value of a non-fulfilled promise\u000a\u000a See http://goo.gl/MqrFmX\u000a");
23 + }
24 + return this._settledValue();
25 +};
26 +
27 +var reason = PromiseInspection.prototype.error =
28 +PromiseInspection.prototype.reason = function () {
29 + if (!this.isRejected()) {
30 + throw new TypeError("cannot get rejection reason of a non-rejected promise\u000a\u000a See http://goo.gl/MqrFmX\u000a");
31 + }
32 + return this._settledValue();
33 +};
34 +
35 +var isFulfilled = PromiseInspection.prototype.isFulfilled = function() {
36 + return (this._bitField & 33554432) !== 0;
37 +};
38 +
39 +var isRejected = PromiseInspection.prototype.isRejected = function () {
40 + return (this._bitField & 16777216) !== 0;
41 +};
42 +
43 +var isPending = PromiseInspection.prototype.isPending = function () {
44 + return (this._bitField & 50397184) === 0;
45 +};
46 +
47 +var isResolved = PromiseInspection.prototype.isResolved = function () {
48 + return (this._bitField & 50331648) !== 0;
49 +};
50 +
51 +PromiseInspection.prototype.isCancelled = function() {
52 + return (this._bitField & 8454144) !== 0;
53 +};
54 +
55 +Promise.prototype.__isCancelled = function() {
56 + return (this._bitField & 65536) === 65536;
57 +};
58 +
59 +Promise.prototype._isCancelled = function() {
60 + return this._target().__isCancelled();
61 +};
62 +
63 +Promise.prototype.isCancelled = function() {
64 + return (this._target()._bitField & 8454144) !== 0;
65 +};
66 +
67 +Promise.prototype.isPending = function() {
68 + return isPending.call(this._target());
69 +};
70 +
71 +Promise.prototype.isRejected = function() {
72 + return isRejected.call(this._target());
73 +};
74 +
75 +Promise.prototype.isFulfilled = function() {
76 + return isFulfilled.call(this._target());
77 +};
78 +
79 +Promise.prototype.isResolved = function() {
80 + return isResolved.call(this._target());
81 +};
82 +
83 +Promise.prototype.value = function() {
84 + return value.call(this._target());
85 +};
86 +
87 +Promise.prototype.reason = function() {
88 + var target = this._target();
89 + target._unsetRejectionIsUnhandled();
90 + return reason.call(target);
91 +};
92 +
93 +Promise.prototype._value = function() {
94 + return this._settledValue();
95 +};
96 +
97 +Promise.prototype._reason = function() {
98 + this._unsetRejectionIsUnhandled();
99 + return this._settledValue();
100 +};
101 +
102 +Promise.PromiseInspection = PromiseInspection;
103 +};
1 +"use strict";
2 +module.exports = function(Promise, INTERNAL) {
3 +var util = require("./util");
4 +var errorObj = util.errorObj;
5 +var isObject = util.isObject;
6 +
7 +function tryConvertToPromise(obj, context) {
8 + if (isObject(obj)) {
9 + if (obj instanceof Promise) return obj;
10 + var then = getThen(obj);
11 + if (then === errorObj) {
12 + if (context) context._pushContext();
13 + var ret = Promise.reject(then.e);
14 + if (context) context._popContext();
15 + return ret;
16 + } else if (typeof then === "function") {
17 + if (isAnyBluebirdPromise(obj)) {
18 + var ret = new Promise(INTERNAL);
19 + obj._then(
20 + ret._fulfill,
21 + ret._reject,
22 + undefined,
23 + ret,
24 + null
25 + );
26 + return ret;
27 + }
28 + return doThenable(obj, then, context);
29 + }
30 + }
31 + return obj;
32 +}
33 +
34 +function doGetThen(obj) {
35 + return obj.then;
36 +}
37 +
38 +function getThen(obj) {
39 + try {
40 + return doGetThen(obj);
41 + } catch (e) {
42 + errorObj.e = e;
43 + return errorObj;
44 + }
45 +}
46 +
47 +var hasProp = {}.hasOwnProperty;
48 +function isAnyBluebirdPromise(obj) {
49 + try {
50 + return hasProp.call(obj, "_promise0");
51 + } catch (e) {
52 + return false;
53 + }
54 +}
55 +
56 +function doThenable(x, then, context) {
57 + var promise = new Promise(INTERNAL);
58 + var ret = promise;
59 + if (context) context._pushContext();
60 + promise._captureStackTrace();
61 + if (context) context._popContext();
62 + var synchronous = true;
63 + var result = util.tryCatch(then).call(x, resolve, reject);
64 + synchronous = false;
65 +
66 + if (promise && result === errorObj) {
67 + promise._rejectCallback(result.e, true, true);
68 + promise = null;
69 + }
70 +
71 + function resolve(value) {
72 + if (!promise) return;
73 + promise._resolveCallback(value);
74 + promise = null;
75 + }
76 +
77 + function reject(reason) {
78 + if (!promise) return;
79 + promise._rejectCallback(reason, synchronous, true);
80 + promise = null;
81 + }
82 + return ret;
83 +}
84 +
85 +return tryConvertToPromise;
86 +};
1 +"use strict";
2 +module.exports = function(Promise, INTERNAL, debug) {
3 +var util = require("./util");
4 +var TimeoutError = Promise.TimeoutError;
5 +
6 +function HandleWrapper(handle) {
7 + this.handle = handle;
8 +}
9 +
10 +HandleWrapper.prototype._resultCancelled = function() {
11 + clearTimeout(this.handle);
12 +};
13 +
14 +var afterValue = function(value) { return delay(+this).thenReturn(value); };
15 +var delay = Promise.delay = function (ms, value) {
16 + var ret;
17 + var handle;
18 + if (value !== undefined) {
19 + ret = Promise.resolve(value)
20 + ._then(afterValue, null, null, ms, undefined);
21 + if (debug.cancellation() && value instanceof Promise) {
22 + ret._setOnCancel(value);
23 + }
24 + } else {
25 + ret = new Promise(INTERNAL);
26 + handle = setTimeout(function() { ret._fulfill(); }, +ms);
27 + if (debug.cancellation()) {
28 + ret._setOnCancel(new HandleWrapper(handle));
29 + }
30 + ret._captureStackTrace();
31 + }
32 + ret._setAsyncGuaranteed();
33 + return ret;
34 +};
35 +
36 +Promise.prototype.delay = function (ms) {
37 + return delay(ms, this);
38 +};
39 +
40 +var afterTimeout = function (promise, message, parent) {
41 + var err;
42 + if (typeof message !== "string") {
43 + if (message instanceof Error) {
44 + err = message;
45 + } else {
46 + err = new TimeoutError("operation timed out");
47 + }
48 + } else {
49 + err = new TimeoutError(message);
50 + }
51 + util.markAsOriginatingFromRejection(err);
52 + promise._attachExtraTrace(err);
53 + promise._reject(err);
54 +
55 + if (parent != null) {
56 + parent.cancel();
57 + }
58 +};
59 +
60 +function successClear(value) {
61 + clearTimeout(this.handle);
62 + return value;
63 +}
64 +
65 +function failureClear(reason) {
66 + clearTimeout(this.handle);
67 + throw reason;
68 +}
69 +
70 +Promise.prototype.timeout = function (ms, message) {
71 + ms = +ms;
72 + var ret, parent;
73 +
74 + var handleWrapper = new HandleWrapper(setTimeout(function timeoutTimeout() {
75 + if (ret.isPending()) {
76 + afterTimeout(ret, message, parent);
77 + }
78 + }, ms));
79 +
80 + if (debug.cancellation()) {
81 + parent = this.then();
82 + ret = parent._then(successClear, failureClear,
83 + undefined, handleWrapper, undefined);
84 + ret._setOnCancel(handleWrapper);
85 + } else {
86 + ret = this._then(successClear, failureClear,
87 + undefined, handleWrapper, undefined);
88 + }
89 +
90 + return ret;
91 +};
92 +
93 +};
1 +"use strict";
2 +module.exports = function (Promise, apiRejection, tryConvertToPromise,
3 + createContext, INTERNAL, debug) {
4 + var util = require("./util");
5 + var TypeError = require("./errors").TypeError;
6 + var inherits = require("./util").inherits;
7 + var errorObj = util.errorObj;
8 + var tryCatch = util.tryCatch;
9 + var NULL = {};
10 +
11 + function thrower(e) {
12 + setTimeout(function(){throw e;}, 0);
13 + }
14 +
15 + function castPreservingDisposable(thenable) {
16 + var maybePromise = tryConvertToPromise(thenable);
17 + if (maybePromise !== thenable &&
18 + typeof thenable._isDisposable === "function" &&
19 + typeof thenable._getDisposer === "function" &&
20 + thenable._isDisposable()) {
21 + maybePromise._setDisposable(thenable._getDisposer());
22 + }
23 + return maybePromise;
24 + }
25 + function dispose(resources, inspection) {
26 + var i = 0;
27 + var len = resources.length;
28 + var ret = new Promise(INTERNAL);
29 + function iterator() {
30 + if (i >= len) return ret._fulfill();
31 + var maybePromise = castPreservingDisposable(resources[i++]);
32 + if (maybePromise instanceof Promise &&
33 + maybePromise._isDisposable()) {
34 + try {
35 + maybePromise = tryConvertToPromise(
36 + maybePromise._getDisposer().tryDispose(inspection),
37 + resources.promise);
38 + } catch (e) {
39 + return thrower(e);
40 + }
41 + if (maybePromise instanceof Promise) {
42 + return maybePromise._then(iterator, thrower,
43 + null, null, null);
44 + }
45 + }
46 + iterator();
47 + }
48 + iterator();
49 + return ret;
50 + }
51 +
52 + function Disposer(data, promise, context) {
53 + this._data = data;
54 + this._promise = promise;
55 + this._context = context;
56 + }
57 +
58 + Disposer.prototype.data = function () {
59 + return this._data;
60 + };
61 +
62 + Disposer.prototype.promise = function () {
63 + return this._promise;
64 + };
65 +
66 + Disposer.prototype.resource = function () {
67 + if (this.promise().isFulfilled()) {
68 + return this.promise().value();
69 + }
70 + return NULL;
71 + };
72 +
73 + Disposer.prototype.tryDispose = function(inspection) {
74 + var resource = this.resource();
75 + var context = this._context;
76 + if (context !== undefined) context._pushContext();
77 + var ret = resource !== NULL
78 + ? this.doDispose(resource, inspection) : null;
79 + if (context !== undefined) context._popContext();
80 + this._promise._unsetDisposable();
81 + this._data = null;
82 + return ret;
83 + };
84 +
85 + Disposer.isDisposer = function (d) {
86 + return (d != null &&
87 + typeof d.resource === "function" &&
88 + typeof d.tryDispose === "function");
89 + };
90 +
91 + function FunctionDisposer(fn, promise, context) {
92 + this.constructor$(fn, promise, context);
93 + }
94 + inherits(FunctionDisposer, Disposer);
95 +
96 + FunctionDisposer.prototype.doDispose = function (resource, inspection) {
97 + var fn = this.data();
98 + return fn.call(resource, resource, inspection);
99 + };
100 +
101 + function maybeUnwrapDisposer(value) {
102 + if (Disposer.isDisposer(value)) {
103 + this.resources[this.index]._setDisposable(value);
104 + return value.promise();
105 + }
106 + return value;
107 + }
108 +
109 + function ResourceList(length) {
110 + this.length = length;
111 + this.promise = null;
112 + this[length-1] = null;
113 + }
114 +
115 + ResourceList.prototype._resultCancelled = function() {
116 + var len = this.length;
117 + for (var i = 0; i < len; ++i) {
118 + var item = this[i];
119 + if (item instanceof Promise) {
120 + item.cancel();
121 + }
122 + }
123 + };
124 +
125 + Promise.using = function () {
126 + var len = arguments.length;
127 + if (len < 2) return apiRejection(
128 + "you must pass at least 2 arguments to Promise.using");
129 + var fn = arguments[len - 1];
130 + if (typeof fn !== "function") {
131 + return apiRejection("expecting a function but got " + util.classString(fn));
132 + }
133 + var input;
134 + var spreadArgs = true;
135 + if (len === 2 && Array.isArray(arguments[0])) {
136 + input = arguments[0];
137 + len = input.length;
138 + spreadArgs = false;
139 + } else {
140 + input = arguments;
141 + len--;
142 + }
143 + var resources = new ResourceList(len);
144 + for (var i = 0; i < len; ++i) {
145 + var resource = input[i];
146 + if (Disposer.isDisposer(resource)) {
147 + var disposer = resource;
148 + resource = resource.promise();
149 + resource._setDisposable(disposer);
150 + } else {
151 + var maybePromise = tryConvertToPromise(resource);
152 + if (maybePromise instanceof Promise) {
153 + resource =
154 + maybePromise._then(maybeUnwrapDisposer, null, null, {
155 + resources: resources,
156 + index: i
157 + }, undefined);
158 + }
159 + }
160 + resources[i] = resource;
161 + }
162 +
163 + var reflectedResources = new Array(resources.length);
164 + for (var i = 0; i < reflectedResources.length; ++i) {
165 + reflectedResources[i] = Promise.resolve(resources[i]).reflect();
166 + }
167 +
168 + var resultPromise = Promise.all(reflectedResources)
169 + .then(function(inspections) {
170 + for (var i = 0; i < inspections.length; ++i) {
171 + var inspection = inspections[i];
172 + if (inspection.isRejected()) {
173 + errorObj.e = inspection.error();
174 + return errorObj;
175 + } else if (!inspection.isFulfilled()) {
176 + resultPromise.cancel();
177 + return;
178 + }
179 + inspections[i] = inspection.value();
180 + }
181 + promise._pushContext();
182 +
183 + fn = tryCatch(fn);
184 + var ret = spreadArgs
185 + ? fn.apply(undefined, inspections) : fn(inspections);
186 + var promiseCreated = promise._popContext();
187 + debug.checkForgottenReturns(
188 + ret, promiseCreated, "Promise.using", promise);
189 + return ret;
190 + });
191 +
192 + var promise = resultPromise.lastly(function() {
193 + var inspection = new Promise.PromiseInspection(resultPromise);
194 + return dispose(resources, inspection);
195 + });
196 + resources.promise = promise;
197 + promise._setOnCancel(resources);
198 + return promise;
199 + };
200 +
201 + Promise.prototype._setDisposable = function (disposer) {
202 + this._bitField = this._bitField | 131072;
203 + this._disposer = disposer;
204 + };
205 +
206 + Promise.prototype._isDisposable = function () {
207 + return (this._bitField & 131072) > 0;
208 + };
209 +
210 + Promise.prototype._getDisposer = function () {
211 + return this._disposer;
212 + };
213 +
214 + Promise.prototype._unsetDisposable = function () {
215 + this._bitField = this._bitField & (~131072);
216 + this._disposer = undefined;
217 + };
218 +
219 + Promise.prototype.disposer = function (fn) {
220 + if (typeof fn === "function") {
221 + return new FunctionDisposer(fn, this, createContext());
222 + }
223 + throw new TypeError();
224 + };
225 +
226 +};
This diff is collapsed. Click to expand it.
1 +{
2 + "_from": "bluebird@^3.5.0",
3 + "_id": "bluebird@3.5.3",
4 + "_inBundle": false,
5 + "_integrity": "sha512-/qKPUQlaW1OyR51WeCPBvRnAlnZFUJkCSG5HzGnuIqhgyJtF+T94lFnn33eiazjRm2LAHVy2guNnaq48X9SJuw==",
6 + "_location": "/bluebird",
7 + "_phantomChildren": {},
8 + "_requested": {
9 + "type": "range",
10 + "registry": true,
11 + "raw": "bluebird@^3.5.0",
12 + "name": "bluebird",
13 + "escapedName": "bluebird",
14 + "rawSpec": "^3.5.0",
15 + "saveSpec": null,
16 + "fetchSpec": "^3.5.0"
17 + },
18 + "_requiredBy": [
19 + "/promise-mysql"
20 + ],
21 + "_resolved": "https://registry.npmjs.org/bluebird/-/bluebird-3.5.3.tgz",
22 + "_shasum": "7d01c6f9616c9a51ab0f8c549a79dfe6ec33efa7",
23 + "_spec": "bluebird@^3.5.0",
24 + "_where": "/Users/donghoon/Documents/Classroom/OpenSourceS:W/Project/node_modules/promise-mysql",
25 + "author": {
26 + "name": "Petka Antonov",
27 + "email": "petka_antonov@hotmail.com",
28 + "url": "http://github.com/petkaantonov/"
29 + },
30 + "browser": "./js/browser/bluebird.js",
31 + "bugs": {
32 + "url": "http://github.com/petkaantonov/bluebird/issues"
33 + },
34 + "bundleDependencies": false,
35 + "deprecated": false,
36 + "description": "Full featured Promises/A+ implementation with exceptionally good performance",
37 + "devDependencies": {
38 + "acorn": "^6.0.2",
39 + "acorn-walk": "^6.1.0",
40 + "baconjs": "^0.7.43",
41 + "bluebird": "^2.9.2",
42 + "body-parser": "^1.10.2",
43 + "browserify": "^8.1.1",
44 + "cli-table": "~0.3.1",
45 + "co": "^4.2.0",
46 + "cross-spawn": "^0.2.3",
47 + "glob": "^4.3.2",
48 + "grunt-saucelabs": "~8.4.1",
49 + "highland": "^2.3.0",
50 + "istanbul": "^0.3.5",
51 + "jshint": "^2.6.0",
52 + "jshint-stylish": "~0.2.0",
53 + "kefir": "^2.4.1",
54 + "mkdirp": "~0.5.0",
55 + "mocha": "~2.1",
56 + "open": "~0.0.5",
57 + "optimist": "~0.6.1",
58 + "rimraf": "~2.2.6",
59 + "rx": "^2.3.25",
60 + "serve-static": "^1.7.1",
61 + "sinon": "~1.7.3",
62 + "uglify-js": "~2.4.16"
63 + },
64 + "files": [
65 + "js/browser",
66 + "js/release",
67 + "LICENSE"
68 + ],
69 + "homepage": "https://github.com/petkaantonov/bluebird",
70 + "keywords": [
71 + "promise",
72 + "performance",
73 + "promises",
74 + "promises-a",
75 + "promises-aplus",
76 + "async",
77 + "await",
78 + "deferred",
79 + "deferreds",
80 + "future",
81 + "flow control",
82 + "dsl",
83 + "fluent interface"
84 + ],
85 + "license": "MIT",
86 + "main": "./js/release/bluebird.js",
87 + "name": "bluebird",
88 + "repository": {
89 + "type": "git",
90 + "url": "git://github.com/petkaantonov/bluebird.git"
91 + },
92 + "scripts": {
93 + "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",
94 + "generate-browser-full": "node tools/build.js --no-clean --no-debug --release --browser --minify",
95 + "istanbul": "istanbul",
96 + "lint": "node scripts/jshint.js",
97 + "prepublish": "npm run generate-browser-core && npm run generate-browser-full",
98 + "test": "node --expose-gc tools/test.js"
99 + },
100 + "version": "3.5.3",
101 + "webpack": "./js/release/bluebird.js"
102 +}
1 +Copyright Node.js contributors. All rights reserved.
2 +
3 +Permission is hereby granted, free of charge, to any person obtaining a copy
4 +of this software and associated documentation files (the "Software"), to
5 +deal in the Software without restriction, including without limitation the
6 +rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
7 +sell copies of the Software, and to permit persons to whom the Software is
8 +furnished to do so, subject to the following conditions:
9 +
10 +The above copyright notice and this permission notice shall be included in
11 +all copies or substantial portions of the Software.
12 +
13 +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14 +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15 +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16 +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17 +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
18 +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
19 +IN THE SOFTWARE.
1 +# core-util-is
2 +
3 +The `util.is*` functions introduced in Node v0.12.
This diff is collapsed. Click to expand it.
1 +// Copyright Joyent, Inc. and other Node contributors.
2 +//
3 +// Permission is hereby granted, free of charge, to any person obtaining a
4 +// copy of this software and associated documentation files (the
5 +// "Software"), to deal in the Software without restriction, including
6 +// without limitation the rights to use, copy, modify, merge, publish,
7 +// distribute, sublicense, and/or sell copies of the Software, and to permit
8 +// persons to whom the Software is furnished to do so, subject to the
9 +// following conditions:
10 +//
11 +// The above copyright notice and this permission notice shall be included
12 +// in all copies or substantial portions of the Software.
13 +//
14 +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
15 +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16 +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
17 +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
18 +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
19 +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
20 +// USE OR OTHER DEALINGS IN THE SOFTWARE.
21 +
22 +// NOTE: These type checking functions intentionally don't use `instanceof`
23 +// because it is fragile and can be easily faked with `Object.create()`.
24 +
25 +function isArray(arg) {
26 + if (Array.isArray) {
27 + return Array.isArray(arg);
28 + }
29 + return objectToString(arg) === '[object Array]';
30 +}
31 +exports.isArray = isArray;
32 +
33 +function isBoolean(arg) {
34 + return typeof arg === 'boolean';
35 +}
36 +exports.isBoolean = isBoolean;
37 +
38 +function isNull(arg) {
39 + return arg === null;
40 +}
41 +exports.isNull = isNull;
42 +
43 +function isNullOrUndefined(arg) {
44 + return arg == null;
45 +}
46 +exports.isNullOrUndefined = isNullOrUndefined;
47 +
48 +function isNumber(arg) {
49 + return typeof arg === 'number';
50 +}
51 +exports.isNumber = isNumber;
52 +
53 +function isString(arg) {
54 + return typeof arg === 'string';
55 +}
56 +exports.isString = isString;
57 +
58 +function isSymbol(arg) {
59 + return typeof arg === 'symbol';
60 +}
61 +exports.isSymbol = isSymbol;
62 +
63 +function isUndefined(arg) {
64 + return arg === void 0;
65 +}
66 +exports.isUndefined = isUndefined;
67 +
68 +function isRegExp(re) {
69 + return objectToString(re) === '[object RegExp]';
70 +}
71 +exports.isRegExp = isRegExp;
72 +
73 +function isObject(arg) {
74 + return typeof arg === 'object' && arg !== null;
75 +}
76 +exports.isObject = isObject;
77 +
78 +function isDate(d) {
79 + return objectToString(d) === '[object Date]';
80 +}
81 +exports.isDate = isDate;
82 +
83 +function isError(e) {
84 + return (objectToString(e) === '[object Error]' || e instanceof Error);
85 +}
86 +exports.isError = isError;
87 +
88 +function isFunction(arg) {
89 + return typeof arg === 'function';
90 +}
91 +exports.isFunction = isFunction;
92 +
93 +function isPrimitive(arg) {
94 + return arg === null ||
95 + typeof arg === 'boolean' ||
96 + typeof arg === 'number' ||
97 + typeof arg === 'string' ||
98 + typeof arg === 'symbol' || // ES6 symbol
99 + typeof arg === 'undefined';
100 +}
101 +exports.isPrimitive = isPrimitive;
102 +
103 +exports.isBuffer = Buffer.isBuffer;
104 +
105 +function objectToString(o) {
106 + return Object.prototype.toString.call(o);
107 +}
1 +{
2 + "_from": "core-util-is@~1.0.0",
3 + "_id": "core-util-is@1.0.2",
4 + "_inBundle": false,
5 + "_integrity": "sha1-tf1UIgqivFq1eqtxQMlAdUUDwac=",
6 + "_location": "/core-util-is",
7 + "_phantomChildren": {},
8 + "_requested": {
9 + "type": "range",
10 + "registry": true,
11 + "raw": "core-util-is@~1.0.0",
12 + "name": "core-util-is",
13 + "escapedName": "core-util-is",
14 + "rawSpec": "~1.0.0",
15 + "saveSpec": null,
16 + "fetchSpec": "~1.0.0"
17 + },
18 + "_requiredBy": [
19 + "/readable-stream"
20 + ],
21 + "_resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.2.tgz",
22 + "_shasum": "b5fd54220aa2bc5ab57aab7140c940754503c1a7",
23 + "_spec": "core-util-is@~1.0.0",
24 + "_where": "/Users/donghoon/Documents/Classroom/OpenSourceS:W/Project/node_modules/readable-stream",
25 + "author": {
26 + "name": "Isaac Z. Schlueter",
27 + "email": "i@izs.me",
28 + "url": "http://blog.izs.me/"
29 + },
30 + "bugs": {
31 + "url": "https://github.com/isaacs/core-util-is/issues"
32 + },
33 + "bundleDependencies": false,
34 + "deprecated": false,
35 + "description": "The `util.is*` functions introduced in Node v0.12.",
36 + "devDependencies": {
37 + "tap": "^2.3.0"
38 + },
39 + "homepage": "https://github.com/isaacs/core-util-is#readme",
40 + "keywords": [
41 + "util",
42 + "isBuffer",
43 + "isArray",
44 + "isNumber",
45 + "isString",
46 + "isRegExp",
47 + "isThis",
48 + "isThat",
49 + "polyfill"
50 + ],
51 + "license": "MIT",
52 + "main": "lib/util.js",
53 + "name": "core-util-is",
54 + "repository": {
55 + "type": "git",
56 + "url": "git://github.com/isaacs/core-util-is.git"
57 + },
58 + "scripts": {
59 + "test": "tap test.js"
60 + },
61 + "version": "1.0.2"
62 +}
1 +var assert = require('tap');
2 +
3 +var t = require('./lib/util');
4 +
5 +assert.equal(t.isArray([]), true);
6 +assert.equal(t.isArray({}), false);
7 +
8 +assert.equal(t.isBoolean(null), false);
9 +assert.equal(t.isBoolean(true), true);
10 +assert.equal(t.isBoolean(false), true);
11 +
12 +assert.equal(t.isNull(null), true);
13 +assert.equal(t.isNull(undefined), false);
14 +assert.equal(t.isNull(false), false);
15 +assert.equal(t.isNull(), false);
16 +
17 +assert.equal(t.isNullOrUndefined(null), true);
18 +assert.equal(t.isNullOrUndefined(undefined), true);
19 +assert.equal(t.isNullOrUndefined(false), false);
20 +assert.equal(t.isNullOrUndefined(), true);
21 +
22 +assert.equal(t.isNumber(null), false);
23 +assert.equal(t.isNumber('1'), false);
24 +assert.equal(t.isNumber(1), true);
25 +
26 +assert.equal(t.isString(null), false);
27 +assert.equal(t.isString('1'), true);
28 +assert.equal(t.isString(1), false);
29 +
30 +assert.equal(t.isSymbol(null), false);
31 +assert.equal(t.isSymbol('1'), false);
32 +assert.equal(t.isSymbol(1), false);
33 +assert.equal(t.isSymbol(Symbol()), true);
34 +
35 +assert.equal(t.isUndefined(null), false);
36 +assert.equal(t.isUndefined(undefined), true);
37 +assert.equal(t.isUndefined(false), false);
38 +assert.equal(t.isUndefined(), true);
39 +
40 +assert.equal(t.isRegExp(null), false);
41 +assert.equal(t.isRegExp('1'), false);
42 +assert.equal(t.isRegExp(new RegExp()), true);
43 +
44 +assert.equal(t.isObject({}), true);
45 +assert.equal(t.isObject([]), true);
46 +assert.equal(t.isObject(new RegExp()), true);
47 +assert.equal(t.isObject(new Date()), true);
48 +
49 +assert.equal(t.isDate(null), false);
50 +assert.equal(t.isDate('1'), false);
51 +assert.equal(t.isDate(new Date()), true);
52 +
53 +assert.equal(t.isError(null), false);
54 +assert.equal(t.isError({ err: true }), false);
55 +assert.equal(t.isError(new Error()), true);
56 +
57 +assert.equal(t.isFunction(null), false);
58 +assert.equal(t.isFunction({ }), false);
59 +assert.equal(t.isFunction(function() {}), true);
60 +
61 +assert.equal(t.isPrimitive(null), true);
62 +assert.equal(t.isPrimitive(''), true);
63 +assert.equal(t.isPrimitive(0), true);
64 +assert.equal(t.isPrimitive(new Date()), false);
65 +
66 +assert.equal(t.isBuffer(null), false);
67 +assert.equal(t.isBuffer({}), false);
68 +assert.equal(t.isBuffer(new Buffer(0)), true);
1 +language: node_js
2 +node_js:
3 + - "0.8"
4 + - "0.10"
1 +
2 +test:
3 + @node_modules/.bin/tape test.js
4 +
5 +.PHONY: test
6 +
1 +
2 +# isarray
3 +
4 +`Array#isArray` for older browsers.
5 +
6 +[![build status](https://secure.travis-ci.org/juliangruber/isarray.svg)](http://travis-ci.org/juliangruber/isarray)
7 +[![downloads](https://img.shields.io/npm/dm/isarray.svg)](https://www.npmjs.org/package/isarray)
8 +
9 +[![browser support](https://ci.testling.com/juliangruber/isarray.png)
10 +](https://ci.testling.com/juliangruber/isarray)
11 +
12 +## Usage
13 +
14 +```js
15 +var isArray = require('isarray');
16 +
17 +console.log(isArray([])); // => true
18 +console.log(isArray({})); // => false
19 +```
20 +
21 +## Installation
22 +
23 +With [npm](http://npmjs.org) do
24 +
25 +```bash
26 +$ npm install isarray
27 +```
28 +
29 +Then bundle for the browser with
30 +[browserify](https://github.com/substack/browserify).
31 +
32 +With [component](http://component.io) do
33 +
34 +```bash
35 +$ component install juliangruber/isarray
36 +```
37 +
38 +## License
39 +
40 +(MIT)
41 +
42 +Copyright (c) 2013 Julian Gruber &lt;julian@juliangruber.com&gt;
43 +
44 +Permission is hereby granted, free of charge, to any person obtaining a copy of
45 +this software and associated documentation files (the "Software"), to deal in
46 +the Software without restriction, including without limitation the rights to
47 +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
48 +of the Software, and to permit persons to whom the Software is furnished to do
49 +so, subject to the following conditions:
50 +
51 +The above copyright notice and this permission notice shall be included in all
52 +copies or substantial portions of the Software.
53 +
54 +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
55 +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
56 +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
57 +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
58 +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
59 +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
60 +SOFTWARE.
1 +{
2 + "name" : "isarray",
3 + "description" : "Array#isArray for older browsers",
4 + "version" : "0.0.1",
5 + "repository" : "juliangruber/isarray",
6 + "homepage": "https://github.com/juliangruber/isarray",
7 + "main" : "index.js",
8 + "scripts" : [
9 + "index.js"
10 + ],
11 + "dependencies" : {},
12 + "keywords": ["browser","isarray","array"],
13 + "author": {
14 + "name": "Julian Gruber",
15 + "email": "mail@juliangruber.com",
16 + "url": "http://juliangruber.com"
17 + },
18 + "license": "MIT"
19 +}
1 +var toString = {}.toString;
2 +
3 +module.exports = Array.isArray || function (arr) {
4 + return toString.call(arr) == '[object Array]';
5 +};
1 +{
2 + "_from": "isarray@~1.0.0",
3 + "_id": "isarray@1.0.0",
4 + "_inBundle": false,
5 + "_integrity": "sha1-u5NdSFgsuhaMBoNJV6VKPgcSTxE=",
6 + "_location": "/isarray",
7 + "_phantomChildren": {},
8 + "_requested": {
9 + "type": "range",
10 + "registry": true,
11 + "raw": "isarray@~1.0.0",
12 + "name": "isarray",
13 + "escapedName": "isarray",
14 + "rawSpec": "~1.0.0",
15 + "saveSpec": null,
16 + "fetchSpec": "~1.0.0"
17 + },
18 + "_requiredBy": [
19 + "/readable-stream"
20 + ],
21 + "_resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz",
22 + "_shasum": "bb935d48582cba168c06834957a54a3e07124f11",
23 + "_spec": "isarray@~1.0.0",
24 + "_where": "/Users/donghoon/Documents/Classroom/OpenSourceS:W/Project/node_modules/readable-stream",
25 + "author": {
26 + "name": "Julian Gruber",
27 + "email": "mail@juliangruber.com",
28 + "url": "http://juliangruber.com"
29 + },
30 + "bugs": {
31 + "url": "https://github.com/juliangruber/isarray/issues"
32 + },
33 + "bundleDependencies": false,
34 + "dependencies": {},
35 + "deprecated": false,
36 + "description": "Array#isArray for older browsers",
37 + "devDependencies": {
38 + "tape": "~2.13.4"
39 + },
40 + "homepage": "https://github.com/juliangruber/isarray",
41 + "keywords": [
42 + "browser",
43 + "isarray",
44 + "array"
45 + ],
46 + "license": "MIT",
47 + "main": "index.js",
48 + "name": "isarray",
49 + "repository": {
50 + "type": "git",
51 + "url": "git://github.com/juliangruber/isarray.git"
52 + },
53 + "scripts": {
54 + "test": "tape test.js"
55 + },
56 + "testling": {
57 + "files": "test.js",
58 + "browsers": [
59 + "ie/8..latest",
60 + "firefox/17..latest",
61 + "firefox/nightly",
62 + "chrome/22..latest",
63 + "chrome/canary",
64 + "opera/12..latest",
65 + "opera/next",
66 + "safari/5.1..latest",
67 + "ipad/6.0..latest",
68 + "iphone/6.0..latest",
69 + "android-browser/4.2..latest"
70 + ]
71 + },
72 + "version": "1.0.0"
73 +}
1 +var isArray = require('./');
2 +var test = require('tape');
3 +
4 +test('is array', function(t){
5 + t.ok(isArray([]));
6 + t.notOk(isArray({}));
7 + t.notOk(isArray(null));
8 + t.notOk(isArray(false));
9 +
10 + var obj = {};
11 + obj[0] = true;
12 + t.notOk(isArray(obj));
13 +
14 + var arr = [];
15 + arr.foo = 'bar';
16 + t.ok(isArray(arr));
17 +
18 + t.end();
19 +});
20 +
This diff is collapsed. Click to expand it.
1 +Copyright (c) 2012 Felix Geisendörfer (felix@debuggable.com) and contributors
2 +
3 + Permission is hereby granted, free of charge, to any person obtaining a copy
4 + of this software and associated documentation files (the "Software"), to deal
5 + in the Software without restriction, including without limitation the rights
6 + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7 + copies of the Software, and to permit persons to whom the Software is
8 + furnished to do so, subject to the following conditions:
9 +
10 + The above copyright notice and this permission notice shall be included in
11 + all copies or substantial portions of the Software.
12 +
13 + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14 + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15 + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16 + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17 + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18 + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
19 + THE SOFTWARE.
This diff is collapsed. Click to expand it.
1 +var Classes = Object.create(null);
2 +
3 +/**
4 + * Create a new Connection instance.
5 + * @param {object|string} config Configuration or connection string for new MySQL connection
6 + * @return {Connection} A new MySQL connection
7 + * @public
8 + */
9 +exports.createConnection = function createConnection(config) {
10 + var Connection = loadClass('Connection');
11 + var ConnectionConfig = loadClass('ConnectionConfig');
12 +
13 + return new Connection({config: new ConnectionConfig(config)});
14 +};
15 +
16 +/**
17 + * Create a new Pool instance.
18 + * @param {object|string} config Configuration or connection string for new MySQL connections
19 + * @return {Pool} A new MySQL pool
20 + * @public
21 + */
22 +exports.createPool = function createPool(config) {
23 + var Pool = loadClass('Pool');
24 + var PoolConfig = loadClass('PoolConfig');
25 +
26 + return new Pool({config: new PoolConfig(config)});
27 +};
28 +
29 +/**
30 + * Create a new PoolCluster instance.
31 + * @param {object} [config] Configuration for pool cluster
32 + * @return {PoolCluster} New MySQL pool cluster
33 + * @public
34 + */
35 +exports.createPoolCluster = function createPoolCluster(config) {
36 + var PoolCluster = loadClass('PoolCluster');
37 +
38 + return new PoolCluster(config);
39 +};
40 +
41 +/**
42 + * Create a new Query instance.
43 + * @param {string} sql The SQL for the query
44 + * @param {array} [values] Any values to insert into placeholders in sql
45 + * @param {function} [callback] The callback to use when query is complete
46 + * @return {Query} New query object
47 + * @public
48 + */
49 +exports.createQuery = function createQuery(sql, values, callback) {
50 + var Connection = loadClass('Connection');
51 +
52 + return Connection.createQuery(sql, values, callback);
53 +};
54 +
55 +/**
56 + * Escape a value for SQL.
57 + * @param {*} value The value to escape
58 + * @param {boolean} [stringifyObjects=false] Setting if objects should be stringified
59 + * @param {string} [timeZone=local] Setting for time zone to use for Date conversion
60 + * @return {string} Escaped string value
61 + * @public
62 + */
63 +exports.escape = function escape(value, stringifyObjects, timeZone) {
64 + var SqlString = loadClass('SqlString');
65 +
66 + return SqlString.escape(value, stringifyObjects, timeZone);
67 +};
68 +
69 +/**
70 + * Escape an identifier for SQL.
71 + * @param {*} value The value to escape
72 + * @param {boolean} [forbidQualified=false] Setting to treat '.' as part of identifier
73 + * @return {string} Escaped string value
74 + * @public
75 + */
76 +exports.escapeId = function escapeId(value, forbidQualified) {
77 + var SqlString = loadClass('SqlString');
78 +
79 + return SqlString.escapeId(value, forbidQualified);
80 +};
81 +
82 +/**
83 + * Format SQL and replacement values into a SQL string.
84 + * @param {string} sql The SQL for the query
85 + * @param {array} [values] Any values to insert into placeholders in sql
86 + * @param {boolean} [stringifyObjects=false] Setting if objects should be stringified
87 + * @param {string} [timeZone=local] Setting for time zone to use for Date conversion
88 + * @return {string} Formatted SQL string
89 + * @public
90 + */
91 +exports.format = function format(sql, values, stringifyObjects, timeZone) {
92 + var SqlString = loadClass('SqlString');
93 +
94 + return SqlString.format(sql, values, stringifyObjects, timeZone);
95 +};
96 +
97 +/**
98 + * Wrap raw SQL strings from escape overriding.
99 + * @param {string} sql The raw SQL
100 + * @return {object} Wrapped object
101 + * @public
102 + */
103 +exports.raw = function raw(sql) {
104 + var SqlString = loadClass('SqlString');
105 +
106 + return SqlString.raw(sql);
107 +};
108 +
109 +/**
110 + * The type constants.
111 + * @public
112 + */
113 +Object.defineProperty(exports, 'Types', {
114 + get: loadClass.bind(null, 'Types')
115 +});
116 +
117 +/**
118 + * Load the given class.
119 + * @param {string} className Name of class to default
120 + * @return {function|object} Class constructor or exports
121 + * @private
122 + */
123 +function loadClass(className) {
124 + var Class = Classes[className];
125 +
126 + if (Class !== undefined) {
127 + return Class;
128 + }
129 +
130 + // This uses a switch for static require analysis
131 + switch (className) {
132 + case 'Connection':
133 + Class = require('./lib/Connection');
134 + break;
135 + case 'ConnectionConfig':
136 + Class = require('./lib/ConnectionConfig');
137 + break;
138 + case 'Pool':
139 + Class = require('./lib/Pool');
140 + break;
141 + case 'PoolCluster':
142 + Class = require('./lib/PoolCluster');
143 + break;
144 + case 'PoolConfig':
145 + Class = require('./lib/PoolConfig');
146 + break;
147 + case 'SqlString':
148 + Class = require('./lib/protocol/SqlString');
149 + break;
150 + case 'Types':
151 + Class = require('./lib/protocol/constants/types');
152 + break;
153 + default:
154 + throw new Error('Cannot find class \'' + className + '\'');
155 + }
156 +
157 + // Store to prevent invoking require()
158 + Classes[className] = Class;
159 +
160 + return Class;
161 +}
This diff is collapsed. Click to expand it.
1 +var urlParse = require('url').parse;
2 +var ClientConstants = require('./protocol/constants/client');
3 +var Charsets = require('./protocol/constants/charsets');
4 +var SSLProfiles = null;
5 +
6 +module.exports = ConnectionConfig;
7 +function ConnectionConfig(options) {
8 + if (typeof options === 'string') {
9 + options = ConnectionConfig.parseUrl(options);
10 + }
11 +
12 + this.host = options.host || 'localhost';
13 + this.port = options.port || 3306;
14 + this.localAddress = options.localAddress;
15 + this.socketPath = options.socketPath;
16 + this.user = options.user || undefined;
17 + this.password = options.password || undefined;
18 + this.database = options.database;
19 + this.connectTimeout = (options.connectTimeout === undefined)
20 + ? (10 * 1000)
21 + : options.connectTimeout;
22 + this.insecureAuth = options.insecureAuth || false;
23 + this.supportBigNumbers = options.supportBigNumbers || false;
24 + this.bigNumberStrings = options.bigNumberStrings || false;
25 + this.dateStrings = options.dateStrings || false;
26 + this.debug = options.debug;
27 + this.trace = options.trace !== false;
28 + this.stringifyObjects = options.stringifyObjects || false;
29 + this.timezone = options.timezone || 'local';
30 + this.flags = options.flags || '';
31 + this.queryFormat = options.queryFormat;
32 + this.pool = options.pool || undefined;
33 + this.ssl = (typeof options.ssl === 'string')
34 + ? ConnectionConfig.getSSLProfile(options.ssl)
35 + : (options.ssl || false);
36 + this.multipleStatements = options.multipleStatements || false;
37 + this.typeCast = (options.typeCast === undefined)
38 + ? true
39 + : options.typeCast;
40 +
41 + if (this.timezone[0] === ' ') {
42 + // "+" is a url encoded char for space so it
43 + // gets translated to space when giving a
44 + // connection string..
45 + this.timezone = '+' + this.timezone.substr(1);
46 + }
47 +
48 + if (this.ssl) {
49 + // Default rejectUnauthorized to true
50 + this.ssl.rejectUnauthorized = this.ssl.rejectUnauthorized !== false;
51 + }
52 +
53 + this.maxPacketSize = 0;
54 + this.charsetNumber = (options.charset)
55 + ? ConnectionConfig.getCharsetNumber(options.charset)
56 + : options.charsetNumber || Charsets.UTF8_GENERAL_CI;
57 +
58 + // Set the client flags
59 + var defaultFlags = ConnectionConfig.getDefaultFlags(options);
60 + this.clientFlags = ConnectionConfig.mergeFlags(defaultFlags, options.flags);
61 +}
62 +
63 +ConnectionConfig.mergeFlags = function mergeFlags(defaultFlags, userFlags) {
64 + var allFlags = ConnectionConfig.parseFlagList(defaultFlags);
65 + var newFlags = ConnectionConfig.parseFlagList(userFlags);
66 +
67 + // Merge the new flags
68 + for (var flag in newFlags) {
69 + if (allFlags[flag] !== false) {
70 + allFlags[flag] = newFlags[flag];
71 + }
72 + }
73 +
74 + // Build flags
75 + var flags = 0x0;
76 + for (var flag in allFlags) {
77 + if (allFlags[flag]) {
78 + // TODO: Throw here on some future release
79 + flags |= ClientConstants['CLIENT_' + flag] || 0x0;
80 + }
81 + }
82 +
83 + return flags;
84 +};
85 +
86 +ConnectionConfig.getCharsetNumber = function getCharsetNumber(charset) {
87 + var num = Charsets[charset.toUpperCase()];
88 +
89 + if (num === undefined) {
90 + throw new TypeError('Unknown charset \'' + charset + '\'');
91 + }
92 +
93 + return num;
94 +};
95 +
96 +ConnectionConfig.getDefaultFlags = function getDefaultFlags(options) {
97 + var defaultFlags = [
98 + '-COMPRESS', // Compression protocol *NOT* supported
99 + '-CONNECT_ATTRS', // Does *NOT* send connection attributes in Protocol::HandshakeResponse41
100 + '+CONNECT_WITH_DB', // One can specify db on connect in Handshake Response Packet
101 + '+FOUND_ROWS', // Send found rows instead of affected rows
102 + '+IGNORE_SIGPIPE', // Don't issue SIGPIPE if network failures
103 + '+IGNORE_SPACE', // Let the parser ignore spaces before '('
104 + '+LOCAL_FILES', // Can use LOAD DATA LOCAL
105 + '+LONG_FLAG', // Longer flags in Protocol::ColumnDefinition320
106 + '+LONG_PASSWORD', // Use the improved version of Old Password Authentication
107 + '+MULTI_RESULTS', // Can handle multiple resultsets for COM_QUERY
108 + '+ODBC', // Special handling of ODBC behaviour
109 + '-PLUGIN_AUTH', // Does *NOT* support auth plugins
110 + '+PROTOCOL_41', // Uses the 4.1 protocol
111 + '+PS_MULTI_RESULTS', // Can handle multiple resultsets for COM_STMT_EXECUTE
112 + '+RESERVED', // Unused
113 + '+SECURE_CONNECTION', // Supports Authentication::Native41
114 + '+TRANSACTIONS' // Expects status flags
115 + ];
116 +
117 + if (options && options.multipleStatements) {
118 + // May send multiple statements per COM_QUERY and COM_STMT_PREPARE
119 + defaultFlags.push('+MULTI_STATEMENTS');
120 + }
121 +
122 + return defaultFlags;
123 +};
124 +
125 +ConnectionConfig.getSSLProfile = function getSSLProfile(name) {
126 + if (!SSLProfiles) {
127 + SSLProfiles = require('./protocol/constants/ssl_profiles');
128 + }
129 +
130 + var ssl = SSLProfiles[name];
131 +
132 + if (ssl === undefined) {
133 + throw new TypeError('Unknown SSL profile \'' + name + '\'');
134 + }
135 +
136 + return ssl;
137 +};
138 +
139 +ConnectionConfig.parseFlagList = function parseFlagList(flagList) {
140 + var allFlags = Object.create(null);
141 +
142 + if (!flagList) {
143 + return allFlags;
144 + }
145 +
146 + var flags = !Array.isArray(flagList)
147 + ? String(flagList || '').toUpperCase().split(/\s*,+\s*/)
148 + : flagList;
149 +
150 + for (var i = 0; i < flags.length; i++) {
151 + var flag = flags[i];
152 + var offset = 1;
153 + var state = flag[0];
154 +
155 + if (state === undefined) {
156 + // TODO: throw here on some future release
157 + continue;
158 + }
159 +
160 + if (state !== '-' && state !== '+') {
161 + offset = 0;
162 + state = '+';
163 + }
164 +
165 + allFlags[flag.substr(offset)] = state === '+';
166 + }
167 +
168 + return allFlags;
169 +};
170 +
171 +ConnectionConfig.parseUrl = function(url) {
172 + url = urlParse(url, true);
173 +
174 + var options = {
175 + host : url.hostname,
176 + port : url.port,
177 + database : url.pathname.substr(1)
178 + };
179 +
180 + if (url.auth) {
181 + var auth = url.auth.split(':');
182 + options.user = auth.shift();
183 + options.password = auth.join(':');
184 + }
185 +
186 + if (url.query) {
187 + for (var key in url.query) {
188 + var value = url.query[key];
189 +
190 + try {
191 + // Try to parse this as a JSON expression first
192 + options[key] = JSON.parse(value);
193 + } catch (err) {
194 + // Otherwise assume it is a plain string
195 + options[key] = value;
196 + }
197 + }
198 + }
199 +
200 + return options;
201 +};
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff could not be displayed because it is too large.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.