Guest User

Untitled

a guest
Jan 12th, 2017
295
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 328.34 KB | None | 0 0
  1. (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
  2. window['Promise'] = require('bluebird');
  3. window['APIGatewayClient'] = require('aws-api-gateway-client');
  4.  
  5. },{"aws-api-gateway-client":2,"bluebird":38}],2:[function(require,module,exports){
  6. /*
  7. * Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
  8. *
  9. * Licensed under the Apache License, Version 2.0 (the "License").
  10. * You may not use this file except in compliance with the License.
  11. * A copy of the License is located at
  12. *
  13. * http://aws.amazon.com/apache2.0
  14. *
  15. * or in the "license" file accompanying this file. This file is distributed
  16. * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
  17. * express or implied. See the License for the specific language governing
  18. * permissions and limitations under the License.
  19. */
  20.  
  21. var apigClientFactory = {};
  22. var apiGateway = require('./lib/apiGatewayCore/apiGatewayClient.js');
  23. var uritemplate = require('url-template');
  24.  
  25. apigClientFactory.newClient = function (config) {
  26. var apigClient = { };
  27. if(config === undefined) {
  28. config = {
  29. accessKey: '',
  30. secretKey: '',
  31. sessionToken: '',
  32. region: '',
  33. apiKey: undefined,
  34. invokeUrl: '',
  35. defaultContentType: 'application/json',
  36. defaultAcceptType: 'application/json'
  37. };
  38. }
  39. if(config.accessKey === undefined) {
  40. config.accessKey = '';
  41. }
  42. if(config.secretKey === undefined) {
  43. config.secretKey = '';
  44. }
  45. if(config.apiKey === undefined) {
  46. config.apiKey = '';
  47. }
  48. if(config.sessionToken === undefined) {
  49. config.sessionToken = '';
  50. }
  51. if(config.region === undefined) {
  52. config.region = 'us-east-1';
  53. }
  54. //If defaultContentType is not defined then default to application/json
  55. if(config.defaultContentType === undefined) {
  56. config.defaultContentType = 'application/json';
  57. }
  58. //If defaultAcceptType is not defined then default to application/json
  59. if(config.defaultAcceptType === undefined) {
  60. config.defaultAcceptType = 'application/json';
  61. }
  62.  
  63. // extract endpoint and path from url
  64. var invokeUrl = config.invokeUrl;
  65. var endpoint = /(^https?:\/\/[^\/]+)/g.exec(invokeUrl)[1];
  66. var pathComponent = invokeUrl.substring(endpoint.length);
  67.  
  68. var sigV4ClientConfig = {
  69. accessKey: config.accessKey,
  70. secretKey: config.secretKey,
  71. sessionToken: config.sessionToken,
  72. serviceName: 'execute-api',
  73. region: config.region,
  74. endpoint: endpoint,
  75. defaultContentType: config.defaultContentType,
  76. defaultAcceptType: config.defaultAcceptType
  77. };
  78.  
  79. var authType = 'NONE';
  80. if (sigV4ClientConfig.accessKey !== undefined && sigV4ClientConfig.accessKey !== '' && sigV4ClientConfig.secretKey !== undefined && sigV4ClientConfig.secretKey !== '') {
  81. authType = 'AWS_IAM';
  82. }
  83.  
  84. var simpleHttpClientConfig = {
  85. endpoint: endpoint,
  86. defaultContentType: config.defaultContentType,
  87. defaultAcceptType: config.defaultAcceptType
  88. };
  89.  
  90. var apiGatewayClient = apiGateway.core.apiGatewayClientFactory.newClient(simpleHttpClientConfig, sigV4ClientConfig);
  91.  
  92.  
  93.  
  94. apigClient.invokeApi = function (params, pathTemplate, method, additionalParams, body) {
  95. if (additionalParams===undefined) additionalParams={};
  96. if (body===undefined) body='';
  97.  
  98. var request = {
  99. verb: method.toUpperCase(),
  100. path: pathComponent + uritemplate.parse(pathTemplate).expand(params),
  101. headers: additionalParams.headers,
  102. queryParams: additionalParams.queryParams,
  103. body: body
  104. };
  105.  
  106. return apiGatewayClient.makeRequest(request, authType, additionalParams, config.apiKey);
  107. };
  108.  
  109.  
  110. return apigClient;
  111. };
  112.  
  113. module.exports = apigClientFactory;
  114.  
  115. },{"./lib/apiGatewayCore/apiGatewayClient.js":3,"url-template":37}],3:[function(require,module,exports){
  116. /*
  117. * Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
  118. *
  119. * Licensed under the Apache License, Version 2.0 (the "License").
  120. * You may not use this file except in compliance with the License.
  121. * A copy of the License is located at
  122. *
  123. * http://aws.amazon.com/apache2.0
  124. *
  125. * or in the "license" file accompanying this file. This file is distributed
  126. * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
  127. * express or implied. See the License for the specific language governing
  128. * permissions and limitations under the License.
  129. */
  130.  
  131. var apiGateway = apiGateway || {};
  132. apiGateway.core = apiGateway.core || {};
  133. apiGateway.core.utils = require('./utils');
  134. apiGateway.core.sigV4ClientFactory = require('./sigV4Client');
  135. apiGateway.core.simpleHttpClientFactory = require('./simpleHttpClient');
  136.  
  137. apiGateway.core.apiGatewayClientFactory = {};
  138. apiGateway.core.apiGatewayClientFactory.newClient = function (simpleHttpClientConfig, sigV4ClientConfig) {
  139. var apiGatewayClient = { };
  140. //Spin up 2 httpClients, one for simple requests, one for SigV4
  141. var sigV4Client = apiGateway.core.sigV4ClientFactory.newClient(sigV4ClientConfig);
  142. var simpleHttpClient = apiGateway.core.simpleHttpClientFactory.newClient(simpleHttpClientConfig);
  143.  
  144. apiGatewayClient.makeRequest = function (request, authType, additionalParams, apiKey) {
  145. //Default the request to use the simple http client
  146. var clientToUse = simpleHttpClient;
  147.  
  148. //Attach the apiKey to the headers request if one was provided
  149. if (apiKey !== undefined && apiKey !== '' && apiKey !== null) {
  150. request.headers['x-api-key'] = apiKey;
  151. }
  152.  
  153. if (request.body === undefined || request.body === '' || request.body === null || Object.keys(request.body).length === 0) {
  154. request.body = undefined;
  155. }
  156.  
  157. // If the user specified any additional headers or query params that may not have been modeled
  158. // merge them into the appropriate request properties
  159. request.headers = apiGateway.core.utils.mergeInto(request.headers, additionalParams.headers);
  160. request.queryParams = apiGateway.core.utils.mergeInto(request.queryParams, additionalParams.queryParams);
  161.  
  162. //If an auth type was specified inject the appropriate auth client
  163. if (authType === 'AWS_IAM') {
  164. clientToUse = sigV4Client;
  165. }
  166.  
  167. //Call the selected http client to make the request, returning a promise once the request is sent
  168. return clientToUse.makeRequest(request);
  169. };
  170. return apiGatewayClient;
  171. };
  172.  
  173. module.exports = apiGateway;
  174.  
  175. },{"./sigV4Client":4,"./simpleHttpClient":5,"./utils":6}],4:[function(require,module,exports){
  176. /*
  177. * Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
  178. *
  179. * Licensed under the Apache License, Version 2.0 (the "License").
  180. * You may not use this file except in compliance with the License.
  181. * A copy of the License is located at
  182. *
  183. * http://aws.amazon.com/apache2.0
  184. *
  185. * or in the "license" file accompanying this file. This file is distributed
  186. * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
  187. * express or implied. See the License for the specific language governing
  188. * permissions and limitations under the License.
  189. */
  190.  
  191. var apiGateway = apiGateway || {};
  192. apiGateway.core = apiGateway.core || {};
  193. apiGateway.core.utils = require('./utils');
  194. var axios = require('axios');
  195. var SHA256 = require('crypto-js/sha256');
  196. var encHex = require('crypto-js/enc-hex');
  197. var HmacSHA256 = require('crypto-js/hmac-sha256');
  198. var urlParser = require('url');
  199.  
  200. apiGateway.core.sigV4ClientFactory = {};
  201. apiGateway.core.sigV4ClientFactory.newClient = function (config) {
  202. var AWS_SHA_256 = 'AWS4-HMAC-SHA256';
  203. var AWS4_REQUEST = 'aws4_request';
  204. var AWS4 = 'AWS4';
  205. var X_AMZ_DATE = 'x-amz-date';
  206. var X_AMZ_SECURITY_TOKEN = 'x-amz-security-token';
  207. var HOST = 'host';
  208. var AUTHORIZATION = 'Authorization';
  209.  
  210. function hash(value) {
  211. return SHA256(value);
  212. }
  213.  
  214. function hexEncode(value) {
  215. return value.toString(encHex);
  216. }
  217.  
  218. function hmac(secret, value) {
  219. return HmacSHA256(value, secret, {asBytes: true});
  220. }
  221.  
  222. function buildCanonicalRequest(method, path, queryParams, headers, payload) {
  223. return method + '\n' +
  224. buildCanonicalUri(path) + '\n' +
  225. buildCanonicalQueryString(queryParams) + '\n' +
  226. buildCanonicalHeaders(headers) + '\n' +
  227. buildCanonicalSignedHeaders(headers) + '\n' +
  228. hexEncode(hash(payload));
  229. }
  230.  
  231. function hashCanonicalRequest(request) {
  232. return hexEncode(hash(request));
  233. }
  234.  
  235. function buildCanonicalUri(uri) {
  236. return encodeURI(uri);
  237. }
  238.  
  239. function buildCanonicalQueryString(queryParams) {
  240. if (Object.keys(queryParams).length < 1) {
  241. return '';
  242. }
  243.  
  244. var sortedQueryParams = [];
  245. for (var property in queryParams) {
  246. if (queryParams.hasOwnProperty(property)) {
  247. sortedQueryParams.push(property);
  248. }
  249. }
  250. sortedQueryParams.sort();
  251.  
  252. var canonicalQueryString = '';
  253. for (var i = 0; i < sortedQueryParams.length; i++) {
  254. canonicalQueryString += sortedQueryParams[i] + '=' + encodeURIComponent(queryParams[sortedQueryParams[i]]) + '&';
  255. }
  256. return canonicalQueryString.substr(0, canonicalQueryString.length - 1);
  257. }
  258.  
  259. function buildCanonicalHeaders(headers) {
  260. var canonicalHeaders = '';
  261. var sortedKeys = [];
  262. for (var property in headers) {
  263. if (headers.hasOwnProperty(property)) {
  264. sortedKeys.push(property);
  265. }
  266. }
  267. sortedKeys.sort();
  268.  
  269. for (var i = 0; i < sortedKeys.length; i++) {
  270. canonicalHeaders += sortedKeys[i].toLowerCase() + ':' + headers[sortedKeys[i]] + '\n';
  271. }
  272. return canonicalHeaders;
  273. }
  274.  
  275. function buildCanonicalSignedHeaders(headers) {
  276. var sortedKeys = [];
  277. for (var property in headers) {
  278. if (headers.hasOwnProperty(property)) {
  279. sortedKeys.push(property.toLowerCase());
  280. }
  281. }
  282. sortedKeys.sort();
  283.  
  284. return sortedKeys.join(';');
  285. }
  286.  
  287. function buildStringToSign(datetime, credentialScope, hashedCanonicalRequest) {
  288. return AWS_SHA_256 + '\n' +
  289. datetime + '\n' +
  290. credentialScope + '\n' +
  291. hashedCanonicalRequest;
  292. }
  293.  
  294. function buildCredentialScope(datetime, region, service) {
  295. return datetime.substr(0, 8) + '/' + region + '/' + service + '/' + AWS4_REQUEST
  296. }
  297.  
  298. function calculateSigningKey(secretKey, datetime, region, service) {
  299. return hmac(hmac(hmac(hmac(AWS4 + secretKey, datetime.substr(0, 8)), region), service), AWS4_REQUEST);
  300. }
  301.  
  302. function calculateSignature(key, stringToSign) {
  303. return hexEncode(hmac(key, stringToSign));
  304. }
  305.  
  306. function buildAuthorizationHeader(accessKey, credentialScope, headers, signature) {
  307. return AWS_SHA_256 + ' Credential=' + accessKey + '/' + credentialScope + ', SignedHeaders=' + buildCanonicalSignedHeaders(headers) + ', Signature=' + signature;
  308. }
  309.  
  310. var awsSigV4Client = { };
  311. if(config.accessKey === undefined || config.secretKey === undefined) {
  312. return awsSigV4Client;
  313. }
  314. awsSigV4Client.accessKey = apiGateway.core.utils.assertDefined(config.accessKey, 'accessKey');
  315. awsSigV4Client.secretKey = apiGateway.core.utils.assertDefined(config.secretKey, 'secretKey');
  316. awsSigV4Client.sessionToken = config.sessionToken;
  317. awsSigV4Client.serviceName = apiGateway.core.utils.assertDefined(config.serviceName, 'serviceName');
  318. awsSigV4Client.region = apiGateway.core.utils.assertDefined(config.region, 'region');
  319. awsSigV4Client.endpoint = apiGateway.core.utils.assertDefined(config.endpoint, 'endpoint');
  320.  
  321. awsSigV4Client.makeRequest = function (request) {
  322. var verb = apiGateway.core.utils.assertDefined(request.verb, 'verb');
  323. var path = apiGateway.core.utils.assertDefined(request.path, 'path');
  324. var queryParams = apiGateway.core.utils.copy(request.queryParams);
  325. if (queryParams === undefined) {
  326. queryParams = {};
  327. }
  328. var headers = apiGateway.core.utils.copy(request.headers);
  329. if (headers === undefined) {
  330. headers = {};
  331. }
  332.  
  333. //If the user has not specified an override for Content type the use default
  334. if(headers['Content-Type'] === undefined) {
  335. headers['Content-Type'] = config.defaultContentType;
  336. }
  337.  
  338. //If the user has not specified an override for Accept type the use default
  339. if(headers['Accept'] === undefined) {
  340. headers['Accept'] = config.defaultAcceptType;
  341. }
  342.  
  343. var body = apiGateway.core.utils.copy(request.body);
  344. if (body === undefined || verb === 'GET') { // override request body and set to empty when signing GET requests
  345. body = '';
  346. } else {
  347. body = JSON.stringify(body);
  348. }
  349.  
  350. //If there is no body remove the content-type header so it is not included in SigV4 calculation
  351. if(body === '' || body === undefined || body === null) {
  352. delete headers['Content-Type'];
  353. }
  354.  
  355. var datetime = new Date().toISOString().replace(/\.\d{3}Z$/, 'Z').replace(/[:\-]|\.\d{3}/g, '');
  356. headers[X_AMZ_DATE] = datetime;
  357. var parser = urlParser.parse(awsSigV4Client.endpoint);
  358. headers[HOST] = parser.hostname;
  359.  
  360. var canonicalRequest = buildCanonicalRequest(verb, path, queryParams, headers, body);
  361. var hashedCanonicalRequest = hashCanonicalRequest(canonicalRequest);
  362. var credentialScope = buildCredentialScope(datetime, awsSigV4Client.region, awsSigV4Client.serviceName);
  363. var stringToSign = buildStringToSign(datetime, credentialScope, hashedCanonicalRequest);
  364. var signingKey = calculateSigningKey(awsSigV4Client.secretKey, datetime, awsSigV4Client.region, awsSigV4Client.serviceName);
  365. var signature = calculateSignature(signingKey, stringToSign);
  366. headers[AUTHORIZATION] = buildAuthorizationHeader(awsSigV4Client.accessKey, credentialScope, headers, signature);
  367. if(awsSigV4Client.sessionToken !== undefined && awsSigV4Client.sessionToken !== '') {
  368. headers[X_AMZ_SECURITY_TOKEN] = awsSigV4Client.sessionToken;
  369. }
  370. delete headers[HOST];
  371.  
  372. var url = config.endpoint + path;
  373. var queryString = buildCanonicalQueryString(queryParams);
  374. if (queryString != '') {
  375. url += '?' + queryString;
  376. }
  377.  
  378. //Need to re-attach Content-Type if it is not specified at this point
  379. if(headers['Content-Type'] === undefined) {
  380. headers['Content-Type'] = config.defaultContentType;
  381. }
  382.  
  383. var signedRequest = {
  384. method: verb,
  385. url: url,
  386. headers: headers,
  387. data: body
  388. };
  389. return axios(signedRequest);
  390. };
  391.  
  392. return awsSigV4Client;
  393. };
  394.  
  395. module.exports = apiGateway.core.sigV4ClientFactory;
  396.  
  397. },{"./utils":6,"axios":7,"crypto-js/enc-hex":33,"crypto-js/hmac-sha256":34,"crypto-js/sha256":36,"url":44}],5:[function(require,module,exports){
  398. /*
  399. * Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
  400. *
  401. * Licensed under the Apache License, Version 2.0 (the "License").
  402. * You may not use this file except in compliance with the License.
  403. * A copy of the License is located at
  404. *
  405. * http://aws.amazon.com/apache2.0
  406. *
  407. * or in the "license" file accompanying this file. This file is distributed
  408. * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
  409. * express or implied. See the License for the specific language governing
  410. * permissions and limitations under the License.
  411. */
  412.  
  413. var apiGateway = apiGateway || {};
  414. apiGateway.core = apiGateway.core || {};
  415. apiGateway.core.utils = require('./utils');
  416. var axios = require('axios');
  417.  
  418. apiGateway.core.simpleHttpClientFactory = {};
  419. apiGateway.core.simpleHttpClientFactory.newClient = function (config) {
  420. function buildCanonicalQueryString(queryParams) {
  421. //Build a properly encoded query string from a QueryParam object
  422. if (Object.keys(queryParams).length < 1) {
  423. return '';
  424. }
  425.  
  426. var canonicalQueryString = '';
  427. for (var property in queryParams) {
  428. if (queryParams.hasOwnProperty(property)) {
  429. canonicalQueryString += encodeURIComponent(property) + '=' + encodeURIComponent(queryParams[property]) + '&';
  430. }
  431. }
  432.  
  433. return canonicalQueryString.substr(0, canonicalQueryString.length - 1);
  434. }
  435.  
  436. var simpleHttpClient = { };
  437. simpleHttpClient.endpoint = apiGateway.core.utils.assertDefined(config.endpoint, 'endpoint');
  438.  
  439. simpleHttpClient.makeRequest = function (request) {
  440. var verb = apiGateway.core.utils.assertDefined(request.verb, 'verb');
  441. var path = apiGateway.core.utils.assertDefined(request.path, 'path');
  442. var queryParams = apiGateway.core.utils.copy(request.queryParams);
  443. if (queryParams === undefined) {
  444. queryParams = {};
  445. }
  446. var headers = apiGateway.core.utils.copy(request.headers);
  447. if (headers === undefined) {
  448. headers = {};
  449. }
  450.  
  451. //If the user has not specified an override for Content type the use default
  452. if(headers['Content-Type'] === undefined) {
  453. headers['Content-Type'] = config.defaultContentType;
  454. }
  455.  
  456. //If the user has not specified an override for Accept type the use default
  457. if(headers['Accept'] === undefined) {
  458. headers['Accept'] = config.defaultAcceptType;
  459. }
  460.  
  461. var body = apiGateway.core.utils.copy(request.body);
  462. if (body === undefined) {
  463. body = '';
  464. }
  465.  
  466. var url = config.endpoint + path;
  467. var queryString = buildCanonicalQueryString(queryParams);
  468. if (queryString != '') {
  469. url += '?' + queryString;
  470. }
  471. var simpleHttpRequest = {
  472. method: verb,
  473. url: url,
  474. headers: headers,
  475. data: body
  476. };
  477. return axios(simpleHttpRequest);
  478. };
  479. return simpleHttpClient;
  480. };
  481.  
  482. module.exports = apiGateway.core.simpleHttpClientFactory;
  483.  
  484. },{"./utils":6,"axios":7}],6:[function(require,module,exports){
  485. /*
  486. * Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
  487. *
  488. * Licensed under the Apache License, Version 2.0 (the "License").
  489. * You may not use this file except in compliance with the License.
  490. * A copy of the License is located at
  491. *
  492. * http://aws.amazon.com/apache2.0
  493. *
  494. * or in the "license" file accompanying this file. This file is distributed
  495. * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
  496. * express or implied. See the License for the specific language governing
  497. * permissions and limitations under the License.
  498. */
  499.  
  500. var apiGateway = apiGateway || {};
  501. apiGateway.core = apiGateway.core || {};
  502.  
  503. apiGateway.core.utils = {
  504. assertDefined: function (object, name) {
  505. if (object === undefined) {
  506. throw name + ' must be defined';
  507. } else {
  508. return object;
  509. }
  510. },
  511. assertParametersDefined: function (params, keys, ignore) {
  512. if (keys === undefined) {
  513. return;
  514. }
  515. if (keys.length > 0 && params === undefined) {
  516. params = {};
  517. }
  518. for (var i = 0; i < keys.length; i++) {
  519. if(!apiGateway.core.utils.contains(ignore, keys[i])) {
  520. apiGateway.core.utils.assertDefined(params[keys[i]], keys[i]);
  521. }
  522. }
  523. },
  524. parseParametersToObject: function (params, keys) {
  525. if (params === undefined) {
  526. return {};
  527. }
  528. var object = { };
  529. for (var i = 0; i < keys.length; i++) {
  530. object[keys[i]] = params[keys[i]];
  531. }
  532. return object;
  533. },
  534. contains: function(a, obj) {
  535. if(a === undefined) { return false;}
  536. var i = a.length;
  537. while (i--) {
  538. if (a[i] === obj) {
  539. return true;
  540. }
  541. }
  542. return false;
  543. },
  544. copy: function (obj) {
  545. if (null == obj || "object" != typeof obj) return obj;
  546. var copy = obj.constructor();
  547. for (var attr in obj) {
  548. if (obj.hasOwnProperty(attr)) copy[attr] = obj[attr];
  549. }
  550. return copy;
  551. },
  552. mergeInto: function (baseObj, additionalProps) {
  553. if (null == baseObj || "object" != typeof baseObj) return baseObj;
  554. var merged = baseObj.constructor();
  555. for (var attr in baseObj) {
  556. if (baseObj.hasOwnProperty(attr)) merged[attr] = baseObj[attr];
  557. }
  558. if (null == additionalProps || "object" != typeof additionalProps) return baseObj;
  559. for (attr in additionalProps) {
  560. if (additionalProps.hasOwnProperty(attr)) merged[attr] = additionalProps[attr];
  561. }
  562. return merged;
  563. }
  564. };
  565.  
  566. module.exports = apiGateway.core.utils;
  567.  
  568. },{}],7:[function(require,module,exports){
  569. module.exports = require('./lib/axios');
  570. },{"./lib/axios":9}],8:[function(require,module,exports){
  571. (function (process){
  572. 'use strict';
  573.  
  574. var utils = require('./../utils');
  575. var settle = require('./../core/settle');
  576. var buildURL = require('./../helpers/buildURL');
  577. var parseHeaders = require('./../helpers/parseHeaders');
  578. var isURLSameOrigin = require('./../helpers/isURLSameOrigin');
  579. var createError = require('../core/createError');
  580. var btoa = (typeof window !== 'undefined' && window.btoa && window.btoa.bind(window)) || require('./../helpers/btoa');
  581.  
  582. module.exports = function xhrAdapter(config) {
  583. return new Promise(function dispatchXhrRequest(resolve, reject) {
  584. var requestData = config.data;
  585. var requestHeaders = config.headers;
  586.  
  587. if (utils.isFormData(requestData)) {
  588. delete requestHeaders['Content-Type']; // Let the browser set it
  589. }
  590.  
  591. var request = new XMLHttpRequest();
  592. var loadEvent = 'onreadystatechange';
  593. var xDomain = false;
  594.  
  595. // For IE 8/9 CORS support
  596. // Only supports POST and GET calls and doesn't returns the response headers.
  597. // DON'T do this for testing b/c XMLHttpRequest is mocked, not XDomainRequest.
  598. if (process.env.NODE_ENV !== 'test' &&
  599. typeof window !== 'undefined' &&
  600. window.XDomainRequest && !('withCredentials' in request) &&
  601. !isURLSameOrigin(config.url)) {
  602. request = new window.XDomainRequest();
  603. loadEvent = 'onload';
  604. xDomain = true;
  605. request.onprogress = function handleProgress() {};
  606. request.ontimeout = function handleTimeout() {};
  607. }
  608.  
  609. // HTTP basic authentication
  610. if (config.auth) {
  611. var username = config.auth.username || '';
  612. var password = config.auth.password || '';
  613. requestHeaders.Authorization = 'Basic ' + btoa(username + ':' + password);
  614. }
  615.  
  616. request.open(config.method.toUpperCase(), buildURL(config.url, config.params, config.paramsSerializer), true);
  617.  
  618. // Set the request timeout in MS
  619. request.timeout = config.timeout;
  620.  
  621. // Listen for ready state
  622. request[loadEvent] = function handleLoad() {
  623. if (!request || (request.readyState !== 4 && !xDomain)) {
  624. return;
  625. }
  626.  
  627. // The request errored out and we didn't get a response, this will be
  628. // handled by onerror instead
  629. // With one exception: request that using file: protocol, most browsers
  630. // will return status as 0 even though it's a successful request
  631. if (request.status === 0 && !(request.responseURL && request.responseURL.indexOf('file:') === 0)) {
  632. return;
  633. }
  634.  
  635. // Prepare the response
  636. var responseHeaders = 'getAllResponseHeaders' in request ? parseHeaders(request.getAllResponseHeaders()) : null;
  637. var responseData = !config.responseType || config.responseType === 'text' ? request.responseText : request.response;
  638. var response = {
  639. data: responseData,
  640. // IE sends 1223 instead of 204 (https://github.com/mzabriskie/axios/issues/201)
  641. status: request.status === 1223 ? 204 : request.status,
  642. statusText: request.status === 1223 ? 'No Content' : request.statusText,
  643. headers: responseHeaders,
  644. config: config,
  645. request: request
  646. };
  647.  
  648. settle(resolve, reject, response);
  649.  
  650. // Clean up request
  651. request = null;
  652. };
  653.  
  654. // Handle low level network errors
  655. request.onerror = function handleError() {
  656. // Real errors are hidden from us by the browser
  657. // onerror should only fire if it's a network error
  658. reject(createError('Network Error', config));
  659.  
  660. // Clean up request
  661. request = null;
  662. };
  663.  
  664. // Handle timeout
  665. request.ontimeout = function handleTimeout() {
  666. reject(createError('timeout of ' + config.timeout + 'ms exceeded', config, 'ECONNABORTED'));
  667.  
  668. // Clean up request
  669. request = null;
  670. };
  671.  
  672. // Add xsrf header
  673. // This is only done if running in a standard browser environment.
  674. // Specifically not if we're in a web worker, or react-native.
  675. if (utils.isStandardBrowserEnv()) {
  676. var cookies = require('./../helpers/cookies');
  677.  
  678. // Add xsrf header
  679. var xsrfValue = (config.withCredentials || isURLSameOrigin(config.url)) && config.xsrfCookieName ?
  680. cookies.read(config.xsrfCookieName) :
  681. undefined;
  682.  
  683. if (xsrfValue) {
  684. requestHeaders[config.xsrfHeaderName] = xsrfValue;
  685. }
  686. }
  687.  
  688. // Add headers to the request
  689. if ('setRequestHeader' in request) {
  690. utils.forEach(requestHeaders, function setRequestHeader(val, key) {
  691. if (typeof requestData === 'undefined' && key.toLowerCase() === 'content-type') {
  692. // Remove Content-Type if data is undefined
  693. delete requestHeaders[key];
  694. } else {
  695. // Otherwise add header to the request
  696. request.setRequestHeader(key, val);
  697. }
  698. });
  699. }
  700.  
  701. // Add withCredentials to request if needed
  702. if (config.withCredentials) {
  703. request.withCredentials = true;
  704. }
  705.  
  706. // Add responseType to request if needed
  707. if (config.responseType) {
  708. try {
  709. request.responseType = config.responseType;
  710. } catch (e) {
  711. if (request.responseType !== 'json') {
  712. throw e;
  713. }
  714. }
  715. }
  716.  
  717. // Handle progress if needed
  718. if (typeof config.onDownloadProgress === 'function') {
  719. request.addEventListener('progress', config.onDownloadProgress);
  720. }
  721.  
  722. // Not all browsers support upload events
  723. if (typeof config.onUploadProgress === 'function' && request.upload) {
  724. request.upload.addEventListener('progress', config.onUploadProgress);
  725. }
  726.  
  727. if (config.cancelToken) {
  728. // Handle cancellation
  729. config.cancelToken.promise.then(function onCanceled(cancel) {
  730. if (!request) {
  731. return;
  732. }
  733.  
  734. request.abort();
  735. reject(cancel);
  736. // Clean up request
  737. request = null;
  738. });
  739. }
  740.  
  741. if (requestData === undefined) {
  742. requestData = null;
  743. }
  744.  
  745. // Send the request
  746. request.send(requestData);
  747. });
  748. };
  749.  
  750. }).call(this,require('_process'))
  751. },{"../core/createError":15,"./../core/settle":18,"./../helpers/btoa":22,"./../helpers/buildURL":23,"./../helpers/cookies":25,"./../helpers/isURLSameOrigin":27,"./../helpers/parseHeaders":29,"./../utils":31,"_process":39}],9:[function(require,module,exports){
  752. 'use strict';
  753.  
  754. var utils = require('./utils');
  755. var bind = require('./helpers/bind');
  756. var Axios = require('./core/Axios');
  757. var defaults = require('./defaults');
  758.  
  759. /**
  760. * Create an instance of Axios
  761. *
  762. * @param {Object} defaultConfig The default config for the instance
  763. * @return {Axios} A new instance of Axios
  764. */
  765. function createInstance(defaultConfig) {
  766. var context = new Axios(defaultConfig);
  767. var instance = bind(Axios.prototype.request, context);
  768.  
  769. // Copy axios.prototype to instance
  770. utils.extend(instance, Axios.prototype, context);
  771.  
  772. // Copy context to instance
  773. utils.extend(instance, context);
  774.  
  775. return instance;
  776. }
  777.  
  778. // Create the default instance to be exported
  779. var axios = createInstance(defaults);
  780.  
  781. // Expose Axios class to allow class inheritance
  782. axios.Axios = Axios;
  783.  
  784. // Factory for creating new instances
  785. axios.create = function create(instanceConfig) {
  786. return createInstance(utils.merge(defaults, instanceConfig));
  787. };
  788.  
  789. // Expose Cancel & CancelToken
  790. axios.Cancel = require('./cancel/Cancel');
  791. axios.CancelToken = require('./cancel/CancelToken');
  792. axios.isCancel = require('./cancel/isCancel');
  793.  
  794. // Expose all/spread
  795. axios.all = function all(promises) {
  796. return Promise.all(promises);
  797. };
  798. axios.spread = require('./helpers/spread');
  799.  
  800. module.exports = axios;
  801.  
  802. // Allow use of default import syntax in TypeScript
  803. module.exports.default = axios;
  804.  
  805. },{"./cancel/Cancel":10,"./cancel/CancelToken":11,"./cancel/isCancel":12,"./core/Axios":13,"./defaults":20,"./helpers/bind":21,"./helpers/spread":30,"./utils":31}],10:[function(require,module,exports){
  806. 'use strict';
  807.  
  808. /**
  809. * A `Cancel` is an object that is thrown when an operation is canceled.
  810. *
  811. * @class
  812. * @param {string=} message The message.
  813. */
  814. function Cancel(message) {
  815. this.message = message;
  816. }
  817.  
  818. Cancel.prototype.toString = function toString() {
  819. return 'Cancel' + (this.message ? ': ' + this.message : '');
  820. };
  821.  
  822. Cancel.prototype.__CANCEL__ = true;
  823.  
  824. module.exports = Cancel;
  825.  
  826. },{}],11:[function(require,module,exports){
  827. 'use strict';
  828.  
  829. var Cancel = require('./Cancel');
  830.  
  831. /**
  832. * A `CancelToken` is an object that can be used to request cancellation of an operation.
  833. *
  834. * @class
  835. * @param {Function} executor The executor function.
  836. */
  837. function CancelToken(executor) {
  838. if (typeof executor !== 'function') {
  839. throw new TypeError('executor must be a function.');
  840. }
  841.  
  842. var resolvePromise;
  843. this.promise = new Promise(function promiseExecutor(resolve) {
  844. resolvePromise = resolve;
  845. });
  846.  
  847. var token = this;
  848. executor(function cancel(message) {
  849. if (token.reason) {
  850. // Cancellation has already been requested
  851. return;
  852. }
  853.  
  854. token.reason = new Cancel(message);
  855. resolvePromise(token.reason);
  856. });
  857. }
  858.  
  859. /**
  860. * Throws a `Cancel` if cancellation has been requested.
  861. */
  862. CancelToken.prototype.throwIfRequested = function throwIfRequested() {
  863. if (this.reason) {
  864. throw this.reason;
  865. }
  866. };
  867.  
  868. /**
  869. * Returns an object that contains a new `CancelToken` and a function that, when called,
  870. * cancels the `CancelToken`.
  871. */
  872. CancelToken.source = function source() {
  873. var cancel;
  874. var token = new CancelToken(function executor(c) {
  875. cancel = c;
  876. });
  877. return {
  878. token: token,
  879. cancel: cancel
  880. };
  881. };
  882.  
  883. module.exports = CancelToken;
  884.  
  885. },{"./Cancel":10}],12:[function(require,module,exports){
  886. 'use strict';
  887.  
  888. module.exports = function isCancel(value) {
  889. return !!(value && value.__CANCEL__);
  890. };
  891.  
  892. },{}],13:[function(require,module,exports){
  893. 'use strict';
  894.  
  895. var defaults = require('./../defaults');
  896. var utils = require('./../utils');
  897. var InterceptorManager = require('./InterceptorManager');
  898. var dispatchRequest = require('./dispatchRequest');
  899. var isAbsoluteURL = require('./../helpers/isAbsoluteURL');
  900. var combineURLs = require('./../helpers/combineURLs');
  901.  
  902. /**
  903. * Create a new instance of Axios
  904. *
  905. * @param {Object} instanceConfig The default config for the instance
  906. */
  907. function Axios(instanceConfig) {
  908. this.defaults = instanceConfig;
  909. this.interceptors = {
  910. request: new InterceptorManager(),
  911. response: new InterceptorManager()
  912. };
  913. }
  914.  
  915. /**
  916. * Dispatch a request
  917. *
  918. * @param {Object} config The config specific for this request (merged with this.defaults)
  919. */
  920. Axios.prototype.request = function request(config) {
  921. /*eslint no-param-reassign:0*/
  922. // Allow for axios('example/url'[, config]) a la fetch API
  923. if (typeof config === 'string') {
  924. config = utils.merge({
  925. url: arguments[0]
  926. }, arguments[1]);
  927. }
  928.  
  929. config = utils.merge(defaults, this.defaults, { method: 'get' }, config);
  930.  
  931. // Support baseURL config
  932. if (config.baseURL && !isAbsoluteURL(config.url)) {
  933. config.url = combineURLs(config.baseURL, config.url);
  934. }
  935.  
  936. // Hook up interceptors middleware
  937. var chain = [dispatchRequest, undefined];
  938. var promise = Promise.resolve(config);
  939.  
  940. this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) {
  941. chain.unshift(interceptor.fulfilled, interceptor.rejected);
  942. });
  943.  
  944. this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) {
  945. chain.push(interceptor.fulfilled, interceptor.rejected);
  946. });
  947.  
  948. while (chain.length) {
  949. promise = promise.then(chain.shift(), chain.shift());
  950. }
  951.  
  952. return promise;
  953. };
  954.  
  955. // Provide aliases for supported request methods
  956. utils.forEach(['delete', 'get', 'head'], function forEachMethodNoData(method) {
  957. /*eslint func-names:0*/
  958. Axios.prototype[method] = function(url, config) {
  959. return this.request(utils.merge(config || {}, {
  960. method: method,
  961. url: url
  962. }));
  963. };
  964. });
  965.  
  966. utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) {
  967. /*eslint func-names:0*/
  968. Axios.prototype[method] = function(url, data, config) {
  969. return this.request(utils.merge(config || {}, {
  970. method: method,
  971. url: url,
  972. data: data
  973. }));
  974. };
  975. });
  976.  
  977. module.exports = Axios;
  978.  
  979. },{"./../defaults":20,"./../helpers/combineURLs":24,"./../helpers/isAbsoluteURL":26,"./../utils":31,"./InterceptorManager":14,"./dispatchRequest":16}],14:[function(require,module,exports){
  980. 'use strict';
  981.  
  982. var utils = require('./../utils');
  983.  
  984. function InterceptorManager() {
  985. this.handlers = [];
  986. }
  987.  
  988. /**
  989. * Add a new interceptor to the stack
  990. *
  991. * @param {Function} fulfilled The function to handle `then` for a `Promise`
  992. * @param {Function} rejected The function to handle `reject` for a `Promise`
  993. *
  994. * @return {Number} An ID used to remove interceptor later
  995. */
  996. InterceptorManager.prototype.use = function use(fulfilled, rejected) {
  997. this.handlers.push({
  998. fulfilled: fulfilled,
  999. rejected: rejected
  1000. });
  1001. return this.handlers.length - 1;
  1002. };
  1003.  
  1004. /**
  1005. * Remove an interceptor from the stack
  1006. *
  1007. * @param {Number} id The ID that was returned by `use`
  1008. */
  1009. InterceptorManager.prototype.eject = function eject(id) {
  1010. if (this.handlers[id]) {
  1011. this.handlers[id] = null;
  1012. }
  1013. };
  1014.  
  1015. /**
  1016. * Iterate over all the registered interceptors
  1017. *
  1018. * This method is particularly useful for skipping over any
  1019. * interceptors that may have become `null` calling `eject`.
  1020. *
  1021. * @param {Function} fn The function to call for each interceptor
  1022. */
  1023. InterceptorManager.prototype.forEach = function forEach(fn) {
  1024. utils.forEach(this.handlers, function forEachHandler(h) {
  1025. if (h !== null) {
  1026. fn(h);
  1027. }
  1028. });
  1029. };
  1030.  
  1031. module.exports = InterceptorManager;
  1032.  
  1033. },{"./../utils":31}],15:[function(require,module,exports){
  1034. 'use strict';
  1035.  
  1036. var enhanceError = require('./enhanceError');
  1037.  
  1038. /**
  1039. * Create an Error with the specified message, config, error code, and response.
  1040. *
  1041. * @param {string} message The error message.
  1042. * @param {Object} config The config.
  1043. * @param {string} [code] The error code (for example, 'ECONNABORTED').
  1044. @ @param {Object} [response] The response.
  1045. * @returns {Error} The created error.
  1046. */
  1047. module.exports = function createError(message, config, code, response) {
  1048. var error = new Error(message);
  1049. return enhanceError(error, config, code, response);
  1050. };
  1051.  
  1052. },{"./enhanceError":17}],16:[function(require,module,exports){
  1053. 'use strict';
  1054.  
  1055. var utils = require('./../utils');
  1056. var transformData = require('./transformData');
  1057. var isCancel = require('../cancel/isCancel');
  1058. var defaults = require('../defaults');
  1059.  
  1060. /**
  1061. * Throws a `Cancel` if cancellation has been requested.
  1062. */
  1063. function throwIfCancellationRequested(config) {
  1064. if (config.cancelToken) {
  1065. config.cancelToken.throwIfRequested();
  1066. }
  1067. }
  1068.  
  1069. /**
  1070. * Dispatch a request to the server using the configured adapter.
  1071. *
  1072. * @param {object} config The config that is to be used for the request
  1073. * @returns {Promise} The Promise to be fulfilled
  1074. */
  1075. module.exports = function dispatchRequest(config) {
  1076. throwIfCancellationRequested(config);
  1077.  
  1078. // Ensure headers exist
  1079. config.headers = config.headers || {};
  1080.  
  1081. // Transform request data
  1082. config.data = transformData(
  1083. config.data,
  1084. config.headers,
  1085. config.transformRequest
  1086. );
  1087.  
  1088. // Flatten headers
  1089. config.headers = utils.merge(
  1090. config.headers.common || {},
  1091. config.headers[config.method] || {},
  1092. config.headers || {}
  1093. );
  1094.  
  1095. utils.forEach(
  1096. ['delete', 'get', 'head', 'post', 'put', 'patch', 'common'],
  1097. function cleanHeaderConfig(method) {
  1098. delete config.headers[method];
  1099. }
  1100. );
  1101.  
  1102. var adapter = config.adapter || defaults.adapter;
  1103.  
  1104. return adapter(config).then(function onAdapterResolution(response) {
  1105. throwIfCancellationRequested(config);
  1106.  
  1107. // Transform response data
  1108. response.data = transformData(
  1109. response.data,
  1110. response.headers,
  1111. config.transformResponse
  1112. );
  1113.  
  1114. return response;
  1115. }, function onAdapterRejection(reason) {
  1116. if (!isCancel(reason)) {
  1117. throwIfCancellationRequested(config);
  1118.  
  1119. // Transform response data
  1120. if (reason && reason.response) {
  1121. reason.response.data = transformData(
  1122. reason.response.data,
  1123. reason.response.headers,
  1124. config.transformResponse
  1125. );
  1126. }
  1127. }
  1128.  
  1129. return Promise.reject(reason);
  1130. });
  1131. };
  1132.  
  1133. },{"../cancel/isCancel":12,"../defaults":20,"./../utils":31,"./transformData":19}],17:[function(require,module,exports){
  1134. 'use strict';
  1135.  
  1136. /**
  1137. * Update an Error with the specified config, error code, and response.
  1138. *
  1139. * @param {Error} error The error to update.
  1140. * @param {Object} config The config.
  1141. * @param {string} [code] The error code (for example, 'ECONNABORTED').
  1142. @ @param {Object} [response] The response.
  1143. * @returns {Error} The error.
  1144. */
  1145. module.exports = function enhanceError(error, config, code, response) {
  1146. error.config = config;
  1147. if (code) {
  1148. error.code = code;
  1149. }
  1150. error.response = response;
  1151. return error;
  1152. };
  1153.  
  1154. },{}],18:[function(require,module,exports){
  1155. 'use strict';
  1156.  
  1157. var createError = require('./createError');
  1158.  
  1159. /**
  1160. * Resolve or reject a Promise based on response status.
  1161. *
  1162. * @param {Function} resolve A function that resolves the promise.
  1163. * @param {Function} reject A function that rejects the promise.
  1164. * @param {object} response The response.
  1165. */
  1166. module.exports = function settle(resolve, reject, response) {
  1167. var validateStatus = response.config.validateStatus;
  1168. // Note: status is not exposed by XDomainRequest
  1169. if (!response.status || !validateStatus || validateStatus(response.status)) {
  1170. resolve(response);
  1171. } else {
  1172. reject(createError(
  1173. 'Request failed with status code ' + response.status,
  1174. response.config,
  1175. null,
  1176. response
  1177. ));
  1178. }
  1179. };
  1180.  
  1181. },{"./createError":15}],19:[function(require,module,exports){
  1182. 'use strict';
  1183.  
  1184. var utils = require('./../utils');
  1185.  
  1186. /**
  1187. * Transform the data for a request or a response
  1188. *
  1189. * @param {Object|String} data The data to be transformed
  1190. * @param {Array} headers The headers for the request or response
  1191. * @param {Array|Function} fns A single function or Array of functions
  1192. * @returns {*} The resulting transformed data
  1193. */
  1194. module.exports = function transformData(data, headers, fns) {
  1195. /*eslint no-param-reassign:0*/
  1196. utils.forEach(fns, function transform(fn) {
  1197. data = fn(data, headers);
  1198. });
  1199.  
  1200. return data;
  1201. };
  1202.  
  1203. },{"./../utils":31}],20:[function(require,module,exports){
  1204. (function (process){
  1205. 'use strict';
  1206.  
  1207. var utils = require('./utils');
  1208. var normalizeHeaderName = require('./helpers/normalizeHeaderName');
  1209.  
  1210. var PROTECTION_PREFIX = /^\)\]\}',?\n/;
  1211. var DEFAULT_CONTENT_TYPE = {
  1212. 'Content-Type': 'application/x-www-form-urlencoded'
  1213. };
  1214.  
  1215. function setContentTypeIfUnset(headers, value) {
  1216. if (!utils.isUndefined(headers) && utils.isUndefined(headers['Content-Type'])) {
  1217. headers['Content-Type'] = value;
  1218. }
  1219. }
  1220.  
  1221. function getDefaultAdapter() {
  1222. var adapter;
  1223. if (typeof XMLHttpRequest !== 'undefined') {
  1224. // For browsers use XHR adapter
  1225. adapter = require('./adapters/xhr');
  1226. } else if (typeof process !== 'undefined') {
  1227. // For node use HTTP adapter
  1228. adapter = require('./adapters/http');
  1229. }
  1230. return adapter;
  1231. }
  1232.  
  1233. var defaults = {
  1234. adapter: getDefaultAdapter(),
  1235.  
  1236. transformRequest: [function transformRequest(data, headers) {
  1237. normalizeHeaderName(headers, 'Content-Type');
  1238. if (utils.isFormData(data) ||
  1239. utils.isArrayBuffer(data) ||
  1240. utils.isStream(data) ||
  1241. utils.isFile(data) ||
  1242. utils.isBlob(data)
  1243. ) {
  1244. return data;
  1245. }
  1246. if (utils.isArrayBufferView(data)) {
  1247. return data.buffer;
  1248. }
  1249. if (utils.isURLSearchParams(data)) {
  1250. setContentTypeIfUnset(headers, 'application/x-www-form-urlencoded;charset=utf-8');
  1251. return data.toString();
  1252. }
  1253. if (utils.isObject(data)) {
  1254. setContentTypeIfUnset(headers, 'application/json;charset=utf-8');
  1255. return JSON.stringify(data);
  1256. }
  1257. return data;
  1258. }],
  1259.  
  1260. transformResponse: [function transformResponse(data) {
  1261. /*eslint no-param-reassign:0*/
  1262. if (typeof data === 'string') {
  1263. data = data.replace(PROTECTION_PREFIX, '');
  1264. try {
  1265. data = JSON.parse(data);
  1266. } catch (e) { /* Ignore */ }
  1267. }
  1268. return data;
  1269. }],
  1270.  
  1271. timeout: 0,
  1272.  
  1273. xsrfCookieName: 'XSRF-TOKEN',
  1274. xsrfHeaderName: 'X-XSRF-TOKEN',
  1275.  
  1276. maxContentLength: -1,
  1277.  
  1278. validateStatus: function validateStatus(status) {
  1279. return status >= 200 && status < 300;
  1280. }
  1281. };
  1282.  
  1283. defaults.headers = {
  1284. common: {
  1285. 'Accept': 'application/json, text/plain, */*'
  1286. }
  1287. };
  1288.  
  1289. utils.forEach(['delete', 'get', 'head'], function forEachMehtodNoData(method) {
  1290. defaults.headers[method] = {};
  1291. });
  1292.  
  1293. utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) {
  1294. defaults.headers[method] = utils.merge(DEFAULT_CONTENT_TYPE);
  1295. });
  1296.  
  1297. module.exports = defaults;
  1298.  
  1299. }).call(this,require('_process'))
  1300. },{"./adapters/http":8,"./adapters/xhr":8,"./helpers/normalizeHeaderName":28,"./utils":31,"_process":39}],21:[function(require,module,exports){
  1301. 'use strict';
  1302.  
  1303. module.exports = function bind(fn, thisArg) {
  1304. return function wrap() {
  1305. var args = new Array(arguments.length);
  1306. for (var i = 0; i < args.length; i++) {
  1307. args[i] = arguments[i];
  1308. }
  1309. return fn.apply(thisArg, args);
  1310. };
  1311. };
  1312.  
  1313. },{}],22:[function(require,module,exports){
  1314. 'use strict';
  1315.  
  1316. // btoa polyfill for IE<10 courtesy https://github.com/davidchambers/Base64.js
  1317.  
  1318. var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
  1319.  
  1320. function E() {
  1321. this.message = 'String contains an invalid character';
  1322. }
  1323. E.prototype = new Error;
  1324. E.prototype.code = 5;
  1325. E.prototype.name = 'InvalidCharacterError';
  1326.  
  1327. function btoa(input) {
  1328. var str = String(input);
  1329. var output = '';
  1330. for (
  1331. // initialize result and counter
  1332. var block, charCode, idx = 0, map = chars;
  1333. // if the next str index does not exist:
  1334. // change the mapping table to "="
  1335. // check if d has no fractional digits
  1336. str.charAt(idx | 0) || (map = '=', idx % 1);
  1337. // "8 - idx % 1 * 8" generates the sequence 2, 4, 6, 8
  1338. output += map.charAt(63 & block >> 8 - idx % 1 * 8)
  1339. ) {
  1340. charCode = str.charCodeAt(idx += 3 / 4);
  1341. if (charCode > 0xFF) {
  1342. throw new E();
  1343. }
  1344. block = block << 8 | charCode;
  1345. }
  1346. return output;
  1347. }
  1348.  
  1349. module.exports = btoa;
  1350.  
  1351. },{}],23:[function(require,module,exports){
  1352. 'use strict';
  1353.  
  1354. var utils = require('./../utils');
  1355.  
  1356. function encode(val) {
  1357. return encodeURIComponent(val).
  1358. replace(/%40/gi, '@').
  1359. replace(/%3A/gi, ':').
  1360. replace(/%24/g, '$').
  1361. replace(/%2C/gi, ',').
  1362. replace(/%20/g, '+').
  1363. replace(/%5B/gi, '[').
  1364. replace(/%5D/gi, ']');
  1365. }
  1366.  
  1367. /**
  1368. * Build a URL by appending params to the end
  1369. *
  1370. * @param {string} url The base of the url (e.g., http://www.google.com)
  1371. * @param {object} [params] The params to be appended
  1372. * @returns {string} The formatted url
  1373. */
  1374. module.exports = function buildURL(url, params, paramsSerializer) {
  1375. /*eslint no-param-reassign:0*/
  1376. if (!params) {
  1377. return url;
  1378. }
  1379.  
  1380. var serializedParams;
  1381. if (paramsSerializer) {
  1382. serializedParams = paramsSerializer(params);
  1383. } else if (utils.isURLSearchParams(params)) {
  1384. serializedParams = params.toString();
  1385. } else {
  1386. var parts = [];
  1387.  
  1388. utils.forEach(params, function serialize(val, key) {
  1389. if (val === null || typeof val === 'undefined') {
  1390. return;
  1391. }
  1392.  
  1393. if (utils.isArray(val)) {
  1394. key = key + '[]';
  1395. }
  1396.  
  1397. if (!utils.isArray(val)) {
  1398. val = [val];
  1399. }
  1400.  
  1401. utils.forEach(val, function parseValue(v) {
  1402. if (utils.isDate(v)) {
  1403. v = v.toISOString();
  1404. } else if (utils.isObject(v)) {
  1405. v = JSON.stringify(v);
  1406. }
  1407. parts.push(encode(key) + '=' + encode(v));
  1408. });
  1409. });
  1410.  
  1411. serializedParams = parts.join('&');
  1412. }
  1413.  
  1414. if (serializedParams) {
  1415. url += (url.indexOf('?') === -1 ? '?' : '&') + serializedParams;
  1416. }
  1417.  
  1418. return url;
  1419. };
  1420.  
  1421. },{"./../utils":31}],24:[function(require,module,exports){
  1422. 'use strict';
  1423.  
  1424. /**
  1425. * Creates a new URL by combining the specified URLs
  1426. *
  1427. * @param {string} baseURL The base URL
  1428. * @param {string} relativeURL The relative URL
  1429. * @returns {string} The combined URL
  1430. */
  1431. module.exports = function combineURLs(baseURL, relativeURL) {
  1432. return baseURL.replace(/\/+$/, '') + '/' + relativeURL.replace(/^\/+/, '');
  1433. };
  1434.  
  1435. },{}],25:[function(require,module,exports){
  1436. 'use strict';
  1437.  
  1438. var utils = require('./../utils');
  1439.  
  1440. module.exports = (
  1441. utils.isStandardBrowserEnv() ?
  1442.  
  1443. // Standard browser envs support document.cookie
  1444. (function standardBrowserEnv() {
  1445. return {
  1446. write: function write(name, value, expires, path, domain, secure) {
  1447. var cookie = [];
  1448. cookie.push(name + '=' + encodeURIComponent(value));
  1449.  
  1450. if (utils.isNumber(expires)) {
  1451. cookie.push('expires=' + new Date(expires).toGMTString());
  1452. }
  1453.  
  1454. if (utils.isString(path)) {
  1455. cookie.push('path=' + path);
  1456. }
  1457.  
  1458. if (utils.isString(domain)) {
  1459. cookie.push('domain=' + domain);
  1460. }
  1461.  
  1462. if (secure === true) {
  1463. cookie.push('secure');
  1464. }
  1465.  
  1466. document.cookie = cookie.join('; ');
  1467. },
  1468.  
  1469. read: function read(name) {
  1470. var match = document.cookie.match(new RegExp('(^|;\\s*)(' + name + ')=([^;]*)'));
  1471. return (match ? decodeURIComponent(match[3]) : null);
  1472. },
  1473.  
  1474. remove: function remove(name) {
  1475. this.write(name, '', Date.now() - 86400000);
  1476. }
  1477. };
  1478. })() :
  1479.  
  1480. // Non standard browser env (web workers, react-native) lack needed support.
  1481. (function nonStandardBrowserEnv() {
  1482. return {
  1483. write: function write() {},
  1484. read: function read() { return null; },
  1485. remove: function remove() {}
  1486. };
  1487. })()
  1488. );
  1489.  
  1490. },{"./../utils":31}],26:[function(require,module,exports){
  1491. 'use strict';
  1492.  
  1493. /**
  1494. * Determines whether the specified URL is absolute
  1495. *
  1496. * @param {string} url The URL to test
  1497. * @returns {boolean} True if the specified URL is absolute, otherwise false
  1498. */
  1499. module.exports = function isAbsoluteURL(url) {
  1500. // A URL is considered absolute if it begins with "<scheme>://" or "//" (protocol-relative URL).
  1501. // RFC 3986 defines scheme name as a sequence of characters beginning with a letter and followed
  1502. // by any combination of letters, digits, plus, period, or hyphen.
  1503. return /^([a-z][a-z\d\+\-\.]*:)?\/\//i.test(url);
  1504. };
  1505.  
  1506. },{}],27:[function(require,module,exports){
  1507. 'use strict';
  1508.  
  1509. var utils = require('./../utils');
  1510.  
  1511. module.exports = (
  1512. utils.isStandardBrowserEnv() ?
  1513.  
  1514. // Standard browser envs have full support of the APIs needed to test
  1515. // whether the request URL is of the same origin as current location.
  1516. (function standardBrowserEnv() {
  1517. var msie = /(msie|trident)/i.test(navigator.userAgent);
  1518. var urlParsingNode = document.createElement('a');
  1519. var originURL;
  1520.  
  1521. /**
  1522. * Parse a URL to discover it's components
  1523. *
  1524. * @param {String} url The URL to be parsed
  1525. * @returns {Object}
  1526. */
  1527. function resolveURL(url) {
  1528. var href = url;
  1529.  
  1530. if (msie) {
  1531. // IE needs attribute set twice to normalize properties
  1532. urlParsingNode.setAttribute('href', href);
  1533. href = urlParsingNode.href;
  1534. }
  1535.  
  1536. urlParsingNode.setAttribute('href', href);
  1537.  
  1538. // urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils
  1539. return {
  1540. href: urlParsingNode.href,
  1541. protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '',
  1542. host: urlParsingNode.host,
  1543. search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, '') : '',
  1544. hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '',
  1545. hostname: urlParsingNode.hostname,
  1546. port: urlParsingNode.port,
  1547. pathname: (urlParsingNode.pathname.charAt(0) === '/') ?
  1548. urlParsingNode.pathname :
  1549. '/' + urlParsingNode.pathname
  1550. };
  1551. }
  1552.  
  1553. originURL = resolveURL(window.location.href);
  1554.  
  1555. /**
  1556. * Determine if a URL shares the same origin as the current location
  1557. *
  1558. * @param {String} requestURL The URL to test
  1559. * @returns {boolean} True if URL shares the same origin, otherwise false
  1560. */
  1561. return function isURLSameOrigin(requestURL) {
  1562. var parsed = (utils.isString(requestURL)) ? resolveURL(requestURL) : requestURL;
  1563. return (parsed.protocol === originURL.protocol &&
  1564. parsed.host === originURL.host);
  1565. };
  1566. })() :
  1567.  
  1568. // Non standard browser envs (web workers, react-native) lack needed support.
  1569. (function nonStandardBrowserEnv() {
  1570. return function isURLSameOrigin() {
  1571. return true;
  1572. };
  1573. })()
  1574. );
  1575.  
  1576. },{"./../utils":31}],28:[function(require,module,exports){
  1577. 'use strict';
  1578.  
  1579. var utils = require('../utils');
  1580.  
  1581. module.exports = function normalizeHeaderName(headers, normalizedName) {
  1582. utils.forEach(headers, function processHeader(value, name) {
  1583. if (name !== normalizedName && name.toUpperCase() === normalizedName.toUpperCase()) {
  1584. headers[normalizedName] = value;
  1585. delete headers[name];
  1586. }
  1587. });
  1588. };
  1589.  
  1590. },{"../utils":31}],29:[function(require,module,exports){
  1591. 'use strict';
  1592.  
  1593. var utils = require('./../utils');
  1594.  
  1595. /**
  1596. * Parse headers into an object
  1597. *
  1598. * ```
  1599. * Date: Wed, 27 Aug 2014 08:58:49 GMT
  1600. * Content-Type: application/json
  1601. * Connection: keep-alive
  1602. * Transfer-Encoding: chunked
  1603. * ```
  1604. *
  1605. * @param {String} headers Headers needing to be parsed
  1606. * @returns {Object} Headers parsed into an object
  1607. */
  1608. module.exports = function parseHeaders(headers) {
  1609. var parsed = {};
  1610. var key;
  1611. var val;
  1612. var i;
  1613.  
  1614. if (!headers) { return parsed; }
  1615.  
  1616. utils.forEach(headers.split('\n'), function parser(line) {
  1617. i = line.indexOf(':');
  1618. key = utils.trim(line.substr(0, i)).toLowerCase();
  1619. val = utils.trim(line.substr(i + 1));
  1620.  
  1621. if (key) {
  1622. parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val;
  1623. }
  1624. });
  1625.  
  1626. return parsed;
  1627. };
  1628.  
  1629. },{"./../utils":31}],30:[function(require,module,exports){
  1630. 'use strict';
  1631.  
  1632. /**
  1633. * Syntactic sugar for invoking a function and expanding an array for arguments.
  1634. *
  1635. * Common use case would be to use `Function.prototype.apply`.
  1636. *
  1637. * ```js
  1638. * function f(x, y, z) {}
  1639. * var args = [1, 2, 3];
  1640. * f.apply(null, args);
  1641. * ```
  1642. *
  1643. * With `spread` this example can be re-written.
  1644. *
  1645. * ```js
  1646. * spread(function(x, y, z) {})([1, 2, 3]);
  1647. * ```
  1648. *
  1649. * @param {Function} callback
  1650. * @returns {Function}
  1651. */
  1652. module.exports = function spread(callback) {
  1653. return function wrap(arr) {
  1654. return callback.apply(null, arr);
  1655. };
  1656. };
  1657.  
  1658. },{}],31:[function(require,module,exports){
  1659. 'use strict';
  1660.  
  1661. var bind = require('./helpers/bind');
  1662.  
  1663. /*global toString:true*/
  1664.  
  1665. // utils is a library of generic helper functions non-specific to axios
  1666.  
  1667. var toString = Object.prototype.toString;
  1668.  
  1669. /**
  1670. * Determine if a value is an Array
  1671. *
  1672. * @param {Object} val The value to test
  1673. * @returns {boolean} True if value is an Array, otherwise false
  1674. */
  1675. function isArray(val) {
  1676. return toString.call(val) === '[object Array]';
  1677. }
  1678.  
  1679. /**
  1680. * Determine if a value is an ArrayBuffer
  1681. *
  1682. * @param {Object} val The value to test
  1683. * @returns {boolean} True if value is an ArrayBuffer, otherwise false
  1684. */
  1685. function isArrayBuffer(val) {
  1686. return toString.call(val) === '[object ArrayBuffer]';
  1687. }
  1688.  
  1689. /**
  1690. * Determine if a value is a FormData
  1691. *
  1692. * @param {Object} val The value to test
  1693. * @returns {boolean} True if value is an FormData, otherwise false
  1694. */
  1695. function isFormData(val) {
  1696. return (typeof FormData !== 'undefined') && (val instanceof FormData);
  1697. }
  1698.  
  1699. /**
  1700. * Determine if a value is a view on an ArrayBuffer
  1701. *
  1702. * @param {Object} val The value to test
  1703. * @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false
  1704. */
  1705. function isArrayBufferView(val) {
  1706. var result;
  1707. if ((typeof ArrayBuffer !== 'undefined') && (ArrayBuffer.isView)) {
  1708. result = ArrayBuffer.isView(val);
  1709. } else {
  1710. result = (val) && (val.buffer) && (val.buffer instanceof ArrayBuffer);
  1711. }
  1712. return result;
  1713. }
  1714.  
  1715. /**
  1716. * Determine if a value is a String
  1717. *
  1718. * @param {Object} val The value to test
  1719. * @returns {boolean} True if value is a String, otherwise false
  1720. */
  1721. function isString(val) {
  1722. return typeof val === 'string';
  1723. }
  1724.  
  1725. /**
  1726. * Determine if a value is a Number
  1727. *
  1728. * @param {Object} val The value to test
  1729. * @returns {boolean} True if value is a Number, otherwise false
  1730. */
  1731. function isNumber(val) {
  1732. return typeof val === 'number';
  1733. }
  1734.  
  1735. /**
  1736. * Determine if a value is undefined
  1737. *
  1738. * @param {Object} val The value to test
  1739. * @returns {boolean} True if the value is undefined, otherwise false
  1740. */
  1741. function isUndefined(val) {
  1742. return typeof val === 'undefined';
  1743. }
  1744.  
  1745. /**
  1746. * Determine if a value is an Object
  1747. *
  1748. * @param {Object} val The value to test
  1749. * @returns {boolean} True if value is an Object, otherwise false
  1750. */
  1751. function isObject(val) {
  1752. return val !== null && typeof val === 'object';
  1753. }
  1754.  
  1755. /**
  1756. * Determine if a value is a Date
  1757. *
  1758. * @param {Object} val The value to test
  1759. * @returns {boolean} True if value is a Date, otherwise false
  1760. */
  1761. function isDate(val) {
  1762. return toString.call(val) === '[object Date]';
  1763. }
  1764.  
  1765. /**
  1766. * Determine if a value is a File
  1767. *
  1768. * @param {Object} val The value to test
  1769. * @returns {boolean} True if value is a File, otherwise false
  1770. */
  1771. function isFile(val) {
  1772. return toString.call(val) === '[object File]';
  1773. }
  1774.  
  1775. /**
  1776. * Determine if a value is a Blob
  1777. *
  1778. * @param {Object} val The value to test
  1779. * @returns {boolean} True if value is a Blob, otherwise false
  1780. */
  1781. function isBlob(val) {
  1782. return toString.call(val) === '[object Blob]';
  1783. }
  1784.  
  1785. /**
  1786. * Determine if a value is a Function
  1787. *
  1788. * @param {Object} val The value to test
  1789. * @returns {boolean} True if value is a Function, otherwise false
  1790. */
  1791. function isFunction(val) {
  1792. return toString.call(val) === '[object Function]';
  1793. }
  1794.  
  1795. /**
  1796. * Determine if a value is a Stream
  1797. *
  1798. * @param {Object} val The value to test
  1799. * @returns {boolean} True if value is a Stream, otherwise false
  1800. */
  1801. function isStream(val) {
  1802. return isObject(val) && isFunction(val.pipe);
  1803. }
  1804.  
  1805. /**
  1806. * Determine if a value is a URLSearchParams object
  1807. *
  1808. * @param {Object} val The value to test
  1809. * @returns {boolean} True if value is a URLSearchParams object, otherwise false
  1810. */
  1811. function isURLSearchParams(val) {
  1812. return typeof URLSearchParams !== 'undefined' && val instanceof URLSearchParams;
  1813. }
  1814.  
  1815. /**
  1816. * Trim excess whitespace off the beginning and end of a string
  1817. *
  1818. * @param {String} str The String to trim
  1819. * @returns {String} The String freed of excess whitespace
  1820. */
  1821. function trim(str) {
  1822. return str.replace(/^\s*/, '').replace(/\s*$/, '');
  1823. }
  1824.  
  1825. /**
  1826. * Determine if we're running in a standard browser environment
  1827. *
  1828. * This allows axios to run in a web worker, and react-native.
  1829. * Both environments support XMLHttpRequest, but not fully standard globals.
  1830. *
  1831. * web workers:
  1832. * typeof window -> undefined
  1833. * typeof document -> undefined
  1834. *
  1835. * react-native:
  1836. * typeof document.createElement -> undefined
  1837. */
  1838. function isStandardBrowserEnv() {
  1839. return (
  1840. typeof window !== 'undefined' &&
  1841. typeof document !== 'undefined' &&
  1842. typeof document.createElement === 'function'
  1843. );
  1844. }
  1845.  
  1846. /**
  1847. * Iterate over an Array or an Object invoking a function for each item.
  1848. *
  1849. * If `obj` is an Array callback will be called passing
  1850. * the value, index, and complete array for each item.
  1851. *
  1852. * If 'obj' is an Object callback will be called passing
  1853. * the value, key, and complete object for each property.
  1854. *
  1855. * @param {Object|Array} obj The object to iterate
  1856. * @param {Function} fn The callback to invoke for each item
  1857. */
  1858. function forEach(obj, fn) {
  1859. // Don't bother if no value provided
  1860. if (obj === null || typeof obj === 'undefined') {
  1861. return;
  1862. }
  1863.  
  1864. // Force an array if not already something iterable
  1865. if (typeof obj !== 'object' && !isArray(obj)) {
  1866. /*eslint no-param-reassign:0*/
  1867. obj = [obj];
  1868. }
  1869.  
  1870. if (isArray(obj)) {
  1871. // Iterate over array values
  1872. for (var i = 0, l = obj.length; i < l; i++) {
  1873. fn.call(null, obj[i], i, obj);
  1874. }
  1875. } else {
  1876. // Iterate over object keys
  1877. for (var key in obj) {
  1878. if (Object.prototype.hasOwnProperty.call(obj, key)) {
  1879. fn.call(null, obj[key], key, obj);
  1880. }
  1881. }
  1882. }
  1883. }
  1884.  
  1885. /**
  1886. * Accepts varargs expecting each argument to be an object, then
  1887. * immutably merges the properties of each object and returns result.
  1888. *
  1889. * When multiple objects contain the same key the later object in
  1890. * the arguments list will take precedence.
  1891. *
  1892. * Example:
  1893. *
  1894. * ```js
  1895. * var result = merge({foo: 123}, {foo: 456});
  1896. * console.log(result.foo); // outputs 456
  1897. * ```
  1898. *
  1899. * @param {Object} obj1 Object to merge
  1900. * @returns {Object} Result of all merge properties
  1901. */
  1902. function merge(/* obj1, obj2, obj3, ... */) {
  1903. var result = {};
  1904. function assignValue(val, key) {
  1905. if (typeof result[key] === 'object' && typeof val === 'object') {
  1906. result[key] = merge(result[key], val);
  1907. } else {
  1908. result[key] = val;
  1909. }
  1910. }
  1911.  
  1912. for (var i = 0, l = arguments.length; i < l; i++) {
  1913. forEach(arguments[i], assignValue);
  1914. }
  1915. return result;
  1916. }
  1917.  
  1918. /**
  1919. * Extends object a by mutably adding to it the properties of object b.
  1920. *
  1921. * @param {Object} a The object to be extended
  1922. * @param {Object} b The object to copy properties from
  1923. * @param {Object} thisArg The object to bind function to
  1924. * @return {Object} The resulting value of object a
  1925. */
  1926. function extend(a, b, thisArg) {
  1927. forEach(b, function assignValue(val, key) {
  1928. if (thisArg && typeof val === 'function') {
  1929. a[key] = bind(val, thisArg);
  1930. } else {
  1931. a[key] = val;
  1932. }
  1933. });
  1934. return a;
  1935. }
  1936.  
  1937. module.exports = {
  1938. isArray: isArray,
  1939. isArrayBuffer: isArrayBuffer,
  1940. isFormData: isFormData,
  1941. isArrayBufferView: isArrayBufferView,
  1942. isString: isString,
  1943. isNumber: isNumber,
  1944. isObject: isObject,
  1945. isUndefined: isUndefined,
  1946. isDate: isDate,
  1947. isFile: isFile,
  1948. isBlob: isBlob,
  1949. isFunction: isFunction,
  1950. isStream: isStream,
  1951. isURLSearchParams: isURLSearchParams,
  1952. isStandardBrowserEnv: isStandardBrowserEnv,
  1953. forEach: forEach,
  1954. merge: merge,
  1955. extend: extend,
  1956. trim: trim
  1957. };
  1958.  
  1959. },{"./helpers/bind":21}],32:[function(require,module,exports){
  1960. ;(function (root, factory) {
  1961. if (typeof exports === "object") {
  1962. // CommonJS
  1963. module.exports = exports = factory();
  1964. }
  1965. else if (typeof define === "function" && define.amd) {
  1966. // AMD
  1967. define([], factory);
  1968. }
  1969. else {
  1970. // Global (browser)
  1971. root.CryptoJS = factory();
  1972. }
  1973. }(this, function () {
  1974.  
  1975. /**
  1976. * CryptoJS core components.
  1977. */
  1978. var CryptoJS = CryptoJS || (function (Math, undefined) {
  1979. /*
  1980. * Local polyfil of Object.create
  1981. */
  1982. var create = Object.create || (function () {
  1983. function F() {};
  1984.  
  1985. return function (obj) {
  1986. var subtype;
  1987.  
  1988. F.prototype = obj;
  1989.  
  1990. subtype = new F();
  1991.  
  1992. F.prototype = null;
  1993.  
  1994. return subtype;
  1995. };
  1996. }())
  1997.  
  1998. /**
  1999. * CryptoJS namespace.
  2000. */
  2001. var C = {};
  2002.  
  2003. /**
  2004. * Library namespace.
  2005. */
  2006. var C_lib = C.lib = {};
  2007.  
  2008. /**
  2009. * Base object for prototypal inheritance.
  2010. */
  2011. var Base = C_lib.Base = (function () {
  2012.  
  2013.  
  2014. return {
  2015. /**
  2016. * Creates a new object that inherits from this object.
  2017. *
  2018. * @param {Object} overrides Properties to copy into the new object.
  2019. *
  2020. * @return {Object} The new object.
  2021. *
  2022. * @static
  2023. *
  2024. * @example
  2025. *
  2026. * var MyType = CryptoJS.lib.Base.extend({
  2027. * field: 'value',
  2028. *
  2029. * method: function () {
  2030. * }
  2031. * });
  2032. */
  2033. extend: function (overrides) {
  2034. // Spawn
  2035. var subtype = create(this);
  2036.  
  2037. // Augment
  2038. if (overrides) {
  2039. subtype.mixIn(overrides);
  2040. }
  2041.  
  2042. // Create default initializer
  2043. if (!subtype.hasOwnProperty('init') || this.init === subtype.init) {
  2044. subtype.init = function () {
  2045. subtype.$super.init.apply(this, arguments);
  2046. };
  2047. }
  2048.  
  2049. // Initializer's prototype is the subtype object
  2050. subtype.init.prototype = subtype;
  2051.  
  2052. // Reference supertype
  2053. subtype.$super = this;
  2054.  
  2055. return subtype;
  2056. },
  2057.  
  2058. /**
  2059. * Extends this object and runs the init method.
  2060. * Arguments to create() will be passed to init().
  2061. *
  2062. * @return {Object} The new object.
  2063. *
  2064. * @static
  2065. *
  2066. * @example
  2067. *
  2068. * var instance = MyType.create();
  2069. */
  2070. create: function () {
  2071. var instance = this.extend();
  2072. instance.init.apply(instance, arguments);
  2073.  
  2074. return instance;
  2075. },
  2076.  
  2077. /**
  2078. * Initializes a newly created object.
  2079. * Override this method to add some logic when your objects are created.
  2080. *
  2081. * @example
  2082. *
  2083. * var MyType = CryptoJS.lib.Base.extend({
  2084. * init: function () {
  2085. * // ...
  2086. * }
  2087. * });
  2088. */
  2089. init: function () {
  2090. },
  2091.  
  2092. /**
  2093. * Copies properties into this object.
  2094. *
  2095. * @param {Object} properties The properties to mix in.
  2096. *
  2097. * @example
  2098. *
  2099. * MyType.mixIn({
  2100. * field: 'value'
  2101. * });
  2102. */
  2103. mixIn: function (properties) {
  2104. for (var propertyName in properties) {
  2105. if (properties.hasOwnProperty(propertyName)) {
  2106. this[propertyName] = properties[propertyName];
  2107. }
  2108. }
  2109.  
  2110. // IE won't copy toString using the loop above
  2111. if (properties.hasOwnProperty('toString')) {
  2112. this.toString = properties.toString;
  2113. }
  2114. },
  2115.  
  2116. /**
  2117. * Creates a copy of this object.
  2118. *
  2119. * @return {Object} The clone.
  2120. *
  2121. * @example
  2122. *
  2123. * var clone = instance.clone();
  2124. */
  2125. clone: function () {
  2126. return this.init.prototype.extend(this);
  2127. }
  2128. };
  2129. }());
  2130.  
  2131. /**
  2132. * An array of 32-bit words.
  2133. *
  2134. * @property {Array} words The array of 32-bit words.
  2135. * @property {number} sigBytes The number of significant bytes in this word array.
  2136. */
  2137. var WordArray = C_lib.WordArray = Base.extend({
  2138. /**
  2139. * Initializes a newly created word array.
  2140. *
  2141. * @param {Array} words (Optional) An array of 32-bit words.
  2142. * @param {number} sigBytes (Optional) The number of significant bytes in the words.
  2143. *
  2144. * @example
  2145. *
  2146. * var wordArray = CryptoJS.lib.WordArray.create();
  2147. * var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607]);
  2148. * var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607], 6);
  2149. */
  2150. init: function (words, sigBytes) {
  2151. words = this.words = words || [];
  2152.  
  2153. if (sigBytes != undefined) {
  2154. this.sigBytes = sigBytes;
  2155. } else {
  2156. this.sigBytes = words.length * 4;
  2157. }
  2158. },
  2159.  
  2160. /**
  2161. * Converts this word array to a string.
  2162. *
  2163. * @param {Encoder} encoder (Optional) The encoding strategy to use. Default: CryptoJS.enc.Hex
  2164. *
  2165. * @return {string} The stringified word array.
  2166. *
  2167. * @example
  2168. *
  2169. * var string = wordArray + '';
  2170. * var string = wordArray.toString();
  2171. * var string = wordArray.toString(CryptoJS.enc.Utf8);
  2172. */
  2173. toString: function (encoder) {
  2174. return (encoder || Hex).stringify(this);
  2175. },
  2176.  
  2177. /**
  2178. * Concatenates a word array to this word array.
  2179. *
  2180. * @param {WordArray} wordArray The word array to append.
  2181. *
  2182. * @return {WordArray} This word array.
  2183. *
  2184. * @example
  2185. *
  2186. * wordArray1.concat(wordArray2);
  2187. */
  2188. concat: function (wordArray) {
  2189. // Shortcuts
  2190. var thisWords = this.words;
  2191. var thatWords = wordArray.words;
  2192. var thisSigBytes = this.sigBytes;
  2193. var thatSigBytes = wordArray.sigBytes;
  2194.  
  2195. // Clamp excess bits
  2196. this.clamp();
  2197.  
  2198. // Concat
  2199. if (thisSigBytes % 4) {
  2200. // Copy one byte at a time
  2201. for (var i = 0; i < thatSigBytes; i++) {
  2202. var thatByte = (thatWords[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff;
  2203. thisWords[(thisSigBytes + i) >>> 2] |= thatByte << (24 - ((thisSigBytes + i) % 4) * 8);
  2204. }
  2205. } else {
  2206. // Copy one word at a time
  2207. for (var i = 0; i < thatSigBytes; i += 4) {
  2208. thisWords[(thisSigBytes + i) >>> 2] = thatWords[i >>> 2];
  2209. }
  2210. }
  2211. this.sigBytes += thatSigBytes;
  2212.  
  2213. // Chainable
  2214. return this;
  2215. },
  2216.  
  2217. /**
  2218. * Removes insignificant bits.
  2219. *
  2220. * @example
  2221. *
  2222. * wordArray.clamp();
  2223. */
  2224. clamp: function () {
  2225. // Shortcuts
  2226. var words = this.words;
  2227. var sigBytes = this.sigBytes;
  2228.  
  2229. // Clamp
  2230. words[sigBytes >>> 2] &= 0xffffffff << (32 - (sigBytes % 4) * 8);
  2231. words.length = Math.ceil(sigBytes / 4);
  2232. },
  2233.  
  2234. /**
  2235. * Creates a copy of this word array.
  2236. *
  2237. * @return {WordArray} The clone.
  2238. *
  2239. * @example
  2240. *
  2241. * var clone = wordArray.clone();
  2242. */
  2243. clone: function () {
  2244. var clone = Base.clone.call(this);
  2245. clone.words = this.words.slice(0);
  2246.  
  2247. return clone;
  2248. },
  2249.  
  2250. /**
  2251. * Creates a word array filled with random bytes.
  2252. *
  2253. * @param {number} nBytes The number of random bytes to generate.
  2254. *
  2255. * @return {WordArray} The random word array.
  2256. *
  2257. * @static
  2258. *
  2259. * @example
  2260. *
  2261. * var wordArray = CryptoJS.lib.WordArray.random(16);
  2262. */
  2263. random: function (nBytes) {
  2264. var words = [];
  2265.  
  2266. var r = (function (m_w) {
  2267. var m_w = m_w;
  2268. var m_z = 0x3ade68b1;
  2269. var mask = 0xffffffff;
  2270.  
  2271. return function () {
  2272. m_z = (0x9069 * (m_z & 0xFFFF) + (m_z >> 0x10)) & mask;
  2273. m_w = (0x4650 * (m_w & 0xFFFF) + (m_w >> 0x10)) & mask;
  2274. var result = ((m_z << 0x10) + m_w) & mask;
  2275. result /= 0x100000000;
  2276. result += 0.5;
  2277. return result * (Math.random() > .5 ? 1 : -1);
  2278. }
  2279. });
  2280.  
  2281. for (var i = 0, rcache; i < nBytes; i += 4) {
  2282. var _r = r((rcache || Math.random()) * 0x100000000);
  2283.  
  2284. rcache = _r() * 0x3ade67b7;
  2285. words.push((_r() * 0x100000000) | 0);
  2286. }
  2287.  
  2288. return new WordArray.init(words, nBytes);
  2289. }
  2290. });
  2291.  
  2292. /**
  2293. * Encoder namespace.
  2294. */
  2295. var C_enc = C.enc = {};
  2296.  
  2297. /**
  2298. * Hex encoding strategy.
  2299. */
  2300. var Hex = C_enc.Hex = {
  2301. /**
  2302. * Converts a word array to a hex string.
  2303. *
  2304. * @param {WordArray} wordArray The word array.
  2305. *
  2306. * @return {string} The hex string.
  2307. *
  2308. * @static
  2309. *
  2310. * @example
  2311. *
  2312. * var hexString = CryptoJS.enc.Hex.stringify(wordArray);
  2313. */
  2314. stringify: function (wordArray) {
  2315. // Shortcuts
  2316. var words = wordArray.words;
  2317. var sigBytes = wordArray.sigBytes;
  2318.  
  2319. // Convert
  2320. var hexChars = [];
  2321. for (var i = 0; i < sigBytes; i++) {
  2322. var bite = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff;
  2323. hexChars.push((bite >>> 4).toString(16));
  2324. hexChars.push((bite & 0x0f).toString(16));
  2325. }
  2326.  
  2327. return hexChars.join('');
  2328. },
  2329.  
  2330. /**
  2331. * Converts a hex string to a word array.
  2332. *
  2333. * @param {string} hexStr The hex string.
  2334. *
  2335. * @return {WordArray} The word array.
  2336. *
  2337. * @static
  2338. *
  2339. * @example
  2340. *
  2341. * var wordArray = CryptoJS.enc.Hex.parse(hexString);
  2342. */
  2343. parse: function (hexStr) {
  2344. // Shortcut
  2345. var hexStrLength = hexStr.length;
  2346.  
  2347. // Convert
  2348. var words = [];
  2349. for (var i = 0; i < hexStrLength; i += 2) {
  2350. words[i >>> 3] |= parseInt(hexStr.substr(i, 2), 16) << (24 - (i % 8) * 4);
  2351. }
  2352.  
  2353. return new WordArray.init(words, hexStrLength / 2);
  2354. }
  2355. };
  2356.  
  2357. /**
  2358. * Latin1 encoding strategy.
  2359. */
  2360. var Latin1 = C_enc.Latin1 = {
  2361. /**
  2362. * Converts a word array to a Latin1 string.
  2363. *
  2364. * @param {WordArray} wordArray The word array.
  2365. *
  2366. * @return {string} The Latin1 string.
  2367. *
  2368. * @static
  2369. *
  2370. * @example
  2371. *
  2372. * var latin1String = CryptoJS.enc.Latin1.stringify(wordArray);
  2373. */
  2374. stringify: function (wordArray) {
  2375. // Shortcuts
  2376. var words = wordArray.words;
  2377. var sigBytes = wordArray.sigBytes;
  2378.  
  2379. // Convert
  2380. var latin1Chars = [];
  2381. for (var i = 0; i < sigBytes; i++) {
  2382. var bite = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff;
  2383. latin1Chars.push(String.fromCharCode(bite));
  2384. }
  2385.  
  2386. return latin1Chars.join('');
  2387. },
  2388.  
  2389. /**
  2390. * Converts a Latin1 string to a word array.
  2391. *
  2392. * @param {string} latin1Str The Latin1 string.
  2393. *
  2394. * @return {WordArray} The word array.
  2395. *
  2396. * @static
  2397. *
  2398. * @example
  2399. *
  2400. * var wordArray = CryptoJS.enc.Latin1.parse(latin1String);
  2401. */
  2402. parse: function (latin1Str) {
  2403. // Shortcut
  2404. var latin1StrLength = latin1Str.length;
  2405.  
  2406. // Convert
  2407. var words = [];
  2408. for (var i = 0; i < latin1StrLength; i++) {
  2409. words[i >>> 2] |= (latin1Str.charCodeAt(i) & 0xff) << (24 - (i % 4) * 8);
  2410. }
  2411.  
  2412. return new WordArray.init(words, latin1StrLength);
  2413. }
  2414. };
  2415.  
  2416. /**
  2417. * UTF-8 encoding strategy.
  2418. */
  2419. var Utf8 = C_enc.Utf8 = {
  2420. /**
  2421. * Converts a word array to a UTF-8 string.
  2422. *
  2423. * @param {WordArray} wordArray The word array.
  2424. *
  2425. * @return {string} The UTF-8 string.
  2426. *
  2427. * @static
  2428. *
  2429. * @example
  2430. *
  2431. * var utf8String = CryptoJS.enc.Utf8.stringify(wordArray);
  2432. */
  2433. stringify: function (wordArray) {
  2434. try {
  2435. return decodeURIComponent(escape(Latin1.stringify(wordArray)));
  2436. } catch (e) {
  2437. throw new Error('Malformed UTF-8 data');
  2438. }
  2439. },
  2440.  
  2441. /**
  2442. * Converts a UTF-8 string to a word array.
  2443. *
  2444. * @param {string} utf8Str The UTF-8 string.
  2445. *
  2446. * @return {WordArray} The word array.
  2447. *
  2448. * @static
  2449. *
  2450. * @example
  2451. *
  2452. * var wordArray = CryptoJS.enc.Utf8.parse(utf8String);
  2453. */
  2454. parse: function (utf8Str) {
  2455. return Latin1.parse(unescape(encodeURIComponent(utf8Str)));
  2456. }
  2457. };
  2458.  
  2459. /**
  2460. * Abstract buffered block algorithm template.
  2461. *
  2462. * The property blockSize must be implemented in a concrete subtype.
  2463. *
  2464. * @property {number} _minBufferSize The number of blocks that should be kept unprocessed in the buffer. Default: 0
  2465. */
  2466. var BufferedBlockAlgorithm = C_lib.BufferedBlockAlgorithm = Base.extend({
  2467. /**
  2468. * Resets this block algorithm's data buffer to its initial state.
  2469. *
  2470. * @example
  2471. *
  2472. * bufferedBlockAlgorithm.reset();
  2473. */
  2474. reset: function () {
  2475. // Initial values
  2476. this._data = new WordArray.init();
  2477. this._nDataBytes = 0;
  2478. },
  2479.  
  2480. /**
  2481. * Adds new data to this block algorithm's buffer.
  2482. *
  2483. * @param {WordArray|string} data The data to append. Strings are converted to a WordArray using UTF-8.
  2484. *
  2485. * @example
  2486. *
  2487. * bufferedBlockAlgorithm._append('data');
  2488. * bufferedBlockAlgorithm._append(wordArray);
  2489. */
  2490. _append: function (data) {
  2491. // Convert string to WordArray, else assume WordArray already
  2492. if (typeof data == 'string') {
  2493. data = Utf8.parse(data);
  2494. }
  2495.  
  2496. // Append
  2497. this._data.concat(data);
  2498. this._nDataBytes += data.sigBytes;
  2499. },
  2500.  
  2501. /**
  2502. * Processes available data blocks.
  2503. *
  2504. * This method invokes _doProcessBlock(offset), which must be implemented by a concrete subtype.
  2505. *
  2506. * @param {boolean} doFlush Whether all blocks and partial blocks should be processed.
  2507. *
  2508. * @return {WordArray} The processed data.
  2509. *
  2510. * @example
  2511. *
  2512. * var processedData = bufferedBlockAlgorithm._process();
  2513. * var processedData = bufferedBlockAlgorithm._process(!!'flush');
  2514. */
  2515. _process: function (doFlush) {
  2516. // Shortcuts
  2517. var data = this._data;
  2518. var dataWords = data.words;
  2519. var dataSigBytes = data.sigBytes;
  2520. var blockSize = this.blockSize;
  2521. var blockSizeBytes = blockSize * 4;
  2522.  
  2523. // Count blocks ready
  2524. var nBlocksReady = dataSigBytes / blockSizeBytes;
  2525. if (doFlush) {
  2526. // Round up to include partial blocks
  2527. nBlocksReady = Math.ceil(nBlocksReady);
  2528. } else {
  2529. // Round down to include only full blocks,
  2530. // less the number of blocks that must remain in the buffer
  2531. nBlocksReady = Math.max((nBlocksReady | 0) - this._minBufferSize, 0);
  2532. }
  2533.  
  2534. // Count words ready
  2535. var nWordsReady = nBlocksReady * blockSize;
  2536.  
  2537. // Count bytes ready
  2538. var nBytesReady = Math.min(nWordsReady * 4, dataSigBytes);
  2539.  
  2540. // Process blocks
  2541. if (nWordsReady) {
  2542. for (var offset = 0; offset < nWordsReady; offset += blockSize) {
  2543. // Perform concrete-algorithm logic
  2544. this._doProcessBlock(dataWords, offset);
  2545. }
  2546.  
  2547. // Remove processed words
  2548. var processedWords = dataWords.splice(0, nWordsReady);
  2549. data.sigBytes -= nBytesReady;
  2550. }
  2551.  
  2552. // Return processed words
  2553. return new WordArray.init(processedWords, nBytesReady);
  2554. },
  2555.  
  2556. /**
  2557. * Creates a copy of this object.
  2558. *
  2559. * @return {Object} The clone.
  2560. *
  2561. * @example
  2562. *
  2563. * var clone = bufferedBlockAlgorithm.clone();
  2564. */
  2565. clone: function () {
  2566. var clone = Base.clone.call(this);
  2567. clone._data = this._data.clone();
  2568.  
  2569. return clone;
  2570. },
  2571.  
  2572. _minBufferSize: 0
  2573. });
  2574.  
  2575. /**
  2576. * Abstract hasher template.
  2577. *
  2578. * @property {number} blockSize The number of 32-bit words this hasher operates on. Default: 16 (512 bits)
  2579. */
  2580. var Hasher = C_lib.Hasher = BufferedBlockAlgorithm.extend({
  2581. /**
  2582. * Configuration options.
  2583. */
  2584. cfg: Base.extend(),
  2585.  
  2586. /**
  2587. * Initializes a newly created hasher.
  2588. *
  2589. * @param {Object} cfg (Optional) The configuration options to use for this hash computation.
  2590. *
  2591. * @example
  2592. *
  2593. * var hasher = CryptoJS.algo.SHA256.create();
  2594. */
  2595. init: function (cfg) {
  2596. // Apply config defaults
  2597. this.cfg = this.cfg.extend(cfg);
  2598.  
  2599. // Set initial values
  2600. this.reset();
  2601. },
  2602.  
  2603. /**
  2604. * Resets this hasher to its initial state.
  2605. *
  2606. * @example
  2607. *
  2608. * hasher.reset();
  2609. */
  2610. reset: function () {
  2611. // Reset data buffer
  2612. BufferedBlockAlgorithm.reset.call(this);
  2613.  
  2614. // Perform concrete-hasher logic
  2615. this._doReset();
  2616. },
  2617.  
  2618. /**
  2619. * Updates this hasher with a message.
  2620. *
  2621. * @param {WordArray|string} messageUpdate The message to append.
  2622. *
  2623. * @return {Hasher} This hasher.
  2624. *
  2625. * @example
  2626. *
  2627. * hasher.update('message');
  2628. * hasher.update(wordArray);
  2629. */
  2630. update: function (messageUpdate) {
  2631. // Append
  2632. this._append(messageUpdate);
  2633.  
  2634. // Update the hash
  2635. this._process();
  2636.  
  2637. // Chainable
  2638. return this;
  2639. },
  2640.  
  2641. /**
  2642. * Finalizes the hash computation.
  2643. * Note that the finalize operation is effectively a destructive, read-once operation.
  2644. *
  2645. * @param {WordArray|string} messageUpdate (Optional) A final message update.
  2646. *
  2647. * @return {WordArray} The hash.
  2648. *
  2649. * @example
  2650. *
  2651. * var hash = hasher.finalize();
  2652. * var hash = hasher.finalize('message');
  2653. * var hash = hasher.finalize(wordArray);
  2654. */
  2655. finalize: function (messageUpdate) {
  2656. // Final message update
  2657. if (messageUpdate) {
  2658. this._append(messageUpdate);
  2659. }
  2660.  
  2661. // Perform concrete-hasher logic
  2662. var hash = this._doFinalize();
  2663.  
  2664. return hash;
  2665. },
  2666.  
  2667. blockSize: 512/32,
  2668.  
  2669. /**
  2670. * Creates a shortcut function to a hasher's object interface.
  2671. *
  2672. * @param {Hasher} hasher The hasher to create a helper for.
  2673. *
  2674. * @return {Function} The shortcut function.
  2675. *
  2676. * @static
  2677. *
  2678. * @example
  2679. *
  2680. * var SHA256 = CryptoJS.lib.Hasher._createHelper(CryptoJS.algo.SHA256);
  2681. */
  2682. _createHelper: function (hasher) {
  2683. return function (message, cfg) {
  2684. return new hasher.init(cfg).finalize(message);
  2685. };
  2686. },
  2687.  
  2688. /**
  2689. * Creates a shortcut function to the HMAC's object interface.
  2690. *
  2691. * @param {Hasher} hasher The hasher to use in this HMAC helper.
  2692. *
  2693. * @return {Function} The shortcut function.
  2694. *
  2695. * @static
  2696. *
  2697. * @example
  2698. *
  2699. * var HmacSHA256 = CryptoJS.lib.Hasher._createHmacHelper(CryptoJS.algo.SHA256);
  2700. */
  2701. _createHmacHelper: function (hasher) {
  2702. return function (message, key) {
  2703. return new C_algo.HMAC.init(hasher, key).finalize(message);
  2704. };
  2705. }
  2706. });
  2707.  
  2708. /**
  2709. * Algorithm namespace.
  2710. */
  2711. var C_algo = C.algo = {};
  2712.  
  2713. return C;
  2714. }(Math));
  2715.  
  2716.  
  2717. return CryptoJS;
  2718.  
  2719. }));
  2720. },{}],33:[function(require,module,exports){
  2721. ;(function (root, factory) {
  2722. if (typeof exports === "object") {
  2723. // CommonJS
  2724. module.exports = exports = factory(require("./core"));
  2725. }
  2726. else if (typeof define === "function" && define.amd) {
  2727. // AMD
  2728. define(["./core"], factory);
  2729. }
  2730. else {
  2731. // Global (browser)
  2732. factory(root.CryptoJS);
  2733. }
  2734. }(this, function (CryptoJS) {
  2735.  
  2736. return CryptoJS.enc.Hex;
  2737.  
  2738. }));
  2739. },{"./core":32}],34:[function(require,module,exports){
  2740. ;(function (root, factory, undef) {
  2741. if (typeof exports === "object") {
  2742. // CommonJS
  2743. module.exports = exports = factory(require("./core"), require("./sha256"), require("./hmac"));
  2744. }
  2745. else if (typeof define === "function" && define.amd) {
  2746. // AMD
  2747. define(["./core", "./sha256", "./hmac"], factory);
  2748. }
  2749. else {
  2750. // Global (browser)
  2751. factory(root.CryptoJS);
  2752. }
  2753. }(this, function (CryptoJS) {
  2754.  
  2755. return CryptoJS.HmacSHA256;
  2756.  
  2757. }));
  2758. },{"./core":32,"./hmac":35,"./sha256":36}],35:[function(require,module,exports){
  2759. ;(function (root, factory) {
  2760. if (typeof exports === "object") {
  2761. // CommonJS
  2762. module.exports = exports = factory(require("./core"));
  2763. }
  2764. else if (typeof define === "function" && define.amd) {
  2765. // AMD
  2766. define(["./core"], factory);
  2767. }
  2768. else {
  2769. // Global (browser)
  2770. factory(root.CryptoJS);
  2771. }
  2772. }(this, function (CryptoJS) {
  2773.  
  2774. (function () {
  2775. // Shortcuts
  2776. var C = CryptoJS;
  2777. var C_lib = C.lib;
  2778. var Base = C_lib.Base;
  2779. var C_enc = C.enc;
  2780. var Utf8 = C_enc.Utf8;
  2781. var C_algo = C.algo;
  2782.  
  2783. /**
  2784. * HMAC algorithm.
  2785. */
  2786. var HMAC = C_algo.HMAC = Base.extend({
  2787. /**
  2788. * Initializes a newly created HMAC.
  2789. *
  2790. * @param {Hasher} hasher The hash algorithm to use.
  2791. * @param {WordArray|string} key The secret key.
  2792. *
  2793. * @example
  2794. *
  2795. * var hmacHasher = CryptoJS.algo.HMAC.create(CryptoJS.algo.SHA256, key);
  2796. */
  2797. init: function (hasher, key) {
  2798. // Init hasher
  2799. hasher = this._hasher = new hasher.init();
  2800.  
  2801. // Convert string to WordArray, else assume WordArray already
  2802. if (typeof key == 'string') {
  2803. key = Utf8.parse(key);
  2804. }
  2805.  
  2806. // Shortcuts
  2807. var hasherBlockSize = hasher.blockSize;
  2808. var hasherBlockSizeBytes = hasherBlockSize * 4;
  2809.  
  2810. // Allow arbitrary length keys
  2811. if (key.sigBytes > hasherBlockSizeBytes) {
  2812. key = hasher.finalize(key);
  2813. }
  2814.  
  2815. // Clamp excess bits
  2816. key.clamp();
  2817.  
  2818. // Clone key for inner and outer pads
  2819. var oKey = this._oKey = key.clone();
  2820. var iKey = this._iKey = key.clone();
  2821.  
  2822. // Shortcuts
  2823. var oKeyWords = oKey.words;
  2824. var iKeyWords = iKey.words;
  2825.  
  2826. // XOR keys with pad constants
  2827. for (var i = 0; i < hasherBlockSize; i++) {
  2828. oKeyWords[i] ^= 0x5c5c5c5c;
  2829. iKeyWords[i] ^= 0x36363636;
  2830. }
  2831. oKey.sigBytes = iKey.sigBytes = hasherBlockSizeBytes;
  2832.  
  2833. // Set initial values
  2834. this.reset();
  2835. },
  2836.  
  2837. /**
  2838. * Resets this HMAC to its initial state.
  2839. *
  2840. * @example
  2841. *
  2842. * hmacHasher.reset();
  2843. */
  2844. reset: function () {
  2845. // Shortcut
  2846. var hasher = this._hasher;
  2847.  
  2848. // Reset
  2849. hasher.reset();
  2850. hasher.update(this._iKey);
  2851. },
  2852.  
  2853. /**
  2854. * Updates this HMAC with a message.
  2855. *
  2856. * @param {WordArray|string} messageUpdate The message to append.
  2857. *
  2858. * @return {HMAC} This HMAC instance.
  2859. *
  2860. * @example
  2861. *
  2862. * hmacHasher.update('message');
  2863. * hmacHasher.update(wordArray);
  2864. */
  2865. update: function (messageUpdate) {
  2866. this._hasher.update(messageUpdate);
  2867.  
  2868. // Chainable
  2869. return this;
  2870. },
  2871.  
  2872. /**
  2873. * Finalizes the HMAC computation.
  2874. * Note that the finalize operation is effectively a destructive, read-once operation.
  2875. *
  2876. * @param {WordArray|string} messageUpdate (Optional) A final message update.
  2877. *
  2878. * @return {WordArray} The HMAC.
  2879. *
  2880. * @example
  2881. *
  2882. * var hmac = hmacHasher.finalize();
  2883. * var hmac = hmacHasher.finalize('message');
  2884. * var hmac = hmacHasher.finalize(wordArray);
  2885. */
  2886. finalize: function (messageUpdate) {
  2887. // Shortcut
  2888. var hasher = this._hasher;
  2889.  
  2890. // Compute HMAC
  2891. var innerHash = hasher.finalize(messageUpdate);
  2892. hasher.reset();
  2893. var hmac = hasher.finalize(this._oKey.clone().concat(innerHash));
  2894.  
  2895. return hmac;
  2896. }
  2897. });
  2898. }());
  2899.  
  2900.  
  2901. }));
  2902. },{"./core":32}],36:[function(require,module,exports){
  2903. ;(function (root, factory) {
  2904. if (typeof exports === "object") {
  2905. // CommonJS
  2906. module.exports = exports = factory(require("./core"));
  2907. }
  2908. else if (typeof define === "function" && define.amd) {
  2909. // AMD
  2910. define(["./core"], factory);
  2911. }
  2912. else {
  2913. // Global (browser)
  2914. factory(root.CryptoJS);
  2915. }
  2916. }(this, function (CryptoJS) {
  2917.  
  2918. (function (Math) {
  2919. // Shortcuts
  2920. var C = CryptoJS;
  2921. var C_lib = C.lib;
  2922. var WordArray = C_lib.WordArray;
  2923. var Hasher = C_lib.Hasher;
  2924. var C_algo = C.algo;
  2925.  
  2926. // Initialization and round constants tables
  2927. var H = [];
  2928. var K = [];
  2929.  
  2930. // Compute constants
  2931. (function () {
  2932. function isPrime(n) {
  2933. var sqrtN = Math.sqrt(n);
  2934. for (var factor = 2; factor <= sqrtN; factor++) {
  2935. if (!(n % factor)) {
  2936. return false;
  2937. }
  2938. }
  2939.  
  2940. return true;
  2941. }
  2942.  
  2943. function getFractionalBits(n) {
  2944. return ((n - (n | 0)) * 0x100000000) | 0;
  2945. }
  2946.  
  2947. var n = 2;
  2948. var nPrime = 0;
  2949. while (nPrime < 64) {
  2950. if (isPrime(n)) {
  2951. if (nPrime < 8) {
  2952. H[nPrime] = getFractionalBits(Math.pow(n, 1 / 2));
  2953. }
  2954. K[nPrime] = getFractionalBits(Math.pow(n, 1 / 3));
  2955.  
  2956. nPrime++;
  2957. }
  2958.  
  2959. n++;
  2960. }
  2961. }());
  2962.  
  2963. // Reusable object
  2964. var W = [];
  2965.  
  2966. /**
  2967. * SHA-256 hash algorithm.
  2968. */
  2969. var SHA256 = C_algo.SHA256 = Hasher.extend({
  2970. _doReset: function () {
  2971. this._hash = new WordArray.init(H.slice(0));
  2972. },
  2973.  
  2974. _doProcessBlock: function (M, offset) {
  2975. // Shortcut
  2976. var H = this._hash.words;
  2977.  
  2978. // Working variables
  2979. var a = H[0];
  2980. var b = H[1];
  2981. var c = H[2];
  2982. var d = H[3];
  2983. var e = H[4];
  2984. var f = H[5];
  2985. var g = H[6];
  2986. var h = H[7];
  2987.  
  2988. // Computation
  2989. for (var i = 0; i < 64; i++) {
  2990. if (i < 16) {
  2991. W[i] = M[offset + i] | 0;
  2992. } else {
  2993. var gamma0x = W[i - 15];
  2994. var gamma0 = ((gamma0x << 25) | (gamma0x >>> 7)) ^
  2995. ((gamma0x << 14) | (gamma0x >>> 18)) ^
  2996. (gamma0x >>> 3);
  2997.  
  2998. var gamma1x = W[i - 2];
  2999. var gamma1 = ((gamma1x << 15) | (gamma1x >>> 17)) ^
  3000. ((gamma1x << 13) | (gamma1x >>> 19)) ^
  3001. (gamma1x >>> 10);
  3002.  
  3003. W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16];
  3004. }
  3005.  
  3006. var ch = (e & f) ^ (~e & g);
  3007. var maj = (a & b) ^ (a & c) ^ (b & c);
  3008.  
  3009. var sigma0 = ((a << 30) | (a >>> 2)) ^ ((a << 19) | (a >>> 13)) ^ ((a << 10) | (a >>> 22));
  3010. var sigma1 = ((e << 26) | (e >>> 6)) ^ ((e << 21) | (e >>> 11)) ^ ((e << 7) | (e >>> 25));
  3011.  
  3012. var t1 = h + sigma1 + ch + K[i] + W[i];
  3013. var t2 = sigma0 + maj;
  3014.  
  3015. h = g;
  3016. g = f;
  3017. f = e;
  3018. e = (d + t1) | 0;
  3019. d = c;
  3020. c = b;
  3021. b = a;
  3022. a = (t1 + t2) | 0;
  3023. }
  3024.  
  3025. // Intermediate hash value
  3026. H[0] = (H[0] + a) | 0;
  3027. H[1] = (H[1] + b) | 0;
  3028. H[2] = (H[2] + c) | 0;
  3029. H[3] = (H[3] + d) | 0;
  3030. H[4] = (H[4] + e) | 0;
  3031. H[5] = (H[5] + f) | 0;
  3032. H[6] = (H[6] + g) | 0;
  3033. H[7] = (H[7] + h) | 0;
  3034. },
  3035.  
  3036. _doFinalize: function () {
  3037. // Shortcuts
  3038. var data = this._data;
  3039. var dataWords = data.words;
  3040.  
  3041. var nBitsTotal = this._nDataBytes * 8;
  3042. var nBitsLeft = data.sigBytes * 8;
  3043.  
  3044. // Add padding
  3045. dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32);
  3046. dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = Math.floor(nBitsTotal / 0x100000000);
  3047. dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 15] = nBitsTotal;
  3048. data.sigBytes = dataWords.length * 4;
  3049.  
  3050. // Hash final blocks
  3051. this._process();
  3052.  
  3053. // Return final computed hash
  3054. return this._hash;
  3055. },
  3056.  
  3057. clone: function () {
  3058. var clone = Hasher.clone.call(this);
  3059. clone._hash = this._hash.clone();
  3060.  
  3061. return clone;
  3062. }
  3063. });
  3064.  
  3065. /**
  3066. * Shortcut function to the hasher's object interface.
  3067. *
  3068. * @param {WordArray|string} message The message to hash.
  3069. *
  3070. * @return {WordArray} The hash.
  3071. *
  3072. * @static
  3073. *
  3074. * @example
  3075. *
  3076. * var hash = CryptoJS.SHA256('message');
  3077. * var hash = CryptoJS.SHA256(wordArray);
  3078. */
  3079. C.SHA256 = Hasher._createHelper(SHA256);
  3080.  
  3081. /**
  3082. * Shortcut function to the HMAC's object interface.
  3083. *
  3084. * @param {WordArray|string} message The message to hash.
  3085. * @param {WordArray|string} key The secret key.
  3086. *
  3087. * @return {WordArray} The HMAC.
  3088. *
  3089. * @static
  3090. *
  3091. * @example
  3092. *
  3093. * var hmac = CryptoJS.HmacSHA256(message, key);
  3094. */
  3095. C.HmacSHA256 = Hasher._createHmacHelper(SHA256);
  3096. }(Math));
  3097.  
  3098.  
  3099. return CryptoJS.SHA256;
  3100.  
  3101. }));
  3102. },{"./core":32}],37:[function(require,module,exports){
  3103. (function (root, factory) {
  3104. if (typeof exports === 'object') {
  3105. module.exports = factory();
  3106. } else if (typeof define === 'function' && define.amd) {
  3107. define([], factory);
  3108. } else {
  3109. root.urltemplate = factory();
  3110. }
  3111. }(this, function () {
  3112. /**
  3113. * @constructor
  3114. */
  3115. function UrlTemplate() {
  3116. }
  3117.  
  3118. /**
  3119. * @private
  3120. * @param {string} str
  3121. * @return {string}
  3122. */
  3123. UrlTemplate.prototype.encodeReserved = function (str) {
  3124. return str.split(/(%[0-9A-Fa-f]{2})/g).map(function (part) {
  3125. if (!/%[0-9A-Fa-f]/.test(part)) {
  3126. part = encodeURI(part).replace(/%5B/g, '[').replace(/%5D/g, ']');
  3127. }
  3128. return part;
  3129. }).join('');
  3130. };
  3131.  
  3132. /**
  3133. * @private
  3134. * @param {string} str
  3135. * @return {string}
  3136. */
  3137. UrlTemplate.prototype.encodeUnreserved = function (str) {
  3138. return encodeURIComponent(str).replace(/[!'()*]/g, function (c) {
  3139. return '%' + c.charCodeAt(0).toString(16).toUpperCase();
  3140. });
  3141. }
  3142.  
  3143. /**
  3144. * @private
  3145. * @param {string} operator
  3146. * @param {string} value
  3147. * @param {string} key
  3148. * @return {string}
  3149. */
  3150. UrlTemplate.prototype.encodeValue = function (operator, value, key) {
  3151. value = (operator === '+' || operator === '#') ? this.encodeReserved(value) : this.encodeUnreserved(value);
  3152.  
  3153. if (key) {
  3154. return this.encodeUnreserved(key) + '=' + value;
  3155. } else {
  3156. return value;
  3157. }
  3158. };
  3159.  
  3160. /**
  3161. * @private
  3162. * @param {*} value
  3163. * @return {boolean}
  3164. */
  3165. UrlTemplate.prototype.isDefined = function (value) {
  3166. return value !== undefined && value !== null;
  3167. };
  3168.  
  3169. /**
  3170. * @private
  3171. * @param {string}
  3172. * @return {boolean}
  3173. */
  3174. UrlTemplate.prototype.isKeyOperator = function (operator) {
  3175. return operator === ';' || operator === '&' || operator === '?';
  3176. };
  3177.  
  3178. /**
  3179. * @private
  3180. * @param {Object} context
  3181. * @param {string} operator
  3182. * @param {string} key
  3183. * @param {string} modifier
  3184. */
  3185. UrlTemplate.prototype.getValues = function (context, operator, key, modifier) {
  3186. var value = context[key],
  3187. result = [];
  3188.  
  3189. if (this.isDefined(value) && value !== '') {
  3190. if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {
  3191. value = value.toString();
  3192.  
  3193. if (modifier && modifier !== '*') {
  3194. value = value.substring(0, parseInt(modifier, 10));
  3195. }
  3196.  
  3197. result.push(this.encodeValue(operator, value, this.isKeyOperator(operator) ? key : null));
  3198. } else {
  3199. if (modifier === '*') {
  3200. if (Array.isArray(value)) {
  3201. value.filter(this.isDefined).forEach(function (value) {
  3202. result.push(this.encodeValue(operator, value, this.isKeyOperator(operator) ? key : null));
  3203. }, this);
  3204. } else {
  3205. Object.keys(value).forEach(function (k) {
  3206. if (this.isDefined(value[k])) {
  3207. result.push(this.encodeValue(operator, value[k], k));
  3208. }
  3209. }, this);
  3210. }
  3211. } else {
  3212. var tmp = [];
  3213.  
  3214. if (Array.isArray(value)) {
  3215. value.filter(this.isDefined).forEach(function (value) {
  3216. tmp.push(this.encodeValue(operator, value));
  3217. }, this);
  3218. } else {
  3219. Object.keys(value).forEach(function (k) {
  3220. if (this.isDefined(value[k])) {
  3221. tmp.push(this.encodeUnreserved(k));
  3222. tmp.push(this.encodeValue(operator, value[k].toString()));
  3223. }
  3224. }, this);
  3225. }
  3226.  
  3227. if (this.isKeyOperator(operator)) {
  3228. result.push(this.encodeUnreserved(key) + '=' + tmp.join(','));
  3229. } else if (tmp.length !== 0) {
  3230. result.push(tmp.join(','));
  3231. }
  3232. }
  3233. }
  3234. } else {
  3235. if (operator === ';') {
  3236. if (this.isDefined(value)) {
  3237. result.push(this.encodeUnreserved(key));
  3238. }
  3239. } else if (value === '' && (operator === '&' || operator === '?')) {
  3240. result.push(this.encodeUnreserved(key) + '=');
  3241. } else if (value === '') {
  3242. result.push('');
  3243. }
  3244. }
  3245. return result;
  3246. };
  3247.  
  3248. /**
  3249. * @param {string} template
  3250. * @return {function(Object):string}
  3251. */
  3252. UrlTemplate.prototype.parse = function (template) {
  3253. var that = this;
  3254. var operators = ['+', '#', '.', '/', ';', '?', '&'];
  3255.  
  3256. return {
  3257. expand: function (context) {
  3258. return template.replace(/\{([^\{\}]+)\}|([^\{\}]+)/g, function (_, expression, literal) {
  3259. if (expression) {
  3260. var operator = null,
  3261. values = [];
  3262.  
  3263. if (operators.indexOf(expression.charAt(0)) !== -1) {
  3264. operator = expression.charAt(0);
  3265. expression = expression.substr(1);
  3266. }
  3267.  
  3268. expression.split(/,/g).forEach(function (variable) {
  3269. var tmp = /([^:\*]*)(?::(\d+)|(\*))?/.exec(variable);
  3270. values.push.apply(values, that.getValues(context, operator, tmp[1], tmp[2] || tmp[3]));
  3271. });
  3272.  
  3273. if (operator && operator !== '+') {
  3274. var separator = ',';
  3275.  
  3276. if (operator === '?') {
  3277. separator = '&';
  3278. } else if (operator !== '#') {
  3279. separator = operator;
  3280. }
  3281. return (values.length !== 0 ? operator : '') + values.join(separator);
  3282. } else {
  3283. return values.join(',');
  3284. }
  3285. } else {
  3286. return that.encodeReserved(literal);
  3287. }
  3288. });
  3289. }
  3290. };
  3291. };
  3292.  
  3293. return new UrlTemplate();
  3294. }));
  3295.  
  3296. },{}],38:[function(require,module,exports){
  3297. (function (process,global){
  3298. /* @preserve
  3299. * The MIT License (MIT)
  3300. *
  3301. * Copyright (c) 2013-2015 Petka Antonov
  3302. *
  3303. * Permission is hereby granted, free of charge, to any person obtaining a copy
  3304. * of this software and associated documentation files (the "Software"), to deal
  3305. * in the Software without restriction, including without limitation the rights
  3306. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  3307. * copies of the Software, and to permit persons to whom the Software is
  3308. * furnished to do so, subject to the following conditions:
  3309. *
  3310. * The above copyright notice and this permission notice shall be included in
  3311. * all copies or substantial portions of the Software.
  3312. *
  3313. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  3314. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  3315. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  3316. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  3317. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  3318. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  3319. * THE SOFTWARE.
  3320. *
  3321. */
  3322. /**
  3323. * bluebird build version 3.4.7
  3324. * Features enabled: core, race, call_get, generators, map, nodeify, promisify, props, reduce, settle, some, using, timers, filter, any, each
  3325. */
  3326. !function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.Promise=e()}}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof _dereq_=="function"&&_dereq_;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof _dereq_=="function"&&_dereq_;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){
  3327. "use strict";
  3328. module.exports = function(Promise) {
  3329. var SomePromiseArray = Promise._SomePromiseArray;
  3330. function any(promises) {
  3331. var ret = new SomePromiseArray(promises);
  3332. var promise = ret.promise();
  3333. ret.setHowMany(1);
  3334. ret.setUnwrap();
  3335. ret.init();
  3336. return promise;
  3337. }
  3338.  
  3339. Promise.any = function (promises) {
  3340. return any(promises);
  3341. };
  3342.  
  3343. Promise.prototype.any = function () {
  3344. return any(this);
  3345. };
  3346.  
  3347. };
  3348.  
  3349. },{}],2:[function(_dereq_,module,exports){
  3350. "use strict";
  3351. var firstLineError;
  3352. try {throw new Error(); } catch (e) {firstLineError = e;}
  3353. var schedule = _dereq_("./schedule");
  3354. var Queue = _dereq_("./queue");
  3355. var util = _dereq_("./util");
  3356.  
  3357. function Async() {
  3358. this._customScheduler = false;
  3359. this._isTickUsed = false;
  3360. this._lateQueue = new Queue(16);
  3361. this._normalQueue = new Queue(16);
  3362. this._haveDrainedQueues = false;
  3363. this._trampolineEnabled = true;
  3364. var self = this;
  3365. this.drainQueues = function () {
  3366. self._drainQueues();
  3367. };
  3368. this._schedule = schedule;
  3369. }
  3370.  
  3371. Async.prototype.setScheduler = function(fn) {
  3372. var prev = this._schedule;
  3373. this._schedule = fn;
  3374. this._customScheduler = true;
  3375. return prev;
  3376. };
  3377.  
  3378. Async.prototype.hasCustomScheduler = function() {
  3379. return this._customScheduler;
  3380. };
  3381.  
  3382. Async.prototype.enableTrampoline = function() {
  3383. this._trampolineEnabled = true;
  3384. };
  3385.  
  3386. Async.prototype.disableTrampolineIfNecessary = function() {
  3387. if (util.hasDevTools) {
  3388. this._trampolineEnabled = false;
  3389. }
  3390. };
  3391.  
  3392. Async.prototype.haveItemsQueued = function () {
  3393. return this._isTickUsed || this._haveDrainedQueues;
  3394. };
  3395.  
  3396.  
  3397. Async.prototype.fatalError = function(e, isNode) {
  3398. if (isNode) {
  3399. process.stderr.write("Fatal " + (e instanceof Error ? e.stack : e) +
  3400. "\n");
  3401. process.exit(2);
  3402. } else {
  3403. this.throwLater(e);
  3404. }
  3405. };
  3406.  
  3407. Async.prototype.throwLater = function(fn, arg) {
  3408. if (arguments.length === 1) {
  3409. arg = fn;
  3410. fn = function () { throw arg; };
  3411. }
  3412. if (typeof setTimeout !== "undefined") {
  3413. setTimeout(function() {
  3414. fn(arg);
  3415. }, 0);
  3416. } else try {
  3417. this._schedule(function() {
  3418. fn(arg);
  3419. });
  3420. } catch (e) {
  3421. throw new Error("No async scheduler available\u000a\u000a See http://goo.gl/MqrFmX\u000a");
  3422. }
  3423. };
  3424.  
  3425. function AsyncInvokeLater(fn, receiver, arg) {
  3426. this._lateQueue.push(fn, receiver, arg);
  3427. this._queueTick();
  3428. }
  3429.  
  3430. function AsyncInvoke(fn, receiver, arg) {
  3431. this._normalQueue.push(fn, receiver, arg);
  3432. this._queueTick();
  3433. }
  3434.  
  3435. function AsyncSettlePromises(promise) {
  3436. this._normalQueue._pushOne(promise);
  3437. this._queueTick();
  3438. }
  3439.  
  3440. if (!util.hasDevTools) {
  3441. Async.prototype.invokeLater = AsyncInvokeLater;
  3442. Async.prototype.invoke = AsyncInvoke;
  3443. Async.prototype.settlePromises = AsyncSettlePromises;
  3444. } else {
  3445. Async.prototype.invokeLater = function (fn, receiver, arg) {
  3446. if (this._trampolineEnabled) {
  3447. AsyncInvokeLater.call(this, fn, receiver, arg);
  3448. } else {
  3449. this._schedule(function() {
  3450. setTimeout(function() {
  3451. fn.call(receiver, arg);
  3452. }, 100);
  3453. });
  3454. }
  3455. };
  3456.  
  3457. Async.prototype.invoke = function (fn, receiver, arg) {
  3458. if (this._trampolineEnabled) {
  3459. AsyncInvoke.call(this, fn, receiver, arg);
  3460. } else {
  3461. this._schedule(function() {
  3462. fn.call(receiver, arg);
  3463. });
  3464. }
  3465. };
  3466.  
  3467. Async.prototype.settlePromises = function(promise) {
  3468. if (this._trampolineEnabled) {
  3469. AsyncSettlePromises.call(this, promise);
  3470. } else {
  3471. this._schedule(function() {
  3472. promise._settlePromises();
  3473. });
  3474. }
  3475. };
  3476. }
  3477.  
  3478. Async.prototype._drainQueue = function(queue) {
  3479. while (queue.length() > 0) {
  3480. var fn = queue.shift();
  3481. if (typeof fn !== "function") {
  3482. fn._settlePromises();
  3483. continue;
  3484. }
  3485. var receiver = queue.shift();
  3486. var arg = queue.shift();
  3487. fn.call(receiver, arg);
  3488. }
  3489. };
  3490.  
  3491. Async.prototype._drainQueues = function () {
  3492. this._drainQueue(this._normalQueue);
  3493. this._reset();
  3494. this._haveDrainedQueues = true;
  3495. this._drainQueue(this._lateQueue);
  3496. };
  3497.  
  3498. Async.prototype._queueTick = function () {
  3499. if (!this._isTickUsed) {
  3500. this._isTickUsed = true;
  3501. this._schedule(this.drainQueues);
  3502. }
  3503. };
  3504.  
  3505. Async.prototype._reset = function () {
  3506. this._isTickUsed = false;
  3507. };
  3508.  
  3509. module.exports = Async;
  3510. module.exports.firstLineError = firstLineError;
  3511.  
  3512. },{"./queue":26,"./schedule":29,"./util":36}],3:[function(_dereq_,module,exports){
  3513. "use strict";
  3514. module.exports = function(Promise, INTERNAL, tryConvertToPromise, debug) {
  3515. var calledBind = false;
  3516. var rejectThis = function(_, e) {
  3517. this._reject(e);
  3518. };
  3519.  
  3520. var targetRejected = function(e, context) {
  3521. context.promiseRejectionQueued = true;
  3522. context.bindingPromise._then(rejectThis, rejectThis, null, this, e);
  3523. };
  3524.  
  3525. var bindingResolved = function(thisArg, context) {
  3526. if (((this._bitField & 50397184) === 0)) {
  3527. this._resolveCallback(context.target);
  3528. }
  3529. };
  3530.  
  3531. var bindingRejected = function(e, context) {
  3532. if (!context.promiseRejectionQueued) this._reject(e);
  3533. };
  3534.  
  3535. Promise.prototype.bind = function (thisArg) {
  3536. if (!calledBind) {
  3537. calledBind = true;
  3538. Promise.prototype._propagateFrom = debug.propagateFromFunction();
  3539. Promise.prototype._boundValue = debug.boundValueFunction();
  3540. }
  3541. var maybePromise = tryConvertToPromise(thisArg);
  3542. var ret = new Promise(INTERNAL);
  3543. ret._propagateFrom(this, 1);
  3544. var target = this._target();
  3545. ret._setBoundTo(maybePromise);
  3546. if (maybePromise instanceof Promise) {
  3547. var context = {
  3548. promiseRejectionQueued: false,
  3549. promise: ret,
  3550. target: target,
  3551. bindingPromise: maybePromise
  3552. };
  3553. target._then(INTERNAL, targetRejected, undefined, ret, context);
  3554. maybePromise._then(
  3555. bindingResolved, bindingRejected, undefined, ret, context);
  3556. ret._setOnCancel(maybePromise);
  3557. } else {
  3558. ret._resolveCallback(target);
  3559. }
  3560. return ret;
  3561. };
  3562.  
  3563. Promise.prototype._setBoundTo = function (obj) {
  3564. if (obj !== undefined) {
  3565. this._bitField = this._bitField | 2097152;
  3566. this._boundTo = obj;
  3567. } else {
  3568. this._bitField = this._bitField & (~2097152);
  3569. }
  3570. };
  3571.  
  3572. Promise.prototype._isBound = function () {
  3573. return (this._bitField & 2097152) === 2097152;
  3574. };
  3575.  
  3576. Promise.bind = function (thisArg, value) {
  3577. return Promise.resolve(value).bind(thisArg);
  3578. };
  3579. };
  3580.  
  3581. },{}],4:[function(_dereq_,module,exports){
  3582. "use strict";
  3583. var old;
  3584. if (typeof Promise !== "undefined") old = Promise;
  3585. function noConflict() {
  3586. try { if (Promise === bluebird) Promise = old; }
  3587. catch (e) {}
  3588. return bluebird;
  3589. }
  3590. var bluebird = _dereq_("./promise")();
  3591. bluebird.noConflict = noConflict;
  3592. module.exports = bluebird;
  3593.  
  3594. },{"./promise":22}],5:[function(_dereq_,module,exports){
  3595. "use strict";
  3596. var cr = Object.create;
  3597. if (cr) {
  3598. var callerCache = cr(null);
  3599. var getterCache = cr(null);
  3600. callerCache[" size"] = getterCache[" size"] = 0;
  3601. }
  3602.  
  3603. module.exports = function(Promise) {
  3604. var util = _dereq_("./util");
  3605. var canEvaluate = util.canEvaluate;
  3606. var isIdentifier = util.isIdentifier;
  3607.  
  3608. var getMethodCaller;
  3609. var getGetter;
  3610. if (!true) {
  3611. var makeMethodCaller = function (methodName) {
  3612. return new Function("ensureMethod", " \n\
  3613. return function(obj) { \n\
  3614. 'use strict' \n\
  3615. var len = this.length; \n\
  3616. ensureMethod(obj, 'methodName'); \n\
  3617. switch(len) { \n\
  3618. case 1: return obj.methodName(this[0]); \n\
  3619. case 2: return obj.methodName(this[0], this[1]); \n\
  3620. case 3: return obj.methodName(this[0], this[1], this[2]); \n\
  3621. case 0: return obj.methodName(); \n\
  3622. default: \n\
  3623. return obj.methodName.apply(obj, this); \n\
  3624. } \n\
  3625. }; \n\
  3626. ".replace(/methodName/g, methodName))(ensureMethod);
  3627. };
  3628.  
  3629. var makeGetter = function (propertyName) {
  3630. return new Function("obj", " \n\
  3631. 'use strict'; \n\
  3632. return obj.propertyName; \n\
  3633. ".replace("propertyName", propertyName));
  3634. };
  3635.  
  3636. var getCompiled = function(name, compiler, cache) {
  3637. var ret = cache[name];
  3638. if (typeof ret !== "function") {
  3639. if (!isIdentifier(name)) {
  3640. return null;
  3641. }
  3642. ret = compiler(name);
  3643. cache[name] = ret;
  3644. cache[" size"]++;
  3645. if (cache[" size"] > 512) {
  3646. var keys = Object.keys(cache);
  3647. for (var i = 0; i < 256; ++i) delete cache[keys[i]];
  3648. cache[" size"] = keys.length - 256;
  3649. }
  3650. }
  3651. return ret;
  3652. };
  3653.  
  3654. getMethodCaller = function(name) {
  3655. return getCompiled(name, makeMethodCaller, callerCache);
  3656. };
  3657.  
  3658. getGetter = function(name) {
  3659. return getCompiled(name, makeGetter, getterCache);
  3660. };
  3661. }
  3662.  
  3663. function ensureMethod(obj, methodName) {
  3664. var fn;
  3665. if (obj != null) fn = obj[methodName];
  3666. if (typeof fn !== "function") {
  3667. var message = "Object " + util.classString(obj) + " has no method '" +
  3668. util.toString(methodName) + "'";
  3669. throw new Promise.TypeError(message);
  3670. }
  3671. return fn;
  3672. }
  3673.  
  3674. function caller(obj) {
  3675. var methodName = this.pop();
  3676. var fn = ensureMethod(obj, methodName);
  3677. return fn.apply(obj, this);
  3678. }
  3679. Promise.prototype.call = function (methodName) {
  3680. var args = [].slice.call(arguments, 1);;
  3681. if (!true) {
  3682. if (canEvaluate) {
  3683. var maybeCaller = getMethodCaller(methodName);
  3684. if (maybeCaller !== null) {
  3685. return this._then(
  3686. maybeCaller, undefined, undefined, args, undefined);
  3687. }
  3688. }
  3689. }
  3690. args.push(methodName);
  3691. return this._then(caller, undefined, undefined, args, undefined);
  3692. };
  3693.  
  3694. function namedGetter(obj) {
  3695. return obj[this];
  3696. }
  3697. function indexedGetter(obj) {
  3698. var index = +this;
  3699. if (index < 0) index = Math.max(0, index + obj.length);
  3700. return obj[index];
  3701. }
  3702. Promise.prototype.get = function (propertyName) {
  3703. var isIndex = (typeof propertyName === "number");
  3704. var getter;
  3705. if (!isIndex) {
  3706. if (canEvaluate) {
  3707. var maybeGetter = getGetter(propertyName);
  3708. getter = maybeGetter !== null ? maybeGetter : namedGetter;
  3709. } else {
  3710. getter = namedGetter;
  3711. }
  3712. } else {
  3713. getter = indexedGetter;
  3714. }
  3715. return this._then(getter, undefined, undefined, propertyName, undefined);
  3716. };
  3717. };
  3718.  
  3719. },{"./util":36}],6:[function(_dereq_,module,exports){
  3720. "use strict";
  3721. module.exports = function(Promise, PromiseArray, apiRejection, debug) {
  3722. var util = _dereq_("./util");
  3723. var tryCatch = util.tryCatch;
  3724. var errorObj = util.errorObj;
  3725. var async = Promise._async;
  3726.  
  3727. Promise.prototype["break"] = Promise.prototype.cancel = function() {
  3728. if (!debug.cancellation()) return this._warn("cancellation is disabled");
  3729.  
  3730. var promise = this;
  3731. var child = promise;
  3732. while (promise._isCancellable()) {
  3733. if (!promise._cancelBy(child)) {
  3734. if (child._isFollowing()) {
  3735. child._followee().cancel();
  3736. } else {
  3737. child._cancelBranched();
  3738. }
  3739. break;
  3740. }
  3741.  
  3742. var parent = promise._cancellationParent;
  3743. if (parent == null || !parent._isCancellable()) {
  3744. if (promise._isFollowing()) {
  3745. promise._followee().cancel();
  3746. } else {
  3747. promise._cancelBranched();
  3748. }
  3749. break;
  3750. } else {
  3751. if (promise._isFollowing()) promise._followee().cancel();
  3752. promise._setWillBeCancelled();
  3753. child = promise;
  3754. promise = parent;
  3755. }
  3756. }
  3757. };
  3758.  
  3759. Promise.prototype._branchHasCancelled = function() {
  3760. this._branchesRemainingToCancel--;
  3761. };
  3762.  
  3763. Promise.prototype._enoughBranchesHaveCancelled = function() {
  3764. return this._branchesRemainingToCancel === undefined ||
  3765. this._branchesRemainingToCancel <= 0;
  3766. };
  3767.  
  3768. Promise.prototype._cancelBy = function(canceller) {
  3769. if (canceller === this) {
  3770. this._branchesRemainingToCancel = 0;
  3771. this._invokeOnCancel();
  3772. return true;
  3773. } else {
  3774. this._branchHasCancelled();
  3775. if (this._enoughBranchesHaveCancelled()) {
  3776. this._invokeOnCancel();
  3777. return true;
  3778. }
  3779. }
  3780. return false;
  3781. };
  3782.  
  3783. Promise.prototype._cancelBranched = function() {
  3784. if (this._enoughBranchesHaveCancelled()) {
  3785. this._cancel();
  3786. }
  3787. };
  3788.  
  3789. Promise.prototype._cancel = function() {
  3790. if (!this._isCancellable()) return;
  3791. this._setCancelled();
  3792. async.invoke(this._cancelPromises, this, undefined);
  3793. };
  3794.  
  3795. Promise.prototype._cancelPromises = function() {
  3796. if (this._length() > 0) this._settlePromises();
  3797. };
  3798.  
  3799. Promise.prototype._unsetOnCancel = function() {
  3800. this._onCancelField = undefined;
  3801. };
  3802.  
  3803. Promise.prototype._isCancellable = function() {
  3804. return this.isPending() && !this._isCancelled();
  3805. };
  3806.  
  3807. Promise.prototype.isCancellable = function() {
  3808. return this.isPending() && !this.isCancelled();
  3809. };
  3810.  
  3811. Promise.prototype._doInvokeOnCancel = function(onCancelCallback, internalOnly) {
  3812. if (util.isArray(onCancelCallback)) {
  3813. for (var i = 0; i < onCancelCallback.length; ++i) {
  3814. this._doInvokeOnCancel(onCancelCallback[i], internalOnly);
  3815. }
  3816. } else if (onCancelCallback !== undefined) {
  3817. if (typeof onCancelCallback === "function") {
  3818. if (!internalOnly) {
  3819. var e = tryCatch(onCancelCallback).call(this._boundValue());
  3820. if (e === errorObj) {
  3821. this._attachExtraTrace(e.e);
  3822. async.throwLater(e.e);
  3823. }
  3824. }
  3825. } else {
  3826. onCancelCallback._resultCancelled(this);
  3827. }
  3828. }
  3829. };
  3830.  
  3831. Promise.prototype._invokeOnCancel = function() {
  3832. var onCancelCallback = this._onCancel();
  3833. this._unsetOnCancel();
  3834. async.invoke(this._doInvokeOnCancel, this, onCancelCallback);
  3835. };
  3836.  
  3837. Promise.prototype._invokeInternalOnCancel = function() {
  3838. if (this._isCancellable()) {
  3839. this._doInvokeOnCancel(this._onCancel(), true);
  3840. this._unsetOnCancel();
  3841. }
  3842. };
  3843.  
  3844. Promise.prototype._resultCancelled = function() {
  3845. this.cancel();
  3846. };
  3847.  
  3848. };
  3849.  
  3850. },{"./util":36}],7:[function(_dereq_,module,exports){
  3851. "use strict";
  3852. module.exports = function(NEXT_FILTER) {
  3853. var util = _dereq_("./util");
  3854. var getKeys = _dereq_("./es5").keys;
  3855. var tryCatch = util.tryCatch;
  3856. var errorObj = util.errorObj;
  3857.  
  3858. function catchFilter(instances, cb, promise) {
  3859. return function(e) {
  3860. var boundTo = promise._boundValue();
  3861. predicateLoop: for (var i = 0; i < instances.length; ++i) {
  3862. var item = instances[i];
  3863.  
  3864. if (item === Error ||
  3865. (item != null && item.prototype instanceof Error)) {
  3866. if (e instanceof item) {
  3867. return tryCatch(cb).call(boundTo, e);
  3868. }
  3869. } else if (typeof item === "function") {
  3870. var matchesPredicate = tryCatch(item).call(boundTo, e);
  3871. if (matchesPredicate === errorObj) {
  3872. return matchesPredicate;
  3873. } else if (matchesPredicate) {
  3874. return tryCatch(cb).call(boundTo, e);
  3875. }
  3876. } else if (util.isObject(e)) {
  3877. var keys = getKeys(item);
  3878. for (var j = 0; j < keys.length; ++j) {
  3879. var key = keys[j];
  3880. if (item[key] != e[key]) {
  3881. continue predicateLoop;
  3882. }
  3883. }
  3884. return tryCatch(cb).call(boundTo, e);
  3885. }
  3886. }
  3887. return NEXT_FILTER;
  3888. };
  3889. }
  3890.  
  3891. return catchFilter;
  3892. };
  3893.  
  3894. },{"./es5":13,"./util":36}],8:[function(_dereq_,module,exports){
  3895. "use strict";
  3896. module.exports = function(Promise) {
  3897. var longStackTraces = false;
  3898. var contextStack = [];
  3899.  
  3900. Promise.prototype._promiseCreated = function() {};
  3901. Promise.prototype._pushContext = function() {};
  3902. Promise.prototype._popContext = function() {return null;};
  3903. Promise._peekContext = Promise.prototype._peekContext = function() {};
  3904.  
  3905. function Context() {
  3906. this._trace = new Context.CapturedTrace(peekContext());
  3907. }
  3908. Context.prototype._pushContext = function () {
  3909. if (this._trace !== undefined) {
  3910. this._trace._promiseCreated = null;
  3911. contextStack.push(this._trace);
  3912. }
  3913. };
  3914.  
  3915. Context.prototype._popContext = function () {
  3916. if (this._trace !== undefined) {
  3917. var trace = contextStack.pop();
  3918. var ret = trace._promiseCreated;
  3919. trace._promiseCreated = null;
  3920. return ret;
  3921. }
  3922. return null;
  3923. };
  3924.  
  3925. function createContext() {
  3926. if (longStackTraces) return new Context();
  3927. }
  3928.  
  3929. function peekContext() {
  3930. var lastIndex = contextStack.length - 1;
  3931. if (lastIndex >= 0) {
  3932. return contextStack[lastIndex];
  3933. }
  3934. return undefined;
  3935. }
  3936. Context.CapturedTrace = null;
  3937. Context.create = createContext;
  3938. Context.deactivateLongStackTraces = function() {};
  3939. Context.activateLongStackTraces = function() {
  3940. var Promise_pushContext = Promise.prototype._pushContext;
  3941. var Promise_popContext = Promise.prototype._popContext;
  3942. var Promise_PeekContext = Promise._peekContext;
  3943. var Promise_peekContext = Promise.prototype._peekContext;
  3944. var Promise_promiseCreated = Promise.prototype._promiseCreated;
  3945. Context.deactivateLongStackTraces = function() {
  3946. Promise.prototype._pushContext = Promise_pushContext;
  3947. Promise.prototype._popContext = Promise_popContext;
  3948. Promise._peekContext = Promise_PeekContext;
  3949. Promise.prototype._peekContext = Promise_peekContext;
  3950. Promise.prototype._promiseCreated = Promise_promiseCreated;
  3951. longStackTraces = false;
  3952. };
  3953. longStackTraces = true;
  3954. Promise.prototype._pushContext = Context.prototype._pushContext;
  3955. Promise.prototype._popContext = Context.prototype._popContext;
  3956. Promise._peekContext = Promise.prototype._peekContext = peekContext;
  3957. Promise.prototype._promiseCreated = function() {
  3958. var ctx = this._peekContext();
  3959. if (ctx && ctx._promiseCreated == null) ctx._promiseCreated = this;
  3960. };
  3961. };
  3962. return Context;
  3963. };
  3964.  
  3965. },{}],9:[function(_dereq_,module,exports){
  3966. "use strict";
  3967. module.exports = function(Promise, Context) {
  3968. var getDomain = Promise._getDomain;
  3969. var async = Promise._async;
  3970. var Warning = _dereq_("./errors").Warning;
  3971. var util = _dereq_("./util");
  3972. var canAttachTrace = util.canAttachTrace;
  3973. var unhandledRejectionHandled;
  3974. var possiblyUnhandledRejection;
  3975. var bluebirdFramePattern =
  3976. /[\\\/]bluebird[\\\/]js[\\\/](release|debug|instrumented)/;
  3977. var nodeFramePattern = /\((?:timers\.js):\d+:\d+\)/;
  3978. var parseLinePattern = /[\/<\(](.+?):(\d+):(\d+)\)?\s*$/;
  3979. var stackFramePattern = null;
  3980. var formatStack = null;
  3981. var indentStackFrames = false;
  3982. var printWarning;
  3983. var debugging = !!(util.env("BLUEBIRD_DEBUG") != 0 &&
  3984. (true ||
  3985. util.env("BLUEBIRD_DEBUG") ||
  3986. util.env("NODE_ENV") === "development"));
  3987.  
  3988. var warnings = !!(util.env("BLUEBIRD_WARNINGS") != 0 &&
  3989. (debugging || util.env("BLUEBIRD_WARNINGS")));
  3990.  
  3991. var longStackTraces = !!(util.env("BLUEBIRD_LONG_STACK_TRACES") != 0 &&
  3992. (debugging || util.env("BLUEBIRD_LONG_STACK_TRACES")));
  3993.  
  3994. var wForgottenReturn = util.env("BLUEBIRD_W_FORGOTTEN_RETURN") != 0 &&
  3995. (warnings || !!util.env("BLUEBIRD_W_FORGOTTEN_RETURN"));
  3996.  
  3997. Promise.prototype.suppressUnhandledRejections = function() {
  3998. var target = this._target();
  3999. target._bitField = ((target._bitField & (~1048576)) |
  4000. 524288);
  4001. };
  4002.  
  4003. Promise.prototype._ensurePossibleRejectionHandled = function () {
  4004. if ((this._bitField & 524288) !== 0) return;
  4005. this._setRejectionIsUnhandled();
  4006. async.invokeLater(this._notifyUnhandledRejection, this, undefined);
  4007. };
  4008.  
  4009. Promise.prototype._notifyUnhandledRejectionIsHandled = function () {
  4010. fireRejectionEvent("rejectionHandled",
  4011. unhandledRejectionHandled, undefined, this);
  4012. };
  4013.  
  4014. Promise.prototype._setReturnedNonUndefined = function() {
  4015. this._bitField = this._bitField | 268435456;
  4016. };
  4017.  
  4018. Promise.prototype._returnedNonUndefined = function() {
  4019. return (this._bitField & 268435456) !== 0;
  4020. };
  4021.  
  4022. Promise.prototype._notifyUnhandledRejection = function () {
  4023. if (this._isRejectionUnhandled()) {
  4024. var reason = this._settledValue();
  4025. this._setUnhandledRejectionIsNotified();
  4026. fireRejectionEvent("unhandledRejection",
  4027. possiblyUnhandledRejection, reason, this);
  4028. }
  4029. };
  4030.  
  4031. Promise.prototype._setUnhandledRejectionIsNotified = function () {
  4032. this._bitField = this._bitField | 262144;
  4033. };
  4034.  
  4035. Promise.prototype._unsetUnhandledRejectionIsNotified = function () {
  4036. this._bitField = this._bitField & (~262144);
  4037. };
  4038.  
  4039. Promise.prototype._isUnhandledRejectionNotified = function () {
  4040. return (this._bitField & 262144) > 0;
  4041. };
  4042.  
  4043. Promise.prototype._setRejectionIsUnhandled = function () {
  4044. this._bitField = this._bitField | 1048576;
  4045. };
  4046.  
  4047. Promise.prototype._unsetRejectionIsUnhandled = function () {
  4048. this._bitField = this._bitField & (~1048576);
  4049. if (this._isUnhandledRejectionNotified()) {
  4050. this._unsetUnhandledRejectionIsNotified();
  4051. this._notifyUnhandledRejectionIsHandled();
  4052. }
  4053. };
  4054.  
  4055. Promise.prototype._isRejectionUnhandled = function () {
  4056. return (this._bitField & 1048576) > 0;
  4057. };
  4058.  
  4059. Promise.prototype._warn = function(message, shouldUseOwnTrace, promise) {
  4060. return warn(message, shouldUseOwnTrace, promise || this);
  4061. };
  4062.  
  4063. Promise.onPossiblyUnhandledRejection = function (fn) {
  4064. var domain = getDomain();
  4065. possiblyUnhandledRejection =
  4066. typeof fn === "function" ? (domain === null ?
  4067. fn : util.domainBind(domain, fn))
  4068. : undefined;
  4069. };
  4070.  
  4071. Promise.onUnhandledRejectionHandled = function (fn) {
  4072. var domain = getDomain();
  4073. unhandledRejectionHandled =
  4074. typeof fn === "function" ? (domain === null ?
  4075. fn : util.domainBind(domain, fn))
  4076. : undefined;
  4077. };
  4078.  
  4079. var disableLongStackTraces = function() {};
  4080. Promise.longStackTraces = function () {
  4081. if (async.haveItemsQueued() && !config.longStackTraces) {
  4082. throw new Error("cannot enable long stack traces after promises have been created\u000a\u000a See http://goo.gl/MqrFmX\u000a");
  4083. }
  4084. if (!config.longStackTraces && longStackTracesIsSupported()) {
  4085. var Promise_captureStackTrace = Promise.prototype._captureStackTrace;
  4086. var Promise_attachExtraTrace = Promise.prototype._attachExtraTrace;
  4087. config.longStackTraces = true;
  4088. disableLongStackTraces = function() {
  4089. if (async.haveItemsQueued() && !config.longStackTraces) {
  4090. throw new Error("cannot enable long stack traces after promises have been created\u000a\u000a See http://goo.gl/MqrFmX\u000a");
  4091. }
  4092. Promise.prototype._captureStackTrace = Promise_captureStackTrace;
  4093. Promise.prototype._attachExtraTrace = Promise_attachExtraTrace;
  4094. Context.deactivateLongStackTraces();
  4095. async.enableTrampoline();
  4096. config.longStackTraces = false;
  4097. };
  4098. Promise.prototype._captureStackTrace = longStackTracesCaptureStackTrace;
  4099. Promise.prototype._attachExtraTrace = longStackTracesAttachExtraTrace;
  4100. Context.activateLongStackTraces();
  4101. async.disableTrampolineIfNecessary();
  4102. }
  4103. };
  4104.  
  4105. Promise.hasLongStackTraces = function () {
  4106. return config.longStackTraces && longStackTracesIsSupported();
  4107. };
  4108.  
  4109. var fireDomEvent = (function() {
  4110. try {
  4111. if (typeof CustomEvent === "function") {
  4112. var event = new CustomEvent("CustomEvent");
  4113. util.global.dispatchEvent(event);
  4114. return function(name, event) {
  4115. var domEvent = new CustomEvent(name.toLowerCase(), {
  4116. detail: event,
  4117. cancelable: true
  4118. });
  4119. return !util.global.dispatchEvent(domEvent);
  4120. };
  4121. } else if (typeof Event === "function") {
  4122. var event = new Event("CustomEvent");
  4123. util.global.dispatchEvent(event);
  4124. return function(name, event) {
  4125. var domEvent = new Event(name.toLowerCase(), {
  4126. cancelable: true
  4127. });
  4128. domEvent.detail = event;
  4129. return !util.global.dispatchEvent(domEvent);
  4130. };
  4131. } else {
  4132. var event = document.createEvent("CustomEvent");
  4133. event.initCustomEvent("testingtheevent", false, true, {});
  4134. util.global.dispatchEvent(event);
  4135. return function(name, event) {
  4136. var domEvent = document.createEvent("CustomEvent");
  4137. domEvent.initCustomEvent(name.toLowerCase(), false, true,
  4138. event);
  4139. return !util.global.dispatchEvent(domEvent);
  4140. };
  4141. }
  4142. } catch (e) {}
  4143. return function() {
  4144. return false;
  4145. };
  4146. })();
  4147.  
  4148. var fireGlobalEvent = (function() {
  4149. if (util.isNode) {
  4150. return function() {
  4151. return process.emit.apply(process, arguments);
  4152. };
  4153. } else {
  4154. if (!util.global) {
  4155. return function() {
  4156. return false;
  4157. };
  4158. }
  4159. return function(name) {
  4160. var methodName = "on" + name.toLowerCase();
  4161. var method = util.global[methodName];
  4162. if (!method) return false;
  4163. method.apply(util.global, [].slice.call(arguments, 1));
  4164. return true;
  4165. };
  4166. }
  4167. })();
  4168.  
  4169. function generatePromiseLifecycleEventObject(name, promise) {
  4170. return {promise: promise};
  4171. }
  4172.  
  4173. var eventToObjectGenerator = {
  4174. promiseCreated: generatePromiseLifecycleEventObject,
  4175. promiseFulfilled: generatePromiseLifecycleEventObject,
  4176. promiseRejected: generatePromiseLifecycleEventObject,
  4177. promiseResolved: generatePromiseLifecycleEventObject,
  4178. promiseCancelled: generatePromiseLifecycleEventObject,
  4179. promiseChained: function(name, promise, child) {
  4180. return {promise: promise, child: child};
  4181. },
  4182. warning: function(name, warning) {
  4183. return {warning: warning};
  4184. },
  4185. unhandledRejection: function (name, reason, promise) {
  4186. return {reason: reason, promise: promise};
  4187. },
  4188. rejectionHandled: generatePromiseLifecycleEventObject
  4189. };
  4190.  
  4191. var activeFireEvent = function (name) {
  4192. var globalEventFired = false;
  4193. try {
  4194. globalEventFired = fireGlobalEvent.apply(null, arguments);
  4195. } catch (e) {
  4196. async.throwLater(e);
  4197. globalEventFired = true;
  4198. }
  4199.  
  4200. var domEventFired = false;
  4201. try {
  4202. domEventFired = fireDomEvent(name,
  4203. eventToObjectGenerator[name].apply(null, arguments));
  4204. } catch (e) {
  4205. async.throwLater(e);
  4206. domEventFired = true;
  4207. }
  4208.  
  4209. return domEventFired || globalEventFired;
  4210. };
  4211.  
  4212. Promise.config = function(opts) {
  4213. opts = Object(opts);
  4214. if ("longStackTraces" in opts) {
  4215. if (opts.longStackTraces) {
  4216. Promise.longStackTraces();
  4217. } else if (!opts.longStackTraces && Promise.hasLongStackTraces()) {
  4218. disableLongStackTraces();
  4219. }
  4220. }
  4221. if ("warnings" in opts) {
  4222. var warningsOption = opts.warnings;
  4223. config.warnings = !!warningsOption;
  4224. wForgottenReturn = config.warnings;
  4225.  
  4226. if (util.isObject(warningsOption)) {
  4227. if ("wForgottenReturn" in warningsOption) {
  4228. wForgottenReturn = !!warningsOption.wForgottenReturn;
  4229. }
  4230. }
  4231. }
  4232. if ("cancellation" in opts && opts.cancellation && !config.cancellation) {
  4233. if (async.haveItemsQueued()) {
  4234. throw new Error(
  4235. "cannot enable cancellation after promises are in use");
  4236. }
  4237. Promise.prototype._clearCancellationData =
  4238. cancellationClearCancellationData;
  4239. Promise.prototype._propagateFrom = cancellationPropagateFrom;
  4240. Promise.prototype._onCancel = cancellationOnCancel;
  4241. Promise.prototype._setOnCancel = cancellationSetOnCancel;
  4242. Promise.prototype._attachCancellationCallback =
  4243. cancellationAttachCancellationCallback;
  4244. Promise.prototype._execute = cancellationExecute;
  4245. propagateFromFunction = cancellationPropagateFrom;
  4246. config.cancellation = true;
  4247. }
  4248. if ("monitoring" in opts) {
  4249. if (opts.monitoring && !config.monitoring) {
  4250. config.monitoring = true;
  4251. Promise.prototype._fireEvent = activeFireEvent;
  4252. } else if (!opts.monitoring && config.monitoring) {
  4253. config.monitoring = false;
  4254. Promise.prototype._fireEvent = defaultFireEvent;
  4255. }
  4256. }
  4257. return Promise;
  4258. };
  4259.  
  4260. function defaultFireEvent() { return false; }
  4261.  
  4262. Promise.prototype._fireEvent = defaultFireEvent;
  4263. Promise.prototype._execute = function(executor, resolve, reject) {
  4264. try {
  4265. executor(resolve, reject);
  4266. } catch (e) {
  4267. return e;
  4268. }
  4269. };
  4270. Promise.prototype._onCancel = function () {};
  4271. Promise.prototype._setOnCancel = function (handler) { ; };
  4272. Promise.prototype._attachCancellationCallback = function(onCancel) {
  4273. ;
  4274. };
  4275. Promise.prototype._captureStackTrace = function () {};
  4276. Promise.prototype._attachExtraTrace = function () {};
  4277. Promise.prototype._clearCancellationData = function() {};
  4278. Promise.prototype._propagateFrom = function (parent, flags) {
  4279. ;
  4280. ;
  4281. };
  4282.  
  4283. function cancellationExecute(executor, resolve, reject) {
  4284. var promise = this;
  4285. try {
  4286. executor(resolve, reject, function(onCancel) {
  4287. if (typeof onCancel !== "function") {
  4288. throw new TypeError("onCancel must be a function, got: " +
  4289. util.toString(onCancel));
  4290. }
  4291. promise._attachCancellationCallback(onCancel);
  4292. });
  4293. } catch (e) {
  4294. return e;
  4295. }
  4296. }
  4297.  
  4298. function cancellationAttachCancellationCallback(onCancel) {
  4299. if (!this._isCancellable()) return this;
  4300.  
  4301. var previousOnCancel = this._onCancel();
  4302. if (previousOnCancel !== undefined) {
  4303. if (util.isArray(previousOnCancel)) {
  4304. previousOnCancel.push(onCancel);
  4305. } else {
  4306. this._setOnCancel([previousOnCancel, onCancel]);
  4307. }
  4308. } else {
  4309. this._setOnCancel(onCancel);
  4310. }
  4311. }
  4312.  
  4313. function cancellationOnCancel() {
  4314. return this._onCancelField;
  4315. }
  4316.  
  4317. function cancellationSetOnCancel(onCancel) {
  4318. this._onCancelField = onCancel;
  4319. }
  4320.  
  4321. function cancellationClearCancellationData() {
  4322. this._cancellationParent = undefined;
  4323. this._onCancelField = undefined;
  4324. }
  4325.  
  4326. function cancellationPropagateFrom(parent, flags) {
  4327. if ((flags & 1) !== 0) {
  4328. this._cancellationParent = parent;
  4329. var branchesRemainingToCancel = parent._branchesRemainingToCancel;
  4330. if (branchesRemainingToCancel === undefined) {
  4331. branchesRemainingToCancel = 0;
  4332. }
  4333. parent._branchesRemainingToCancel = branchesRemainingToCancel + 1;
  4334. }
  4335. if ((flags & 2) !== 0 && parent._isBound()) {
  4336. this._setBoundTo(parent._boundTo);
  4337. }
  4338. }
  4339.  
  4340. function bindingPropagateFrom(parent, flags) {
  4341. if ((flags & 2) !== 0 && parent._isBound()) {
  4342. this._setBoundTo(parent._boundTo);
  4343. }
  4344. }
  4345. var propagateFromFunction = bindingPropagateFrom;
  4346.  
  4347. function boundValueFunction() {
  4348. var ret = this._boundTo;
  4349. if (ret !== undefined) {
  4350. if (ret instanceof Promise) {
  4351. if (ret.isFulfilled()) {
  4352. return ret.value();
  4353. } else {
  4354. return undefined;
  4355. }
  4356. }
  4357. }
  4358. return ret;
  4359. }
  4360.  
  4361. function longStackTracesCaptureStackTrace() {
  4362. this._trace = new CapturedTrace(this._peekContext());
  4363. }
  4364.  
  4365. function longStackTracesAttachExtraTrace(error, ignoreSelf) {
  4366. if (canAttachTrace(error)) {
  4367. var trace = this._trace;
  4368. if (trace !== undefined) {
  4369. if (ignoreSelf) trace = trace._parent;
  4370. }
  4371. if (trace !== undefined) {
  4372. trace.attachExtraTrace(error);
  4373. } else if (!error.__stackCleaned__) {
  4374. var parsed = parseStackAndMessage(error);
  4375. util.notEnumerableProp(error, "stack",
  4376. parsed.message + "\n" + parsed.stack.join("\n"));
  4377. util.notEnumerableProp(error, "__stackCleaned__", true);
  4378. }
  4379. }
  4380. }
  4381.  
  4382. function checkForgottenReturns(returnValue, promiseCreated, name, promise,
  4383. parent) {
  4384. if (returnValue === undefined && promiseCreated !== null &&
  4385. wForgottenReturn) {
  4386. if (parent !== undefined && parent._returnedNonUndefined()) return;
  4387. if ((promise._bitField & 65535) === 0) return;
  4388.  
  4389. if (name) name = name + " ";
  4390. var handlerLine = "";
  4391. var creatorLine = "";
  4392. if (promiseCreated._trace) {
  4393. var traceLines = promiseCreated._trace.stack.split("\n");
  4394. var stack = cleanStack(traceLines);
  4395. for (var i = stack.length - 1; i >= 0; --i) {
  4396. var line = stack[i];
  4397. if (!nodeFramePattern.test(line)) {
  4398. var lineMatches = line.match(parseLinePattern);
  4399. if (lineMatches) {
  4400. handlerLine = "at " + lineMatches[1] +
  4401. ":" + lineMatches[2] + ":" + lineMatches[3] + " ";
  4402. }
  4403. break;
  4404. }
  4405. }
  4406.  
  4407. if (stack.length > 0) {
  4408. var firstUserLine = stack[0];
  4409. for (var i = 0; i < traceLines.length; ++i) {
  4410.  
  4411. if (traceLines[i] === firstUserLine) {
  4412. if (i > 0) {
  4413. creatorLine = "\n" + traceLines[i - 1];
  4414. }
  4415. break;
  4416. }
  4417. }
  4418.  
  4419. }
  4420. }
  4421. var msg = "a promise was created in a " + name +
  4422. "handler " + handlerLine + "but was not returned from it, " +
  4423. "see http://goo.gl/rRqMUw" +
  4424. creatorLine;
  4425. promise._warn(msg, true, promiseCreated);
  4426. }
  4427. }
  4428.  
  4429. function deprecated(name, replacement) {
  4430. var message = name +
  4431. " is deprecated and will be removed in a future version.";
  4432. if (replacement) message += " Use " + replacement + " instead.";
  4433. return warn(message);
  4434. }
  4435.  
  4436. function warn(message, shouldUseOwnTrace, promise) {
  4437. if (!config.warnings) return;
  4438. var warning = new Warning(message);
  4439. var ctx;
  4440. if (shouldUseOwnTrace) {
  4441. promise._attachExtraTrace(warning);
  4442. } else if (config.longStackTraces && (ctx = Promise._peekContext())) {
  4443. ctx.attachExtraTrace(warning);
  4444. } else {
  4445. var parsed = parseStackAndMessage(warning);
  4446. warning.stack = parsed.message + "\n" + parsed.stack.join("\n");
  4447. }
  4448.  
  4449. if (!activeFireEvent("warning", warning)) {
  4450. formatAndLogError(warning, "", true);
  4451. }
  4452. }
  4453.  
  4454. function reconstructStack(message, stacks) {
  4455. for (var i = 0; i < stacks.length - 1; ++i) {
  4456. stacks[i].push("From previous event:");
  4457. stacks[i] = stacks[i].join("\n");
  4458. }
  4459. if (i < stacks.length) {
  4460. stacks[i] = stacks[i].join("\n");
  4461. }
  4462. return message + "\n" + stacks.join("\n");
  4463. }
  4464.  
  4465. function removeDuplicateOrEmptyJumps(stacks) {
  4466. for (var i = 0; i < stacks.length; ++i) {
  4467. if (stacks[i].length === 0 ||
  4468. ((i + 1 < stacks.length) && stacks[i][0] === stacks[i+1][0])) {
  4469. stacks.splice(i, 1);
  4470. i--;
  4471. }
  4472. }
  4473. }
  4474.  
  4475. function removeCommonRoots(stacks) {
  4476. var current = stacks[0];
  4477. for (var i = 1; i < stacks.length; ++i) {
  4478. var prev = stacks[i];
  4479. var currentLastIndex = current.length - 1;
  4480. var currentLastLine = current[currentLastIndex];
  4481. var commonRootMeetPoint = -1;
  4482.  
  4483. for (var j = prev.length - 1; j >= 0; --j) {
  4484. if (prev[j] === currentLastLine) {
  4485. commonRootMeetPoint = j;
  4486. break;
  4487. }
  4488. }
  4489.  
  4490. for (var j = commonRootMeetPoint; j >= 0; --j) {
  4491. var line = prev[j];
  4492. if (current[currentLastIndex] === line) {
  4493. current.pop();
  4494. currentLastIndex--;
  4495. } else {
  4496. break;
  4497. }
  4498. }
  4499. current = prev;
  4500. }
  4501. }
  4502.  
  4503. function cleanStack(stack) {
  4504. var ret = [];
  4505. for (var i = 0; i < stack.length; ++i) {
  4506. var line = stack[i];
  4507. var isTraceLine = " (No stack trace)" === line ||
  4508. stackFramePattern.test(line);
  4509. var isInternalFrame = isTraceLine && shouldIgnore(line);
  4510. if (isTraceLine && !isInternalFrame) {
  4511. if (indentStackFrames && line.charAt(0) !== " ") {
  4512. line = " " + line;
  4513. }
  4514. ret.push(line);
  4515. }
  4516. }
  4517. return ret;
  4518. }
  4519.  
  4520. function stackFramesAsArray(error) {
  4521. var stack = error.stack.replace(/\s+$/g, "").split("\n");
  4522. for (var i = 0; i < stack.length; ++i) {
  4523. var line = stack[i];
  4524. if (" (No stack trace)" === line || stackFramePattern.test(line)) {
  4525. break;
  4526. }
  4527. }
  4528. if (i > 0 && error.name != "SyntaxError") {
  4529. stack = stack.slice(i);
  4530. }
  4531. return stack;
  4532. }
  4533.  
  4534. function parseStackAndMessage(error) {
  4535. var stack = error.stack;
  4536. var message = error.toString();
  4537. stack = typeof stack === "string" && stack.length > 0
  4538. ? stackFramesAsArray(error) : [" (No stack trace)"];
  4539. return {
  4540. message: message,
  4541. stack: error.name == "SyntaxError" ? stack : cleanStack(stack)
  4542. };
  4543. }
  4544.  
  4545. function formatAndLogError(error, title, isSoft) {
  4546. if (typeof console !== "undefined") {
  4547. var message;
  4548. if (util.isObject(error)) {
  4549. var stack = error.stack;
  4550. message = title + formatStack(stack, error);
  4551. } else {
  4552. message = title + String(error);
  4553. }
  4554. if (typeof printWarning === "function") {
  4555. printWarning(message, isSoft);
  4556. } else if (typeof console.log === "function" ||
  4557. typeof console.log === "object") {
  4558. console.log(message);
  4559. }
  4560. }
  4561. }
  4562.  
  4563. function fireRejectionEvent(name, localHandler, reason, promise) {
  4564. var localEventFired = false;
  4565. try {
  4566. if (typeof localHandler === "function") {
  4567. localEventFired = true;
  4568. if (name === "rejectionHandled") {
  4569. localHandler(promise);
  4570. } else {
  4571. localHandler(reason, promise);
  4572. }
  4573. }
  4574. } catch (e) {
  4575. async.throwLater(e);
  4576. }
  4577.  
  4578. if (name === "unhandledRejection") {
  4579. if (!activeFireEvent(name, reason, promise) && !localEventFired) {
  4580. formatAndLogError(reason, "Unhandled rejection ");
  4581. }
  4582. } else {
  4583. activeFireEvent(name, promise);
  4584. }
  4585. }
  4586.  
  4587. function formatNonError(obj) {
  4588. var str;
  4589. if (typeof obj === "function") {
  4590. str = "[function " +
  4591. (obj.name || "anonymous") +
  4592. "]";
  4593. } else {
  4594. str = obj && typeof obj.toString === "function"
  4595. ? obj.toString() : util.toString(obj);
  4596. var ruselessToString = /\[object [a-zA-Z0-9$_]+\]/;
  4597. if (ruselessToString.test(str)) {
  4598. try {
  4599. var newStr = JSON.stringify(obj);
  4600. str = newStr;
  4601. }
  4602. catch(e) {
  4603.  
  4604. }
  4605. }
  4606. if (str.length === 0) {
  4607. str = "(empty array)";
  4608. }
  4609. }
  4610. return ("(<" + snip(str) + ">, no stack trace)");
  4611. }
  4612.  
  4613. function snip(str) {
  4614. var maxChars = 41;
  4615. if (str.length < maxChars) {
  4616. return str;
  4617. }
  4618. return str.substr(0, maxChars - 3) + "...";
  4619. }
  4620.  
  4621. function longStackTracesIsSupported() {
  4622. return typeof captureStackTrace === "function";
  4623. }
  4624.  
  4625. var shouldIgnore = function() { return false; };
  4626. var parseLineInfoRegex = /[\/<\(]([^:\/]+):(\d+):(?:\d+)\)?\s*$/;
  4627. function parseLineInfo(line) {
  4628. var matches = line.match(parseLineInfoRegex);
  4629. if (matches) {
  4630. return {
  4631. fileName: matches[1],
  4632. line: parseInt(matches[2], 10)
  4633. };
  4634. }
  4635. }
  4636.  
  4637. function setBounds(firstLineError, lastLineError) {
  4638. if (!longStackTracesIsSupported()) return;
  4639. var firstStackLines = firstLineError.stack.split("\n");
  4640. var lastStackLines = lastLineError.stack.split("\n");
  4641. var firstIndex = -1;
  4642. var lastIndex = -1;
  4643. var firstFileName;
  4644. var lastFileName;
  4645. for (var i = 0; i < firstStackLines.length; ++i) {
  4646. var result = parseLineInfo(firstStackLines[i]);
  4647. if (result) {
  4648. firstFileName = result.fileName;
  4649. firstIndex = result.line;
  4650. break;
  4651. }
  4652. }
  4653. for (var i = 0; i < lastStackLines.length; ++i) {
  4654. var result = parseLineInfo(lastStackLines[i]);
  4655. if (result) {
  4656. lastFileName = result.fileName;
  4657. lastIndex = result.line;
  4658. break;
  4659. }
  4660. }
  4661. if (firstIndex < 0 || lastIndex < 0 || !firstFileName || !lastFileName ||
  4662. firstFileName !== lastFileName || firstIndex >= lastIndex) {
  4663. return;
  4664. }
  4665.  
  4666. shouldIgnore = function(line) {
  4667. if (bluebirdFramePattern.test(line)) return true;
  4668. var info = parseLineInfo(line);
  4669. if (info) {
  4670. if (info.fileName === firstFileName &&
  4671. (firstIndex <= info.line && info.line <= lastIndex)) {
  4672. return true;
  4673. }
  4674. }
  4675. return false;
  4676. };
  4677. }
  4678.  
  4679. function CapturedTrace(parent) {
  4680. this._parent = parent;
  4681. this._promisesCreated = 0;
  4682. var length = this._length = 1 + (parent === undefined ? 0 : parent._length);
  4683. captureStackTrace(this, CapturedTrace);
  4684. if (length > 32) this.uncycle();
  4685. }
  4686. util.inherits(CapturedTrace, Error);
  4687. Context.CapturedTrace = CapturedTrace;
  4688.  
  4689. CapturedTrace.prototype.uncycle = function() {
  4690. var length = this._length;
  4691. if (length < 2) return;
  4692. var nodes = [];
  4693. var stackToIndex = {};
  4694.  
  4695. for (var i = 0, node = this; node !== undefined; ++i) {
  4696. nodes.push(node);
  4697. node = node._parent;
  4698. }
  4699. length = this._length = i;
  4700. for (var i = length - 1; i >= 0; --i) {
  4701. var stack = nodes[i].stack;
  4702. if (stackToIndex[stack] === undefined) {
  4703. stackToIndex[stack] = i;
  4704. }
  4705. }
  4706. for (var i = 0; i < length; ++i) {
  4707. var currentStack = nodes[i].stack;
  4708. var index = stackToIndex[currentStack];
  4709. if (index !== undefined && index !== i) {
  4710. if (index > 0) {
  4711. nodes[index - 1]._parent = undefined;
  4712. nodes[index - 1]._length = 1;
  4713. }
  4714. nodes[i]._parent = undefined;
  4715. nodes[i]._length = 1;
  4716. var cycleEdgeNode = i > 0 ? nodes[i - 1] : this;
  4717.  
  4718. if (index < length - 1) {
  4719. cycleEdgeNode._parent = nodes[index + 1];
  4720. cycleEdgeNode._parent.uncycle();
  4721. cycleEdgeNode._length =
  4722. cycleEdgeNode._parent._length + 1;
  4723. } else {
  4724. cycleEdgeNode._parent = undefined;
  4725. cycleEdgeNode._length = 1;
  4726. }
  4727. var currentChildLength = cycleEdgeNode._length + 1;
  4728. for (var j = i - 2; j >= 0; --j) {
  4729. nodes[j]._length = currentChildLength;
  4730. currentChildLength++;
  4731. }
  4732. return;
  4733. }
  4734. }
  4735. };
  4736.  
  4737. CapturedTrace.prototype.attachExtraTrace = function(error) {
  4738. if (error.__stackCleaned__) return;
  4739. this.uncycle();
  4740. var parsed = parseStackAndMessage(error);
  4741. var message = parsed.message;
  4742. var stacks = [parsed.stack];
  4743.  
  4744. var trace = this;
  4745. while (trace !== undefined) {
  4746. stacks.push(cleanStack(trace.stack.split("\n")));
  4747. trace = trace._parent;
  4748. }
  4749. removeCommonRoots(stacks);
  4750. removeDuplicateOrEmptyJumps(stacks);
  4751. util.notEnumerableProp(error, "stack", reconstructStack(message, stacks));
  4752. util.notEnumerableProp(error, "__stackCleaned__", true);
  4753. };
  4754.  
  4755. var captureStackTrace = (function stackDetection() {
  4756. var v8stackFramePattern = /^\s*at\s*/;
  4757. var v8stackFormatter = function(stack, error) {
  4758. if (typeof stack === "string") return stack;
  4759.  
  4760. if (error.name !== undefined &&
  4761. error.message !== undefined) {
  4762. return error.toString();
  4763. }
  4764. return formatNonError(error);
  4765. };
  4766.  
  4767. if (typeof Error.stackTraceLimit === "number" &&
  4768. typeof Error.captureStackTrace === "function") {
  4769. Error.stackTraceLimit += 6;
  4770. stackFramePattern = v8stackFramePattern;
  4771. formatStack = v8stackFormatter;
  4772. var captureStackTrace = Error.captureStackTrace;
  4773.  
  4774. shouldIgnore = function(line) {
  4775. return bluebirdFramePattern.test(line);
  4776. };
  4777. return function(receiver, ignoreUntil) {
  4778. Error.stackTraceLimit += 6;
  4779. captureStackTrace(receiver, ignoreUntil);
  4780. Error.stackTraceLimit -= 6;
  4781. };
  4782. }
  4783. var err = new Error();
  4784.  
  4785. if (typeof err.stack === "string" &&
  4786. err.stack.split("\n")[0].indexOf("stackDetection@") >= 0) {
  4787. stackFramePattern = /@/;
  4788. formatStack = v8stackFormatter;
  4789. indentStackFrames = true;
  4790. return function captureStackTrace(o) {
  4791. o.stack = new Error().stack;
  4792. };
  4793. }
  4794.  
  4795. var hasStackAfterThrow;
  4796. try { throw new Error(); }
  4797. catch(e) {
  4798. hasStackAfterThrow = ("stack" in e);
  4799. }
  4800. if (!("stack" in err) && hasStackAfterThrow &&
  4801. typeof Error.stackTraceLimit === "number") {
  4802. stackFramePattern = v8stackFramePattern;
  4803. formatStack = v8stackFormatter;
  4804. return function captureStackTrace(o) {
  4805. Error.stackTraceLimit += 6;
  4806. try { throw new Error(); }
  4807. catch(e) { o.stack = e.stack; }
  4808. Error.stackTraceLimit -= 6;
  4809. };
  4810. }
  4811.  
  4812. formatStack = function(stack, error) {
  4813. if (typeof stack === "string") return stack;
  4814.  
  4815. if ((typeof error === "object" ||
  4816. typeof error === "function") &&
  4817. error.name !== undefined &&
  4818. error.message !== undefined) {
  4819. return error.toString();
  4820. }
  4821. return formatNonError(error);
  4822. };
  4823.  
  4824. return null;
  4825.  
  4826. })([]);
  4827.  
  4828. if (typeof console !== "undefined" && typeof console.warn !== "undefined") {
  4829. printWarning = function (message) {
  4830. console.warn(message);
  4831. };
  4832. if (util.isNode && process.stderr.isTTY) {
  4833. printWarning = function(message, isSoft) {
  4834. var color = isSoft ? "\u001b[33m" : "\u001b[31m";
  4835. console.warn(color + message + "\u001b[0m\n");
  4836. };
  4837. } else if (!util.isNode && typeof (new Error().stack) === "string") {
  4838. printWarning = function(message, isSoft) {
  4839. console.warn("%c" + message,
  4840. isSoft ? "color: darkorange" : "color: red");
  4841. };
  4842. }
  4843. }
  4844.  
  4845. var config = {
  4846. warnings: warnings,
  4847. longStackTraces: false,
  4848. cancellation: false,
  4849. monitoring: false
  4850. };
  4851.  
  4852. if (longStackTraces) Promise.longStackTraces();
  4853.  
  4854. return {
  4855. longStackTraces: function() {
  4856. return config.longStackTraces;
  4857. },
  4858. warnings: function() {
  4859. return config.warnings;
  4860. },
  4861. cancellation: function() {
  4862. return config.cancellation;
  4863. },
  4864. monitoring: function() {
  4865. return config.monitoring;
  4866. },
  4867. propagateFromFunction: function() {
  4868. return propagateFromFunction;
  4869. },
  4870. boundValueFunction: function() {
  4871. return boundValueFunction;
  4872. },
  4873. checkForgottenReturns: checkForgottenReturns,
  4874. setBounds: setBounds,
  4875. warn: warn,
  4876. deprecated: deprecated,
  4877. CapturedTrace: CapturedTrace,
  4878. fireDomEvent: fireDomEvent,
  4879. fireGlobalEvent: fireGlobalEvent
  4880. };
  4881. };
  4882.  
  4883. },{"./errors":12,"./util":36}],10:[function(_dereq_,module,exports){
  4884. "use strict";
  4885. module.exports = function(Promise) {
  4886. function returner() {
  4887. return this.value;
  4888. }
  4889. function thrower() {
  4890. throw this.reason;
  4891. }
  4892.  
  4893. Promise.prototype["return"] =
  4894. Promise.prototype.thenReturn = function (value) {
  4895. if (value instanceof Promise) value.suppressUnhandledRejections();
  4896. return this._then(
  4897. returner, undefined, undefined, {value: value}, undefined);
  4898. };
  4899.  
  4900. Promise.prototype["throw"] =
  4901. Promise.prototype.thenThrow = function (reason) {
  4902. return this._then(
  4903. thrower, undefined, undefined, {reason: reason}, undefined);
  4904. };
  4905.  
  4906. Promise.prototype.catchThrow = function (reason) {
  4907. if (arguments.length <= 1) {
  4908. return this._then(
  4909. undefined, thrower, undefined, {reason: reason}, undefined);
  4910. } else {
  4911. var _reason = arguments[1];
  4912. var handler = function() {throw _reason;};
  4913. return this.caught(reason, handler);
  4914. }
  4915. };
  4916.  
  4917. Promise.prototype.catchReturn = function (value) {
  4918. if (arguments.length <= 1) {
  4919. if (value instanceof Promise) value.suppressUnhandledRejections();
  4920. return this._then(
  4921. undefined, returner, undefined, {value: value}, undefined);
  4922. } else {
  4923. var _value = arguments[1];
  4924. if (_value instanceof Promise) _value.suppressUnhandledRejections();
  4925. var handler = function() {return _value;};
  4926. return this.caught(value, handler);
  4927. }
  4928. };
  4929. };
  4930.  
  4931. },{}],11:[function(_dereq_,module,exports){
  4932. "use strict";
  4933. module.exports = function(Promise, INTERNAL) {
  4934. var PromiseReduce = Promise.reduce;
  4935. var PromiseAll = Promise.all;
  4936.  
  4937. function promiseAllThis() {
  4938. return PromiseAll(this);
  4939. }
  4940.  
  4941. function PromiseMapSeries(promises, fn) {
  4942. return PromiseReduce(promises, fn, INTERNAL, INTERNAL);
  4943. }
  4944.  
  4945. Promise.prototype.each = function (fn) {
  4946. return PromiseReduce(this, fn, INTERNAL, 0)
  4947. ._then(promiseAllThis, undefined, undefined, this, undefined);
  4948. };
  4949.  
  4950. Promise.prototype.mapSeries = function (fn) {
  4951. return PromiseReduce(this, fn, INTERNAL, INTERNAL);
  4952. };
  4953.  
  4954. Promise.each = function (promises, fn) {
  4955. return PromiseReduce(promises, fn, INTERNAL, 0)
  4956. ._then(promiseAllThis, undefined, undefined, promises, undefined);
  4957. };
  4958.  
  4959. Promise.mapSeries = PromiseMapSeries;
  4960. };
  4961.  
  4962.  
  4963. },{}],12:[function(_dereq_,module,exports){
  4964. "use strict";
  4965. var es5 = _dereq_("./es5");
  4966. var Objectfreeze = es5.freeze;
  4967. var util = _dereq_("./util");
  4968. var inherits = util.inherits;
  4969. var notEnumerableProp = util.notEnumerableProp;
  4970.  
  4971. function subError(nameProperty, defaultMessage) {
  4972. function SubError(message) {
  4973. if (!(this instanceof SubError)) return new SubError(message);
  4974. notEnumerableProp(this, "message",
  4975. typeof message === "string" ? message : defaultMessage);
  4976. notEnumerableProp(this, "name", nameProperty);
  4977. if (Error.captureStackTrace) {
  4978. Error.captureStackTrace(this, this.constructor);
  4979. } else {
  4980. Error.call(this);
  4981. }
  4982. }
  4983. inherits(SubError, Error);
  4984. return SubError;
  4985. }
  4986.  
  4987. var _TypeError, _RangeError;
  4988. var Warning = subError("Warning", "warning");
  4989. var CancellationError = subError("CancellationError", "cancellation error");
  4990. var TimeoutError = subError("TimeoutError", "timeout error");
  4991. var AggregateError = subError("AggregateError", "aggregate error");
  4992. try {
  4993. _TypeError = TypeError;
  4994. _RangeError = RangeError;
  4995. } catch(e) {
  4996. _TypeError = subError("TypeError", "type error");
  4997. _RangeError = subError("RangeError", "range error");
  4998. }
  4999.  
  5000. var methods = ("join pop push shift unshift slice filter forEach some " +
  5001. "every map indexOf lastIndexOf reduce reduceRight sort reverse").split(" ");
  5002.  
  5003. for (var i = 0; i < methods.length; ++i) {
  5004. if (typeof Array.prototype[methods[i]] === "function") {
  5005. AggregateError.prototype[methods[i]] = Array.prototype[methods[i]];
  5006. }
  5007. }
  5008.  
  5009. es5.defineProperty(AggregateError.prototype, "length", {
  5010. value: 0,
  5011. configurable: false,
  5012. writable: true,
  5013. enumerable: true
  5014. });
  5015. AggregateError.prototype["isOperational"] = true;
  5016. var level = 0;
  5017. AggregateError.prototype.toString = function() {
  5018. var indent = Array(level * 4 + 1).join(" ");
  5019. var ret = "\n" + indent + "AggregateError of:" + "\n";
  5020. level++;
  5021. indent = Array(level * 4 + 1).join(" ");
  5022. for (var i = 0; i < this.length; ++i) {
  5023. var str = this[i] === this ? "[Circular AggregateError]" : this[i] + "";
  5024. var lines = str.split("\n");
  5025. for (var j = 0; j < lines.length; ++j) {
  5026. lines[j] = indent + lines[j];
  5027. }
  5028. str = lines.join("\n");
  5029. ret += str + "\n";
  5030. }
  5031. level--;
  5032. return ret;
  5033. };
  5034.  
  5035. function OperationalError(message) {
  5036. if (!(this instanceof OperationalError))
  5037. return new OperationalError(message);
  5038. notEnumerableProp(this, "name", "OperationalError");
  5039. notEnumerableProp(this, "message", message);
  5040. this.cause = message;
  5041. this["isOperational"] = true;
  5042.  
  5043. if (message instanceof Error) {
  5044. notEnumerableProp(this, "message", message.message);
  5045. notEnumerableProp(this, "stack", message.stack);
  5046. } else if (Error.captureStackTrace) {
  5047. Error.captureStackTrace(this, this.constructor);
  5048. }
  5049.  
  5050. }
  5051. inherits(OperationalError, Error);
  5052.  
  5053. var errorTypes = Error["__BluebirdErrorTypes__"];
  5054. if (!errorTypes) {
  5055. errorTypes = Objectfreeze({
  5056. CancellationError: CancellationError,
  5057. TimeoutError: TimeoutError,
  5058. OperationalError: OperationalError,
  5059. RejectionError: OperationalError,
  5060. AggregateError: AggregateError
  5061. });
  5062. es5.defineProperty(Error, "__BluebirdErrorTypes__", {
  5063. value: errorTypes,
  5064. writable: false,
  5065. enumerable: false,
  5066. configurable: false
  5067. });
  5068. }
  5069.  
  5070. module.exports = {
  5071. Error: Error,
  5072. TypeError: _TypeError,
  5073. RangeError: _RangeError,
  5074. CancellationError: errorTypes.CancellationError,
  5075. OperationalError: errorTypes.OperationalError,
  5076. TimeoutError: errorTypes.TimeoutError,
  5077. AggregateError: errorTypes.AggregateError,
  5078. Warning: Warning
  5079. };
  5080.  
  5081. },{"./es5":13,"./util":36}],13:[function(_dereq_,module,exports){
  5082. var isES5 = (function(){
  5083. "use strict";
  5084. return this === undefined;
  5085. })();
  5086.  
  5087. if (isES5) {
  5088. module.exports = {
  5089. freeze: Object.freeze,
  5090. defineProperty: Object.defineProperty,
  5091. getDescriptor: Object.getOwnPropertyDescriptor,
  5092. keys: Object.keys,
  5093. names: Object.getOwnPropertyNames,
  5094. getPrototypeOf: Object.getPrototypeOf,
  5095. isArray: Array.isArray,
  5096. isES5: isES5,
  5097. propertyIsWritable: function(obj, prop) {
  5098. var descriptor = Object.getOwnPropertyDescriptor(obj, prop);
  5099. return !!(!descriptor || descriptor.writable || descriptor.set);
  5100. }
  5101. };
  5102. } else {
  5103. var has = {}.hasOwnProperty;
  5104. var str = {}.toString;
  5105. var proto = {}.constructor.prototype;
  5106.  
  5107. var ObjectKeys = function (o) {
  5108. var ret = [];
  5109. for (var key in o) {
  5110. if (has.call(o, key)) {
  5111. ret.push(key);
  5112. }
  5113. }
  5114. return ret;
  5115. };
  5116.  
  5117. var ObjectGetDescriptor = function(o, key) {
  5118. return {value: o[key]};
  5119. };
  5120.  
  5121. var ObjectDefineProperty = function (o, key, desc) {
  5122. o[key] = desc.value;
  5123. return o;
  5124. };
  5125.  
  5126. var ObjectFreeze = function (obj) {
  5127. return obj;
  5128. };
  5129.  
  5130. var ObjectGetPrototypeOf = function (obj) {
  5131. try {
  5132. return Object(obj).constructor.prototype;
  5133. }
  5134. catch (e) {
  5135. return proto;
  5136. }
  5137. };
  5138.  
  5139. var ArrayIsArray = function (obj) {
  5140. try {
  5141. return str.call(obj) === "[object Array]";
  5142. }
  5143. catch(e) {
  5144. return false;
  5145. }
  5146. };
  5147.  
  5148. module.exports = {
  5149. isArray: ArrayIsArray,
  5150. keys: ObjectKeys,
  5151. names: ObjectKeys,
  5152. defineProperty: ObjectDefineProperty,
  5153. getDescriptor: ObjectGetDescriptor,
  5154. freeze: ObjectFreeze,
  5155. getPrototypeOf: ObjectGetPrototypeOf,
  5156. isES5: isES5,
  5157. propertyIsWritable: function() {
  5158. return true;
  5159. }
  5160. };
  5161. }
  5162.  
  5163. },{}],14:[function(_dereq_,module,exports){
  5164. "use strict";
  5165. module.exports = function(Promise, INTERNAL) {
  5166. var PromiseMap = Promise.map;
  5167.  
  5168. Promise.prototype.filter = function (fn, options) {
  5169. return PromiseMap(this, fn, options, INTERNAL);
  5170. };
  5171.  
  5172. Promise.filter = function (promises, fn, options) {
  5173. return PromiseMap(promises, fn, options, INTERNAL);
  5174. };
  5175. };
  5176.  
  5177. },{}],15:[function(_dereq_,module,exports){
  5178. "use strict";
  5179. module.exports = function(Promise, tryConvertToPromise) {
  5180. var util = _dereq_("./util");
  5181. var CancellationError = Promise.CancellationError;
  5182. var errorObj = util.errorObj;
  5183.  
  5184. function PassThroughHandlerContext(promise, type, handler) {
  5185. this.promise = promise;
  5186. this.type = type;
  5187. this.handler = handler;
  5188. this.called = false;
  5189. this.cancelPromise = null;
  5190. }
  5191.  
  5192. PassThroughHandlerContext.prototype.isFinallyHandler = function() {
  5193. return this.type === 0;
  5194. };
  5195.  
  5196. function FinallyHandlerCancelReaction(finallyHandler) {
  5197. this.finallyHandler = finallyHandler;
  5198. }
  5199.  
  5200. FinallyHandlerCancelReaction.prototype._resultCancelled = function() {
  5201. checkCancel(this.finallyHandler);
  5202. };
  5203.  
  5204. function checkCancel(ctx, reason) {
  5205. if (ctx.cancelPromise != null) {
  5206. if (arguments.length > 1) {
  5207. ctx.cancelPromise._reject(reason);
  5208. } else {
  5209. ctx.cancelPromise._cancel();
  5210. }
  5211. ctx.cancelPromise = null;
  5212. return true;
  5213. }
  5214. return false;
  5215. }
  5216.  
  5217. function succeed() {
  5218. return finallyHandler.call(this, this.promise._target()._settledValue());
  5219. }
  5220. function fail(reason) {
  5221. if (checkCancel(this, reason)) return;
  5222. errorObj.e = reason;
  5223. return errorObj;
  5224. }
  5225. function finallyHandler(reasonOrValue) {
  5226. var promise = this.promise;
  5227. var handler = this.handler;
  5228.  
  5229. if (!this.called) {
  5230. this.called = true;
  5231. var ret = this.isFinallyHandler()
  5232. ? handler.call(promise._boundValue())
  5233. : handler.call(promise._boundValue(), reasonOrValue);
  5234. if (ret !== undefined) {
  5235. promise._setReturnedNonUndefined();
  5236. var maybePromise = tryConvertToPromise(ret, promise);
  5237. if (maybePromise instanceof Promise) {
  5238. if (this.cancelPromise != null) {
  5239. if (maybePromise._isCancelled()) {
  5240. var reason =
  5241. new CancellationError("late cancellation observer");
  5242. promise._attachExtraTrace(reason);
  5243. errorObj.e = reason;
  5244. return errorObj;
  5245. } else if (maybePromise.isPending()) {
  5246. maybePromise._attachCancellationCallback(
  5247. new FinallyHandlerCancelReaction(this));
  5248. }
  5249. }
  5250. return maybePromise._then(
  5251. succeed, fail, undefined, this, undefined);
  5252. }
  5253. }
  5254. }
  5255.  
  5256. if (promise.isRejected()) {
  5257. checkCancel(this);
  5258. errorObj.e = reasonOrValue;
  5259. return errorObj;
  5260. } else {
  5261. checkCancel(this);
  5262. return reasonOrValue;
  5263. }
  5264. }
  5265.  
  5266. Promise.prototype._passThrough = function(handler, type, success, fail) {
  5267. if (typeof handler !== "function") return this.then();
  5268. return this._then(success,
  5269. fail,
  5270. undefined,
  5271. new PassThroughHandlerContext(this, type, handler),
  5272. undefined);
  5273. };
  5274.  
  5275. Promise.prototype.lastly =
  5276. Promise.prototype["finally"] = function (handler) {
  5277. return this._passThrough(handler,
  5278. 0,
  5279. finallyHandler,
  5280. finallyHandler);
  5281. };
  5282.  
  5283. Promise.prototype.tap = function (handler) {
  5284. return this._passThrough(handler, 1, finallyHandler);
  5285. };
  5286.  
  5287. return PassThroughHandlerContext;
  5288. };
  5289.  
  5290. },{"./util":36}],16:[function(_dereq_,module,exports){
  5291. "use strict";
  5292. module.exports = function(Promise,
  5293. apiRejection,
  5294. INTERNAL,
  5295. tryConvertToPromise,
  5296. Proxyable,
  5297. debug) {
  5298. var errors = _dereq_("./errors");
  5299. var TypeError = errors.TypeError;
  5300. var util = _dereq_("./util");
  5301. var errorObj = util.errorObj;
  5302. var tryCatch = util.tryCatch;
  5303. var yieldHandlers = [];
  5304.  
  5305. function promiseFromYieldHandler(value, yieldHandlers, traceParent) {
  5306. for (var i = 0; i < yieldHandlers.length; ++i) {
  5307. traceParent._pushContext();
  5308. var result = tryCatch(yieldHandlers[i])(value);
  5309. traceParent._popContext();
  5310. if (result === errorObj) {
  5311. traceParent._pushContext();
  5312. var ret = Promise.reject(errorObj.e);
  5313. traceParent._popContext();
  5314. return ret;
  5315. }
  5316. var maybePromise = tryConvertToPromise(result, traceParent);
  5317. if (maybePromise instanceof Promise) return maybePromise;
  5318. }
  5319. return null;
  5320. }
  5321.  
  5322. function PromiseSpawn(generatorFunction, receiver, yieldHandler, stack) {
  5323. if (debug.cancellation()) {
  5324. var internal = new Promise(INTERNAL);
  5325. var _finallyPromise = this._finallyPromise = new Promise(INTERNAL);
  5326. this._promise = internal.lastly(function() {
  5327. return _finallyPromise;
  5328. });
  5329. internal._captureStackTrace();
  5330. internal._setOnCancel(this);
  5331. } else {
  5332. var promise = this._promise = new Promise(INTERNAL);
  5333. promise._captureStackTrace();
  5334. }
  5335. this._stack = stack;
  5336. this._generatorFunction = generatorFunction;
  5337. this._receiver = receiver;
  5338. this._generator = undefined;
  5339. this._yieldHandlers = typeof yieldHandler === "function"
  5340. ? [yieldHandler].concat(yieldHandlers)
  5341. : yieldHandlers;
  5342. this._yieldedPromise = null;
  5343. this._cancellationPhase = false;
  5344. }
  5345. util.inherits(PromiseSpawn, Proxyable);
  5346.  
  5347. PromiseSpawn.prototype._isResolved = function() {
  5348. return this._promise === null;
  5349. };
  5350.  
  5351. PromiseSpawn.prototype._cleanup = function() {
  5352. this._promise = this._generator = null;
  5353. if (debug.cancellation() && this._finallyPromise !== null) {
  5354. this._finallyPromise._fulfill();
  5355. this._finallyPromise = null;
  5356. }
  5357. };
  5358.  
  5359. PromiseSpawn.prototype._promiseCancelled = function() {
  5360. if (this._isResolved()) return;
  5361. var implementsReturn = typeof this._generator["return"] !== "undefined";
  5362.  
  5363. var result;
  5364. if (!implementsReturn) {
  5365. var reason = new Promise.CancellationError(
  5366. "generator .return() sentinel");
  5367. Promise.coroutine.returnSentinel = reason;
  5368. this._promise._attachExtraTrace(reason);
  5369. this._promise._pushContext();
  5370. result = tryCatch(this._generator["throw"]).call(this._generator,
  5371. reason);
  5372. this._promise._popContext();
  5373. } else {
  5374. this._promise._pushContext();
  5375. result = tryCatch(this._generator["return"]).call(this._generator,
  5376. undefined);
  5377. this._promise._popContext();
  5378. }
  5379. this._cancellationPhase = true;
  5380. this._yieldedPromise = null;
  5381. this._continue(result);
  5382. };
  5383.  
  5384. PromiseSpawn.prototype._promiseFulfilled = function(value) {
  5385. this._yieldedPromise = null;
  5386. this._promise._pushContext();
  5387. var result = tryCatch(this._generator.next).call(this._generator, value);
  5388. this._promise._popContext();
  5389. this._continue(result);
  5390. };
  5391.  
  5392. PromiseSpawn.prototype._promiseRejected = function(reason) {
  5393. this._yieldedPromise = null;
  5394. this._promise._attachExtraTrace(reason);
  5395. this._promise._pushContext();
  5396. var result = tryCatch(this._generator["throw"])
  5397. .call(this._generator, reason);
  5398. this._promise._popContext();
  5399. this._continue(result);
  5400. };
  5401.  
  5402. PromiseSpawn.prototype._resultCancelled = function() {
  5403. if (this._yieldedPromise instanceof Promise) {
  5404. var promise = this._yieldedPromise;
  5405. this._yieldedPromise = null;
  5406. promise.cancel();
  5407. }
  5408. };
  5409.  
  5410. PromiseSpawn.prototype.promise = function () {
  5411. return this._promise;
  5412. };
  5413.  
  5414. PromiseSpawn.prototype._run = function () {
  5415. this._generator = this._generatorFunction.call(this._receiver);
  5416. this._receiver =
  5417. this._generatorFunction = undefined;
  5418. this._promiseFulfilled(undefined);
  5419. };
  5420.  
  5421. PromiseSpawn.prototype._continue = function (result) {
  5422. var promise = this._promise;
  5423. if (result === errorObj) {
  5424. this._cleanup();
  5425. if (this._cancellationPhase) {
  5426. return promise.cancel();
  5427. } else {
  5428. return promise._rejectCallback(result.e, false);
  5429. }
  5430. }
  5431.  
  5432. var value = result.value;
  5433. if (result.done === true) {
  5434. this._cleanup();
  5435. if (this._cancellationPhase) {
  5436. return promise.cancel();
  5437. } else {
  5438. return promise._resolveCallback(value);
  5439. }
  5440. } else {
  5441. var maybePromise = tryConvertToPromise(value, this._promise);
  5442. if (!(maybePromise instanceof Promise)) {
  5443. maybePromise =
  5444. promiseFromYieldHandler(maybePromise,
  5445. this._yieldHandlers,
  5446. this._promise);
  5447. if (maybePromise === null) {
  5448. this._promiseRejected(
  5449. new TypeError(
  5450. "A value %s was yielded that could not be treated as a promise\u000a\u000a See http://goo.gl/MqrFmX\u000a\u000a".replace("%s", value) +
  5451. "From coroutine:\u000a" +
  5452. this._stack.split("\n").slice(1, -7).join("\n")
  5453. )
  5454. );
  5455. return;
  5456. }
  5457. }
  5458. maybePromise = maybePromise._target();
  5459. var bitField = maybePromise._bitField;
  5460. ;
  5461. if (((bitField & 50397184) === 0)) {
  5462. this._yieldedPromise = maybePromise;
  5463. maybePromise._proxy(this, null);
  5464. } else if (((bitField & 33554432) !== 0)) {
  5465. Promise._async.invoke(
  5466. this._promiseFulfilled, this, maybePromise._value()
  5467. );
  5468. } else if (((bitField & 16777216) !== 0)) {
  5469. Promise._async.invoke(
  5470. this._promiseRejected, this, maybePromise._reason()
  5471. );
  5472. } else {
  5473. this._promiseCancelled();
  5474. }
  5475. }
  5476. };
  5477.  
  5478. Promise.coroutine = function (generatorFunction, options) {
  5479. if (typeof generatorFunction !== "function") {
  5480. throw new TypeError("generatorFunction must be a function\u000a\u000a See http://goo.gl/MqrFmX\u000a");
  5481. }
  5482. var yieldHandler = Object(options).yieldHandler;
  5483. var PromiseSpawn$ = PromiseSpawn;
  5484. var stack = new Error().stack;
  5485. return function () {
  5486. var generator = generatorFunction.apply(this, arguments);
  5487. var spawn = new PromiseSpawn$(undefined, undefined, yieldHandler,
  5488. stack);
  5489. var ret = spawn.promise();
  5490. spawn._generator = generator;
  5491. spawn._promiseFulfilled(undefined);
  5492. return ret;
  5493. };
  5494. };
  5495.  
  5496. Promise.coroutine.addYieldHandler = function(fn) {
  5497. if (typeof fn !== "function") {
  5498. throw new TypeError("expecting a function but got " + util.classString(fn));
  5499. }
  5500. yieldHandlers.push(fn);
  5501. };
  5502.  
  5503. Promise.spawn = function (generatorFunction) {
  5504. debug.deprecated("Promise.spawn()", "Promise.coroutine()");
  5505. if (typeof generatorFunction !== "function") {
  5506. return apiRejection("generatorFunction must be a function\u000a\u000a See http://goo.gl/MqrFmX\u000a");
  5507. }
  5508. var spawn = new PromiseSpawn(generatorFunction, this);
  5509. var ret = spawn.promise();
  5510. spawn._run(Promise.spawn);
  5511. return ret;
  5512. };
  5513. };
  5514.  
  5515. },{"./errors":12,"./util":36}],17:[function(_dereq_,module,exports){
  5516. "use strict";
  5517. module.exports =
  5518. function(Promise, PromiseArray, tryConvertToPromise, INTERNAL, async,
  5519. getDomain) {
  5520. var util = _dereq_("./util");
  5521. var canEvaluate = util.canEvaluate;
  5522. var tryCatch = util.tryCatch;
  5523. var errorObj = util.errorObj;
  5524. var reject;
  5525.  
  5526. if (!true) {
  5527. if (canEvaluate) {
  5528. var thenCallback = function(i) {
  5529. return new Function("value", "holder", " \n\
  5530. 'use strict'; \n\
  5531. holder.pIndex = value; \n\
  5532. holder.checkFulfillment(this); \n\
  5533. ".replace(/Index/g, i));
  5534. };
  5535.  
  5536. var promiseSetter = function(i) {
  5537. return new Function("promise", "holder", " \n\
  5538. 'use strict'; \n\
  5539. holder.pIndex = promise; \n\
  5540. ".replace(/Index/g, i));
  5541. };
  5542.  
  5543. var generateHolderClass = function(total) {
  5544. var props = new Array(total);
  5545. for (var i = 0; i < props.length; ++i) {
  5546. props[i] = "this.p" + (i+1);
  5547. }
  5548. var assignment = props.join(" = ") + " = null;";
  5549. var cancellationCode= "var promise;\n" + props.map(function(prop) {
  5550. return " \n\
  5551. promise = " + prop + "; \n\
  5552. if (promise instanceof Promise) { \n\
  5553. promise.cancel(); \n\
  5554. } \n\
  5555. ";
  5556. }).join("\n");
  5557. var passedArguments = props.join(", ");
  5558. var name = "Holder$" + total;
  5559.  
  5560.  
  5561. var code = "return function(tryCatch, errorObj, Promise, async) { \n\
  5562. 'use strict'; \n\
  5563. function [TheName](fn) { \n\
  5564. [TheProperties] \n\
  5565. this.fn = fn; \n\
  5566. this.asyncNeeded = true; \n\
  5567. this.now = 0; \n\
  5568. } \n\
  5569. \n\
  5570. [TheName].prototype._callFunction = function(promise) { \n\
  5571. promise._pushContext(); \n\
  5572. var ret = tryCatch(this.fn)([ThePassedArguments]); \n\
  5573. promise._popContext(); \n\
  5574. if (ret === errorObj) { \n\
  5575. promise._rejectCallback(ret.e, false); \n\
  5576. } else { \n\
  5577. promise._resolveCallback(ret); \n\
  5578. } \n\
  5579. }; \n\
  5580. \n\
  5581. [TheName].prototype.checkFulfillment = function(promise) { \n\
  5582. var now = ++this.now; \n\
  5583. if (now === [TheTotal]) { \n\
  5584. if (this.asyncNeeded) { \n\
  5585. async.invoke(this._callFunction, this, promise); \n\
  5586. } else { \n\
  5587. this._callFunction(promise); \n\
  5588. } \n\
  5589. \n\
  5590. } \n\
  5591. }; \n\
  5592. \n\
  5593. [TheName].prototype._resultCancelled = function() { \n\
  5594. [CancellationCode] \n\
  5595. }; \n\
  5596. \n\
  5597. return [TheName]; \n\
  5598. }(tryCatch, errorObj, Promise, async); \n\
  5599. ";
  5600.  
  5601. code = code.replace(/\[TheName\]/g, name)
  5602. .replace(/\[TheTotal\]/g, total)
  5603. .replace(/\[ThePassedArguments\]/g, passedArguments)
  5604. .replace(/\[TheProperties\]/g, assignment)
  5605. .replace(/\[CancellationCode\]/g, cancellationCode);
  5606.  
  5607. return new Function("tryCatch", "errorObj", "Promise", "async", code)
  5608. (tryCatch, errorObj, Promise, async);
  5609. };
  5610.  
  5611. var holderClasses = [];
  5612. var thenCallbacks = [];
  5613. var promiseSetters = [];
  5614.  
  5615. for (var i = 0; i < 8; ++i) {
  5616. holderClasses.push(generateHolderClass(i + 1));
  5617. thenCallbacks.push(thenCallback(i + 1));
  5618. promiseSetters.push(promiseSetter(i + 1));
  5619. }
  5620.  
  5621. reject = function (reason) {
  5622. this._reject(reason);
  5623. };
  5624. }}
  5625.  
  5626. Promise.join = function () {
  5627. var last = arguments.length - 1;
  5628. var fn;
  5629. if (last > 0 && typeof arguments[last] === "function") {
  5630. fn = arguments[last];
  5631. if (!true) {
  5632. if (last <= 8 && canEvaluate) {
  5633. var ret = new Promise(INTERNAL);
  5634. ret._captureStackTrace();
  5635. var HolderClass = holderClasses[last - 1];
  5636. var holder = new HolderClass(fn);
  5637. var callbacks = thenCallbacks;
  5638.  
  5639. for (var i = 0; i < last; ++i) {
  5640. var maybePromise = tryConvertToPromise(arguments[i], ret);
  5641. if (maybePromise instanceof Promise) {
  5642. maybePromise = maybePromise._target();
  5643. var bitField = maybePromise._bitField;
  5644. ;
  5645. if (((bitField & 50397184) === 0)) {
  5646. maybePromise._then(callbacks[i], reject,
  5647. undefined, ret, holder);
  5648. promiseSetters[i](maybePromise, holder);
  5649. holder.asyncNeeded = false;
  5650. } else if (((bitField & 33554432) !== 0)) {
  5651. callbacks[i].call(ret,
  5652. maybePromise._value(), holder);
  5653. } else if (((bitField & 16777216) !== 0)) {
  5654. ret._reject(maybePromise._reason());
  5655. } else {
  5656. ret._cancel();
  5657. }
  5658. } else {
  5659. callbacks[i].call(ret, maybePromise, holder);
  5660. }
  5661. }
  5662.  
  5663. if (!ret._isFateSealed()) {
  5664. if (holder.asyncNeeded) {
  5665. var domain = getDomain();
  5666. if (domain !== null) {
  5667. holder.fn = util.domainBind(domain, holder.fn);
  5668. }
  5669. }
  5670. ret._setAsyncGuaranteed();
  5671. ret._setOnCancel(holder);
  5672. }
  5673. return ret;
  5674. }
  5675. }
  5676. }
  5677. var args = [].slice.call(arguments);;
  5678. if (fn) args.pop();
  5679. var ret = new PromiseArray(args).promise();
  5680. return fn !== undefined ? ret.spread(fn) : ret;
  5681. };
  5682.  
  5683. };
  5684.  
  5685. },{"./util":36}],18:[function(_dereq_,module,exports){
  5686. "use strict";
  5687. module.exports = function(Promise,
  5688. PromiseArray,
  5689. apiRejection,
  5690. tryConvertToPromise,
  5691. INTERNAL,
  5692. debug) {
  5693. var getDomain = Promise._getDomain;
  5694. var util = _dereq_("./util");
  5695. var tryCatch = util.tryCatch;
  5696. var errorObj = util.errorObj;
  5697. var async = Promise._async;
  5698.  
  5699. function MappingPromiseArray(promises, fn, limit, _filter) {
  5700. this.constructor$(promises);
  5701. this._promise._captureStackTrace();
  5702. var domain = getDomain();
  5703. this._callback = domain === null ? fn : util.domainBind(domain, fn);
  5704. this._preservedValues = _filter === INTERNAL
  5705. ? new Array(this.length())
  5706. : null;
  5707. this._limit = limit;
  5708. this._inFlight = 0;
  5709. this._queue = [];
  5710. async.invoke(this._asyncInit, this, undefined);
  5711. }
  5712. util.inherits(MappingPromiseArray, PromiseArray);
  5713.  
  5714. MappingPromiseArray.prototype._asyncInit = function() {
  5715. this._init$(undefined, -2);
  5716. };
  5717.  
  5718. MappingPromiseArray.prototype._init = function () {};
  5719.  
  5720. MappingPromiseArray.prototype._promiseFulfilled = function (value, index) {
  5721. var values = this._values;
  5722. var length = this.length();
  5723. var preservedValues = this._preservedValues;
  5724. var limit = this._limit;
  5725.  
  5726. if (index < 0) {
  5727. index = (index * -1) - 1;
  5728. values[index] = value;
  5729. if (limit >= 1) {
  5730. this._inFlight--;
  5731. this._drainQueue();
  5732. if (this._isResolved()) return true;
  5733. }
  5734. } else {
  5735. if (limit >= 1 && this._inFlight >= limit) {
  5736. values[index] = value;
  5737. this._queue.push(index);
  5738. return false;
  5739. }
  5740. if (preservedValues !== null) preservedValues[index] = value;
  5741.  
  5742. var promise = this._promise;
  5743. var callback = this._callback;
  5744. var receiver = promise._boundValue();
  5745. promise._pushContext();
  5746. var ret = tryCatch(callback).call(receiver, value, index, length);
  5747. var promiseCreated = promise._popContext();
  5748. debug.checkForgottenReturns(
  5749. ret,
  5750. promiseCreated,
  5751. preservedValues !== null ? "Promise.filter" : "Promise.map",
  5752. promise
  5753. );
  5754. if (ret === errorObj) {
  5755. this._reject(ret.e);
  5756. return true;
  5757. }
  5758.  
  5759. var maybePromise = tryConvertToPromise(ret, this._promise);
  5760. if (maybePromise instanceof Promise) {
  5761. maybePromise = maybePromise._target();
  5762. var bitField = maybePromise._bitField;
  5763. ;
  5764. if (((bitField & 50397184) === 0)) {
  5765. if (limit >= 1) this._inFlight++;
  5766. values[index] = maybePromise;
  5767. maybePromise._proxy(this, (index + 1) * -1);
  5768. return false;
  5769. } else if (((bitField & 33554432) !== 0)) {
  5770. ret = maybePromise._value();
  5771. } else if (((bitField & 16777216) !== 0)) {
  5772. this._reject(maybePromise._reason());
  5773. return true;
  5774. } else {
  5775. this._cancel();
  5776. return true;
  5777. }
  5778. }
  5779. values[index] = ret;
  5780. }
  5781. var totalResolved = ++this._totalResolved;
  5782. if (totalResolved >= length) {
  5783. if (preservedValues !== null) {
  5784. this._filter(values, preservedValues);
  5785. } else {
  5786. this._resolve(values);
  5787. }
  5788. return true;
  5789. }
  5790. return false;
  5791. };
  5792.  
  5793. MappingPromiseArray.prototype._drainQueue = function () {
  5794. var queue = this._queue;
  5795. var limit = this._limit;
  5796. var values = this._values;
  5797. while (queue.length > 0 && this._inFlight < limit) {
  5798. if (this._isResolved()) return;
  5799. var index = queue.pop();
  5800. this._promiseFulfilled(values[index], index);
  5801. }
  5802. };
  5803.  
  5804. MappingPromiseArray.prototype._filter = function (booleans, values) {
  5805. var len = values.length;
  5806. var ret = new Array(len);
  5807. var j = 0;
  5808. for (var i = 0; i < len; ++i) {
  5809. if (booleans[i]) ret[j++] = values[i];
  5810. }
  5811. ret.length = j;
  5812. this._resolve(ret);
  5813. };
  5814.  
  5815. MappingPromiseArray.prototype.preservedValues = function () {
  5816. return this._preservedValues;
  5817. };
  5818.  
  5819. function map(promises, fn, options, _filter) {
  5820. if (typeof fn !== "function") {
  5821. return apiRejection("expecting a function but got " + util.classString(fn));
  5822. }
  5823.  
  5824. var limit = 0;
  5825. if (options !== undefined) {
  5826. if (typeof options === "object" && options !== null) {
  5827. if (typeof options.concurrency !== "number") {
  5828. return Promise.reject(
  5829. new TypeError("'concurrency' must be a number but it is " +
  5830. util.classString(options.concurrency)));
  5831. }
  5832. limit = options.concurrency;
  5833. } else {
  5834. return Promise.reject(new TypeError(
  5835. "options argument must be an object but it is " +
  5836. util.classString(options)));
  5837. }
  5838. }
  5839. limit = typeof limit === "number" &&
  5840. isFinite(limit) && limit >= 1 ? limit : 0;
  5841. return new MappingPromiseArray(promises, fn, limit, _filter).promise();
  5842. }
  5843.  
  5844. Promise.prototype.map = function (fn, options) {
  5845. return map(this, fn, options, null);
  5846. };
  5847.  
  5848. Promise.map = function (promises, fn, options, _filter) {
  5849. return map(promises, fn, options, _filter);
  5850. };
  5851.  
  5852.  
  5853. };
  5854.  
  5855. },{"./util":36}],19:[function(_dereq_,module,exports){
  5856. "use strict";
  5857. module.exports =
  5858. function(Promise, INTERNAL, tryConvertToPromise, apiRejection, debug) {
  5859. var util = _dereq_("./util");
  5860. var tryCatch = util.tryCatch;
  5861.  
  5862. Promise.method = function (fn) {
  5863. if (typeof fn !== "function") {
  5864. throw new Promise.TypeError("expecting a function but got " + util.classString(fn));
  5865. }
  5866. return function () {
  5867. var ret = new Promise(INTERNAL);
  5868. ret._captureStackTrace();
  5869. ret._pushContext();
  5870. var value = tryCatch(fn).apply(this, arguments);
  5871. var promiseCreated = ret._popContext();
  5872. debug.checkForgottenReturns(
  5873. value, promiseCreated, "Promise.method", ret);
  5874. ret._resolveFromSyncValue(value);
  5875. return ret;
  5876. };
  5877. };
  5878.  
  5879. Promise.attempt = Promise["try"] = function (fn) {
  5880. if (typeof fn !== "function") {
  5881. return apiRejection("expecting a function but got " + util.classString(fn));
  5882. }
  5883. var ret = new Promise(INTERNAL);
  5884. ret._captureStackTrace();
  5885. ret._pushContext();
  5886. var value;
  5887. if (arguments.length > 1) {
  5888. debug.deprecated("calling Promise.try with more than 1 argument");
  5889. var arg = arguments[1];
  5890. var ctx = arguments[2];
  5891. value = util.isArray(arg) ? tryCatch(fn).apply(ctx, arg)
  5892. : tryCatch(fn).call(ctx, arg);
  5893. } else {
  5894. value = tryCatch(fn)();
  5895. }
  5896. var promiseCreated = ret._popContext();
  5897. debug.checkForgottenReturns(
  5898. value, promiseCreated, "Promise.try", ret);
  5899. ret._resolveFromSyncValue(value);
  5900. return ret;
  5901. };
  5902.  
  5903. Promise.prototype._resolveFromSyncValue = function (value) {
  5904. if (value === util.errorObj) {
  5905. this._rejectCallback(value.e, false);
  5906. } else {
  5907. this._resolveCallback(value, true);
  5908. }
  5909. };
  5910. };
  5911.  
  5912. },{"./util":36}],20:[function(_dereq_,module,exports){
  5913. "use strict";
  5914. var util = _dereq_("./util");
  5915. var maybeWrapAsError = util.maybeWrapAsError;
  5916. var errors = _dereq_("./errors");
  5917. var OperationalError = errors.OperationalError;
  5918. var es5 = _dereq_("./es5");
  5919.  
  5920. function isUntypedError(obj) {
  5921. return obj instanceof Error &&
  5922. es5.getPrototypeOf(obj) === Error.prototype;
  5923. }
  5924.  
  5925. var rErrorKey = /^(?:name|message|stack|cause)$/;
  5926. function wrapAsOperationalError(obj) {
  5927. var ret;
  5928. if (isUntypedError(obj)) {
  5929. ret = new OperationalError(obj);
  5930. ret.name = obj.name;
  5931. ret.message = obj.message;
  5932. ret.stack = obj.stack;
  5933. var keys = es5.keys(obj);
  5934. for (var i = 0; i < keys.length; ++i) {
  5935. var key = keys[i];
  5936. if (!rErrorKey.test(key)) {
  5937. ret[key] = obj[key];
  5938. }
  5939. }
  5940. return ret;
  5941. }
  5942. util.markAsOriginatingFromRejection(obj);
  5943. return obj;
  5944. }
  5945.  
  5946. function nodebackForPromise(promise, multiArgs) {
  5947. return function(err, value) {
  5948. if (promise === null) return;
  5949. if (err) {
  5950. var wrapped = wrapAsOperationalError(maybeWrapAsError(err));
  5951. promise._attachExtraTrace(wrapped);
  5952. promise._reject(wrapped);
  5953. } else if (!multiArgs) {
  5954. promise._fulfill(value);
  5955. } else {
  5956. var args = [].slice.call(arguments, 1);;
  5957. promise._fulfill(args);
  5958. }
  5959. promise = null;
  5960. };
  5961. }
  5962.  
  5963. module.exports = nodebackForPromise;
  5964.  
  5965. },{"./errors":12,"./es5":13,"./util":36}],21:[function(_dereq_,module,exports){
  5966. "use strict";
  5967. module.exports = function(Promise) {
  5968. var util = _dereq_("./util");
  5969. var async = Promise._async;
  5970. var tryCatch = util.tryCatch;
  5971. var errorObj = util.errorObj;
  5972.  
  5973. function spreadAdapter(val, nodeback) {
  5974. var promise = this;
  5975. if (!util.isArray(val)) return successAdapter.call(promise, val, nodeback);
  5976. var ret =
  5977. tryCatch(nodeback).apply(promise._boundValue(), [null].concat(val));
  5978. if (ret === errorObj) {
  5979. async.throwLater(ret.e);
  5980. }
  5981. }
  5982.  
  5983. function successAdapter(val, nodeback) {
  5984. var promise = this;
  5985. var receiver = promise._boundValue();
  5986. var ret = val === undefined
  5987. ? tryCatch(nodeback).call(receiver, null)
  5988. : tryCatch(nodeback).call(receiver, null, val);
  5989. if (ret === errorObj) {
  5990. async.throwLater(ret.e);
  5991. }
  5992. }
  5993. function errorAdapter(reason, nodeback) {
  5994. var promise = this;
  5995. if (!reason) {
  5996. var newReason = new Error(reason + "");
  5997. newReason.cause = reason;
  5998. reason = newReason;
  5999. }
  6000. var ret = tryCatch(nodeback).call(promise._boundValue(), reason);
  6001. if (ret === errorObj) {
  6002. async.throwLater(ret.e);
  6003. }
  6004. }
  6005.  
  6006. Promise.prototype.asCallback = Promise.prototype.nodeify = function (nodeback,
  6007. options) {
  6008. if (typeof nodeback == "function") {
  6009. var adapter = successAdapter;
  6010. if (options !== undefined && Object(options).spread) {
  6011. adapter = spreadAdapter;
  6012. }
  6013. this._then(
  6014. adapter,
  6015. errorAdapter,
  6016. undefined,
  6017. this,
  6018. nodeback
  6019. );
  6020. }
  6021. return this;
  6022. };
  6023. };
  6024.  
  6025. },{"./util":36}],22:[function(_dereq_,module,exports){
  6026. "use strict";
  6027. module.exports = function() {
  6028. var makeSelfResolutionError = function () {
  6029. return new TypeError("circular promise resolution chain\u000a\u000a See http://goo.gl/MqrFmX\u000a");
  6030. };
  6031. var reflectHandler = function() {
  6032. return new Promise.PromiseInspection(this._target());
  6033. };
  6034. var apiRejection = function(msg) {
  6035. return Promise.reject(new TypeError(msg));
  6036. };
  6037. function Proxyable() {}
  6038. var UNDEFINED_BINDING = {};
  6039. var util = _dereq_("./util");
  6040.  
  6041. var getDomain;
  6042. if (util.isNode) {
  6043. getDomain = function() {
  6044. var ret = process.domain;
  6045. if (ret === undefined) ret = null;
  6046. return ret;
  6047. };
  6048. } else {
  6049. getDomain = function() {
  6050. return null;
  6051. };
  6052. }
  6053. util.notEnumerableProp(Promise, "_getDomain", getDomain);
  6054.  
  6055. var es5 = _dereq_("./es5");
  6056. var Async = _dereq_("./async");
  6057. var async = new Async();
  6058. es5.defineProperty(Promise, "_async", {value: async});
  6059. var errors = _dereq_("./errors");
  6060. var TypeError = Promise.TypeError = errors.TypeError;
  6061. Promise.RangeError = errors.RangeError;
  6062. var CancellationError = Promise.CancellationError = errors.CancellationError;
  6063. Promise.TimeoutError = errors.TimeoutError;
  6064. Promise.OperationalError = errors.OperationalError;
  6065. Promise.RejectionError = errors.OperationalError;
  6066. Promise.AggregateError = errors.AggregateError;
  6067. var INTERNAL = function(){};
  6068. var APPLY = {};
  6069. var NEXT_FILTER = {};
  6070. var tryConvertToPromise = _dereq_("./thenables")(Promise, INTERNAL);
  6071. var PromiseArray =
  6072. _dereq_("./promise_array")(Promise, INTERNAL,
  6073. tryConvertToPromise, apiRejection, Proxyable);
  6074. var Context = _dereq_("./context")(Promise);
  6075. /*jshint unused:false*/
  6076. var createContext = Context.create;
  6077. var debug = _dereq_("./debuggability")(Promise, Context);
  6078. var CapturedTrace = debug.CapturedTrace;
  6079. var PassThroughHandlerContext =
  6080. _dereq_("./finally")(Promise, tryConvertToPromise);
  6081. var catchFilter = _dereq_("./catch_filter")(NEXT_FILTER);
  6082. var nodebackForPromise = _dereq_("./nodeback");
  6083. var errorObj = util.errorObj;
  6084. var tryCatch = util.tryCatch;
  6085. function check(self, executor) {
  6086. if (typeof executor !== "function") {
  6087. throw new TypeError("expecting a function but got " + util.classString(executor));
  6088. }
  6089. if (self.constructor !== Promise) {
  6090. throw new TypeError("the promise constructor cannot be invoked directly\u000a\u000a See http://goo.gl/MqrFmX\u000a");
  6091. }
  6092. }
  6093.  
  6094. function Promise(executor) {
  6095. this._bitField = 0;
  6096. this._fulfillmentHandler0 = undefined;
  6097. this._rejectionHandler0 = undefined;
  6098. this._promise0 = undefined;
  6099. this._receiver0 = undefined;
  6100. if (executor !== INTERNAL) {
  6101. check(this, executor);
  6102. this._resolveFromExecutor(executor);
  6103. }
  6104. this._promiseCreated();
  6105. this._fireEvent("promiseCreated", this);
  6106. }
  6107.  
  6108. Promise.prototype.toString = function () {
  6109. return "[object Promise]";
  6110. };
  6111.  
  6112. Promise.prototype.caught = Promise.prototype["catch"] = function (fn) {
  6113. var len = arguments.length;
  6114. if (len > 1) {
  6115. var catchInstances = new Array(len - 1),
  6116. j = 0, i;
  6117. for (i = 0; i < len - 1; ++i) {
  6118. var item = arguments[i];
  6119. if (util.isObject(item)) {
  6120. catchInstances[j++] = item;
  6121. } else {
  6122. return apiRejection("expecting an object but got " +
  6123. "A catch statement predicate " + util.classString(item));
  6124. }
  6125. }
  6126. catchInstances.length = j;
  6127. fn = arguments[i];
  6128. return this.then(undefined, catchFilter(catchInstances, fn, this));
  6129. }
  6130. return this.then(undefined, fn);
  6131. };
  6132.  
  6133. Promise.prototype.reflect = function () {
  6134. return this._then(reflectHandler,
  6135. reflectHandler, undefined, this, undefined);
  6136. };
  6137.  
  6138. Promise.prototype.then = function (didFulfill, didReject) {
  6139. if (debug.warnings() && arguments.length > 0 &&
  6140. typeof didFulfill !== "function" &&
  6141. typeof didReject !== "function") {
  6142. var msg = ".then() only accepts functions but was passed: " +
  6143. util.classString(didFulfill);
  6144. if (arguments.length > 1) {
  6145. msg += ", " + util.classString(didReject);
  6146. }
  6147. this._warn(msg);
  6148. }
  6149. return this._then(didFulfill, didReject, undefined, undefined, undefined);
  6150. };
  6151.  
  6152. Promise.prototype.done = function (didFulfill, didReject) {
  6153. var promise =
  6154. this._then(didFulfill, didReject, undefined, undefined, undefined);
  6155. promise._setIsFinal();
  6156. };
  6157.  
  6158. Promise.prototype.spread = function (fn) {
  6159. if (typeof fn !== "function") {
  6160. return apiRejection("expecting a function but got " + util.classString(fn));
  6161. }
  6162. return this.all()._then(fn, undefined, undefined, APPLY, undefined);
  6163. };
  6164.  
  6165. Promise.prototype.toJSON = function () {
  6166. var ret = {
  6167. isFulfilled: false,
  6168. isRejected: false,
  6169. fulfillmentValue: undefined,
  6170. rejectionReason: undefined
  6171. };
  6172. if (this.isFulfilled()) {
  6173. ret.fulfillmentValue = this.value();
  6174. ret.isFulfilled = true;
  6175. } else if (this.isRejected()) {
  6176. ret.rejectionReason = this.reason();
  6177. ret.isRejected = true;
  6178. }
  6179. return ret;
  6180. };
  6181.  
  6182. Promise.prototype.all = function () {
  6183. if (arguments.length > 0) {
  6184. this._warn(".all() was passed arguments but it does not take any");
  6185. }
  6186. return new PromiseArray(this).promise();
  6187. };
  6188.  
  6189. Promise.prototype.error = function (fn) {
  6190. return this.caught(util.originatesFromRejection, fn);
  6191. };
  6192.  
  6193. Promise.getNewLibraryCopy = module.exports;
  6194.  
  6195. Promise.is = function (val) {
  6196. return val instanceof Promise;
  6197. };
  6198.  
  6199. Promise.fromNode = Promise.fromCallback = function(fn) {
  6200. var ret = new Promise(INTERNAL);
  6201. ret._captureStackTrace();
  6202. var multiArgs = arguments.length > 1 ? !!Object(arguments[1]).multiArgs
  6203. : false;
  6204. var result = tryCatch(fn)(nodebackForPromise(ret, multiArgs));
  6205. if (result === errorObj) {
  6206. ret._rejectCallback(result.e, true);
  6207. }
  6208. if (!ret._isFateSealed()) ret._setAsyncGuaranteed();
  6209. return ret;
  6210. };
  6211.  
  6212. Promise.all = function (promises) {
  6213. return new PromiseArray(promises).promise();
  6214. };
  6215.  
  6216. Promise.cast = function (obj) {
  6217. var ret = tryConvertToPromise(obj);
  6218. if (!(ret instanceof Promise)) {
  6219. ret = new Promise(INTERNAL);
  6220. ret._captureStackTrace();
  6221. ret._setFulfilled();
  6222. ret._rejectionHandler0 = obj;
  6223. }
  6224. return ret;
  6225. };
  6226.  
  6227. Promise.resolve = Promise.fulfilled = Promise.cast;
  6228.  
  6229. Promise.reject = Promise.rejected = function (reason) {
  6230. var ret = new Promise(INTERNAL);
  6231. ret._captureStackTrace();
  6232. ret._rejectCallback(reason, true);
  6233. return ret;
  6234. };
  6235.  
  6236. Promise.setScheduler = function(fn) {
  6237. if (typeof fn !== "function") {
  6238. throw new TypeError("expecting a function but got " + util.classString(fn));
  6239. }
  6240. return async.setScheduler(fn);
  6241. };
  6242.  
  6243. Promise.prototype._then = function (
  6244. didFulfill,
  6245. didReject,
  6246. _, receiver,
  6247. internalData
  6248. ) {
  6249. var haveInternalData = internalData !== undefined;
  6250. var promise = haveInternalData ? internalData : new Promise(INTERNAL);
  6251. var target = this._target();
  6252. var bitField = target._bitField;
  6253.  
  6254. if (!haveInternalData) {
  6255. promise._propagateFrom(this, 3);
  6256. promise._captureStackTrace();
  6257. if (receiver === undefined &&
  6258. ((this._bitField & 2097152) !== 0)) {
  6259. if (!((bitField & 50397184) === 0)) {
  6260. receiver = this._boundValue();
  6261. } else {
  6262. receiver = target === this ? undefined : this._boundTo;
  6263. }
  6264. }
  6265. this._fireEvent("promiseChained", this, promise);
  6266. }
  6267.  
  6268. var domain = getDomain();
  6269. if (!((bitField & 50397184) === 0)) {
  6270. var handler, value, settler = target._settlePromiseCtx;
  6271. if (((bitField & 33554432) !== 0)) {
  6272. value = target._rejectionHandler0;
  6273. handler = didFulfill;
  6274. } else if (((bitField & 16777216) !== 0)) {
  6275. value = target._fulfillmentHandler0;
  6276. handler = didReject;
  6277. target._unsetRejectionIsUnhandled();
  6278. } else {
  6279. settler = target._settlePromiseLateCancellationObserver;
  6280. value = new CancellationError("late cancellation observer");
  6281. target._attachExtraTrace(value);
  6282. handler = didReject;
  6283. }
  6284.  
  6285. async.invoke(settler, target, {
  6286. handler: domain === null ? handler
  6287. : (typeof handler === "function" &&
  6288. util.domainBind(domain, handler)),
  6289. promise: promise,
  6290. receiver: receiver,
  6291. value: value
  6292. });
  6293. } else {
  6294. target._addCallbacks(didFulfill, didReject, promise, receiver, domain);
  6295. }
  6296.  
  6297. return promise;
  6298. };
  6299.  
  6300. Promise.prototype._length = function () {
  6301. return this._bitField & 65535;
  6302. };
  6303.  
  6304. Promise.prototype._isFateSealed = function () {
  6305. return (this._bitField & 117506048) !== 0;
  6306. };
  6307.  
  6308. Promise.prototype._isFollowing = function () {
  6309. return (this._bitField & 67108864) === 67108864;
  6310. };
  6311.  
  6312. Promise.prototype._setLength = function (len) {
  6313. this._bitField = (this._bitField & -65536) |
  6314. (len & 65535);
  6315. };
  6316.  
  6317. Promise.prototype._setFulfilled = function () {
  6318. this._bitField = this._bitField | 33554432;
  6319. this._fireEvent("promiseFulfilled", this);
  6320. };
  6321.  
  6322. Promise.prototype._setRejected = function () {
  6323. this._bitField = this._bitField | 16777216;
  6324. this._fireEvent("promiseRejected", this);
  6325. };
  6326.  
  6327. Promise.prototype._setFollowing = function () {
  6328. this._bitField = this._bitField | 67108864;
  6329. this._fireEvent("promiseResolved", this);
  6330. };
  6331.  
  6332. Promise.prototype._setIsFinal = function () {
  6333. this._bitField = this._bitField | 4194304;
  6334. };
  6335.  
  6336. Promise.prototype._isFinal = function () {
  6337. return (this._bitField & 4194304) > 0;
  6338. };
  6339.  
  6340. Promise.prototype._unsetCancelled = function() {
  6341. this._bitField = this._bitField & (~65536);
  6342. };
  6343.  
  6344. Promise.prototype._setCancelled = function() {
  6345. this._bitField = this._bitField | 65536;
  6346. this._fireEvent("promiseCancelled", this);
  6347. };
  6348.  
  6349. Promise.prototype._setWillBeCancelled = function() {
  6350. this._bitField = this._bitField | 8388608;
  6351. };
  6352.  
  6353. Promise.prototype._setAsyncGuaranteed = function() {
  6354. if (async.hasCustomScheduler()) return;
  6355. this._bitField = this._bitField | 134217728;
  6356. };
  6357.  
  6358. Promise.prototype._receiverAt = function (index) {
  6359. var ret = index === 0 ? this._receiver0 : this[
  6360. index * 4 - 4 + 3];
  6361. if (ret === UNDEFINED_BINDING) {
  6362. return undefined;
  6363. } else if (ret === undefined && this._isBound()) {
  6364. return this._boundValue();
  6365. }
  6366. return ret;
  6367. };
  6368.  
  6369. Promise.prototype._promiseAt = function (index) {
  6370. return this[
  6371. index * 4 - 4 + 2];
  6372. };
  6373.  
  6374. Promise.prototype._fulfillmentHandlerAt = function (index) {
  6375. return this[
  6376. index * 4 - 4 + 0];
  6377. };
  6378.  
  6379. Promise.prototype._rejectionHandlerAt = function (index) {
  6380. return this[
  6381. index * 4 - 4 + 1];
  6382. };
  6383.  
  6384. Promise.prototype._boundValue = function() {};
  6385.  
  6386. Promise.prototype._migrateCallback0 = function (follower) {
  6387. var bitField = follower._bitField;
  6388. var fulfill = follower._fulfillmentHandler0;
  6389. var reject = follower._rejectionHandler0;
  6390. var promise = follower._promise0;
  6391. var receiver = follower._receiverAt(0);
  6392. if (receiver === undefined) receiver = UNDEFINED_BINDING;
  6393. this._addCallbacks(fulfill, reject, promise, receiver, null);
  6394. };
  6395.  
  6396. Promise.prototype._migrateCallbackAt = function (follower, index) {
  6397. var fulfill = follower._fulfillmentHandlerAt(index);
  6398. var reject = follower._rejectionHandlerAt(index);
  6399. var promise = follower._promiseAt(index);
  6400. var receiver = follower._receiverAt(index);
  6401. if (receiver === undefined) receiver = UNDEFINED_BINDING;
  6402. this._addCallbacks(fulfill, reject, promise, receiver, null);
  6403. };
  6404.  
  6405. Promise.prototype._addCallbacks = function (
  6406. fulfill,
  6407. reject,
  6408. promise,
  6409. receiver,
  6410. domain
  6411. ) {
  6412. var index = this._length();
  6413.  
  6414. if (index >= 65535 - 4) {
  6415. index = 0;
  6416. this._setLength(0);
  6417. }
  6418.  
  6419. if (index === 0) {
  6420. this._promise0 = promise;
  6421. this._receiver0 = receiver;
  6422. if (typeof fulfill === "function") {
  6423. this._fulfillmentHandler0 =
  6424. domain === null ? fulfill : util.domainBind(domain, fulfill);
  6425. }
  6426. if (typeof reject === "function") {
  6427. this._rejectionHandler0 =
  6428. domain === null ? reject : util.domainBind(domain, reject);
  6429. }
  6430. } else {
  6431. var base = index * 4 - 4;
  6432. this[base + 2] = promise;
  6433. this[base + 3] = receiver;
  6434. if (typeof fulfill === "function") {
  6435. this[base + 0] =
  6436. domain === null ? fulfill : util.domainBind(domain, fulfill);
  6437. }
  6438. if (typeof reject === "function") {
  6439. this[base + 1] =
  6440. domain === null ? reject : util.domainBind(domain, reject);
  6441. }
  6442. }
  6443. this._setLength(index + 1);
  6444. return index;
  6445. };
  6446.  
  6447. Promise.prototype._proxy = function (proxyable, arg) {
  6448. this._addCallbacks(undefined, undefined, arg, proxyable, null);
  6449. };
  6450.  
  6451. Promise.prototype._resolveCallback = function(value, shouldBind) {
  6452. if (((this._bitField & 117506048) !== 0)) return;
  6453. if (value === this)
  6454. return this._rejectCallback(makeSelfResolutionError(), false);
  6455. var maybePromise = tryConvertToPromise(value, this);
  6456. if (!(maybePromise instanceof Promise)) return this._fulfill(value);
  6457.  
  6458. if (shouldBind) this._propagateFrom(maybePromise, 2);
  6459.  
  6460. var promise = maybePromise._target();
  6461.  
  6462. if (promise === this) {
  6463. this._reject(makeSelfResolutionError());
  6464. return;
  6465. }
  6466.  
  6467. var bitField = promise._bitField;
  6468. if (((bitField & 50397184) === 0)) {
  6469. var len = this._length();
  6470. if (len > 0) promise._migrateCallback0(this);
  6471. for (var i = 1; i < len; ++i) {
  6472. promise._migrateCallbackAt(this, i);
  6473. }
  6474. this._setFollowing();
  6475. this._setLength(0);
  6476. this._setFollowee(promise);
  6477. } else if (((bitField & 33554432) !== 0)) {
  6478. this._fulfill(promise._value());
  6479. } else if (((bitField & 16777216) !== 0)) {
  6480. this._reject(promise._reason());
  6481. } else {
  6482. var reason = new CancellationError("late cancellation observer");
  6483. promise._attachExtraTrace(reason);
  6484. this._reject(reason);
  6485. }
  6486. };
  6487.  
  6488. Promise.prototype._rejectCallback =
  6489. function(reason, synchronous, ignoreNonErrorWarnings) {
  6490. var trace = util.ensureErrorObject(reason);
  6491. var hasStack = trace === reason;
  6492. if (!hasStack && !ignoreNonErrorWarnings && debug.warnings()) {
  6493. var message = "a promise was rejected with a non-error: " +
  6494. util.classString(reason);
  6495. this._warn(message, true);
  6496. }
  6497. this._attachExtraTrace(trace, synchronous ? hasStack : false);
  6498. this._reject(reason);
  6499. };
  6500.  
  6501. Promise.prototype._resolveFromExecutor = function (executor) {
  6502. var promise = this;
  6503. this._captureStackTrace();
  6504. this._pushContext();
  6505. var synchronous = true;
  6506. var r = this._execute(executor, function(value) {
  6507. promise._resolveCallback(value);
  6508. }, function (reason) {
  6509. promise._rejectCallback(reason, synchronous);
  6510. });
  6511. synchronous = false;
  6512. this._popContext();
  6513.  
  6514. if (r !== undefined) {
  6515. promise._rejectCallback(r, true);
  6516. }
  6517. };
  6518.  
  6519. Promise.prototype._settlePromiseFromHandler = function (
  6520. handler, receiver, value, promise
  6521. ) {
  6522. var bitField = promise._bitField;
  6523. if (((bitField & 65536) !== 0)) return;
  6524. promise._pushContext();
  6525. var x;
  6526. if (receiver === APPLY) {
  6527. if (!value || typeof value.length !== "number") {
  6528. x = errorObj;
  6529. x.e = new TypeError("cannot .spread() a non-array: " +
  6530. util.classString(value));
  6531. } else {
  6532. x = tryCatch(handler).apply(this._boundValue(), value);
  6533. }
  6534. } else {
  6535. x = tryCatch(handler).call(receiver, value);
  6536. }
  6537. var promiseCreated = promise._popContext();
  6538. bitField = promise._bitField;
  6539. if (((bitField & 65536) !== 0)) return;
  6540.  
  6541. if (x === NEXT_FILTER) {
  6542. promise._reject(value);
  6543. } else if (x === errorObj) {
  6544. promise._rejectCallback(x.e, false);
  6545. } else {
  6546. debug.checkForgottenReturns(x, promiseCreated, "", promise, this);
  6547. promise._resolveCallback(x);
  6548. }
  6549. };
  6550.  
  6551. Promise.prototype._target = function() {
  6552. var ret = this;
  6553. while (ret._isFollowing()) ret = ret._followee();
  6554. return ret;
  6555. };
  6556.  
  6557. Promise.prototype._followee = function() {
  6558. return this._rejectionHandler0;
  6559. };
  6560.  
  6561. Promise.prototype._setFollowee = function(promise) {
  6562. this._rejectionHandler0 = promise;
  6563. };
  6564.  
  6565. Promise.prototype._settlePromise = function(promise, handler, receiver, value) {
  6566. var isPromise = promise instanceof Promise;
  6567. var bitField = this._bitField;
  6568. var asyncGuaranteed = ((bitField & 134217728) !== 0);
  6569. if (((bitField & 65536) !== 0)) {
  6570. if (isPromise) promise._invokeInternalOnCancel();
  6571.  
  6572. if (receiver instanceof PassThroughHandlerContext &&
  6573. receiver.isFinallyHandler()) {
  6574. receiver.cancelPromise = promise;
  6575. if (tryCatch(handler).call(receiver, value) === errorObj) {
  6576. promise._reject(errorObj.e);
  6577. }
  6578. } else if (handler === reflectHandler) {
  6579. promise._fulfill(reflectHandler.call(receiver));
  6580. } else if (receiver instanceof Proxyable) {
  6581. receiver._promiseCancelled(promise);
  6582. } else if (isPromise || promise instanceof PromiseArray) {
  6583. promise._cancel();
  6584. } else {
  6585. receiver.cancel();
  6586. }
  6587. } else if (typeof handler === "function") {
  6588. if (!isPromise) {
  6589. handler.call(receiver, value, promise);
  6590. } else {
  6591. if (asyncGuaranteed) promise._setAsyncGuaranteed();
  6592. this._settlePromiseFromHandler(handler, receiver, value, promise);
  6593. }
  6594. } else if (receiver instanceof Proxyable) {
  6595. if (!receiver._isResolved()) {
  6596. if (((bitField & 33554432) !== 0)) {
  6597. receiver._promiseFulfilled(value, promise);
  6598. } else {
  6599. receiver._promiseRejected(value, promise);
  6600. }
  6601. }
  6602. } else if (isPromise) {
  6603. if (asyncGuaranteed) promise._setAsyncGuaranteed();
  6604. if (((bitField & 33554432) !== 0)) {
  6605. promise._fulfill(value);
  6606. } else {
  6607. promise._reject(value);
  6608. }
  6609. }
  6610. };
  6611.  
  6612. Promise.prototype._settlePromiseLateCancellationObserver = function(ctx) {
  6613. var handler = ctx.handler;
  6614. var promise = ctx.promise;
  6615. var receiver = ctx.receiver;
  6616. var value = ctx.value;
  6617. if (typeof handler === "function") {
  6618. if (!(promise instanceof Promise)) {
  6619. handler.call(receiver, value, promise);
  6620. } else {
  6621. this._settlePromiseFromHandler(handler, receiver, value, promise);
  6622. }
  6623. } else if (promise instanceof Promise) {
  6624. promise._reject(value);
  6625. }
  6626. };
  6627.  
  6628. Promise.prototype._settlePromiseCtx = function(ctx) {
  6629. this._settlePromise(ctx.promise, ctx.handler, ctx.receiver, ctx.value);
  6630. };
  6631.  
  6632. Promise.prototype._settlePromise0 = function(handler, value, bitField) {
  6633. var promise = this._promise0;
  6634. var receiver = this._receiverAt(0);
  6635. this._promise0 = undefined;
  6636. this._receiver0 = undefined;
  6637. this._settlePromise(promise, handler, receiver, value);
  6638. };
  6639.  
  6640. Promise.prototype._clearCallbackDataAtIndex = function(index) {
  6641. var base = index * 4 - 4;
  6642. this[base + 2] =
  6643. this[base + 3] =
  6644. this[base + 0] =
  6645. this[base + 1] = undefined;
  6646. };
  6647.  
  6648. Promise.prototype._fulfill = function (value) {
  6649. var bitField = this._bitField;
  6650. if (((bitField & 117506048) >>> 16)) return;
  6651. if (value === this) {
  6652. var err = makeSelfResolutionError();
  6653. this._attachExtraTrace(err);
  6654. return this._reject(err);
  6655. }
  6656. this._setFulfilled();
  6657. this._rejectionHandler0 = value;
  6658.  
  6659. if ((bitField & 65535) > 0) {
  6660. if (((bitField & 134217728) !== 0)) {
  6661. this._settlePromises();
  6662. } else {
  6663. async.settlePromises(this);
  6664. }
  6665. }
  6666. };
  6667.  
  6668. Promise.prototype._reject = function (reason) {
  6669. var bitField = this._bitField;
  6670. if (((bitField & 117506048) >>> 16)) return;
  6671. this._setRejected();
  6672. this._fulfillmentHandler0 = reason;
  6673.  
  6674. if (this._isFinal()) {
  6675. return async.fatalError(reason, util.isNode);
  6676. }
  6677.  
  6678. if ((bitField & 65535) > 0) {
  6679. async.settlePromises(this);
  6680. } else {
  6681. this._ensurePossibleRejectionHandled();
  6682. }
  6683. };
  6684.  
  6685. Promise.prototype._fulfillPromises = function (len, value) {
  6686. for (var i = 1; i < len; i++) {
  6687. var handler = this._fulfillmentHandlerAt(i);
  6688. var promise = this._promiseAt(i);
  6689. var receiver = this._receiverAt(i);
  6690. this._clearCallbackDataAtIndex(i);
  6691. this._settlePromise(promise, handler, receiver, value);
  6692. }
  6693. };
  6694.  
  6695. Promise.prototype._rejectPromises = function (len, reason) {
  6696. for (var i = 1; i < len; i++) {
  6697. var handler = this._rejectionHandlerAt(i);
  6698. var promise = this._promiseAt(i);
  6699. var receiver = this._receiverAt(i);
  6700. this._clearCallbackDataAtIndex(i);
  6701. this._settlePromise(promise, handler, receiver, reason);
  6702. }
  6703. };
  6704.  
  6705. Promise.prototype._settlePromises = function () {
  6706. var bitField = this._bitField;
  6707. var len = (bitField & 65535);
  6708.  
  6709. if (len > 0) {
  6710. if (((bitField & 16842752) !== 0)) {
  6711. var reason = this._fulfillmentHandler0;
  6712. this._settlePromise0(this._rejectionHandler0, reason, bitField);
  6713. this._rejectPromises(len, reason);
  6714. } else {
  6715. var value = this._rejectionHandler0;
  6716. this._settlePromise0(this._fulfillmentHandler0, value, bitField);
  6717. this._fulfillPromises(len, value);
  6718. }
  6719. this._setLength(0);
  6720. }
  6721. this._clearCancellationData();
  6722. };
  6723.  
  6724. Promise.prototype._settledValue = function() {
  6725. var bitField = this._bitField;
  6726. if (((bitField & 33554432) !== 0)) {
  6727. return this._rejectionHandler0;
  6728. } else if (((bitField & 16777216) !== 0)) {
  6729. return this._fulfillmentHandler0;
  6730. }
  6731. };
  6732.  
  6733. function deferResolve(v) {this.promise._resolveCallback(v);}
  6734. function deferReject(v) {this.promise._rejectCallback(v, false);}
  6735.  
  6736. Promise.defer = Promise.pending = function() {
  6737. debug.deprecated("Promise.defer", "new Promise");
  6738. var promise = new Promise(INTERNAL);
  6739. return {
  6740. promise: promise,
  6741. resolve: deferResolve,
  6742. reject: deferReject
  6743. };
  6744. };
  6745.  
  6746. util.notEnumerableProp(Promise,
  6747. "_makeSelfResolutionError",
  6748. makeSelfResolutionError);
  6749.  
  6750. _dereq_("./method")(Promise, INTERNAL, tryConvertToPromise, apiRejection,
  6751. debug);
  6752. _dereq_("./bind")(Promise, INTERNAL, tryConvertToPromise, debug);
  6753. _dereq_("./cancel")(Promise, PromiseArray, apiRejection, debug);
  6754. _dereq_("./direct_resolve")(Promise);
  6755. _dereq_("./synchronous_inspection")(Promise);
  6756. _dereq_("./join")(
  6757. Promise, PromiseArray, tryConvertToPromise, INTERNAL, async, getDomain);
  6758. Promise.Promise = Promise;
  6759. Promise.version = "3.4.7";
  6760. _dereq_('./map.js')(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL, debug);
  6761. _dereq_('./call_get.js')(Promise);
  6762. _dereq_('./using.js')(Promise, apiRejection, tryConvertToPromise, createContext, INTERNAL, debug);
  6763. _dereq_('./timers.js')(Promise, INTERNAL, debug);
  6764. _dereq_('./generators.js')(Promise, apiRejection, INTERNAL, tryConvertToPromise, Proxyable, debug);
  6765. _dereq_('./nodeify.js')(Promise);
  6766. _dereq_('./promisify.js')(Promise, INTERNAL);
  6767. _dereq_('./props.js')(Promise, PromiseArray, tryConvertToPromise, apiRejection);
  6768. _dereq_('./race.js')(Promise, INTERNAL, tryConvertToPromise, apiRejection);
  6769. _dereq_('./reduce.js')(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL, debug);
  6770. _dereq_('./settle.js')(Promise, PromiseArray, debug);
  6771. _dereq_('./some.js')(Promise, PromiseArray, apiRejection);
  6772. _dereq_('./filter.js')(Promise, INTERNAL);
  6773. _dereq_('./each.js')(Promise, INTERNAL);
  6774. _dereq_('./any.js')(Promise);
  6775.  
  6776. util.toFastProperties(Promise);
  6777. util.toFastProperties(Promise.prototype);
  6778. function fillTypes(value) {
  6779. var p = new Promise(INTERNAL);
  6780. p._fulfillmentHandler0 = value;
  6781. p._rejectionHandler0 = value;
  6782. p._promise0 = value;
  6783. p._receiver0 = value;
  6784. }
  6785. // Complete slack tracking, opt out of field-type tracking and
  6786. // stabilize map
  6787. fillTypes({a: 1});
  6788. fillTypes({b: 2});
  6789. fillTypes({c: 3});
  6790. fillTypes(1);
  6791. fillTypes(function(){});
  6792. fillTypes(undefined);
  6793. fillTypes(false);
  6794. fillTypes(new Promise(INTERNAL));
  6795. debug.setBounds(Async.firstLineError, util.lastLineError);
  6796. return Promise;
  6797.  
  6798. };
  6799.  
  6800. },{"./any.js":1,"./async":2,"./bind":3,"./call_get.js":5,"./cancel":6,"./catch_filter":7,"./context":8,"./debuggability":9,"./direct_resolve":10,"./each.js":11,"./errors":12,"./es5":13,"./filter.js":14,"./finally":15,"./generators.js":16,"./join":17,"./map.js":18,"./method":19,"./nodeback":20,"./nodeify.js":21,"./promise_array":23,"./promisify.js":24,"./props.js":25,"./race.js":27,"./reduce.js":28,"./settle.js":30,"./some.js":31,"./synchronous_inspection":32,"./thenables":33,"./timers.js":34,"./using.js":35,"./util":36}],23:[function(_dereq_,module,exports){
  6801. "use strict";
  6802. module.exports = function(Promise, INTERNAL, tryConvertToPromise,
  6803. apiRejection, Proxyable) {
  6804. var util = _dereq_("./util");
  6805. var isArray = util.isArray;
  6806.  
  6807. function toResolutionValue(val) {
  6808. switch(val) {
  6809. case -2: return [];
  6810. case -3: return {};
  6811. }
  6812. }
  6813.  
  6814. function PromiseArray(values) {
  6815. var promise = this._promise = new Promise(INTERNAL);
  6816. if (values instanceof Promise) {
  6817. promise._propagateFrom(values, 3);
  6818. }
  6819. promise._setOnCancel(this);
  6820. this._values = values;
  6821. this._length = 0;
  6822. this._totalResolved = 0;
  6823. this._init(undefined, -2);
  6824. }
  6825. util.inherits(PromiseArray, Proxyable);
  6826.  
  6827. PromiseArray.prototype.length = function () {
  6828. return this._length;
  6829. };
  6830.  
  6831. PromiseArray.prototype.promise = function () {
  6832. return this._promise;
  6833. };
  6834.  
  6835. PromiseArray.prototype._init = function init(_, resolveValueIfEmpty) {
  6836. var values = tryConvertToPromise(this._values, this._promise);
  6837. if (values instanceof Promise) {
  6838. values = values._target();
  6839. var bitField = values._bitField;
  6840. ;
  6841. this._values = values;
  6842.  
  6843. if (((bitField & 50397184) === 0)) {
  6844. this._promise._setAsyncGuaranteed();
  6845. return values._then(
  6846. init,
  6847. this._reject,
  6848. undefined,
  6849. this,
  6850. resolveValueIfEmpty
  6851. );
  6852. } else if (((bitField & 33554432) !== 0)) {
  6853. values = values._value();
  6854. } else if (((bitField & 16777216) !== 0)) {
  6855. return this._reject(values._reason());
  6856. } else {
  6857. return this._cancel();
  6858. }
  6859. }
  6860. values = util.asArray(values);
  6861. if (values === null) {
  6862. var err = apiRejection(
  6863. "expecting an array or an iterable object but got " + util.classString(values)).reason();
  6864. this._promise._rejectCallback(err, false);
  6865. return;
  6866. }
  6867.  
  6868. if (values.length === 0) {
  6869. if (resolveValueIfEmpty === -5) {
  6870. this._resolveEmptyArray();
  6871. }
  6872. else {
  6873. this._resolve(toResolutionValue(resolveValueIfEmpty));
  6874. }
  6875. return;
  6876. }
  6877. this._iterate(values);
  6878. };
  6879.  
  6880. PromiseArray.prototype._iterate = function(values) {
  6881. var len = this.getActualLength(values.length);
  6882. this._length = len;
  6883. this._values = this.shouldCopyValues() ? new Array(len) : this._values;
  6884. var result = this._promise;
  6885. var isResolved = false;
  6886. var bitField = null;
  6887. for (var i = 0; i < len; ++i) {
  6888. var maybePromise = tryConvertToPromise(values[i], result);
  6889.  
  6890. if (maybePromise instanceof Promise) {
  6891. maybePromise = maybePromise._target();
  6892. bitField = maybePromise._bitField;
  6893. } else {
  6894. bitField = null;
  6895. }
  6896.  
  6897. if (isResolved) {
  6898. if (bitField !== null) {
  6899. maybePromise.suppressUnhandledRejections();
  6900. }
  6901. } else if (bitField !== null) {
  6902. if (((bitField & 50397184) === 0)) {
  6903. maybePromise._proxy(this, i);
  6904. this._values[i] = maybePromise;
  6905. } else if (((bitField & 33554432) !== 0)) {
  6906. isResolved = this._promiseFulfilled(maybePromise._value(), i);
  6907. } else if (((bitField & 16777216) !== 0)) {
  6908. isResolved = this._promiseRejected(maybePromise._reason(), i);
  6909. } else {
  6910. isResolved = this._promiseCancelled(i);
  6911. }
  6912. } else {
  6913. isResolved = this._promiseFulfilled(maybePromise, i);
  6914. }
  6915. }
  6916. if (!isResolved) result._setAsyncGuaranteed();
  6917. };
  6918.  
  6919. PromiseArray.prototype._isResolved = function () {
  6920. return this._values === null;
  6921. };
  6922.  
  6923. PromiseArray.prototype._resolve = function (value) {
  6924. this._values = null;
  6925. this._promise._fulfill(value);
  6926. };
  6927.  
  6928. PromiseArray.prototype._cancel = function() {
  6929. if (this._isResolved() || !this._promise._isCancellable()) return;
  6930. this._values = null;
  6931. this._promise._cancel();
  6932. };
  6933.  
  6934. PromiseArray.prototype._reject = function (reason) {
  6935. this._values = null;
  6936. this._promise._rejectCallback(reason, false);
  6937. };
  6938.  
  6939. PromiseArray.prototype._promiseFulfilled = function (value, index) {
  6940. this._values[index] = value;
  6941. var totalResolved = ++this._totalResolved;
  6942. if (totalResolved >= this._length) {
  6943. this._resolve(this._values);
  6944. return true;
  6945. }
  6946. return false;
  6947. };
  6948.  
  6949. PromiseArray.prototype._promiseCancelled = function() {
  6950. this._cancel();
  6951. return true;
  6952. };
  6953.  
  6954. PromiseArray.prototype._promiseRejected = function (reason) {
  6955. this._totalResolved++;
  6956. this._reject(reason);
  6957. return true;
  6958. };
  6959.  
  6960. PromiseArray.prototype._resultCancelled = function() {
  6961. if (this._isResolved()) return;
  6962. var values = this._values;
  6963. this._cancel();
  6964. if (values instanceof Promise) {
  6965. values.cancel();
  6966. } else {
  6967. for (var i = 0; i < values.length; ++i) {
  6968. if (values[i] instanceof Promise) {
  6969. values[i].cancel();
  6970. }
  6971. }
  6972. }
  6973. };
  6974.  
  6975. PromiseArray.prototype.shouldCopyValues = function () {
  6976. return true;
  6977. };
  6978.  
  6979. PromiseArray.prototype.getActualLength = function (len) {
  6980. return len;
  6981. };
  6982.  
  6983. return PromiseArray;
  6984. };
  6985.  
  6986. },{"./util":36}],24:[function(_dereq_,module,exports){
  6987. "use strict";
  6988. module.exports = function(Promise, INTERNAL) {
  6989. var THIS = {};
  6990. var util = _dereq_("./util");
  6991. var nodebackForPromise = _dereq_("./nodeback");
  6992. var withAppended = util.withAppended;
  6993. var maybeWrapAsError = util.maybeWrapAsError;
  6994. var canEvaluate = util.canEvaluate;
  6995. var TypeError = _dereq_("./errors").TypeError;
  6996. var defaultSuffix = "Async";
  6997. var defaultPromisified = {__isPromisified__: true};
  6998. var noCopyProps = [
  6999. "arity", "length",
  7000. "name",
  7001. "arguments",
  7002. "caller",
  7003. "callee",
  7004. "prototype",
  7005. "__isPromisified__"
  7006. ];
  7007. var noCopyPropsPattern = new RegExp("^(?:" + noCopyProps.join("|") + ")$");
  7008.  
  7009. var defaultFilter = function(name) {
  7010. return util.isIdentifier(name) &&
  7011. name.charAt(0) !== "_" &&
  7012. name !== "constructor";
  7013. };
  7014.  
  7015. function propsFilter(key) {
  7016. return !noCopyPropsPattern.test(key);
  7017. }
  7018.  
  7019. function isPromisified(fn) {
  7020. try {
  7021. return fn.__isPromisified__ === true;
  7022. }
  7023. catch (e) {
  7024. return false;
  7025. }
  7026. }
  7027.  
  7028. function hasPromisified(obj, key, suffix) {
  7029. var val = util.getDataPropertyOrDefault(obj, key + suffix,
  7030. defaultPromisified);
  7031. return val ? isPromisified(val) : false;
  7032. }
  7033. function checkValid(ret, suffix, suffixRegexp) {
  7034. for (var i = 0; i < ret.length; i += 2) {
  7035. var key = ret[i];
  7036. if (suffixRegexp.test(key)) {
  7037. var keyWithoutAsyncSuffix = key.replace(suffixRegexp, "");
  7038. for (var j = 0; j < ret.length; j += 2) {
  7039. if (ret[j] === keyWithoutAsyncSuffix) {
  7040. throw new TypeError("Cannot promisify an API that has normal methods with '%s'-suffix\u000a\u000a See http://goo.gl/MqrFmX\u000a"
  7041. .replace("%s", suffix));
  7042. }
  7043. }
  7044. }
  7045. }
  7046. }
  7047.  
  7048. function promisifiableMethods(obj, suffix, suffixRegexp, filter) {
  7049. var keys = util.inheritedDataKeys(obj);
  7050. var ret = [];
  7051. for (var i = 0; i < keys.length; ++i) {
  7052. var key = keys[i];
  7053. var value = obj[key];
  7054. var passesDefaultFilter = filter === defaultFilter
  7055. ? true : defaultFilter(key, value, obj);
  7056. if (typeof value === "function" &&
  7057. !isPromisified(value) &&
  7058. !hasPromisified(obj, key, suffix) &&
  7059. filter(key, value, obj, passesDefaultFilter)) {
  7060. ret.push(key, value);
  7061. }
  7062. }
  7063. checkValid(ret, suffix, suffixRegexp);
  7064. return ret;
  7065. }
  7066.  
  7067. var escapeIdentRegex = function(str) {
  7068. return str.replace(/([$])/, "\\$");
  7069. };
  7070.  
  7071. var makeNodePromisifiedEval;
  7072. if (!true) {
  7073. var switchCaseArgumentOrder = function(likelyArgumentCount) {
  7074. var ret = [likelyArgumentCount];
  7075. var min = Math.max(0, likelyArgumentCount - 1 - 3);
  7076. for(var i = likelyArgumentCount - 1; i >= min; --i) {
  7077. ret.push(i);
  7078. }
  7079. for(var i = likelyArgumentCount + 1; i <= 3; ++i) {
  7080. ret.push(i);
  7081. }
  7082. return ret;
  7083. };
  7084.  
  7085. var argumentSequence = function(argumentCount) {
  7086. return util.filledRange(argumentCount, "_arg", "");
  7087. };
  7088.  
  7089. var parameterDeclaration = function(parameterCount) {
  7090. return util.filledRange(
  7091. Math.max(parameterCount, 3), "_arg", "");
  7092. };
  7093.  
  7094. var parameterCount = function(fn) {
  7095. if (typeof fn.length === "number") {
  7096. return Math.max(Math.min(fn.length, 1023 + 1), 0);
  7097. }
  7098. return 0;
  7099. };
  7100.  
  7101. makeNodePromisifiedEval =
  7102. function(callback, receiver, originalName, fn, _, multiArgs) {
  7103. var newParameterCount = Math.max(0, parameterCount(fn) - 1);
  7104. var argumentOrder = switchCaseArgumentOrder(newParameterCount);
  7105. var shouldProxyThis = typeof callback === "string" || receiver === THIS;
  7106.  
  7107. function generateCallForArgumentCount(count) {
  7108. var args = argumentSequence(count).join(", ");
  7109. var comma = count > 0 ? ", " : "";
  7110. var ret;
  7111. if (shouldProxyThis) {
  7112. ret = "ret = callback.call(this, {{args}}, nodeback); break;\n";
  7113. } else {
  7114. ret = receiver === undefined
  7115. ? "ret = callback({{args}}, nodeback); break;\n"
  7116. : "ret = callback.call(receiver, {{args}}, nodeback); break;\n";
  7117. }
  7118. return ret.replace("{{args}}", args).replace(", ", comma);
  7119. }
  7120.  
  7121. function generateArgumentSwitchCase() {
  7122. var ret = "";
  7123. for (var i = 0; i < argumentOrder.length; ++i) {
  7124. ret += "case " + argumentOrder[i] +":" +
  7125. generateCallForArgumentCount(argumentOrder[i]);
  7126. }
  7127.  
  7128. ret += " \n\
  7129. default: \n\
  7130. var args = new Array(len + 1); \n\
  7131. var i = 0; \n\
  7132. for (var i = 0; i < len; ++i) { \n\
  7133. args[i] = arguments[i]; \n\
  7134. } \n\
  7135. args[i] = nodeback; \n\
  7136. [CodeForCall] \n\
  7137. break; \n\
  7138. ".replace("[CodeForCall]", (shouldProxyThis
  7139. ? "ret = callback.apply(this, args);\n"
  7140. : "ret = callback.apply(receiver, args);\n"));
  7141. return ret;
  7142. }
  7143.  
  7144. var getFunctionCode = typeof callback === "string"
  7145. ? ("this != null ? this['"+callback+"'] : fn")
  7146. : "fn";
  7147. var body = "'use strict'; \n\
  7148. var ret = function (Parameters) { \n\
  7149. 'use strict'; \n\
  7150. var len = arguments.length; \n\
  7151. var promise = new Promise(INTERNAL); \n\
  7152. promise._captureStackTrace(); \n\
  7153. var nodeback = nodebackForPromise(promise, " + multiArgs + "); \n\
  7154. var ret; \n\
  7155. var callback = tryCatch([GetFunctionCode]); \n\
  7156. switch(len) { \n\
  7157. [CodeForSwitchCase] \n\
  7158. } \n\
  7159. if (ret === errorObj) { \n\
  7160. promise._rejectCallback(maybeWrapAsError(ret.e), true, true);\n\
  7161. } \n\
  7162. if (!promise._isFateSealed()) promise._setAsyncGuaranteed(); \n\
  7163. return promise; \n\
  7164. }; \n\
  7165. notEnumerableProp(ret, '__isPromisified__', true); \n\
  7166. return ret; \n\
  7167. ".replace("[CodeForSwitchCase]", generateArgumentSwitchCase())
  7168. .replace("[GetFunctionCode]", getFunctionCode);
  7169. body = body.replace("Parameters", parameterDeclaration(newParameterCount));
  7170. return new Function("Promise",
  7171. "fn",
  7172. "receiver",
  7173. "withAppended",
  7174. "maybeWrapAsError",
  7175. "nodebackForPromise",
  7176. "tryCatch",
  7177. "errorObj",
  7178. "notEnumerableProp",
  7179. "INTERNAL",
  7180. body)(
  7181. Promise,
  7182. fn,
  7183. receiver,
  7184. withAppended,
  7185. maybeWrapAsError,
  7186. nodebackForPromise,
  7187. util.tryCatch,
  7188. util.errorObj,
  7189. util.notEnumerableProp,
  7190. INTERNAL);
  7191. };
  7192. }
  7193.  
  7194. function makeNodePromisifiedClosure(callback, receiver, _, fn, __, multiArgs) {
  7195. var defaultThis = (function() {return this;})();
  7196. var method = callback;
  7197. if (typeof method === "string") {
  7198. callback = fn;
  7199. }
  7200. function promisified() {
  7201. var _receiver = receiver;
  7202. if (receiver === THIS) _receiver = this;
  7203. var promise = new Promise(INTERNAL);
  7204. promise._captureStackTrace();
  7205. var cb = typeof method === "string" && this !== defaultThis
  7206. ? this[method] : callback;
  7207. var fn = nodebackForPromise(promise, multiArgs);
  7208. try {
  7209. cb.apply(_receiver, withAppended(arguments, fn));
  7210. } catch(e) {
  7211. promise._rejectCallback(maybeWrapAsError(e), true, true);
  7212. }
  7213. if (!promise._isFateSealed()) promise._setAsyncGuaranteed();
  7214. return promise;
  7215. }
  7216. util.notEnumerableProp(promisified, "__isPromisified__", true);
  7217. return promisified;
  7218. }
  7219.  
  7220. var makeNodePromisified = canEvaluate
  7221. ? makeNodePromisifiedEval
  7222. : makeNodePromisifiedClosure;
  7223.  
  7224. function promisifyAll(obj, suffix, filter, promisifier, multiArgs) {
  7225. var suffixRegexp = new RegExp(escapeIdentRegex(suffix) + "$");
  7226. var methods =
  7227. promisifiableMethods(obj, suffix, suffixRegexp, filter);
  7228.  
  7229. for (var i = 0, len = methods.length; i < len; i+= 2) {
  7230. var key = methods[i];
  7231. var fn = methods[i+1];
  7232. var promisifiedKey = key + suffix;
  7233. if (promisifier === makeNodePromisified) {
  7234. obj[promisifiedKey] =
  7235. makeNodePromisified(key, THIS, key, fn, suffix, multiArgs);
  7236. } else {
  7237. var promisified = promisifier(fn, function() {
  7238. return makeNodePromisified(key, THIS, key,
  7239. fn, suffix, multiArgs);
  7240. });
  7241. util.notEnumerableProp(promisified, "__isPromisified__", true);
  7242. obj[promisifiedKey] = promisified;
  7243. }
  7244. }
  7245. util.toFastProperties(obj);
  7246. return obj;
  7247. }
  7248.  
  7249. function promisify(callback, receiver, multiArgs) {
  7250. return makeNodePromisified(callback, receiver, undefined,
  7251. callback, null, multiArgs);
  7252. }
  7253.  
  7254. Promise.promisify = function (fn, options) {
  7255. if (typeof fn !== "function") {
  7256. throw new TypeError("expecting a function but got " + util.classString(fn));
  7257. }
  7258. if (isPromisified(fn)) {
  7259. return fn;
  7260. }
  7261. options = Object(options);
  7262. var receiver = options.context === undefined ? THIS : options.context;
  7263. var multiArgs = !!options.multiArgs;
  7264. var ret = promisify(fn, receiver, multiArgs);
  7265. util.copyDescriptors(fn, ret, propsFilter);
  7266. return ret;
  7267. };
  7268.  
  7269. Promise.promisifyAll = function (target, options) {
  7270. if (typeof target !== "function" && typeof target !== "object") {
  7271. throw new TypeError("the target of promisifyAll must be an object or a function\u000a\u000a See http://goo.gl/MqrFmX\u000a");
  7272. }
  7273. options = Object(options);
  7274. var multiArgs = !!options.multiArgs;
  7275. var suffix = options.suffix;
  7276. if (typeof suffix !== "string") suffix = defaultSuffix;
  7277. var filter = options.filter;
  7278. if (typeof filter !== "function") filter = defaultFilter;
  7279. var promisifier = options.promisifier;
  7280. if (typeof promisifier !== "function") promisifier = makeNodePromisified;
  7281.  
  7282. if (!util.isIdentifier(suffix)) {
  7283. throw new RangeError("suffix must be a valid identifier\u000a\u000a See http://goo.gl/MqrFmX\u000a");
  7284. }
  7285.  
  7286. var keys = util.inheritedDataKeys(target);
  7287. for (var i = 0; i < keys.length; ++i) {
  7288. var value = target[keys[i]];
  7289. if (keys[i] !== "constructor" &&
  7290. util.isClass(value)) {
  7291. promisifyAll(value.prototype, suffix, filter, promisifier,
  7292. multiArgs);
  7293. promisifyAll(value, suffix, filter, promisifier, multiArgs);
  7294. }
  7295. }
  7296.  
  7297. return promisifyAll(target, suffix, filter, promisifier, multiArgs);
  7298. };
  7299. };
  7300.  
  7301.  
  7302. },{"./errors":12,"./nodeback":20,"./util":36}],25:[function(_dereq_,module,exports){
  7303. "use strict";
  7304. module.exports = function(
  7305. Promise, PromiseArray, tryConvertToPromise, apiRejection) {
  7306. var util = _dereq_("./util");
  7307. var isObject = util.isObject;
  7308. var es5 = _dereq_("./es5");
  7309. var Es6Map;
  7310. if (typeof Map === "function") Es6Map = Map;
  7311.  
  7312. var mapToEntries = (function() {
  7313. var index = 0;
  7314. var size = 0;
  7315.  
  7316. function extractEntry(value, key) {
  7317. this[index] = value;
  7318. this[index + size] = key;
  7319. index++;
  7320. }
  7321.  
  7322. return function mapToEntries(map) {
  7323. size = map.size;
  7324. index = 0;
  7325. var ret = new Array(map.size * 2);
  7326. map.forEach(extractEntry, ret);
  7327. return ret;
  7328. };
  7329. })();
  7330.  
  7331. var entriesToMap = function(entries) {
  7332. var ret = new Es6Map();
  7333. var length = entries.length / 2 | 0;
  7334. for (var i = 0; i < length; ++i) {
  7335. var key = entries[length + i];
  7336. var value = entries[i];
  7337. ret.set(key, value);
  7338. }
  7339. return ret;
  7340. };
  7341.  
  7342. function PropertiesPromiseArray(obj) {
  7343. var isMap = false;
  7344. var entries;
  7345. if (Es6Map !== undefined && obj instanceof Es6Map) {
  7346. entries = mapToEntries(obj);
  7347. isMap = true;
  7348. } else {
  7349. var keys = es5.keys(obj);
  7350. var len = keys.length;
  7351. entries = new Array(len * 2);
  7352. for (var i = 0; i < len; ++i) {
  7353. var key = keys[i];
  7354. entries[i] = obj[key];
  7355. entries[i + len] = key;
  7356. }
  7357. }
  7358. this.constructor$(entries);
  7359. this._isMap = isMap;
  7360. this._init$(undefined, -3);
  7361. }
  7362. util.inherits(PropertiesPromiseArray, PromiseArray);
  7363.  
  7364. PropertiesPromiseArray.prototype._init = function () {};
  7365.  
  7366. PropertiesPromiseArray.prototype._promiseFulfilled = function (value, index) {
  7367. this._values[index] = value;
  7368. var totalResolved = ++this._totalResolved;
  7369. if (totalResolved >= this._length) {
  7370. var val;
  7371. if (this._isMap) {
  7372. val = entriesToMap(this._values);
  7373. } else {
  7374. val = {};
  7375. var keyOffset = this.length();
  7376. for (var i = 0, len = this.length(); i < len; ++i) {
  7377. val[this._values[i + keyOffset]] = this._values[i];
  7378. }
  7379. }
  7380. this._resolve(val);
  7381. return true;
  7382. }
  7383. return false;
  7384. };
  7385.  
  7386. PropertiesPromiseArray.prototype.shouldCopyValues = function () {
  7387. return false;
  7388. };
  7389.  
  7390. PropertiesPromiseArray.prototype.getActualLength = function (len) {
  7391. return len >> 1;
  7392. };
  7393.  
  7394. function props(promises) {
  7395. var ret;
  7396. var castValue = tryConvertToPromise(promises);
  7397.  
  7398. if (!isObject(castValue)) {
  7399. return apiRejection("cannot await properties of a non-object\u000a\u000a See http://goo.gl/MqrFmX\u000a");
  7400. } else if (castValue instanceof Promise) {
  7401. ret = castValue._then(
  7402. Promise.props, undefined, undefined, undefined, undefined);
  7403. } else {
  7404. ret = new PropertiesPromiseArray(castValue).promise();
  7405. }
  7406.  
  7407. if (castValue instanceof Promise) {
  7408. ret._propagateFrom(castValue, 2);
  7409. }
  7410. return ret;
  7411. }
  7412.  
  7413. Promise.prototype.props = function () {
  7414. return props(this);
  7415. };
  7416.  
  7417. Promise.props = function (promises) {
  7418. return props(promises);
  7419. };
  7420. };
  7421.  
  7422. },{"./es5":13,"./util":36}],26:[function(_dereq_,module,exports){
  7423. "use strict";
  7424. function arrayMove(src, srcIndex, dst, dstIndex, len) {
  7425. for (var j = 0; j < len; ++j) {
  7426. dst[j + dstIndex] = src[j + srcIndex];
  7427. src[j + srcIndex] = void 0;
  7428. }
  7429. }
  7430.  
  7431. function Queue(capacity) {
  7432. this._capacity = capacity;
  7433. this._length = 0;
  7434. this._front = 0;
  7435. }
  7436.  
  7437. Queue.prototype._willBeOverCapacity = function (size) {
  7438. return this._capacity < size;
  7439. };
  7440.  
  7441. Queue.prototype._pushOne = function (arg) {
  7442. var length = this.length();
  7443. this._checkCapacity(length + 1);
  7444. var i = (this._front + length) & (this._capacity - 1);
  7445. this[i] = arg;
  7446. this._length = length + 1;
  7447. };
  7448.  
  7449. Queue.prototype.push = function (fn, receiver, arg) {
  7450. var length = this.length() + 3;
  7451. if (this._willBeOverCapacity(length)) {
  7452. this._pushOne(fn);
  7453. this._pushOne(receiver);
  7454. this._pushOne(arg);
  7455. return;
  7456. }
  7457. var j = this._front + length - 3;
  7458. this._checkCapacity(length);
  7459. var wrapMask = this._capacity - 1;
  7460. this[(j + 0) & wrapMask] = fn;
  7461. this[(j + 1) & wrapMask] = receiver;
  7462. this[(j + 2) & wrapMask] = arg;
  7463. this._length = length;
  7464. };
  7465.  
  7466. Queue.prototype.shift = function () {
  7467. var front = this._front,
  7468. ret = this[front];
  7469.  
  7470. this[front] = undefined;
  7471. this._front = (front + 1) & (this._capacity - 1);
  7472. this._length--;
  7473. return ret;
  7474. };
  7475.  
  7476. Queue.prototype.length = function () {
  7477. return this._length;
  7478. };
  7479.  
  7480. Queue.prototype._checkCapacity = function (size) {
  7481. if (this._capacity < size) {
  7482. this._resizeTo(this._capacity << 1);
  7483. }
  7484. };
  7485.  
  7486. Queue.prototype._resizeTo = function (capacity) {
  7487. var oldCapacity = this._capacity;
  7488. this._capacity = capacity;
  7489. var front = this._front;
  7490. var length = this._length;
  7491. var moveItemsCount = (front + length) & (oldCapacity - 1);
  7492. arrayMove(this, 0, this, oldCapacity, moveItemsCount);
  7493. };
  7494.  
  7495. module.exports = Queue;
  7496.  
  7497. },{}],27:[function(_dereq_,module,exports){
  7498. "use strict";
  7499. module.exports = function(
  7500. Promise, INTERNAL, tryConvertToPromise, apiRejection) {
  7501. var util = _dereq_("./util");
  7502.  
  7503. var raceLater = function (promise) {
  7504. return promise.then(function(array) {
  7505. return race(array, promise);
  7506. });
  7507. };
  7508.  
  7509. function race(promises, parent) {
  7510. var maybePromise = tryConvertToPromise(promises);
  7511.  
  7512. if (maybePromise instanceof Promise) {
  7513. return raceLater(maybePromise);
  7514. } else {
  7515. promises = util.asArray(promises);
  7516. if (promises === null)
  7517. return apiRejection("expecting an array or an iterable object but got " + util.classString(promises));
  7518. }
  7519.  
  7520. var ret = new Promise(INTERNAL);
  7521. if (parent !== undefined) {
  7522. ret._propagateFrom(parent, 3);
  7523. }
  7524. var fulfill = ret._fulfill;
  7525. var reject = ret._reject;
  7526. for (var i = 0, len = promises.length; i < len; ++i) {
  7527. var val = promises[i];
  7528.  
  7529. if (val === undefined && !(i in promises)) {
  7530. continue;
  7531. }
  7532.  
  7533. Promise.cast(val)._then(fulfill, reject, undefined, ret, null);
  7534. }
  7535. return ret;
  7536. }
  7537.  
  7538. Promise.race = function (promises) {
  7539. return race(promises, undefined);
  7540. };
  7541.  
  7542. Promise.prototype.race = function () {
  7543. return race(this, undefined);
  7544. };
  7545.  
  7546. };
  7547.  
  7548. },{"./util":36}],28:[function(_dereq_,module,exports){
  7549. "use strict";
  7550. module.exports = function(Promise,
  7551. PromiseArray,
  7552. apiRejection,
  7553. tryConvertToPromise,
  7554. INTERNAL,
  7555. debug) {
  7556. var getDomain = Promise._getDomain;
  7557. var util = _dereq_("./util");
  7558. var tryCatch = util.tryCatch;
  7559.  
  7560. function ReductionPromiseArray(promises, fn, initialValue, _each) {
  7561. this.constructor$(promises);
  7562. var domain = getDomain();
  7563. this._fn = domain === null ? fn : util.domainBind(domain, fn);
  7564. if (initialValue !== undefined) {
  7565. initialValue = Promise.resolve(initialValue);
  7566. initialValue._attachCancellationCallback(this);
  7567. }
  7568. this._initialValue = initialValue;
  7569. this._currentCancellable = null;
  7570. if(_each === INTERNAL) {
  7571. this._eachValues = Array(this._length);
  7572. } else if (_each === 0) {
  7573. this._eachValues = null;
  7574. } else {
  7575. this._eachValues = undefined;
  7576. }
  7577. this._promise._captureStackTrace();
  7578. this._init$(undefined, -5);
  7579. }
  7580. util.inherits(ReductionPromiseArray, PromiseArray);
  7581.  
  7582. ReductionPromiseArray.prototype._gotAccum = function(accum) {
  7583. if (this._eachValues !== undefined &&
  7584. this._eachValues !== null &&
  7585. accum !== INTERNAL) {
  7586. this._eachValues.push(accum);
  7587. }
  7588. };
  7589.  
  7590. ReductionPromiseArray.prototype._eachComplete = function(value) {
  7591. if (this._eachValues !== null) {
  7592. this._eachValues.push(value);
  7593. }
  7594. return this._eachValues;
  7595. };
  7596.  
  7597. ReductionPromiseArray.prototype._init = function() {};
  7598.  
  7599. ReductionPromiseArray.prototype._resolveEmptyArray = function() {
  7600. this._resolve(this._eachValues !== undefined ? this._eachValues
  7601. : this._initialValue);
  7602. };
  7603.  
  7604. ReductionPromiseArray.prototype.shouldCopyValues = function () {
  7605. return false;
  7606. };
  7607.  
  7608. ReductionPromiseArray.prototype._resolve = function(value) {
  7609. this._promise._resolveCallback(value);
  7610. this._values = null;
  7611. };
  7612.  
  7613. ReductionPromiseArray.prototype._resultCancelled = function(sender) {
  7614. if (sender === this._initialValue) return this._cancel();
  7615. if (this._isResolved()) return;
  7616. this._resultCancelled$();
  7617. if (this._currentCancellable instanceof Promise) {
  7618. this._currentCancellable.cancel();
  7619. }
  7620. if (this._initialValue instanceof Promise) {
  7621. this._initialValue.cancel();
  7622. }
  7623. };
  7624.  
  7625. ReductionPromiseArray.prototype._iterate = function (values) {
  7626. this._values = values;
  7627. var value;
  7628. var i;
  7629. var length = values.length;
  7630. if (this._initialValue !== undefined) {
  7631. value = this._initialValue;
  7632. i = 0;
  7633. } else {
  7634. value = Promise.resolve(values[0]);
  7635. i = 1;
  7636. }
  7637.  
  7638. this._currentCancellable = value;
  7639.  
  7640. if (!value.isRejected()) {
  7641. for (; i < length; ++i) {
  7642. var ctx = {
  7643. accum: null,
  7644. value: values[i],
  7645. index: i,
  7646. length: length,
  7647. array: this
  7648. };
  7649. value = value._then(gotAccum, undefined, undefined, ctx, undefined);
  7650. }
  7651. }
  7652.  
  7653. if (this._eachValues !== undefined) {
  7654. value = value
  7655. ._then(this._eachComplete, undefined, undefined, this, undefined);
  7656. }
  7657. value._then(completed, completed, undefined, value, this);
  7658. };
  7659.  
  7660. Promise.prototype.reduce = function (fn, initialValue) {
  7661. return reduce(this, fn, initialValue, null);
  7662. };
  7663.  
  7664. Promise.reduce = function (promises, fn, initialValue, _each) {
  7665. return reduce(promises, fn, initialValue, _each);
  7666. };
  7667.  
  7668. function completed(valueOrReason, array) {
  7669. if (this.isFulfilled()) {
  7670. array._resolve(valueOrReason);
  7671. } else {
  7672. array._reject(valueOrReason);
  7673. }
  7674. }
  7675.  
  7676. function reduce(promises, fn, initialValue, _each) {
  7677. if (typeof fn !== "function") {
  7678. return apiRejection("expecting a function but got " + util.classString(fn));
  7679. }
  7680. var array = new ReductionPromiseArray(promises, fn, initialValue, _each);
  7681. return array.promise();
  7682. }
  7683.  
  7684. function gotAccum(accum) {
  7685. this.accum = accum;
  7686. this.array._gotAccum(accum);
  7687. var value = tryConvertToPromise(this.value, this.array._promise);
  7688. if (value instanceof Promise) {
  7689. this.array._currentCancellable = value;
  7690. return value._then(gotValue, undefined, undefined, this, undefined);
  7691. } else {
  7692. return gotValue.call(this, value);
  7693. }
  7694. }
  7695.  
  7696. function gotValue(value) {
  7697. var array = this.array;
  7698. var promise = array._promise;
  7699. var fn = tryCatch(array._fn);
  7700. promise._pushContext();
  7701. var ret;
  7702. if (array._eachValues !== undefined) {
  7703. ret = fn.call(promise._boundValue(), value, this.index, this.length);
  7704. } else {
  7705. ret = fn.call(promise._boundValue(),
  7706. this.accum, value, this.index, this.length);
  7707. }
  7708. if (ret instanceof Promise) {
  7709. array._currentCancellable = ret;
  7710. }
  7711. var promiseCreated = promise._popContext();
  7712. debug.checkForgottenReturns(
  7713. ret,
  7714. promiseCreated,
  7715. array._eachValues !== undefined ? "Promise.each" : "Promise.reduce",
  7716. promise
  7717. );
  7718. return ret;
  7719. }
  7720. };
  7721.  
  7722. },{"./util":36}],29:[function(_dereq_,module,exports){
  7723. "use strict";
  7724. var util = _dereq_("./util");
  7725. var schedule;
  7726. var noAsyncScheduler = function() {
  7727. throw new Error("No async scheduler available\u000a\u000a See http://goo.gl/MqrFmX\u000a");
  7728. };
  7729. var NativePromise = util.getNativePromise();
  7730. if (util.isNode && typeof MutationObserver === "undefined") {
  7731. var GlobalSetImmediate = global.setImmediate;
  7732. var ProcessNextTick = process.nextTick;
  7733. schedule = util.isRecentNode
  7734. ? function(fn) { GlobalSetImmediate.call(global, fn); }
  7735. : function(fn) { ProcessNextTick.call(process, fn); };
  7736. } else if (typeof NativePromise === "function" &&
  7737. typeof NativePromise.resolve === "function") {
  7738. var nativePromise = NativePromise.resolve();
  7739. schedule = function(fn) {
  7740. nativePromise.then(fn);
  7741. };
  7742. } else if ((typeof MutationObserver !== "undefined") &&
  7743. !(typeof window !== "undefined" &&
  7744. window.navigator &&
  7745. (window.navigator.standalone || window.cordova))) {
  7746. schedule = (function() {
  7747. var div = document.createElement("div");
  7748. var opts = {attributes: true};
  7749. var toggleScheduled = false;
  7750. var div2 = document.createElement("div");
  7751. var o2 = new MutationObserver(function() {
  7752. div.classList.toggle("foo");
  7753. toggleScheduled = false;
  7754. });
  7755. o2.observe(div2, opts);
  7756.  
  7757. var scheduleToggle = function() {
  7758. if (toggleScheduled) return;
  7759. toggleScheduled = true;
  7760. div2.classList.toggle("foo");
  7761. };
  7762.  
  7763. return function schedule(fn) {
  7764. var o = new MutationObserver(function() {
  7765. o.disconnect();
  7766. fn();
  7767. });
  7768. o.observe(div, opts);
  7769. scheduleToggle();
  7770. };
  7771. })();
  7772. } else if (typeof setImmediate !== "undefined") {
  7773. schedule = function (fn) {
  7774. setImmediate(fn);
  7775. };
  7776. } else if (typeof setTimeout !== "undefined") {
  7777. schedule = function (fn) {
  7778. setTimeout(fn, 0);
  7779. };
  7780. } else {
  7781. schedule = noAsyncScheduler;
  7782. }
  7783. module.exports = schedule;
  7784.  
  7785. },{"./util":36}],30:[function(_dereq_,module,exports){
  7786. "use strict";
  7787. module.exports =
  7788. function(Promise, PromiseArray, debug) {
  7789. var PromiseInspection = Promise.PromiseInspection;
  7790. var util = _dereq_("./util");
  7791.  
  7792. function SettledPromiseArray(values) {
  7793. this.constructor$(values);
  7794. }
  7795. util.inherits(SettledPromiseArray, PromiseArray);
  7796.  
  7797. SettledPromiseArray.prototype._promiseResolved = function (index, inspection) {
  7798. this._values[index] = inspection;
  7799. var totalResolved = ++this._totalResolved;
  7800. if (totalResolved >= this._length) {
  7801. this._resolve(this._values);
  7802. return true;
  7803. }
  7804. return false;
  7805. };
  7806.  
  7807. SettledPromiseArray.prototype._promiseFulfilled = function (value, index) {
  7808. var ret = new PromiseInspection();
  7809. ret._bitField = 33554432;
  7810. ret._settledValueField = value;
  7811. return this._promiseResolved(index, ret);
  7812. };
  7813. SettledPromiseArray.prototype._promiseRejected = function (reason, index) {
  7814. var ret = new PromiseInspection();
  7815. ret._bitField = 16777216;
  7816. ret._settledValueField = reason;
  7817. return this._promiseResolved(index, ret);
  7818. };
  7819.  
  7820. Promise.settle = function (promises) {
  7821. debug.deprecated(".settle()", ".reflect()");
  7822. return new SettledPromiseArray(promises).promise();
  7823. };
  7824.  
  7825. Promise.prototype.settle = function () {
  7826. return Promise.settle(this);
  7827. };
  7828. };
  7829.  
  7830. },{"./util":36}],31:[function(_dereq_,module,exports){
  7831. "use strict";
  7832. module.exports =
  7833. function(Promise, PromiseArray, apiRejection) {
  7834. var util = _dereq_("./util");
  7835. var RangeError = _dereq_("./errors").RangeError;
  7836. var AggregateError = _dereq_("./errors").AggregateError;
  7837. var isArray = util.isArray;
  7838. var CANCELLATION = {};
  7839.  
  7840.  
  7841. function SomePromiseArray(values) {
  7842. this.constructor$(values);
  7843. this._howMany = 0;
  7844. this._unwrap = false;
  7845. this._initialized = false;
  7846. }
  7847. util.inherits(SomePromiseArray, PromiseArray);
  7848.  
  7849. SomePromiseArray.prototype._init = function () {
  7850. if (!this._initialized) {
  7851. return;
  7852. }
  7853. if (this._howMany === 0) {
  7854. this._resolve([]);
  7855. return;
  7856. }
  7857. this._init$(undefined, -5);
  7858. var isArrayResolved = isArray(this._values);
  7859. if (!this._isResolved() &&
  7860. isArrayResolved &&
  7861. this._howMany > this._canPossiblyFulfill()) {
  7862. this._reject(this._getRangeError(this.length()));
  7863. }
  7864. };
  7865.  
  7866. SomePromiseArray.prototype.init = function () {
  7867. this._initialized = true;
  7868. this._init();
  7869. };
  7870.  
  7871. SomePromiseArray.prototype.setUnwrap = function () {
  7872. this._unwrap = true;
  7873. };
  7874.  
  7875. SomePromiseArray.prototype.howMany = function () {
  7876. return this._howMany;
  7877. };
  7878.  
  7879. SomePromiseArray.prototype.setHowMany = function (count) {
  7880. this._howMany = count;
  7881. };
  7882.  
  7883. SomePromiseArray.prototype._promiseFulfilled = function (value) {
  7884. this._addFulfilled(value);
  7885. if (this._fulfilled() === this.howMany()) {
  7886. this._values.length = this.howMany();
  7887. if (this.howMany() === 1 && this._unwrap) {
  7888. this._resolve(this._values[0]);
  7889. } else {
  7890. this._resolve(this._values);
  7891. }
  7892. return true;
  7893. }
  7894. return false;
  7895.  
  7896. };
  7897. SomePromiseArray.prototype._promiseRejected = function (reason) {
  7898. this._addRejected(reason);
  7899. return this._checkOutcome();
  7900. };
  7901.  
  7902. SomePromiseArray.prototype._promiseCancelled = function () {
  7903. if (this._values instanceof Promise || this._values == null) {
  7904. return this._cancel();
  7905. }
  7906. this._addRejected(CANCELLATION);
  7907. return this._checkOutcome();
  7908. };
  7909.  
  7910. SomePromiseArray.prototype._checkOutcome = function() {
  7911. if (this.howMany() > this._canPossiblyFulfill()) {
  7912. var e = new AggregateError();
  7913. for (var i = this.length(); i < this._values.length; ++i) {
  7914. if (this._values[i] !== CANCELLATION) {
  7915. e.push(this._values[i]);
  7916. }
  7917. }
  7918. if (e.length > 0) {
  7919. this._reject(e);
  7920. } else {
  7921. this._cancel();
  7922. }
  7923. return true;
  7924. }
  7925. return false;
  7926. };
  7927.  
  7928. SomePromiseArray.prototype._fulfilled = function () {
  7929. return this._totalResolved;
  7930. };
  7931.  
  7932. SomePromiseArray.prototype._rejected = function () {
  7933. return this._values.length - this.length();
  7934. };
  7935.  
  7936. SomePromiseArray.prototype._addRejected = function (reason) {
  7937. this._values.push(reason);
  7938. };
  7939.  
  7940. SomePromiseArray.prototype._addFulfilled = function (value) {
  7941. this._values[this._totalResolved++] = value;
  7942. };
  7943.  
  7944. SomePromiseArray.prototype._canPossiblyFulfill = function () {
  7945. return this.length() - this._rejected();
  7946. };
  7947.  
  7948. SomePromiseArray.prototype._getRangeError = function (count) {
  7949. var message = "Input array must contain at least " +
  7950. this._howMany + " items but contains only " + count + " items";
  7951. return new RangeError(message);
  7952. };
  7953.  
  7954. SomePromiseArray.prototype._resolveEmptyArray = function () {
  7955. this._reject(this._getRangeError(0));
  7956. };
  7957.  
  7958. function some(promises, howMany) {
  7959. if ((howMany | 0) !== howMany || howMany < 0) {
  7960. return apiRejection("expecting a positive integer\u000a\u000a See http://goo.gl/MqrFmX\u000a");
  7961. }
  7962. var ret = new SomePromiseArray(promises);
  7963. var promise = ret.promise();
  7964. ret.setHowMany(howMany);
  7965. ret.init();
  7966. return promise;
  7967. }
  7968.  
  7969. Promise.some = function (promises, howMany) {
  7970. return some(promises, howMany);
  7971. };
  7972.  
  7973. Promise.prototype.some = function (howMany) {
  7974. return some(this, howMany);
  7975. };
  7976.  
  7977. Promise._SomePromiseArray = SomePromiseArray;
  7978. };
  7979.  
  7980. },{"./errors":12,"./util":36}],32:[function(_dereq_,module,exports){
  7981. "use strict";
  7982. module.exports = function(Promise) {
  7983. function PromiseInspection(promise) {
  7984. if (promise !== undefined) {
  7985. promise = promise._target();
  7986. this._bitField = promise._bitField;
  7987. this._settledValueField = promise._isFateSealed()
  7988. ? promise._settledValue() : undefined;
  7989. }
  7990. else {
  7991. this._bitField = 0;
  7992. this._settledValueField = undefined;
  7993. }
  7994. }
  7995.  
  7996. PromiseInspection.prototype._settledValue = function() {
  7997. return this._settledValueField;
  7998. };
  7999.  
  8000. var value = PromiseInspection.prototype.value = function () {
  8001. if (!this.isFulfilled()) {
  8002. throw new TypeError("cannot get fulfillment value of a non-fulfilled promise\u000a\u000a See http://goo.gl/MqrFmX\u000a");
  8003. }
  8004. return this._settledValue();
  8005. };
  8006.  
  8007. var reason = PromiseInspection.prototype.error =
  8008. PromiseInspection.prototype.reason = function () {
  8009. if (!this.isRejected()) {
  8010. throw new TypeError("cannot get rejection reason of a non-rejected promise\u000a\u000a See http://goo.gl/MqrFmX\u000a");
  8011. }
  8012. return this._settledValue();
  8013. };
  8014.  
  8015. var isFulfilled = PromiseInspection.prototype.isFulfilled = function() {
  8016. return (this._bitField & 33554432) !== 0;
  8017. };
  8018.  
  8019. var isRejected = PromiseInspection.prototype.isRejected = function () {
  8020. return (this._bitField & 16777216) !== 0;
  8021. };
  8022.  
  8023. var isPending = PromiseInspection.prototype.isPending = function () {
  8024. return (this._bitField & 50397184) === 0;
  8025. };
  8026.  
  8027. var isResolved = PromiseInspection.prototype.isResolved = function () {
  8028. return (this._bitField & 50331648) !== 0;
  8029. };
  8030.  
  8031. PromiseInspection.prototype.isCancelled = function() {
  8032. return (this._bitField & 8454144) !== 0;
  8033. };
  8034.  
  8035. Promise.prototype.__isCancelled = function() {
  8036. return (this._bitField & 65536) === 65536;
  8037. };
  8038.  
  8039. Promise.prototype._isCancelled = function() {
  8040. return this._target().__isCancelled();
  8041. };
  8042.  
  8043. Promise.prototype.isCancelled = function() {
  8044. return (this._target()._bitField & 8454144) !== 0;
  8045. };
  8046.  
  8047. Promise.prototype.isPending = function() {
  8048. return isPending.call(this._target());
  8049. };
  8050.  
  8051. Promise.prototype.isRejected = function() {
  8052. return isRejected.call(this._target());
  8053. };
  8054.  
  8055. Promise.prototype.isFulfilled = function() {
  8056. return isFulfilled.call(this._target());
  8057. };
  8058.  
  8059. Promise.prototype.isResolved = function() {
  8060. return isResolved.call(this._target());
  8061. };
  8062.  
  8063. Promise.prototype.value = function() {
  8064. return value.call(this._target());
  8065. };
  8066.  
  8067. Promise.prototype.reason = function() {
  8068. var target = this._target();
  8069. target._unsetRejectionIsUnhandled();
  8070. return reason.call(target);
  8071. };
  8072.  
  8073. Promise.prototype._value = function() {
  8074. return this._settledValue();
  8075. };
  8076.  
  8077. Promise.prototype._reason = function() {
  8078. this._unsetRejectionIsUnhandled();
  8079. return this._settledValue();
  8080. };
  8081.  
  8082. Promise.PromiseInspection = PromiseInspection;
  8083. };
  8084.  
  8085. },{}],33:[function(_dereq_,module,exports){
  8086. "use strict";
  8087. module.exports = function(Promise, INTERNAL) {
  8088. var util = _dereq_("./util");
  8089. var errorObj = util.errorObj;
  8090. var isObject = util.isObject;
  8091.  
  8092. function tryConvertToPromise(obj, context) {
  8093. if (isObject(obj)) {
  8094. if (obj instanceof Promise) return obj;
  8095. var then = getThen(obj);
  8096. if (then === errorObj) {
  8097. if (context) context._pushContext();
  8098. var ret = Promise.reject(then.e);
  8099. if (context) context._popContext();
  8100. return ret;
  8101. } else if (typeof then === "function") {
  8102. if (isAnyBluebirdPromise(obj)) {
  8103. var ret = new Promise(INTERNAL);
  8104. obj._then(
  8105. ret._fulfill,
  8106. ret._reject,
  8107. undefined,
  8108. ret,
  8109. null
  8110. );
  8111. return ret;
  8112. }
  8113. return doThenable(obj, then, context);
  8114. }
  8115. }
  8116. return obj;
  8117. }
  8118.  
  8119. function doGetThen(obj) {
  8120. return obj.then;
  8121. }
  8122.  
  8123. function getThen(obj) {
  8124. try {
  8125. return doGetThen(obj);
  8126. } catch (e) {
  8127. errorObj.e = e;
  8128. return errorObj;
  8129. }
  8130. }
  8131.  
  8132. var hasProp = {}.hasOwnProperty;
  8133. function isAnyBluebirdPromise(obj) {
  8134. try {
  8135. return hasProp.call(obj, "_promise0");
  8136. } catch (e) {
  8137. return false;
  8138. }
  8139. }
  8140.  
  8141. function doThenable(x, then, context) {
  8142. var promise = new Promise(INTERNAL);
  8143. var ret = promise;
  8144. if (context) context._pushContext();
  8145. promise._captureStackTrace();
  8146. if (context) context._popContext();
  8147. var synchronous = true;
  8148. var result = util.tryCatch(then).call(x, resolve, reject);
  8149. synchronous = false;
  8150.  
  8151. if (promise && result === errorObj) {
  8152. promise._rejectCallback(result.e, true, true);
  8153. promise = null;
  8154. }
  8155.  
  8156. function resolve(value) {
  8157. if (!promise) return;
  8158. promise._resolveCallback(value);
  8159. promise = null;
  8160. }
  8161.  
  8162. function reject(reason) {
  8163. if (!promise) return;
  8164. promise._rejectCallback(reason, synchronous, true);
  8165. promise = null;
  8166. }
  8167. return ret;
  8168. }
  8169.  
  8170. return tryConvertToPromise;
  8171. };
  8172.  
  8173. },{"./util":36}],34:[function(_dereq_,module,exports){
  8174. "use strict";
  8175. module.exports = function(Promise, INTERNAL, debug) {
  8176. var util = _dereq_("./util");
  8177. var TimeoutError = Promise.TimeoutError;
  8178.  
  8179. function HandleWrapper(handle) {
  8180. this.handle = handle;
  8181. }
  8182.  
  8183. HandleWrapper.prototype._resultCancelled = function() {
  8184. clearTimeout(this.handle);
  8185. };
  8186.  
  8187. var afterValue = function(value) { return delay(+this).thenReturn(value); };
  8188. var delay = Promise.delay = function (ms, value) {
  8189. var ret;
  8190. var handle;
  8191. if (value !== undefined) {
  8192. ret = Promise.resolve(value)
  8193. ._then(afterValue, null, null, ms, undefined);
  8194. if (debug.cancellation() && value instanceof Promise) {
  8195. ret._setOnCancel(value);
  8196. }
  8197. } else {
  8198. ret = new Promise(INTERNAL);
  8199. handle = setTimeout(function() { ret._fulfill(); }, +ms);
  8200. if (debug.cancellation()) {
  8201. ret._setOnCancel(new HandleWrapper(handle));
  8202. }
  8203. ret._captureStackTrace();
  8204. }
  8205. ret._setAsyncGuaranteed();
  8206. return ret;
  8207. };
  8208.  
  8209. Promise.prototype.delay = function (ms) {
  8210. return delay(ms, this);
  8211. };
  8212.  
  8213. var afterTimeout = function (promise, message, parent) {
  8214. var err;
  8215. if (typeof message !== "string") {
  8216. if (message instanceof Error) {
  8217. err = message;
  8218. } else {
  8219. err = new TimeoutError("operation timed out");
  8220. }
  8221. } else {
  8222. err = new TimeoutError(message);
  8223. }
  8224. util.markAsOriginatingFromRejection(err);
  8225. promise._attachExtraTrace(err);
  8226. promise._reject(err);
  8227.  
  8228. if (parent != null) {
  8229. parent.cancel();
  8230. }
  8231. };
  8232.  
  8233. function successClear(value) {
  8234. clearTimeout(this.handle);
  8235. return value;
  8236. }
  8237.  
  8238. function failureClear(reason) {
  8239. clearTimeout(this.handle);
  8240. throw reason;
  8241. }
  8242.  
  8243. Promise.prototype.timeout = function (ms, message) {
  8244. ms = +ms;
  8245. var ret, parent;
  8246.  
  8247. var handleWrapper = new HandleWrapper(setTimeout(function timeoutTimeout() {
  8248. if (ret.isPending()) {
  8249. afterTimeout(ret, message, parent);
  8250. }
  8251. }, ms));
  8252.  
  8253. if (debug.cancellation()) {
  8254. parent = this.then();
  8255. ret = parent._then(successClear, failureClear,
  8256. undefined, handleWrapper, undefined);
  8257. ret._setOnCancel(handleWrapper);
  8258. } else {
  8259. ret = this._then(successClear, failureClear,
  8260. undefined, handleWrapper, undefined);
  8261. }
  8262.  
  8263. return ret;
  8264. };
  8265.  
  8266. };
  8267.  
  8268. },{"./util":36}],35:[function(_dereq_,module,exports){
  8269. "use strict";
  8270. module.exports = function (Promise, apiRejection, tryConvertToPromise,
  8271. createContext, INTERNAL, debug) {
  8272. var util = _dereq_("./util");
  8273. var TypeError = _dereq_("./errors").TypeError;
  8274. var inherits = _dereq_("./util").inherits;
  8275. var errorObj = util.errorObj;
  8276. var tryCatch = util.tryCatch;
  8277. var NULL = {};
  8278.  
  8279. function thrower(e) {
  8280. setTimeout(function(){throw e;}, 0);
  8281. }
  8282.  
  8283. function castPreservingDisposable(thenable) {
  8284. var maybePromise = tryConvertToPromise(thenable);
  8285. if (maybePromise !== thenable &&
  8286. typeof thenable._isDisposable === "function" &&
  8287. typeof thenable._getDisposer === "function" &&
  8288. thenable._isDisposable()) {
  8289. maybePromise._setDisposable(thenable._getDisposer());
  8290. }
  8291. return maybePromise;
  8292. }
  8293. function dispose(resources, inspection) {
  8294. var i = 0;
  8295. var len = resources.length;
  8296. var ret = new Promise(INTERNAL);
  8297. function iterator() {
  8298. if (i >= len) return ret._fulfill();
  8299. var maybePromise = castPreservingDisposable(resources[i++]);
  8300. if (maybePromise instanceof Promise &&
  8301. maybePromise._isDisposable()) {
  8302. try {
  8303. maybePromise = tryConvertToPromise(
  8304. maybePromise._getDisposer().tryDispose(inspection),
  8305. resources.promise);
  8306. } catch (e) {
  8307. return thrower(e);
  8308. }
  8309. if (maybePromise instanceof Promise) {
  8310. return maybePromise._then(iterator, thrower,
  8311. null, null, null);
  8312. }
  8313. }
  8314. iterator();
  8315. }
  8316. iterator();
  8317. return ret;
  8318. }
  8319.  
  8320. function Disposer(data, promise, context) {
  8321. this._data = data;
  8322. this._promise = promise;
  8323. this._context = context;
  8324. }
  8325.  
  8326. Disposer.prototype.data = function () {
  8327. return this._data;
  8328. };
  8329.  
  8330. Disposer.prototype.promise = function () {
  8331. return this._promise;
  8332. };
  8333.  
  8334. Disposer.prototype.resource = function () {
  8335. if (this.promise().isFulfilled()) {
  8336. return this.promise().value();
  8337. }
  8338. return NULL;
  8339. };
  8340.  
  8341. Disposer.prototype.tryDispose = function(inspection) {
  8342. var resource = this.resource();
  8343. var context = this._context;
  8344. if (context !== undefined) context._pushContext();
  8345. var ret = resource !== NULL
  8346. ? this.doDispose(resource, inspection) : null;
  8347. if (context !== undefined) context._popContext();
  8348. this._promise._unsetDisposable();
  8349. this._data = null;
  8350. return ret;
  8351. };
  8352.  
  8353. Disposer.isDisposer = function (d) {
  8354. return (d != null &&
  8355. typeof d.resource === "function" &&
  8356. typeof d.tryDispose === "function");
  8357. };
  8358.  
  8359. function FunctionDisposer(fn, promise, context) {
  8360. this.constructor$(fn, promise, context);
  8361. }
  8362. inherits(FunctionDisposer, Disposer);
  8363.  
  8364. FunctionDisposer.prototype.doDispose = function (resource, inspection) {
  8365. var fn = this.data();
  8366. return fn.call(resource, resource, inspection);
  8367. };
  8368.  
  8369. function maybeUnwrapDisposer(value) {
  8370. if (Disposer.isDisposer(value)) {
  8371. this.resources[this.index]._setDisposable(value);
  8372. return value.promise();
  8373. }
  8374. return value;
  8375. }
  8376.  
  8377. function ResourceList(length) {
  8378. this.length = length;
  8379. this.promise = null;
  8380. this[length-1] = null;
  8381. }
  8382.  
  8383. ResourceList.prototype._resultCancelled = function() {
  8384. var len = this.length;
  8385. for (var i = 0; i < len; ++i) {
  8386. var item = this[i];
  8387. if (item instanceof Promise) {
  8388. item.cancel();
  8389. }
  8390. }
  8391. };
  8392.  
  8393. Promise.using = function () {
  8394. var len = arguments.length;
  8395. if (len < 2) return apiRejection(
  8396. "you must pass at least 2 arguments to Promise.using");
  8397. var fn = arguments[len - 1];
  8398. if (typeof fn !== "function") {
  8399. return apiRejection("expecting a function but got " + util.classString(fn));
  8400. }
  8401. var input;
  8402. var spreadArgs = true;
  8403. if (len === 2 && Array.isArray(arguments[0])) {
  8404. input = arguments[0];
  8405. len = input.length;
  8406. spreadArgs = false;
  8407. } else {
  8408. input = arguments;
  8409. len--;
  8410. }
  8411. var resources = new ResourceList(len);
  8412. for (var i = 0; i < len; ++i) {
  8413. var resource = input[i];
  8414. if (Disposer.isDisposer(resource)) {
  8415. var disposer = resource;
  8416. resource = resource.promise();
  8417. resource._setDisposable(disposer);
  8418. } else {
  8419. var maybePromise = tryConvertToPromise(resource);
  8420. if (maybePromise instanceof Promise) {
  8421. resource =
  8422. maybePromise._then(maybeUnwrapDisposer, null, null, {
  8423. resources: resources,
  8424. index: i
  8425. }, undefined);
  8426. }
  8427. }
  8428. resources[i] = resource;
  8429. }
  8430.  
  8431. var reflectedResources = new Array(resources.length);
  8432. for (var i = 0; i < reflectedResources.length; ++i) {
  8433. reflectedResources[i] = Promise.resolve(resources[i]).reflect();
  8434. }
  8435.  
  8436. var resultPromise = Promise.all(reflectedResources)
  8437. .then(function(inspections) {
  8438. for (var i = 0; i < inspections.length; ++i) {
  8439. var inspection = inspections[i];
  8440. if (inspection.isRejected()) {
  8441. errorObj.e = inspection.error();
  8442. return errorObj;
  8443. } else if (!inspection.isFulfilled()) {
  8444. resultPromise.cancel();
  8445. return;
  8446. }
  8447. inspections[i] = inspection.value();
  8448. }
  8449. promise._pushContext();
  8450.  
  8451. fn = tryCatch(fn);
  8452. var ret = spreadArgs
  8453. ? fn.apply(undefined, inspections) : fn(inspections);
  8454. var promiseCreated = promise._popContext();
  8455. debug.checkForgottenReturns(
  8456. ret, promiseCreated, "Promise.using", promise);
  8457. return ret;
  8458. });
  8459.  
  8460. var promise = resultPromise.lastly(function() {
  8461. var inspection = new Promise.PromiseInspection(resultPromise);
  8462. return dispose(resources, inspection);
  8463. });
  8464. resources.promise = promise;
  8465. promise._setOnCancel(resources);
  8466. return promise;
  8467. };
  8468.  
  8469. Promise.prototype._setDisposable = function (disposer) {
  8470. this._bitField = this._bitField | 131072;
  8471. this._disposer = disposer;
  8472. };
  8473.  
  8474. Promise.prototype._isDisposable = function () {
  8475. return (this._bitField & 131072) > 0;
  8476. };
  8477.  
  8478. Promise.prototype._getDisposer = function () {
  8479. return this._disposer;
  8480. };
  8481.  
  8482. Promise.prototype._unsetDisposable = function () {
  8483. this._bitField = this._bitField & (~131072);
  8484. this._disposer = undefined;
  8485. };
  8486.  
  8487. Promise.prototype.disposer = function (fn) {
  8488. if (typeof fn === "function") {
  8489. return new FunctionDisposer(fn, this, createContext());
  8490. }
  8491. throw new TypeError();
  8492. };
  8493.  
  8494. };
  8495.  
  8496. },{"./errors":12,"./util":36}],36:[function(_dereq_,module,exports){
  8497. "use strict";
  8498. var es5 = _dereq_("./es5");
  8499. var canEvaluate = typeof navigator == "undefined";
  8500.  
  8501. var errorObj = {e: {}};
  8502. var tryCatchTarget;
  8503. var globalObject = typeof self !== "undefined" ? self :
  8504. typeof window !== "undefined" ? window :
  8505. typeof global !== "undefined" ? global :
  8506. this !== undefined ? this : null;
  8507.  
  8508. function tryCatcher() {
  8509. try {
  8510. var target = tryCatchTarget;
  8511. tryCatchTarget = null;
  8512. return target.apply(this, arguments);
  8513. } catch (e) {
  8514. errorObj.e = e;
  8515. return errorObj;
  8516. }
  8517. }
  8518. function tryCatch(fn) {
  8519. tryCatchTarget = fn;
  8520. return tryCatcher;
  8521. }
  8522.  
  8523. var inherits = function(Child, Parent) {
  8524. var hasProp = {}.hasOwnProperty;
  8525.  
  8526. function T() {
  8527. this.constructor = Child;
  8528. this.constructor$ = Parent;
  8529. for (var propertyName in Parent.prototype) {
  8530. if (hasProp.call(Parent.prototype, propertyName) &&
  8531. propertyName.charAt(propertyName.length-1) !== "$"
  8532. ) {
  8533. this[propertyName + "$"] = Parent.prototype[propertyName];
  8534. }
  8535. }
  8536. }
  8537. T.prototype = Parent.prototype;
  8538. Child.prototype = new T();
  8539. return Child.prototype;
  8540. };
  8541.  
  8542.  
  8543. function isPrimitive(val) {
  8544. return val == null || val === true || val === false ||
  8545. typeof val === "string" || typeof val === "number";
  8546.  
  8547. }
  8548.  
  8549. function isObject(value) {
  8550. return typeof value === "function" ||
  8551. typeof value === "object" && value !== null;
  8552. }
  8553.  
  8554. function maybeWrapAsError(maybeError) {
  8555. if (!isPrimitive(maybeError)) return maybeError;
  8556.  
  8557. return new Error(safeToString(maybeError));
  8558. }
  8559.  
  8560. function withAppended(target, appendee) {
  8561. var len = target.length;
  8562. var ret = new Array(len + 1);
  8563. var i;
  8564. for (i = 0; i < len; ++i) {
  8565. ret[i] = target[i];
  8566. }
  8567. ret[i] = appendee;
  8568. return ret;
  8569. }
  8570.  
  8571. function getDataPropertyOrDefault(obj, key, defaultValue) {
  8572. if (es5.isES5) {
  8573. var desc = Object.getOwnPropertyDescriptor(obj, key);
  8574.  
  8575. if (desc != null) {
  8576. return desc.get == null && desc.set == null
  8577. ? desc.value
  8578. : defaultValue;
  8579. }
  8580. } else {
  8581. return {}.hasOwnProperty.call(obj, key) ? obj[key] : undefined;
  8582. }
  8583. }
  8584.  
  8585. function notEnumerableProp(obj, name, value) {
  8586. if (isPrimitive(obj)) return obj;
  8587. var descriptor = {
  8588. value: value,
  8589. configurable: true,
  8590. enumerable: false,
  8591. writable: true
  8592. };
  8593. es5.defineProperty(obj, name, descriptor);
  8594. return obj;
  8595. }
  8596.  
  8597. function thrower(r) {
  8598. throw r;
  8599. }
  8600.  
  8601. var inheritedDataKeys = (function() {
  8602. var excludedPrototypes = [
  8603. Array.prototype,
  8604. Object.prototype,
  8605. Function.prototype
  8606. ];
  8607.  
  8608. var isExcludedProto = function(val) {
  8609. for (var i = 0; i < excludedPrototypes.length; ++i) {
  8610. if (excludedPrototypes[i] === val) {
  8611. return true;
  8612. }
  8613. }
  8614. return false;
  8615. };
  8616.  
  8617. if (es5.isES5) {
  8618. var getKeys = Object.getOwnPropertyNames;
  8619. return function(obj) {
  8620. var ret = [];
  8621. var visitedKeys = Object.create(null);
  8622. while (obj != null && !isExcludedProto(obj)) {
  8623. var keys;
  8624. try {
  8625. keys = getKeys(obj);
  8626. } catch (e) {
  8627. return ret;
  8628. }
  8629. for (var i = 0; i < keys.length; ++i) {
  8630. var key = keys[i];
  8631. if (visitedKeys[key]) continue;
  8632. visitedKeys[key] = true;
  8633. var desc = Object.getOwnPropertyDescriptor(obj, key);
  8634. if (desc != null && desc.get == null && desc.set == null) {
  8635. ret.push(key);
  8636. }
  8637. }
  8638. obj = es5.getPrototypeOf(obj);
  8639. }
  8640. return ret;
  8641. };
  8642. } else {
  8643. var hasProp = {}.hasOwnProperty;
  8644. return function(obj) {
  8645. if (isExcludedProto(obj)) return [];
  8646. var ret = [];
  8647.  
  8648. /*jshint forin:false */
  8649. enumeration: for (var key in obj) {
  8650. if (hasProp.call(obj, key)) {
  8651. ret.push(key);
  8652. } else {
  8653. for (var i = 0; i < excludedPrototypes.length; ++i) {
  8654. if (hasProp.call(excludedPrototypes[i], key)) {
  8655. continue enumeration;
  8656. }
  8657. }
  8658. ret.push(key);
  8659. }
  8660. }
  8661. return ret;
  8662. };
  8663. }
  8664.  
  8665. })();
  8666.  
  8667. var thisAssignmentPattern = /this\s*\.\s*\S+\s*=/;
  8668. function isClass(fn) {
  8669. try {
  8670. if (typeof fn === "function") {
  8671. var keys = es5.names(fn.prototype);
  8672.  
  8673. var hasMethods = es5.isES5 && keys.length > 1;
  8674. var hasMethodsOtherThanConstructor = keys.length > 0 &&
  8675. !(keys.length === 1 && keys[0] === "constructor");
  8676. var hasThisAssignmentAndStaticMethods =
  8677. thisAssignmentPattern.test(fn + "") && es5.names(fn).length > 0;
  8678.  
  8679. if (hasMethods || hasMethodsOtherThanConstructor ||
  8680. hasThisAssignmentAndStaticMethods) {
  8681. return true;
  8682. }
  8683. }
  8684. return false;
  8685. } catch (e) {
  8686. return false;
  8687. }
  8688. }
  8689.  
  8690. function toFastProperties(obj) {
  8691. /*jshint -W027,-W055,-W031*/
  8692. function FakeConstructor() {}
  8693. FakeConstructor.prototype = obj;
  8694. var l = 8;
  8695. while (l--) new FakeConstructor();
  8696. return obj;
  8697. eval(obj);
  8698. }
  8699.  
  8700. var rident = /^[a-z$_][a-z$_0-9]*$/i;
  8701. function isIdentifier(str) {
  8702. return rident.test(str);
  8703. }
  8704.  
  8705. function filledRange(count, prefix, suffix) {
  8706. var ret = new Array(count);
  8707. for(var i = 0; i < count; ++i) {
  8708. ret[i] = prefix + i + suffix;
  8709. }
  8710. return ret;
  8711. }
  8712.  
  8713. function safeToString(obj) {
  8714. try {
  8715. return obj + "";
  8716. } catch (e) {
  8717. return "[no string representation]";
  8718. }
  8719. }
  8720.  
  8721. function isError(obj) {
  8722. return obj !== null &&
  8723. typeof obj === "object" &&
  8724. typeof obj.message === "string" &&
  8725. typeof obj.name === "string";
  8726. }
  8727.  
  8728. function markAsOriginatingFromRejection(e) {
  8729. try {
  8730. notEnumerableProp(e, "isOperational", true);
  8731. }
  8732. catch(ignore) {}
  8733. }
  8734.  
  8735. function originatesFromRejection(e) {
  8736. if (e == null) return false;
  8737. return ((e instanceof Error["__BluebirdErrorTypes__"].OperationalError) ||
  8738. e["isOperational"] === true);
  8739. }
  8740.  
  8741. function canAttachTrace(obj) {
  8742. return isError(obj) && es5.propertyIsWritable(obj, "stack");
  8743. }
  8744.  
  8745. var ensureErrorObject = (function() {
  8746. if (!("stack" in new Error())) {
  8747. return function(value) {
  8748. if (canAttachTrace(value)) return value;
  8749. try {throw new Error(safeToString(value));}
  8750. catch(err) {return err;}
  8751. };
  8752. } else {
  8753. return function(value) {
  8754. if (canAttachTrace(value)) return value;
  8755. return new Error(safeToString(value));
  8756. };
  8757. }
  8758. })();
  8759.  
  8760. function classString(obj) {
  8761. return {}.toString.call(obj);
  8762. }
  8763.  
  8764. function copyDescriptors(from, to, filter) {
  8765. var keys = es5.names(from);
  8766. for (var i = 0; i < keys.length; ++i) {
  8767. var key = keys[i];
  8768. if (filter(key)) {
  8769. try {
  8770. es5.defineProperty(to, key, es5.getDescriptor(from, key));
  8771. } catch (ignore) {}
  8772. }
  8773. }
  8774. }
  8775.  
  8776. var asArray = function(v) {
  8777. if (es5.isArray(v)) {
  8778. return v;
  8779. }
  8780. return null;
  8781. };
  8782.  
  8783. if (typeof Symbol !== "undefined" && Symbol.iterator) {
  8784. var ArrayFrom = typeof Array.from === "function" ? function(v) {
  8785. return Array.from(v);
  8786. } : function(v) {
  8787. var ret = [];
  8788. var it = v[Symbol.iterator]();
  8789. var itResult;
  8790. while (!((itResult = it.next()).done)) {
  8791. ret.push(itResult.value);
  8792. }
  8793. return ret;
  8794. };
  8795.  
  8796. asArray = function(v) {
  8797. if (es5.isArray(v)) {
  8798. return v;
  8799. } else if (v != null && typeof v[Symbol.iterator] === "function") {
  8800. return ArrayFrom(v);
  8801. }
  8802. return null;
  8803. };
  8804. }
  8805.  
  8806. var isNode = typeof process !== "undefined" &&
  8807. classString(process).toLowerCase() === "[object process]";
  8808.  
  8809. var hasEnvVariables = typeof process !== "undefined" &&
  8810. typeof process.env !== "undefined";
  8811.  
  8812. function env(key) {
  8813. return hasEnvVariables ? process.env[key] : undefined;
  8814. }
  8815.  
  8816. function getNativePromise() {
  8817. if (typeof Promise === "function") {
  8818. try {
  8819. var promise = new Promise(function(){});
  8820. if ({}.toString.call(promise) === "[object Promise]") {
  8821. return Promise;
  8822. }
  8823. } catch (e) {}
  8824. }
  8825. }
  8826.  
  8827. function domainBind(self, cb) {
  8828. return self.bind(cb);
  8829. }
  8830.  
  8831. var ret = {
  8832. isClass: isClass,
  8833. isIdentifier: isIdentifier,
  8834. inheritedDataKeys: inheritedDataKeys,
  8835. getDataPropertyOrDefault: getDataPropertyOrDefault,
  8836. thrower: thrower,
  8837. isArray: es5.isArray,
  8838. asArray: asArray,
  8839. notEnumerableProp: notEnumerableProp,
  8840. isPrimitive: isPrimitive,
  8841. isObject: isObject,
  8842. isError: isError,
  8843. canEvaluate: canEvaluate,
  8844. errorObj: errorObj,
  8845. tryCatch: tryCatch,
  8846. inherits: inherits,
  8847. withAppended: withAppended,
  8848. maybeWrapAsError: maybeWrapAsError,
  8849. toFastProperties: toFastProperties,
  8850. filledRange: filledRange,
  8851. toString: safeToString,
  8852. canAttachTrace: canAttachTrace,
  8853. ensureErrorObject: ensureErrorObject,
  8854. originatesFromRejection: originatesFromRejection,
  8855. markAsOriginatingFromRejection: markAsOriginatingFromRejection,
  8856. classString: classString,
  8857. copyDescriptors: copyDescriptors,
  8858. hasDevTools: typeof chrome !== "undefined" && chrome &&
  8859. typeof chrome.loadTimes === "function",
  8860. isNode: isNode,
  8861. hasEnvVariables: hasEnvVariables,
  8862. env: env,
  8863. global: globalObject,
  8864. getNativePromise: getNativePromise,
  8865. domainBind: domainBind
  8866. };
  8867. ret.isRecentNode = ret.isNode && (function() {
  8868. var version = process.versions.node.split(".").map(Number);
  8869. return (version[0] === 0 && version[1] > 10) || (version[0] > 0);
  8870. })();
  8871.  
  8872. if (ret.isNode) ret.toFastProperties(process);
  8873.  
  8874. try {throw new Error(); } catch (e) {ret.lastLineError = e;}
  8875. module.exports = ret;
  8876.  
  8877. },{"./es5":13}]},{},[4])(4)
  8878. }); ;if (typeof window !== 'undefined' && window !== null) { window.P = window.Promise; } else if (typeof self !== 'undefined' && self !== null) { self.P = self.Promise; }
  8879. }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  8880. },{"_process":39}],39:[function(require,module,exports){
  8881. // shim for using process in browser
  8882. var process = module.exports = {};
  8883.  
  8884. // cached from whatever global is present so that test runners that stub it
  8885. // don't break things. But we need to wrap it in a try catch in case it is
  8886. // wrapped in strict mode code which doesn't define any globals. It's inside a
  8887. // function because try/catches deoptimize in certain engines.
  8888.  
  8889. var cachedSetTimeout;
  8890. var cachedClearTimeout;
  8891.  
  8892. function defaultSetTimout() {
  8893. throw new Error('setTimeout has not been defined');
  8894. }
  8895. function defaultClearTimeout () {
  8896. throw new Error('clearTimeout has not been defined');
  8897. }
  8898. (function () {
  8899. try {
  8900. if (typeof setTimeout === 'function') {
  8901. cachedSetTimeout = setTimeout;
  8902. } else {
  8903. cachedSetTimeout = defaultSetTimout;
  8904. }
  8905. } catch (e) {
  8906. cachedSetTimeout = defaultSetTimout;
  8907. }
  8908. try {
  8909. if (typeof clearTimeout === 'function') {
  8910. cachedClearTimeout = clearTimeout;
  8911. } else {
  8912. cachedClearTimeout = defaultClearTimeout;
  8913. }
  8914. } catch (e) {
  8915. cachedClearTimeout = defaultClearTimeout;
  8916. }
  8917. } ())
  8918. function runTimeout(fun) {
  8919. if (cachedSetTimeout === setTimeout) {
  8920. //normal enviroments in sane situations
  8921. return setTimeout(fun, 0);
  8922. }
  8923. // if setTimeout wasn't available but was latter defined
  8924. if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
  8925. cachedSetTimeout = setTimeout;
  8926. return setTimeout(fun, 0);
  8927. }
  8928. try {
  8929. // when when somebody has screwed with setTimeout but no I.E. maddness
  8930. return cachedSetTimeout(fun, 0);
  8931. } catch(e){
  8932. try {
  8933. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  8934. return cachedSetTimeout.call(null, fun, 0);
  8935. } catch(e){
  8936. // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
  8937. return cachedSetTimeout.call(this, fun, 0);
  8938. }
  8939. }
  8940.  
  8941.  
  8942. }
  8943. function runClearTimeout(marker) {
  8944. if (cachedClearTimeout === clearTimeout) {
  8945. //normal enviroments in sane situations
  8946. return clearTimeout(marker);
  8947. }
  8948. // if clearTimeout wasn't available but was latter defined
  8949. if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
  8950. cachedClearTimeout = clearTimeout;
  8951. return clearTimeout(marker);
  8952. }
  8953. try {
  8954. // when when somebody has screwed with setTimeout but no I.E. maddness
  8955. return cachedClearTimeout(marker);
  8956. } catch (e){
  8957. try {
  8958. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  8959. return cachedClearTimeout.call(null, marker);
  8960. } catch (e){
  8961. // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
  8962. // Some versions of I.E. have different rules for clearTimeout vs setTimeout
  8963. return cachedClearTimeout.call(this, marker);
  8964. }
  8965. }
  8966.  
  8967.  
  8968.  
  8969. }
  8970. var queue = [];
  8971. var draining = false;
  8972. var currentQueue;
  8973. var queueIndex = -1;
  8974.  
  8975. function cleanUpNextTick() {
  8976. if (!draining || !currentQueue) {
  8977. return;
  8978. }
  8979. draining = false;
  8980. if (currentQueue.length) {
  8981. queue = currentQueue.concat(queue);
  8982. } else {
  8983. queueIndex = -1;
  8984. }
  8985. if (queue.length) {
  8986. drainQueue();
  8987. }
  8988. }
  8989.  
  8990. function drainQueue() {
  8991. if (draining) {
  8992. return;
  8993. }
  8994. var timeout = runTimeout(cleanUpNextTick);
  8995. draining = true;
  8996.  
  8997. var len = queue.length;
  8998. while(len) {
  8999. currentQueue = queue;
  9000. queue = [];
  9001. while (++queueIndex < len) {
  9002. if (currentQueue) {
  9003. currentQueue[queueIndex].run();
  9004. }
  9005. }
  9006. queueIndex = -1;
  9007. len = queue.length;
  9008. }
  9009. currentQueue = null;
  9010. draining = false;
  9011. runClearTimeout(timeout);
  9012. }
  9013.  
  9014. process.nextTick = function (fun) {
  9015. var args = new Array(arguments.length - 1);
  9016. if (arguments.length > 1) {
  9017. for (var i = 1; i < arguments.length; i++) {
  9018. args[i - 1] = arguments[i];
  9019. }
  9020. }
  9021. queue.push(new Item(fun, args));
  9022. if (queue.length === 1 && !draining) {
  9023. runTimeout(drainQueue);
  9024. }
  9025. };
  9026.  
  9027. // v8 likes predictible objects
  9028. function Item(fun, array) {
  9029. this.fun = fun;
  9030. this.array = array;
  9031. }
  9032. Item.prototype.run = function () {
  9033. this.fun.apply(null, this.array);
  9034. };
  9035. process.title = 'browser';
  9036. process.browser = true;
  9037. process.env = {};
  9038. process.argv = [];
  9039. process.version = ''; // empty string to avoid regexp issues
  9040. process.versions = {};
  9041.  
  9042. function noop() {}
  9043.  
  9044. process.on = noop;
  9045. process.addListener = noop;
  9046. process.once = noop;
  9047. process.off = noop;
  9048. process.removeListener = noop;
  9049. process.removeAllListeners = noop;
  9050. process.emit = noop;
  9051.  
  9052. process.binding = function (name) {
  9053. throw new Error('process.binding is not supported');
  9054. };
  9055.  
  9056. process.cwd = function () { return '/' };
  9057. process.chdir = function (dir) {
  9058. throw new Error('process.chdir is not supported');
  9059. };
  9060. process.umask = function() { return 0; };
  9061.  
  9062. },{}],40:[function(require,module,exports){
  9063. (function (global){
  9064. /*! https://mths.be/punycode v1.4.1 by @mathias */
  9065. ;(function(root) {
  9066.  
  9067. /** Detect free variables */
  9068. var freeExports = typeof exports == 'object' && exports &&
  9069. !exports.nodeType && exports;
  9070. var freeModule = typeof module == 'object' && module &&
  9071. !module.nodeType && module;
  9072. var freeGlobal = typeof global == 'object' && global;
  9073. if (
  9074. freeGlobal.global === freeGlobal ||
  9075. freeGlobal.window === freeGlobal ||
  9076. freeGlobal.self === freeGlobal
  9077. ) {
  9078. root = freeGlobal;
  9079. }
  9080.  
  9081. /**
  9082. * The `punycode` object.
  9083. * @name punycode
  9084. * @type Object
  9085. */
  9086. var punycode,
  9087.  
  9088. /** Highest positive signed 32-bit float value */
  9089. maxInt = 2147483647, // aka. 0x7FFFFFFF or 2^31-1
  9090.  
  9091. /** Bootstring parameters */
  9092. base = 36,
  9093. tMin = 1,
  9094. tMax = 26,
  9095. skew = 38,
  9096. damp = 700,
  9097. initialBias = 72,
  9098. initialN = 128, // 0x80
  9099. delimiter = '-', // '\x2D'
  9100.  
  9101. /** Regular expressions */
  9102. regexPunycode = /^xn--/,
  9103. regexNonASCII = /[^\x20-\x7E]/, // unprintable ASCII chars + non-ASCII chars
  9104. regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g, // RFC 3490 separators
  9105.  
  9106. /** Error messages */
  9107. errors = {
  9108. 'overflow': 'Overflow: input needs wider integers to process',
  9109. 'not-basic': 'Illegal input >= 0x80 (not a basic code point)',
  9110. 'invalid-input': 'Invalid input'
  9111. },
  9112.  
  9113. /** Convenience shortcuts */
  9114. baseMinusTMin = base - tMin,
  9115. floor = Math.floor,
  9116. stringFromCharCode = String.fromCharCode,
  9117.  
  9118. /** Temporary variable */
  9119. key;
  9120.  
  9121. /*--------------------------------------------------------------------------*/
  9122.  
  9123. /**
  9124. * A generic error utility function.
  9125. * @private
  9126. * @param {String} type The error type.
  9127. * @returns {Error} Throws a `RangeError` with the applicable error message.
  9128. */
  9129. function error(type) {
  9130. throw new RangeError(errors[type]);
  9131. }
  9132.  
  9133. /**
  9134. * A generic `Array#map` utility function.
  9135. * @private
  9136. * @param {Array} array The array to iterate over.
  9137. * @param {Function} callback The function that gets called for every array
  9138. * item.
  9139. * @returns {Array} A new array of values returned by the callback function.
  9140. */
  9141. function map(array, fn) {
  9142. var length = array.length;
  9143. var result = [];
  9144. while (length--) {
  9145. result[length] = fn(array[length]);
  9146. }
  9147. return result;
  9148. }
  9149.  
  9150. /**
  9151. * A simple `Array#map`-like wrapper to work with domain name strings or email
  9152. * addresses.
  9153. * @private
  9154. * @param {String} domain The domain name or email address.
  9155. * @param {Function} callback The function that gets called for every
  9156. * character.
  9157. * @returns {Array} A new string of characters returned by the callback
  9158. * function.
  9159. */
  9160. function mapDomain(string, fn) {
  9161. var parts = string.split('@');
  9162. var result = '';
  9163. if (parts.length > 1) {
  9164. // In email addresses, only the domain name should be punycoded. Leave
  9165. // the local part (i.e. everything up to `@`) intact.
  9166. result = parts[0] + '@';
  9167. string = parts[1];
  9168. }
  9169. // Avoid `split(regex)` for IE8 compatibility. See #17.
  9170. string = string.replace(regexSeparators, '\x2E');
  9171. var labels = string.split('.');
  9172. var encoded = map(labels, fn).join('.');
  9173. return result + encoded;
  9174. }
  9175.  
  9176. /**
  9177. * Creates an array containing the numeric code points of each Unicode
  9178. * character in the string. While JavaScript uses UCS-2 internally,
  9179. * this function will convert a pair of surrogate halves (each of which
  9180. * UCS-2 exposes as separate characters) into a single code point,
  9181. * matching UTF-16.
  9182. * @see `punycode.ucs2.encode`
  9183. * @see <https://mathiasbynens.be/notes/javascript-encoding>
  9184. * @memberOf punycode.ucs2
  9185. * @name decode
  9186. * @param {String} string The Unicode input string (UCS-2).
  9187. * @returns {Array} The new array of code points.
  9188. */
  9189. function ucs2decode(string) {
  9190. var output = [],
  9191. counter = 0,
  9192. length = string.length,
  9193. value,
  9194. extra;
  9195. while (counter < length) {
  9196. value = string.charCodeAt(counter++);
  9197. if (value >= 0xD800 && value <= 0xDBFF && counter < length) {
  9198. // high surrogate, and there is a next character
  9199. extra = string.charCodeAt(counter++);
  9200. if ((extra & 0xFC00) == 0xDC00) { // low surrogate
  9201. output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000);
  9202. } else {
  9203. // unmatched surrogate; only append this code unit, in case the next
  9204. // code unit is the high surrogate of a surrogate pair
  9205. output.push(value);
  9206. counter--;
  9207. }
  9208. } else {
  9209. output.push(value);
  9210. }
  9211. }
  9212. return output;
  9213. }
  9214.  
  9215. /**
  9216. * Creates a string based on an array of numeric code points.
  9217. * @see `punycode.ucs2.decode`
  9218. * @memberOf punycode.ucs2
  9219. * @name encode
  9220. * @param {Array} codePoints The array of numeric code points.
  9221. * @returns {String} The new Unicode string (UCS-2).
  9222. */
  9223. function ucs2encode(array) {
  9224. return map(array, function(value) {
  9225. var output = '';
  9226. if (value > 0xFFFF) {
  9227. value -= 0x10000;
  9228. output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800);
  9229. value = 0xDC00 | value & 0x3FF;
  9230. }
  9231. output += stringFromCharCode(value);
  9232. return output;
  9233. }).join('');
  9234. }
  9235.  
  9236. /**
  9237. * Converts a basic code point into a digit/integer.
  9238. * @see `digitToBasic()`
  9239. * @private
  9240. * @param {Number} codePoint The basic numeric code point value.
  9241. * @returns {Number} The numeric value of a basic code point (for use in
  9242. * representing integers) in the range `0` to `base - 1`, or `base` if
  9243. * the code point does not represent a value.
  9244. */
  9245. function basicToDigit(codePoint) {
  9246. if (codePoint - 48 < 10) {
  9247. return codePoint - 22;
  9248. }
  9249. if (codePoint - 65 < 26) {
  9250. return codePoint - 65;
  9251. }
  9252. if (codePoint - 97 < 26) {
  9253. return codePoint - 97;
  9254. }
  9255. return base;
  9256. }
  9257.  
  9258. /**
  9259. * Converts a digit/integer into a basic code point.
  9260. * @see `basicToDigit()`
  9261. * @private
  9262. * @param {Number} digit The numeric value of a basic code point.
  9263. * @returns {Number} The basic code point whose value (when used for
  9264. * representing integers) is `digit`, which needs to be in the range
  9265. * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is
  9266. * used; else, the lowercase form is used. The behavior is undefined
  9267. * if `flag` is non-zero and `digit` has no uppercase form.
  9268. */
  9269. function digitToBasic(digit, flag) {
  9270. // 0..25 map to ASCII a..z or A..Z
  9271. // 26..35 map to ASCII 0..9
  9272. return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5);
  9273. }
  9274.  
  9275. /**
  9276. * Bias adaptation function as per section 3.4 of RFC 3492.
  9277. * https://tools.ietf.org/html/rfc3492#section-3.4
  9278. * @private
  9279. */
  9280. function adapt(delta, numPoints, firstTime) {
  9281. var k = 0;
  9282. delta = firstTime ? floor(delta / damp) : delta >> 1;
  9283. delta += floor(delta / numPoints);
  9284. for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) {
  9285. delta = floor(delta / baseMinusTMin);
  9286. }
  9287. return floor(k + (baseMinusTMin + 1) * delta / (delta + skew));
  9288. }
  9289.  
  9290. /**
  9291. * Converts a Punycode string of ASCII-only symbols to a string of Unicode
  9292. * symbols.
  9293. * @memberOf punycode
  9294. * @param {String} input The Punycode string of ASCII-only symbols.
  9295. * @returns {String} The resulting string of Unicode symbols.
  9296. */
  9297. function decode(input) {
  9298. // Don't use UCS-2
  9299. var output = [],
  9300. inputLength = input.length,
  9301. out,
  9302. i = 0,
  9303. n = initialN,
  9304. bias = initialBias,
  9305. basic,
  9306. j,
  9307. index,
  9308. oldi,
  9309. w,
  9310. k,
  9311. digit,
  9312. t,
  9313. /** Cached calculation results */
  9314. baseMinusT;
  9315.  
  9316. // Handle the basic code points: let `basic` be the number of input code
  9317. // points before the last delimiter, or `0` if there is none, then copy
  9318. // the first basic code points to the output.
  9319.  
  9320. basic = input.lastIndexOf(delimiter);
  9321. if (basic < 0) {
  9322. basic = 0;
  9323. }
  9324.  
  9325. for (j = 0; j < basic; ++j) {
  9326. // if it's not a basic code point
  9327. if (input.charCodeAt(j) >= 0x80) {
  9328. error('not-basic');
  9329. }
  9330. output.push(input.charCodeAt(j));
  9331. }
  9332.  
  9333. // Main decoding loop: start just after the last delimiter if any basic code
  9334. // points were copied; start at the beginning otherwise.
  9335.  
  9336. for (index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) {
  9337.  
  9338. // `index` is the index of the next character to be consumed.
  9339. // Decode a generalized variable-length integer into `delta`,
  9340. // which gets added to `i`. The overflow checking is easier
  9341. // if we increase `i` as we go, then subtract off its starting
  9342. // value at the end to obtain `delta`.
  9343. for (oldi = i, w = 1, k = base; /* no condition */; k += base) {
  9344.  
  9345. if (index >= inputLength) {
  9346. error('invalid-input');
  9347. }
  9348.  
  9349. digit = basicToDigit(input.charCodeAt(index++));
  9350.  
  9351. if (digit >= base || digit > floor((maxInt - i) / w)) {
  9352. error('overflow');
  9353. }
  9354.  
  9355. i += digit * w;
  9356. t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
  9357.  
  9358. if (digit < t) {
  9359. break;
  9360. }
  9361.  
  9362. baseMinusT = base - t;
  9363. if (w > floor(maxInt / baseMinusT)) {
  9364. error('overflow');
  9365. }
  9366.  
  9367. w *= baseMinusT;
  9368.  
  9369. }
  9370.  
  9371. out = output.length + 1;
  9372. bias = adapt(i - oldi, out, oldi == 0);
  9373.  
  9374. // `i` was supposed to wrap around from `out` to `0`,
  9375. // incrementing `n` each time, so we'll fix that now:
  9376. if (floor(i / out) > maxInt - n) {
  9377. error('overflow');
  9378. }
  9379.  
  9380. n += floor(i / out);
  9381. i %= out;
  9382.  
  9383. // Insert `n` at position `i` of the output
  9384. output.splice(i++, 0, n);
  9385.  
  9386. }
  9387.  
  9388. return ucs2encode(output);
  9389. }
  9390.  
  9391. /**
  9392. * Converts a string of Unicode symbols (e.g. a domain name label) to a
  9393. * Punycode string of ASCII-only symbols.
  9394. * @memberOf punycode
  9395. * @param {String} input The string of Unicode symbols.
  9396. * @returns {String} The resulting Punycode string of ASCII-only symbols.
  9397. */
  9398. function encode(input) {
  9399. var n,
  9400. delta,
  9401. handledCPCount,
  9402. basicLength,
  9403. bias,
  9404. j,
  9405. m,
  9406. q,
  9407. k,
  9408. t,
  9409. currentValue,
  9410. output = [],
  9411. /** `inputLength` will hold the number of code points in `input`. */
  9412. inputLength,
  9413. /** Cached calculation results */
  9414. handledCPCountPlusOne,
  9415. baseMinusT,
  9416. qMinusT;
  9417.  
  9418. // Convert the input in UCS-2 to Unicode
  9419. input = ucs2decode(input);
  9420.  
  9421. // Cache the length
  9422. inputLength = input.length;
  9423.  
  9424. // Initialize the state
  9425. n = initialN;
  9426. delta = 0;
  9427. bias = initialBias;
  9428.  
  9429. // Handle the basic code points
  9430. for (j = 0; j < inputLength; ++j) {
  9431. currentValue = input[j];
  9432. if (currentValue < 0x80) {
  9433. output.push(stringFromCharCode(currentValue));
  9434. }
  9435. }
  9436.  
  9437. handledCPCount = basicLength = output.length;
  9438.  
  9439. // `handledCPCount` is the number of code points that have been handled;
  9440. // `basicLength` is the number of basic code points.
  9441.  
  9442. // Finish the basic string - if it is not empty - with a delimiter
  9443. if (basicLength) {
  9444. output.push(delimiter);
  9445. }
  9446.  
  9447. // Main encoding loop:
  9448. while (handledCPCount < inputLength) {
  9449.  
  9450. // All non-basic code points < n have been handled already. Find the next
  9451. // larger one:
  9452. for (m = maxInt, j = 0; j < inputLength; ++j) {
  9453. currentValue = input[j];
  9454. if (currentValue >= n && currentValue < m) {
  9455. m = currentValue;
  9456. }
  9457. }
  9458.  
  9459. // Increase `delta` enough to advance the decoder's <n,i> state to <m,0>,
  9460. // but guard against overflow
  9461. handledCPCountPlusOne = handledCPCount + 1;
  9462. if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) {
  9463. error('overflow');
  9464. }
  9465.  
  9466. delta += (m - n) * handledCPCountPlusOne;
  9467. n = m;
  9468.  
  9469. for (j = 0; j < inputLength; ++j) {
  9470. currentValue = input[j];
  9471.  
  9472. if (currentValue < n && ++delta > maxInt) {
  9473. error('overflow');
  9474. }
  9475.  
  9476. if (currentValue == n) {
  9477. // Represent delta as a generalized variable-length integer
  9478. for (q = delta, k = base; /* no condition */; k += base) {
  9479. t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
  9480. if (q < t) {
  9481. break;
  9482. }
  9483. qMinusT = q - t;
  9484. baseMinusT = base - t;
  9485. output.push(
  9486. stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0))
  9487. );
  9488. q = floor(qMinusT / baseMinusT);
  9489. }
  9490.  
  9491. output.push(stringFromCharCode(digitToBasic(q, 0)));
  9492. bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength);
  9493. delta = 0;
  9494. ++handledCPCount;
  9495. }
  9496. }
  9497.  
  9498. ++delta;
  9499. ++n;
  9500.  
  9501. }
  9502. return output.join('');
  9503. }
  9504.  
  9505. /**
  9506. * Converts a Punycode string representing a domain name or an email address
  9507. * to Unicode. Only the Punycoded parts of the input will be converted, i.e.
  9508. * it doesn't matter if you call it on a string that has already been
  9509. * converted to Unicode.
  9510. * @memberOf punycode
  9511. * @param {String} input The Punycoded domain name or email address to
  9512. * convert to Unicode.
  9513. * @returns {String} The Unicode representation of the given Punycode
  9514. * string.
  9515. */
  9516. function toUnicode(input) {
  9517. return mapDomain(input, function(string) {
  9518. return regexPunycode.test(string)
  9519. ? decode(string.slice(4).toLowerCase())
  9520. : string;
  9521. });
  9522. }
  9523.  
  9524. /**
  9525. * Converts a Unicode string representing a domain name or an email address to
  9526. * Punycode. Only the non-ASCII parts of the domain name will be converted,
  9527. * i.e. it doesn't matter if you call it with a domain that's already in
  9528. * ASCII.
  9529. * @memberOf punycode
  9530. * @param {String} input The domain name or email address to convert, as a
  9531. * Unicode string.
  9532. * @returns {String} The Punycode representation of the given domain name or
  9533. * email address.
  9534. */
  9535. function toASCII(input) {
  9536. return mapDomain(input, function(string) {
  9537. return regexNonASCII.test(string)
  9538. ? 'xn--' + encode(string)
  9539. : string;
  9540. });
  9541. }
  9542.  
  9543. /*--------------------------------------------------------------------------*/
  9544.  
  9545. /** Define the public API */
  9546. punycode = {
  9547. /**
  9548. * A string representing the current Punycode.js version number.
  9549. * @memberOf punycode
  9550. * @type String
  9551. */
  9552. 'version': '1.4.1',
  9553. /**
  9554. * An object of methods to convert from JavaScript's internal character
  9555. * representation (UCS-2) to Unicode code points, and back.
  9556. * @see <https://mathiasbynens.be/notes/javascript-encoding>
  9557. * @memberOf punycode
  9558. * @type Object
  9559. */
  9560. 'ucs2': {
  9561. 'decode': ucs2decode,
  9562. 'encode': ucs2encode
  9563. },
  9564. 'decode': decode,
  9565. 'encode': encode,
  9566. 'toASCII': toASCII,
  9567. 'toUnicode': toUnicode
  9568. };
  9569.  
  9570. /** Expose `punycode` */
  9571. // Some AMD build optimizers, like r.js, check for specific condition patterns
  9572. // like the following:
  9573. if (
  9574. typeof define == 'function' &&
  9575. typeof define.amd == 'object' &&
  9576. define.amd
  9577. ) {
  9578. define('punycode', function() {
  9579. return punycode;
  9580. });
  9581. } else if (freeExports && freeModule) {
  9582. if (module.exports == freeExports) {
  9583. // in Node.js, io.js, or RingoJS v0.8.0+
  9584. freeModule.exports = punycode;
  9585. } else {
  9586. // in Narwhal or RingoJS v0.7.0-
  9587. for (key in punycode) {
  9588. punycode.hasOwnProperty(key) && (freeExports[key] = punycode[key]);
  9589. }
  9590. }
  9591. } else {
  9592. // in Rhino or a web browser
  9593. root.punycode = punycode;
  9594. }
  9595.  
  9596. }(this));
  9597.  
  9598. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  9599. },{}],41:[function(require,module,exports){
  9600. // Copyright Joyent, Inc. and other Node contributors.
  9601. //
  9602. // Permission is hereby granted, free of charge, to any person obtaining a
  9603. // copy of this software and associated documentation files (the
  9604. // "Software"), to deal in the Software without restriction, including
  9605. // without limitation the rights to use, copy, modify, merge, publish,
  9606. // distribute, sublicense, and/or sell copies of the Software, and to permit
  9607. // persons to whom the Software is furnished to do so, subject to the
  9608. // following conditions:
  9609. //
  9610. // The above copyright notice and this permission notice shall be included
  9611. // in all copies or substantial portions of the Software.
  9612. //
  9613. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  9614. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  9615. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  9616. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  9617. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  9618. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  9619. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  9620.  
  9621. 'use strict';
  9622.  
  9623. // If obj.hasOwnProperty has been overridden, then calling
  9624. // obj.hasOwnProperty(prop) will break.
  9625. // See: https://github.com/joyent/node/issues/1707
  9626. function hasOwnProperty(obj, prop) {
  9627. return Object.prototype.hasOwnProperty.call(obj, prop);
  9628. }
  9629.  
  9630. module.exports = function(qs, sep, eq, options) {
  9631. sep = sep || '&';
  9632. eq = eq || '=';
  9633. var obj = {};
  9634.  
  9635. if (typeof qs !== 'string' || qs.length === 0) {
  9636. return obj;
  9637. }
  9638.  
  9639. var regexp = /\+/g;
  9640. qs = qs.split(sep);
  9641.  
  9642. var maxKeys = 1000;
  9643. if (options && typeof options.maxKeys === 'number') {
  9644. maxKeys = options.maxKeys;
  9645. }
  9646.  
  9647. var len = qs.length;
  9648. // maxKeys <= 0 means that we should not limit keys count
  9649. if (maxKeys > 0 && len > maxKeys) {
  9650. len = maxKeys;
  9651. }
  9652.  
  9653. for (var i = 0; i < len; ++i) {
  9654. var x = qs[i].replace(regexp, '%20'),
  9655. idx = x.indexOf(eq),
  9656. kstr, vstr, k, v;
  9657.  
  9658. if (idx >= 0) {
  9659. kstr = x.substr(0, idx);
  9660. vstr = x.substr(idx + 1);
  9661. } else {
  9662. kstr = x;
  9663. vstr = '';
  9664. }
  9665.  
  9666. k = decodeURIComponent(kstr);
  9667. v = decodeURIComponent(vstr);
  9668.  
  9669. if (!hasOwnProperty(obj, k)) {
  9670. obj[k] = v;
  9671. } else if (isArray(obj[k])) {
  9672. obj[k].push(v);
  9673. } else {
  9674. obj[k] = [obj[k], v];
  9675. }
  9676. }
  9677.  
  9678. return obj;
  9679. };
  9680.  
  9681. var isArray = Array.isArray || function (xs) {
  9682. return Object.prototype.toString.call(xs) === '[object Array]';
  9683. };
  9684.  
  9685. },{}],42:[function(require,module,exports){
  9686. // Copyright Joyent, Inc. and other Node contributors.
  9687. //
  9688. // Permission is hereby granted, free of charge, to any person obtaining a
  9689. // copy of this software and associated documentation files (the
  9690. // "Software"), to deal in the Software without restriction, including
  9691. // without limitation the rights to use, copy, modify, merge, publish,
  9692. // distribute, sublicense, and/or sell copies of the Software, and to permit
  9693. // persons to whom the Software is furnished to do so, subject to the
  9694. // following conditions:
  9695. //
  9696. // The above copyright notice and this permission notice shall be included
  9697. // in all copies or substantial portions of the Software.
  9698. //
  9699. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  9700. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  9701. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  9702. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  9703. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  9704. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  9705. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  9706.  
  9707. 'use strict';
  9708.  
  9709. var stringifyPrimitive = function(v) {
  9710. switch (typeof v) {
  9711. case 'string':
  9712. return v;
  9713.  
  9714. case 'boolean':
  9715. return v ? 'true' : 'false';
  9716.  
  9717. case 'number':
  9718. return isFinite(v) ? v : '';
  9719.  
  9720. default:
  9721. return '';
  9722. }
  9723. };
  9724.  
  9725. module.exports = function(obj, sep, eq, name) {
  9726. sep = sep || '&';
  9727. eq = eq || '=';
  9728. if (obj === null) {
  9729. obj = undefined;
  9730. }
  9731.  
  9732. if (typeof obj === 'object') {
  9733. return map(objectKeys(obj), function(k) {
  9734. var ks = encodeURIComponent(stringifyPrimitive(k)) + eq;
  9735. if (isArray(obj[k])) {
  9736. return map(obj[k], function(v) {
  9737. return ks + encodeURIComponent(stringifyPrimitive(v));
  9738. }).join(sep);
  9739. } else {
  9740. return ks + encodeURIComponent(stringifyPrimitive(obj[k]));
  9741. }
  9742. }).join(sep);
  9743.  
  9744. }
  9745.  
  9746. if (!name) return '';
  9747. return encodeURIComponent(stringifyPrimitive(name)) + eq +
  9748. encodeURIComponent(stringifyPrimitive(obj));
  9749. };
  9750.  
  9751. var isArray = Array.isArray || function (xs) {
  9752. return Object.prototype.toString.call(xs) === '[object Array]';
  9753. };
  9754.  
  9755. function map (xs, f) {
  9756. if (xs.map) return xs.map(f);
  9757. var res = [];
  9758. for (var i = 0; i < xs.length; i++) {
  9759. res.push(f(xs[i], i));
  9760. }
  9761. return res;
  9762. }
  9763.  
  9764. var objectKeys = Object.keys || function (obj) {
  9765. var res = [];
  9766. for (var key in obj) {
  9767. if (Object.prototype.hasOwnProperty.call(obj, key)) res.push(key);
  9768. }
  9769. return res;
  9770. };
  9771.  
  9772. },{}],43:[function(require,module,exports){
  9773. 'use strict';
  9774.  
  9775. exports.decode = exports.parse = require('./decode');
  9776. exports.encode = exports.stringify = require('./encode');
  9777.  
  9778. },{"./decode":41,"./encode":42}],44:[function(require,module,exports){
  9779. // Copyright Joyent, Inc. and other Node contributors.
  9780. //
  9781. // Permission is hereby granted, free of charge, to any person obtaining a
  9782. // copy of this software and associated documentation files (the
  9783. // "Software"), to deal in the Software without restriction, including
  9784. // without limitation the rights to use, copy, modify, merge, publish,
  9785. // distribute, sublicense, and/or sell copies of the Software, and to permit
  9786. // persons to whom the Software is furnished to do so, subject to the
  9787. // following conditions:
  9788. //
  9789. // The above copyright notice and this permission notice shall be included
  9790. // in all copies or substantial portions of the Software.
  9791. //
  9792. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  9793. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  9794. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  9795. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  9796. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  9797. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  9798. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  9799.  
  9800. 'use strict';
  9801.  
  9802. var punycode = require('punycode');
  9803. var util = require('./util');
  9804.  
  9805. exports.parse = urlParse;
  9806. exports.resolve = urlResolve;
  9807. exports.resolveObject = urlResolveObject;
  9808. exports.format = urlFormat;
  9809.  
  9810. exports.Url = Url;
  9811.  
  9812. function Url() {
  9813. this.protocol = null;
  9814. this.slashes = null;
  9815. this.auth = null;
  9816. this.host = null;
  9817. this.port = null;
  9818. this.hostname = null;
  9819. this.hash = null;
  9820. this.search = null;
  9821. this.query = null;
  9822. this.pathname = null;
  9823. this.path = null;
  9824. this.href = null;
  9825. }
  9826.  
  9827. // Reference: RFC 3986, RFC 1808, RFC 2396
  9828.  
  9829. // define these here so at least they only have to be
  9830. // compiled once on the first module load.
  9831. var protocolPattern = /^([a-z0-9.+-]+:)/i,
  9832. portPattern = /:[0-9]*$/,
  9833.  
  9834. // Special case for a simple path URL
  9835. simplePathPattern = /^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/,
  9836.  
  9837. // RFC 2396: characters reserved for delimiting URLs.
  9838. // We actually just auto-escape these.
  9839. delims = ['<', '>', '"', '`', ' ', '\r', '\n', '\t'],
  9840.  
  9841. // RFC 2396: characters not allowed for various reasons.
  9842. unwise = ['{', '}', '|', '\\', '^', '`'].concat(delims),
  9843.  
  9844. // Allowed by RFCs, but cause of XSS attacks. Always escape these.
  9845. autoEscape = ['\''].concat(unwise),
  9846. // Characters that are never ever allowed in a hostname.
  9847. // Note that any invalid chars are also handled, but these
  9848. // are the ones that are *expected* to be seen, so we fast-path
  9849. // them.
  9850. nonHostChars = ['%', '/', '?', ';', '#'].concat(autoEscape),
  9851. hostEndingChars = ['/', '?', '#'],
  9852. hostnameMaxLen = 255,
  9853. hostnamePartPattern = /^[+a-z0-9A-Z_-]{0,63}$/,
  9854. hostnamePartStart = /^([+a-z0-9A-Z_-]{0,63})(.*)$/,
  9855. // protocols that can allow "unsafe" and "unwise" chars.
  9856. unsafeProtocol = {
  9857. 'javascript': true,
  9858. 'javascript:': true
  9859. },
  9860. // protocols that never have a hostname.
  9861. hostlessProtocol = {
  9862. 'javascript': true,
  9863. 'javascript:': true
  9864. },
  9865. // protocols that always contain a // bit.
  9866. slashedProtocol = {
  9867. 'http': true,
  9868. 'https': true,
  9869. 'ftp': true,
  9870. 'gopher': true,
  9871. 'file': true,
  9872. 'http:': true,
  9873. 'https:': true,
  9874. 'ftp:': true,
  9875. 'gopher:': true,
  9876. 'file:': true
  9877. },
  9878. querystring = require('querystring');
  9879.  
  9880. function urlParse(url, parseQueryString, slashesDenoteHost) {
  9881. if (url && util.isObject(url) && url instanceof Url) return url;
  9882.  
  9883. var u = new Url;
  9884. u.parse(url, parseQueryString, slashesDenoteHost);
  9885. return u;
  9886. }
  9887.  
  9888. Url.prototype.parse = function(url, parseQueryString, slashesDenoteHost) {
  9889. if (!util.isString(url)) {
  9890. throw new TypeError("Parameter 'url' must be a string, not " + typeof url);
  9891. }
  9892.  
  9893. // Copy chrome, IE, opera backslash-handling behavior.
  9894. // Back slashes before the query string get converted to forward slashes
  9895. // See: https://code.google.com/p/chromium/issues/detail?id=25916
  9896. var queryIndex = url.indexOf('?'),
  9897. splitter =
  9898. (queryIndex !== -1 && queryIndex < url.indexOf('#')) ? '?' : '#',
  9899. uSplit = url.split(splitter),
  9900. slashRegex = /\\/g;
  9901. uSplit[0] = uSplit[0].replace(slashRegex, '/');
  9902. url = uSplit.join(splitter);
  9903.  
  9904. var rest = url;
  9905.  
  9906. // trim before proceeding.
  9907. // This is to support parse stuff like " http://foo.com \n"
  9908. rest = rest.trim();
  9909.  
  9910. if (!slashesDenoteHost && url.split('#').length === 1) {
  9911. // Try fast path regexp
  9912. var simplePath = simplePathPattern.exec(rest);
  9913. if (simplePath) {
  9914. this.path = rest;
  9915. this.href = rest;
  9916. this.pathname = simplePath[1];
  9917. if (simplePath[2]) {
  9918. this.search = simplePath[2];
  9919. if (parseQueryString) {
  9920. this.query = querystring.parse(this.search.substr(1));
  9921. } else {
  9922. this.query = this.search.substr(1);
  9923. }
  9924. } else if (parseQueryString) {
  9925. this.search = '';
  9926. this.query = {};
  9927. }
  9928. return this;
  9929. }
  9930. }
  9931.  
  9932. var proto = protocolPattern.exec(rest);
  9933. if (proto) {
  9934. proto = proto[0];
  9935. var lowerProto = proto.toLowerCase();
  9936. this.protocol = lowerProto;
  9937. rest = rest.substr(proto.length);
  9938. }
  9939.  
  9940. // figure out if it's got a host
  9941. // user@server is *always* interpreted as a hostname, and url
  9942. // resolution will treat //foo/bar as host=foo,path=bar because that's
  9943. // how the browser resolves relative URLs.
  9944. if (slashesDenoteHost || proto || rest.match(/^\/\/[^@\/]+@[^@\/]+/)) {
  9945. var slashes = rest.substr(0, 2) === '//';
  9946. if (slashes && !(proto && hostlessProtocol[proto])) {
  9947. rest = rest.substr(2);
  9948. this.slashes = true;
  9949. }
  9950. }
  9951.  
  9952. if (!hostlessProtocol[proto] &&
  9953. (slashes || (proto && !slashedProtocol[proto]))) {
  9954.  
  9955. // there's a hostname.
  9956. // the first instance of /, ?, ;, or # ends the host.
  9957. //
  9958. // If there is an @ in the hostname, then non-host chars *are* allowed
  9959. // to the left of the last @ sign, unless some host-ending character
  9960. // comes *before* the @-sign.
  9961. // URLs are obnoxious.
  9962. //
  9963. // ex:
  9964. // http://a@b@c/ => user:a@b host:c
  9965. // http://a@b?@c => user:a host:c path:/?@c
  9966.  
  9967. // v0.12 TODO(isaacs): This is not quite how Chrome does things.
  9968. // Review our test case against browsers more comprehensively.
  9969.  
  9970. // find the first instance of any hostEndingChars
  9971. var hostEnd = -1;
  9972. for (var i = 0; i < hostEndingChars.length; i++) {
  9973. var hec = rest.indexOf(hostEndingChars[i]);
  9974. if (hec !== -1 && (hostEnd === -1 || hec < hostEnd))
  9975. hostEnd = hec;
  9976. }
  9977.  
  9978. // at this point, either we have an explicit point where the
  9979. // auth portion cannot go past, or the last @ char is the decider.
  9980. var auth, atSign;
  9981. if (hostEnd === -1) {
  9982. // atSign can be anywhere.
  9983. atSign = rest.lastIndexOf('@');
  9984. } else {
  9985. // atSign must be in auth portion.
  9986. // http://a@b/c@d => host:b auth:a path:/c@d
  9987. atSign = rest.lastIndexOf('@', hostEnd);
  9988. }
  9989.  
  9990. // Now we have a portion which is definitely the auth.
  9991. // Pull that off.
  9992. if (atSign !== -1) {
  9993. auth = rest.slice(0, atSign);
  9994. rest = rest.slice(atSign + 1);
  9995. this.auth = decodeURIComponent(auth);
  9996. }
  9997.  
  9998. // the host is the remaining to the left of the first non-host char
  9999. hostEnd = -1;
  10000. for (var i = 0; i < nonHostChars.length; i++) {
  10001. var hec = rest.indexOf(nonHostChars[i]);
  10002. if (hec !== -1 && (hostEnd === -1 || hec < hostEnd))
  10003. hostEnd = hec;
  10004. }
  10005. // if we still have not hit it, then the entire thing is a host.
  10006. if (hostEnd === -1)
  10007. hostEnd = rest.length;
  10008.  
  10009. this.host = rest.slice(0, hostEnd);
  10010. rest = rest.slice(hostEnd);
  10011.  
  10012. // pull out port.
  10013. this.parseHost();
  10014.  
  10015. // we've indicated that there is a hostname,
  10016. // so even if it's empty, it has to be present.
  10017. this.hostname = this.hostname || '';
  10018.  
  10019. // if hostname begins with [ and ends with ]
  10020. // assume that it's an IPv6 address.
  10021. var ipv6Hostname = this.hostname[0] === '[' &&
  10022. this.hostname[this.hostname.length - 1] === ']';
  10023.  
  10024. // validate a little.
  10025. if (!ipv6Hostname) {
  10026. var hostparts = this.hostname.split(/\./);
  10027. for (var i = 0, l = hostparts.length; i < l; i++) {
  10028. var part = hostparts[i];
  10029. if (!part) continue;
  10030. if (!part.match(hostnamePartPattern)) {
  10031. var newpart = '';
  10032. for (var j = 0, k = part.length; j < k; j++) {
  10033. if (part.charCodeAt(j) > 127) {
  10034. // we replace non-ASCII char with a temporary placeholder
  10035. // we need this to make sure size of hostname is not
  10036. // broken by replacing non-ASCII by nothing
  10037. newpart += 'x';
  10038. } else {
  10039. newpart += part[j];
  10040. }
  10041. }
  10042. // we test again with ASCII char only
  10043. if (!newpart.match(hostnamePartPattern)) {
  10044. var validParts = hostparts.slice(0, i);
  10045. var notHost = hostparts.slice(i + 1);
  10046. var bit = part.match(hostnamePartStart);
  10047. if (bit) {
  10048. validParts.push(bit[1]);
  10049. notHost.unshift(bit[2]);
  10050. }
  10051. if (notHost.length) {
  10052. rest = '/' + notHost.join('.') + rest;
  10053. }
  10054. this.hostname = validParts.join('.');
  10055. break;
  10056. }
  10057. }
  10058. }
  10059. }
  10060.  
  10061. if (this.hostname.length > hostnameMaxLen) {
  10062. this.hostname = '';
  10063. } else {
  10064. // hostnames are always lower case.
  10065. this.hostname = this.hostname.toLowerCase();
  10066. }
  10067.  
  10068. if (!ipv6Hostname) {
  10069. // IDNA Support: Returns a punycoded representation of "domain".
  10070. // It only converts parts of the domain name that
  10071. // have non-ASCII characters, i.e. it doesn't matter if
  10072. // you call it with a domain that already is ASCII-only.
  10073. this.hostname = punycode.toASCII(this.hostname);
  10074. }
  10075.  
  10076. var p = this.port ? ':' + this.port : '';
  10077. var h = this.hostname || '';
  10078. this.host = h + p;
  10079. this.href += this.host;
  10080.  
  10081. // strip [ and ] from the hostname
  10082. // the host field still retains them, though
  10083. if (ipv6Hostname) {
  10084. this.hostname = this.hostname.substr(1, this.hostname.length - 2);
  10085. if (rest[0] !== '/') {
  10086. rest = '/' + rest;
  10087. }
  10088. }
  10089. }
  10090.  
  10091. // now rest is set to the post-host stuff.
  10092. // chop off any delim chars.
  10093. if (!unsafeProtocol[lowerProto]) {
  10094.  
  10095. // First, make 100% sure that any "autoEscape" chars get
  10096. // escaped, even if encodeURIComponent doesn't think they
  10097. // need to be.
  10098. for (var i = 0, l = autoEscape.length; i < l; i++) {
  10099. var ae = autoEscape[i];
  10100. if (rest.indexOf(ae) === -1)
  10101. continue;
  10102. var esc = encodeURIComponent(ae);
  10103. if (esc === ae) {
  10104. esc = escape(ae);
  10105. }
  10106. rest = rest.split(ae).join(esc);
  10107. }
  10108. }
  10109.  
  10110.  
  10111. // chop off from the tail first.
  10112. var hash = rest.indexOf('#');
  10113. if (hash !== -1) {
  10114. // got a fragment string.
  10115. this.hash = rest.substr(hash);
  10116. rest = rest.slice(0, hash);
  10117. }
  10118. var qm = rest.indexOf('?');
  10119. if (qm !== -1) {
  10120. this.search = rest.substr(qm);
  10121. this.query = rest.substr(qm + 1);
  10122. if (parseQueryString) {
  10123. this.query = querystring.parse(this.query);
  10124. }
  10125. rest = rest.slice(0, qm);
  10126. } else if (parseQueryString) {
  10127. // no query string, but parseQueryString still requested
  10128. this.search = '';
  10129. this.query = {};
  10130. }
  10131. if (rest) this.pathname = rest;
  10132. if (slashedProtocol[lowerProto] &&
  10133. this.hostname && !this.pathname) {
  10134. this.pathname = '/';
  10135. }
  10136.  
  10137. //to support http.request
  10138. if (this.pathname || this.search) {
  10139. var p = this.pathname || '';
  10140. var s = this.search || '';
  10141. this.path = p + s;
  10142. }
  10143.  
  10144. // finally, reconstruct the href based on what has been validated.
  10145. this.href = this.format();
  10146. return this;
  10147. };
  10148.  
  10149. // format a parsed object into a url string
  10150. function urlFormat(obj) {
  10151. // ensure it's an object, and not a string url.
  10152. // If it's an obj, this is a no-op.
  10153. // this way, you can call url_format() on strings
  10154. // to clean up potentially wonky urls.
  10155. if (util.isString(obj)) obj = urlParse(obj);
  10156. if (!(obj instanceof Url)) return Url.prototype.format.call(obj);
  10157. return obj.format();
  10158. }
  10159.  
  10160. Url.prototype.format = function() {
  10161. var auth = this.auth || '';
  10162. if (auth) {
  10163. auth = encodeURIComponent(auth);
  10164. auth = auth.replace(/%3A/i, ':');
  10165. auth += '@';
  10166. }
  10167.  
  10168. var protocol = this.protocol || '',
  10169. pathname = this.pathname || '',
  10170. hash = this.hash || '',
  10171. host = false,
  10172. query = '';
  10173.  
  10174. if (this.host) {
  10175. host = auth + this.host;
  10176. } else if (this.hostname) {
  10177. host = auth + (this.hostname.indexOf(':') === -1 ?
  10178. this.hostname :
  10179. '[' + this.hostname + ']');
  10180. if (this.port) {
  10181. host += ':' + this.port;
  10182. }
  10183. }
  10184.  
  10185. if (this.query &&
  10186. util.isObject(this.query) &&
  10187. Object.keys(this.query).length) {
  10188. query = querystring.stringify(this.query);
  10189. }
  10190.  
  10191. var search = this.search || (query && ('?' + query)) || '';
  10192.  
  10193. if (protocol && protocol.substr(-1) !== ':') protocol += ':';
  10194.  
  10195. // only the slashedProtocols get the //. Not mailto:, xmpp:, etc.
  10196. // unless they had them to begin with.
  10197. if (this.slashes ||
  10198. (!protocol || slashedProtocol[protocol]) && host !== false) {
  10199. host = '//' + (host || '');
  10200. if (pathname && pathname.charAt(0) !== '/') pathname = '/' + pathname;
  10201. } else if (!host) {
  10202. host = '';
  10203. }
  10204.  
  10205. if (hash && hash.charAt(0) !== '#') hash = '#' + hash;
  10206. if (search && search.charAt(0) !== '?') search = '?' + search;
  10207.  
  10208. pathname = pathname.replace(/[?#]/g, function(match) {
  10209. return encodeURIComponent(match);
  10210. });
  10211. search = search.replace('#', '%23');
  10212.  
  10213. return protocol + host + pathname + search + hash;
  10214. };
  10215.  
  10216. function urlResolve(source, relative) {
  10217. return urlParse(source, false, true).resolve(relative);
  10218. }
  10219.  
  10220. Url.prototype.resolve = function(relative) {
  10221. return this.resolveObject(urlParse(relative, false, true)).format();
  10222. };
  10223.  
  10224. function urlResolveObject(source, relative) {
  10225. if (!source) return relative;
  10226. return urlParse(source, false, true).resolveObject(relative);
  10227. }
  10228.  
  10229. Url.prototype.resolveObject = function(relative) {
  10230. if (util.isString(relative)) {
  10231. var rel = new Url();
  10232. rel.parse(relative, false, true);
  10233. relative = rel;
  10234. }
  10235.  
  10236. var result = new Url();
  10237. var tkeys = Object.keys(this);
  10238. for (var tk = 0; tk < tkeys.length; tk++) {
  10239. var tkey = tkeys[tk];
  10240. result[tkey] = this[tkey];
  10241. }
  10242.  
  10243. // hash is always overridden, no matter what.
  10244. // even href="" will remove it.
  10245. result.hash = relative.hash;
  10246.  
  10247. // if the relative url is empty, then there's nothing left to do here.
  10248. if (relative.href === '') {
  10249. result.href = result.format();
  10250. return result;
  10251. }
  10252.  
  10253. // hrefs like //foo/bar always cut to the protocol.
  10254. if (relative.slashes && !relative.protocol) {
  10255. // take everything except the protocol from relative
  10256. var rkeys = Object.keys(relative);
  10257. for (var rk = 0; rk < rkeys.length; rk++) {
  10258. var rkey = rkeys[rk];
  10259. if (rkey !== 'protocol')
  10260. result[rkey] = relative[rkey];
  10261. }
  10262.  
  10263. //urlParse appends trailing / to urls like http://www.example.com
  10264. if (slashedProtocol[result.protocol] &&
  10265. result.hostname && !result.pathname) {
  10266. result.path = result.pathname = '/';
  10267. }
  10268.  
  10269. result.href = result.format();
  10270. return result;
  10271. }
  10272.  
  10273. if (relative.protocol && relative.protocol !== result.protocol) {
  10274. // if it's a known url protocol, then changing
  10275. // the protocol does weird things
  10276. // first, if it's not file:, then we MUST have a host,
  10277. // and if there was a path
  10278. // to begin with, then we MUST have a path.
  10279. // if it is file:, then the host is dropped,
  10280. // because that's known to be hostless.
  10281. // anything else is assumed to be absolute.
  10282. if (!slashedProtocol[relative.protocol]) {
  10283. var keys = Object.keys(relative);
  10284. for (var v = 0; v < keys.length; v++) {
  10285. var k = keys[v];
  10286. result[k] = relative[k];
  10287. }
  10288. result.href = result.format();
  10289. return result;
  10290. }
  10291.  
  10292. result.protocol = relative.protocol;
  10293. if (!relative.host && !hostlessProtocol[relative.protocol]) {
  10294. var relPath = (relative.pathname || '').split('/');
  10295. while (relPath.length && !(relative.host = relPath.shift()));
  10296. if (!relative.host) relative.host = '';
  10297. if (!relative.hostname) relative.hostname = '';
  10298. if (relPath[0] !== '') relPath.unshift('');
  10299. if (relPath.length < 2) relPath.unshift('');
  10300. result.pathname = relPath.join('/');
  10301. } else {
  10302. result.pathname = relative.pathname;
  10303. }
  10304. result.search = relative.search;
  10305. result.query = relative.query;
  10306. result.host = relative.host || '';
  10307. result.auth = relative.auth;
  10308. result.hostname = relative.hostname || relative.host;
  10309. result.port = relative.port;
  10310. // to support http.request
  10311. if (result.pathname || result.search) {
  10312. var p = result.pathname || '';
  10313. var s = result.search || '';
  10314. result.path = p + s;
  10315. }
  10316. result.slashes = result.slashes || relative.slashes;
  10317. result.href = result.format();
  10318. return result;
  10319. }
  10320.  
  10321. var isSourceAbs = (result.pathname && result.pathname.charAt(0) === '/'),
  10322. isRelAbs = (
  10323. relative.host ||
  10324. relative.pathname && relative.pathname.charAt(0) === '/'
  10325. ),
  10326. mustEndAbs = (isRelAbs || isSourceAbs ||
  10327. (result.host && relative.pathname)),
  10328. removeAllDots = mustEndAbs,
  10329. srcPath = result.pathname && result.pathname.split('/') || [],
  10330. relPath = relative.pathname && relative.pathname.split('/') || [],
  10331. psychotic = result.protocol && !slashedProtocol[result.protocol];
  10332.  
  10333. // if the url is a non-slashed url, then relative
  10334. // links like ../.. should be able
  10335. // to crawl up to the hostname, as well. This is strange.
  10336. // result.protocol has already been set by now.
  10337. // Later on, put the first path part into the host field.
  10338. if (psychotic) {
  10339. result.hostname = '';
  10340. result.port = null;
  10341. if (result.host) {
  10342. if (srcPath[0] === '') srcPath[0] = result.host;
  10343. else srcPath.unshift(result.host);
  10344. }
  10345. result.host = '';
  10346. if (relative.protocol) {
  10347. relative.hostname = null;
  10348. relative.port = null;
  10349. if (relative.host) {
  10350. if (relPath[0] === '') relPath[0] = relative.host;
  10351. else relPath.unshift(relative.host);
  10352. }
  10353. relative.host = null;
  10354. }
  10355. mustEndAbs = mustEndAbs && (relPath[0] === '' || srcPath[0] === '');
  10356. }
  10357.  
  10358. if (isRelAbs) {
  10359. // it's absolute.
  10360. result.host = (relative.host || relative.host === '') ?
  10361. relative.host : result.host;
  10362. result.hostname = (relative.hostname || relative.hostname === '') ?
  10363. relative.hostname : result.hostname;
  10364. result.search = relative.search;
  10365. result.query = relative.query;
  10366. srcPath = relPath;
  10367. // fall through to the dot-handling below.
  10368. } else if (relPath.length) {
  10369. // it's relative
  10370. // throw away the existing file, and take the new path instead.
  10371. if (!srcPath) srcPath = [];
  10372. srcPath.pop();
  10373. srcPath = srcPath.concat(relPath);
  10374. result.search = relative.search;
  10375. result.query = relative.query;
  10376. } else if (!util.isNullOrUndefined(relative.search)) {
  10377. // just pull out the search.
  10378. // like href='?foo'.
  10379. // Put this after the other two cases because it simplifies the booleans
  10380. if (psychotic) {
  10381. result.hostname = result.host = srcPath.shift();
  10382. //occationaly the auth can get stuck only in host
  10383. //this especially happens in cases like
  10384. //url.resolveObject('mailto:local1@domain1', 'local2@domain2')
  10385. var authInHost = result.host && result.host.indexOf('@') > 0 ?
  10386. result.host.split('@') : false;
  10387. if (authInHost) {
  10388. result.auth = authInHost.shift();
  10389. result.host = result.hostname = authInHost.shift();
  10390. }
  10391. }
  10392. result.search = relative.search;
  10393. result.query = relative.query;
  10394. //to support http.request
  10395. if (!util.isNull(result.pathname) || !util.isNull(result.search)) {
  10396. result.path = (result.pathname ? result.pathname : '') +
  10397. (result.search ? result.search : '');
  10398. }
  10399. result.href = result.format();
  10400. return result;
  10401. }
  10402.  
  10403. if (!srcPath.length) {
  10404. // no path at all. easy.
  10405. // we've already handled the other stuff above.
  10406. result.pathname = null;
  10407. //to support http.request
  10408. if (result.search) {
  10409. result.path = '/' + result.search;
  10410. } else {
  10411. result.path = null;
  10412. }
  10413. result.href = result.format();
  10414. return result;
  10415. }
  10416.  
  10417. // if a url ENDs in . or .., then it must get a trailing slash.
  10418. // however, if it ends in anything else non-slashy,
  10419. // then it must NOT get a trailing slash.
  10420. var last = srcPath.slice(-1)[0];
  10421. var hasTrailingSlash = (
  10422. (result.host || relative.host || srcPath.length > 1) &&
  10423. (last === '.' || last === '..') || last === '');
  10424.  
  10425. // strip single dots, resolve double dots to parent dir
  10426. // if the path tries to go above the root, `up` ends up > 0
  10427. var up = 0;
  10428. for (var i = srcPath.length; i >= 0; i--) {
  10429. last = srcPath[i];
  10430. if (last === '.') {
  10431. srcPath.splice(i, 1);
  10432. } else if (last === '..') {
  10433. srcPath.splice(i, 1);
  10434. up++;
  10435. } else if (up) {
  10436. srcPath.splice(i, 1);
  10437. up--;
  10438. }
  10439. }
  10440.  
  10441. // if the path is allowed to go above the root, restore leading ..s
  10442. if (!mustEndAbs && !removeAllDots) {
  10443. for (; up--; up) {
  10444. srcPath.unshift('..');
  10445. }
  10446. }
  10447.  
  10448. if (mustEndAbs && srcPath[0] !== '' &&
  10449. (!srcPath[0] || srcPath[0].charAt(0) !== '/')) {
  10450. srcPath.unshift('');
  10451. }
  10452.  
  10453. if (hasTrailingSlash && (srcPath.join('/').substr(-1) !== '/')) {
  10454. srcPath.push('');
  10455. }
  10456.  
  10457. var isAbsolute = srcPath[0] === '' ||
  10458. (srcPath[0] && srcPath[0].charAt(0) === '/');
  10459.  
  10460. // put the host back
  10461. if (psychotic) {
  10462. result.hostname = result.host = isAbsolute ? '' :
  10463. srcPath.length ? srcPath.shift() : '';
  10464. //occationaly the auth can get stuck only in host
  10465. //this especially happens in cases like
  10466. //url.resolveObject('mailto:local1@domain1', 'local2@domain2')
  10467. var authInHost = result.host && result.host.indexOf('@') > 0 ?
  10468. result.host.split('@') : false;
  10469. if (authInHost) {
  10470. result.auth = authInHost.shift();
  10471. result.host = result.hostname = authInHost.shift();
  10472. }
  10473. }
  10474.  
  10475. mustEndAbs = mustEndAbs || (result.host && srcPath.length);
  10476.  
  10477. if (mustEndAbs && !isAbsolute) {
  10478. srcPath.unshift('');
  10479. }
  10480.  
  10481. if (!srcPath.length) {
  10482. result.pathname = null;
  10483. result.path = null;
  10484. } else {
  10485. result.pathname = srcPath.join('/');
  10486. }
  10487.  
  10488. //to support request.http
  10489. if (!util.isNull(result.pathname) || !util.isNull(result.search)) {
  10490. result.path = (result.pathname ? result.pathname : '') +
  10491. (result.search ? result.search : '');
  10492. }
  10493. result.auth = relative.auth || result.auth;
  10494. result.slashes = result.slashes || relative.slashes;
  10495. result.href = result.format();
  10496. return result;
  10497. };
  10498.  
  10499. Url.prototype.parseHost = function() {
  10500. var host = this.host;
  10501. var port = portPattern.exec(host);
  10502. if (port) {
  10503. port = port[0];
  10504. if (port !== ':') {
  10505. this.port = port.substr(1);
  10506. }
  10507. host = host.substr(0, host.length - port.length);
  10508. }
  10509. if (host) this.hostname = host;
  10510. };
  10511.  
  10512. },{"./util":45,"punycode":40,"querystring":43}],45:[function(require,module,exports){
  10513. 'use strict';
  10514.  
  10515. module.exports = {
  10516. isString: function(arg) {
  10517. return typeof(arg) === 'string';
  10518. },
  10519. isObject: function(arg) {
  10520. return typeof(arg) === 'object' && arg !== null;
  10521. },
  10522. isNull: function(arg) {
  10523. return arg === null;
  10524. },
  10525. isNullOrUndefined: function(arg) {
  10526. return arg == null;
  10527. }
  10528. };
  10529.  
  10530. },{}]},{},[1]);
Add Comment
Please, Sign In to add comment