UNPKG

2.61 MBJavaScriptView Raw
1(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.percyClient = f()}})(function(){var define,module,exports;return (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){
2'use strict';
3
4var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
5
6function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
7
8var utils = require('./utils');
9
10var GIT_COMMIT_FORMAT = ['COMMIT_SHA:%H', 'AUTHOR_NAME:%an', 'AUTHOR_EMAIL:%ae', 'COMMITTER_NAME:%cn', 'COMMITTER_EMAIL:%ce', 'COMMITTED_DATE:%ai',
11// Note: order is important, this must come last because the regex is a multiline match.
12'COMMIT_MESSAGE:%B'].join('%n'); // git show format uses %n for newlines.
13
14var Environment = function () {
15 function Environment(env) {
16 _classCallCheck(this, Environment);
17
18 if (!env) {
19 throw new Error('"env" arg is required to create an Environment.');
20 }
21 this._env = env;
22 }
23
24 _createClass(Environment, [{
25 key: 'gitExec',
26 value: function gitExec(args) {
27 var child_process = require('child_process');
28 try {
29 var result = child_process.spawnSync('git', args);
30 if (result.status == 0) {
31 return result.stdout.toString().trim();
32 } else {
33 return '';
34 }
35 } catch (error) {
36 return '';
37 }
38 }
39 }, {
40 key: 'rawCommitData',
41 value: function rawCommitData(commitSha) {
42 // Make sure commitSha is only alphanumeric characters and ^ to prevent command injection.
43 if (commitSha.length > 100 || !commitSha.match(/^[0-9a-zA-Z^]+$/)) {
44 return '';
45 }
46
47 var args = ['show', commitSha, '--quiet', '--format="' + GIT_COMMIT_FORMAT + '"'];
48 return this.gitExec(args);
49 }
50
51 // If not running in a git repo, allow undefined for certain commit attributes.
52
53 }, {
54 key: 'parse',
55 value: function parse(formattedCommitData, regex) {
56 return (formattedCommitData && formattedCommitData.match(regex) || [])[1];
57 }
58 }, {
59 key: 'rawBranch',
60 value: function rawBranch() {
61 return this.gitExec(['rev-parse', '--abbrev-ref', 'HEAD']);
62 }
63 }, {
64 key: 'ci',
65 get: function get() {
66 if (this._env.TRAVIS_BUILD_ID) {
67 return 'travis';
68 } else if (this._env.JENKINS_URL && this._env.ghprbPullId) {
69 // Pull Request Builder plugin.
70 return 'jenkins-prb';
71 } else if (this._env.JENKINS_URL) {
72 return 'jenkins';
73 } else if (this._env.CIRCLECI) {
74 return 'circle';
75 } else if (this._env.CI_NAME && this._env.CI_NAME == 'codeship') {
76 return 'codeship';
77 } else if (this._env.DRONE == 'true') {
78 return 'drone';
79 } else if (this._env.SEMAPHORE == 'true') {
80 return 'semaphore';
81 } else if (this._env.BUILDKITE == 'true') {
82 return 'buildkite';
83 } else if (this._env.HEROKU_TEST_RUN_ID) {
84 return 'heroku';
85 } else if (this._env.GITLAB_CI == 'true') {
86 return 'gitlab';
87 } else if (this._env.TF_BUILD == 'True') {
88 return 'azure';
89 } else if (this._env.APPVEYOR == 'True' || this._env.APPVEYOR == 'true') {
90 return 'appveyor';
91 } else if (this._env.PROBO_ENVIRONMENT == 'TRUE') {
92 return 'probo';
93 } else if (this._env.BITBUCKET_BUILD_NUMBER) {
94 return 'bitbucket';
95 } else if (this._env.CI) {
96 // this should always be the last branch
97 return 'CI/unknown';
98 }
99
100 return null;
101 }
102 }, {
103 key: 'ciVersion',
104 get: function get() {
105 switch (this.ci) {
106 case 'gitlab':
107 return 'gitlab/' + this._env.CI_SERVER_VERSION;
108 }
109 return this.ci;
110 }
111 }, {
112 key: 'commitData',
113 get: function get() {
114 // Read the result from environment data
115 var result = {
116 branch: this.branch,
117 sha: this.commitSha,
118
119 // These GIT_ environment vars are from the Jenkins Git Plugin, but could be
120 // used generically. This behavior may change in the future.
121 authorName: this._env['GIT_AUTHOR_NAME'],
122 authorEmail: this._env['GIT_AUTHOR_EMAIL'],
123 committerName: this._env['GIT_COMMITTER_NAME'],
124 committerEmail: this._env['GIT_COMMITTER_EMAIL']
125 };
126
127 // Try and get more meta-data from git
128 var formattedCommitData = '';
129 if (this.commitSha) {
130 formattedCommitData = this.rawCommitData(this.commitSha);
131 }
132 if (!formattedCommitData) {
133 formattedCommitData = this.rawCommitData('HEAD');
134 }
135 if (!formattedCommitData) {
136 return result;
137 }
138
139 // If this.commitSha didn't provide a sha, use the one from the commit
140 if (!result.sha) {
141 result.sha = this.parse(formattedCommitData, /COMMIT_SHA:(.*)/);
142 }
143
144 result.message = this.parse(formattedCommitData, /COMMIT_MESSAGE:(.*)/m);
145 result.committedAt = this.parse(formattedCommitData, /COMMITTED_DATE:(.*)/);
146 result.authorName = this.parse(formattedCommitData, /AUTHOR_NAME:(.*)/);
147 result.authorEmail = this.parse(formattedCommitData, /AUTHOR_EMAIL:(.*)/);
148 result.committerName = this.parse(formattedCommitData, /COMMITTER_NAME:(.*)/);
149 result.committerEmail = this.parse(formattedCommitData, /COMMITTER_EMAIL:(.*)/);
150
151 return result;
152 }
153 }, {
154 key: 'jenkinsMergeCommitBuild',
155 get: function get() {
156 var formattedCommitData = this.rawCommitData('HEAD');
157
158 if (!formattedCommitData) {
159 return false;
160 }
161
162 var authorName = this.parse(formattedCommitData, /AUTHOR_NAME:(.*)/);
163 var authorEmail = this.parse(formattedCommitData, /AUTHOR_EMAIL:(.*)/);
164 var message = this.parse(formattedCommitData, /COMMIT_MESSAGE:(.*)/m);
165
166 if (authorName === 'Jenkins' && authorEmail === 'nobody@nowhere') {
167 // Example merge message: Merge commit 'ec4d24c3d22f3c95e34af95c1fda2d462396d885' into HEAD
168 if (message.substring(0, 13) === 'Merge commit ' && message.substring(55) === ' into HEAD') {
169 return true;
170 }
171 }
172
173 return false;
174 }
175 }, {
176 key: 'secondToLastCommitSHA',
177 get: function get() {
178 var formattedCommitData = this.rawCommitData('HEAD^');
179
180 if (!formattedCommitData) {
181 return null;
182 }
183
184 return this.parse(formattedCommitData, /COMMIT_SHA:(.*)/);
185 }
186 }, {
187 key: 'commitSha',
188 get: function get() {
189 if (this._env.PERCY_COMMIT) {
190 return this._env.PERCY_COMMIT;
191 }
192 switch (this.ci) {
193 case 'travis':
194 return this._env.TRAVIS_COMMIT;
195 case 'jenkins-prb':
196 // Pull Request Builder Plugin OR Git Plugin.
197 return this._env.ghprbActualCommit || this._env.GIT_COMMIT;
198 case 'jenkins':
199 if (this.jenkinsMergeCommitBuild) {
200 return this.secondToLastCommitSHA;
201 }
202 return this._env.GIT_COMMIT;
203 case 'circle':
204 return this._env.CIRCLE_SHA1;
205 case 'codeship':
206 return this._env.CI_COMMIT_ID;
207 case 'drone':
208 return this._env.DRONE_COMMIT;
209 case 'semaphore':
210 return this._env.REVISION;
211 case 'buildkite':
212 {
213 var commitSha = this._env.BUILDKITE_COMMIT;
214 // Buildkite mixes SHAs and non-SHAs in BUILDKITE_COMMIT, so we return null if non-SHA.
215 return commitSha !== 'HEAD' ? this._env.BUILDKITE_COMMIT : null;
216 }
217 case 'heroku':
218 return this._env.HEROKU_TEST_RUN_COMMIT_VERSION;
219 case 'gitlab':
220 return this._env.CI_COMMIT_SHA;
221 case 'azure':
222 return this._env.SYSTEM_PULLREQUEST_SOURCECOMMITID || this._env.BUILD_SOURCEVERSION;
223 case 'appveyor':
224 return this._env.APPVEYOR_PULL_REQUEST_HEAD_COMMIT || this._env.APPVEYOR_REPO_COMMIT;
225 case 'probo':
226 return this._env.COMMIT_REF;
227 case 'bitbucket':
228 return this._env.BITBUCKET_COMMIT;
229 }
230
231 return null;
232 }
233 }, {
234 key: 'targetCommitSha',
235 get: function get() {
236 return this._env.PERCY_TARGET_COMMIT || null;
237 }
238 }, {
239 key: 'partialBuild',
240 get: function get() {
241 var partial = this._env.PERCY_PARTIAL_BUILD;
242 return !!partial && partial !== '0';
243 }
244 }, {
245 key: 'branch',
246 get: function get() {
247 if (this._env.PERCY_BRANCH) {
248 return this._env.PERCY_BRANCH;
249 }
250 var result = '';
251 switch (this.ci) {
252 case 'travis':
253 if (this.pullRequestNumber && this._env.TRAVIS_PULL_REQUEST_BRANCH) {
254 result = this._env.TRAVIS_PULL_REQUEST_BRANCH;
255 } else {
256 result = this._env.TRAVIS_BRANCH;
257 }
258 break;
259 case 'jenkins-prb':
260 result = this._env.ghprbSourceBranch;
261 break;
262 case 'jenkins':
263 result = this._env.CHANGE_BRANCH || this._env.GIT_BRANCH;
264 break;
265 case 'circle':
266 result = this._env.CIRCLE_BRANCH;
267 break;
268 case 'codeship':
269 result = this._env.CI_BRANCH;
270 break;
271 case 'drone':
272 result = this._env.DRONE_BRANCH;
273 break;
274 case 'semaphore':
275 result = this._env.BRANCH_NAME;
276 break;
277 case 'buildkite':
278 result = this._env.BUILDKITE_BRANCH;
279 break;
280 case 'heroku':
281 result = this._env.HEROKU_TEST_RUN_BRANCH;
282 break;
283 case 'gitlab':
284 result = this._env.CI_COMMIT_REF_NAME;
285 break;
286 case 'azure':
287 result = this._env.SYSTEM_PULLREQUEST_SOURCEBRANCH || this._env.BUILD_SOURCEBRANCHNAME;
288 break;
289 case 'appveyor':
290 result = this._env.APPVEYOR_PULL_REQUEST_HEAD_REPO_BRANCH || this._env.APPVEYOR_REPO_BRANCH;
291 break;
292 case 'probo':
293 result = this._env.BRANCH_NAME;
294 break;
295 case 'bitbucket':
296 result = this._env.BITBUCKET_BRANCH;
297 break;
298 }
299
300 if (result == '') {
301 result = this.rawBranch();
302 }
303
304 if (result == '') {
305 // Branch not specified
306 result = null;
307 }
308
309 return result;
310 }
311 }, {
312 key: 'targetBranch',
313 get: function get() {
314 return this._env.PERCY_TARGET_BRANCH || null;
315 }
316 }, {
317 key: 'pullRequestNumber',
318 get: function get() {
319 if (this._env.PERCY_PULL_REQUEST) {
320 return this._env.PERCY_PULL_REQUEST;
321 }
322 switch (this.ci) {
323 case 'travis':
324 return this._env.TRAVIS_PULL_REQUEST !== 'false' ? this._env.TRAVIS_PULL_REQUEST : null;
325 case 'jenkins-prb':
326 return this._env.ghprbPullId;
327 case 'jenkins':
328 return this._env.CHANGE_ID || null;
329 case 'circle':
330 if (this._env.CI_PULL_REQUESTS && this._env.CI_PULL_REQUESTS !== '') {
331 return this._env.CI_PULL_REQUESTS.split('/').slice(-1)[0];
332 }
333 break;
334 case 'codeship':
335 // Unfortunately, codeship always returns 'false' for CI_PULL_REQUEST. For now, return null.
336 break;
337 case 'drone':
338 return this._env.CI_PULL_REQUEST;
339 case 'semaphore':
340 return this._env.PULL_REQUEST_NUMBER;
341 case 'buildkite':
342 return this._env.BUILDKITE_PULL_REQUEST !== 'false' ? this._env.BUILDKITE_PULL_REQUEST : null;
343 case 'gitlab':
344 return this._env.CI_MERGE_REQUEST_IID || null;
345 case 'azure':
346 return this._env.SYSTEM_PULLREQUEST_PULLREQUESTNUMBER || null;
347 case 'appveyor':
348 return this._env.APPVEYOR_PULL_REQUEST_NUMBER || null;
349 case 'probo':
350 if (this._env.PULL_REQUEST_LINK && this._env.PULL_REQUEST_LINK !== '') {
351 return this._env.PULL_REQUEST_LINK.split('/').slice(-1)[0];
352 }
353 break;
354 case 'bitbucket':
355 return this._env.BITBUCKET_PR_ID || null;
356 }
357 return null;
358 }
359
360 // A nonce which will be the same for all nodes of a parallel build, used to identify shards
361 // of the same CI build. This is usually just the CI environment build ID.
362
363 }, {
364 key: 'parallelNonce',
365 get: function get() {
366 if (this._env.PERCY_PARALLEL_NONCE) {
367 return this._env.PERCY_PARALLEL_NONCE;
368 }
369 switch (this.ci) {
370 case 'travis':
371 return this._env.TRAVIS_BUILD_NUMBER;
372 case 'jenkins-prb':
373 return this._env.BUILD_NUMBER;
374 case 'jenkins':
375 if (this._env.BUILD_TAG) {
376 return utils.reverseString(this._env.BUILD_TAG).substring(0, 60);
377 }
378 break;
379 case 'circle':
380 return this._env.CIRCLE_WORKFLOW_ID || this._env.CIRCLE_BUILD_NUM;
381 case 'codeship':
382 return this._env.CI_BUILD_NUMBER || this._env.CI_BUILD_ID;
383 case 'drone':
384 return this._env.DRONE_BUILD_NUMBER;
385 case 'semaphore':
386 return this._env.SEMAPHORE_BRANCH_ID + '/' + this._env.SEMAPHORE_BUILD_NUMBER;
387 case 'buildkite':
388 return this._env.BUILDKITE_BUILD_ID;
389 case 'heroku':
390 return this._env.HEROKU_TEST_RUN_ID;
391 case 'gitlab':
392 return this._env.CI_PIPELINE_ID;
393 case 'azure':
394 return this._env.BUILD_BUILDID;
395 case 'appveyor':
396 return this._env.APPVEYOR_BUILD_ID;
397 case 'probo':
398 return this._env.BUILD_ID;
399 case 'bitbucket':
400 return this._env.BITBUCKET_BUILD_NUMBER;
401 }
402 return null;
403 }
404 }, {
405 key: 'parallelTotalShards',
406 get: function get() {
407 if (this._env.PERCY_PARALLEL_TOTAL) {
408 return parseInt(this._env.PERCY_PARALLEL_TOTAL);
409 }
410 switch (this.ci) {
411 case 'travis':
412 // Support for https://github.com/ArturT/knapsack
413 if (this._env.CI_NODE_TOTAL) {
414 return parseInt(this._env.CI_NODE_TOTAL);
415 }
416 break;
417 case 'jenkins-prb':
418 break;
419 case 'jenkins':
420 break;
421 case 'circle':
422 if (this._env.CIRCLE_NODE_TOTAL) {
423 return parseInt(this._env.CIRCLE_NODE_TOTAL);
424 }
425 break;
426 case 'codeship':
427 if (this._env.CI_NODE_TOTAL) {
428 return parseInt(this._env.CI_NODE_TOTAL);
429 }
430 break;
431 case 'drone':
432 break;
433 case 'semaphore':
434 if (this._env.SEMAPHORE_THREAD_COUNT) {
435 return parseInt(this._env.SEMAPHORE_THREAD_COUNT);
436 }
437 break;
438 case 'buildkite':
439 if (this._env.BUILDKITE_PARALLEL_JOB_COUNT) {
440 return parseInt(this._env.BUILDKITE_PARALLEL_JOB_COUNT);
441 }
442 break;
443 case 'heroku':
444 if (this._env.CI_NODE_TOTAL) {
445 return parseInt(this._env.CI_NODE_TOTAL);
446 }
447 break;
448 case 'azure':
449 // SYSTEM_TOTALJOBSINPHASE is set for parallel builds and non-parallel matrix builds, so
450 // check build strategy is parallel by ensuring SYSTEM_PARALLELEXECUTIONTYPE == MultiMachine
451 if (this._env.SYSTEM_PARALLELEXECUTIONTYPE == 'MultiMachine' && this._env.SYSTEM_TOTALJOBSINPHASE) {
452 return parseInt(this._env.SYSTEM_TOTALJOBSINPHASE);
453 }
454 break;
455 }
456 return null;
457 }
458 }]);
459
460 return Environment;
461}();
462
463module.exports = Environment;
464},{"./utils":4,"child_process":112}],2:[function(require,module,exports){
465(function (process){
466'use strict';
467
468var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
469
470var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
471
472function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
473
474var http = require('http');
475var https = require('https');
476var utils = require('./utils');
477var Environment = require('./environment');
478var UserAgent = require('./user-agent');
479var retry = require('bluebird-retry');
480var requestPromise = require('request-promise');
481var PromisePool = require('es6-promise-pool');
482var regeneratorRuntime = require('regenerator-runtime'); // eslint-disable-line no-unused-vars
483var fs = require('fs');
484
485require('dotenv').config();
486
487var JSON_API_CONTENT_TYPE = 'application/vnd.api+json';
488var CONCURRENCY = 2;
489
490var Resource = function () {
491 function Resource(options) {
492 _classCallCheck(this, Resource);
493
494 if (!options.resourceUrl) {
495 throw new Error('"resourceUrl" arg is required to create a Resource.');
496 }
497 if (!options.sha && !options.content) {
498 throw new Error('Either "sha" or "content" is required to create a Resource.');
499 }
500 if (/\s/.test(options.resourceUrl)) {
501 throw new Error('"resourceUrl" arg includes whitespace. It needs to be encoded.');
502 }
503 this.resourceUrl = options.resourceUrl;
504 this.content = options.content;
505 this.sha = options.sha || utils.sha256hash(options.content);
506 this.mimetype = options.mimetype;
507 this.isRoot = options.isRoot;
508
509 // Temporary convenience attributes, will not be serialized. These are used, for example,
510 // to hold the local path so reading file contents can be deferred.
511 this.localPath = options.localPath;
512 }
513
514 _createClass(Resource, [{
515 key: 'serialize',
516 value: function serialize() {
517 return {
518 type: 'resources',
519 id: this.sha,
520 attributes: {
521 'resource-url': this.resourceUrl,
522 mimetype: this.mimetype || null,
523 'is-root': this.isRoot || null
524 }
525 };
526 }
527 }]);
528
529 return Resource;
530}();
531
532var PercyClient = function () {
533 function PercyClient(options) {
534 _classCallCheck(this, PercyClient);
535
536 options = options || {};
537 this.token = options.token;
538 this.apiUrl = options.apiUrl || 'https://percy.io/api/v1';
539 this.environment = options.environment || new Environment(process.env);
540 this._httpClient = requestPromise;
541 this._httpModule = this.apiUrl.indexOf('http://') === 0 ? http : https;
542 // A custom HttpAgent with pooling and keepalive.
543 this._httpAgent = new this._httpModule.Agent({
544 maxSockets: 5,
545 keepAlive: true
546 });
547 this._clientInfo = options.clientInfo;
548 this._environmentInfo = options.environmentInfo;
549 this._sdkClientInfo = null;
550 this._sdkEnvironmentInfo = null;
551 }
552
553 _createClass(PercyClient, [{
554 key: '_headers',
555 value: function _headers(headers) {
556 return _extends({
557 Authorization: 'Token token=' + this.token,
558 'User-Agent': new UserAgent(this).toString()
559 }, headers);
560 }
561 }, {
562 key: '_httpGet',
563 value: function _httpGet(uri) {
564 var requestOptions = {
565 method: 'GET',
566 uri: uri,
567 headers: this._headers(),
568 json: true,
569 resolveWithFullResponse: true,
570 agent: this._httpAgent
571 };
572
573 return retry(this._httpClient, {
574 context: this,
575 args: [uri, requestOptions],
576 interval: 50,
577 max_tries: 5,
578 throw_original: true,
579 predicate: function predicate(err) {
580 return err.statusCode >= 500 && err.statusCode < 600;
581 }
582 });
583 }
584 }, {
585 key: '_httpPost',
586 value: function _httpPost(uri, data) {
587 var requestOptions = {
588 method: 'POST',
589 uri: uri,
590 body: data,
591 headers: this._headers({ 'Content-Type': JSON_API_CONTENT_TYPE }),
592 json: true,
593 resolveWithFullResponse: true,
594 agent: this._httpAgent
595 };
596
597 return retry(this._httpClient, {
598 context: this,
599 args: [uri, requestOptions],
600 interval: 50,
601 max_tries: 5,
602 throw_original: true,
603 predicate: function predicate(err) {
604 return err.statusCode >= 500 && err.statusCode < 600;
605 }
606 });
607 }
608 }, {
609 key: 'createBuild',
610 value: function createBuild(options) {
611 var parallelNonce = this.environment.parallelNonce;
612 var parallelTotalShards = this.environment.parallelTotalShards;
613
614 // Only pass parallelism data if it all exists.
615 if (!parallelNonce || !parallelTotalShards) {
616 parallelNonce = null;
617 parallelTotalShards = null;
618 }
619
620 options = options || {};
621
622 var commitData = options['commitData'] || this.environment.commitData;
623
624 var data = {
625 data: {
626 type: 'builds',
627 attributes: {
628 branch: commitData.branch,
629 'target-branch': this.environment.targetBranch,
630 'target-commit-sha': this.environment.targetCommitSha,
631 'commit-sha': commitData.sha,
632 'commit-committed-at': commitData.committedAt,
633 'commit-author-name': commitData.authorName,
634 'commit-author-email': commitData.authorEmail,
635 'commit-committer-name': commitData.committerName,
636 'commit-committer-email': commitData.committerEmail,
637 'commit-message': commitData.message,
638 'pull-request-number': this.environment.pullRequestNumber,
639 'parallel-nonce': parallelNonce,
640 'parallel-total-shards': parallelTotalShards,
641 partial: this.environment.partialBuild
642 }
643 }
644 };
645
646 if (options.resources) {
647 data['data']['relationships'] = {
648 resources: {
649 data: options.resources.map(function (resource) {
650 return resource.serialize();
651 })
652 }
653 };
654 }
655
656 return this._httpPost(this.apiUrl + '/builds/', data);
657 }
658
659 // This method is unavailable to normal write-only project tokens.
660
661 }, {
662 key: 'getBuild',
663 value: function getBuild(buildId) {
664 return this._httpGet(this.apiUrl + '/builds/' + buildId);
665 }
666
667 // This method is unavailable to normal write-only project tokens.
668
669 }, {
670 key: 'getBuilds',
671 value: function getBuilds(project, filter) {
672 filter = filter || {};
673 var queryString = Object.keys(filter).map(function (key) {
674 if (Array.isArray(filter[key])) {
675 // If filter value is an array, match Percy API's format expectations of:
676 // filter[key][]=value1&filter[key][]=value2
677 return filter[key].map(function (array_value) {
678 return 'filter[' + key + '][]=' + array_value;
679 }).join('&');
680 } else {
681 return 'filter[' + key + ']=' + filter[key];
682 }
683 }).join('&');
684
685 if (queryString.length > 0) {
686 queryString = '?' + queryString;
687 }
688
689 return this._httpGet(this.apiUrl + '/projects/' + project + '/builds' + queryString);
690 }
691 }, {
692 key: 'makeResource',
693 value: function makeResource(options) {
694 return new Resource(options);
695 }
696
697 // Synchronously walks a directory of compiled assets and returns an array of Resource objects.
698
699 }, {
700 key: 'gatherBuildResources',
701 value: function gatherBuildResources(rootDir, options) {
702 return utils.gatherBuildResources(this, rootDir, options);
703 }
704 }, {
705 key: 'uploadResource',
706 value: function uploadResource(buildId, content) {
707 var sha = utils.sha256hash(content);
708 var data = {
709 data: {
710 type: 'resources',
711 id: sha,
712 attributes: {
713 'base64-content': utils.base64encode(content)
714 }
715 }
716 };
717
718 return this._httpPost(this.apiUrl + '/builds/' + buildId + '/resources/', data);
719 }
720 }, {
721 key: 'uploadResources',
722 value: function uploadResources(buildId, resources) {
723 var _marked = /*#__PURE__*/regeneratorRuntime.mark(generatePromises);
724
725 var _this = this;
726 function generatePromises() {
727 var _iteratorNormalCompletion, _didIteratorError, _iteratorError, _iterator, _step, resource, content;
728
729 return regeneratorRuntime.wrap(function generatePromises$(_context) {
730 while (1) {
731 switch (_context.prev = _context.next) {
732 case 0:
733 _iteratorNormalCompletion = true;
734 _didIteratorError = false;
735 _iteratorError = undefined;
736 _context.prev = 3;
737 _iterator = resources[Symbol.iterator]();
738
739 case 5:
740 if (_iteratorNormalCompletion = (_step = _iterator.next()).done) {
741 _context.next = 13;
742 break;
743 }
744
745 resource = _step.value;
746 content = resource.localPath ? fs.readFileSync(resource.localPath) : resource.content;
747 _context.next = 10;
748 return _this.uploadResource(buildId, content);
749
750 case 10:
751 _iteratorNormalCompletion = true;
752 _context.next = 5;
753 break;
754
755 case 13:
756 _context.next = 19;
757 break;
758
759 case 15:
760 _context.prev = 15;
761 _context.t0 = _context['catch'](3);
762 _didIteratorError = true;
763 _iteratorError = _context.t0;
764
765 case 19:
766 _context.prev = 19;
767 _context.prev = 20;
768
769 if (!_iteratorNormalCompletion && _iterator.return) {
770 _iterator.return();
771 }
772
773 case 22:
774 _context.prev = 22;
775
776 if (!_didIteratorError) {
777 _context.next = 25;
778 break;
779 }
780
781 throw _iteratorError;
782
783 case 25:
784 return _context.finish(22);
785
786 case 26:
787 return _context.finish(19);
788
789 case 27:
790 case 'end':
791 return _context.stop();
792 }
793 }
794 }, _marked, this, [[3, 15, 19, 27], [20,, 22, 26]]);
795 }
796
797 var pool = new PromisePool(generatePromises(), CONCURRENCY);
798 return pool.start();
799 }
800 }, {
801 key: 'uploadMissingResources',
802 value: function uploadMissingResources(buildId, response, resources) {
803 var missingResourceShas = utils.getMissingResources(response);
804 if (!missingResourceShas.length) {
805 return Promise.resolve();
806 }
807
808 var resourcesBySha = resources.reduce(function (map, resource) {
809 map[resource.sha] = resource;
810 return map;
811 }, {});
812 var missingResources = missingResourceShas.map(function (resource) {
813 return resourcesBySha[resource.id];
814 });
815
816 return this.uploadResources(buildId, missingResources);
817 }
818 }, {
819 key: 'createSnapshot',
820 value: function createSnapshot(buildId, resources, options) {
821 options = options || {};
822 resources = resources || [];
823
824 var data = {
825 data: {
826 type: 'snapshots',
827 attributes: {
828 name: options.name || null,
829 'enable-javascript': options.enableJavaScript || null,
830 widths: options.widths || null,
831 'minimum-height': options.minimumHeight || null
832 },
833 relationships: {
834 resources: {
835 data: resources.map(function (resource) {
836 return resource.serialize();
837 })
838 }
839 }
840 }
841 };
842
843 this._sdkClientInfo = options.clientInfo;
844 this._sdkEnvironmentInfo = options.environmentInfo;
845 return this._httpPost(this.apiUrl + '/builds/' + buildId + '/snapshots/', data);
846 }
847 }, {
848 key: 'finalizeSnapshot',
849 value: function finalizeSnapshot(snapshotId) {
850 return this._httpPost(this.apiUrl + '/snapshots/' + snapshotId + '/finalize', {});
851 }
852 }, {
853 key: 'finalizeBuild',
854 value: function finalizeBuild(buildId, options) {
855 options = options || {};
856 var allShards = options.allShards || false;
857 var query = allShards ? '?all-shards=true' : '';
858 return this._httpPost(this.apiUrl + '/builds/' + buildId + '/finalize' + query, {});
859 }
860 }]);
861
862 return PercyClient;
863}();
864
865module.exports = PercyClient;
866}).call(this,require('_process'))
867},{"./environment":1,"./user-agent":3,"./utils":4,"_process":265,"bluebird-retry":77,"dotenv":138,"es6-promise-pool":158,"fs":112,"http":362,"https":208,"regenerator-runtime":294,"request-promise":298}],3:[function(require,module,exports){
868(function (process){
869'use strict';
870
871var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
872
873var _package = require('../package.json');
874
875function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
876
877var UserAgent = function () {
878 function UserAgent(client) {
879 _classCallCheck(this, UserAgent);
880
881 if (!client) {
882 throw new Error('"client" arg is required to create a UserAgent.');
883 }
884 this._client = client;
885 }
886
887 _createClass(UserAgent, [{
888 key: 'toString',
889 value: function toString() {
890 var client = ['Percy/' + this._apiVersion(), this._client._sdkClientInfo, this._client._clientInfo, 'percy-js/' + _package.version].filter(function (el) {
891 return el != null;
892 }).join(' ');
893
894 var environment = [this._client._sdkEnvironmentInfo, this._client._environmentInfo, 'node/' + this._nodeVersion(), this._client.environment.ciVersion].filter(function (el) {
895 return el != null;
896 }).join('; ');
897
898 return client + ' (' + environment + ')';
899 }
900 }, {
901 key: '_nodeVersion',
902 value: function _nodeVersion() {
903 return process.version;
904 }
905 }, {
906 key: '_apiVersion',
907 value: function _apiVersion() {
908 return (/\w+$/.exec(this._client.apiUrl)
909 );
910 }
911 }]);
912
913 return UserAgent;
914}();
915
916module.exports = UserAgent;
917}).call(this,require('_process'))
918},{"../package.json":407,"_process":265}],4:[function(require,module,exports){
919(function (Buffer){
920'use strict';
921
922var base64 = require('base64-js');
923var crypto = require('crypto');
924var fs = require('fs');
925var path = require('path');
926var walk = require('walk');
927
928var MAX_FILE_SIZE_BYTES = 15728640; // 15MB.
929
930module.exports = {
931 sha256hash: function sha256hash(content) {
932 return crypto.createHash('sha256').update(content, 'utf8').digest('hex');
933 },
934 base64encode: function base64encode(content) {
935 return base64.fromByteArray(new Buffer(content));
936 },
937 getMissingResources: function getMissingResources(response) {
938 return response && response.body && response.body.data && response.body.data.relationships && response.body.data.relationships['missing-resources'] && response.body.data.relationships['missing-resources'].data || [];
939 },
940
941
942 // Synchronously walk a directory of compiled assets, read each file and calculate its SHA 256
943 // hash, and create an array of Resource objects.
944 gatherBuildResources: function gatherBuildResources(percyClient, rootDir) {
945 var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
946
947 // The base of the URL that will be prepended to every resource URL, such as "/assets".
948 options.baseUrlPath = options.baseUrlPath || '';
949 options.skippedPathRegexes = options.skippedPathRegexes || [];
950 options.followLinks = options.followLinks || true;
951
952 var resources = [];
953
954 var fileWalker = function fileWalker(root, fileStats, next) {
955 var absolutePath = path.join(root, fileStats.name);
956 var resourceUrl = absolutePath.replace(rootDir, '');
957
958 if (path.sep == '\\') {
959 // Windows support: transform filesystem backslashes into forward-slashes for the URL.
960 resourceUrl = resourceUrl.replace(/\\/g, '/');
961 }
962
963 // Prepend the baseUrlPath if it is given. We normalize it to make sure it does not have
964 // a trailing slash, or it's a blank string.
965 var normalizedBaseUrlPath = (options.baseUrlPath || '/').replace(/\/$/, '');
966 resourceUrl = normalizedBaseUrlPath + resourceUrl;
967
968 // Skip excluded paths.
969 for (var i in options.skippedPathRegexes) {
970 if (resourceUrl.match(options.skippedPathRegexes[i])) {
971 next();
972 return;
973 }
974 }
975
976 // Skip large files.
977 if (fs.statSync(absolutePath)['size'] > MAX_FILE_SIZE_BYTES) {
978 // eslint-disable-next-line no-console
979 console.warn('\n[percy][WARNING] Skipping large build resource: ', resourceUrl);
980 return;
981 }
982
983 // Note: this is synchronous and potentially memory intensive, but we don't keep a
984 // reference to the content around so each should be garbage collected. Reevaluate?
985 var content = fs.readFileSync(absolutePath);
986 var sha = crypto.createHash('sha256').update(content).digest('hex');
987
988 var resource = percyClient.makeResource({
989 resourceUrl: encodeURI(resourceUrl),
990 sha: sha,
991 localPath: absolutePath
992 });
993
994 resources.push(resource);
995 next();
996 };
997
998 var walkOptions = {
999 // Follow symlinks because assets may be just symlinks.
1000 followLinks: options.followLinks,
1001 listeners: {
1002 file: fileWalker
1003 }
1004 };
1005 walk.walkSync(rootDir, walkOptions);
1006
1007 return resources;
1008 },
1009 reverseString: function reverseString(str) {
1010 return str.split('').reverse().join('');
1011 }
1012};
1013}).call(this,require("buffer").Buffer)
1014},{"base64-js":75,"buffer":114,"crypto":126,"fs":112,"path":257,"walk":405}],5:[function(require,module,exports){
1015'use strict';
1016
1017var compileSchema = require('./compile')
1018 , resolve = require('./compile/resolve')
1019 , Cache = require('./cache')
1020 , SchemaObject = require('./compile/schema_obj')
1021 , stableStringify = require('fast-json-stable-stringify')
1022 , formats = require('./compile/formats')
1023 , rules = require('./compile/rules')
1024 , $dataMetaSchema = require('./data')
1025 , util = require('./compile/util');
1026
1027module.exports = Ajv;
1028
1029Ajv.prototype.validate = validate;
1030Ajv.prototype.compile = compile;
1031Ajv.prototype.addSchema = addSchema;
1032Ajv.prototype.addMetaSchema = addMetaSchema;
1033Ajv.prototype.validateSchema = validateSchema;
1034Ajv.prototype.getSchema = getSchema;
1035Ajv.prototype.removeSchema = removeSchema;
1036Ajv.prototype.addFormat = addFormat;
1037Ajv.prototype.errorsText = errorsText;
1038
1039Ajv.prototype._addSchema = _addSchema;
1040Ajv.prototype._compile = _compile;
1041
1042Ajv.prototype.compileAsync = require('./compile/async');
1043var customKeyword = require('./keyword');
1044Ajv.prototype.addKeyword = customKeyword.add;
1045Ajv.prototype.getKeyword = customKeyword.get;
1046Ajv.prototype.removeKeyword = customKeyword.remove;
1047Ajv.prototype.validateKeyword = customKeyword.validate;
1048
1049var errorClasses = require('./compile/error_classes');
1050Ajv.ValidationError = errorClasses.Validation;
1051Ajv.MissingRefError = errorClasses.MissingRef;
1052Ajv.$dataMetaSchema = $dataMetaSchema;
1053
1054var META_SCHEMA_ID = 'http://json-schema.org/draft-07/schema';
1055
1056var META_IGNORE_OPTIONS = [ 'removeAdditional', 'useDefaults', 'coerceTypes', 'strictDefaults' ];
1057var META_SUPPORT_DATA = ['/properties'];
1058
1059/**
1060 * Creates validator instance.
1061 * Usage: `Ajv(opts)`
1062 * @param {Object} opts optional options
1063 * @return {Object} ajv instance
1064 */
1065function Ajv(opts) {
1066 if (!(this instanceof Ajv)) return new Ajv(opts);
1067 opts = this._opts = util.copy(opts) || {};
1068 setLogger(this);
1069 this._schemas = {};
1070 this._refs = {};
1071 this._fragments = {};
1072 this._formats = formats(opts.format);
1073
1074 this._cache = opts.cache || new Cache;
1075 this._loadingSchemas = {};
1076 this._compilations = [];
1077 this.RULES = rules();
1078 this._getId = chooseGetId(opts);
1079
1080 opts.loopRequired = opts.loopRequired || Infinity;
1081 if (opts.errorDataPath == 'property') opts._errorDataPathProperty = true;
1082 if (opts.serialize === undefined) opts.serialize = stableStringify;
1083 this._metaOpts = getMetaSchemaOptions(this);
1084
1085 if (opts.formats) addInitialFormats(this);
1086 addDefaultMetaSchema(this);
1087 if (typeof opts.meta == 'object') this.addMetaSchema(opts.meta);
1088 if (opts.nullable) this.addKeyword('nullable', {metaSchema: {type: 'boolean'}});
1089 addInitialSchemas(this);
1090}
1091
1092
1093
1094/**
1095 * Validate data using schema
1096 * Schema will be compiled and cached (using serialized JSON as key. [fast-json-stable-stringify](https://github.com/epoberezkin/fast-json-stable-stringify) is used to serialize.
1097 * @this Ajv
1098 * @param {String|Object} schemaKeyRef key, ref or schema object
1099 * @param {Any} data to be validated
1100 * @return {Boolean} validation result. Errors from the last validation will be available in `ajv.errors` (and also in compiled schema: `schema.errors`).
1101 */
1102function validate(schemaKeyRef, data) {
1103 var v;
1104 if (typeof schemaKeyRef == 'string') {
1105 v = this.getSchema(schemaKeyRef);
1106 if (!v) throw new Error('no schema with key or ref "' + schemaKeyRef + '"');
1107 } else {
1108 var schemaObj = this._addSchema(schemaKeyRef);
1109 v = schemaObj.validate || this._compile(schemaObj);
1110 }
1111
1112 var valid = v(data);
1113 if (v.$async !== true) this.errors = v.errors;
1114 return valid;
1115}
1116
1117
1118/**
1119 * Create validating function for passed schema.
1120 * @this Ajv
1121 * @param {Object} schema schema object
1122 * @param {Boolean} _meta true if schema is a meta-schema. Used internally to compile meta schemas of custom keywords.
1123 * @return {Function} validating function
1124 */
1125function compile(schema, _meta) {
1126 var schemaObj = this._addSchema(schema, undefined, _meta);
1127 return schemaObj.validate || this._compile(schemaObj);
1128}
1129
1130
1131/**
1132 * Adds schema to the instance.
1133 * @this Ajv
1134 * @param {Object|Array} schema schema or array of schemas. If array is passed, `key` and other parameters will be ignored.
1135 * @param {String} key Optional schema key. Can be passed to `validate` method instead of schema object or id/ref. One schema per instance can have empty `id` and `key`.
1136 * @param {Boolean} _skipValidation true to skip schema validation. Used internally, option validateSchema should be used instead.
1137 * @param {Boolean} _meta true if schema is a meta-schema. Used internally, addMetaSchema should be used instead.
1138 * @return {Ajv} this for method chaining
1139 */
1140function addSchema(schema, key, _skipValidation, _meta) {
1141 if (Array.isArray(schema)){
1142 for (var i=0; i<schema.length; i++) this.addSchema(schema[i], undefined, _skipValidation, _meta);
1143 return this;
1144 }
1145 var id = this._getId(schema);
1146 if (id !== undefined && typeof id != 'string')
1147 throw new Error('schema id must be string');
1148 key = resolve.normalizeId(key || id);
1149 checkUnique(this, key);
1150 this._schemas[key] = this._addSchema(schema, _skipValidation, _meta, true);
1151 return this;
1152}
1153
1154
1155/**
1156 * Add schema that will be used to validate other schemas
1157 * options in META_IGNORE_OPTIONS are alway set to false
1158 * @this Ajv
1159 * @param {Object} schema schema object
1160 * @param {String} key optional schema key
1161 * @param {Boolean} skipValidation true to skip schema validation, can be used to override validateSchema option for meta-schema
1162 * @return {Ajv} this for method chaining
1163 */
1164function addMetaSchema(schema, key, skipValidation) {
1165 this.addSchema(schema, key, skipValidation, true);
1166 return this;
1167}
1168
1169
1170/**
1171 * Validate schema
1172 * @this Ajv
1173 * @param {Object} schema schema to validate
1174 * @param {Boolean} throwOrLogError pass true to throw (or log) an error if invalid
1175 * @return {Boolean} true if schema is valid
1176 */
1177function validateSchema(schema, throwOrLogError) {
1178 var $schema = schema.$schema;
1179 if ($schema !== undefined && typeof $schema != 'string')
1180 throw new Error('$schema must be a string');
1181 $schema = $schema || this._opts.defaultMeta || defaultMeta(this);
1182 if (!$schema) {
1183 this.logger.warn('meta-schema not available');
1184 this.errors = null;
1185 return true;
1186 }
1187 var valid = this.validate($schema, schema);
1188 if (!valid && throwOrLogError) {
1189 var message = 'schema is invalid: ' + this.errorsText();
1190 if (this._opts.validateSchema == 'log') this.logger.error(message);
1191 else throw new Error(message);
1192 }
1193 return valid;
1194}
1195
1196
1197function defaultMeta(self) {
1198 var meta = self._opts.meta;
1199 self._opts.defaultMeta = typeof meta == 'object'
1200 ? self._getId(meta) || meta
1201 : self.getSchema(META_SCHEMA_ID)
1202 ? META_SCHEMA_ID
1203 : undefined;
1204 return self._opts.defaultMeta;
1205}
1206
1207
1208/**
1209 * Get compiled schema from the instance by `key` or `ref`.
1210 * @this Ajv
1211 * @param {String} keyRef `key` that was passed to `addSchema` or full schema reference (`schema.id` or resolved id).
1212 * @return {Function} schema validating function (with property `schema`).
1213 */
1214function getSchema(keyRef) {
1215 var schemaObj = _getSchemaObj(this, keyRef);
1216 switch (typeof schemaObj) {
1217 case 'object': return schemaObj.validate || this._compile(schemaObj);
1218 case 'string': return this.getSchema(schemaObj);
1219 case 'undefined': return _getSchemaFragment(this, keyRef);
1220 }
1221}
1222
1223
1224function _getSchemaFragment(self, ref) {
1225 var res = resolve.schema.call(self, { schema: {} }, ref);
1226 if (res) {
1227 var schema = res.schema
1228 , root = res.root
1229 , baseId = res.baseId;
1230 var v = compileSchema.call(self, schema, root, undefined, baseId);
1231 self._fragments[ref] = new SchemaObject({
1232 ref: ref,
1233 fragment: true,
1234 schema: schema,
1235 root: root,
1236 baseId: baseId,
1237 validate: v
1238 });
1239 return v;
1240 }
1241}
1242
1243
1244function _getSchemaObj(self, keyRef) {
1245 keyRef = resolve.normalizeId(keyRef);
1246 return self._schemas[keyRef] || self._refs[keyRef] || self._fragments[keyRef];
1247}
1248
1249
1250/**
1251 * Remove cached schema(s).
1252 * If no parameter is passed all schemas but meta-schemas are removed.
1253 * If RegExp is passed all schemas with key/id matching pattern but meta-schemas are removed.
1254 * Even if schema is referenced by other schemas it still can be removed as other schemas have local references.
1255 * @this Ajv
1256 * @param {String|Object|RegExp} schemaKeyRef key, ref, pattern to match key/ref or schema object
1257 * @return {Ajv} this for method chaining
1258 */
1259function removeSchema(schemaKeyRef) {
1260 if (schemaKeyRef instanceof RegExp) {
1261 _removeAllSchemas(this, this._schemas, schemaKeyRef);
1262 _removeAllSchemas(this, this._refs, schemaKeyRef);
1263 return this;
1264 }
1265 switch (typeof schemaKeyRef) {
1266 case 'undefined':
1267 _removeAllSchemas(this, this._schemas);
1268 _removeAllSchemas(this, this._refs);
1269 this._cache.clear();
1270 return this;
1271 case 'string':
1272 var schemaObj = _getSchemaObj(this, schemaKeyRef);
1273 if (schemaObj) this._cache.del(schemaObj.cacheKey);
1274 delete this._schemas[schemaKeyRef];
1275 delete this._refs[schemaKeyRef];
1276 return this;
1277 case 'object':
1278 var serialize = this._opts.serialize;
1279 var cacheKey = serialize ? serialize(schemaKeyRef) : schemaKeyRef;
1280 this._cache.del(cacheKey);
1281 var id = this._getId(schemaKeyRef);
1282 if (id) {
1283 id = resolve.normalizeId(id);
1284 delete this._schemas[id];
1285 delete this._refs[id];
1286 }
1287 }
1288 return this;
1289}
1290
1291
1292function _removeAllSchemas(self, schemas, regex) {
1293 for (var keyRef in schemas) {
1294 var schemaObj = schemas[keyRef];
1295 if (!schemaObj.meta && (!regex || regex.test(keyRef))) {
1296 self._cache.del(schemaObj.cacheKey);
1297 delete schemas[keyRef];
1298 }
1299 }
1300}
1301
1302
1303/* @this Ajv */
1304function _addSchema(schema, skipValidation, meta, shouldAddSchema) {
1305 if (typeof schema != 'object' && typeof schema != 'boolean')
1306 throw new Error('schema should be object or boolean');
1307 var serialize = this._opts.serialize;
1308 var cacheKey = serialize ? serialize(schema) : schema;
1309 var cached = this._cache.get(cacheKey);
1310 if (cached) return cached;
1311
1312 shouldAddSchema = shouldAddSchema || this._opts.addUsedSchema !== false;
1313
1314 var id = resolve.normalizeId(this._getId(schema));
1315 if (id && shouldAddSchema) checkUnique(this, id);
1316
1317 var willValidate = this._opts.validateSchema !== false && !skipValidation;
1318 var recursiveMeta;
1319 if (willValidate && !(recursiveMeta = id && id == resolve.normalizeId(schema.$schema)))
1320 this.validateSchema(schema, true);
1321
1322 var localRefs = resolve.ids.call(this, schema);
1323
1324 var schemaObj = new SchemaObject({
1325 id: id,
1326 schema: schema,
1327 localRefs: localRefs,
1328 cacheKey: cacheKey,
1329 meta: meta
1330 });
1331
1332 if (id[0] != '#' && shouldAddSchema) this._refs[id] = schemaObj;
1333 this._cache.put(cacheKey, schemaObj);
1334
1335 if (willValidate && recursiveMeta) this.validateSchema(schema, true);
1336
1337 return schemaObj;
1338}
1339
1340
1341/* @this Ajv */
1342function _compile(schemaObj, root) {
1343 if (schemaObj.compiling) {
1344 schemaObj.validate = callValidate;
1345 callValidate.schema = schemaObj.schema;
1346 callValidate.errors = null;
1347 callValidate.root = root ? root : callValidate;
1348 if (schemaObj.schema.$async === true)
1349 callValidate.$async = true;
1350 return callValidate;
1351 }
1352 schemaObj.compiling = true;
1353
1354 var currentOpts;
1355 if (schemaObj.meta) {
1356 currentOpts = this._opts;
1357 this._opts = this._metaOpts;
1358 }
1359
1360 var v;
1361 try { v = compileSchema.call(this, schemaObj.schema, root, schemaObj.localRefs); }
1362 catch(e) {
1363 delete schemaObj.validate;
1364 throw e;
1365 }
1366 finally {
1367 schemaObj.compiling = false;
1368 if (schemaObj.meta) this._opts = currentOpts;
1369 }
1370
1371 schemaObj.validate = v;
1372 schemaObj.refs = v.refs;
1373 schemaObj.refVal = v.refVal;
1374 schemaObj.root = v.root;
1375 return v;
1376
1377
1378 /* @this {*} - custom context, see passContext option */
1379 function callValidate() {
1380 /* jshint validthis: true */
1381 var _validate = schemaObj.validate;
1382 var result = _validate.apply(this, arguments);
1383 callValidate.errors = _validate.errors;
1384 return result;
1385 }
1386}
1387
1388
1389function chooseGetId(opts) {
1390 switch (opts.schemaId) {
1391 case 'auto': return _get$IdOrId;
1392 case 'id': return _getId;
1393 default: return _get$Id;
1394 }
1395}
1396
1397/* @this Ajv */
1398function _getId(schema) {
1399 if (schema.$id) this.logger.warn('schema $id ignored', schema.$id);
1400 return schema.id;
1401}
1402
1403/* @this Ajv */
1404function _get$Id(schema) {
1405 if (schema.id) this.logger.warn('schema id ignored', schema.id);
1406 return schema.$id;
1407}
1408
1409
1410function _get$IdOrId(schema) {
1411 if (schema.$id && schema.id && schema.$id != schema.id)
1412 throw new Error('schema $id is different from id');
1413 return schema.$id || schema.id;
1414}
1415
1416
1417/**
1418 * Convert array of error message objects to string
1419 * @this Ajv
1420 * @param {Array<Object>} errors optional array of validation errors, if not passed errors from the instance are used.
1421 * @param {Object} options optional options with properties `separator` and `dataVar`.
1422 * @return {String} human readable string with all errors descriptions
1423 */
1424function errorsText(errors, options) {
1425 errors = errors || this.errors;
1426 if (!errors) return 'No errors';
1427 options = options || {};
1428 var separator = options.separator === undefined ? ', ' : options.separator;
1429 var dataVar = options.dataVar === undefined ? 'data' : options.dataVar;
1430
1431 var text = '';
1432 for (var i=0; i<errors.length; i++) {
1433 var e = errors[i];
1434 if (e) text += dataVar + e.dataPath + ' ' + e.message + separator;
1435 }
1436 return text.slice(0, -separator.length);
1437}
1438
1439
1440/**
1441 * Add custom format
1442 * @this Ajv
1443 * @param {String} name format name
1444 * @param {String|RegExp|Function} format string is converted to RegExp; function should return boolean (true when valid)
1445 * @return {Ajv} this for method chaining
1446 */
1447function addFormat(name, format) {
1448 if (typeof format == 'string') format = new RegExp(format);
1449 this._formats[name] = format;
1450 return this;
1451}
1452
1453
1454function addDefaultMetaSchema(self) {
1455 var $dataSchema;
1456 if (self._opts.$data) {
1457 $dataSchema = require('./refs/data.json');
1458 self.addMetaSchema($dataSchema, $dataSchema.$id, true);
1459 }
1460 if (self._opts.meta === false) return;
1461 var metaSchema = require('./refs/json-schema-draft-07.json');
1462 if (self._opts.$data) metaSchema = $dataMetaSchema(metaSchema, META_SUPPORT_DATA);
1463 self.addMetaSchema(metaSchema, META_SCHEMA_ID, true);
1464 self._refs['http://json-schema.org/schema'] = META_SCHEMA_ID;
1465}
1466
1467
1468function addInitialSchemas(self) {
1469 var optsSchemas = self._opts.schemas;
1470 if (!optsSchemas) return;
1471 if (Array.isArray(optsSchemas)) self.addSchema(optsSchemas);
1472 else for (var key in optsSchemas) self.addSchema(optsSchemas[key], key);
1473}
1474
1475
1476function addInitialFormats(self) {
1477 for (var name in self._opts.formats) {
1478 var format = self._opts.formats[name];
1479 self.addFormat(name, format);
1480 }
1481}
1482
1483
1484function checkUnique(self, id) {
1485 if (self._schemas[id] || self._refs[id])
1486 throw new Error('schema with key or id "' + id + '" already exists');
1487}
1488
1489
1490function getMetaSchemaOptions(self) {
1491 var metaOpts = util.copy(self._opts);
1492 for (var i=0; i<META_IGNORE_OPTIONS.length; i++)
1493 delete metaOpts[META_IGNORE_OPTIONS[i]];
1494 return metaOpts;
1495}
1496
1497
1498function setLogger(self) {
1499 var logger = self._opts.logger;
1500 if (logger === false) {
1501 self.logger = {log: noop, warn: noop, error: noop};
1502 } else {
1503 if (logger === undefined) logger = console;
1504 if (!(typeof logger == 'object' && logger.log && logger.warn && logger.error))
1505 throw new Error('logger must implement log, warn and error methods');
1506 self.logger = logger;
1507 }
1508}
1509
1510
1511function noop() {}
1512
1513},{"./cache":6,"./compile":10,"./compile/async":7,"./compile/error_classes":8,"./compile/formats":9,"./compile/resolve":11,"./compile/rules":12,"./compile/schema_obj":13,"./compile/util":15,"./data":16,"./keyword":43,"./refs/data.json":44,"./refs/json-schema-draft-07.json":46,"fast-json-stable-stringify":164}],6:[function(require,module,exports){
1514'use strict';
1515
1516
1517var Cache = module.exports = function Cache() {
1518 this._cache = {};
1519};
1520
1521
1522Cache.prototype.put = function Cache_put(key, value) {
1523 this._cache[key] = value;
1524};
1525
1526
1527Cache.prototype.get = function Cache_get(key) {
1528 return this._cache[key];
1529};
1530
1531
1532Cache.prototype.del = function Cache_del(key) {
1533 delete this._cache[key];
1534};
1535
1536
1537Cache.prototype.clear = function Cache_clear() {
1538 this._cache = {};
1539};
1540
1541},{}],7:[function(require,module,exports){
1542'use strict';
1543
1544var MissingRefError = require('./error_classes').MissingRef;
1545
1546module.exports = compileAsync;
1547
1548
1549/**
1550 * Creates validating function for passed schema with asynchronous loading of missing schemas.
1551 * `loadSchema` option should be a function that accepts schema uri and returns promise that resolves with the schema.
1552 * @this Ajv
1553 * @param {Object} schema schema object
1554 * @param {Boolean} meta optional true to compile meta-schema; this parameter can be skipped
1555 * @param {Function} callback an optional node-style callback, it is called with 2 parameters: error (or null) and validating function.
1556 * @return {Promise} promise that resolves with a validating function.
1557 */
1558function compileAsync(schema, meta, callback) {
1559 /* eslint no-shadow: 0 */
1560 /* global Promise */
1561 /* jshint validthis: true */
1562 var self = this;
1563 if (typeof this._opts.loadSchema != 'function')
1564 throw new Error('options.loadSchema should be a function');
1565
1566 if (typeof meta == 'function') {
1567 callback = meta;
1568 meta = undefined;
1569 }
1570
1571 var p = loadMetaSchemaOf(schema).then(function () {
1572 var schemaObj = self._addSchema(schema, undefined, meta);
1573 return schemaObj.validate || _compileAsync(schemaObj);
1574 });
1575
1576 if (callback) {
1577 p.then(
1578 function(v) { callback(null, v); },
1579 callback
1580 );
1581 }
1582
1583 return p;
1584
1585
1586 function loadMetaSchemaOf(sch) {
1587 var $schema = sch.$schema;
1588 return $schema && !self.getSchema($schema)
1589 ? compileAsync.call(self, { $ref: $schema }, true)
1590 : Promise.resolve();
1591 }
1592
1593
1594 function _compileAsync(schemaObj) {
1595 try { return self._compile(schemaObj); }
1596 catch(e) {
1597 if (e instanceof MissingRefError) return loadMissingSchema(e);
1598 throw e;
1599 }
1600
1601
1602 function loadMissingSchema(e) {
1603 var ref = e.missingSchema;
1604 if (added(ref)) throw new Error('Schema ' + ref + ' is loaded but ' + e.missingRef + ' cannot be resolved');
1605
1606 var schemaPromise = self._loadingSchemas[ref];
1607 if (!schemaPromise) {
1608 schemaPromise = self._loadingSchemas[ref] = self._opts.loadSchema(ref);
1609 schemaPromise.then(removePromise, removePromise);
1610 }
1611
1612 return schemaPromise.then(function (sch) {
1613 if (!added(ref)) {
1614 return loadMetaSchemaOf(sch).then(function () {
1615 if (!added(ref)) self.addSchema(sch, ref, undefined, meta);
1616 });
1617 }
1618 }).then(function() {
1619 return _compileAsync(schemaObj);
1620 });
1621
1622 function removePromise() {
1623 delete self._loadingSchemas[ref];
1624 }
1625
1626 function added(ref) {
1627 return self._refs[ref] || self._schemas[ref];
1628 }
1629 }
1630 }
1631}
1632
1633},{"./error_classes":8}],8:[function(require,module,exports){
1634'use strict';
1635
1636var resolve = require('./resolve');
1637
1638module.exports = {
1639 Validation: errorSubclass(ValidationError),
1640 MissingRef: errorSubclass(MissingRefError)
1641};
1642
1643
1644function ValidationError(errors) {
1645 this.message = 'validation failed';
1646 this.errors = errors;
1647 this.ajv = this.validation = true;
1648}
1649
1650
1651MissingRefError.message = function (baseId, ref) {
1652 return 'can\'t resolve reference ' + ref + ' from id ' + baseId;
1653};
1654
1655
1656function MissingRefError(baseId, ref, message) {
1657 this.message = message || MissingRefError.message(baseId, ref);
1658 this.missingRef = resolve.url(baseId, ref);
1659 this.missingSchema = resolve.normalizeId(resolve.fullPath(this.missingRef));
1660}
1661
1662
1663function errorSubclass(Subclass) {
1664 Subclass.prototype = Object.create(Error.prototype);
1665 Subclass.prototype.constructor = Subclass;
1666 return Subclass;
1667}
1668
1669},{"./resolve":11}],9:[function(require,module,exports){
1670'use strict';
1671
1672var util = require('./util');
1673
1674var DATE = /^(\d\d\d\d)-(\d\d)-(\d\d)$/;
1675var DAYS = [0,31,28,31,30,31,30,31,31,30,31,30,31];
1676var TIME = /^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d:\d\d)?$/i;
1677var HOSTNAME = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*$/i;
1678var URI = /^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;
1679var URIREF = /^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;
1680// uri-template: https://tools.ietf.org/html/rfc6570
1681var URITEMPLATE = /^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i;
1682// For the source: https://gist.github.com/dperini/729294
1683// For test cases: https://mathiasbynens.be/demo/url-regex
1684// @todo Delete current URL in favour of the commented out URL rule when this issue is fixed https://github.com/eslint/eslint/issues/7983.
1685// var URL = /^(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)(?:\.(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu;
1686var URL = /^(?:(?:http[s\u017F]?|ftp):\/\/)(?:(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+(?::(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*)?@)?(?:(?!10(?:\.[0-9]{1,3}){3})(?!127(?:\.[0-9]{1,3}){3})(?!169\.254(?:\.[0-9]{1,3}){2})(?!192\.168(?:\.[0-9]{1,3}){2})(?!172\.(?:1[6-9]|2[0-9]|3[01])(?:\.[0-9]{1,3}){2})(?:[1-9][0-9]?|1[0-9][0-9]|2[01][0-9]|22[0-3])(?:\.(?:1?[0-9]{1,2}|2[0-4][0-9]|25[0-5])){2}(?:\.(?:[1-9][0-9]?|1[0-9][0-9]|2[0-4][0-9]|25[0-4]))|(?:(?:(?:[0-9KSa-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+-?)*(?:[0-9KSa-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+)(?:\.(?:(?:[0-9KSa-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+-?)*(?:[0-9KSa-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+)*(?:\.(?:(?:[KSa-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]){2,})))(?::[0-9]{2,5})?(?:\/(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*)?$/i;
1687var UUID = /^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i;
1688var JSON_POINTER = /^(?:\/(?:[^~/]|~0|~1)*)*$/;
1689var JSON_POINTER_URI_FRAGMENT = /^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i;
1690var RELATIVE_JSON_POINTER = /^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/;
1691
1692
1693module.exports = formats;
1694
1695function formats(mode) {
1696 mode = mode == 'full' ? 'full' : 'fast';
1697 return util.copy(formats[mode]);
1698}
1699
1700
1701formats.fast = {
1702 // date: http://tools.ietf.org/html/rfc3339#section-5.6
1703 date: /^\d\d\d\d-[0-1]\d-[0-3]\d$/,
1704 // date-time: http://tools.ietf.org/html/rfc3339#section-5.6
1705 time: /^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d:\d\d)?$/i,
1706 'date-time': /^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d:\d\d)$/i,
1707 // uri: https://github.com/mafintosh/is-my-json-valid/blob/master/formats.js
1708 uri: /^(?:[a-z][a-z0-9+-.]*:)(?:\/?\/)?[^\s]*$/i,
1709 'uri-reference': /^(?:(?:[a-z][a-z0-9+-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,
1710 'uri-template': URITEMPLATE,
1711 url: URL,
1712 // email (sources from jsen validator):
1713 // http://stackoverflow.com/questions/201323/using-a-regular-expression-to-validate-an-email-address#answer-8829363
1714 // http://www.w3.org/TR/html5/forms.html#valid-e-mail-address (search for 'willful violation')
1715 email: /^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i,
1716 hostname: HOSTNAME,
1717 // optimized https://www.safaribooksonline.com/library/view/regular-expressions-cookbook/9780596802837/ch07s16.html
1718 ipv4: /^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,
1719 // optimized http://stackoverflow.com/questions/53497/regular-expression-that-matches-valid-ipv6-addresses
1720 ipv6: /^\s*(?:(?:(?:[0-9a-f]{1,4}:){7}(?:[0-9a-f]{1,4}|:))|(?:(?:[0-9a-f]{1,4}:){6}(?::[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){5}(?:(?:(?::[0-9a-f]{1,4}){1,2})|:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){4}(?:(?:(?::[0-9a-f]{1,4}){1,3})|(?:(?::[0-9a-f]{1,4})?:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){3}(?:(?:(?::[0-9a-f]{1,4}){1,4})|(?:(?::[0-9a-f]{1,4}){0,2}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){2}(?:(?:(?::[0-9a-f]{1,4}){1,5})|(?:(?::[0-9a-f]{1,4}){0,3}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){1}(?:(?:(?::[0-9a-f]{1,4}){1,6})|(?:(?::[0-9a-f]{1,4}){0,4}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?::(?:(?:(?::[0-9a-f]{1,4}){1,7})|(?:(?::[0-9a-f]{1,4}){0,5}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(?:%.+)?\s*$/i,
1721 regex: regex,
1722 // uuid: http://tools.ietf.org/html/rfc4122
1723 uuid: UUID,
1724 // JSON-pointer: https://tools.ietf.org/html/rfc6901
1725 // uri fragment: https://tools.ietf.org/html/rfc3986#appendix-A
1726 'json-pointer': JSON_POINTER,
1727 'json-pointer-uri-fragment': JSON_POINTER_URI_FRAGMENT,
1728 // relative JSON-pointer: http://tools.ietf.org/html/draft-luff-relative-json-pointer-00
1729 'relative-json-pointer': RELATIVE_JSON_POINTER
1730};
1731
1732
1733formats.full = {
1734 date: date,
1735 time: time,
1736 'date-time': date_time,
1737 uri: uri,
1738 'uri-reference': URIREF,
1739 'uri-template': URITEMPLATE,
1740 url: URL,
1741 email: /^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,
1742 hostname: hostname,
1743 ipv4: /^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,
1744 ipv6: /^\s*(?:(?:(?:[0-9a-f]{1,4}:){7}(?:[0-9a-f]{1,4}|:))|(?:(?:[0-9a-f]{1,4}:){6}(?::[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){5}(?:(?:(?::[0-9a-f]{1,4}){1,2})|:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){4}(?:(?:(?::[0-9a-f]{1,4}){1,3})|(?:(?::[0-9a-f]{1,4})?:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){3}(?:(?:(?::[0-9a-f]{1,4}){1,4})|(?:(?::[0-9a-f]{1,4}){0,2}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){2}(?:(?:(?::[0-9a-f]{1,4}){1,5})|(?:(?::[0-9a-f]{1,4}){0,3}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){1}(?:(?:(?::[0-9a-f]{1,4}){1,6})|(?:(?::[0-9a-f]{1,4}){0,4}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?::(?:(?:(?::[0-9a-f]{1,4}){1,7})|(?:(?::[0-9a-f]{1,4}){0,5}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(?:%.+)?\s*$/i,
1745 regex: regex,
1746 uuid: UUID,
1747 'json-pointer': JSON_POINTER,
1748 'json-pointer-uri-fragment': JSON_POINTER_URI_FRAGMENT,
1749 'relative-json-pointer': RELATIVE_JSON_POINTER
1750};
1751
1752
1753function isLeapYear(year) {
1754 // https://tools.ietf.org/html/rfc3339#appendix-C
1755 return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
1756}
1757
1758
1759function date(str) {
1760 // full-date from http://tools.ietf.org/html/rfc3339#section-5.6
1761 var matches = str.match(DATE);
1762 if (!matches) return false;
1763
1764 var year = +matches[1];
1765 var month = +matches[2];
1766 var day = +matches[3];
1767
1768 return month >= 1 && month <= 12 && day >= 1 &&
1769 day <= (month == 2 && isLeapYear(year) ? 29 : DAYS[month]);
1770}
1771
1772
1773function time(str, full) {
1774 var matches = str.match(TIME);
1775 if (!matches) return false;
1776
1777 var hour = matches[1];
1778 var minute = matches[2];
1779 var second = matches[3];
1780 var timeZone = matches[5];
1781 return ((hour <= 23 && minute <= 59 && second <= 59) ||
1782 (hour == 23 && minute == 59 && second == 60)) &&
1783 (!full || timeZone);
1784}
1785
1786
1787var DATE_TIME_SEPARATOR = /t|\s/i;
1788function date_time(str) {
1789 // http://tools.ietf.org/html/rfc3339#section-5.6
1790 var dateTime = str.split(DATE_TIME_SEPARATOR);
1791 return dateTime.length == 2 && date(dateTime[0]) && time(dateTime[1], true);
1792}
1793
1794
1795function hostname(str) {
1796 // https://tools.ietf.org/html/rfc1034#section-3.5
1797 // https://tools.ietf.org/html/rfc1123#section-2
1798 return str.length <= 255 && HOSTNAME.test(str);
1799}
1800
1801
1802var NOT_URI_FRAGMENT = /\/|:/;
1803function uri(str) {
1804 // http://jmrware.com/articles/2009/uri_regexp/URI_regex.html + optional protocol + required "."
1805 return NOT_URI_FRAGMENT.test(str) && URI.test(str);
1806}
1807
1808
1809var Z_ANCHOR = /[^\\]\\Z/;
1810function regex(str) {
1811 if (Z_ANCHOR.test(str)) return false;
1812 try {
1813 new RegExp(str);
1814 return true;
1815 } catch(e) {
1816 return false;
1817 }
1818}
1819
1820},{"./util":15}],10:[function(require,module,exports){
1821'use strict';
1822
1823var resolve = require('./resolve')
1824 , util = require('./util')
1825 , errorClasses = require('./error_classes')
1826 , stableStringify = require('fast-json-stable-stringify');
1827
1828var validateGenerator = require('../dotjs/validate');
1829
1830/**
1831 * Functions below are used inside compiled validations function
1832 */
1833
1834var ucs2length = util.ucs2length;
1835var equal = require('fast-deep-equal');
1836
1837// this error is thrown by async schemas to return validation errors via exception
1838var ValidationError = errorClasses.Validation;
1839
1840module.exports = compile;
1841
1842
1843/**
1844 * Compiles schema to validation function
1845 * @this Ajv
1846 * @param {Object} schema schema object
1847 * @param {Object} root object with information about the root schema for this schema
1848 * @param {Object} localRefs the hash of local references inside the schema (created by resolve.id), used for inline resolution
1849 * @param {String} baseId base ID for IDs in the schema
1850 * @return {Function} validation function
1851 */
1852function compile(schema, root, localRefs, baseId) {
1853 /* jshint validthis: true, evil: true */
1854 /* eslint no-shadow: 0 */
1855 var self = this
1856 , opts = this._opts
1857 , refVal = [ undefined ]
1858 , refs = {}
1859 , patterns = []
1860 , patternsHash = {}
1861 , defaults = []
1862 , defaultsHash = {}
1863 , customRules = [];
1864
1865 root = root || { schema: schema, refVal: refVal, refs: refs };
1866
1867 var c = checkCompiling.call(this, schema, root, baseId);
1868 var compilation = this._compilations[c.index];
1869 if (c.compiling) return (compilation.callValidate = callValidate);
1870
1871 var formats = this._formats;
1872 var RULES = this.RULES;
1873
1874 try {
1875 var v = localCompile(schema, root, localRefs, baseId);
1876 compilation.validate = v;
1877 var cv = compilation.callValidate;
1878 if (cv) {
1879 cv.schema = v.schema;
1880 cv.errors = null;
1881 cv.refs = v.refs;
1882 cv.refVal = v.refVal;
1883 cv.root = v.root;
1884 cv.$async = v.$async;
1885 if (opts.sourceCode) cv.source = v.source;
1886 }
1887 return v;
1888 } finally {
1889 endCompiling.call(this, schema, root, baseId);
1890 }
1891
1892 /* @this {*} - custom context, see passContext option */
1893 function callValidate() {
1894 /* jshint validthis: true */
1895 var validate = compilation.validate;
1896 var result = validate.apply(this, arguments);
1897 callValidate.errors = validate.errors;
1898 return result;
1899 }
1900
1901 function localCompile(_schema, _root, localRefs, baseId) {
1902 var isRoot = !_root || (_root && _root.schema == _schema);
1903 if (_root.schema != root.schema)
1904 return compile.call(self, _schema, _root, localRefs, baseId);
1905
1906 var $async = _schema.$async === true;
1907
1908 var sourceCode = validateGenerator({
1909 isTop: true,
1910 schema: _schema,
1911 isRoot: isRoot,
1912 baseId: baseId,
1913 root: _root,
1914 schemaPath: '',
1915 errSchemaPath: '#',
1916 errorPath: '""',
1917 MissingRefError: errorClasses.MissingRef,
1918 RULES: RULES,
1919 validate: validateGenerator,
1920 util: util,
1921 resolve: resolve,
1922 resolveRef: resolveRef,
1923 usePattern: usePattern,
1924 useDefault: useDefault,
1925 useCustomRule: useCustomRule,
1926 opts: opts,
1927 formats: formats,
1928 logger: self.logger,
1929 self: self
1930 });
1931
1932 sourceCode = vars(refVal, refValCode) + vars(patterns, patternCode)
1933 + vars(defaults, defaultCode) + vars(customRules, customRuleCode)
1934 + sourceCode;
1935
1936 if (opts.processCode) sourceCode = opts.processCode(sourceCode);
1937 // console.log('\n\n\n *** \n', JSON.stringify(sourceCode));
1938 var validate;
1939 try {
1940 var makeValidate = new Function(
1941 'self',
1942 'RULES',
1943 'formats',
1944 'root',
1945 'refVal',
1946 'defaults',
1947 'customRules',
1948 'equal',
1949 'ucs2length',
1950 'ValidationError',
1951 sourceCode
1952 );
1953
1954 validate = makeValidate(
1955 self,
1956 RULES,
1957 formats,
1958 root,
1959 refVal,
1960 defaults,
1961 customRules,
1962 equal,
1963 ucs2length,
1964 ValidationError
1965 );
1966
1967 refVal[0] = validate;
1968 } catch(e) {
1969 self.logger.error('Error compiling schema, function code:', sourceCode);
1970 throw e;
1971 }
1972
1973 validate.schema = _schema;
1974 validate.errors = null;
1975 validate.refs = refs;
1976 validate.refVal = refVal;
1977 validate.root = isRoot ? validate : _root;
1978 if ($async) validate.$async = true;
1979 if (opts.sourceCode === true) {
1980 validate.source = {
1981 code: sourceCode,
1982 patterns: patterns,
1983 defaults: defaults
1984 };
1985 }
1986
1987 return validate;
1988 }
1989
1990 function resolveRef(baseId, ref, isRoot) {
1991 ref = resolve.url(baseId, ref);
1992 var refIndex = refs[ref];
1993 var _refVal, refCode;
1994 if (refIndex !== undefined) {
1995 _refVal = refVal[refIndex];
1996 refCode = 'refVal[' + refIndex + ']';
1997 return resolvedRef(_refVal, refCode);
1998 }
1999 if (!isRoot && root.refs) {
2000 var rootRefId = root.refs[ref];
2001 if (rootRefId !== undefined) {
2002 _refVal = root.refVal[rootRefId];
2003 refCode = addLocalRef(ref, _refVal);
2004 return resolvedRef(_refVal, refCode);
2005 }
2006 }
2007
2008 refCode = addLocalRef(ref);
2009 var v = resolve.call(self, localCompile, root, ref);
2010 if (v === undefined) {
2011 var localSchema = localRefs && localRefs[ref];
2012 if (localSchema) {
2013 v = resolve.inlineRef(localSchema, opts.inlineRefs)
2014 ? localSchema
2015 : compile.call(self, localSchema, root, localRefs, baseId);
2016 }
2017 }
2018
2019 if (v === undefined) {
2020 removeLocalRef(ref);
2021 } else {
2022 replaceLocalRef(ref, v);
2023 return resolvedRef(v, refCode);
2024 }
2025 }
2026
2027 function addLocalRef(ref, v) {
2028 var refId = refVal.length;
2029 refVal[refId] = v;
2030 refs[ref] = refId;
2031 return 'refVal' + refId;
2032 }
2033
2034 function removeLocalRef(ref) {
2035 delete refs[ref];
2036 }
2037
2038 function replaceLocalRef(ref, v) {
2039 var refId = refs[ref];
2040 refVal[refId] = v;
2041 }
2042
2043 function resolvedRef(refVal, code) {
2044 return typeof refVal == 'object' || typeof refVal == 'boolean'
2045 ? { code: code, schema: refVal, inline: true }
2046 : { code: code, $async: refVal && !!refVal.$async };
2047 }
2048
2049 function usePattern(regexStr) {
2050 var index = patternsHash[regexStr];
2051 if (index === undefined) {
2052 index = patternsHash[regexStr] = patterns.length;
2053 patterns[index] = regexStr;
2054 }
2055 return 'pattern' + index;
2056 }
2057
2058 function useDefault(value) {
2059 switch (typeof value) {
2060 case 'boolean':
2061 case 'number':
2062 return '' + value;
2063 case 'string':
2064 return util.toQuotedString(value);
2065 case 'object':
2066 if (value === null) return 'null';
2067 var valueStr = stableStringify(value);
2068 var index = defaultsHash[valueStr];
2069 if (index === undefined) {
2070 index = defaultsHash[valueStr] = defaults.length;
2071 defaults[index] = value;
2072 }
2073 return 'default' + index;
2074 }
2075 }
2076
2077 function useCustomRule(rule, schema, parentSchema, it) {
2078 if (self._opts.validateSchema !== false) {
2079 var deps = rule.definition.dependencies;
2080 if (deps && !deps.every(function(keyword) {
2081 return Object.prototype.hasOwnProperty.call(parentSchema, keyword);
2082 }))
2083 throw new Error('parent schema must have all required keywords: ' + deps.join(','));
2084
2085 var validateSchema = rule.definition.validateSchema;
2086 if (validateSchema) {
2087 var valid = validateSchema(schema);
2088 if (!valid) {
2089 var message = 'keyword schema is invalid: ' + self.errorsText(validateSchema.errors);
2090 if (self._opts.validateSchema == 'log') self.logger.error(message);
2091 else throw new Error(message);
2092 }
2093 }
2094 }
2095
2096 var compile = rule.definition.compile
2097 , inline = rule.definition.inline
2098 , macro = rule.definition.macro;
2099
2100 var validate;
2101 if (compile) {
2102 validate = compile.call(self, schema, parentSchema, it);
2103 } else if (macro) {
2104 validate = macro.call(self, schema, parentSchema, it);
2105 if (opts.validateSchema !== false) self.validateSchema(validate, true);
2106 } else if (inline) {
2107 validate = inline.call(self, it, rule.keyword, schema, parentSchema);
2108 } else {
2109 validate = rule.definition.validate;
2110 if (!validate) return;
2111 }
2112
2113 if (validate === undefined)
2114 throw new Error('custom keyword "' + rule.keyword + '"failed to compile');
2115
2116 var index = customRules.length;
2117 customRules[index] = validate;
2118
2119 return {
2120 code: 'customRule' + index,
2121 validate: validate
2122 };
2123 }
2124}
2125
2126
2127/**
2128 * Checks if the schema is currently compiled
2129 * @this Ajv
2130 * @param {Object} schema schema to compile
2131 * @param {Object} root root object
2132 * @param {String} baseId base schema ID
2133 * @return {Object} object with properties "index" (compilation index) and "compiling" (boolean)
2134 */
2135function checkCompiling(schema, root, baseId) {
2136 /* jshint validthis: true */
2137 var index = compIndex.call(this, schema, root, baseId);
2138 if (index >= 0) return { index: index, compiling: true };
2139 index = this._compilations.length;
2140 this._compilations[index] = {
2141 schema: schema,
2142 root: root,
2143 baseId: baseId
2144 };
2145 return { index: index, compiling: false };
2146}
2147
2148
2149/**
2150 * Removes the schema from the currently compiled list
2151 * @this Ajv
2152 * @param {Object} schema schema to compile
2153 * @param {Object} root root object
2154 * @param {String} baseId base schema ID
2155 */
2156function endCompiling(schema, root, baseId) {
2157 /* jshint validthis: true */
2158 var i = compIndex.call(this, schema, root, baseId);
2159 if (i >= 0) this._compilations.splice(i, 1);
2160}
2161
2162
2163/**
2164 * Index of schema compilation in the currently compiled list
2165 * @this Ajv
2166 * @param {Object} schema schema to compile
2167 * @param {Object} root root object
2168 * @param {String} baseId base schema ID
2169 * @return {Integer} compilation index
2170 */
2171function compIndex(schema, root, baseId) {
2172 /* jshint validthis: true */
2173 for (var i=0; i<this._compilations.length; i++) {
2174 var c = this._compilations[i];
2175 if (c.schema == schema && c.root == root && c.baseId == baseId) return i;
2176 }
2177 return -1;
2178}
2179
2180
2181function patternCode(i, patterns) {
2182 return 'var pattern' + i + ' = new RegExp(' + util.toQuotedString(patterns[i]) + ');';
2183}
2184
2185
2186function defaultCode(i) {
2187 return 'var default' + i + ' = defaults[' + i + '];';
2188}
2189
2190
2191function refValCode(i, refVal) {
2192 return refVal[i] === undefined ? '' : 'var refVal' + i + ' = refVal[' + i + '];';
2193}
2194
2195
2196function customRuleCode(i) {
2197 return 'var customRule' + i + ' = customRules[' + i + '];';
2198}
2199
2200
2201function vars(arr, statement) {
2202 if (!arr.length) return '';
2203 var code = '';
2204 for (var i=0; i<arr.length; i++)
2205 code += statement(i, arr);
2206 return code;
2207}
2208
2209},{"../dotjs/validate":42,"./error_classes":8,"./resolve":11,"./util":15,"fast-deep-equal":163,"fast-json-stable-stringify":164}],11:[function(require,module,exports){
2210'use strict';
2211
2212var URI = require('uri-js')
2213 , equal = require('fast-deep-equal')
2214 , util = require('./util')
2215 , SchemaObject = require('./schema_obj')
2216 , traverse = require('json-schema-traverse');
2217
2218module.exports = resolve;
2219
2220resolve.normalizeId = normalizeId;
2221resolve.fullPath = getFullPath;
2222resolve.url = resolveUrl;
2223resolve.ids = resolveIds;
2224resolve.inlineRef = inlineRef;
2225resolve.schema = resolveSchema;
2226
2227/**
2228 * [resolve and compile the references ($ref)]
2229 * @this Ajv
2230 * @param {Function} compile reference to schema compilation funciton (localCompile)
2231 * @param {Object} root object with information about the root schema for the current schema
2232 * @param {String} ref reference to resolve
2233 * @return {Object|Function} schema object (if the schema can be inlined) or validation function
2234 */
2235function resolve(compile, root, ref) {
2236 /* jshint validthis: true */
2237 var refVal = this._refs[ref];
2238 if (typeof refVal == 'string') {
2239 if (this._refs[refVal]) refVal = this._refs[refVal];
2240 else return resolve.call(this, compile, root, refVal);
2241 }
2242
2243 refVal = refVal || this._schemas[ref];
2244 if (refVal instanceof SchemaObject) {
2245 return inlineRef(refVal.schema, this._opts.inlineRefs)
2246 ? refVal.schema
2247 : refVal.validate || this._compile(refVal);
2248 }
2249
2250 var res = resolveSchema.call(this, root, ref);
2251 var schema, v, baseId;
2252 if (res) {
2253 schema = res.schema;
2254 root = res.root;
2255 baseId = res.baseId;
2256 }
2257
2258 if (schema instanceof SchemaObject) {
2259 v = schema.validate || compile.call(this, schema.schema, root, undefined, baseId);
2260 } else if (schema !== undefined) {
2261 v = inlineRef(schema, this._opts.inlineRefs)
2262 ? schema
2263 : compile.call(this, schema, root, undefined, baseId);
2264 }
2265
2266 return v;
2267}
2268
2269
2270/**
2271 * Resolve schema, its root and baseId
2272 * @this Ajv
2273 * @param {Object} root root object with properties schema, refVal, refs
2274 * @param {String} ref reference to resolve
2275 * @return {Object} object with properties schema, root, baseId
2276 */
2277function resolveSchema(root, ref) {
2278 /* jshint validthis: true */
2279 var p = URI.parse(ref)
2280 , refPath = _getFullPath(p)
2281 , baseId = getFullPath(this._getId(root.schema));
2282 if (Object.keys(root.schema).length === 0 || refPath !== baseId) {
2283 var id = normalizeId(refPath);
2284 var refVal = this._refs[id];
2285 if (typeof refVal == 'string') {
2286 return resolveRecursive.call(this, root, refVal, p);
2287 } else if (refVal instanceof SchemaObject) {
2288 if (!refVal.validate) this._compile(refVal);
2289 root = refVal;
2290 } else {
2291 refVal = this._schemas[id];
2292 if (refVal instanceof SchemaObject) {
2293 if (!refVal.validate) this._compile(refVal);
2294 if (id == normalizeId(ref))
2295 return { schema: refVal, root: root, baseId: baseId };
2296 root = refVal;
2297 } else {
2298 return;
2299 }
2300 }
2301 if (!root.schema) return;
2302 baseId = getFullPath(this._getId(root.schema));
2303 }
2304 return getJsonPointer.call(this, p, baseId, root.schema, root);
2305}
2306
2307
2308/* @this Ajv */
2309function resolveRecursive(root, ref, parsedRef) {
2310 /* jshint validthis: true */
2311 var res = resolveSchema.call(this, root, ref);
2312 if (res) {
2313 var schema = res.schema;
2314 var baseId = res.baseId;
2315 root = res.root;
2316 var id = this._getId(schema);
2317 if (id) baseId = resolveUrl(baseId, id);
2318 return getJsonPointer.call(this, parsedRef, baseId, schema, root);
2319 }
2320}
2321
2322
2323var PREVENT_SCOPE_CHANGE = util.toHash(['properties', 'patternProperties', 'enum', 'dependencies', 'definitions']);
2324/* @this Ajv */
2325function getJsonPointer(parsedRef, baseId, schema, root) {
2326 /* jshint validthis: true */
2327 parsedRef.fragment = parsedRef.fragment || '';
2328 if (parsedRef.fragment.slice(0,1) != '/') return;
2329 var parts = parsedRef.fragment.split('/');
2330
2331 for (var i = 1; i < parts.length; i++) {
2332 var part = parts[i];
2333 if (part) {
2334 part = util.unescapeFragment(part);
2335 schema = schema[part];
2336 if (schema === undefined) break;
2337 var id;
2338 if (!PREVENT_SCOPE_CHANGE[part]) {
2339 id = this._getId(schema);
2340 if (id) baseId = resolveUrl(baseId, id);
2341 if (schema.$ref) {
2342 var $ref = resolveUrl(baseId, schema.$ref);
2343 var res = resolveSchema.call(this, root, $ref);
2344 if (res) {
2345 schema = res.schema;
2346 root = res.root;
2347 baseId = res.baseId;
2348 }
2349 }
2350 }
2351 }
2352 }
2353 if (schema !== undefined && schema !== root.schema)
2354 return { schema: schema, root: root, baseId: baseId };
2355}
2356
2357
2358var SIMPLE_INLINED = util.toHash([
2359 'type', 'format', 'pattern',
2360 'maxLength', 'minLength',
2361 'maxProperties', 'minProperties',
2362 'maxItems', 'minItems',
2363 'maximum', 'minimum',
2364 'uniqueItems', 'multipleOf',
2365 'required', 'enum'
2366]);
2367function inlineRef(schema, limit) {
2368 if (limit === false) return false;
2369 if (limit === undefined || limit === true) return checkNoRef(schema);
2370 else if (limit) return countKeys(schema) <= limit;
2371}
2372
2373
2374function checkNoRef(schema) {
2375 var item;
2376 if (Array.isArray(schema)) {
2377 for (var i=0; i<schema.length; i++) {
2378 item = schema[i];
2379 if (typeof item == 'object' && !checkNoRef(item)) return false;
2380 }
2381 } else {
2382 for (var key in schema) {
2383 if (key == '$ref') return false;
2384 item = schema[key];
2385 if (typeof item == 'object' && !checkNoRef(item)) return false;
2386 }
2387 }
2388 return true;
2389}
2390
2391
2392function countKeys(schema) {
2393 var count = 0, item;
2394 if (Array.isArray(schema)) {
2395 for (var i=0; i<schema.length; i++) {
2396 item = schema[i];
2397 if (typeof item == 'object') count += countKeys(item);
2398 if (count == Infinity) return Infinity;
2399 }
2400 } else {
2401 for (var key in schema) {
2402 if (key == '$ref') return Infinity;
2403 if (SIMPLE_INLINED[key]) {
2404 count++;
2405 } else {
2406 item = schema[key];
2407 if (typeof item == 'object') count += countKeys(item) + 1;
2408 if (count == Infinity) return Infinity;
2409 }
2410 }
2411 }
2412 return count;
2413}
2414
2415
2416function getFullPath(id, normalize) {
2417 if (normalize !== false) id = normalizeId(id);
2418 var p = URI.parse(id);
2419 return _getFullPath(p);
2420}
2421
2422
2423function _getFullPath(p) {
2424 return URI.serialize(p).split('#')[0] + '#';
2425}
2426
2427
2428var TRAILING_SLASH_HASH = /#\/?$/;
2429function normalizeId(id) {
2430 return id ? id.replace(TRAILING_SLASH_HASH, '') : '';
2431}
2432
2433
2434function resolveUrl(baseId, id) {
2435 id = normalizeId(id);
2436 return URI.resolve(baseId, id);
2437}
2438
2439
2440/* @this Ajv */
2441function resolveIds(schema) {
2442 var schemaId = normalizeId(this._getId(schema));
2443 var baseIds = {'': schemaId};
2444 var fullPaths = {'': getFullPath(schemaId, false)};
2445 var localRefs = {};
2446 var self = this;
2447
2448 traverse(schema, {allKeys: true}, function(sch, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex) {
2449 if (jsonPtr === '') return;
2450 var id = self._getId(sch);
2451 var baseId = baseIds[parentJsonPtr];
2452 var fullPath = fullPaths[parentJsonPtr] + '/' + parentKeyword;
2453 if (keyIndex !== undefined)
2454 fullPath += '/' + (typeof keyIndex == 'number' ? keyIndex : util.escapeFragment(keyIndex));
2455
2456 if (typeof id == 'string') {
2457 id = baseId = normalizeId(baseId ? URI.resolve(baseId, id) : id);
2458
2459 var refVal = self._refs[id];
2460 if (typeof refVal == 'string') refVal = self._refs[refVal];
2461 if (refVal && refVal.schema) {
2462 if (!equal(sch, refVal.schema))
2463 throw new Error('id "' + id + '" resolves to more than one schema');
2464 } else if (id != normalizeId(fullPath)) {
2465 if (id[0] == '#') {
2466 if (localRefs[id] && !equal(sch, localRefs[id]))
2467 throw new Error('id "' + id + '" resolves to more than one schema');
2468 localRefs[id] = sch;
2469 } else {
2470 self._refs[id] = fullPath;
2471 }
2472 }
2473 }
2474 baseIds[jsonPtr] = baseId;
2475 fullPaths[jsonPtr] = fullPath;
2476 });
2477
2478 return localRefs;
2479}
2480
2481},{"./schema_obj":13,"./util":15,"fast-deep-equal":163,"json-schema-traverse":216,"uri-js":392}],12:[function(require,module,exports){
2482'use strict';
2483
2484var ruleModules = require('../dotjs')
2485 , toHash = require('./util').toHash;
2486
2487module.exports = function rules() {
2488 var RULES = [
2489 { type: 'number',
2490 rules: [ { 'maximum': ['exclusiveMaximum'] },
2491 { 'minimum': ['exclusiveMinimum'] }, 'multipleOf', 'format'] },
2492 { type: 'string',
2493 rules: [ 'maxLength', 'minLength', 'pattern', 'format' ] },
2494 { type: 'array',
2495 rules: [ 'maxItems', 'minItems', 'items', 'contains', 'uniqueItems' ] },
2496 { type: 'object',
2497 rules: [ 'maxProperties', 'minProperties', 'required', 'dependencies', 'propertyNames',
2498 { 'properties': ['additionalProperties', 'patternProperties'] } ] },
2499 { rules: [ '$ref', 'const', 'enum', 'not', 'anyOf', 'oneOf', 'allOf', 'if' ] }
2500 ];
2501
2502 var ALL = [ 'type', '$comment' ];
2503 var KEYWORDS = [
2504 '$schema', '$id', 'id', '$data', '$async', 'title',
2505 'description', 'default', 'definitions',
2506 'examples', 'readOnly', 'writeOnly',
2507 'contentMediaType', 'contentEncoding',
2508 'additionalItems', 'then', 'else'
2509 ];
2510 var TYPES = [ 'number', 'integer', 'string', 'array', 'object', 'boolean', 'null' ];
2511 RULES.all = toHash(ALL);
2512 RULES.types = toHash(TYPES);
2513
2514 RULES.forEach(function (group) {
2515 group.rules = group.rules.map(function (keyword) {
2516 var implKeywords;
2517 if (typeof keyword == 'object') {
2518 var key = Object.keys(keyword)[0];
2519 implKeywords = keyword[key];
2520 keyword = key;
2521 implKeywords.forEach(function (k) {
2522 ALL.push(k);
2523 RULES.all[k] = true;
2524 });
2525 }
2526 ALL.push(keyword);
2527 var rule = RULES.all[keyword] = {
2528 keyword: keyword,
2529 code: ruleModules[keyword],
2530 implements: implKeywords
2531 };
2532 return rule;
2533 });
2534
2535 RULES.all.$comment = {
2536 keyword: '$comment',
2537 code: ruleModules.$comment
2538 };
2539
2540 if (group.type) RULES.types[group.type] = group;
2541 });
2542
2543 RULES.keywords = toHash(ALL.concat(KEYWORDS));
2544 RULES.custom = {};
2545
2546 return RULES;
2547};
2548
2549},{"../dotjs":31,"./util":15}],13:[function(require,module,exports){
2550'use strict';
2551
2552var util = require('./util');
2553
2554module.exports = SchemaObject;
2555
2556function SchemaObject(obj) {
2557 util.copy(obj, this);
2558}
2559
2560},{"./util":15}],14:[function(require,module,exports){
2561'use strict';
2562
2563// https://mathiasbynens.be/notes/javascript-encoding
2564// https://github.com/bestiejs/punycode.js - punycode.ucs2.decode
2565module.exports = function ucs2length(str) {
2566 var length = 0
2567 , len = str.length
2568 , pos = 0
2569 , value;
2570 while (pos < len) {
2571 length++;
2572 value = str.charCodeAt(pos++);
2573 if (value >= 0xD800 && value <= 0xDBFF && pos < len) {
2574 // high surrogate, and there is a next character
2575 value = str.charCodeAt(pos);
2576 if ((value & 0xFC00) == 0xDC00) pos++; // low surrogate
2577 }
2578 }
2579 return length;
2580};
2581
2582},{}],15:[function(require,module,exports){
2583'use strict';
2584
2585
2586module.exports = {
2587 copy: copy,
2588 checkDataType: checkDataType,
2589 checkDataTypes: checkDataTypes,
2590 coerceToTypes: coerceToTypes,
2591 toHash: toHash,
2592 getProperty: getProperty,
2593 escapeQuotes: escapeQuotes,
2594 equal: require('fast-deep-equal'),
2595 ucs2length: require('./ucs2length'),
2596 varOccurences: varOccurences,
2597 varReplace: varReplace,
2598 cleanUpCode: cleanUpCode,
2599 finalCleanUpCode: finalCleanUpCode,
2600 schemaHasRules: schemaHasRules,
2601 schemaHasRulesExcept: schemaHasRulesExcept,
2602 schemaUnknownRules: schemaUnknownRules,
2603 toQuotedString: toQuotedString,
2604 getPathExpr: getPathExpr,
2605 getPath: getPath,
2606 getData: getData,
2607 unescapeFragment: unescapeFragment,
2608 unescapeJsonPointer: unescapeJsonPointer,
2609 escapeFragment: escapeFragment,
2610 escapeJsonPointer: escapeJsonPointer
2611};
2612
2613
2614function copy(o, to) {
2615 to = to || {};
2616 for (var key in o) to[key] = o[key];
2617 return to;
2618}
2619
2620
2621function checkDataType(dataType, data, negate) {
2622 var EQUAL = negate ? ' !== ' : ' === '
2623 , AND = negate ? ' || ' : ' && '
2624 , OK = negate ? '!' : ''
2625 , NOT = negate ? '' : '!';
2626 switch (dataType) {
2627 case 'null': return data + EQUAL + 'null';
2628 case 'array': return OK + 'Array.isArray(' + data + ')';
2629 case 'object': return '(' + OK + data + AND +
2630 'typeof ' + data + EQUAL + '"object"' + AND +
2631 NOT + 'Array.isArray(' + data + '))';
2632 case 'integer': return '(typeof ' + data + EQUAL + '"number"' + AND +
2633 NOT + '(' + data + ' % 1)' +
2634 AND + data + EQUAL + data + ')';
2635 default: return 'typeof ' + data + EQUAL + '"' + dataType + '"';
2636 }
2637}
2638
2639
2640function checkDataTypes(dataTypes, data) {
2641 switch (dataTypes.length) {
2642 case 1: return checkDataType(dataTypes[0], data, true);
2643 default:
2644 var code = '';
2645 var types = toHash(dataTypes);
2646 if (types.array && types.object) {
2647 code = types.null ? '(': '(!' + data + ' || ';
2648 code += 'typeof ' + data + ' !== "object")';
2649 delete types.null;
2650 delete types.array;
2651 delete types.object;
2652 }
2653 if (types.number) delete types.integer;
2654 for (var t in types)
2655 code += (code ? ' && ' : '' ) + checkDataType(t, data, true);
2656
2657 return code;
2658 }
2659}
2660
2661
2662var COERCE_TO_TYPES = toHash([ 'string', 'number', 'integer', 'boolean', 'null' ]);
2663function coerceToTypes(optionCoerceTypes, dataTypes) {
2664 if (Array.isArray(dataTypes)) {
2665 var types = [];
2666 for (var i=0; i<dataTypes.length; i++) {
2667 var t = dataTypes[i];
2668 if (COERCE_TO_TYPES[t]) types[types.length] = t;
2669 else if (optionCoerceTypes === 'array' && t === 'array') types[types.length] = t;
2670 }
2671 if (types.length) return types;
2672 } else if (COERCE_TO_TYPES[dataTypes]) {
2673 return [dataTypes];
2674 } else if (optionCoerceTypes === 'array' && dataTypes === 'array') {
2675 return ['array'];
2676 }
2677}
2678
2679
2680function toHash(arr) {
2681 var hash = {};
2682 for (var i=0; i<arr.length; i++) hash[arr[i]] = true;
2683 return hash;
2684}
2685
2686
2687var IDENTIFIER = /^[a-z$_][a-z$_0-9]*$/i;
2688var SINGLE_QUOTE = /'|\\/g;
2689function getProperty(key) {
2690 return typeof key == 'number'
2691 ? '[' + key + ']'
2692 : IDENTIFIER.test(key)
2693 ? '.' + key
2694 : "['" + escapeQuotes(key) + "']";
2695}
2696
2697
2698function escapeQuotes(str) {
2699 return str.replace(SINGLE_QUOTE, '\\$&')
2700 .replace(/\n/g, '\\n')
2701 .replace(/\r/g, '\\r')
2702 .replace(/\f/g, '\\f')
2703 .replace(/\t/g, '\\t');
2704}
2705
2706
2707function varOccurences(str, dataVar) {
2708 dataVar += '[^0-9]';
2709 var matches = str.match(new RegExp(dataVar, 'g'));
2710 return matches ? matches.length : 0;
2711}
2712
2713
2714function varReplace(str, dataVar, expr) {
2715 dataVar += '([^0-9])';
2716 expr = expr.replace(/\$/g, '$$$$');
2717 return str.replace(new RegExp(dataVar, 'g'), expr + '$1');
2718}
2719
2720
2721var EMPTY_ELSE = /else\s*{\s*}/g
2722 , EMPTY_IF_NO_ELSE = /if\s*\([^)]+\)\s*\{\s*\}(?!\s*else)/g
2723 , EMPTY_IF_WITH_ELSE = /if\s*\(([^)]+)\)\s*\{\s*\}\s*else(?!\s*if)/g;
2724function cleanUpCode(out) {
2725 return out.replace(EMPTY_ELSE, '')
2726 .replace(EMPTY_IF_NO_ELSE, '')
2727 .replace(EMPTY_IF_WITH_ELSE, 'if (!($1))');
2728}
2729
2730
2731var ERRORS_REGEXP = /[^v.]errors/g
2732 , REMOVE_ERRORS = /var errors = 0;|var vErrors = null;|validate.errors = vErrors;/g
2733 , REMOVE_ERRORS_ASYNC = /var errors = 0;|var vErrors = null;/g
2734 , RETURN_VALID = 'return errors === 0;'
2735 , RETURN_TRUE = 'validate.errors = null; return true;'
2736 , RETURN_ASYNC = /if \(errors === 0\) return data;\s*else throw new ValidationError\(vErrors\);/
2737 , RETURN_DATA_ASYNC = 'return data;'
2738 , ROOTDATA_REGEXP = /[^A-Za-z_$]rootData[^A-Za-z0-9_$]/g
2739 , REMOVE_ROOTDATA = /if \(rootData === undefined\) rootData = data;/;
2740
2741function finalCleanUpCode(out, async) {
2742 var matches = out.match(ERRORS_REGEXP);
2743 if (matches && matches.length == 2) {
2744 out = async
2745 ? out.replace(REMOVE_ERRORS_ASYNC, '')
2746 .replace(RETURN_ASYNC, RETURN_DATA_ASYNC)
2747 : out.replace(REMOVE_ERRORS, '')
2748 .replace(RETURN_VALID, RETURN_TRUE);
2749 }
2750
2751 matches = out.match(ROOTDATA_REGEXP);
2752 if (!matches || matches.length !== 3) return out;
2753 return out.replace(REMOVE_ROOTDATA, '');
2754}
2755
2756
2757function schemaHasRules(schema, rules) {
2758 if (typeof schema == 'boolean') return !schema;
2759 for (var key in schema) if (rules[key]) return true;
2760}
2761
2762
2763function schemaHasRulesExcept(schema, rules, exceptKeyword) {
2764 if (typeof schema == 'boolean') return !schema && exceptKeyword != 'not';
2765 for (var key in schema) if (key != exceptKeyword && rules[key]) return true;
2766}
2767
2768
2769function schemaUnknownRules(schema, rules) {
2770 if (typeof schema == 'boolean') return;
2771 for (var key in schema) if (!rules[key]) return key;
2772}
2773
2774
2775function toQuotedString(str) {
2776 return '\'' + escapeQuotes(str) + '\'';
2777}
2778
2779
2780function getPathExpr(currentPath, expr, jsonPointers, isNumber) {
2781 var path = jsonPointers // false by default
2782 ? '\'/\' + ' + expr + (isNumber ? '' : '.replace(/~/g, \'~0\').replace(/\\//g, \'~1\')')
2783 : (isNumber ? '\'[\' + ' + expr + ' + \']\'' : '\'[\\\'\' + ' + expr + ' + \'\\\']\'');
2784 return joinPaths(currentPath, path);
2785}
2786
2787
2788function getPath(currentPath, prop, jsonPointers) {
2789 var path = jsonPointers // false by default
2790 ? toQuotedString('/' + escapeJsonPointer(prop))
2791 : toQuotedString(getProperty(prop));
2792 return joinPaths(currentPath, path);
2793}
2794
2795
2796var JSON_POINTER = /^\/(?:[^~]|~0|~1)*$/;
2797var RELATIVE_JSON_POINTER = /^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;
2798function getData($data, lvl, paths) {
2799 var up, jsonPointer, data, matches;
2800 if ($data === '') return 'rootData';
2801 if ($data[0] == '/') {
2802 if (!JSON_POINTER.test($data)) throw new Error('Invalid JSON-pointer: ' + $data);
2803 jsonPointer = $data;
2804 data = 'rootData';
2805 } else {
2806 matches = $data.match(RELATIVE_JSON_POINTER);
2807 if (!matches) throw new Error('Invalid JSON-pointer: ' + $data);
2808 up = +matches[1];
2809 jsonPointer = matches[2];
2810 if (jsonPointer == '#') {
2811 if (up >= lvl) throw new Error('Cannot access property/index ' + up + ' levels up, current level is ' + lvl);
2812 return paths[lvl - up];
2813 }
2814
2815 if (up > lvl) throw new Error('Cannot access data ' + up + ' levels up, current level is ' + lvl);
2816 data = 'data' + ((lvl - up) || '');
2817 if (!jsonPointer) return data;
2818 }
2819
2820 var expr = data;
2821 var segments = jsonPointer.split('/');
2822 for (var i=0; i<segments.length; i++) {
2823 var segment = segments[i];
2824 if (segment) {
2825 data += getProperty(unescapeJsonPointer(segment));
2826 expr += ' && ' + data;
2827 }
2828 }
2829 return expr;
2830}
2831
2832
2833function joinPaths (a, b) {
2834 if (a == '""') return b;
2835 return (a + ' + ' + b).replace(/' \+ '/g, '');
2836}
2837
2838
2839function unescapeFragment(str) {
2840 return unescapeJsonPointer(decodeURIComponent(str));
2841}
2842
2843
2844function escapeFragment(str) {
2845 return encodeURIComponent(escapeJsonPointer(str));
2846}
2847
2848
2849function escapeJsonPointer(str) {
2850 return str.replace(/~/g, '~0').replace(/\//g, '~1');
2851}
2852
2853
2854function unescapeJsonPointer(str) {
2855 return str.replace(/~1/g, '/').replace(/~0/g, '~');
2856}
2857
2858},{"./ucs2length":14,"fast-deep-equal":163}],16:[function(require,module,exports){
2859'use strict';
2860
2861var KEYWORDS = [
2862 'multipleOf',
2863 'maximum',
2864 'exclusiveMaximum',
2865 'minimum',
2866 'exclusiveMinimum',
2867 'maxLength',
2868 'minLength',
2869 'pattern',
2870 'additionalItems',
2871 'maxItems',
2872 'minItems',
2873 'uniqueItems',
2874 'maxProperties',
2875 'minProperties',
2876 'required',
2877 'additionalProperties',
2878 'enum',
2879 'format',
2880 'const'
2881];
2882
2883module.exports = function (metaSchema, keywordsJsonPointers) {
2884 for (var i=0; i<keywordsJsonPointers.length; i++) {
2885 metaSchema = JSON.parse(JSON.stringify(metaSchema));
2886 var segments = keywordsJsonPointers[i].split('/');
2887 var keywords = metaSchema;
2888 var j;
2889 for (j=1; j<segments.length; j++)
2890 keywords = keywords[segments[j]];
2891
2892 for (j=0; j<KEYWORDS.length; j++) {
2893 var key = KEYWORDS[j];
2894 var schema = keywords[key];
2895 if (schema) {
2896 keywords[key] = {
2897 anyOf: [
2898 schema,
2899 { $ref: 'https://raw.githubusercontent.com/epoberezkin/ajv/master/lib/refs/data.json#' }
2900 ]
2901 };
2902 }
2903 }
2904 }
2905
2906 return metaSchema;
2907};
2908
2909},{}],17:[function(require,module,exports){
2910'use strict';
2911module.exports = function generate__limit(it, $keyword, $ruleType) {
2912 var out = ' ';
2913 var $lvl = it.level;
2914 var $dataLvl = it.dataLevel;
2915 var $schema = it.schema[$keyword];
2916 var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
2917 var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
2918 var $breakOnError = !it.opts.allErrors;
2919 var $errorKeyword;
2920 var $data = 'data' + ($dataLvl || '');
2921 var $isData = it.opts.$data && $schema && $schema.$data,
2922 $schemaValue;
2923 if ($isData) {
2924 out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; ';
2925 $schemaValue = 'schema' + $lvl;
2926 } else {
2927 $schemaValue = $schema;
2928 }
2929 var $isMax = $keyword == 'maximum',
2930 $exclusiveKeyword = $isMax ? 'exclusiveMaximum' : 'exclusiveMinimum',
2931 $schemaExcl = it.schema[$exclusiveKeyword],
2932 $isDataExcl = it.opts.$data && $schemaExcl && $schemaExcl.$data,
2933 $op = $isMax ? '<' : '>',
2934 $notOp = $isMax ? '>' : '<',
2935 $errorKeyword = undefined;
2936 if ($isDataExcl) {
2937 var $schemaValueExcl = it.util.getData($schemaExcl.$data, $dataLvl, it.dataPathArr),
2938 $exclusive = 'exclusive' + $lvl,
2939 $exclType = 'exclType' + $lvl,
2940 $exclIsNumber = 'exclIsNumber' + $lvl,
2941 $opExpr = 'op' + $lvl,
2942 $opStr = '\' + ' + $opExpr + ' + \'';
2943 out += ' var schemaExcl' + ($lvl) + ' = ' + ($schemaValueExcl) + '; ';
2944 $schemaValueExcl = 'schemaExcl' + $lvl;
2945 out += ' var ' + ($exclusive) + '; var ' + ($exclType) + ' = typeof ' + ($schemaValueExcl) + '; if (' + ($exclType) + ' != \'boolean\' && ' + ($exclType) + ' != \'undefined\' && ' + ($exclType) + ' != \'number\') { ';
2946 var $errorKeyword = $exclusiveKeyword;
2947 var $$outStack = $$outStack || [];
2948 $$outStack.push(out);
2949 out = ''; /* istanbul ignore else */
2950 if (it.createErrors !== false) {
2951 out += ' { keyword: \'' + ($errorKeyword || '_exclusiveLimit') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} ';
2952 if (it.opts.messages !== false) {
2953 out += ' , message: \'' + ($exclusiveKeyword) + ' should be boolean\' ';
2954 }
2955 if (it.opts.verbose) {
2956 out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
2957 }
2958 out += ' } ';
2959 } else {
2960 out += ' {} ';
2961 }
2962 var __err = out;
2963 out = $$outStack.pop();
2964 if (!it.compositeRule && $breakOnError) {
2965 /* istanbul ignore if */
2966 if (it.async) {
2967 out += ' throw new ValidationError([' + (__err) + ']); ';
2968 } else {
2969 out += ' validate.errors = [' + (__err) + ']; return false; ';
2970 }
2971 } else {
2972 out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
2973 }
2974 out += ' } else if ( ';
2975 if ($isData) {
2976 out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || ';
2977 }
2978 out += ' ' + ($exclType) + ' == \'number\' ? ( (' + ($exclusive) + ' = ' + ($schemaValue) + ' === undefined || ' + ($schemaValueExcl) + ' ' + ($op) + '= ' + ($schemaValue) + ') ? ' + ($data) + ' ' + ($notOp) + '= ' + ($schemaValueExcl) + ' : ' + ($data) + ' ' + ($notOp) + ' ' + ($schemaValue) + ' ) : ( (' + ($exclusive) + ' = ' + ($schemaValueExcl) + ' === true) ? ' + ($data) + ' ' + ($notOp) + '= ' + ($schemaValue) + ' : ' + ($data) + ' ' + ($notOp) + ' ' + ($schemaValue) + ' ) || ' + ($data) + ' !== ' + ($data) + ') { var op' + ($lvl) + ' = ' + ($exclusive) + ' ? \'' + ($op) + '\' : \'' + ($op) + '=\'; ';
2979 if ($schema === undefined) {
2980 $errorKeyword = $exclusiveKeyword;
2981 $errSchemaPath = it.errSchemaPath + '/' + $exclusiveKeyword;
2982 $schemaValue = $schemaValueExcl;
2983 $isData = $isDataExcl;
2984 }
2985 } else {
2986 var $exclIsNumber = typeof $schemaExcl == 'number',
2987 $opStr = $op;
2988 if ($exclIsNumber && $isData) {
2989 var $opExpr = '\'' + $opStr + '\'';
2990 out += ' if ( ';
2991 if ($isData) {
2992 out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || ';
2993 }
2994 out += ' ( ' + ($schemaValue) + ' === undefined || ' + ($schemaExcl) + ' ' + ($op) + '= ' + ($schemaValue) + ' ? ' + ($data) + ' ' + ($notOp) + '= ' + ($schemaExcl) + ' : ' + ($data) + ' ' + ($notOp) + ' ' + ($schemaValue) + ' ) || ' + ($data) + ' !== ' + ($data) + ') { ';
2995 } else {
2996 if ($exclIsNumber && $schema === undefined) {
2997 $exclusive = true;
2998 $errorKeyword = $exclusiveKeyword;
2999 $errSchemaPath = it.errSchemaPath + '/' + $exclusiveKeyword;
3000 $schemaValue = $schemaExcl;
3001 $notOp += '=';
3002 } else {
3003 if ($exclIsNumber) $schemaValue = Math[$isMax ? 'min' : 'max']($schemaExcl, $schema);
3004 if ($schemaExcl === ($exclIsNumber ? $schemaValue : true)) {
3005 $exclusive = true;
3006 $errorKeyword = $exclusiveKeyword;
3007 $errSchemaPath = it.errSchemaPath + '/' + $exclusiveKeyword;
3008 $notOp += '=';
3009 } else {
3010 $exclusive = false;
3011 $opStr += '=';
3012 }
3013 }
3014 var $opExpr = '\'' + $opStr + '\'';
3015 out += ' if ( ';
3016 if ($isData) {
3017 out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || ';
3018 }
3019 out += ' ' + ($data) + ' ' + ($notOp) + ' ' + ($schemaValue) + ' || ' + ($data) + ' !== ' + ($data) + ') { ';
3020 }
3021 }
3022 $errorKeyword = $errorKeyword || $keyword;
3023 var $$outStack = $$outStack || [];
3024 $$outStack.push(out);
3025 out = ''; /* istanbul ignore else */
3026 if (it.createErrors !== false) {
3027 out += ' { keyword: \'' + ($errorKeyword || '_limit') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { comparison: ' + ($opExpr) + ', limit: ' + ($schemaValue) + ', exclusive: ' + ($exclusive) + ' } ';
3028 if (it.opts.messages !== false) {
3029 out += ' , message: \'should be ' + ($opStr) + ' ';
3030 if ($isData) {
3031 out += '\' + ' + ($schemaValue);
3032 } else {
3033 out += '' + ($schemaValue) + '\'';
3034 }
3035 }
3036 if (it.opts.verbose) {
3037 out += ' , schema: ';
3038 if ($isData) {
3039 out += 'validate.schema' + ($schemaPath);
3040 } else {
3041 out += '' + ($schema);
3042 }
3043 out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
3044 }
3045 out += ' } ';
3046 } else {
3047 out += ' {} ';
3048 }
3049 var __err = out;
3050 out = $$outStack.pop();
3051 if (!it.compositeRule && $breakOnError) {
3052 /* istanbul ignore if */
3053 if (it.async) {
3054 out += ' throw new ValidationError([' + (__err) + ']); ';
3055 } else {
3056 out += ' validate.errors = [' + (__err) + ']; return false; ';
3057 }
3058 } else {
3059 out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
3060 }
3061 out += ' } ';
3062 if ($breakOnError) {
3063 out += ' else { ';
3064 }
3065 return out;
3066}
3067
3068},{}],18:[function(require,module,exports){
3069'use strict';
3070module.exports = function generate__limitItems(it, $keyword, $ruleType) {
3071 var out = ' ';
3072 var $lvl = it.level;
3073 var $dataLvl = it.dataLevel;
3074 var $schema = it.schema[$keyword];
3075 var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
3076 var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
3077 var $breakOnError = !it.opts.allErrors;
3078 var $errorKeyword;
3079 var $data = 'data' + ($dataLvl || '');
3080 var $isData = it.opts.$data && $schema && $schema.$data,
3081 $schemaValue;
3082 if ($isData) {
3083 out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; ';
3084 $schemaValue = 'schema' + $lvl;
3085 } else {
3086 $schemaValue = $schema;
3087 }
3088 var $op = $keyword == 'maxItems' ? '>' : '<';
3089 out += 'if ( ';
3090 if ($isData) {
3091 out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || ';
3092 }
3093 out += ' ' + ($data) + '.length ' + ($op) + ' ' + ($schemaValue) + ') { ';
3094 var $errorKeyword = $keyword;
3095 var $$outStack = $$outStack || [];
3096 $$outStack.push(out);
3097 out = ''; /* istanbul ignore else */
3098 if (it.createErrors !== false) {
3099 out += ' { keyword: \'' + ($errorKeyword || '_limitItems') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { limit: ' + ($schemaValue) + ' } ';
3100 if (it.opts.messages !== false) {
3101 out += ' , message: \'should NOT have ';
3102 if ($keyword == 'maxItems') {
3103 out += 'more';
3104 } else {
3105 out += 'fewer';
3106 }
3107 out += ' than ';
3108 if ($isData) {
3109 out += '\' + ' + ($schemaValue) + ' + \'';
3110 } else {
3111 out += '' + ($schema);
3112 }
3113 out += ' items\' ';
3114 }
3115 if (it.opts.verbose) {
3116 out += ' , schema: ';
3117 if ($isData) {
3118 out += 'validate.schema' + ($schemaPath);
3119 } else {
3120 out += '' + ($schema);
3121 }
3122 out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
3123 }
3124 out += ' } ';
3125 } else {
3126 out += ' {} ';
3127 }
3128 var __err = out;
3129 out = $$outStack.pop();
3130 if (!it.compositeRule && $breakOnError) {
3131 /* istanbul ignore if */
3132 if (it.async) {
3133 out += ' throw new ValidationError([' + (__err) + ']); ';
3134 } else {
3135 out += ' validate.errors = [' + (__err) + ']; return false; ';
3136 }
3137 } else {
3138 out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
3139 }
3140 out += '} ';
3141 if ($breakOnError) {
3142 out += ' else { ';
3143 }
3144 return out;
3145}
3146
3147},{}],19:[function(require,module,exports){
3148'use strict';
3149module.exports = function generate__limitLength(it, $keyword, $ruleType) {
3150 var out = ' ';
3151 var $lvl = it.level;
3152 var $dataLvl = it.dataLevel;
3153 var $schema = it.schema[$keyword];
3154 var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
3155 var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
3156 var $breakOnError = !it.opts.allErrors;
3157 var $errorKeyword;
3158 var $data = 'data' + ($dataLvl || '');
3159 var $isData = it.opts.$data && $schema && $schema.$data,
3160 $schemaValue;
3161 if ($isData) {
3162 out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; ';
3163 $schemaValue = 'schema' + $lvl;
3164 } else {
3165 $schemaValue = $schema;
3166 }
3167 var $op = $keyword == 'maxLength' ? '>' : '<';
3168 out += 'if ( ';
3169 if ($isData) {
3170 out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || ';
3171 }
3172 if (it.opts.unicode === false) {
3173 out += ' ' + ($data) + '.length ';
3174 } else {
3175 out += ' ucs2length(' + ($data) + ') ';
3176 }
3177 out += ' ' + ($op) + ' ' + ($schemaValue) + ') { ';
3178 var $errorKeyword = $keyword;
3179 var $$outStack = $$outStack || [];
3180 $$outStack.push(out);
3181 out = ''; /* istanbul ignore else */
3182 if (it.createErrors !== false) {
3183 out += ' { keyword: \'' + ($errorKeyword || '_limitLength') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { limit: ' + ($schemaValue) + ' } ';
3184 if (it.opts.messages !== false) {
3185 out += ' , message: \'should NOT be ';
3186 if ($keyword == 'maxLength') {
3187 out += 'longer';
3188 } else {
3189 out += 'shorter';
3190 }
3191 out += ' than ';
3192 if ($isData) {
3193 out += '\' + ' + ($schemaValue) + ' + \'';
3194 } else {
3195 out += '' + ($schema);
3196 }
3197 out += ' characters\' ';
3198 }
3199 if (it.opts.verbose) {
3200 out += ' , schema: ';
3201 if ($isData) {
3202 out += 'validate.schema' + ($schemaPath);
3203 } else {
3204 out += '' + ($schema);
3205 }
3206 out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
3207 }
3208 out += ' } ';
3209 } else {
3210 out += ' {} ';
3211 }
3212 var __err = out;
3213 out = $$outStack.pop();
3214 if (!it.compositeRule && $breakOnError) {
3215 /* istanbul ignore if */
3216 if (it.async) {
3217 out += ' throw new ValidationError([' + (__err) + ']); ';
3218 } else {
3219 out += ' validate.errors = [' + (__err) + ']; return false; ';
3220 }
3221 } else {
3222 out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
3223 }
3224 out += '} ';
3225 if ($breakOnError) {
3226 out += ' else { ';
3227 }
3228 return out;
3229}
3230
3231},{}],20:[function(require,module,exports){
3232'use strict';
3233module.exports = function generate__limitProperties(it, $keyword, $ruleType) {
3234 var out = ' ';
3235 var $lvl = it.level;
3236 var $dataLvl = it.dataLevel;
3237 var $schema = it.schema[$keyword];
3238 var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
3239 var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
3240 var $breakOnError = !it.opts.allErrors;
3241 var $errorKeyword;
3242 var $data = 'data' + ($dataLvl || '');
3243 var $isData = it.opts.$data && $schema && $schema.$data,
3244 $schemaValue;
3245 if ($isData) {
3246 out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; ';
3247 $schemaValue = 'schema' + $lvl;
3248 } else {
3249 $schemaValue = $schema;
3250 }
3251 var $op = $keyword == 'maxProperties' ? '>' : '<';
3252 out += 'if ( ';
3253 if ($isData) {
3254 out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || ';
3255 }
3256 out += ' Object.keys(' + ($data) + ').length ' + ($op) + ' ' + ($schemaValue) + ') { ';
3257 var $errorKeyword = $keyword;
3258 var $$outStack = $$outStack || [];
3259 $$outStack.push(out);
3260 out = ''; /* istanbul ignore else */
3261 if (it.createErrors !== false) {
3262 out += ' { keyword: \'' + ($errorKeyword || '_limitProperties') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { limit: ' + ($schemaValue) + ' } ';
3263 if (it.opts.messages !== false) {
3264 out += ' , message: \'should NOT have ';
3265 if ($keyword == 'maxProperties') {
3266 out += 'more';
3267 } else {
3268 out += 'fewer';
3269 }
3270 out += ' than ';
3271 if ($isData) {
3272 out += '\' + ' + ($schemaValue) + ' + \'';
3273 } else {
3274 out += '' + ($schema);
3275 }
3276 out += ' properties\' ';
3277 }
3278 if (it.opts.verbose) {
3279 out += ' , schema: ';
3280 if ($isData) {
3281 out += 'validate.schema' + ($schemaPath);
3282 } else {
3283 out += '' + ($schema);
3284 }
3285 out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
3286 }
3287 out += ' } ';
3288 } else {
3289 out += ' {} ';
3290 }
3291 var __err = out;
3292 out = $$outStack.pop();
3293 if (!it.compositeRule && $breakOnError) {
3294 /* istanbul ignore if */
3295 if (it.async) {
3296 out += ' throw new ValidationError([' + (__err) + ']); ';
3297 } else {
3298 out += ' validate.errors = [' + (__err) + ']; return false; ';
3299 }
3300 } else {
3301 out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
3302 }
3303 out += '} ';
3304 if ($breakOnError) {
3305 out += ' else { ';
3306 }
3307 return out;
3308}
3309
3310},{}],21:[function(require,module,exports){
3311'use strict';
3312module.exports = function generate_allOf(it, $keyword, $ruleType) {
3313 var out = ' ';
3314 var $schema = it.schema[$keyword];
3315 var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
3316 var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
3317 var $breakOnError = !it.opts.allErrors;
3318 var $it = it.util.copy(it);
3319 var $closingBraces = '';
3320 $it.level++;
3321 var $nextValid = 'valid' + $it.level;
3322 var $currentBaseId = $it.baseId,
3323 $allSchemasEmpty = true;
3324 var arr1 = $schema;
3325 if (arr1) {
3326 var $sch, $i = -1,
3327 l1 = arr1.length - 1;
3328 while ($i < l1) {
3329 $sch = arr1[$i += 1];
3330 if (it.util.schemaHasRules($sch, it.RULES.all)) {
3331 $allSchemasEmpty = false;
3332 $it.schema = $sch;
3333 $it.schemaPath = $schemaPath + '[' + $i + ']';
3334 $it.errSchemaPath = $errSchemaPath + '/' + $i;
3335 out += ' ' + (it.validate($it)) + ' ';
3336 $it.baseId = $currentBaseId;
3337 if ($breakOnError) {
3338 out += ' if (' + ($nextValid) + ') { ';
3339 $closingBraces += '}';
3340 }
3341 }
3342 }
3343 }
3344 if ($breakOnError) {
3345 if ($allSchemasEmpty) {
3346 out += ' if (true) { ';
3347 } else {
3348 out += ' ' + ($closingBraces.slice(0, -1)) + ' ';
3349 }
3350 }
3351 out = it.util.cleanUpCode(out);
3352 return out;
3353}
3354
3355},{}],22:[function(require,module,exports){
3356'use strict';
3357module.exports = function generate_anyOf(it, $keyword, $ruleType) {
3358 var out = ' ';
3359 var $lvl = it.level;
3360 var $dataLvl = it.dataLevel;
3361 var $schema = it.schema[$keyword];
3362 var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
3363 var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
3364 var $breakOnError = !it.opts.allErrors;
3365 var $data = 'data' + ($dataLvl || '');
3366 var $valid = 'valid' + $lvl;
3367 var $errs = 'errs__' + $lvl;
3368 var $it = it.util.copy(it);
3369 var $closingBraces = '';
3370 $it.level++;
3371 var $nextValid = 'valid' + $it.level;
3372 var $noEmptySchema = $schema.every(function($sch) {
3373 return it.util.schemaHasRules($sch, it.RULES.all);
3374 });
3375 if ($noEmptySchema) {
3376 var $currentBaseId = $it.baseId;
3377 out += ' var ' + ($errs) + ' = errors; var ' + ($valid) + ' = false; ';
3378 var $wasComposite = it.compositeRule;
3379 it.compositeRule = $it.compositeRule = true;
3380 var arr1 = $schema;
3381 if (arr1) {
3382 var $sch, $i = -1,
3383 l1 = arr1.length - 1;
3384 while ($i < l1) {
3385 $sch = arr1[$i += 1];
3386 $it.schema = $sch;
3387 $it.schemaPath = $schemaPath + '[' + $i + ']';
3388 $it.errSchemaPath = $errSchemaPath + '/' + $i;
3389 out += ' ' + (it.validate($it)) + ' ';
3390 $it.baseId = $currentBaseId;
3391 out += ' ' + ($valid) + ' = ' + ($valid) + ' || ' + ($nextValid) + '; if (!' + ($valid) + ') { ';
3392 $closingBraces += '}';
3393 }
3394 }
3395 it.compositeRule = $it.compositeRule = $wasComposite;
3396 out += ' ' + ($closingBraces) + ' if (!' + ($valid) + ') { var err = '; /* istanbul ignore else */
3397 if (it.createErrors !== false) {
3398 out += ' { keyword: \'' + ('anyOf') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} ';
3399 if (it.opts.messages !== false) {
3400 out += ' , message: \'should match some schema in anyOf\' ';
3401 }
3402 if (it.opts.verbose) {
3403 out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
3404 }
3405 out += ' } ';
3406 } else {
3407 out += ' {} ';
3408 }
3409 out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
3410 if (!it.compositeRule && $breakOnError) {
3411 /* istanbul ignore if */
3412 if (it.async) {
3413 out += ' throw new ValidationError(vErrors); ';
3414 } else {
3415 out += ' validate.errors = vErrors; return false; ';
3416 }
3417 }
3418 out += ' } else { errors = ' + ($errs) + '; if (vErrors !== null) { if (' + ($errs) + ') vErrors.length = ' + ($errs) + '; else vErrors = null; } ';
3419 if (it.opts.allErrors) {
3420 out += ' } ';
3421 }
3422 out = it.util.cleanUpCode(out);
3423 } else {
3424 if ($breakOnError) {
3425 out += ' if (true) { ';
3426 }
3427 }
3428 return out;
3429}
3430
3431},{}],23:[function(require,module,exports){
3432'use strict';
3433module.exports = function generate_comment(it, $keyword, $ruleType) {
3434 var out = ' ';
3435 var $schema = it.schema[$keyword];
3436 var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
3437 var $breakOnError = !it.opts.allErrors;
3438 var $comment = it.util.toQuotedString($schema);
3439 if (it.opts.$comment === true) {
3440 out += ' console.log(' + ($comment) + ');';
3441 } else if (typeof it.opts.$comment == 'function') {
3442 out += ' self._opts.$comment(' + ($comment) + ', ' + (it.util.toQuotedString($errSchemaPath)) + ', validate.root.schema);';
3443 }
3444 return out;
3445}
3446
3447},{}],24:[function(require,module,exports){
3448'use strict';
3449module.exports = function generate_const(it, $keyword, $ruleType) {
3450 var out = ' ';
3451 var $lvl = it.level;
3452 var $dataLvl = it.dataLevel;
3453 var $schema = it.schema[$keyword];
3454 var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
3455 var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
3456 var $breakOnError = !it.opts.allErrors;
3457 var $data = 'data' + ($dataLvl || '');
3458 var $valid = 'valid' + $lvl;
3459 var $isData = it.opts.$data && $schema && $schema.$data,
3460 $schemaValue;
3461 if ($isData) {
3462 out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; ';
3463 $schemaValue = 'schema' + $lvl;
3464 } else {
3465 $schemaValue = $schema;
3466 }
3467 if (!$isData) {
3468 out += ' var schema' + ($lvl) + ' = validate.schema' + ($schemaPath) + ';';
3469 }
3470 out += 'var ' + ($valid) + ' = equal(' + ($data) + ', schema' + ($lvl) + '); if (!' + ($valid) + ') { ';
3471 var $$outStack = $$outStack || [];
3472 $$outStack.push(out);
3473 out = ''; /* istanbul ignore else */
3474 if (it.createErrors !== false) {
3475 out += ' { keyword: \'' + ('const') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { allowedValue: schema' + ($lvl) + ' } ';
3476 if (it.opts.messages !== false) {
3477 out += ' , message: \'should be equal to constant\' ';
3478 }
3479 if (it.opts.verbose) {
3480 out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
3481 }
3482 out += ' } ';
3483 } else {
3484 out += ' {} ';
3485 }
3486 var __err = out;
3487 out = $$outStack.pop();
3488 if (!it.compositeRule && $breakOnError) {
3489 /* istanbul ignore if */
3490 if (it.async) {
3491 out += ' throw new ValidationError([' + (__err) + ']); ';
3492 } else {
3493 out += ' validate.errors = [' + (__err) + ']; return false; ';
3494 }
3495 } else {
3496 out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
3497 }
3498 out += ' }';
3499 if ($breakOnError) {
3500 out += ' else { ';
3501 }
3502 return out;
3503}
3504
3505},{}],25:[function(require,module,exports){
3506'use strict';
3507module.exports = function generate_contains(it, $keyword, $ruleType) {
3508 var out = ' ';
3509 var $lvl = it.level;
3510 var $dataLvl = it.dataLevel;
3511 var $schema = it.schema[$keyword];
3512 var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
3513 var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
3514 var $breakOnError = !it.opts.allErrors;
3515 var $data = 'data' + ($dataLvl || '');
3516 var $valid = 'valid' + $lvl;
3517 var $errs = 'errs__' + $lvl;
3518 var $it = it.util.copy(it);
3519 var $closingBraces = '';
3520 $it.level++;
3521 var $nextValid = 'valid' + $it.level;
3522 var $idx = 'i' + $lvl,
3523 $dataNxt = $it.dataLevel = it.dataLevel + 1,
3524 $nextData = 'data' + $dataNxt,
3525 $currentBaseId = it.baseId,
3526 $nonEmptySchema = it.util.schemaHasRules($schema, it.RULES.all);
3527 out += 'var ' + ($errs) + ' = errors;var ' + ($valid) + ';';
3528 if ($nonEmptySchema) {
3529 var $wasComposite = it.compositeRule;
3530 it.compositeRule = $it.compositeRule = true;
3531 $it.schema = $schema;
3532 $it.schemaPath = $schemaPath;
3533 $it.errSchemaPath = $errSchemaPath;
3534 out += ' var ' + ($nextValid) + ' = false; for (var ' + ($idx) + ' = 0; ' + ($idx) + ' < ' + ($data) + '.length; ' + ($idx) + '++) { ';
3535 $it.errorPath = it.util.getPathExpr(it.errorPath, $idx, it.opts.jsonPointers, true);
3536 var $passData = $data + '[' + $idx + ']';
3537 $it.dataPathArr[$dataNxt] = $idx;
3538 var $code = it.validate($it);
3539 $it.baseId = $currentBaseId;
3540 if (it.util.varOccurences($code, $nextData) < 2) {
3541 out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' ';
3542 } else {
3543 out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' ';
3544 }
3545 out += ' if (' + ($nextValid) + ') break; } ';
3546 it.compositeRule = $it.compositeRule = $wasComposite;
3547 out += ' ' + ($closingBraces) + ' if (!' + ($nextValid) + ') {';
3548 } else {
3549 out += ' if (' + ($data) + '.length == 0) {';
3550 }
3551 var $$outStack = $$outStack || [];
3552 $$outStack.push(out);
3553 out = ''; /* istanbul ignore else */
3554 if (it.createErrors !== false) {
3555 out += ' { keyword: \'' + ('contains') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} ';
3556 if (it.opts.messages !== false) {
3557 out += ' , message: \'should contain a valid item\' ';
3558 }
3559 if (it.opts.verbose) {
3560 out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
3561 }
3562 out += ' } ';
3563 } else {
3564 out += ' {} ';
3565 }
3566 var __err = out;
3567 out = $$outStack.pop();
3568 if (!it.compositeRule && $breakOnError) {
3569 /* istanbul ignore if */
3570 if (it.async) {
3571 out += ' throw new ValidationError([' + (__err) + ']); ';
3572 } else {
3573 out += ' validate.errors = [' + (__err) + ']; return false; ';
3574 }
3575 } else {
3576 out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
3577 }
3578 out += ' } else { ';
3579 if ($nonEmptySchema) {
3580 out += ' errors = ' + ($errs) + '; if (vErrors !== null) { if (' + ($errs) + ') vErrors.length = ' + ($errs) + '; else vErrors = null; } ';
3581 }
3582 if (it.opts.allErrors) {
3583 out += ' } ';
3584 }
3585 out = it.util.cleanUpCode(out);
3586 return out;
3587}
3588
3589},{}],26:[function(require,module,exports){
3590'use strict';
3591module.exports = function generate_custom(it, $keyword, $ruleType) {
3592 var out = ' ';
3593 var $lvl = it.level;
3594 var $dataLvl = it.dataLevel;
3595 var $schema = it.schema[$keyword];
3596 var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
3597 var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
3598 var $breakOnError = !it.opts.allErrors;
3599 var $errorKeyword;
3600 var $data = 'data' + ($dataLvl || '');
3601 var $valid = 'valid' + $lvl;
3602 var $errs = 'errs__' + $lvl;
3603 var $isData = it.opts.$data && $schema && $schema.$data,
3604 $schemaValue;
3605 if ($isData) {
3606 out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; ';
3607 $schemaValue = 'schema' + $lvl;
3608 } else {
3609 $schemaValue = $schema;
3610 }
3611 var $rule = this,
3612 $definition = 'definition' + $lvl,
3613 $rDef = $rule.definition,
3614 $closingBraces = '';
3615 var $compile, $inline, $macro, $ruleValidate, $validateCode;
3616 if ($isData && $rDef.$data) {
3617 $validateCode = 'keywordValidate' + $lvl;
3618 var $validateSchema = $rDef.validateSchema;
3619 out += ' var ' + ($definition) + ' = RULES.custom[\'' + ($keyword) + '\'].definition; var ' + ($validateCode) + ' = ' + ($definition) + '.validate;';
3620 } else {
3621 $ruleValidate = it.useCustomRule($rule, $schema, it.schema, it);
3622 if (!$ruleValidate) return;
3623 $schemaValue = 'validate.schema' + $schemaPath;
3624 $validateCode = $ruleValidate.code;
3625 $compile = $rDef.compile;
3626 $inline = $rDef.inline;
3627 $macro = $rDef.macro;
3628 }
3629 var $ruleErrs = $validateCode + '.errors',
3630 $i = 'i' + $lvl,
3631 $ruleErr = 'ruleErr' + $lvl,
3632 $asyncKeyword = $rDef.async;
3633 if ($asyncKeyword && !it.async) throw new Error('async keyword in sync schema');
3634 if (!($inline || $macro)) {
3635 out += '' + ($ruleErrs) + ' = null;';
3636 }
3637 out += 'var ' + ($errs) + ' = errors;var ' + ($valid) + ';';
3638 if ($isData && $rDef.$data) {
3639 $closingBraces += '}';
3640 out += ' if (' + ($schemaValue) + ' === undefined) { ' + ($valid) + ' = true; } else { ';
3641 if ($validateSchema) {
3642 $closingBraces += '}';
3643 out += ' ' + ($valid) + ' = ' + ($definition) + '.validateSchema(' + ($schemaValue) + '); if (' + ($valid) + ') { ';
3644 }
3645 }
3646 if ($inline) {
3647 if ($rDef.statements) {
3648 out += ' ' + ($ruleValidate.validate) + ' ';
3649 } else {
3650 out += ' ' + ($valid) + ' = ' + ($ruleValidate.validate) + '; ';
3651 }
3652 } else if ($macro) {
3653 var $it = it.util.copy(it);
3654 var $closingBraces = '';
3655 $it.level++;
3656 var $nextValid = 'valid' + $it.level;
3657 $it.schema = $ruleValidate.validate;
3658 $it.schemaPath = '';
3659 var $wasComposite = it.compositeRule;
3660 it.compositeRule = $it.compositeRule = true;
3661 var $code = it.validate($it).replace(/validate\.schema/g, $validateCode);
3662 it.compositeRule = $it.compositeRule = $wasComposite;
3663 out += ' ' + ($code);
3664 } else {
3665 var $$outStack = $$outStack || [];
3666 $$outStack.push(out);
3667 out = '';
3668 out += ' ' + ($validateCode) + '.call( ';
3669 if (it.opts.passContext) {
3670 out += 'this';
3671 } else {
3672 out += 'self';
3673 }
3674 if ($compile || $rDef.schema === false) {
3675 out += ' , ' + ($data) + ' ';
3676 } else {
3677 out += ' , ' + ($schemaValue) + ' , ' + ($data) + ' , validate.schema' + (it.schemaPath) + ' ';
3678 }
3679 out += ' , (dataPath || \'\')';
3680 if (it.errorPath != '""') {
3681 out += ' + ' + (it.errorPath);
3682 }
3683 var $parentData = $dataLvl ? 'data' + (($dataLvl - 1) || '') : 'parentData',
3684 $parentDataProperty = $dataLvl ? it.dataPathArr[$dataLvl] : 'parentDataProperty';
3685 out += ' , ' + ($parentData) + ' , ' + ($parentDataProperty) + ' , rootData ) ';
3686 var def_callRuleValidate = out;
3687 out = $$outStack.pop();
3688 if ($rDef.errors === false) {
3689 out += ' ' + ($valid) + ' = ';
3690 if ($asyncKeyword) {
3691 out += 'await ';
3692 }
3693 out += '' + (def_callRuleValidate) + '; ';
3694 } else {
3695 if ($asyncKeyword) {
3696 $ruleErrs = 'customErrors' + $lvl;
3697 out += ' var ' + ($ruleErrs) + ' = null; try { ' + ($valid) + ' = await ' + (def_callRuleValidate) + '; } catch (e) { ' + ($valid) + ' = false; if (e instanceof ValidationError) ' + ($ruleErrs) + ' = e.errors; else throw e; } ';
3698 } else {
3699 out += ' ' + ($ruleErrs) + ' = null; ' + ($valid) + ' = ' + (def_callRuleValidate) + '; ';
3700 }
3701 }
3702 }
3703 if ($rDef.modifying) {
3704 out += ' if (' + ($parentData) + ') ' + ($data) + ' = ' + ($parentData) + '[' + ($parentDataProperty) + '];';
3705 }
3706 out += '' + ($closingBraces);
3707 if ($rDef.valid) {
3708 if ($breakOnError) {
3709 out += ' if (true) { ';
3710 }
3711 } else {
3712 out += ' if ( ';
3713 if ($rDef.valid === undefined) {
3714 out += ' !';
3715 if ($macro) {
3716 out += '' + ($nextValid);
3717 } else {
3718 out += '' + ($valid);
3719 }
3720 } else {
3721 out += ' ' + (!$rDef.valid) + ' ';
3722 }
3723 out += ') { ';
3724 $errorKeyword = $rule.keyword;
3725 var $$outStack = $$outStack || [];
3726 $$outStack.push(out);
3727 out = '';
3728 var $$outStack = $$outStack || [];
3729 $$outStack.push(out);
3730 out = ''; /* istanbul ignore else */
3731 if (it.createErrors !== false) {
3732 out += ' { keyword: \'' + ($errorKeyword || 'custom') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { keyword: \'' + ($rule.keyword) + '\' } ';
3733 if (it.opts.messages !== false) {
3734 out += ' , message: \'should pass "' + ($rule.keyword) + '" keyword validation\' ';
3735 }
3736 if (it.opts.verbose) {
3737 out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
3738 }
3739 out += ' } ';
3740 } else {
3741 out += ' {} ';
3742 }
3743 var __err = out;
3744 out = $$outStack.pop();
3745 if (!it.compositeRule && $breakOnError) {
3746 /* istanbul ignore if */
3747 if (it.async) {
3748 out += ' throw new ValidationError([' + (__err) + ']); ';
3749 } else {
3750 out += ' validate.errors = [' + (__err) + ']; return false; ';
3751 }
3752 } else {
3753 out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
3754 }
3755 var def_customError = out;
3756 out = $$outStack.pop();
3757 if ($inline) {
3758 if ($rDef.errors) {
3759 if ($rDef.errors != 'full') {
3760 out += ' for (var ' + ($i) + '=' + ($errs) + '; ' + ($i) + '<errors; ' + ($i) + '++) { var ' + ($ruleErr) + ' = vErrors[' + ($i) + ']; if (' + ($ruleErr) + '.dataPath === undefined) ' + ($ruleErr) + '.dataPath = (dataPath || \'\') + ' + (it.errorPath) + '; if (' + ($ruleErr) + '.schemaPath === undefined) { ' + ($ruleErr) + '.schemaPath = "' + ($errSchemaPath) + '"; } ';
3761 if (it.opts.verbose) {
3762 out += ' ' + ($ruleErr) + '.schema = ' + ($schemaValue) + '; ' + ($ruleErr) + '.data = ' + ($data) + '; ';
3763 }
3764 out += ' } ';
3765 }
3766 } else {
3767 if ($rDef.errors === false) {
3768 out += ' ' + (def_customError) + ' ';
3769 } else {
3770 out += ' if (' + ($errs) + ' == errors) { ' + (def_customError) + ' } else { for (var ' + ($i) + '=' + ($errs) + '; ' + ($i) + '<errors; ' + ($i) + '++) { var ' + ($ruleErr) + ' = vErrors[' + ($i) + ']; if (' + ($ruleErr) + '.dataPath === undefined) ' + ($ruleErr) + '.dataPath = (dataPath || \'\') + ' + (it.errorPath) + '; if (' + ($ruleErr) + '.schemaPath === undefined) { ' + ($ruleErr) + '.schemaPath = "' + ($errSchemaPath) + '"; } ';
3771 if (it.opts.verbose) {
3772 out += ' ' + ($ruleErr) + '.schema = ' + ($schemaValue) + '; ' + ($ruleErr) + '.data = ' + ($data) + '; ';
3773 }
3774 out += ' } } ';
3775 }
3776 }
3777 } else if ($macro) {
3778 out += ' var err = '; /* istanbul ignore else */
3779 if (it.createErrors !== false) {
3780 out += ' { keyword: \'' + ($errorKeyword || 'custom') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { keyword: \'' + ($rule.keyword) + '\' } ';
3781 if (it.opts.messages !== false) {
3782 out += ' , message: \'should pass "' + ($rule.keyword) + '" keyword validation\' ';
3783 }
3784 if (it.opts.verbose) {
3785 out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
3786 }
3787 out += ' } ';
3788 } else {
3789 out += ' {} ';
3790 }
3791 out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
3792 if (!it.compositeRule && $breakOnError) {
3793 /* istanbul ignore if */
3794 if (it.async) {
3795 out += ' throw new ValidationError(vErrors); ';
3796 } else {
3797 out += ' validate.errors = vErrors; return false; ';
3798 }
3799 }
3800 } else {
3801 if ($rDef.errors === false) {
3802 out += ' ' + (def_customError) + ' ';
3803 } else {
3804 out += ' if (Array.isArray(' + ($ruleErrs) + ')) { if (vErrors === null) vErrors = ' + ($ruleErrs) + '; else vErrors = vErrors.concat(' + ($ruleErrs) + '); errors = vErrors.length; for (var ' + ($i) + '=' + ($errs) + '; ' + ($i) + '<errors; ' + ($i) + '++) { var ' + ($ruleErr) + ' = vErrors[' + ($i) + ']; if (' + ($ruleErr) + '.dataPath === undefined) ' + ($ruleErr) + '.dataPath = (dataPath || \'\') + ' + (it.errorPath) + '; ' + ($ruleErr) + '.schemaPath = "' + ($errSchemaPath) + '"; ';
3805 if (it.opts.verbose) {
3806 out += ' ' + ($ruleErr) + '.schema = ' + ($schemaValue) + '; ' + ($ruleErr) + '.data = ' + ($data) + '; ';
3807 }
3808 out += ' } } else { ' + (def_customError) + ' } ';
3809 }
3810 }
3811 out += ' } ';
3812 if ($breakOnError) {
3813 out += ' else { ';
3814 }
3815 }
3816 return out;
3817}
3818
3819},{}],27:[function(require,module,exports){
3820'use strict';
3821module.exports = function generate_dependencies(it, $keyword, $ruleType) {
3822 var out = ' ';
3823 var $lvl = it.level;
3824 var $dataLvl = it.dataLevel;
3825 var $schema = it.schema[$keyword];
3826 var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
3827 var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
3828 var $breakOnError = !it.opts.allErrors;
3829 var $data = 'data' + ($dataLvl || '');
3830 var $errs = 'errs__' + $lvl;
3831 var $it = it.util.copy(it);
3832 var $closingBraces = '';
3833 $it.level++;
3834 var $nextValid = 'valid' + $it.level;
3835 var $schemaDeps = {},
3836 $propertyDeps = {},
3837 $ownProperties = it.opts.ownProperties;
3838 for ($property in $schema) {
3839 var $sch = $schema[$property];
3840 var $deps = Array.isArray($sch) ? $propertyDeps : $schemaDeps;
3841 $deps[$property] = $sch;
3842 }
3843 out += 'var ' + ($errs) + ' = errors;';
3844 var $currentErrorPath = it.errorPath;
3845 out += 'var missing' + ($lvl) + ';';
3846 for (var $property in $propertyDeps) {
3847 $deps = $propertyDeps[$property];
3848 if ($deps.length) {
3849 out += ' if ( ' + ($data) + (it.util.getProperty($property)) + ' !== undefined ';
3850 if ($ownProperties) {
3851 out += ' && Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($property)) + '\') ';
3852 }
3853 if ($breakOnError) {
3854 out += ' && ( ';
3855 var arr1 = $deps;
3856 if (arr1) {
3857 var $propertyKey, $i = -1,
3858 l1 = arr1.length - 1;
3859 while ($i < l1) {
3860 $propertyKey = arr1[$i += 1];
3861 if ($i) {
3862 out += ' || ';
3863 }
3864 var $prop = it.util.getProperty($propertyKey),
3865 $useData = $data + $prop;
3866 out += ' ( ( ' + ($useData) + ' === undefined ';
3867 if ($ownProperties) {
3868 out += ' || ! Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($propertyKey)) + '\') ';
3869 }
3870 out += ') && (missing' + ($lvl) + ' = ' + (it.util.toQuotedString(it.opts.jsonPointers ? $propertyKey : $prop)) + ') ) ';
3871 }
3872 }
3873 out += ')) { ';
3874 var $propertyPath = 'missing' + $lvl,
3875 $missingProperty = '\' + ' + $propertyPath + ' + \'';
3876 if (it.opts._errorDataPathProperty) {
3877 it.errorPath = it.opts.jsonPointers ? it.util.getPathExpr($currentErrorPath, $propertyPath, true) : $currentErrorPath + ' + ' + $propertyPath;
3878 }
3879 var $$outStack = $$outStack || [];
3880 $$outStack.push(out);
3881 out = ''; /* istanbul ignore else */
3882 if (it.createErrors !== false) {
3883 out += ' { keyword: \'' + ('dependencies') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { property: \'' + (it.util.escapeQuotes($property)) + '\', missingProperty: \'' + ($missingProperty) + '\', depsCount: ' + ($deps.length) + ', deps: \'' + (it.util.escapeQuotes($deps.length == 1 ? $deps[0] : $deps.join(", "))) + '\' } ';
3884 if (it.opts.messages !== false) {
3885 out += ' , message: \'should have ';
3886 if ($deps.length == 1) {
3887 out += 'property ' + (it.util.escapeQuotes($deps[0]));
3888 } else {
3889 out += 'properties ' + (it.util.escapeQuotes($deps.join(", ")));
3890 }
3891 out += ' when property ' + (it.util.escapeQuotes($property)) + ' is present\' ';
3892 }
3893 if (it.opts.verbose) {
3894 out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
3895 }
3896 out += ' } ';
3897 } else {
3898 out += ' {} ';
3899 }
3900 var __err = out;
3901 out = $$outStack.pop();
3902 if (!it.compositeRule && $breakOnError) {
3903 /* istanbul ignore if */
3904 if (it.async) {
3905 out += ' throw new ValidationError([' + (__err) + ']); ';
3906 } else {
3907 out += ' validate.errors = [' + (__err) + ']; return false; ';
3908 }
3909 } else {
3910 out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
3911 }
3912 } else {
3913 out += ' ) { ';
3914 var arr2 = $deps;
3915 if (arr2) {
3916 var $propertyKey, i2 = -1,
3917 l2 = arr2.length - 1;
3918 while (i2 < l2) {
3919 $propertyKey = arr2[i2 += 1];
3920 var $prop = it.util.getProperty($propertyKey),
3921 $missingProperty = it.util.escapeQuotes($propertyKey),
3922 $useData = $data + $prop;
3923 if (it.opts._errorDataPathProperty) {
3924 it.errorPath = it.util.getPath($currentErrorPath, $propertyKey, it.opts.jsonPointers);
3925 }
3926 out += ' if ( ' + ($useData) + ' === undefined ';
3927 if ($ownProperties) {
3928 out += ' || ! Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($propertyKey)) + '\') ';
3929 }
3930 out += ') { var err = '; /* istanbul ignore else */
3931 if (it.createErrors !== false) {
3932 out += ' { keyword: \'' + ('dependencies') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { property: \'' + (it.util.escapeQuotes($property)) + '\', missingProperty: \'' + ($missingProperty) + '\', depsCount: ' + ($deps.length) + ', deps: \'' + (it.util.escapeQuotes($deps.length == 1 ? $deps[0] : $deps.join(", "))) + '\' } ';
3933 if (it.opts.messages !== false) {
3934 out += ' , message: \'should have ';
3935 if ($deps.length == 1) {
3936 out += 'property ' + (it.util.escapeQuotes($deps[0]));
3937 } else {
3938 out += 'properties ' + (it.util.escapeQuotes($deps.join(", ")));
3939 }
3940 out += ' when property ' + (it.util.escapeQuotes($property)) + ' is present\' ';
3941 }
3942 if (it.opts.verbose) {
3943 out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
3944 }
3945 out += ' } ';
3946 } else {
3947 out += ' {} ';
3948 }
3949 out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } ';
3950 }
3951 }
3952 }
3953 out += ' } ';
3954 if ($breakOnError) {
3955 $closingBraces += '}';
3956 out += ' else { ';
3957 }
3958 }
3959 }
3960 it.errorPath = $currentErrorPath;
3961 var $currentBaseId = $it.baseId;
3962 for (var $property in $schemaDeps) {
3963 var $sch = $schemaDeps[$property];
3964 if (it.util.schemaHasRules($sch, it.RULES.all)) {
3965 out += ' ' + ($nextValid) + ' = true; if ( ' + ($data) + (it.util.getProperty($property)) + ' !== undefined ';
3966 if ($ownProperties) {
3967 out += ' && Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($property)) + '\') ';
3968 }
3969 out += ') { ';
3970 $it.schema = $sch;
3971 $it.schemaPath = $schemaPath + it.util.getProperty($property);
3972 $it.errSchemaPath = $errSchemaPath + '/' + it.util.escapeFragment($property);
3973 out += ' ' + (it.validate($it)) + ' ';
3974 $it.baseId = $currentBaseId;
3975 out += ' } ';
3976 if ($breakOnError) {
3977 out += ' if (' + ($nextValid) + ') { ';
3978 $closingBraces += '}';
3979 }
3980 }
3981 }
3982 if ($breakOnError) {
3983 out += ' ' + ($closingBraces) + ' if (' + ($errs) + ' == errors) {';
3984 }
3985 out = it.util.cleanUpCode(out);
3986 return out;
3987}
3988
3989},{}],28:[function(require,module,exports){
3990'use strict';
3991module.exports = function generate_enum(it, $keyword, $ruleType) {
3992 var out = ' ';
3993 var $lvl = it.level;
3994 var $dataLvl = it.dataLevel;
3995 var $schema = it.schema[$keyword];
3996 var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
3997 var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
3998 var $breakOnError = !it.opts.allErrors;
3999 var $data = 'data' + ($dataLvl || '');
4000 var $valid = 'valid' + $lvl;
4001 var $isData = it.opts.$data && $schema && $schema.$data,
4002 $schemaValue;
4003 if ($isData) {
4004 out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; ';
4005 $schemaValue = 'schema' + $lvl;
4006 } else {
4007 $schemaValue = $schema;
4008 }
4009 var $i = 'i' + $lvl,
4010 $vSchema = 'schema' + $lvl;
4011 if (!$isData) {
4012 out += ' var ' + ($vSchema) + ' = validate.schema' + ($schemaPath) + ';';
4013 }
4014 out += 'var ' + ($valid) + ';';
4015 if ($isData) {
4016 out += ' if (schema' + ($lvl) + ' === undefined) ' + ($valid) + ' = true; else if (!Array.isArray(schema' + ($lvl) + ')) ' + ($valid) + ' = false; else {';
4017 }
4018 out += '' + ($valid) + ' = false;for (var ' + ($i) + '=0; ' + ($i) + '<' + ($vSchema) + '.length; ' + ($i) + '++) if (equal(' + ($data) + ', ' + ($vSchema) + '[' + ($i) + '])) { ' + ($valid) + ' = true; break; }';
4019 if ($isData) {
4020 out += ' } ';
4021 }
4022 out += ' if (!' + ($valid) + ') { ';
4023 var $$outStack = $$outStack || [];
4024 $$outStack.push(out);
4025 out = ''; /* istanbul ignore else */
4026 if (it.createErrors !== false) {
4027 out += ' { keyword: \'' + ('enum') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { allowedValues: schema' + ($lvl) + ' } ';
4028 if (it.opts.messages !== false) {
4029 out += ' , message: \'should be equal to one of the allowed values\' ';
4030 }
4031 if (it.opts.verbose) {
4032 out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
4033 }
4034 out += ' } ';
4035 } else {
4036 out += ' {} ';
4037 }
4038 var __err = out;
4039 out = $$outStack.pop();
4040 if (!it.compositeRule && $breakOnError) {
4041 /* istanbul ignore if */
4042 if (it.async) {
4043 out += ' throw new ValidationError([' + (__err) + ']); ';
4044 } else {
4045 out += ' validate.errors = [' + (__err) + ']; return false; ';
4046 }
4047 } else {
4048 out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
4049 }
4050 out += ' }';
4051 if ($breakOnError) {
4052 out += ' else { ';
4053 }
4054 return out;
4055}
4056
4057},{}],29:[function(require,module,exports){
4058'use strict';
4059module.exports = function generate_format(it, $keyword, $ruleType) {
4060 var out = ' ';
4061 var $lvl = it.level;
4062 var $dataLvl = it.dataLevel;
4063 var $schema = it.schema[$keyword];
4064 var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
4065 var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
4066 var $breakOnError = !it.opts.allErrors;
4067 var $data = 'data' + ($dataLvl || '');
4068 if (it.opts.format === false) {
4069 if ($breakOnError) {
4070 out += ' if (true) { ';
4071 }
4072 return out;
4073 }
4074 var $isData = it.opts.$data && $schema && $schema.$data,
4075 $schemaValue;
4076 if ($isData) {
4077 out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; ';
4078 $schemaValue = 'schema' + $lvl;
4079 } else {
4080 $schemaValue = $schema;
4081 }
4082 var $unknownFormats = it.opts.unknownFormats,
4083 $allowUnknown = Array.isArray($unknownFormats);
4084 if ($isData) {
4085 var $format = 'format' + $lvl,
4086 $isObject = 'isObject' + $lvl,
4087 $formatType = 'formatType' + $lvl;
4088 out += ' var ' + ($format) + ' = formats[' + ($schemaValue) + ']; var ' + ($isObject) + ' = typeof ' + ($format) + ' == \'object\' && !(' + ($format) + ' instanceof RegExp) && ' + ($format) + '.validate; var ' + ($formatType) + ' = ' + ($isObject) + ' && ' + ($format) + '.type || \'string\'; if (' + ($isObject) + ') { ';
4089 if (it.async) {
4090 out += ' var async' + ($lvl) + ' = ' + ($format) + '.async; ';
4091 }
4092 out += ' ' + ($format) + ' = ' + ($format) + '.validate; } if ( ';
4093 if ($isData) {
4094 out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'string\') || ';
4095 }
4096 out += ' (';
4097 if ($unknownFormats != 'ignore') {
4098 out += ' (' + ($schemaValue) + ' && !' + ($format) + ' ';
4099 if ($allowUnknown) {
4100 out += ' && self._opts.unknownFormats.indexOf(' + ($schemaValue) + ') == -1 ';
4101 }
4102 out += ') || ';
4103 }
4104 out += ' (' + ($format) + ' && ' + ($formatType) + ' == \'' + ($ruleType) + '\' && !(typeof ' + ($format) + ' == \'function\' ? ';
4105 if (it.async) {
4106 out += ' (async' + ($lvl) + ' ? await ' + ($format) + '(' + ($data) + ') : ' + ($format) + '(' + ($data) + ')) ';
4107 } else {
4108 out += ' ' + ($format) + '(' + ($data) + ') ';
4109 }
4110 out += ' : ' + ($format) + '.test(' + ($data) + '))))) {';
4111 } else {
4112 var $format = it.formats[$schema];
4113 if (!$format) {
4114 if ($unknownFormats == 'ignore') {
4115 it.logger.warn('unknown format "' + $schema + '" ignored in schema at path "' + it.errSchemaPath + '"');
4116 if ($breakOnError) {
4117 out += ' if (true) { ';
4118 }
4119 return out;
4120 } else if ($allowUnknown && $unknownFormats.indexOf($schema) >= 0) {
4121 if ($breakOnError) {
4122 out += ' if (true) { ';
4123 }
4124 return out;
4125 } else {
4126 throw new Error('unknown format "' + $schema + '" is used in schema at path "' + it.errSchemaPath + '"');
4127 }
4128 }
4129 var $isObject = typeof $format == 'object' && !($format instanceof RegExp) && $format.validate;
4130 var $formatType = $isObject && $format.type || 'string';
4131 if ($isObject) {
4132 var $async = $format.async === true;
4133 $format = $format.validate;
4134 }
4135 if ($formatType != $ruleType) {
4136 if ($breakOnError) {
4137 out += ' if (true) { ';
4138 }
4139 return out;
4140 }
4141 if ($async) {
4142 if (!it.async) throw new Error('async format in sync schema');
4143 var $formatRef = 'formats' + it.util.getProperty($schema) + '.validate';
4144 out += ' if (!(await ' + ($formatRef) + '(' + ($data) + '))) { ';
4145 } else {
4146 out += ' if (! ';
4147 var $formatRef = 'formats' + it.util.getProperty($schema);
4148 if ($isObject) $formatRef += '.validate';
4149 if (typeof $format == 'function') {
4150 out += ' ' + ($formatRef) + '(' + ($data) + ') ';
4151 } else {
4152 out += ' ' + ($formatRef) + '.test(' + ($data) + ') ';
4153 }
4154 out += ') { ';
4155 }
4156 }
4157 var $$outStack = $$outStack || [];
4158 $$outStack.push(out);
4159 out = ''; /* istanbul ignore else */
4160 if (it.createErrors !== false) {
4161 out += ' { keyword: \'' + ('format') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { format: ';
4162 if ($isData) {
4163 out += '' + ($schemaValue);
4164 } else {
4165 out += '' + (it.util.toQuotedString($schema));
4166 }
4167 out += ' } ';
4168 if (it.opts.messages !== false) {
4169 out += ' , message: \'should match format "';
4170 if ($isData) {
4171 out += '\' + ' + ($schemaValue) + ' + \'';
4172 } else {
4173 out += '' + (it.util.escapeQuotes($schema));
4174 }
4175 out += '"\' ';
4176 }
4177 if (it.opts.verbose) {
4178 out += ' , schema: ';
4179 if ($isData) {
4180 out += 'validate.schema' + ($schemaPath);
4181 } else {
4182 out += '' + (it.util.toQuotedString($schema));
4183 }
4184 out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
4185 }
4186 out += ' } ';
4187 } else {
4188 out += ' {} ';
4189 }
4190 var __err = out;
4191 out = $$outStack.pop();
4192 if (!it.compositeRule && $breakOnError) {
4193 /* istanbul ignore if */
4194 if (it.async) {
4195 out += ' throw new ValidationError([' + (__err) + ']); ';
4196 } else {
4197 out += ' validate.errors = [' + (__err) + ']; return false; ';
4198 }
4199 } else {
4200 out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
4201 }
4202 out += ' } ';
4203 if ($breakOnError) {
4204 out += ' else { ';
4205 }
4206 return out;
4207}
4208
4209},{}],30:[function(require,module,exports){
4210'use strict';
4211module.exports = function generate_if(it, $keyword, $ruleType) {
4212 var out = ' ';
4213 var $lvl = it.level;
4214 var $dataLvl = it.dataLevel;
4215 var $schema = it.schema[$keyword];
4216 var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
4217 var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
4218 var $breakOnError = !it.opts.allErrors;
4219 var $data = 'data' + ($dataLvl || '');
4220 var $valid = 'valid' + $lvl;
4221 var $errs = 'errs__' + $lvl;
4222 var $it = it.util.copy(it);
4223 $it.level++;
4224 var $nextValid = 'valid' + $it.level;
4225 var $thenSch = it.schema['then'],
4226 $elseSch = it.schema['else'],
4227 $thenPresent = $thenSch !== undefined && it.util.schemaHasRules($thenSch, it.RULES.all),
4228 $elsePresent = $elseSch !== undefined && it.util.schemaHasRules($elseSch, it.RULES.all),
4229 $currentBaseId = $it.baseId;
4230 if ($thenPresent || $elsePresent) {
4231 var $ifClause;
4232 $it.createErrors = false;
4233 $it.schema = $schema;
4234 $it.schemaPath = $schemaPath;
4235 $it.errSchemaPath = $errSchemaPath;
4236 out += ' var ' + ($errs) + ' = errors; var ' + ($valid) + ' = true; ';
4237 var $wasComposite = it.compositeRule;
4238 it.compositeRule = $it.compositeRule = true;
4239 out += ' ' + (it.validate($it)) + ' ';
4240 $it.baseId = $currentBaseId;
4241 $it.createErrors = true;
4242 out += ' errors = ' + ($errs) + '; if (vErrors !== null) { if (' + ($errs) + ') vErrors.length = ' + ($errs) + '; else vErrors = null; } ';
4243 it.compositeRule = $it.compositeRule = $wasComposite;
4244 if ($thenPresent) {
4245 out += ' if (' + ($nextValid) + ') { ';
4246 $it.schema = it.schema['then'];
4247 $it.schemaPath = it.schemaPath + '.then';
4248 $it.errSchemaPath = it.errSchemaPath + '/then';
4249 out += ' ' + (it.validate($it)) + ' ';
4250 $it.baseId = $currentBaseId;
4251 out += ' ' + ($valid) + ' = ' + ($nextValid) + '; ';
4252 if ($thenPresent && $elsePresent) {
4253 $ifClause = 'ifClause' + $lvl;
4254 out += ' var ' + ($ifClause) + ' = \'then\'; ';
4255 } else {
4256 $ifClause = '\'then\'';
4257 }
4258 out += ' } ';
4259 if ($elsePresent) {
4260 out += ' else { ';
4261 }
4262 } else {
4263 out += ' if (!' + ($nextValid) + ') { ';
4264 }
4265 if ($elsePresent) {
4266 $it.schema = it.schema['else'];
4267 $it.schemaPath = it.schemaPath + '.else';
4268 $it.errSchemaPath = it.errSchemaPath + '/else';
4269 out += ' ' + (it.validate($it)) + ' ';
4270 $it.baseId = $currentBaseId;
4271 out += ' ' + ($valid) + ' = ' + ($nextValid) + '; ';
4272 if ($thenPresent && $elsePresent) {
4273 $ifClause = 'ifClause' + $lvl;
4274 out += ' var ' + ($ifClause) + ' = \'else\'; ';
4275 } else {
4276 $ifClause = '\'else\'';
4277 }
4278 out += ' } ';
4279 }
4280 out += ' if (!' + ($valid) + ') { var err = '; /* istanbul ignore else */
4281 if (it.createErrors !== false) {
4282 out += ' { keyword: \'' + ('if') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { failingKeyword: ' + ($ifClause) + ' } ';
4283 if (it.opts.messages !== false) {
4284 out += ' , message: \'should match "\' + ' + ($ifClause) + ' + \'" schema\' ';
4285 }
4286 if (it.opts.verbose) {
4287 out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
4288 }
4289 out += ' } ';
4290 } else {
4291 out += ' {} ';
4292 }
4293 out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
4294 if (!it.compositeRule && $breakOnError) {
4295 /* istanbul ignore if */
4296 if (it.async) {
4297 out += ' throw new ValidationError(vErrors); ';
4298 } else {
4299 out += ' validate.errors = vErrors; return false; ';
4300 }
4301 }
4302 out += ' } ';
4303 if ($breakOnError) {
4304 out += ' else { ';
4305 }
4306 out = it.util.cleanUpCode(out);
4307 } else {
4308 if ($breakOnError) {
4309 out += ' if (true) { ';
4310 }
4311 }
4312 return out;
4313}
4314
4315},{}],31:[function(require,module,exports){
4316'use strict';
4317
4318//all requires must be explicit because browserify won't work with dynamic requires
4319module.exports = {
4320 '$ref': require('./ref'),
4321 allOf: require('./allOf'),
4322 anyOf: require('./anyOf'),
4323 '$comment': require('./comment'),
4324 const: require('./const'),
4325 contains: require('./contains'),
4326 dependencies: require('./dependencies'),
4327 'enum': require('./enum'),
4328 format: require('./format'),
4329 'if': require('./if'),
4330 items: require('./items'),
4331 maximum: require('./_limit'),
4332 minimum: require('./_limit'),
4333 maxItems: require('./_limitItems'),
4334 minItems: require('./_limitItems'),
4335 maxLength: require('./_limitLength'),
4336 minLength: require('./_limitLength'),
4337 maxProperties: require('./_limitProperties'),
4338 minProperties: require('./_limitProperties'),
4339 multipleOf: require('./multipleOf'),
4340 not: require('./not'),
4341 oneOf: require('./oneOf'),
4342 pattern: require('./pattern'),
4343 properties: require('./properties'),
4344 propertyNames: require('./propertyNames'),
4345 required: require('./required'),
4346 uniqueItems: require('./uniqueItems'),
4347 validate: require('./validate')
4348};
4349
4350},{"./_limit":17,"./_limitItems":18,"./_limitLength":19,"./_limitProperties":20,"./allOf":21,"./anyOf":22,"./comment":23,"./const":24,"./contains":25,"./dependencies":27,"./enum":28,"./format":29,"./if":30,"./items":32,"./multipleOf":33,"./not":34,"./oneOf":35,"./pattern":36,"./properties":37,"./propertyNames":38,"./ref":39,"./required":40,"./uniqueItems":41,"./validate":42}],32:[function(require,module,exports){
4351'use strict';
4352module.exports = function generate_items(it, $keyword, $ruleType) {
4353 var out = ' ';
4354 var $lvl = it.level;
4355 var $dataLvl = it.dataLevel;
4356 var $schema = it.schema[$keyword];
4357 var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
4358 var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
4359 var $breakOnError = !it.opts.allErrors;
4360 var $data = 'data' + ($dataLvl || '');
4361 var $valid = 'valid' + $lvl;
4362 var $errs = 'errs__' + $lvl;
4363 var $it = it.util.copy(it);
4364 var $closingBraces = '';
4365 $it.level++;
4366 var $nextValid = 'valid' + $it.level;
4367 var $idx = 'i' + $lvl,
4368 $dataNxt = $it.dataLevel = it.dataLevel + 1,
4369 $nextData = 'data' + $dataNxt,
4370 $currentBaseId = it.baseId;
4371 out += 'var ' + ($errs) + ' = errors;var ' + ($valid) + ';';
4372 if (Array.isArray($schema)) {
4373 var $additionalItems = it.schema.additionalItems;
4374 if ($additionalItems === false) {
4375 out += ' ' + ($valid) + ' = ' + ($data) + '.length <= ' + ($schema.length) + '; ';
4376 var $currErrSchemaPath = $errSchemaPath;
4377 $errSchemaPath = it.errSchemaPath + '/additionalItems';
4378 out += ' if (!' + ($valid) + ') { ';
4379 var $$outStack = $$outStack || [];
4380 $$outStack.push(out);
4381 out = ''; /* istanbul ignore else */
4382 if (it.createErrors !== false) {
4383 out += ' { keyword: \'' + ('additionalItems') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { limit: ' + ($schema.length) + ' } ';
4384 if (it.opts.messages !== false) {
4385 out += ' , message: \'should NOT have more than ' + ($schema.length) + ' items\' ';
4386 }
4387 if (it.opts.verbose) {
4388 out += ' , schema: false , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
4389 }
4390 out += ' } ';
4391 } else {
4392 out += ' {} ';
4393 }
4394 var __err = out;
4395 out = $$outStack.pop();
4396 if (!it.compositeRule && $breakOnError) {
4397 /* istanbul ignore if */
4398 if (it.async) {
4399 out += ' throw new ValidationError([' + (__err) + ']); ';
4400 } else {
4401 out += ' validate.errors = [' + (__err) + ']; return false; ';
4402 }
4403 } else {
4404 out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
4405 }
4406 out += ' } ';
4407 $errSchemaPath = $currErrSchemaPath;
4408 if ($breakOnError) {
4409 $closingBraces += '}';
4410 out += ' else { ';
4411 }
4412 }
4413 var arr1 = $schema;
4414 if (arr1) {
4415 var $sch, $i = -1,
4416 l1 = arr1.length - 1;
4417 while ($i < l1) {
4418 $sch = arr1[$i += 1];
4419 if (it.util.schemaHasRules($sch, it.RULES.all)) {
4420 out += ' ' + ($nextValid) + ' = true; if (' + ($data) + '.length > ' + ($i) + ') { ';
4421 var $passData = $data + '[' + $i + ']';
4422 $it.schema = $sch;
4423 $it.schemaPath = $schemaPath + '[' + $i + ']';
4424 $it.errSchemaPath = $errSchemaPath + '/' + $i;
4425 $it.errorPath = it.util.getPathExpr(it.errorPath, $i, it.opts.jsonPointers, true);
4426 $it.dataPathArr[$dataNxt] = $i;
4427 var $code = it.validate($it);
4428 $it.baseId = $currentBaseId;
4429 if (it.util.varOccurences($code, $nextData) < 2) {
4430 out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' ';
4431 } else {
4432 out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' ';
4433 }
4434 out += ' } ';
4435 if ($breakOnError) {
4436 out += ' if (' + ($nextValid) + ') { ';
4437 $closingBraces += '}';
4438 }
4439 }
4440 }
4441 }
4442 if (typeof $additionalItems == 'object' && it.util.schemaHasRules($additionalItems, it.RULES.all)) {
4443 $it.schema = $additionalItems;
4444 $it.schemaPath = it.schemaPath + '.additionalItems';
4445 $it.errSchemaPath = it.errSchemaPath + '/additionalItems';
4446 out += ' ' + ($nextValid) + ' = true; if (' + ($data) + '.length > ' + ($schema.length) + ') { for (var ' + ($idx) + ' = ' + ($schema.length) + '; ' + ($idx) + ' < ' + ($data) + '.length; ' + ($idx) + '++) { ';
4447 $it.errorPath = it.util.getPathExpr(it.errorPath, $idx, it.opts.jsonPointers, true);
4448 var $passData = $data + '[' + $idx + ']';
4449 $it.dataPathArr[$dataNxt] = $idx;
4450 var $code = it.validate($it);
4451 $it.baseId = $currentBaseId;
4452 if (it.util.varOccurences($code, $nextData) < 2) {
4453 out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' ';
4454 } else {
4455 out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' ';
4456 }
4457 if ($breakOnError) {
4458 out += ' if (!' + ($nextValid) + ') break; ';
4459 }
4460 out += ' } } ';
4461 if ($breakOnError) {
4462 out += ' if (' + ($nextValid) + ') { ';
4463 $closingBraces += '}';
4464 }
4465 }
4466 } else if (it.util.schemaHasRules($schema, it.RULES.all)) {
4467 $it.schema = $schema;
4468 $it.schemaPath = $schemaPath;
4469 $it.errSchemaPath = $errSchemaPath;
4470 out += ' for (var ' + ($idx) + ' = ' + (0) + '; ' + ($idx) + ' < ' + ($data) + '.length; ' + ($idx) + '++) { ';
4471 $it.errorPath = it.util.getPathExpr(it.errorPath, $idx, it.opts.jsonPointers, true);
4472 var $passData = $data + '[' + $idx + ']';
4473 $it.dataPathArr[$dataNxt] = $idx;
4474 var $code = it.validate($it);
4475 $it.baseId = $currentBaseId;
4476 if (it.util.varOccurences($code, $nextData) < 2) {
4477 out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' ';
4478 } else {
4479 out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' ';
4480 }
4481 if ($breakOnError) {
4482 out += ' if (!' + ($nextValid) + ') break; ';
4483 }
4484 out += ' }';
4485 }
4486 if ($breakOnError) {
4487 out += ' ' + ($closingBraces) + ' if (' + ($errs) + ' == errors) {';
4488 }
4489 out = it.util.cleanUpCode(out);
4490 return out;
4491}
4492
4493},{}],33:[function(require,module,exports){
4494'use strict';
4495module.exports = function generate_multipleOf(it, $keyword, $ruleType) {
4496 var out = ' ';
4497 var $lvl = it.level;
4498 var $dataLvl = it.dataLevel;
4499 var $schema = it.schema[$keyword];
4500 var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
4501 var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
4502 var $breakOnError = !it.opts.allErrors;
4503 var $data = 'data' + ($dataLvl || '');
4504 var $isData = it.opts.$data && $schema && $schema.$data,
4505 $schemaValue;
4506 if ($isData) {
4507 out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; ';
4508 $schemaValue = 'schema' + $lvl;
4509 } else {
4510 $schemaValue = $schema;
4511 }
4512 out += 'var division' + ($lvl) + ';if (';
4513 if ($isData) {
4514 out += ' ' + ($schemaValue) + ' !== undefined && ( typeof ' + ($schemaValue) + ' != \'number\' || ';
4515 }
4516 out += ' (division' + ($lvl) + ' = ' + ($data) + ' / ' + ($schemaValue) + ', ';
4517 if (it.opts.multipleOfPrecision) {
4518 out += ' Math.abs(Math.round(division' + ($lvl) + ') - division' + ($lvl) + ') > 1e-' + (it.opts.multipleOfPrecision) + ' ';
4519 } else {
4520 out += ' division' + ($lvl) + ' !== parseInt(division' + ($lvl) + ') ';
4521 }
4522 out += ' ) ';
4523 if ($isData) {
4524 out += ' ) ';
4525 }
4526 out += ' ) { ';
4527 var $$outStack = $$outStack || [];
4528 $$outStack.push(out);
4529 out = ''; /* istanbul ignore else */
4530 if (it.createErrors !== false) {
4531 out += ' { keyword: \'' + ('multipleOf') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { multipleOf: ' + ($schemaValue) + ' } ';
4532 if (it.opts.messages !== false) {
4533 out += ' , message: \'should be multiple of ';
4534 if ($isData) {
4535 out += '\' + ' + ($schemaValue);
4536 } else {
4537 out += '' + ($schemaValue) + '\'';
4538 }
4539 }
4540 if (it.opts.verbose) {
4541 out += ' , schema: ';
4542 if ($isData) {
4543 out += 'validate.schema' + ($schemaPath);
4544 } else {
4545 out += '' + ($schema);
4546 }
4547 out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
4548 }
4549 out += ' } ';
4550 } else {
4551 out += ' {} ';
4552 }
4553 var __err = out;
4554 out = $$outStack.pop();
4555 if (!it.compositeRule && $breakOnError) {
4556 /* istanbul ignore if */
4557 if (it.async) {
4558 out += ' throw new ValidationError([' + (__err) + ']); ';
4559 } else {
4560 out += ' validate.errors = [' + (__err) + ']; return false; ';
4561 }
4562 } else {
4563 out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
4564 }
4565 out += '} ';
4566 if ($breakOnError) {
4567 out += ' else { ';
4568 }
4569 return out;
4570}
4571
4572},{}],34:[function(require,module,exports){
4573'use strict';
4574module.exports = function generate_not(it, $keyword, $ruleType) {
4575 var out = ' ';
4576 var $lvl = it.level;
4577 var $dataLvl = it.dataLevel;
4578 var $schema = it.schema[$keyword];
4579 var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
4580 var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
4581 var $breakOnError = !it.opts.allErrors;
4582 var $data = 'data' + ($dataLvl || '');
4583 var $errs = 'errs__' + $lvl;
4584 var $it = it.util.copy(it);
4585 $it.level++;
4586 var $nextValid = 'valid' + $it.level;
4587 if (it.util.schemaHasRules($schema, it.RULES.all)) {
4588 $it.schema = $schema;
4589 $it.schemaPath = $schemaPath;
4590 $it.errSchemaPath = $errSchemaPath;
4591 out += ' var ' + ($errs) + ' = errors; ';
4592 var $wasComposite = it.compositeRule;
4593 it.compositeRule = $it.compositeRule = true;
4594 $it.createErrors = false;
4595 var $allErrorsOption;
4596 if ($it.opts.allErrors) {
4597 $allErrorsOption = $it.opts.allErrors;
4598 $it.opts.allErrors = false;
4599 }
4600 out += ' ' + (it.validate($it)) + ' ';
4601 $it.createErrors = true;
4602 if ($allErrorsOption) $it.opts.allErrors = $allErrorsOption;
4603 it.compositeRule = $it.compositeRule = $wasComposite;
4604 out += ' if (' + ($nextValid) + ') { ';
4605 var $$outStack = $$outStack || [];
4606 $$outStack.push(out);
4607 out = ''; /* istanbul ignore else */
4608 if (it.createErrors !== false) {
4609 out += ' { keyword: \'' + ('not') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} ';
4610 if (it.opts.messages !== false) {
4611 out += ' , message: \'should NOT be valid\' ';
4612 }
4613 if (it.opts.verbose) {
4614 out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
4615 }
4616 out += ' } ';
4617 } else {
4618 out += ' {} ';
4619 }
4620 var __err = out;
4621 out = $$outStack.pop();
4622 if (!it.compositeRule && $breakOnError) {
4623 /* istanbul ignore if */
4624 if (it.async) {
4625 out += ' throw new ValidationError([' + (__err) + ']); ';
4626 } else {
4627 out += ' validate.errors = [' + (__err) + ']; return false; ';
4628 }
4629 } else {
4630 out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
4631 }
4632 out += ' } else { errors = ' + ($errs) + '; if (vErrors !== null) { if (' + ($errs) + ') vErrors.length = ' + ($errs) + '; else vErrors = null; } ';
4633 if (it.opts.allErrors) {
4634 out += ' } ';
4635 }
4636 } else {
4637 out += ' var err = '; /* istanbul ignore else */
4638 if (it.createErrors !== false) {
4639 out += ' { keyword: \'' + ('not') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} ';
4640 if (it.opts.messages !== false) {
4641 out += ' , message: \'should NOT be valid\' ';
4642 }
4643 if (it.opts.verbose) {
4644 out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
4645 }
4646 out += ' } ';
4647 } else {
4648 out += ' {} ';
4649 }
4650 out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
4651 if ($breakOnError) {
4652 out += ' if (false) { ';
4653 }
4654 }
4655 return out;
4656}
4657
4658},{}],35:[function(require,module,exports){
4659'use strict';
4660module.exports = function generate_oneOf(it, $keyword, $ruleType) {
4661 var out = ' ';
4662 var $lvl = it.level;
4663 var $dataLvl = it.dataLevel;
4664 var $schema = it.schema[$keyword];
4665 var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
4666 var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
4667 var $breakOnError = !it.opts.allErrors;
4668 var $data = 'data' + ($dataLvl || '');
4669 var $valid = 'valid' + $lvl;
4670 var $errs = 'errs__' + $lvl;
4671 var $it = it.util.copy(it);
4672 var $closingBraces = '';
4673 $it.level++;
4674 var $nextValid = 'valid' + $it.level;
4675 var $currentBaseId = $it.baseId,
4676 $prevValid = 'prevValid' + $lvl,
4677 $passingSchemas = 'passingSchemas' + $lvl;
4678 out += 'var ' + ($errs) + ' = errors , ' + ($prevValid) + ' = false , ' + ($valid) + ' = false , ' + ($passingSchemas) + ' = null; ';
4679 var $wasComposite = it.compositeRule;
4680 it.compositeRule = $it.compositeRule = true;
4681 var arr1 = $schema;
4682 if (arr1) {
4683 var $sch, $i = -1,
4684 l1 = arr1.length - 1;
4685 while ($i < l1) {
4686 $sch = arr1[$i += 1];
4687 if (it.util.schemaHasRules($sch, it.RULES.all)) {
4688 $it.schema = $sch;
4689 $it.schemaPath = $schemaPath + '[' + $i + ']';
4690 $it.errSchemaPath = $errSchemaPath + '/' + $i;
4691 out += ' ' + (it.validate($it)) + ' ';
4692 $it.baseId = $currentBaseId;
4693 } else {
4694 out += ' var ' + ($nextValid) + ' = true; ';
4695 }
4696 if ($i) {
4697 out += ' if (' + ($nextValid) + ' && ' + ($prevValid) + ') { ' + ($valid) + ' = false; ' + ($passingSchemas) + ' = [' + ($passingSchemas) + ', ' + ($i) + ']; } else { ';
4698 $closingBraces += '}';
4699 }
4700 out += ' if (' + ($nextValid) + ') { ' + ($valid) + ' = ' + ($prevValid) + ' = true; ' + ($passingSchemas) + ' = ' + ($i) + '; }';
4701 }
4702 }
4703 it.compositeRule = $it.compositeRule = $wasComposite;
4704 out += '' + ($closingBraces) + 'if (!' + ($valid) + ') { var err = '; /* istanbul ignore else */
4705 if (it.createErrors !== false) {
4706 out += ' { keyword: \'' + ('oneOf') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { passingSchemas: ' + ($passingSchemas) + ' } ';
4707 if (it.opts.messages !== false) {
4708 out += ' , message: \'should match exactly one schema in oneOf\' ';
4709 }
4710 if (it.opts.verbose) {
4711 out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
4712 }
4713 out += ' } ';
4714 } else {
4715 out += ' {} ';
4716 }
4717 out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
4718 if (!it.compositeRule && $breakOnError) {
4719 /* istanbul ignore if */
4720 if (it.async) {
4721 out += ' throw new ValidationError(vErrors); ';
4722 } else {
4723 out += ' validate.errors = vErrors; return false; ';
4724 }
4725 }
4726 out += '} else { errors = ' + ($errs) + '; if (vErrors !== null) { if (' + ($errs) + ') vErrors.length = ' + ($errs) + '; else vErrors = null; }';
4727 if (it.opts.allErrors) {
4728 out += ' } ';
4729 }
4730 return out;
4731}
4732
4733},{}],36:[function(require,module,exports){
4734'use strict';
4735module.exports = function generate_pattern(it, $keyword, $ruleType) {
4736 var out = ' ';
4737 var $lvl = it.level;
4738 var $dataLvl = it.dataLevel;
4739 var $schema = it.schema[$keyword];
4740 var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
4741 var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
4742 var $breakOnError = !it.opts.allErrors;
4743 var $data = 'data' + ($dataLvl || '');
4744 var $isData = it.opts.$data && $schema && $schema.$data,
4745 $schemaValue;
4746 if ($isData) {
4747 out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; ';
4748 $schemaValue = 'schema' + $lvl;
4749 } else {
4750 $schemaValue = $schema;
4751 }
4752 var $regexp = $isData ? '(new RegExp(' + $schemaValue + '))' : it.usePattern($schema);
4753 out += 'if ( ';
4754 if ($isData) {
4755 out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'string\') || ';
4756 }
4757 out += ' !' + ($regexp) + '.test(' + ($data) + ') ) { ';
4758 var $$outStack = $$outStack || [];
4759 $$outStack.push(out);
4760 out = ''; /* istanbul ignore else */
4761 if (it.createErrors !== false) {
4762 out += ' { keyword: \'' + ('pattern') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { pattern: ';
4763 if ($isData) {
4764 out += '' + ($schemaValue);
4765 } else {
4766 out += '' + (it.util.toQuotedString($schema));
4767 }
4768 out += ' } ';
4769 if (it.opts.messages !== false) {
4770 out += ' , message: \'should match pattern "';
4771 if ($isData) {
4772 out += '\' + ' + ($schemaValue) + ' + \'';
4773 } else {
4774 out += '' + (it.util.escapeQuotes($schema));
4775 }
4776 out += '"\' ';
4777 }
4778 if (it.opts.verbose) {
4779 out += ' , schema: ';
4780 if ($isData) {
4781 out += 'validate.schema' + ($schemaPath);
4782 } else {
4783 out += '' + (it.util.toQuotedString($schema));
4784 }
4785 out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
4786 }
4787 out += ' } ';
4788 } else {
4789 out += ' {} ';
4790 }
4791 var __err = out;
4792 out = $$outStack.pop();
4793 if (!it.compositeRule && $breakOnError) {
4794 /* istanbul ignore if */
4795 if (it.async) {
4796 out += ' throw new ValidationError([' + (__err) + ']); ';
4797 } else {
4798 out += ' validate.errors = [' + (__err) + ']; return false; ';
4799 }
4800 } else {
4801 out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
4802 }
4803 out += '} ';
4804 if ($breakOnError) {
4805 out += ' else { ';
4806 }
4807 return out;
4808}
4809
4810},{}],37:[function(require,module,exports){
4811'use strict';
4812module.exports = function generate_properties(it, $keyword, $ruleType) {
4813 var out = ' ';
4814 var $lvl = it.level;
4815 var $dataLvl = it.dataLevel;
4816 var $schema = it.schema[$keyword];
4817 var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
4818 var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
4819 var $breakOnError = !it.opts.allErrors;
4820 var $data = 'data' + ($dataLvl || '');
4821 var $errs = 'errs__' + $lvl;
4822 var $it = it.util.copy(it);
4823 var $closingBraces = '';
4824 $it.level++;
4825 var $nextValid = 'valid' + $it.level;
4826 var $key = 'key' + $lvl,
4827 $idx = 'idx' + $lvl,
4828 $dataNxt = $it.dataLevel = it.dataLevel + 1,
4829 $nextData = 'data' + $dataNxt,
4830 $dataProperties = 'dataProperties' + $lvl;
4831 var $schemaKeys = Object.keys($schema || {}),
4832 $pProperties = it.schema.patternProperties || {},
4833 $pPropertyKeys = Object.keys($pProperties),
4834 $aProperties = it.schema.additionalProperties,
4835 $someProperties = $schemaKeys.length || $pPropertyKeys.length,
4836 $noAdditional = $aProperties === false,
4837 $additionalIsSchema = typeof $aProperties == 'object' && Object.keys($aProperties).length,
4838 $removeAdditional = it.opts.removeAdditional,
4839 $checkAdditional = $noAdditional || $additionalIsSchema || $removeAdditional,
4840 $ownProperties = it.opts.ownProperties,
4841 $currentBaseId = it.baseId;
4842 var $required = it.schema.required;
4843 if ($required && !(it.opts.$data && $required.$data) && $required.length < it.opts.loopRequired) var $requiredHash = it.util.toHash($required);
4844 out += 'var ' + ($errs) + ' = errors;var ' + ($nextValid) + ' = true;';
4845 if ($ownProperties) {
4846 out += ' var ' + ($dataProperties) + ' = undefined;';
4847 }
4848 if ($checkAdditional) {
4849 if ($ownProperties) {
4850 out += ' ' + ($dataProperties) + ' = ' + ($dataProperties) + ' || Object.keys(' + ($data) + '); for (var ' + ($idx) + '=0; ' + ($idx) + '<' + ($dataProperties) + '.length; ' + ($idx) + '++) { var ' + ($key) + ' = ' + ($dataProperties) + '[' + ($idx) + ']; ';
4851 } else {
4852 out += ' for (var ' + ($key) + ' in ' + ($data) + ') { ';
4853 }
4854 if ($someProperties) {
4855 out += ' var isAdditional' + ($lvl) + ' = !(false ';
4856 if ($schemaKeys.length) {
4857 if ($schemaKeys.length > 8) {
4858 out += ' || validate.schema' + ($schemaPath) + '.hasOwnProperty(' + ($key) + ') ';
4859 } else {
4860 var arr1 = $schemaKeys;
4861 if (arr1) {
4862 var $propertyKey, i1 = -1,
4863 l1 = arr1.length - 1;
4864 while (i1 < l1) {
4865 $propertyKey = arr1[i1 += 1];
4866 out += ' || ' + ($key) + ' == ' + (it.util.toQuotedString($propertyKey)) + ' ';
4867 }
4868 }
4869 }
4870 }
4871 if ($pPropertyKeys.length) {
4872 var arr2 = $pPropertyKeys;
4873 if (arr2) {
4874 var $pProperty, $i = -1,
4875 l2 = arr2.length - 1;
4876 while ($i < l2) {
4877 $pProperty = arr2[$i += 1];
4878 out += ' || ' + (it.usePattern($pProperty)) + '.test(' + ($key) + ') ';
4879 }
4880 }
4881 }
4882 out += ' ); if (isAdditional' + ($lvl) + ') { ';
4883 }
4884 if ($removeAdditional == 'all') {
4885 out += ' delete ' + ($data) + '[' + ($key) + ']; ';
4886 } else {
4887 var $currentErrorPath = it.errorPath;
4888 var $additionalProperty = '\' + ' + $key + ' + \'';
4889 if (it.opts._errorDataPathProperty) {
4890 it.errorPath = it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers);
4891 }
4892 if ($noAdditional) {
4893 if ($removeAdditional) {
4894 out += ' delete ' + ($data) + '[' + ($key) + ']; ';
4895 } else {
4896 out += ' ' + ($nextValid) + ' = false; ';
4897 var $currErrSchemaPath = $errSchemaPath;
4898 $errSchemaPath = it.errSchemaPath + '/additionalProperties';
4899 var $$outStack = $$outStack || [];
4900 $$outStack.push(out);
4901 out = ''; /* istanbul ignore else */
4902 if (it.createErrors !== false) {
4903 out += ' { keyword: \'' + ('additionalProperties') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { additionalProperty: \'' + ($additionalProperty) + '\' } ';
4904 if (it.opts.messages !== false) {
4905 out += ' , message: \'';
4906 if (it.opts._errorDataPathProperty) {
4907 out += 'is an invalid additional property';
4908 } else {
4909 out += 'should NOT have additional properties';
4910 }
4911 out += '\' ';
4912 }
4913 if (it.opts.verbose) {
4914 out += ' , schema: false , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
4915 }
4916 out += ' } ';
4917 } else {
4918 out += ' {} ';
4919 }
4920 var __err = out;
4921 out = $$outStack.pop();
4922 if (!it.compositeRule && $breakOnError) {
4923 /* istanbul ignore if */
4924 if (it.async) {
4925 out += ' throw new ValidationError([' + (__err) + ']); ';
4926 } else {
4927 out += ' validate.errors = [' + (__err) + ']; return false; ';
4928 }
4929 } else {
4930 out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
4931 }
4932 $errSchemaPath = $currErrSchemaPath;
4933 if ($breakOnError) {
4934 out += ' break; ';
4935 }
4936 }
4937 } else if ($additionalIsSchema) {
4938 if ($removeAdditional == 'failing') {
4939 out += ' var ' + ($errs) + ' = errors; ';
4940 var $wasComposite = it.compositeRule;
4941 it.compositeRule = $it.compositeRule = true;
4942 $it.schema = $aProperties;
4943 $it.schemaPath = it.schemaPath + '.additionalProperties';
4944 $it.errSchemaPath = it.errSchemaPath + '/additionalProperties';
4945 $it.errorPath = it.opts._errorDataPathProperty ? it.errorPath : it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers);
4946 var $passData = $data + '[' + $key + ']';
4947 $it.dataPathArr[$dataNxt] = $key;
4948 var $code = it.validate($it);
4949 $it.baseId = $currentBaseId;
4950 if (it.util.varOccurences($code, $nextData) < 2) {
4951 out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' ';
4952 } else {
4953 out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' ';
4954 }
4955 out += ' if (!' + ($nextValid) + ') { errors = ' + ($errs) + '; if (validate.errors !== null) { if (errors) validate.errors.length = errors; else validate.errors = null; } delete ' + ($data) + '[' + ($key) + ']; } ';
4956 it.compositeRule = $it.compositeRule = $wasComposite;
4957 } else {
4958 $it.schema = $aProperties;
4959 $it.schemaPath = it.schemaPath + '.additionalProperties';
4960 $it.errSchemaPath = it.errSchemaPath + '/additionalProperties';
4961 $it.errorPath = it.opts._errorDataPathProperty ? it.errorPath : it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers);
4962 var $passData = $data + '[' + $key + ']';
4963 $it.dataPathArr[$dataNxt] = $key;
4964 var $code = it.validate($it);
4965 $it.baseId = $currentBaseId;
4966 if (it.util.varOccurences($code, $nextData) < 2) {
4967 out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' ';
4968 } else {
4969 out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' ';
4970 }
4971 if ($breakOnError) {
4972 out += ' if (!' + ($nextValid) + ') break; ';
4973 }
4974 }
4975 }
4976 it.errorPath = $currentErrorPath;
4977 }
4978 if ($someProperties) {
4979 out += ' } ';
4980 }
4981 out += ' } ';
4982 if ($breakOnError) {
4983 out += ' if (' + ($nextValid) + ') { ';
4984 $closingBraces += '}';
4985 }
4986 }
4987 var $useDefaults = it.opts.useDefaults && !it.compositeRule;
4988 if ($schemaKeys.length) {
4989 var arr3 = $schemaKeys;
4990 if (arr3) {
4991 var $propertyKey, i3 = -1,
4992 l3 = arr3.length - 1;
4993 while (i3 < l3) {
4994 $propertyKey = arr3[i3 += 1];
4995 var $sch = $schema[$propertyKey];
4996 if (it.util.schemaHasRules($sch, it.RULES.all)) {
4997 var $prop = it.util.getProperty($propertyKey),
4998 $passData = $data + $prop,
4999 $hasDefault = $useDefaults && $sch.default !== undefined;
5000 $it.schema = $sch;
5001 $it.schemaPath = $schemaPath + $prop;
5002 $it.errSchemaPath = $errSchemaPath + '/' + it.util.escapeFragment($propertyKey);
5003 $it.errorPath = it.util.getPath(it.errorPath, $propertyKey, it.opts.jsonPointers);
5004 $it.dataPathArr[$dataNxt] = it.util.toQuotedString($propertyKey);
5005 var $code = it.validate($it);
5006 $it.baseId = $currentBaseId;
5007 if (it.util.varOccurences($code, $nextData) < 2) {
5008 $code = it.util.varReplace($code, $nextData, $passData);
5009 var $useData = $passData;
5010 } else {
5011 var $useData = $nextData;
5012 out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ';
5013 }
5014 if ($hasDefault) {
5015 out += ' ' + ($code) + ' ';
5016 } else {
5017 if ($requiredHash && $requiredHash[$propertyKey]) {
5018 out += ' if ( ' + ($useData) + ' === undefined ';
5019 if ($ownProperties) {
5020 out += ' || ! Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($propertyKey)) + '\') ';
5021 }
5022 out += ') { ' + ($nextValid) + ' = false; ';
5023 var $currentErrorPath = it.errorPath,
5024 $currErrSchemaPath = $errSchemaPath,
5025 $missingProperty = it.util.escapeQuotes($propertyKey);
5026 if (it.opts._errorDataPathProperty) {
5027 it.errorPath = it.util.getPath($currentErrorPath, $propertyKey, it.opts.jsonPointers);
5028 }
5029 $errSchemaPath = it.errSchemaPath + '/required';
5030 var $$outStack = $$outStack || [];
5031 $$outStack.push(out);
5032 out = ''; /* istanbul ignore else */
5033 if (it.createErrors !== false) {
5034 out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } ';
5035 if (it.opts.messages !== false) {
5036 out += ' , message: \'';
5037 if (it.opts._errorDataPathProperty) {
5038 out += 'is a required property';
5039 } else {
5040 out += 'should have required property \\\'' + ($missingProperty) + '\\\'';
5041 }
5042 out += '\' ';
5043 }
5044 if (it.opts.verbose) {
5045 out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
5046 }
5047 out += ' } ';
5048 } else {
5049 out += ' {} ';
5050 }
5051 var __err = out;
5052 out = $$outStack.pop();
5053 if (!it.compositeRule && $breakOnError) {
5054 /* istanbul ignore if */
5055 if (it.async) {
5056 out += ' throw new ValidationError([' + (__err) + ']); ';
5057 } else {
5058 out += ' validate.errors = [' + (__err) + ']; return false; ';
5059 }
5060 } else {
5061 out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
5062 }
5063 $errSchemaPath = $currErrSchemaPath;
5064 it.errorPath = $currentErrorPath;
5065 out += ' } else { ';
5066 } else {
5067 if ($breakOnError) {
5068 out += ' if ( ' + ($useData) + ' === undefined ';
5069 if ($ownProperties) {
5070 out += ' || ! Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($propertyKey)) + '\') ';
5071 }
5072 out += ') { ' + ($nextValid) + ' = true; } else { ';
5073 } else {
5074 out += ' if (' + ($useData) + ' !== undefined ';
5075 if ($ownProperties) {
5076 out += ' && Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($propertyKey)) + '\') ';
5077 }
5078 out += ' ) { ';
5079 }
5080 }
5081 out += ' ' + ($code) + ' } ';
5082 }
5083 }
5084 if ($breakOnError) {
5085 out += ' if (' + ($nextValid) + ') { ';
5086 $closingBraces += '}';
5087 }
5088 }
5089 }
5090 }
5091 if ($pPropertyKeys.length) {
5092 var arr4 = $pPropertyKeys;
5093 if (arr4) {
5094 var $pProperty, i4 = -1,
5095 l4 = arr4.length - 1;
5096 while (i4 < l4) {
5097 $pProperty = arr4[i4 += 1];
5098 var $sch = $pProperties[$pProperty];
5099 if (it.util.schemaHasRules($sch, it.RULES.all)) {
5100 $it.schema = $sch;
5101 $it.schemaPath = it.schemaPath + '.patternProperties' + it.util.getProperty($pProperty);
5102 $it.errSchemaPath = it.errSchemaPath + '/patternProperties/' + it.util.escapeFragment($pProperty);
5103 if ($ownProperties) {
5104 out += ' ' + ($dataProperties) + ' = ' + ($dataProperties) + ' || Object.keys(' + ($data) + '); for (var ' + ($idx) + '=0; ' + ($idx) + '<' + ($dataProperties) + '.length; ' + ($idx) + '++) { var ' + ($key) + ' = ' + ($dataProperties) + '[' + ($idx) + ']; ';
5105 } else {
5106 out += ' for (var ' + ($key) + ' in ' + ($data) + ') { ';
5107 }
5108 out += ' if (' + (it.usePattern($pProperty)) + '.test(' + ($key) + ')) { ';
5109 $it.errorPath = it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers);
5110 var $passData = $data + '[' + $key + ']';
5111 $it.dataPathArr[$dataNxt] = $key;
5112 var $code = it.validate($it);
5113 $it.baseId = $currentBaseId;
5114 if (it.util.varOccurences($code, $nextData) < 2) {
5115 out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' ';
5116 } else {
5117 out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' ';
5118 }
5119 if ($breakOnError) {
5120 out += ' if (!' + ($nextValid) + ') break; ';
5121 }
5122 out += ' } ';
5123 if ($breakOnError) {
5124 out += ' else ' + ($nextValid) + ' = true; ';
5125 }
5126 out += ' } ';
5127 if ($breakOnError) {
5128 out += ' if (' + ($nextValid) + ') { ';
5129 $closingBraces += '}';
5130 }
5131 }
5132 }
5133 }
5134 }
5135 if ($breakOnError) {
5136 out += ' ' + ($closingBraces) + ' if (' + ($errs) + ' == errors) {';
5137 }
5138 out = it.util.cleanUpCode(out);
5139 return out;
5140}
5141
5142},{}],38:[function(require,module,exports){
5143'use strict';
5144module.exports = function generate_propertyNames(it, $keyword, $ruleType) {
5145 var out = ' ';
5146 var $lvl = it.level;
5147 var $dataLvl = it.dataLevel;
5148 var $schema = it.schema[$keyword];
5149 var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
5150 var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
5151 var $breakOnError = !it.opts.allErrors;
5152 var $data = 'data' + ($dataLvl || '');
5153 var $errs = 'errs__' + $lvl;
5154 var $it = it.util.copy(it);
5155 var $closingBraces = '';
5156 $it.level++;
5157 var $nextValid = 'valid' + $it.level;
5158 out += 'var ' + ($errs) + ' = errors;';
5159 if (it.util.schemaHasRules($schema, it.RULES.all)) {
5160 $it.schema = $schema;
5161 $it.schemaPath = $schemaPath;
5162 $it.errSchemaPath = $errSchemaPath;
5163 var $key = 'key' + $lvl,
5164 $idx = 'idx' + $lvl,
5165 $i = 'i' + $lvl,
5166 $invalidName = '\' + ' + $key + ' + \'',
5167 $dataNxt = $it.dataLevel = it.dataLevel + 1,
5168 $nextData = 'data' + $dataNxt,
5169 $dataProperties = 'dataProperties' + $lvl,
5170 $ownProperties = it.opts.ownProperties,
5171 $currentBaseId = it.baseId;
5172 if ($ownProperties) {
5173 out += ' var ' + ($dataProperties) + ' = undefined; ';
5174 }
5175 if ($ownProperties) {
5176 out += ' ' + ($dataProperties) + ' = ' + ($dataProperties) + ' || Object.keys(' + ($data) + '); for (var ' + ($idx) + '=0; ' + ($idx) + '<' + ($dataProperties) + '.length; ' + ($idx) + '++) { var ' + ($key) + ' = ' + ($dataProperties) + '[' + ($idx) + ']; ';
5177 } else {
5178 out += ' for (var ' + ($key) + ' in ' + ($data) + ') { ';
5179 }
5180 out += ' var startErrs' + ($lvl) + ' = errors; ';
5181 var $passData = $key;
5182 var $wasComposite = it.compositeRule;
5183 it.compositeRule = $it.compositeRule = true;
5184 var $code = it.validate($it);
5185 $it.baseId = $currentBaseId;
5186 if (it.util.varOccurences($code, $nextData) < 2) {
5187 out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' ';
5188 } else {
5189 out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' ';
5190 }
5191 it.compositeRule = $it.compositeRule = $wasComposite;
5192 out += ' if (!' + ($nextValid) + ') { for (var ' + ($i) + '=startErrs' + ($lvl) + '; ' + ($i) + '<errors; ' + ($i) + '++) { vErrors[' + ($i) + '].propertyName = ' + ($key) + '; } var err = '; /* istanbul ignore else */
5193 if (it.createErrors !== false) {
5194 out += ' { keyword: \'' + ('propertyNames') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { propertyName: \'' + ($invalidName) + '\' } ';
5195 if (it.opts.messages !== false) {
5196 out += ' , message: \'property name \\\'' + ($invalidName) + '\\\' is invalid\' ';
5197 }
5198 if (it.opts.verbose) {
5199 out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
5200 }
5201 out += ' } ';
5202 } else {
5203 out += ' {} ';
5204 }
5205 out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
5206 if (!it.compositeRule && $breakOnError) {
5207 /* istanbul ignore if */
5208 if (it.async) {
5209 out += ' throw new ValidationError(vErrors); ';
5210 } else {
5211 out += ' validate.errors = vErrors; return false; ';
5212 }
5213 }
5214 if ($breakOnError) {
5215 out += ' break; ';
5216 }
5217 out += ' } }';
5218 }
5219 if ($breakOnError) {
5220 out += ' ' + ($closingBraces) + ' if (' + ($errs) + ' == errors) {';
5221 }
5222 out = it.util.cleanUpCode(out);
5223 return out;
5224}
5225
5226},{}],39:[function(require,module,exports){
5227'use strict';
5228module.exports = function generate_ref(it, $keyword, $ruleType) {
5229 var out = ' ';
5230 var $lvl = it.level;
5231 var $dataLvl = it.dataLevel;
5232 var $schema = it.schema[$keyword];
5233 var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
5234 var $breakOnError = !it.opts.allErrors;
5235 var $data = 'data' + ($dataLvl || '');
5236 var $valid = 'valid' + $lvl;
5237 var $async, $refCode;
5238 if ($schema == '#' || $schema == '#/') {
5239 if (it.isRoot) {
5240 $async = it.async;
5241 $refCode = 'validate';
5242 } else {
5243 $async = it.root.schema.$async === true;
5244 $refCode = 'root.refVal[0]';
5245 }
5246 } else {
5247 var $refVal = it.resolveRef(it.baseId, $schema, it.isRoot);
5248 if ($refVal === undefined) {
5249 var $message = it.MissingRefError.message(it.baseId, $schema);
5250 if (it.opts.missingRefs == 'fail') {
5251 it.logger.error($message);
5252 var $$outStack = $$outStack || [];
5253 $$outStack.push(out);
5254 out = ''; /* istanbul ignore else */
5255 if (it.createErrors !== false) {
5256 out += ' { keyword: \'' + ('$ref') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { ref: \'' + (it.util.escapeQuotes($schema)) + '\' } ';
5257 if (it.opts.messages !== false) {
5258 out += ' , message: \'can\\\'t resolve reference ' + (it.util.escapeQuotes($schema)) + '\' ';
5259 }
5260 if (it.opts.verbose) {
5261 out += ' , schema: ' + (it.util.toQuotedString($schema)) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
5262 }
5263 out += ' } ';
5264 } else {
5265 out += ' {} ';
5266 }
5267 var __err = out;
5268 out = $$outStack.pop();
5269 if (!it.compositeRule && $breakOnError) {
5270 /* istanbul ignore if */
5271 if (it.async) {
5272 out += ' throw new ValidationError([' + (__err) + ']); ';
5273 } else {
5274 out += ' validate.errors = [' + (__err) + ']; return false; ';
5275 }
5276 } else {
5277 out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
5278 }
5279 if ($breakOnError) {
5280 out += ' if (false) { ';
5281 }
5282 } else if (it.opts.missingRefs == 'ignore') {
5283 it.logger.warn($message);
5284 if ($breakOnError) {
5285 out += ' if (true) { ';
5286 }
5287 } else {
5288 throw new it.MissingRefError(it.baseId, $schema, $message);
5289 }
5290 } else if ($refVal.inline) {
5291 var $it = it.util.copy(it);
5292 $it.level++;
5293 var $nextValid = 'valid' + $it.level;
5294 $it.schema = $refVal.schema;
5295 $it.schemaPath = '';
5296 $it.errSchemaPath = $schema;
5297 var $code = it.validate($it).replace(/validate\.schema/g, $refVal.code);
5298 out += ' ' + ($code) + ' ';
5299 if ($breakOnError) {
5300 out += ' if (' + ($nextValid) + ') { ';
5301 }
5302 } else {
5303 $async = $refVal.$async === true || (it.async && $refVal.$async !== false);
5304 $refCode = $refVal.code;
5305 }
5306 }
5307 if ($refCode) {
5308 var $$outStack = $$outStack || [];
5309 $$outStack.push(out);
5310 out = '';
5311 if (it.opts.passContext) {
5312 out += ' ' + ($refCode) + '.call(this, ';
5313 } else {
5314 out += ' ' + ($refCode) + '( ';
5315 }
5316 out += ' ' + ($data) + ', (dataPath || \'\')';
5317 if (it.errorPath != '""') {
5318 out += ' + ' + (it.errorPath);
5319 }
5320 var $parentData = $dataLvl ? 'data' + (($dataLvl - 1) || '') : 'parentData',
5321 $parentDataProperty = $dataLvl ? it.dataPathArr[$dataLvl] : 'parentDataProperty';
5322 out += ' , ' + ($parentData) + ' , ' + ($parentDataProperty) + ', rootData) ';
5323 var __callValidate = out;
5324 out = $$outStack.pop();
5325 if ($async) {
5326 if (!it.async) throw new Error('async schema referenced by sync schema');
5327 if ($breakOnError) {
5328 out += ' var ' + ($valid) + '; ';
5329 }
5330 out += ' try { await ' + (__callValidate) + '; ';
5331 if ($breakOnError) {
5332 out += ' ' + ($valid) + ' = true; ';
5333 }
5334 out += ' } catch (e) { if (!(e instanceof ValidationError)) throw e; if (vErrors === null) vErrors = e.errors; else vErrors = vErrors.concat(e.errors); errors = vErrors.length; ';
5335 if ($breakOnError) {
5336 out += ' ' + ($valid) + ' = false; ';
5337 }
5338 out += ' } ';
5339 if ($breakOnError) {
5340 out += ' if (' + ($valid) + ') { ';
5341 }
5342 } else {
5343 out += ' if (!' + (__callValidate) + ') { if (vErrors === null) vErrors = ' + ($refCode) + '.errors; else vErrors = vErrors.concat(' + ($refCode) + '.errors); errors = vErrors.length; } ';
5344 if ($breakOnError) {
5345 out += ' else { ';
5346 }
5347 }
5348 }
5349 return out;
5350}
5351
5352},{}],40:[function(require,module,exports){
5353'use strict';
5354module.exports = function generate_required(it, $keyword, $ruleType) {
5355 var out = ' ';
5356 var $lvl = it.level;
5357 var $dataLvl = it.dataLevel;
5358 var $schema = it.schema[$keyword];
5359 var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
5360 var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
5361 var $breakOnError = !it.opts.allErrors;
5362 var $data = 'data' + ($dataLvl || '');
5363 var $valid = 'valid' + $lvl;
5364 var $isData = it.opts.$data && $schema && $schema.$data,
5365 $schemaValue;
5366 if ($isData) {
5367 out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; ';
5368 $schemaValue = 'schema' + $lvl;
5369 } else {
5370 $schemaValue = $schema;
5371 }
5372 var $vSchema = 'schema' + $lvl;
5373 if (!$isData) {
5374 if ($schema.length < it.opts.loopRequired && it.schema.properties && Object.keys(it.schema.properties).length) {
5375 var $required = [];
5376 var arr1 = $schema;
5377 if (arr1) {
5378 var $property, i1 = -1,
5379 l1 = arr1.length - 1;
5380 while (i1 < l1) {
5381 $property = arr1[i1 += 1];
5382 var $propertySch = it.schema.properties[$property];
5383 if (!($propertySch && it.util.schemaHasRules($propertySch, it.RULES.all))) {
5384 $required[$required.length] = $property;
5385 }
5386 }
5387 }
5388 } else {
5389 var $required = $schema;
5390 }
5391 }
5392 if ($isData || $required.length) {
5393 var $currentErrorPath = it.errorPath,
5394 $loopRequired = $isData || $required.length >= it.opts.loopRequired,
5395 $ownProperties = it.opts.ownProperties;
5396 if ($breakOnError) {
5397 out += ' var missing' + ($lvl) + '; ';
5398 if ($loopRequired) {
5399 if (!$isData) {
5400 out += ' var ' + ($vSchema) + ' = validate.schema' + ($schemaPath) + '; ';
5401 }
5402 var $i = 'i' + $lvl,
5403 $propertyPath = 'schema' + $lvl + '[' + $i + ']',
5404 $missingProperty = '\' + ' + $propertyPath + ' + \'';
5405 if (it.opts._errorDataPathProperty) {
5406 it.errorPath = it.util.getPathExpr($currentErrorPath, $propertyPath, it.opts.jsonPointers);
5407 }
5408 out += ' var ' + ($valid) + ' = true; ';
5409 if ($isData) {
5410 out += ' if (schema' + ($lvl) + ' === undefined) ' + ($valid) + ' = true; else if (!Array.isArray(schema' + ($lvl) + ')) ' + ($valid) + ' = false; else {';
5411 }
5412 out += ' for (var ' + ($i) + ' = 0; ' + ($i) + ' < ' + ($vSchema) + '.length; ' + ($i) + '++) { ' + ($valid) + ' = ' + ($data) + '[' + ($vSchema) + '[' + ($i) + ']] !== undefined ';
5413 if ($ownProperties) {
5414 out += ' && Object.prototype.hasOwnProperty.call(' + ($data) + ', ' + ($vSchema) + '[' + ($i) + ']) ';
5415 }
5416 out += '; if (!' + ($valid) + ') break; } ';
5417 if ($isData) {
5418 out += ' } ';
5419 }
5420 out += ' if (!' + ($valid) + ') { ';
5421 var $$outStack = $$outStack || [];
5422 $$outStack.push(out);
5423 out = ''; /* istanbul ignore else */
5424 if (it.createErrors !== false) {
5425 out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } ';
5426 if (it.opts.messages !== false) {
5427 out += ' , message: \'';
5428 if (it.opts._errorDataPathProperty) {
5429 out += 'is a required property';
5430 } else {
5431 out += 'should have required property \\\'' + ($missingProperty) + '\\\'';
5432 }
5433 out += '\' ';
5434 }
5435 if (it.opts.verbose) {
5436 out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
5437 }
5438 out += ' } ';
5439 } else {
5440 out += ' {} ';
5441 }
5442 var __err = out;
5443 out = $$outStack.pop();
5444 if (!it.compositeRule && $breakOnError) {
5445 /* istanbul ignore if */
5446 if (it.async) {
5447 out += ' throw new ValidationError([' + (__err) + ']); ';
5448 } else {
5449 out += ' validate.errors = [' + (__err) + ']; return false; ';
5450 }
5451 } else {
5452 out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
5453 }
5454 out += ' } else { ';
5455 } else {
5456 out += ' if ( ';
5457 var arr2 = $required;
5458 if (arr2) {
5459 var $propertyKey, $i = -1,
5460 l2 = arr2.length - 1;
5461 while ($i < l2) {
5462 $propertyKey = arr2[$i += 1];
5463 if ($i) {
5464 out += ' || ';
5465 }
5466 var $prop = it.util.getProperty($propertyKey),
5467 $useData = $data + $prop;
5468 out += ' ( ( ' + ($useData) + ' === undefined ';
5469 if ($ownProperties) {
5470 out += ' || ! Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($propertyKey)) + '\') ';
5471 }
5472 out += ') && (missing' + ($lvl) + ' = ' + (it.util.toQuotedString(it.opts.jsonPointers ? $propertyKey : $prop)) + ') ) ';
5473 }
5474 }
5475 out += ') { ';
5476 var $propertyPath = 'missing' + $lvl,
5477 $missingProperty = '\' + ' + $propertyPath + ' + \'';
5478 if (it.opts._errorDataPathProperty) {
5479 it.errorPath = it.opts.jsonPointers ? it.util.getPathExpr($currentErrorPath, $propertyPath, true) : $currentErrorPath + ' + ' + $propertyPath;
5480 }
5481 var $$outStack = $$outStack || [];
5482 $$outStack.push(out);
5483 out = ''; /* istanbul ignore else */
5484 if (it.createErrors !== false) {
5485 out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } ';
5486 if (it.opts.messages !== false) {
5487 out += ' , message: \'';
5488 if (it.opts._errorDataPathProperty) {
5489 out += 'is a required property';
5490 } else {
5491 out += 'should have required property \\\'' + ($missingProperty) + '\\\'';
5492 }
5493 out += '\' ';
5494 }
5495 if (it.opts.verbose) {
5496 out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
5497 }
5498 out += ' } ';
5499 } else {
5500 out += ' {} ';
5501 }
5502 var __err = out;
5503 out = $$outStack.pop();
5504 if (!it.compositeRule && $breakOnError) {
5505 /* istanbul ignore if */
5506 if (it.async) {
5507 out += ' throw new ValidationError([' + (__err) + ']); ';
5508 } else {
5509 out += ' validate.errors = [' + (__err) + ']; return false; ';
5510 }
5511 } else {
5512 out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
5513 }
5514 out += ' } else { ';
5515 }
5516 } else {
5517 if ($loopRequired) {
5518 if (!$isData) {
5519 out += ' var ' + ($vSchema) + ' = validate.schema' + ($schemaPath) + '; ';
5520 }
5521 var $i = 'i' + $lvl,
5522 $propertyPath = 'schema' + $lvl + '[' + $i + ']',
5523 $missingProperty = '\' + ' + $propertyPath + ' + \'';
5524 if (it.opts._errorDataPathProperty) {
5525 it.errorPath = it.util.getPathExpr($currentErrorPath, $propertyPath, it.opts.jsonPointers);
5526 }
5527 if ($isData) {
5528 out += ' if (' + ($vSchema) + ' && !Array.isArray(' + ($vSchema) + ')) { var err = '; /* istanbul ignore else */
5529 if (it.createErrors !== false) {
5530 out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } ';
5531 if (it.opts.messages !== false) {
5532 out += ' , message: \'';
5533 if (it.opts._errorDataPathProperty) {
5534 out += 'is a required property';
5535 } else {
5536 out += 'should have required property \\\'' + ($missingProperty) + '\\\'';
5537 }
5538 out += '\' ';
5539 }
5540 if (it.opts.verbose) {
5541 out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
5542 }
5543 out += ' } ';
5544 } else {
5545 out += ' {} ';
5546 }
5547 out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } else if (' + ($vSchema) + ' !== undefined) { ';
5548 }
5549 out += ' for (var ' + ($i) + ' = 0; ' + ($i) + ' < ' + ($vSchema) + '.length; ' + ($i) + '++) { if (' + ($data) + '[' + ($vSchema) + '[' + ($i) + ']] === undefined ';
5550 if ($ownProperties) {
5551 out += ' || ! Object.prototype.hasOwnProperty.call(' + ($data) + ', ' + ($vSchema) + '[' + ($i) + ']) ';
5552 }
5553 out += ') { var err = '; /* istanbul ignore else */
5554 if (it.createErrors !== false) {
5555 out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } ';
5556 if (it.opts.messages !== false) {
5557 out += ' , message: \'';
5558 if (it.opts._errorDataPathProperty) {
5559 out += 'is a required property';
5560 } else {
5561 out += 'should have required property \\\'' + ($missingProperty) + '\\\'';
5562 }
5563 out += '\' ';
5564 }
5565 if (it.opts.verbose) {
5566 out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
5567 }
5568 out += ' } ';
5569 } else {
5570 out += ' {} ';
5571 }
5572 out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } } ';
5573 if ($isData) {
5574 out += ' } ';
5575 }
5576 } else {
5577 var arr3 = $required;
5578 if (arr3) {
5579 var $propertyKey, i3 = -1,
5580 l3 = arr3.length - 1;
5581 while (i3 < l3) {
5582 $propertyKey = arr3[i3 += 1];
5583 var $prop = it.util.getProperty($propertyKey),
5584 $missingProperty = it.util.escapeQuotes($propertyKey),
5585 $useData = $data + $prop;
5586 if (it.opts._errorDataPathProperty) {
5587 it.errorPath = it.util.getPath($currentErrorPath, $propertyKey, it.opts.jsonPointers);
5588 }
5589 out += ' if ( ' + ($useData) + ' === undefined ';
5590 if ($ownProperties) {
5591 out += ' || ! Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($propertyKey)) + '\') ';
5592 }
5593 out += ') { var err = '; /* istanbul ignore else */
5594 if (it.createErrors !== false) {
5595 out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } ';
5596 if (it.opts.messages !== false) {
5597 out += ' , message: \'';
5598 if (it.opts._errorDataPathProperty) {
5599 out += 'is a required property';
5600 } else {
5601 out += 'should have required property \\\'' + ($missingProperty) + '\\\'';
5602 }
5603 out += '\' ';
5604 }
5605 if (it.opts.verbose) {
5606 out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
5607 }
5608 out += ' } ';
5609 } else {
5610 out += ' {} ';
5611 }
5612 out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } ';
5613 }
5614 }
5615 }
5616 }
5617 it.errorPath = $currentErrorPath;
5618 } else if ($breakOnError) {
5619 out += ' if (true) {';
5620 }
5621 return out;
5622}
5623
5624},{}],41:[function(require,module,exports){
5625'use strict';
5626module.exports = function generate_uniqueItems(it, $keyword, $ruleType) {
5627 var out = ' ';
5628 var $lvl = it.level;
5629 var $dataLvl = it.dataLevel;
5630 var $schema = it.schema[$keyword];
5631 var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
5632 var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
5633 var $breakOnError = !it.opts.allErrors;
5634 var $data = 'data' + ($dataLvl || '');
5635 var $valid = 'valid' + $lvl;
5636 var $isData = it.opts.$data && $schema && $schema.$data,
5637 $schemaValue;
5638 if ($isData) {
5639 out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; ';
5640 $schemaValue = 'schema' + $lvl;
5641 } else {
5642 $schemaValue = $schema;
5643 }
5644 if (($schema || $isData) && it.opts.uniqueItems !== false) {
5645 if ($isData) {
5646 out += ' var ' + ($valid) + '; if (' + ($schemaValue) + ' === false || ' + ($schemaValue) + ' === undefined) ' + ($valid) + ' = true; else if (typeof ' + ($schemaValue) + ' != \'boolean\') ' + ($valid) + ' = false; else { ';
5647 }
5648 out += ' var i = ' + ($data) + '.length , ' + ($valid) + ' = true , j; if (i > 1) { ';
5649 var $itemType = it.schema.items && it.schema.items.type,
5650 $typeIsArray = Array.isArray($itemType);
5651 if (!$itemType || $itemType == 'object' || $itemType == 'array' || ($typeIsArray && ($itemType.indexOf('object') >= 0 || $itemType.indexOf('array') >= 0))) {
5652 out += ' outer: for (;i--;) { for (j = i; j--;) { if (equal(' + ($data) + '[i], ' + ($data) + '[j])) { ' + ($valid) + ' = false; break outer; } } } ';
5653 } else {
5654 out += ' var itemIndices = {}, item; for (;i--;) { var item = ' + ($data) + '[i]; ';
5655 var $method = 'checkDataType' + ($typeIsArray ? 's' : '');
5656 out += ' if (' + (it.util[$method]($itemType, 'item', true)) + ') continue; ';
5657 if ($typeIsArray) {
5658 out += ' if (typeof item == \'string\') item = \'"\' + item; ';
5659 }
5660 out += ' if (typeof itemIndices[item] == \'number\') { ' + ($valid) + ' = false; j = itemIndices[item]; break; } itemIndices[item] = i; } ';
5661 }
5662 out += ' } ';
5663 if ($isData) {
5664 out += ' } ';
5665 }
5666 out += ' if (!' + ($valid) + ') { ';
5667 var $$outStack = $$outStack || [];
5668 $$outStack.push(out);
5669 out = ''; /* istanbul ignore else */
5670 if (it.createErrors !== false) {
5671 out += ' { keyword: \'' + ('uniqueItems') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { i: i, j: j } ';
5672 if (it.opts.messages !== false) {
5673 out += ' , message: \'should NOT have duplicate items (items ## \' + j + \' and \' + i + \' are identical)\' ';
5674 }
5675 if (it.opts.verbose) {
5676 out += ' , schema: ';
5677 if ($isData) {
5678 out += 'validate.schema' + ($schemaPath);
5679 } else {
5680 out += '' + ($schema);
5681 }
5682 out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
5683 }
5684 out += ' } ';
5685 } else {
5686 out += ' {} ';
5687 }
5688 var __err = out;
5689 out = $$outStack.pop();
5690 if (!it.compositeRule && $breakOnError) {
5691 /* istanbul ignore if */
5692 if (it.async) {
5693 out += ' throw new ValidationError([' + (__err) + ']); ';
5694 } else {
5695 out += ' validate.errors = [' + (__err) + ']; return false; ';
5696 }
5697 } else {
5698 out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
5699 }
5700 out += ' } ';
5701 if ($breakOnError) {
5702 out += ' else { ';
5703 }
5704 } else {
5705 if ($breakOnError) {
5706 out += ' if (true) { ';
5707 }
5708 }
5709 return out;
5710}
5711
5712},{}],42:[function(require,module,exports){
5713'use strict';
5714module.exports = function generate_validate(it, $keyword, $ruleType) {
5715 var out = '';
5716 var $async = it.schema.$async === true,
5717 $refKeywords = it.util.schemaHasRulesExcept(it.schema, it.RULES.all, '$ref'),
5718 $id = it.self._getId(it.schema);
5719 if (it.opts.strictKeywords) {
5720 var $unknownKwd = it.util.schemaUnknownRules(it.schema, it.RULES.keywords);
5721 if ($unknownKwd) {
5722 var $keywordsMsg = 'unknown keyword: ' + $unknownKwd;
5723 if (it.opts.strictKeywords === 'log') it.logger.warn($keywordsMsg);
5724 else throw new Error($keywordsMsg);
5725 }
5726 }
5727 if (it.isTop) {
5728 out += ' var validate = ';
5729 if ($async) {
5730 it.async = true;
5731 out += 'async ';
5732 }
5733 out += 'function(data, dataPath, parentData, parentDataProperty, rootData) { \'use strict\'; ';
5734 if ($id && (it.opts.sourceCode || it.opts.processCode)) {
5735 out += ' ' + ('/\*# sourceURL=' + $id + ' */') + ' ';
5736 }
5737 }
5738 if (typeof it.schema == 'boolean' || !($refKeywords || it.schema.$ref)) {
5739 var $keyword = 'false schema';
5740 var $lvl = it.level;
5741 var $dataLvl = it.dataLevel;
5742 var $schema = it.schema[$keyword];
5743 var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
5744 var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
5745 var $breakOnError = !it.opts.allErrors;
5746 var $errorKeyword;
5747 var $data = 'data' + ($dataLvl || '');
5748 var $valid = 'valid' + $lvl;
5749 if (it.schema === false) {
5750 if (it.isTop) {
5751 $breakOnError = true;
5752 } else {
5753 out += ' var ' + ($valid) + ' = false; ';
5754 }
5755 var $$outStack = $$outStack || [];
5756 $$outStack.push(out);
5757 out = ''; /* istanbul ignore else */
5758 if (it.createErrors !== false) {
5759 out += ' { keyword: \'' + ($errorKeyword || 'false schema') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} ';
5760 if (it.opts.messages !== false) {
5761 out += ' , message: \'boolean schema is false\' ';
5762 }
5763 if (it.opts.verbose) {
5764 out += ' , schema: false , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
5765 }
5766 out += ' } ';
5767 } else {
5768 out += ' {} ';
5769 }
5770 var __err = out;
5771 out = $$outStack.pop();
5772 if (!it.compositeRule && $breakOnError) {
5773 /* istanbul ignore if */
5774 if (it.async) {
5775 out += ' throw new ValidationError([' + (__err) + ']); ';
5776 } else {
5777 out += ' validate.errors = [' + (__err) + ']; return false; ';
5778 }
5779 } else {
5780 out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
5781 }
5782 } else {
5783 if (it.isTop) {
5784 if ($async) {
5785 out += ' return data; ';
5786 } else {
5787 out += ' validate.errors = null; return true; ';
5788 }
5789 } else {
5790 out += ' var ' + ($valid) + ' = true; ';
5791 }
5792 }
5793 if (it.isTop) {
5794 out += ' }; return validate; ';
5795 }
5796 return out;
5797 }
5798 if (it.isTop) {
5799 var $top = it.isTop,
5800 $lvl = it.level = 0,
5801 $dataLvl = it.dataLevel = 0,
5802 $data = 'data';
5803 it.rootId = it.resolve.fullPath(it.self._getId(it.root.schema));
5804 it.baseId = it.baseId || it.rootId;
5805 delete it.isTop;
5806 it.dataPathArr = [undefined];
5807 if (it.schema.default !== undefined && it.opts.useDefaults && it.opts.strictDefaults) {
5808 var $defaultMsg = 'default is ignored in the schema root';
5809 if (it.opts.strictDefaults === 'log') it.logger.warn($defaultMsg);
5810 else throw new Error($defaultMsg);
5811 }
5812 out += ' var vErrors = null; ';
5813 out += ' var errors = 0; ';
5814 out += ' if (rootData === undefined) rootData = data; ';
5815 } else {
5816 var $lvl = it.level,
5817 $dataLvl = it.dataLevel,
5818 $data = 'data' + ($dataLvl || '');
5819 if ($id) it.baseId = it.resolve.url(it.baseId, $id);
5820 if ($async && !it.async) throw new Error('async schema in sync schema');
5821 out += ' var errs_' + ($lvl) + ' = errors;';
5822 }
5823 var $valid = 'valid' + $lvl,
5824 $breakOnError = !it.opts.allErrors,
5825 $closingBraces1 = '',
5826 $closingBraces2 = '';
5827 var $errorKeyword;
5828 var $typeSchema = it.schema.type,
5829 $typeIsArray = Array.isArray($typeSchema);
5830 if ($typeSchema && it.opts.nullable && it.schema.nullable === true) {
5831 if ($typeIsArray) {
5832 if ($typeSchema.indexOf('null') == -1) $typeSchema = $typeSchema.concat('null');
5833 } else if ($typeSchema != 'null') {
5834 $typeSchema = [$typeSchema, 'null'];
5835 $typeIsArray = true;
5836 }
5837 }
5838 if ($typeIsArray && $typeSchema.length == 1) {
5839 $typeSchema = $typeSchema[0];
5840 $typeIsArray = false;
5841 }
5842 if (it.schema.$ref && $refKeywords) {
5843 if (it.opts.extendRefs == 'fail') {
5844 throw new Error('$ref: validation keywords used in schema at path "' + it.errSchemaPath + '" (see option extendRefs)');
5845 } else if (it.opts.extendRefs !== true) {
5846 $refKeywords = false;
5847 it.logger.warn('$ref: keywords ignored in schema at path "' + it.errSchemaPath + '"');
5848 }
5849 }
5850 if (it.schema.$comment && it.opts.$comment) {
5851 out += ' ' + (it.RULES.all.$comment.code(it, '$comment'));
5852 }
5853 if ($typeSchema) {
5854 if (it.opts.coerceTypes) {
5855 var $coerceToTypes = it.util.coerceToTypes(it.opts.coerceTypes, $typeSchema);
5856 }
5857 var $rulesGroup = it.RULES.types[$typeSchema];
5858 if ($coerceToTypes || $typeIsArray || $rulesGroup === true || ($rulesGroup && !$shouldUseGroup($rulesGroup))) {
5859 var $schemaPath = it.schemaPath + '.type',
5860 $errSchemaPath = it.errSchemaPath + '/type';
5861 var $schemaPath = it.schemaPath + '.type',
5862 $errSchemaPath = it.errSchemaPath + '/type',
5863 $method = $typeIsArray ? 'checkDataTypes' : 'checkDataType';
5864 out += ' if (' + (it.util[$method]($typeSchema, $data, true)) + ') { ';
5865 if ($coerceToTypes) {
5866 var $dataType = 'dataType' + $lvl,
5867 $coerced = 'coerced' + $lvl;
5868 out += ' var ' + ($dataType) + ' = typeof ' + ($data) + '; ';
5869 if (it.opts.coerceTypes == 'array') {
5870 out += ' if (' + ($dataType) + ' == \'object\' && Array.isArray(' + ($data) + ')) ' + ($dataType) + ' = \'array\'; ';
5871 }
5872 out += ' var ' + ($coerced) + ' = undefined; ';
5873 var $bracesCoercion = '';
5874 var arr1 = $coerceToTypes;
5875 if (arr1) {
5876 var $type, $i = -1,
5877 l1 = arr1.length - 1;
5878 while ($i < l1) {
5879 $type = arr1[$i += 1];
5880 if ($i) {
5881 out += ' if (' + ($coerced) + ' === undefined) { ';
5882 $bracesCoercion += '}';
5883 }
5884 if (it.opts.coerceTypes == 'array' && $type != 'array') {
5885 out += ' if (' + ($dataType) + ' == \'array\' && ' + ($data) + '.length == 1) { ' + ($coerced) + ' = ' + ($data) + ' = ' + ($data) + '[0]; ' + ($dataType) + ' = typeof ' + ($data) + '; } ';
5886 }
5887 if ($type == 'string') {
5888 out += ' if (' + ($dataType) + ' == \'number\' || ' + ($dataType) + ' == \'boolean\') ' + ($coerced) + ' = \'\' + ' + ($data) + '; else if (' + ($data) + ' === null) ' + ($coerced) + ' = \'\'; ';
5889 } else if ($type == 'number' || $type == 'integer') {
5890 out += ' if (' + ($dataType) + ' == \'boolean\' || ' + ($data) + ' === null || (' + ($dataType) + ' == \'string\' && ' + ($data) + ' && ' + ($data) + ' == +' + ($data) + ' ';
5891 if ($type == 'integer') {
5892 out += ' && !(' + ($data) + ' % 1)';
5893 }
5894 out += ')) ' + ($coerced) + ' = +' + ($data) + '; ';
5895 } else if ($type == 'boolean') {
5896 out += ' if (' + ($data) + ' === \'false\' || ' + ($data) + ' === 0 || ' + ($data) + ' === null) ' + ($coerced) + ' = false; else if (' + ($data) + ' === \'true\' || ' + ($data) + ' === 1) ' + ($coerced) + ' = true; ';
5897 } else if ($type == 'null') {
5898 out += ' if (' + ($data) + ' === \'\' || ' + ($data) + ' === 0 || ' + ($data) + ' === false) ' + ($coerced) + ' = null; ';
5899 } else if (it.opts.coerceTypes == 'array' && $type == 'array') {
5900 out += ' if (' + ($dataType) + ' == \'string\' || ' + ($dataType) + ' == \'number\' || ' + ($dataType) + ' == \'boolean\' || ' + ($data) + ' == null) ' + ($coerced) + ' = [' + ($data) + ']; ';
5901 }
5902 }
5903 }
5904 out += ' ' + ($bracesCoercion) + ' if (' + ($coerced) + ' === undefined) { ';
5905 var $$outStack = $$outStack || [];
5906 $$outStack.push(out);
5907 out = ''; /* istanbul ignore else */
5908 if (it.createErrors !== false) {
5909 out += ' { keyword: \'' + ($errorKeyword || 'type') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { type: \'';
5910 if ($typeIsArray) {
5911 out += '' + ($typeSchema.join(","));
5912 } else {
5913 out += '' + ($typeSchema);
5914 }
5915 out += '\' } ';
5916 if (it.opts.messages !== false) {
5917 out += ' , message: \'should be ';
5918 if ($typeIsArray) {
5919 out += '' + ($typeSchema.join(","));
5920 } else {
5921 out += '' + ($typeSchema);
5922 }
5923 out += '\' ';
5924 }
5925 if (it.opts.verbose) {
5926 out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
5927 }
5928 out += ' } ';
5929 } else {
5930 out += ' {} ';
5931 }
5932 var __err = out;
5933 out = $$outStack.pop();
5934 if (!it.compositeRule && $breakOnError) {
5935 /* istanbul ignore if */
5936 if (it.async) {
5937 out += ' throw new ValidationError([' + (__err) + ']); ';
5938 } else {
5939 out += ' validate.errors = [' + (__err) + ']; return false; ';
5940 }
5941 } else {
5942 out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
5943 }
5944 out += ' } else { ';
5945 var $parentData = $dataLvl ? 'data' + (($dataLvl - 1) || '') : 'parentData',
5946 $parentDataProperty = $dataLvl ? it.dataPathArr[$dataLvl] : 'parentDataProperty';
5947 out += ' ' + ($data) + ' = ' + ($coerced) + '; ';
5948 if (!$dataLvl) {
5949 out += 'if (' + ($parentData) + ' !== undefined)';
5950 }
5951 out += ' ' + ($parentData) + '[' + ($parentDataProperty) + '] = ' + ($coerced) + '; } ';
5952 } else {
5953 var $$outStack = $$outStack || [];
5954 $$outStack.push(out);
5955 out = ''; /* istanbul ignore else */
5956 if (it.createErrors !== false) {
5957 out += ' { keyword: \'' + ($errorKeyword || 'type') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { type: \'';
5958 if ($typeIsArray) {
5959 out += '' + ($typeSchema.join(","));
5960 } else {
5961 out += '' + ($typeSchema);
5962 }
5963 out += '\' } ';
5964 if (it.opts.messages !== false) {
5965 out += ' , message: \'should be ';
5966 if ($typeIsArray) {
5967 out += '' + ($typeSchema.join(","));
5968 } else {
5969 out += '' + ($typeSchema);
5970 }
5971 out += '\' ';
5972 }
5973 if (it.opts.verbose) {
5974 out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
5975 }
5976 out += ' } ';
5977 } else {
5978 out += ' {} ';
5979 }
5980 var __err = out;
5981 out = $$outStack.pop();
5982 if (!it.compositeRule && $breakOnError) {
5983 /* istanbul ignore if */
5984 if (it.async) {
5985 out += ' throw new ValidationError([' + (__err) + ']); ';
5986 } else {
5987 out += ' validate.errors = [' + (__err) + ']; return false; ';
5988 }
5989 } else {
5990 out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
5991 }
5992 }
5993 out += ' } ';
5994 }
5995 }
5996 if (it.schema.$ref && !$refKeywords) {
5997 out += ' ' + (it.RULES.all.$ref.code(it, '$ref')) + ' ';
5998 if ($breakOnError) {
5999 out += ' } if (errors === ';
6000 if ($top) {
6001 out += '0';
6002 } else {
6003 out += 'errs_' + ($lvl);
6004 }
6005 out += ') { ';
6006 $closingBraces2 += '}';
6007 }
6008 } else {
6009 var arr2 = it.RULES;
6010 if (arr2) {
6011 var $rulesGroup, i2 = -1,
6012 l2 = arr2.length - 1;
6013 while (i2 < l2) {
6014 $rulesGroup = arr2[i2 += 1];
6015 if ($shouldUseGroup($rulesGroup)) {
6016 if ($rulesGroup.type) {
6017 out += ' if (' + (it.util.checkDataType($rulesGroup.type, $data)) + ') { ';
6018 }
6019 if (it.opts.useDefaults) {
6020 if ($rulesGroup.type == 'object' && it.schema.properties) {
6021 var $schema = it.schema.properties,
6022 $schemaKeys = Object.keys($schema);
6023 var arr3 = $schemaKeys;
6024 if (arr3) {
6025 var $propertyKey, i3 = -1,
6026 l3 = arr3.length - 1;
6027 while (i3 < l3) {
6028 $propertyKey = arr3[i3 += 1];
6029 var $sch = $schema[$propertyKey];
6030 if ($sch.default !== undefined) {
6031 var $passData = $data + it.util.getProperty($propertyKey);
6032 if (it.compositeRule) {
6033 if (it.opts.strictDefaults) {
6034 var $defaultMsg = 'default is ignored for: ' + $passData;
6035 if (it.opts.strictDefaults === 'log') it.logger.warn($defaultMsg);
6036 else throw new Error($defaultMsg);
6037 }
6038 } else {
6039 out += ' if (' + ($passData) + ' === undefined ';
6040 if (it.opts.useDefaults == 'empty') {
6041 out += ' || ' + ($passData) + ' === null || ' + ($passData) + ' === \'\' ';
6042 }
6043 out += ' ) ' + ($passData) + ' = ';
6044 if (it.opts.useDefaults == 'shared') {
6045 out += ' ' + (it.useDefault($sch.default)) + ' ';
6046 } else {
6047 out += ' ' + (JSON.stringify($sch.default)) + ' ';
6048 }
6049 out += '; ';
6050 }
6051 }
6052 }
6053 }
6054 } else if ($rulesGroup.type == 'array' && Array.isArray(it.schema.items)) {
6055 var arr4 = it.schema.items;
6056 if (arr4) {
6057 var $sch, $i = -1,
6058 l4 = arr4.length - 1;
6059 while ($i < l4) {
6060 $sch = arr4[$i += 1];
6061 if ($sch.default !== undefined) {
6062 var $passData = $data + '[' + $i + ']';
6063 if (it.compositeRule) {
6064 if (it.opts.strictDefaults) {
6065 var $defaultMsg = 'default is ignored for: ' + $passData;
6066 if (it.opts.strictDefaults === 'log') it.logger.warn($defaultMsg);
6067 else throw new Error($defaultMsg);
6068 }
6069 } else {
6070 out += ' if (' + ($passData) + ' === undefined ';
6071 if (it.opts.useDefaults == 'empty') {
6072 out += ' || ' + ($passData) + ' === null || ' + ($passData) + ' === \'\' ';
6073 }
6074 out += ' ) ' + ($passData) + ' = ';
6075 if (it.opts.useDefaults == 'shared') {
6076 out += ' ' + (it.useDefault($sch.default)) + ' ';
6077 } else {
6078 out += ' ' + (JSON.stringify($sch.default)) + ' ';
6079 }
6080 out += '; ';
6081 }
6082 }
6083 }
6084 }
6085 }
6086 }
6087 var arr5 = $rulesGroup.rules;
6088 if (arr5) {
6089 var $rule, i5 = -1,
6090 l5 = arr5.length - 1;
6091 while (i5 < l5) {
6092 $rule = arr5[i5 += 1];
6093 if ($shouldUseRule($rule)) {
6094 var $code = $rule.code(it, $rule.keyword, $rulesGroup.type);
6095 if ($code) {
6096 out += ' ' + ($code) + ' ';
6097 if ($breakOnError) {
6098 $closingBraces1 += '}';
6099 }
6100 }
6101 }
6102 }
6103 }
6104 if ($breakOnError) {
6105 out += ' ' + ($closingBraces1) + ' ';
6106 $closingBraces1 = '';
6107 }
6108 if ($rulesGroup.type) {
6109 out += ' } ';
6110 if ($typeSchema && $typeSchema === $rulesGroup.type && !$coerceToTypes) {
6111 out += ' else { ';
6112 var $schemaPath = it.schemaPath + '.type',
6113 $errSchemaPath = it.errSchemaPath + '/type';
6114 var $$outStack = $$outStack || [];
6115 $$outStack.push(out);
6116 out = ''; /* istanbul ignore else */
6117 if (it.createErrors !== false) {
6118 out += ' { keyword: \'' + ($errorKeyword || 'type') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { type: \'';
6119 if ($typeIsArray) {
6120 out += '' + ($typeSchema.join(","));
6121 } else {
6122 out += '' + ($typeSchema);
6123 }
6124 out += '\' } ';
6125 if (it.opts.messages !== false) {
6126 out += ' , message: \'should be ';
6127 if ($typeIsArray) {
6128 out += '' + ($typeSchema.join(","));
6129 } else {
6130 out += '' + ($typeSchema);
6131 }
6132 out += '\' ';
6133 }
6134 if (it.opts.verbose) {
6135 out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
6136 }
6137 out += ' } ';
6138 } else {
6139 out += ' {} ';
6140 }
6141 var __err = out;
6142 out = $$outStack.pop();
6143 if (!it.compositeRule && $breakOnError) {
6144 /* istanbul ignore if */
6145 if (it.async) {
6146 out += ' throw new ValidationError([' + (__err) + ']); ';
6147 } else {
6148 out += ' validate.errors = [' + (__err) + ']; return false; ';
6149 }
6150 } else {
6151 out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
6152 }
6153 out += ' } ';
6154 }
6155 }
6156 if ($breakOnError) {
6157 out += ' if (errors === ';
6158 if ($top) {
6159 out += '0';
6160 } else {
6161 out += 'errs_' + ($lvl);
6162 }
6163 out += ') { ';
6164 $closingBraces2 += '}';
6165 }
6166 }
6167 }
6168 }
6169 }
6170 if ($breakOnError) {
6171 out += ' ' + ($closingBraces2) + ' ';
6172 }
6173 if ($top) {
6174 if ($async) {
6175 out += ' if (errors === 0) return data; ';
6176 out += ' else throw new ValidationError(vErrors); ';
6177 } else {
6178 out += ' validate.errors = vErrors; ';
6179 out += ' return errors === 0; ';
6180 }
6181 out += ' }; return validate;';
6182 } else {
6183 out += ' var ' + ($valid) + ' = errors === errs_' + ($lvl) + ';';
6184 }
6185 out = it.util.cleanUpCode(out);
6186 if ($top) {
6187 out = it.util.finalCleanUpCode(out, $async);
6188 }
6189
6190 function $shouldUseGroup($rulesGroup) {
6191 var rules = $rulesGroup.rules;
6192 for (var i = 0; i < rules.length; i++)
6193 if ($shouldUseRule(rules[i])) return true;
6194 }
6195
6196 function $shouldUseRule($rule) {
6197 return it.schema[$rule.keyword] !== undefined || ($rule.implements && $ruleImplementsSomeKeyword($rule));
6198 }
6199
6200 function $ruleImplementsSomeKeyword($rule) {
6201 var impl = $rule.implements;
6202 for (var i = 0; i < impl.length; i++)
6203 if (it.schema[impl[i]] !== undefined) return true;
6204 }
6205 return out;
6206}
6207
6208},{}],43:[function(require,module,exports){
6209'use strict';
6210
6211var IDENTIFIER = /^[a-z_$][a-z0-9_$-]*$/i;
6212var customRuleCode = require('./dotjs/custom');
6213var metaSchema = require('./refs/json-schema-draft-07.json');
6214
6215module.exports = {
6216 add: addKeyword,
6217 get: getKeyword,
6218 remove: removeKeyword,
6219 validate: validateKeyword
6220};
6221
6222var definitionSchema = {
6223 definitions: {
6224 simpleTypes: metaSchema.definitions.simpleTypes
6225 },
6226 type: 'object',
6227 dependencies: {
6228 schema: ['validate'],
6229 $data: ['validate'],
6230 statements: ['inline'],
6231 valid: {not: {required: ['macro']}}
6232 },
6233 properties: {
6234 type: metaSchema.properties.type,
6235 schema: {type: 'boolean'},
6236 statements: {type: 'boolean'},
6237 dependencies: {
6238 type: 'array',
6239 items: {type: 'string'}
6240 },
6241 metaSchema: {type: 'object'},
6242 modifying: {type: 'boolean'},
6243 valid: {type: 'boolean'},
6244 $data: {type: 'boolean'},
6245 async: {type: 'boolean'},
6246 errors: {
6247 anyOf: [
6248 {type: 'boolean'},
6249 {const: 'full'}
6250 ]
6251 }
6252 }
6253};
6254
6255/**
6256 * Define custom keyword
6257 * @this Ajv
6258 * @param {String} keyword custom keyword, should be unique (including different from all standard, custom and macro keywords).
6259 * @param {Object} definition keyword definition object with properties `type` (type(s) which the keyword applies to), `validate` or `compile`.
6260 * @return {Ajv} this for method chaining
6261 */
6262function addKeyword(keyword, definition) {
6263 /* jshint validthis: true */
6264 /* eslint no-shadow: 0 */
6265 var RULES = this.RULES;
6266 if (RULES.keywords[keyword])
6267 throw new Error('Keyword ' + keyword + ' is already defined');
6268
6269 if (!IDENTIFIER.test(keyword))
6270 throw new Error('Keyword ' + keyword + ' is not a valid identifier');
6271
6272 if (definition) {
6273 this.validateKeyword(definition, true);
6274
6275 var dataType = definition.type;
6276 if (Array.isArray(dataType)) {
6277 for (var i=0; i<dataType.length; i++)
6278 _addRule(keyword, dataType[i], definition);
6279 } else {
6280 _addRule(keyword, dataType, definition);
6281 }
6282
6283 var metaSchema = definition.metaSchema;
6284 if (metaSchema) {
6285 if (definition.$data && this._opts.$data) {
6286 metaSchema = {
6287 anyOf: [
6288 metaSchema,
6289 { '$ref': 'https://raw.githubusercontent.com/epoberezkin/ajv/master/lib/refs/data.json#' }
6290 ]
6291 };
6292 }
6293 definition.validateSchema = this.compile(metaSchema, true);
6294 }
6295 }
6296
6297 RULES.keywords[keyword] = RULES.all[keyword] = true;
6298
6299
6300 function _addRule(keyword, dataType, definition) {
6301 var ruleGroup;
6302 for (var i=0; i<RULES.length; i++) {
6303 var rg = RULES[i];
6304 if (rg.type == dataType) {
6305 ruleGroup = rg;
6306 break;
6307 }
6308 }
6309
6310 if (!ruleGroup) {
6311 ruleGroup = { type: dataType, rules: [] };
6312 RULES.push(ruleGroup);
6313 }
6314
6315 var rule = {
6316 keyword: keyword,
6317 definition: definition,
6318 custom: true,
6319 code: customRuleCode,
6320 implements: definition.implements
6321 };
6322 ruleGroup.rules.push(rule);
6323 RULES.custom[keyword] = rule;
6324 }
6325
6326 return this;
6327}
6328
6329
6330/**
6331 * Get keyword
6332 * @this Ajv
6333 * @param {String} keyword pre-defined or custom keyword.
6334 * @return {Object|Boolean} custom keyword definition, `true` if it is a predefined keyword, `false` otherwise.
6335 */
6336function getKeyword(keyword) {
6337 /* jshint validthis: true */
6338 var rule = this.RULES.custom[keyword];
6339 return rule ? rule.definition : this.RULES.keywords[keyword] || false;
6340}
6341
6342
6343/**
6344 * Remove keyword
6345 * @this Ajv
6346 * @param {String} keyword pre-defined or custom keyword.
6347 * @return {Ajv} this for method chaining
6348 */
6349function removeKeyword(keyword) {
6350 /* jshint validthis: true */
6351 var RULES = this.RULES;
6352 delete RULES.keywords[keyword];
6353 delete RULES.all[keyword];
6354 delete RULES.custom[keyword];
6355 for (var i=0; i<RULES.length; i++) {
6356 var rules = RULES[i].rules;
6357 for (var j=0; j<rules.length; j++) {
6358 if (rules[j].keyword == keyword) {
6359 rules.splice(j, 1);
6360 break;
6361 }
6362 }
6363 }
6364 return this;
6365}
6366
6367
6368/**
6369 * Validate keyword definition
6370 * @this Ajv
6371 * @param {Object} definition keyword definition object.
6372 * @param {Boolean} throwError true to throw exception if definition is invalid
6373 * @return {boolean} validation result
6374 */
6375function validateKeyword(definition, throwError) {
6376 validateKeyword.errors = null;
6377 var v = this._validateKeyword = this._validateKeyword
6378 || this.compile(definitionSchema, true);
6379
6380 if (v(definition)) return true;
6381 validateKeyword.errors = v.errors;
6382 if (throwError)
6383 throw new Error('custom keyword definition is invalid: ' + this.errorsText(v.errors));
6384 else
6385 return false;
6386}
6387
6388},{"./dotjs/custom":26,"./refs/json-schema-draft-07.json":46}],44:[function(require,module,exports){
6389module.exports={
6390 "$schema": "http://json-schema.org/draft-07/schema#",
6391 "$id": "https://raw.githubusercontent.com/epoberezkin/ajv/master/lib/refs/data.json#",
6392 "description": "Meta-schema for $data reference (JSON Schema extension proposal)",
6393 "type": "object",
6394 "required": [ "$data" ],
6395 "properties": {
6396 "$data": {
6397 "type": "string",
6398 "anyOf": [
6399 { "format": "relative-json-pointer" },
6400 { "format": "json-pointer" }
6401 ]
6402 }
6403 },
6404 "additionalProperties": false
6405}
6406
6407},{}],45:[function(require,module,exports){
6408module.exports={
6409 "$schema": "http://json-schema.org/draft-06/schema#",
6410 "$id": "http://json-schema.org/draft-06/schema#",
6411 "title": "Core schema meta-schema",
6412 "definitions": {
6413 "schemaArray": {
6414 "type": "array",
6415 "minItems": 1,
6416 "items": { "$ref": "#" }
6417 },
6418 "nonNegativeInteger": {
6419 "type": "integer",
6420 "minimum": 0
6421 },
6422 "nonNegativeIntegerDefault0": {
6423 "allOf": [
6424 { "$ref": "#/definitions/nonNegativeInteger" },
6425 { "default": 0 }
6426 ]
6427 },
6428 "simpleTypes": {
6429 "enum": [
6430 "array",
6431 "boolean",
6432 "integer",
6433 "null",
6434 "number",
6435 "object",
6436 "string"
6437 ]
6438 },
6439 "stringArray": {
6440 "type": "array",
6441 "items": { "type": "string" },
6442 "uniqueItems": true,
6443 "default": []
6444 }
6445 },
6446 "type": ["object", "boolean"],
6447 "properties": {
6448 "$id": {
6449 "type": "string",
6450 "format": "uri-reference"
6451 },
6452 "$schema": {
6453 "type": "string",
6454 "format": "uri"
6455 },
6456 "$ref": {
6457 "type": "string",
6458 "format": "uri-reference"
6459 },
6460 "title": {
6461 "type": "string"
6462 },
6463 "description": {
6464 "type": "string"
6465 },
6466 "default": {},
6467 "examples": {
6468 "type": "array",
6469 "items": {}
6470 },
6471 "multipleOf": {
6472 "type": "number",
6473 "exclusiveMinimum": 0
6474 },
6475 "maximum": {
6476 "type": "number"
6477 },
6478 "exclusiveMaximum": {
6479 "type": "number"
6480 },
6481 "minimum": {
6482 "type": "number"
6483 },
6484 "exclusiveMinimum": {
6485 "type": "number"
6486 },
6487 "maxLength": { "$ref": "#/definitions/nonNegativeInteger" },
6488 "minLength": { "$ref": "#/definitions/nonNegativeIntegerDefault0" },
6489 "pattern": {
6490 "type": "string",
6491 "format": "regex"
6492 },
6493 "additionalItems": { "$ref": "#" },
6494 "items": {
6495 "anyOf": [
6496 { "$ref": "#" },
6497 { "$ref": "#/definitions/schemaArray" }
6498 ],
6499 "default": {}
6500 },
6501 "maxItems": { "$ref": "#/definitions/nonNegativeInteger" },
6502 "minItems": { "$ref": "#/definitions/nonNegativeIntegerDefault0" },
6503 "uniqueItems": {
6504 "type": "boolean",
6505 "default": false
6506 },
6507 "contains": { "$ref": "#" },
6508 "maxProperties": { "$ref": "#/definitions/nonNegativeInteger" },
6509 "minProperties": { "$ref": "#/definitions/nonNegativeIntegerDefault0" },
6510 "required": { "$ref": "#/definitions/stringArray" },
6511 "additionalProperties": { "$ref": "#" },
6512 "definitions": {
6513 "type": "object",
6514 "additionalProperties": { "$ref": "#" },
6515 "default": {}
6516 },
6517 "properties": {
6518 "type": "object",
6519 "additionalProperties": { "$ref": "#" },
6520 "default": {}
6521 },
6522 "patternProperties": {
6523 "type": "object",
6524 "additionalProperties": { "$ref": "#" },
6525 "default": {}
6526 },
6527 "dependencies": {
6528 "type": "object",
6529 "additionalProperties": {
6530 "anyOf": [
6531 { "$ref": "#" },
6532 { "$ref": "#/definitions/stringArray" }
6533 ]
6534 }
6535 },
6536 "propertyNames": { "$ref": "#" },
6537 "const": {},
6538 "enum": {
6539 "type": "array",
6540 "minItems": 1,
6541 "uniqueItems": true
6542 },
6543 "type": {
6544 "anyOf": [
6545 { "$ref": "#/definitions/simpleTypes" },
6546 {
6547 "type": "array",
6548 "items": { "$ref": "#/definitions/simpleTypes" },
6549 "minItems": 1,
6550 "uniqueItems": true
6551 }
6552 ]
6553 },
6554 "format": { "type": "string" },
6555 "allOf": { "$ref": "#/definitions/schemaArray" },
6556 "anyOf": { "$ref": "#/definitions/schemaArray" },
6557 "oneOf": { "$ref": "#/definitions/schemaArray" },
6558 "not": { "$ref": "#" }
6559 },
6560 "default": {}
6561}
6562
6563},{}],46:[function(require,module,exports){
6564module.exports={
6565 "$schema": "http://json-schema.org/draft-07/schema#",
6566 "$id": "http://json-schema.org/draft-07/schema#",
6567 "title": "Core schema meta-schema",
6568 "definitions": {
6569 "schemaArray": {
6570 "type": "array",
6571 "minItems": 1,
6572 "items": { "$ref": "#" }
6573 },
6574 "nonNegativeInteger": {
6575 "type": "integer",
6576 "minimum": 0
6577 },
6578 "nonNegativeIntegerDefault0": {
6579 "allOf": [
6580 { "$ref": "#/definitions/nonNegativeInteger" },
6581 { "default": 0 }
6582 ]
6583 },
6584 "simpleTypes": {
6585 "enum": [
6586 "array",
6587 "boolean",
6588 "integer",
6589 "null",
6590 "number",
6591 "object",
6592 "string"
6593 ]
6594 },
6595 "stringArray": {
6596 "type": "array",
6597 "items": { "type": "string" },
6598 "uniqueItems": true,
6599 "default": []
6600 }
6601 },
6602 "type": ["object", "boolean"],
6603 "properties": {
6604 "$id": {
6605 "type": "string",
6606 "format": "uri-reference"
6607 },
6608 "$schema": {
6609 "type": "string",
6610 "format": "uri"
6611 },
6612 "$ref": {
6613 "type": "string",
6614 "format": "uri-reference"
6615 },
6616 "$comment": {
6617 "type": "string"
6618 },
6619 "title": {
6620 "type": "string"
6621 },
6622 "description": {
6623 "type": "string"
6624 },
6625 "default": true,
6626 "readOnly": {
6627 "type": "boolean",
6628 "default": false
6629 },
6630 "examples": {
6631 "type": "array",
6632 "items": true
6633 },
6634 "multipleOf": {
6635 "type": "number",
6636 "exclusiveMinimum": 0
6637 },
6638 "maximum": {
6639 "type": "number"
6640 },
6641 "exclusiveMaximum": {
6642 "type": "number"
6643 },
6644 "minimum": {
6645 "type": "number"
6646 },
6647 "exclusiveMinimum": {
6648 "type": "number"
6649 },
6650 "maxLength": { "$ref": "#/definitions/nonNegativeInteger" },
6651 "minLength": { "$ref": "#/definitions/nonNegativeIntegerDefault0" },
6652 "pattern": {
6653 "type": "string",
6654 "format": "regex"
6655 },
6656 "additionalItems": { "$ref": "#" },
6657 "items": {
6658 "anyOf": [
6659 { "$ref": "#" },
6660 { "$ref": "#/definitions/schemaArray" }
6661 ],
6662 "default": true
6663 },
6664 "maxItems": { "$ref": "#/definitions/nonNegativeInteger" },
6665 "minItems": { "$ref": "#/definitions/nonNegativeIntegerDefault0" },
6666 "uniqueItems": {
6667 "type": "boolean",
6668 "default": false
6669 },
6670 "contains": { "$ref": "#" },
6671 "maxProperties": { "$ref": "#/definitions/nonNegativeInteger" },
6672 "minProperties": { "$ref": "#/definitions/nonNegativeIntegerDefault0" },
6673 "required": { "$ref": "#/definitions/stringArray" },
6674 "additionalProperties": { "$ref": "#" },
6675 "definitions": {
6676 "type": "object",
6677 "additionalProperties": { "$ref": "#" },
6678 "default": {}
6679 },
6680 "properties": {
6681 "type": "object",
6682 "additionalProperties": { "$ref": "#" },
6683 "default": {}
6684 },
6685 "patternProperties": {
6686 "type": "object",
6687 "additionalProperties": { "$ref": "#" },
6688 "propertyNames": { "format": "regex" },
6689 "default": {}
6690 },
6691 "dependencies": {
6692 "type": "object",
6693 "additionalProperties": {
6694 "anyOf": [
6695 { "$ref": "#" },
6696 { "$ref": "#/definitions/stringArray" }
6697 ]
6698 }
6699 },
6700 "propertyNames": { "$ref": "#" },
6701 "const": true,
6702 "enum": {
6703 "type": "array",
6704 "items": true,
6705 "minItems": 1,
6706 "uniqueItems": true
6707 },
6708 "type": {
6709 "anyOf": [
6710 { "$ref": "#/definitions/simpleTypes" },
6711 {
6712 "type": "array",
6713 "items": { "$ref": "#/definitions/simpleTypes" },
6714 "minItems": 1,
6715 "uniqueItems": true
6716 }
6717 ]
6718 },
6719 "format": { "type": "string" },
6720 "contentMediaType": { "type": "string" },
6721 "contentEncoding": { "type": "string" },
6722 "if": {"$ref": "#"},
6723 "then": {"$ref": "#"},
6724 "else": {"$ref": "#"},
6725 "allOf": { "$ref": "#/definitions/schemaArray" },
6726 "anyOf": { "$ref": "#/definitions/schemaArray" },
6727 "oneOf": { "$ref": "#/definitions/schemaArray" },
6728 "not": { "$ref": "#" }
6729 },
6730 "default": true
6731}
6732
6733},{}],47:[function(require,module,exports){
6734var asn1 = exports;
6735
6736asn1.bignum = require('bn.js');
6737
6738asn1.define = require('./asn1/api').define;
6739asn1.base = require('./asn1/base');
6740asn1.constants = require('./asn1/constants');
6741asn1.decoders = require('./asn1/decoders');
6742asn1.encoders = require('./asn1/encoders');
6743
6744},{"./asn1/api":48,"./asn1/base":50,"./asn1/constants":54,"./asn1/decoders":56,"./asn1/encoders":59,"bn.js":80}],48:[function(require,module,exports){
6745var asn1 = require('../asn1');
6746var inherits = require('inherits');
6747
6748var api = exports;
6749
6750api.define = function define(name, body) {
6751 return new Entity(name, body);
6752};
6753
6754function Entity(name, body) {
6755 this.name = name;
6756 this.body = body;
6757
6758 this.decoders = {};
6759 this.encoders = {};
6760};
6761
6762Entity.prototype._createNamed = function createNamed(base) {
6763 var named;
6764 try {
6765 named = require('vm').runInThisContext(
6766 '(function ' + this.name + '(entity) {\n' +
6767 ' this._initNamed(entity);\n' +
6768 '})'
6769 );
6770 } catch (e) {
6771 named = function (entity) {
6772 this._initNamed(entity);
6773 };
6774 }
6775 inherits(named, base);
6776 named.prototype._initNamed = function initnamed(entity) {
6777 base.call(this, entity);
6778 };
6779
6780 return new named(this);
6781};
6782
6783Entity.prototype._getDecoder = function _getDecoder(enc) {
6784 enc = enc || 'der';
6785 // Lazily create decoder
6786 if (!this.decoders.hasOwnProperty(enc))
6787 this.decoders[enc] = this._createNamed(asn1.decoders[enc]);
6788 return this.decoders[enc];
6789};
6790
6791Entity.prototype.decode = function decode(data, enc, options) {
6792 return this._getDecoder(enc).decode(data, options);
6793};
6794
6795Entity.prototype._getEncoder = function _getEncoder(enc) {
6796 enc = enc || 'der';
6797 // Lazily create encoder
6798 if (!this.encoders.hasOwnProperty(enc))
6799 this.encoders[enc] = this._createNamed(asn1.encoders[enc]);
6800 return this.encoders[enc];
6801};
6802
6803Entity.prototype.encode = function encode(data, enc, /* internal */ reporter) {
6804 return this._getEncoder(enc).encode(data, reporter);
6805};
6806
6807},{"../asn1":47,"inherits":210,"vm":403}],49:[function(require,module,exports){
6808var inherits = require('inherits');
6809var Reporter = require('../base').Reporter;
6810var Buffer = require('buffer').Buffer;
6811
6812function DecoderBuffer(base, options) {
6813 Reporter.call(this, options);
6814 if (!Buffer.isBuffer(base)) {
6815 this.error('Input not Buffer');
6816 return;
6817 }
6818
6819 this.base = base;
6820 this.offset = 0;
6821 this.length = base.length;
6822}
6823inherits(DecoderBuffer, Reporter);
6824exports.DecoderBuffer = DecoderBuffer;
6825
6826DecoderBuffer.prototype.save = function save() {
6827 return { offset: this.offset, reporter: Reporter.prototype.save.call(this) };
6828};
6829
6830DecoderBuffer.prototype.restore = function restore(save) {
6831 // Return skipped data
6832 var res = new DecoderBuffer(this.base);
6833 res.offset = save.offset;
6834 res.length = this.offset;
6835
6836 this.offset = save.offset;
6837 Reporter.prototype.restore.call(this, save.reporter);
6838
6839 return res;
6840};
6841
6842DecoderBuffer.prototype.isEmpty = function isEmpty() {
6843 return this.offset === this.length;
6844};
6845
6846DecoderBuffer.prototype.readUInt8 = function readUInt8(fail) {
6847 if (this.offset + 1 <= this.length)
6848 return this.base.readUInt8(this.offset++, true);
6849 else
6850 return this.error(fail || 'DecoderBuffer overrun');
6851}
6852
6853DecoderBuffer.prototype.skip = function skip(bytes, fail) {
6854 if (!(this.offset + bytes <= this.length))
6855 return this.error(fail || 'DecoderBuffer overrun');
6856
6857 var res = new DecoderBuffer(this.base);
6858
6859 // Share reporter state
6860 res._reporterState = this._reporterState;
6861
6862 res.offset = this.offset;
6863 res.length = this.offset + bytes;
6864 this.offset += bytes;
6865 return res;
6866}
6867
6868DecoderBuffer.prototype.raw = function raw(save) {
6869 return this.base.slice(save ? save.offset : this.offset, this.length);
6870}
6871
6872function EncoderBuffer(value, reporter) {
6873 if (Array.isArray(value)) {
6874 this.length = 0;
6875 this.value = value.map(function(item) {
6876 if (!(item instanceof EncoderBuffer))
6877 item = new EncoderBuffer(item, reporter);
6878 this.length += item.length;
6879 return item;
6880 }, this);
6881 } else if (typeof value === 'number') {
6882 if (!(0 <= value && value <= 0xff))
6883 return reporter.error('non-byte EncoderBuffer value');
6884 this.value = value;
6885 this.length = 1;
6886 } else if (typeof value === 'string') {
6887 this.value = value;
6888 this.length = Buffer.byteLength(value);
6889 } else if (Buffer.isBuffer(value)) {
6890 this.value = value;
6891 this.length = value.length;
6892 } else {
6893 return reporter.error('Unsupported type: ' + typeof value);
6894 }
6895}
6896exports.EncoderBuffer = EncoderBuffer;
6897
6898EncoderBuffer.prototype.join = function join(out, offset) {
6899 if (!out)
6900 out = new Buffer(this.length);
6901 if (!offset)
6902 offset = 0;
6903
6904 if (this.length === 0)
6905 return out;
6906
6907 if (Array.isArray(this.value)) {
6908 this.value.forEach(function(item) {
6909 item.join(out, offset);
6910 offset += item.length;
6911 });
6912 } else {
6913 if (typeof this.value === 'number')
6914 out[offset] = this.value;
6915 else if (typeof this.value === 'string')
6916 out.write(this.value, offset);
6917 else if (Buffer.isBuffer(this.value))
6918 this.value.copy(out, offset);
6919 offset += this.length;
6920 }
6921
6922 return out;
6923};
6924
6925},{"../base":50,"buffer":114,"inherits":210}],50:[function(require,module,exports){
6926var base = exports;
6927
6928base.Reporter = require('./reporter').Reporter;
6929base.DecoderBuffer = require('./buffer').DecoderBuffer;
6930base.EncoderBuffer = require('./buffer').EncoderBuffer;
6931base.Node = require('./node');
6932
6933},{"./buffer":49,"./node":51,"./reporter":52}],51:[function(require,module,exports){
6934var Reporter = require('../base').Reporter;
6935var EncoderBuffer = require('../base').EncoderBuffer;
6936var DecoderBuffer = require('../base').DecoderBuffer;
6937var assert = require('minimalistic-assert');
6938
6939// Supported tags
6940var tags = [
6941 'seq', 'seqof', 'set', 'setof', 'objid', 'bool',
6942 'gentime', 'utctime', 'null_', 'enum', 'int', 'objDesc',
6943 'bitstr', 'bmpstr', 'charstr', 'genstr', 'graphstr', 'ia5str', 'iso646str',
6944 'numstr', 'octstr', 'printstr', 't61str', 'unistr', 'utf8str', 'videostr'
6945];
6946
6947// Public methods list
6948var methods = [
6949 'key', 'obj', 'use', 'optional', 'explicit', 'implicit', 'def', 'choice',
6950 'any', 'contains'
6951].concat(tags);
6952
6953// Overrided methods list
6954var overrided = [
6955 '_peekTag', '_decodeTag', '_use',
6956 '_decodeStr', '_decodeObjid', '_decodeTime',
6957 '_decodeNull', '_decodeInt', '_decodeBool', '_decodeList',
6958
6959 '_encodeComposite', '_encodeStr', '_encodeObjid', '_encodeTime',
6960 '_encodeNull', '_encodeInt', '_encodeBool'
6961];
6962
6963function Node(enc, parent) {
6964 var state = {};
6965 this._baseState = state;
6966
6967 state.enc = enc;
6968
6969 state.parent = parent || null;
6970 state.children = null;
6971
6972 // State
6973 state.tag = null;
6974 state.args = null;
6975 state.reverseArgs = null;
6976 state.choice = null;
6977 state.optional = false;
6978 state.any = false;
6979 state.obj = false;
6980 state.use = null;
6981 state.useDecoder = null;
6982 state.key = null;
6983 state['default'] = null;
6984 state.explicit = null;
6985 state.implicit = null;
6986 state.contains = null;
6987
6988 // Should create new instance on each method
6989 if (!state.parent) {
6990 state.children = [];
6991 this._wrap();
6992 }
6993}
6994module.exports = Node;
6995
6996var stateProps = [
6997 'enc', 'parent', 'children', 'tag', 'args', 'reverseArgs', 'choice',
6998 'optional', 'any', 'obj', 'use', 'alteredUse', 'key', 'default', 'explicit',
6999 'implicit', 'contains'
7000];
7001
7002Node.prototype.clone = function clone() {
7003 var state = this._baseState;
7004 var cstate = {};
7005 stateProps.forEach(function(prop) {
7006 cstate[prop] = state[prop];
7007 });
7008 var res = new this.constructor(cstate.parent);
7009 res._baseState = cstate;
7010 return res;
7011};
7012
7013Node.prototype._wrap = function wrap() {
7014 var state = this._baseState;
7015 methods.forEach(function(method) {
7016 this[method] = function _wrappedMethod() {
7017 var clone = new this.constructor(this);
7018 state.children.push(clone);
7019 return clone[method].apply(clone, arguments);
7020 };
7021 }, this);
7022};
7023
7024Node.prototype._init = function init(body) {
7025 var state = this._baseState;
7026
7027 assert(state.parent === null);
7028 body.call(this);
7029
7030 // Filter children
7031 state.children = state.children.filter(function(child) {
7032 return child._baseState.parent === this;
7033 }, this);
7034 assert.equal(state.children.length, 1, 'Root node can have only one child');
7035};
7036
7037Node.prototype._useArgs = function useArgs(args) {
7038 var state = this._baseState;
7039
7040 // Filter children and args
7041 var children = args.filter(function(arg) {
7042 return arg instanceof this.constructor;
7043 }, this);
7044 args = args.filter(function(arg) {
7045 return !(arg instanceof this.constructor);
7046 }, this);
7047
7048 if (children.length !== 0) {
7049 assert(state.children === null);
7050 state.children = children;
7051
7052 // Replace parent to maintain backward link
7053 children.forEach(function(child) {
7054 child._baseState.parent = this;
7055 }, this);
7056 }
7057 if (args.length !== 0) {
7058 assert(state.args === null);
7059 state.args = args;
7060 state.reverseArgs = args.map(function(arg) {
7061 if (typeof arg !== 'object' || arg.constructor !== Object)
7062 return arg;
7063
7064 var res = {};
7065 Object.keys(arg).forEach(function(key) {
7066 if (key == (key | 0))
7067 key |= 0;
7068 var value = arg[key];
7069 res[value] = key;
7070 });
7071 return res;
7072 });
7073 }
7074};
7075
7076//
7077// Overrided methods
7078//
7079
7080overrided.forEach(function(method) {
7081 Node.prototype[method] = function _overrided() {
7082 var state = this._baseState;
7083 throw new Error(method + ' not implemented for encoding: ' + state.enc);
7084 };
7085});
7086
7087//
7088// Public methods
7089//
7090
7091tags.forEach(function(tag) {
7092 Node.prototype[tag] = function _tagMethod() {
7093 var state = this._baseState;
7094 var args = Array.prototype.slice.call(arguments);
7095
7096 assert(state.tag === null);
7097 state.tag = tag;
7098
7099 this._useArgs(args);
7100
7101 return this;
7102 };
7103});
7104
7105Node.prototype.use = function use(item) {
7106 assert(item);
7107 var state = this._baseState;
7108
7109 assert(state.use === null);
7110 state.use = item;
7111
7112 return this;
7113};
7114
7115Node.prototype.optional = function optional() {
7116 var state = this._baseState;
7117
7118 state.optional = true;
7119
7120 return this;
7121};
7122
7123Node.prototype.def = function def(val) {
7124 var state = this._baseState;
7125
7126 assert(state['default'] === null);
7127 state['default'] = val;
7128 state.optional = true;
7129
7130 return this;
7131};
7132
7133Node.prototype.explicit = function explicit(num) {
7134 var state = this._baseState;
7135
7136 assert(state.explicit === null && state.implicit === null);
7137 state.explicit = num;
7138
7139 return this;
7140};
7141
7142Node.prototype.implicit = function implicit(num) {
7143 var state = this._baseState;
7144
7145 assert(state.explicit === null && state.implicit === null);
7146 state.implicit = num;
7147
7148 return this;
7149};
7150
7151Node.prototype.obj = function obj() {
7152 var state = this._baseState;
7153 var args = Array.prototype.slice.call(arguments);
7154
7155 state.obj = true;
7156
7157 if (args.length !== 0)
7158 this._useArgs(args);
7159
7160 return this;
7161};
7162
7163Node.prototype.key = function key(newKey) {
7164 var state = this._baseState;
7165
7166 assert(state.key === null);
7167 state.key = newKey;
7168
7169 return this;
7170};
7171
7172Node.prototype.any = function any() {
7173 var state = this._baseState;
7174
7175 state.any = true;
7176
7177 return this;
7178};
7179
7180Node.prototype.choice = function choice(obj) {
7181 var state = this._baseState;
7182
7183 assert(state.choice === null);
7184 state.choice = obj;
7185 this._useArgs(Object.keys(obj).map(function(key) {
7186 return obj[key];
7187 }));
7188
7189 return this;
7190};
7191
7192Node.prototype.contains = function contains(item) {
7193 var state = this._baseState;
7194
7195 assert(state.use === null);
7196 state.contains = item;
7197
7198 return this;
7199};
7200
7201//
7202// Decoding
7203//
7204
7205Node.prototype._decode = function decode(input, options) {
7206 var state = this._baseState;
7207
7208 // Decode root node
7209 if (state.parent === null)
7210 return input.wrapResult(state.children[0]._decode(input, options));
7211
7212 var result = state['default'];
7213 var present = true;
7214
7215 var prevKey = null;
7216 if (state.key !== null)
7217 prevKey = input.enterKey(state.key);
7218
7219 // Check if tag is there
7220 if (state.optional) {
7221 var tag = null;
7222 if (state.explicit !== null)
7223 tag = state.explicit;
7224 else if (state.implicit !== null)
7225 tag = state.implicit;
7226 else if (state.tag !== null)
7227 tag = state.tag;
7228
7229 if (tag === null && !state.any) {
7230 // Trial and Error
7231 var save = input.save();
7232 try {
7233 if (state.choice === null)
7234 this._decodeGeneric(state.tag, input, options);
7235 else
7236 this._decodeChoice(input, options);
7237 present = true;
7238 } catch (e) {
7239 present = false;
7240 }
7241 input.restore(save);
7242 } else {
7243 present = this._peekTag(input, tag, state.any);
7244
7245 if (input.isError(present))
7246 return present;
7247 }
7248 }
7249
7250 // Push object on stack
7251 var prevObj;
7252 if (state.obj && present)
7253 prevObj = input.enterObject();
7254
7255 if (present) {
7256 // Unwrap explicit values
7257 if (state.explicit !== null) {
7258 var explicit = this._decodeTag(input, state.explicit);
7259 if (input.isError(explicit))
7260 return explicit;
7261 input = explicit;
7262 }
7263
7264 var start = input.offset;
7265
7266 // Unwrap implicit and normal values
7267 if (state.use === null && state.choice === null) {
7268 if (state.any)
7269 var save = input.save();
7270 var body = this._decodeTag(
7271 input,
7272 state.implicit !== null ? state.implicit : state.tag,
7273 state.any
7274 );
7275 if (input.isError(body))
7276 return body;
7277
7278 if (state.any)
7279 result = input.raw(save);
7280 else
7281 input = body;
7282 }
7283
7284 if (options && options.track && state.tag !== null)
7285 options.track(input.path(), start, input.length, 'tagged');
7286
7287 if (options && options.track && state.tag !== null)
7288 options.track(input.path(), input.offset, input.length, 'content');
7289
7290 // Select proper method for tag
7291 if (state.any)
7292 result = result;
7293 else if (state.choice === null)
7294 result = this._decodeGeneric(state.tag, input, options);
7295 else
7296 result = this._decodeChoice(input, options);
7297
7298 if (input.isError(result))
7299 return result;
7300
7301 // Decode children
7302 if (!state.any && state.choice === null && state.children !== null) {
7303 state.children.forEach(function decodeChildren(child) {
7304 // NOTE: We are ignoring errors here, to let parser continue with other
7305 // parts of encoded data
7306 child._decode(input, options);
7307 });
7308 }
7309
7310 // Decode contained/encoded by schema, only in bit or octet strings
7311 if (state.contains && (state.tag === 'octstr' || state.tag === 'bitstr')) {
7312 var data = new DecoderBuffer(result);
7313 result = this._getUse(state.contains, input._reporterState.obj)
7314 ._decode(data, options);
7315 }
7316 }
7317
7318 // Pop object
7319 if (state.obj && present)
7320 result = input.leaveObject(prevObj);
7321
7322 // Set key
7323 if (state.key !== null && (result !== null || present === true))
7324 input.leaveKey(prevKey, state.key, result);
7325 else if (prevKey !== null)
7326 input.exitKey(prevKey);
7327
7328 return result;
7329};
7330
7331Node.prototype._decodeGeneric = function decodeGeneric(tag, input, options) {
7332 var state = this._baseState;
7333
7334 if (tag === 'seq' || tag === 'set')
7335 return null;
7336 if (tag === 'seqof' || tag === 'setof')
7337 return this._decodeList(input, tag, state.args[0], options);
7338 else if (/str$/.test(tag))
7339 return this._decodeStr(input, tag, options);
7340 else if (tag === 'objid' && state.args)
7341 return this._decodeObjid(input, state.args[0], state.args[1], options);
7342 else if (tag === 'objid')
7343 return this._decodeObjid(input, null, null, options);
7344 else if (tag === 'gentime' || tag === 'utctime')
7345 return this._decodeTime(input, tag, options);
7346 else if (tag === 'null_')
7347 return this._decodeNull(input, options);
7348 else if (tag === 'bool')
7349 return this._decodeBool(input, options);
7350 else if (tag === 'objDesc')
7351 return this._decodeStr(input, tag, options);
7352 else if (tag === 'int' || tag === 'enum')
7353 return this._decodeInt(input, state.args && state.args[0], options);
7354
7355 if (state.use !== null) {
7356 return this._getUse(state.use, input._reporterState.obj)
7357 ._decode(input, options);
7358 } else {
7359 return input.error('unknown tag: ' + tag);
7360 }
7361};
7362
7363Node.prototype._getUse = function _getUse(entity, obj) {
7364
7365 var state = this._baseState;
7366 // Create altered use decoder if implicit is set
7367 state.useDecoder = this._use(entity, obj);
7368 assert(state.useDecoder._baseState.parent === null);
7369 state.useDecoder = state.useDecoder._baseState.children[0];
7370 if (state.implicit !== state.useDecoder._baseState.implicit) {
7371 state.useDecoder = state.useDecoder.clone();
7372 state.useDecoder._baseState.implicit = state.implicit;
7373 }
7374 return state.useDecoder;
7375};
7376
7377Node.prototype._decodeChoice = function decodeChoice(input, options) {
7378 var state = this._baseState;
7379 var result = null;
7380 var match = false;
7381
7382 Object.keys(state.choice).some(function(key) {
7383 var save = input.save();
7384 var node = state.choice[key];
7385 try {
7386 var value = node._decode(input, options);
7387 if (input.isError(value))
7388 return false;
7389
7390 result = { type: key, value: value };
7391 match = true;
7392 } catch (e) {
7393 input.restore(save);
7394 return false;
7395 }
7396 return true;
7397 }, this);
7398
7399 if (!match)
7400 return input.error('Choice not matched');
7401
7402 return result;
7403};
7404
7405//
7406// Encoding
7407//
7408
7409Node.prototype._createEncoderBuffer = function createEncoderBuffer(data) {
7410 return new EncoderBuffer(data, this.reporter);
7411};
7412
7413Node.prototype._encode = function encode(data, reporter, parent) {
7414 var state = this._baseState;
7415 if (state['default'] !== null && state['default'] === data)
7416 return;
7417
7418 var result = this._encodeValue(data, reporter, parent);
7419 if (result === undefined)
7420 return;
7421
7422 if (this._skipDefault(result, reporter, parent))
7423 return;
7424
7425 return result;
7426};
7427
7428Node.prototype._encodeValue = function encode(data, reporter, parent) {
7429 var state = this._baseState;
7430
7431 // Decode root node
7432 if (state.parent === null)
7433 return state.children[0]._encode(data, reporter || new Reporter());
7434
7435 var result = null;
7436
7437 // Set reporter to share it with a child class
7438 this.reporter = reporter;
7439
7440 // Check if data is there
7441 if (state.optional && data === undefined) {
7442 if (state['default'] !== null)
7443 data = state['default']
7444 else
7445 return;
7446 }
7447
7448 // Encode children first
7449 var content = null;
7450 var primitive = false;
7451 if (state.any) {
7452 // Anything that was given is translated to buffer
7453 result = this._createEncoderBuffer(data);
7454 } else if (state.choice) {
7455 result = this._encodeChoice(data, reporter);
7456 } else if (state.contains) {
7457 content = this._getUse(state.contains, parent)._encode(data, reporter);
7458 primitive = true;
7459 } else if (state.children) {
7460 content = state.children.map(function(child) {
7461 if (child._baseState.tag === 'null_')
7462 return child._encode(null, reporter, data);
7463
7464 if (child._baseState.key === null)
7465 return reporter.error('Child should have a key');
7466 var prevKey = reporter.enterKey(child._baseState.key);
7467
7468 if (typeof data !== 'object')
7469 return reporter.error('Child expected, but input is not object');
7470
7471 var res = child._encode(data[child._baseState.key], reporter, data);
7472 reporter.leaveKey(prevKey);
7473
7474 return res;
7475 }, this).filter(function(child) {
7476 return child;
7477 });
7478 content = this._createEncoderBuffer(content);
7479 } else {
7480 if (state.tag === 'seqof' || state.tag === 'setof') {
7481 // TODO(indutny): this should be thrown on DSL level
7482 if (!(state.args && state.args.length === 1))
7483 return reporter.error('Too many args for : ' + state.tag);
7484
7485 if (!Array.isArray(data))
7486 return reporter.error('seqof/setof, but data is not Array');
7487
7488 var child = this.clone();
7489 child._baseState.implicit = null;
7490 content = this._createEncoderBuffer(data.map(function(item) {
7491 var state = this._baseState;
7492
7493 return this._getUse(state.args[0], data)._encode(item, reporter);
7494 }, child));
7495 } else if (state.use !== null) {
7496 result = this._getUse(state.use, parent)._encode(data, reporter);
7497 } else {
7498 content = this._encodePrimitive(state.tag, data);
7499 primitive = true;
7500 }
7501 }
7502
7503 // Encode data itself
7504 var result;
7505 if (!state.any && state.choice === null) {
7506 var tag = state.implicit !== null ? state.implicit : state.tag;
7507 var cls = state.implicit === null ? 'universal' : 'context';
7508
7509 if (tag === null) {
7510 if (state.use === null)
7511 reporter.error('Tag could be omitted only for .use()');
7512 } else {
7513 if (state.use === null)
7514 result = this._encodeComposite(tag, primitive, cls, content);
7515 }
7516 }
7517
7518 // Wrap in explicit
7519 if (state.explicit !== null)
7520 result = this._encodeComposite(state.explicit, false, 'context', result);
7521
7522 return result;
7523};
7524
7525Node.prototype._encodeChoice = function encodeChoice(data, reporter) {
7526 var state = this._baseState;
7527
7528 var node = state.choice[data.type];
7529 if (!node) {
7530 assert(
7531 false,
7532 data.type + ' not found in ' +
7533 JSON.stringify(Object.keys(state.choice)));
7534 }
7535 return node._encode(data.value, reporter);
7536};
7537
7538Node.prototype._encodePrimitive = function encodePrimitive(tag, data) {
7539 var state = this._baseState;
7540
7541 if (/str$/.test(tag))
7542 return this._encodeStr(data, tag);
7543 else if (tag === 'objid' && state.args)
7544 return this._encodeObjid(data, state.reverseArgs[0], state.args[1]);
7545 else if (tag === 'objid')
7546 return this._encodeObjid(data, null, null);
7547 else if (tag === 'gentime' || tag === 'utctime')
7548 return this._encodeTime(data, tag);
7549 else if (tag === 'null_')
7550 return this._encodeNull();
7551 else if (tag === 'int' || tag === 'enum')
7552 return this._encodeInt(data, state.args && state.reverseArgs[0]);
7553 else if (tag === 'bool')
7554 return this._encodeBool(data);
7555 else if (tag === 'objDesc')
7556 return this._encodeStr(data, tag);
7557 else
7558 throw new Error('Unsupported tag: ' + tag);
7559};
7560
7561Node.prototype._isNumstr = function isNumstr(str) {
7562 return /^[0-9 ]*$/.test(str);
7563};
7564
7565Node.prototype._isPrintstr = function isPrintstr(str) {
7566 return /^[A-Za-z0-9 '\(\)\+,\-\.\/:=\?]*$/.test(str);
7567};
7568
7569},{"../base":50,"minimalistic-assert":237}],52:[function(require,module,exports){
7570var inherits = require('inherits');
7571
7572function Reporter(options) {
7573 this._reporterState = {
7574 obj: null,
7575 path: [],
7576 options: options || {},
7577 errors: []
7578 };
7579}
7580exports.Reporter = Reporter;
7581
7582Reporter.prototype.isError = function isError(obj) {
7583 return obj instanceof ReporterError;
7584};
7585
7586Reporter.prototype.save = function save() {
7587 var state = this._reporterState;
7588
7589 return { obj: state.obj, pathLen: state.path.length };
7590};
7591
7592Reporter.prototype.restore = function restore(data) {
7593 var state = this._reporterState;
7594
7595 state.obj = data.obj;
7596 state.path = state.path.slice(0, data.pathLen);
7597};
7598
7599Reporter.prototype.enterKey = function enterKey(key) {
7600 return this._reporterState.path.push(key);
7601};
7602
7603Reporter.prototype.exitKey = function exitKey(index) {
7604 var state = this._reporterState;
7605
7606 state.path = state.path.slice(0, index - 1);
7607};
7608
7609Reporter.prototype.leaveKey = function leaveKey(index, key, value) {
7610 var state = this._reporterState;
7611
7612 this.exitKey(index);
7613 if (state.obj !== null)
7614 state.obj[key] = value;
7615};
7616
7617Reporter.prototype.path = function path() {
7618 return this._reporterState.path.join('/');
7619};
7620
7621Reporter.prototype.enterObject = function enterObject() {
7622 var state = this._reporterState;
7623
7624 var prev = state.obj;
7625 state.obj = {};
7626 return prev;
7627};
7628
7629Reporter.prototype.leaveObject = function leaveObject(prev) {
7630 var state = this._reporterState;
7631
7632 var now = state.obj;
7633 state.obj = prev;
7634 return now;
7635};
7636
7637Reporter.prototype.error = function error(msg) {
7638 var err;
7639 var state = this._reporterState;
7640
7641 var inherited = msg instanceof ReporterError;
7642 if (inherited) {
7643 err = msg;
7644 } else {
7645 err = new ReporterError(state.path.map(function(elem) {
7646 return '[' + JSON.stringify(elem) + ']';
7647 }).join(''), msg.message || msg, msg.stack);
7648 }
7649
7650 if (!state.options.partial)
7651 throw err;
7652
7653 if (!inherited)
7654 state.errors.push(err);
7655
7656 return err;
7657};
7658
7659Reporter.prototype.wrapResult = function wrapResult(result) {
7660 var state = this._reporterState;
7661 if (!state.options.partial)
7662 return result;
7663
7664 return {
7665 result: this.isError(result) ? null : result,
7666 errors: state.errors
7667 };
7668};
7669
7670function ReporterError(path, msg) {
7671 this.path = path;
7672 this.rethrow(msg);
7673};
7674inherits(ReporterError, Error);
7675
7676ReporterError.prototype.rethrow = function rethrow(msg) {
7677 this.message = msg + ' at: ' + (this.path || '(shallow)');
7678 if (Error.captureStackTrace)
7679 Error.captureStackTrace(this, ReporterError);
7680
7681 if (!this.stack) {
7682 try {
7683 // IE only adds stack when thrown
7684 throw new Error(this.message);
7685 } catch (e) {
7686 this.stack = e.stack;
7687 }
7688 }
7689 return this;
7690};
7691
7692},{"inherits":210}],53:[function(require,module,exports){
7693var constants = require('../constants');
7694
7695exports.tagClass = {
7696 0: 'universal',
7697 1: 'application',
7698 2: 'context',
7699 3: 'private'
7700};
7701exports.tagClassByName = constants._reverse(exports.tagClass);
7702
7703exports.tag = {
7704 0x00: 'end',
7705 0x01: 'bool',
7706 0x02: 'int',
7707 0x03: 'bitstr',
7708 0x04: 'octstr',
7709 0x05: 'null_',
7710 0x06: 'objid',
7711 0x07: 'objDesc',
7712 0x08: 'external',
7713 0x09: 'real',
7714 0x0a: 'enum',
7715 0x0b: 'embed',
7716 0x0c: 'utf8str',
7717 0x0d: 'relativeOid',
7718 0x10: 'seq',
7719 0x11: 'set',
7720 0x12: 'numstr',
7721 0x13: 'printstr',
7722 0x14: 't61str',
7723 0x15: 'videostr',
7724 0x16: 'ia5str',
7725 0x17: 'utctime',
7726 0x18: 'gentime',
7727 0x19: 'graphstr',
7728 0x1a: 'iso646str',
7729 0x1b: 'genstr',
7730 0x1c: 'unistr',
7731 0x1d: 'charstr',
7732 0x1e: 'bmpstr'
7733};
7734exports.tagByName = constants._reverse(exports.tag);
7735
7736},{"../constants":54}],54:[function(require,module,exports){
7737var constants = exports;
7738
7739// Helper
7740constants._reverse = function reverse(map) {
7741 var res = {};
7742
7743 Object.keys(map).forEach(function(key) {
7744 // Convert key to integer if it is stringified
7745 if ((key | 0) == key)
7746 key = key | 0;
7747
7748 var value = map[key];
7749 res[value] = key;
7750 });
7751
7752 return res;
7753};
7754
7755constants.der = require('./der');
7756
7757},{"./der":53}],55:[function(require,module,exports){
7758var inherits = require('inherits');
7759
7760var asn1 = require('../../asn1');
7761var base = asn1.base;
7762var bignum = asn1.bignum;
7763
7764// Import DER constants
7765var der = asn1.constants.der;
7766
7767function DERDecoder(entity) {
7768 this.enc = 'der';
7769 this.name = entity.name;
7770 this.entity = entity;
7771
7772 // Construct base tree
7773 this.tree = new DERNode();
7774 this.tree._init(entity.body);
7775};
7776module.exports = DERDecoder;
7777
7778DERDecoder.prototype.decode = function decode(data, options) {
7779 if (!(data instanceof base.DecoderBuffer))
7780 data = new base.DecoderBuffer(data, options);
7781
7782 return this.tree._decode(data, options);
7783};
7784
7785// Tree methods
7786
7787function DERNode(parent) {
7788 base.Node.call(this, 'der', parent);
7789}
7790inherits(DERNode, base.Node);
7791
7792DERNode.prototype._peekTag = function peekTag(buffer, tag, any) {
7793 if (buffer.isEmpty())
7794 return false;
7795
7796 var state = buffer.save();
7797 var decodedTag = derDecodeTag(buffer, 'Failed to peek tag: "' + tag + '"');
7798 if (buffer.isError(decodedTag))
7799 return decodedTag;
7800
7801 buffer.restore(state);
7802
7803 return decodedTag.tag === tag || decodedTag.tagStr === tag ||
7804 (decodedTag.tagStr + 'of') === tag || any;
7805};
7806
7807DERNode.prototype._decodeTag = function decodeTag(buffer, tag, any) {
7808 var decodedTag = derDecodeTag(buffer,
7809 'Failed to decode tag of "' + tag + '"');
7810 if (buffer.isError(decodedTag))
7811 return decodedTag;
7812
7813 var len = derDecodeLen(buffer,
7814 decodedTag.primitive,
7815 'Failed to get length of "' + tag + '"');
7816
7817 // Failure
7818 if (buffer.isError(len))
7819 return len;
7820
7821 if (!any &&
7822 decodedTag.tag !== tag &&
7823 decodedTag.tagStr !== tag &&
7824 decodedTag.tagStr + 'of' !== tag) {
7825 return buffer.error('Failed to match tag: "' + tag + '"');
7826 }
7827
7828 if (decodedTag.primitive || len !== null)
7829 return buffer.skip(len, 'Failed to match body of: "' + tag + '"');
7830
7831 // Indefinite length... find END tag
7832 var state = buffer.save();
7833 var res = this._skipUntilEnd(
7834 buffer,
7835 'Failed to skip indefinite length body: "' + this.tag + '"');
7836 if (buffer.isError(res))
7837 return res;
7838
7839 len = buffer.offset - state.offset;
7840 buffer.restore(state);
7841 return buffer.skip(len, 'Failed to match body of: "' + tag + '"');
7842};
7843
7844DERNode.prototype._skipUntilEnd = function skipUntilEnd(buffer, fail) {
7845 while (true) {
7846 var tag = derDecodeTag(buffer, fail);
7847 if (buffer.isError(tag))
7848 return tag;
7849 var len = derDecodeLen(buffer, tag.primitive, fail);
7850 if (buffer.isError(len))
7851 return len;
7852
7853 var res;
7854 if (tag.primitive || len !== null)
7855 res = buffer.skip(len)
7856 else
7857 res = this._skipUntilEnd(buffer, fail);
7858
7859 // Failure
7860 if (buffer.isError(res))
7861 return res;
7862
7863 if (tag.tagStr === 'end')
7864 break;
7865 }
7866};
7867
7868DERNode.prototype._decodeList = function decodeList(buffer, tag, decoder,
7869 options) {
7870 var result = [];
7871 while (!buffer.isEmpty()) {
7872 var possibleEnd = this._peekTag(buffer, 'end');
7873 if (buffer.isError(possibleEnd))
7874 return possibleEnd;
7875
7876 var res = decoder.decode(buffer, 'der', options);
7877 if (buffer.isError(res) && possibleEnd)
7878 break;
7879 result.push(res);
7880 }
7881 return result;
7882};
7883
7884DERNode.prototype._decodeStr = function decodeStr(buffer, tag) {
7885 if (tag === 'bitstr') {
7886 var unused = buffer.readUInt8();
7887 if (buffer.isError(unused))
7888 return unused;
7889 return { unused: unused, data: buffer.raw() };
7890 } else if (tag === 'bmpstr') {
7891 var raw = buffer.raw();
7892 if (raw.length % 2 === 1)
7893 return buffer.error('Decoding of string type: bmpstr length mismatch');
7894
7895 var str = '';
7896 for (var i = 0; i < raw.length / 2; i++) {
7897 str += String.fromCharCode(raw.readUInt16BE(i * 2));
7898 }
7899 return str;
7900 } else if (tag === 'numstr') {
7901 var numstr = buffer.raw().toString('ascii');
7902 if (!this._isNumstr(numstr)) {
7903 return buffer.error('Decoding of string type: ' +
7904 'numstr unsupported characters');
7905 }
7906 return numstr;
7907 } else if (tag === 'octstr') {
7908 return buffer.raw();
7909 } else if (tag === 'objDesc') {
7910 return buffer.raw();
7911 } else if (tag === 'printstr') {
7912 var printstr = buffer.raw().toString('ascii');
7913 if (!this._isPrintstr(printstr)) {
7914 return buffer.error('Decoding of string type: ' +
7915 'printstr unsupported characters');
7916 }
7917 return printstr;
7918 } else if (/str$/.test(tag)) {
7919 return buffer.raw().toString();
7920 } else {
7921 return buffer.error('Decoding of string type: ' + tag + ' unsupported');
7922 }
7923};
7924
7925DERNode.prototype._decodeObjid = function decodeObjid(buffer, values, relative) {
7926 var result;
7927 var identifiers = [];
7928 var ident = 0;
7929 while (!buffer.isEmpty()) {
7930 var subident = buffer.readUInt8();
7931 ident <<= 7;
7932 ident |= subident & 0x7f;
7933 if ((subident & 0x80) === 0) {
7934 identifiers.push(ident);
7935 ident = 0;
7936 }
7937 }
7938 if (subident & 0x80)
7939 identifiers.push(ident);
7940
7941 var first = (identifiers[0] / 40) | 0;
7942 var second = identifiers[0] % 40;
7943
7944 if (relative)
7945 result = identifiers;
7946 else
7947 result = [first, second].concat(identifiers.slice(1));
7948
7949 if (values) {
7950 var tmp = values[result.join(' ')];
7951 if (tmp === undefined)
7952 tmp = values[result.join('.')];
7953 if (tmp !== undefined)
7954 result = tmp;
7955 }
7956
7957 return result;
7958};
7959
7960DERNode.prototype._decodeTime = function decodeTime(buffer, tag) {
7961 var str = buffer.raw().toString();
7962 if (tag === 'gentime') {
7963 var year = str.slice(0, 4) | 0;
7964 var mon = str.slice(4, 6) | 0;
7965 var day = str.slice(6, 8) | 0;
7966 var hour = str.slice(8, 10) | 0;
7967 var min = str.slice(10, 12) | 0;
7968 var sec = str.slice(12, 14) | 0;
7969 } else if (tag === 'utctime') {
7970 var year = str.slice(0, 2) | 0;
7971 var mon = str.slice(2, 4) | 0;
7972 var day = str.slice(4, 6) | 0;
7973 var hour = str.slice(6, 8) | 0;
7974 var min = str.slice(8, 10) | 0;
7975 var sec = str.slice(10, 12) | 0;
7976 if (year < 70)
7977 year = 2000 + year;
7978 else
7979 year = 1900 + year;
7980 } else {
7981 return buffer.error('Decoding ' + tag + ' time is not supported yet');
7982 }
7983
7984 return Date.UTC(year, mon - 1, day, hour, min, sec, 0);
7985};
7986
7987DERNode.prototype._decodeNull = function decodeNull(buffer) {
7988 return null;
7989};
7990
7991DERNode.prototype._decodeBool = function decodeBool(buffer) {
7992 var res = buffer.readUInt8();
7993 if (buffer.isError(res))
7994 return res;
7995 else
7996 return res !== 0;
7997};
7998
7999DERNode.prototype._decodeInt = function decodeInt(buffer, values) {
8000 // Bigint, return as it is (assume big endian)
8001 var raw = buffer.raw();
8002 var res = new bignum(raw);
8003
8004 if (values)
8005 res = values[res.toString(10)] || res;
8006
8007 return res;
8008};
8009
8010DERNode.prototype._use = function use(entity, obj) {
8011 if (typeof entity === 'function')
8012 entity = entity(obj);
8013 return entity._getDecoder('der').tree;
8014};
8015
8016// Utility methods
8017
8018function derDecodeTag(buf, fail) {
8019 var tag = buf.readUInt8(fail);
8020 if (buf.isError(tag))
8021 return tag;
8022
8023 var cls = der.tagClass[tag >> 6];
8024 var primitive = (tag & 0x20) === 0;
8025
8026 // Multi-octet tag - load
8027 if ((tag & 0x1f) === 0x1f) {
8028 var oct = tag;
8029 tag = 0;
8030 while ((oct & 0x80) === 0x80) {
8031 oct = buf.readUInt8(fail);
8032 if (buf.isError(oct))
8033 return oct;
8034
8035 tag <<= 7;
8036 tag |= oct & 0x7f;
8037 }
8038 } else {
8039 tag &= 0x1f;
8040 }
8041 var tagStr = der.tag[tag];
8042
8043 return {
8044 cls: cls,
8045 primitive: primitive,
8046 tag: tag,
8047 tagStr: tagStr
8048 };
8049}
8050
8051function derDecodeLen(buf, primitive, fail) {
8052 var len = buf.readUInt8(fail);
8053 if (buf.isError(len))
8054 return len;
8055
8056 // Indefinite form
8057 if (!primitive && len === 0x80)
8058 return null;
8059
8060 // Definite form
8061 if ((len & 0x80) === 0) {
8062 // Short form
8063 return len;
8064 }
8065
8066 // Long form
8067 var num = len & 0x7f;
8068 if (num > 4)
8069 return buf.error('length octect is too long');
8070
8071 len = 0;
8072 for (var i = 0; i < num; i++) {
8073 len <<= 8;
8074 var j = buf.readUInt8(fail);
8075 if (buf.isError(j))
8076 return j;
8077 len |= j;
8078 }
8079
8080 return len;
8081}
8082
8083},{"../../asn1":47,"inherits":210}],56:[function(require,module,exports){
8084var decoders = exports;
8085
8086decoders.der = require('./der');
8087decoders.pem = require('./pem');
8088
8089},{"./der":55,"./pem":57}],57:[function(require,module,exports){
8090var inherits = require('inherits');
8091var Buffer = require('buffer').Buffer;
8092
8093var DERDecoder = require('./der');
8094
8095function PEMDecoder(entity) {
8096 DERDecoder.call(this, entity);
8097 this.enc = 'pem';
8098};
8099inherits(PEMDecoder, DERDecoder);
8100module.exports = PEMDecoder;
8101
8102PEMDecoder.prototype.decode = function decode(data, options) {
8103 var lines = data.toString().split(/[\r\n]+/g);
8104
8105 var label = options.label.toUpperCase();
8106
8107 var re = /^-----(BEGIN|END) ([^-]+)-----$/;
8108 var start = -1;
8109 var end = -1;
8110 for (var i = 0; i < lines.length; i++) {
8111 var match = lines[i].match(re);
8112 if (match === null)
8113 continue;
8114
8115 if (match[2] !== label)
8116 continue;
8117
8118 if (start === -1) {
8119 if (match[1] !== 'BEGIN')
8120 break;
8121 start = i;
8122 } else {
8123 if (match[1] !== 'END')
8124 break;
8125 end = i;
8126 break;
8127 }
8128 }
8129 if (start === -1 || end === -1)
8130 throw new Error('PEM section not found for: ' + label);
8131
8132 var base64 = lines.slice(start + 1, end).join('');
8133 // Remove excessive symbols
8134 base64.replace(/[^a-z0-9\+\/=]+/gi, '');
8135
8136 var input = new Buffer(base64, 'base64');
8137 return DERDecoder.prototype.decode.call(this, input, options);
8138};
8139
8140},{"./der":55,"buffer":114,"inherits":210}],58:[function(require,module,exports){
8141var inherits = require('inherits');
8142var Buffer = require('buffer').Buffer;
8143
8144var asn1 = require('../../asn1');
8145var base = asn1.base;
8146
8147// Import DER constants
8148var der = asn1.constants.der;
8149
8150function DEREncoder(entity) {
8151 this.enc = 'der';
8152 this.name = entity.name;
8153 this.entity = entity;
8154
8155 // Construct base tree
8156 this.tree = new DERNode();
8157 this.tree._init(entity.body);
8158};
8159module.exports = DEREncoder;
8160
8161DEREncoder.prototype.encode = function encode(data, reporter) {
8162 return this.tree._encode(data, reporter).join();
8163};
8164
8165// Tree methods
8166
8167function DERNode(parent) {
8168 base.Node.call(this, 'der', parent);
8169}
8170inherits(DERNode, base.Node);
8171
8172DERNode.prototype._encodeComposite = function encodeComposite(tag,
8173 primitive,
8174 cls,
8175 content) {
8176 var encodedTag = encodeTag(tag, primitive, cls, this.reporter);
8177
8178 // Short form
8179 if (content.length < 0x80) {
8180 var header = new Buffer(2);
8181 header[0] = encodedTag;
8182 header[1] = content.length;
8183 return this._createEncoderBuffer([ header, content ]);
8184 }
8185
8186 // Long form
8187 // Count octets required to store length
8188 var lenOctets = 1;
8189 for (var i = content.length; i >= 0x100; i >>= 8)
8190 lenOctets++;
8191
8192 var header = new Buffer(1 + 1 + lenOctets);
8193 header[0] = encodedTag;
8194 header[1] = 0x80 | lenOctets;
8195
8196 for (var i = 1 + lenOctets, j = content.length; j > 0; i--, j >>= 8)
8197 header[i] = j & 0xff;
8198
8199 return this._createEncoderBuffer([ header, content ]);
8200};
8201
8202DERNode.prototype._encodeStr = function encodeStr(str, tag) {
8203 if (tag === 'bitstr') {
8204 return this._createEncoderBuffer([ str.unused | 0, str.data ]);
8205 } else if (tag === 'bmpstr') {
8206 var buf = new Buffer(str.length * 2);
8207 for (var i = 0; i < str.length; i++) {
8208 buf.writeUInt16BE(str.charCodeAt(i), i * 2);
8209 }
8210 return this._createEncoderBuffer(buf);
8211 } else if (tag === 'numstr') {
8212 if (!this._isNumstr(str)) {
8213 return this.reporter.error('Encoding of string type: numstr supports ' +
8214 'only digits and space');
8215 }
8216 return this._createEncoderBuffer(str);
8217 } else if (tag === 'printstr') {
8218 if (!this._isPrintstr(str)) {
8219 return this.reporter.error('Encoding of string type: printstr supports ' +
8220 'only latin upper and lower case letters, ' +
8221 'digits, space, apostrophe, left and rigth ' +
8222 'parenthesis, plus sign, comma, hyphen, ' +
8223 'dot, slash, colon, equal sign, ' +
8224 'question mark');
8225 }
8226 return this._createEncoderBuffer(str);
8227 } else if (/str$/.test(tag)) {
8228 return this._createEncoderBuffer(str);
8229 } else if (tag === 'objDesc') {
8230 return this._createEncoderBuffer(str);
8231 } else {
8232 return this.reporter.error('Encoding of string type: ' + tag +
8233 ' unsupported');
8234 }
8235};
8236
8237DERNode.prototype._encodeObjid = function encodeObjid(id, values, relative) {
8238 if (typeof id === 'string') {
8239 if (!values)
8240 return this.reporter.error('string objid given, but no values map found');
8241 if (!values.hasOwnProperty(id))
8242 return this.reporter.error('objid not found in values map');
8243 id = values[id].split(/[\s\.]+/g);
8244 for (var i = 0; i < id.length; i++)
8245 id[i] |= 0;
8246 } else if (Array.isArray(id)) {
8247 id = id.slice();
8248 for (var i = 0; i < id.length; i++)
8249 id[i] |= 0;
8250 }
8251
8252 if (!Array.isArray(id)) {
8253 return this.reporter.error('objid() should be either array or string, ' +
8254 'got: ' + JSON.stringify(id));
8255 }
8256
8257 if (!relative) {
8258 if (id[1] >= 40)
8259 return this.reporter.error('Second objid identifier OOB');
8260 id.splice(0, 2, id[0] * 40 + id[1]);
8261 }
8262
8263 // Count number of octets
8264 var size = 0;
8265 for (var i = 0; i < id.length; i++) {
8266 var ident = id[i];
8267 for (size++; ident >= 0x80; ident >>= 7)
8268 size++;
8269 }
8270
8271 var objid = new Buffer(size);
8272 var offset = objid.length - 1;
8273 for (var i = id.length - 1; i >= 0; i--) {
8274 var ident = id[i];
8275 objid[offset--] = ident & 0x7f;
8276 while ((ident >>= 7) > 0)
8277 objid[offset--] = 0x80 | (ident & 0x7f);
8278 }
8279
8280 return this._createEncoderBuffer(objid);
8281};
8282
8283function two(num) {
8284 if (num < 10)
8285 return '0' + num;
8286 else
8287 return num;
8288}
8289
8290DERNode.prototype._encodeTime = function encodeTime(time, tag) {
8291 var str;
8292 var date = new Date(time);
8293
8294 if (tag === 'gentime') {
8295 str = [
8296 two(date.getFullYear()),
8297 two(date.getUTCMonth() + 1),
8298 two(date.getUTCDate()),
8299 two(date.getUTCHours()),
8300 two(date.getUTCMinutes()),
8301 two(date.getUTCSeconds()),
8302 'Z'
8303 ].join('');
8304 } else if (tag === 'utctime') {
8305 str = [
8306 two(date.getFullYear() % 100),
8307 two(date.getUTCMonth() + 1),
8308 two(date.getUTCDate()),
8309 two(date.getUTCHours()),
8310 two(date.getUTCMinutes()),
8311 two(date.getUTCSeconds()),
8312 'Z'
8313 ].join('');
8314 } else {
8315 this.reporter.error('Encoding ' + tag + ' time is not supported yet');
8316 }
8317
8318 return this._encodeStr(str, 'octstr');
8319};
8320
8321DERNode.prototype._encodeNull = function encodeNull() {
8322 return this._createEncoderBuffer('');
8323};
8324
8325DERNode.prototype._encodeInt = function encodeInt(num, values) {
8326 if (typeof num === 'string') {
8327 if (!values)
8328 return this.reporter.error('String int or enum given, but no values map');
8329 if (!values.hasOwnProperty(num)) {
8330 return this.reporter.error('Values map doesn\'t contain: ' +
8331 JSON.stringify(num));
8332 }
8333 num = values[num];
8334 }
8335
8336 // Bignum, assume big endian
8337 if (typeof num !== 'number' && !Buffer.isBuffer(num)) {
8338 var numArray = num.toArray();
8339 if (!num.sign && numArray[0] & 0x80) {
8340 numArray.unshift(0);
8341 }
8342 num = new Buffer(numArray);
8343 }
8344
8345 if (Buffer.isBuffer(num)) {
8346 var size = num.length;
8347 if (num.length === 0)
8348 size++;
8349
8350 var out = new Buffer(size);
8351 num.copy(out);
8352 if (num.length === 0)
8353 out[0] = 0
8354 return this._createEncoderBuffer(out);
8355 }
8356
8357 if (num < 0x80)
8358 return this._createEncoderBuffer(num);
8359
8360 if (num < 0x100)
8361 return this._createEncoderBuffer([0, num]);
8362
8363 var size = 1;
8364 for (var i = num; i >= 0x100; i >>= 8)
8365 size++;
8366
8367 var out = new Array(size);
8368 for (var i = out.length - 1; i >= 0; i--) {
8369 out[i] = num & 0xff;
8370 num >>= 8;
8371 }
8372 if(out[0] & 0x80) {
8373 out.unshift(0);
8374 }
8375
8376 return this._createEncoderBuffer(new Buffer(out));
8377};
8378
8379DERNode.prototype._encodeBool = function encodeBool(value) {
8380 return this._createEncoderBuffer(value ? 0xff : 0);
8381};
8382
8383DERNode.prototype._use = function use(entity, obj) {
8384 if (typeof entity === 'function')
8385 entity = entity(obj);
8386 return entity._getEncoder('der').tree;
8387};
8388
8389DERNode.prototype._skipDefault = function skipDefault(dataBuffer, reporter, parent) {
8390 var state = this._baseState;
8391 var i;
8392 if (state['default'] === null)
8393 return false;
8394
8395 var data = dataBuffer.join();
8396 if (state.defaultBuffer === undefined)
8397 state.defaultBuffer = this._encodeValue(state['default'], reporter, parent).join();
8398
8399 if (data.length !== state.defaultBuffer.length)
8400 return false;
8401
8402 for (i=0; i < data.length; i++)
8403 if (data[i] !== state.defaultBuffer[i])
8404 return false;
8405
8406 return true;
8407};
8408
8409// Utility methods
8410
8411function encodeTag(tag, primitive, cls, reporter) {
8412 var res;
8413
8414 if (tag === 'seqof')
8415 tag = 'seq';
8416 else if (tag === 'setof')
8417 tag = 'set';
8418
8419 if (der.tagByName.hasOwnProperty(tag))
8420 res = der.tagByName[tag];
8421 else if (typeof tag === 'number' && (tag | 0) === tag)
8422 res = tag;
8423 else
8424 return reporter.error('Unknown tag: ' + tag);
8425
8426 if (res >= 0x1f)
8427 return reporter.error('Multi-octet tag encoding unsupported');
8428
8429 if (!primitive)
8430 res |= 0x20;
8431
8432 res |= (der.tagClassByName[cls || 'universal'] << 6);
8433
8434 return res;
8435}
8436
8437},{"../../asn1":47,"buffer":114,"inherits":210}],59:[function(require,module,exports){
8438var encoders = exports;
8439
8440encoders.der = require('./der');
8441encoders.pem = require('./pem');
8442
8443},{"./der":58,"./pem":60}],60:[function(require,module,exports){
8444var inherits = require('inherits');
8445
8446var DEREncoder = require('./der');
8447
8448function PEMEncoder(entity) {
8449 DEREncoder.call(this, entity);
8450 this.enc = 'pem';
8451};
8452inherits(PEMEncoder, DEREncoder);
8453module.exports = PEMEncoder;
8454
8455PEMEncoder.prototype.encode = function encode(data, options) {
8456 var buf = DEREncoder.prototype.encode.call(this, data);
8457
8458 var p = buf.toString('base64');
8459 var out = [ '-----BEGIN ' + options.label + '-----' ];
8460 for (var i = 0; i < p.length; i += 64)
8461 out.push(p.slice(i, i + 64));
8462 out.push('-----END ' + options.label + '-----');
8463 return out.join('\n');
8464};
8465
8466},{"./der":58,"inherits":210}],61:[function(require,module,exports){
8467// Copyright 2011 Mark Cavage <mcavage@gmail.com> All rights reserved.
8468
8469
8470module.exports = {
8471
8472 newInvalidAsn1Error: function (msg) {
8473 var e = new Error();
8474 e.name = 'InvalidAsn1Error';
8475 e.message = msg || '';
8476 return e;
8477 }
8478
8479};
8480
8481},{}],62:[function(require,module,exports){
8482// Copyright 2011 Mark Cavage <mcavage@gmail.com> All rights reserved.
8483
8484var errors = require('./errors');
8485var types = require('./types');
8486
8487var Reader = require('./reader');
8488var Writer = require('./writer');
8489
8490
8491// --- Exports
8492
8493module.exports = {
8494
8495 Reader: Reader,
8496
8497 Writer: Writer
8498
8499};
8500
8501for (var t in types) {
8502 if (types.hasOwnProperty(t))
8503 module.exports[t] = types[t];
8504}
8505for (var e in errors) {
8506 if (errors.hasOwnProperty(e))
8507 module.exports[e] = errors[e];
8508}
8509
8510},{"./errors":61,"./reader":63,"./types":64,"./writer":65}],63:[function(require,module,exports){
8511// Copyright 2011 Mark Cavage <mcavage@gmail.com> All rights reserved.
8512
8513var assert = require('assert');
8514var Buffer = require('safer-buffer').Buffer;
8515
8516var ASN1 = require('./types');
8517var errors = require('./errors');
8518
8519
8520// --- Globals
8521
8522var newInvalidAsn1Error = errors.newInvalidAsn1Error;
8523
8524
8525
8526// --- API
8527
8528function Reader(data) {
8529 if (!data || !Buffer.isBuffer(data))
8530 throw new TypeError('data must be a node Buffer');
8531
8532 this._buf = data;
8533 this._size = data.length;
8534
8535 // These hold the "current" state
8536 this._len = 0;
8537 this._offset = 0;
8538}
8539
8540Object.defineProperty(Reader.prototype, 'length', {
8541 enumerable: true,
8542 get: function () { return (this._len); }
8543});
8544
8545Object.defineProperty(Reader.prototype, 'offset', {
8546 enumerable: true,
8547 get: function () { return (this._offset); }
8548});
8549
8550Object.defineProperty(Reader.prototype, 'remain', {
8551 get: function () { return (this._size - this._offset); }
8552});
8553
8554Object.defineProperty(Reader.prototype, 'buffer', {
8555 get: function () { return (this._buf.slice(this._offset)); }
8556});
8557
8558
8559/**
8560 * Reads a single byte and advances offset; you can pass in `true` to make this
8561 * a "peek" operation (i.e., get the byte, but don't advance the offset).
8562 *
8563 * @param {Boolean} peek true means don't move offset.
8564 * @return {Number} the next byte, null if not enough data.
8565 */
8566Reader.prototype.readByte = function (peek) {
8567 if (this._size - this._offset < 1)
8568 return null;
8569
8570 var b = this._buf[this._offset] & 0xff;
8571
8572 if (!peek)
8573 this._offset += 1;
8574
8575 return b;
8576};
8577
8578
8579Reader.prototype.peek = function () {
8580 return this.readByte(true);
8581};
8582
8583
8584/**
8585 * Reads a (potentially) variable length off the BER buffer. This call is
8586 * not really meant to be called directly, as callers have to manipulate
8587 * the internal buffer afterwards.
8588 *
8589 * As a result of this call, you can call `Reader.length`, until the
8590 * next thing called that does a readLength.
8591 *
8592 * @return {Number} the amount of offset to advance the buffer.
8593 * @throws {InvalidAsn1Error} on bad ASN.1
8594 */
8595Reader.prototype.readLength = function (offset) {
8596 if (offset === undefined)
8597 offset = this._offset;
8598
8599 if (offset >= this._size)
8600 return null;
8601
8602 var lenB = this._buf[offset++] & 0xff;
8603 if (lenB === null)
8604 return null;
8605
8606 if ((lenB & 0x80) === 0x80) {
8607 lenB &= 0x7f;
8608
8609 if (lenB === 0)
8610 throw newInvalidAsn1Error('Indefinite length not supported');
8611
8612 if (lenB > 4)
8613 throw newInvalidAsn1Error('encoding too long');
8614
8615 if (this._size - offset < lenB)
8616 return null;
8617
8618 this._len = 0;
8619 for (var i = 0; i < lenB; i++)
8620 this._len = (this._len << 8) + (this._buf[offset++] & 0xff);
8621
8622 } else {
8623 // Wasn't a variable length
8624 this._len = lenB;
8625 }
8626
8627 return offset;
8628};
8629
8630
8631/**
8632 * Parses the next sequence in this BER buffer.
8633 *
8634 * To get the length of the sequence, call `Reader.length`.
8635 *
8636 * @return {Number} the sequence's tag.
8637 */
8638Reader.prototype.readSequence = function (tag) {
8639 var seq = this.peek();
8640 if (seq === null)
8641 return null;
8642 if (tag !== undefined && tag !== seq)
8643 throw newInvalidAsn1Error('Expected 0x' + tag.toString(16) +
8644 ': got 0x' + seq.toString(16));
8645
8646 var o = this.readLength(this._offset + 1); // stored in `length`
8647 if (o === null)
8648 return null;
8649
8650 this._offset = o;
8651 return seq;
8652};
8653
8654
8655Reader.prototype.readInt = function () {
8656 return this._readTag(ASN1.Integer);
8657};
8658
8659
8660Reader.prototype.readBoolean = function () {
8661 return (this._readTag(ASN1.Boolean) === 0 ? false : true);
8662};
8663
8664
8665Reader.prototype.readEnumeration = function () {
8666 return this._readTag(ASN1.Enumeration);
8667};
8668
8669
8670Reader.prototype.readString = function (tag, retbuf) {
8671 if (!tag)
8672 tag = ASN1.OctetString;
8673
8674 var b = this.peek();
8675 if (b === null)
8676 return null;
8677
8678 if (b !== tag)
8679 throw newInvalidAsn1Error('Expected 0x' + tag.toString(16) +
8680 ': got 0x' + b.toString(16));
8681
8682 var o = this.readLength(this._offset + 1); // stored in `length`
8683
8684 if (o === null)
8685 return null;
8686
8687 if (this.length > this._size - o)
8688 return null;
8689
8690 this._offset = o;
8691
8692 if (this.length === 0)
8693 return retbuf ? Buffer.alloc(0) : '';
8694
8695 var str = this._buf.slice(this._offset, this._offset + this.length);
8696 this._offset += this.length;
8697
8698 return retbuf ? str : str.toString('utf8');
8699};
8700
8701Reader.prototype.readOID = function (tag) {
8702 if (!tag)
8703 tag = ASN1.OID;
8704
8705 var b = this.readString(tag, true);
8706 if (b === null)
8707 return null;
8708
8709 var values = [];
8710 var value = 0;
8711
8712 for (var i = 0; i < b.length; i++) {
8713 var byte = b[i] & 0xff;
8714
8715 value <<= 7;
8716 value += byte & 0x7f;
8717 if ((byte & 0x80) === 0) {
8718 values.push(value);
8719 value = 0;
8720 }
8721 }
8722
8723 value = values.shift();
8724 values.unshift(value % 40);
8725 values.unshift((value / 40) >> 0);
8726
8727 return values.join('.');
8728};
8729
8730
8731Reader.prototype._readTag = function (tag) {
8732 assert.ok(tag !== undefined);
8733
8734 var b = this.peek();
8735
8736 if (b === null)
8737 return null;
8738
8739 if (b !== tag)
8740 throw newInvalidAsn1Error('Expected 0x' + tag.toString(16) +
8741 ': got 0x' + b.toString(16));
8742
8743 var o = this.readLength(this._offset + 1); // stored in `length`
8744 if (o === null)
8745 return null;
8746
8747 if (this.length > 4)
8748 throw newInvalidAsn1Error('Integer too long: ' + this.length);
8749
8750 if (this.length > this._size - o)
8751 return null;
8752 this._offset = o;
8753
8754 var fb = this._buf[this._offset];
8755 var value = 0;
8756
8757 for (var i = 0; i < this.length; i++) {
8758 value <<= 8;
8759 value |= (this._buf[this._offset++] & 0xff);
8760 }
8761
8762 if ((fb & 0x80) === 0x80 && i !== 4)
8763 value -= (1 << (i * 8));
8764
8765 return value >> 0;
8766};
8767
8768
8769
8770// --- Exported API
8771
8772module.exports = Reader;
8773
8774},{"./errors":61,"./types":64,"assert":68,"safer-buffer":326}],64:[function(require,module,exports){
8775// Copyright 2011 Mark Cavage <mcavage@gmail.com> All rights reserved.
8776
8777
8778module.exports = {
8779 EOC: 0,
8780 Boolean: 1,
8781 Integer: 2,
8782 BitString: 3,
8783 OctetString: 4,
8784 Null: 5,
8785 OID: 6,
8786 ObjectDescriptor: 7,
8787 External: 8,
8788 Real: 9, // float
8789 Enumeration: 10,
8790 PDV: 11,
8791 Utf8String: 12,
8792 RelativeOID: 13,
8793 Sequence: 16,
8794 Set: 17,
8795 NumericString: 18,
8796 PrintableString: 19,
8797 T61String: 20,
8798 VideotexString: 21,
8799 IA5String: 22,
8800 UTCTime: 23,
8801 GeneralizedTime: 24,
8802 GraphicString: 25,
8803 VisibleString: 26,
8804 GeneralString: 28,
8805 UniversalString: 29,
8806 CharacterString: 30,
8807 BMPString: 31,
8808 Constructor: 32,
8809 Context: 128
8810};
8811
8812},{}],65:[function(require,module,exports){
8813// Copyright 2011 Mark Cavage <mcavage@gmail.com> All rights reserved.
8814
8815var assert = require('assert');
8816var Buffer = require('safer-buffer').Buffer;
8817var ASN1 = require('./types');
8818var errors = require('./errors');
8819
8820
8821// --- Globals
8822
8823var newInvalidAsn1Error = errors.newInvalidAsn1Error;
8824
8825var DEFAULT_OPTS = {
8826 size: 1024,
8827 growthFactor: 8
8828};
8829
8830
8831// --- Helpers
8832
8833function merge(from, to) {
8834 assert.ok(from);
8835 assert.equal(typeof (from), 'object');
8836 assert.ok(to);
8837 assert.equal(typeof (to), 'object');
8838
8839 var keys = Object.getOwnPropertyNames(from);
8840 keys.forEach(function (key) {
8841 if (to[key])
8842 return;
8843
8844 var value = Object.getOwnPropertyDescriptor(from, key);
8845 Object.defineProperty(to, key, value);
8846 });
8847
8848 return to;
8849}
8850
8851
8852
8853// --- API
8854
8855function Writer(options) {
8856 options = merge(DEFAULT_OPTS, options || {});
8857
8858 this._buf = Buffer.alloc(options.size || 1024);
8859 this._size = this._buf.length;
8860 this._offset = 0;
8861 this._options = options;
8862
8863 // A list of offsets in the buffer where we need to insert
8864 // sequence tag/len pairs.
8865 this._seq = [];
8866}
8867
8868Object.defineProperty(Writer.prototype, 'buffer', {
8869 get: function () {
8870 if (this._seq.length)
8871 throw newInvalidAsn1Error(this._seq.length + ' unended sequence(s)');
8872
8873 return (this._buf.slice(0, this._offset));
8874 }
8875});
8876
8877Writer.prototype.writeByte = function (b) {
8878 if (typeof (b) !== 'number')
8879 throw new TypeError('argument must be a Number');
8880
8881 this._ensure(1);
8882 this._buf[this._offset++] = b;
8883};
8884
8885
8886Writer.prototype.writeInt = function (i, tag) {
8887 if (typeof (i) !== 'number')
8888 throw new TypeError('argument must be a Number');
8889 if (typeof (tag) !== 'number')
8890 tag = ASN1.Integer;
8891
8892 var sz = 4;
8893
8894 while ((((i & 0xff800000) === 0) || ((i & 0xff800000) === 0xff800000 >> 0)) &&
8895 (sz > 1)) {
8896 sz--;
8897 i <<= 8;
8898 }
8899
8900 if (sz > 4)
8901 throw newInvalidAsn1Error('BER ints cannot be > 0xffffffff');
8902
8903 this._ensure(2 + sz);
8904 this._buf[this._offset++] = tag;
8905 this._buf[this._offset++] = sz;
8906
8907 while (sz-- > 0) {
8908 this._buf[this._offset++] = ((i & 0xff000000) >>> 24);
8909 i <<= 8;
8910 }
8911
8912};
8913
8914
8915Writer.prototype.writeNull = function () {
8916 this.writeByte(ASN1.Null);
8917 this.writeByte(0x00);
8918};
8919
8920
8921Writer.prototype.writeEnumeration = function (i, tag) {
8922 if (typeof (i) !== 'number')
8923 throw new TypeError('argument must be a Number');
8924 if (typeof (tag) !== 'number')
8925 tag = ASN1.Enumeration;
8926
8927 return this.writeInt(i, tag);
8928};
8929
8930
8931Writer.prototype.writeBoolean = function (b, tag) {
8932 if (typeof (b) !== 'boolean')
8933 throw new TypeError('argument must be a Boolean');
8934 if (typeof (tag) !== 'number')
8935 tag = ASN1.Boolean;
8936
8937 this._ensure(3);
8938 this._buf[this._offset++] = tag;
8939 this._buf[this._offset++] = 0x01;
8940 this._buf[this._offset++] = b ? 0xff : 0x00;
8941};
8942
8943
8944Writer.prototype.writeString = function (s, tag) {
8945 if (typeof (s) !== 'string')
8946 throw new TypeError('argument must be a string (was: ' + typeof (s) + ')');
8947 if (typeof (tag) !== 'number')
8948 tag = ASN1.OctetString;
8949
8950 var len = Buffer.byteLength(s);
8951 this.writeByte(tag);
8952 this.writeLength(len);
8953 if (len) {
8954 this._ensure(len);
8955 this._buf.write(s, this._offset);
8956 this._offset += len;
8957 }
8958};
8959
8960
8961Writer.prototype.writeBuffer = function (buf, tag) {
8962 if (typeof (tag) !== 'number')
8963 throw new TypeError('tag must be a number');
8964 if (!Buffer.isBuffer(buf))
8965 throw new TypeError('argument must be a buffer');
8966
8967 this.writeByte(tag);
8968 this.writeLength(buf.length);
8969 this._ensure(buf.length);
8970 buf.copy(this._buf, this._offset, 0, buf.length);
8971 this._offset += buf.length;
8972};
8973
8974
8975Writer.prototype.writeStringArray = function (strings) {
8976 if ((!strings instanceof Array))
8977 throw new TypeError('argument must be an Array[String]');
8978
8979 var self = this;
8980 strings.forEach(function (s) {
8981 self.writeString(s);
8982 });
8983};
8984
8985// This is really to solve DER cases, but whatever for now
8986Writer.prototype.writeOID = function (s, tag) {
8987 if (typeof (s) !== 'string')
8988 throw new TypeError('argument must be a string');
8989 if (typeof (tag) !== 'number')
8990 tag = ASN1.OID;
8991
8992 if (!/^([0-9]+\.){3,}[0-9]+$/.test(s))
8993 throw new Error('argument is not a valid OID string');
8994
8995 function encodeOctet(bytes, octet) {
8996 if (octet < 128) {
8997 bytes.push(octet);
8998 } else if (octet < 16384) {
8999 bytes.push((octet >>> 7) | 0x80);
9000 bytes.push(octet & 0x7F);
9001 } else if (octet < 2097152) {
9002 bytes.push((octet >>> 14) | 0x80);
9003 bytes.push(((octet >>> 7) | 0x80) & 0xFF);
9004 bytes.push(octet & 0x7F);
9005 } else if (octet < 268435456) {
9006 bytes.push((octet >>> 21) | 0x80);
9007 bytes.push(((octet >>> 14) | 0x80) & 0xFF);
9008 bytes.push(((octet >>> 7) | 0x80) & 0xFF);
9009 bytes.push(octet & 0x7F);
9010 } else {
9011 bytes.push(((octet >>> 28) | 0x80) & 0xFF);
9012 bytes.push(((octet >>> 21) | 0x80) & 0xFF);
9013 bytes.push(((octet >>> 14) | 0x80) & 0xFF);
9014 bytes.push(((octet >>> 7) | 0x80) & 0xFF);
9015 bytes.push(octet & 0x7F);
9016 }
9017 }
9018
9019 var tmp = s.split('.');
9020 var bytes = [];
9021 bytes.push(parseInt(tmp[0], 10) * 40 + parseInt(tmp[1], 10));
9022 tmp.slice(2).forEach(function (b) {
9023 encodeOctet(bytes, parseInt(b, 10));
9024 });
9025
9026 var self = this;
9027 this._ensure(2 + bytes.length);
9028 this.writeByte(tag);
9029 this.writeLength(bytes.length);
9030 bytes.forEach(function (b) {
9031 self.writeByte(b);
9032 });
9033};
9034
9035
9036Writer.prototype.writeLength = function (len) {
9037 if (typeof (len) !== 'number')
9038 throw new TypeError('argument must be a Number');
9039
9040 this._ensure(4);
9041
9042 if (len <= 0x7f) {
9043 this._buf[this._offset++] = len;
9044 } else if (len <= 0xff) {
9045 this._buf[this._offset++] = 0x81;
9046 this._buf[this._offset++] = len;
9047 } else if (len <= 0xffff) {
9048 this._buf[this._offset++] = 0x82;
9049 this._buf[this._offset++] = len >> 8;
9050 this._buf[this._offset++] = len;
9051 } else if (len <= 0xffffff) {
9052 this._buf[this._offset++] = 0x83;
9053 this._buf[this._offset++] = len >> 16;
9054 this._buf[this._offset++] = len >> 8;
9055 this._buf[this._offset++] = len;
9056 } else {
9057 throw newInvalidAsn1Error('Length too long (> 4 bytes)');
9058 }
9059};
9060
9061Writer.prototype.startSequence = function (tag) {
9062 if (typeof (tag) !== 'number')
9063 tag = ASN1.Sequence | ASN1.Constructor;
9064
9065 this.writeByte(tag);
9066 this._seq.push(this._offset);
9067 this._ensure(3);
9068 this._offset += 3;
9069};
9070
9071
9072Writer.prototype.endSequence = function () {
9073 var seq = this._seq.pop();
9074 var start = seq + 3;
9075 var len = this._offset - start;
9076
9077 if (len <= 0x7f) {
9078 this._shift(start, len, -2);
9079 this._buf[seq] = len;
9080 } else if (len <= 0xff) {
9081 this._shift(start, len, -1);
9082 this._buf[seq] = 0x81;
9083 this._buf[seq + 1] = len;
9084 } else if (len <= 0xffff) {
9085 this._buf[seq] = 0x82;
9086 this._buf[seq + 1] = len >> 8;
9087 this._buf[seq + 2] = len;
9088 } else if (len <= 0xffffff) {
9089 this._shift(start, len, 1);
9090 this._buf[seq] = 0x83;
9091 this._buf[seq + 1] = len >> 16;
9092 this._buf[seq + 2] = len >> 8;
9093 this._buf[seq + 3] = len;
9094 } else {
9095 throw newInvalidAsn1Error('Sequence too long');
9096 }
9097};
9098
9099
9100Writer.prototype._shift = function (start, len, shift) {
9101 assert.ok(start !== undefined);
9102 assert.ok(len !== undefined);
9103 assert.ok(shift);
9104
9105 this._buf.copy(this._buf, start + shift, start, start + len);
9106 this._offset += shift;
9107};
9108
9109Writer.prototype._ensure = function (len) {
9110 assert.ok(len);
9111
9112 if (this._size - this._offset < len) {
9113 var sz = this._size * this._options.growthFactor;
9114 if (sz - this._offset < len)
9115 sz += len;
9116
9117 var buf = Buffer.alloc(sz);
9118
9119 this._buf.copy(buf, 0, 0, this._offset);
9120 this._buf = buf;
9121 this._size = sz;
9122 }
9123};
9124
9125
9126
9127// --- Exported API
9128
9129module.exports = Writer;
9130
9131},{"./errors":61,"./types":64,"assert":68,"safer-buffer":326}],66:[function(require,module,exports){
9132// Copyright 2011 Mark Cavage <mcavage@gmail.com> All rights reserved.
9133
9134// If you have no idea what ASN.1 or BER is, see this:
9135// ftp://ftp.rsa.com/pub/pkcs/ascii/layman.asc
9136
9137var Ber = require('./ber/index');
9138
9139
9140
9141// --- Exported API
9142
9143module.exports = {
9144
9145 Ber: Ber,
9146
9147 BerReader: Ber.Reader,
9148
9149 BerWriter: Ber.Writer
9150
9151};
9152
9153},{"./ber/index":62}],67:[function(require,module,exports){
9154(function (Buffer,process){
9155// Copyright (c) 2012, Mark Cavage. All rights reserved.
9156// Copyright 2015 Joyent, Inc.
9157
9158var assert = require('assert');
9159var Stream = require('stream').Stream;
9160var util = require('util');
9161
9162
9163///--- Globals
9164
9165/* JSSTYLED */
9166var UUID_REGEXP = /^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}$/;
9167
9168
9169///--- Internal
9170
9171function _capitalize(str) {
9172 return (str.charAt(0).toUpperCase() + str.slice(1));
9173}
9174
9175function _toss(name, expected, oper, arg, actual) {
9176 throw new assert.AssertionError({
9177 message: util.format('%s (%s) is required', name, expected),
9178 actual: (actual === undefined) ? typeof (arg) : actual(arg),
9179 expected: expected,
9180 operator: oper || '===',
9181 stackStartFunction: _toss.caller
9182 });
9183}
9184
9185function _getClass(arg) {
9186 return (Object.prototype.toString.call(arg).slice(8, -1));
9187}
9188
9189function noop() {
9190 // Why even bother with asserts?
9191}
9192
9193
9194///--- Exports
9195
9196var types = {
9197 bool: {
9198 check: function (arg) { return typeof (arg) === 'boolean'; }
9199 },
9200 func: {
9201 check: function (arg) { return typeof (arg) === 'function'; }
9202 },
9203 string: {
9204 check: function (arg) { return typeof (arg) === 'string'; }
9205 },
9206 object: {
9207 check: function (arg) {
9208 return typeof (arg) === 'object' && arg !== null;
9209 }
9210 },
9211 number: {
9212 check: function (arg) {
9213 return typeof (arg) === 'number' && !isNaN(arg);
9214 }
9215 },
9216 finite: {
9217 check: function (arg) {
9218 return typeof (arg) === 'number' && !isNaN(arg) && isFinite(arg);
9219 }
9220 },
9221 buffer: {
9222 check: function (arg) { return Buffer.isBuffer(arg); },
9223 operator: 'Buffer.isBuffer'
9224 },
9225 array: {
9226 check: function (arg) { return Array.isArray(arg); },
9227 operator: 'Array.isArray'
9228 },
9229 stream: {
9230 check: function (arg) { return arg instanceof Stream; },
9231 operator: 'instanceof',
9232 actual: _getClass
9233 },
9234 date: {
9235 check: function (arg) { return arg instanceof Date; },
9236 operator: 'instanceof',
9237 actual: _getClass
9238 },
9239 regexp: {
9240 check: function (arg) { return arg instanceof RegExp; },
9241 operator: 'instanceof',
9242 actual: _getClass
9243 },
9244 uuid: {
9245 check: function (arg) {
9246 return typeof (arg) === 'string' && UUID_REGEXP.test(arg);
9247 },
9248 operator: 'isUUID'
9249 }
9250};
9251
9252function _setExports(ndebug) {
9253 var keys = Object.keys(types);
9254 var out;
9255
9256 /* re-export standard assert */
9257 if (process.env.NODE_NDEBUG) {
9258 out = noop;
9259 } else {
9260 out = function (arg, msg) {
9261 if (!arg) {
9262 _toss(msg, 'true', arg);
9263 }
9264 };
9265 }
9266
9267 /* standard checks */
9268 keys.forEach(function (k) {
9269 if (ndebug) {
9270 out[k] = noop;
9271 return;
9272 }
9273 var type = types[k];
9274 out[k] = function (arg, msg) {
9275 if (!type.check(arg)) {
9276 _toss(msg, k, type.operator, arg, type.actual);
9277 }
9278 };
9279 });
9280
9281 /* optional checks */
9282 keys.forEach(function (k) {
9283 var name = 'optional' + _capitalize(k);
9284 if (ndebug) {
9285 out[name] = noop;
9286 return;
9287 }
9288 var type = types[k];
9289 out[name] = function (arg, msg) {
9290 if (arg === undefined || arg === null) {
9291 return;
9292 }
9293 if (!type.check(arg)) {
9294 _toss(msg, k, type.operator, arg, type.actual);
9295 }
9296 };
9297 });
9298
9299 /* arrayOf checks */
9300 keys.forEach(function (k) {
9301 var name = 'arrayOf' + _capitalize(k);
9302 if (ndebug) {
9303 out[name] = noop;
9304 return;
9305 }
9306 var type = types[k];
9307 var expected = '[' + k + ']';
9308 out[name] = function (arg, msg) {
9309 if (!Array.isArray(arg)) {
9310 _toss(msg, expected, type.operator, arg, type.actual);
9311 }
9312 var i;
9313 for (i = 0; i < arg.length; i++) {
9314 if (!type.check(arg[i])) {
9315 _toss(msg, expected, type.operator, arg, type.actual);
9316 }
9317 }
9318 };
9319 });
9320
9321 /* optionalArrayOf checks */
9322 keys.forEach(function (k) {
9323 var name = 'optionalArrayOf' + _capitalize(k);
9324 if (ndebug) {
9325 out[name] = noop;
9326 return;
9327 }
9328 var type = types[k];
9329 var expected = '[' + k + ']';
9330 out[name] = function (arg, msg) {
9331 if (arg === undefined || arg === null) {
9332 return;
9333 }
9334 if (!Array.isArray(arg)) {
9335 _toss(msg, expected, type.operator, arg, type.actual);
9336 }
9337 var i;
9338 for (i = 0; i < arg.length; i++) {
9339 if (!type.check(arg[i])) {
9340 _toss(msg, expected, type.operator, arg, type.actual);
9341 }
9342 }
9343 };
9344 });
9345
9346 /* re-export built-in assertions */
9347 Object.keys(assert).forEach(function (k) {
9348 if (k === 'AssertionError') {
9349 out[k] = assert[k];
9350 return;
9351 }
9352 if (ndebug) {
9353 out[k] = noop;
9354 return;
9355 }
9356 out[k] = assert[k];
9357 });
9358
9359 /* export ourselves (for unit tests _only_) */
9360 out._setExports = _setExports;
9361
9362 return out;
9363}
9364
9365module.exports = _setExports(process.env.NODE_NDEBUG);
9366
9367}).call(this,{"isBuffer":require("../is-buffer/index.js")},require('_process'))
9368},{"../is-buffer/index.js":211,"_process":265,"assert":68,"stream":361,"util":397}],68:[function(require,module,exports){
9369(function (global){
9370'use strict';
9371
9372// compare and isBuffer taken from https://github.com/feross/buffer/blob/680e9e5e488f22aac27599a57dc844a6315928dd/index.js
9373// original notice:
9374
9375/*!
9376 * The buffer module from node.js, for the browser.
9377 *
9378 * @author Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
9379 * @license MIT
9380 */
9381function compare(a, b) {
9382 if (a === b) {
9383 return 0;
9384 }
9385
9386 var x = a.length;
9387 var y = b.length;
9388
9389 for (var i = 0, len = Math.min(x, y); i < len; ++i) {
9390 if (a[i] !== b[i]) {
9391 x = a[i];
9392 y = b[i];
9393 break;
9394 }
9395 }
9396
9397 if (x < y) {
9398 return -1;
9399 }
9400 if (y < x) {
9401 return 1;
9402 }
9403 return 0;
9404}
9405function isBuffer(b) {
9406 if (global.Buffer && typeof global.Buffer.isBuffer === 'function') {
9407 return global.Buffer.isBuffer(b);
9408 }
9409 return !!(b != null && b._isBuffer);
9410}
9411
9412// based on node assert, original notice:
9413
9414// http://wiki.commonjs.org/wiki/Unit_Testing/1.0
9415//
9416// THIS IS NOT TESTED NOR LIKELY TO WORK OUTSIDE V8!
9417//
9418// Originally from narwhal.js (http://narwhaljs.org)
9419// Copyright (c) 2009 Thomas Robinson <280north.com>
9420//
9421// Permission is hereby granted, free of charge, to any person obtaining a copy
9422// of this software and associated documentation files (the 'Software'), to
9423// deal in the Software without restriction, including without limitation the
9424// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
9425// sell copies of the Software, and to permit persons to whom the Software is
9426// furnished to do so, subject to the following conditions:
9427//
9428// The above copyright notice and this permission notice shall be included in
9429// all copies or substantial portions of the Software.
9430//
9431// THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
9432// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
9433// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
9434// AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
9435// ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
9436// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
9437
9438var util = require('util/');
9439var hasOwn = Object.prototype.hasOwnProperty;
9440var pSlice = Array.prototype.slice;
9441var functionsHaveNames = (function () {
9442 return function foo() {}.name === 'foo';
9443}());
9444function pToString (obj) {
9445 return Object.prototype.toString.call(obj);
9446}
9447function isView(arrbuf) {
9448 if (isBuffer(arrbuf)) {
9449 return false;
9450 }
9451 if (typeof global.ArrayBuffer !== 'function') {
9452 return false;
9453 }
9454 if (typeof ArrayBuffer.isView === 'function') {
9455 return ArrayBuffer.isView(arrbuf);
9456 }
9457 if (!arrbuf) {
9458 return false;
9459 }
9460 if (arrbuf instanceof DataView) {
9461 return true;
9462 }
9463 if (arrbuf.buffer && arrbuf.buffer instanceof ArrayBuffer) {
9464 return true;
9465 }
9466 return false;
9467}
9468// 1. The assert module provides functions that throw
9469// AssertionError's when particular conditions are not met. The
9470// assert module must conform to the following interface.
9471
9472var assert = module.exports = ok;
9473
9474// 2. The AssertionError is defined in assert.
9475// new assert.AssertionError({ message: message,
9476// actual: actual,
9477// expected: expected })
9478
9479var regex = /\s*function\s+([^\(\s]*)\s*/;
9480// based on https://github.com/ljharb/function.prototype.name/blob/adeeeec8bfcc6068b187d7d9fb3d5bb1d3a30899/implementation.js
9481function getName(func) {
9482 if (!util.isFunction(func)) {
9483 return;
9484 }
9485 if (functionsHaveNames) {
9486 return func.name;
9487 }
9488 var str = func.toString();
9489 var match = str.match(regex);
9490 return match && match[1];
9491}
9492assert.AssertionError = function AssertionError(options) {
9493 this.name = 'AssertionError';
9494 this.actual = options.actual;
9495 this.expected = options.expected;
9496 this.operator = options.operator;
9497 if (options.message) {
9498 this.message = options.message;
9499 this.generatedMessage = false;
9500 } else {
9501 this.message = getMessage(this);
9502 this.generatedMessage = true;
9503 }
9504 var stackStartFunction = options.stackStartFunction || fail;
9505 if (Error.captureStackTrace) {
9506 Error.captureStackTrace(this, stackStartFunction);
9507 } else {
9508 // non v8 browsers so we can have a stacktrace
9509 var err = new Error();
9510 if (err.stack) {
9511 var out = err.stack;
9512
9513 // try to strip useless frames
9514 var fn_name = getName(stackStartFunction);
9515 var idx = out.indexOf('\n' + fn_name);
9516 if (idx >= 0) {
9517 // once we have located the function frame
9518 // we need to strip out everything before it (and its line)
9519 var next_line = out.indexOf('\n', idx + 1);
9520 out = out.substring(next_line + 1);
9521 }
9522
9523 this.stack = out;
9524 }
9525 }
9526};
9527
9528// assert.AssertionError instanceof Error
9529util.inherits(assert.AssertionError, Error);
9530
9531function truncate(s, n) {
9532 if (typeof s === 'string') {
9533 return s.length < n ? s : s.slice(0, n);
9534 } else {
9535 return s;
9536 }
9537}
9538function inspect(something) {
9539 if (functionsHaveNames || !util.isFunction(something)) {
9540 return util.inspect(something);
9541 }
9542 var rawname = getName(something);
9543 var name = rawname ? ': ' + rawname : '';
9544 return '[Function' + name + ']';
9545}
9546function getMessage(self) {
9547 return truncate(inspect(self.actual), 128) + ' ' +
9548 self.operator + ' ' +
9549 truncate(inspect(self.expected), 128);
9550}
9551
9552// At present only the three keys mentioned above are used and
9553// understood by the spec. Implementations or sub modules can pass
9554// other keys to the AssertionError's constructor - they will be
9555// ignored.
9556
9557// 3. All of the following functions must throw an AssertionError
9558// when a corresponding condition is not met, with a message that
9559// may be undefined if not provided. All assertion methods provide
9560// both the actual and expected values to the assertion error for
9561// display purposes.
9562
9563function fail(actual, expected, message, operator, stackStartFunction) {
9564 throw new assert.AssertionError({
9565 message: message,
9566 actual: actual,
9567 expected: expected,
9568 operator: operator,
9569 stackStartFunction: stackStartFunction
9570 });
9571}
9572
9573// EXTENSION! allows for well behaved errors defined elsewhere.
9574assert.fail = fail;
9575
9576// 4. Pure assertion tests whether a value is truthy, as determined
9577// by !!guard.
9578// assert.ok(guard, message_opt);
9579// This statement is equivalent to assert.equal(true, !!guard,
9580// message_opt);. To test strictly for the value true, use
9581// assert.strictEqual(true, guard, message_opt);.
9582
9583function ok(value, message) {
9584 if (!value) fail(value, true, message, '==', assert.ok);
9585}
9586assert.ok = ok;
9587
9588// 5. The equality assertion tests shallow, coercive equality with
9589// ==.
9590// assert.equal(actual, expected, message_opt);
9591
9592assert.equal = function equal(actual, expected, message) {
9593 if (actual != expected) fail(actual, expected, message, '==', assert.equal);
9594};
9595
9596// 6. The non-equality assertion tests for whether two objects are not equal
9597// with != assert.notEqual(actual, expected, message_opt);
9598
9599assert.notEqual = function notEqual(actual, expected, message) {
9600 if (actual == expected) {
9601 fail(actual, expected, message, '!=', assert.notEqual);
9602 }
9603};
9604
9605// 7. The equivalence assertion tests a deep equality relation.
9606// assert.deepEqual(actual, expected, message_opt);
9607
9608assert.deepEqual = function deepEqual(actual, expected, message) {
9609 if (!_deepEqual(actual, expected, false)) {
9610 fail(actual, expected, message, 'deepEqual', assert.deepEqual);
9611 }
9612};
9613
9614assert.deepStrictEqual = function deepStrictEqual(actual, expected, message) {
9615 if (!_deepEqual(actual, expected, true)) {
9616 fail(actual, expected, message, 'deepStrictEqual', assert.deepStrictEqual);
9617 }
9618};
9619
9620function _deepEqual(actual, expected, strict, memos) {
9621 // 7.1. All identical values are equivalent, as determined by ===.
9622 if (actual === expected) {
9623 return true;
9624 } else if (isBuffer(actual) && isBuffer(expected)) {
9625 return compare(actual, expected) === 0;
9626
9627 // 7.2. If the expected value is a Date object, the actual value is
9628 // equivalent if it is also a Date object that refers to the same time.
9629 } else if (util.isDate(actual) && util.isDate(expected)) {
9630 return actual.getTime() === expected.getTime();
9631
9632 // 7.3 If the expected value is a RegExp object, the actual value is
9633 // equivalent if it is also a RegExp object with the same source and
9634 // properties (`global`, `multiline`, `lastIndex`, `ignoreCase`).
9635 } else if (util.isRegExp(actual) && util.isRegExp(expected)) {
9636 return actual.source === expected.source &&
9637 actual.global === expected.global &&
9638 actual.multiline === expected.multiline &&
9639 actual.lastIndex === expected.lastIndex &&
9640 actual.ignoreCase === expected.ignoreCase;
9641
9642 // 7.4. Other pairs that do not both pass typeof value == 'object',
9643 // equivalence is determined by ==.
9644 } else if ((actual === null || typeof actual !== 'object') &&
9645 (expected === null || typeof expected !== 'object')) {
9646 return strict ? actual === expected : actual == expected;
9647
9648 // If both values are instances of typed arrays, wrap their underlying
9649 // ArrayBuffers in a Buffer each to increase performance
9650 // This optimization requires the arrays to have the same type as checked by
9651 // Object.prototype.toString (aka pToString). Never perform binary
9652 // comparisons for Float*Arrays, though, since e.g. +0 === -0 but their
9653 // bit patterns are not identical.
9654 } else if (isView(actual) && isView(expected) &&
9655 pToString(actual) === pToString(expected) &&
9656 !(actual instanceof Float32Array ||
9657 actual instanceof Float64Array)) {
9658 return compare(new Uint8Array(actual.buffer),
9659 new Uint8Array(expected.buffer)) === 0;
9660
9661 // 7.5 For all other Object pairs, including Array objects, equivalence is
9662 // determined by having the same number of owned properties (as verified
9663 // with Object.prototype.hasOwnProperty.call), the same set of keys
9664 // (although not necessarily the same order), equivalent values for every
9665 // corresponding key, and an identical 'prototype' property. Note: this
9666 // accounts for both named and indexed properties on Arrays.
9667 } else if (isBuffer(actual) !== isBuffer(expected)) {
9668 return false;
9669 } else {
9670 memos = memos || {actual: [], expected: []};
9671
9672 var actualIndex = memos.actual.indexOf(actual);
9673 if (actualIndex !== -1) {
9674 if (actualIndex === memos.expected.indexOf(expected)) {
9675 return true;
9676 }
9677 }
9678
9679 memos.actual.push(actual);
9680 memos.expected.push(expected);
9681
9682 return objEquiv(actual, expected, strict, memos);
9683 }
9684}
9685
9686function isArguments(object) {
9687 return Object.prototype.toString.call(object) == '[object Arguments]';
9688}
9689
9690function objEquiv(a, b, strict, actualVisitedObjects) {
9691 if (a === null || a === undefined || b === null || b === undefined)
9692 return false;
9693 // if one is a primitive, the other must be same
9694 if (util.isPrimitive(a) || util.isPrimitive(b))
9695 return a === b;
9696 if (strict && Object.getPrototypeOf(a) !== Object.getPrototypeOf(b))
9697 return false;
9698 var aIsArgs = isArguments(a);
9699 var bIsArgs = isArguments(b);
9700 if ((aIsArgs && !bIsArgs) || (!aIsArgs && bIsArgs))
9701 return false;
9702 if (aIsArgs) {
9703 a = pSlice.call(a);
9704 b = pSlice.call(b);
9705 return _deepEqual(a, b, strict);
9706 }
9707 var ka = objectKeys(a);
9708 var kb = objectKeys(b);
9709 var key, i;
9710 // having the same number of owned properties (keys incorporates
9711 // hasOwnProperty)
9712 if (ka.length !== kb.length)
9713 return false;
9714 //the same set of keys (although not necessarily the same order),
9715 ka.sort();
9716 kb.sort();
9717 //~~~cheap key test
9718 for (i = ka.length - 1; i >= 0; i--) {
9719 if (ka[i] !== kb[i])
9720 return false;
9721 }
9722 //equivalent values for every corresponding key, and
9723 //~~~possibly expensive deep test
9724 for (i = ka.length - 1; i >= 0; i--) {
9725 key = ka[i];
9726 if (!_deepEqual(a[key], b[key], strict, actualVisitedObjects))
9727 return false;
9728 }
9729 return true;
9730}
9731
9732// 8. The non-equivalence assertion tests for any deep inequality.
9733// assert.notDeepEqual(actual, expected, message_opt);
9734
9735assert.notDeepEqual = function notDeepEqual(actual, expected, message) {
9736 if (_deepEqual(actual, expected, false)) {
9737 fail(actual, expected, message, 'notDeepEqual', assert.notDeepEqual);
9738 }
9739};
9740
9741assert.notDeepStrictEqual = notDeepStrictEqual;
9742function notDeepStrictEqual(actual, expected, message) {
9743 if (_deepEqual(actual, expected, true)) {
9744 fail(actual, expected, message, 'notDeepStrictEqual', notDeepStrictEqual);
9745 }
9746}
9747
9748
9749// 9. The strict equality assertion tests strict equality, as determined by ===.
9750// assert.strictEqual(actual, expected, message_opt);
9751
9752assert.strictEqual = function strictEqual(actual, expected, message) {
9753 if (actual !== expected) {
9754 fail(actual, expected, message, '===', assert.strictEqual);
9755 }
9756};
9757
9758// 10. The strict non-equality assertion tests for strict inequality, as
9759// determined by !==. assert.notStrictEqual(actual, expected, message_opt);
9760
9761assert.notStrictEqual = function notStrictEqual(actual, expected, message) {
9762 if (actual === expected) {
9763 fail(actual, expected, message, '!==', assert.notStrictEqual);
9764 }
9765};
9766
9767function expectedException(actual, expected) {
9768 if (!actual || !expected) {
9769 return false;
9770 }
9771
9772 if (Object.prototype.toString.call(expected) == '[object RegExp]') {
9773 return expected.test(actual);
9774 }
9775
9776 try {
9777 if (actual instanceof expected) {
9778 return true;
9779 }
9780 } catch (e) {
9781 // Ignore. The instanceof check doesn't work for arrow functions.
9782 }
9783
9784 if (Error.isPrototypeOf(expected)) {
9785 return false;
9786 }
9787
9788 return expected.call({}, actual) === true;
9789}
9790
9791function _tryBlock(block) {
9792 var error;
9793 try {
9794 block();
9795 } catch (e) {
9796 error = e;
9797 }
9798 return error;
9799}
9800
9801function _throws(shouldThrow, block, expected, message) {
9802 var actual;
9803
9804 if (typeof block !== 'function') {
9805 throw new TypeError('"block" argument must be a function');
9806 }
9807
9808 if (typeof expected === 'string') {
9809 message = expected;
9810 expected = null;
9811 }
9812
9813 actual = _tryBlock(block);
9814
9815 message = (expected && expected.name ? ' (' + expected.name + ').' : '.') +
9816 (message ? ' ' + message : '.');
9817
9818 if (shouldThrow && !actual) {
9819 fail(actual, expected, 'Missing expected exception' + message);
9820 }
9821
9822 var userProvidedMessage = typeof message === 'string';
9823 var isUnwantedException = !shouldThrow && util.isError(actual);
9824 var isUnexpectedException = !shouldThrow && actual && !expected;
9825
9826 if ((isUnwantedException &&
9827 userProvidedMessage &&
9828 expectedException(actual, expected)) ||
9829 isUnexpectedException) {
9830 fail(actual, expected, 'Got unwanted exception' + message);
9831 }
9832
9833 if ((shouldThrow && actual && expected &&
9834 !expectedException(actual, expected)) || (!shouldThrow && actual)) {
9835 throw actual;
9836 }
9837}
9838
9839// 11. Expected to throw an error:
9840// assert.throws(block, Error_opt, message_opt);
9841
9842assert.throws = function(block, /*optional*/error, /*optional*/message) {
9843 _throws(true, block, error, message);
9844};
9845
9846// EXTENSION! This is annoying to write outside this module.
9847assert.doesNotThrow = function(block, /*optional*/error, /*optional*/message) {
9848 _throws(false, block, error, message);
9849};
9850
9851assert.ifError = function(err) { if (err) throw err; };
9852
9853var objectKeys = Object.keys || function (obj) {
9854 var keys = [];
9855 for (var key in obj) {
9856 if (hasOwn.call(obj, key)) keys.push(key);
9857 }
9858 return keys;
9859};
9860
9861}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
9862},{"util/":71}],69:[function(require,module,exports){
9863if (typeof Object.create === 'function') {
9864 // implementation from standard node.js 'util' module
9865 module.exports = function inherits(ctor, superCtor) {
9866 ctor.super_ = superCtor
9867 ctor.prototype = Object.create(superCtor.prototype, {
9868 constructor: {
9869 value: ctor,
9870 enumerable: false,
9871 writable: true,
9872 configurable: true
9873 }
9874 });
9875 };
9876} else {
9877 // old school shim for old browsers
9878 module.exports = function inherits(ctor, superCtor) {
9879 ctor.super_ = superCtor
9880 var TempCtor = function () {}
9881 TempCtor.prototype = superCtor.prototype
9882 ctor.prototype = new TempCtor()
9883 ctor.prototype.constructor = ctor
9884 }
9885}
9886
9887},{}],70:[function(require,module,exports){
9888module.exports = function isBuffer(arg) {
9889 return arg && typeof arg === 'object'
9890 && typeof arg.copy === 'function'
9891 && typeof arg.fill === 'function'
9892 && typeof arg.readUInt8 === 'function';
9893}
9894},{}],71:[function(require,module,exports){
9895(function (process,global){
9896// Copyright Joyent, Inc. and other Node contributors.
9897//
9898// Permission is hereby granted, free of charge, to any person obtaining a
9899// copy of this software and associated documentation files (the
9900// "Software"), to deal in the Software without restriction, including
9901// without limitation the rights to use, copy, modify, merge, publish,
9902// distribute, sublicense, and/or sell copies of the Software, and to permit
9903// persons to whom the Software is furnished to do so, subject to the
9904// following conditions:
9905//
9906// The above copyright notice and this permission notice shall be included
9907// in all copies or substantial portions of the Software.
9908//
9909// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
9910// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
9911// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
9912// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
9913// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
9914// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
9915// USE OR OTHER DEALINGS IN THE SOFTWARE.
9916
9917var formatRegExp = /%[sdj%]/g;
9918exports.format = function(f) {
9919 if (!isString(f)) {
9920 var objects = [];
9921 for (var i = 0; i < arguments.length; i++) {
9922 objects.push(inspect(arguments[i]));
9923 }
9924 return objects.join(' ');
9925 }
9926
9927 var i = 1;
9928 var args = arguments;
9929 var len = args.length;
9930 var str = String(f).replace(formatRegExp, function(x) {
9931 if (x === '%%') return '%';
9932 if (i >= len) return x;
9933 switch (x) {
9934 case '%s': return String(args[i++]);
9935 case '%d': return Number(args[i++]);
9936 case '%j':
9937 try {
9938 return JSON.stringify(args[i++]);
9939 } catch (_) {
9940 return '[Circular]';
9941 }
9942 default:
9943 return x;
9944 }
9945 });
9946 for (var x = args[i]; i < len; x = args[++i]) {
9947 if (isNull(x) || !isObject(x)) {
9948 str += ' ' + x;
9949 } else {
9950 str += ' ' + inspect(x);
9951 }
9952 }
9953 return str;
9954};
9955
9956
9957// Mark that a method should not be used.
9958// Returns a modified function which warns once by default.
9959// If --no-deprecation is set, then it is a no-op.
9960exports.deprecate = function(fn, msg) {
9961 // Allow for deprecating things in the process of starting up.
9962 if (isUndefined(global.process)) {
9963 return function() {
9964 return exports.deprecate(fn, msg).apply(this, arguments);
9965 };
9966 }
9967
9968 if (process.noDeprecation === true) {
9969 return fn;
9970 }
9971
9972 var warned = false;
9973 function deprecated() {
9974 if (!warned) {
9975 if (process.throwDeprecation) {
9976 throw new Error(msg);
9977 } else if (process.traceDeprecation) {
9978 console.trace(msg);
9979 } else {
9980 console.error(msg);
9981 }
9982 warned = true;
9983 }
9984 return fn.apply(this, arguments);
9985 }
9986
9987 return deprecated;
9988};
9989
9990
9991var debugs = {};
9992var debugEnviron;
9993exports.debuglog = function(set) {
9994 if (isUndefined(debugEnviron))
9995 debugEnviron = process.env.NODE_DEBUG || '';
9996 set = set.toUpperCase();
9997 if (!debugs[set]) {
9998 if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) {
9999 var pid = process.pid;
10000 debugs[set] = function() {
10001 var msg = exports.format.apply(exports, arguments);
10002 console.error('%s %d: %s', set, pid, msg);
10003 };
10004 } else {
10005 debugs[set] = function() {};
10006 }
10007 }
10008 return debugs[set];
10009};
10010
10011
10012/**
10013 * Echos the value of a value. Trys to print the value out
10014 * in the best way possible given the different types.
10015 *
10016 * @param {Object} obj The object to print out.
10017 * @param {Object} opts Optional options object that alters the output.
10018 */
10019/* legacy: obj, showHidden, depth, colors*/
10020function inspect(obj, opts) {
10021 // default options
10022 var ctx = {
10023 seen: [],
10024 stylize: stylizeNoColor
10025 };
10026 // legacy...
10027 if (arguments.length >= 3) ctx.depth = arguments[2];
10028 if (arguments.length >= 4) ctx.colors = arguments[3];
10029 if (isBoolean(opts)) {
10030 // legacy...
10031 ctx.showHidden = opts;
10032 } else if (opts) {
10033 // got an "options" object
10034 exports._extend(ctx, opts);
10035 }
10036 // set default options
10037 if (isUndefined(ctx.showHidden)) ctx.showHidden = false;
10038 if (isUndefined(ctx.depth)) ctx.depth = 2;
10039 if (isUndefined(ctx.colors)) ctx.colors = false;
10040 if (isUndefined(ctx.customInspect)) ctx.customInspect = true;
10041 if (ctx.colors) ctx.stylize = stylizeWithColor;
10042 return formatValue(ctx, obj, ctx.depth);
10043}
10044exports.inspect = inspect;
10045
10046
10047// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
10048inspect.colors = {
10049 'bold' : [1, 22],
10050 'italic' : [3, 23],
10051 'underline' : [4, 24],
10052 'inverse' : [7, 27],
10053 'white' : [37, 39],
10054 'grey' : [90, 39],
10055 'black' : [30, 39],
10056 'blue' : [34, 39],
10057 'cyan' : [36, 39],
10058 'green' : [32, 39],
10059 'magenta' : [35, 39],
10060 'red' : [31, 39],
10061 'yellow' : [33, 39]
10062};
10063
10064// Don't use 'blue' not visible on cmd.exe
10065inspect.styles = {
10066 'special': 'cyan',
10067 'number': 'yellow',
10068 'boolean': 'yellow',
10069 'undefined': 'grey',
10070 'null': 'bold',
10071 'string': 'green',
10072 'date': 'magenta',
10073 // "name": intentionally not styling
10074 'regexp': 'red'
10075};
10076
10077
10078function stylizeWithColor(str, styleType) {
10079 var style = inspect.styles[styleType];
10080
10081 if (style) {
10082 return '\u001b[' + inspect.colors[style][0] + 'm' + str +
10083 '\u001b[' + inspect.colors[style][1] + 'm';
10084 } else {
10085 return str;
10086 }
10087}
10088
10089
10090function stylizeNoColor(str, styleType) {
10091 return str;
10092}
10093
10094
10095function arrayToHash(array) {
10096 var hash = {};
10097
10098 array.forEach(function(val, idx) {
10099 hash[val] = true;
10100 });
10101
10102 return hash;
10103}
10104
10105
10106function formatValue(ctx, value, recurseTimes) {
10107 // Provide a hook for user-specified inspect functions.
10108 // Check that value is an object with an inspect function on it
10109 if (ctx.customInspect &&
10110 value &&
10111 isFunction(value.inspect) &&
10112 // Filter out the util module, it's inspect function is special
10113 value.inspect !== exports.inspect &&
10114 // Also filter out any prototype objects using the circular check.
10115 !(value.constructor && value.constructor.prototype === value)) {
10116 var ret = value.inspect(recurseTimes, ctx);
10117 if (!isString(ret)) {
10118 ret = formatValue(ctx, ret, recurseTimes);
10119 }
10120 return ret;
10121 }
10122
10123 // Primitive types cannot have properties
10124 var primitive = formatPrimitive(ctx, value);
10125 if (primitive) {
10126 return primitive;
10127 }
10128
10129 // Look up the keys of the object.
10130 var keys = Object.keys(value);
10131 var visibleKeys = arrayToHash(keys);
10132
10133 if (ctx.showHidden) {
10134 keys = Object.getOwnPropertyNames(value);
10135 }
10136
10137 // IE doesn't make error fields non-enumerable
10138 // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx
10139 if (isError(value)
10140 && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) {
10141 return formatError(value);
10142 }
10143
10144 // Some type of object without properties can be shortcutted.
10145 if (keys.length === 0) {
10146 if (isFunction(value)) {
10147 var name = value.name ? ': ' + value.name : '';
10148 return ctx.stylize('[Function' + name + ']', 'special');
10149 }
10150 if (isRegExp(value)) {
10151 return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
10152 }
10153 if (isDate(value)) {
10154 return ctx.stylize(Date.prototype.toString.call(value), 'date');
10155 }
10156 if (isError(value)) {
10157 return formatError(value);
10158 }
10159 }
10160
10161 var base = '', array = false, braces = ['{', '}'];
10162
10163 // Make Array say that they are Array
10164 if (isArray(value)) {
10165 array = true;
10166 braces = ['[', ']'];
10167 }
10168
10169 // Make functions say that they are functions
10170 if (isFunction(value)) {
10171 var n = value.name ? ': ' + value.name : '';
10172 base = ' [Function' + n + ']';
10173 }
10174
10175 // Make RegExps say that they are RegExps
10176 if (isRegExp(value)) {
10177 base = ' ' + RegExp.prototype.toString.call(value);
10178 }
10179
10180 // Make dates with properties first say the date
10181 if (isDate(value)) {
10182 base = ' ' + Date.prototype.toUTCString.call(value);
10183 }
10184
10185 // Make error with message first say the error
10186 if (isError(value)) {
10187 base = ' ' + formatError(value);
10188 }
10189
10190 if (keys.length === 0 && (!array || value.length == 0)) {
10191 return braces[0] + base + braces[1];
10192 }
10193
10194 if (recurseTimes < 0) {
10195 if (isRegExp(value)) {
10196 return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
10197 } else {
10198 return ctx.stylize('[Object]', 'special');
10199 }
10200 }
10201
10202 ctx.seen.push(value);
10203
10204 var output;
10205 if (array) {
10206 output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
10207 } else {
10208 output = keys.map(function(key) {
10209 return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);
10210 });
10211 }
10212
10213 ctx.seen.pop();
10214
10215 return reduceToSingleString(output, base, braces);
10216}
10217
10218
10219function formatPrimitive(ctx, value) {
10220 if (isUndefined(value))
10221 return ctx.stylize('undefined', 'undefined');
10222 if (isString(value)) {
10223 var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '')
10224 .replace(/'/g, "\\'")
10225 .replace(/\\"/g, '"') + '\'';
10226 return ctx.stylize(simple, 'string');
10227 }
10228 if (isNumber(value))
10229 return ctx.stylize('' + value, 'number');
10230 if (isBoolean(value))
10231 return ctx.stylize('' + value, 'boolean');
10232 // For some reason typeof null is "object", so special case here.
10233 if (isNull(value))
10234 return ctx.stylize('null', 'null');
10235}
10236
10237
10238function formatError(value) {
10239 return '[' + Error.prototype.toString.call(value) + ']';
10240}
10241
10242
10243function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
10244 var output = [];
10245 for (var i = 0, l = value.length; i < l; ++i) {
10246 if (hasOwnProperty(value, String(i))) {
10247 output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
10248 String(i), true));
10249 } else {
10250 output.push('');
10251 }
10252 }
10253 keys.forEach(function(key) {
10254 if (!key.match(/^\d+$/)) {
10255 output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
10256 key, true));
10257 }
10258 });
10259 return output;
10260}
10261
10262
10263function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
10264 var name, str, desc;
10265 desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] };
10266 if (desc.get) {
10267 if (desc.set) {
10268 str = ctx.stylize('[Getter/Setter]', 'special');
10269 } else {
10270 str = ctx.stylize('[Getter]', 'special');
10271 }
10272 } else {
10273 if (desc.set) {
10274 str = ctx.stylize('[Setter]', 'special');
10275 }
10276 }
10277 if (!hasOwnProperty(visibleKeys, key)) {
10278 name = '[' + key + ']';
10279 }
10280 if (!str) {
10281 if (ctx.seen.indexOf(desc.value) < 0) {
10282 if (isNull(recurseTimes)) {
10283 str = formatValue(ctx, desc.value, null);
10284 } else {
10285 str = formatValue(ctx, desc.value, recurseTimes - 1);
10286 }
10287 if (str.indexOf('\n') > -1) {
10288 if (array) {
10289 str = str.split('\n').map(function(line) {
10290 return ' ' + line;
10291 }).join('\n').substr(2);
10292 } else {
10293 str = '\n' + str.split('\n').map(function(line) {
10294 return ' ' + line;
10295 }).join('\n');
10296 }
10297 }
10298 } else {
10299 str = ctx.stylize('[Circular]', 'special');
10300 }
10301 }
10302 if (isUndefined(name)) {
10303 if (array && key.match(/^\d+$/)) {
10304 return str;
10305 }
10306 name = JSON.stringify('' + key);
10307 if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
10308 name = name.substr(1, name.length - 2);
10309 name = ctx.stylize(name, 'name');
10310 } else {
10311 name = name.replace(/'/g, "\\'")
10312 .replace(/\\"/g, '"')
10313 .replace(/(^"|"$)/g, "'");
10314 name = ctx.stylize(name, 'string');
10315 }
10316 }
10317
10318 return name + ': ' + str;
10319}
10320
10321
10322function reduceToSingleString(output, base, braces) {
10323 var numLinesEst = 0;
10324 var length = output.reduce(function(prev, cur) {
10325 numLinesEst++;
10326 if (cur.indexOf('\n') >= 0) numLinesEst++;
10327 return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1;
10328 }, 0);
10329
10330 if (length > 60) {
10331 return braces[0] +
10332 (base === '' ? '' : base + '\n ') +
10333 ' ' +
10334 output.join(',\n ') +
10335 ' ' +
10336 braces[1];
10337 }
10338
10339 return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];
10340}
10341
10342
10343// NOTE: These type checking functions intentionally don't use `instanceof`
10344// because it is fragile and can be easily faked with `Object.create()`.
10345function isArray(ar) {
10346 return Array.isArray(ar);
10347}
10348exports.isArray = isArray;
10349
10350function isBoolean(arg) {
10351 return typeof arg === 'boolean';
10352}
10353exports.isBoolean = isBoolean;
10354
10355function isNull(arg) {
10356 return arg === null;
10357}
10358exports.isNull = isNull;
10359
10360function isNullOrUndefined(arg) {
10361 return arg == null;
10362}
10363exports.isNullOrUndefined = isNullOrUndefined;
10364
10365function isNumber(arg) {
10366 return typeof arg === 'number';
10367}
10368exports.isNumber = isNumber;
10369
10370function isString(arg) {
10371 return typeof arg === 'string';
10372}
10373exports.isString = isString;
10374
10375function isSymbol(arg) {
10376 return typeof arg === 'symbol';
10377}
10378exports.isSymbol = isSymbol;
10379
10380function isUndefined(arg) {
10381 return arg === void 0;
10382}
10383exports.isUndefined = isUndefined;
10384
10385function isRegExp(re) {
10386 return isObject(re) && objectToString(re) === '[object RegExp]';
10387}
10388exports.isRegExp = isRegExp;
10389
10390function isObject(arg) {
10391 return typeof arg === 'object' && arg !== null;
10392}
10393exports.isObject = isObject;
10394
10395function isDate(d) {
10396 return isObject(d) && objectToString(d) === '[object Date]';
10397}
10398exports.isDate = isDate;
10399
10400function isError(e) {
10401 return isObject(e) &&
10402 (objectToString(e) === '[object Error]' || e instanceof Error);
10403}
10404exports.isError = isError;
10405
10406function isFunction(arg) {
10407 return typeof arg === 'function';
10408}
10409exports.isFunction = isFunction;
10410
10411function isPrimitive(arg) {
10412 return arg === null ||
10413 typeof arg === 'boolean' ||
10414 typeof arg === 'number' ||
10415 typeof arg === 'string' ||
10416 typeof arg === 'symbol' || // ES6 symbol
10417 typeof arg === 'undefined';
10418}
10419exports.isPrimitive = isPrimitive;
10420
10421exports.isBuffer = require('./support/isBuffer');
10422
10423function objectToString(o) {
10424 return Object.prototype.toString.call(o);
10425}
10426
10427
10428function pad(n) {
10429 return n < 10 ? '0' + n.toString(10) : n.toString(10);
10430}
10431
10432
10433var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
10434 'Oct', 'Nov', 'Dec'];
10435
10436// 26 Feb 16:19:34
10437function timestamp() {
10438 var d = new Date();
10439 var time = [pad(d.getHours()),
10440 pad(d.getMinutes()),
10441 pad(d.getSeconds())].join(':');
10442 return [d.getDate(), months[d.getMonth()], time].join(' ');
10443}
10444
10445
10446// log is just a thin wrapper to console.log that prepends a timestamp
10447exports.log = function() {
10448 console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments));
10449};
10450
10451
10452/**
10453 * Inherit the prototype methods from one constructor into another.
10454 *
10455 * The Function.prototype.inherits from lang.js rewritten as a standalone
10456 * function (not on Function.prototype). NOTE: If this file is to be loaded
10457 * during bootstrapping this function needs to be rewritten using some native
10458 * functions as prototype setup using normal JavaScript does not work as
10459 * expected during bootstrapping (see mirror.js in r114903).
10460 *
10461 * @param {function} ctor Constructor function which needs to inherit the
10462 * prototype.
10463 * @param {function} superCtor Constructor function to inherit prototype from.
10464 */
10465exports.inherits = require('inherits');
10466
10467exports._extend = function(origin, add) {
10468 // Don't do anything if add isn't an object
10469 if (!add || !isObject(add)) return origin;
10470
10471 var keys = Object.keys(add);
10472 var i = keys.length;
10473 while (i--) {
10474 origin[keys[i]] = add[keys[i]];
10475 }
10476 return origin;
10477};
10478
10479function hasOwnProperty(obj, prop) {
10480 return Object.prototype.hasOwnProperty.call(obj, prop);
10481}
10482
10483}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
10484},{"./support/isBuffer":70,"_process":265,"inherits":69}],72:[function(require,module,exports){
10485
10486/*!
10487 * Copyright 2010 LearnBoost <dev@learnboost.com>
10488 *
10489 * Licensed under the Apache License, Version 2.0 (the "License");
10490 * you may not use this file except in compliance with the License.
10491 * You may obtain a copy of the License at
10492 *
10493 * http://www.apache.org/licenses/LICENSE-2.0
10494 *
10495 * Unless required by applicable law or agreed to in writing, software
10496 * distributed under the License is distributed on an "AS IS" BASIS,
10497 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
10498 * See the License for the specific language governing permissions and
10499 * limitations under the License.
10500 */
10501
10502/**
10503 * Module dependencies.
10504 */
10505
10506var crypto = require('crypto')
10507 , parse = require('url').parse
10508 ;
10509
10510/**
10511 * Valid keys.
10512 */
10513
10514var keys =
10515 [ 'acl'
10516 , 'location'
10517 , 'logging'
10518 , 'notification'
10519 , 'partNumber'
10520 , 'policy'
10521 , 'requestPayment'
10522 , 'torrent'
10523 , 'uploadId'
10524 , 'uploads'
10525 , 'versionId'
10526 , 'versioning'
10527 , 'versions'
10528 , 'website'
10529 ]
10530
10531/**
10532 * Return an "Authorization" header value with the given `options`
10533 * in the form of "AWS <key>:<signature>"
10534 *
10535 * @param {Object} options
10536 * @return {String}
10537 * @api private
10538 */
10539
10540function authorization (options) {
10541 return 'AWS ' + options.key + ':' + sign(options)
10542}
10543
10544module.exports = authorization
10545module.exports.authorization = authorization
10546
10547/**
10548 * Simple HMAC-SHA1 Wrapper
10549 *
10550 * @param {Object} options
10551 * @return {String}
10552 * @api private
10553 */
10554
10555function hmacSha1 (options) {
10556 return crypto.createHmac('sha1', options.secret).update(options.message).digest('base64')
10557}
10558
10559module.exports.hmacSha1 = hmacSha1
10560
10561/**
10562 * Create a base64 sha1 HMAC for `options`.
10563 *
10564 * @param {Object} options
10565 * @return {String}
10566 * @api private
10567 */
10568
10569function sign (options) {
10570 options.message = stringToSign(options)
10571 return hmacSha1(options)
10572}
10573module.exports.sign = sign
10574
10575/**
10576 * Create a base64 sha1 HMAC for `options`.
10577 *
10578 * Specifically to be used with S3 presigned URLs
10579 *
10580 * @param {Object} options
10581 * @return {String}
10582 * @api private
10583 */
10584
10585function signQuery (options) {
10586 options.message = queryStringToSign(options)
10587 return hmacSha1(options)
10588}
10589module.exports.signQuery= signQuery
10590
10591/**
10592 * Return a string for sign() with the given `options`.
10593 *
10594 * Spec:
10595 *
10596 * <verb>\n
10597 * <md5>\n
10598 * <content-type>\n
10599 * <date>\n
10600 * [headers\n]
10601 * <resource>
10602 *
10603 * @param {Object} options
10604 * @return {String}
10605 * @api private
10606 */
10607
10608function stringToSign (options) {
10609 var headers = options.amazonHeaders || ''
10610 if (headers) headers += '\n'
10611 var r =
10612 [ options.verb
10613 , options.md5
10614 , options.contentType
10615 , options.date ? options.date.toUTCString() : ''
10616 , headers + options.resource
10617 ]
10618 return r.join('\n')
10619}
10620module.exports.stringToSign = stringToSign
10621
10622/**
10623 * Return a string for sign() with the given `options`, but is meant exclusively
10624 * for S3 presigned URLs
10625 *
10626 * Spec:
10627 *
10628 * <date>\n
10629 * <resource>
10630 *
10631 * @param {Object} options
10632 * @return {String}
10633 * @api private
10634 */
10635
10636function queryStringToSign (options){
10637 return 'GET\n\n\n' + options.date + '\n' + options.resource
10638}
10639module.exports.queryStringToSign = queryStringToSign
10640
10641/**
10642 * Perform the following:
10643 *
10644 * - ignore non-amazon headers
10645 * - lowercase fields
10646 * - sort lexicographically
10647 * - trim whitespace between ":"
10648 * - join with newline
10649 *
10650 * @param {Object} headers
10651 * @return {String}
10652 * @api private
10653 */
10654
10655function canonicalizeHeaders (headers) {
10656 var buf = []
10657 , fields = Object.keys(headers)
10658 ;
10659 for (var i = 0, len = fields.length; i < len; ++i) {
10660 var field = fields[i]
10661 , val = headers[field]
10662 , field = field.toLowerCase()
10663 ;
10664 if (0 !== field.indexOf('x-amz')) continue
10665 buf.push(field + ':' + val)
10666 }
10667 return buf.sort().join('\n')
10668}
10669module.exports.canonicalizeHeaders = canonicalizeHeaders
10670
10671/**
10672 * Perform the following:
10673 *
10674 * - ignore non sub-resources
10675 * - sort lexicographically
10676 *
10677 * @param {String} resource
10678 * @return {String}
10679 * @api private
10680 */
10681
10682function canonicalizeResource (resource) {
10683 var url = parse(resource, true)
10684 , path = url.pathname
10685 , buf = []
10686 ;
10687
10688 Object.keys(url.query).forEach(function(key){
10689 if (!~keys.indexOf(key)) return
10690 var val = '' == url.query[key] ? '' : '=' + encodeURIComponent(url.query[key])
10691 buf.push(key + val)
10692 })
10693
10694 return path + (buf.length ? '?' + buf.sort().join('&') : '')
10695}
10696module.exports.canonicalizeResource = canonicalizeResource
10697
10698},{"crypto":126,"url":393}],73:[function(require,module,exports){
10699(function (process,Buffer){
10700var aws4 = exports,
10701 url = require('url'),
10702 querystring = require('querystring'),
10703 crypto = require('crypto'),
10704 lru = require('./lru'),
10705 credentialsCache = lru(1000)
10706
10707// http://docs.amazonwebservices.com/general/latest/gr/signature-version-4.html
10708
10709function hmac(key, string, encoding) {
10710 return crypto.createHmac('sha256', key).update(string, 'utf8').digest(encoding)
10711}
10712
10713function hash(string, encoding) {
10714 return crypto.createHash('sha256').update(string, 'utf8').digest(encoding)
10715}
10716
10717// This function assumes the string has already been percent encoded
10718function encodeRfc3986(urlEncodedString) {
10719 return urlEncodedString.replace(/[!'()*]/g, function(c) {
10720 return '%' + c.charCodeAt(0).toString(16).toUpperCase()
10721 })
10722}
10723
10724// request: { path | body, [host], [method], [headers], [service], [region] }
10725// credentials: { accessKeyId, secretAccessKey, [sessionToken] }
10726function RequestSigner(request, credentials) {
10727
10728 if (typeof request === 'string') request = url.parse(request)
10729
10730 var headers = request.headers = (request.headers || {}),
10731 hostParts = this.matchHost(request.hostname || request.host || headers.Host || headers.host)
10732
10733 this.request = request
10734 this.credentials = credentials || this.defaultCredentials()
10735
10736 this.service = request.service || hostParts[0] || ''
10737 this.region = request.region || hostParts[1] || 'us-east-1'
10738
10739 // SES uses a different domain from the service name
10740 if (this.service === 'email') this.service = 'ses'
10741
10742 if (!request.method && request.body)
10743 request.method = 'POST'
10744
10745 if (!headers.Host && !headers.host) {
10746 headers.Host = request.hostname || request.host || this.createHost()
10747
10748 // If a port is specified explicitly, use it as is
10749 if (request.port)
10750 headers.Host += ':' + request.port
10751 }
10752 if (!request.hostname && !request.host)
10753 request.hostname = headers.Host || headers.host
10754
10755 this.isCodeCommitGit = this.service === 'codecommit' && request.method === 'GIT'
10756}
10757
10758RequestSigner.prototype.matchHost = function(host) {
10759 var match = (host || '').match(/([^\.]+)\.(?:([^\.]*)\.)?amazonaws\.com(\.cn)?$/)
10760 var hostParts = (match || []).slice(1, 3)
10761
10762 // ES's hostParts are sometimes the other way round, if the value that is expected
10763 // to be region equals ‘es’ switch them back
10764 // e.g. search-cluster-name-aaaa00aaaa0aaa0aaaaaaa0aaa.us-east-1.es.amazonaws.com
10765 if (hostParts[1] === 'es')
10766 hostParts = hostParts.reverse()
10767
10768 return hostParts
10769}
10770
10771// http://docs.aws.amazon.com/general/latest/gr/rande.html
10772RequestSigner.prototype.isSingleRegion = function() {
10773 // Special case for S3 and SimpleDB in us-east-1
10774 if (['s3', 'sdb'].indexOf(this.service) >= 0 && this.region === 'us-east-1') return true
10775
10776 return ['cloudfront', 'ls', 'route53', 'iam', 'importexport', 'sts']
10777 .indexOf(this.service) >= 0
10778}
10779
10780RequestSigner.prototype.createHost = function() {
10781 var region = this.isSingleRegion() ? '' :
10782 (this.service === 's3' && this.region !== 'us-east-1' ? '-' : '.') + this.region,
10783 service = this.service === 'ses' ? 'email' : this.service
10784 return service + region + '.amazonaws.com'
10785}
10786
10787RequestSigner.prototype.prepareRequest = function() {
10788 this.parsePath()
10789
10790 var request = this.request, headers = request.headers, query
10791
10792 if (request.signQuery) {
10793
10794 this.parsedPath.query = query = this.parsedPath.query || {}
10795
10796 if (this.credentials.sessionToken)
10797 query['X-Amz-Security-Token'] = this.credentials.sessionToken
10798
10799 if (this.service === 's3' && !query['X-Amz-Expires'])
10800 query['X-Amz-Expires'] = 86400
10801
10802 if (query['X-Amz-Date'])
10803 this.datetime = query['X-Amz-Date']
10804 else
10805 query['X-Amz-Date'] = this.getDateTime()
10806
10807 query['X-Amz-Algorithm'] = 'AWS4-HMAC-SHA256'
10808 query['X-Amz-Credential'] = this.credentials.accessKeyId + '/' + this.credentialString()
10809 query['X-Amz-SignedHeaders'] = this.signedHeaders()
10810
10811 } else {
10812
10813 if (!request.doNotModifyHeaders && !this.isCodeCommitGit) {
10814 if (request.body && !headers['Content-Type'] && !headers['content-type'])
10815 headers['Content-Type'] = 'application/x-www-form-urlencoded; charset=utf-8'
10816
10817 if (request.body && !headers['Content-Length'] && !headers['content-length'])
10818 headers['Content-Length'] = Buffer.byteLength(request.body)
10819
10820 if (this.credentials.sessionToken && !headers['X-Amz-Security-Token'] && !headers['x-amz-security-token'])
10821 headers['X-Amz-Security-Token'] = this.credentials.sessionToken
10822
10823 if (this.service === 's3' && !headers['X-Amz-Content-Sha256'] && !headers['x-amz-content-sha256'])
10824 headers['X-Amz-Content-Sha256'] = hash(this.request.body || '', 'hex')
10825
10826 if (headers['X-Amz-Date'] || headers['x-amz-date'])
10827 this.datetime = headers['X-Amz-Date'] || headers['x-amz-date']
10828 else
10829 headers['X-Amz-Date'] = this.getDateTime()
10830 }
10831
10832 delete headers.Authorization
10833 delete headers.authorization
10834 }
10835}
10836
10837RequestSigner.prototype.sign = function() {
10838 if (!this.parsedPath) this.prepareRequest()
10839
10840 if (this.request.signQuery) {
10841 this.parsedPath.query['X-Amz-Signature'] = this.signature()
10842 } else {
10843 this.request.headers.Authorization = this.authHeader()
10844 }
10845
10846 this.request.path = this.formatPath()
10847
10848 return this.request
10849}
10850
10851RequestSigner.prototype.getDateTime = function() {
10852 if (!this.datetime) {
10853 var headers = this.request.headers,
10854 date = new Date(headers.Date || headers.date || new Date)
10855
10856 this.datetime = date.toISOString().replace(/[:\-]|\.\d{3}/g, '')
10857
10858 // Remove the trailing 'Z' on the timestamp string for CodeCommit git access
10859 if (this.isCodeCommitGit) this.datetime = this.datetime.slice(0, -1)
10860 }
10861 return this.datetime
10862}
10863
10864RequestSigner.prototype.getDate = function() {
10865 return this.getDateTime().substr(0, 8)
10866}
10867
10868RequestSigner.prototype.authHeader = function() {
10869 return [
10870 'AWS4-HMAC-SHA256 Credential=' + this.credentials.accessKeyId + '/' + this.credentialString(),
10871 'SignedHeaders=' + this.signedHeaders(),
10872 'Signature=' + this.signature(),
10873 ].join(', ')
10874}
10875
10876RequestSigner.prototype.signature = function() {
10877 var date = this.getDate(),
10878 cacheKey = [this.credentials.secretAccessKey, date, this.region, this.service].join(),
10879 kDate, kRegion, kService, kCredentials = credentialsCache.get(cacheKey)
10880 if (!kCredentials) {
10881 kDate = hmac('AWS4' + this.credentials.secretAccessKey, date)
10882 kRegion = hmac(kDate, this.region)
10883 kService = hmac(kRegion, this.service)
10884 kCredentials = hmac(kService, 'aws4_request')
10885 credentialsCache.set(cacheKey, kCredentials)
10886 }
10887 return hmac(kCredentials, this.stringToSign(), 'hex')
10888}
10889
10890RequestSigner.prototype.stringToSign = function() {
10891 return [
10892 'AWS4-HMAC-SHA256',
10893 this.getDateTime(),
10894 this.credentialString(),
10895 hash(this.canonicalString(), 'hex'),
10896 ].join('\n')
10897}
10898
10899RequestSigner.prototype.canonicalString = function() {
10900 if (!this.parsedPath) this.prepareRequest()
10901
10902 var pathStr = this.parsedPath.path,
10903 query = this.parsedPath.query,
10904 headers = this.request.headers,
10905 queryStr = '',
10906 normalizePath = this.service !== 's3',
10907 decodePath = this.service === 's3' || this.request.doNotEncodePath,
10908 decodeSlashesInPath = this.service === 's3',
10909 firstValOnly = this.service === 's3',
10910 bodyHash
10911
10912 if (this.service === 's3' && this.request.signQuery) {
10913 bodyHash = 'UNSIGNED-PAYLOAD'
10914 } else if (this.isCodeCommitGit) {
10915 bodyHash = ''
10916 } else {
10917 bodyHash = headers['X-Amz-Content-Sha256'] || headers['x-amz-content-sha256'] ||
10918 hash(this.request.body || '', 'hex')
10919 }
10920
10921 if (query) {
10922 queryStr = encodeRfc3986(querystring.stringify(Object.keys(query).sort().reduce(function(obj, key) {
10923 if (!key) return obj
10924 obj[key] = !Array.isArray(query[key]) ? query[key] :
10925 (firstValOnly ? query[key][0] : query[key].slice().sort())
10926 return obj
10927 }, {})))
10928 }
10929 if (pathStr !== '/') {
10930 if (normalizePath) pathStr = pathStr.replace(/\/{2,}/g, '/')
10931 pathStr = pathStr.split('/').reduce(function(path, piece) {
10932 if (normalizePath && piece === '..') {
10933 path.pop()
10934 } else if (!normalizePath || piece !== '.') {
10935 if (decodePath) piece = decodeURIComponent(piece)
10936 path.push(encodeRfc3986(encodeURIComponent(piece)))
10937 }
10938 return path
10939 }, []).join('/')
10940 if (pathStr[0] !== '/') pathStr = '/' + pathStr
10941 if (decodeSlashesInPath) pathStr = pathStr.replace(/%2F/g, '/')
10942 }
10943
10944 return [
10945 this.request.method || 'GET',
10946 pathStr,
10947 queryStr,
10948 this.canonicalHeaders() + '\n',
10949 this.signedHeaders(),
10950 bodyHash,
10951 ].join('\n')
10952}
10953
10954RequestSigner.prototype.canonicalHeaders = function() {
10955 var headers = this.request.headers
10956 function trimAll(header) {
10957 return header.toString().trim().replace(/\s+/g, ' ')
10958 }
10959 return Object.keys(headers)
10960 .sort(function(a, b) { return a.toLowerCase() < b.toLowerCase() ? -1 : 1 })
10961 .map(function(key) { return key.toLowerCase() + ':' + trimAll(headers[key]) })
10962 .join('\n')
10963}
10964
10965RequestSigner.prototype.signedHeaders = function() {
10966 return Object.keys(this.request.headers)
10967 .map(function(key) { return key.toLowerCase() })
10968 .sort()
10969 .join(';')
10970}
10971
10972RequestSigner.prototype.credentialString = function() {
10973 return [
10974 this.getDate(),
10975 this.region,
10976 this.service,
10977 'aws4_request',
10978 ].join('/')
10979}
10980
10981RequestSigner.prototype.defaultCredentials = function() {
10982 var env = process.env
10983 return {
10984 accessKeyId: env.AWS_ACCESS_KEY_ID || env.AWS_ACCESS_KEY,
10985 secretAccessKey: env.AWS_SECRET_ACCESS_KEY || env.AWS_SECRET_KEY,
10986 sessionToken: env.AWS_SESSION_TOKEN,
10987 }
10988}
10989
10990RequestSigner.prototype.parsePath = function() {
10991 var path = this.request.path || '/',
10992 queryIx = path.indexOf('?'),
10993 query = null
10994
10995 if (queryIx >= 0) {
10996 query = querystring.parse(path.slice(queryIx + 1))
10997 path = path.slice(0, queryIx)
10998 }
10999
11000 // S3 doesn't always encode characters > 127 correctly and
11001 // all services don't encode characters > 255 correctly
11002 // So if there are non-reserved chars (and it's not already all % encoded), just encode them all
11003 if (/[^0-9A-Za-z!'()*\-._~%/]/.test(path)) {
11004 path = path.split('/').map(function(piece) {
11005 return encodeURIComponent(decodeURIComponent(piece))
11006 }).join('/')
11007 }
11008
11009 this.parsedPath = {
11010 path: path,
11011 query: query,
11012 }
11013}
11014
11015RequestSigner.prototype.formatPath = function() {
11016 var path = this.parsedPath.path,
11017 query = this.parsedPath.query
11018
11019 if (!query) return path
11020
11021 // Services don't support empty query string keys
11022 if (query[''] != null) delete query['']
11023
11024 return path + '?' + encodeRfc3986(querystring.stringify(query))
11025}
11026
11027aws4.RequestSigner = RequestSigner
11028
11029aws4.sign = function(request, credentials) {
11030 return new RequestSigner(request, credentials).sign()
11031}
11032
11033}).call(this,require('_process'),require("buffer").Buffer)
11034},{"./lru":74,"_process":265,"buffer":114,"crypto":126,"querystring":277,"url":393}],74:[function(require,module,exports){
11035module.exports = function(size) {
11036 return new LruCache(size)
11037}
11038
11039function LruCache(size) {
11040 this.capacity = size | 0
11041 this.map = Object.create(null)
11042 this.list = new DoublyLinkedList()
11043}
11044
11045LruCache.prototype.get = function(key) {
11046 var node = this.map[key]
11047 if (node == null) return undefined
11048 this.used(node)
11049 return node.val
11050}
11051
11052LruCache.prototype.set = function(key, val) {
11053 var node = this.map[key]
11054 if (node != null) {
11055 node.val = val
11056 } else {
11057 if (!this.capacity) this.prune()
11058 if (!this.capacity) return false
11059 node = new DoublyLinkedNode(key, val)
11060 this.map[key] = node
11061 this.capacity--
11062 }
11063 this.used(node)
11064 return true
11065}
11066
11067LruCache.prototype.used = function(node) {
11068 this.list.moveToFront(node)
11069}
11070
11071LruCache.prototype.prune = function() {
11072 var node = this.list.pop()
11073 if (node != null) {
11074 delete this.map[node.key]
11075 this.capacity++
11076 }
11077}
11078
11079
11080function DoublyLinkedList() {
11081 this.firstNode = null
11082 this.lastNode = null
11083}
11084
11085DoublyLinkedList.prototype.moveToFront = function(node) {
11086 if (this.firstNode == node) return
11087
11088 this.remove(node)
11089
11090 if (this.firstNode == null) {
11091 this.firstNode = node
11092 this.lastNode = node
11093 node.prev = null
11094 node.next = null
11095 } else {
11096 node.prev = null
11097 node.next = this.firstNode
11098 node.next.prev = node
11099 this.firstNode = node
11100 }
11101}
11102
11103DoublyLinkedList.prototype.pop = function() {
11104 var lastNode = this.lastNode
11105 if (lastNode != null) {
11106 this.remove(lastNode)
11107 }
11108 return lastNode
11109}
11110
11111DoublyLinkedList.prototype.remove = function(node) {
11112 if (this.firstNode == node) {
11113 this.firstNode = node.next
11114 } else if (node.prev != null) {
11115 node.prev.next = node.next
11116 }
11117 if (this.lastNode == node) {
11118 this.lastNode = node.prev
11119 } else if (node.next != null) {
11120 node.next.prev = node.prev
11121 }
11122}
11123
11124
11125function DoublyLinkedNode(key, val) {
11126 this.key = key
11127 this.val = val
11128 this.prev = null
11129 this.next = null
11130}
11131
11132},{}],75:[function(require,module,exports){
11133'use strict'
11134
11135exports.byteLength = byteLength
11136exports.toByteArray = toByteArray
11137exports.fromByteArray = fromByteArray
11138
11139var lookup = []
11140var revLookup = []
11141var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array
11142
11143var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
11144for (var i = 0, len = code.length; i < len; ++i) {
11145 lookup[i] = code[i]
11146 revLookup[code.charCodeAt(i)] = i
11147}
11148
11149// Support decoding URL-safe base64 strings, as Node.js does.
11150// See: https://en.wikipedia.org/wiki/Base64#URL_applications
11151revLookup['-'.charCodeAt(0)] = 62
11152revLookup['_'.charCodeAt(0)] = 63
11153
11154function getLens (b64) {
11155 var len = b64.length
11156
11157 if (len % 4 > 0) {
11158 throw new Error('Invalid string. Length must be a multiple of 4')
11159 }
11160
11161 // Trim off extra bytes after placeholder bytes are found
11162 // See: https://github.com/beatgammit/base64-js/issues/42
11163 var validLen = b64.indexOf('=')
11164 if (validLen === -1) validLen = len
11165
11166 var placeHoldersLen = validLen === len
11167 ? 0
11168 : 4 - (validLen % 4)
11169
11170 return [validLen, placeHoldersLen]
11171}
11172
11173// base64 is 4/3 + up to two characters of the original data
11174function byteLength (b64) {
11175 var lens = getLens(b64)
11176 var validLen = lens[0]
11177 var placeHoldersLen = lens[1]
11178 return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen
11179}
11180
11181function _byteLength (b64, validLen, placeHoldersLen) {
11182 return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen
11183}
11184
11185function toByteArray (b64) {
11186 var tmp
11187 var lens = getLens(b64)
11188 var validLen = lens[0]
11189 var placeHoldersLen = lens[1]
11190
11191 var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen))
11192
11193 var curByte = 0
11194
11195 // if there are placeholders, only get up to the last complete 4 chars
11196 var len = placeHoldersLen > 0
11197 ? validLen - 4
11198 : validLen
11199
11200 var i
11201 for (i = 0; i < len; i += 4) {
11202 tmp =
11203 (revLookup[b64.charCodeAt(i)] << 18) |
11204 (revLookup[b64.charCodeAt(i + 1)] << 12) |
11205 (revLookup[b64.charCodeAt(i + 2)] << 6) |
11206 revLookup[b64.charCodeAt(i + 3)]
11207 arr[curByte++] = (tmp >> 16) & 0xFF
11208 arr[curByte++] = (tmp >> 8) & 0xFF
11209 arr[curByte++] = tmp & 0xFF
11210 }
11211
11212 if (placeHoldersLen === 2) {
11213 tmp =
11214 (revLookup[b64.charCodeAt(i)] << 2) |
11215 (revLookup[b64.charCodeAt(i + 1)] >> 4)
11216 arr[curByte++] = tmp & 0xFF
11217 }
11218
11219 if (placeHoldersLen === 1) {
11220 tmp =
11221 (revLookup[b64.charCodeAt(i)] << 10) |
11222 (revLookup[b64.charCodeAt(i + 1)] << 4) |
11223 (revLookup[b64.charCodeAt(i + 2)] >> 2)
11224 arr[curByte++] = (tmp >> 8) & 0xFF
11225 arr[curByte++] = tmp & 0xFF
11226 }
11227
11228 return arr
11229}
11230
11231function tripletToBase64 (num) {
11232 return lookup[num >> 18 & 0x3F] +
11233 lookup[num >> 12 & 0x3F] +
11234 lookup[num >> 6 & 0x3F] +
11235 lookup[num & 0x3F]
11236}
11237
11238function encodeChunk (uint8, start, end) {
11239 var tmp
11240 var output = []
11241 for (var i = start; i < end; i += 3) {
11242 tmp =
11243 ((uint8[i] << 16) & 0xFF0000) +
11244 ((uint8[i + 1] << 8) & 0xFF00) +
11245 (uint8[i + 2] & 0xFF)
11246 output.push(tripletToBase64(tmp))
11247 }
11248 return output.join('')
11249}
11250
11251function fromByteArray (uint8) {
11252 var tmp
11253 var len = uint8.length
11254 var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes
11255 var parts = []
11256 var maxChunkLength = 16383 // must be multiple of 3
11257
11258 // go through the array every three bytes, we'll deal with trailing stuff later
11259 for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
11260 parts.push(encodeChunk(
11261 uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)
11262 ))
11263 }
11264
11265 // pad the end with zeros, but make sure to not forget the extra bytes
11266 if (extraBytes === 1) {
11267 tmp = uint8[len - 1]
11268 parts.push(
11269 lookup[tmp >> 2] +
11270 lookup[(tmp << 4) & 0x3F] +
11271 '=='
11272 )
11273 } else if (extraBytes === 2) {
11274 tmp = (uint8[len - 2] << 8) + uint8[len - 1]
11275 parts.push(
11276 lookup[tmp >> 10] +
11277 lookup[(tmp >> 4) & 0x3F] +
11278 lookup[(tmp << 2) & 0x3F] +
11279 '='
11280 )
11281 }
11282
11283 return parts.join('')
11284}
11285
11286},{}],76:[function(require,module,exports){
11287'use strict';
11288
11289var crypto_hash_sha512 = require('tweetnacl').lowlevel.crypto_hash;
11290
11291/*
11292 * This file is a 1:1 port from the OpenBSD blowfish.c and bcrypt_pbkdf.c. As a
11293 * result, it retains the original copyright and license. The two files are
11294 * under slightly different (but compatible) licenses, and are here combined in
11295 * one file.
11296 *
11297 * Credit for the actual porting work goes to:
11298 * Devi Mandiri <me@devi.web.id>
11299 */
11300
11301/*
11302 * The Blowfish portions are under the following license:
11303 *
11304 * Blowfish block cipher for OpenBSD
11305 * Copyright 1997 Niels Provos <provos@physnet.uni-hamburg.de>
11306 * All rights reserved.
11307 *
11308 * Implementation advice by David Mazieres <dm@lcs.mit.edu>.
11309 *
11310 * Redistribution and use in source and binary forms, with or without
11311 * modification, are permitted provided that the following conditions
11312 * are met:
11313 * 1. Redistributions of source code must retain the above copyright
11314 * notice, this list of conditions and the following disclaimer.
11315 * 2. Redistributions in binary form must reproduce the above copyright
11316 * notice, this list of conditions and the following disclaimer in the
11317 * documentation and/or other materials provided with the distribution.
11318 * 3. The name of the author may not be used to endorse or promote products
11319 * derived from this software without specific prior written permission.
11320 *
11321 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
11322 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
11323 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
11324 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
11325 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
11326 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
11327 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
11328 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
11329 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
11330 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
11331 */
11332
11333/*
11334 * The bcrypt_pbkdf portions are under the following license:
11335 *
11336 * Copyright (c) 2013 Ted Unangst <tedu@openbsd.org>
11337 *
11338 * Permission to use, copy, modify, and distribute this software for any
11339 * purpose with or without fee is hereby granted, provided that the above
11340 * copyright notice and this permission notice appear in all copies.
11341 *
11342 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11343 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
11344 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11345 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
11346 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
11347 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
11348 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
11349 */
11350
11351/*
11352 * Performance improvements (Javascript-specific):
11353 *
11354 * Copyright 2016, Joyent Inc
11355 * Author: Alex Wilson <alex.wilson@joyent.com>
11356 *
11357 * Permission to use, copy, modify, and distribute this software for any
11358 * purpose with or without fee is hereby granted, provided that the above
11359 * copyright notice and this permission notice appear in all copies.
11360 *
11361 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11362 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
11363 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11364 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
11365 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
11366 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
11367 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
11368 */
11369
11370// Ported from OpenBSD bcrypt_pbkdf.c v1.9
11371
11372var BLF_J = 0;
11373
11374var Blowfish = function() {
11375 this.S = [
11376 new Uint32Array([
11377 0xd1310ba6, 0x98dfb5ac, 0x2ffd72db, 0xd01adfb7,
11378 0xb8e1afed, 0x6a267e96, 0xba7c9045, 0xf12c7f99,
11379 0x24a19947, 0xb3916cf7, 0x0801f2e2, 0x858efc16,
11380 0x636920d8, 0x71574e69, 0xa458fea3, 0xf4933d7e,
11381 0x0d95748f, 0x728eb658, 0x718bcd58, 0x82154aee,
11382 0x7b54a41d, 0xc25a59b5, 0x9c30d539, 0x2af26013,
11383 0xc5d1b023, 0x286085f0, 0xca417918, 0xb8db38ef,
11384 0x8e79dcb0, 0x603a180e, 0x6c9e0e8b, 0xb01e8a3e,
11385 0xd71577c1, 0xbd314b27, 0x78af2fda, 0x55605c60,
11386 0xe65525f3, 0xaa55ab94, 0x57489862, 0x63e81440,
11387 0x55ca396a, 0x2aab10b6, 0xb4cc5c34, 0x1141e8ce,
11388 0xa15486af, 0x7c72e993, 0xb3ee1411, 0x636fbc2a,
11389 0x2ba9c55d, 0x741831f6, 0xce5c3e16, 0x9b87931e,
11390 0xafd6ba33, 0x6c24cf5c, 0x7a325381, 0x28958677,
11391 0x3b8f4898, 0x6b4bb9af, 0xc4bfe81b, 0x66282193,
11392 0x61d809cc, 0xfb21a991, 0x487cac60, 0x5dec8032,
11393 0xef845d5d, 0xe98575b1, 0xdc262302, 0xeb651b88,
11394 0x23893e81, 0xd396acc5, 0x0f6d6ff3, 0x83f44239,
11395 0x2e0b4482, 0xa4842004, 0x69c8f04a, 0x9e1f9b5e,
11396 0x21c66842, 0xf6e96c9a, 0x670c9c61, 0xabd388f0,
11397 0x6a51a0d2, 0xd8542f68, 0x960fa728, 0xab5133a3,
11398 0x6eef0b6c, 0x137a3be4, 0xba3bf050, 0x7efb2a98,
11399 0xa1f1651d, 0x39af0176, 0x66ca593e, 0x82430e88,
11400 0x8cee8619, 0x456f9fb4, 0x7d84a5c3, 0x3b8b5ebe,
11401 0xe06f75d8, 0x85c12073, 0x401a449f, 0x56c16aa6,
11402 0x4ed3aa62, 0x363f7706, 0x1bfedf72, 0x429b023d,
11403 0x37d0d724, 0xd00a1248, 0xdb0fead3, 0x49f1c09b,
11404 0x075372c9, 0x80991b7b, 0x25d479d8, 0xf6e8def7,
11405 0xe3fe501a, 0xb6794c3b, 0x976ce0bd, 0x04c006ba,
11406 0xc1a94fb6, 0x409f60c4, 0x5e5c9ec2, 0x196a2463,
11407 0x68fb6faf, 0x3e6c53b5, 0x1339b2eb, 0x3b52ec6f,
11408 0x6dfc511f, 0x9b30952c, 0xcc814544, 0xaf5ebd09,
11409 0xbee3d004, 0xde334afd, 0x660f2807, 0x192e4bb3,
11410 0xc0cba857, 0x45c8740f, 0xd20b5f39, 0xb9d3fbdb,
11411 0x5579c0bd, 0x1a60320a, 0xd6a100c6, 0x402c7279,
11412 0x679f25fe, 0xfb1fa3cc, 0x8ea5e9f8, 0xdb3222f8,
11413 0x3c7516df, 0xfd616b15, 0x2f501ec8, 0xad0552ab,
11414 0x323db5fa, 0xfd238760, 0x53317b48, 0x3e00df82,
11415 0x9e5c57bb, 0xca6f8ca0, 0x1a87562e, 0xdf1769db,
11416 0xd542a8f6, 0x287effc3, 0xac6732c6, 0x8c4f5573,
11417 0x695b27b0, 0xbbca58c8, 0xe1ffa35d, 0xb8f011a0,
11418 0x10fa3d98, 0xfd2183b8, 0x4afcb56c, 0x2dd1d35b,
11419 0x9a53e479, 0xb6f84565, 0xd28e49bc, 0x4bfb9790,
11420 0xe1ddf2da, 0xa4cb7e33, 0x62fb1341, 0xcee4c6e8,
11421 0xef20cada, 0x36774c01, 0xd07e9efe, 0x2bf11fb4,
11422 0x95dbda4d, 0xae909198, 0xeaad8e71, 0x6b93d5a0,
11423 0xd08ed1d0, 0xafc725e0, 0x8e3c5b2f, 0x8e7594b7,
11424 0x8ff6e2fb, 0xf2122b64, 0x8888b812, 0x900df01c,
11425 0x4fad5ea0, 0x688fc31c, 0xd1cff191, 0xb3a8c1ad,
11426 0x2f2f2218, 0xbe0e1777, 0xea752dfe, 0x8b021fa1,
11427 0xe5a0cc0f, 0xb56f74e8, 0x18acf3d6, 0xce89e299,
11428 0xb4a84fe0, 0xfd13e0b7, 0x7cc43b81, 0xd2ada8d9,
11429 0x165fa266, 0x80957705, 0x93cc7314, 0x211a1477,
11430 0xe6ad2065, 0x77b5fa86, 0xc75442f5, 0xfb9d35cf,
11431 0xebcdaf0c, 0x7b3e89a0, 0xd6411bd3, 0xae1e7e49,
11432 0x00250e2d, 0x2071b35e, 0x226800bb, 0x57b8e0af,
11433 0x2464369b, 0xf009b91e, 0x5563911d, 0x59dfa6aa,
11434 0x78c14389, 0xd95a537f, 0x207d5ba2, 0x02e5b9c5,
11435 0x83260376, 0x6295cfa9, 0x11c81968, 0x4e734a41,
11436 0xb3472dca, 0x7b14a94a, 0x1b510052, 0x9a532915,
11437 0xd60f573f, 0xbc9bc6e4, 0x2b60a476, 0x81e67400,
11438 0x08ba6fb5, 0x571be91f, 0xf296ec6b, 0x2a0dd915,
11439 0xb6636521, 0xe7b9f9b6, 0xff34052e, 0xc5855664,
11440 0x53b02d5d, 0xa99f8fa1, 0x08ba4799, 0x6e85076a]),
11441 new Uint32Array([
11442 0x4b7a70e9, 0xb5b32944, 0xdb75092e, 0xc4192623,
11443 0xad6ea6b0, 0x49a7df7d, 0x9cee60b8, 0x8fedb266,
11444 0xecaa8c71, 0x699a17ff, 0x5664526c, 0xc2b19ee1,
11445 0x193602a5, 0x75094c29, 0xa0591340, 0xe4183a3e,
11446 0x3f54989a, 0x5b429d65, 0x6b8fe4d6, 0x99f73fd6,
11447 0xa1d29c07, 0xefe830f5, 0x4d2d38e6, 0xf0255dc1,
11448 0x4cdd2086, 0x8470eb26, 0x6382e9c6, 0x021ecc5e,
11449 0x09686b3f, 0x3ebaefc9, 0x3c971814, 0x6b6a70a1,
11450 0x687f3584, 0x52a0e286, 0xb79c5305, 0xaa500737,
11451 0x3e07841c, 0x7fdeae5c, 0x8e7d44ec, 0x5716f2b8,
11452 0xb03ada37, 0xf0500c0d, 0xf01c1f04, 0x0200b3ff,
11453 0xae0cf51a, 0x3cb574b2, 0x25837a58, 0xdc0921bd,
11454 0xd19113f9, 0x7ca92ff6, 0x94324773, 0x22f54701,
11455 0x3ae5e581, 0x37c2dadc, 0xc8b57634, 0x9af3dda7,
11456 0xa9446146, 0x0fd0030e, 0xecc8c73e, 0xa4751e41,
11457 0xe238cd99, 0x3bea0e2f, 0x3280bba1, 0x183eb331,
11458 0x4e548b38, 0x4f6db908, 0x6f420d03, 0xf60a04bf,
11459 0x2cb81290, 0x24977c79, 0x5679b072, 0xbcaf89af,
11460 0xde9a771f, 0xd9930810, 0xb38bae12, 0xdccf3f2e,
11461 0x5512721f, 0x2e6b7124, 0x501adde6, 0x9f84cd87,
11462 0x7a584718, 0x7408da17, 0xbc9f9abc, 0xe94b7d8c,
11463 0xec7aec3a, 0xdb851dfa, 0x63094366, 0xc464c3d2,
11464 0xef1c1847, 0x3215d908, 0xdd433b37, 0x24c2ba16,
11465 0x12a14d43, 0x2a65c451, 0x50940002, 0x133ae4dd,
11466 0x71dff89e, 0x10314e55, 0x81ac77d6, 0x5f11199b,
11467 0x043556f1, 0xd7a3c76b, 0x3c11183b, 0x5924a509,
11468 0xf28fe6ed, 0x97f1fbfa, 0x9ebabf2c, 0x1e153c6e,
11469 0x86e34570, 0xeae96fb1, 0x860e5e0a, 0x5a3e2ab3,
11470 0x771fe71c, 0x4e3d06fa, 0x2965dcb9, 0x99e71d0f,
11471 0x803e89d6, 0x5266c825, 0x2e4cc978, 0x9c10b36a,
11472 0xc6150eba, 0x94e2ea78, 0xa5fc3c53, 0x1e0a2df4,
11473 0xf2f74ea7, 0x361d2b3d, 0x1939260f, 0x19c27960,
11474 0x5223a708, 0xf71312b6, 0xebadfe6e, 0xeac31f66,
11475 0xe3bc4595, 0xa67bc883, 0xb17f37d1, 0x018cff28,
11476 0xc332ddef, 0xbe6c5aa5, 0x65582185, 0x68ab9802,
11477 0xeecea50f, 0xdb2f953b, 0x2aef7dad, 0x5b6e2f84,
11478 0x1521b628, 0x29076170, 0xecdd4775, 0x619f1510,
11479 0x13cca830, 0xeb61bd96, 0x0334fe1e, 0xaa0363cf,
11480 0xb5735c90, 0x4c70a239, 0xd59e9e0b, 0xcbaade14,
11481 0xeecc86bc, 0x60622ca7, 0x9cab5cab, 0xb2f3846e,
11482 0x648b1eaf, 0x19bdf0ca, 0xa02369b9, 0x655abb50,
11483 0x40685a32, 0x3c2ab4b3, 0x319ee9d5, 0xc021b8f7,
11484 0x9b540b19, 0x875fa099, 0x95f7997e, 0x623d7da8,
11485 0xf837889a, 0x97e32d77, 0x11ed935f, 0x16681281,
11486 0x0e358829, 0xc7e61fd6, 0x96dedfa1, 0x7858ba99,
11487 0x57f584a5, 0x1b227263, 0x9b83c3ff, 0x1ac24696,
11488 0xcdb30aeb, 0x532e3054, 0x8fd948e4, 0x6dbc3128,
11489 0x58ebf2ef, 0x34c6ffea, 0xfe28ed61, 0xee7c3c73,
11490 0x5d4a14d9, 0xe864b7e3, 0x42105d14, 0x203e13e0,
11491 0x45eee2b6, 0xa3aaabea, 0xdb6c4f15, 0xfacb4fd0,
11492 0xc742f442, 0xef6abbb5, 0x654f3b1d, 0x41cd2105,
11493 0xd81e799e, 0x86854dc7, 0xe44b476a, 0x3d816250,
11494 0xcf62a1f2, 0x5b8d2646, 0xfc8883a0, 0xc1c7b6a3,
11495 0x7f1524c3, 0x69cb7492, 0x47848a0b, 0x5692b285,
11496 0x095bbf00, 0xad19489d, 0x1462b174, 0x23820e00,
11497 0x58428d2a, 0x0c55f5ea, 0x1dadf43e, 0x233f7061,
11498 0x3372f092, 0x8d937e41, 0xd65fecf1, 0x6c223bdb,
11499 0x7cde3759, 0xcbee7460, 0x4085f2a7, 0xce77326e,
11500 0xa6078084, 0x19f8509e, 0xe8efd855, 0x61d99735,
11501 0xa969a7aa, 0xc50c06c2, 0x5a04abfc, 0x800bcadc,
11502 0x9e447a2e, 0xc3453484, 0xfdd56705, 0x0e1e9ec9,
11503 0xdb73dbd3, 0x105588cd, 0x675fda79, 0xe3674340,
11504 0xc5c43465, 0x713e38d8, 0x3d28f89e, 0xf16dff20,
11505 0x153e21e7, 0x8fb03d4a, 0xe6e39f2b, 0xdb83adf7]),
11506 new Uint32Array([
11507 0xe93d5a68, 0x948140f7, 0xf64c261c, 0x94692934,
11508 0x411520f7, 0x7602d4f7, 0xbcf46b2e, 0xd4a20068,
11509 0xd4082471, 0x3320f46a, 0x43b7d4b7, 0x500061af,
11510 0x1e39f62e, 0x97244546, 0x14214f74, 0xbf8b8840,
11511 0x4d95fc1d, 0x96b591af, 0x70f4ddd3, 0x66a02f45,
11512 0xbfbc09ec, 0x03bd9785, 0x7fac6dd0, 0x31cb8504,
11513 0x96eb27b3, 0x55fd3941, 0xda2547e6, 0xabca0a9a,
11514 0x28507825, 0x530429f4, 0x0a2c86da, 0xe9b66dfb,
11515 0x68dc1462, 0xd7486900, 0x680ec0a4, 0x27a18dee,
11516 0x4f3ffea2, 0xe887ad8c, 0xb58ce006, 0x7af4d6b6,
11517 0xaace1e7c, 0xd3375fec, 0xce78a399, 0x406b2a42,
11518 0x20fe9e35, 0xd9f385b9, 0xee39d7ab, 0x3b124e8b,
11519 0x1dc9faf7, 0x4b6d1856, 0x26a36631, 0xeae397b2,
11520 0x3a6efa74, 0xdd5b4332, 0x6841e7f7, 0xca7820fb,
11521 0xfb0af54e, 0xd8feb397, 0x454056ac, 0xba489527,
11522 0x55533a3a, 0x20838d87, 0xfe6ba9b7, 0xd096954b,
11523 0x55a867bc, 0xa1159a58, 0xcca92963, 0x99e1db33,
11524 0xa62a4a56, 0x3f3125f9, 0x5ef47e1c, 0x9029317c,
11525 0xfdf8e802, 0x04272f70, 0x80bb155c, 0x05282ce3,
11526 0x95c11548, 0xe4c66d22, 0x48c1133f, 0xc70f86dc,
11527 0x07f9c9ee, 0x41041f0f, 0x404779a4, 0x5d886e17,
11528 0x325f51eb, 0xd59bc0d1, 0xf2bcc18f, 0x41113564,
11529 0x257b7834, 0x602a9c60, 0xdff8e8a3, 0x1f636c1b,
11530 0x0e12b4c2, 0x02e1329e, 0xaf664fd1, 0xcad18115,
11531 0x6b2395e0, 0x333e92e1, 0x3b240b62, 0xeebeb922,
11532 0x85b2a20e, 0xe6ba0d99, 0xde720c8c, 0x2da2f728,
11533 0xd0127845, 0x95b794fd, 0x647d0862, 0xe7ccf5f0,
11534 0x5449a36f, 0x877d48fa, 0xc39dfd27, 0xf33e8d1e,
11535 0x0a476341, 0x992eff74, 0x3a6f6eab, 0xf4f8fd37,
11536 0xa812dc60, 0xa1ebddf8, 0x991be14c, 0xdb6e6b0d,
11537 0xc67b5510, 0x6d672c37, 0x2765d43b, 0xdcd0e804,
11538 0xf1290dc7, 0xcc00ffa3, 0xb5390f92, 0x690fed0b,
11539 0x667b9ffb, 0xcedb7d9c, 0xa091cf0b, 0xd9155ea3,
11540 0xbb132f88, 0x515bad24, 0x7b9479bf, 0x763bd6eb,
11541 0x37392eb3, 0xcc115979, 0x8026e297, 0xf42e312d,
11542 0x6842ada7, 0xc66a2b3b, 0x12754ccc, 0x782ef11c,
11543 0x6a124237, 0xb79251e7, 0x06a1bbe6, 0x4bfb6350,
11544 0x1a6b1018, 0x11caedfa, 0x3d25bdd8, 0xe2e1c3c9,
11545 0x44421659, 0x0a121386, 0xd90cec6e, 0xd5abea2a,
11546 0x64af674e, 0xda86a85f, 0xbebfe988, 0x64e4c3fe,
11547 0x9dbc8057, 0xf0f7c086, 0x60787bf8, 0x6003604d,
11548 0xd1fd8346, 0xf6381fb0, 0x7745ae04, 0xd736fccc,
11549 0x83426b33, 0xf01eab71, 0xb0804187, 0x3c005e5f,
11550 0x77a057be, 0xbde8ae24, 0x55464299, 0xbf582e61,
11551 0x4e58f48f, 0xf2ddfda2, 0xf474ef38, 0x8789bdc2,
11552 0x5366f9c3, 0xc8b38e74, 0xb475f255, 0x46fcd9b9,
11553 0x7aeb2661, 0x8b1ddf84, 0x846a0e79, 0x915f95e2,
11554 0x466e598e, 0x20b45770, 0x8cd55591, 0xc902de4c,
11555 0xb90bace1, 0xbb8205d0, 0x11a86248, 0x7574a99e,
11556 0xb77f19b6, 0xe0a9dc09, 0x662d09a1, 0xc4324633,
11557 0xe85a1f02, 0x09f0be8c, 0x4a99a025, 0x1d6efe10,
11558 0x1ab93d1d, 0x0ba5a4df, 0xa186f20f, 0x2868f169,
11559 0xdcb7da83, 0x573906fe, 0xa1e2ce9b, 0x4fcd7f52,
11560 0x50115e01, 0xa70683fa, 0xa002b5c4, 0x0de6d027,
11561 0x9af88c27, 0x773f8641, 0xc3604c06, 0x61a806b5,
11562 0xf0177a28, 0xc0f586e0, 0x006058aa, 0x30dc7d62,
11563 0x11e69ed7, 0x2338ea63, 0x53c2dd94, 0xc2c21634,
11564 0xbbcbee56, 0x90bcb6de, 0xebfc7da1, 0xce591d76,
11565 0x6f05e409, 0x4b7c0188, 0x39720a3d, 0x7c927c24,
11566 0x86e3725f, 0x724d9db9, 0x1ac15bb4, 0xd39eb8fc,
11567 0xed545578, 0x08fca5b5, 0xd83d7cd3, 0x4dad0fc4,
11568 0x1e50ef5e, 0xb161e6f8, 0xa28514d9, 0x6c51133c,
11569 0x6fd5c7e7, 0x56e14ec4, 0x362abfce, 0xddc6c837,
11570 0xd79a3234, 0x92638212, 0x670efa8e, 0x406000e0]),
11571 new Uint32Array([
11572 0x3a39ce37, 0xd3faf5cf, 0xabc27737, 0x5ac52d1b,
11573 0x5cb0679e, 0x4fa33742, 0xd3822740, 0x99bc9bbe,
11574 0xd5118e9d, 0xbf0f7315, 0xd62d1c7e, 0xc700c47b,
11575 0xb78c1b6b, 0x21a19045, 0xb26eb1be, 0x6a366eb4,
11576 0x5748ab2f, 0xbc946e79, 0xc6a376d2, 0x6549c2c8,
11577 0x530ff8ee, 0x468dde7d, 0xd5730a1d, 0x4cd04dc6,
11578 0x2939bbdb, 0xa9ba4650, 0xac9526e8, 0xbe5ee304,
11579 0xa1fad5f0, 0x6a2d519a, 0x63ef8ce2, 0x9a86ee22,
11580 0xc089c2b8, 0x43242ef6, 0xa51e03aa, 0x9cf2d0a4,
11581 0x83c061ba, 0x9be96a4d, 0x8fe51550, 0xba645bd6,
11582 0x2826a2f9, 0xa73a3ae1, 0x4ba99586, 0xef5562e9,
11583 0xc72fefd3, 0xf752f7da, 0x3f046f69, 0x77fa0a59,
11584 0x80e4a915, 0x87b08601, 0x9b09e6ad, 0x3b3ee593,
11585 0xe990fd5a, 0x9e34d797, 0x2cf0b7d9, 0x022b8b51,
11586 0x96d5ac3a, 0x017da67d, 0xd1cf3ed6, 0x7c7d2d28,
11587 0x1f9f25cf, 0xadf2b89b, 0x5ad6b472, 0x5a88f54c,
11588 0xe029ac71, 0xe019a5e6, 0x47b0acfd, 0xed93fa9b,
11589 0xe8d3c48d, 0x283b57cc, 0xf8d56629, 0x79132e28,
11590 0x785f0191, 0xed756055, 0xf7960e44, 0xe3d35e8c,
11591 0x15056dd4, 0x88f46dba, 0x03a16125, 0x0564f0bd,
11592 0xc3eb9e15, 0x3c9057a2, 0x97271aec, 0xa93a072a,
11593 0x1b3f6d9b, 0x1e6321f5, 0xf59c66fb, 0x26dcf319,
11594 0x7533d928, 0xb155fdf5, 0x03563482, 0x8aba3cbb,
11595 0x28517711, 0xc20ad9f8, 0xabcc5167, 0xccad925f,
11596 0x4de81751, 0x3830dc8e, 0x379d5862, 0x9320f991,
11597 0xea7a90c2, 0xfb3e7bce, 0x5121ce64, 0x774fbe32,
11598 0xa8b6e37e, 0xc3293d46, 0x48de5369, 0x6413e680,
11599 0xa2ae0810, 0xdd6db224, 0x69852dfd, 0x09072166,
11600 0xb39a460a, 0x6445c0dd, 0x586cdecf, 0x1c20c8ae,
11601 0x5bbef7dd, 0x1b588d40, 0xccd2017f, 0x6bb4e3bb,
11602 0xdda26a7e, 0x3a59ff45, 0x3e350a44, 0xbcb4cdd5,
11603 0x72eacea8, 0xfa6484bb, 0x8d6612ae, 0xbf3c6f47,
11604 0xd29be463, 0x542f5d9e, 0xaec2771b, 0xf64e6370,
11605 0x740e0d8d, 0xe75b1357, 0xf8721671, 0xaf537d5d,
11606 0x4040cb08, 0x4eb4e2cc, 0x34d2466a, 0x0115af84,
11607 0xe1b00428, 0x95983a1d, 0x06b89fb4, 0xce6ea048,
11608 0x6f3f3b82, 0x3520ab82, 0x011a1d4b, 0x277227f8,
11609 0x611560b1, 0xe7933fdc, 0xbb3a792b, 0x344525bd,
11610 0xa08839e1, 0x51ce794b, 0x2f32c9b7, 0xa01fbac9,
11611 0xe01cc87e, 0xbcc7d1f6, 0xcf0111c3, 0xa1e8aac7,
11612 0x1a908749, 0xd44fbd9a, 0xd0dadecb, 0xd50ada38,
11613 0x0339c32a, 0xc6913667, 0x8df9317c, 0xe0b12b4f,
11614 0xf79e59b7, 0x43f5bb3a, 0xf2d519ff, 0x27d9459c,
11615 0xbf97222c, 0x15e6fc2a, 0x0f91fc71, 0x9b941525,
11616 0xfae59361, 0xceb69ceb, 0xc2a86459, 0x12baa8d1,
11617 0xb6c1075e, 0xe3056a0c, 0x10d25065, 0xcb03a442,
11618 0xe0ec6e0e, 0x1698db3b, 0x4c98a0be, 0x3278e964,
11619 0x9f1f9532, 0xe0d392df, 0xd3a0342b, 0x8971f21e,
11620 0x1b0a7441, 0x4ba3348c, 0xc5be7120, 0xc37632d8,
11621 0xdf359f8d, 0x9b992f2e, 0xe60b6f47, 0x0fe3f11d,
11622 0xe54cda54, 0x1edad891, 0xce6279cf, 0xcd3e7e6f,
11623 0x1618b166, 0xfd2c1d05, 0x848fd2c5, 0xf6fb2299,
11624 0xf523f357, 0xa6327623, 0x93a83531, 0x56cccd02,
11625 0xacf08162, 0x5a75ebb5, 0x6e163697, 0x88d273cc,
11626 0xde966292, 0x81b949d0, 0x4c50901b, 0x71c65614,
11627 0xe6c6c7bd, 0x327a140a, 0x45e1d006, 0xc3f27b9a,
11628 0xc9aa53fd, 0x62a80f00, 0xbb25bfe2, 0x35bdd2f6,
11629 0x71126905, 0xb2040222, 0xb6cbcf7c, 0xcd769c2b,
11630 0x53113ec0, 0x1640e3d3, 0x38abbd60, 0x2547adf0,
11631 0xba38209c, 0xf746ce76, 0x77afa1c5, 0x20756060,
11632 0x85cbfe4e, 0x8ae88dd8, 0x7aaaf9b0, 0x4cf9aa7e,
11633 0x1948c25c, 0x02fb8a8c, 0x01c36ae4, 0xd6ebe1f9,
11634 0x90d4f869, 0xa65cdea0, 0x3f09252d, 0xc208e69f,
11635 0xb74e6132, 0xce77e25b, 0x578fdfe3, 0x3ac372e6])
11636 ];
11637 this.P = new Uint32Array([
11638 0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344,
11639 0xa4093822, 0x299f31d0, 0x082efa98, 0xec4e6c89,
11640 0x452821e6, 0x38d01377, 0xbe5466cf, 0x34e90c6c,
11641 0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5, 0xb5470917,
11642 0x9216d5d9, 0x8979fb1b]);
11643};
11644
11645function F(S, x8, i) {
11646 return (((S[0][x8[i+3]] +
11647 S[1][x8[i+2]]) ^
11648 S[2][x8[i+1]]) +
11649 S[3][x8[i]]);
11650};
11651
11652Blowfish.prototype.encipher = function(x, x8) {
11653 if (x8 === undefined) {
11654 x8 = new Uint8Array(x.buffer);
11655 if (x.byteOffset !== 0)
11656 x8 = x8.subarray(x.byteOffset);
11657 }
11658 x[0] ^= this.P[0];
11659 for (var i = 1; i < 16; i += 2) {
11660 x[1] ^= F(this.S, x8, 0) ^ this.P[i];
11661 x[0] ^= F(this.S, x8, 4) ^ this.P[i+1];
11662 }
11663 var t = x[0];
11664 x[0] = x[1] ^ this.P[17];
11665 x[1] = t;
11666};
11667
11668Blowfish.prototype.decipher = function(x) {
11669 var x8 = new Uint8Array(x.buffer);
11670 if (x.byteOffset !== 0)
11671 x8 = x8.subarray(x.byteOffset);
11672 x[0] ^= this.P[17];
11673 for (var i = 16; i > 0; i -= 2) {
11674 x[1] ^= F(this.S, x8, 0) ^ this.P[i];
11675 x[0] ^= F(this.S, x8, 4) ^ this.P[i-1];
11676 }
11677 var t = x[0];
11678 x[0] = x[1] ^ this.P[0];
11679 x[1] = t;
11680};
11681
11682function stream2word(data, databytes){
11683 var i, temp = 0;
11684 for (i = 0; i < 4; i++, BLF_J++) {
11685 if (BLF_J >= databytes) BLF_J = 0;
11686 temp = (temp << 8) | data[BLF_J];
11687 }
11688 return temp;
11689};
11690
11691Blowfish.prototype.expand0state = function(key, keybytes) {
11692 var d = new Uint32Array(2), i, k;
11693 var d8 = new Uint8Array(d.buffer);
11694
11695 for (i = 0, BLF_J = 0; i < 18; i++) {
11696 this.P[i] ^= stream2word(key, keybytes);
11697 }
11698 BLF_J = 0;
11699
11700 for (i = 0; i < 18; i += 2) {
11701 this.encipher(d, d8);
11702 this.P[i] = d[0];
11703 this.P[i+1] = d[1];
11704 }
11705
11706 for (i = 0; i < 4; i++) {
11707 for (k = 0; k < 256; k += 2) {
11708 this.encipher(d, d8);
11709 this.S[i][k] = d[0];
11710 this.S[i][k+1] = d[1];
11711 }
11712 }
11713};
11714
11715Blowfish.prototype.expandstate = function(data, databytes, key, keybytes) {
11716 var d = new Uint32Array(2), i, k;
11717
11718 for (i = 0, BLF_J = 0; i < 18; i++) {
11719 this.P[i] ^= stream2word(key, keybytes);
11720 }
11721
11722 for (i = 0, BLF_J = 0; i < 18; i += 2) {
11723 d[0] ^= stream2word(data, databytes);
11724 d[1] ^= stream2word(data, databytes);
11725 this.encipher(d);
11726 this.P[i] = d[0];
11727 this.P[i+1] = d[1];
11728 }
11729
11730 for (i = 0; i < 4; i++) {
11731 for (k = 0; k < 256; k += 2) {
11732 d[0] ^= stream2word(data, databytes);
11733 d[1] ^= stream2word(data, databytes);
11734 this.encipher(d);
11735 this.S[i][k] = d[0];
11736 this.S[i][k+1] = d[1];
11737 }
11738 }
11739 BLF_J = 0;
11740};
11741
11742Blowfish.prototype.enc = function(data, blocks) {
11743 for (var i = 0; i < blocks; i++) {
11744 this.encipher(data.subarray(i*2));
11745 }
11746};
11747
11748Blowfish.prototype.dec = function(data, blocks) {
11749 for (var i = 0; i < blocks; i++) {
11750 this.decipher(data.subarray(i*2));
11751 }
11752};
11753
11754var BCRYPT_BLOCKS = 8,
11755 BCRYPT_HASHSIZE = 32;
11756
11757function bcrypt_hash(sha2pass, sha2salt, out) {
11758 var state = new Blowfish(),
11759 cdata = new Uint32Array(BCRYPT_BLOCKS), i,
11760 ciphertext = new Uint8Array([79,120,121,99,104,114,111,109,97,116,105,
11761 99,66,108,111,119,102,105,115,104,83,119,97,116,68,121,110,97,109,
11762 105,116,101]); //"OxychromaticBlowfishSwatDynamite"
11763
11764 state.expandstate(sha2salt, 64, sha2pass, 64);
11765 for (i = 0; i < 64; i++) {
11766 state.expand0state(sha2salt, 64);
11767 state.expand0state(sha2pass, 64);
11768 }
11769
11770 for (i = 0; i < BCRYPT_BLOCKS; i++)
11771 cdata[i] = stream2word(ciphertext, ciphertext.byteLength);
11772 for (i = 0; i < 64; i++)
11773 state.enc(cdata, cdata.byteLength / 8);
11774
11775 for (i = 0; i < BCRYPT_BLOCKS; i++) {
11776 out[4*i+3] = cdata[i] >>> 24;
11777 out[4*i+2] = cdata[i] >>> 16;
11778 out[4*i+1] = cdata[i] >>> 8;
11779 out[4*i+0] = cdata[i];
11780 }
11781};
11782
11783function bcrypt_pbkdf(pass, passlen, salt, saltlen, key, keylen, rounds) {
11784 var sha2pass = new Uint8Array(64),
11785 sha2salt = new Uint8Array(64),
11786 out = new Uint8Array(BCRYPT_HASHSIZE),
11787 tmpout = new Uint8Array(BCRYPT_HASHSIZE),
11788 countsalt = new Uint8Array(saltlen+4),
11789 i, j, amt, stride, dest, count,
11790 origkeylen = keylen;
11791
11792 if (rounds < 1)
11793 return -1;
11794 if (passlen === 0 || saltlen === 0 || keylen === 0 ||
11795 keylen > (out.byteLength * out.byteLength) || saltlen > (1<<20))
11796 return -1;
11797
11798 stride = Math.floor((keylen + out.byteLength - 1) / out.byteLength);
11799 amt = Math.floor((keylen + stride - 1) / stride);
11800
11801 for (i = 0; i < saltlen; i++)
11802 countsalt[i] = salt[i];
11803
11804 crypto_hash_sha512(sha2pass, pass, passlen);
11805
11806 for (count = 1; keylen > 0; count++) {
11807 countsalt[saltlen+0] = count >>> 24;
11808 countsalt[saltlen+1] = count >>> 16;
11809 countsalt[saltlen+2] = count >>> 8;
11810 countsalt[saltlen+3] = count;
11811
11812 crypto_hash_sha512(sha2salt, countsalt, saltlen + 4);
11813 bcrypt_hash(sha2pass, sha2salt, tmpout);
11814 for (i = out.byteLength; i--;)
11815 out[i] = tmpout[i];
11816
11817 for (i = 1; i < rounds; i++) {
11818 crypto_hash_sha512(sha2salt, tmpout, tmpout.byteLength);
11819 bcrypt_hash(sha2pass, sha2salt, tmpout);
11820 for (j = 0; j < out.byteLength; j++)
11821 out[j] ^= tmpout[j];
11822 }
11823
11824 amt = Math.min(amt, keylen);
11825 for (i = 0; i < amt; i++) {
11826 dest = i * stride + (count - 1);
11827 if (dest >= origkeylen)
11828 break;
11829 key[dest] = out[i];
11830 }
11831 keylen -= i;
11832 }
11833
11834 return 0;
11835};
11836
11837module.exports = {
11838 BLOCKS: BCRYPT_BLOCKS,
11839 HASHSIZE: BCRYPT_HASHSIZE,
11840 hash: bcrypt_hash,
11841 pbkdf: bcrypt_pbkdf
11842};
11843
11844},{"tweetnacl":391}],77:[function(require,module,exports){
11845
11846module.exports = require('./lib/bluebird-retry');
11847
11848},{"./lib/bluebird-retry":78}],78:[function(require,module,exports){
11849var Promise = require('bluebird');
11850
11851// Subclass of Error that can be thrown to indicate that retry should stop.
11852//
11853// If called with an instance of Error subclass, then the retry promise will be
11854// rejected with the given error.
11855//
11856// Otherwise the cancel error object itself is propagated to the caller.
11857//
11858function StopError(err) {
11859 this.name = 'StopError';
11860 if (err instanceof Error) {
11861 this.err = err
11862 } else {
11863 this.message = err || 'cancelled'
11864 }
11865}
11866StopError.prototype = Object.create(Error.prototype);
11867
11868retry.StopError = StopError;
11869
11870
11871// Retry `func` until it succeeds.
11872//
11873// For each attempt, invokes `func` with `options.args` as arguments and
11874// `options.context` as `this`.
11875//
11876// Waits `options.interval` milliseconds (default 1000) between attempts.
11877//
11878// Increases wait by a factor of `options.backoff` each interval, up to
11879// a limit of `options.max_interval`.
11880//
11881// Keeps trying until `options.timeout` milliseconds have elapsed,
11882// or `options.max_tries` have been attempted, whichever comes first.
11883//
11884// If neither is specified, then the default is to make 5 attempts.
11885//
11886
11887function retry(func, options) {
11888 options = options || {};
11889
11890 var interval = typeof options.interval === 'number' ? options.interval : 1000;
11891
11892 var max_tries, giveup_time;
11893 if (typeof(options.max_tries) !== 'undefined') {
11894 max_tries = options.max_tries;
11895 }
11896
11897 if (options.timeout) {
11898 giveup_time = new Date().getTime() + options.timeout;
11899 }
11900
11901 if (!max_tries && !giveup_time) {
11902 max_tries = 5;
11903 }
11904
11905 var tries = 0;
11906 var start = new Date().getTime();
11907
11908 // If the user didn't supply a predicate function then add one that
11909 // always succeeds.
11910 //
11911 // This is used in bluebird's filtered catch to flag the error types
11912 // that should retry.
11913 var predicate = options.predicate || function(err) { return true; }
11914 var stopped = false;
11915
11916 function try_once() {
11917 var tryStart = new Date().getTime();
11918 return Promise.attempt(function() {
11919 return func.apply(options.context, options.args);
11920 })
11921 .caught(StopError, function(err) {
11922 stopped = true;
11923 if (err.err instanceof Error) {
11924 return Promise.reject(err.err);
11925 } else {
11926 return Promise.reject(err);
11927 }
11928 })
11929 .caught(predicate, function(err) {
11930 if (stopped) {
11931 return Promise.reject(err);
11932 }
11933 ++tries;
11934 if (tries > 1) {
11935 interval = backoff(interval, options);
11936 }
11937 var now = new Date().getTime();
11938
11939 if ((max_tries && (tries === max_tries) ||
11940 (giveup_time && (now + interval >= giveup_time)))) {
11941
11942 if (! (err instanceof Error)) {
11943 var failure = err;
11944
11945 if (failure) {
11946 if (typeof failure !== 'string') {
11947 failure = JSON.stringify(failure);
11948 }
11949 }
11950
11951 err = new Error('rejected with non-error: ' + failure);
11952 err.failure = failure;
11953 } else if (options.throw_original) {
11954 return Promise.reject(err);
11955 }
11956
11957 var timeout = new Error('operation timed out after ' + (now - start) + ' ms, ' + tries + ' tries with error: ' + err.message);
11958 timeout.failure = err;
11959 timeout.code = 'ETIMEDOUT';
11960 return Promise.reject(timeout);
11961 } else {
11962 var delay = interval - (now - tryStart);
11963 if (delay <= 0) {
11964 return try_once();
11965 } else {
11966 return Promise.delay(delay).then(try_once);
11967 }
11968 }
11969 });
11970 }
11971 return try_once();
11972}
11973
11974// Return the updated interval after applying the various backoff options
11975function backoff(interval, options) {
11976 if (options.backoff) {
11977 interval = interval * options.backoff;
11978 }
11979
11980 if (options.max_interval) {
11981 interval = Math.min(interval, options.max_interval);
11982 }
11983
11984 return interval;
11985}
11986
11987module.exports = retry;
11988
11989},{"bluebird":79}],79:[function(require,module,exports){
11990(function (process,global,setImmediate){
11991/* @preserve
11992 * The MIT License (MIT)
11993 *
11994 * Copyright (c) 2013-2018 Petka Antonov
11995 *
11996 * Permission is hereby granted, free of charge, to any person obtaining a copy
11997 * of this software and associated documentation files (the "Software"), to deal
11998 * in the Software without restriction, including without limitation the rights
11999 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
12000 * copies of the Software, and to permit persons to whom the Software is
12001 * furnished to do so, subject to the following conditions:
12002 *
12003 * The above copyright notice and this permission notice shall be included in
12004 * all copies or substantial portions of the Software.
12005 *
12006 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
12007 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
12008 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
12009 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
12010 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
12011 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
12012 * THE SOFTWARE.
12013 *
12014 */
12015/**
12016 * bluebird build version 3.5.5
12017 * Features enabled: core, race, call_get, generators, map, nodeify, promisify, props, reduce, settle, some, using, timers, filter, any, each
12018*/
12019!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){
12020"use strict";
12021module.exports = function(Promise) {
12022var SomePromiseArray = Promise._SomePromiseArray;
12023function any(promises) {
12024 var ret = new SomePromiseArray(promises);
12025 var promise = ret.promise();
12026 ret.setHowMany(1);
12027 ret.setUnwrap();
12028 ret.init();
12029 return promise;
12030}
12031
12032Promise.any = function (promises) {
12033 return any(promises);
12034};
12035
12036Promise.prototype.any = function () {
12037 return any(this);
12038};
12039
12040};
12041
12042},{}],2:[function(_dereq_,module,exports){
12043"use strict";
12044var firstLineError;
12045try {throw new Error(); } catch (e) {firstLineError = e;}
12046var schedule = _dereq_("./schedule");
12047var Queue = _dereq_("./queue");
12048var util = _dereq_("./util");
12049
12050function Async() {
12051 this._customScheduler = false;
12052 this._isTickUsed = false;
12053 this._lateQueue = new Queue(16);
12054 this._normalQueue = new Queue(16);
12055 this._haveDrainedQueues = false;
12056 this._trampolineEnabled = true;
12057 var self = this;
12058 this.drainQueues = function () {
12059 self._drainQueues();
12060 };
12061 this._schedule = schedule;
12062}
12063
12064Async.prototype.setScheduler = function(fn) {
12065 var prev = this._schedule;
12066 this._schedule = fn;
12067 this._customScheduler = true;
12068 return prev;
12069};
12070
12071Async.prototype.hasCustomScheduler = function() {
12072 return this._customScheduler;
12073};
12074
12075Async.prototype.enableTrampoline = function() {
12076 this._trampolineEnabled = true;
12077};
12078
12079Async.prototype.disableTrampolineIfNecessary = function() {
12080 if (util.hasDevTools) {
12081 this._trampolineEnabled = false;
12082 }
12083};
12084
12085Async.prototype.haveItemsQueued = function () {
12086 return this._isTickUsed || this._haveDrainedQueues;
12087};
12088
12089
12090Async.prototype.fatalError = function(e, isNode) {
12091 if (isNode) {
12092 process.stderr.write("Fatal " + (e instanceof Error ? e.stack : e) +
12093 "\n");
12094 process.exit(2);
12095 } else {
12096 this.throwLater(e);
12097 }
12098};
12099
12100Async.prototype.throwLater = function(fn, arg) {
12101 if (arguments.length === 1) {
12102 arg = fn;
12103 fn = function () { throw arg; };
12104 }
12105 if (typeof setTimeout !== "undefined") {
12106 setTimeout(function() {
12107 fn(arg);
12108 }, 0);
12109 } else try {
12110 this._schedule(function() {
12111 fn(arg);
12112 });
12113 } catch (e) {
12114 throw new Error("No async scheduler available\u000a\u000a See http://goo.gl/MqrFmX\u000a");
12115 }
12116};
12117
12118function AsyncInvokeLater(fn, receiver, arg) {
12119 this._lateQueue.push(fn, receiver, arg);
12120 this._queueTick();
12121}
12122
12123function AsyncInvoke(fn, receiver, arg) {
12124 this._normalQueue.push(fn, receiver, arg);
12125 this._queueTick();
12126}
12127
12128function AsyncSettlePromises(promise) {
12129 this._normalQueue._pushOne(promise);
12130 this._queueTick();
12131}
12132
12133if (!util.hasDevTools) {
12134 Async.prototype.invokeLater = AsyncInvokeLater;
12135 Async.prototype.invoke = AsyncInvoke;
12136 Async.prototype.settlePromises = AsyncSettlePromises;
12137} else {
12138 Async.prototype.invokeLater = function (fn, receiver, arg) {
12139 if (this._trampolineEnabled) {
12140 AsyncInvokeLater.call(this, fn, receiver, arg);
12141 } else {
12142 this._schedule(function() {
12143 setTimeout(function() {
12144 fn.call(receiver, arg);
12145 }, 100);
12146 });
12147 }
12148 };
12149
12150 Async.prototype.invoke = function (fn, receiver, arg) {
12151 if (this._trampolineEnabled) {
12152 AsyncInvoke.call(this, fn, receiver, arg);
12153 } else {
12154 this._schedule(function() {
12155 fn.call(receiver, arg);
12156 });
12157 }
12158 };
12159
12160 Async.prototype.settlePromises = function(promise) {
12161 if (this._trampolineEnabled) {
12162 AsyncSettlePromises.call(this, promise);
12163 } else {
12164 this._schedule(function() {
12165 promise._settlePromises();
12166 });
12167 }
12168 };
12169}
12170
12171function _drainQueue(queue) {
12172 while (queue.length() > 0) {
12173 _drainQueueStep(queue);
12174 }
12175}
12176
12177function _drainQueueStep(queue) {
12178 var fn = queue.shift();
12179 if (typeof fn !== "function") {
12180 fn._settlePromises();
12181 } else {
12182 var receiver = queue.shift();
12183 var arg = queue.shift();
12184 fn.call(receiver, arg);
12185 }
12186}
12187
12188Async.prototype._drainQueues = function () {
12189 _drainQueue(this._normalQueue);
12190 this._reset();
12191 this._haveDrainedQueues = true;
12192 _drainQueue(this._lateQueue);
12193};
12194
12195Async.prototype._queueTick = function () {
12196 if (!this._isTickUsed) {
12197 this._isTickUsed = true;
12198 this._schedule(this.drainQueues);
12199 }
12200};
12201
12202Async.prototype._reset = function () {
12203 this._isTickUsed = false;
12204};
12205
12206module.exports = Async;
12207module.exports.firstLineError = firstLineError;
12208
12209},{"./queue":26,"./schedule":29,"./util":36}],3:[function(_dereq_,module,exports){
12210"use strict";
12211module.exports = function(Promise, INTERNAL, tryConvertToPromise, debug) {
12212var calledBind = false;
12213var rejectThis = function(_, e) {
12214 this._reject(e);
12215};
12216
12217var targetRejected = function(e, context) {
12218 context.promiseRejectionQueued = true;
12219 context.bindingPromise._then(rejectThis, rejectThis, null, this, e);
12220};
12221
12222var bindingResolved = function(thisArg, context) {
12223 if (((this._bitField & 50397184) === 0)) {
12224 this._resolveCallback(context.target);
12225 }
12226};
12227
12228var bindingRejected = function(e, context) {
12229 if (!context.promiseRejectionQueued) this._reject(e);
12230};
12231
12232Promise.prototype.bind = function (thisArg) {
12233 if (!calledBind) {
12234 calledBind = true;
12235 Promise.prototype._propagateFrom = debug.propagateFromFunction();
12236 Promise.prototype._boundValue = debug.boundValueFunction();
12237 }
12238 var maybePromise = tryConvertToPromise(thisArg);
12239 var ret = new Promise(INTERNAL);
12240 ret._propagateFrom(this, 1);
12241 var target = this._target();
12242 ret._setBoundTo(maybePromise);
12243 if (maybePromise instanceof Promise) {
12244 var context = {
12245 promiseRejectionQueued: false,
12246 promise: ret,
12247 target: target,
12248 bindingPromise: maybePromise
12249 };
12250 target._then(INTERNAL, targetRejected, undefined, ret, context);
12251 maybePromise._then(
12252 bindingResolved, bindingRejected, undefined, ret, context);
12253 ret._setOnCancel(maybePromise);
12254 } else {
12255 ret._resolveCallback(target);
12256 }
12257 return ret;
12258};
12259
12260Promise.prototype._setBoundTo = function (obj) {
12261 if (obj !== undefined) {
12262 this._bitField = this._bitField | 2097152;
12263 this._boundTo = obj;
12264 } else {
12265 this._bitField = this._bitField & (~2097152);
12266 }
12267};
12268
12269Promise.prototype._isBound = function () {
12270 return (this._bitField & 2097152) === 2097152;
12271};
12272
12273Promise.bind = function (thisArg, value) {
12274 return Promise.resolve(value).bind(thisArg);
12275};
12276};
12277
12278},{}],4:[function(_dereq_,module,exports){
12279"use strict";
12280var old;
12281if (typeof Promise !== "undefined") old = Promise;
12282function noConflict() {
12283 try { if (Promise === bluebird) Promise = old; }
12284 catch (e) {}
12285 return bluebird;
12286}
12287var bluebird = _dereq_("./promise")();
12288bluebird.noConflict = noConflict;
12289module.exports = bluebird;
12290
12291},{"./promise":22}],5:[function(_dereq_,module,exports){
12292"use strict";
12293var cr = Object.create;
12294if (cr) {
12295 var callerCache = cr(null);
12296 var getterCache = cr(null);
12297 callerCache[" size"] = getterCache[" size"] = 0;
12298}
12299
12300module.exports = function(Promise) {
12301var util = _dereq_("./util");
12302var canEvaluate = util.canEvaluate;
12303var isIdentifier = util.isIdentifier;
12304
12305var getMethodCaller;
12306var getGetter;
12307if (!true) {
12308var makeMethodCaller = function (methodName) {
12309 return new Function("ensureMethod", " \n\
12310 return function(obj) { \n\
12311 'use strict' \n\
12312 var len = this.length; \n\
12313 ensureMethod(obj, 'methodName'); \n\
12314 switch(len) { \n\
12315 case 1: return obj.methodName(this[0]); \n\
12316 case 2: return obj.methodName(this[0], this[1]); \n\
12317 case 3: return obj.methodName(this[0], this[1], this[2]); \n\
12318 case 0: return obj.methodName(); \n\
12319 default: \n\
12320 return obj.methodName.apply(obj, this); \n\
12321 } \n\
12322 }; \n\
12323 ".replace(/methodName/g, methodName))(ensureMethod);
12324};
12325
12326var makeGetter = function (propertyName) {
12327 return new Function("obj", " \n\
12328 'use strict'; \n\
12329 return obj.propertyName; \n\
12330 ".replace("propertyName", propertyName));
12331};
12332
12333var getCompiled = function(name, compiler, cache) {
12334 var ret = cache[name];
12335 if (typeof ret !== "function") {
12336 if (!isIdentifier(name)) {
12337 return null;
12338 }
12339 ret = compiler(name);
12340 cache[name] = ret;
12341 cache[" size"]++;
12342 if (cache[" size"] > 512) {
12343 var keys = Object.keys(cache);
12344 for (var i = 0; i < 256; ++i) delete cache[keys[i]];
12345 cache[" size"] = keys.length - 256;
12346 }
12347 }
12348 return ret;
12349};
12350
12351getMethodCaller = function(name) {
12352 return getCompiled(name, makeMethodCaller, callerCache);
12353};
12354
12355getGetter = function(name) {
12356 return getCompiled(name, makeGetter, getterCache);
12357};
12358}
12359
12360function ensureMethod(obj, methodName) {
12361 var fn;
12362 if (obj != null) fn = obj[methodName];
12363 if (typeof fn !== "function") {
12364 var message = "Object " + util.classString(obj) + " has no method '" +
12365 util.toString(methodName) + "'";
12366 throw new Promise.TypeError(message);
12367 }
12368 return fn;
12369}
12370
12371function caller(obj) {
12372 var methodName = this.pop();
12373 var fn = ensureMethod(obj, methodName);
12374 return fn.apply(obj, this);
12375}
12376Promise.prototype.call = function (methodName) {
12377 var args = [].slice.call(arguments, 1);;
12378 if (!true) {
12379 if (canEvaluate) {
12380 var maybeCaller = getMethodCaller(methodName);
12381 if (maybeCaller !== null) {
12382 return this._then(
12383 maybeCaller, undefined, undefined, args, undefined);
12384 }
12385 }
12386 }
12387 args.push(methodName);
12388 return this._then(caller, undefined, undefined, args, undefined);
12389};
12390
12391function namedGetter(obj) {
12392 return obj[this];
12393}
12394function indexedGetter(obj) {
12395 var index = +this;
12396 if (index < 0) index = Math.max(0, index + obj.length);
12397 return obj[index];
12398}
12399Promise.prototype.get = function (propertyName) {
12400 var isIndex = (typeof propertyName === "number");
12401 var getter;
12402 if (!isIndex) {
12403 if (canEvaluate) {
12404 var maybeGetter = getGetter(propertyName);
12405 getter = maybeGetter !== null ? maybeGetter : namedGetter;
12406 } else {
12407 getter = namedGetter;
12408 }
12409 } else {
12410 getter = indexedGetter;
12411 }
12412 return this._then(getter, undefined, undefined, propertyName, undefined);
12413};
12414};
12415
12416},{"./util":36}],6:[function(_dereq_,module,exports){
12417"use strict";
12418module.exports = function(Promise, PromiseArray, apiRejection, debug) {
12419var util = _dereq_("./util");
12420var tryCatch = util.tryCatch;
12421var errorObj = util.errorObj;
12422var async = Promise._async;
12423
12424Promise.prototype["break"] = Promise.prototype.cancel = function() {
12425 if (!debug.cancellation()) return this._warn("cancellation is disabled");
12426
12427 var promise = this;
12428 var child = promise;
12429 while (promise._isCancellable()) {
12430 if (!promise._cancelBy(child)) {
12431 if (child._isFollowing()) {
12432 child._followee().cancel();
12433 } else {
12434 child._cancelBranched();
12435 }
12436 break;
12437 }
12438
12439 var parent = promise._cancellationParent;
12440 if (parent == null || !parent._isCancellable()) {
12441 if (promise._isFollowing()) {
12442 promise._followee().cancel();
12443 } else {
12444 promise._cancelBranched();
12445 }
12446 break;
12447 } else {
12448 if (promise._isFollowing()) promise._followee().cancel();
12449 promise._setWillBeCancelled();
12450 child = promise;
12451 promise = parent;
12452 }
12453 }
12454};
12455
12456Promise.prototype._branchHasCancelled = function() {
12457 this._branchesRemainingToCancel--;
12458};
12459
12460Promise.prototype._enoughBranchesHaveCancelled = function() {
12461 return this._branchesRemainingToCancel === undefined ||
12462 this._branchesRemainingToCancel <= 0;
12463};
12464
12465Promise.prototype._cancelBy = function(canceller) {
12466 if (canceller === this) {
12467 this._branchesRemainingToCancel = 0;
12468 this._invokeOnCancel();
12469 return true;
12470 } else {
12471 this._branchHasCancelled();
12472 if (this._enoughBranchesHaveCancelled()) {
12473 this._invokeOnCancel();
12474 return true;
12475 }
12476 }
12477 return false;
12478};
12479
12480Promise.prototype._cancelBranched = function() {
12481 if (this._enoughBranchesHaveCancelled()) {
12482 this._cancel();
12483 }
12484};
12485
12486Promise.prototype._cancel = function() {
12487 if (!this._isCancellable()) return;
12488 this._setCancelled();
12489 async.invoke(this._cancelPromises, this, undefined);
12490};
12491
12492Promise.prototype._cancelPromises = function() {
12493 if (this._length() > 0) this._settlePromises();
12494};
12495
12496Promise.prototype._unsetOnCancel = function() {
12497 this._onCancelField = undefined;
12498};
12499
12500Promise.prototype._isCancellable = function() {
12501 return this.isPending() && !this._isCancelled();
12502};
12503
12504Promise.prototype.isCancellable = function() {
12505 return this.isPending() && !this.isCancelled();
12506};
12507
12508Promise.prototype._doInvokeOnCancel = function(onCancelCallback, internalOnly) {
12509 if (util.isArray(onCancelCallback)) {
12510 for (var i = 0; i < onCancelCallback.length; ++i) {
12511 this._doInvokeOnCancel(onCancelCallback[i], internalOnly);
12512 }
12513 } else if (onCancelCallback !== undefined) {
12514 if (typeof onCancelCallback === "function") {
12515 if (!internalOnly) {
12516 var e = tryCatch(onCancelCallback).call(this._boundValue());
12517 if (e === errorObj) {
12518 this._attachExtraTrace(e.e);
12519 async.throwLater(e.e);
12520 }
12521 }
12522 } else {
12523 onCancelCallback._resultCancelled(this);
12524 }
12525 }
12526};
12527
12528Promise.prototype._invokeOnCancel = function() {
12529 var onCancelCallback = this._onCancel();
12530 this._unsetOnCancel();
12531 async.invoke(this._doInvokeOnCancel, this, onCancelCallback);
12532};
12533
12534Promise.prototype._invokeInternalOnCancel = function() {
12535 if (this._isCancellable()) {
12536 this._doInvokeOnCancel(this._onCancel(), true);
12537 this._unsetOnCancel();
12538 }
12539};
12540
12541Promise.prototype._resultCancelled = function() {
12542 this.cancel();
12543};
12544
12545};
12546
12547},{"./util":36}],7:[function(_dereq_,module,exports){
12548"use strict";
12549module.exports = function(NEXT_FILTER) {
12550var util = _dereq_("./util");
12551var getKeys = _dereq_("./es5").keys;
12552var tryCatch = util.tryCatch;
12553var errorObj = util.errorObj;
12554
12555function catchFilter(instances, cb, promise) {
12556 return function(e) {
12557 var boundTo = promise._boundValue();
12558 predicateLoop: for (var i = 0; i < instances.length; ++i) {
12559 var item = instances[i];
12560
12561 if (item === Error ||
12562 (item != null && item.prototype instanceof Error)) {
12563 if (e instanceof item) {
12564 return tryCatch(cb).call(boundTo, e);
12565 }
12566 } else if (typeof item === "function") {
12567 var matchesPredicate = tryCatch(item).call(boundTo, e);
12568 if (matchesPredicate === errorObj) {
12569 return matchesPredicate;
12570 } else if (matchesPredicate) {
12571 return tryCatch(cb).call(boundTo, e);
12572 }
12573 } else if (util.isObject(e)) {
12574 var keys = getKeys(item);
12575 for (var j = 0; j < keys.length; ++j) {
12576 var key = keys[j];
12577 if (item[key] != e[key]) {
12578 continue predicateLoop;
12579 }
12580 }
12581 return tryCatch(cb).call(boundTo, e);
12582 }
12583 }
12584 return NEXT_FILTER;
12585 };
12586}
12587
12588return catchFilter;
12589};
12590
12591},{"./es5":13,"./util":36}],8:[function(_dereq_,module,exports){
12592"use strict";
12593module.exports = function(Promise) {
12594var longStackTraces = false;
12595var contextStack = [];
12596
12597Promise.prototype._promiseCreated = function() {};
12598Promise.prototype._pushContext = function() {};
12599Promise.prototype._popContext = function() {return null;};
12600Promise._peekContext = Promise.prototype._peekContext = function() {};
12601
12602function Context() {
12603 this._trace = new Context.CapturedTrace(peekContext());
12604}
12605Context.prototype._pushContext = function () {
12606 if (this._trace !== undefined) {
12607 this._trace._promiseCreated = null;
12608 contextStack.push(this._trace);
12609 }
12610};
12611
12612Context.prototype._popContext = function () {
12613 if (this._trace !== undefined) {
12614 var trace = contextStack.pop();
12615 var ret = trace._promiseCreated;
12616 trace._promiseCreated = null;
12617 return ret;
12618 }
12619 return null;
12620};
12621
12622function createContext() {
12623 if (longStackTraces) return new Context();
12624}
12625
12626function peekContext() {
12627 var lastIndex = contextStack.length - 1;
12628 if (lastIndex >= 0) {
12629 return contextStack[lastIndex];
12630 }
12631 return undefined;
12632}
12633Context.CapturedTrace = null;
12634Context.create = createContext;
12635Context.deactivateLongStackTraces = function() {};
12636Context.activateLongStackTraces = function() {
12637 var Promise_pushContext = Promise.prototype._pushContext;
12638 var Promise_popContext = Promise.prototype._popContext;
12639 var Promise_PeekContext = Promise._peekContext;
12640 var Promise_peekContext = Promise.prototype._peekContext;
12641 var Promise_promiseCreated = Promise.prototype._promiseCreated;
12642 Context.deactivateLongStackTraces = function() {
12643 Promise.prototype._pushContext = Promise_pushContext;
12644 Promise.prototype._popContext = Promise_popContext;
12645 Promise._peekContext = Promise_PeekContext;
12646 Promise.prototype._peekContext = Promise_peekContext;
12647 Promise.prototype._promiseCreated = Promise_promiseCreated;
12648 longStackTraces = false;
12649 };
12650 longStackTraces = true;
12651 Promise.prototype._pushContext = Context.prototype._pushContext;
12652 Promise.prototype._popContext = Context.prototype._popContext;
12653 Promise._peekContext = Promise.prototype._peekContext = peekContext;
12654 Promise.prototype._promiseCreated = function() {
12655 var ctx = this._peekContext();
12656 if (ctx && ctx._promiseCreated == null) ctx._promiseCreated = this;
12657 };
12658};
12659return Context;
12660};
12661
12662},{}],9:[function(_dereq_,module,exports){
12663"use strict";
12664module.exports = function(Promise, Context) {
12665var getDomain = Promise._getDomain;
12666var async = Promise._async;
12667var Warning = _dereq_("./errors").Warning;
12668var util = _dereq_("./util");
12669var es5 = _dereq_("./es5");
12670var canAttachTrace = util.canAttachTrace;
12671var unhandledRejectionHandled;
12672var possiblyUnhandledRejection;
12673var bluebirdFramePattern =
12674 /[\\\/]bluebird[\\\/]js[\\\/](release|debug|instrumented)/;
12675var nodeFramePattern = /\((?:timers\.js):\d+:\d+\)/;
12676var parseLinePattern = /[\/<\(](.+?):(\d+):(\d+)\)?\s*$/;
12677var stackFramePattern = null;
12678var formatStack = null;
12679var indentStackFrames = false;
12680var printWarning;
12681var debugging = !!(util.env("BLUEBIRD_DEBUG") != 0 &&
12682 (true ||
12683 util.env("BLUEBIRD_DEBUG") ||
12684 util.env("NODE_ENV") === "development"));
12685
12686var warnings = !!(util.env("BLUEBIRD_WARNINGS") != 0 &&
12687 (debugging || util.env("BLUEBIRD_WARNINGS")));
12688
12689var longStackTraces = !!(util.env("BLUEBIRD_LONG_STACK_TRACES") != 0 &&
12690 (debugging || util.env("BLUEBIRD_LONG_STACK_TRACES")));
12691
12692var wForgottenReturn = util.env("BLUEBIRD_W_FORGOTTEN_RETURN") != 0 &&
12693 (warnings || !!util.env("BLUEBIRD_W_FORGOTTEN_RETURN"));
12694
12695Promise.prototype.suppressUnhandledRejections = function() {
12696 var target = this._target();
12697 target._bitField = ((target._bitField & (~1048576)) |
12698 524288);
12699};
12700
12701Promise.prototype._ensurePossibleRejectionHandled = function () {
12702 if ((this._bitField & 524288) !== 0) return;
12703 this._setRejectionIsUnhandled();
12704 var self = this;
12705 setTimeout(function() {
12706 self._notifyUnhandledRejection();
12707 }, 1);
12708};
12709
12710Promise.prototype._notifyUnhandledRejectionIsHandled = function () {
12711 fireRejectionEvent("rejectionHandled",
12712 unhandledRejectionHandled, undefined, this);
12713};
12714
12715Promise.prototype._setReturnedNonUndefined = function() {
12716 this._bitField = this._bitField | 268435456;
12717};
12718
12719Promise.prototype._returnedNonUndefined = function() {
12720 return (this._bitField & 268435456) !== 0;
12721};
12722
12723Promise.prototype._notifyUnhandledRejection = function () {
12724 if (this._isRejectionUnhandled()) {
12725 var reason = this._settledValue();
12726 this._setUnhandledRejectionIsNotified();
12727 fireRejectionEvent("unhandledRejection",
12728 possiblyUnhandledRejection, reason, this);
12729 }
12730};
12731
12732Promise.prototype._setUnhandledRejectionIsNotified = function () {
12733 this._bitField = this._bitField | 262144;
12734};
12735
12736Promise.prototype._unsetUnhandledRejectionIsNotified = function () {
12737 this._bitField = this._bitField & (~262144);
12738};
12739
12740Promise.prototype._isUnhandledRejectionNotified = function () {
12741 return (this._bitField & 262144) > 0;
12742};
12743
12744Promise.prototype._setRejectionIsUnhandled = function () {
12745 this._bitField = this._bitField | 1048576;
12746};
12747
12748Promise.prototype._unsetRejectionIsUnhandled = function () {
12749 this._bitField = this._bitField & (~1048576);
12750 if (this._isUnhandledRejectionNotified()) {
12751 this._unsetUnhandledRejectionIsNotified();
12752 this._notifyUnhandledRejectionIsHandled();
12753 }
12754};
12755
12756Promise.prototype._isRejectionUnhandled = function () {
12757 return (this._bitField & 1048576) > 0;
12758};
12759
12760Promise.prototype._warn = function(message, shouldUseOwnTrace, promise) {
12761 return warn(message, shouldUseOwnTrace, promise || this);
12762};
12763
12764Promise.onPossiblyUnhandledRejection = function (fn) {
12765 var domain = getDomain();
12766 possiblyUnhandledRejection =
12767 typeof fn === "function" ? (domain === null ?
12768 fn : util.domainBind(domain, fn))
12769 : undefined;
12770};
12771
12772Promise.onUnhandledRejectionHandled = function (fn) {
12773 var domain = getDomain();
12774 unhandledRejectionHandled =
12775 typeof fn === "function" ? (domain === null ?
12776 fn : util.domainBind(domain, fn))
12777 : undefined;
12778};
12779
12780var disableLongStackTraces = function() {};
12781Promise.longStackTraces = function () {
12782 if (async.haveItemsQueued() && !config.longStackTraces) {
12783 throw new Error("cannot enable long stack traces after promises have been created\u000a\u000a See http://goo.gl/MqrFmX\u000a");
12784 }
12785 if (!config.longStackTraces && longStackTracesIsSupported()) {
12786 var Promise_captureStackTrace = Promise.prototype._captureStackTrace;
12787 var Promise_attachExtraTrace = Promise.prototype._attachExtraTrace;
12788 var Promise_dereferenceTrace = Promise.prototype._dereferenceTrace;
12789 config.longStackTraces = true;
12790 disableLongStackTraces = function() {
12791 if (async.haveItemsQueued() && !config.longStackTraces) {
12792 throw new Error("cannot enable long stack traces after promises have been created\u000a\u000a See http://goo.gl/MqrFmX\u000a");
12793 }
12794 Promise.prototype._captureStackTrace = Promise_captureStackTrace;
12795 Promise.prototype._attachExtraTrace = Promise_attachExtraTrace;
12796 Promise.prototype._dereferenceTrace = Promise_dereferenceTrace;
12797 Context.deactivateLongStackTraces();
12798 async.enableTrampoline();
12799 config.longStackTraces = false;
12800 };
12801 Promise.prototype._captureStackTrace = longStackTracesCaptureStackTrace;
12802 Promise.prototype._attachExtraTrace = longStackTracesAttachExtraTrace;
12803 Promise.prototype._dereferenceTrace = longStackTracesDereferenceTrace;
12804 Context.activateLongStackTraces();
12805 async.disableTrampolineIfNecessary();
12806 }
12807};
12808
12809Promise.hasLongStackTraces = function () {
12810 return config.longStackTraces && longStackTracesIsSupported();
12811};
12812
12813var fireDomEvent = (function() {
12814 try {
12815 if (typeof CustomEvent === "function") {
12816 var event = new CustomEvent("CustomEvent");
12817 util.global.dispatchEvent(event);
12818 return function(name, event) {
12819 var eventData = {
12820 detail: event,
12821 cancelable: true
12822 };
12823 es5.defineProperty(
12824 eventData, "promise", {value: event.promise});
12825 es5.defineProperty(eventData, "reason", {value: event.reason});
12826 var domEvent = new CustomEvent(name.toLowerCase(), eventData);
12827 return !util.global.dispatchEvent(domEvent);
12828 };
12829 } else if (typeof Event === "function") {
12830 var event = new Event("CustomEvent");
12831 util.global.dispatchEvent(event);
12832 return function(name, event) {
12833 var domEvent = new Event(name.toLowerCase(), {
12834 cancelable: true
12835 });
12836 domEvent.detail = event;
12837 es5.defineProperty(domEvent, "promise", {value: event.promise});
12838 es5.defineProperty(domEvent, "reason", {value: event.reason});
12839 return !util.global.dispatchEvent(domEvent);
12840 };
12841 } else {
12842 var event = document.createEvent("CustomEvent");
12843 event.initCustomEvent("testingtheevent", false, true, {});
12844 util.global.dispatchEvent(event);
12845 return function(name, event) {
12846 var domEvent = document.createEvent("CustomEvent");
12847 domEvent.initCustomEvent(name.toLowerCase(), false, true,
12848 event);
12849 return !util.global.dispatchEvent(domEvent);
12850 };
12851 }
12852 } catch (e) {}
12853 return function() {
12854 return false;
12855 };
12856})();
12857
12858var fireGlobalEvent = (function() {
12859 if (util.isNode) {
12860 return function() {
12861 return process.emit.apply(process, arguments);
12862 };
12863 } else {
12864 if (!util.global) {
12865 return function() {
12866 return false;
12867 };
12868 }
12869 return function(name) {
12870 var methodName = "on" + name.toLowerCase();
12871 var method = util.global[methodName];
12872 if (!method) return false;
12873 method.apply(util.global, [].slice.call(arguments, 1));
12874 return true;
12875 };
12876 }
12877})();
12878
12879function generatePromiseLifecycleEventObject(name, promise) {
12880 return {promise: promise};
12881}
12882
12883var eventToObjectGenerator = {
12884 promiseCreated: generatePromiseLifecycleEventObject,
12885 promiseFulfilled: generatePromiseLifecycleEventObject,
12886 promiseRejected: generatePromiseLifecycleEventObject,
12887 promiseResolved: generatePromiseLifecycleEventObject,
12888 promiseCancelled: generatePromiseLifecycleEventObject,
12889 promiseChained: function(name, promise, child) {
12890 return {promise: promise, child: child};
12891 },
12892 warning: function(name, warning) {
12893 return {warning: warning};
12894 },
12895 unhandledRejection: function (name, reason, promise) {
12896 return {reason: reason, promise: promise};
12897 },
12898 rejectionHandled: generatePromiseLifecycleEventObject
12899};
12900
12901var activeFireEvent = function (name) {
12902 var globalEventFired = false;
12903 try {
12904 globalEventFired = fireGlobalEvent.apply(null, arguments);
12905 } catch (e) {
12906 async.throwLater(e);
12907 globalEventFired = true;
12908 }
12909
12910 var domEventFired = false;
12911 try {
12912 domEventFired = fireDomEvent(name,
12913 eventToObjectGenerator[name].apply(null, arguments));
12914 } catch (e) {
12915 async.throwLater(e);
12916 domEventFired = true;
12917 }
12918
12919 return domEventFired || globalEventFired;
12920};
12921
12922Promise.config = function(opts) {
12923 opts = Object(opts);
12924 if ("longStackTraces" in opts) {
12925 if (opts.longStackTraces) {
12926 Promise.longStackTraces();
12927 } else if (!opts.longStackTraces && Promise.hasLongStackTraces()) {
12928 disableLongStackTraces();
12929 }
12930 }
12931 if ("warnings" in opts) {
12932 var warningsOption = opts.warnings;
12933 config.warnings = !!warningsOption;
12934 wForgottenReturn = config.warnings;
12935
12936 if (util.isObject(warningsOption)) {
12937 if ("wForgottenReturn" in warningsOption) {
12938 wForgottenReturn = !!warningsOption.wForgottenReturn;
12939 }
12940 }
12941 }
12942 if ("cancellation" in opts && opts.cancellation && !config.cancellation) {
12943 if (async.haveItemsQueued()) {
12944 throw new Error(
12945 "cannot enable cancellation after promises are in use");
12946 }
12947 Promise.prototype._clearCancellationData =
12948 cancellationClearCancellationData;
12949 Promise.prototype._propagateFrom = cancellationPropagateFrom;
12950 Promise.prototype._onCancel = cancellationOnCancel;
12951 Promise.prototype._setOnCancel = cancellationSetOnCancel;
12952 Promise.prototype._attachCancellationCallback =
12953 cancellationAttachCancellationCallback;
12954 Promise.prototype._execute = cancellationExecute;
12955 propagateFromFunction = cancellationPropagateFrom;
12956 config.cancellation = true;
12957 }
12958 if ("monitoring" in opts) {
12959 if (opts.monitoring && !config.monitoring) {
12960 config.monitoring = true;
12961 Promise.prototype._fireEvent = activeFireEvent;
12962 } else if (!opts.monitoring && config.monitoring) {
12963 config.monitoring = false;
12964 Promise.prototype._fireEvent = defaultFireEvent;
12965 }
12966 }
12967 return Promise;
12968};
12969
12970function defaultFireEvent() { return false; }
12971
12972Promise.prototype._fireEvent = defaultFireEvent;
12973Promise.prototype._execute = function(executor, resolve, reject) {
12974 try {
12975 executor(resolve, reject);
12976 } catch (e) {
12977 return e;
12978 }
12979};
12980Promise.prototype._onCancel = function () {};
12981Promise.prototype._setOnCancel = function (handler) { ; };
12982Promise.prototype._attachCancellationCallback = function(onCancel) {
12983 ;
12984};
12985Promise.prototype._captureStackTrace = function () {};
12986Promise.prototype._attachExtraTrace = function () {};
12987Promise.prototype._dereferenceTrace = function () {};
12988Promise.prototype._clearCancellationData = function() {};
12989Promise.prototype._propagateFrom = function (parent, flags) {
12990 ;
12991 ;
12992};
12993
12994function cancellationExecute(executor, resolve, reject) {
12995 var promise = this;
12996 try {
12997 executor(resolve, reject, function(onCancel) {
12998 if (typeof onCancel !== "function") {
12999 throw new TypeError("onCancel must be a function, got: " +
13000 util.toString(onCancel));
13001 }
13002 promise._attachCancellationCallback(onCancel);
13003 });
13004 } catch (e) {
13005 return e;
13006 }
13007}
13008
13009function cancellationAttachCancellationCallback(onCancel) {
13010 if (!this._isCancellable()) return this;
13011
13012 var previousOnCancel = this._onCancel();
13013 if (previousOnCancel !== undefined) {
13014 if (util.isArray(previousOnCancel)) {
13015 previousOnCancel.push(onCancel);
13016 } else {
13017 this._setOnCancel([previousOnCancel, onCancel]);
13018 }
13019 } else {
13020 this._setOnCancel(onCancel);
13021 }
13022}
13023
13024function cancellationOnCancel() {
13025 return this._onCancelField;
13026}
13027
13028function cancellationSetOnCancel(onCancel) {
13029 this._onCancelField = onCancel;
13030}
13031
13032function cancellationClearCancellationData() {
13033 this._cancellationParent = undefined;
13034 this._onCancelField = undefined;
13035}
13036
13037function cancellationPropagateFrom(parent, flags) {
13038 if ((flags & 1) !== 0) {
13039 this._cancellationParent = parent;
13040 var branchesRemainingToCancel = parent._branchesRemainingToCancel;
13041 if (branchesRemainingToCancel === undefined) {
13042 branchesRemainingToCancel = 0;
13043 }
13044 parent._branchesRemainingToCancel = branchesRemainingToCancel + 1;
13045 }
13046 if ((flags & 2) !== 0 && parent._isBound()) {
13047 this._setBoundTo(parent._boundTo);
13048 }
13049}
13050
13051function bindingPropagateFrom(parent, flags) {
13052 if ((flags & 2) !== 0 && parent._isBound()) {
13053 this._setBoundTo(parent._boundTo);
13054 }
13055}
13056var propagateFromFunction = bindingPropagateFrom;
13057
13058function boundValueFunction() {
13059 var ret = this._boundTo;
13060 if (ret !== undefined) {
13061 if (ret instanceof Promise) {
13062 if (ret.isFulfilled()) {
13063 return ret.value();
13064 } else {
13065 return undefined;
13066 }
13067 }
13068 }
13069 return ret;
13070}
13071
13072function longStackTracesCaptureStackTrace() {
13073 this._trace = new CapturedTrace(this._peekContext());
13074}
13075
13076function longStackTracesAttachExtraTrace(error, ignoreSelf) {
13077 if (canAttachTrace(error)) {
13078 var trace = this._trace;
13079 if (trace !== undefined) {
13080 if (ignoreSelf) trace = trace._parent;
13081 }
13082 if (trace !== undefined) {
13083 trace.attachExtraTrace(error);
13084 } else if (!error.__stackCleaned__) {
13085 var parsed = parseStackAndMessage(error);
13086 util.notEnumerableProp(error, "stack",
13087 parsed.message + "\n" + parsed.stack.join("\n"));
13088 util.notEnumerableProp(error, "__stackCleaned__", true);
13089 }
13090 }
13091}
13092
13093function longStackTracesDereferenceTrace() {
13094 this._trace = undefined;
13095}
13096
13097function checkForgottenReturns(returnValue, promiseCreated, name, promise,
13098 parent) {
13099 if (returnValue === undefined && promiseCreated !== null &&
13100 wForgottenReturn) {
13101 if (parent !== undefined && parent._returnedNonUndefined()) return;
13102 if ((promise._bitField & 65535) === 0) return;
13103
13104 if (name) name = name + " ";
13105 var handlerLine = "";
13106 var creatorLine = "";
13107 if (promiseCreated._trace) {
13108 var traceLines = promiseCreated._trace.stack.split("\n");
13109 var stack = cleanStack(traceLines);
13110 for (var i = stack.length - 1; i >= 0; --i) {
13111 var line = stack[i];
13112 if (!nodeFramePattern.test(line)) {
13113 var lineMatches = line.match(parseLinePattern);
13114 if (lineMatches) {
13115 handlerLine = "at " + lineMatches[1] +
13116 ":" + lineMatches[2] + ":" + lineMatches[3] + " ";
13117 }
13118 break;
13119 }
13120 }
13121
13122 if (stack.length > 0) {
13123 var firstUserLine = stack[0];
13124 for (var i = 0; i < traceLines.length; ++i) {
13125
13126 if (traceLines[i] === firstUserLine) {
13127 if (i > 0) {
13128 creatorLine = "\n" + traceLines[i - 1];
13129 }
13130 break;
13131 }
13132 }
13133
13134 }
13135 }
13136 var msg = "a promise was created in a " + name +
13137 "handler " + handlerLine + "but was not returned from it, " +
13138 "see http://goo.gl/rRqMUw" +
13139 creatorLine;
13140 promise._warn(msg, true, promiseCreated);
13141 }
13142}
13143
13144function deprecated(name, replacement) {
13145 var message = name +
13146 " is deprecated and will be removed in a future version.";
13147 if (replacement) message += " Use " + replacement + " instead.";
13148 return warn(message);
13149}
13150
13151function warn(message, shouldUseOwnTrace, promise) {
13152 if (!config.warnings) return;
13153 var warning = new Warning(message);
13154 var ctx;
13155 if (shouldUseOwnTrace) {
13156 promise._attachExtraTrace(warning);
13157 } else if (config.longStackTraces && (ctx = Promise._peekContext())) {
13158 ctx.attachExtraTrace(warning);
13159 } else {
13160 var parsed = parseStackAndMessage(warning);
13161 warning.stack = parsed.message + "\n" + parsed.stack.join("\n");
13162 }
13163
13164 if (!activeFireEvent("warning", warning)) {
13165 formatAndLogError(warning, "", true);
13166 }
13167}
13168
13169function reconstructStack(message, stacks) {
13170 for (var i = 0; i < stacks.length - 1; ++i) {
13171 stacks[i].push("From previous event:");
13172 stacks[i] = stacks[i].join("\n");
13173 }
13174 if (i < stacks.length) {
13175 stacks[i] = stacks[i].join("\n");
13176 }
13177 return message + "\n" + stacks.join("\n");
13178}
13179
13180function removeDuplicateOrEmptyJumps(stacks) {
13181 for (var i = 0; i < stacks.length; ++i) {
13182 if (stacks[i].length === 0 ||
13183 ((i + 1 < stacks.length) && stacks[i][0] === stacks[i+1][0])) {
13184 stacks.splice(i, 1);
13185 i--;
13186 }
13187 }
13188}
13189
13190function removeCommonRoots(stacks) {
13191 var current = stacks[0];
13192 for (var i = 1; i < stacks.length; ++i) {
13193 var prev = stacks[i];
13194 var currentLastIndex = current.length - 1;
13195 var currentLastLine = current[currentLastIndex];
13196 var commonRootMeetPoint = -1;
13197
13198 for (var j = prev.length - 1; j >= 0; --j) {
13199 if (prev[j] === currentLastLine) {
13200 commonRootMeetPoint = j;
13201 break;
13202 }
13203 }
13204
13205 for (var j = commonRootMeetPoint; j >= 0; --j) {
13206 var line = prev[j];
13207 if (current[currentLastIndex] === line) {
13208 current.pop();
13209 currentLastIndex--;
13210 } else {
13211 break;
13212 }
13213 }
13214 current = prev;
13215 }
13216}
13217
13218function cleanStack(stack) {
13219 var ret = [];
13220 for (var i = 0; i < stack.length; ++i) {
13221 var line = stack[i];
13222 var isTraceLine = " (No stack trace)" === line ||
13223 stackFramePattern.test(line);
13224 var isInternalFrame = isTraceLine && shouldIgnore(line);
13225 if (isTraceLine && !isInternalFrame) {
13226 if (indentStackFrames && line.charAt(0) !== " ") {
13227 line = " " + line;
13228 }
13229 ret.push(line);
13230 }
13231 }
13232 return ret;
13233}
13234
13235function stackFramesAsArray(error) {
13236 var stack = error.stack.replace(/\s+$/g, "").split("\n");
13237 for (var i = 0; i < stack.length; ++i) {
13238 var line = stack[i];
13239 if (" (No stack trace)" === line || stackFramePattern.test(line)) {
13240 break;
13241 }
13242 }
13243 if (i > 0 && error.name != "SyntaxError") {
13244 stack = stack.slice(i);
13245 }
13246 return stack;
13247}
13248
13249function parseStackAndMessage(error) {
13250 var stack = error.stack;
13251 var message = error.toString();
13252 stack = typeof stack === "string" && stack.length > 0
13253 ? stackFramesAsArray(error) : [" (No stack trace)"];
13254 return {
13255 message: message,
13256 stack: error.name == "SyntaxError" ? stack : cleanStack(stack)
13257 };
13258}
13259
13260function formatAndLogError(error, title, isSoft) {
13261 if (typeof console !== "undefined") {
13262 var message;
13263 if (util.isObject(error)) {
13264 var stack = error.stack;
13265 message = title + formatStack(stack, error);
13266 } else {
13267 message = title + String(error);
13268 }
13269 if (typeof printWarning === "function") {
13270 printWarning(message, isSoft);
13271 } else if (typeof console.log === "function" ||
13272 typeof console.log === "object") {
13273 console.log(message);
13274 }
13275 }
13276}
13277
13278function fireRejectionEvent(name, localHandler, reason, promise) {
13279 var localEventFired = false;
13280 try {
13281 if (typeof localHandler === "function") {
13282 localEventFired = true;
13283 if (name === "rejectionHandled") {
13284 localHandler(promise);
13285 } else {
13286 localHandler(reason, promise);
13287 }
13288 }
13289 } catch (e) {
13290 async.throwLater(e);
13291 }
13292
13293 if (name === "unhandledRejection") {
13294 if (!activeFireEvent(name, reason, promise) && !localEventFired) {
13295 formatAndLogError(reason, "Unhandled rejection ");
13296 }
13297 } else {
13298 activeFireEvent(name, promise);
13299 }
13300}
13301
13302function formatNonError(obj) {
13303 var str;
13304 if (typeof obj === "function") {
13305 str = "[function " +
13306 (obj.name || "anonymous") +
13307 "]";
13308 } else {
13309 str = obj && typeof obj.toString === "function"
13310 ? obj.toString() : util.toString(obj);
13311 var ruselessToString = /\[object [a-zA-Z0-9$_]+\]/;
13312 if (ruselessToString.test(str)) {
13313 try {
13314 var newStr = JSON.stringify(obj);
13315 str = newStr;
13316 }
13317 catch(e) {
13318
13319 }
13320 }
13321 if (str.length === 0) {
13322 str = "(empty array)";
13323 }
13324 }
13325 return ("(<" + snip(str) + ">, no stack trace)");
13326}
13327
13328function snip(str) {
13329 var maxChars = 41;
13330 if (str.length < maxChars) {
13331 return str;
13332 }
13333 return str.substr(0, maxChars - 3) + "...";
13334}
13335
13336function longStackTracesIsSupported() {
13337 return typeof captureStackTrace === "function";
13338}
13339
13340var shouldIgnore = function() { return false; };
13341var parseLineInfoRegex = /[\/<\(]([^:\/]+):(\d+):(?:\d+)\)?\s*$/;
13342function parseLineInfo(line) {
13343 var matches = line.match(parseLineInfoRegex);
13344 if (matches) {
13345 return {
13346 fileName: matches[1],
13347 line: parseInt(matches[2], 10)
13348 };
13349 }
13350}
13351
13352function setBounds(firstLineError, lastLineError) {
13353 if (!longStackTracesIsSupported()) return;
13354 var firstStackLines = (firstLineError.stack || "").split("\n");
13355 var lastStackLines = (lastLineError.stack || "").split("\n");
13356 var firstIndex = -1;
13357 var lastIndex = -1;
13358 var firstFileName;
13359 var lastFileName;
13360 for (var i = 0; i < firstStackLines.length; ++i) {
13361 var result = parseLineInfo(firstStackLines[i]);
13362 if (result) {
13363 firstFileName = result.fileName;
13364 firstIndex = result.line;
13365 break;
13366 }
13367 }
13368 for (var i = 0; i < lastStackLines.length; ++i) {
13369 var result = parseLineInfo(lastStackLines[i]);
13370 if (result) {
13371 lastFileName = result.fileName;
13372 lastIndex = result.line;
13373 break;
13374 }
13375 }
13376 if (firstIndex < 0 || lastIndex < 0 || !firstFileName || !lastFileName ||
13377 firstFileName !== lastFileName || firstIndex >= lastIndex) {
13378 return;
13379 }
13380
13381 shouldIgnore = function(line) {
13382 if (bluebirdFramePattern.test(line)) return true;
13383 var info = parseLineInfo(line);
13384 if (info) {
13385 if (info.fileName === firstFileName &&
13386 (firstIndex <= info.line && info.line <= lastIndex)) {
13387 return true;
13388 }
13389 }
13390 return false;
13391 };
13392}
13393
13394function CapturedTrace(parent) {
13395 this._parent = parent;
13396 this._promisesCreated = 0;
13397 var length = this._length = 1 + (parent === undefined ? 0 : parent._length);
13398 captureStackTrace(this, CapturedTrace);
13399 if (length > 32) this.uncycle();
13400}
13401util.inherits(CapturedTrace, Error);
13402Context.CapturedTrace = CapturedTrace;
13403
13404CapturedTrace.prototype.uncycle = function() {
13405 var length = this._length;
13406 if (length < 2) return;
13407 var nodes = [];
13408 var stackToIndex = {};
13409
13410 for (var i = 0, node = this; node !== undefined; ++i) {
13411 nodes.push(node);
13412 node = node._parent;
13413 }
13414 length = this._length = i;
13415 for (var i = length - 1; i >= 0; --i) {
13416 var stack = nodes[i].stack;
13417 if (stackToIndex[stack] === undefined) {
13418 stackToIndex[stack] = i;
13419 }
13420 }
13421 for (var i = 0; i < length; ++i) {
13422 var currentStack = nodes[i].stack;
13423 var index = stackToIndex[currentStack];
13424 if (index !== undefined && index !== i) {
13425 if (index > 0) {
13426 nodes[index - 1]._parent = undefined;
13427 nodes[index - 1]._length = 1;
13428 }
13429 nodes[i]._parent = undefined;
13430 nodes[i]._length = 1;
13431 var cycleEdgeNode = i > 0 ? nodes[i - 1] : this;
13432
13433 if (index < length - 1) {
13434 cycleEdgeNode._parent = nodes[index + 1];
13435 cycleEdgeNode._parent.uncycle();
13436 cycleEdgeNode._length =
13437 cycleEdgeNode._parent._length + 1;
13438 } else {
13439 cycleEdgeNode._parent = undefined;
13440 cycleEdgeNode._length = 1;
13441 }
13442 var currentChildLength = cycleEdgeNode._length + 1;
13443 for (var j = i - 2; j >= 0; --j) {
13444 nodes[j]._length = currentChildLength;
13445 currentChildLength++;
13446 }
13447 return;
13448 }
13449 }
13450};
13451
13452CapturedTrace.prototype.attachExtraTrace = function(error) {
13453 if (error.__stackCleaned__) return;
13454 this.uncycle();
13455 var parsed = parseStackAndMessage(error);
13456 var message = parsed.message;
13457 var stacks = [parsed.stack];
13458
13459 var trace = this;
13460 while (trace !== undefined) {
13461 stacks.push(cleanStack(trace.stack.split("\n")));
13462 trace = trace._parent;
13463 }
13464 removeCommonRoots(stacks);
13465 removeDuplicateOrEmptyJumps(stacks);
13466 util.notEnumerableProp(error, "stack", reconstructStack(message, stacks));
13467 util.notEnumerableProp(error, "__stackCleaned__", true);
13468};
13469
13470var captureStackTrace = (function stackDetection() {
13471 var v8stackFramePattern = /^\s*at\s*/;
13472 var v8stackFormatter = function(stack, error) {
13473 if (typeof stack === "string") return stack;
13474
13475 if (error.name !== undefined &&
13476 error.message !== undefined) {
13477 return error.toString();
13478 }
13479 return formatNonError(error);
13480 };
13481
13482 if (typeof Error.stackTraceLimit === "number" &&
13483 typeof Error.captureStackTrace === "function") {
13484 Error.stackTraceLimit += 6;
13485 stackFramePattern = v8stackFramePattern;
13486 formatStack = v8stackFormatter;
13487 var captureStackTrace = Error.captureStackTrace;
13488
13489 shouldIgnore = function(line) {
13490 return bluebirdFramePattern.test(line);
13491 };
13492 return function(receiver, ignoreUntil) {
13493 Error.stackTraceLimit += 6;
13494 captureStackTrace(receiver, ignoreUntil);
13495 Error.stackTraceLimit -= 6;
13496 };
13497 }
13498 var err = new Error();
13499
13500 if (typeof err.stack === "string" &&
13501 err.stack.split("\n")[0].indexOf("stackDetection@") >= 0) {
13502 stackFramePattern = /@/;
13503 formatStack = v8stackFormatter;
13504 indentStackFrames = true;
13505 return function captureStackTrace(o) {
13506 o.stack = new Error().stack;
13507 };
13508 }
13509
13510 var hasStackAfterThrow;
13511 try { throw new Error(); }
13512 catch(e) {
13513 hasStackAfterThrow = ("stack" in e);
13514 }
13515 if (!("stack" in err) && hasStackAfterThrow &&
13516 typeof Error.stackTraceLimit === "number") {
13517 stackFramePattern = v8stackFramePattern;
13518 formatStack = v8stackFormatter;
13519 return function captureStackTrace(o) {
13520 Error.stackTraceLimit += 6;
13521 try { throw new Error(); }
13522 catch(e) { o.stack = e.stack; }
13523 Error.stackTraceLimit -= 6;
13524 };
13525 }
13526
13527 formatStack = function(stack, error) {
13528 if (typeof stack === "string") return stack;
13529
13530 if ((typeof error === "object" ||
13531 typeof error === "function") &&
13532 error.name !== undefined &&
13533 error.message !== undefined) {
13534 return error.toString();
13535 }
13536 return formatNonError(error);
13537 };
13538
13539 return null;
13540
13541})([]);
13542
13543if (typeof console !== "undefined" && typeof console.warn !== "undefined") {
13544 printWarning = function (message) {
13545 console.warn(message);
13546 };
13547 if (util.isNode && process.stderr.isTTY) {
13548 printWarning = function(message, isSoft) {
13549 var color = isSoft ? "\u001b[33m" : "\u001b[31m";
13550 console.warn(color + message + "\u001b[0m\n");
13551 };
13552 } else if (!util.isNode && typeof (new Error().stack) === "string") {
13553 printWarning = function(message, isSoft) {
13554 console.warn("%c" + message,
13555 isSoft ? "color: darkorange" : "color: red");
13556 };
13557 }
13558}
13559
13560var config = {
13561 warnings: warnings,
13562 longStackTraces: false,
13563 cancellation: false,
13564 monitoring: false
13565};
13566
13567if (longStackTraces) Promise.longStackTraces();
13568
13569return {
13570 longStackTraces: function() {
13571 return config.longStackTraces;
13572 },
13573 warnings: function() {
13574 return config.warnings;
13575 },
13576 cancellation: function() {
13577 return config.cancellation;
13578 },
13579 monitoring: function() {
13580 return config.monitoring;
13581 },
13582 propagateFromFunction: function() {
13583 return propagateFromFunction;
13584 },
13585 boundValueFunction: function() {
13586 return boundValueFunction;
13587 },
13588 checkForgottenReturns: checkForgottenReturns,
13589 setBounds: setBounds,
13590 warn: warn,
13591 deprecated: deprecated,
13592 CapturedTrace: CapturedTrace,
13593 fireDomEvent: fireDomEvent,
13594 fireGlobalEvent: fireGlobalEvent
13595};
13596};
13597
13598},{"./errors":12,"./es5":13,"./util":36}],10:[function(_dereq_,module,exports){
13599"use strict";
13600module.exports = function(Promise) {
13601function returner() {
13602 return this.value;
13603}
13604function thrower() {
13605 throw this.reason;
13606}
13607
13608Promise.prototype["return"] =
13609Promise.prototype.thenReturn = function (value) {
13610 if (value instanceof Promise) value.suppressUnhandledRejections();
13611 return this._then(
13612 returner, undefined, undefined, {value: value}, undefined);
13613};
13614
13615Promise.prototype["throw"] =
13616Promise.prototype.thenThrow = function (reason) {
13617 return this._then(
13618 thrower, undefined, undefined, {reason: reason}, undefined);
13619};
13620
13621Promise.prototype.catchThrow = function (reason) {
13622 if (arguments.length <= 1) {
13623 return this._then(
13624 undefined, thrower, undefined, {reason: reason}, undefined);
13625 } else {
13626 var _reason = arguments[1];
13627 var handler = function() {throw _reason;};
13628 return this.caught(reason, handler);
13629 }
13630};
13631
13632Promise.prototype.catchReturn = function (value) {
13633 if (arguments.length <= 1) {
13634 if (value instanceof Promise) value.suppressUnhandledRejections();
13635 return this._then(
13636 undefined, returner, undefined, {value: value}, undefined);
13637 } else {
13638 var _value = arguments[1];
13639 if (_value instanceof Promise) _value.suppressUnhandledRejections();
13640 var handler = function() {return _value;};
13641 return this.caught(value, handler);
13642 }
13643};
13644};
13645
13646},{}],11:[function(_dereq_,module,exports){
13647"use strict";
13648module.exports = function(Promise, INTERNAL) {
13649var PromiseReduce = Promise.reduce;
13650var PromiseAll = Promise.all;
13651
13652function promiseAllThis() {
13653 return PromiseAll(this);
13654}
13655
13656function PromiseMapSeries(promises, fn) {
13657 return PromiseReduce(promises, fn, INTERNAL, INTERNAL);
13658}
13659
13660Promise.prototype.each = function (fn) {
13661 return PromiseReduce(this, fn, INTERNAL, 0)
13662 ._then(promiseAllThis, undefined, undefined, this, undefined);
13663};
13664
13665Promise.prototype.mapSeries = function (fn) {
13666 return PromiseReduce(this, fn, INTERNAL, INTERNAL);
13667};
13668
13669Promise.each = function (promises, fn) {
13670 return PromiseReduce(promises, fn, INTERNAL, 0)
13671 ._then(promiseAllThis, undefined, undefined, promises, undefined);
13672};
13673
13674Promise.mapSeries = PromiseMapSeries;
13675};
13676
13677
13678},{}],12:[function(_dereq_,module,exports){
13679"use strict";
13680var es5 = _dereq_("./es5");
13681var Objectfreeze = es5.freeze;
13682var util = _dereq_("./util");
13683var inherits = util.inherits;
13684var notEnumerableProp = util.notEnumerableProp;
13685
13686function subError(nameProperty, defaultMessage) {
13687 function SubError(message) {
13688 if (!(this instanceof SubError)) return new SubError(message);
13689 notEnumerableProp(this, "message",
13690 typeof message === "string" ? message : defaultMessage);
13691 notEnumerableProp(this, "name", nameProperty);
13692 if (Error.captureStackTrace) {
13693 Error.captureStackTrace(this, this.constructor);
13694 } else {
13695 Error.call(this);
13696 }
13697 }
13698 inherits(SubError, Error);
13699 return SubError;
13700}
13701
13702var _TypeError, _RangeError;
13703var Warning = subError("Warning", "warning");
13704var CancellationError = subError("CancellationError", "cancellation error");
13705var TimeoutError = subError("TimeoutError", "timeout error");
13706var AggregateError = subError("AggregateError", "aggregate error");
13707try {
13708 _TypeError = TypeError;
13709 _RangeError = RangeError;
13710} catch(e) {
13711 _TypeError = subError("TypeError", "type error");
13712 _RangeError = subError("RangeError", "range error");
13713}
13714
13715var methods = ("join pop push shift unshift slice filter forEach some " +
13716 "every map indexOf lastIndexOf reduce reduceRight sort reverse").split(" ");
13717
13718for (var i = 0; i < methods.length; ++i) {
13719 if (typeof Array.prototype[methods[i]] === "function") {
13720 AggregateError.prototype[methods[i]] = Array.prototype[methods[i]];
13721 }
13722}
13723
13724es5.defineProperty(AggregateError.prototype, "length", {
13725 value: 0,
13726 configurable: false,
13727 writable: true,
13728 enumerable: true
13729});
13730AggregateError.prototype["isOperational"] = true;
13731var level = 0;
13732AggregateError.prototype.toString = function() {
13733 var indent = Array(level * 4 + 1).join(" ");
13734 var ret = "\n" + indent + "AggregateError of:" + "\n";
13735 level++;
13736 indent = Array(level * 4 + 1).join(" ");
13737 for (var i = 0; i < this.length; ++i) {
13738 var str = this[i] === this ? "[Circular AggregateError]" : this[i] + "";
13739 var lines = str.split("\n");
13740 for (var j = 0; j < lines.length; ++j) {
13741 lines[j] = indent + lines[j];
13742 }
13743 str = lines.join("\n");
13744 ret += str + "\n";
13745 }
13746 level--;
13747 return ret;
13748};
13749
13750function OperationalError(message) {
13751 if (!(this instanceof OperationalError))
13752 return new OperationalError(message);
13753 notEnumerableProp(this, "name", "OperationalError");
13754 notEnumerableProp(this, "message", message);
13755 this.cause = message;
13756 this["isOperational"] = true;
13757
13758 if (message instanceof Error) {
13759 notEnumerableProp(this, "message", message.message);
13760 notEnumerableProp(this, "stack", message.stack);
13761 } else if (Error.captureStackTrace) {
13762 Error.captureStackTrace(this, this.constructor);
13763 }
13764
13765}
13766inherits(OperationalError, Error);
13767
13768var errorTypes = Error["__BluebirdErrorTypes__"];
13769if (!errorTypes) {
13770 errorTypes = Objectfreeze({
13771 CancellationError: CancellationError,
13772 TimeoutError: TimeoutError,
13773 OperationalError: OperationalError,
13774 RejectionError: OperationalError,
13775 AggregateError: AggregateError
13776 });
13777 es5.defineProperty(Error, "__BluebirdErrorTypes__", {
13778 value: errorTypes,
13779 writable: false,
13780 enumerable: false,
13781 configurable: false
13782 });
13783}
13784
13785module.exports = {
13786 Error: Error,
13787 TypeError: _TypeError,
13788 RangeError: _RangeError,
13789 CancellationError: errorTypes.CancellationError,
13790 OperationalError: errorTypes.OperationalError,
13791 TimeoutError: errorTypes.TimeoutError,
13792 AggregateError: errorTypes.AggregateError,
13793 Warning: Warning
13794};
13795
13796},{"./es5":13,"./util":36}],13:[function(_dereq_,module,exports){
13797var isES5 = (function(){
13798 "use strict";
13799 return this === undefined;
13800})();
13801
13802if (isES5) {
13803 module.exports = {
13804 freeze: Object.freeze,
13805 defineProperty: Object.defineProperty,
13806 getDescriptor: Object.getOwnPropertyDescriptor,
13807 keys: Object.keys,
13808 names: Object.getOwnPropertyNames,
13809 getPrototypeOf: Object.getPrototypeOf,
13810 isArray: Array.isArray,
13811 isES5: isES5,
13812 propertyIsWritable: function(obj, prop) {
13813 var descriptor = Object.getOwnPropertyDescriptor(obj, prop);
13814 return !!(!descriptor || descriptor.writable || descriptor.set);
13815 }
13816 };
13817} else {
13818 var has = {}.hasOwnProperty;
13819 var str = {}.toString;
13820 var proto = {}.constructor.prototype;
13821
13822 var ObjectKeys = function (o) {
13823 var ret = [];
13824 for (var key in o) {
13825 if (has.call(o, key)) {
13826 ret.push(key);
13827 }
13828 }
13829 return ret;
13830 };
13831
13832 var ObjectGetDescriptor = function(o, key) {
13833 return {value: o[key]};
13834 };
13835
13836 var ObjectDefineProperty = function (o, key, desc) {
13837 o[key] = desc.value;
13838 return o;
13839 };
13840
13841 var ObjectFreeze = function (obj) {
13842 return obj;
13843 };
13844
13845 var ObjectGetPrototypeOf = function (obj) {
13846 try {
13847 return Object(obj).constructor.prototype;
13848 }
13849 catch (e) {
13850 return proto;
13851 }
13852 };
13853
13854 var ArrayIsArray = function (obj) {
13855 try {
13856 return str.call(obj) === "[object Array]";
13857 }
13858 catch(e) {
13859 return false;
13860 }
13861 };
13862
13863 module.exports = {
13864 isArray: ArrayIsArray,
13865 keys: ObjectKeys,
13866 names: ObjectKeys,
13867 defineProperty: ObjectDefineProperty,
13868 getDescriptor: ObjectGetDescriptor,
13869 freeze: ObjectFreeze,
13870 getPrototypeOf: ObjectGetPrototypeOf,
13871 isES5: isES5,
13872 propertyIsWritable: function() {
13873 return true;
13874 }
13875 };
13876}
13877
13878},{}],14:[function(_dereq_,module,exports){
13879"use strict";
13880module.exports = function(Promise, INTERNAL) {
13881var PromiseMap = Promise.map;
13882
13883Promise.prototype.filter = function (fn, options) {
13884 return PromiseMap(this, fn, options, INTERNAL);
13885};
13886
13887Promise.filter = function (promises, fn, options) {
13888 return PromiseMap(promises, fn, options, INTERNAL);
13889};
13890};
13891
13892},{}],15:[function(_dereq_,module,exports){
13893"use strict";
13894module.exports = function(Promise, tryConvertToPromise, NEXT_FILTER) {
13895var util = _dereq_("./util");
13896var CancellationError = Promise.CancellationError;
13897var errorObj = util.errorObj;
13898var catchFilter = _dereq_("./catch_filter")(NEXT_FILTER);
13899
13900function PassThroughHandlerContext(promise, type, handler) {
13901 this.promise = promise;
13902 this.type = type;
13903 this.handler = handler;
13904 this.called = false;
13905 this.cancelPromise = null;
13906}
13907
13908PassThroughHandlerContext.prototype.isFinallyHandler = function() {
13909 return this.type === 0;
13910};
13911
13912function FinallyHandlerCancelReaction(finallyHandler) {
13913 this.finallyHandler = finallyHandler;
13914}
13915
13916FinallyHandlerCancelReaction.prototype._resultCancelled = function() {
13917 checkCancel(this.finallyHandler);
13918};
13919
13920function checkCancel(ctx, reason) {
13921 if (ctx.cancelPromise != null) {
13922 if (arguments.length > 1) {
13923 ctx.cancelPromise._reject(reason);
13924 } else {
13925 ctx.cancelPromise._cancel();
13926 }
13927 ctx.cancelPromise = null;
13928 return true;
13929 }
13930 return false;
13931}
13932
13933function succeed() {
13934 return finallyHandler.call(this, this.promise._target()._settledValue());
13935}
13936function fail(reason) {
13937 if (checkCancel(this, reason)) return;
13938 errorObj.e = reason;
13939 return errorObj;
13940}
13941function finallyHandler(reasonOrValue) {
13942 var promise = this.promise;
13943 var handler = this.handler;
13944
13945 if (!this.called) {
13946 this.called = true;
13947 var ret = this.isFinallyHandler()
13948 ? handler.call(promise._boundValue())
13949 : handler.call(promise._boundValue(), reasonOrValue);
13950 if (ret === NEXT_FILTER) {
13951 return ret;
13952 } else if (ret !== undefined) {
13953 promise._setReturnedNonUndefined();
13954 var maybePromise = tryConvertToPromise(ret, promise);
13955 if (maybePromise instanceof Promise) {
13956 if (this.cancelPromise != null) {
13957 if (maybePromise._isCancelled()) {
13958 var reason =
13959 new CancellationError("late cancellation observer");
13960 promise._attachExtraTrace(reason);
13961 errorObj.e = reason;
13962 return errorObj;
13963 } else if (maybePromise.isPending()) {
13964 maybePromise._attachCancellationCallback(
13965 new FinallyHandlerCancelReaction(this));
13966 }
13967 }
13968 return maybePromise._then(
13969 succeed, fail, undefined, this, undefined);
13970 }
13971 }
13972 }
13973
13974 if (promise.isRejected()) {
13975 checkCancel(this);
13976 errorObj.e = reasonOrValue;
13977 return errorObj;
13978 } else {
13979 checkCancel(this);
13980 return reasonOrValue;
13981 }
13982}
13983
13984Promise.prototype._passThrough = function(handler, type, success, fail) {
13985 if (typeof handler !== "function") return this.then();
13986 return this._then(success,
13987 fail,
13988 undefined,
13989 new PassThroughHandlerContext(this, type, handler),
13990 undefined);
13991};
13992
13993Promise.prototype.lastly =
13994Promise.prototype["finally"] = function (handler) {
13995 return this._passThrough(handler,
13996 0,
13997 finallyHandler,
13998 finallyHandler);
13999};
14000
14001
14002Promise.prototype.tap = function (handler) {
14003 return this._passThrough(handler, 1, finallyHandler);
14004};
14005
14006Promise.prototype.tapCatch = function (handlerOrPredicate) {
14007 var len = arguments.length;
14008 if(len === 1) {
14009 return this._passThrough(handlerOrPredicate,
14010 1,
14011 undefined,
14012 finallyHandler);
14013 } else {
14014 var catchInstances = new Array(len - 1),
14015 j = 0, i;
14016 for (i = 0; i < len - 1; ++i) {
14017 var item = arguments[i];
14018 if (util.isObject(item)) {
14019 catchInstances[j++] = item;
14020 } else {
14021 return Promise.reject(new TypeError(
14022 "tapCatch statement predicate: "
14023 + "expecting an object but got " + util.classString(item)
14024 ));
14025 }
14026 }
14027 catchInstances.length = j;
14028 var handler = arguments[i];
14029 return this._passThrough(catchFilter(catchInstances, handler, this),
14030 1,
14031 undefined,
14032 finallyHandler);
14033 }
14034
14035};
14036
14037return PassThroughHandlerContext;
14038};
14039
14040},{"./catch_filter":7,"./util":36}],16:[function(_dereq_,module,exports){
14041"use strict";
14042module.exports = function(Promise,
14043 apiRejection,
14044 INTERNAL,
14045 tryConvertToPromise,
14046 Proxyable,
14047 debug) {
14048var errors = _dereq_("./errors");
14049var TypeError = errors.TypeError;
14050var util = _dereq_("./util");
14051var errorObj = util.errorObj;
14052var tryCatch = util.tryCatch;
14053var yieldHandlers = [];
14054
14055function promiseFromYieldHandler(value, yieldHandlers, traceParent) {
14056 for (var i = 0; i < yieldHandlers.length; ++i) {
14057 traceParent._pushContext();
14058 var result = tryCatch(yieldHandlers[i])(value);
14059 traceParent._popContext();
14060 if (result === errorObj) {
14061 traceParent._pushContext();
14062 var ret = Promise.reject(errorObj.e);
14063 traceParent._popContext();
14064 return ret;
14065 }
14066 var maybePromise = tryConvertToPromise(result, traceParent);
14067 if (maybePromise instanceof Promise) return maybePromise;
14068 }
14069 return null;
14070}
14071
14072function PromiseSpawn(generatorFunction, receiver, yieldHandler, stack) {
14073 if (debug.cancellation()) {
14074 var internal = new Promise(INTERNAL);
14075 var _finallyPromise = this._finallyPromise = new Promise(INTERNAL);
14076 this._promise = internal.lastly(function() {
14077 return _finallyPromise;
14078 });
14079 internal._captureStackTrace();
14080 internal._setOnCancel(this);
14081 } else {
14082 var promise = this._promise = new Promise(INTERNAL);
14083 promise._captureStackTrace();
14084 }
14085 this._stack = stack;
14086 this._generatorFunction = generatorFunction;
14087 this._receiver = receiver;
14088 this._generator = undefined;
14089 this._yieldHandlers = typeof yieldHandler === "function"
14090 ? [yieldHandler].concat(yieldHandlers)
14091 : yieldHandlers;
14092 this._yieldedPromise = null;
14093 this._cancellationPhase = false;
14094}
14095util.inherits(PromiseSpawn, Proxyable);
14096
14097PromiseSpawn.prototype._isResolved = function() {
14098 return this._promise === null;
14099};
14100
14101PromiseSpawn.prototype._cleanup = function() {
14102 this._promise = this._generator = null;
14103 if (debug.cancellation() && this._finallyPromise !== null) {
14104 this._finallyPromise._fulfill();
14105 this._finallyPromise = null;
14106 }
14107};
14108
14109PromiseSpawn.prototype._promiseCancelled = function() {
14110 if (this._isResolved()) return;
14111 var implementsReturn = typeof this._generator["return"] !== "undefined";
14112
14113 var result;
14114 if (!implementsReturn) {
14115 var reason = new Promise.CancellationError(
14116 "generator .return() sentinel");
14117 Promise.coroutine.returnSentinel = reason;
14118 this._promise._attachExtraTrace(reason);
14119 this._promise._pushContext();
14120 result = tryCatch(this._generator["throw"]).call(this._generator,
14121 reason);
14122 this._promise._popContext();
14123 } else {
14124 this._promise._pushContext();
14125 result = tryCatch(this._generator["return"]).call(this._generator,
14126 undefined);
14127 this._promise._popContext();
14128 }
14129 this._cancellationPhase = true;
14130 this._yieldedPromise = null;
14131 this._continue(result);
14132};
14133
14134PromiseSpawn.prototype._promiseFulfilled = function(value) {
14135 this._yieldedPromise = null;
14136 this._promise._pushContext();
14137 var result = tryCatch(this._generator.next).call(this._generator, value);
14138 this._promise._popContext();
14139 this._continue(result);
14140};
14141
14142PromiseSpawn.prototype._promiseRejected = function(reason) {
14143 this._yieldedPromise = null;
14144 this._promise._attachExtraTrace(reason);
14145 this._promise._pushContext();
14146 var result = tryCatch(this._generator["throw"])
14147 .call(this._generator, reason);
14148 this._promise._popContext();
14149 this._continue(result);
14150};
14151
14152PromiseSpawn.prototype._resultCancelled = function() {
14153 if (this._yieldedPromise instanceof Promise) {
14154 var promise = this._yieldedPromise;
14155 this._yieldedPromise = null;
14156 promise.cancel();
14157 }
14158};
14159
14160PromiseSpawn.prototype.promise = function () {
14161 return this._promise;
14162};
14163
14164PromiseSpawn.prototype._run = function () {
14165 this._generator = this._generatorFunction.call(this._receiver);
14166 this._receiver =
14167 this._generatorFunction = undefined;
14168 this._promiseFulfilled(undefined);
14169};
14170
14171PromiseSpawn.prototype._continue = function (result) {
14172 var promise = this._promise;
14173 if (result === errorObj) {
14174 this._cleanup();
14175 if (this._cancellationPhase) {
14176 return promise.cancel();
14177 } else {
14178 return promise._rejectCallback(result.e, false);
14179 }
14180 }
14181
14182 var value = result.value;
14183 if (result.done === true) {
14184 this._cleanup();
14185 if (this._cancellationPhase) {
14186 return promise.cancel();
14187 } else {
14188 return promise._resolveCallback(value);
14189 }
14190 } else {
14191 var maybePromise = tryConvertToPromise(value, this._promise);
14192 if (!(maybePromise instanceof Promise)) {
14193 maybePromise =
14194 promiseFromYieldHandler(maybePromise,
14195 this._yieldHandlers,
14196 this._promise);
14197 if (maybePromise === null) {
14198 this._promiseRejected(
14199 new TypeError(
14200 "A value %s was yielded that could not be treated as a promise\u000a\u000a See http://goo.gl/MqrFmX\u000a\u000a".replace("%s", String(value)) +
14201 "From coroutine:\u000a" +
14202 this._stack.split("\n").slice(1, -7).join("\n")
14203 )
14204 );
14205 return;
14206 }
14207 }
14208 maybePromise = maybePromise._target();
14209 var bitField = maybePromise._bitField;
14210 ;
14211 if (((bitField & 50397184) === 0)) {
14212 this._yieldedPromise = maybePromise;
14213 maybePromise._proxy(this, null);
14214 } else if (((bitField & 33554432) !== 0)) {
14215 Promise._async.invoke(
14216 this._promiseFulfilled, this, maybePromise._value()
14217 );
14218 } else if (((bitField & 16777216) !== 0)) {
14219 Promise._async.invoke(
14220 this._promiseRejected, this, maybePromise._reason()
14221 );
14222 } else {
14223 this._promiseCancelled();
14224 }
14225 }
14226};
14227
14228Promise.coroutine = function (generatorFunction, options) {
14229 if (typeof generatorFunction !== "function") {
14230 throw new TypeError("generatorFunction must be a function\u000a\u000a See http://goo.gl/MqrFmX\u000a");
14231 }
14232 var yieldHandler = Object(options).yieldHandler;
14233 var PromiseSpawn$ = PromiseSpawn;
14234 var stack = new Error().stack;
14235 return function () {
14236 var generator = generatorFunction.apply(this, arguments);
14237 var spawn = new PromiseSpawn$(undefined, undefined, yieldHandler,
14238 stack);
14239 var ret = spawn.promise();
14240 spawn._generator = generator;
14241 spawn._promiseFulfilled(undefined);
14242 return ret;
14243 };
14244};
14245
14246Promise.coroutine.addYieldHandler = function(fn) {
14247 if (typeof fn !== "function") {
14248 throw new TypeError("expecting a function but got " + util.classString(fn));
14249 }
14250 yieldHandlers.push(fn);
14251};
14252
14253Promise.spawn = function (generatorFunction) {
14254 debug.deprecated("Promise.spawn()", "Promise.coroutine()");
14255 if (typeof generatorFunction !== "function") {
14256 return apiRejection("generatorFunction must be a function\u000a\u000a See http://goo.gl/MqrFmX\u000a");
14257 }
14258 var spawn = new PromiseSpawn(generatorFunction, this);
14259 var ret = spawn.promise();
14260 spawn._run(Promise.spawn);
14261 return ret;
14262};
14263};
14264
14265},{"./errors":12,"./util":36}],17:[function(_dereq_,module,exports){
14266"use strict";
14267module.exports =
14268function(Promise, PromiseArray, tryConvertToPromise, INTERNAL, async,
14269 getDomain) {
14270var util = _dereq_("./util");
14271var canEvaluate = util.canEvaluate;
14272var tryCatch = util.tryCatch;
14273var errorObj = util.errorObj;
14274var reject;
14275
14276if (!true) {
14277if (canEvaluate) {
14278 var thenCallback = function(i) {
14279 return new Function("value", "holder", " \n\
14280 'use strict'; \n\
14281 holder.pIndex = value; \n\
14282 holder.checkFulfillment(this); \n\
14283 ".replace(/Index/g, i));
14284 };
14285
14286 var promiseSetter = function(i) {
14287 return new Function("promise", "holder", " \n\
14288 'use strict'; \n\
14289 holder.pIndex = promise; \n\
14290 ".replace(/Index/g, i));
14291 };
14292
14293 var generateHolderClass = function(total) {
14294 var props = new Array(total);
14295 for (var i = 0; i < props.length; ++i) {
14296 props[i] = "this.p" + (i+1);
14297 }
14298 var assignment = props.join(" = ") + " = null;";
14299 var cancellationCode= "var promise;\n" + props.map(function(prop) {
14300 return " \n\
14301 promise = " + prop + "; \n\
14302 if (promise instanceof Promise) { \n\
14303 promise.cancel(); \n\
14304 } \n\
14305 ";
14306 }).join("\n");
14307 var passedArguments = props.join(", ");
14308 var name = "Holder$" + total;
14309
14310
14311 var code = "return function(tryCatch, errorObj, Promise, async) { \n\
14312 'use strict'; \n\
14313 function [TheName](fn) { \n\
14314 [TheProperties] \n\
14315 this.fn = fn; \n\
14316 this.asyncNeeded = true; \n\
14317 this.now = 0; \n\
14318 } \n\
14319 \n\
14320 [TheName].prototype._callFunction = function(promise) { \n\
14321 promise._pushContext(); \n\
14322 var ret = tryCatch(this.fn)([ThePassedArguments]); \n\
14323 promise._popContext(); \n\
14324 if (ret === errorObj) { \n\
14325 promise._rejectCallback(ret.e, false); \n\
14326 } else { \n\
14327 promise._resolveCallback(ret); \n\
14328 } \n\
14329 }; \n\
14330 \n\
14331 [TheName].prototype.checkFulfillment = function(promise) { \n\
14332 var now = ++this.now; \n\
14333 if (now === [TheTotal]) { \n\
14334 if (this.asyncNeeded) { \n\
14335 async.invoke(this._callFunction, this, promise); \n\
14336 } else { \n\
14337 this._callFunction(promise); \n\
14338 } \n\
14339 \n\
14340 } \n\
14341 }; \n\
14342 \n\
14343 [TheName].prototype._resultCancelled = function() { \n\
14344 [CancellationCode] \n\
14345 }; \n\
14346 \n\
14347 return [TheName]; \n\
14348 }(tryCatch, errorObj, Promise, async); \n\
14349 ";
14350
14351 code = code.replace(/\[TheName\]/g, name)
14352 .replace(/\[TheTotal\]/g, total)
14353 .replace(/\[ThePassedArguments\]/g, passedArguments)
14354 .replace(/\[TheProperties\]/g, assignment)
14355 .replace(/\[CancellationCode\]/g, cancellationCode);
14356
14357 return new Function("tryCatch", "errorObj", "Promise", "async", code)
14358 (tryCatch, errorObj, Promise, async);
14359 };
14360
14361 var holderClasses = [];
14362 var thenCallbacks = [];
14363 var promiseSetters = [];
14364
14365 for (var i = 0; i < 8; ++i) {
14366 holderClasses.push(generateHolderClass(i + 1));
14367 thenCallbacks.push(thenCallback(i + 1));
14368 promiseSetters.push(promiseSetter(i + 1));
14369 }
14370
14371 reject = function (reason) {
14372 this._reject(reason);
14373 };
14374}}
14375
14376Promise.join = function () {
14377 var last = arguments.length - 1;
14378 var fn;
14379 if (last > 0 && typeof arguments[last] === "function") {
14380 fn = arguments[last];
14381 if (!true) {
14382 if (last <= 8 && canEvaluate) {
14383 var ret = new Promise(INTERNAL);
14384 ret._captureStackTrace();
14385 var HolderClass = holderClasses[last - 1];
14386 var holder = new HolderClass(fn);
14387 var callbacks = thenCallbacks;
14388
14389 for (var i = 0; i < last; ++i) {
14390 var maybePromise = tryConvertToPromise(arguments[i], ret);
14391 if (maybePromise instanceof Promise) {
14392 maybePromise = maybePromise._target();
14393 var bitField = maybePromise._bitField;
14394 ;
14395 if (((bitField & 50397184) === 0)) {
14396 maybePromise._then(callbacks[i], reject,
14397 undefined, ret, holder);
14398 promiseSetters[i](maybePromise, holder);
14399 holder.asyncNeeded = false;
14400 } else if (((bitField & 33554432) !== 0)) {
14401 callbacks[i].call(ret,
14402 maybePromise._value(), holder);
14403 } else if (((bitField & 16777216) !== 0)) {
14404 ret._reject(maybePromise._reason());
14405 } else {
14406 ret._cancel();
14407 }
14408 } else {
14409 callbacks[i].call(ret, maybePromise, holder);
14410 }
14411 }
14412
14413 if (!ret._isFateSealed()) {
14414 if (holder.asyncNeeded) {
14415 var domain = getDomain();
14416 if (domain !== null) {
14417 holder.fn = util.domainBind(domain, holder.fn);
14418 }
14419 }
14420 ret._setAsyncGuaranteed();
14421 ret._setOnCancel(holder);
14422 }
14423 return ret;
14424 }
14425 }
14426 }
14427 var args = [].slice.call(arguments);;
14428 if (fn) args.pop();
14429 var ret = new PromiseArray(args).promise();
14430 return fn !== undefined ? ret.spread(fn) : ret;
14431};
14432
14433};
14434
14435},{"./util":36}],18:[function(_dereq_,module,exports){
14436"use strict";
14437module.exports = function(Promise,
14438 PromiseArray,
14439 apiRejection,
14440 tryConvertToPromise,
14441 INTERNAL,
14442 debug) {
14443var getDomain = Promise._getDomain;
14444var util = _dereq_("./util");
14445var tryCatch = util.tryCatch;
14446var errorObj = util.errorObj;
14447var async = Promise._async;
14448
14449function MappingPromiseArray(promises, fn, limit, _filter) {
14450 this.constructor$(promises);
14451 this._promise._captureStackTrace();
14452 var domain = getDomain();
14453 this._callback = domain === null ? fn : util.domainBind(domain, fn);
14454 this._preservedValues = _filter === INTERNAL
14455 ? new Array(this.length())
14456 : null;
14457 this._limit = limit;
14458 this._inFlight = 0;
14459 this._queue = [];
14460 async.invoke(this._asyncInit, this, undefined);
14461}
14462util.inherits(MappingPromiseArray, PromiseArray);
14463
14464MappingPromiseArray.prototype._asyncInit = function() {
14465 this._init$(undefined, -2);
14466};
14467
14468MappingPromiseArray.prototype._init = function () {};
14469
14470MappingPromiseArray.prototype._promiseFulfilled = function (value, index) {
14471 var values = this._values;
14472 var length = this.length();
14473 var preservedValues = this._preservedValues;
14474 var limit = this._limit;
14475
14476 if (index < 0) {
14477 index = (index * -1) - 1;
14478 values[index] = value;
14479 if (limit >= 1) {
14480 this._inFlight--;
14481 this._drainQueue();
14482 if (this._isResolved()) return true;
14483 }
14484 } else {
14485 if (limit >= 1 && this._inFlight >= limit) {
14486 values[index] = value;
14487 this._queue.push(index);
14488 return false;
14489 }
14490 if (preservedValues !== null) preservedValues[index] = value;
14491
14492 var promise = this._promise;
14493 var callback = this._callback;
14494 var receiver = promise._boundValue();
14495 promise._pushContext();
14496 var ret = tryCatch(callback).call(receiver, value, index, length);
14497 var promiseCreated = promise._popContext();
14498 debug.checkForgottenReturns(
14499 ret,
14500 promiseCreated,
14501 preservedValues !== null ? "Promise.filter" : "Promise.map",
14502 promise
14503 );
14504 if (ret === errorObj) {
14505 this._reject(ret.e);
14506 return true;
14507 }
14508
14509 var maybePromise = tryConvertToPromise(ret, this._promise);
14510 if (maybePromise instanceof Promise) {
14511 maybePromise = maybePromise._target();
14512 var bitField = maybePromise._bitField;
14513 ;
14514 if (((bitField & 50397184) === 0)) {
14515 if (limit >= 1) this._inFlight++;
14516 values[index] = maybePromise;
14517 maybePromise._proxy(this, (index + 1) * -1);
14518 return false;
14519 } else if (((bitField & 33554432) !== 0)) {
14520 ret = maybePromise._value();
14521 } else if (((bitField & 16777216) !== 0)) {
14522 this._reject(maybePromise._reason());
14523 return true;
14524 } else {
14525 this._cancel();
14526 return true;
14527 }
14528 }
14529 values[index] = ret;
14530 }
14531 var totalResolved = ++this._totalResolved;
14532 if (totalResolved >= length) {
14533 if (preservedValues !== null) {
14534 this._filter(values, preservedValues);
14535 } else {
14536 this._resolve(values);
14537 }
14538 return true;
14539 }
14540 return false;
14541};
14542
14543MappingPromiseArray.prototype._drainQueue = function () {
14544 var queue = this._queue;
14545 var limit = this._limit;
14546 var values = this._values;
14547 while (queue.length > 0 && this._inFlight < limit) {
14548 if (this._isResolved()) return;
14549 var index = queue.pop();
14550 this._promiseFulfilled(values[index], index);
14551 }
14552};
14553
14554MappingPromiseArray.prototype._filter = function (booleans, values) {
14555 var len = values.length;
14556 var ret = new Array(len);
14557 var j = 0;
14558 for (var i = 0; i < len; ++i) {
14559 if (booleans[i]) ret[j++] = values[i];
14560 }
14561 ret.length = j;
14562 this._resolve(ret);
14563};
14564
14565MappingPromiseArray.prototype.preservedValues = function () {
14566 return this._preservedValues;
14567};
14568
14569function map(promises, fn, options, _filter) {
14570 if (typeof fn !== "function") {
14571 return apiRejection("expecting a function but got " + util.classString(fn));
14572 }
14573
14574 var limit = 0;
14575 if (options !== undefined) {
14576 if (typeof options === "object" && options !== null) {
14577 if (typeof options.concurrency !== "number") {
14578 return Promise.reject(
14579 new TypeError("'concurrency' must be a number but it is " +
14580 util.classString(options.concurrency)));
14581 }
14582 limit = options.concurrency;
14583 } else {
14584 return Promise.reject(new TypeError(
14585 "options argument must be an object but it is " +
14586 util.classString(options)));
14587 }
14588 }
14589 limit = typeof limit === "number" &&
14590 isFinite(limit) && limit >= 1 ? limit : 0;
14591 return new MappingPromiseArray(promises, fn, limit, _filter).promise();
14592}
14593
14594Promise.prototype.map = function (fn, options) {
14595 return map(this, fn, options, null);
14596};
14597
14598Promise.map = function (promises, fn, options, _filter) {
14599 return map(promises, fn, options, _filter);
14600};
14601
14602
14603};
14604
14605},{"./util":36}],19:[function(_dereq_,module,exports){
14606"use strict";
14607module.exports =
14608function(Promise, INTERNAL, tryConvertToPromise, apiRejection, debug) {
14609var util = _dereq_("./util");
14610var tryCatch = util.tryCatch;
14611
14612Promise.method = function (fn) {
14613 if (typeof fn !== "function") {
14614 throw new Promise.TypeError("expecting a function but got " + util.classString(fn));
14615 }
14616 return function () {
14617 var ret = new Promise(INTERNAL);
14618 ret._captureStackTrace();
14619 ret._pushContext();
14620 var value = tryCatch(fn).apply(this, arguments);
14621 var promiseCreated = ret._popContext();
14622 debug.checkForgottenReturns(
14623 value, promiseCreated, "Promise.method", ret);
14624 ret._resolveFromSyncValue(value);
14625 return ret;
14626 };
14627};
14628
14629Promise.attempt = Promise["try"] = function (fn) {
14630 if (typeof fn !== "function") {
14631 return apiRejection("expecting a function but got " + util.classString(fn));
14632 }
14633 var ret = new Promise(INTERNAL);
14634 ret._captureStackTrace();
14635 ret._pushContext();
14636 var value;
14637 if (arguments.length > 1) {
14638 debug.deprecated("calling Promise.try with more than 1 argument");
14639 var arg = arguments[1];
14640 var ctx = arguments[2];
14641 value = util.isArray(arg) ? tryCatch(fn).apply(ctx, arg)
14642 : tryCatch(fn).call(ctx, arg);
14643 } else {
14644 value = tryCatch(fn)();
14645 }
14646 var promiseCreated = ret._popContext();
14647 debug.checkForgottenReturns(
14648 value, promiseCreated, "Promise.try", ret);
14649 ret._resolveFromSyncValue(value);
14650 return ret;
14651};
14652
14653Promise.prototype._resolveFromSyncValue = function (value) {
14654 if (value === util.errorObj) {
14655 this._rejectCallback(value.e, false);
14656 } else {
14657 this._resolveCallback(value, true);
14658 }
14659};
14660};
14661
14662},{"./util":36}],20:[function(_dereq_,module,exports){
14663"use strict";
14664var util = _dereq_("./util");
14665var maybeWrapAsError = util.maybeWrapAsError;
14666var errors = _dereq_("./errors");
14667var OperationalError = errors.OperationalError;
14668var es5 = _dereq_("./es5");
14669
14670function isUntypedError(obj) {
14671 return obj instanceof Error &&
14672 es5.getPrototypeOf(obj) === Error.prototype;
14673}
14674
14675var rErrorKey = /^(?:name|message|stack|cause)$/;
14676function wrapAsOperationalError(obj) {
14677 var ret;
14678 if (isUntypedError(obj)) {
14679 ret = new OperationalError(obj);
14680 ret.name = obj.name;
14681 ret.message = obj.message;
14682 ret.stack = obj.stack;
14683 var keys = es5.keys(obj);
14684 for (var i = 0; i < keys.length; ++i) {
14685 var key = keys[i];
14686 if (!rErrorKey.test(key)) {
14687 ret[key] = obj[key];
14688 }
14689 }
14690 return ret;
14691 }
14692 util.markAsOriginatingFromRejection(obj);
14693 return obj;
14694}
14695
14696function nodebackForPromise(promise, multiArgs) {
14697 return function(err, value) {
14698 if (promise === null) return;
14699 if (err) {
14700 var wrapped = wrapAsOperationalError(maybeWrapAsError(err));
14701 promise._attachExtraTrace(wrapped);
14702 promise._reject(wrapped);
14703 } else if (!multiArgs) {
14704 promise._fulfill(value);
14705 } else {
14706 var args = [].slice.call(arguments, 1);;
14707 promise._fulfill(args);
14708 }
14709 promise = null;
14710 };
14711}
14712
14713module.exports = nodebackForPromise;
14714
14715},{"./errors":12,"./es5":13,"./util":36}],21:[function(_dereq_,module,exports){
14716"use strict";
14717module.exports = function(Promise) {
14718var util = _dereq_("./util");
14719var async = Promise._async;
14720var tryCatch = util.tryCatch;
14721var errorObj = util.errorObj;
14722
14723function spreadAdapter(val, nodeback) {
14724 var promise = this;
14725 if (!util.isArray(val)) return successAdapter.call(promise, val, nodeback);
14726 var ret =
14727 tryCatch(nodeback).apply(promise._boundValue(), [null].concat(val));
14728 if (ret === errorObj) {
14729 async.throwLater(ret.e);
14730 }
14731}
14732
14733function successAdapter(val, nodeback) {
14734 var promise = this;
14735 var receiver = promise._boundValue();
14736 var ret = val === undefined
14737 ? tryCatch(nodeback).call(receiver, null)
14738 : tryCatch(nodeback).call(receiver, null, val);
14739 if (ret === errorObj) {
14740 async.throwLater(ret.e);
14741 }
14742}
14743function errorAdapter(reason, nodeback) {
14744 var promise = this;
14745 if (!reason) {
14746 var newReason = new Error(reason + "");
14747 newReason.cause = reason;
14748 reason = newReason;
14749 }
14750 var ret = tryCatch(nodeback).call(promise._boundValue(), reason);
14751 if (ret === errorObj) {
14752 async.throwLater(ret.e);
14753 }
14754}
14755
14756Promise.prototype.asCallback = Promise.prototype.nodeify = function (nodeback,
14757 options) {
14758 if (typeof nodeback == "function") {
14759 var adapter = successAdapter;
14760 if (options !== undefined && Object(options).spread) {
14761 adapter = spreadAdapter;
14762 }
14763 this._then(
14764 adapter,
14765 errorAdapter,
14766 undefined,
14767 this,
14768 nodeback
14769 );
14770 }
14771 return this;
14772};
14773};
14774
14775},{"./util":36}],22:[function(_dereq_,module,exports){
14776"use strict";
14777module.exports = function() {
14778var makeSelfResolutionError = function () {
14779 return new TypeError("circular promise resolution chain\u000a\u000a See http://goo.gl/MqrFmX\u000a");
14780};
14781var reflectHandler = function() {
14782 return new Promise.PromiseInspection(this._target());
14783};
14784var apiRejection = function(msg) {
14785 return Promise.reject(new TypeError(msg));
14786};
14787function Proxyable() {}
14788var UNDEFINED_BINDING = {};
14789var util = _dereq_("./util");
14790
14791var getDomain;
14792if (util.isNode) {
14793 getDomain = function() {
14794 var ret = process.domain;
14795 if (ret === undefined) ret = null;
14796 return ret;
14797 };
14798} else {
14799 getDomain = function() {
14800 return null;
14801 };
14802}
14803util.notEnumerableProp(Promise, "_getDomain", getDomain);
14804
14805var es5 = _dereq_("./es5");
14806var Async = _dereq_("./async");
14807var async = new Async();
14808es5.defineProperty(Promise, "_async", {value: async});
14809var errors = _dereq_("./errors");
14810var TypeError = Promise.TypeError = errors.TypeError;
14811Promise.RangeError = errors.RangeError;
14812var CancellationError = Promise.CancellationError = errors.CancellationError;
14813Promise.TimeoutError = errors.TimeoutError;
14814Promise.OperationalError = errors.OperationalError;
14815Promise.RejectionError = errors.OperationalError;
14816Promise.AggregateError = errors.AggregateError;
14817var INTERNAL = function(){};
14818var APPLY = {};
14819var NEXT_FILTER = {};
14820var tryConvertToPromise = _dereq_("./thenables")(Promise, INTERNAL);
14821var PromiseArray =
14822 _dereq_("./promise_array")(Promise, INTERNAL,
14823 tryConvertToPromise, apiRejection, Proxyable);
14824var Context = _dereq_("./context")(Promise);
14825 /*jshint unused:false*/
14826var createContext = Context.create;
14827var debug = _dereq_("./debuggability")(Promise, Context);
14828var CapturedTrace = debug.CapturedTrace;
14829var PassThroughHandlerContext =
14830 _dereq_("./finally")(Promise, tryConvertToPromise, NEXT_FILTER);
14831var catchFilter = _dereq_("./catch_filter")(NEXT_FILTER);
14832var nodebackForPromise = _dereq_("./nodeback");
14833var errorObj = util.errorObj;
14834var tryCatch = util.tryCatch;
14835function check(self, executor) {
14836 if (self == null || self.constructor !== Promise) {
14837 throw new TypeError("the promise constructor cannot be invoked directly\u000a\u000a See http://goo.gl/MqrFmX\u000a");
14838 }
14839 if (typeof executor !== "function") {
14840 throw new TypeError("expecting a function but got " + util.classString(executor));
14841 }
14842
14843}
14844
14845function Promise(executor) {
14846 if (executor !== INTERNAL) {
14847 check(this, executor);
14848 }
14849 this._bitField = 0;
14850 this._fulfillmentHandler0 = undefined;
14851 this._rejectionHandler0 = undefined;
14852 this._promise0 = undefined;
14853 this._receiver0 = undefined;
14854 this._resolveFromExecutor(executor);
14855 this._promiseCreated();
14856 this._fireEvent("promiseCreated", this);
14857}
14858
14859Promise.prototype.toString = function () {
14860 return "[object Promise]";
14861};
14862
14863Promise.prototype.caught = Promise.prototype["catch"] = function (fn) {
14864 var len = arguments.length;
14865 if (len > 1) {
14866 var catchInstances = new Array(len - 1),
14867 j = 0, i;
14868 for (i = 0; i < len - 1; ++i) {
14869 var item = arguments[i];
14870 if (util.isObject(item)) {
14871 catchInstances[j++] = item;
14872 } else {
14873 return apiRejection("Catch statement predicate: " +
14874 "expecting an object but got " + util.classString(item));
14875 }
14876 }
14877 catchInstances.length = j;
14878 fn = arguments[i];
14879
14880 if (typeof fn !== "function") {
14881 throw new TypeError("The last argument to .catch() " +
14882 "must be a function, got " + util.toString(fn));
14883 }
14884 return this.then(undefined, catchFilter(catchInstances, fn, this));
14885 }
14886 return this.then(undefined, fn);
14887};
14888
14889Promise.prototype.reflect = function () {
14890 return this._then(reflectHandler,
14891 reflectHandler, undefined, this, undefined);
14892};
14893
14894Promise.prototype.then = function (didFulfill, didReject) {
14895 if (debug.warnings() && arguments.length > 0 &&
14896 typeof didFulfill !== "function" &&
14897 typeof didReject !== "function") {
14898 var msg = ".then() only accepts functions but was passed: " +
14899 util.classString(didFulfill);
14900 if (arguments.length > 1) {
14901 msg += ", " + util.classString(didReject);
14902 }
14903 this._warn(msg);
14904 }
14905 return this._then(didFulfill, didReject, undefined, undefined, undefined);
14906};
14907
14908Promise.prototype.done = function (didFulfill, didReject) {
14909 var promise =
14910 this._then(didFulfill, didReject, undefined, undefined, undefined);
14911 promise._setIsFinal();
14912};
14913
14914Promise.prototype.spread = function (fn) {
14915 if (typeof fn !== "function") {
14916 return apiRejection("expecting a function but got " + util.classString(fn));
14917 }
14918 return this.all()._then(fn, undefined, undefined, APPLY, undefined);
14919};
14920
14921Promise.prototype.toJSON = function () {
14922 var ret = {
14923 isFulfilled: false,
14924 isRejected: false,
14925 fulfillmentValue: undefined,
14926 rejectionReason: undefined
14927 };
14928 if (this.isFulfilled()) {
14929 ret.fulfillmentValue = this.value();
14930 ret.isFulfilled = true;
14931 } else if (this.isRejected()) {
14932 ret.rejectionReason = this.reason();
14933 ret.isRejected = true;
14934 }
14935 return ret;
14936};
14937
14938Promise.prototype.all = function () {
14939 if (arguments.length > 0) {
14940 this._warn(".all() was passed arguments but it does not take any");
14941 }
14942 return new PromiseArray(this).promise();
14943};
14944
14945Promise.prototype.error = function (fn) {
14946 return this.caught(util.originatesFromRejection, fn);
14947};
14948
14949Promise.getNewLibraryCopy = module.exports;
14950
14951Promise.is = function (val) {
14952 return val instanceof Promise;
14953};
14954
14955Promise.fromNode = Promise.fromCallback = function(fn) {
14956 var ret = new Promise(INTERNAL);
14957 ret._captureStackTrace();
14958 var multiArgs = arguments.length > 1 ? !!Object(arguments[1]).multiArgs
14959 : false;
14960 var result = tryCatch(fn)(nodebackForPromise(ret, multiArgs));
14961 if (result === errorObj) {
14962 ret._rejectCallback(result.e, true);
14963 }
14964 if (!ret._isFateSealed()) ret._setAsyncGuaranteed();
14965 return ret;
14966};
14967
14968Promise.all = function (promises) {
14969 return new PromiseArray(promises).promise();
14970};
14971
14972Promise.cast = function (obj) {
14973 var ret = tryConvertToPromise(obj);
14974 if (!(ret instanceof Promise)) {
14975 ret = new Promise(INTERNAL);
14976 ret._captureStackTrace();
14977 ret._setFulfilled();
14978 ret._rejectionHandler0 = obj;
14979 }
14980 return ret;
14981};
14982
14983Promise.resolve = Promise.fulfilled = Promise.cast;
14984
14985Promise.reject = Promise.rejected = function (reason) {
14986 var ret = new Promise(INTERNAL);
14987 ret._captureStackTrace();
14988 ret._rejectCallback(reason, true);
14989 return ret;
14990};
14991
14992Promise.setScheduler = function(fn) {
14993 if (typeof fn !== "function") {
14994 throw new TypeError("expecting a function but got " + util.classString(fn));
14995 }
14996 return async.setScheduler(fn);
14997};
14998
14999Promise.prototype._then = function (
15000 didFulfill,
15001 didReject,
15002 _, receiver,
15003 internalData
15004) {
15005 var haveInternalData = internalData !== undefined;
15006 var promise = haveInternalData ? internalData : new Promise(INTERNAL);
15007 var target = this._target();
15008 var bitField = target._bitField;
15009
15010 if (!haveInternalData) {
15011 promise._propagateFrom(this, 3);
15012 promise._captureStackTrace();
15013 if (receiver === undefined &&
15014 ((this._bitField & 2097152) !== 0)) {
15015 if (!((bitField & 50397184) === 0)) {
15016 receiver = this._boundValue();
15017 } else {
15018 receiver = target === this ? undefined : this._boundTo;
15019 }
15020 }
15021 this._fireEvent("promiseChained", this, promise);
15022 }
15023
15024 var domain = getDomain();
15025 if (!((bitField & 50397184) === 0)) {
15026 var handler, value, settler = target._settlePromiseCtx;
15027 if (((bitField & 33554432) !== 0)) {
15028 value = target._rejectionHandler0;
15029 handler = didFulfill;
15030 } else if (((bitField & 16777216) !== 0)) {
15031 value = target._fulfillmentHandler0;
15032 handler = didReject;
15033 target._unsetRejectionIsUnhandled();
15034 } else {
15035 settler = target._settlePromiseLateCancellationObserver;
15036 value = new CancellationError("late cancellation observer");
15037 target._attachExtraTrace(value);
15038 handler = didReject;
15039 }
15040
15041 async.invoke(settler, target, {
15042 handler: domain === null ? handler
15043 : (typeof handler === "function" &&
15044 util.domainBind(domain, handler)),
15045 promise: promise,
15046 receiver: receiver,
15047 value: value
15048 });
15049 } else {
15050 target._addCallbacks(didFulfill, didReject, promise, receiver, domain);
15051 }
15052
15053 return promise;
15054};
15055
15056Promise.prototype._length = function () {
15057 return this._bitField & 65535;
15058};
15059
15060Promise.prototype._isFateSealed = function () {
15061 return (this._bitField & 117506048) !== 0;
15062};
15063
15064Promise.prototype._isFollowing = function () {
15065 return (this._bitField & 67108864) === 67108864;
15066};
15067
15068Promise.prototype._setLength = function (len) {
15069 this._bitField = (this._bitField & -65536) |
15070 (len & 65535);
15071};
15072
15073Promise.prototype._setFulfilled = function () {
15074 this._bitField = this._bitField | 33554432;
15075 this._fireEvent("promiseFulfilled", this);
15076};
15077
15078Promise.prototype._setRejected = function () {
15079 this._bitField = this._bitField | 16777216;
15080 this._fireEvent("promiseRejected", this);
15081};
15082
15083Promise.prototype._setFollowing = function () {
15084 this._bitField = this._bitField | 67108864;
15085 this._fireEvent("promiseResolved", this);
15086};
15087
15088Promise.prototype._setIsFinal = function () {
15089 this._bitField = this._bitField | 4194304;
15090};
15091
15092Promise.prototype._isFinal = function () {
15093 return (this._bitField & 4194304) > 0;
15094};
15095
15096Promise.prototype._unsetCancelled = function() {
15097 this._bitField = this._bitField & (~65536);
15098};
15099
15100Promise.prototype._setCancelled = function() {
15101 this._bitField = this._bitField | 65536;
15102 this._fireEvent("promiseCancelled", this);
15103};
15104
15105Promise.prototype._setWillBeCancelled = function() {
15106 this._bitField = this._bitField | 8388608;
15107};
15108
15109Promise.prototype._setAsyncGuaranteed = function() {
15110 if (async.hasCustomScheduler()) return;
15111 this._bitField = this._bitField | 134217728;
15112};
15113
15114Promise.prototype._receiverAt = function (index) {
15115 var ret = index === 0 ? this._receiver0 : this[
15116 index * 4 - 4 + 3];
15117 if (ret === UNDEFINED_BINDING) {
15118 return undefined;
15119 } else if (ret === undefined && this._isBound()) {
15120 return this._boundValue();
15121 }
15122 return ret;
15123};
15124
15125Promise.prototype._promiseAt = function (index) {
15126 return this[
15127 index * 4 - 4 + 2];
15128};
15129
15130Promise.prototype._fulfillmentHandlerAt = function (index) {
15131 return this[
15132 index * 4 - 4 + 0];
15133};
15134
15135Promise.prototype._rejectionHandlerAt = function (index) {
15136 return this[
15137 index * 4 - 4 + 1];
15138};
15139
15140Promise.prototype._boundValue = function() {};
15141
15142Promise.prototype._migrateCallback0 = function (follower) {
15143 var bitField = follower._bitField;
15144 var fulfill = follower._fulfillmentHandler0;
15145 var reject = follower._rejectionHandler0;
15146 var promise = follower._promise0;
15147 var receiver = follower._receiverAt(0);
15148 if (receiver === undefined) receiver = UNDEFINED_BINDING;
15149 this._addCallbacks(fulfill, reject, promise, receiver, null);
15150};
15151
15152Promise.prototype._migrateCallbackAt = function (follower, index) {
15153 var fulfill = follower._fulfillmentHandlerAt(index);
15154 var reject = follower._rejectionHandlerAt(index);
15155 var promise = follower._promiseAt(index);
15156 var receiver = follower._receiverAt(index);
15157 if (receiver === undefined) receiver = UNDEFINED_BINDING;
15158 this._addCallbacks(fulfill, reject, promise, receiver, null);
15159};
15160
15161Promise.prototype._addCallbacks = function (
15162 fulfill,
15163 reject,
15164 promise,
15165 receiver,
15166 domain
15167) {
15168 var index = this._length();
15169
15170 if (index >= 65535 - 4) {
15171 index = 0;
15172 this._setLength(0);
15173 }
15174
15175 if (index === 0) {
15176 this._promise0 = promise;
15177 this._receiver0 = receiver;
15178 if (typeof fulfill === "function") {
15179 this._fulfillmentHandler0 =
15180 domain === null ? fulfill : util.domainBind(domain, fulfill);
15181 }
15182 if (typeof reject === "function") {
15183 this._rejectionHandler0 =
15184 domain === null ? reject : util.domainBind(domain, reject);
15185 }
15186 } else {
15187 var base = index * 4 - 4;
15188 this[base + 2] = promise;
15189 this[base + 3] = receiver;
15190 if (typeof fulfill === "function") {
15191 this[base + 0] =
15192 domain === null ? fulfill : util.domainBind(domain, fulfill);
15193 }
15194 if (typeof reject === "function") {
15195 this[base + 1] =
15196 domain === null ? reject : util.domainBind(domain, reject);
15197 }
15198 }
15199 this._setLength(index + 1);
15200 return index;
15201};
15202
15203Promise.prototype._proxy = function (proxyable, arg) {
15204 this._addCallbacks(undefined, undefined, arg, proxyable, null);
15205};
15206
15207Promise.prototype._resolveCallback = function(value, shouldBind) {
15208 if (((this._bitField & 117506048) !== 0)) return;
15209 if (value === this)
15210 return this._rejectCallback(makeSelfResolutionError(), false);
15211 var maybePromise = tryConvertToPromise(value, this);
15212 if (!(maybePromise instanceof Promise)) return this._fulfill(value);
15213
15214 if (shouldBind) this._propagateFrom(maybePromise, 2);
15215
15216 var promise = maybePromise._target();
15217
15218 if (promise === this) {
15219 this._reject(makeSelfResolutionError());
15220 return;
15221 }
15222
15223 var bitField = promise._bitField;
15224 if (((bitField & 50397184) === 0)) {
15225 var len = this._length();
15226 if (len > 0) promise._migrateCallback0(this);
15227 for (var i = 1; i < len; ++i) {
15228 promise._migrateCallbackAt(this, i);
15229 }
15230 this._setFollowing();
15231 this._setLength(0);
15232 this._setFollowee(promise);
15233 } else if (((bitField & 33554432) !== 0)) {
15234 this._fulfill(promise._value());
15235 } else if (((bitField & 16777216) !== 0)) {
15236 this._reject(promise._reason());
15237 } else {
15238 var reason = new CancellationError("late cancellation observer");
15239 promise._attachExtraTrace(reason);
15240 this._reject(reason);
15241 }
15242};
15243
15244Promise.prototype._rejectCallback =
15245function(reason, synchronous, ignoreNonErrorWarnings) {
15246 var trace = util.ensureErrorObject(reason);
15247 var hasStack = trace === reason;
15248 if (!hasStack && !ignoreNonErrorWarnings && debug.warnings()) {
15249 var message = "a promise was rejected with a non-error: " +
15250 util.classString(reason);
15251 this._warn(message, true);
15252 }
15253 this._attachExtraTrace(trace, synchronous ? hasStack : false);
15254 this._reject(reason);
15255};
15256
15257Promise.prototype._resolveFromExecutor = function (executor) {
15258 if (executor === INTERNAL) return;
15259 var promise = this;
15260 this._captureStackTrace();
15261 this._pushContext();
15262 var synchronous = true;
15263 var r = this._execute(executor, function(value) {
15264 promise._resolveCallback(value);
15265 }, function (reason) {
15266 promise._rejectCallback(reason, synchronous);
15267 });
15268 synchronous = false;
15269 this._popContext();
15270
15271 if (r !== undefined) {
15272 promise._rejectCallback(r, true);
15273 }
15274};
15275
15276Promise.prototype._settlePromiseFromHandler = function (
15277 handler, receiver, value, promise
15278) {
15279 var bitField = promise._bitField;
15280 if (((bitField & 65536) !== 0)) return;
15281 promise._pushContext();
15282 var x;
15283 if (receiver === APPLY) {
15284 if (!value || typeof value.length !== "number") {
15285 x = errorObj;
15286 x.e = new TypeError("cannot .spread() a non-array: " +
15287 util.classString(value));
15288 } else {
15289 x = tryCatch(handler).apply(this._boundValue(), value);
15290 }
15291 } else {
15292 x = tryCatch(handler).call(receiver, value);
15293 }
15294 var promiseCreated = promise._popContext();
15295 bitField = promise._bitField;
15296 if (((bitField & 65536) !== 0)) return;
15297
15298 if (x === NEXT_FILTER) {
15299 promise._reject(value);
15300 } else if (x === errorObj) {
15301 promise._rejectCallback(x.e, false);
15302 } else {
15303 debug.checkForgottenReturns(x, promiseCreated, "", promise, this);
15304 promise._resolveCallback(x);
15305 }
15306};
15307
15308Promise.prototype._target = function() {
15309 var ret = this;
15310 while (ret._isFollowing()) ret = ret._followee();
15311 return ret;
15312};
15313
15314Promise.prototype._followee = function() {
15315 return this._rejectionHandler0;
15316};
15317
15318Promise.prototype._setFollowee = function(promise) {
15319 this._rejectionHandler0 = promise;
15320};
15321
15322Promise.prototype._settlePromise = function(promise, handler, receiver, value) {
15323 var isPromise = promise instanceof Promise;
15324 var bitField = this._bitField;
15325 var asyncGuaranteed = ((bitField & 134217728) !== 0);
15326 if (((bitField & 65536) !== 0)) {
15327 if (isPromise) promise._invokeInternalOnCancel();
15328
15329 if (receiver instanceof PassThroughHandlerContext &&
15330 receiver.isFinallyHandler()) {
15331 receiver.cancelPromise = promise;
15332 if (tryCatch(handler).call(receiver, value) === errorObj) {
15333 promise._reject(errorObj.e);
15334 }
15335 } else if (handler === reflectHandler) {
15336 promise._fulfill(reflectHandler.call(receiver));
15337 } else if (receiver instanceof Proxyable) {
15338 receiver._promiseCancelled(promise);
15339 } else if (isPromise || promise instanceof PromiseArray) {
15340 promise._cancel();
15341 } else {
15342 receiver.cancel();
15343 }
15344 } else if (typeof handler === "function") {
15345 if (!isPromise) {
15346 handler.call(receiver, value, promise);
15347 } else {
15348 if (asyncGuaranteed) promise._setAsyncGuaranteed();
15349 this._settlePromiseFromHandler(handler, receiver, value, promise);
15350 }
15351 } else if (receiver instanceof Proxyable) {
15352 if (!receiver._isResolved()) {
15353 if (((bitField & 33554432) !== 0)) {
15354 receiver._promiseFulfilled(value, promise);
15355 } else {
15356 receiver._promiseRejected(value, promise);
15357 }
15358 }
15359 } else if (isPromise) {
15360 if (asyncGuaranteed) promise._setAsyncGuaranteed();
15361 if (((bitField & 33554432) !== 0)) {
15362 promise._fulfill(value);
15363 } else {
15364 promise._reject(value);
15365 }
15366 }
15367};
15368
15369Promise.prototype._settlePromiseLateCancellationObserver = function(ctx) {
15370 var handler = ctx.handler;
15371 var promise = ctx.promise;
15372 var receiver = ctx.receiver;
15373 var value = ctx.value;
15374 if (typeof handler === "function") {
15375 if (!(promise instanceof Promise)) {
15376 handler.call(receiver, value, promise);
15377 } else {
15378 this._settlePromiseFromHandler(handler, receiver, value, promise);
15379 }
15380 } else if (promise instanceof Promise) {
15381 promise._reject(value);
15382 }
15383};
15384
15385Promise.prototype._settlePromiseCtx = function(ctx) {
15386 this._settlePromise(ctx.promise, ctx.handler, ctx.receiver, ctx.value);
15387};
15388
15389Promise.prototype._settlePromise0 = function(handler, value, bitField) {
15390 var promise = this._promise0;
15391 var receiver = this._receiverAt(0);
15392 this._promise0 = undefined;
15393 this._receiver0 = undefined;
15394 this._settlePromise(promise, handler, receiver, value);
15395};
15396
15397Promise.prototype._clearCallbackDataAtIndex = function(index) {
15398 var base = index * 4 - 4;
15399 this[base + 2] =
15400 this[base + 3] =
15401 this[base + 0] =
15402 this[base + 1] = undefined;
15403};
15404
15405Promise.prototype._fulfill = function (value) {
15406 var bitField = this._bitField;
15407 if (((bitField & 117506048) >>> 16)) return;
15408 if (value === this) {
15409 var err = makeSelfResolutionError();
15410 this._attachExtraTrace(err);
15411 return this._reject(err);
15412 }
15413 this._setFulfilled();
15414 this._rejectionHandler0 = value;
15415
15416 if ((bitField & 65535) > 0) {
15417 if (((bitField & 134217728) !== 0)) {
15418 this._settlePromises();
15419 } else {
15420 async.settlePromises(this);
15421 }
15422 this._dereferenceTrace();
15423 }
15424};
15425
15426Promise.prototype._reject = function (reason) {
15427 var bitField = this._bitField;
15428 if (((bitField & 117506048) >>> 16)) return;
15429 this._setRejected();
15430 this._fulfillmentHandler0 = reason;
15431
15432 if (this._isFinal()) {
15433 return async.fatalError(reason, util.isNode);
15434 }
15435
15436 if ((bitField & 65535) > 0) {
15437 async.settlePromises(this);
15438 } else {
15439 this._ensurePossibleRejectionHandled();
15440 }
15441};
15442
15443Promise.prototype._fulfillPromises = function (len, value) {
15444 for (var i = 1; i < len; i++) {
15445 var handler = this._fulfillmentHandlerAt(i);
15446 var promise = this._promiseAt(i);
15447 var receiver = this._receiverAt(i);
15448 this._clearCallbackDataAtIndex(i);
15449 this._settlePromise(promise, handler, receiver, value);
15450 }
15451};
15452
15453Promise.prototype._rejectPromises = function (len, reason) {
15454 for (var i = 1; i < len; i++) {
15455 var handler = this._rejectionHandlerAt(i);
15456 var promise = this._promiseAt(i);
15457 var receiver = this._receiverAt(i);
15458 this._clearCallbackDataAtIndex(i);
15459 this._settlePromise(promise, handler, receiver, reason);
15460 }
15461};
15462
15463Promise.prototype._settlePromises = function () {
15464 var bitField = this._bitField;
15465 var len = (bitField & 65535);
15466
15467 if (len > 0) {
15468 if (((bitField & 16842752) !== 0)) {
15469 var reason = this._fulfillmentHandler0;
15470 this._settlePromise0(this._rejectionHandler0, reason, bitField);
15471 this._rejectPromises(len, reason);
15472 } else {
15473 var value = this._rejectionHandler0;
15474 this._settlePromise0(this._fulfillmentHandler0, value, bitField);
15475 this._fulfillPromises(len, value);
15476 }
15477 this._setLength(0);
15478 }
15479 this._clearCancellationData();
15480};
15481
15482Promise.prototype._settledValue = function() {
15483 var bitField = this._bitField;
15484 if (((bitField & 33554432) !== 0)) {
15485 return this._rejectionHandler0;
15486 } else if (((bitField & 16777216) !== 0)) {
15487 return this._fulfillmentHandler0;
15488 }
15489};
15490
15491if (typeof Symbol !== "undefined" && Symbol.toStringTag) {
15492 es5.defineProperty(Promise.prototype, Symbol.toStringTag, {
15493 get: function () {
15494 return "Object";
15495 }
15496 });
15497}
15498
15499function deferResolve(v) {this.promise._resolveCallback(v);}
15500function deferReject(v) {this.promise._rejectCallback(v, false);}
15501
15502Promise.defer = Promise.pending = function() {
15503 debug.deprecated("Promise.defer", "new Promise");
15504 var promise = new Promise(INTERNAL);
15505 return {
15506 promise: promise,
15507 resolve: deferResolve,
15508 reject: deferReject
15509 };
15510};
15511
15512util.notEnumerableProp(Promise,
15513 "_makeSelfResolutionError",
15514 makeSelfResolutionError);
15515
15516_dereq_("./method")(Promise, INTERNAL, tryConvertToPromise, apiRejection,
15517 debug);
15518_dereq_("./bind")(Promise, INTERNAL, tryConvertToPromise, debug);
15519_dereq_("./cancel")(Promise, PromiseArray, apiRejection, debug);
15520_dereq_("./direct_resolve")(Promise);
15521_dereq_("./synchronous_inspection")(Promise);
15522_dereq_("./join")(
15523 Promise, PromiseArray, tryConvertToPromise, INTERNAL, async, getDomain);
15524Promise.Promise = Promise;
15525Promise.version = "3.5.5";
15526_dereq_('./call_get.js')(Promise);
15527_dereq_('./generators.js')(Promise, apiRejection, INTERNAL, tryConvertToPromise, Proxyable, debug);
15528_dereq_('./map.js')(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL, debug);
15529_dereq_('./nodeify.js')(Promise);
15530_dereq_('./promisify.js')(Promise, INTERNAL);
15531_dereq_('./props.js')(Promise, PromiseArray, tryConvertToPromise, apiRejection);
15532_dereq_('./race.js')(Promise, INTERNAL, tryConvertToPromise, apiRejection);
15533_dereq_('./reduce.js')(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL, debug);
15534_dereq_('./settle.js')(Promise, PromiseArray, debug);
15535_dereq_('./some.js')(Promise, PromiseArray, apiRejection);
15536_dereq_('./timers.js')(Promise, INTERNAL, debug);
15537_dereq_('./using.js')(Promise, apiRejection, tryConvertToPromise, createContext, INTERNAL, debug);
15538_dereq_('./any.js')(Promise);
15539_dereq_('./each.js')(Promise, INTERNAL);
15540_dereq_('./filter.js')(Promise, INTERNAL);
15541
15542 util.toFastProperties(Promise);
15543 util.toFastProperties(Promise.prototype);
15544 function fillTypes(value) {
15545 var p = new Promise(INTERNAL);
15546 p._fulfillmentHandler0 = value;
15547 p._rejectionHandler0 = value;
15548 p._promise0 = value;
15549 p._receiver0 = value;
15550 }
15551 // Complete slack tracking, opt out of field-type tracking and
15552 // stabilize map
15553 fillTypes({a: 1});
15554 fillTypes({b: 2});
15555 fillTypes({c: 3});
15556 fillTypes(1);
15557 fillTypes(function(){});
15558 fillTypes(undefined);
15559 fillTypes(false);
15560 fillTypes(new Promise(INTERNAL));
15561 debug.setBounds(Async.firstLineError, util.lastLineError);
15562 return Promise;
15563
15564};
15565
15566},{"./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){
15567"use strict";
15568module.exports = function(Promise, INTERNAL, tryConvertToPromise,
15569 apiRejection, Proxyable) {
15570var util = _dereq_("./util");
15571var isArray = util.isArray;
15572
15573function toResolutionValue(val) {
15574 switch(val) {
15575 case -2: return [];
15576 case -3: return {};
15577 case -6: return new Map();
15578 }
15579}
15580
15581function PromiseArray(values) {
15582 var promise = this._promise = new Promise(INTERNAL);
15583 if (values instanceof Promise) {
15584 promise._propagateFrom(values, 3);
15585 }
15586 promise._setOnCancel(this);
15587 this._values = values;
15588 this._length = 0;
15589 this._totalResolved = 0;
15590 this._init(undefined, -2);
15591}
15592util.inherits(PromiseArray, Proxyable);
15593
15594PromiseArray.prototype.length = function () {
15595 return this._length;
15596};
15597
15598PromiseArray.prototype.promise = function () {
15599 return this._promise;
15600};
15601
15602PromiseArray.prototype._init = function init(_, resolveValueIfEmpty) {
15603 var values = tryConvertToPromise(this._values, this._promise);
15604 if (values instanceof Promise) {
15605 values = values._target();
15606 var bitField = values._bitField;
15607 ;
15608 this._values = values;
15609
15610 if (((bitField & 50397184) === 0)) {
15611 this._promise._setAsyncGuaranteed();
15612 return values._then(
15613 init,
15614 this._reject,
15615 undefined,
15616 this,
15617 resolveValueIfEmpty
15618 );
15619 } else if (((bitField & 33554432) !== 0)) {
15620 values = values._value();
15621 } else if (((bitField & 16777216) !== 0)) {
15622 return this._reject(values._reason());
15623 } else {
15624 return this._cancel();
15625 }
15626 }
15627 values = util.asArray(values);
15628 if (values === null) {
15629 var err = apiRejection(
15630 "expecting an array or an iterable object but got " + util.classString(values)).reason();
15631 this._promise._rejectCallback(err, false);
15632 return;
15633 }
15634
15635 if (values.length === 0) {
15636 if (resolveValueIfEmpty === -5) {
15637 this._resolveEmptyArray();
15638 }
15639 else {
15640 this._resolve(toResolutionValue(resolveValueIfEmpty));
15641 }
15642 return;
15643 }
15644 this._iterate(values);
15645};
15646
15647PromiseArray.prototype._iterate = function(values) {
15648 var len = this.getActualLength(values.length);
15649 this._length = len;
15650 this._values = this.shouldCopyValues() ? new Array(len) : this._values;
15651 var result = this._promise;
15652 var isResolved = false;
15653 var bitField = null;
15654 for (var i = 0; i < len; ++i) {
15655 var maybePromise = tryConvertToPromise(values[i], result);
15656
15657 if (maybePromise instanceof Promise) {
15658 maybePromise = maybePromise._target();
15659 bitField = maybePromise._bitField;
15660 } else {
15661 bitField = null;
15662 }
15663
15664 if (isResolved) {
15665 if (bitField !== null) {
15666 maybePromise.suppressUnhandledRejections();
15667 }
15668 } else if (bitField !== null) {
15669 if (((bitField & 50397184) === 0)) {
15670 maybePromise._proxy(this, i);
15671 this._values[i] = maybePromise;
15672 } else if (((bitField & 33554432) !== 0)) {
15673 isResolved = this._promiseFulfilled(maybePromise._value(), i);
15674 } else if (((bitField & 16777216) !== 0)) {
15675 isResolved = this._promiseRejected(maybePromise._reason(), i);
15676 } else {
15677 isResolved = this._promiseCancelled(i);
15678 }
15679 } else {
15680 isResolved = this._promiseFulfilled(maybePromise, i);
15681 }
15682 }
15683 if (!isResolved) result._setAsyncGuaranteed();
15684};
15685
15686PromiseArray.prototype._isResolved = function () {
15687 return this._values === null;
15688};
15689
15690PromiseArray.prototype._resolve = function (value) {
15691 this._values = null;
15692 this._promise._fulfill(value);
15693};
15694
15695PromiseArray.prototype._cancel = function() {
15696 if (this._isResolved() || !this._promise._isCancellable()) return;
15697 this._values = null;
15698 this._promise._cancel();
15699};
15700
15701PromiseArray.prototype._reject = function (reason) {
15702 this._values = null;
15703 this._promise._rejectCallback(reason, false);
15704};
15705
15706PromiseArray.prototype._promiseFulfilled = function (value, index) {
15707 this._values[index] = value;
15708 var totalResolved = ++this._totalResolved;
15709 if (totalResolved >= this._length) {
15710 this._resolve(this._values);
15711 return true;
15712 }
15713 return false;
15714};
15715
15716PromiseArray.prototype._promiseCancelled = function() {
15717 this._cancel();
15718 return true;
15719};
15720
15721PromiseArray.prototype._promiseRejected = function (reason) {
15722 this._totalResolved++;
15723 this._reject(reason);
15724 return true;
15725};
15726
15727PromiseArray.prototype._resultCancelled = function() {
15728 if (this._isResolved()) return;
15729 var values = this._values;
15730 this._cancel();
15731 if (values instanceof Promise) {
15732 values.cancel();
15733 } else {
15734 for (var i = 0; i < values.length; ++i) {
15735 if (values[i] instanceof Promise) {
15736 values[i].cancel();
15737 }
15738 }
15739 }
15740};
15741
15742PromiseArray.prototype.shouldCopyValues = function () {
15743 return true;
15744};
15745
15746PromiseArray.prototype.getActualLength = function (len) {
15747 return len;
15748};
15749
15750return PromiseArray;
15751};
15752
15753},{"./util":36}],24:[function(_dereq_,module,exports){
15754"use strict";
15755module.exports = function(Promise, INTERNAL) {
15756var THIS = {};
15757var util = _dereq_("./util");
15758var nodebackForPromise = _dereq_("./nodeback");
15759var withAppended = util.withAppended;
15760var maybeWrapAsError = util.maybeWrapAsError;
15761var canEvaluate = util.canEvaluate;
15762var TypeError = _dereq_("./errors").TypeError;
15763var defaultSuffix = "Async";
15764var defaultPromisified = {__isPromisified__: true};
15765var noCopyProps = [
15766 "arity", "length",
15767 "name",
15768 "arguments",
15769 "caller",
15770 "callee",
15771 "prototype",
15772 "__isPromisified__"
15773];
15774var noCopyPropsPattern = new RegExp("^(?:" + noCopyProps.join("|") + ")$");
15775
15776var defaultFilter = function(name) {
15777 return util.isIdentifier(name) &&
15778 name.charAt(0) !== "_" &&
15779 name !== "constructor";
15780};
15781
15782function propsFilter(key) {
15783 return !noCopyPropsPattern.test(key);
15784}
15785
15786function isPromisified(fn) {
15787 try {
15788 return fn.__isPromisified__ === true;
15789 }
15790 catch (e) {
15791 return false;
15792 }
15793}
15794
15795function hasPromisified(obj, key, suffix) {
15796 var val = util.getDataPropertyOrDefault(obj, key + suffix,
15797 defaultPromisified);
15798 return val ? isPromisified(val) : false;
15799}
15800function checkValid(ret, suffix, suffixRegexp) {
15801 for (var i = 0; i < ret.length; i += 2) {
15802 var key = ret[i];
15803 if (suffixRegexp.test(key)) {
15804 var keyWithoutAsyncSuffix = key.replace(suffixRegexp, "");
15805 for (var j = 0; j < ret.length; j += 2) {
15806 if (ret[j] === keyWithoutAsyncSuffix) {
15807 throw new TypeError("Cannot promisify an API that has normal methods with '%s'-suffix\u000a\u000a See http://goo.gl/MqrFmX\u000a"
15808 .replace("%s", suffix));
15809 }
15810 }
15811 }
15812 }
15813}
15814
15815function promisifiableMethods(obj, suffix, suffixRegexp, filter) {
15816 var keys = util.inheritedDataKeys(obj);
15817 var ret = [];
15818 for (var i = 0; i < keys.length; ++i) {
15819 var key = keys[i];
15820 var value = obj[key];
15821 var passesDefaultFilter = filter === defaultFilter
15822 ? true : defaultFilter(key, value, obj);
15823 if (typeof value === "function" &&
15824 !isPromisified(value) &&
15825 !hasPromisified(obj, key, suffix) &&
15826 filter(key, value, obj, passesDefaultFilter)) {
15827 ret.push(key, value);
15828 }
15829 }
15830 checkValid(ret, suffix, suffixRegexp);
15831 return ret;
15832}
15833
15834var escapeIdentRegex = function(str) {
15835 return str.replace(/([$])/, "\\$");
15836};
15837
15838var makeNodePromisifiedEval;
15839if (!true) {
15840var switchCaseArgumentOrder = function(likelyArgumentCount) {
15841 var ret = [likelyArgumentCount];
15842 var min = Math.max(0, likelyArgumentCount - 1 - 3);
15843 for(var i = likelyArgumentCount - 1; i >= min; --i) {
15844 ret.push(i);
15845 }
15846 for(var i = likelyArgumentCount + 1; i <= 3; ++i) {
15847 ret.push(i);
15848 }
15849 return ret;
15850};
15851
15852var argumentSequence = function(argumentCount) {
15853 return util.filledRange(argumentCount, "_arg", "");
15854};
15855
15856var parameterDeclaration = function(parameterCount) {
15857 return util.filledRange(
15858 Math.max(parameterCount, 3), "_arg", "");
15859};
15860
15861var parameterCount = function(fn) {
15862 if (typeof fn.length === "number") {
15863 return Math.max(Math.min(fn.length, 1023 + 1), 0);
15864 }
15865 return 0;
15866};
15867
15868makeNodePromisifiedEval =
15869function(callback, receiver, originalName, fn, _, multiArgs) {
15870 var newParameterCount = Math.max(0, parameterCount(fn) - 1);
15871 var argumentOrder = switchCaseArgumentOrder(newParameterCount);
15872 var shouldProxyThis = typeof callback === "string" || receiver === THIS;
15873
15874 function generateCallForArgumentCount(count) {
15875 var args = argumentSequence(count).join(", ");
15876 var comma = count > 0 ? ", " : "";
15877 var ret;
15878 if (shouldProxyThis) {
15879 ret = "ret = callback.call(this, {{args}}, nodeback); break;\n";
15880 } else {
15881 ret = receiver === undefined
15882 ? "ret = callback({{args}}, nodeback); break;\n"
15883 : "ret = callback.call(receiver, {{args}}, nodeback); break;\n";
15884 }
15885 return ret.replace("{{args}}", args).replace(", ", comma);
15886 }
15887
15888 function generateArgumentSwitchCase() {
15889 var ret = "";
15890 for (var i = 0; i < argumentOrder.length; ++i) {
15891 ret += "case " + argumentOrder[i] +":" +
15892 generateCallForArgumentCount(argumentOrder[i]);
15893 }
15894
15895 ret += " \n\
15896 default: \n\
15897 var args = new Array(len + 1); \n\
15898 var i = 0; \n\
15899 for (var i = 0; i < len; ++i) { \n\
15900 args[i] = arguments[i]; \n\
15901 } \n\
15902 args[i] = nodeback; \n\
15903 [CodeForCall] \n\
15904 break; \n\
15905 ".replace("[CodeForCall]", (shouldProxyThis
15906 ? "ret = callback.apply(this, args);\n"
15907 : "ret = callback.apply(receiver, args);\n"));
15908 return ret;
15909 }
15910
15911 var getFunctionCode = typeof callback === "string"
15912 ? ("this != null ? this['"+callback+"'] : fn")
15913 : "fn";
15914 var body = "'use strict'; \n\
15915 var ret = function (Parameters) { \n\
15916 'use strict'; \n\
15917 var len = arguments.length; \n\
15918 var promise = new Promise(INTERNAL); \n\
15919 promise._captureStackTrace(); \n\
15920 var nodeback = nodebackForPromise(promise, " + multiArgs + "); \n\
15921 var ret; \n\
15922 var callback = tryCatch([GetFunctionCode]); \n\
15923 switch(len) { \n\
15924 [CodeForSwitchCase] \n\
15925 } \n\
15926 if (ret === errorObj) { \n\
15927 promise._rejectCallback(maybeWrapAsError(ret.e), true, true);\n\
15928 } \n\
15929 if (!promise._isFateSealed()) promise._setAsyncGuaranteed(); \n\
15930 return promise; \n\
15931 }; \n\
15932 notEnumerableProp(ret, '__isPromisified__', true); \n\
15933 return ret; \n\
15934 ".replace("[CodeForSwitchCase]", generateArgumentSwitchCase())
15935 .replace("[GetFunctionCode]", getFunctionCode);
15936 body = body.replace("Parameters", parameterDeclaration(newParameterCount));
15937 return new Function("Promise",
15938 "fn",
15939 "receiver",
15940 "withAppended",
15941 "maybeWrapAsError",
15942 "nodebackForPromise",
15943 "tryCatch",
15944 "errorObj",
15945 "notEnumerableProp",
15946 "INTERNAL",
15947 body)(
15948 Promise,
15949 fn,
15950 receiver,
15951 withAppended,
15952 maybeWrapAsError,
15953 nodebackForPromise,
15954 util.tryCatch,
15955 util.errorObj,
15956 util.notEnumerableProp,
15957 INTERNAL);
15958};
15959}
15960
15961function makeNodePromisifiedClosure(callback, receiver, _, fn, __, multiArgs) {
15962 var defaultThis = (function() {return this;})();
15963 var method = callback;
15964 if (typeof method === "string") {
15965 callback = fn;
15966 }
15967 function promisified() {
15968 var _receiver = receiver;
15969 if (receiver === THIS) _receiver = this;
15970 var promise = new Promise(INTERNAL);
15971 promise._captureStackTrace();
15972 var cb = typeof method === "string" && this !== defaultThis
15973 ? this[method] : callback;
15974 var fn = nodebackForPromise(promise, multiArgs);
15975 try {
15976 cb.apply(_receiver, withAppended(arguments, fn));
15977 } catch(e) {
15978 promise._rejectCallback(maybeWrapAsError(e), true, true);
15979 }
15980 if (!promise._isFateSealed()) promise._setAsyncGuaranteed();
15981 return promise;
15982 }
15983 util.notEnumerableProp(promisified, "__isPromisified__", true);
15984 return promisified;
15985}
15986
15987var makeNodePromisified = canEvaluate
15988 ? makeNodePromisifiedEval
15989 : makeNodePromisifiedClosure;
15990
15991function promisifyAll(obj, suffix, filter, promisifier, multiArgs) {
15992 var suffixRegexp = new RegExp(escapeIdentRegex(suffix) + "$");
15993 var methods =
15994 promisifiableMethods(obj, suffix, suffixRegexp, filter);
15995
15996 for (var i = 0, len = methods.length; i < len; i+= 2) {
15997 var key = methods[i];
15998 var fn = methods[i+1];
15999 var promisifiedKey = key + suffix;
16000 if (promisifier === makeNodePromisified) {
16001 obj[promisifiedKey] =
16002 makeNodePromisified(key, THIS, key, fn, suffix, multiArgs);
16003 } else {
16004 var promisified = promisifier(fn, function() {
16005 return makeNodePromisified(key, THIS, key,
16006 fn, suffix, multiArgs);
16007 });
16008 util.notEnumerableProp(promisified, "__isPromisified__", true);
16009 obj[promisifiedKey] = promisified;
16010 }
16011 }
16012 util.toFastProperties(obj);
16013 return obj;
16014}
16015
16016function promisify(callback, receiver, multiArgs) {
16017 return makeNodePromisified(callback, receiver, undefined,
16018 callback, null, multiArgs);
16019}
16020
16021Promise.promisify = function (fn, options) {
16022 if (typeof fn !== "function") {
16023 throw new TypeError("expecting a function but got " + util.classString(fn));
16024 }
16025 if (isPromisified(fn)) {
16026 return fn;
16027 }
16028 options = Object(options);
16029 var receiver = options.context === undefined ? THIS : options.context;
16030 var multiArgs = !!options.multiArgs;
16031 var ret = promisify(fn, receiver, multiArgs);
16032 util.copyDescriptors(fn, ret, propsFilter);
16033 return ret;
16034};
16035
16036Promise.promisifyAll = function (target, options) {
16037 if (typeof target !== "function" && typeof target !== "object") {
16038 throw new TypeError("the target of promisifyAll must be an object or a function\u000a\u000a See http://goo.gl/MqrFmX\u000a");
16039 }
16040 options = Object(options);
16041 var multiArgs = !!options.multiArgs;
16042 var suffix = options.suffix;
16043 if (typeof suffix !== "string") suffix = defaultSuffix;
16044 var filter = options.filter;
16045 if (typeof filter !== "function") filter = defaultFilter;
16046 var promisifier = options.promisifier;
16047 if (typeof promisifier !== "function") promisifier = makeNodePromisified;
16048
16049 if (!util.isIdentifier(suffix)) {
16050 throw new RangeError("suffix must be a valid identifier\u000a\u000a See http://goo.gl/MqrFmX\u000a");
16051 }
16052
16053 var keys = util.inheritedDataKeys(target);
16054 for (var i = 0; i < keys.length; ++i) {
16055 var value = target[keys[i]];
16056 if (keys[i] !== "constructor" &&
16057 util.isClass(value)) {
16058 promisifyAll(value.prototype, suffix, filter, promisifier,
16059 multiArgs);
16060 promisifyAll(value, suffix, filter, promisifier, multiArgs);
16061 }
16062 }
16063
16064 return promisifyAll(target, suffix, filter, promisifier, multiArgs);
16065};
16066};
16067
16068
16069},{"./errors":12,"./nodeback":20,"./util":36}],25:[function(_dereq_,module,exports){
16070"use strict";
16071module.exports = function(
16072 Promise, PromiseArray, tryConvertToPromise, apiRejection) {
16073var util = _dereq_("./util");
16074var isObject = util.isObject;
16075var es5 = _dereq_("./es5");
16076var Es6Map;
16077if (typeof Map === "function") Es6Map = Map;
16078
16079var mapToEntries = (function() {
16080 var index = 0;
16081 var size = 0;
16082
16083 function extractEntry(value, key) {
16084 this[index] = value;
16085 this[index + size] = key;
16086 index++;
16087 }
16088
16089 return function mapToEntries(map) {
16090 size = map.size;
16091 index = 0;
16092 var ret = new Array(map.size * 2);
16093 map.forEach(extractEntry, ret);
16094 return ret;
16095 };
16096})();
16097
16098var entriesToMap = function(entries) {
16099 var ret = new Es6Map();
16100 var length = entries.length / 2 | 0;
16101 for (var i = 0; i < length; ++i) {
16102 var key = entries[length + i];
16103 var value = entries[i];
16104 ret.set(key, value);
16105 }
16106 return ret;
16107};
16108
16109function PropertiesPromiseArray(obj) {
16110 var isMap = false;
16111 var entries;
16112 if (Es6Map !== undefined && obj instanceof Es6Map) {
16113 entries = mapToEntries(obj);
16114 isMap = true;
16115 } else {
16116 var keys = es5.keys(obj);
16117 var len = keys.length;
16118 entries = new Array(len * 2);
16119 for (var i = 0; i < len; ++i) {
16120 var key = keys[i];
16121 entries[i] = obj[key];
16122 entries[i + len] = key;
16123 }
16124 }
16125 this.constructor$(entries);
16126 this._isMap = isMap;
16127 this._init$(undefined, isMap ? -6 : -3);
16128}
16129util.inherits(PropertiesPromiseArray, PromiseArray);
16130
16131PropertiesPromiseArray.prototype._init = function () {};
16132
16133PropertiesPromiseArray.prototype._promiseFulfilled = function (value, index) {
16134 this._values[index] = value;
16135 var totalResolved = ++this._totalResolved;
16136 if (totalResolved >= this._length) {
16137 var val;
16138 if (this._isMap) {
16139 val = entriesToMap(this._values);
16140 } else {
16141 val = {};
16142 var keyOffset = this.length();
16143 for (var i = 0, len = this.length(); i < len; ++i) {
16144 val[this._values[i + keyOffset]] = this._values[i];
16145 }
16146 }
16147 this._resolve(val);
16148 return true;
16149 }
16150 return false;
16151};
16152
16153PropertiesPromiseArray.prototype.shouldCopyValues = function () {
16154 return false;
16155};
16156
16157PropertiesPromiseArray.prototype.getActualLength = function (len) {
16158 return len >> 1;
16159};
16160
16161function props(promises) {
16162 var ret;
16163 var castValue = tryConvertToPromise(promises);
16164
16165 if (!isObject(castValue)) {
16166 return apiRejection("cannot await properties of a non-object\u000a\u000a See http://goo.gl/MqrFmX\u000a");
16167 } else if (castValue instanceof Promise) {
16168 ret = castValue._then(
16169 Promise.props, undefined, undefined, undefined, undefined);
16170 } else {
16171 ret = new PropertiesPromiseArray(castValue).promise();
16172 }
16173
16174 if (castValue instanceof Promise) {
16175 ret._propagateFrom(castValue, 2);
16176 }
16177 return ret;
16178}
16179
16180Promise.prototype.props = function () {
16181 return props(this);
16182};
16183
16184Promise.props = function (promises) {
16185 return props(promises);
16186};
16187};
16188
16189},{"./es5":13,"./util":36}],26:[function(_dereq_,module,exports){
16190"use strict";
16191function arrayMove(src, srcIndex, dst, dstIndex, len) {
16192 for (var j = 0; j < len; ++j) {
16193 dst[j + dstIndex] = src[j + srcIndex];
16194 src[j + srcIndex] = void 0;
16195 }
16196}
16197
16198function Queue(capacity) {
16199 this._capacity = capacity;
16200 this._length = 0;
16201 this._front = 0;
16202}
16203
16204Queue.prototype._willBeOverCapacity = function (size) {
16205 return this._capacity < size;
16206};
16207
16208Queue.prototype._pushOne = function (arg) {
16209 var length = this.length();
16210 this._checkCapacity(length + 1);
16211 var i = (this._front + length) & (this._capacity - 1);
16212 this[i] = arg;
16213 this._length = length + 1;
16214};
16215
16216Queue.prototype.push = function (fn, receiver, arg) {
16217 var length = this.length() + 3;
16218 if (this._willBeOverCapacity(length)) {
16219 this._pushOne(fn);
16220 this._pushOne(receiver);
16221 this._pushOne(arg);
16222 return;
16223 }
16224 var j = this._front + length - 3;
16225 this._checkCapacity(length);
16226 var wrapMask = this._capacity - 1;
16227 this[(j + 0) & wrapMask] = fn;
16228 this[(j + 1) & wrapMask] = receiver;
16229 this[(j + 2) & wrapMask] = arg;
16230 this._length = length;
16231};
16232
16233Queue.prototype.shift = function () {
16234 var front = this._front,
16235 ret = this[front];
16236
16237 this[front] = undefined;
16238 this._front = (front + 1) & (this._capacity - 1);
16239 this._length--;
16240 return ret;
16241};
16242
16243Queue.prototype.length = function () {
16244 return this._length;
16245};
16246
16247Queue.prototype._checkCapacity = function (size) {
16248 if (this._capacity < size) {
16249 this._resizeTo(this._capacity << 1);
16250 }
16251};
16252
16253Queue.prototype._resizeTo = function (capacity) {
16254 var oldCapacity = this._capacity;
16255 this._capacity = capacity;
16256 var front = this._front;
16257 var length = this._length;
16258 var moveItemsCount = (front + length) & (oldCapacity - 1);
16259 arrayMove(this, 0, this, oldCapacity, moveItemsCount);
16260};
16261
16262module.exports = Queue;
16263
16264},{}],27:[function(_dereq_,module,exports){
16265"use strict";
16266module.exports = function(
16267 Promise, INTERNAL, tryConvertToPromise, apiRejection) {
16268var util = _dereq_("./util");
16269
16270var raceLater = function (promise) {
16271 return promise.then(function(array) {
16272 return race(array, promise);
16273 });
16274};
16275
16276function race(promises, parent) {
16277 var maybePromise = tryConvertToPromise(promises);
16278
16279 if (maybePromise instanceof Promise) {
16280 return raceLater(maybePromise);
16281 } else {
16282 promises = util.asArray(promises);
16283 if (promises === null)
16284 return apiRejection("expecting an array or an iterable object but got " + util.classString(promises));
16285 }
16286
16287 var ret = new Promise(INTERNAL);
16288 if (parent !== undefined) {
16289 ret._propagateFrom(parent, 3);
16290 }
16291 var fulfill = ret._fulfill;
16292 var reject = ret._reject;
16293 for (var i = 0, len = promises.length; i < len; ++i) {
16294 var val = promises[i];
16295
16296 if (val === undefined && !(i in promises)) {
16297 continue;
16298 }
16299
16300 Promise.cast(val)._then(fulfill, reject, undefined, ret, null);
16301 }
16302 return ret;
16303}
16304
16305Promise.race = function (promises) {
16306 return race(promises, undefined);
16307};
16308
16309Promise.prototype.race = function () {
16310 return race(this, undefined);
16311};
16312
16313};
16314
16315},{"./util":36}],28:[function(_dereq_,module,exports){
16316"use strict";
16317module.exports = function(Promise,
16318 PromiseArray,
16319 apiRejection,
16320 tryConvertToPromise,
16321 INTERNAL,
16322 debug) {
16323var getDomain = Promise._getDomain;
16324var util = _dereq_("./util");
16325var tryCatch = util.tryCatch;
16326
16327function ReductionPromiseArray(promises, fn, initialValue, _each) {
16328 this.constructor$(promises);
16329 var domain = getDomain();
16330 this._fn = domain === null ? fn : util.domainBind(domain, fn);
16331 if (initialValue !== undefined) {
16332 initialValue = Promise.resolve(initialValue);
16333 initialValue._attachCancellationCallback(this);
16334 }
16335 this._initialValue = initialValue;
16336 this._currentCancellable = null;
16337 if(_each === INTERNAL) {
16338 this._eachValues = Array(this._length);
16339 } else if (_each === 0) {
16340 this._eachValues = null;
16341 } else {
16342 this._eachValues = undefined;
16343 }
16344 this._promise._captureStackTrace();
16345 this._init$(undefined, -5);
16346}
16347util.inherits(ReductionPromiseArray, PromiseArray);
16348
16349ReductionPromiseArray.prototype._gotAccum = function(accum) {
16350 if (this._eachValues !== undefined &&
16351 this._eachValues !== null &&
16352 accum !== INTERNAL) {
16353 this._eachValues.push(accum);
16354 }
16355};
16356
16357ReductionPromiseArray.prototype._eachComplete = function(value) {
16358 if (this._eachValues !== null) {
16359 this._eachValues.push(value);
16360 }
16361 return this._eachValues;
16362};
16363
16364ReductionPromiseArray.prototype._init = function() {};
16365
16366ReductionPromiseArray.prototype._resolveEmptyArray = function() {
16367 this._resolve(this._eachValues !== undefined ? this._eachValues
16368 : this._initialValue);
16369};
16370
16371ReductionPromiseArray.prototype.shouldCopyValues = function () {
16372 return false;
16373};
16374
16375ReductionPromiseArray.prototype._resolve = function(value) {
16376 this._promise._resolveCallback(value);
16377 this._values = null;
16378};
16379
16380ReductionPromiseArray.prototype._resultCancelled = function(sender) {
16381 if (sender === this._initialValue) return this._cancel();
16382 if (this._isResolved()) return;
16383 this._resultCancelled$();
16384 if (this._currentCancellable instanceof Promise) {
16385 this._currentCancellable.cancel();
16386 }
16387 if (this._initialValue instanceof Promise) {
16388 this._initialValue.cancel();
16389 }
16390};
16391
16392ReductionPromiseArray.prototype._iterate = function (values) {
16393 this._values = values;
16394 var value;
16395 var i;
16396 var length = values.length;
16397 if (this._initialValue !== undefined) {
16398 value = this._initialValue;
16399 i = 0;
16400 } else {
16401 value = Promise.resolve(values[0]);
16402 i = 1;
16403 }
16404
16405 this._currentCancellable = value;
16406
16407 if (!value.isRejected()) {
16408 for (; i < length; ++i) {
16409 var ctx = {
16410 accum: null,
16411 value: values[i],
16412 index: i,
16413 length: length,
16414 array: this
16415 };
16416 value = value._then(gotAccum, undefined, undefined, ctx, undefined);
16417 }
16418 }
16419
16420 if (this._eachValues !== undefined) {
16421 value = value
16422 ._then(this._eachComplete, undefined, undefined, this, undefined);
16423 }
16424 value._then(completed, completed, undefined, value, this);
16425};
16426
16427Promise.prototype.reduce = function (fn, initialValue) {
16428 return reduce(this, fn, initialValue, null);
16429};
16430
16431Promise.reduce = function (promises, fn, initialValue, _each) {
16432 return reduce(promises, fn, initialValue, _each);
16433};
16434
16435function completed(valueOrReason, array) {
16436 if (this.isFulfilled()) {
16437 array._resolve(valueOrReason);
16438 } else {
16439 array._reject(valueOrReason);
16440 }
16441}
16442
16443function reduce(promises, fn, initialValue, _each) {
16444 if (typeof fn !== "function") {
16445 return apiRejection("expecting a function but got " + util.classString(fn));
16446 }
16447 var array = new ReductionPromiseArray(promises, fn, initialValue, _each);
16448 return array.promise();
16449}
16450
16451function gotAccum(accum) {
16452 this.accum = accum;
16453 this.array._gotAccum(accum);
16454 var value = tryConvertToPromise(this.value, this.array._promise);
16455 if (value instanceof Promise) {
16456 this.array._currentCancellable = value;
16457 return value._then(gotValue, undefined, undefined, this, undefined);
16458 } else {
16459 return gotValue.call(this, value);
16460 }
16461}
16462
16463function gotValue(value) {
16464 var array = this.array;
16465 var promise = array._promise;
16466 var fn = tryCatch(array._fn);
16467 promise._pushContext();
16468 var ret;
16469 if (array._eachValues !== undefined) {
16470 ret = fn.call(promise._boundValue(), value, this.index, this.length);
16471 } else {
16472 ret = fn.call(promise._boundValue(),
16473 this.accum, value, this.index, this.length);
16474 }
16475 if (ret instanceof Promise) {
16476 array._currentCancellable = ret;
16477 }
16478 var promiseCreated = promise._popContext();
16479 debug.checkForgottenReturns(
16480 ret,
16481 promiseCreated,
16482 array._eachValues !== undefined ? "Promise.each" : "Promise.reduce",
16483 promise
16484 );
16485 return ret;
16486}
16487};
16488
16489},{"./util":36}],29:[function(_dereq_,module,exports){
16490"use strict";
16491var util = _dereq_("./util");
16492var schedule;
16493var noAsyncScheduler = function() {
16494 throw new Error("No async scheduler available\u000a\u000a See http://goo.gl/MqrFmX\u000a");
16495};
16496var NativePromise = util.getNativePromise();
16497if (util.isNode && typeof MutationObserver === "undefined") {
16498 var GlobalSetImmediate = global.setImmediate;
16499 var ProcessNextTick = process.nextTick;
16500 schedule = util.isRecentNode
16501 ? function(fn) { GlobalSetImmediate.call(global, fn); }
16502 : function(fn) { ProcessNextTick.call(process, fn); };
16503} else if (typeof NativePromise === "function" &&
16504 typeof NativePromise.resolve === "function") {
16505 var nativePromise = NativePromise.resolve();
16506 schedule = function(fn) {
16507 nativePromise.then(fn);
16508 };
16509} else if ((typeof MutationObserver !== "undefined") &&
16510 !(typeof window !== "undefined" &&
16511 window.navigator &&
16512 (window.navigator.standalone || window.cordova)) &&
16513 ("classList" in document.documentElement)) {
16514 schedule = (function() {
16515 var div = document.createElement("div");
16516 var opts = {attributes: true};
16517 var toggleScheduled = false;
16518 var div2 = document.createElement("div");
16519 var o2 = new MutationObserver(function() {
16520 div.classList.toggle("foo");
16521 toggleScheduled = false;
16522 });
16523 o2.observe(div2, opts);
16524
16525 var scheduleToggle = function() {
16526 if (toggleScheduled) return;
16527 toggleScheduled = true;
16528 div2.classList.toggle("foo");
16529 };
16530
16531 return function schedule(fn) {
16532 var o = new MutationObserver(function() {
16533 o.disconnect();
16534 fn();
16535 });
16536 o.observe(div, opts);
16537 scheduleToggle();
16538 };
16539 })();
16540} else if (typeof setImmediate !== "undefined") {
16541 schedule = function (fn) {
16542 setImmediate(fn);
16543 };
16544} else if (typeof setTimeout !== "undefined") {
16545 schedule = function (fn) {
16546 setTimeout(fn, 0);
16547 };
16548} else {
16549 schedule = noAsyncScheduler;
16550}
16551module.exports = schedule;
16552
16553},{"./util":36}],30:[function(_dereq_,module,exports){
16554"use strict";
16555module.exports =
16556 function(Promise, PromiseArray, debug) {
16557var PromiseInspection = Promise.PromiseInspection;
16558var util = _dereq_("./util");
16559
16560function SettledPromiseArray(values) {
16561 this.constructor$(values);
16562}
16563util.inherits(SettledPromiseArray, PromiseArray);
16564
16565SettledPromiseArray.prototype._promiseResolved = function (index, inspection) {
16566 this._values[index] = inspection;
16567 var totalResolved = ++this._totalResolved;
16568 if (totalResolved >= this._length) {
16569 this._resolve(this._values);
16570 return true;
16571 }
16572 return false;
16573};
16574
16575SettledPromiseArray.prototype._promiseFulfilled = function (value, index) {
16576 var ret = new PromiseInspection();
16577 ret._bitField = 33554432;
16578 ret._settledValueField = value;
16579 return this._promiseResolved(index, ret);
16580};
16581SettledPromiseArray.prototype._promiseRejected = function (reason, index) {
16582 var ret = new PromiseInspection();
16583 ret._bitField = 16777216;
16584 ret._settledValueField = reason;
16585 return this._promiseResolved(index, ret);
16586};
16587
16588Promise.settle = function (promises) {
16589 debug.deprecated(".settle()", ".reflect()");
16590 return new SettledPromiseArray(promises).promise();
16591};
16592
16593Promise.prototype.settle = function () {
16594 return Promise.settle(this);
16595};
16596};
16597
16598},{"./util":36}],31:[function(_dereq_,module,exports){
16599"use strict";
16600module.exports =
16601function(Promise, PromiseArray, apiRejection) {
16602var util = _dereq_("./util");
16603var RangeError = _dereq_("./errors").RangeError;
16604var AggregateError = _dereq_("./errors").AggregateError;
16605var isArray = util.isArray;
16606var CANCELLATION = {};
16607
16608
16609function SomePromiseArray(values) {
16610 this.constructor$(values);
16611 this._howMany = 0;
16612 this._unwrap = false;
16613 this._initialized = false;
16614}
16615util.inherits(SomePromiseArray, PromiseArray);
16616
16617SomePromiseArray.prototype._init = function () {
16618 if (!this._initialized) {
16619 return;
16620 }
16621 if (this._howMany === 0) {
16622 this._resolve([]);
16623 return;
16624 }
16625 this._init$(undefined, -5);
16626 var isArrayResolved = isArray(this._values);
16627 if (!this._isResolved() &&
16628 isArrayResolved &&
16629 this._howMany > this._canPossiblyFulfill()) {
16630 this._reject(this._getRangeError(this.length()));
16631 }
16632};
16633
16634SomePromiseArray.prototype.init = function () {
16635 this._initialized = true;
16636 this._init();
16637};
16638
16639SomePromiseArray.prototype.setUnwrap = function () {
16640 this._unwrap = true;
16641};
16642
16643SomePromiseArray.prototype.howMany = function () {
16644 return this._howMany;
16645};
16646
16647SomePromiseArray.prototype.setHowMany = function (count) {
16648 this._howMany = count;
16649};
16650
16651SomePromiseArray.prototype._promiseFulfilled = function (value) {
16652 this._addFulfilled(value);
16653 if (this._fulfilled() === this.howMany()) {
16654 this._values.length = this.howMany();
16655 if (this.howMany() === 1 && this._unwrap) {
16656 this._resolve(this._values[0]);
16657 } else {
16658 this._resolve(this._values);
16659 }
16660 return true;
16661 }
16662 return false;
16663
16664};
16665SomePromiseArray.prototype._promiseRejected = function (reason) {
16666 this._addRejected(reason);
16667 return this._checkOutcome();
16668};
16669
16670SomePromiseArray.prototype._promiseCancelled = function () {
16671 if (this._values instanceof Promise || this._values == null) {
16672 return this._cancel();
16673 }
16674 this._addRejected(CANCELLATION);
16675 return this._checkOutcome();
16676};
16677
16678SomePromiseArray.prototype._checkOutcome = function() {
16679 if (this.howMany() > this._canPossiblyFulfill()) {
16680 var e = new AggregateError();
16681 for (var i = this.length(); i < this._values.length; ++i) {
16682 if (this._values[i] !== CANCELLATION) {
16683 e.push(this._values[i]);
16684 }
16685 }
16686 if (e.length > 0) {
16687 this._reject(e);
16688 } else {
16689 this._cancel();
16690 }
16691 return true;
16692 }
16693 return false;
16694};
16695
16696SomePromiseArray.prototype._fulfilled = function () {
16697 return this._totalResolved;
16698};
16699
16700SomePromiseArray.prototype._rejected = function () {
16701 return this._values.length - this.length();
16702};
16703
16704SomePromiseArray.prototype._addRejected = function (reason) {
16705 this._values.push(reason);
16706};
16707
16708SomePromiseArray.prototype._addFulfilled = function (value) {
16709 this._values[this._totalResolved++] = value;
16710};
16711
16712SomePromiseArray.prototype._canPossiblyFulfill = function () {
16713 return this.length() - this._rejected();
16714};
16715
16716SomePromiseArray.prototype._getRangeError = function (count) {
16717 var message = "Input array must contain at least " +
16718 this._howMany + " items but contains only " + count + " items";
16719 return new RangeError(message);
16720};
16721
16722SomePromiseArray.prototype._resolveEmptyArray = function () {
16723 this._reject(this._getRangeError(0));
16724};
16725
16726function some(promises, howMany) {
16727 if ((howMany | 0) !== howMany || howMany < 0) {
16728 return apiRejection("expecting a positive integer\u000a\u000a See http://goo.gl/MqrFmX\u000a");
16729 }
16730 var ret = new SomePromiseArray(promises);
16731 var promise = ret.promise();
16732 ret.setHowMany(howMany);
16733 ret.init();
16734 return promise;
16735}
16736
16737Promise.some = function (promises, howMany) {
16738 return some(promises, howMany);
16739};
16740
16741Promise.prototype.some = function (howMany) {
16742 return some(this, howMany);
16743};
16744
16745Promise._SomePromiseArray = SomePromiseArray;
16746};
16747
16748},{"./errors":12,"./util":36}],32:[function(_dereq_,module,exports){
16749"use strict";
16750module.exports = function(Promise) {
16751function PromiseInspection(promise) {
16752 if (promise !== undefined) {
16753 promise = promise._target();
16754 this._bitField = promise._bitField;
16755 this._settledValueField = promise._isFateSealed()
16756 ? promise._settledValue() : undefined;
16757 }
16758 else {
16759 this._bitField = 0;
16760 this._settledValueField = undefined;
16761 }
16762}
16763
16764PromiseInspection.prototype._settledValue = function() {
16765 return this._settledValueField;
16766};
16767
16768var value = PromiseInspection.prototype.value = function () {
16769 if (!this.isFulfilled()) {
16770 throw new TypeError("cannot get fulfillment value of a non-fulfilled promise\u000a\u000a See http://goo.gl/MqrFmX\u000a");
16771 }
16772 return this._settledValue();
16773};
16774
16775var reason = PromiseInspection.prototype.error =
16776PromiseInspection.prototype.reason = function () {
16777 if (!this.isRejected()) {
16778 throw new TypeError("cannot get rejection reason of a non-rejected promise\u000a\u000a See http://goo.gl/MqrFmX\u000a");
16779 }
16780 return this._settledValue();
16781};
16782
16783var isFulfilled = PromiseInspection.prototype.isFulfilled = function() {
16784 return (this._bitField & 33554432) !== 0;
16785};
16786
16787var isRejected = PromiseInspection.prototype.isRejected = function () {
16788 return (this._bitField & 16777216) !== 0;
16789};
16790
16791var isPending = PromiseInspection.prototype.isPending = function () {
16792 return (this._bitField & 50397184) === 0;
16793};
16794
16795var isResolved = PromiseInspection.prototype.isResolved = function () {
16796 return (this._bitField & 50331648) !== 0;
16797};
16798
16799PromiseInspection.prototype.isCancelled = function() {
16800 return (this._bitField & 8454144) !== 0;
16801};
16802
16803Promise.prototype.__isCancelled = function() {
16804 return (this._bitField & 65536) === 65536;
16805};
16806
16807Promise.prototype._isCancelled = function() {
16808 return this._target().__isCancelled();
16809};
16810
16811Promise.prototype.isCancelled = function() {
16812 return (this._target()._bitField & 8454144) !== 0;
16813};
16814
16815Promise.prototype.isPending = function() {
16816 return isPending.call(this._target());
16817};
16818
16819Promise.prototype.isRejected = function() {
16820 return isRejected.call(this._target());
16821};
16822
16823Promise.prototype.isFulfilled = function() {
16824 return isFulfilled.call(this._target());
16825};
16826
16827Promise.prototype.isResolved = function() {
16828 return isResolved.call(this._target());
16829};
16830
16831Promise.prototype.value = function() {
16832 return value.call(this._target());
16833};
16834
16835Promise.prototype.reason = function() {
16836 var target = this._target();
16837 target._unsetRejectionIsUnhandled();
16838 return reason.call(target);
16839};
16840
16841Promise.prototype._value = function() {
16842 return this._settledValue();
16843};
16844
16845Promise.prototype._reason = function() {
16846 this._unsetRejectionIsUnhandled();
16847 return this._settledValue();
16848};
16849
16850Promise.PromiseInspection = PromiseInspection;
16851};
16852
16853},{}],33:[function(_dereq_,module,exports){
16854"use strict";
16855module.exports = function(Promise, INTERNAL) {
16856var util = _dereq_("./util");
16857var errorObj = util.errorObj;
16858var isObject = util.isObject;
16859
16860function tryConvertToPromise(obj, context) {
16861 if (isObject(obj)) {
16862 if (obj instanceof Promise) return obj;
16863 var then = getThen(obj);
16864 if (then === errorObj) {
16865 if (context) context._pushContext();
16866 var ret = Promise.reject(then.e);
16867 if (context) context._popContext();
16868 return ret;
16869 } else if (typeof then === "function") {
16870 if (isAnyBluebirdPromise(obj)) {
16871 var ret = new Promise(INTERNAL);
16872 obj._then(
16873 ret._fulfill,
16874 ret._reject,
16875 undefined,
16876 ret,
16877 null
16878 );
16879 return ret;
16880 }
16881 return doThenable(obj, then, context);
16882 }
16883 }
16884 return obj;
16885}
16886
16887function doGetThen(obj) {
16888 return obj.then;
16889}
16890
16891function getThen(obj) {
16892 try {
16893 return doGetThen(obj);
16894 } catch (e) {
16895 errorObj.e = e;
16896 return errorObj;
16897 }
16898}
16899
16900var hasProp = {}.hasOwnProperty;
16901function isAnyBluebirdPromise(obj) {
16902 try {
16903 return hasProp.call(obj, "_promise0");
16904 } catch (e) {
16905 return false;
16906 }
16907}
16908
16909function doThenable(x, then, context) {
16910 var promise = new Promise(INTERNAL);
16911 var ret = promise;
16912 if (context) context._pushContext();
16913 promise._captureStackTrace();
16914 if (context) context._popContext();
16915 var synchronous = true;
16916 var result = util.tryCatch(then).call(x, resolve, reject);
16917 synchronous = false;
16918
16919 if (promise && result === errorObj) {
16920 promise._rejectCallback(result.e, true, true);
16921 promise = null;
16922 }
16923
16924 function resolve(value) {
16925 if (!promise) return;
16926 promise._resolveCallback(value);
16927 promise = null;
16928 }
16929
16930 function reject(reason) {
16931 if (!promise) return;
16932 promise._rejectCallback(reason, synchronous, true);
16933 promise = null;
16934 }
16935 return ret;
16936}
16937
16938return tryConvertToPromise;
16939};
16940
16941},{"./util":36}],34:[function(_dereq_,module,exports){
16942"use strict";
16943module.exports = function(Promise, INTERNAL, debug) {
16944var util = _dereq_("./util");
16945var TimeoutError = Promise.TimeoutError;
16946
16947function HandleWrapper(handle) {
16948 this.handle = handle;
16949}
16950
16951HandleWrapper.prototype._resultCancelled = function() {
16952 clearTimeout(this.handle);
16953};
16954
16955var afterValue = function(value) { return delay(+this).thenReturn(value); };
16956var delay = Promise.delay = function (ms, value) {
16957 var ret;
16958 var handle;
16959 if (value !== undefined) {
16960 ret = Promise.resolve(value)
16961 ._then(afterValue, null, null, ms, undefined);
16962 if (debug.cancellation() && value instanceof Promise) {
16963 ret._setOnCancel(value);
16964 }
16965 } else {
16966 ret = new Promise(INTERNAL);
16967 handle = setTimeout(function() { ret._fulfill(); }, +ms);
16968 if (debug.cancellation()) {
16969 ret._setOnCancel(new HandleWrapper(handle));
16970 }
16971 ret._captureStackTrace();
16972 }
16973 ret._setAsyncGuaranteed();
16974 return ret;
16975};
16976
16977Promise.prototype.delay = function (ms) {
16978 return delay(ms, this);
16979};
16980
16981var afterTimeout = function (promise, message, parent) {
16982 var err;
16983 if (typeof message !== "string") {
16984 if (message instanceof Error) {
16985 err = message;
16986 } else {
16987 err = new TimeoutError("operation timed out");
16988 }
16989 } else {
16990 err = new TimeoutError(message);
16991 }
16992 util.markAsOriginatingFromRejection(err);
16993 promise._attachExtraTrace(err);
16994 promise._reject(err);
16995
16996 if (parent != null) {
16997 parent.cancel();
16998 }
16999};
17000
17001function successClear(value) {
17002 clearTimeout(this.handle);
17003 return value;
17004}
17005
17006function failureClear(reason) {
17007 clearTimeout(this.handle);
17008 throw reason;
17009}
17010
17011Promise.prototype.timeout = function (ms, message) {
17012 ms = +ms;
17013 var ret, parent;
17014
17015 var handleWrapper = new HandleWrapper(setTimeout(function timeoutTimeout() {
17016 if (ret.isPending()) {
17017 afterTimeout(ret, message, parent);
17018 }
17019 }, ms));
17020
17021 if (debug.cancellation()) {
17022 parent = this.then();
17023 ret = parent._then(successClear, failureClear,
17024 undefined, handleWrapper, undefined);
17025 ret._setOnCancel(handleWrapper);
17026 } else {
17027 ret = this._then(successClear, failureClear,
17028 undefined, handleWrapper, undefined);
17029 }
17030
17031 return ret;
17032};
17033
17034};
17035
17036},{"./util":36}],35:[function(_dereq_,module,exports){
17037"use strict";
17038module.exports = function (Promise, apiRejection, tryConvertToPromise,
17039 createContext, INTERNAL, debug) {
17040 var util = _dereq_("./util");
17041 var TypeError = _dereq_("./errors").TypeError;
17042 var inherits = _dereq_("./util").inherits;
17043 var errorObj = util.errorObj;
17044 var tryCatch = util.tryCatch;
17045 var NULL = {};
17046
17047 function thrower(e) {
17048 setTimeout(function(){throw e;}, 0);
17049 }
17050
17051 function castPreservingDisposable(thenable) {
17052 var maybePromise = tryConvertToPromise(thenable);
17053 if (maybePromise !== thenable &&
17054 typeof thenable._isDisposable === "function" &&
17055 typeof thenable._getDisposer === "function" &&
17056 thenable._isDisposable()) {
17057 maybePromise._setDisposable(thenable._getDisposer());
17058 }
17059 return maybePromise;
17060 }
17061 function dispose(resources, inspection) {
17062 var i = 0;
17063 var len = resources.length;
17064 var ret = new Promise(INTERNAL);
17065 function iterator() {
17066 if (i >= len) return ret._fulfill();
17067 var maybePromise = castPreservingDisposable(resources[i++]);
17068 if (maybePromise instanceof Promise &&
17069 maybePromise._isDisposable()) {
17070 try {
17071 maybePromise = tryConvertToPromise(
17072 maybePromise._getDisposer().tryDispose(inspection),
17073 resources.promise);
17074 } catch (e) {
17075 return thrower(e);
17076 }
17077 if (maybePromise instanceof Promise) {
17078 return maybePromise._then(iterator, thrower,
17079 null, null, null);
17080 }
17081 }
17082 iterator();
17083 }
17084 iterator();
17085 return ret;
17086 }
17087
17088 function Disposer(data, promise, context) {
17089 this._data = data;
17090 this._promise = promise;
17091 this._context = context;
17092 }
17093
17094 Disposer.prototype.data = function () {
17095 return this._data;
17096 };
17097
17098 Disposer.prototype.promise = function () {
17099 return this._promise;
17100 };
17101
17102 Disposer.prototype.resource = function () {
17103 if (this.promise().isFulfilled()) {
17104 return this.promise().value();
17105 }
17106 return NULL;
17107 };
17108
17109 Disposer.prototype.tryDispose = function(inspection) {
17110 var resource = this.resource();
17111 var context = this._context;
17112 if (context !== undefined) context._pushContext();
17113 var ret = resource !== NULL
17114 ? this.doDispose(resource, inspection) : null;
17115 if (context !== undefined) context._popContext();
17116 this._promise._unsetDisposable();
17117 this._data = null;
17118 return ret;
17119 };
17120
17121 Disposer.isDisposer = function (d) {
17122 return (d != null &&
17123 typeof d.resource === "function" &&
17124 typeof d.tryDispose === "function");
17125 };
17126
17127 function FunctionDisposer(fn, promise, context) {
17128 this.constructor$(fn, promise, context);
17129 }
17130 inherits(FunctionDisposer, Disposer);
17131
17132 FunctionDisposer.prototype.doDispose = function (resource, inspection) {
17133 var fn = this.data();
17134 return fn.call(resource, resource, inspection);
17135 };
17136
17137 function maybeUnwrapDisposer(value) {
17138 if (Disposer.isDisposer(value)) {
17139 this.resources[this.index]._setDisposable(value);
17140 return value.promise();
17141 }
17142 return value;
17143 }
17144
17145 function ResourceList(length) {
17146 this.length = length;
17147 this.promise = null;
17148 this[length-1] = null;
17149 }
17150
17151 ResourceList.prototype._resultCancelled = function() {
17152 var len = this.length;
17153 for (var i = 0; i < len; ++i) {
17154 var item = this[i];
17155 if (item instanceof Promise) {
17156 item.cancel();
17157 }
17158 }
17159 };
17160
17161 Promise.using = function () {
17162 var len = arguments.length;
17163 if (len < 2) return apiRejection(
17164 "you must pass at least 2 arguments to Promise.using");
17165 var fn = arguments[len - 1];
17166 if (typeof fn !== "function") {
17167 return apiRejection("expecting a function but got " + util.classString(fn));
17168 }
17169 var input;
17170 var spreadArgs = true;
17171 if (len === 2 && Array.isArray(arguments[0])) {
17172 input = arguments[0];
17173 len = input.length;
17174 spreadArgs = false;
17175 } else {
17176 input = arguments;
17177 len--;
17178 }
17179 var resources = new ResourceList(len);
17180 for (var i = 0; i < len; ++i) {
17181 var resource = input[i];
17182 if (Disposer.isDisposer(resource)) {
17183 var disposer = resource;
17184 resource = resource.promise();
17185 resource._setDisposable(disposer);
17186 } else {
17187 var maybePromise = tryConvertToPromise(resource);
17188 if (maybePromise instanceof Promise) {
17189 resource =
17190 maybePromise._then(maybeUnwrapDisposer, null, null, {
17191 resources: resources,
17192 index: i
17193 }, undefined);
17194 }
17195 }
17196 resources[i] = resource;
17197 }
17198
17199 var reflectedResources = new Array(resources.length);
17200 for (var i = 0; i < reflectedResources.length; ++i) {
17201 reflectedResources[i] = Promise.resolve(resources[i]).reflect();
17202 }
17203
17204 var resultPromise = Promise.all(reflectedResources)
17205 .then(function(inspections) {
17206 for (var i = 0; i < inspections.length; ++i) {
17207 var inspection = inspections[i];
17208 if (inspection.isRejected()) {
17209 errorObj.e = inspection.error();
17210 return errorObj;
17211 } else if (!inspection.isFulfilled()) {
17212 resultPromise.cancel();
17213 return;
17214 }
17215 inspections[i] = inspection.value();
17216 }
17217 promise._pushContext();
17218
17219 fn = tryCatch(fn);
17220 var ret = spreadArgs
17221 ? fn.apply(undefined, inspections) : fn(inspections);
17222 var promiseCreated = promise._popContext();
17223 debug.checkForgottenReturns(
17224 ret, promiseCreated, "Promise.using", promise);
17225 return ret;
17226 });
17227
17228 var promise = resultPromise.lastly(function() {
17229 var inspection = new Promise.PromiseInspection(resultPromise);
17230 return dispose(resources, inspection);
17231 });
17232 resources.promise = promise;
17233 promise._setOnCancel(resources);
17234 return promise;
17235 };
17236
17237 Promise.prototype._setDisposable = function (disposer) {
17238 this._bitField = this._bitField | 131072;
17239 this._disposer = disposer;
17240 };
17241
17242 Promise.prototype._isDisposable = function () {
17243 return (this._bitField & 131072) > 0;
17244 };
17245
17246 Promise.prototype._getDisposer = function () {
17247 return this._disposer;
17248 };
17249
17250 Promise.prototype._unsetDisposable = function () {
17251 this._bitField = this._bitField & (~131072);
17252 this._disposer = undefined;
17253 };
17254
17255 Promise.prototype.disposer = function (fn) {
17256 if (typeof fn === "function") {
17257 return new FunctionDisposer(fn, this, createContext());
17258 }
17259 throw new TypeError();
17260 };
17261
17262};
17263
17264},{"./errors":12,"./util":36}],36:[function(_dereq_,module,exports){
17265"use strict";
17266var es5 = _dereq_("./es5");
17267var canEvaluate = typeof navigator == "undefined";
17268
17269var errorObj = {e: {}};
17270var tryCatchTarget;
17271var globalObject = typeof self !== "undefined" ? self :
17272 typeof window !== "undefined" ? window :
17273 typeof global !== "undefined" ? global :
17274 this !== undefined ? this : null;
17275
17276function tryCatcher() {
17277 try {
17278 var target = tryCatchTarget;
17279 tryCatchTarget = null;
17280 return target.apply(this, arguments);
17281 } catch (e) {
17282 errorObj.e = e;
17283 return errorObj;
17284 }
17285}
17286function tryCatch(fn) {
17287 tryCatchTarget = fn;
17288 return tryCatcher;
17289}
17290
17291var inherits = function(Child, Parent) {
17292 var hasProp = {}.hasOwnProperty;
17293
17294 function T() {
17295 this.constructor = Child;
17296 this.constructor$ = Parent;
17297 for (var propertyName in Parent.prototype) {
17298 if (hasProp.call(Parent.prototype, propertyName) &&
17299 propertyName.charAt(propertyName.length-1) !== "$"
17300 ) {
17301 this[propertyName + "$"] = Parent.prototype[propertyName];
17302 }
17303 }
17304 }
17305 T.prototype = Parent.prototype;
17306 Child.prototype = new T();
17307 return Child.prototype;
17308};
17309
17310
17311function isPrimitive(val) {
17312 return val == null || val === true || val === false ||
17313 typeof val === "string" || typeof val === "number";
17314
17315}
17316
17317function isObject(value) {
17318 return typeof value === "function" ||
17319 typeof value === "object" && value !== null;
17320}
17321
17322function maybeWrapAsError(maybeError) {
17323 if (!isPrimitive(maybeError)) return maybeError;
17324
17325 return new Error(safeToString(maybeError));
17326}
17327
17328function withAppended(target, appendee) {
17329 var len = target.length;
17330 var ret = new Array(len + 1);
17331 var i;
17332 for (i = 0; i < len; ++i) {
17333 ret[i] = target[i];
17334 }
17335 ret[i] = appendee;
17336 return ret;
17337}
17338
17339function getDataPropertyOrDefault(obj, key, defaultValue) {
17340 if (es5.isES5) {
17341 var desc = Object.getOwnPropertyDescriptor(obj, key);
17342
17343 if (desc != null) {
17344 return desc.get == null && desc.set == null
17345 ? desc.value
17346 : defaultValue;
17347 }
17348 } else {
17349 return {}.hasOwnProperty.call(obj, key) ? obj[key] : undefined;
17350 }
17351}
17352
17353function notEnumerableProp(obj, name, value) {
17354 if (isPrimitive(obj)) return obj;
17355 var descriptor = {
17356 value: value,
17357 configurable: true,
17358 enumerable: false,
17359 writable: true
17360 };
17361 es5.defineProperty(obj, name, descriptor);
17362 return obj;
17363}
17364
17365function thrower(r) {
17366 throw r;
17367}
17368
17369var inheritedDataKeys = (function() {
17370 var excludedPrototypes = [
17371 Array.prototype,
17372 Object.prototype,
17373 Function.prototype
17374 ];
17375
17376 var isExcludedProto = function(val) {
17377 for (var i = 0; i < excludedPrototypes.length; ++i) {
17378 if (excludedPrototypes[i] === val) {
17379 return true;
17380 }
17381 }
17382 return false;
17383 };
17384
17385 if (es5.isES5) {
17386 var getKeys = Object.getOwnPropertyNames;
17387 return function(obj) {
17388 var ret = [];
17389 var visitedKeys = Object.create(null);
17390 while (obj != null && !isExcludedProto(obj)) {
17391 var keys;
17392 try {
17393 keys = getKeys(obj);
17394 } catch (e) {
17395 return ret;
17396 }
17397 for (var i = 0; i < keys.length; ++i) {
17398 var key = keys[i];
17399 if (visitedKeys[key]) continue;
17400 visitedKeys[key] = true;
17401 var desc = Object.getOwnPropertyDescriptor(obj, key);
17402 if (desc != null && desc.get == null && desc.set == null) {
17403 ret.push(key);
17404 }
17405 }
17406 obj = es5.getPrototypeOf(obj);
17407 }
17408 return ret;
17409 };
17410 } else {
17411 var hasProp = {}.hasOwnProperty;
17412 return function(obj) {
17413 if (isExcludedProto(obj)) return [];
17414 var ret = [];
17415
17416 /*jshint forin:false */
17417 enumeration: for (var key in obj) {
17418 if (hasProp.call(obj, key)) {
17419 ret.push(key);
17420 } else {
17421 for (var i = 0; i < excludedPrototypes.length; ++i) {
17422 if (hasProp.call(excludedPrototypes[i], key)) {
17423 continue enumeration;
17424 }
17425 }
17426 ret.push(key);
17427 }
17428 }
17429 return ret;
17430 };
17431 }
17432
17433})();
17434
17435var thisAssignmentPattern = /this\s*\.\s*\S+\s*=/;
17436function isClass(fn) {
17437 try {
17438 if (typeof fn === "function") {
17439 var keys = es5.names(fn.prototype);
17440
17441 var hasMethods = es5.isES5 && keys.length > 1;
17442 var hasMethodsOtherThanConstructor = keys.length > 0 &&
17443 !(keys.length === 1 && keys[0] === "constructor");
17444 var hasThisAssignmentAndStaticMethods =
17445 thisAssignmentPattern.test(fn + "") && es5.names(fn).length > 0;
17446
17447 if (hasMethods || hasMethodsOtherThanConstructor ||
17448 hasThisAssignmentAndStaticMethods) {
17449 return true;
17450 }
17451 }
17452 return false;
17453 } catch (e) {
17454 return false;
17455 }
17456}
17457
17458function toFastProperties(obj) {
17459 /*jshint -W027,-W055,-W031*/
17460 function FakeConstructor() {}
17461 FakeConstructor.prototype = obj;
17462 var receiver = new FakeConstructor();
17463 function ic() {
17464 return typeof receiver.foo;
17465 }
17466 ic();
17467 ic();
17468 return obj;
17469 eval(obj);
17470}
17471
17472var rident = /^[a-z$_][a-z$_0-9]*$/i;
17473function isIdentifier(str) {
17474 return rident.test(str);
17475}
17476
17477function filledRange(count, prefix, suffix) {
17478 var ret = new Array(count);
17479 for(var i = 0; i < count; ++i) {
17480 ret[i] = prefix + i + suffix;
17481 }
17482 return ret;
17483}
17484
17485function safeToString(obj) {
17486 try {
17487 return obj + "";
17488 } catch (e) {
17489 return "[no string representation]";
17490 }
17491}
17492
17493function isError(obj) {
17494 return obj instanceof Error ||
17495 (obj !== null &&
17496 typeof obj === "object" &&
17497 typeof obj.message === "string" &&
17498 typeof obj.name === "string");
17499}
17500
17501function markAsOriginatingFromRejection(e) {
17502 try {
17503 notEnumerableProp(e, "isOperational", true);
17504 }
17505 catch(ignore) {}
17506}
17507
17508function originatesFromRejection(e) {
17509 if (e == null) return false;
17510 return ((e instanceof Error["__BluebirdErrorTypes__"].OperationalError) ||
17511 e["isOperational"] === true);
17512}
17513
17514function canAttachTrace(obj) {
17515 return isError(obj) && es5.propertyIsWritable(obj, "stack");
17516}
17517
17518var ensureErrorObject = (function() {
17519 if (!("stack" in new Error())) {
17520 return function(value) {
17521 if (canAttachTrace(value)) return value;
17522 try {throw new Error(safeToString(value));}
17523 catch(err) {return err;}
17524 };
17525 } else {
17526 return function(value) {
17527 if (canAttachTrace(value)) return value;
17528 return new Error(safeToString(value));
17529 };
17530 }
17531})();
17532
17533function classString(obj) {
17534 return {}.toString.call(obj);
17535}
17536
17537function copyDescriptors(from, to, filter) {
17538 var keys = es5.names(from);
17539 for (var i = 0; i < keys.length; ++i) {
17540 var key = keys[i];
17541 if (filter(key)) {
17542 try {
17543 es5.defineProperty(to, key, es5.getDescriptor(from, key));
17544 } catch (ignore) {}
17545 }
17546 }
17547}
17548
17549var asArray = function(v) {
17550 if (es5.isArray(v)) {
17551 return v;
17552 }
17553 return null;
17554};
17555
17556if (typeof Symbol !== "undefined" && Symbol.iterator) {
17557 var ArrayFrom = typeof Array.from === "function" ? function(v) {
17558 return Array.from(v);
17559 } : function(v) {
17560 var ret = [];
17561 var it = v[Symbol.iterator]();
17562 var itResult;
17563 while (!((itResult = it.next()).done)) {
17564 ret.push(itResult.value);
17565 }
17566 return ret;
17567 };
17568
17569 asArray = function(v) {
17570 if (es5.isArray(v)) {
17571 return v;
17572 } else if (v != null && typeof v[Symbol.iterator] === "function") {
17573 return ArrayFrom(v);
17574 }
17575 return null;
17576 };
17577}
17578
17579var isNode = typeof process !== "undefined" &&
17580 classString(process).toLowerCase() === "[object process]";
17581
17582var hasEnvVariables = typeof process !== "undefined" &&
17583 typeof process.env !== "undefined";
17584
17585function env(key) {
17586 return hasEnvVariables ? process.env[key] : undefined;
17587}
17588
17589function getNativePromise() {
17590 if (typeof Promise === "function") {
17591 try {
17592 var promise = new Promise(function(){});
17593 if ({}.toString.call(promise) === "[object Promise]") {
17594 return Promise;
17595 }
17596 } catch (e) {}
17597 }
17598}
17599
17600function domainBind(self, cb) {
17601 return self.bind(cb);
17602}
17603
17604var ret = {
17605 isClass: isClass,
17606 isIdentifier: isIdentifier,
17607 inheritedDataKeys: inheritedDataKeys,
17608 getDataPropertyOrDefault: getDataPropertyOrDefault,
17609 thrower: thrower,
17610 isArray: es5.isArray,
17611 asArray: asArray,
17612 notEnumerableProp: notEnumerableProp,
17613 isPrimitive: isPrimitive,
17614 isObject: isObject,
17615 isError: isError,
17616 canEvaluate: canEvaluate,
17617 errorObj: errorObj,
17618 tryCatch: tryCatch,
17619 inherits: inherits,
17620 withAppended: withAppended,
17621 maybeWrapAsError: maybeWrapAsError,
17622 toFastProperties: toFastProperties,
17623 filledRange: filledRange,
17624 toString: safeToString,
17625 canAttachTrace: canAttachTrace,
17626 ensureErrorObject: ensureErrorObject,
17627 originatesFromRejection: originatesFromRejection,
17628 markAsOriginatingFromRejection: markAsOriginatingFromRejection,
17629 classString: classString,
17630 copyDescriptors: copyDescriptors,
17631 hasDevTools: typeof chrome !== "undefined" && chrome &&
17632 typeof chrome.loadTimes === "function",
17633 isNode: isNode,
17634 hasEnvVariables: hasEnvVariables,
17635 env: env,
17636 global: globalObject,
17637 getNativePromise: getNativePromise,
17638 domainBind: domainBind
17639};
17640ret.isRecentNode = ret.isNode && (function() {
17641 var version;
17642 if (process.versions && process.versions.node) {
17643 version = process.versions.node.split(".").map(Number);
17644 } else if (process.version) {
17645 version = process.version.split(".").map(Number);
17646 }
17647 return (version[0] === 0 && version[1] > 10) || (version[0] > 0);
17648})();
17649
17650if (ret.isNode) ret.toFastProperties(process);
17651
17652try {throw new Error(); } catch (e) {ret.lastLineError = e;}
17653module.exports = ret;
17654
17655},{"./es5":13}]},{},[4])(4)
17656}); ;if (typeof window !== 'undefined' && window !== null) { window.P = window.Promise; } else if (typeof self !== 'undefined' && self !== null) { self.P = self.Promise; }
17657}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},require("timers").setImmediate)
17658},{"_process":265,"timers":382}],80:[function(require,module,exports){
17659(function (module, exports) {
17660 'use strict';
17661
17662 // Utils
17663 function assert (val, msg) {
17664 if (!val) throw new Error(msg || 'Assertion failed');
17665 }
17666
17667 // Could use `inherits` module, but don't want to move from single file
17668 // architecture yet.
17669 function inherits (ctor, superCtor) {
17670 ctor.super_ = superCtor;
17671 var TempCtor = function () {};
17672 TempCtor.prototype = superCtor.prototype;
17673 ctor.prototype = new TempCtor();
17674 ctor.prototype.constructor = ctor;
17675 }
17676
17677 // BN
17678
17679 function BN (number, base, endian) {
17680 if (BN.isBN(number)) {
17681 return number;
17682 }
17683
17684 this.negative = 0;
17685 this.words = null;
17686 this.length = 0;
17687
17688 // Reduction context
17689 this.red = null;
17690
17691 if (number !== null) {
17692 if (base === 'le' || base === 'be') {
17693 endian = base;
17694 base = 10;
17695 }
17696
17697 this._init(number || 0, base || 10, endian || 'be');
17698 }
17699 }
17700 if (typeof module === 'object') {
17701 module.exports = BN;
17702 } else {
17703 exports.BN = BN;
17704 }
17705
17706 BN.BN = BN;
17707 BN.wordSize = 26;
17708
17709 var Buffer;
17710 try {
17711 Buffer = require('buffer').Buffer;
17712 } catch (e) {
17713 }
17714
17715 BN.isBN = function isBN (num) {
17716 if (num instanceof BN) {
17717 return true;
17718 }
17719
17720 return num !== null && typeof num === 'object' &&
17721 num.constructor.wordSize === BN.wordSize && Array.isArray(num.words);
17722 };
17723
17724 BN.max = function max (left, right) {
17725 if (left.cmp(right) > 0) return left;
17726 return right;
17727 };
17728
17729 BN.min = function min (left, right) {
17730 if (left.cmp(right) < 0) return left;
17731 return right;
17732 };
17733
17734 BN.prototype._init = function init (number, base, endian) {
17735 if (typeof number === 'number') {
17736 return this._initNumber(number, base, endian);
17737 }
17738
17739 if (typeof number === 'object') {
17740 return this._initArray(number, base, endian);
17741 }
17742
17743 if (base === 'hex') {
17744 base = 16;
17745 }
17746 assert(base === (base | 0) && base >= 2 && base <= 36);
17747
17748 number = number.toString().replace(/\s+/g, '');
17749 var start = 0;
17750 if (number[0] === '-') {
17751 start++;
17752 }
17753
17754 if (base === 16) {
17755 this._parseHex(number, start);
17756 } else {
17757 this._parseBase(number, base, start);
17758 }
17759
17760 if (number[0] === '-') {
17761 this.negative = 1;
17762 }
17763
17764 this.strip();
17765
17766 if (endian !== 'le') return;
17767
17768 this._initArray(this.toArray(), base, endian);
17769 };
17770
17771 BN.prototype._initNumber = function _initNumber (number, base, endian) {
17772 if (number < 0) {
17773 this.negative = 1;
17774 number = -number;
17775 }
17776 if (number < 0x4000000) {
17777 this.words = [ number & 0x3ffffff ];
17778 this.length = 1;
17779 } else if (number < 0x10000000000000) {
17780 this.words = [
17781 number & 0x3ffffff,
17782 (number / 0x4000000) & 0x3ffffff
17783 ];
17784 this.length = 2;
17785 } else {
17786 assert(number < 0x20000000000000); // 2 ^ 53 (unsafe)
17787 this.words = [
17788 number & 0x3ffffff,
17789 (number / 0x4000000) & 0x3ffffff,
17790 1
17791 ];
17792 this.length = 3;
17793 }
17794
17795 if (endian !== 'le') return;
17796
17797 // Reverse the bytes
17798 this._initArray(this.toArray(), base, endian);
17799 };
17800
17801 BN.prototype._initArray = function _initArray (number, base, endian) {
17802 // Perhaps a Uint8Array
17803 assert(typeof number.length === 'number');
17804 if (number.length <= 0) {
17805 this.words = [ 0 ];
17806 this.length = 1;
17807 return this;
17808 }
17809
17810 this.length = Math.ceil(number.length / 3);
17811 this.words = new Array(this.length);
17812 for (var i = 0; i < this.length; i++) {
17813 this.words[i] = 0;
17814 }
17815
17816 var j, w;
17817 var off = 0;
17818 if (endian === 'be') {
17819 for (i = number.length - 1, j = 0; i >= 0; i -= 3) {
17820 w = number[i] | (number[i - 1] << 8) | (number[i - 2] << 16);
17821 this.words[j] |= (w << off) & 0x3ffffff;
17822 this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff;
17823 off += 24;
17824 if (off >= 26) {
17825 off -= 26;
17826 j++;
17827 }
17828 }
17829 } else if (endian === 'le') {
17830 for (i = 0, j = 0; i < number.length; i += 3) {
17831 w = number[i] | (number[i + 1] << 8) | (number[i + 2] << 16);
17832 this.words[j] |= (w << off) & 0x3ffffff;
17833 this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff;
17834 off += 24;
17835 if (off >= 26) {
17836 off -= 26;
17837 j++;
17838 }
17839 }
17840 }
17841 return this.strip();
17842 };
17843
17844 function parseHex (str, start, end) {
17845 var r = 0;
17846 var len = Math.min(str.length, end);
17847 for (var i = start; i < len; i++) {
17848 var c = str.charCodeAt(i) - 48;
17849
17850 r <<= 4;
17851
17852 // 'a' - 'f'
17853 if (c >= 49 && c <= 54) {
17854 r |= c - 49 + 0xa;
17855
17856 // 'A' - 'F'
17857 } else if (c >= 17 && c <= 22) {
17858 r |= c - 17 + 0xa;
17859
17860 // '0' - '9'
17861 } else {
17862 r |= c & 0xf;
17863 }
17864 }
17865 return r;
17866 }
17867
17868 BN.prototype._parseHex = function _parseHex (number, start) {
17869 // Create possibly bigger array to ensure that it fits the number
17870 this.length = Math.ceil((number.length - start) / 6);
17871 this.words = new Array(this.length);
17872 for (var i = 0; i < this.length; i++) {
17873 this.words[i] = 0;
17874 }
17875
17876 var j, w;
17877 // Scan 24-bit chunks and add them to the number
17878 var off = 0;
17879 for (i = number.length - 6, j = 0; i >= start; i -= 6) {
17880 w = parseHex(number, i, i + 6);
17881 this.words[j] |= (w << off) & 0x3ffffff;
17882 // NOTE: `0x3fffff` is intentional here, 26bits max shift + 24bit hex limb
17883 this.words[j + 1] |= w >>> (26 - off) & 0x3fffff;
17884 off += 24;
17885 if (off >= 26) {
17886 off -= 26;
17887 j++;
17888 }
17889 }
17890 if (i + 6 !== start) {
17891 w = parseHex(number, start, i + 6);
17892 this.words[j] |= (w << off) & 0x3ffffff;
17893 this.words[j + 1] |= w >>> (26 - off) & 0x3fffff;
17894 }
17895 this.strip();
17896 };
17897
17898 function parseBase (str, start, end, mul) {
17899 var r = 0;
17900 var len = Math.min(str.length, end);
17901 for (var i = start; i < len; i++) {
17902 var c = str.charCodeAt(i) - 48;
17903
17904 r *= mul;
17905
17906 // 'a'
17907 if (c >= 49) {
17908 r += c - 49 + 0xa;
17909
17910 // 'A'
17911 } else if (c >= 17) {
17912 r += c - 17 + 0xa;
17913
17914 // '0' - '9'
17915 } else {
17916 r += c;
17917 }
17918 }
17919 return r;
17920 }
17921
17922 BN.prototype._parseBase = function _parseBase (number, base, start) {
17923 // Initialize as zero
17924 this.words = [ 0 ];
17925 this.length = 1;
17926
17927 // Find length of limb in base
17928 for (var limbLen = 0, limbPow = 1; limbPow <= 0x3ffffff; limbPow *= base) {
17929 limbLen++;
17930 }
17931 limbLen--;
17932 limbPow = (limbPow / base) | 0;
17933
17934 var total = number.length - start;
17935 var mod = total % limbLen;
17936 var end = Math.min(total, total - mod) + start;
17937
17938 var word = 0;
17939 for (var i = start; i < end; i += limbLen) {
17940 word = parseBase(number, i, i + limbLen, base);
17941
17942 this.imuln(limbPow);
17943 if (this.words[0] + word < 0x4000000) {
17944 this.words[0] += word;
17945 } else {
17946 this._iaddn(word);
17947 }
17948 }
17949
17950 if (mod !== 0) {
17951 var pow = 1;
17952 word = parseBase(number, i, number.length, base);
17953
17954 for (i = 0; i < mod; i++) {
17955 pow *= base;
17956 }
17957
17958 this.imuln(pow);
17959 if (this.words[0] + word < 0x4000000) {
17960 this.words[0] += word;
17961 } else {
17962 this._iaddn(word);
17963 }
17964 }
17965 };
17966
17967 BN.prototype.copy = function copy (dest) {
17968 dest.words = new Array(this.length);
17969 for (var i = 0; i < this.length; i++) {
17970 dest.words[i] = this.words[i];
17971 }
17972 dest.length = this.length;
17973 dest.negative = this.negative;
17974 dest.red = this.red;
17975 };
17976
17977 BN.prototype.clone = function clone () {
17978 var r = new BN(null);
17979 this.copy(r);
17980 return r;
17981 };
17982
17983 BN.prototype._expand = function _expand (size) {
17984 while (this.length < size) {
17985 this.words[this.length++] = 0;
17986 }
17987 return this;
17988 };
17989
17990 // Remove leading `0` from `this`
17991 BN.prototype.strip = function strip () {
17992 while (this.length > 1 && this.words[this.length - 1] === 0) {
17993 this.length--;
17994 }
17995 return this._normSign();
17996 };
17997
17998 BN.prototype._normSign = function _normSign () {
17999 // -0 = 0
18000 if (this.length === 1 && this.words[0] === 0) {
18001 this.negative = 0;
18002 }
18003 return this;
18004 };
18005
18006 BN.prototype.inspect = function inspect () {
18007 return (this.red ? '<BN-R: ' : '<BN: ') + this.toString(16) + '>';
18008 };
18009
18010 /*
18011
18012 var zeros = [];
18013 var groupSizes = [];
18014 var groupBases = [];
18015
18016 var s = '';
18017 var i = -1;
18018 while (++i < BN.wordSize) {
18019 zeros[i] = s;
18020 s += '0';
18021 }
18022 groupSizes[0] = 0;
18023 groupSizes[1] = 0;
18024 groupBases[0] = 0;
18025 groupBases[1] = 0;
18026 var base = 2 - 1;
18027 while (++base < 36 + 1) {
18028 var groupSize = 0;
18029 var groupBase = 1;
18030 while (groupBase < (1 << BN.wordSize) / base) {
18031 groupBase *= base;
18032 groupSize += 1;
18033 }
18034 groupSizes[base] = groupSize;
18035 groupBases[base] = groupBase;
18036 }
18037
18038 */
18039
18040 var zeros = [
18041 '',
18042 '0',
18043 '00',
18044 '000',
18045 '0000',
18046 '00000',
18047 '000000',
18048 '0000000',
18049 '00000000',
18050 '000000000',
18051 '0000000000',
18052 '00000000000',
18053 '000000000000',
18054 '0000000000000',
18055 '00000000000000',
18056 '000000000000000',
18057 '0000000000000000',
18058 '00000000000000000',
18059 '000000000000000000',
18060 '0000000000000000000',
18061 '00000000000000000000',
18062 '000000000000000000000',
18063 '0000000000000000000000',
18064 '00000000000000000000000',
18065 '000000000000000000000000',
18066 '0000000000000000000000000'
18067 ];
18068
18069 var groupSizes = [
18070 0, 0,
18071 25, 16, 12, 11, 10, 9, 8,
18072 8, 7, 7, 7, 7, 6, 6,
18073 6, 6, 6, 6, 6, 5, 5,
18074 5, 5, 5, 5, 5, 5, 5,
18075 5, 5, 5, 5, 5, 5, 5
18076 ];
18077
18078 var groupBases = [
18079 0, 0,
18080 33554432, 43046721, 16777216, 48828125, 60466176, 40353607, 16777216,
18081 43046721, 10000000, 19487171, 35831808, 62748517, 7529536, 11390625,
18082 16777216, 24137569, 34012224, 47045881, 64000000, 4084101, 5153632,
18083 6436343, 7962624, 9765625, 11881376, 14348907, 17210368, 20511149,
18084 24300000, 28629151, 33554432, 39135393, 45435424, 52521875, 60466176
18085 ];
18086
18087 BN.prototype.toString = function toString (base, padding) {
18088 base = base || 10;
18089 padding = padding | 0 || 1;
18090
18091 var out;
18092 if (base === 16 || base === 'hex') {
18093 out = '';
18094 var off = 0;
18095 var carry = 0;
18096 for (var i = 0; i < this.length; i++) {
18097 var w = this.words[i];
18098 var word = (((w << off) | carry) & 0xffffff).toString(16);
18099 carry = (w >>> (24 - off)) & 0xffffff;
18100 if (carry !== 0 || i !== this.length - 1) {
18101 out = zeros[6 - word.length] + word + out;
18102 } else {
18103 out = word + out;
18104 }
18105 off += 2;
18106 if (off >= 26) {
18107 off -= 26;
18108 i--;
18109 }
18110 }
18111 if (carry !== 0) {
18112 out = carry.toString(16) + out;
18113 }
18114 while (out.length % padding !== 0) {
18115 out = '0' + out;
18116 }
18117 if (this.negative !== 0) {
18118 out = '-' + out;
18119 }
18120 return out;
18121 }
18122
18123 if (base === (base | 0) && base >= 2 && base <= 36) {
18124 // var groupSize = Math.floor(BN.wordSize * Math.LN2 / Math.log(base));
18125 var groupSize = groupSizes[base];
18126 // var groupBase = Math.pow(base, groupSize);
18127 var groupBase = groupBases[base];
18128 out = '';
18129 var c = this.clone();
18130 c.negative = 0;
18131 while (!c.isZero()) {
18132 var r = c.modn(groupBase).toString(base);
18133 c = c.idivn(groupBase);
18134
18135 if (!c.isZero()) {
18136 out = zeros[groupSize - r.length] + r + out;
18137 } else {
18138 out = r + out;
18139 }
18140 }
18141 if (this.isZero()) {
18142 out = '0' + out;
18143 }
18144 while (out.length % padding !== 0) {
18145 out = '0' + out;
18146 }
18147 if (this.negative !== 0) {
18148 out = '-' + out;
18149 }
18150 return out;
18151 }
18152
18153 assert(false, 'Base should be between 2 and 36');
18154 };
18155
18156 BN.prototype.toNumber = function toNumber () {
18157 var ret = this.words[0];
18158 if (this.length === 2) {
18159 ret += this.words[1] * 0x4000000;
18160 } else if (this.length === 3 && this.words[2] === 0x01) {
18161 // NOTE: at this stage it is known that the top bit is set
18162 ret += 0x10000000000000 + (this.words[1] * 0x4000000);
18163 } else if (this.length > 2) {
18164 assert(false, 'Number can only safely store up to 53 bits');
18165 }
18166 return (this.negative !== 0) ? -ret : ret;
18167 };
18168
18169 BN.prototype.toJSON = function toJSON () {
18170 return this.toString(16);
18171 };
18172
18173 BN.prototype.toBuffer = function toBuffer (endian, length) {
18174 assert(typeof Buffer !== 'undefined');
18175 return this.toArrayLike(Buffer, endian, length);
18176 };
18177
18178 BN.prototype.toArray = function toArray (endian, length) {
18179 return this.toArrayLike(Array, endian, length);
18180 };
18181
18182 BN.prototype.toArrayLike = function toArrayLike (ArrayType, endian, length) {
18183 var byteLength = this.byteLength();
18184 var reqLength = length || Math.max(1, byteLength);
18185 assert(byteLength <= reqLength, 'byte array longer than desired length');
18186 assert(reqLength > 0, 'Requested array length <= 0');
18187
18188 this.strip();
18189 var littleEndian = endian === 'le';
18190 var res = new ArrayType(reqLength);
18191
18192 var b, i;
18193 var q = this.clone();
18194 if (!littleEndian) {
18195 // Assume big-endian
18196 for (i = 0; i < reqLength - byteLength; i++) {
18197 res[i] = 0;
18198 }
18199
18200 for (i = 0; !q.isZero(); i++) {
18201 b = q.andln(0xff);
18202 q.iushrn(8);
18203
18204 res[reqLength - i - 1] = b;
18205 }
18206 } else {
18207 for (i = 0; !q.isZero(); i++) {
18208 b = q.andln(0xff);
18209 q.iushrn(8);
18210
18211 res[i] = b;
18212 }
18213
18214 for (; i < reqLength; i++) {
18215 res[i] = 0;
18216 }
18217 }
18218
18219 return res;
18220 };
18221
18222 if (Math.clz32) {
18223 BN.prototype._countBits = function _countBits (w) {
18224 return 32 - Math.clz32(w);
18225 };
18226 } else {
18227 BN.prototype._countBits = function _countBits (w) {
18228 var t = w;
18229 var r = 0;
18230 if (t >= 0x1000) {
18231 r += 13;
18232 t >>>= 13;
18233 }
18234 if (t >= 0x40) {
18235 r += 7;
18236 t >>>= 7;
18237 }
18238 if (t >= 0x8) {
18239 r += 4;
18240 t >>>= 4;
18241 }
18242 if (t >= 0x02) {
18243 r += 2;
18244 t >>>= 2;
18245 }
18246 return r + t;
18247 };
18248 }
18249
18250 BN.prototype._zeroBits = function _zeroBits (w) {
18251 // Short-cut
18252 if (w === 0) return 26;
18253
18254 var t = w;
18255 var r = 0;
18256 if ((t & 0x1fff) === 0) {
18257 r += 13;
18258 t >>>= 13;
18259 }
18260 if ((t & 0x7f) === 0) {
18261 r += 7;
18262 t >>>= 7;
18263 }
18264 if ((t & 0xf) === 0) {
18265 r += 4;
18266 t >>>= 4;
18267 }
18268 if ((t & 0x3) === 0) {
18269 r += 2;
18270 t >>>= 2;
18271 }
18272 if ((t & 0x1) === 0) {
18273 r++;
18274 }
18275 return r;
18276 };
18277
18278 // Return number of used bits in a BN
18279 BN.prototype.bitLength = function bitLength () {
18280 var w = this.words[this.length - 1];
18281 var hi = this._countBits(w);
18282 return (this.length - 1) * 26 + hi;
18283 };
18284
18285 function toBitArray (num) {
18286 var w = new Array(num.bitLength());
18287
18288 for (var bit = 0; bit < w.length; bit++) {
18289 var off = (bit / 26) | 0;
18290 var wbit = bit % 26;
18291
18292 w[bit] = (num.words[off] & (1 << wbit)) >>> wbit;
18293 }
18294
18295 return w;
18296 }
18297
18298 // Number of trailing zero bits
18299 BN.prototype.zeroBits = function zeroBits () {
18300 if (this.isZero()) return 0;
18301
18302 var r = 0;
18303 for (var i = 0; i < this.length; i++) {
18304 var b = this._zeroBits(this.words[i]);
18305 r += b;
18306 if (b !== 26) break;
18307 }
18308 return r;
18309 };
18310
18311 BN.prototype.byteLength = function byteLength () {
18312 return Math.ceil(this.bitLength() / 8);
18313 };
18314
18315 BN.prototype.toTwos = function toTwos (width) {
18316 if (this.negative !== 0) {
18317 return this.abs().inotn(width).iaddn(1);
18318 }
18319 return this.clone();
18320 };
18321
18322 BN.prototype.fromTwos = function fromTwos (width) {
18323 if (this.testn(width - 1)) {
18324 return this.notn(width).iaddn(1).ineg();
18325 }
18326 return this.clone();
18327 };
18328
18329 BN.prototype.isNeg = function isNeg () {
18330 return this.negative !== 0;
18331 };
18332
18333 // Return negative clone of `this`
18334 BN.prototype.neg = function neg () {
18335 return this.clone().ineg();
18336 };
18337
18338 BN.prototype.ineg = function ineg () {
18339 if (!this.isZero()) {
18340 this.negative ^= 1;
18341 }
18342
18343 return this;
18344 };
18345
18346 // Or `num` with `this` in-place
18347 BN.prototype.iuor = function iuor (num) {
18348 while (this.length < num.length) {
18349 this.words[this.length++] = 0;
18350 }
18351
18352 for (var i = 0; i < num.length; i++) {
18353 this.words[i] = this.words[i] | num.words[i];
18354 }
18355
18356 return this.strip();
18357 };
18358
18359 BN.prototype.ior = function ior (num) {
18360 assert((this.negative | num.negative) === 0);
18361 return this.iuor(num);
18362 };
18363
18364 // Or `num` with `this`
18365 BN.prototype.or = function or (num) {
18366 if (this.length > num.length) return this.clone().ior(num);
18367 return num.clone().ior(this);
18368 };
18369
18370 BN.prototype.uor = function uor (num) {
18371 if (this.length > num.length) return this.clone().iuor(num);
18372 return num.clone().iuor(this);
18373 };
18374
18375 // And `num` with `this` in-place
18376 BN.prototype.iuand = function iuand (num) {
18377 // b = min-length(num, this)
18378 var b;
18379 if (this.length > num.length) {
18380 b = num;
18381 } else {
18382 b = this;
18383 }
18384
18385 for (var i = 0; i < b.length; i++) {
18386 this.words[i] = this.words[i] & num.words[i];
18387 }
18388
18389 this.length = b.length;
18390
18391 return this.strip();
18392 };
18393
18394 BN.prototype.iand = function iand (num) {
18395 assert((this.negative | num.negative) === 0);
18396 return this.iuand(num);
18397 };
18398
18399 // And `num` with `this`
18400 BN.prototype.and = function and (num) {
18401 if (this.length > num.length) return this.clone().iand(num);
18402 return num.clone().iand(this);
18403 };
18404
18405 BN.prototype.uand = function uand (num) {
18406 if (this.length > num.length) return this.clone().iuand(num);
18407 return num.clone().iuand(this);
18408 };
18409
18410 // Xor `num` with `this` in-place
18411 BN.prototype.iuxor = function iuxor (num) {
18412 // a.length > b.length
18413 var a;
18414 var b;
18415 if (this.length > num.length) {
18416 a = this;
18417 b = num;
18418 } else {
18419 a = num;
18420 b = this;
18421 }
18422
18423 for (var i = 0; i < b.length; i++) {
18424 this.words[i] = a.words[i] ^ b.words[i];
18425 }
18426
18427 if (this !== a) {
18428 for (; i < a.length; i++) {
18429 this.words[i] = a.words[i];
18430 }
18431 }
18432
18433 this.length = a.length;
18434
18435 return this.strip();
18436 };
18437
18438 BN.prototype.ixor = function ixor (num) {
18439 assert((this.negative | num.negative) === 0);
18440 return this.iuxor(num);
18441 };
18442
18443 // Xor `num` with `this`
18444 BN.prototype.xor = function xor (num) {
18445 if (this.length > num.length) return this.clone().ixor(num);
18446 return num.clone().ixor(this);
18447 };
18448
18449 BN.prototype.uxor = function uxor (num) {
18450 if (this.length > num.length) return this.clone().iuxor(num);
18451 return num.clone().iuxor(this);
18452 };
18453
18454 // Not ``this`` with ``width`` bitwidth
18455 BN.prototype.inotn = function inotn (width) {
18456 assert(typeof width === 'number' && width >= 0);
18457
18458 var bytesNeeded = Math.ceil(width / 26) | 0;
18459 var bitsLeft = width % 26;
18460
18461 // Extend the buffer with leading zeroes
18462 this._expand(bytesNeeded);
18463
18464 if (bitsLeft > 0) {
18465 bytesNeeded--;
18466 }
18467
18468 // Handle complete words
18469 for (var i = 0; i < bytesNeeded; i++) {
18470 this.words[i] = ~this.words[i] & 0x3ffffff;
18471 }
18472
18473 // Handle the residue
18474 if (bitsLeft > 0) {
18475 this.words[i] = ~this.words[i] & (0x3ffffff >> (26 - bitsLeft));
18476 }
18477
18478 // And remove leading zeroes
18479 return this.strip();
18480 };
18481
18482 BN.prototype.notn = function notn (width) {
18483 return this.clone().inotn(width);
18484 };
18485
18486 // Set `bit` of `this`
18487 BN.prototype.setn = function setn (bit, val) {
18488 assert(typeof bit === 'number' && bit >= 0);
18489
18490 var off = (bit / 26) | 0;
18491 var wbit = bit % 26;
18492
18493 this._expand(off + 1);
18494
18495 if (val) {
18496 this.words[off] = this.words[off] | (1 << wbit);
18497 } else {
18498 this.words[off] = this.words[off] & ~(1 << wbit);
18499 }
18500
18501 return this.strip();
18502 };
18503
18504 // Add `num` to `this` in-place
18505 BN.prototype.iadd = function iadd (num) {
18506 var r;
18507
18508 // negative + positive
18509 if (this.negative !== 0 && num.negative === 0) {
18510 this.negative = 0;
18511 r = this.isub(num);
18512 this.negative ^= 1;
18513 return this._normSign();
18514
18515 // positive + negative
18516 } else if (this.negative === 0 && num.negative !== 0) {
18517 num.negative = 0;
18518 r = this.isub(num);
18519 num.negative = 1;
18520 return r._normSign();
18521 }
18522
18523 // a.length > b.length
18524 var a, b;
18525 if (this.length > num.length) {
18526 a = this;
18527 b = num;
18528 } else {
18529 a = num;
18530 b = this;
18531 }
18532
18533 var carry = 0;
18534 for (var i = 0; i < b.length; i++) {
18535 r = (a.words[i] | 0) + (b.words[i] | 0) + carry;
18536 this.words[i] = r & 0x3ffffff;
18537 carry = r >>> 26;
18538 }
18539 for (; carry !== 0 && i < a.length; i++) {
18540 r = (a.words[i] | 0) + carry;
18541 this.words[i] = r & 0x3ffffff;
18542 carry = r >>> 26;
18543 }
18544
18545 this.length = a.length;
18546 if (carry !== 0) {
18547 this.words[this.length] = carry;
18548 this.length++;
18549 // Copy the rest of the words
18550 } else if (a !== this) {
18551 for (; i < a.length; i++) {
18552 this.words[i] = a.words[i];
18553 }
18554 }
18555
18556 return this;
18557 };
18558
18559 // Add `num` to `this`
18560 BN.prototype.add = function add (num) {
18561 var res;
18562 if (num.negative !== 0 && this.negative === 0) {
18563 num.negative = 0;
18564 res = this.sub(num);
18565 num.negative ^= 1;
18566 return res;
18567 } else if (num.negative === 0 && this.negative !== 0) {
18568 this.negative = 0;
18569 res = num.sub(this);
18570 this.negative = 1;
18571 return res;
18572 }
18573
18574 if (this.length > num.length) return this.clone().iadd(num);
18575
18576 return num.clone().iadd(this);
18577 };
18578
18579 // Subtract `num` from `this` in-place
18580 BN.prototype.isub = function isub (num) {
18581 // this - (-num) = this + num
18582 if (num.negative !== 0) {
18583 num.negative = 0;
18584 var r = this.iadd(num);
18585 num.negative = 1;
18586 return r._normSign();
18587
18588 // -this - num = -(this + num)
18589 } else if (this.negative !== 0) {
18590 this.negative = 0;
18591 this.iadd(num);
18592 this.negative = 1;
18593 return this._normSign();
18594 }
18595
18596 // At this point both numbers are positive
18597 var cmp = this.cmp(num);
18598
18599 // Optimization - zeroify
18600 if (cmp === 0) {
18601 this.negative = 0;
18602 this.length = 1;
18603 this.words[0] = 0;
18604 return this;
18605 }
18606
18607 // a > b
18608 var a, b;
18609 if (cmp > 0) {
18610 a = this;
18611 b = num;
18612 } else {
18613 a = num;
18614 b = this;
18615 }
18616
18617 var carry = 0;
18618 for (var i = 0; i < b.length; i++) {
18619 r = (a.words[i] | 0) - (b.words[i] | 0) + carry;
18620 carry = r >> 26;
18621 this.words[i] = r & 0x3ffffff;
18622 }
18623 for (; carry !== 0 && i < a.length; i++) {
18624 r = (a.words[i] | 0) + carry;
18625 carry = r >> 26;
18626 this.words[i] = r & 0x3ffffff;
18627 }
18628
18629 // Copy rest of the words
18630 if (carry === 0 && i < a.length && a !== this) {
18631 for (; i < a.length; i++) {
18632 this.words[i] = a.words[i];
18633 }
18634 }
18635
18636 this.length = Math.max(this.length, i);
18637
18638 if (a !== this) {
18639 this.negative = 1;
18640 }
18641
18642 return this.strip();
18643 };
18644
18645 // Subtract `num` from `this`
18646 BN.prototype.sub = function sub (num) {
18647 return this.clone().isub(num);
18648 };
18649
18650 function smallMulTo (self, num, out) {
18651 out.negative = num.negative ^ self.negative;
18652 var len = (self.length + num.length) | 0;
18653 out.length = len;
18654 len = (len - 1) | 0;
18655
18656 // Peel one iteration (compiler can't do it, because of code complexity)
18657 var a = self.words[0] | 0;
18658 var b = num.words[0] | 0;
18659 var r = a * b;
18660
18661 var lo = r & 0x3ffffff;
18662 var carry = (r / 0x4000000) | 0;
18663 out.words[0] = lo;
18664
18665 for (var k = 1; k < len; k++) {
18666 // Sum all words with the same `i + j = k` and accumulate `ncarry`,
18667 // note that ncarry could be >= 0x3ffffff
18668 var ncarry = carry >>> 26;
18669 var rword = carry & 0x3ffffff;
18670 var maxJ = Math.min(k, num.length - 1);
18671 for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) {
18672 var i = (k - j) | 0;
18673 a = self.words[i] | 0;
18674 b = num.words[j] | 0;
18675 r = a * b + rword;
18676 ncarry += (r / 0x4000000) | 0;
18677 rword = r & 0x3ffffff;
18678 }
18679 out.words[k] = rword | 0;
18680 carry = ncarry | 0;
18681 }
18682 if (carry !== 0) {
18683 out.words[k] = carry | 0;
18684 } else {
18685 out.length--;
18686 }
18687
18688 return out.strip();
18689 }
18690
18691 // TODO(indutny): it may be reasonable to omit it for users who don't need
18692 // to work with 256-bit numbers, otherwise it gives 20% improvement for 256-bit
18693 // multiplication (like elliptic secp256k1).
18694 var comb10MulTo = function comb10MulTo (self, num, out) {
18695 var a = self.words;
18696 var b = num.words;
18697 var o = out.words;
18698 var c = 0;
18699 var lo;
18700 var mid;
18701 var hi;
18702 var a0 = a[0] | 0;
18703 var al0 = a0 & 0x1fff;
18704 var ah0 = a0 >>> 13;
18705 var a1 = a[1] | 0;
18706 var al1 = a1 & 0x1fff;
18707 var ah1 = a1 >>> 13;
18708 var a2 = a[2] | 0;
18709 var al2 = a2 & 0x1fff;
18710 var ah2 = a2 >>> 13;
18711 var a3 = a[3] | 0;
18712 var al3 = a3 & 0x1fff;
18713 var ah3 = a3 >>> 13;
18714 var a4 = a[4] | 0;
18715 var al4 = a4 & 0x1fff;
18716 var ah4 = a4 >>> 13;
18717 var a5 = a[5] | 0;
18718 var al5 = a5 & 0x1fff;
18719 var ah5 = a5 >>> 13;
18720 var a6 = a[6] | 0;
18721 var al6 = a6 & 0x1fff;
18722 var ah6 = a6 >>> 13;
18723 var a7 = a[7] | 0;
18724 var al7 = a7 & 0x1fff;
18725 var ah7 = a7 >>> 13;
18726 var a8 = a[8] | 0;
18727 var al8 = a8 & 0x1fff;
18728 var ah8 = a8 >>> 13;
18729 var a9 = a[9] | 0;
18730 var al9 = a9 & 0x1fff;
18731 var ah9 = a9 >>> 13;
18732 var b0 = b[0] | 0;
18733 var bl0 = b0 & 0x1fff;
18734 var bh0 = b0 >>> 13;
18735 var b1 = b[1] | 0;
18736 var bl1 = b1 & 0x1fff;
18737 var bh1 = b1 >>> 13;
18738 var b2 = b[2] | 0;
18739 var bl2 = b2 & 0x1fff;
18740 var bh2 = b2 >>> 13;
18741 var b3 = b[3] | 0;
18742 var bl3 = b3 & 0x1fff;
18743 var bh3 = b3 >>> 13;
18744 var b4 = b[4] | 0;
18745 var bl4 = b4 & 0x1fff;
18746 var bh4 = b4 >>> 13;
18747 var b5 = b[5] | 0;
18748 var bl5 = b5 & 0x1fff;
18749 var bh5 = b5 >>> 13;
18750 var b6 = b[6] | 0;
18751 var bl6 = b6 & 0x1fff;
18752 var bh6 = b6 >>> 13;
18753 var b7 = b[7] | 0;
18754 var bl7 = b7 & 0x1fff;
18755 var bh7 = b7 >>> 13;
18756 var b8 = b[8] | 0;
18757 var bl8 = b8 & 0x1fff;
18758 var bh8 = b8 >>> 13;
18759 var b9 = b[9] | 0;
18760 var bl9 = b9 & 0x1fff;
18761 var bh9 = b9 >>> 13;
18762
18763 out.negative = self.negative ^ num.negative;
18764 out.length = 19;
18765 /* k = 0 */
18766 lo = Math.imul(al0, bl0);
18767 mid = Math.imul(al0, bh0);
18768 mid = (mid + Math.imul(ah0, bl0)) | 0;
18769 hi = Math.imul(ah0, bh0);
18770 var w0 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
18771 c = (((hi + (mid >>> 13)) | 0) + (w0 >>> 26)) | 0;
18772 w0 &= 0x3ffffff;
18773 /* k = 1 */
18774 lo = Math.imul(al1, bl0);
18775 mid = Math.imul(al1, bh0);
18776 mid = (mid + Math.imul(ah1, bl0)) | 0;
18777 hi = Math.imul(ah1, bh0);
18778 lo = (lo + Math.imul(al0, bl1)) | 0;
18779 mid = (mid + Math.imul(al0, bh1)) | 0;
18780 mid = (mid + Math.imul(ah0, bl1)) | 0;
18781 hi = (hi + Math.imul(ah0, bh1)) | 0;
18782 var w1 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
18783 c = (((hi + (mid >>> 13)) | 0) + (w1 >>> 26)) | 0;
18784 w1 &= 0x3ffffff;
18785 /* k = 2 */
18786 lo = Math.imul(al2, bl0);
18787 mid = Math.imul(al2, bh0);
18788 mid = (mid + Math.imul(ah2, bl0)) | 0;
18789 hi = Math.imul(ah2, bh0);
18790 lo = (lo + Math.imul(al1, bl1)) | 0;
18791 mid = (mid + Math.imul(al1, bh1)) | 0;
18792 mid = (mid + Math.imul(ah1, bl1)) | 0;
18793 hi = (hi + Math.imul(ah1, bh1)) | 0;
18794 lo = (lo + Math.imul(al0, bl2)) | 0;
18795 mid = (mid + Math.imul(al0, bh2)) | 0;
18796 mid = (mid + Math.imul(ah0, bl2)) | 0;
18797 hi = (hi + Math.imul(ah0, bh2)) | 0;
18798 var w2 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
18799 c = (((hi + (mid >>> 13)) | 0) + (w2 >>> 26)) | 0;
18800 w2 &= 0x3ffffff;
18801 /* k = 3 */
18802 lo = Math.imul(al3, bl0);
18803 mid = Math.imul(al3, bh0);
18804 mid = (mid + Math.imul(ah3, bl0)) | 0;
18805 hi = Math.imul(ah3, bh0);
18806 lo = (lo + Math.imul(al2, bl1)) | 0;
18807 mid = (mid + Math.imul(al2, bh1)) | 0;
18808 mid = (mid + Math.imul(ah2, bl1)) | 0;
18809 hi = (hi + Math.imul(ah2, bh1)) | 0;
18810 lo = (lo + Math.imul(al1, bl2)) | 0;
18811 mid = (mid + Math.imul(al1, bh2)) | 0;
18812 mid = (mid + Math.imul(ah1, bl2)) | 0;
18813 hi = (hi + Math.imul(ah1, bh2)) | 0;
18814 lo = (lo + Math.imul(al0, bl3)) | 0;
18815 mid = (mid + Math.imul(al0, bh3)) | 0;
18816 mid = (mid + Math.imul(ah0, bl3)) | 0;
18817 hi = (hi + Math.imul(ah0, bh3)) | 0;
18818 var w3 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
18819 c = (((hi + (mid >>> 13)) | 0) + (w3 >>> 26)) | 0;
18820 w3 &= 0x3ffffff;
18821 /* k = 4 */
18822 lo = Math.imul(al4, bl0);
18823 mid = Math.imul(al4, bh0);
18824 mid = (mid + Math.imul(ah4, bl0)) | 0;
18825 hi = Math.imul(ah4, bh0);
18826 lo = (lo + Math.imul(al3, bl1)) | 0;
18827 mid = (mid + Math.imul(al3, bh1)) | 0;
18828 mid = (mid + Math.imul(ah3, bl1)) | 0;
18829 hi = (hi + Math.imul(ah3, bh1)) | 0;
18830 lo = (lo + Math.imul(al2, bl2)) | 0;
18831 mid = (mid + Math.imul(al2, bh2)) | 0;
18832 mid = (mid + Math.imul(ah2, bl2)) | 0;
18833 hi = (hi + Math.imul(ah2, bh2)) | 0;
18834 lo = (lo + Math.imul(al1, bl3)) | 0;
18835 mid = (mid + Math.imul(al1, bh3)) | 0;
18836 mid = (mid + Math.imul(ah1, bl3)) | 0;
18837 hi = (hi + Math.imul(ah1, bh3)) | 0;
18838 lo = (lo + Math.imul(al0, bl4)) | 0;
18839 mid = (mid + Math.imul(al0, bh4)) | 0;
18840 mid = (mid + Math.imul(ah0, bl4)) | 0;
18841 hi = (hi + Math.imul(ah0, bh4)) | 0;
18842 var w4 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
18843 c = (((hi + (mid >>> 13)) | 0) + (w4 >>> 26)) | 0;
18844 w4 &= 0x3ffffff;
18845 /* k = 5 */
18846 lo = Math.imul(al5, bl0);
18847 mid = Math.imul(al5, bh0);
18848 mid = (mid + Math.imul(ah5, bl0)) | 0;
18849 hi = Math.imul(ah5, bh0);
18850 lo = (lo + Math.imul(al4, bl1)) | 0;
18851 mid = (mid + Math.imul(al4, bh1)) | 0;
18852 mid = (mid + Math.imul(ah4, bl1)) | 0;
18853 hi = (hi + Math.imul(ah4, bh1)) | 0;
18854 lo = (lo + Math.imul(al3, bl2)) | 0;
18855 mid = (mid + Math.imul(al3, bh2)) | 0;
18856 mid = (mid + Math.imul(ah3, bl2)) | 0;
18857 hi = (hi + Math.imul(ah3, bh2)) | 0;
18858 lo = (lo + Math.imul(al2, bl3)) | 0;
18859 mid = (mid + Math.imul(al2, bh3)) | 0;
18860 mid = (mid + Math.imul(ah2, bl3)) | 0;
18861 hi = (hi + Math.imul(ah2, bh3)) | 0;
18862 lo = (lo + Math.imul(al1, bl4)) | 0;
18863 mid = (mid + Math.imul(al1, bh4)) | 0;
18864 mid = (mid + Math.imul(ah1, bl4)) | 0;
18865 hi = (hi + Math.imul(ah1, bh4)) | 0;
18866 lo = (lo + Math.imul(al0, bl5)) | 0;
18867 mid = (mid + Math.imul(al0, bh5)) | 0;
18868 mid = (mid + Math.imul(ah0, bl5)) | 0;
18869 hi = (hi + Math.imul(ah0, bh5)) | 0;
18870 var w5 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
18871 c = (((hi + (mid >>> 13)) | 0) + (w5 >>> 26)) | 0;
18872 w5 &= 0x3ffffff;
18873 /* k = 6 */
18874 lo = Math.imul(al6, bl0);
18875 mid = Math.imul(al6, bh0);
18876 mid = (mid + Math.imul(ah6, bl0)) | 0;
18877 hi = Math.imul(ah6, bh0);
18878 lo = (lo + Math.imul(al5, bl1)) | 0;
18879 mid = (mid + Math.imul(al5, bh1)) | 0;
18880 mid = (mid + Math.imul(ah5, bl1)) | 0;
18881 hi = (hi + Math.imul(ah5, bh1)) | 0;
18882 lo = (lo + Math.imul(al4, bl2)) | 0;
18883 mid = (mid + Math.imul(al4, bh2)) | 0;
18884 mid = (mid + Math.imul(ah4, bl2)) | 0;
18885 hi = (hi + Math.imul(ah4, bh2)) | 0;
18886 lo = (lo + Math.imul(al3, bl3)) | 0;
18887 mid = (mid + Math.imul(al3, bh3)) | 0;
18888 mid = (mid + Math.imul(ah3, bl3)) | 0;
18889 hi = (hi + Math.imul(ah3, bh3)) | 0;
18890 lo = (lo + Math.imul(al2, bl4)) | 0;
18891 mid = (mid + Math.imul(al2, bh4)) | 0;
18892 mid = (mid + Math.imul(ah2, bl4)) | 0;
18893 hi = (hi + Math.imul(ah2, bh4)) | 0;
18894 lo = (lo + Math.imul(al1, bl5)) | 0;
18895 mid = (mid + Math.imul(al1, bh5)) | 0;
18896 mid = (mid + Math.imul(ah1, bl5)) | 0;
18897 hi = (hi + Math.imul(ah1, bh5)) | 0;
18898 lo = (lo + Math.imul(al0, bl6)) | 0;
18899 mid = (mid + Math.imul(al0, bh6)) | 0;
18900 mid = (mid + Math.imul(ah0, bl6)) | 0;
18901 hi = (hi + Math.imul(ah0, bh6)) | 0;
18902 var w6 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
18903 c = (((hi + (mid >>> 13)) | 0) + (w6 >>> 26)) | 0;
18904 w6 &= 0x3ffffff;
18905 /* k = 7 */
18906 lo = Math.imul(al7, bl0);
18907 mid = Math.imul(al7, bh0);
18908 mid = (mid + Math.imul(ah7, bl0)) | 0;
18909 hi = Math.imul(ah7, bh0);
18910 lo = (lo + Math.imul(al6, bl1)) | 0;
18911 mid = (mid + Math.imul(al6, bh1)) | 0;
18912 mid = (mid + Math.imul(ah6, bl1)) | 0;
18913 hi = (hi + Math.imul(ah6, bh1)) | 0;
18914 lo = (lo + Math.imul(al5, bl2)) | 0;
18915 mid = (mid + Math.imul(al5, bh2)) | 0;
18916 mid = (mid + Math.imul(ah5, bl2)) | 0;
18917 hi = (hi + Math.imul(ah5, bh2)) | 0;
18918 lo = (lo + Math.imul(al4, bl3)) | 0;
18919 mid = (mid + Math.imul(al4, bh3)) | 0;
18920 mid = (mid + Math.imul(ah4, bl3)) | 0;
18921 hi = (hi + Math.imul(ah4, bh3)) | 0;
18922 lo = (lo + Math.imul(al3, bl4)) | 0;
18923 mid = (mid + Math.imul(al3, bh4)) | 0;
18924 mid = (mid + Math.imul(ah3, bl4)) | 0;
18925 hi = (hi + Math.imul(ah3, bh4)) | 0;
18926 lo = (lo + Math.imul(al2, bl5)) | 0;
18927 mid = (mid + Math.imul(al2, bh5)) | 0;
18928 mid = (mid + Math.imul(ah2, bl5)) | 0;
18929 hi = (hi + Math.imul(ah2, bh5)) | 0;
18930 lo = (lo + Math.imul(al1, bl6)) | 0;
18931 mid = (mid + Math.imul(al1, bh6)) | 0;
18932 mid = (mid + Math.imul(ah1, bl6)) | 0;
18933 hi = (hi + Math.imul(ah1, bh6)) | 0;
18934 lo = (lo + Math.imul(al0, bl7)) | 0;
18935 mid = (mid + Math.imul(al0, bh7)) | 0;
18936 mid = (mid + Math.imul(ah0, bl7)) | 0;
18937 hi = (hi + Math.imul(ah0, bh7)) | 0;
18938 var w7 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
18939 c = (((hi + (mid >>> 13)) | 0) + (w7 >>> 26)) | 0;
18940 w7 &= 0x3ffffff;
18941 /* k = 8 */
18942 lo = Math.imul(al8, bl0);
18943 mid = Math.imul(al8, bh0);
18944 mid = (mid + Math.imul(ah8, bl0)) | 0;
18945 hi = Math.imul(ah8, bh0);
18946 lo = (lo + Math.imul(al7, bl1)) | 0;
18947 mid = (mid + Math.imul(al7, bh1)) | 0;
18948 mid = (mid + Math.imul(ah7, bl1)) | 0;
18949 hi = (hi + Math.imul(ah7, bh1)) | 0;
18950 lo = (lo + Math.imul(al6, bl2)) | 0;
18951 mid = (mid + Math.imul(al6, bh2)) | 0;
18952 mid = (mid + Math.imul(ah6, bl2)) | 0;
18953 hi = (hi + Math.imul(ah6, bh2)) | 0;
18954 lo = (lo + Math.imul(al5, bl3)) | 0;
18955 mid = (mid + Math.imul(al5, bh3)) | 0;
18956 mid = (mid + Math.imul(ah5, bl3)) | 0;
18957 hi = (hi + Math.imul(ah5, bh3)) | 0;
18958 lo = (lo + Math.imul(al4, bl4)) | 0;
18959 mid = (mid + Math.imul(al4, bh4)) | 0;
18960 mid = (mid + Math.imul(ah4, bl4)) | 0;
18961 hi = (hi + Math.imul(ah4, bh4)) | 0;
18962 lo = (lo + Math.imul(al3, bl5)) | 0;
18963 mid = (mid + Math.imul(al3, bh5)) | 0;
18964 mid = (mid + Math.imul(ah3, bl5)) | 0;
18965 hi = (hi + Math.imul(ah3, bh5)) | 0;
18966 lo = (lo + Math.imul(al2, bl6)) | 0;
18967 mid = (mid + Math.imul(al2, bh6)) | 0;
18968 mid = (mid + Math.imul(ah2, bl6)) | 0;
18969 hi = (hi + Math.imul(ah2, bh6)) | 0;
18970 lo = (lo + Math.imul(al1, bl7)) | 0;
18971 mid = (mid + Math.imul(al1, bh7)) | 0;
18972 mid = (mid + Math.imul(ah1, bl7)) | 0;
18973 hi = (hi + Math.imul(ah1, bh7)) | 0;
18974 lo = (lo + Math.imul(al0, bl8)) | 0;
18975 mid = (mid + Math.imul(al0, bh8)) | 0;
18976 mid = (mid + Math.imul(ah0, bl8)) | 0;
18977 hi = (hi + Math.imul(ah0, bh8)) | 0;
18978 var w8 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
18979 c = (((hi + (mid >>> 13)) | 0) + (w8 >>> 26)) | 0;
18980 w8 &= 0x3ffffff;
18981 /* k = 9 */
18982 lo = Math.imul(al9, bl0);
18983 mid = Math.imul(al9, bh0);
18984 mid = (mid + Math.imul(ah9, bl0)) | 0;
18985 hi = Math.imul(ah9, bh0);
18986 lo = (lo + Math.imul(al8, bl1)) | 0;
18987 mid = (mid + Math.imul(al8, bh1)) | 0;
18988 mid = (mid + Math.imul(ah8, bl1)) | 0;
18989 hi = (hi + Math.imul(ah8, bh1)) | 0;
18990 lo = (lo + Math.imul(al7, bl2)) | 0;
18991 mid = (mid + Math.imul(al7, bh2)) | 0;
18992 mid = (mid + Math.imul(ah7, bl2)) | 0;
18993 hi = (hi + Math.imul(ah7, bh2)) | 0;
18994 lo = (lo + Math.imul(al6, bl3)) | 0;
18995 mid = (mid + Math.imul(al6, bh3)) | 0;
18996 mid = (mid + Math.imul(ah6, bl3)) | 0;
18997 hi = (hi + Math.imul(ah6, bh3)) | 0;
18998 lo = (lo + Math.imul(al5, bl4)) | 0;
18999 mid = (mid + Math.imul(al5, bh4)) | 0;
19000 mid = (mid + Math.imul(ah5, bl4)) | 0;
19001 hi = (hi + Math.imul(ah5, bh4)) | 0;
19002 lo = (lo + Math.imul(al4, bl5)) | 0;
19003 mid = (mid + Math.imul(al4, bh5)) | 0;
19004 mid = (mid + Math.imul(ah4, bl5)) | 0;
19005 hi = (hi + Math.imul(ah4, bh5)) | 0;
19006 lo = (lo + Math.imul(al3, bl6)) | 0;
19007 mid = (mid + Math.imul(al3, bh6)) | 0;
19008 mid = (mid + Math.imul(ah3, bl6)) | 0;
19009 hi = (hi + Math.imul(ah3, bh6)) | 0;
19010 lo = (lo + Math.imul(al2, bl7)) | 0;
19011 mid = (mid + Math.imul(al2, bh7)) | 0;
19012 mid = (mid + Math.imul(ah2, bl7)) | 0;
19013 hi = (hi + Math.imul(ah2, bh7)) | 0;
19014 lo = (lo + Math.imul(al1, bl8)) | 0;
19015 mid = (mid + Math.imul(al1, bh8)) | 0;
19016 mid = (mid + Math.imul(ah1, bl8)) | 0;
19017 hi = (hi + Math.imul(ah1, bh8)) | 0;
19018 lo = (lo + Math.imul(al0, bl9)) | 0;
19019 mid = (mid + Math.imul(al0, bh9)) | 0;
19020 mid = (mid + Math.imul(ah0, bl9)) | 0;
19021 hi = (hi + Math.imul(ah0, bh9)) | 0;
19022 var w9 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
19023 c = (((hi + (mid >>> 13)) | 0) + (w9 >>> 26)) | 0;
19024 w9 &= 0x3ffffff;
19025 /* k = 10 */
19026 lo = Math.imul(al9, bl1);
19027 mid = Math.imul(al9, bh1);
19028 mid = (mid + Math.imul(ah9, bl1)) | 0;
19029 hi = Math.imul(ah9, bh1);
19030 lo = (lo + Math.imul(al8, bl2)) | 0;
19031 mid = (mid + Math.imul(al8, bh2)) | 0;
19032 mid = (mid + Math.imul(ah8, bl2)) | 0;
19033 hi = (hi + Math.imul(ah8, bh2)) | 0;
19034 lo = (lo + Math.imul(al7, bl3)) | 0;
19035 mid = (mid + Math.imul(al7, bh3)) | 0;
19036 mid = (mid + Math.imul(ah7, bl3)) | 0;
19037 hi = (hi + Math.imul(ah7, bh3)) | 0;
19038 lo = (lo + Math.imul(al6, bl4)) | 0;
19039 mid = (mid + Math.imul(al6, bh4)) | 0;
19040 mid = (mid + Math.imul(ah6, bl4)) | 0;
19041 hi = (hi + Math.imul(ah6, bh4)) | 0;
19042 lo = (lo + Math.imul(al5, bl5)) | 0;
19043 mid = (mid + Math.imul(al5, bh5)) | 0;
19044 mid = (mid + Math.imul(ah5, bl5)) | 0;
19045 hi = (hi + Math.imul(ah5, bh5)) | 0;
19046 lo = (lo + Math.imul(al4, bl6)) | 0;
19047 mid = (mid + Math.imul(al4, bh6)) | 0;
19048 mid = (mid + Math.imul(ah4, bl6)) | 0;
19049 hi = (hi + Math.imul(ah4, bh6)) | 0;
19050 lo = (lo + Math.imul(al3, bl7)) | 0;
19051 mid = (mid + Math.imul(al3, bh7)) | 0;
19052 mid = (mid + Math.imul(ah3, bl7)) | 0;
19053 hi = (hi + Math.imul(ah3, bh7)) | 0;
19054 lo = (lo + Math.imul(al2, bl8)) | 0;
19055 mid = (mid + Math.imul(al2, bh8)) | 0;
19056 mid = (mid + Math.imul(ah2, bl8)) | 0;
19057 hi = (hi + Math.imul(ah2, bh8)) | 0;
19058 lo = (lo + Math.imul(al1, bl9)) | 0;
19059 mid = (mid + Math.imul(al1, bh9)) | 0;
19060 mid = (mid + Math.imul(ah1, bl9)) | 0;
19061 hi = (hi + Math.imul(ah1, bh9)) | 0;
19062 var w10 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
19063 c = (((hi + (mid >>> 13)) | 0) + (w10 >>> 26)) | 0;
19064 w10 &= 0x3ffffff;
19065 /* k = 11 */
19066 lo = Math.imul(al9, bl2);
19067 mid = Math.imul(al9, bh2);
19068 mid = (mid + Math.imul(ah9, bl2)) | 0;
19069 hi = Math.imul(ah9, bh2);
19070 lo = (lo + Math.imul(al8, bl3)) | 0;
19071 mid = (mid + Math.imul(al8, bh3)) | 0;
19072 mid = (mid + Math.imul(ah8, bl3)) | 0;
19073 hi = (hi + Math.imul(ah8, bh3)) | 0;
19074 lo = (lo + Math.imul(al7, bl4)) | 0;
19075 mid = (mid + Math.imul(al7, bh4)) | 0;
19076 mid = (mid + Math.imul(ah7, bl4)) | 0;
19077 hi = (hi + Math.imul(ah7, bh4)) | 0;
19078 lo = (lo + Math.imul(al6, bl5)) | 0;
19079 mid = (mid + Math.imul(al6, bh5)) | 0;
19080 mid = (mid + Math.imul(ah6, bl5)) | 0;
19081 hi = (hi + Math.imul(ah6, bh5)) | 0;
19082 lo = (lo + Math.imul(al5, bl6)) | 0;
19083 mid = (mid + Math.imul(al5, bh6)) | 0;
19084 mid = (mid + Math.imul(ah5, bl6)) | 0;
19085 hi = (hi + Math.imul(ah5, bh6)) | 0;
19086 lo = (lo + Math.imul(al4, bl7)) | 0;
19087 mid = (mid + Math.imul(al4, bh7)) | 0;
19088 mid = (mid + Math.imul(ah4, bl7)) | 0;
19089 hi = (hi + Math.imul(ah4, bh7)) | 0;
19090 lo = (lo + Math.imul(al3, bl8)) | 0;
19091 mid = (mid + Math.imul(al3, bh8)) | 0;
19092 mid = (mid + Math.imul(ah3, bl8)) | 0;
19093 hi = (hi + Math.imul(ah3, bh8)) | 0;
19094 lo = (lo + Math.imul(al2, bl9)) | 0;
19095 mid = (mid + Math.imul(al2, bh9)) | 0;
19096 mid = (mid + Math.imul(ah2, bl9)) | 0;
19097 hi = (hi + Math.imul(ah2, bh9)) | 0;
19098 var w11 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
19099 c = (((hi + (mid >>> 13)) | 0) + (w11 >>> 26)) | 0;
19100 w11 &= 0x3ffffff;
19101 /* k = 12 */
19102 lo = Math.imul(al9, bl3);
19103 mid = Math.imul(al9, bh3);
19104 mid = (mid + Math.imul(ah9, bl3)) | 0;
19105 hi = Math.imul(ah9, bh3);
19106 lo = (lo + Math.imul(al8, bl4)) | 0;
19107 mid = (mid + Math.imul(al8, bh4)) | 0;
19108 mid = (mid + Math.imul(ah8, bl4)) | 0;
19109 hi = (hi + Math.imul(ah8, bh4)) | 0;
19110 lo = (lo + Math.imul(al7, bl5)) | 0;
19111 mid = (mid + Math.imul(al7, bh5)) | 0;
19112 mid = (mid + Math.imul(ah7, bl5)) | 0;
19113 hi = (hi + Math.imul(ah7, bh5)) | 0;
19114 lo = (lo + Math.imul(al6, bl6)) | 0;
19115 mid = (mid + Math.imul(al6, bh6)) | 0;
19116 mid = (mid + Math.imul(ah6, bl6)) | 0;
19117 hi = (hi + Math.imul(ah6, bh6)) | 0;
19118 lo = (lo + Math.imul(al5, bl7)) | 0;
19119 mid = (mid + Math.imul(al5, bh7)) | 0;
19120 mid = (mid + Math.imul(ah5, bl7)) | 0;
19121 hi = (hi + Math.imul(ah5, bh7)) | 0;
19122 lo = (lo + Math.imul(al4, bl8)) | 0;
19123 mid = (mid + Math.imul(al4, bh8)) | 0;
19124 mid = (mid + Math.imul(ah4, bl8)) | 0;
19125 hi = (hi + Math.imul(ah4, bh8)) | 0;
19126 lo = (lo + Math.imul(al3, bl9)) | 0;
19127 mid = (mid + Math.imul(al3, bh9)) | 0;
19128 mid = (mid + Math.imul(ah3, bl9)) | 0;
19129 hi = (hi + Math.imul(ah3, bh9)) | 0;
19130 var w12 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
19131 c = (((hi + (mid >>> 13)) | 0) + (w12 >>> 26)) | 0;
19132 w12 &= 0x3ffffff;
19133 /* k = 13 */
19134 lo = Math.imul(al9, bl4);
19135 mid = Math.imul(al9, bh4);
19136 mid = (mid + Math.imul(ah9, bl4)) | 0;
19137 hi = Math.imul(ah9, bh4);
19138 lo = (lo + Math.imul(al8, bl5)) | 0;
19139 mid = (mid + Math.imul(al8, bh5)) | 0;
19140 mid = (mid + Math.imul(ah8, bl5)) | 0;
19141 hi = (hi + Math.imul(ah8, bh5)) | 0;
19142 lo = (lo + Math.imul(al7, bl6)) | 0;
19143 mid = (mid + Math.imul(al7, bh6)) | 0;
19144 mid = (mid + Math.imul(ah7, bl6)) | 0;
19145 hi = (hi + Math.imul(ah7, bh6)) | 0;
19146 lo = (lo + Math.imul(al6, bl7)) | 0;
19147 mid = (mid + Math.imul(al6, bh7)) | 0;
19148 mid = (mid + Math.imul(ah6, bl7)) | 0;
19149 hi = (hi + Math.imul(ah6, bh7)) | 0;
19150 lo = (lo + Math.imul(al5, bl8)) | 0;
19151 mid = (mid + Math.imul(al5, bh8)) | 0;
19152 mid = (mid + Math.imul(ah5, bl8)) | 0;
19153 hi = (hi + Math.imul(ah5, bh8)) | 0;
19154 lo = (lo + Math.imul(al4, bl9)) | 0;
19155 mid = (mid + Math.imul(al4, bh9)) | 0;
19156 mid = (mid + Math.imul(ah4, bl9)) | 0;
19157 hi = (hi + Math.imul(ah4, bh9)) | 0;
19158 var w13 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
19159 c = (((hi + (mid >>> 13)) | 0) + (w13 >>> 26)) | 0;
19160 w13 &= 0x3ffffff;
19161 /* k = 14 */
19162 lo = Math.imul(al9, bl5);
19163 mid = Math.imul(al9, bh5);
19164 mid = (mid + Math.imul(ah9, bl5)) | 0;
19165 hi = Math.imul(ah9, bh5);
19166 lo = (lo + Math.imul(al8, bl6)) | 0;
19167 mid = (mid + Math.imul(al8, bh6)) | 0;
19168 mid = (mid + Math.imul(ah8, bl6)) | 0;
19169 hi = (hi + Math.imul(ah8, bh6)) | 0;
19170 lo = (lo + Math.imul(al7, bl7)) | 0;
19171 mid = (mid + Math.imul(al7, bh7)) | 0;
19172 mid = (mid + Math.imul(ah7, bl7)) | 0;
19173 hi = (hi + Math.imul(ah7, bh7)) | 0;
19174 lo = (lo + Math.imul(al6, bl8)) | 0;
19175 mid = (mid + Math.imul(al6, bh8)) | 0;
19176 mid = (mid + Math.imul(ah6, bl8)) | 0;
19177 hi = (hi + Math.imul(ah6, bh8)) | 0;
19178 lo = (lo + Math.imul(al5, bl9)) | 0;
19179 mid = (mid + Math.imul(al5, bh9)) | 0;
19180 mid = (mid + Math.imul(ah5, bl9)) | 0;
19181 hi = (hi + Math.imul(ah5, bh9)) | 0;
19182 var w14 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
19183 c = (((hi + (mid >>> 13)) | 0) + (w14 >>> 26)) | 0;
19184 w14 &= 0x3ffffff;
19185 /* k = 15 */
19186 lo = Math.imul(al9, bl6);
19187 mid = Math.imul(al9, bh6);
19188 mid = (mid + Math.imul(ah9, bl6)) | 0;
19189 hi = Math.imul(ah9, bh6);
19190 lo = (lo + Math.imul(al8, bl7)) | 0;
19191 mid = (mid + Math.imul(al8, bh7)) | 0;
19192 mid = (mid + Math.imul(ah8, bl7)) | 0;
19193 hi = (hi + Math.imul(ah8, bh7)) | 0;
19194 lo = (lo + Math.imul(al7, bl8)) | 0;
19195 mid = (mid + Math.imul(al7, bh8)) | 0;
19196 mid = (mid + Math.imul(ah7, bl8)) | 0;
19197 hi = (hi + Math.imul(ah7, bh8)) | 0;
19198 lo = (lo + Math.imul(al6, bl9)) | 0;
19199 mid = (mid + Math.imul(al6, bh9)) | 0;
19200 mid = (mid + Math.imul(ah6, bl9)) | 0;
19201 hi = (hi + Math.imul(ah6, bh9)) | 0;
19202 var w15 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
19203 c = (((hi + (mid >>> 13)) | 0) + (w15 >>> 26)) | 0;
19204 w15 &= 0x3ffffff;
19205 /* k = 16 */
19206 lo = Math.imul(al9, bl7);
19207 mid = Math.imul(al9, bh7);
19208 mid = (mid + Math.imul(ah9, bl7)) | 0;
19209 hi = Math.imul(ah9, bh7);
19210 lo = (lo + Math.imul(al8, bl8)) | 0;
19211 mid = (mid + Math.imul(al8, bh8)) | 0;
19212 mid = (mid + Math.imul(ah8, bl8)) | 0;
19213 hi = (hi + Math.imul(ah8, bh8)) | 0;
19214 lo = (lo + Math.imul(al7, bl9)) | 0;
19215 mid = (mid + Math.imul(al7, bh9)) | 0;
19216 mid = (mid + Math.imul(ah7, bl9)) | 0;
19217 hi = (hi + Math.imul(ah7, bh9)) | 0;
19218 var w16 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
19219 c = (((hi + (mid >>> 13)) | 0) + (w16 >>> 26)) | 0;
19220 w16 &= 0x3ffffff;
19221 /* k = 17 */
19222 lo = Math.imul(al9, bl8);
19223 mid = Math.imul(al9, bh8);
19224 mid = (mid + Math.imul(ah9, bl8)) | 0;
19225 hi = Math.imul(ah9, bh8);
19226 lo = (lo + Math.imul(al8, bl9)) | 0;
19227 mid = (mid + Math.imul(al8, bh9)) | 0;
19228 mid = (mid + Math.imul(ah8, bl9)) | 0;
19229 hi = (hi + Math.imul(ah8, bh9)) | 0;
19230 var w17 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
19231 c = (((hi + (mid >>> 13)) | 0) + (w17 >>> 26)) | 0;
19232 w17 &= 0x3ffffff;
19233 /* k = 18 */
19234 lo = Math.imul(al9, bl9);
19235 mid = Math.imul(al9, bh9);
19236 mid = (mid + Math.imul(ah9, bl9)) | 0;
19237 hi = Math.imul(ah9, bh9);
19238 var w18 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
19239 c = (((hi + (mid >>> 13)) | 0) + (w18 >>> 26)) | 0;
19240 w18 &= 0x3ffffff;
19241 o[0] = w0;
19242 o[1] = w1;
19243 o[2] = w2;
19244 o[3] = w3;
19245 o[4] = w4;
19246 o[5] = w5;
19247 o[6] = w6;
19248 o[7] = w7;
19249 o[8] = w8;
19250 o[9] = w9;
19251 o[10] = w10;
19252 o[11] = w11;
19253 o[12] = w12;
19254 o[13] = w13;
19255 o[14] = w14;
19256 o[15] = w15;
19257 o[16] = w16;
19258 o[17] = w17;
19259 o[18] = w18;
19260 if (c !== 0) {
19261 o[19] = c;
19262 out.length++;
19263 }
19264 return out;
19265 };
19266
19267 // Polyfill comb
19268 if (!Math.imul) {
19269 comb10MulTo = smallMulTo;
19270 }
19271
19272 function bigMulTo (self, num, out) {
19273 out.negative = num.negative ^ self.negative;
19274 out.length = self.length + num.length;
19275
19276 var carry = 0;
19277 var hncarry = 0;
19278 for (var k = 0; k < out.length - 1; k++) {
19279 // Sum all words with the same `i + j = k` and accumulate `ncarry`,
19280 // note that ncarry could be >= 0x3ffffff
19281 var ncarry = hncarry;
19282 hncarry = 0;
19283 var rword = carry & 0x3ffffff;
19284 var maxJ = Math.min(k, num.length - 1);
19285 for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) {
19286 var i = k - j;
19287 var a = self.words[i] | 0;
19288 var b = num.words[j] | 0;
19289 var r = a * b;
19290
19291 var lo = r & 0x3ffffff;
19292 ncarry = (ncarry + ((r / 0x4000000) | 0)) | 0;
19293 lo = (lo + rword) | 0;
19294 rword = lo & 0x3ffffff;
19295 ncarry = (ncarry + (lo >>> 26)) | 0;
19296
19297 hncarry += ncarry >>> 26;
19298 ncarry &= 0x3ffffff;
19299 }
19300 out.words[k] = rword;
19301 carry = ncarry;
19302 ncarry = hncarry;
19303 }
19304 if (carry !== 0) {
19305 out.words[k] = carry;
19306 } else {
19307 out.length--;
19308 }
19309
19310 return out.strip();
19311 }
19312
19313 function jumboMulTo (self, num, out) {
19314 var fftm = new FFTM();
19315 return fftm.mulp(self, num, out);
19316 }
19317
19318 BN.prototype.mulTo = function mulTo (num, out) {
19319 var res;
19320 var len = this.length + num.length;
19321 if (this.length === 10 && num.length === 10) {
19322 res = comb10MulTo(this, num, out);
19323 } else if (len < 63) {
19324 res = smallMulTo(this, num, out);
19325 } else if (len < 1024) {
19326 res = bigMulTo(this, num, out);
19327 } else {
19328 res = jumboMulTo(this, num, out);
19329 }
19330
19331 return res;
19332 };
19333
19334 // Cooley-Tukey algorithm for FFT
19335 // slightly revisited to rely on looping instead of recursion
19336
19337 function FFTM (x, y) {
19338 this.x = x;
19339 this.y = y;
19340 }
19341
19342 FFTM.prototype.makeRBT = function makeRBT (N) {
19343 var t = new Array(N);
19344 var l = BN.prototype._countBits(N) - 1;
19345 for (var i = 0; i < N; i++) {
19346 t[i] = this.revBin(i, l, N);
19347 }
19348
19349 return t;
19350 };
19351
19352 // Returns binary-reversed representation of `x`
19353 FFTM.prototype.revBin = function revBin (x, l, N) {
19354 if (x === 0 || x === N - 1) return x;
19355
19356 var rb = 0;
19357 for (var i = 0; i < l; i++) {
19358 rb |= (x & 1) << (l - i - 1);
19359 x >>= 1;
19360 }
19361
19362 return rb;
19363 };
19364
19365 // Performs "tweedling" phase, therefore 'emulating'
19366 // behaviour of the recursive algorithm
19367 FFTM.prototype.permute = function permute (rbt, rws, iws, rtws, itws, N) {
19368 for (var i = 0; i < N; i++) {
19369 rtws[i] = rws[rbt[i]];
19370 itws[i] = iws[rbt[i]];
19371 }
19372 };
19373
19374 FFTM.prototype.transform = function transform (rws, iws, rtws, itws, N, rbt) {
19375 this.permute(rbt, rws, iws, rtws, itws, N);
19376
19377 for (var s = 1; s < N; s <<= 1) {
19378 var l = s << 1;
19379
19380 var rtwdf = Math.cos(2 * Math.PI / l);
19381 var itwdf = Math.sin(2 * Math.PI / l);
19382
19383 for (var p = 0; p < N; p += l) {
19384 var rtwdf_ = rtwdf;
19385 var itwdf_ = itwdf;
19386
19387 for (var j = 0; j < s; j++) {
19388 var re = rtws[p + j];
19389 var ie = itws[p + j];
19390
19391 var ro = rtws[p + j + s];
19392 var io = itws[p + j + s];
19393
19394 var rx = rtwdf_ * ro - itwdf_ * io;
19395
19396 io = rtwdf_ * io + itwdf_ * ro;
19397 ro = rx;
19398
19399 rtws[p + j] = re + ro;
19400 itws[p + j] = ie + io;
19401
19402 rtws[p + j + s] = re - ro;
19403 itws[p + j + s] = ie - io;
19404
19405 /* jshint maxdepth : false */
19406 if (j !== l) {
19407 rx = rtwdf * rtwdf_ - itwdf * itwdf_;
19408
19409 itwdf_ = rtwdf * itwdf_ + itwdf * rtwdf_;
19410 rtwdf_ = rx;
19411 }
19412 }
19413 }
19414 }
19415 };
19416
19417 FFTM.prototype.guessLen13b = function guessLen13b (n, m) {
19418 var N = Math.max(m, n) | 1;
19419 var odd = N & 1;
19420 var i = 0;
19421 for (N = N / 2 | 0; N; N = N >>> 1) {
19422 i++;
19423 }
19424
19425 return 1 << i + 1 + odd;
19426 };
19427
19428 FFTM.prototype.conjugate = function conjugate (rws, iws, N) {
19429 if (N <= 1) return;
19430
19431 for (var i = 0; i < N / 2; i++) {
19432 var t = rws[i];
19433
19434 rws[i] = rws[N - i - 1];
19435 rws[N - i - 1] = t;
19436
19437 t = iws[i];
19438
19439 iws[i] = -iws[N - i - 1];
19440 iws[N - i - 1] = -t;
19441 }
19442 };
19443
19444 FFTM.prototype.normalize13b = function normalize13b (ws, N) {
19445 var carry = 0;
19446 for (var i = 0; i < N / 2; i++) {
19447 var w = Math.round(ws[2 * i + 1] / N) * 0x2000 +
19448 Math.round(ws[2 * i] / N) +
19449 carry;
19450
19451 ws[i] = w & 0x3ffffff;
19452
19453 if (w < 0x4000000) {
19454 carry = 0;
19455 } else {
19456 carry = w / 0x4000000 | 0;
19457 }
19458 }
19459
19460 return ws;
19461 };
19462
19463 FFTM.prototype.convert13b = function convert13b (ws, len, rws, N) {
19464 var carry = 0;
19465 for (var i = 0; i < len; i++) {
19466 carry = carry + (ws[i] | 0);
19467
19468 rws[2 * i] = carry & 0x1fff; carry = carry >>> 13;
19469 rws[2 * i + 1] = carry & 0x1fff; carry = carry >>> 13;
19470 }
19471
19472 // Pad with zeroes
19473 for (i = 2 * len; i < N; ++i) {
19474 rws[i] = 0;
19475 }
19476
19477 assert(carry === 0);
19478 assert((carry & ~0x1fff) === 0);
19479 };
19480
19481 FFTM.prototype.stub = function stub (N) {
19482 var ph = new Array(N);
19483 for (var i = 0; i < N; i++) {
19484 ph[i] = 0;
19485 }
19486
19487 return ph;
19488 };
19489
19490 FFTM.prototype.mulp = function mulp (x, y, out) {
19491 var N = 2 * this.guessLen13b(x.length, y.length);
19492
19493 var rbt = this.makeRBT(N);
19494
19495 var _ = this.stub(N);
19496
19497 var rws = new Array(N);
19498 var rwst = new Array(N);
19499 var iwst = new Array(N);
19500
19501 var nrws = new Array(N);
19502 var nrwst = new Array(N);
19503 var niwst = new Array(N);
19504
19505 var rmws = out.words;
19506 rmws.length = N;
19507
19508 this.convert13b(x.words, x.length, rws, N);
19509 this.convert13b(y.words, y.length, nrws, N);
19510
19511 this.transform(rws, _, rwst, iwst, N, rbt);
19512 this.transform(nrws, _, nrwst, niwst, N, rbt);
19513
19514 for (var i = 0; i < N; i++) {
19515 var rx = rwst[i] * nrwst[i] - iwst[i] * niwst[i];
19516 iwst[i] = rwst[i] * niwst[i] + iwst[i] * nrwst[i];
19517 rwst[i] = rx;
19518 }
19519
19520 this.conjugate(rwst, iwst, N);
19521 this.transform(rwst, iwst, rmws, _, N, rbt);
19522 this.conjugate(rmws, _, N);
19523 this.normalize13b(rmws, N);
19524
19525 out.negative = x.negative ^ y.negative;
19526 out.length = x.length + y.length;
19527 return out.strip();
19528 };
19529
19530 // Multiply `this` by `num`
19531 BN.prototype.mul = function mul (num) {
19532 var out = new BN(null);
19533 out.words = new Array(this.length + num.length);
19534 return this.mulTo(num, out);
19535 };
19536
19537 // Multiply employing FFT
19538 BN.prototype.mulf = function mulf (num) {
19539 var out = new BN(null);
19540 out.words = new Array(this.length + num.length);
19541 return jumboMulTo(this, num, out);
19542 };
19543
19544 // In-place Multiplication
19545 BN.prototype.imul = function imul (num) {
19546 return this.clone().mulTo(num, this);
19547 };
19548
19549 BN.prototype.imuln = function imuln (num) {
19550 assert(typeof num === 'number');
19551 assert(num < 0x4000000);
19552
19553 // Carry
19554 var carry = 0;
19555 for (var i = 0; i < this.length; i++) {
19556 var w = (this.words[i] | 0) * num;
19557 var lo = (w & 0x3ffffff) + (carry & 0x3ffffff);
19558 carry >>= 26;
19559 carry += (w / 0x4000000) | 0;
19560 // NOTE: lo is 27bit maximum
19561 carry += lo >>> 26;
19562 this.words[i] = lo & 0x3ffffff;
19563 }
19564
19565 if (carry !== 0) {
19566 this.words[i] = carry;
19567 this.length++;
19568 }
19569
19570 return this;
19571 };
19572
19573 BN.prototype.muln = function muln (num) {
19574 return this.clone().imuln(num);
19575 };
19576
19577 // `this` * `this`
19578 BN.prototype.sqr = function sqr () {
19579 return this.mul(this);
19580 };
19581
19582 // `this` * `this` in-place
19583 BN.prototype.isqr = function isqr () {
19584 return this.imul(this.clone());
19585 };
19586
19587 // Math.pow(`this`, `num`)
19588 BN.prototype.pow = function pow (num) {
19589 var w = toBitArray(num);
19590 if (w.length === 0) return new BN(1);
19591
19592 // Skip leading zeroes
19593 var res = this;
19594 for (var i = 0; i < w.length; i++, res = res.sqr()) {
19595 if (w[i] !== 0) break;
19596 }
19597
19598 if (++i < w.length) {
19599 for (var q = res.sqr(); i < w.length; i++, q = q.sqr()) {
19600 if (w[i] === 0) continue;
19601
19602 res = res.mul(q);
19603 }
19604 }
19605
19606 return res;
19607 };
19608
19609 // Shift-left in-place
19610 BN.prototype.iushln = function iushln (bits) {
19611 assert(typeof bits === 'number' && bits >= 0);
19612 var r = bits % 26;
19613 var s = (bits - r) / 26;
19614 var carryMask = (0x3ffffff >>> (26 - r)) << (26 - r);
19615 var i;
19616
19617 if (r !== 0) {
19618 var carry = 0;
19619
19620 for (i = 0; i < this.length; i++) {
19621 var newCarry = this.words[i] & carryMask;
19622 var c = ((this.words[i] | 0) - newCarry) << r;
19623 this.words[i] = c | carry;
19624 carry = newCarry >>> (26 - r);
19625 }
19626
19627 if (carry) {
19628 this.words[i] = carry;
19629 this.length++;
19630 }
19631 }
19632
19633 if (s !== 0) {
19634 for (i = this.length - 1; i >= 0; i--) {
19635 this.words[i + s] = this.words[i];
19636 }
19637
19638 for (i = 0; i < s; i++) {
19639 this.words[i] = 0;
19640 }
19641
19642 this.length += s;
19643 }
19644
19645 return this.strip();
19646 };
19647
19648 BN.prototype.ishln = function ishln (bits) {
19649 // TODO(indutny): implement me
19650 assert(this.negative === 0);
19651 return this.iushln(bits);
19652 };
19653
19654 // Shift-right in-place
19655 // NOTE: `hint` is a lowest bit before trailing zeroes
19656 // NOTE: if `extended` is present - it will be filled with destroyed bits
19657 BN.prototype.iushrn = function iushrn (bits, hint, extended) {
19658 assert(typeof bits === 'number' && bits >= 0);
19659 var h;
19660 if (hint) {
19661 h = (hint - (hint % 26)) / 26;
19662 } else {
19663 h = 0;
19664 }
19665
19666 var r = bits % 26;
19667 var s = Math.min((bits - r) / 26, this.length);
19668 var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r);
19669 var maskedWords = extended;
19670
19671 h -= s;
19672 h = Math.max(0, h);
19673
19674 // Extended mode, copy masked part
19675 if (maskedWords) {
19676 for (var i = 0; i < s; i++) {
19677 maskedWords.words[i] = this.words[i];
19678 }
19679 maskedWords.length = s;
19680 }
19681
19682 if (s === 0) {
19683 // No-op, we should not move anything at all
19684 } else if (this.length > s) {
19685 this.length -= s;
19686 for (i = 0; i < this.length; i++) {
19687 this.words[i] = this.words[i + s];
19688 }
19689 } else {
19690 this.words[0] = 0;
19691 this.length = 1;
19692 }
19693
19694 var carry = 0;
19695 for (i = this.length - 1; i >= 0 && (carry !== 0 || i >= h); i--) {
19696 var word = this.words[i] | 0;
19697 this.words[i] = (carry << (26 - r)) | (word >>> r);
19698 carry = word & mask;
19699 }
19700
19701 // Push carried bits as a mask
19702 if (maskedWords && carry !== 0) {
19703 maskedWords.words[maskedWords.length++] = carry;
19704 }
19705
19706 if (this.length === 0) {
19707 this.words[0] = 0;
19708 this.length = 1;
19709 }
19710
19711 return this.strip();
19712 };
19713
19714 BN.prototype.ishrn = function ishrn (bits, hint, extended) {
19715 // TODO(indutny): implement me
19716 assert(this.negative === 0);
19717 return this.iushrn(bits, hint, extended);
19718 };
19719
19720 // Shift-left
19721 BN.prototype.shln = function shln (bits) {
19722 return this.clone().ishln(bits);
19723 };
19724
19725 BN.prototype.ushln = function ushln (bits) {
19726 return this.clone().iushln(bits);
19727 };
19728
19729 // Shift-right
19730 BN.prototype.shrn = function shrn (bits) {
19731 return this.clone().ishrn(bits);
19732 };
19733
19734 BN.prototype.ushrn = function ushrn (bits) {
19735 return this.clone().iushrn(bits);
19736 };
19737
19738 // Test if n bit is set
19739 BN.prototype.testn = function testn (bit) {
19740 assert(typeof bit === 'number' && bit >= 0);
19741 var r = bit % 26;
19742 var s = (bit - r) / 26;
19743 var q = 1 << r;
19744
19745 // Fast case: bit is much higher than all existing words
19746 if (this.length <= s) return false;
19747
19748 // Check bit and return
19749 var w = this.words[s];
19750
19751 return !!(w & q);
19752 };
19753
19754 // Return only lowers bits of number (in-place)
19755 BN.prototype.imaskn = function imaskn (bits) {
19756 assert(typeof bits === 'number' && bits >= 0);
19757 var r = bits % 26;
19758 var s = (bits - r) / 26;
19759
19760 assert(this.negative === 0, 'imaskn works only with positive numbers');
19761
19762 if (this.length <= s) {
19763 return this;
19764 }
19765
19766 if (r !== 0) {
19767 s++;
19768 }
19769 this.length = Math.min(s, this.length);
19770
19771 if (r !== 0) {
19772 var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r);
19773 this.words[this.length - 1] &= mask;
19774 }
19775
19776 return this.strip();
19777 };
19778
19779 // Return only lowers bits of number
19780 BN.prototype.maskn = function maskn (bits) {
19781 return this.clone().imaskn(bits);
19782 };
19783
19784 // Add plain number `num` to `this`
19785 BN.prototype.iaddn = function iaddn (num) {
19786 assert(typeof num === 'number');
19787 assert(num < 0x4000000);
19788 if (num < 0) return this.isubn(-num);
19789
19790 // Possible sign change
19791 if (this.negative !== 0) {
19792 if (this.length === 1 && (this.words[0] | 0) < num) {
19793 this.words[0] = num - (this.words[0] | 0);
19794 this.negative = 0;
19795 return this;
19796 }
19797
19798 this.negative = 0;
19799 this.isubn(num);
19800 this.negative = 1;
19801 return this;
19802 }
19803
19804 // Add without checks
19805 return this._iaddn(num);
19806 };
19807
19808 BN.prototype._iaddn = function _iaddn (num) {
19809 this.words[0] += num;
19810
19811 // Carry
19812 for (var i = 0; i < this.length && this.words[i] >= 0x4000000; i++) {
19813 this.words[i] -= 0x4000000;
19814 if (i === this.length - 1) {
19815 this.words[i + 1] = 1;
19816 } else {
19817 this.words[i + 1]++;
19818 }
19819 }
19820 this.length = Math.max(this.length, i + 1);
19821
19822 return this;
19823 };
19824
19825 // Subtract plain number `num` from `this`
19826 BN.prototype.isubn = function isubn (num) {
19827 assert(typeof num === 'number');
19828 assert(num < 0x4000000);
19829 if (num < 0) return this.iaddn(-num);
19830
19831 if (this.negative !== 0) {
19832 this.negative = 0;
19833 this.iaddn(num);
19834 this.negative = 1;
19835 return this;
19836 }
19837
19838 this.words[0] -= num;
19839
19840 if (this.length === 1 && this.words[0] < 0) {
19841 this.words[0] = -this.words[0];
19842 this.negative = 1;
19843 } else {
19844 // Carry
19845 for (var i = 0; i < this.length && this.words[i] < 0; i++) {
19846 this.words[i] += 0x4000000;
19847 this.words[i + 1] -= 1;
19848 }
19849 }
19850
19851 return this.strip();
19852 };
19853
19854 BN.prototype.addn = function addn (num) {
19855 return this.clone().iaddn(num);
19856 };
19857
19858 BN.prototype.subn = function subn (num) {
19859 return this.clone().isubn(num);
19860 };
19861
19862 BN.prototype.iabs = function iabs () {
19863 this.negative = 0;
19864
19865 return this;
19866 };
19867
19868 BN.prototype.abs = function abs () {
19869 return this.clone().iabs();
19870 };
19871
19872 BN.prototype._ishlnsubmul = function _ishlnsubmul (num, mul, shift) {
19873 var len = num.length + shift;
19874 var i;
19875
19876 this._expand(len);
19877
19878 var w;
19879 var carry = 0;
19880 for (i = 0; i < num.length; i++) {
19881 w = (this.words[i + shift] | 0) + carry;
19882 var right = (num.words[i] | 0) * mul;
19883 w -= right & 0x3ffffff;
19884 carry = (w >> 26) - ((right / 0x4000000) | 0);
19885 this.words[i + shift] = w & 0x3ffffff;
19886 }
19887 for (; i < this.length - shift; i++) {
19888 w = (this.words[i + shift] | 0) + carry;
19889 carry = w >> 26;
19890 this.words[i + shift] = w & 0x3ffffff;
19891 }
19892
19893 if (carry === 0) return this.strip();
19894
19895 // Subtraction overflow
19896 assert(carry === -1);
19897 carry = 0;
19898 for (i = 0; i < this.length; i++) {
19899 w = -(this.words[i] | 0) + carry;
19900 carry = w >> 26;
19901 this.words[i] = w & 0x3ffffff;
19902 }
19903 this.negative = 1;
19904
19905 return this.strip();
19906 };
19907
19908 BN.prototype._wordDiv = function _wordDiv (num, mode) {
19909 var shift = this.length - num.length;
19910
19911 var a = this.clone();
19912 var b = num;
19913
19914 // Normalize
19915 var bhi = b.words[b.length - 1] | 0;
19916 var bhiBits = this._countBits(bhi);
19917 shift = 26 - bhiBits;
19918 if (shift !== 0) {
19919 b = b.ushln(shift);
19920 a.iushln(shift);
19921 bhi = b.words[b.length - 1] | 0;
19922 }
19923
19924 // Initialize quotient
19925 var m = a.length - b.length;
19926 var q;
19927
19928 if (mode !== 'mod') {
19929 q = new BN(null);
19930 q.length = m + 1;
19931 q.words = new Array(q.length);
19932 for (var i = 0; i < q.length; i++) {
19933 q.words[i] = 0;
19934 }
19935 }
19936
19937 var diff = a.clone()._ishlnsubmul(b, 1, m);
19938 if (diff.negative === 0) {
19939 a = diff;
19940 if (q) {
19941 q.words[m] = 1;
19942 }
19943 }
19944
19945 for (var j = m - 1; j >= 0; j--) {
19946 var qj = (a.words[b.length + j] | 0) * 0x4000000 +
19947 (a.words[b.length + j - 1] | 0);
19948
19949 // NOTE: (qj / bhi) is (0x3ffffff * 0x4000000 + 0x3ffffff) / 0x2000000 max
19950 // (0x7ffffff)
19951 qj = Math.min((qj / bhi) | 0, 0x3ffffff);
19952
19953 a._ishlnsubmul(b, qj, j);
19954 while (a.negative !== 0) {
19955 qj--;
19956 a.negative = 0;
19957 a._ishlnsubmul(b, 1, j);
19958 if (!a.isZero()) {
19959 a.negative ^= 1;
19960 }
19961 }
19962 if (q) {
19963 q.words[j] = qj;
19964 }
19965 }
19966 if (q) {
19967 q.strip();
19968 }
19969 a.strip();
19970
19971 // Denormalize
19972 if (mode !== 'div' && shift !== 0) {
19973 a.iushrn(shift);
19974 }
19975
19976 return {
19977 div: q || null,
19978 mod: a
19979 };
19980 };
19981
19982 // NOTE: 1) `mode` can be set to `mod` to request mod only,
19983 // to `div` to request div only, or be absent to
19984 // request both div & mod
19985 // 2) `positive` is true if unsigned mod is requested
19986 BN.prototype.divmod = function divmod (num, mode, positive) {
19987 assert(!num.isZero());
19988
19989 if (this.isZero()) {
19990 return {
19991 div: new BN(0),
19992 mod: new BN(0)
19993 };
19994 }
19995
19996 var div, mod, res;
19997 if (this.negative !== 0 && num.negative === 0) {
19998 res = this.neg().divmod(num, mode);
19999
20000 if (mode !== 'mod') {
20001 div = res.div.neg();
20002 }
20003
20004 if (mode !== 'div') {
20005 mod = res.mod.neg();
20006 if (positive && mod.negative !== 0) {
20007 mod.iadd(num);
20008 }
20009 }
20010
20011 return {
20012 div: div,
20013 mod: mod
20014 };
20015 }
20016
20017 if (this.negative === 0 && num.negative !== 0) {
20018 res = this.divmod(num.neg(), mode);
20019
20020 if (mode !== 'mod') {
20021 div = res.div.neg();
20022 }
20023
20024 return {
20025 div: div,
20026 mod: res.mod
20027 };
20028 }
20029
20030 if ((this.negative & num.negative) !== 0) {
20031 res = this.neg().divmod(num.neg(), mode);
20032
20033 if (mode !== 'div') {
20034 mod = res.mod.neg();
20035 if (positive && mod.negative !== 0) {
20036 mod.isub(num);
20037 }
20038 }
20039
20040 return {
20041 div: res.div,
20042 mod: mod
20043 };
20044 }
20045
20046 // Both numbers are positive at this point
20047
20048 // Strip both numbers to approximate shift value
20049 if (num.length > this.length || this.cmp(num) < 0) {
20050 return {
20051 div: new BN(0),
20052 mod: this
20053 };
20054 }
20055
20056 // Very short reduction
20057 if (num.length === 1) {
20058 if (mode === 'div') {
20059 return {
20060 div: this.divn(num.words[0]),
20061 mod: null
20062 };
20063 }
20064
20065 if (mode === 'mod') {
20066 return {
20067 div: null,
20068 mod: new BN(this.modn(num.words[0]))
20069 };
20070 }
20071
20072 return {
20073 div: this.divn(num.words[0]),
20074 mod: new BN(this.modn(num.words[0]))
20075 };
20076 }
20077
20078 return this._wordDiv(num, mode);
20079 };
20080
20081 // Find `this` / `num`
20082 BN.prototype.div = function div (num) {
20083 return this.divmod(num, 'div', false).div;
20084 };
20085
20086 // Find `this` % `num`
20087 BN.prototype.mod = function mod (num) {
20088 return this.divmod(num, 'mod', false).mod;
20089 };
20090
20091 BN.prototype.umod = function umod (num) {
20092 return this.divmod(num, 'mod', true).mod;
20093 };
20094
20095 // Find Round(`this` / `num`)
20096 BN.prototype.divRound = function divRound (num) {
20097 var dm = this.divmod(num);
20098
20099 // Fast case - exact division
20100 if (dm.mod.isZero()) return dm.div;
20101
20102 var mod = dm.div.negative !== 0 ? dm.mod.isub(num) : dm.mod;
20103
20104 var half = num.ushrn(1);
20105 var r2 = num.andln(1);
20106 var cmp = mod.cmp(half);
20107
20108 // Round down
20109 if (cmp < 0 || r2 === 1 && cmp === 0) return dm.div;
20110
20111 // Round up
20112 return dm.div.negative !== 0 ? dm.div.isubn(1) : dm.div.iaddn(1);
20113 };
20114
20115 BN.prototype.modn = function modn (num) {
20116 assert(num <= 0x3ffffff);
20117 var p = (1 << 26) % num;
20118
20119 var acc = 0;
20120 for (var i = this.length - 1; i >= 0; i--) {
20121 acc = (p * acc + (this.words[i] | 0)) % num;
20122 }
20123
20124 return acc;
20125 };
20126
20127 // In-place division by number
20128 BN.prototype.idivn = function idivn (num) {
20129 assert(num <= 0x3ffffff);
20130
20131 var carry = 0;
20132 for (var i = this.length - 1; i >= 0; i--) {
20133 var w = (this.words[i] | 0) + carry * 0x4000000;
20134 this.words[i] = (w / num) | 0;
20135 carry = w % num;
20136 }
20137
20138 return this.strip();
20139 };
20140
20141 BN.prototype.divn = function divn (num) {
20142 return this.clone().idivn(num);
20143 };
20144
20145 BN.prototype.egcd = function egcd (p) {
20146 assert(p.negative === 0);
20147 assert(!p.isZero());
20148
20149 var x = this;
20150 var y = p.clone();
20151
20152 if (x.negative !== 0) {
20153 x = x.umod(p);
20154 } else {
20155 x = x.clone();
20156 }
20157
20158 // A * x + B * y = x
20159 var A = new BN(1);
20160 var B = new BN(0);
20161
20162 // C * x + D * y = y
20163 var C = new BN(0);
20164 var D = new BN(1);
20165
20166 var g = 0;
20167
20168 while (x.isEven() && y.isEven()) {
20169 x.iushrn(1);
20170 y.iushrn(1);
20171 ++g;
20172 }
20173
20174 var yp = y.clone();
20175 var xp = x.clone();
20176
20177 while (!x.isZero()) {
20178 for (var i = 0, im = 1; (x.words[0] & im) === 0 && i < 26; ++i, im <<= 1);
20179 if (i > 0) {
20180 x.iushrn(i);
20181 while (i-- > 0) {
20182 if (A.isOdd() || B.isOdd()) {
20183 A.iadd(yp);
20184 B.isub(xp);
20185 }
20186
20187 A.iushrn(1);
20188 B.iushrn(1);
20189 }
20190 }
20191
20192 for (var j = 0, jm = 1; (y.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1);
20193 if (j > 0) {
20194 y.iushrn(j);
20195 while (j-- > 0) {
20196 if (C.isOdd() || D.isOdd()) {
20197 C.iadd(yp);
20198 D.isub(xp);
20199 }
20200
20201 C.iushrn(1);
20202 D.iushrn(1);
20203 }
20204 }
20205
20206 if (x.cmp(y) >= 0) {
20207 x.isub(y);
20208 A.isub(C);
20209 B.isub(D);
20210 } else {
20211 y.isub(x);
20212 C.isub(A);
20213 D.isub(B);
20214 }
20215 }
20216
20217 return {
20218 a: C,
20219 b: D,
20220 gcd: y.iushln(g)
20221 };
20222 };
20223
20224 // This is reduced incarnation of the binary EEA
20225 // above, designated to invert members of the
20226 // _prime_ fields F(p) at a maximal speed
20227 BN.prototype._invmp = function _invmp (p) {
20228 assert(p.negative === 0);
20229 assert(!p.isZero());
20230
20231 var a = this;
20232 var b = p.clone();
20233
20234 if (a.negative !== 0) {
20235 a = a.umod(p);
20236 } else {
20237 a = a.clone();
20238 }
20239
20240 var x1 = new BN(1);
20241 var x2 = new BN(0);
20242
20243 var delta = b.clone();
20244
20245 while (a.cmpn(1) > 0 && b.cmpn(1) > 0) {
20246 for (var i = 0, im = 1; (a.words[0] & im) === 0 && i < 26; ++i, im <<= 1);
20247 if (i > 0) {
20248 a.iushrn(i);
20249 while (i-- > 0) {
20250 if (x1.isOdd()) {
20251 x1.iadd(delta);
20252 }
20253
20254 x1.iushrn(1);
20255 }
20256 }
20257
20258 for (var j = 0, jm = 1; (b.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1);
20259 if (j > 0) {
20260 b.iushrn(j);
20261 while (j-- > 0) {
20262 if (x2.isOdd()) {
20263 x2.iadd(delta);
20264 }
20265
20266 x2.iushrn(1);
20267 }
20268 }
20269
20270 if (a.cmp(b) >= 0) {
20271 a.isub(b);
20272 x1.isub(x2);
20273 } else {
20274 b.isub(a);
20275 x2.isub(x1);
20276 }
20277 }
20278
20279 var res;
20280 if (a.cmpn(1) === 0) {
20281 res = x1;
20282 } else {
20283 res = x2;
20284 }
20285
20286 if (res.cmpn(0) < 0) {
20287 res.iadd(p);
20288 }
20289
20290 return res;
20291 };
20292
20293 BN.prototype.gcd = function gcd (num) {
20294 if (this.isZero()) return num.abs();
20295 if (num.isZero()) return this.abs();
20296
20297 var a = this.clone();
20298 var b = num.clone();
20299 a.negative = 0;
20300 b.negative = 0;
20301
20302 // Remove common factor of two
20303 for (var shift = 0; a.isEven() && b.isEven(); shift++) {
20304 a.iushrn(1);
20305 b.iushrn(1);
20306 }
20307
20308 do {
20309 while (a.isEven()) {
20310 a.iushrn(1);
20311 }
20312 while (b.isEven()) {
20313 b.iushrn(1);
20314 }
20315
20316 var r = a.cmp(b);
20317 if (r < 0) {
20318 // Swap `a` and `b` to make `a` always bigger than `b`
20319 var t = a;
20320 a = b;
20321 b = t;
20322 } else if (r === 0 || b.cmpn(1) === 0) {
20323 break;
20324 }
20325
20326 a.isub(b);
20327 } while (true);
20328
20329 return b.iushln(shift);
20330 };
20331
20332 // Invert number in the field F(num)
20333 BN.prototype.invm = function invm (num) {
20334 return this.egcd(num).a.umod(num);
20335 };
20336
20337 BN.prototype.isEven = function isEven () {
20338 return (this.words[0] & 1) === 0;
20339 };
20340
20341 BN.prototype.isOdd = function isOdd () {
20342 return (this.words[0] & 1) === 1;
20343 };
20344
20345 // And first word and num
20346 BN.prototype.andln = function andln (num) {
20347 return this.words[0] & num;
20348 };
20349
20350 // Increment at the bit position in-line
20351 BN.prototype.bincn = function bincn (bit) {
20352 assert(typeof bit === 'number');
20353 var r = bit % 26;
20354 var s = (bit - r) / 26;
20355 var q = 1 << r;
20356
20357 // Fast case: bit is much higher than all existing words
20358 if (this.length <= s) {
20359 this._expand(s + 1);
20360 this.words[s] |= q;
20361 return this;
20362 }
20363
20364 // Add bit and propagate, if needed
20365 var carry = q;
20366 for (var i = s; carry !== 0 && i < this.length; i++) {
20367 var w = this.words[i] | 0;
20368 w += carry;
20369 carry = w >>> 26;
20370 w &= 0x3ffffff;
20371 this.words[i] = w;
20372 }
20373 if (carry !== 0) {
20374 this.words[i] = carry;
20375 this.length++;
20376 }
20377 return this;
20378 };
20379
20380 BN.prototype.isZero = function isZero () {
20381 return this.length === 1 && this.words[0] === 0;
20382 };
20383
20384 BN.prototype.cmpn = function cmpn (num) {
20385 var negative = num < 0;
20386
20387 if (this.negative !== 0 && !negative) return -1;
20388 if (this.negative === 0 && negative) return 1;
20389
20390 this.strip();
20391
20392 var res;
20393 if (this.length > 1) {
20394 res = 1;
20395 } else {
20396 if (negative) {
20397 num = -num;
20398 }
20399
20400 assert(num <= 0x3ffffff, 'Number is too big');
20401
20402 var w = this.words[0] | 0;
20403 res = w === num ? 0 : w < num ? -1 : 1;
20404 }
20405 if (this.negative !== 0) return -res | 0;
20406 return res;
20407 };
20408
20409 // Compare two numbers and return:
20410 // 1 - if `this` > `num`
20411 // 0 - if `this` == `num`
20412 // -1 - if `this` < `num`
20413 BN.prototype.cmp = function cmp (num) {
20414 if (this.negative !== 0 && num.negative === 0) return -1;
20415 if (this.negative === 0 && num.negative !== 0) return 1;
20416
20417 var res = this.ucmp(num);
20418 if (this.negative !== 0) return -res | 0;
20419 return res;
20420 };
20421
20422 // Unsigned comparison
20423 BN.prototype.ucmp = function ucmp (num) {
20424 // At this point both numbers have the same sign
20425 if (this.length > num.length) return 1;
20426 if (this.length < num.length) return -1;
20427
20428 var res = 0;
20429 for (var i = this.length - 1; i >= 0; i--) {
20430 var a = this.words[i] | 0;
20431 var b = num.words[i] | 0;
20432
20433 if (a === b) continue;
20434 if (a < b) {
20435 res = -1;
20436 } else if (a > b) {
20437 res = 1;
20438 }
20439 break;
20440 }
20441 return res;
20442 };
20443
20444 BN.prototype.gtn = function gtn (num) {
20445 return this.cmpn(num) === 1;
20446 };
20447
20448 BN.prototype.gt = function gt (num) {
20449 return this.cmp(num) === 1;
20450 };
20451
20452 BN.prototype.gten = function gten (num) {
20453 return this.cmpn(num) >= 0;
20454 };
20455
20456 BN.prototype.gte = function gte (num) {
20457 return this.cmp(num) >= 0;
20458 };
20459
20460 BN.prototype.ltn = function ltn (num) {
20461 return this.cmpn(num) === -1;
20462 };
20463
20464 BN.prototype.lt = function lt (num) {
20465 return this.cmp(num) === -1;
20466 };
20467
20468 BN.prototype.lten = function lten (num) {
20469 return this.cmpn(num) <= 0;
20470 };
20471
20472 BN.prototype.lte = function lte (num) {
20473 return this.cmp(num) <= 0;
20474 };
20475
20476 BN.prototype.eqn = function eqn (num) {
20477 return this.cmpn(num) === 0;
20478 };
20479
20480 BN.prototype.eq = function eq (num) {
20481 return this.cmp(num) === 0;
20482 };
20483
20484 //
20485 // A reduce context, could be using montgomery or something better, depending
20486 // on the `m` itself.
20487 //
20488 BN.red = function red (num) {
20489 return new Red(num);
20490 };
20491
20492 BN.prototype.toRed = function toRed (ctx) {
20493 assert(!this.red, 'Already a number in reduction context');
20494 assert(this.negative === 0, 'red works only with positives');
20495 return ctx.convertTo(this)._forceRed(ctx);
20496 };
20497
20498 BN.prototype.fromRed = function fromRed () {
20499 assert(this.red, 'fromRed works only with numbers in reduction context');
20500 return this.red.convertFrom(this);
20501 };
20502
20503 BN.prototype._forceRed = function _forceRed (ctx) {
20504 this.red = ctx;
20505 return this;
20506 };
20507
20508 BN.prototype.forceRed = function forceRed (ctx) {
20509 assert(!this.red, 'Already a number in reduction context');
20510 return this._forceRed(ctx);
20511 };
20512
20513 BN.prototype.redAdd = function redAdd (num) {
20514 assert(this.red, 'redAdd works only with red numbers');
20515 return this.red.add(this, num);
20516 };
20517
20518 BN.prototype.redIAdd = function redIAdd (num) {
20519 assert(this.red, 'redIAdd works only with red numbers');
20520 return this.red.iadd(this, num);
20521 };
20522
20523 BN.prototype.redSub = function redSub (num) {
20524 assert(this.red, 'redSub works only with red numbers');
20525 return this.red.sub(this, num);
20526 };
20527
20528 BN.prototype.redISub = function redISub (num) {
20529 assert(this.red, 'redISub works only with red numbers');
20530 return this.red.isub(this, num);
20531 };
20532
20533 BN.prototype.redShl = function redShl (num) {
20534 assert(this.red, 'redShl works only with red numbers');
20535 return this.red.shl(this, num);
20536 };
20537
20538 BN.prototype.redMul = function redMul (num) {
20539 assert(this.red, 'redMul works only with red numbers');
20540 this.red._verify2(this, num);
20541 return this.red.mul(this, num);
20542 };
20543
20544 BN.prototype.redIMul = function redIMul (num) {
20545 assert(this.red, 'redMul works only with red numbers');
20546 this.red._verify2(this, num);
20547 return this.red.imul(this, num);
20548 };
20549
20550 BN.prototype.redSqr = function redSqr () {
20551 assert(this.red, 'redSqr works only with red numbers');
20552 this.red._verify1(this);
20553 return this.red.sqr(this);
20554 };
20555
20556 BN.prototype.redISqr = function redISqr () {
20557 assert(this.red, 'redISqr works only with red numbers');
20558 this.red._verify1(this);
20559 return this.red.isqr(this);
20560 };
20561
20562 // Square root over p
20563 BN.prototype.redSqrt = function redSqrt () {
20564 assert(this.red, 'redSqrt works only with red numbers');
20565 this.red._verify1(this);
20566 return this.red.sqrt(this);
20567 };
20568
20569 BN.prototype.redInvm = function redInvm () {
20570 assert(this.red, 'redInvm works only with red numbers');
20571 this.red._verify1(this);
20572 return this.red.invm(this);
20573 };
20574
20575 // Return negative clone of `this` % `red modulo`
20576 BN.prototype.redNeg = function redNeg () {
20577 assert(this.red, 'redNeg works only with red numbers');
20578 this.red._verify1(this);
20579 return this.red.neg(this);
20580 };
20581
20582 BN.prototype.redPow = function redPow (num) {
20583 assert(this.red && !num.red, 'redPow(normalNum)');
20584 this.red._verify1(this);
20585 return this.red.pow(this, num);
20586 };
20587
20588 // Prime numbers with efficient reduction
20589 var primes = {
20590 k256: null,
20591 p224: null,
20592 p192: null,
20593 p25519: null
20594 };
20595
20596 // Pseudo-Mersenne prime
20597 function MPrime (name, p) {
20598 // P = 2 ^ N - K
20599 this.name = name;
20600 this.p = new BN(p, 16);
20601 this.n = this.p.bitLength();
20602 this.k = new BN(1).iushln(this.n).isub(this.p);
20603
20604 this.tmp = this._tmp();
20605 }
20606
20607 MPrime.prototype._tmp = function _tmp () {
20608 var tmp = new BN(null);
20609 tmp.words = new Array(Math.ceil(this.n / 13));
20610 return tmp;
20611 };
20612
20613 MPrime.prototype.ireduce = function ireduce (num) {
20614 // Assumes that `num` is less than `P^2`
20615 // num = HI * (2 ^ N - K) + HI * K + LO = HI * K + LO (mod P)
20616 var r = num;
20617 var rlen;
20618
20619 do {
20620 this.split(r, this.tmp);
20621 r = this.imulK(r);
20622 r = r.iadd(this.tmp);
20623 rlen = r.bitLength();
20624 } while (rlen > this.n);
20625
20626 var cmp = rlen < this.n ? -1 : r.ucmp(this.p);
20627 if (cmp === 0) {
20628 r.words[0] = 0;
20629 r.length = 1;
20630 } else if (cmp > 0) {
20631 r.isub(this.p);
20632 } else {
20633 r.strip();
20634 }
20635
20636 return r;
20637 };
20638
20639 MPrime.prototype.split = function split (input, out) {
20640 input.iushrn(this.n, 0, out);
20641 };
20642
20643 MPrime.prototype.imulK = function imulK (num) {
20644 return num.imul(this.k);
20645 };
20646
20647 function K256 () {
20648 MPrime.call(
20649 this,
20650 'k256',
20651 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f');
20652 }
20653 inherits(K256, MPrime);
20654
20655 K256.prototype.split = function split (input, output) {
20656 // 256 = 9 * 26 + 22
20657 var mask = 0x3fffff;
20658
20659 var outLen = Math.min(input.length, 9);
20660 for (var i = 0; i < outLen; i++) {
20661 output.words[i] = input.words[i];
20662 }
20663 output.length = outLen;
20664
20665 if (input.length <= 9) {
20666 input.words[0] = 0;
20667 input.length = 1;
20668 return;
20669 }
20670
20671 // Shift by 9 limbs
20672 var prev = input.words[9];
20673 output.words[output.length++] = prev & mask;
20674
20675 for (i = 10; i < input.length; i++) {
20676 var next = input.words[i] | 0;
20677 input.words[i - 10] = ((next & mask) << 4) | (prev >>> 22);
20678 prev = next;
20679 }
20680 prev >>>= 22;
20681 input.words[i - 10] = prev;
20682 if (prev === 0 && input.length > 10) {
20683 input.length -= 10;
20684 } else {
20685 input.length -= 9;
20686 }
20687 };
20688
20689 K256.prototype.imulK = function imulK (num) {
20690 // K = 0x1000003d1 = [ 0x40, 0x3d1 ]
20691 num.words[num.length] = 0;
20692 num.words[num.length + 1] = 0;
20693 num.length += 2;
20694
20695 // bounded at: 0x40 * 0x3ffffff + 0x3d0 = 0x100000390
20696 var lo = 0;
20697 for (var i = 0; i < num.length; i++) {
20698 var w = num.words[i] | 0;
20699 lo += w * 0x3d1;
20700 num.words[i] = lo & 0x3ffffff;
20701 lo = w * 0x40 + ((lo / 0x4000000) | 0);
20702 }
20703
20704 // Fast length reduction
20705 if (num.words[num.length - 1] === 0) {
20706 num.length--;
20707 if (num.words[num.length - 1] === 0) {
20708 num.length--;
20709 }
20710 }
20711 return num;
20712 };
20713
20714 function P224 () {
20715 MPrime.call(
20716 this,
20717 'p224',
20718 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001');
20719 }
20720 inherits(P224, MPrime);
20721
20722 function P192 () {
20723 MPrime.call(
20724 this,
20725 'p192',
20726 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff');
20727 }
20728 inherits(P192, MPrime);
20729
20730 function P25519 () {
20731 // 2 ^ 255 - 19
20732 MPrime.call(
20733 this,
20734 '25519',
20735 '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed');
20736 }
20737 inherits(P25519, MPrime);
20738
20739 P25519.prototype.imulK = function imulK (num) {
20740 // K = 0x13
20741 var carry = 0;
20742 for (var i = 0; i < num.length; i++) {
20743 var hi = (num.words[i] | 0) * 0x13 + carry;
20744 var lo = hi & 0x3ffffff;
20745 hi >>>= 26;
20746
20747 num.words[i] = lo;
20748 carry = hi;
20749 }
20750 if (carry !== 0) {
20751 num.words[num.length++] = carry;
20752 }
20753 return num;
20754 };
20755
20756 // Exported mostly for testing purposes, use plain name instead
20757 BN._prime = function prime (name) {
20758 // Cached version of prime
20759 if (primes[name]) return primes[name];
20760
20761 var prime;
20762 if (name === 'k256') {
20763 prime = new K256();
20764 } else if (name === 'p224') {
20765 prime = new P224();
20766 } else if (name === 'p192') {
20767 prime = new P192();
20768 } else if (name === 'p25519') {
20769 prime = new P25519();
20770 } else {
20771 throw new Error('Unknown prime ' + name);
20772 }
20773 primes[name] = prime;
20774
20775 return prime;
20776 };
20777
20778 //
20779 // Base reduction engine
20780 //
20781 function Red (m) {
20782 if (typeof m === 'string') {
20783 var prime = BN._prime(m);
20784 this.m = prime.p;
20785 this.prime = prime;
20786 } else {
20787 assert(m.gtn(1), 'modulus must be greater than 1');
20788 this.m = m;
20789 this.prime = null;
20790 }
20791 }
20792
20793 Red.prototype._verify1 = function _verify1 (a) {
20794 assert(a.negative === 0, 'red works only with positives');
20795 assert(a.red, 'red works only with red numbers');
20796 };
20797
20798 Red.prototype._verify2 = function _verify2 (a, b) {
20799 assert((a.negative | b.negative) === 0, 'red works only with positives');
20800 assert(a.red && a.red === b.red,
20801 'red works only with red numbers');
20802 };
20803
20804 Red.prototype.imod = function imod (a) {
20805 if (this.prime) return this.prime.ireduce(a)._forceRed(this);
20806 return a.umod(this.m)._forceRed(this);
20807 };
20808
20809 Red.prototype.neg = function neg (a) {
20810 if (a.isZero()) {
20811 return a.clone();
20812 }
20813
20814 return this.m.sub(a)._forceRed(this);
20815 };
20816
20817 Red.prototype.add = function add (a, b) {
20818 this._verify2(a, b);
20819
20820 var res = a.add(b);
20821 if (res.cmp(this.m) >= 0) {
20822 res.isub(this.m);
20823 }
20824 return res._forceRed(this);
20825 };
20826
20827 Red.prototype.iadd = function iadd (a, b) {
20828 this._verify2(a, b);
20829
20830 var res = a.iadd(b);
20831 if (res.cmp(this.m) >= 0) {
20832 res.isub(this.m);
20833 }
20834 return res;
20835 };
20836
20837 Red.prototype.sub = function sub (a, b) {
20838 this._verify2(a, b);
20839
20840 var res = a.sub(b);
20841 if (res.cmpn(0) < 0) {
20842 res.iadd(this.m);
20843 }
20844 return res._forceRed(this);
20845 };
20846
20847 Red.prototype.isub = function isub (a, b) {
20848 this._verify2(a, b);
20849
20850 var res = a.isub(b);
20851 if (res.cmpn(0) < 0) {
20852 res.iadd(this.m);
20853 }
20854 return res;
20855 };
20856
20857 Red.prototype.shl = function shl (a, num) {
20858 this._verify1(a);
20859 return this.imod(a.ushln(num));
20860 };
20861
20862 Red.prototype.imul = function imul (a, b) {
20863 this._verify2(a, b);
20864 return this.imod(a.imul(b));
20865 };
20866
20867 Red.prototype.mul = function mul (a, b) {
20868 this._verify2(a, b);
20869 return this.imod(a.mul(b));
20870 };
20871
20872 Red.prototype.isqr = function isqr (a) {
20873 return this.imul(a, a.clone());
20874 };
20875
20876 Red.prototype.sqr = function sqr (a) {
20877 return this.mul(a, a);
20878 };
20879
20880 Red.prototype.sqrt = function sqrt (a) {
20881 if (a.isZero()) return a.clone();
20882
20883 var mod3 = this.m.andln(3);
20884 assert(mod3 % 2 === 1);
20885
20886 // Fast case
20887 if (mod3 === 3) {
20888 var pow = this.m.add(new BN(1)).iushrn(2);
20889 return this.pow(a, pow);
20890 }
20891
20892 // Tonelli-Shanks algorithm (Totally unoptimized and slow)
20893 //
20894 // Find Q and S, that Q * 2 ^ S = (P - 1)
20895 var q = this.m.subn(1);
20896 var s = 0;
20897 while (!q.isZero() && q.andln(1) === 0) {
20898 s++;
20899 q.iushrn(1);
20900 }
20901 assert(!q.isZero());
20902
20903 var one = new BN(1).toRed(this);
20904 var nOne = one.redNeg();
20905
20906 // Find quadratic non-residue
20907 // NOTE: Max is such because of generalized Riemann hypothesis.
20908 var lpow = this.m.subn(1).iushrn(1);
20909 var z = this.m.bitLength();
20910 z = new BN(2 * z * z).toRed(this);
20911
20912 while (this.pow(z, lpow).cmp(nOne) !== 0) {
20913 z.redIAdd(nOne);
20914 }
20915
20916 var c = this.pow(z, q);
20917 var r = this.pow(a, q.addn(1).iushrn(1));
20918 var t = this.pow(a, q);
20919 var m = s;
20920 while (t.cmp(one) !== 0) {
20921 var tmp = t;
20922 for (var i = 0; tmp.cmp(one) !== 0; i++) {
20923 tmp = tmp.redSqr();
20924 }
20925 assert(i < m);
20926 var b = this.pow(c, new BN(1).iushln(m - i - 1));
20927
20928 r = r.redMul(b);
20929 c = b.redSqr();
20930 t = t.redMul(c);
20931 m = i;
20932 }
20933
20934 return r;
20935 };
20936
20937 Red.prototype.invm = function invm (a) {
20938 var inv = a._invmp(this.m);
20939 if (inv.negative !== 0) {
20940 inv.negative = 0;
20941 return this.imod(inv).redNeg();
20942 } else {
20943 return this.imod(inv);
20944 }
20945 };
20946
20947 Red.prototype.pow = function pow (a, num) {
20948 if (num.isZero()) return new BN(1).toRed(this);
20949 if (num.cmpn(1) === 0) return a.clone();
20950
20951 var windowSize = 4;
20952 var wnd = new Array(1 << windowSize);
20953 wnd[0] = new BN(1).toRed(this);
20954 wnd[1] = a;
20955 for (var i = 2; i < wnd.length; i++) {
20956 wnd[i] = this.mul(wnd[i - 1], a);
20957 }
20958
20959 var res = wnd[0];
20960 var current = 0;
20961 var currentLen = 0;
20962 var start = num.bitLength() % 26;
20963 if (start === 0) {
20964 start = 26;
20965 }
20966
20967 for (i = num.length - 1; i >= 0; i--) {
20968 var word = num.words[i];
20969 for (var j = start - 1; j >= 0; j--) {
20970 var bit = (word >> j) & 1;
20971 if (res !== wnd[0]) {
20972 res = this.sqr(res);
20973 }
20974
20975 if (bit === 0 && current === 0) {
20976 currentLen = 0;
20977 continue;
20978 }
20979
20980 current <<= 1;
20981 current |= bit;
20982 currentLen++;
20983 if (currentLen !== windowSize && (i !== 0 || j !== 0)) continue;
20984
20985 res = this.mul(res, wnd[current]);
20986 currentLen = 0;
20987 current = 0;
20988 }
20989 start = 26;
20990 }
20991
20992 return res;
20993 };
20994
20995 Red.prototype.convertTo = function convertTo (num) {
20996 var r = num.umod(this.m);
20997
20998 return r === num ? r.clone() : r;
20999 };
21000
21001 Red.prototype.convertFrom = function convertFrom (num) {
21002 var res = num.clone();
21003 res.red = null;
21004 return res;
21005 };
21006
21007 //
21008 // Montgomery method engine
21009 //
21010
21011 BN.mont = function mont (num) {
21012 return new Mont(num);
21013 };
21014
21015 function Mont (m) {
21016 Red.call(this, m);
21017
21018 this.shift = this.m.bitLength();
21019 if (this.shift % 26 !== 0) {
21020 this.shift += 26 - (this.shift % 26);
21021 }
21022
21023 this.r = new BN(1).iushln(this.shift);
21024 this.r2 = this.imod(this.r.sqr());
21025 this.rinv = this.r._invmp(this.m);
21026
21027 this.minv = this.rinv.mul(this.r).isubn(1).div(this.m);
21028 this.minv = this.minv.umod(this.r);
21029 this.minv = this.r.sub(this.minv);
21030 }
21031 inherits(Mont, Red);
21032
21033 Mont.prototype.convertTo = function convertTo (num) {
21034 return this.imod(num.ushln(this.shift));
21035 };
21036
21037 Mont.prototype.convertFrom = function convertFrom (num) {
21038 var r = this.imod(num.mul(this.rinv));
21039 r.red = null;
21040 return r;
21041 };
21042
21043 Mont.prototype.imul = function imul (a, b) {
21044 if (a.isZero() || b.isZero()) {
21045 a.words[0] = 0;
21046 a.length = 1;
21047 return a;
21048 }
21049
21050 var t = a.imul(b);
21051 var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m);
21052 var u = t.isub(c).iushrn(this.shift);
21053 var res = u;
21054
21055 if (u.cmp(this.m) >= 0) {
21056 res = u.isub(this.m);
21057 } else if (u.cmpn(0) < 0) {
21058 res = u.iadd(this.m);
21059 }
21060
21061 return res._forceRed(this);
21062 };
21063
21064 Mont.prototype.mul = function mul (a, b) {
21065 if (a.isZero() || b.isZero()) return new BN(0)._forceRed(this);
21066
21067 var t = a.mul(b);
21068 var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m);
21069 var u = t.isub(c).iushrn(this.shift);
21070 var res = u;
21071 if (u.cmp(this.m) >= 0) {
21072 res = u.isub(this.m);
21073 } else if (u.cmpn(0) < 0) {
21074 res = u.iadd(this.m);
21075 }
21076
21077 return res._forceRed(this);
21078 };
21079
21080 Mont.prototype.invm = function invm (a) {
21081 // (AR)^-1 * R^2 = (A^-1 * R^-1) * R^2 = A^-1 * R
21082 var res = this.imod(a._invmp(this.m).mul(this.r2));
21083 return res._forceRed(this);
21084 };
21085})(typeof module === 'undefined' || module, this);
21086
21087},{"buffer":82}],81:[function(require,module,exports){
21088var r;
21089
21090module.exports = function rand(len) {
21091 if (!r)
21092 r = new Rand(null);
21093
21094 return r.generate(len);
21095};
21096
21097function Rand(rand) {
21098 this.rand = rand;
21099}
21100module.exports.Rand = Rand;
21101
21102Rand.prototype.generate = function generate(len) {
21103 return this._rand(len);
21104};
21105
21106// Emulate crypto API using randy
21107Rand.prototype._rand = function _rand(n) {
21108 if (this.rand.getBytes)
21109 return this.rand.getBytes(n);
21110
21111 var res = new Uint8Array(n);
21112 for (var i = 0; i < res.length; i++)
21113 res[i] = this.rand.getByte();
21114 return res;
21115};
21116
21117if (typeof self === 'object') {
21118 if (self.crypto && self.crypto.getRandomValues) {
21119 // Modern browsers
21120 Rand.prototype._rand = function _rand(n) {
21121 var arr = new Uint8Array(n);
21122 self.crypto.getRandomValues(arr);
21123 return arr;
21124 };
21125 } else if (self.msCrypto && self.msCrypto.getRandomValues) {
21126 // IE
21127 Rand.prototype._rand = function _rand(n) {
21128 var arr = new Uint8Array(n);
21129 self.msCrypto.getRandomValues(arr);
21130 return arr;
21131 };
21132
21133 // Safari's WebWorkers do not have `crypto`
21134 } else if (typeof window === 'object') {
21135 // Old junk
21136 Rand.prototype._rand = function() {
21137 throw new Error('Not implemented yet');
21138 };
21139 }
21140} else {
21141 // Node.js or Web worker with no crypto support
21142 try {
21143 var crypto = require('crypto');
21144 if (typeof crypto.randomBytes !== 'function')
21145 throw new Error('Not supported');
21146
21147 Rand.prototype._rand = function _rand(n) {
21148 return crypto.randomBytes(n);
21149 };
21150 } catch (e) {
21151 }
21152}
21153
21154},{"crypto":82}],82:[function(require,module,exports){
21155
21156},{}],83:[function(require,module,exports){
21157// based on the aes implimentation in triple sec
21158// https://github.com/keybase/triplesec
21159// which is in turn based on the one from crypto-js
21160// https://code.google.com/p/crypto-js/
21161
21162var Buffer = require('safe-buffer').Buffer
21163
21164function asUInt32Array (buf) {
21165 if (!Buffer.isBuffer(buf)) buf = Buffer.from(buf)
21166
21167 var len = (buf.length / 4) | 0
21168 var out = new Array(len)
21169
21170 for (var i = 0; i < len; i++) {
21171 out[i] = buf.readUInt32BE(i * 4)
21172 }
21173
21174 return out
21175}
21176
21177function scrubVec (v) {
21178 for (var i = 0; i < v.length; v++) {
21179 v[i] = 0
21180 }
21181}
21182
21183function cryptBlock (M, keySchedule, SUB_MIX, SBOX, nRounds) {
21184 var SUB_MIX0 = SUB_MIX[0]
21185 var SUB_MIX1 = SUB_MIX[1]
21186 var SUB_MIX2 = SUB_MIX[2]
21187 var SUB_MIX3 = SUB_MIX[3]
21188
21189 var s0 = M[0] ^ keySchedule[0]
21190 var s1 = M[1] ^ keySchedule[1]
21191 var s2 = M[2] ^ keySchedule[2]
21192 var s3 = M[3] ^ keySchedule[3]
21193 var t0, t1, t2, t3
21194 var ksRow = 4
21195
21196 for (var round = 1; round < nRounds; round++) {
21197 t0 = SUB_MIX0[s0 >>> 24] ^ SUB_MIX1[(s1 >>> 16) & 0xff] ^ SUB_MIX2[(s2 >>> 8) & 0xff] ^ SUB_MIX3[s3 & 0xff] ^ keySchedule[ksRow++]
21198 t1 = SUB_MIX0[s1 >>> 24] ^ SUB_MIX1[(s2 >>> 16) & 0xff] ^ SUB_MIX2[(s3 >>> 8) & 0xff] ^ SUB_MIX3[s0 & 0xff] ^ keySchedule[ksRow++]
21199 t2 = SUB_MIX0[s2 >>> 24] ^ SUB_MIX1[(s3 >>> 16) & 0xff] ^ SUB_MIX2[(s0 >>> 8) & 0xff] ^ SUB_MIX3[s1 & 0xff] ^ keySchedule[ksRow++]
21200 t3 = SUB_MIX0[s3 >>> 24] ^ SUB_MIX1[(s0 >>> 16) & 0xff] ^ SUB_MIX2[(s1 >>> 8) & 0xff] ^ SUB_MIX3[s2 & 0xff] ^ keySchedule[ksRow++]
21201 s0 = t0
21202 s1 = t1
21203 s2 = t2
21204 s3 = t3
21205 }
21206
21207 t0 = ((SBOX[s0 >>> 24] << 24) | (SBOX[(s1 >>> 16) & 0xff] << 16) | (SBOX[(s2 >>> 8) & 0xff] << 8) | SBOX[s3 & 0xff]) ^ keySchedule[ksRow++]
21208 t1 = ((SBOX[s1 >>> 24] << 24) | (SBOX[(s2 >>> 16) & 0xff] << 16) | (SBOX[(s3 >>> 8) & 0xff] << 8) | SBOX[s0 & 0xff]) ^ keySchedule[ksRow++]
21209 t2 = ((SBOX[s2 >>> 24] << 24) | (SBOX[(s3 >>> 16) & 0xff] << 16) | (SBOX[(s0 >>> 8) & 0xff] << 8) | SBOX[s1 & 0xff]) ^ keySchedule[ksRow++]
21210 t3 = ((SBOX[s3 >>> 24] << 24) | (SBOX[(s0 >>> 16) & 0xff] << 16) | (SBOX[(s1 >>> 8) & 0xff] << 8) | SBOX[s2 & 0xff]) ^ keySchedule[ksRow++]
21211 t0 = t0 >>> 0
21212 t1 = t1 >>> 0
21213 t2 = t2 >>> 0
21214 t3 = t3 >>> 0
21215
21216 return [t0, t1, t2, t3]
21217}
21218
21219// AES constants
21220var RCON = [0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36]
21221var G = (function () {
21222 // Compute double table
21223 var d = new Array(256)
21224 for (var j = 0; j < 256; j++) {
21225 if (j < 128) {
21226 d[j] = j << 1
21227 } else {
21228 d[j] = (j << 1) ^ 0x11b
21229 }
21230 }
21231
21232 var SBOX = []
21233 var INV_SBOX = []
21234 var SUB_MIX = [[], [], [], []]
21235 var INV_SUB_MIX = [[], [], [], []]
21236
21237 // Walk GF(2^8)
21238 var x = 0
21239 var xi = 0
21240 for (var i = 0; i < 256; ++i) {
21241 // Compute sbox
21242 var sx = xi ^ (xi << 1) ^ (xi << 2) ^ (xi << 3) ^ (xi << 4)
21243 sx = (sx >>> 8) ^ (sx & 0xff) ^ 0x63
21244 SBOX[x] = sx
21245 INV_SBOX[sx] = x
21246
21247 // Compute multiplication
21248 var x2 = d[x]
21249 var x4 = d[x2]
21250 var x8 = d[x4]
21251
21252 // Compute sub bytes, mix columns tables
21253 var t = (d[sx] * 0x101) ^ (sx * 0x1010100)
21254 SUB_MIX[0][x] = (t << 24) | (t >>> 8)
21255 SUB_MIX[1][x] = (t << 16) | (t >>> 16)
21256 SUB_MIX[2][x] = (t << 8) | (t >>> 24)
21257 SUB_MIX[3][x] = t
21258
21259 // Compute inv sub bytes, inv mix columns tables
21260 t = (x8 * 0x1010101) ^ (x4 * 0x10001) ^ (x2 * 0x101) ^ (x * 0x1010100)
21261 INV_SUB_MIX[0][sx] = (t << 24) | (t >>> 8)
21262 INV_SUB_MIX[1][sx] = (t << 16) | (t >>> 16)
21263 INV_SUB_MIX[2][sx] = (t << 8) | (t >>> 24)
21264 INV_SUB_MIX[3][sx] = t
21265
21266 if (x === 0) {
21267 x = xi = 1
21268 } else {
21269 x = x2 ^ d[d[d[x8 ^ x2]]]
21270 xi ^= d[d[xi]]
21271 }
21272 }
21273
21274 return {
21275 SBOX: SBOX,
21276 INV_SBOX: INV_SBOX,
21277 SUB_MIX: SUB_MIX,
21278 INV_SUB_MIX: INV_SUB_MIX
21279 }
21280})()
21281
21282function AES (key) {
21283 this._key = asUInt32Array(key)
21284 this._reset()
21285}
21286
21287AES.blockSize = 4 * 4
21288AES.keySize = 256 / 8
21289AES.prototype.blockSize = AES.blockSize
21290AES.prototype.keySize = AES.keySize
21291AES.prototype._reset = function () {
21292 var keyWords = this._key
21293 var keySize = keyWords.length
21294 var nRounds = keySize + 6
21295 var ksRows = (nRounds + 1) * 4
21296
21297 var keySchedule = []
21298 for (var k = 0; k < keySize; k++) {
21299 keySchedule[k] = keyWords[k]
21300 }
21301
21302 for (k = keySize; k < ksRows; k++) {
21303 var t = keySchedule[k - 1]
21304
21305 if (k % keySize === 0) {
21306 t = (t << 8) | (t >>> 24)
21307 t =
21308 (G.SBOX[t >>> 24] << 24) |
21309 (G.SBOX[(t >>> 16) & 0xff] << 16) |
21310 (G.SBOX[(t >>> 8) & 0xff] << 8) |
21311 (G.SBOX[t & 0xff])
21312
21313 t ^= RCON[(k / keySize) | 0] << 24
21314 } else if (keySize > 6 && k % keySize === 4) {
21315 t =
21316 (G.SBOX[t >>> 24] << 24) |
21317 (G.SBOX[(t >>> 16) & 0xff] << 16) |
21318 (G.SBOX[(t >>> 8) & 0xff] << 8) |
21319 (G.SBOX[t & 0xff])
21320 }
21321
21322 keySchedule[k] = keySchedule[k - keySize] ^ t
21323 }
21324
21325 var invKeySchedule = []
21326 for (var ik = 0; ik < ksRows; ik++) {
21327 var ksR = ksRows - ik
21328 var tt = keySchedule[ksR - (ik % 4 ? 0 : 4)]
21329
21330 if (ik < 4 || ksR <= 4) {
21331 invKeySchedule[ik] = tt
21332 } else {
21333 invKeySchedule[ik] =
21334 G.INV_SUB_MIX[0][G.SBOX[tt >>> 24]] ^
21335 G.INV_SUB_MIX[1][G.SBOX[(tt >>> 16) & 0xff]] ^
21336 G.INV_SUB_MIX[2][G.SBOX[(tt >>> 8) & 0xff]] ^
21337 G.INV_SUB_MIX[3][G.SBOX[tt & 0xff]]
21338 }
21339 }
21340
21341 this._nRounds = nRounds
21342 this._keySchedule = keySchedule
21343 this._invKeySchedule = invKeySchedule
21344}
21345
21346AES.prototype.encryptBlockRaw = function (M) {
21347 M = asUInt32Array(M)
21348 return cryptBlock(M, this._keySchedule, G.SUB_MIX, G.SBOX, this._nRounds)
21349}
21350
21351AES.prototype.encryptBlock = function (M) {
21352 var out = this.encryptBlockRaw(M)
21353 var buf = Buffer.allocUnsafe(16)
21354 buf.writeUInt32BE(out[0], 0)
21355 buf.writeUInt32BE(out[1], 4)
21356 buf.writeUInt32BE(out[2], 8)
21357 buf.writeUInt32BE(out[3], 12)
21358 return buf
21359}
21360
21361AES.prototype.decryptBlock = function (M) {
21362 M = asUInt32Array(M)
21363
21364 // swap
21365 var m1 = M[1]
21366 M[1] = M[3]
21367 M[3] = m1
21368
21369 var out = cryptBlock(M, this._invKeySchedule, G.INV_SUB_MIX, G.INV_SBOX, this._nRounds)
21370 var buf = Buffer.allocUnsafe(16)
21371 buf.writeUInt32BE(out[0], 0)
21372 buf.writeUInt32BE(out[3], 4)
21373 buf.writeUInt32BE(out[2], 8)
21374 buf.writeUInt32BE(out[1], 12)
21375 return buf
21376}
21377
21378AES.prototype.scrub = function () {
21379 scrubVec(this._keySchedule)
21380 scrubVec(this._invKeySchedule)
21381 scrubVec(this._key)
21382}
21383
21384module.exports.AES = AES
21385
21386},{"safe-buffer":325}],84:[function(require,module,exports){
21387var aes = require('./aes')
21388var Buffer = require('safe-buffer').Buffer
21389var Transform = require('cipher-base')
21390var inherits = require('inherits')
21391var GHASH = require('./ghash')
21392var xor = require('buffer-xor')
21393var incr32 = require('./incr32')
21394
21395function xorTest (a, b) {
21396 var out = 0
21397 if (a.length !== b.length) out++
21398
21399 var len = Math.min(a.length, b.length)
21400 for (var i = 0; i < len; ++i) {
21401 out += (a[i] ^ b[i])
21402 }
21403
21404 return out
21405}
21406
21407function calcIv (self, iv, ck) {
21408 if (iv.length === 12) {
21409 self._finID = Buffer.concat([iv, Buffer.from([0, 0, 0, 1])])
21410 return Buffer.concat([iv, Buffer.from([0, 0, 0, 2])])
21411 }
21412 var ghash = new GHASH(ck)
21413 var len = iv.length
21414 var toPad = len % 16
21415 ghash.update(iv)
21416 if (toPad) {
21417 toPad = 16 - toPad
21418 ghash.update(Buffer.alloc(toPad, 0))
21419 }
21420 ghash.update(Buffer.alloc(8, 0))
21421 var ivBits = len * 8
21422 var tail = Buffer.alloc(8)
21423 tail.writeUIntBE(ivBits, 0, 8)
21424 ghash.update(tail)
21425 self._finID = ghash.state
21426 var out = Buffer.from(self._finID)
21427 incr32(out)
21428 return out
21429}
21430function StreamCipher (mode, key, iv, decrypt) {
21431 Transform.call(this)
21432
21433 var h = Buffer.alloc(4, 0)
21434
21435 this._cipher = new aes.AES(key)
21436 var ck = this._cipher.encryptBlock(h)
21437 this._ghash = new GHASH(ck)
21438 iv = calcIv(this, iv, ck)
21439
21440 this._prev = Buffer.from(iv)
21441 this._cache = Buffer.allocUnsafe(0)
21442 this._secCache = Buffer.allocUnsafe(0)
21443 this._decrypt = decrypt
21444 this._alen = 0
21445 this._len = 0
21446 this._mode = mode
21447
21448 this._authTag = null
21449 this._called = false
21450}
21451
21452inherits(StreamCipher, Transform)
21453
21454StreamCipher.prototype._update = function (chunk) {
21455 if (!this._called && this._alen) {
21456 var rump = 16 - (this._alen % 16)
21457 if (rump < 16) {
21458 rump = Buffer.alloc(rump, 0)
21459 this._ghash.update(rump)
21460 }
21461 }
21462
21463 this._called = true
21464 var out = this._mode.encrypt(this, chunk)
21465 if (this._decrypt) {
21466 this._ghash.update(chunk)
21467 } else {
21468 this._ghash.update(out)
21469 }
21470 this._len += chunk.length
21471 return out
21472}
21473
21474StreamCipher.prototype._final = function () {
21475 if (this._decrypt && !this._authTag) throw new Error('Unsupported state or unable to authenticate data')
21476
21477 var tag = xor(this._ghash.final(this._alen * 8, this._len * 8), this._cipher.encryptBlock(this._finID))
21478 if (this._decrypt && xorTest(tag, this._authTag)) throw new Error('Unsupported state or unable to authenticate data')
21479
21480 this._authTag = tag
21481 this._cipher.scrub()
21482}
21483
21484StreamCipher.prototype.getAuthTag = function getAuthTag () {
21485 if (this._decrypt || !Buffer.isBuffer(this._authTag)) throw new Error('Attempting to get auth tag in unsupported state')
21486
21487 return this._authTag
21488}
21489
21490StreamCipher.prototype.setAuthTag = function setAuthTag (tag) {
21491 if (!this._decrypt) throw new Error('Attempting to set auth tag in unsupported state')
21492
21493 this._authTag = tag
21494}
21495
21496StreamCipher.prototype.setAAD = function setAAD (buf) {
21497 if (this._called) throw new Error('Attempting to set AAD in unsupported state')
21498
21499 this._ghash.update(buf)
21500 this._alen += buf.length
21501}
21502
21503module.exports = StreamCipher
21504
21505},{"./aes":83,"./ghash":88,"./incr32":89,"buffer-xor":113,"cipher-base":117,"inherits":210,"safe-buffer":325}],85:[function(require,module,exports){
21506var ciphers = require('./encrypter')
21507var deciphers = require('./decrypter')
21508var modes = require('./modes/list.json')
21509
21510function getCiphers () {
21511 return Object.keys(modes)
21512}
21513
21514exports.createCipher = exports.Cipher = ciphers.createCipher
21515exports.createCipheriv = exports.Cipheriv = ciphers.createCipheriv
21516exports.createDecipher = exports.Decipher = deciphers.createDecipher
21517exports.createDecipheriv = exports.Decipheriv = deciphers.createDecipheriv
21518exports.listCiphers = exports.getCiphers = getCiphers
21519
21520},{"./decrypter":86,"./encrypter":87,"./modes/list.json":97}],86:[function(require,module,exports){
21521var AuthCipher = require('./authCipher')
21522var Buffer = require('safe-buffer').Buffer
21523var MODES = require('./modes')
21524var StreamCipher = require('./streamCipher')
21525var Transform = require('cipher-base')
21526var aes = require('./aes')
21527var ebtk = require('evp_bytestokey')
21528var inherits = require('inherits')
21529
21530function Decipher (mode, key, iv) {
21531 Transform.call(this)
21532
21533 this._cache = new Splitter()
21534 this._last = void 0
21535 this._cipher = new aes.AES(key)
21536 this._prev = Buffer.from(iv)
21537 this._mode = mode
21538 this._autopadding = true
21539}
21540
21541inherits(Decipher, Transform)
21542
21543Decipher.prototype._update = function (data) {
21544 this._cache.add(data)
21545 var chunk
21546 var thing
21547 var out = []
21548 while ((chunk = this._cache.get(this._autopadding))) {
21549 thing = this._mode.decrypt(this, chunk)
21550 out.push(thing)
21551 }
21552 return Buffer.concat(out)
21553}
21554
21555Decipher.prototype._final = function () {
21556 var chunk = this._cache.flush()
21557 if (this._autopadding) {
21558 return unpad(this._mode.decrypt(this, chunk))
21559 } else if (chunk) {
21560 throw new Error('data not multiple of block length')
21561 }
21562}
21563
21564Decipher.prototype.setAutoPadding = function (setTo) {
21565 this._autopadding = !!setTo
21566 return this
21567}
21568
21569function Splitter () {
21570 this.cache = Buffer.allocUnsafe(0)
21571}
21572
21573Splitter.prototype.add = function (data) {
21574 this.cache = Buffer.concat([this.cache, data])
21575}
21576
21577Splitter.prototype.get = function (autoPadding) {
21578 var out
21579 if (autoPadding) {
21580 if (this.cache.length > 16) {
21581 out = this.cache.slice(0, 16)
21582 this.cache = this.cache.slice(16)
21583 return out
21584 }
21585 } else {
21586 if (this.cache.length >= 16) {
21587 out = this.cache.slice(0, 16)
21588 this.cache = this.cache.slice(16)
21589 return out
21590 }
21591 }
21592
21593 return null
21594}
21595
21596Splitter.prototype.flush = function () {
21597 if (this.cache.length) return this.cache
21598}
21599
21600function unpad (last) {
21601 var padded = last[15]
21602 if (padded < 1 || padded > 16) {
21603 throw new Error('unable to decrypt data')
21604 }
21605 var i = -1
21606 while (++i < padded) {
21607 if (last[(i + (16 - padded))] !== padded) {
21608 throw new Error('unable to decrypt data')
21609 }
21610 }
21611 if (padded === 16) return
21612
21613 return last.slice(0, 16 - padded)
21614}
21615
21616function createDecipheriv (suite, password, iv) {
21617 var config = MODES[suite.toLowerCase()]
21618 if (!config) throw new TypeError('invalid suite type')
21619
21620 if (typeof iv === 'string') iv = Buffer.from(iv)
21621 if (config.mode !== 'GCM' && iv.length !== config.iv) throw new TypeError('invalid iv length ' + iv.length)
21622
21623 if (typeof password === 'string') password = Buffer.from(password)
21624 if (password.length !== config.key / 8) throw new TypeError('invalid key length ' + password.length)
21625
21626 if (config.type === 'stream') {
21627 return new StreamCipher(config.module, password, iv, true)
21628 } else if (config.type === 'auth') {
21629 return new AuthCipher(config.module, password, iv, true)
21630 }
21631
21632 return new Decipher(config.module, password, iv)
21633}
21634
21635function createDecipher (suite, password) {
21636 var config = MODES[suite.toLowerCase()]
21637 if (!config) throw new TypeError('invalid suite type')
21638
21639 var keys = ebtk(password, false, config.key, config.iv)
21640 return createDecipheriv(suite, keys.key, keys.iv)
21641}
21642
21643exports.createDecipher = createDecipher
21644exports.createDecipheriv = createDecipheriv
21645
21646},{"./aes":83,"./authCipher":84,"./modes":96,"./streamCipher":99,"cipher-base":117,"evp_bytestokey":160,"inherits":210,"safe-buffer":325}],87:[function(require,module,exports){
21647var MODES = require('./modes')
21648var AuthCipher = require('./authCipher')
21649var Buffer = require('safe-buffer').Buffer
21650var StreamCipher = require('./streamCipher')
21651var Transform = require('cipher-base')
21652var aes = require('./aes')
21653var ebtk = require('evp_bytestokey')
21654var inherits = require('inherits')
21655
21656function Cipher (mode, key, iv) {
21657 Transform.call(this)
21658
21659 this._cache = new Splitter()
21660 this._cipher = new aes.AES(key)
21661 this._prev = Buffer.from(iv)
21662 this._mode = mode
21663 this._autopadding = true
21664}
21665
21666inherits(Cipher, Transform)
21667
21668Cipher.prototype._update = function (data) {
21669 this._cache.add(data)
21670 var chunk
21671 var thing
21672 var out = []
21673
21674 while ((chunk = this._cache.get())) {
21675 thing = this._mode.encrypt(this, chunk)
21676 out.push(thing)
21677 }
21678
21679 return Buffer.concat(out)
21680}
21681
21682var PADDING = Buffer.alloc(16, 0x10)
21683
21684Cipher.prototype._final = function () {
21685 var chunk = this._cache.flush()
21686 if (this._autopadding) {
21687 chunk = this._mode.encrypt(this, chunk)
21688 this._cipher.scrub()
21689 return chunk
21690 }
21691
21692 if (!chunk.equals(PADDING)) {
21693 this._cipher.scrub()
21694 throw new Error('data not multiple of block length')
21695 }
21696}
21697
21698Cipher.prototype.setAutoPadding = function (setTo) {
21699 this._autopadding = !!setTo
21700 return this
21701}
21702
21703function Splitter () {
21704 this.cache = Buffer.allocUnsafe(0)
21705}
21706
21707Splitter.prototype.add = function (data) {
21708 this.cache = Buffer.concat([this.cache, data])
21709}
21710
21711Splitter.prototype.get = function () {
21712 if (this.cache.length > 15) {
21713 var out = this.cache.slice(0, 16)
21714 this.cache = this.cache.slice(16)
21715 return out
21716 }
21717 return null
21718}
21719
21720Splitter.prototype.flush = function () {
21721 var len = 16 - this.cache.length
21722 var padBuff = Buffer.allocUnsafe(len)
21723
21724 var i = -1
21725 while (++i < len) {
21726 padBuff.writeUInt8(len, i)
21727 }
21728
21729 return Buffer.concat([this.cache, padBuff])
21730}
21731
21732function createCipheriv (suite, password, iv) {
21733 var config = MODES[suite.toLowerCase()]
21734 if (!config) throw new TypeError('invalid suite type')
21735
21736 if (typeof password === 'string') password = Buffer.from(password)
21737 if (password.length !== config.key / 8) throw new TypeError('invalid key length ' + password.length)
21738
21739 if (typeof iv === 'string') iv = Buffer.from(iv)
21740 if (config.mode !== 'GCM' && iv.length !== config.iv) throw new TypeError('invalid iv length ' + iv.length)
21741
21742 if (config.type === 'stream') {
21743 return new StreamCipher(config.module, password, iv)
21744 } else if (config.type === 'auth') {
21745 return new AuthCipher(config.module, password, iv)
21746 }
21747
21748 return new Cipher(config.module, password, iv)
21749}
21750
21751function createCipher (suite, password) {
21752 var config = MODES[suite.toLowerCase()]
21753 if (!config) throw new TypeError('invalid suite type')
21754
21755 var keys = ebtk(password, false, config.key, config.iv)
21756 return createCipheriv(suite, keys.key, keys.iv)
21757}
21758
21759exports.createCipheriv = createCipheriv
21760exports.createCipher = createCipher
21761
21762},{"./aes":83,"./authCipher":84,"./modes":96,"./streamCipher":99,"cipher-base":117,"evp_bytestokey":160,"inherits":210,"safe-buffer":325}],88:[function(require,module,exports){
21763var Buffer = require('safe-buffer').Buffer
21764var ZEROES = Buffer.alloc(16, 0)
21765
21766function toArray (buf) {
21767 return [
21768 buf.readUInt32BE(0),
21769 buf.readUInt32BE(4),
21770 buf.readUInt32BE(8),
21771 buf.readUInt32BE(12)
21772 ]
21773}
21774
21775function fromArray (out) {
21776 var buf = Buffer.allocUnsafe(16)
21777 buf.writeUInt32BE(out[0] >>> 0, 0)
21778 buf.writeUInt32BE(out[1] >>> 0, 4)
21779 buf.writeUInt32BE(out[2] >>> 0, 8)
21780 buf.writeUInt32BE(out[3] >>> 0, 12)
21781 return buf
21782}
21783
21784function GHASH (key) {
21785 this.h = key
21786 this.state = Buffer.alloc(16, 0)
21787 this.cache = Buffer.allocUnsafe(0)
21788}
21789
21790// from http://bitwiseshiftleft.github.io/sjcl/doc/symbols/src/core_gcm.js.html
21791// by Juho Vähä-Herttua
21792GHASH.prototype.ghash = function (block) {
21793 var i = -1
21794 while (++i < block.length) {
21795 this.state[i] ^= block[i]
21796 }
21797 this._multiply()
21798}
21799
21800GHASH.prototype._multiply = function () {
21801 var Vi = toArray(this.h)
21802 var Zi = [0, 0, 0, 0]
21803 var j, xi, lsbVi
21804 var i = -1
21805 while (++i < 128) {
21806 xi = (this.state[~~(i / 8)] & (1 << (7 - (i % 8)))) !== 0
21807 if (xi) {
21808 // Z_i+1 = Z_i ^ V_i
21809 Zi[0] ^= Vi[0]
21810 Zi[1] ^= Vi[1]
21811 Zi[2] ^= Vi[2]
21812 Zi[3] ^= Vi[3]
21813 }
21814
21815 // Store the value of LSB(V_i)
21816 lsbVi = (Vi[3] & 1) !== 0
21817
21818 // V_i+1 = V_i >> 1
21819 for (j = 3; j > 0; j--) {
21820 Vi[j] = (Vi[j] >>> 1) | ((Vi[j - 1] & 1) << 31)
21821 }
21822 Vi[0] = Vi[0] >>> 1
21823
21824 // If LSB(V_i) is 1, V_i+1 = (V_i >> 1) ^ R
21825 if (lsbVi) {
21826 Vi[0] = Vi[0] ^ (0xe1 << 24)
21827 }
21828 }
21829 this.state = fromArray(Zi)
21830}
21831
21832GHASH.prototype.update = function (buf) {
21833 this.cache = Buffer.concat([this.cache, buf])
21834 var chunk
21835 while (this.cache.length >= 16) {
21836 chunk = this.cache.slice(0, 16)
21837 this.cache = this.cache.slice(16)
21838 this.ghash(chunk)
21839 }
21840}
21841
21842GHASH.prototype.final = function (abl, bl) {
21843 if (this.cache.length) {
21844 this.ghash(Buffer.concat([this.cache, ZEROES], 16))
21845 }
21846
21847 this.ghash(fromArray([0, abl, 0, bl]))
21848 return this.state
21849}
21850
21851module.exports = GHASH
21852
21853},{"safe-buffer":325}],89:[function(require,module,exports){
21854function incr32 (iv) {
21855 var len = iv.length
21856 var item
21857 while (len--) {
21858 item = iv.readUInt8(len)
21859 if (item === 255) {
21860 iv.writeUInt8(0, len)
21861 } else {
21862 item++
21863 iv.writeUInt8(item, len)
21864 break
21865 }
21866 }
21867}
21868module.exports = incr32
21869
21870},{}],90:[function(require,module,exports){
21871var xor = require('buffer-xor')
21872
21873exports.encrypt = function (self, block) {
21874 var data = xor(block, self._prev)
21875
21876 self._prev = self._cipher.encryptBlock(data)
21877 return self._prev
21878}
21879
21880exports.decrypt = function (self, block) {
21881 var pad = self._prev
21882
21883 self._prev = block
21884 var out = self._cipher.decryptBlock(block)
21885
21886 return xor(out, pad)
21887}
21888
21889},{"buffer-xor":113}],91:[function(require,module,exports){
21890var Buffer = require('safe-buffer').Buffer
21891var xor = require('buffer-xor')
21892
21893function encryptStart (self, data, decrypt) {
21894 var len = data.length
21895 var out = xor(data, self._cache)
21896 self._cache = self._cache.slice(len)
21897 self._prev = Buffer.concat([self._prev, decrypt ? data : out])
21898 return out
21899}
21900
21901exports.encrypt = function (self, data, decrypt) {
21902 var out = Buffer.allocUnsafe(0)
21903 var len
21904
21905 while (data.length) {
21906 if (self._cache.length === 0) {
21907 self._cache = self._cipher.encryptBlock(self._prev)
21908 self._prev = Buffer.allocUnsafe(0)
21909 }
21910
21911 if (self._cache.length <= data.length) {
21912 len = self._cache.length
21913 out = Buffer.concat([out, encryptStart(self, data.slice(0, len), decrypt)])
21914 data = data.slice(len)
21915 } else {
21916 out = Buffer.concat([out, encryptStart(self, data, decrypt)])
21917 break
21918 }
21919 }
21920
21921 return out
21922}
21923
21924},{"buffer-xor":113,"safe-buffer":325}],92:[function(require,module,exports){
21925var Buffer = require('safe-buffer').Buffer
21926
21927function encryptByte (self, byteParam, decrypt) {
21928 var pad
21929 var i = -1
21930 var len = 8
21931 var out = 0
21932 var bit, value
21933 while (++i < len) {
21934 pad = self._cipher.encryptBlock(self._prev)
21935 bit = (byteParam & (1 << (7 - i))) ? 0x80 : 0
21936 value = pad[0] ^ bit
21937 out += ((value & 0x80) >> (i % 8))
21938 self._prev = shiftIn(self._prev, decrypt ? bit : value)
21939 }
21940 return out
21941}
21942
21943function shiftIn (buffer, value) {
21944 var len = buffer.length
21945 var i = -1
21946 var out = Buffer.allocUnsafe(buffer.length)
21947 buffer = Buffer.concat([buffer, Buffer.from([value])])
21948
21949 while (++i < len) {
21950 out[i] = buffer[i] << 1 | buffer[i + 1] >> (7)
21951 }
21952
21953 return out
21954}
21955
21956exports.encrypt = function (self, chunk, decrypt) {
21957 var len = chunk.length
21958 var out = Buffer.allocUnsafe(len)
21959 var i = -1
21960
21961 while (++i < len) {
21962 out[i] = encryptByte(self, chunk[i], decrypt)
21963 }
21964
21965 return out
21966}
21967
21968},{"safe-buffer":325}],93:[function(require,module,exports){
21969var Buffer = require('safe-buffer').Buffer
21970
21971function encryptByte (self, byteParam, decrypt) {
21972 var pad = self._cipher.encryptBlock(self._prev)
21973 var out = pad[0] ^ byteParam
21974
21975 self._prev = Buffer.concat([
21976 self._prev.slice(1),
21977 Buffer.from([decrypt ? byteParam : out])
21978 ])
21979
21980 return out
21981}
21982
21983exports.encrypt = function (self, chunk, decrypt) {
21984 var len = chunk.length
21985 var out = Buffer.allocUnsafe(len)
21986 var i = -1
21987
21988 while (++i < len) {
21989 out[i] = encryptByte(self, chunk[i], decrypt)
21990 }
21991
21992 return out
21993}
21994
21995},{"safe-buffer":325}],94:[function(require,module,exports){
21996var xor = require('buffer-xor')
21997var Buffer = require('safe-buffer').Buffer
21998var incr32 = require('../incr32')
21999
22000function getBlock (self) {
22001 var out = self._cipher.encryptBlockRaw(self._prev)
22002 incr32(self._prev)
22003 return out
22004}
22005
22006var blockSize = 16
22007exports.encrypt = function (self, chunk) {
22008 var chunkNum = Math.ceil(chunk.length / blockSize)
22009 var start = self._cache.length
22010 self._cache = Buffer.concat([
22011 self._cache,
22012 Buffer.allocUnsafe(chunkNum * blockSize)
22013 ])
22014 for (var i = 0; i < chunkNum; i++) {
22015 var out = getBlock(self)
22016 var offset = start + i * blockSize
22017 self._cache.writeUInt32BE(out[0], offset + 0)
22018 self._cache.writeUInt32BE(out[1], offset + 4)
22019 self._cache.writeUInt32BE(out[2], offset + 8)
22020 self._cache.writeUInt32BE(out[3], offset + 12)
22021 }
22022 var pad = self._cache.slice(0, chunk.length)
22023 self._cache = self._cache.slice(chunk.length)
22024 return xor(chunk, pad)
22025}
22026
22027},{"../incr32":89,"buffer-xor":113,"safe-buffer":325}],95:[function(require,module,exports){
22028exports.encrypt = function (self, block) {
22029 return self._cipher.encryptBlock(block)
22030}
22031
22032exports.decrypt = function (self, block) {
22033 return self._cipher.decryptBlock(block)
22034}
22035
22036},{}],96:[function(require,module,exports){
22037var modeModules = {
22038 ECB: require('./ecb'),
22039 CBC: require('./cbc'),
22040 CFB: require('./cfb'),
22041 CFB8: require('./cfb8'),
22042 CFB1: require('./cfb1'),
22043 OFB: require('./ofb'),
22044 CTR: require('./ctr'),
22045 GCM: require('./ctr')
22046}
22047
22048var modes = require('./list.json')
22049
22050for (var key in modes) {
22051 modes[key].module = modeModules[modes[key].mode]
22052}
22053
22054module.exports = modes
22055
22056},{"./cbc":90,"./cfb":91,"./cfb1":92,"./cfb8":93,"./ctr":94,"./ecb":95,"./list.json":97,"./ofb":98}],97:[function(require,module,exports){
22057module.exports={
22058 "aes-128-ecb": {
22059 "cipher": "AES",
22060 "key": 128,
22061 "iv": 0,
22062 "mode": "ECB",
22063 "type": "block"
22064 },
22065 "aes-192-ecb": {
22066 "cipher": "AES",
22067 "key": 192,
22068 "iv": 0,
22069 "mode": "ECB",
22070 "type": "block"
22071 },
22072 "aes-256-ecb": {
22073 "cipher": "AES",
22074 "key": 256,
22075 "iv": 0,
22076 "mode": "ECB",
22077 "type": "block"
22078 },
22079 "aes-128-cbc": {
22080 "cipher": "AES",
22081 "key": 128,
22082 "iv": 16,
22083 "mode": "CBC",
22084 "type": "block"
22085 },
22086 "aes-192-cbc": {
22087 "cipher": "AES",
22088 "key": 192,
22089 "iv": 16,
22090 "mode": "CBC",
22091 "type": "block"
22092 },
22093 "aes-256-cbc": {
22094 "cipher": "AES",
22095 "key": 256,
22096 "iv": 16,
22097 "mode": "CBC",
22098 "type": "block"
22099 },
22100 "aes128": {
22101 "cipher": "AES",
22102 "key": 128,
22103 "iv": 16,
22104 "mode": "CBC",
22105 "type": "block"
22106 },
22107 "aes192": {
22108 "cipher": "AES",
22109 "key": 192,
22110 "iv": 16,
22111 "mode": "CBC",
22112 "type": "block"
22113 },
22114 "aes256": {
22115 "cipher": "AES",
22116 "key": 256,
22117 "iv": 16,
22118 "mode": "CBC",
22119 "type": "block"
22120 },
22121 "aes-128-cfb": {
22122 "cipher": "AES",
22123 "key": 128,
22124 "iv": 16,
22125 "mode": "CFB",
22126 "type": "stream"
22127 },
22128 "aes-192-cfb": {
22129 "cipher": "AES",
22130 "key": 192,
22131 "iv": 16,
22132 "mode": "CFB",
22133 "type": "stream"
22134 },
22135 "aes-256-cfb": {
22136 "cipher": "AES",
22137 "key": 256,
22138 "iv": 16,
22139 "mode": "CFB",
22140 "type": "stream"
22141 },
22142 "aes-128-cfb8": {
22143 "cipher": "AES",
22144 "key": 128,
22145 "iv": 16,
22146 "mode": "CFB8",
22147 "type": "stream"
22148 },
22149 "aes-192-cfb8": {
22150 "cipher": "AES",
22151 "key": 192,
22152 "iv": 16,
22153 "mode": "CFB8",
22154 "type": "stream"
22155 },
22156 "aes-256-cfb8": {
22157 "cipher": "AES",
22158 "key": 256,
22159 "iv": 16,
22160 "mode": "CFB8",
22161 "type": "stream"
22162 },
22163 "aes-128-cfb1": {
22164 "cipher": "AES",
22165 "key": 128,
22166 "iv": 16,
22167 "mode": "CFB1",
22168 "type": "stream"
22169 },
22170 "aes-192-cfb1": {
22171 "cipher": "AES",
22172 "key": 192,
22173 "iv": 16,
22174 "mode": "CFB1",
22175 "type": "stream"
22176 },
22177 "aes-256-cfb1": {
22178 "cipher": "AES",
22179 "key": 256,
22180 "iv": 16,
22181 "mode": "CFB1",
22182 "type": "stream"
22183 },
22184 "aes-128-ofb": {
22185 "cipher": "AES",
22186 "key": 128,
22187 "iv": 16,
22188 "mode": "OFB",
22189 "type": "stream"
22190 },
22191 "aes-192-ofb": {
22192 "cipher": "AES",
22193 "key": 192,
22194 "iv": 16,
22195 "mode": "OFB",
22196 "type": "stream"
22197 },
22198 "aes-256-ofb": {
22199 "cipher": "AES",
22200 "key": 256,
22201 "iv": 16,
22202 "mode": "OFB",
22203 "type": "stream"
22204 },
22205 "aes-128-ctr": {
22206 "cipher": "AES",
22207 "key": 128,
22208 "iv": 16,
22209 "mode": "CTR",
22210 "type": "stream"
22211 },
22212 "aes-192-ctr": {
22213 "cipher": "AES",
22214 "key": 192,
22215 "iv": 16,
22216 "mode": "CTR",
22217 "type": "stream"
22218 },
22219 "aes-256-ctr": {
22220 "cipher": "AES",
22221 "key": 256,
22222 "iv": 16,
22223 "mode": "CTR",
22224 "type": "stream"
22225 },
22226 "aes-128-gcm": {
22227 "cipher": "AES",
22228 "key": 128,
22229 "iv": 12,
22230 "mode": "GCM",
22231 "type": "auth"
22232 },
22233 "aes-192-gcm": {
22234 "cipher": "AES",
22235 "key": 192,
22236 "iv": 12,
22237 "mode": "GCM",
22238 "type": "auth"
22239 },
22240 "aes-256-gcm": {
22241 "cipher": "AES",
22242 "key": 256,
22243 "iv": 12,
22244 "mode": "GCM",
22245 "type": "auth"
22246 }
22247}
22248
22249},{}],98:[function(require,module,exports){
22250(function (Buffer){
22251var xor = require('buffer-xor')
22252
22253function getBlock (self) {
22254 self._prev = self._cipher.encryptBlock(self._prev)
22255 return self._prev
22256}
22257
22258exports.encrypt = function (self, chunk) {
22259 while (self._cache.length < chunk.length) {
22260 self._cache = Buffer.concat([self._cache, getBlock(self)])
22261 }
22262
22263 var pad = self._cache.slice(0, chunk.length)
22264 self._cache = self._cache.slice(chunk.length)
22265 return xor(chunk, pad)
22266}
22267
22268}).call(this,require("buffer").Buffer)
22269},{"buffer":114,"buffer-xor":113}],99:[function(require,module,exports){
22270var aes = require('./aes')
22271var Buffer = require('safe-buffer').Buffer
22272var Transform = require('cipher-base')
22273var inherits = require('inherits')
22274
22275function StreamCipher (mode, key, iv, decrypt) {
22276 Transform.call(this)
22277
22278 this._cipher = new aes.AES(key)
22279 this._prev = Buffer.from(iv)
22280 this._cache = Buffer.allocUnsafe(0)
22281 this._secCache = Buffer.allocUnsafe(0)
22282 this._decrypt = decrypt
22283 this._mode = mode
22284}
22285
22286inherits(StreamCipher, Transform)
22287
22288StreamCipher.prototype._update = function (chunk) {
22289 return this._mode.encrypt(this, chunk, this._decrypt)
22290}
22291
22292StreamCipher.prototype._final = function () {
22293 this._cipher.scrub()
22294}
22295
22296module.exports = StreamCipher
22297
22298},{"./aes":83,"cipher-base":117,"inherits":210,"safe-buffer":325}],100:[function(require,module,exports){
22299var DES = require('browserify-des')
22300var aes = require('browserify-aes/browser')
22301var aesModes = require('browserify-aes/modes')
22302var desModes = require('browserify-des/modes')
22303var ebtk = require('evp_bytestokey')
22304
22305function createCipher (suite, password) {
22306 suite = suite.toLowerCase()
22307
22308 var keyLen, ivLen
22309 if (aesModes[suite]) {
22310 keyLen = aesModes[suite].key
22311 ivLen = aesModes[suite].iv
22312 } else if (desModes[suite]) {
22313 keyLen = desModes[suite].key * 8
22314 ivLen = desModes[suite].iv
22315 } else {
22316 throw new TypeError('invalid suite type')
22317 }
22318
22319 var keys = ebtk(password, false, keyLen, ivLen)
22320 return createCipheriv(suite, keys.key, keys.iv)
22321}
22322
22323function createDecipher (suite, password) {
22324 suite = suite.toLowerCase()
22325
22326 var keyLen, ivLen
22327 if (aesModes[suite]) {
22328 keyLen = aesModes[suite].key
22329 ivLen = aesModes[suite].iv
22330 } else if (desModes[suite]) {
22331 keyLen = desModes[suite].key * 8
22332 ivLen = desModes[suite].iv
22333 } else {
22334 throw new TypeError('invalid suite type')
22335 }
22336
22337 var keys = ebtk(password, false, keyLen, ivLen)
22338 return createDecipheriv(suite, keys.key, keys.iv)
22339}
22340
22341function createCipheriv (suite, key, iv) {
22342 suite = suite.toLowerCase()
22343 if (aesModes[suite]) return aes.createCipheriv(suite, key, iv)
22344 if (desModes[suite]) return new DES({ key: key, iv: iv, mode: suite })
22345
22346 throw new TypeError('invalid suite type')
22347}
22348
22349function createDecipheriv (suite, key, iv) {
22350 suite = suite.toLowerCase()
22351 if (aesModes[suite]) return aes.createDecipheriv(suite, key, iv)
22352 if (desModes[suite]) return new DES({ key: key, iv: iv, mode: suite, decrypt: true })
22353
22354 throw new TypeError('invalid suite type')
22355}
22356
22357function getCiphers () {
22358 return Object.keys(desModes).concat(aes.getCiphers())
22359}
22360
22361exports.createCipher = exports.Cipher = createCipher
22362exports.createCipheriv = exports.Cipheriv = createCipheriv
22363exports.createDecipher = exports.Decipher = createDecipher
22364exports.createDecipheriv = exports.Decipheriv = createDecipheriv
22365exports.listCiphers = exports.getCiphers = getCiphers
22366
22367},{"browserify-aes/browser":85,"browserify-aes/modes":96,"browserify-des":101,"browserify-des/modes":102,"evp_bytestokey":160}],101:[function(require,module,exports){
22368var CipherBase = require('cipher-base')
22369var des = require('des.js')
22370var inherits = require('inherits')
22371var Buffer = require('safe-buffer').Buffer
22372
22373var modes = {
22374 'des-ede3-cbc': des.CBC.instantiate(des.EDE),
22375 'des-ede3': des.EDE,
22376 'des-ede-cbc': des.CBC.instantiate(des.EDE),
22377 'des-ede': des.EDE,
22378 'des-cbc': des.CBC.instantiate(des.DES),
22379 'des-ecb': des.DES
22380}
22381modes.des = modes['des-cbc']
22382modes.des3 = modes['des-ede3-cbc']
22383module.exports = DES
22384inherits(DES, CipherBase)
22385function DES (opts) {
22386 CipherBase.call(this)
22387 var modeName = opts.mode.toLowerCase()
22388 var mode = modes[modeName]
22389 var type
22390 if (opts.decrypt) {
22391 type = 'decrypt'
22392 } else {
22393 type = 'encrypt'
22394 }
22395 var key = opts.key
22396 if (!Buffer.isBuffer(key)) {
22397 key = Buffer.from(key)
22398 }
22399 if (modeName === 'des-ede' || modeName === 'des-ede-cbc') {
22400 key = Buffer.concat([key, key.slice(0, 8)])
22401 }
22402 var iv = opts.iv
22403 if (!Buffer.isBuffer(iv)) {
22404 iv = Buffer.from(iv)
22405 }
22406 this._des = mode.create({
22407 key: key,
22408 iv: iv,
22409 type: type
22410 })
22411}
22412DES.prototype._update = function (data) {
22413 return Buffer.from(this._des.update(data))
22414}
22415DES.prototype._final = function () {
22416 return Buffer.from(this._des.final())
22417}
22418
22419},{"cipher-base":117,"des.js":128,"inherits":210,"safe-buffer":325}],102:[function(require,module,exports){
22420exports['des-ecb'] = {
22421 key: 8,
22422 iv: 0
22423}
22424exports['des-cbc'] = exports.des = {
22425 key: 8,
22426 iv: 8
22427}
22428exports['des-ede3-cbc'] = exports.des3 = {
22429 key: 24,
22430 iv: 8
22431}
22432exports['des-ede3'] = {
22433 key: 24,
22434 iv: 0
22435}
22436exports['des-ede-cbc'] = {
22437 key: 16,
22438 iv: 8
22439}
22440exports['des-ede'] = {
22441 key: 16,
22442 iv: 0
22443}
22444
22445},{}],103:[function(require,module,exports){
22446(function (Buffer){
22447var bn = require('bn.js');
22448var randomBytes = require('randombytes');
22449module.exports = crt;
22450function blind(priv) {
22451 var r = getr(priv);
22452 var blinder = r.toRed(bn.mont(priv.modulus))
22453 .redPow(new bn(priv.publicExponent)).fromRed();
22454 return {
22455 blinder: blinder,
22456 unblinder:r.invm(priv.modulus)
22457 };
22458}
22459function crt(msg, priv) {
22460 var blinds = blind(priv);
22461 var len = priv.modulus.byteLength();
22462 var mod = bn.mont(priv.modulus);
22463 var blinded = new bn(msg).mul(blinds.blinder).umod(priv.modulus);
22464 var c1 = blinded.toRed(bn.mont(priv.prime1));
22465 var c2 = blinded.toRed(bn.mont(priv.prime2));
22466 var qinv = priv.coefficient;
22467 var p = priv.prime1;
22468 var q = priv.prime2;
22469 var m1 = c1.redPow(priv.exponent1);
22470 var m2 = c2.redPow(priv.exponent2);
22471 m1 = m1.fromRed();
22472 m2 = m2.fromRed();
22473 var h = m1.isub(m2).imul(qinv).umod(p);
22474 h.imul(q);
22475 m2.iadd(h);
22476 return new Buffer(m2.imul(blinds.unblinder).umod(priv.modulus).toArray(false, len));
22477}
22478crt.getr = getr;
22479function getr(priv) {
22480 var len = priv.modulus.byteLength();
22481 var r = new bn(randomBytes(len));
22482 while (r.cmp(priv.modulus) >= 0 || !r.umod(priv.prime1) || !r.umod(priv.prime2)) {
22483 r = new bn(randomBytes(len));
22484 }
22485 return r;
22486}
22487
22488}).call(this,require("buffer").Buffer)
22489},{"bn.js":80,"buffer":114,"randombytes":278}],104:[function(require,module,exports){
22490module.exports = require('./browser/algorithms.json')
22491
22492},{"./browser/algorithms.json":105}],105:[function(require,module,exports){
22493module.exports={
22494 "sha224WithRSAEncryption": {
22495 "sign": "rsa",
22496 "hash": "sha224",
22497 "id": "302d300d06096086480165030402040500041c"
22498 },
22499 "RSA-SHA224": {
22500 "sign": "ecdsa/rsa",
22501 "hash": "sha224",
22502 "id": "302d300d06096086480165030402040500041c"
22503 },
22504 "sha256WithRSAEncryption": {
22505 "sign": "rsa",
22506 "hash": "sha256",
22507 "id": "3031300d060960864801650304020105000420"
22508 },
22509 "RSA-SHA256": {
22510 "sign": "ecdsa/rsa",
22511 "hash": "sha256",
22512 "id": "3031300d060960864801650304020105000420"
22513 },
22514 "sha384WithRSAEncryption": {
22515 "sign": "rsa",
22516 "hash": "sha384",
22517 "id": "3041300d060960864801650304020205000430"
22518 },
22519 "RSA-SHA384": {
22520 "sign": "ecdsa/rsa",
22521 "hash": "sha384",
22522 "id": "3041300d060960864801650304020205000430"
22523 },
22524 "sha512WithRSAEncryption": {
22525 "sign": "rsa",
22526 "hash": "sha512",
22527 "id": "3051300d060960864801650304020305000440"
22528 },
22529 "RSA-SHA512": {
22530 "sign": "ecdsa/rsa",
22531 "hash": "sha512",
22532 "id": "3051300d060960864801650304020305000440"
22533 },
22534 "RSA-SHA1": {
22535 "sign": "rsa",
22536 "hash": "sha1",
22537 "id": "3021300906052b0e03021a05000414"
22538 },
22539 "ecdsa-with-SHA1": {
22540 "sign": "ecdsa",
22541 "hash": "sha1",
22542 "id": ""
22543 },
22544 "sha256": {
22545 "sign": "ecdsa",
22546 "hash": "sha256",
22547 "id": ""
22548 },
22549 "sha224": {
22550 "sign": "ecdsa",
22551 "hash": "sha224",
22552 "id": ""
22553 },
22554 "sha384": {
22555 "sign": "ecdsa",
22556 "hash": "sha384",
22557 "id": ""
22558 },
22559 "sha512": {
22560 "sign": "ecdsa",
22561 "hash": "sha512",
22562 "id": ""
22563 },
22564 "DSA-SHA": {
22565 "sign": "dsa",
22566 "hash": "sha1",
22567 "id": ""
22568 },
22569 "DSA-SHA1": {
22570 "sign": "dsa",
22571 "hash": "sha1",
22572 "id": ""
22573 },
22574 "DSA": {
22575 "sign": "dsa",
22576 "hash": "sha1",
22577 "id": ""
22578 },
22579 "DSA-WITH-SHA224": {
22580 "sign": "dsa",
22581 "hash": "sha224",
22582 "id": ""
22583 },
22584 "DSA-SHA224": {
22585 "sign": "dsa",
22586 "hash": "sha224",
22587 "id": ""
22588 },
22589 "DSA-WITH-SHA256": {
22590 "sign": "dsa",
22591 "hash": "sha256",
22592 "id": ""
22593 },
22594 "DSA-SHA256": {
22595 "sign": "dsa",
22596 "hash": "sha256",
22597 "id": ""
22598 },
22599 "DSA-WITH-SHA384": {
22600 "sign": "dsa",
22601 "hash": "sha384",
22602 "id": ""
22603 },
22604 "DSA-SHA384": {
22605 "sign": "dsa",
22606 "hash": "sha384",
22607 "id": ""
22608 },
22609 "DSA-WITH-SHA512": {
22610 "sign": "dsa",
22611 "hash": "sha512",
22612 "id": ""
22613 },
22614 "DSA-SHA512": {
22615 "sign": "dsa",
22616 "hash": "sha512",
22617 "id": ""
22618 },
22619 "DSA-RIPEMD160": {
22620 "sign": "dsa",
22621 "hash": "rmd160",
22622 "id": ""
22623 },
22624 "ripemd160WithRSA": {
22625 "sign": "rsa",
22626 "hash": "rmd160",
22627 "id": "3021300906052b2403020105000414"
22628 },
22629 "RSA-RIPEMD160": {
22630 "sign": "rsa",
22631 "hash": "rmd160",
22632 "id": "3021300906052b2403020105000414"
22633 },
22634 "md5WithRSAEncryption": {
22635 "sign": "rsa",
22636 "hash": "md5",
22637 "id": "3020300c06082a864886f70d020505000410"
22638 },
22639 "RSA-MD5": {
22640 "sign": "rsa",
22641 "hash": "md5",
22642 "id": "3020300c06082a864886f70d020505000410"
22643 }
22644}
22645
22646},{}],106:[function(require,module,exports){
22647module.exports={
22648 "1.3.132.0.10": "secp256k1",
22649 "1.3.132.0.33": "p224",
22650 "1.2.840.10045.3.1.1": "p192",
22651 "1.2.840.10045.3.1.7": "p256",
22652 "1.3.132.0.34": "p384",
22653 "1.3.132.0.35": "p521"
22654}
22655
22656},{}],107:[function(require,module,exports){
22657(function (Buffer){
22658var createHash = require('create-hash')
22659var stream = require('stream')
22660var inherits = require('inherits')
22661var sign = require('./sign')
22662var verify = require('./verify')
22663
22664var algorithms = require('./algorithms.json')
22665Object.keys(algorithms).forEach(function (key) {
22666 algorithms[key].id = new Buffer(algorithms[key].id, 'hex')
22667 algorithms[key.toLowerCase()] = algorithms[key]
22668})
22669
22670function Sign (algorithm) {
22671 stream.Writable.call(this)
22672
22673 var data = algorithms[algorithm]
22674 if (!data) throw new Error('Unknown message digest')
22675
22676 this._hashType = data.hash
22677 this._hash = createHash(data.hash)
22678 this._tag = data.id
22679 this._signType = data.sign
22680}
22681inherits(Sign, stream.Writable)
22682
22683Sign.prototype._write = function _write (data, _, done) {
22684 this._hash.update(data)
22685 done()
22686}
22687
22688Sign.prototype.update = function update (data, enc) {
22689 if (typeof data === 'string') data = new Buffer(data, enc)
22690
22691 this._hash.update(data)
22692 return this
22693}
22694
22695Sign.prototype.sign = function signMethod (key, enc) {
22696 this.end()
22697 var hash = this._hash.digest()
22698 var sig = sign(hash, key, this._hashType, this._signType, this._tag)
22699
22700 return enc ? sig.toString(enc) : sig
22701}
22702
22703function Verify (algorithm) {
22704 stream.Writable.call(this)
22705
22706 var data = algorithms[algorithm]
22707 if (!data) throw new Error('Unknown message digest')
22708
22709 this._hash = createHash(data.hash)
22710 this._tag = data.id
22711 this._signType = data.sign
22712}
22713inherits(Verify, stream.Writable)
22714
22715Verify.prototype._write = function _write (data, _, done) {
22716 this._hash.update(data)
22717 done()
22718}
22719
22720Verify.prototype.update = function update (data, enc) {
22721 if (typeof data === 'string') data = new Buffer(data, enc)
22722
22723 this._hash.update(data)
22724 return this
22725}
22726
22727Verify.prototype.verify = function verifyMethod (key, sig, enc) {
22728 if (typeof sig === 'string') sig = new Buffer(sig, enc)
22729
22730 this.end()
22731 var hash = this._hash.digest()
22732 return verify(sig, hash, key, this._signType, this._tag)
22733}
22734
22735function createSign (algorithm) {
22736 return new Sign(algorithm)
22737}
22738
22739function createVerify (algorithm) {
22740 return new Verify(algorithm)
22741}
22742
22743module.exports = {
22744 Sign: createSign,
22745 Verify: createVerify,
22746 createSign: createSign,
22747 createVerify: createVerify
22748}
22749
22750}).call(this,require("buffer").Buffer)
22751},{"./algorithms.json":105,"./sign":108,"./verify":109,"buffer":114,"create-hash":122,"inherits":210,"stream":361}],108:[function(require,module,exports){
22752(function (Buffer){
22753// much of this based on https://github.com/indutny/self-signed/blob/gh-pages/lib/rsa.js
22754var createHmac = require('create-hmac')
22755var crt = require('browserify-rsa')
22756var EC = require('elliptic').ec
22757var BN = require('bn.js')
22758var parseKeys = require('parse-asn1')
22759var curves = require('./curves.json')
22760
22761function sign (hash, key, hashType, signType, tag) {
22762 var priv = parseKeys(key)
22763 if (priv.curve) {
22764 // rsa keys can be interpreted as ecdsa ones in openssl
22765 if (signType !== 'ecdsa' && signType !== 'ecdsa/rsa') throw new Error('wrong private key type')
22766 return ecSign(hash, priv)
22767 } else if (priv.type === 'dsa') {
22768 if (signType !== 'dsa') throw new Error('wrong private key type')
22769 return dsaSign(hash, priv, hashType)
22770 } else {
22771 if (signType !== 'rsa' && signType !== 'ecdsa/rsa') throw new Error('wrong private key type')
22772 }
22773 hash = Buffer.concat([tag, hash])
22774 var len = priv.modulus.byteLength()
22775 var pad = [ 0, 1 ]
22776 while (hash.length + pad.length + 1 < len) pad.push(0xff)
22777 pad.push(0x00)
22778 var i = -1
22779 while (++i < hash.length) pad.push(hash[i])
22780
22781 var out = crt(pad, priv)
22782 return out
22783}
22784
22785function ecSign (hash, priv) {
22786 var curveId = curves[priv.curve.join('.')]
22787 if (!curveId) throw new Error('unknown curve ' + priv.curve.join('.'))
22788
22789 var curve = new EC(curveId)
22790 var key = curve.keyFromPrivate(priv.privateKey)
22791 var out = key.sign(hash)
22792
22793 return new Buffer(out.toDER())
22794}
22795
22796function dsaSign (hash, priv, algo) {
22797 var x = priv.params.priv_key
22798 var p = priv.params.p
22799 var q = priv.params.q
22800 var g = priv.params.g
22801 var r = new BN(0)
22802 var k
22803 var H = bits2int(hash, q).mod(q)
22804 var s = false
22805 var kv = getKey(x, q, hash, algo)
22806 while (s === false) {
22807 k = makeKey(q, kv, algo)
22808 r = makeR(g, k, p, q)
22809 s = k.invm(q).imul(H.add(x.mul(r))).mod(q)
22810 if (s.cmpn(0) === 0) {
22811 s = false
22812 r = new BN(0)
22813 }
22814 }
22815 return toDER(r, s)
22816}
22817
22818function toDER (r, s) {
22819 r = r.toArray()
22820 s = s.toArray()
22821
22822 // Pad values
22823 if (r[0] & 0x80) r = [ 0 ].concat(r)
22824 if (s[0] & 0x80) s = [ 0 ].concat(s)
22825
22826 var total = r.length + s.length + 4
22827 var res = [ 0x30, total, 0x02, r.length ]
22828 res = res.concat(r, [ 0x02, s.length ], s)
22829 return new Buffer(res)
22830}
22831
22832function getKey (x, q, hash, algo) {
22833 x = new Buffer(x.toArray())
22834 if (x.length < q.byteLength()) {
22835 var zeros = new Buffer(q.byteLength() - x.length)
22836 zeros.fill(0)
22837 x = Buffer.concat([ zeros, x ])
22838 }
22839 var hlen = hash.length
22840 var hbits = bits2octets(hash, q)
22841 var v = new Buffer(hlen)
22842 v.fill(1)
22843 var k = new Buffer(hlen)
22844 k.fill(0)
22845 k = createHmac(algo, k).update(v).update(new Buffer([ 0 ])).update(x).update(hbits).digest()
22846 v = createHmac(algo, k).update(v).digest()
22847 k = createHmac(algo, k).update(v).update(new Buffer([ 1 ])).update(x).update(hbits).digest()
22848 v = createHmac(algo, k).update(v).digest()
22849 return { k: k, v: v }
22850}
22851
22852function bits2int (obits, q) {
22853 var bits = new BN(obits)
22854 var shift = (obits.length << 3) - q.bitLength()
22855 if (shift > 0) bits.ishrn(shift)
22856 return bits
22857}
22858
22859function bits2octets (bits, q) {
22860 bits = bits2int(bits, q)
22861 bits = bits.mod(q)
22862 var out = new Buffer(bits.toArray())
22863 if (out.length < q.byteLength()) {
22864 var zeros = new Buffer(q.byteLength() - out.length)
22865 zeros.fill(0)
22866 out = Buffer.concat([ zeros, out ])
22867 }
22868 return out
22869}
22870
22871function makeKey (q, kv, algo) {
22872 var t
22873 var k
22874
22875 do {
22876 t = new Buffer(0)
22877
22878 while (t.length * 8 < q.bitLength()) {
22879 kv.v = createHmac(algo, kv.k).update(kv.v).digest()
22880 t = Buffer.concat([ t, kv.v ])
22881 }
22882
22883 k = bits2int(t, q)
22884 kv.k = createHmac(algo, kv.k).update(kv.v).update(new Buffer([ 0 ])).digest()
22885 kv.v = createHmac(algo, kv.k).update(kv.v).digest()
22886 } while (k.cmp(q) !== -1)
22887
22888 return k
22889}
22890
22891function makeR (g, k, p, q) {
22892 return g.toRed(BN.mont(p)).redPow(k).fromRed().mod(q)
22893}
22894
22895module.exports = sign
22896module.exports.getKey = getKey
22897module.exports.makeKey = makeKey
22898
22899}).call(this,require("buffer").Buffer)
22900},{"./curves.json":106,"bn.js":80,"browserify-rsa":103,"buffer":114,"create-hmac":124,"elliptic":142,"parse-asn1":256}],109:[function(require,module,exports){
22901(function (Buffer){
22902// much of this based on https://github.com/indutny/self-signed/blob/gh-pages/lib/rsa.js
22903var BN = require('bn.js')
22904var EC = require('elliptic').ec
22905var parseKeys = require('parse-asn1')
22906var curves = require('./curves.json')
22907
22908function verify (sig, hash, key, signType, tag) {
22909 var pub = parseKeys(key)
22910 if (pub.type === 'ec') {
22911 // rsa keys can be interpreted as ecdsa ones in openssl
22912 if (signType !== 'ecdsa' && signType !== 'ecdsa/rsa') throw new Error('wrong public key type')
22913 return ecVerify(sig, hash, pub)
22914 } else if (pub.type === 'dsa') {
22915 if (signType !== 'dsa') throw new Error('wrong public key type')
22916 return dsaVerify(sig, hash, pub)
22917 } else {
22918 if (signType !== 'rsa' && signType !== 'ecdsa/rsa') throw new Error('wrong public key type')
22919 }
22920 hash = Buffer.concat([tag, hash])
22921 var len = pub.modulus.byteLength()
22922 var pad = [ 1 ]
22923 var padNum = 0
22924 while (hash.length + pad.length + 2 < len) {
22925 pad.push(0xff)
22926 padNum++
22927 }
22928 pad.push(0x00)
22929 var i = -1
22930 while (++i < hash.length) {
22931 pad.push(hash[i])
22932 }
22933 pad = new Buffer(pad)
22934 var red = BN.mont(pub.modulus)
22935 sig = new BN(sig).toRed(red)
22936
22937 sig = sig.redPow(new BN(pub.publicExponent))
22938 sig = new Buffer(sig.fromRed().toArray())
22939 var out = padNum < 8 ? 1 : 0
22940 len = Math.min(sig.length, pad.length)
22941 if (sig.length !== pad.length) out = 1
22942
22943 i = -1
22944 while (++i < len) out |= sig[i] ^ pad[i]
22945 return out === 0
22946}
22947
22948function ecVerify (sig, hash, pub) {
22949 var curveId = curves[pub.data.algorithm.curve.join('.')]
22950 if (!curveId) throw new Error('unknown curve ' + pub.data.algorithm.curve.join('.'))
22951
22952 var curve = new EC(curveId)
22953 var pubkey = pub.data.subjectPrivateKey.data
22954
22955 return curve.verify(hash, sig, pubkey)
22956}
22957
22958function dsaVerify (sig, hash, pub) {
22959 var p = pub.data.p
22960 var q = pub.data.q
22961 var g = pub.data.g
22962 var y = pub.data.pub_key
22963 var unpacked = parseKeys.signature.decode(sig, 'der')
22964 var s = unpacked.s
22965 var r = unpacked.r
22966 checkValue(s, q)
22967 checkValue(r, q)
22968 var montp = BN.mont(p)
22969 var w = s.invm(q)
22970 var v = g.toRed(montp)
22971 .redPow(new BN(hash).mul(w).mod(q))
22972 .fromRed()
22973 .mul(y.toRed(montp).redPow(r.mul(w).mod(q)).fromRed())
22974 .mod(p)
22975 .mod(q)
22976 return v.cmp(r) === 0
22977}
22978
22979function checkValue (b, q) {
22980 if (b.cmpn(0) <= 0) throw new Error('invalid sig')
22981 if (b.cmp(q) >= q) throw new Error('invalid sig')
22982}
22983
22984module.exports = verify
22985
22986}).call(this,require("buffer").Buffer)
22987},{"./curves.json":106,"bn.js":80,"buffer":114,"elliptic":142,"parse-asn1":256}],110:[function(require,module,exports){
22988(function (process,Buffer){
22989'use strict';
22990/* eslint camelcase: "off" */
22991
22992var assert = require('assert');
22993
22994var Zstream = require('pako/lib/zlib/zstream');
22995var zlib_deflate = require('pako/lib/zlib/deflate.js');
22996var zlib_inflate = require('pako/lib/zlib/inflate.js');
22997var constants = require('pako/lib/zlib/constants');
22998
22999for (var key in constants) {
23000 exports[key] = constants[key];
23001}
23002
23003// zlib modes
23004exports.NONE = 0;
23005exports.DEFLATE = 1;
23006exports.INFLATE = 2;
23007exports.GZIP = 3;
23008exports.GUNZIP = 4;
23009exports.DEFLATERAW = 5;
23010exports.INFLATERAW = 6;
23011exports.UNZIP = 7;
23012
23013var GZIP_HEADER_ID1 = 0x1f;
23014var GZIP_HEADER_ID2 = 0x8b;
23015
23016/**
23017 * Emulate Node's zlib C++ layer for use by the JS layer in index.js
23018 */
23019function Zlib(mode) {
23020 if (typeof mode !== 'number' || mode < exports.DEFLATE || mode > exports.UNZIP) {
23021 throw new TypeError('Bad argument');
23022 }
23023
23024 this.dictionary = null;
23025 this.err = 0;
23026 this.flush = 0;
23027 this.init_done = false;
23028 this.level = 0;
23029 this.memLevel = 0;
23030 this.mode = mode;
23031 this.strategy = 0;
23032 this.windowBits = 0;
23033 this.write_in_progress = false;
23034 this.pending_close = false;
23035 this.gzip_id_bytes_read = 0;
23036}
23037
23038Zlib.prototype.close = function () {
23039 if (this.write_in_progress) {
23040 this.pending_close = true;
23041 return;
23042 }
23043
23044 this.pending_close = false;
23045
23046 assert(this.init_done, 'close before init');
23047 assert(this.mode <= exports.UNZIP);
23048
23049 if (this.mode === exports.DEFLATE || this.mode === exports.GZIP || this.mode === exports.DEFLATERAW) {
23050 zlib_deflate.deflateEnd(this.strm);
23051 } else if (this.mode === exports.INFLATE || this.mode === exports.GUNZIP || this.mode === exports.INFLATERAW || this.mode === exports.UNZIP) {
23052 zlib_inflate.inflateEnd(this.strm);
23053 }
23054
23055 this.mode = exports.NONE;
23056
23057 this.dictionary = null;
23058};
23059
23060Zlib.prototype.write = function (flush, input, in_off, in_len, out, out_off, out_len) {
23061 return this._write(true, flush, input, in_off, in_len, out, out_off, out_len);
23062};
23063
23064Zlib.prototype.writeSync = function (flush, input, in_off, in_len, out, out_off, out_len) {
23065 return this._write(false, flush, input, in_off, in_len, out, out_off, out_len);
23066};
23067
23068Zlib.prototype._write = function (async, flush, input, in_off, in_len, out, out_off, out_len) {
23069 assert.equal(arguments.length, 8);
23070
23071 assert(this.init_done, 'write before init');
23072 assert(this.mode !== exports.NONE, 'already finalized');
23073 assert.equal(false, this.write_in_progress, 'write already in progress');
23074 assert.equal(false, this.pending_close, 'close is pending');
23075
23076 this.write_in_progress = true;
23077
23078 assert.equal(false, flush === undefined, 'must provide flush value');
23079
23080 this.write_in_progress = true;
23081
23082 if (flush !== exports.Z_NO_FLUSH && flush !== exports.Z_PARTIAL_FLUSH && flush !== exports.Z_SYNC_FLUSH && flush !== exports.Z_FULL_FLUSH && flush !== exports.Z_FINISH && flush !== exports.Z_BLOCK) {
23083 throw new Error('Invalid flush value');
23084 }
23085
23086 if (input == null) {
23087 input = Buffer.alloc(0);
23088 in_len = 0;
23089 in_off = 0;
23090 }
23091
23092 this.strm.avail_in = in_len;
23093 this.strm.input = input;
23094 this.strm.next_in = in_off;
23095 this.strm.avail_out = out_len;
23096 this.strm.output = out;
23097 this.strm.next_out = out_off;
23098 this.flush = flush;
23099
23100 if (!async) {
23101 // sync version
23102 this._process();
23103
23104 if (this._checkError()) {
23105 return this._afterSync();
23106 }
23107 return;
23108 }
23109
23110 // async version
23111 var self = this;
23112 process.nextTick(function () {
23113 self._process();
23114 self._after();
23115 });
23116
23117 return this;
23118};
23119
23120Zlib.prototype._afterSync = function () {
23121 var avail_out = this.strm.avail_out;
23122 var avail_in = this.strm.avail_in;
23123
23124 this.write_in_progress = false;
23125
23126 return [avail_in, avail_out];
23127};
23128
23129Zlib.prototype._process = function () {
23130 var next_expected_header_byte = null;
23131
23132 // If the avail_out is left at 0, then it means that it ran out
23133 // of room. If there was avail_out left over, then it means
23134 // that all of the input was consumed.
23135 switch (this.mode) {
23136 case exports.DEFLATE:
23137 case exports.GZIP:
23138 case exports.DEFLATERAW:
23139 this.err = zlib_deflate.deflate(this.strm, this.flush);
23140 break;
23141 case exports.UNZIP:
23142 if (this.strm.avail_in > 0) {
23143 next_expected_header_byte = this.strm.next_in;
23144 }
23145
23146 switch (this.gzip_id_bytes_read) {
23147 case 0:
23148 if (next_expected_header_byte === null) {
23149 break;
23150 }
23151
23152 if (this.strm.input[next_expected_header_byte] === GZIP_HEADER_ID1) {
23153 this.gzip_id_bytes_read = 1;
23154 next_expected_header_byte++;
23155
23156 if (this.strm.avail_in === 1) {
23157 // The only available byte was already read.
23158 break;
23159 }
23160 } else {
23161 this.mode = exports.INFLATE;
23162 break;
23163 }
23164
23165 // fallthrough
23166 case 1:
23167 if (next_expected_header_byte === null) {
23168 break;
23169 }
23170
23171 if (this.strm.input[next_expected_header_byte] === GZIP_HEADER_ID2) {
23172 this.gzip_id_bytes_read = 2;
23173 this.mode = exports.GUNZIP;
23174 } else {
23175 // There is no actual difference between INFLATE and INFLATERAW
23176 // (after initialization).
23177 this.mode = exports.INFLATE;
23178 }
23179
23180 break;
23181 default:
23182 throw new Error('invalid number of gzip magic number bytes read');
23183 }
23184
23185 // fallthrough
23186 case exports.INFLATE:
23187 case exports.GUNZIP:
23188 case exports.INFLATERAW:
23189 this.err = zlib_inflate.inflate(this.strm, this.flush
23190
23191 // If data was encoded with dictionary
23192 );if (this.err === exports.Z_NEED_DICT && this.dictionary) {
23193 // Load it
23194 this.err = zlib_inflate.inflateSetDictionary(this.strm, this.dictionary);
23195 if (this.err === exports.Z_OK) {
23196 // And try to decode again
23197 this.err = zlib_inflate.inflate(this.strm, this.flush);
23198 } else if (this.err === exports.Z_DATA_ERROR) {
23199 // Both inflateSetDictionary() and inflate() return Z_DATA_ERROR.
23200 // Make it possible for After() to tell a bad dictionary from bad
23201 // input.
23202 this.err = exports.Z_NEED_DICT;
23203 }
23204 }
23205 while (this.strm.avail_in > 0 && this.mode === exports.GUNZIP && this.err === exports.Z_STREAM_END && this.strm.next_in[0] !== 0x00) {
23206 // Bytes remain in input buffer. Perhaps this is another compressed
23207 // member in the same archive, or just trailing garbage.
23208 // Trailing zero bytes are okay, though, since they are frequently
23209 // used for padding.
23210
23211 this.reset();
23212 this.err = zlib_inflate.inflate(this.strm, this.flush);
23213 }
23214 break;
23215 default:
23216 throw new Error('Unknown mode ' + this.mode);
23217 }
23218};
23219
23220Zlib.prototype._checkError = function () {
23221 // Acceptable error states depend on the type of zlib stream.
23222 switch (this.err) {
23223 case exports.Z_OK:
23224 case exports.Z_BUF_ERROR:
23225 if (this.strm.avail_out !== 0 && this.flush === exports.Z_FINISH) {
23226 this._error('unexpected end of file');
23227 return false;
23228 }
23229 break;
23230 case exports.Z_STREAM_END:
23231 // normal statuses, not fatal
23232 break;
23233 case exports.Z_NEED_DICT:
23234 if (this.dictionary == null) {
23235 this._error('Missing dictionary');
23236 } else {
23237 this._error('Bad dictionary');
23238 }
23239 return false;
23240 default:
23241 // something else.
23242 this._error('Zlib error');
23243 return false;
23244 }
23245
23246 return true;
23247};
23248
23249Zlib.prototype._after = function () {
23250 if (!this._checkError()) {
23251 return;
23252 }
23253
23254 var avail_out = this.strm.avail_out;
23255 var avail_in = this.strm.avail_in;
23256
23257 this.write_in_progress = false;
23258
23259 // call the write() cb
23260 this.callback(avail_in, avail_out);
23261
23262 if (this.pending_close) {
23263 this.close();
23264 }
23265};
23266
23267Zlib.prototype._error = function (message) {
23268 if (this.strm.msg) {
23269 message = this.strm.msg;
23270 }
23271 this.onerror(message, this.err
23272
23273 // no hope of rescue.
23274 );this.write_in_progress = false;
23275 if (this.pending_close) {
23276 this.close();
23277 }
23278};
23279
23280Zlib.prototype.init = function (windowBits, level, memLevel, strategy, dictionary) {
23281 assert(arguments.length === 4 || arguments.length === 5, 'init(windowBits, level, memLevel, strategy, [dictionary])');
23282
23283 assert(windowBits >= 8 && windowBits <= 15, 'invalid windowBits');
23284 assert(level >= -1 && level <= 9, 'invalid compression level');
23285
23286 assert(memLevel >= 1 && memLevel <= 9, 'invalid memlevel');
23287
23288 assert(strategy === exports.Z_FILTERED || strategy === exports.Z_HUFFMAN_ONLY || strategy === exports.Z_RLE || strategy === exports.Z_FIXED || strategy === exports.Z_DEFAULT_STRATEGY, 'invalid strategy');
23289
23290 this._init(level, windowBits, memLevel, strategy, dictionary);
23291 this._setDictionary();
23292};
23293
23294Zlib.prototype.params = function () {
23295 throw new Error('deflateParams Not supported');
23296};
23297
23298Zlib.prototype.reset = function () {
23299 this._reset();
23300 this._setDictionary();
23301};
23302
23303Zlib.prototype._init = function (level, windowBits, memLevel, strategy, dictionary) {
23304 this.level = level;
23305 this.windowBits = windowBits;
23306 this.memLevel = memLevel;
23307 this.strategy = strategy;
23308
23309 this.flush = exports.Z_NO_FLUSH;
23310
23311 this.err = exports.Z_OK;
23312
23313 if (this.mode === exports.GZIP || this.mode === exports.GUNZIP) {
23314 this.windowBits += 16;
23315 }
23316
23317 if (this.mode === exports.UNZIP) {
23318 this.windowBits += 32;
23319 }
23320
23321 if (this.mode === exports.DEFLATERAW || this.mode === exports.INFLATERAW) {
23322 this.windowBits = -1 * this.windowBits;
23323 }
23324
23325 this.strm = new Zstream();
23326
23327 switch (this.mode) {
23328 case exports.DEFLATE:
23329 case exports.GZIP:
23330 case exports.DEFLATERAW:
23331 this.err = zlib_deflate.deflateInit2(this.strm, this.level, exports.Z_DEFLATED, this.windowBits, this.memLevel, this.strategy);
23332 break;
23333 case exports.INFLATE:
23334 case exports.GUNZIP:
23335 case exports.INFLATERAW:
23336 case exports.UNZIP:
23337 this.err = zlib_inflate.inflateInit2(this.strm, this.windowBits);
23338 break;
23339 default:
23340 throw new Error('Unknown mode ' + this.mode);
23341 }
23342
23343 if (this.err !== exports.Z_OK) {
23344 this._error('Init error');
23345 }
23346
23347 this.dictionary = dictionary;
23348
23349 this.write_in_progress = false;
23350 this.init_done = true;
23351};
23352
23353Zlib.prototype._setDictionary = function () {
23354 if (this.dictionary == null) {
23355 return;
23356 }
23357
23358 this.err = exports.Z_OK;
23359
23360 switch (this.mode) {
23361 case exports.DEFLATE:
23362 case exports.DEFLATERAW:
23363 this.err = zlib_deflate.deflateSetDictionary(this.strm, this.dictionary);
23364 break;
23365 default:
23366 break;
23367 }
23368
23369 if (this.err !== exports.Z_OK) {
23370 this._error('Failed to set dictionary');
23371 }
23372};
23373
23374Zlib.prototype._reset = function () {
23375 this.err = exports.Z_OK;
23376
23377 switch (this.mode) {
23378 case exports.DEFLATE:
23379 case exports.DEFLATERAW:
23380 case exports.GZIP:
23381 this.err = zlib_deflate.deflateReset(this.strm);
23382 break;
23383 case exports.INFLATE:
23384 case exports.INFLATERAW:
23385 case exports.GUNZIP:
23386 this.err = zlib_inflate.inflateReset(this.strm);
23387 break;
23388 default:
23389 break;
23390 }
23391
23392 if (this.err !== exports.Z_OK) {
23393 this._error('Failed to reset stream');
23394 }
23395};
23396
23397exports.Zlib = Zlib;
23398}).call(this,require('_process'),require("buffer").Buffer)
23399},{"_process":265,"assert":68,"buffer":114,"pako/lib/zlib/constants":243,"pako/lib/zlib/deflate.js":245,"pako/lib/zlib/inflate.js":247,"pako/lib/zlib/zstream":251}],111:[function(require,module,exports){
23400(function (process){
23401'use strict';
23402
23403var Buffer = require('buffer').Buffer;
23404var Transform = require('stream').Transform;
23405var binding = require('./binding');
23406var util = require('util');
23407var assert = require('assert').ok;
23408var kMaxLength = require('buffer').kMaxLength;
23409var kRangeErrorMessage = 'Cannot create final Buffer. It would be larger ' + 'than 0x' + kMaxLength.toString(16) + ' bytes';
23410
23411// zlib doesn't provide these, so kludge them in following the same
23412// const naming scheme zlib uses.
23413binding.Z_MIN_WINDOWBITS = 8;
23414binding.Z_MAX_WINDOWBITS = 15;
23415binding.Z_DEFAULT_WINDOWBITS = 15;
23416
23417// fewer than 64 bytes per chunk is stupid.
23418// technically it could work with as few as 8, but even 64 bytes
23419// is absurdly low. Usually a MB or more is best.
23420binding.Z_MIN_CHUNK = 64;
23421binding.Z_MAX_CHUNK = Infinity;
23422binding.Z_DEFAULT_CHUNK = 16 * 1024;
23423
23424binding.Z_MIN_MEMLEVEL = 1;
23425binding.Z_MAX_MEMLEVEL = 9;
23426binding.Z_DEFAULT_MEMLEVEL = 8;
23427
23428binding.Z_MIN_LEVEL = -1;
23429binding.Z_MAX_LEVEL = 9;
23430binding.Z_DEFAULT_LEVEL = binding.Z_DEFAULT_COMPRESSION;
23431
23432// expose all the zlib constants
23433var bkeys = Object.keys(binding);
23434for (var bk = 0; bk < bkeys.length; bk++) {
23435 var bkey = bkeys[bk];
23436 if (bkey.match(/^Z/)) {
23437 Object.defineProperty(exports, bkey, {
23438 enumerable: true, value: binding[bkey], writable: false
23439 });
23440 }
23441}
23442
23443// translation table for return codes.
23444var codes = {
23445 Z_OK: binding.Z_OK,
23446 Z_STREAM_END: binding.Z_STREAM_END,
23447 Z_NEED_DICT: binding.Z_NEED_DICT,
23448 Z_ERRNO: binding.Z_ERRNO,
23449 Z_STREAM_ERROR: binding.Z_STREAM_ERROR,
23450 Z_DATA_ERROR: binding.Z_DATA_ERROR,
23451 Z_MEM_ERROR: binding.Z_MEM_ERROR,
23452 Z_BUF_ERROR: binding.Z_BUF_ERROR,
23453 Z_VERSION_ERROR: binding.Z_VERSION_ERROR
23454};
23455
23456var ckeys = Object.keys(codes);
23457for (var ck = 0; ck < ckeys.length; ck++) {
23458 var ckey = ckeys[ck];
23459 codes[codes[ckey]] = ckey;
23460}
23461
23462Object.defineProperty(exports, 'codes', {
23463 enumerable: true, value: Object.freeze(codes), writable: false
23464});
23465
23466exports.Deflate = Deflate;
23467exports.Inflate = Inflate;
23468exports.Gzip = Gzip;
23469exports.Gunzip = Gunzip;
23470exports.DeflateRaw = DeflateRaw;
23471exports.InflateRaw = InflateRaw;
23472exports.Unzip = Unzip;
23473
23474exports.createDeflate = function (o) {
23475 return new Deflate(o);
23476};
23477
23478exports.createInflate = function (o) {
23479 return new Inflate(o);
23480};
23481
23482exports.createDeflateRaw = function (o) {
23483 return new DeflateRaw(o);
23484};
23485
23486exports.createInflateRaw = function (o) {
23487 return new InflateRaw(o);
23488};
23489
23490exports.createGzip = function (o) {
23491 return new Gzip(o);
23492};
23493
23494exports.createGunzip = function (o) {
23495 return new Gunzip(o);
23496};
23497
23498exports.createUnzip = function (o) {
23499 return new Unzip(o);
23500};
23501
23502// Convenience methods.
23503// compress/decompress a string or buffer in one step.
23504exports.deflate = function (buffer, opts, callback) {
23505 if (typeof opts === 'function') {
23506 callback = opts;
23507 opts = {};
23508 }
23509 return zlibBuffer(new Deflate(opts), buffer, callback);
23510};
23511
23512exports.deflateSync = function (buffer, opts) {
23513 return zlibBufferSync(new Deflate(opts), buffer);
23514};
23515
23516exports.gzip = function (buffer, opts, callback) {
23517 if (typeof opts === 'function') {
23518 callback = opts;
23519 opts = {};
23520 }
23521 return zlibBuffer(new Gzip(opts), buffer, callback);
23522};
23523
23524exports.gzipSync = function (buffer, opts) {
23525 return zlibBufferSync(new Gzip(opts), buffer);
23526};
23527
23528exports.deflateRaw = function (buffer, opts, callback) {
23529 if (typeof opts === 'function') {
23530 callback = opts;
23531 opts = {};
23532 }
23533 return zlibBuffer(new DeflateRaw(opts), buffer, callback);
23534};
23535
23536exports.deflateRawSync = function (buffer, opts) {
23537 return zlibBufferSync(new DeflateRaw(opts), buffer);
23538};
23539
23540exports.unzip = function (buffer, opts, callback) {
23541 if (typeof opts === 'function') {
23542 callback = opts;
23543 opts = {};
23544 }
23545 return zlibBuffer(new Unzip(opts), buffer, callback);
23546};
23547
23548exports.unzipSync = function (buffer, opts) {
23549 return zlibBufferSync(new Unzip(opts), buffer);
23550};
23551
23552exports.inflate = function (buffer, opts, callback) {
23553 if (typeof opts === 'function') {
23554 callback = opts;
23555 opts = {};
23556 }
23557 return zlibBuffer(new Inflate(opts), buffer, callback);
23558};
23559
23560exports.inflateSync = function (buffer, opts) {
23561 return zlibBufferSync(new Inflate(opts), buffer);
23562};
23563
23564exports.gunzip = function (buffer, opts, callback) {
23565 if (typeof opts === 'function') {
23566 callback = opts;
23567 opts = {};
23568 }
23569 return zlibBuffer(new Gunzip(opts), buffer, callback);
23570};
23571
23572exports.gunzipSync = function (buffer, opts) {
23573 return zlibBufferSync(new Gunzip(opts), buffer);
23574};
23575
23576exports.inflateRaw = function (buffer, opts, callback) {
23577 if (typeof opts === 'function') {
23578 callback = opts;
23579 opts = {};
23580 }
23581 return zlibBuffer(new InflateRaw(opts), buffer, callback);
23582};
23583
23584exports.inflateRawSync = function (buffer, opts) {
23585 return zlibBufferSync(new InflateRaw(opts), buffer);
23586};
23587
23588function zlibBuffer(engine, buffer, callback) {
23589 var buffers = [];
23590 var nread = 0;
23591
23592 engine.on('error', onError);
23593 engine.on('end', onEnd);
23594
23595 engine.end(buffer);
23596 flow();
23597
23598 function flow() {
23599 var chunk;
23600 while (null !== (chunk = engine.read())) {
23601 buffers.push(chunk);
23602 nread += chunk.length;
23603 }
23604 engine.once('readable', flow);
23605 }
23606
23607 function onError(err) {
23608 engine.removeListener('end', onEnd);
23609 engine.removeListener('readable', flow);
23610 callback(err);
23611 }
23612
23613 function onEnd() {
23614 var buf;
23615 var err = null;
23616
23617 if (nread >= kMaxLength) {
23618 err = new RangeError(kRangeErrorMessage);
23619 } else {
23620 buf = Buffer.concat(buffers, nread);
23621 }
23622
23623 buffers = [];
23624 engine.close();
23625 callback(err, buf);
23626 }
23627}
23628
23629function zlibBufferSync(engine, buffer) {
23630 if (typeof buffer === 'string') buffer = Buffer.from(buffer);
23631
23632 if (!Buffer.isBuffer(buffer)) throw new TypeError('Not a string or buffer');
23633
23634 var flushFlag = engine._finishFlushFlag;
23635
23636 return engine._processChunk(buffer, flushFlag);
23637}
23638
23639// generic zlib
23640// minimal 2-byte header
23641function Deflate(opts) {
23642 if (!(this instanceof Deflate)) return new Deflate(opts);
23643 Zlib.call(this, opts, binding.DEFLATE);
23644}
23645
23646function Inflate(opts) {
23647 if (!(this instanceof Inflate)) return new Inflate(opts);
23648 Zlib.call(this, opts, binding.INFLATE);
23649}
23650
23651// gzip - bigger header, same deflate compression
23652function Gzip(opts) {
23653 if (!(this instanceof Gzip)) return new Gzip(opts);
23654 Zlib.call(this, opts, binding.GZIP);
23655}
23656
23657function Gunzip(opts) {
23658 if (!(this instanceof Gunzip)) return new Gunzip(opts);
23659 Zlib.call(this, opts, binding.GUNZIP);
23660}
23661
23662// raw - no header
23663function DeflateRaw(opts) {
23664 if (!(this instanceof DeflateRaw)) return new DeflateRaw(opts);
23665 Zlib.call(this, opts, binding.DEFLATERAW);
23666}
23667
23668function InflateRaw(opts) {
23669 if (!(this instanceof InflateRaw)) return new InflateRaw(opts);
23670 Zlib.call(this, opts, binding.INFLATERAW);
23671}
23672
23673// auto-detect header.
23674function Unzip(opts) {
23675 if (!(this instanceof Unzip)) return new Unzip(opts);
23676 Zlib.call(this, opts, binding.UNZIP);
23677}
23678
23679function isValidFlushFlag(flag) {
23680 return flag === binding.Z_NO_FLUSH || flag === binding.Z_PARTIAL_FLUSH || flag === binding.Z_SYNC_FLUSH || flag === binding.Z_FULL_FLUSH || flag === binding.Z_FINISH || flag === binding.Z_BLOCK;
23681}
23682
23683// the Zlib class they all inherit from
23684// This thing manages the queue of requests, and returns
23685// true or false if there is anything in the queue when
23686// you call the .write() method.
23687
23688function Zlib(opts, mode) {
23689 var _this = this;
23690
23691 this._opts = opts = opts || {};
23692 this._chunkSize = opts.chunkSize || exports.Z_DEFAULT_CHUNK;
23693
23694 Transform.call(this, opts);
23695
23696 if (opts.flush && !isValidFlushFlag(opts.flush)) {
23697 throw new Error('Invalid flush flag: ' + opts.flush);
23698 }
23699 if (opts.finishFlush && !isValidFlushFlag(opts.finishFlush)) {
23700 throw new Error('Invalid flush flag: ' + opts.finishFlush);
23701 }
23702
23703 this._flushFlag = opts.flush || binding.Z_NO_FLUSH;
23704 this._finishFlushFlag = typeof opts.finishFlush !== 'undefined' ? opts.finishFlush : binding.Z_FINISH;
23705
23706 if (opts.chunkSize) {
23707 if (opts.chunkSize < exports.Z_MIN_CHUNK || opts.chunkSize > exports.Z_MAX_CHUNK) {
23708 throw new Error('Invalid chunk size: ' + opts.chunkSize);
23709 }
23710 }
23711
23712 if (opts.windowBits) {
23713 if (opts.windowBits < exports.Z_MIN_WINDOWBITS || opts.windowBits > exports.Z_MAX_WINDOWBITS) {
23714 throw new Error('Invalid windowBits: ' + opts.windowBits);
23715 }
23716 }
23717
23718 if (opts.level) {
23719 if (opts.level < exports.Z_MIN_LEVEL || opts.level > exports.Z_MAX_LEVEL) {
23720 throw new Error('Invalid compression level: ' + opts.level);
23721 }
23722 }
23723
23724 if (opts.memLevel) {
23725 if (opts.memLevel < exports.Z_MIN_MEMLEVEL || opts.memLevel > exports.Z_MAX_MEMLEVEL) {
23726 throw new Error('Invalid memLevel: ' + opts.memLevel);
23727 }
23728 }
23729
23730 if (opts.strategy) {
23731 if (opts.strategy != exports.Z_FILTERED && opts.strategy != exports.Z_HUFFMAN_ONLY && opts.strategy != exports.Z_RLE && opts.strategy != exports.Z_FIXED && opts.strategy != exports.Z_DEFAULT_STRATEGY) {
23732 throw new Error('Invalid strategy: ' + opts.strategy);
23733 }
23734 }
23735
23736 if (opts.dictionary) {
23737 if (!Buffer.isBuffer(opts.dictionary)) {
23738 throw new Error('Invalid dictionary: it should be a Buffer instance');
23739 }
23740 }
23741
23742 this._handle = new binding.Zlib(mode);
23743
23744 var self = this;
23745 this._hadError = false;
23746 this._handle.onerror = function (message, errno) {
23747 // there is no way to cleanly recover.
23748 // continuing only obscures problems.
23749 _close(self);
23750 self._hadError = true;
23751
23752 var error = new Error(message);
23753 error.errno = errno;
23754 error.code = exports.codes[errno];
23755 self.emit('error', error);
23756 };
23757
23758 var level = exports.Z_DEFAULT_COMPRESSION;
23759 if (typeof opts.level === 'number') level = opts.level;
23760
23761 var strategy = exports.Z_DEFAULT_STRATEGY;
23762 if (typeof opts.strategy === 'number') strategy = opts.strategy;
23763
23764 this._handle.init(opts.windowBits || exports.Z_DEFAULT_WINDOWBITS, level, opts.memLevel || exports.Z_DEFAULT_MEMLEVEL, strategy, opts.dictionary);
23765
23766 this._buffer = Buffer.allocUnsafe(this._chunkSize);
23767 this._offset = 0;
23768 this._level = level;
23769 this._strategy = strategy;
23770
23771 this.once('end', this.close);
23772
23773 Object.defineProperty(this, '_closed', {
23774 get: function () {
23775 return !_this._handle;
23776 },
23777 configurable: true,
23778 enumerable: true
23779 });
23780}
23781
23782util.inherits(Zlib, Transform);
23783
23784Zlib.prototype.params = function (level, strategy, callback) {
23785 if (level < exports.Z_MIN_LEVEL || level > exports.Z_MAX_LEVEL) {
23786 throw new RangeError('Invalid compression level: ' + level);
23787 }
23788 if (strategy != exports.Z_FILTERED && strategy != exports.Z_HUFFMAN_ONLY && strategy != exports.Z_RLE && strategy != exports.Z_FIXED && strategy != exports.Z_DEFAULT_STRATEGY) {
23789 throw new TypeError('Invalid strategy: ' + strategy);
23790 }
23791
23792 if (this._level !== level || this._strategy !== strategy) {
23793 var self = this;
23794 this.flush(binding.Z_SYNC_FLUSH, function () {
23795 assert(self._handle, 'zlib binding closed');
23796 self._handle.params(level, strategy);
23797 if (!self._hadError) {
23798 self._level = level;
23799 self._strategy = strategy;
23800 if (callback) callback();
23801 }
23802 });
23803 } else {
23804 process.nextTick(callback);
23805 }
23806};
23807
23808Zlib.prototype.reset = function () {
23809 assert(this._handle, 'zlib binding closed');
23810 return this._handle.reset();
23811};
23812
23813// This is the _flush function called by the transform class,
23814// internally, when the last chunk has been written.
23815Zlib.prototype._flush = function (callback) {
23816 this._transform(Buffer.alloc(0), '', callback);
23817};
23818
23819Zlib.prototype.flush = function (kind, callback) {
23820 var _this2 = this;
23821
23822 var ws = this._writableState;
23823
23824 if (typeof kind === 'function' || kind === undefined && !callback) {
23825 callback = kind;
23826 kind = binding.Z_FULL_FLUSH;
23827 }
23828
23829 if (ws.ended) {
23830 if (callback) process.nextTick(callback);
23831 } else if (ws.ending) {
23832 if (callback) this.once('end', callback);
23833 } else if (ws.needDrain) {
23834 if (callback) {
23835 this.once('drain', function () {
23836 return _this2.flush(kind, callback);
23837 });
23838 }
23839 } else {
23840 this._flushFlag = kind;
23841 this.write(Buffer.alloc(0), '', callback);
23842 }
23843};
23844
23845Zlib.prototype.close = function (callback) {
23846 _close(this, callback);
23847 process.nextTick(emitCloseNT, this);
23848};
23849
23850function _close(engine, callback) {
23851 if (callback) process.nextTick(callback);
23852
23853 // Caller may invoke .close after a zlib error (which will null _handle).
23854 if (!engine._handle) return;
23855
23856 engine._handle.close();
23857 engine._handle = null;
23858}
23859
23860function emitCloseNT(self) {
23861 self.emit('close');
23862}
23863
23864Zlib.prototype._transform = function (chunk, encoding, cb) {
23865 var flushFlag;
23866 var ws = this._writableState;
23867 var ending = ws.ending || ws.ended;
23868 var last = ending && (!chunk || ws.length === chunk.length);
23869
23870 if (chunk !== null && !Buffer.isBuffer(chunk)) return cb(new Error('invalid input'));
23871
23872 if (!this._handle) return cb(new Error('zlib binding closed'));
23873
23874 // If it's the last chunk, or a final flush, we use the Z_FINISH flush flag
23875 // (or whatever flag was provided using opts.finishFlush).
23876 // If it's explicitly flushing at some other time, then we use
23877 // Z_FULL_FLUSH. Otherwise, use Z_NO_FLUSH for maximum compression
23878 // goodness.
23879 if (last) flushFlag = this._finishFlushFlag;else {
23880 flushFlag = this._flushFlag;
23881 // once we've flushed the last of the queue, stop flushing and
23882 // go back to the normal behavior.
23883 if (chunk.length >= ws.length) {
23884 this._flushFlag = this._opts.flush || binding.Z_NO_FLUSH;
23885 }
23886 }
23887
23888 this._processChunk(chunk, flushFlag, cb);
23889};
23890
23891Zlib.prototype._processChunk = function (chunk, flushFlag, cb) {
23892 var availInBefore = chunk && chunk.length;
23893 var availOutBefore = this._chunkSize - this._offset;
23894 var inOff = 0;
23895
23896 var self = this;
23897
23898 var async = typeof cb === 'function';
23899
23900 if (!async) {
23901 var buffers = [];
23902 var nread = 0;
23903
23904 var error;
23905 this.on('error', function (er) {
23906 error = er;
23907 });
23908
23909 assert(this._handle, 'zlib binding closed');
23910 do {
23911 var res = this._handle.writeSync(flushFlag, chunk, // in
23912 inOff, // in_off
23913 availInBefore, // in_len
23914 this._buffer, // out
23915 this._offset, //out_off
23916 availOutBefore); // out_len
23917 } while (!this._hadError && callback(res[0], res[1]));
23918
23919 if (this._hadError) {
23920 throw error;
23921 }
23922
23923 if (nread >= kMaxLength) {
23924 _close(this);
23925 throw new RangeError(kRangeErrorMessage);
23926 }
23927
23928 var buf = Buffer.concat(buffers, nread);
23929 _close(this);
23930
23931 return buf;
23932 }
23933
23934 assert(this._handle, 'zlib binding closed');
23935 var req = this._handle.write(flushFlag, chunk, // in
23936 inOff, // in_off
23937 availInBefore, // in_len
23938 this._buffer, // out
23939 this._offset, //out_off
23940 availOutBefore); // out_len
23941
23942 req.buffer = chunk;
23943 req.callback = callback;
23944
23945 function callback(availInAfter, availOutAfter) {
23946 // When the callback is used in an async write, the callback's
23947 // context is the `req` object that was created. The req object
23948 // is === this._handle, and that's why it's important to null
23949 // out the values after they are done being used. `this._handle`
23950 // can stay in memory longer than the callback and buffer are needed.
23951 if (this) {
23952 this.buffer = null;
23953 this.callback = null;
23954 }
23955
23956 if (self._hadError) return;
23957
23958 var have = availOutBefore - availOutAfter;
23959 assert(have >= 0, 'have should not go down');
23960
23961 if (have > 0) {
23962 var out = self._buffer.slice(self._offset, self._offset + have);
23963 self._offset += have;
23964 // serve some output to the consumer.
23965 if (async) {
23966 self.push(out);
23967 } else {
23968 buffers.push(out);
23969 nread += out.length;
23970 }
23971 }
23972
23973 // exhausted the output buffer, or used all the input create a new one.
23974 if (availOutAfter === 0 || self._offset >= self._chunkSize) {
23975 availOutBefore = self._chunkSize;
23976 self._offset = 0;
23977 self._buffer = Buffer.allocUnsafe(self._chunkSize);
23978 }
23979
23980 if (availOutAfter === 0) {
23981 // Not actually done. Need to reprocess.
23982 // Also, update the availInBefore to the availInAfter value,
23983 // so that if we have to hit it a third (fourth, etc.) time,
23984 // it'll have the correct byte counts.
23985 inOff += availInBefore - availInAfter;
23986 availInBefore = availInAfter;
23987
23988 if (!async) return true;
23989
23990 var newReq = self._handle.write(flushFlag, chunk, inOff, availInBefore, self._buffer, self._offset, self._chunkSize);
23991 newReq.callback = callback; // this same function
23992 newReq.buffer = chunk;
23993 return;
23994 }
23995
23996 if (!async) return false;
23997
23998 // finished with the chunk.
23999 cb();
24000 }
24001};
24002
24003util.inherits(Deflate, Zlib);
24004util.inherits(Inflate, Zlib);
24005util.inherits(Gzip, Zlib);
24006util.inherits(Gunzip, Zlib);
24007util.inherits(DeflateRaw, Zlib);
24008util.inherits(InflateRaw, Zlib);
24009util.inherits(Unzip, Zlib);
24010}).call(this,require('_process'))
24011},{"./binding":110,"_process":265,"assert":68,"buffer":114,"stream":361,"util":397}],112:[function(require,module,exports){
24012arguments[4][82][0].apply(exports,arguments)
24013},{"dup":82}],113:[function(require,module,exports){
24014(function (Buffer){
24015module.exports = function xor (a, b) {
24016 var length = Math.min(a.length, b.length)
24017 var buffer = new Buffer(length)
24018
24019 for (var i = 0; i < length; ++i) {
24020 buffer[i] = a[i] ^ b[i]
24021 }
24022
24023 return buffer
24024}
24025
24026}).call(this,require("buffer").Buffer)
24027},{"buffer":114}],114:[function(require,module,exports){
24028(function (Buffer){
24029/*!
24030 * The buffer module from node.js, for the browser.
24031 *
24032 * @author Feross Aboukhadijeh <https://feross.org>
24033 * @license MIT
24034 */
24035/* eslint-disable no-proto */
24036
24037'use strict'
24038
24039var base64 = require('base64-js')
24040var ieee754 = require('ieee754')
24041
24042exports.Buffer = Buffer
24043exports.SlowBuffer = SlowBuffer
24044exports.INSPECT_MAX_BYTES = 50
24045
24046var K_MAX_LENGTH = 0x7fffffff
24047exports.kMaxLength = K_MAX_LENGTH
24048
24049/**
24050 * If `Buffer.TYPED_ARRAY_SUPPORT`:
24051 * === true Use Uint8Array implementation (fastest)
24052 * === false Print warning and recommend using `buffer` v4.x which has an Object
24053 * implementation (most compatible, even IE6)
24054 *
24055 * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
24056 * Opera 11.6+, iOS 4.2+.
24057 *
24058 * We report that the browser does not support typed arrays if the are not subclassable
24059 * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array`
24060 * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support
24061 * for __proto__ and has a buggy typed array implementation.
24062 */
24063Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport()
24064
24065if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' &&
24066 typeof console.error === 'function') {
24067 console.error(
24068 'This browser lacks typed array (Uint8Array) support which is required by ' +
24069 '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.'
24070 )
24071}
24072
24073function typedArraySupport () {
24074 // Can typed array instances can be augmented?
24075 try {
24076 var arr = new Uint8Array(1)
24077 arr.__proto__ = { __proto__: Uint8Array.prototype, foo: function () { return 42 } }
24078 return arr.foo() === 42
24079 } catch (e) {
24080 return false
24081 }
24082}
24083
24084Object.defineProperty(Buffer.prototype, 'parent', {
24085 enumerable: true,
24086 get: function () {
24087 if (!Buffer.isBuffer(this)) return undefined
24088 return this.buffer
24089 }
24090})
24091
24092Object.defineProperty(Buffer.prototype, 'offset', {
24093 enumerable: true,
24094 get: function () {
24095 if (!Buffer.isBuffer(this)) return undefined
24096 return this.byteOffset
24097 }
24098})
24099
24100function createBuffer (length) {
24101 if (length > K_MAX_LENGTH) {
24102 throw new RangeError('The value "' + length + '" is invalid for option "size"')
24103 }
24104 // Return an augmented `Uint8Array` instance
24105 var buf = new Uint8Array(length)
24106 buf.__proto__ = Buffer.prototype
24107 return buf
24108}
24109
24110/**
24111 * The Buffer constructor returns instances of `Uint8Array` that have their
24112 * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
24113 * `Uint8Array`, so the returned instances will have all the node `Buffer` methods
24114 * and the `Uint8Array` methods. Square bracket notation works as expected -- it
24115 * returns a single octet.
24116 *
24117 * The `Uint8Array` prototype remains unmodified.
24118 */
24119
24120function Buffer (arg, encodingOrOffset, length) {
24121 // Common case.
24122 if (typeof arg === 'number') {
24123 if (typeof encodingOrOffset === 'string') {
24124 throw new TypeError(
24125 'The "string" argument must be of type string. Received type number'
24126 )
24127 }
24128 return allocUnsafe(arg)
24129 }
24130 return from(arg, encodingOrOffset, length)
24131}
24132
24133// Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97
24134if (typeof Symbol !== 'undefined' && Symbol.species != null &&
24135 Buffer[Symbol.species] === Buffer) {
24136 Object.defineProperty(Buffer, Symbol.species, {
24137 value: null,
24138 configurable: true,
24139 enumerable: false,
24140 writable: false
24141 })
24142}
24143
24144Buffer.poolSize = 8192 // not used by this implementation
24145
24146function from (value, encodingOrOffset, length) {
24147 if (typeof value === 'string') {
24148 return fromString(value, encodingOrOffset)
24149 }
24150
24151 if (ArrayBuffer.isView(value)) {
24152 return fromArrayLike(value)
24153 }
24154
24155 if (value == null) {
24156 throw TypeError(
24157 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +
24158 'or Array-like Object. Received type ' + (typeof value)
24159 )
24160 }
24161
24162 if (isInstance(value, ArrayBuffer) ||
24163 (value && isInstance(value.buffer, ArrayBuffer))) {
24164 return fromArrayBuffer(value, encodingOrOffset, length)
24165 }
24166
24167 if (typeof value === 'number') {
24168 throw new TypeError(
24169 'The "value" argument must not be of type number. Received type number'
24170 )
24171 }
24172
24173 var valueOf = value.valueOf && value.valueOf()
24174 if (valueOf != null && valueOf !== value) {
24175 return Buffer.from(valueOf, encodingOrOffset, length)
24176 }
24177
24178 var b = fromObject(value)
24179 if (b) return b
24180
24181 if (typeof Symbol !== 'undefined' && Symbol.toPrimitive != null &&
24182 typeof value[Symbol.toPrimitive] === 'function') {
24183 return Buffer.from(
24184 value[Symbol.toPrimitive]('string'), encodingOrOffset, length
24185 )
24186 }
24187
24188 throw new TypeError(
24189 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +
24190 'or Array-like Object. Received type ' + (typeof value)
24191 )
24192}
24193
24194/**
24195 * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
24196 * if value is a number.
24197 * Buffer.from(str[, encoding])
24198 * Buffer.from(array)
24199 * Buffer.from(buffer)
24200 * Buffer.from(arrayBuffer[, byteOffset[, length]])
24201 **/
24202Buffer.from = function (value, encodingOrOffset, length) {
24203 return from(value, encodingOrOffset, length)
24204}
24205
24206// Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug:
24207// https://github.com/feross/buffer/pull/148
24208Buffer.prototype.__proto__ = Uint8Array.prototype
24209Buffer.__proto__ = Uint8Array
24210
24211function assertSize (size) {
24212 if (typeof size !== 'number') {
24213 throw new TypeError('"size" argument must be of type number')
24214 } else if (size < 0) {
24215 throw new RangeError('The value "' + size + '" is invalid for option "size"')
24216 }
24217}
24218
24219function alloc (size, fill, encoding) {
24220 assertSize(size)
24221 if (size <= 0) {
24222 return createBuffer(size)
24223 }
24224 if (fill !== undefined) {
24225 // Only pay attention to encoding if it's a string. This
24226 // prevents accidentally sending in a number that would
24227 // be interpretted as a start offset.
24228 return typeof encoding === 'string'
24229 ? createBuffer(size).fill(fill, encoding)
24230 : createBuffer(size).fill(fill)
24231 }
24232 return createBuffer(size)
24233}
24234
24235/**
24236 * Creates a new filled Buffer instance.
24237 * alloc(size[, fill[, encoding]])
24238 **/
24239Buffer.alloc = function (size, fill, encoding) {
24240 return alloc(size, fill, encoding)
24241}
24242
24243function allocUnsafe (size) {
24244 assertSize(size)
24245 return createBuffer(size < 0 ? 0 : checked(size) | 0)
24246}
24247
24248/**
24249 * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
24250 * */
24251Buffer.allocUnsafe = function (size) {
24252 return allocUnsafe(size)
24253}
24254/**
24255 * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
24256 */
24257Buffer.allocUnsafeSlow = function (size) {
24258 return allocUnsafe(size)
24259}
24260
24261function fromString (string, encoding) {
24262 if (typeof encoding !== 'string' || encoding === '') {
24263 encoding = 'utf8'
24264 }
24265
24266 if (!Buffer.isEncoding(encoding)) {
24267 throw new TypeError('Unknown encoding: ' + encoding)
24268 }
24269
24270 var length = byteLength(string, encoding) | 0
24271 var buf = createBuffer(length)
24272
24273 var actual = buf.write(string, encoding)
24274
24275 if (actual !== length) {
24276 // Writing a hex string, for example, that contains invalid characters will
24277 // cause everything after the first invalid character to be ignored. (e.g.
24278 // 'abxxcd' will be treated as 'ab')
24279 buf = buf.slice(0, actual)
24280 }
24281
24282 return buf
24283}
24284
24285function fromArrayLike (array) {
24286 var length = array.length < 0 ? 0 : checked(array.length) | 0
24287 var buf = createBuffer(length)
24288 for (var i = 0; i < length; i += 1) {
24289 buf[i] = array[i] & 255
24290 }
24291 return buf
24292}
24293
24294function fromArrayBuffer (array, byteOffset, length) {
24295 if (byteOffset < 0 || array.byteLength < byteOffset) {
24296 throw new RangeError('"offset" is outside of buffer bounds')
24297 }
24298
24299 if (array.byteLength < byteOffset + (length || 0)) {
24300 throw new RangeError('"length" is outside of buffer bounds')
24301 }
24302
24303 var buf
24304 if (byteOffset === undefined && length === undefined) {
24305 buf = new Uint8Array(array)
24306 } else if (length === undefined) {
24307 buf = new Uint8Array(array, byteOffset)
24308 } else {
24309 buf = new Uint8Array(array, byteOffset, length)
24310 }
24311
24312 // Return an augmented `Uint8Array` instance
24313 buf.__proto__ = Buffer.prototype
24314 return buf
24315}
24316
24317function fromObject (obj) {
24318 if (Buffer.isBuffer(obj)) {
24319 var len = checked(obj.length) | 0
24320 var buf = createBuffer(len)
24321
24322 if (buf.length === 0) {
24323 return buf
24324 }
24325
24326 obj.copy(buf, 0, 0, len)
24327 return buf
24328 }
24329
24330 if (obj.length !== undefined) {
24331 if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) {
24332 return createBuffer(0)
24333 }
24334 return fromArrayLike(obj)
24335 }
24336
24337 if (obj.type === 'Buffer' && Array.isArray(obj.data)) {
24338 return fromArrayLike(obj.data)
24339 }
24340}
24341
24342function checked (length) {
24343 // Note: cannot use `length < K_MAX_LENGTH` here because that fails when
24344 // length is NaN (which is otherwise coerced to zero.)
24345 if (length >= K_MAX_LENGTH) {
24346 throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
24347 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes')
24348 }
24349 return length | 0
24350}
24351
24352function SlowBuffer (length) {
24353 if (+length != length) { // eslint-disable-line eqeqeq
24354 length = 0
24355 }
24356 return Buffer.alloc(+length)
24357}
24358
24359Buffer.isBuffer = function isBuffer (b) {
24360 return b != null && b._isBuffer === true &&
24361 b !== Buffer.prototype // so Buffer.isBuffer(Buffer.prototype) will be false
24362}
24363
24364Buffer.compare = function compare (a, b) {
24365 if (isInstance(a, Uint8Array)) a = Buffer.from(a, a.offset, a.byteLength)
24366 if (isInstance(b, Uint8Array)) b = Buffer.from(b, b.offset, b.byteLength)
24367 if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
24368 throw new TypeError(
24369 'The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array'
24370 )
24371 }
24372
24373 if (a === b) return 0
24374
24375 var x = a.length
24376 var y = b.length
24377
24378 for (var i = 0, len = Math.min(x, y); i < len; ++i) {
24379 if (a[i] !== b[i]) {
24380 x = a[i]
24381 y = b[i]
24382 break
24383 }
24384 }
24385
24386 if (x < y) return -1
24387 if (y < x) return 1
24388 return 0
24389}
24390
24391Buffer.isEncoding = function isEncoding (encoding) {
24392 switch (String(encoding).toLowerCase()) {
24393 case 'hex':
24394 case 'utf8':
24395 case 'utf-8':
24396 case 'ascii':
24397 case 'latin1':
24398 case 'binary':
24399 case 'base64':
24400 case 'ucs2':
24401 case 'ucs-2':
24402 case 'utf16le':
24403 case 'utf-16le':
24404 return true
24405 default:
24406 return false
24407 }
24408}
24409
24410Buffer.concat = function concat (list, length) {
24411 if (!Array.isArray(list)) {
24412 throw new TypeError('"list" argument must be an Array of Buffers')
24413 }
24414
24415 if (list.length === 0) {
24416 return Buffer.alloc(0)
24417 }
24418
24419 var i
24420 if (length === undefined) {
24421 length = 0
24422 for (i = 0; i < list.length; ++i) {
24423 length += list[i].length
24424 }
24425 }
24426
24427 var buffer = Buffer.allocUnsafe(length)
24428 var pos = 0
24429 for (i = 0; i < list.length; ++i) {
24430 var buf = list[i]
24431 if (isInstance(buf, Uint8Array)) {
24432 buf = Buffer.from(buf)
24433 }
24434 if (!Buffer.isBuffer(buf)) {
24435 throw new TypeError('"list" argument must be an Array of Buffers')
24436 }
24437 buf.copy(buffer, pos)
24438 pos += buf.length
24439 }
24440 return buffer
24441}
24442
24443function byteLength (string, encoding) {
24444 if (Buffer.isBuffer(string)) {
24445 return string.length
24446 }
24447 if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) {
24448 return string.byteLength
24449 }
24450 if (typeof string !== 'string') {
24451 throw new TypeError(
24452 'The "string" argument must be one of type string, Buffer, or ArrayBuffer. ' +
24453 'Received type ' + typeof string
24454 )
24455 }
24456
24457 var len = string.length
24458 var mustMatch = (arguments.length > 2 && arguments[2] === true)
24459 if (!mustMatch && len === 0) return 0
24460
24461 // Use a for loop to avoid recursion
24462 var loweredCase = false
24463 for (;;) {
24464 switch (encoding) {
24465 case 'ascii':
24466 case 'latin1':
24467 case 'binary':
24468 return len
24469 case 'utf8':
24470 case 'utf-8':
24471 return utf8ToBytes(string).length
24472 case 'ucs2':
24473 case 'ucs-2':
24474 case 'utf16le':
24475 case 'utf-16le':
24476 return len * 2
24477 case 'hex':
24478 return len >>> 1
24479 case 'base64':
24480 return base64ToBytes(string).length
24481 default:
24482 if (loweredCase) {
24483 return mustMatch ? -1 : utf8ToBytes(string).length // assume utf8
24484 }
24485 encoding = ('' + encoding).toLowerCase()
24486 loweredCase = true
24487 }
24488 }
24489}
24490Buffer.byteLength = byteLength
24491
24492function slowToString (encoding, start, end) {
24493 var loweredCase = false
24494
24495 // No need to verify that "this.length <= MAX_UINT32" since it's a read-only
24496 // property of a typed array.
24497
24498 // This behaves neither like String nor Uint8Array in that we set start/end
24499 // to their upper/lower bounds if the value passed is out of range.
24500 // undefined is handled specially as per ECMA-262 6th Edition,
24501 // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
24502 if (start === undefined || start < 0) {
24503 start = 0
24504 }
24505 // Return early if start > this.length. Done here to prevent potential uint32
24506 // coercion fail below.
24507 if (start > this.length) {
24508 return ''
24509 }
24510
24511 if (end === undefined || end > this.length) {
24512 end = this.length
24513 }
24514
24515 if (end <= 0) {
24516 return ''
24517 }
24518
24519 // Force coersion to uint32. This will also coerce falsey/NaN values to 0.
24520 end >>>= 0
24521 start >>>= 0
24522
24523 if (end <= start) {
24524 return ''
24525 }
24526
24527 if (!encoding) encoding = 'utf8'
24528
24529 while (true) {
24530 switch (encoding) {
24531 case 'hex':
24532 return hexSlice(this, start, end)
24533
24534 case 'utf8':
24535 case 'utf-8':
24536 return utf8Slice(this, start, end)
24537
24538 case 'ascii':
24539 return asciiSlice(this, start, end)
24540
24541 case 'latin1':
24542 case 'binary':
24543 return latin1Slice(this, start, end)
24544
24545 case 'base64':
24546 return base64Slice(this, start, end)
24547
24548 case 'ucs2':
24549 case 'ucs-2':
24550 case 'utf16le':
24551 case 'utf-16le':
24552 return utf16leSlice(this, start, end)
24553
24554 default:
24555 if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
24556 encoding = (encoding + '').toLowerCase()
24557 loweredCase = true
24558 }
24559 }
24560}
24561
24562// This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package)
24563// to detect a Buffer instance. It's not possible to use `instanceof Buffer`
24564// reliably in a browserify context because there could be multiple different
24565// copies of the 'buffer' package in use. This method works even for Buffer
24566// instances that were created from another copy of the `buffer` package.
24567// See: https://github.com/feross/buffer/issues/154
24568Buffer.prototype._isBuffer = true
24569
24570function swap (b, n, m) {
24571 var i = b[n]
24572 b[n] = b[m]
24573 b[m] = i
24574}
24575
24576Buffer.prototype.swap16 = function swap16 () {
24577 var len = this.length
24578 if (len % 2 !== 0) {
24579 throw new RangeError('Buffer size must be a multiple of 16-bits')
24580 }
24581 for (var i = 0; i < len; i += 2) {
24582 swap(this, i, i + 1)
24583 }
24584 return this
24585}
24586
24587Buffer.prototype.swap32 = function swap32 () {
24588 var len = this.length
24589 if (len % 4 !== 0) {
24590 throw new RangeError('Buffer size must be a multiple of 32-bits')
24591 }
24592 for (var i = 0; i < len; i += 4) {
24593 swap(this, i, i + 3)
24594 swap(this, i + 1, i + 2)
24595 }
24596 return this
24597}
24598
24599Buffer.prototype.swap64 = function swap64 () {
24600 var len = this.length
24601 if (len % 8 !== 0) {
24602 throw new RangeError('Buffer size must be a multiple of 64-bits')
24603 }
24604 for (var i = 0; i < len; i += 8) {
24605 swap(this, i, i + 7)
24606 swap(this, i + 1, i + 6)
24607 swap(this, i + 2, i + 5)
24608 swap(this, i + 3, i + 4)
24609 }
24610 return this
24611}
24612
24613Buffer.prototype.toString = function toString () {
24614 var length = this.length
24615 if (length === 0) return ''
24616 if (arguments.length === 0) return utf8Slice(this, 0, length)
24617 return slowToString.apply(this, arguments)
24618}
24619
24620Buffer.prototype.toLocaleString = Buffer.prototype.toString
24621
24622Buffer.prototype.equals = function equals (b) {
24623 if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
24624 if (this === b) return true
24625 return Buffer.compare(this, b) === 0
24626}
24627
24628Buffer.prototype.inspect = function inspect () {
24629 var str = ''
24630 var max = exports.INSPECT_MAX_BYTES
24631 str = this.toString('hex', 0, max).replace(/(.{2})/g, '$1 ').trim()
24632 if (this.length > max) str += ' ... '
24633 return '<Buffer ' + str + '>'
24634}
24635
24636Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {
24637 if (isInstance(target, Uint8Array)) {
24638 target = Buffer.from(target, target.offset, target.byteLength)
24639 }
24640 if (!Buffer.isBuffer(target)) {
24641 throw new TypeError(
24642 'The "target" argument must be one of type Buffer or Uint8Array. ' +
24643 'Received type ' + (typeof target)
24644 )
24645 }
24646
24647 if (start === undefined) {
24648 start = 0
24649 }
24650 if (end === undefined) {
24651 end = target ? target.length : 0
24652 }
24653 if (thisStart === undefined) {
24654 thisStart = 0
24655 }
24656 if (thisEnd === undefined) {
24657 thisEnd = this.length
24658 }
24659
24660 if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
24661 throw new RangeError('out of range index')
24662 }
24663
24664 if (thisStart >= thisEnd && start >= end) {
24665 return 0
24666 }
24667 if (thisStart >= thisEnd) {
24668 return -1
24669 }
24670 if (start >= end) {
24671 return 1
24672 }
24673
24674 start >>>= 0
24675 end >>>= 0
24676 thisStart >>>= 0
24677 thisEnd >>>= 0
24678
24679 if (this === target) return 0
24680
24681 var x = thisEnd - thisStart
24682 var y = end - start
24683 var len = Math.min(x, y)
24684
24685 var thisCopy = this.slice(thisStart, thisEnd)
24686 var targetCopy = target.slice(start, end)
24687
24688 for (var i = 0; i < len; ++i) {
24689 if (thisCopy[i] !== targetCopy[i]) {
24690 x = thisCopy[i]
24691 y = targetCopy[i]
24692 break
24693 }
24694 }
24695
24696 if (x < y) return -1
24697 if (y < x) return 1
24698 return 0
24699}
24700
24701// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
24702// OR the last index of `val` in `buffer` at offset <= `byteOffset`.
24703//
24704// Arguments:
24705// - buffer - a Buffer to search
24706// - val - a string, Buffer, or number
24707// - byteOffset - an index into `buffer`; will be clamped to an int32
24708// - encoding - an optional encoding, relevant is val is a string
24709// - dir - true for indexOf, false for lastIndexOf
24710function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {
24711 // Empty buffer means no match
24712 if (buffer.length === 0) return -1
24713
24714 // Normalize byteOffset
24715 if (typeof byteOffset === 'string') {
24716 encoding = byteOffset
24717 byteOffset = 0
24718 } else if (byteOffset > 0x7fffffff) {
24719 byteOffset = 0x7fffffff
24720 } else if (byteOffset < -0x80000000) {
24721 byteOffset = -0x80000000
24722 }
24723 byteOffset = +byteOffset // Coerce to Number.
24724 if (numberIsNaN(byteOffset)) {
24725 // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
24726 byteOffset = dir ? 0 : (buffer.length - 1)
24727 }
24728
24729 // Normalize byteOffset: negative offsets start from the end of the buffer
24730 if (byteOffset < 0) byteOffset = buffer.length + byteOffset
24731 if (byteOffset >= buffer.length) {
24732 if (dir) return -1
24733 else byteOffset = buffer.length - 1
24734 } else if (byteOffset < 0) {
24735 if (dir) byteOffset = 0
24736 else return -1
24737 }
24738
24739 // Normalize val
24740 if (typeof val === 'string') {
24741 val = Buffer.from(val, encoding)
24742 }
24743
24744 // Finally, search either indexOf (if dir is true) or lastIndexOf
24745 if (Buffer.isBuffer(val)) {
24746 // Special case: looking for empty string/buffer always fails
24747 if (val.length === 0) {
24748 return -1
24749 }
24750 return arrayIndexOf(buffer, val, byteOffset, encoding, dir)
24751 } else if (typeof val === 'number') {
24752 val = val & 0xFF // Search for a byte value [0-255]
24753 if (typeof Uint8Array.prototype.indexOf === 'function') {
24754 if (dir) {
24755 return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)
24756 } else {
24757 return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)
24758 }
24759 }
24760 return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir)
24761 }
24762
24763 throw new TypeError('val must be string, number or Buffer')
24764}
24765
24766function arrayIndexOf (arr, val, byteOffset, encoding, dir) {
24767 var indexSize = 1
24768 var arrLength = arr.length
24769 var valLength = val.length
24770
24771 if (encoding !== undefined) {
24772 encoding = String(encoding).toLowerCase()
24773 if (encoding === 'ucs2' || encoding === 'ucs-2' ||
24774 encoding === 'utf16le' || encoding === 'utf-16le') {
24775 if (arr.length < 2 || val.length < 2) {
24776 return -1
24777 }
24778 indexSize = 2
24779 arrLength /= 2
24780 valLength /= 2
24781 byteOffset /= 2
24782 }
24783 }
24784
24785 function read (buf, i) {
24786 if (indexSize === 1) {
24787 return buf[i]
24788 } else {
24789 return buf.readUInt16BE(i * indexSize)
24790 }
24791 }
24792
24793 var i
24794 if (dir) {
24795 var foundIndex = -1
24796 for (i = byteOffset; i < arrLength; i++) {
24797 if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
24798 if (foundIndex === -1) foundIndex = i
24799 if (i - foundIndex + 1 === valLength) return foundIndex * indexSize
24800 } else {
24801 if (foundIndex !== -1) i -= i - foundIndex
24802 foundIndex = -1
24803 }
24804 }
24805 } else {
24806 if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength
24807 for (i = byteOffset; i >= 0; i--) {
24808 var found = true
24809 for (var j = 0; j < valLength; j++) {
24810 if (read(arr, i + j) !== read(val, j)) {
24811 found = false
24812 break
24813 }
24814 }
24815 if (found) return i
24816 }
24817 }
24818
24819 return -1
24820}
24821
24822Buffer.prototype.includes = function includes (val, byteOffset, encoding) {
24823 return this.indexOf(val, byteOffset, encoding) !== -1
24824}
24825
24826Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {
24827 return bidirectionalIndexOf(this, val, byteOffset, encoding, true)
24828}
24829
24830Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {
24831 return bidirectionalIndexOf(this, val, byteOffset, encoding, false)
24832}
24833
24834function hexWrite (buf, string, offset, length) {
24835 offset = Number(offset) || 0
24836 var remaining = buf.length - offset
24837 if (!length) {
24838 length = remaining
24839 } else {
24840 length = Number(length)
24841 if (length > remaining) {
24842 length = remaining
24843 }
24844 }
24845
24846 var strLen = string.length
24847
24848 if (length > strLen / 2) {
24849 length = strLen / 2
24850 }
24851 for (var i = 0; i < length; ++i) {
24852 var parsed = parseInt(string.substr(i * 2, 2), 16)
24853 if (numberIsNaN(parsed)) return i
24854 buf[offset + i] = parsed
24855 }
24856 return i
24857}
24858
24859function utf8Write (buf, string, offset, length) {
24860 return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
24861}
24862
24863function asciiWrite (buf, string, offset, length) {
24864 return blitBuffer(asciiToBytes(string), buf, offset, length)
24865}
24866
24867function latin1Write (buf, string, offset, length) {
24868 return asciiWrite(buf, string, offset, length)
24869}
24870
24871function base64Write (buf, string, offset, length) {
24872 return blitBuffer(base64ToBytes(string), buf, offset, length)
24873}
24874
24875function ucs2Write (buf, string, offset, length) {
24876 return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
24877}
24878
24879Buffer.prototype.write = function write (string, offset, length, encoding) {
24880 // Buffer#write(string)
24881 if (offset === undefined) {
24882 encoding = 'utf8'
24883 length = this.length
24884 offset = 0
24885 // Buffer#write(string, encoding)
24886 } else if (length === undefined && typeof offset === 'string') {
24887 encoding = offset
24888 length = this.length
24889 offset = 0
24890 // Buffer#write(string, offset[, length][, encoding])
24891 } else if (isFinite(offset)) {
24892 offset = offset >>> 0
24893 if (isFinite(length)) {
24894 length = length >>> 0
24895 if (encoding === undefined) encoding = 'utf8'
24896 } else {
24897 encoding = length
24898 length = undefined
24899 }
24900 } else {
24901 throw new Error(
24902 'Buffer.write(string, encoding, offset[, length]) is no longer supported'
24903 )
24904 }
24905
24906 var remaining = this.length - offset
24907 if (length === undefined || length > remaining) length = remaining
24908
24909 if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
24910 throw new RangeError('Attempt to write outside buffer bounds')
24911 }
24912
24913 if (!encoding) encoding = 'utf8'
24914
24915 var loweredCase = false
24916 for (;;) {
24917 switch (encoding) {
24918 case 'hex':
24919 return hexWrite(this, string, offset, length)
24920
24921 case 'utf8':
24922 case 'utf-8':
24923 return utf8Write(this, string, offset, length)
24924
24925 case 'ascii':
24926 return asciiWrite(this, string, offset, length)
24927
24928 case 'latin1':
24929 case 'binary':
24930 return latin1Write(this, string, offset, length)
24931
24932 case 'base64':
24933 // Warning: maxLength not taken into account in base64Write
24934 return base64Write(this, string, offset, length)
24935
24936 case 'ucs2':
24937 case 'ucs-2':
24938 case 'utf16le':
24939 case 'utf-16le':
24940 return ucs2Write(this, string, offset, length)
24941
24942 default:
24943 if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
24944 encoding = ('' + encoding).toLowerCase()
24945 loweredCase = true
24946 }
24947 }
24948}
24949
24950Buffer.prototype.toJSON = function toJSON () {
24951 return {
24952 type: 'Buffer',
24953 data: Array.prototype.slice.call(this._arr || this, 0)
24954 }
24955}
24956
24957function base64Slice (buf, start, end) {
24958 if (start === 0 && end === buf.length) {
24959 return base64.fromByteArray(buf)
24960 } else {
24961 return base64.fromByteArray(buf.slice(start, end))
24962 }
24963}
24964
24965function utf8Slice (buf, start, end) {
24966 end = Math.min(buf.length, end)
24967 var res = []
24968
24969 var i = start
24970 while (i < end) {
24971 var firstByte = buf[i]
24972 var codePoint = null
24973 var bytesPerSequence = (firstByte > 0xEF) ? 4
24974 : (firstByte > 0xDF) ? 3
24975 : (firstByte > 0xBF) ? 2
24976 : 1
24977
24978 if (i + bytesPerSequence <= end) {
24979 var secondByte, thirdByte, fourthByte, tempCodePoint
24980
24981 switch (bytesPerSequence) {
24982 case 1:
24983 if (firstByte < 0x80) {
24984 codePoint = firstByte
24985 }
24986 break
24987 case 2:
24988 secondByte = buf[i + 1]
24989 if ((secondByte & 0xC0) === 0x80) {
24990 tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)
24991 if (tempCodePoint > 0x7F) {
24992 codePoint = tempCodePoint
24993 }
24994 }
24995 break
24996 case 3:
24997 secondByte = buf[i + 1]
24998 thirdByte = buf[i + 2]
24999 if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
25000 tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)
25001 if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
25002 codePoint = tempCodePoint
25003 }
25004 }
25005 break
25006 case 4:
25007 secondByte = buf[i + 1]
25008 thirdByte = buf[i + 2]
25009 fourthByte = buf[i + 3]
25010 if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
25011 tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)
25012 if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
25013 codePoint = tempCodePoint
25014 }
25015 }
25016 }
25017 }
25018
25019 if (codePoint === null) {
25020 // we did not generate a valid codePoint so insert a
25021 // replacement char (U+FFFD) and advance only 1 byte
25022 codePoint = 0xFFFD
25023 bytesPerSequence = 1
25024 } else if (codePoint > 0xFFFF) {
25025 // encode to utf16 (surrogate pair dance)
25026 codePoint -= 0x10000
25027 res.push(codePoint >>> 10 & 0x3FF | 0xD800)
25028 codePoint = 0xDC00 | codePoint & 0x3FF
25029 }
25030
25031 res.push(codePoint)
25032 i += bytesPerSequence
25033 }
25034
25035 return decodeCodePointsArray(res)
25036}
25037
25038// Based on http://stackoverflow.com/a/22747272/680742, the browser with
25039// the lowest limit is Chrome, with 0x10000 args.
25040// We go 1 magnitude less, for safety
25041var MAX_ARGUMENTS_LENGTH = 0x1000
25042
25043function decodeCodePointsArray (codePoints) {
25044 var len = codePoints.length
25045 if (len <= MAX_ARGUMENTS_LENGTH) {
25046 return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
25047 }
25048
25049 // Decode in chunks to avoid "call stack size exceeded".
25050 var res = ''
25051 var i = 0
25052 while (i < len) {
25053 res += String.fromCharCode.apply(
25054 String,
25055 codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
25056 )
25057 }
25058 return res
25059}
25060
25061function asciiSlice (buf, start, end) {
25062 var ret = ''
25063 end = Math.min(buf.length, end)
25064
25065 for (var i = start; i < end; ++i) {
25066 ret += String.fromCharCode(buf[i] & 0x7F)
25067 }
25068 return ret
25069}
25070
25071function latin1Slice (buf, start, end) {
25072 var ret = ''
25073 end = Math.min(buf.length, end)
25074
25075 for (var i = start; i < end; ++i) {
25076 ret += String.fromCharCode(buf[i])
25077 }
25078 return ret
25079}
25080
25081function hexSlice (buf, start, end) {
25082 var len = buf.length
25083
25084 if (!start || start < 0) start = 0
25085 if (!end || end < 0 || end > len) end = len
25086
25087 var out = ''
25088 for (var i = start; i < end; ++i) {
25089 out += toHex(buf[i])
25090 }
25091 return out
25092}
25093
25094function utf16leSlice (buf, start, end) {
25095 var bytes = buf.slice(start, end)
25096 var res = ''
25097 for (var i = 0; i < bytes.length; i += 2) {
25098 res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256))
25099 }
25100 return res
25101}
25102
25103Buffer.prototype.slice = function slice (start, end) {
25104 var len = this.length
25105 start = ~~start
25106 end = end === undefined ? len : ~~end
25107
25108 if (start < 0) {
25109 start += len
25110 if (start < 0) start = 0
25111 } else if (start > len) {
25112 start = len
25113 }
25114
25115 if (end < 0) {
25116 end += len
25117 if (end < 0) end = 0
25118 } else if (end > len) {
25119 end = len
25120 }
25121
25122 if (end < start) end = start
25123
25124 var newBuf = this.subarray(start, end)
25125 // Return an augmented `Uint8Array` instance
25126 newBuf.__proto__ = Buffer.prototype
25127 return newBuf
25128}
25129
25130/*
25131 * Need to make sure that buffer isn't trying to write out of bounds.
25132 */
25133function checkOffset (offset, ext, length) {
25134 if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
25135 if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
25136}
25137
25138Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
25139 offset = offset >>> 0
25140 byteLength = byteLength >>> 0
25141 if (!noAssert) checkOffset(offset, byteLength, this.length)
25142
25143 var val = this[offset]
25144 var mul = 1
25145 var i = 0
25146 while (++i < byteLength && (mul *= 0x100)) {
25147 val += this[offset + i] * mul
25148 }
25149
25150 return val
25151}
25152
25153Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
25154 offset = offset >>> 0
25155 byteLength = byteLength >>> 0
25156 if (!noAssert) {
25157 checkOffset(offset, byteLength, this.length)
25158 }
25159
25160 var val = this[offset + --byteLength]
25161 var mul = 1
25162 while (byteLength > 0 && (mul *= 0x100)) {
25163 val += this[offset + --byteLength] * mul
25164 }
25165
25166 return val
25167}
25168
25169Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
25170 offset = offset >>> 0
25171 if (!noAssert) checkOffset(offset, 1, this.length)
25172 return this[offset]
25173}
25174
25175Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
25176 offset = offset >>> 0
25177 if (!noAssert) checkOffset(offset, 2, this.length)
25178 return this[offset] | (this[offset + 1] << 8)
25179}
25180
25181Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
25182 offset = offset >>> 0
25183 if (!noAssert) checkOffset(offset, 2, this.length)
25184 return (this[offset] << 8) | this[offset + 1]
25185}
25186
25187Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
25188 offset = offset >>> 0
25189 if (!noAssert) checkOffset(offset, 4, this.length)
25190
25191 return ((this[offset]) |
25192 (this[offset + 1] << 8) |
25193 (this[offset + 2] << 16)) +
25194 (this[offset + 3] * 0x1000000)
25195}
25196
25197Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
25198 offset = offset >>> 0
25199 if (!noAssert) checkOffset(offset, 4, this.length)
25200
25201 return (this[offset] * 0x1000000) +
25202 ((this[offset + 1] << 16) |
25203 (this[offset + 2] << 8) |
25204 this[offset + 3])
25205}
25206
25207Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
25208 offset = offset >>> 0
25209 byteLength = byteLength >>> 0
25210 if (!noAssert) checkOffset(offset, byteLength, this.length)
25211
25212 var val = this[offset]
25213 var mul = 1
25214 var i = 0
25215 while (++i < byteLength && (mul *= 0x100)) {
25216 val += this[offset + i] * mul
25217 }
25218 mul *= 0x80
25219
25220 if (val >= mul) val -= Math.pow(2, 8 * byteLength)
25221
25222 return val
25223}
25224
25225Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
25226 offset = offset >>> 0
25227 byteLength = byteLength >>> 0
25228 if (!noAssert) checkOffset(offset, byteLength, this.length)
25229
25230 var i = byteLength
25231 var mul = 1
25232 var val = this[offset + --i]
25233 while (i > 0 && (mul *= 0x100)) {
25234 val += this[offset + --i] * mul
25235 }
25236 mul *= 0x80
25237
25238 if (val >= mul) val -= Math.pow(2, 8 * byteLength)
25239
25240 return val
25241}
25242
25243Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
25244 offset = offset >>> 0
25245 if (!noAssert) checkOffset(offset, 1, this.length)
25246 if (!(this[offset] & 0x80)) return (this[offset])
25247 return ((0xff - this[offset] + 1) * -1)
25248}
25249
25250Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
25251 offset = offset >>> 0
25252 if (!noAssert) checkOffset(offset, 2, this.length)
25253 var val = this[offset] | (this[offset + 1] << 8)
25254 return (val & 0x8000) ? val | 0xFFFF0000 : val
25255}
25256
25257Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
25258 offset = offset >>> 0
25259 if (!noAssert) checkOffset(offset, 2, this.length)
25260 var val = this[offset + 1] | (this[offset] << 8)
25261 return (val & 0x8000) ? val | 0xFFFF0000 : val
25262}
25263
25264Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
25265 offset = offset >>> 0
25266 if (!noAssert) checkOffset(offset, 4, this.length)
25267
25268 return (this[offset]) |
25269 (this[offset + 1] << 8) |
25270 (this[offset + 2] << 16) |
25271 (this[offset + 3] << 24)
25272}
25273
25274Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
25275 offset = offset >>> 0
25276 if (!noAssert) checkOffset(offset, 4, this.length)
25277
25278 return (this[offset] << 24) |
25279 (this[offset + 1] << 16) |
25280 (this[offset + 2] << 8) |
25281 (this[offset + 3])
25282}
25283
25284Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
25285 offset = offset >>> 0
25286 if (!noAssert) checkOffset(offset, 4, this.length)
25287 return ieee754.read(this, offset, true, 23, 4)
25288}
25289
25290Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
25291 offset = offset >>> 0
25292 if (!noAssert) checkOffset(offset, 4, this.length)
25293 return ieee754.read(this, offset, false, 23, 4)
25294}
25295
25296Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
25297 offset = offset >>> 0
25298 if (!noAssert) checkOffset(offset, 8, this.length)
25299 return ieee754.read(this, offset, true, 52, 8)
25300}
25301
25302Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
25303 offset = offset >>> 0
25304 if (!noAssert) checkOffset(offset, 8, this.length)
25305 return ieee754.read(this, offset, false, 52, 8)
25306}
25307
25308function checkInt (buf, value, offset, ext, max, min) {
25309 if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance')
25310 if (value > max || value < min) throw new RangeError('"value" argument is out of bounds')
25311 if (offset + ext > buf.length) throw new RangeError('Index out of range')
25312}
25313
25314Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
25315 value = +value
25316 offset = offset >>> 0
25317 byteLength = byteLength >>> 0
25318 if (!noAssert) {
25319 var maxBytes = Math.pow(2, 8 * byteLength) - 1
25320 checkInt(this, value, offset, byteLength, maxBytes, 0)
25321 }
25322
25323 var mul = 1
25324 var i = 0
25325 this[offset] = value & 0xFF
25326 while (++i < byteLength && (mul *= 0x100)) {
25327 this[offset + i] = (value / mul) & 0xFF
25328 }
25329
25330 return offset + byteLength
25331}
25332
25333Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
25334 value = +value
25335 offset = offset >>> 0
25336 byteLength = byteLength >>> 0
25337 if (!noAssert) {
25338 var maxBytes = Math.pow(2, 8 * byteLength) - 1
25339 checkInt(this, value, offset, byteLength, maxBytes, 0)
25340 }
25341
25342 var i = byteLength - 1
25343 var mul = 1
25344 this[offset + i] = value & 0xFF
25345 while (--i >= 0 && (mul *= 0x100)) {
25346 this[offset + i] = (value / mul) & 0xFF
25347 }
25348
25349 return offset + byteLength
25350}
25351
25352Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
25353 value = +value
25354 offset = offset >>> 0
25355 if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)
25356 this[offset] = (value & 0xff)
25357 return offset + 1
25358}
25359
25360Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
25361 value = +value
25362 offset = offset >>> 0
25363 if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
25364 this[offset] = (value & 0xff)
25365 this[offset + 1] = (value >>> 8)
25366 return offset + 2
25367}
25368
25369Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
25370 value = +value
25371 offset = offset >>> 0
25372 if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
25373 this[offset] = (value >>> 8)
25374 this[offset + 1] = (value & 0xff)
25375 return offset + 2
25376}
25377
25378Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
25379 value = +value
25380 offset = offset >>> 0
25381 if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
25382 this[offset + 3] = (value >>> 24)
25383 this[offset + 2] = (value >>> 16)
25384 this[offset + 1] = (value >>> 8)
25385 this[offset] = (value & 0xff)
25386 return offset + 4
25387}
25388
25389Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
25390 value = +value
25391 offset = offset >>> 0
25392 if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
25393 this[offset] = (value >>> 24)
25394 this[offset + 1] = (value >>> 16)
25395 this[offset + 2] = (value >>> 8)
25396 this[offset + 3] = (value & 0xff)
25397 return offset + 4
25398}
25399
25400Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
25401 value = +value
25402 offset = offset >>> 0
25403 if (!noAssert) {
25404 var limit = Math.pow(2, (8 * byteLength) - 1)
25405
25406 checkInt(this, value, offset, byteLength, limit - 1, -limit)
25407 }
25408
25409 var i = 0
25410 var mul = 1
25411 var sub = 0
25412 this[offset] = value & 0xFF
25413 while (++i < byteLength && (mul *= 0x100)) {
25414 if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
25415 sub = 1
25416 }
25417 this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
25418 }
25419
25420 return offset + byteLength
25421}
25422
25423Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
25424 value = +value
25425 offset = offset >>> 0
25426 if (!noAssert) {
25427 var limit = Math.pow(2, (8 * byteLength) - 1)
25428
25429 checkInt(this, value, offset, byteLength, limit - 1, -limit)
25430 }
25431
25432 var i = byteLength - 1
25433 var mul = 1
25434 var sub = 0
25435 this[offset + i] = value & 0xFF
25436 while (--i >= 0 && (mul *= 0x100)) {
25437 if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
25438 sub = 1
25439 }
25440 this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
25441 }
25442
25443 return offset + byteLength
25444}
25445
25446Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
25447 value = +value
25448 offset = offset >>> 0
25449 if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)
25450 if (value < 0) value = 0xff + value + 1
25451 this[offset] = (value & 0xff)
25452 return offset + 1
25453}
25454
25455Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
25456 value = +value
25457 offset = offset >>> 0
25458 if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
25459 this[offset] = (value & 0xff)
25460 this[offset + 1] = (value >>> 8)
25461 return offset + 2
25462}
25463
25464Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
25465 value = +value
25466 offset = offset >>> 0
25467 if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
25468 this[offset] = (value >>> 8)
25469 this[offset + 1] = (value & 0xff)
25470 return offset + 2
25471}
25472
25473Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
25474 value = +value
25475 offset = offset >>> 0
25476 if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
25477 this[offset] = (value & 0xff)
25478 this[offset + 1] = (value >>> 8)
25479 this[offset + 2] = (value >>> 16)
25480 this[offset + 3] = (value >>> 24)
25481 return offset + 4
25482}
25483
25484Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
25485 value = +value
25486 offset = offset >>> 0
25487 if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
25488 if (value < 0) value = 0xffffffff + value + 1
25489 this[offset] = (value >>> 24)
25490 this[offset + 1] = (value >>> 16)
25491 this[offset + 2] = (value >>> 8)
25492 this[offset + 3] = (value & 0xff)
25493 return offset + 4
25494}
25495
25496function checkIEEE754 (buf, value, offset, ext, max, min) {
25497 if (offset + ext > buf.length) throw new RangeError('Index out of range')
25498 if (offset < 0) throw new RangeError('Index out of range')
25499}
25500
25501function writeFloat (buf, value, offset, littleEndian, noAssert) {
25502 value = +value
25503 offset = offset >>> 0
25504 if (!noAssert) {
25505 checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)
25506 }
25507 ieee754.write(buf, value, offset, littleEndian, 23, 4)
25508 return offset + 4
25509}
25510
25511Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
25512 return writeFloat(this, value, offset, true, noAssert)
25513}
25514
25515Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
25516 return writeFloat(this, value, offset, false, noAssert)
25517}
25518
25519function writeDouble (buf, value, offset, littleEndian, noAssert) {
25520 value = +value
25521 offset = offset >>> 0
25522 if (!noAssert) {
25523 checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)
25524 }
25525 ieee754.write(buf, value, offset, littleEndian, 52, 8)
25526 return offset + 8
25527}
25528
25529Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
25530 return writeDouble(this, value, offset, true, noAssert)
25531}
25532
25533Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
25534 return writeDouble(this, value, offset, false, noAssert)
25535}
25536
25537// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
25538Buffer.prototype.copy = function copy (target, targetStart, start, end) {
25539 if (!Buffer.isBuffer(target)) throw new TypeError('argument should be a Buffer')
25540 if (!start) start = 0
25541 if (!end && end !== 0) end = this.length
25542 if (targetStart >= target.length) targetStart = target.length
25543 if (!targetStart) targetStart = 0
25544 if (end > 0 && end < start) end = start
25545
25546 // Copy 0 bytes; we're done
25547 if (end === start) return 0
25548 if (target.length === 0 || this.length === 0) return 0
25549
25550 // Fatal error conditions
25551 if (targetStart < 0) {
25552 throw new RangeError('targetStart out of bounds')
25553 }
25554 if (start < 0 || start >= this.length) throw new RangeError('Index out of range')
25555 if (end < 0) throw new RangeError('sourceEnd out of bounds')
25556
25557 // Are we oob?
25558 if (end > this.length) end = this.length
25559 if (target.length - targetStart < end - start) {
25560 end = target.length - targetStart + start
25561 }
25562
25563 var len = end - start
25564
25565 if (this === target && typeof Uint8Array.prototype.copyWithin === 'function') {
25566 // Use built-in when available, missing from IE11
25567 this.copyWithin(targetStart, start, end)
25568 } else if (this === target && start < targetStart && targetStart < end) {
25569 // descending copy from end
25570 for (var i = len - 1; i >= 0; --i) {
25571 target[i + targetStart] = this[i + start]
25572 }
25573 } else {
25574 Uint8Array.prototype.set.call(
25575 target,
25576 this.subarray(start, end),
25577 targetStart
25578 )
25579 }
25580
25581 return len
25582}
25583
25584// Usage:
25585// buffer.fill(number[, offset[, end]])
25586// buffer.fill(buffer[, offset[, end]])
25587// buffer.fill(string[, offset[, end]][, encoding])
25588Buffer.prototype.fill = function fill (val, start, end, encoding) {
25589 // Handle string cases:
25590 if (typeof val === 'string') {
25591 if (typeof start === 'string') {
25592 encoding = start
25593 start = 0
25594 end = this.length
25595 } else if (typeof end === 'string') {
25596 encoding = end
25597 end = this.length
25598 }
25599 if (encoding !== undefined && typeof encoding !== 'string') {
25600 throw new TypeError('encoding must be a string')
25601 }
25602 if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
25603 throw new TypeError('Unknown encoding: ' + encoding)
25604 }
25605 if (val.length === 1) {
25606 var code = val.charCodeAt(0)
25607 if ((encoding === 'utf8' && code < 128) ||
25608 encoding === 'latin1') {
25609 // Fast path: If `val` fits into a single byte, use that numeric value.
25610 val = code
25611 }
25612 }
25613 } else if (typeof val === 'number') {
25614 val = val & 255
25615 }
25616
25617 // Invalid ranges are not set to a default, so can range check early.
25618 if (start < 0 || this.length < start || this.length < end) {
25619 throw new RangeError('Out of range index')
25620 }
25621
25622 if (end <= start) {
25623 return this
25624 }
25625
25626 start = start >>> 0
25627 end = end === undefined ? this.length : end >>> 0
25628
25629 if (!val) val = 0
25630
25631 var i
25632 if (typeof val === 'number') {
25633 for (i = start; i < end; ++i) {
25634 this[i] = val
25635 }
25636 } else {
25637 var bytes = Buffer.isBuffer(val)
25638 ? val
25639 : Buffer.from(val, encoding)
25640 var len = bytes.length
25641 if (len === 0) {
25642 throw new TypeError('The value "' + val +
25643 '" is invalid for argument "value"')
25644 }
25645 for (i = 0; i < end - start; ++i) {
25646 this[i + start] = bytes[i % len]
25647 }
25648 }
25649
25650 return this
25651}
25652
25653// HELPER FUNCTIONS
25654// ================
25655
25656var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g
25657
25658function base64clean (str) {
25659 // Node takes equal signs as end of the Base64 encoding
25660 str = str.split('=')[0]
25661 // Node strips out invalid characters like \n and \t from the string, base64-js does not
25662 str = str.trim().replace(INVALID_BASE64_RE, '')
25663 // Node converts strings with length < 2 to ''
25664 if (str.length < 2) return ''
25665 // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
25666 while (str.length % 4 !== 0) {
25667 str = str + '='
25668 }
25669 return str
25670}
25671
25672function toHex (n) {
25673 if (n < 16) return '0' + n.toString(16)
25674 return n.toString(16)
25675}
25676
25677function utf8ToBytes (string, units) {
25678 units = units || Infinity
25679 var codePoint
25680 var length = string.length
25681 var leadSurrogate = null
25682 var bytes = []
25683
25684 for (var i = 0; i < length; ++i) {
25685 codePoint = string.charCodeAt(i)
25686
25687 // is surrogate component
25688 if (codePoint > 0xD7FF && codePoint < 0xE000) {
25689 // last char was a lead
25690 if (!leadSurrogate) {
25691 // no lead yet
25692 if (codePoint > 0xDBFF) {
25693 // unexpected trail
25694 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
25695 continue
25696 } else if (i + 1 === length) {
25697 // unpaired lead
25698 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
25699 continue
25700 }
25701
25702 // valid lead
25703 leadSurrogate = codePoint
25704
25705 continue
25706 }
25707
25708 // 2 leads in a row
25709 if (codePoint < 0xDC00) {
25710 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
25711 leadSurrogate = codePoint
25712 continue
25713 }
25714
25715 // valid surrogate pair
25716 codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000
25717 } else if (leadSurrogate) {
25718 // valid bmp char, but last char was a lead
25719 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
25720 }
25721
25722 leadSurrogate = null
25723
25724 // encode utf8
25725 if (codePoint < 0x80) {
25726 if ((units -= 1) < 0) break
25727 bytes.push(codePoint)
25728 } else if (codePoint < 0x800) {
25729 if ((units -= 2) < 0) break
25730 bytes.push(
25731 codePoint >> 0x6 | 0xC0,
25732 codePoint & 0x3F | 0x80
25733 )
25734 } else if (codePoint < 0x10000) {
25735 if ((units -= 3) < 0) break
25736 bytes.push(
25737 codePoint >> 0xC | 0xE0,
25738 codePoint >> 0x6 & 0x3F | 0x80,
25739 codePoint & 0x3F | 0x80
25740 )
25741 } else if (codePoint < 0x110000) {
25742 if ((units -= 4) < 0) break
25743 bytes.push(
25744 codePoint >> 0x12 | 0xF0,
25745 codePoint >> 0xC & 0x3F | 0x80,
25746 codePoint >> 0x6 & 0x3F | 0x80,
25747 codePoint & 0x3F | 0x80
25748 )
25749 } else {
25750 throw new Error('Invalid code point')
25751 }
25752 }
25753
25754 return bytes
25755}
25756
25757function asciiToBytes (str) {
25758 var byteArray = []
25759 for (var i = 0; i < str.length; ++i) {
25760 // Node's code seems to be doing this and not & 0x7F..
25761 byteArray.push(str.charCodeAt(i) & 0xFF)
25762 }
25763 return byteArray
25764}
25765
25766function utf16leToBytes (str, units) {
25767 var c, hi, lo
25768 var byteArray = []
25769 for (var i = 0; i < str.length; ++i) {
25770 if ((units -= 2) < 0) break
25771
25772 c = str.charCodeAt(i)
25773 hi = c >> 8
25774 lo = c % 256
25775 byteArray.push(lo)
25776 byteArray.push(hi)
25777 }
25778
25779 return byteArray
25780}
25781
25782function base64ToBytes (str) {
25783 return base64.toByteArray(base64clean(str))
25784}
25785
25786function blitBuffer (src, dst, offset, length) {
25787 for (var i = 0; i < length; ++i) {
25788 if ((i + offset >= dst.length) || (i >= src.length)) break
25789 dst[i + offset] = src[i]
25790 }
25791 return i
25792}
25793
25794// ArrayBuffer or Uint8Array objects from other contexts (i.e. iframes) do not pass
25795// the `instanceof` check but they should be treated as of that type.
25796// See: https://github.com/feross/buffer/issues/166
25797function isInstance (obj, type) {
25798 return obj instanceof type ||
25799 (obj != null && obj.constructor != null && obj.constructor.name != null &&
25800 obj.constructor.name === type.name)
25801}
25802function numberIsNaN (obj) {
25803 // For IE11 support
25804 return obj !== obj // eslint-disable-line no-self-compare
25805}
25806
25807}).call(this,require("buffer").Buffer)
25808},{"base64-js":75,"buffer":114,"ieee754":209}],115:[function(require,module,exports){
25809module.exports = {
25810 "100": "Continue",
25811 "101": "Switching Protocols",
25812 "102": "Processing",
25813 "200": "OK",
25814 "201": "Created",
25815 "202": "Accepted",
25816 "203": "Non-Authoritative Information",
25817 "204": "No Content",
25818 "205": "Reset Content",
25819 "206": "Partial Content",
25820 "207": "Multi-Status",
25821 "208": "Already Reported",
25822 "226": "IM Used",
25823 "300": "Multiple Choices",
25824 "301": "Moved Permanently",
25825 "302": "Found",
25826 "303": "See Other",
25827 "304": "Not Modified",
25828 "305": "Use Proxy",
25829 "307": "Temporary Redirect",
25830 "308": "Permanent Redirect",
25831 "400": "Bad Request",
25832 "401": "Unauthorized",
25833 "402": "Payment Required",
25834 "403": "Forbidden",
25835 "404": "Not Found",
25836 "405": "Method Not Allowed",
25837 "406": "Not Acceptable",
25838 "407": "Proxy Authentication Required",
25839 "408": "Request Timeout",
25840 "409": "Conflict",
25841 "410": "Gone",
25842 "411": "Length Required",
25843 "412": "Precondition Failed",
25844 "413": "Payload Too Large",
25845 "414": "URI Too Long",
25846 "415": "Unsupported Media Type",
25847 "416": "Range Not Satisfiable",
25848 "417": "Expectation Failed",
25849 "418": "I'm a teapot",
25850 "421": "Misdirected Request",
25851 "422": "Unprocessable Entity",
25852 "423": "Locked",
25853 "424": "Failed Dependency",
25854 "425": "Unordered Collection",
25855 "426": "Upgrade Required",
25856 "428": "Precondition Required",
25857 "429": "Too Many Requests",
25858 "431": "Request Header Fields Too Large",
25859 "451": "Unavailable For Legal Reasons",
25860 "500": "Internal Server Error",
25861 "501": "Not Implemented",
25862 "502": "Bad Gateway",
25863 "503": "Service Unavailable",
25864 "504": "Gateway Timeout",
25865 "505": "HTTP Version Not Supported",
25866 "506": "Variant Also Negotiates",
25867 "507": "Insufficient Storage",
25868 "508": "Loop Detected",
25869 "509": "Bandwidth Limit Exceeded",
25870 "510": "Not Extended",
25871 "511": "Network Authentication Required"
25872}
25873
25874},{}],116:[function(require,module,exports){
25875function Caseless (dict) {
25876 this.dict = dict || {}
25877}
25878Caseless.prototype.set = function (name, value, clobber) {
25879 if (typeof name === 'object') {
25880 for (var i in name) {
25881 this.set(i, name[i], value)
25882 }
25883 } else {
25884 if (typeof clobber === 'undefined') clobber = true
25885 var has = this.has(name)
25886
25887 if (!clobber && has) this.dict[has] = this.dict[has] + ',' + value
25888 else this.dict[has || name] = value
25889 return has
25890 }
25891}
25892Caseless.prototype.has = function (name) {
25893 var keys = Object.keys(this.dict)
25894 , name = name.toLowerCase()
25895 ;
25896 for (var i=0;i<keys.length;i++) {
25897 if (keys[i].toLowerCase() === name) return keys[i]
25898 }
25899 return false
25900}
25901Caseless.prototype.get = function (name) {
25902 name = name.toLowerCase()
25903 var result, _key
25904 var headers = this.dict
25905 Object.keys(headers).forEach(function (key) {
25906 _key = key.toLowerCase()
25907 if (name === _key) result = headers[key]
25908 })
25909 return result
25910}
25911Caseless.prototype.swap = function (name) {
25912 var has = this.has(name)
25913 if (has === name) return
25914 if (!has) throw new Error('There is no header than matches "'+name+'"')
25915 this.dict[name] = this.dict[has]
25916 delete this.dict[has]
25917}
25918Caseless.prototype.del = function (name) {
25919 var has = this.has(name)
25920 return delete this.dict[has || name]
25921}
25922
25923module.exports = function (dict) {return new Caseless(dict)}
25924module.exports.httpify = function (resp, headers) {
25925 var c = new Caseless(headers)
25926 resp.setHeader = function (key, value, clobber) {
25927 if (typeof value === 'undefined') return
25928 return c.set(key, value, clobber)
25929 }
25930 resp.hasHeader = function (key) {
25931 return c.has(key)
25932 }
25933 resp.getHeader = function (key) {
25934 return c.get(key)
25935 }
25936 resp.removeHeader = function (key) {
25937 return c.del(key)
25938 }
25939 resp.headers = c.dict
25940 return c
25941}
25942
25943},{}],117:[function(require,module,exports){
25944var Buffer = require('safe-buffer').Buffer
25945var Transform = require('stream').Transform
25946var StringDecoder = require('string_decoder').StringDecoder
25947var inherits = require('inherits')
25948
25949function CipherBase (hashMode) {
25950 Transform.call(this)
25951 this.hashMode = typeof hashMode === 'string'
25952 if (this.hashMode) {
25953 this[hashMode] = this._finalOrDigest
25954 } else {
25955 this.final = this._finalOrDigest
25956 }
25957 if (this._final) {
25958 this.__final = this._final
25959 this._final = null
25960 }
25961 this._decoder = null
25962 this._encoding = null
25963}
25964inherits(CipherBase, Transform)
25965
25966CipherBase.prototype.update = function (data, inputEnc, outputEnc) {
25967 if (typeof data === 'string') {
25968 data = Buffer.from(data, inputEnc)
25969 }
25970
25971 var outData = this._update(data)
25972 if (this.hashMode) return this
25973
25974 if (outputEnc) {
25975 outData = this._toString(outData, outputEnc)
25976 }
25977
25978 return outData
25979}
25980
25981CipherBase.prototype.setAutoPadding = function () {}
25982CipherBase.prototype.getAuthTag = function () {
25983 throw new Error('trying to get auth tag in unsupported state')
25984}
25985
25986CipherBase.prototype.setAuthTag = function () {
25987 throw new Error('trying to set auth tag in unsupported state')
25988}
25989
25990CipherBase.prototype.setAAD = function () {
25991 throw new Error('trying to set aad in unsupported state')
25992}
25993
25994CipherBase.prototype._transform = function (data, _, next) {
25995 var err
25996 try {
25997 if (this.hashMode) {
25998 this._update(data)
25999 } else {
26000 this.push(this._update(data))
26001 }
26002 } catch (e) {
26003 err = e
26004 } finally {
26005 next(err)
26006 }
26007}
26008CipherBase.prototype._flush = function (done) {
26009 var err
26010 try {
26011 this.push(this.__final())
26012 } catch (e) {
26013 err = e
26014 }
26015
26016 done(err)
26017}
26018CipherBase.prototype._finalOrDigest = function (outputEnc) {
26019 var outData = this.__final() || Buffer.alloc(0)
26020 if (outputEnc) {
26021 outData = this._toString(outData, outputEnc, true)
26022 }
26023 return outData
26024}
26025
26026CipherBase.prototype._toString = function (value, enc, fin) {
26027 if (!this._decoder) {
26028 this._decoder = new StringDecoder(enc)
26029 this._encoding = enc
26030 }
26031
26032 if (this._encoding !== enc) throw new Error('can\'t switch encodings')
26033
26034 var out = this._decoder.write(value)
26035 if (fin) {
26036 out += this._decoder.end()
26037 }
26038
26039 return out
26040}
26041
26042module.exports = CipherBase
26043
26044},{"inherits":210,"safe-buffer":325,"stream":361,"string_decoder":381}],118:[function(require,module,exports){
26045(function (Buffer){
26046var util = require('util');
26047var Stream = require('stream').Stream;
26048var DelayedStream = require('delayed-stream');
26049var defer = require('./defer.js');
26050
26051module.exports = CombinedStream;
26052function CombinedStream() {
26053 this.writable = false;
26054 this.readable = true;
26055 this.dataSize = 0;
26056 this.maxDataSize = 2 * 1024 * 1024;
26057 this.pauseStreams = true;
26058
26059 this._released = false;
26060 this._streams = [];
26061 this._currentStream = null;
26062}
26063util.inherits(CombinedStream, Stream);
26064
26065CombinedStream.create = function(options) {
26066 var combinedStream = new this();
26067
26068 options = options || {};
26069 for (var option in options) {
26070 combinedStream[option] = options[option];
26071 }
26072
26073 return combinedStream;
26074};
26075
26076CombinedStream.isStreamLike = function(stream) {
26077 return (typeof stream !== 'function')
26078 && (typeof stream !== 'string')
26079 && (typeof stream !== 'boolean')
26080 && (typeof stream !== 'number')
26081 && (!Buffer.isBuffer(stream));
26082};
26083
26084CombinedStream.prototype.append = function(stream) {
26085 var isStreamLike = CombinedStream.isStreamLike(stream);
26086
26087 if (isStreamLike) {
26088 if (!(stream instanceof DelayedStream)) {
26089 var newStream = DelayedStream.create(stream, {
26090 maxDataSize: Infinity,
26091 pauseStream: this.pauseStreams,
26092 });
26093 stream.on('data', this._checkDataSize.bind(this));
26094 stream = newStream;
26095 }
26096
26097 this._handleErrors(stream);
26098
26099 if (this.pauseStreams) {
26100 stream.pause();
26101 }
26102 }
26103
26104 this._streams.push(stream);
26105 return this;
26106};
26107
26108CombinedStream.prototype.pipe = function(dest, options) {
26109 Stream.prototype.pipe.call(this, dest, options);
26110 this.resume();
26111 return dest;
26112};
26113
26114CombinedStream.prototype._getNext = function() {
26115 this._currentStream = null;
26116 var stream = this._streams.shift();
26117
26118
26119 if (typeof stream == 'undefined') {
26120 this.end();
26121 return;
26122 }
26123
26124 if (typeof stream !== 'function') {
26125 this._pipeNext(stream);
26126 return;
26127 }
26128
26129 var getStream = stream;
26130 getStream(function(stream) {
26131 var isStreamLike = CombinedStream.isStreamLike(stream);
26132 if (isStreamLike) {
26133 stream.on('data', this._checkDataSize.bind(this));
26134 this._handleErrors(stream);
26135 }
26136
26137 defer(this._pipeNext.bind(this, stream));
26138 }.bind(this));
26139};
26140
26141CombinedStream.prototype._pipeNext = function(stream) {
26142 this._currentStream = stream;
26143
26144 var isStreamLike = CombinedStream.isStreamLike(stream);
26145 if (isStreamLike) {
26146 stream.on('end', this._getNext.bind(this));
26147 stream.pipe(this, {end: false});
26148 return;
26149 }
26150
26151 var value = stream;
26152 this.write(value);
26153 this._getNext();
26154};
26155
26156CombinedStream.prototype._handleErrors = function(stream) {
26157 var self = this;
26158 stream.on('error', function(err) {
26159 self._emitError(err);
26160 });
26161};
26162
26163CombinedStream.prototype.write = function(data) {
26164 this.emit('data', data);
26165};
26166
26167CombinedStream.prototype.pause = function() {
26168 if (!this.pauseStreams) {
26169 return;
26170 }
26171
26172 if(this.pauseStreams && this._currentStream && typeof(this._currentStream.pause) == 'function') this._currentStream.pause();
26173 this.emit('pause');
26174};
26175
26176CombinedStream.prototype.resume = function() {
26177 if (!this._released) {
26178 this._released = true;
26179 this.writable = true;
26180 this._getNext();
26181 }
26182
26183 if(this.pauseStreams && this._currentStream && typeof(this._currentStream.resume) == 'function') this._currentStream.resume();
26184 this.emit('resume');
26185};
26186
26187CombinedStream.prototype.end = function() {
26188 this._reset();
26189 this.emit('end');
26190};
26191
26192CombinedStream.prototype.destroy = function() {
26193 this._reset();
26194 this.emit('close');
26195};
26196
26197CombinedStream.prototype._reset = function() {
26198 this.writable = false;
26199 this._streams = [];
26200 this._currentStream = null;
26201};
26202
26203CombinedStream.prototype._checkDataSize = function() {
26204 this._updateDataSize();
26205 if (this.dataSize <= this.maxDataSize) {
26206 return;
26207 }
26208
26209 var message =
26210 'DelayedStream#maxDataSize of ' + this.maxDataSize + ' bytes exceeded.';
26211 this._emitError(new Error(message));
26212};
26213
26214CombinedStream.prototype._updateDataSize = function() {
26215 this.dataSize = 0;
26216
26217 var self = this;
26218 this._streams.forEach(function(stream) {
26219 if (!stream.dataSize) {
26220 return;
26221 }
26222
26223 self.dataSize += stream.dataSize;
26224 });
26225
26226 if (this._currentStream && this._currentStream.dataSize) {
26227 this.dataSize += this._currentStream.dataSize;
26228 }
26229};
26230
26231CombinedStream.prototype._emitError = function(err) {
26232 this._reset();
26233 this.emit('error', err);
26234};
26235
26236}).call(this,{"isBuffer":require("../../is-buffer/index.js")})
26237},{"../../is-buffer/index.js":211,"./defer.js":119,"delayed-stream":127,"stream":361,"util":397}],119:[function(require,module,exports){
26238(function (process,setImmediate){
26239module.exports = defer;
26240
26241/**
26242 * Runs provided function on next iteration of the event loop
26243 *
26244 * @param {function} fn - function to run
26245 */
26246function defer(fn)
26247{
26248 var nextTick = typeof setImmediate == 'function'
26249 ? setImmediate
26250 : (
26251 typeof process == 'object' && typeof process.nextTick == 'function'
26252 ? process.nextTick
26253 : null
26254 );
26255
26256 if (nextTick)
26257 {
26258 nextTick(fn);
26259 }
26260 else
26261 {
26262 setTimeout(fn, 0);
26263 }
26264}
26265
26266}).call(this,require('_process'),require("timers").setImmediate)
26267},{"_process":265,"timers":382}],120:[function(require,module,exports){
26268(function (Buffer){
26269// Copyright Joyent, Inc. and other Node contributors.
26270//
26271// Permission is hereby granted, free of charge, to any person obtaining a
26272// copy of this software and associated documentation files (the
26273// "Software"), to deal in the Software without restriction, including
26274// without limitation the rights to use, copy, modify, merge, publish,
26275// distribute, sublicense, and/or sell copies of the Software, and to permit
26276// persons to whom the Software is furnished to do so, subject to the
26277// following conditions:
26278//
26279// The above copyright notice and this permission notice shall be included
26280// in all copies or substantial portions of the Software.
26281//
26282// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
26283// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
26284// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
26285// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
26286// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
26287// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
26288// USE OR OTHER DEALINGS IN THE SOFTWARE.
26289
26290// NOTE: These type checking functions intentionally don't use `instanceof`
26291// because it is fragile and can be easily faked with `Object.create()`.
26292
26293function isArray(arg) {
26294 if (Array.isArray) {
26295 return Array.isArray(arg);
26296 }
26297 return objectToString(arg) === '[object Array]';
26298}
26299exports.isArray = isArray;
26300
26301function isBoolean(arg) {
26302 return typeof arg === 'boolean';
26303}
26304exports.isBoolean = isBoolean;
26305
26306function isNull(arg) {
26307 return arg === null;
26308}
26309exports.isNull = isNull;
26310
26311function isNullOrUndefined(arg) {
26312 return arg == null;
26313}
26314exports.isNullOrUndefined = isNullOrUndefined;
26315
26316function isNumber(arg) {
26317 return typeof arg === 'number';
26318}
26319exports.isNumber = isNumber;
26320
26321function isString(arg) {
26322 return typeof arg === 'string';
26323}
26324exports.isString = isString;
26325
26326function isSymbol(arg) {
26327 return typeof arg === 'symbol';
26328}
26329exports.isSymbol = isSymbol;
26330
26331function isUndefined(arg) {
26332 return arg === void 0;
26333}
26334exports.isUndefined = isUndefined;
26335
26336function isRegExp(re) {
26337 return objectToString(re) === '[object RegExp]';
26338}
26339exports.isRegExp = isRegExp;
26340
26341function isObject(arg) {
26342 return typeof arg === 'object' && arg !== null;
26343}
26344exports.isObject = isObject;
26345
26346function isDate(d) {
26347 return objectToString(d) === '[object Date]';
26348}
26349exports.isDate = isDate;
26350
26351function isError(e) {
26352 return (objectToString(e) === '[object Error]' || e instanceof Error);
26353}
26354exports.isError = isError;
26355
26356function isFunction(arg) {
26357 return typeof arg === 'function';
26358}
26359exports.isFunction = isFunction;
26360
26361function isPrimitive(arg) {
26362 return arg === null ||
26363 typeof arg === 'boolean' ||
26364 typeof arg === 'number' ||
26365 typeof arg === 'string' ||
26366 typeof arg === 'symbol' || // ES6 symbol
26367 typeof arg === 'undefined';
26368}
26369exports.isPrimitive = isPrimitive;
26370
26371exports.isBuffer = Buffer.isBuffer;
26372
26373function objectToString(o) {
26374 return Object.prototype.toString.call(o);
26375}
26376
26377}).call(this,{"isBuffer":require("../../is-buffer/index.js")})
26378},{"../../is-buffer/index.js":211}],121:[function(require,module,exports){
26379(function (Buffer){
26380var elliptic = require('elliptic')
26381var BN = require('bn.js')
26382
26383module.exports = function createECDH (curve) {
26384 return new ECDH(curve)
26385}
26386
26387var aliases = {
26388 secp256k1: {
26389 name: 'secp256k1',
26390 byteLength: 32
26391 },
26392 secp224r1: {
26393 name: 'p224',
26394 byteLength: 28
26395 },
26396 prime256v1: {
26397 name: 'p256',
26398 byteLength: 32
26399 },
26400 prime192v1: {
26401 name: 'p192',
26402 byteLength: 24
26403 },
26404 ed25519: {
26405 name: 'ed25519',
26406 byteLength: 32
26407 },
26408 secp384r1: {
26409 name: 'p384',
26410 byteLength: 48
26411 },
26412 secp521r1: {
26413 name: 'p521',
26414 byteLength: 66
26415 }
26416}
26417
26418aliases.p224 = aliases.secp224r1
26419aliases.p256 = aliases.secp256r1 = aliases.prime256v1
26420aliases.p192 = aliases.secp192r1 = aliases.prime192v1
26421aliases.p384 = aliases.secp384r1
26422aliases.p521 = aliases.secp521r1
26423
26424function ECDH (curve) {
26425 this.curveType = aliases[curve]
26426 if (!this.curveType) {
26427 this.curveType = {
26428 name: curve
26429 }
26430 }
26431 this.curve = new elliptic.ec(this.curveType.name) // eslint-disable-line new-cap
26432 this.keys = void 0
26433}
26434
26435ECDH.prototype.generateKeys = function (enc, format) {
26436 this.keys = this.curve.genKeyPair()
26437 return this.getPublicKey(enc, format)
26438}
26439
26440ECDH.prototype.computeSecret = function (other, inenc, enc) {
26441 inenc = inenc || 'utf8'
26442 if (!Buffer.isBuffer(other)) {
26443 other = new Buffer(other, inenc)
26444 }
26445 var otherPub = this.curve.keyFromPublic(other).getPublic()
26446 var out = otherPub.mul(this.keys.getPrivate()).getX()
26447 return formatReturnValue(out, enc, this.curveType.byteLength)
26448}
26449
26450ECDH.prototype.getPublicKey = function (enc, format) {
26451 var key = this.keys.getPublic(format === 'compressed', true)
26452 if (format === 'hybrid') {
26453 if (key[key.length - 1] % 2) {
26454 key[0] = 7
26455 } else {
26456 key[0] = 6
26457 }
26458 }
26459 return formatReturnValue(key, enc)
26460}
26461
26462ECDH.prototype.getPrivateKey = function (enc) {
26463 return formatReturnValue(this.keys.getPrivate(), enc)
26464}
26465
26466ECDH.prototype.setPublicKey = function (pub, enc) {
26467 enc = enc || 'utf8'
26468 if (!Buffer.isBuffer(pub)) {
26469 pub = new Buffer(pub, enc)
26470 }
26471 this.keys._importPublic(pub)
26472 return this
26473}
26474
26475ECDH.prototype.setPrivateKey = function (priv, enc) {
26476 enc = enc || 'utf8'
26477 if (!Buffer.isBuffer(priv)) {
26478 priv = new Buffer(priv, enc)
26479 }
26480
26481 var _priv = new BN(priv)
26482 _priv = _priv.toString(16)
26483 this.keys = this.curve.genKeyPair()
26484 this.keys._importPrivate(_priv)
26485 return this
26486}
26487
26488function formatReturnValue (bn, enc, len) {
26489 if (!Array.isArray(bn)) {
26490 bn = bn.toArray()
26491 }
26492 var buf = new Buffer(bn)
26493 if (len && buf.length < len) {
26494 var zeros = new Buffer(len - buf.length)
26495 zeros.fill(0)
26496 buf = Buffer.concat([zeros, buf])
26497 }
26498 if (!enc) {
26499 return buf
26500 } else {
26501 return buf.toString(enc)
26502 }
26503}
26504
26505}).call(this,require("buffer").Buffer)
26506},{"bn.js":80,"buffer":114,"elliptic":142}],122:[function(require,module,exports){
26507'use strict'
26508var inherits = require('inherits')
26509var MD5 = require('md5.js')
26510var RIPEMD160 = require('ripemd160')
26511var sha = require('sha.js')
26512var Base = require('cipher-base')
26513
26514function Hash (hash) {
26515 Base.call(this, 'digest')
26516
26517 this._hash = hash
26518}
26519
26520inherits(Hash, Base)
26521
26522Hash.prototype._update = function (data) {
26523 this._hash.update(data)
26524}
26525
26526Hash.prototype._final = function () {
26527 return this._hash.digest()
26528}
26529
26530module.exports = function createHash (alg) {
26531 alg = alg.toLowerCase()
26532 if (alg === 'md5') return new MD5()
26533 if (alg === 'rmd160' || alg === 'ripemd160') return new RIPEMD160()
26534
26535 return new Hash(sha(alg))
26536}
26537
26538},{"cipher-base":117,"inherits":210,"md5.js":232,"ripemd160":324,"sha.js":328}],123:[function(require,module,exports){
26539var MD5 = require('md5.js')
26540
26541module.exports = function (buffer) {
26542 return new MD5().update(buffer).digest()
26543}
26544
26545},{"md5.js":232}],124:[function(require,module,exports){
26546'use strict'
26547var inherits = require('inherits')
26548var Legacy = require('./legacy')
26549var Base = require('cipher-base')
26550var Buffer = require('safe-buffer').Buffer
26551var md5 = require('create-hash/md5')
26552var RIPEMD160 = require('ripemd160')
26553
26554var sha = require('sha.js')
26555
26556var ZEROS = Buffer.alloc(128)
26557
26558function Hmac (alg, key) {
26559 Base.call(this, 'digest')
26560 if (typeof key === 'string') {
26561 key = Buffer.from(key)
26562 }
26563
26564 var blocksize = (alg === 'sha512' || alg === 'sha384') ? 128 : 64
26565
26566 this._alg = alg
26567 this._key = key
26568 if (key.length > blocksize) {
26569 var hash = alg === 'rmd160' ? new RIPEMD160() : sha(alg)
26570 key = hash.update(key).digest()
26571 } else if (key.length < blocksize) {
26572 key = Buffer.concat([key, ZEROS], blocksize)
26573 }
26574
26575 var ipad = this._ipad = Buffer.allocUnsafe(blocksize)
26576 var opad = this._opad = Buffer.allocUnsafe(blocksize)
26577
26578 for (var i = 0; i < blocksize; i++) {
26579 ipad[i] = key[i] ^ 0x36
26580 opad[i] = key[i] ^ 0x5C
26581 }
26582 this._hash = alg === 'rmd160' ? new RIPEMD160() : sha(alg)
26583 this._hash.update(ipad)
26584}
26585
26586inherits(Hmac, Base)
26587
26588Hmac.prototype._update = function (data) {
26589 this._hash.update(data)
26590}
26591
26592Hmac.prototype._final = function () {
26593 var h = this._hash.digest()
26594 var hash = this._alg === 'rmd160' ? new RIPEMD160() : sha(this._alg)
26595 return hash.update(this._opad).update(h).digest()
26596}
26597
26598module.exports = function createHmac (alg, key) {
26599 alg = alg.toLowerCase()
26600 if (alg === 'rmd160' || alg === 'ripemd160') {
26601 return new Hmac('rmd160', key)
26602 }
26603 if (alg === 'md5') {
26604 return new Legacy(md5, key)
26605 }
26606 return new Hmac(alg, key)
26607}
26608
26609},{"./legacy":125,"cipher-base":117,"create-hash/md5":123,"inherits":210,"ripemd160":324,"safe-buffer":325,"sha.js":328}],125:[function(require,module,exports){
26610'use strict'
26611var inherits = require('inherits')
26612var Buffer = require('safe-buffer').Buffer
26613
26614var Base = require('cipher-base')
26615
26616var ZEROS = Buffer.alloc(128)
26617var blocksize = 64
26618
26619function Hmac (alg, key) {
26620 Base.call(this, 'digest')
26621 if (typeof key === 'string') {
26622 key = Buffer.from(key)
26623 }
26624
26625 this._alg = alg
26626 this._key = key
26627
26628 if (key.length > blocksize) {
26629 key = alg(key)
26630 } else if (key.length < blocksize) {
26631 key = Buffer.concat([key, ZEROS], blocksize)
26632 }
26633
26634 var ipad = this._ipad = Buffer.allocUnsafe(blocksize)
26635 var opad = this._opad = Buffer.allocUnsafe(blocksize)
26636
26637 for (var i = 0; i < blocksize; i++) {
26638 ipad[i] = key[i] ^ 0x36
26639 opad[i] = key[i] ^ 0x5C
26640 }
26641
26642 this._hash = [ipad]
26643}
26644
26645inherits(Hmac, Base)
26646
26647Hmac.prototype._update = function (data) {
26648 this._hash.push(data)
26649}
26650
26651Hmac.prototype._final = function () {
26652 var h = this._alg(Buffer.concat(this._hash))
26653 return this._alg(Buffer.concat([this._opad, h]))
26654}
26655module.exports = Hmac
26656
26657},{"cipher-base":117,"inherits":210,"safe-buffer":325}],126:[function(require,module,exports){
26658'use strict'
26659
26660exports.randomBytes = exports.rng = exports.pseudoRandomBytes = exports.prng = require('randombytes')
26661exports.createHash = exports.Hash = require('create-hash')
26662exports.createHmac = exports.Hmac = require('create-hmac')
26663
26664var algos = require('browserify-sign/algos')
26665var algoKeys = Object.keys(algos)
26666var hashes = ['sha1', 'sha224', 'sha256', 'sha384', 'sha512', 'md5', 'rmd160'].concat(algoKeys)
26667exports.getHashes = function () {
26668 return hashes
26669}
26670
26671var p = require('pbkdf2')
26672exports.pbkdf2 = p.pbkdf2
26673exports.pbkdf2Sync = p.pbkdf2Sync
26674
26675var aes = require('browserify-cipher')
26676
26677exports.Cipher = aes.Cipher
26678exports.createCipher = aes.createCipher
26679exports.Cipheriv = aes.Cipheriv
26680exports.createCipheriv = aes.createCipheriv
26681exports.Decipher = aes.Decipher
26682exports.createDecipher = aes.createDecipher
26683exports.Decipheriv = aes.Decipheriv
26684exports.createDecipheriv = aes.createDecipheriv
26685exports.getCiphers = aes.getCiphers
26686exports.listCiphers = aes.listCiphers
26687
26688var dh = require('diffie-hellman')
26689
26690exports.DiffieHellmanGroup = dh.DiffieHellmanGroup
26691exports.createDiffieHellmanGroup = dh.createDiffieHellmanGroup
26692exports.getDiffieHellman = dh.getDiffieHellman
26693exports.createDiffieHellman = dh.createDiffieHellman
26694exports.DiffieHellman = dh.DiffieHellman
26695
26696var sign = require('browserify-sign')
26697
26698exports.createSign = sign.createSign
26699exports.Sign = sign.Sign
26700exports.createVerify = sign.createVerify
26701exports.Verify = sign.Verify
26702
26703exports.createECDH = require('create-ecdh')
26704
26705var publicEncrypt = require('public-encrypt')
26706
26707exports.publicEncrypt = publicEncrypt.publicEncrypt
26708exports.privateEncrypt = publicEncrypt.privateEncrypt
26709exports.publicDecrypt = publicEncrypt.publicDecrypt
26710exports.privateDecrypt = publicEncrypt.privateDecrypt
26711
26712// the least I can do is make error messages for the rest of the node.js/crypto api.
26713// ;[
26714// 'createCredentials'
26715// ].forEach(function (name) {
26716// exports[name] = function () {
26717// throw new Error([
26718// 'sorry, ' + name + ' is not implemented yet',
26719// 'we accept pull requests',
26720// 'https://github.com/crypto-browserify/crypto-browserify'
26721// ].join('\n'))
26722// }
26723// })
26724
26725var rf = require('randomfill')
26726
26727exports.randomFill = rf.randomFill
26728exports.randomFillSync = rf.randomFillSync
26729
26730exports.createCredentials = function () {
26731 throw new Error([
26732 'sorry, createCredentials is not implemented yet',
26733 'we accept pull requests',
26734 'https://github.com/crypto-browserify/crypto-browserify'
26735 ].join('\n'))
26736}
26737
26738exports.constants = {
26739 'DH_CHECK_P_NOT_SAFE_PRIME': 2,
26740 'DH_CHECK_P_NOT_PRIME': 1,
26741 'DH_UNABLE_TO_CHECK_GENERATOR': 4,
26742 'DH_NOT_SUITABLE_GENERATOR': 8,
26743 'NPN_ENABLED': 1,
26744 'ALPN_ENABLED': 1,
26745 'RSA_PKCS1_PADDING': 1,
26746 'RSA_SSLV23_PADDING': 2,
26747 'RSA_NO_PADDING': 3,
26748 'RSA_PKCS1_OAEP_PADDING': 4,
26749 'RSA_X931_PADDING': 5,
26750 'RSA_PKCS1_PSS_PADDING': 6,
26751 'POINT_CONVERSION_COMPRESSED': 2,
26752 'POINT_CONVERSION_UNCOMPRESSED': 4,
26753 'POINT_CONVERSION_HYBRID': 6
26754}
26755
26756},{"browserify-cipher":100,"browserify-sign":107,"browserify-sign/algos":104,"create-ecdh":121,"create-hash":122,"create-hmac":124,"diffie-hellman":134,"pbkdf2":258,"public-encrypt":268,"randombytes":278,"randomfill":279}],127:[function(require,module,exports){
26757var Stream = require('stream').Stream;
26758var util = require('util');
26759
26760module.exports = DelayedStream;
26761function DelayedStream() {
26762 this.source = null;
26763 this.dataSize = 0;
26764 this.maxDataSize = 1024 * 1024;
26765 this.pauseStream = true;
26766
26767 this._maxDataSizeExceeded = false;
26768 this._released = false;
26769 this._bufferedEvents = [];
26770}
26771util.inherits(DelayedStream, Stream);
26772
26773DelayedStream.create = function(source, options) {
26774 var delayedStream = new this();
26775
26776 options = options || {};
26777 for (var option in options) {
26778 delayedStream[option] = options[option];
26779 }
26780
26781 delayedStream.source = source;
26782
26783 var realEmit = source.emit;
26784 source.emit = function() {
26785 delayedStream._handleEmit(arguments);
26786 return realEmit.apply(source, arguments);
26787 };
26788
26789 source.on('error', function() {});
26790 if (delayedStream.pauseStream) {
26791 source.pause();
26792 }
26793
26794 return delayedStream;
26795};
26796
26797Object.defineProperty(DelayedStream.prototype, 'readable', {
26798 configurable: true,
26799 enumerable: true,
26800 get: function() {
26801 return this.source.readable;
26802 }
26803});
26804
26805DelayedStream.prototype.setEncoding = function() {
26806 return this.source.setEncoding.apply(this.source, arguments);
26807};
26808
26809DelayedStream.prototype.resume = function() {
26810 if (!this._released) {
26811 this.release();
26812 }
26813
26814 this.source.resume();
26815};
26816
26817DelayedStream.prototype.pause = function() {
26818 this.source.pause();
26819};
26820
26821DelayedStream.prototype.release = function() {
26822 this._released = true;
26823
26824 this._bufferedEvents.forEach(function(args) {
26825 this.emit.apply(this, args);
26826 }.bind(this));
26827 this._bufferedEvents = [];
26828};
26829
26830DelayedStream.prototype.pipe = function() {
26831 var r = Stream.prototype.pipe.apply(this, arguments);
26832 this.resume();
26833 return r;
26834};
26835
26836DelayedStream.prototype._handleEmit = function(args) {
26837 if (this._released) {
26838 this.emit.apply(this, args);
26839 return;
26840 }
26841
26842 if (args[0] === 'data') {
26843 this.dataSize += args[1].length;
26844 this._checkIfMaxDataSizeExceeded();
26845 }
26846
26847 this._bufferedEvents.push(args);
26848};
26849
26850DelayedStream.prototype._checkIfMaxDataSizeExceeded = function() {
26851 if (this._maxDataSizeExceeded) {
26852 return;
26853 }
26854
26855 if (this.dataSize <= this.maxDataSize) {
26856 return;
26857 }
26858
26859 this._maxDataSizeExceeded = true;
26860 var message =
26861 'DelayedStream#maxDataSize of ' + this.maxDataSize + ' bytes exceeded.'
26862 this.emit('error', new Error(message));
26863};
26864
26865},{"stream":361,"util":397}],128:[function(require,module,exports){
26866'use strict';
26867
26868exports.utils = require('./des/utils');
26869exports.Cipher = require('./des/cipher');
26870exports.DES = require('./des/des');
26871exports.CBC = require('./des/cbc');
26872exports.EDE = require('./des/ede');
26873
26874},{"./des/cbc":129,"./des/cipher":130,"./des/des":131,"./des/ede":132,"./des/utils":133}],129:[function(require,module,exports){
26875'use strict';
26876
26877var assert = require('minimalistic-assert');
26878var inherits = require('inherits');
26879
26880var proto = {};
26881
26882function CBCState(iv) {
26883 assert.equal(iv.length, 8, 'Invalid IV length');
26884
26885 this.iv = new Array(8);
26886 for (var i = 0; i < this.iv.length; i++)
26887 this.iv[i] = iv[i];
26888}
26889
26890function instantiate(Base) {
26891 function CBC(options) {
26892 Base.call(this, options);
26893 this._cbcInit();
26894 }
26895 inherits(CBC, Base);
26896
26897 var keys = Object.keys(proto);
26898 for (var i = 0; i < keys.length; i++) {
26899 var key = keys[i];
26900 CBC.prototype[key] = proto[key];
26901 }
26902
26903 CBC.create = function create(options) {
26904 return new CBC(options);
26905 };
26906
26907 return CBC;
26908}
26909
26910exports.instantiate = instantiate;
26911
26912proto._cbcInit = function _cbcInit() {
26913 var state = new CBCState(this.options.iv);
26914 this._cbcState = state;
26915};
26916
26917proto._update = function _update(inp, inOff, out, outOff) {
26918 var state = this._cbcState;
26919 var superProto = this.constructor.super_.prototype;
26920
26921 var iv = state.iv;
26922 if (this.type === 'encrypt') {
26923 for (var i = 0; i < this.blockSize; i++)
26924 iv[i] ^= inp[inOff + i];
26925
26926 superProto._update.call(this, iv, 0, out, outOff);
26927
26928 for (var i = 0; i < this.blockSize; i++)
26929 iv[i] = out[outOff + i];
26930 } else {
26931 superProto._update.call(this, inp, inOff, out, outOff);
26932
26933 for (var i = 0; i < this.blockSize; i++)
26934 out[outOff + i] ^= iv[i];
26935
26936 for (var i = 0; i < this.blockSize; i++)
26937 iv[i] = inp[inOff + i];
26938 }
26939};
26940
26941},{"inherits":210,"minimalistic-assert":237}],130:[function(require,module,exports){
26942'use strict';
26943
26944var assert = require('minimalistic-assert');
26945
26946function Cipher(options) {
26947 this.options = options;
26948
26949 this.type = this.options.type;
26950 this.blockSize = 8;
26951 this._init();
26952
26953 this.buffer = new Array(this.blockSize);
26954 this.bufferOff = 0;
26955}
26956module.exports = Cipher;
26957
26958Cipher.prototype._init = function _init() {
26959 // Might be overrided
26960};
26961
26962Cipher.prototype.update = function update(data) {
26963 if (data.length === 0)
26964 return [];
26965
26966 if (this.type === 'decrypt')
26967 return this._updateDecrypt(data);
26968 else
26969 return this._updateEncrypt(data);
26970};
26971
26972Cipher.prototype._buffer = function _buffer(data, off) {
26973 // Append data to buffer
26974 var min = Math.min(this.buffer.length - this.bufferOff, data.length - off);
26975 for (var i = 0; i < min; i++)
26976 this.buffer[this.bufferOff + i] = data[off + i];
26977 this.bufferOff += min;
26978
26979 // Shift next
26980 return min;
26981};
26982
26983Cipher.prototype._flushBuffer = function _flushBuffer(out, off) {
26984 this._update(this.buffer, 0, out, off);
26985 this.bufferOff = 0;
26986 return this.blockSize;
26987};
26988
26989Cipher.prototype._updateEncrypt = function _updateEncrypt(data) {
26990 var inputOff = 0;
26991 var outputOff = 0;
26992
26993 var count = ((this.bufferOff + data.length) / this.blockSize) | 0;
26994 var out = new Array(count * this.blockSize);
26995
26996 if (this.bufferOff !== 0) {
26997 inputOff += this._buffer(data, inputOff);
26998
26999 if (this.bufferOff === this.buffer.length)
27000 outputOff += this._flushBuffer(out, outputOff);
27001 }
27002
27003 // Write blocks
27004 var max = data.length - ((data.length - inputOff) % this.blockSize);
27005 for (; inputOff < max; inputOff += this.blockSize) {
27006 this._update(data, inputOff, out, outputOff);
27007 outputOff += this.blockSize;
27008 }
27009
27010 // Queue rest
27011 for (; inputOff < data.length; inputOff++, this.bufferOff++)
27012 this.buffer[this.bufferOff] = data[inputOff];
27013
27014 return out;
27015};
27016
27017Cipher.prototype._updateDecrypt = function _updateDecrypt(data) {
27018 var inputOff = 0;
27019 var outputOff = 0;
27020
27021 var count = Math.ceil((this.bufferOff + data.length) / this.blockSize) - 1;
27022 var out = new Array(count * this.blockSize);
27023
27024 // TODO(indutny): optimize it, this is far from optimal
27025 for (; count > 0; count--) {
27026 inputOff += this._buffer(data, inputOff);
27027 outputOff += this._flushBuffer(out, outputOff);
27028 }
27029
27030 // Buffer rest of the input
27031 inputOff += this._buffer(data, inputOff);
27032
27033 return out;
27034};
27035
27036Cipher.prototype.final = function final(buffer) {
27037 var first;
27038 if (buffer)
27039 first = this.update(buffer);
27040
27041 var last;
27042 if (this.type === 'encrypt')
27043 last = this._finalEncrypt();
27044 else
27045 last = this._finalDecrypt();
27046
27047 if (first)
27048 return first.concat(last);
27049 else
27050 return last;
27051};
27052
27053Cipher.prototype._pad = function _pad(buffer, off) {
27054 if (off === 0)
27055 return false;
27056
27057 while (off < buffer.length)
27058 buffer[off++] = 0;
27059
27060 return true;
27061};
27062
27063Cipher.prototype._finalEncrypt = function _finalEncrypt() {
27064 if (!this._pad(this.buffer, this.bufferOff))
27065 return [];
27066
27067 var out = new Array(this.blockSize);
27068 this._update(this.buffer, 0, out, 0);
27069 return out;
27070};
27071
27072Cipher.prototype._unpad = function _unpad(buffer) {
27073 return buffer;
27074};
27075
27076Cipher.prototype._finalDecrypt = function _finalDecrypt() {
27077 assert.equal(this.bufferOff, this.blockSize, 'Not enough data to decrypt');
27078 var out = new Array(this.blockSize);
27079 this._flushBuffer(out, 0);
27080
27081 return this._unpad(out);
27082};
27083
27084},{"minimalistic-assert":237}],131:[function(require,module,exports){
27085'use strict';
27086
27087var assert = require('minimalistic-assert');
27088var inherits = require('inherits');
27089
27090var des = require('../des');
27091var utils = des.utils;
27092var Cipher = des.Cipher;
27093
27094function DESState() {
27095 this.tmp = new Array(2);
27096 this.keys = null;
27097}
27098
27099function DES(options) {
27100 Cipher.call(this, options);
27101
27102 var state = new DESState();
27103 this._desState = state;
27104
27105 this.deriveKeys(state, options.key);
27106}
27107inherits(DES, Cipher);
27108module.exports = DES;
27109
27110DES.create = function create(options) {
27111 return new DES(options);
27112};
27113
27114var shiftTable = [
27115 1, 1, 2, 2, 2, 2, 2, 2,
27116 1, 2, 2, 2, 2, 2, 2, 1
27117];
27118
27119DES.prototype.deriveKeys = function deriveKeys(state, key) {
27120 state.keys = new Array(16 * 2);
27121
27122 assert.equal(key.length, this.blockSize, 'Invalid key length');
27123
27124 var kL = utils.readUInt32BE(key, 0);
27125 var kR = utils.readUInt32BE(key, 4);
27126
27127 utils.pc1(kL, kR, state.tmp, 0);
27128 kL = state.tmp[0];
27129 kR = state.tmp[1];
27130 for (var i = 0; i < state.keys.length; i += 2) {
27131 var shift = shiftTable[i >>> 1];
27132 kL = utils.r28shl(kL, shift);
27133 kR = utils.r28shl(kR, shift);
27134 utils.pc2(kL, kR, state.keys, i);
27135 }
27136};
27137
27138DES.prototype._update = function _update(inp, inOff, out, outOff) {
27139 var state = this._desState;
27140
27141 var l = utils.readUInt32BE(inp, inOff);
27142 var r = utils.readUInt32BE(inp, inOff + 4);
27143
27144 // Initial Permutation
27145 utils.ip(l, r, state.tmp, 0);
27146 l = state.tmp[0];
27147 r = state.tmp[1];
27148
27149 if (this.type === 'encrypt')
27150 this._encrypt(state, l, r, state.tmp, 0);
27151 else
27152 this._decrypt(state, l, r, state.tmp, 0);
27153
27154 l = state.tmp[0];
27155 r = state.tmp[1];
27156
27157 utils.writeUInt32BE(out, l, outOff);
27158 utils.writeUInt32BE(out, r, outOff + 4);
27159};
27160
27161DES.prototype._pad = function _pad(buffer, off) {
27162 var value = buffer.length - off;
27163 for (var i = off; i < buffer.length; i++)
27164 buffer[i] = value;
27165
27166 return true;
27167};
27168
27169DES.prototype._unpad = function _unpad(buffer) {
27170 var pad = buffer[buffer.length - 1];
27171 for (var i = buffer.length - pad; i < buffer.length; i++)
27172 assert.equal(buffer[i], pad);
27173
27174 return buffer.slice(0, buffer.length - pad);
27175};
27176
27177DES.prototype._encrypt = function _encrypt(state, lStart, rStart, out, off) {
27178 var l = lStart;
27179 var r = rStart;
27180
27181 // Apply f() x16 times
27182 for (var i = 0; i < state.keys.length; i += 2) {
27183 var keyL = state.keys[i];
27184 var keyR = state.keys[i + 1];
27185
27186 // f(r, k)
27187 utils.expand(r, state.tmp, 0);
27188
27189 keyL ^= state.tmp[0];
27190 keyR ^= state.tmp[1];
27191 var s = utils.substitute(keyL, keyR);
27192 var f = utils.permute(s);
27193
27194 var t = r;
27195 r = (l ^ f) >>> 0;
27196 l = t;
27197 }
27198
27199 // Reverse Initial Permutation
27200 utils.rip(r, l, out, off);
27201};
27202
27203DES.prototype._decrypt = function _decrypt(state, lStart, rStart, out, off) {
27204 var l = rStart;
27205 var r = lStart;
27206
27207 // Apply f() x16 times
27208 for (var i = state.keys.length - 2; i >= 0; i -= 2) {
27209 var keyL = state.keys[i];
27210 var keyR = state.keys[i + 1];
27211
27212 // f(r, k)
27213 utils.expand(l, state.tmp, 0);
27214
27215 keyL ^= state.tmp[0];
27216 keyR ^= state.tmp[1];
27217 var s = utils.substitute(keyL, keyR);
27218 var f = utils.permute(s);
27219
27220 var t = l;
27221 l = (r ^ f) >>> 0;
27222 r = t;
27223 }
27224
27225 // Reverse Initial Permutation
27226 utils.rip(l, r, out, off);
27227};
27228
27229},{"../des":128,"inherits":210,"minimalistic-assert":237}],132:[function(require,module,exports){
27230'use strict';
27231
27232var assert = require('minimalistic-assert');
27233var inherits = require('inherits');
27234
27235var des = require('../des');
27236var Cipher = des.Cipher;
27237var DES = des.DES;
27238
27239function EDEState(type, key) {
27240 assert.equal(key.length, 24, 'Invalid key length');
27241
27242 var k1 = key.slice(0, 8);
27243 var k2 = key.slice(8, 16);
27244 var k3 = key.slice(16, 24);
27245
27246 if (type === 'encrypt') {
27247 this.ciphers = [
27248 DES.create({ type: 'encrypt', key: k1 }),
27249 DES.create({ type: 'decrypt', key: k2 }),
27250 DES.create({ type: 'encrypt', key: k3 })
27251 ];
27252 } else {
27253 this.ciphers = [
27254 DES.create({ type: 'decrypt', key: k3 }),
27255 DES.create({ type: 'encrypt', key: k2 }),
27256 DES.create({ type: 'decrypt', key: k1 })
27257 ];
27258 }
27259}
27260
27261function EDE(options) {
27262 Cipher.call(this, options);
27263
27264 var state = new EDEState(this.type, this.options.key);
27265 this._edeState = state;
27266}
27267inherits(EDE, Cipher);
27268
27269module.exports = EDE;
27270
27271EDE.create = function create(options) {
27272 return new EDE(options);
27273};
27274
27275EDE.prototype._update = function _update(inp, inOff, out, outOff) {
27276 var state = this._edeState;
27277
27278 state.ciphers[0]._update(inp, inOff, out, outOff);
27279 state.ciphers[1]._update(out, outOff, out, outOff);
27280 state.ciphers[2]._update(out, outOff, out, outOff);
27281};
27282
27283EDE.prototype._pad = DES.prototype._pad;
27284EDE.prototype._unpad = DES.prototype._unpad;
27285
27286},{"../des":128,"inherits":210,"minimalistic-assert":237}],133:[function(require,module,exports){
27287'use strict';
27288
27289exports.readUInt32BE = function readUInt32BE(bytes, off) {
27290 var res = (bytes[0 + off] << 24) |
27291 (bytes[1 + off] << 16) |
27292 (bytes[2 + off] << 8) |
27293 bytes[3 + off];
27294 return res >>> 0;
27295};
27296
27297exports.writeUInt32BE = function writeUInt32BE(bytes, value, off) {
27298 bytes[0 + off] = value >>> 24;
27299 bytes[1 + off] = (value >>> 16) & 0xff;
27300 bytes[2 + off] = (value >>> 8) & 0xff;
27301 bytes[3 + off] = value & 0xff;
27302};
27303
27304exports.ip = function ip(inL, inR, out, off) {
27305 var outL = 0;
27306 var outR = 0;
27307
27308 for (var i = 6; i >= 0; i -= 2) {
27309 for (var j = 0; j <= 24; j += 8) {
27310 outL <<= 1;
27311 outL |= (inR >>> (j + i)) & 1;
27312 }
27313 for (var j = 0; j <= 24; j += 8) {
27314 outL <<= 1;
27315 outL |= (inL >>> (j + i)) & 1;
27316 }
27317 }
27318
27319 for (var i = 6; i >= 0; i -= 2) {
27320 for (var j = 1; j <= 25; j += 8) {
27321 outR <<= 1;
27322 outR |= (inR >>> (j + i)) & 1;
27323 }
27324 for (var j = 1; j <= 25; j += 8) {
27325 outR <<= 1;
27326 outR |= (inL >>> (j + i)) & 1;
27327 }
27328 }
27329
27330 out[off + 0] = outL >>> 0;
27331 out[off + 1] = outR >>> 0;
27332};
27333
27334exports.rip = function rip(inL, inR, out, off) {
27335 var outL = 0;
27336 var outR = 0;
27337
27338 for (var i = 0; i < 4; i++) {
27339 for (var j = 24; j >= 0; j -= 8) {
27340 outL <<= 1;
27341 outL |= (inR >>> (j + i)) & 1;
27342 outL <<= 1;
27343 outL |= (inL >>> (j + i)) & 1;
27344 }
27345 }
27346 for (var i = 4; i < 8; i++) {
27347 for (var j = 24; j >= 0; j -= 8) {
27348 outR <<= 1;
27349 outR |= (inR >>> (j + i)) & 1;
27350 outR <<= 1;
27351 outR |= (inL >>> (j + i)) & 1;
27352 }
27353 }
27354
27355 out[off + 0] = outL >>> 0;
27356 out[off + 1] = outR >>> 0;
27357};
27358
27359exports.pc1 = function pc1(inL, inR, out, off) {
27360 var outL = 0;
27361 var outR = 0;
27362
27363 // 7, 15, 23, 31, 39, 47, 55, 63
27364 // 6, 14, 22, 30, 39, 47, 55, 63
27365 // 5, 13, 21, 29, 39, 47, 55, 63
27366 // 4, 12, 20, 28
27367 for (var i = 7; i >= 5; i--) {
27368 for (var j = 0; j <= 24; j += 8) {
27369 outL <<= 1;
27370 outL |= (inR >> (j + i)) & 1;
27371 }
27372 for (var j = 0; j <= 24; j += 8) {
27373 outL <<= 1;
27374 outL |= (inL >> (j + i)) & 1;
27375 }
27376 }
27377 for (var j = 0; j <= 24; j += 8) {
27378 outL <<= 1;
27379 outL |= (inR >> (j + i)) & 1;
27380 }
27381
27382 // 1, 9, 17, 25, 33, 41, 49, 57
27383 // 2, 10, 18, 26, 34, 42, 50, 58
27384 // 3, 11, 19, 27, 35, 43, 51, 59
27385 // 36, 44, 52, 60
27386 for (var i = 1; i <= 3; i++) {
27387 for (var j = 0; j <= 24; j += 8) {
27388 outR <<= 1;
27389 outR |= (inR >> (j + i)) & 1;
27390 }
27391 for (var j = 0; j <= 24; j += 8) {
27392 outR <<= 1;
27393 outR |= (inL >> (j + i)) & 1;
27394 }
27395 }
27396 for (var j = 0; j <= 24; j += 8) {
27397 outR <<= 1;
27398 outR |= (inL >> (j + i)) & 1;
27399 }
27400
27401 out[off + 0] = outL >>> 0;
27402 out[off + 1] = outR >>> 0;
27403};
27404
27405exports.r28shl = function r28shl(num, shift) {
27406 return ((num << shift) & 0xfffffff) | (num >>> (28 - shift));
27407};
27408
27409var pc2table = [
27410 // inL => outL
27411 14, 11, 17, 4, 27, 23, 25, 0,
27412 13, 22, 7, 18, 5, 9, 16, 24,
27413 2, 20, 12, 21, 1, 8, 15, 26,
27414
27415 // inR => outR
27416 15, 4, 25, 19, 9, 1, 26, 16,
27417 5, 11, 23, 8, 12, 7, 17, 0,
27418 22, 3, 10, 14, 6, 20, 27, 24
27419];
27420
27421exports.pc2 = function pc2(inL, inR, out, off) {
27422 var outL = 0;
27423 var outR = 0;
27424
27425 var len = pc2table.length >>> 1;
27426 for (var i = 0; i < len; i++) {
27427 outL <<= 1;
27428 outL |= (inL >>> pc2table[i]) & 0x1;
27429 }
27430 for (var i = len; i < pc2table.length; i++) {
27431 outR <<= 1;
27432 outR |= (inR >>> pc2table[i]) & 0x1;
27433 }
27434
27435 out[off + 0] = outL >>> 0;
27436 out[off + 1] = outR >>> 0;
27437};
27438
27439exports.expand = function expand(r, out, off) {
27440 var outL = 0;
27441 var outR = 0;
27442
27443 outL = ((r & 1) << 5) | (r >>> 27);
27444 for (var i = 23; i >= 15; i -= 4) {
27445 outL <<= 6;
27446 outL |= (r >>> i) & 0x3f;
27447 }
27448 for (var i = 11; i >= 3; i -= 4) {
27449 outR |= (r >>> i) & 0x3f;
27450 outR <<= 6;
27451 }
27452 outR |= ((r & 0x1f) << 1) | (r >>> 31);
27453
27454 out[off + 0] = outL >>> 0;
27455 out[off + 1] = outR >>> 0;
27456};
27457
27458var sTable = [
27459 14, 0, 4, 15, 13, 7, 1, 4, 2, 14, 15, 2, 11, 13, 8, 1,
27460 3, 10, 10, 6, 6, 12, 12, 11, 5, 9, 9, 5, 0, 3, 7, 8,
27461 4, 15, 1, 12, 14, 8, 8, 2, 13, 4, 6, 9, 2, 1, 11, 7,
27462 15, 5, 12, 11, 9, 3, 7, 14, 3, 10, 10, 0, 5, 6, 0, 13,
27463
27464 15, 3, 1, 13, 8, 4, 14, 7, 6, 15, 11, 2, 3, 8, 4, 14,
27465 9, 12, 7, 0, 2, 1, 13, 10, 12, 6, 0, 9, 5, 11, 10, 5,
27466 0, 13, 14, 8, 7, 10, 11, 1, 10, 3, 4, 15, 13, 4, 1, 2,
27467 5, 11, 8, 6, 12, 7, 6, 12, 9, 0, 3, 5, 2, 14, 15, 9,
27468
27469 10, 13, 0, 7, 9, 0, 14, 9, 6, 3, 3, 4, 15, 6, 5, 10,
27470 1, 2, 13, 8, 12, 5, 7, 14, 11, 12, 4, 11, 2, 15, 8, 1,
27471 13, 1, 6, 10, 4, 13, 9, 0, 8, 6, 15, 9, 3, 8, 0, 7,
27472 11, 4, 1, 15, 2, 14, 12, 3, 5, 11, 10, 5, 14, 2, 7, 12,
27473
27474 7, 13, 13, 8, 14, 11, 3, 5, 0, 6, 6, 15, 9, 0, 10, 3,
27475 1, 4, 2, 7, 8, 2, 5, 12, 11, 1, 12, 10, 4, 14, 15, 9,
27476 10, 3, 6, 15, 9, 0, 0, 6, 12, 10, 11, 1, 7, 13, 13, 8,
27477 15, 9, 1, 4, 3, 5, 14, 11, 5, 12, 2, 7, 8, 2, 4, 14,
27478
27479 2, 14, 12, 11, 4, 2, 1, 12, 7, 4, 10, 7, 11, 13, 6, 1,
27480 8, 5, 5, 0, 3, 15, 15, 10, 13, 3, 0, 9, 14, 8, 9, 6,
27481 4, 11, 2, 8, 1, 12, 11, 7, 10, 1, 13, 14, 7, 2, 8, 13,
27482 15, 6, 9, 15, 12, 0, 5, 9, 6, 10, 3, 4, 0, 5, 14, 3,
27483
27484 12, 10, 1, 15, 10, 4, 15, 2, 9, 7, 2, 12, 6, 9, 8, 5,
27485 0, 6, 13, 1, 3, 13, 4, 14, 14, 0, 7, 11, 5, 3, 11, 8,
27486 9, 4, 14, 3, 15, 2, 5, 12, 2, 9, 8, 5, 12, 15, 3, 10,
27487 7, 11, 0, 14, 4, 1, 10, 7, 1, 6, 13, 0, 11, 8, 6, 13,
27488
27489 4, 13, 11, 0, 2, 11, 14, 7, 15, 4, 0, 9, 8, 1, 13, 10,
27490 3, 14, 12, 3, 9, 5, 7, 12, 5, 2, 10, 15, 6, 8, 1, 6,
27491 1, 6, 4, 11, 11, 13, 13, 8, 12, 1, 3, 4, 7, 10, 14, 7,
27492 10, 9, 15, 5, 6, 0, 8, 15, 0, 14, 5, 2, 9, 3, 2, 12,
27493
27494 13, 1, 2, 15, 8, 13, 4, 8, 6, 10, 15, 3, 11, 7, 1, 4,
27495 10, 12, 9, 5, 3, 6, 14, 11, 5, 0, 0, 14, 12, 9, 7, 2,
27496 7, 2, 11, 1, 4, 14, 1, 7, 9, 4, 12, 10, 14, 8, 2, 13,
27497 0, 15, 6, 12, 10, 9, 13, 0, 15, 3, 3, 5, 5, 6, 8, 11
27498];
27499
27500exports.substitute = function substitute(inL, inR) {
27501 var out = 0;
27502 for (var i = 0; i < 4; i++) {
27503 var b = (inL >>> (18 - i * 6)) & 0x3f;
27504 var sb = sTable[i * 0x40 + b];
27505
27506 out <<= 4;
27507 out |= sb;
27508 }
27509 for (var i = 0; i < 4; i++) {
27510 var b = (inR >>> (18 - i * 6)) & 0x3f;
27511 var sb = sTable[4 * 0x40 + i * 0x40 + b];
27512
27513 out <<= 4;
27514 out |= sb;
27515 }
27516 return out >>> 0;
27517};
27518
27519var permuteTable = [
27520 16, 25, 12, 11, 3, 20, 4, 15, 31, 17, 9, 6, 27, 14, 1, 22,
27521 30, 24, 8, 18, 0, 5, 29, 23, 13, 19, 2, 26, 10, 21, 28, 7
27522];
27523
27524exports.permute = function permute(num) {
27525 var out = 0;
27526 for (var i = 0; i < permuteTable.length; i++) {
27527 out <<= 1;
27528 out |= (num >>> permuteTable[i]) & 0x1;
27529 }
27530 return out >>> 0;
27531};
27532
27533exports.padSplit = function padSplit(num, size, group) {
27534 var str = num.toString(2);
27535 while (str.length < size)
27536 str = '0' + str;
27537
27538 var out = [];
27539 for (var i = 0; i < size; i += group)
27540 out.push(str.slice(i, i + group));
27541 return out.join(' ');
27542};
27543
27544},{}],134:[function(require,module,exports){
27545(function (Buffer){
27546var generatePrime = require('./lib/generatePrime')
27547var primes = require('./lib/primes.json')
27548
27549var DH = require('./lib/dh')
27550
27551function getDiffieHellman (mod) {
27552 var prime = new Buffer(primes[mod].prime, 'hex')
27553 var gen = new Buffer(primes[mod].gen, 'hex')
27554
27555 return new DH(prime, gen)
27556}
27557
27558var ENCODINGS = {
27559 'binary': true, 'hex': true, 'base64': true
27560}
27561
27562function createDiffieHellman (prime, enc, generator, genc) {
27563 if (Buffer.isBuffer(enc) || ENCODINGS[enc] === undefined) {
27564 return createDiffieHellman(prime, 'binary', enc, generator)
27565 }
27566
27567 enc = enc || 'binary'
27568 genc = genc || 'binary'
27569 generator = generator || new Buffer([2])
27570
27571 if (!Buffer.isBuffer(generator)) {
27572 generator = new Buffer(generator, genc)
27573 }
27574
27575 if (typeof prime === 'number') {
27576 return new DH(generatePrime(prime, generator), generator, true)
27577 }
27578
27579 if (!Buffer.isBuffer(prime)) {
27580 prime = new Buffer(prime, enc)
27581 }
27582
27583 return new DH(prime, generator, true)
27584}
27585
27586exports.DiffieHellmanGroup = exports.createDiffieHellmanGroup = exports.getDiffieHellman = getDiffieHellman
27587exports.createDiffieHellman = exports.DiffieHellman = createDiffieHellman
27588
27589}).call(this,require("buffer").Buffer)
27590},{"./lib/dh":135,"./lib/generatePrime":136,"./lib/primes.json":137,"buffer":114}],135:[function(require,module,exports){
27591(function (Buffer){
27592var BN = require('bn.js');
27593var MillerRabin = require('miller-rabin');
27594var millerRabin = new MillerRabin();
27595var TWENTYFOUR = new BN(24);
27596var ELEVEN = new BN(11);
27597var TEN = new BN(10);
27598var THREE = new BN(3);
27599var SEVEN = new BN(7);
27600var primes = require('./generatePrime');
27601var randomBytes = require('randombytes');
27602module.exports = DH;
27603
27604function setPublicKey(pub, enc) {
27605 enc = enc || 'utf8';
27606 if (!Buffer.isBuffer(pub)) {
27607 pub = new Buffer(pub, enc);
27608 }
27609 this._pub = new BN(pub);
27610 return this;
27611}
27612
27613function setPrivateKey(priv, enc) {
27614 enc = enc || 'utf8';
27615 if (!Buffer.isBuffer(priv)) {
27616 priv = new Buffer(priv, enc);
27617 }
27618 this._priv = new BN(priv);
27619 return this;
27620}
27621
27622var primeCache = {};
27623function checkPrime(prime, generator) {
27624 var gen = generator.toString('hex');
27625 var hex = [gen, prime.toString(16)].join('_');
27626 if (hex in primeCache) {
27627 return primeCache[hex];
27628 }
27629 var error = 0;
27630
27631 if (prime.isEven() ||
27632 !primes.simpleSieve ||
27633 !primes.fermatTest(prime) ||
27634 !millerRabin.test(prime)) {
27635 //not a prime so +1
27636 error += 1;
27637
27638 if (gen === '02' || gen === '05') {
27639 // we'd be able to check the generator
27640 // it would fail so +8
27641 error += 8;
27642 } else {
27643 //we wouldn't be able to test the generator
27644 // so +4
27645 error += 4;
27646 }
27647 primeCache[hex] = error;
27648 return error;
27649 }
27650 if (!millerRabin.test(prime.shrn(1))) {
27651 //not a safe prime
27652 error += 2;
27653 }
27654 var rem;
27655 switch (gen) {
27656 case '02':
27657 if (prime.mod(TWENTYFOUR).cmp(ELEVEN)) {
27658 // unsuidable generator
27659 error += 8;
27660 }
27661 break;
27662 case '05':
27663 rem = prime.mod(TEN);
27664 if (rem.cmp(THREE) && rem.cmp(SEVEN)) {
27665 // prime mod 10 needs to equal 3 or 7
27666 error += 8;
27667 }
27668 break;
27669 default:
27670 error += 4;
27671 }
27672 primeCache[hex] = error;
27673 return error;
27674}
27675
27676function DH(prime, generator, malleable) {
27677 this.setGenerator(generator);
27678 this.__prime = new BN(prime);
27679 this._prime = BN.mont(this.__prime);
27680 this._primeLen = prime.length;
27681 this._pub = undefined;
27682 this._priv = undefined;
27683 this._primeCode = undefined;
27684 if (malleable) {
27685 this.setPublicKey = setPublicKey;
27686 this.setPrivateKey = setPrivateKey;
27687 } else {
27688 this._primeCode = 8;
27689 }
27690}
27691Object.defineProperty(DH.prototype, 'verifyError', {
27692 enumerable: true,
27693 get: function () {
27694 if (typeof this._primeCode !== 'number') {
27695 this._primeCode = checkPrime(this.__prime, this.__gen);
27696 }
27697 return this._primeCode;
27698 }
27699});
27700DH.prototype.generateKeys = function () {
27701 if (!this._priv) {
27702 this._priv = new BN(randomBytes(this._primeLen));
27703 }
27704 this._pub = this._gen.toRed(this._prime).redPow(this._priv).fromRed();
27705 return this.getPublicKey();
27706};
27707
27708DH.prototype.computeSecret = function (other) {
27709 other = new BN(other);
27710 other = other.toRed(this._prime);
27711 var secret = other.redPow(this._priv).fromRed();
27712 var out = new Buffer(secret.toArray());
27713 var prime = this.getPrime();
27714 if (out.length < prime.length) {
27715 var front = new Buffer(prime.length - out.length);
27716 front.fill(0);
27717 out = Buffer.concat([front, out]);
27718 }
27719 return out;
27720};
27721
27722DH.prototype.getPublicKey = function getPublicKey(enc) {
27723 return formatReturnValue(this._pub, enc);
27724};
27725
27726DH.prototype.getPrivateKey = function getPrivateKey(enc) {
27727 return formatReturnValue(this._priv, enc);
27728};
27729
27730DH.prototype.getPrime = function (enc) {
27731 return formatReturnValue(this.__prime, enc);
27732};
27733
27734DH.prototype.getGenerator = function (enc) {
27735 return formatReturnValue(this._gen, enc);
27736};
27737
27738DH.prototype.setGenerator = function (gen, enc) {
27739 enc = enc || 'utf8';
27740 if (!Buffer.isBuffer(gen)) {
27741 gen = new Buffer(gen, enc);
27742 }
27743 this.__gen = gen;
27744 this._gen = new BN(gen);
27745 return this;
27746};
27747
27748function formatReturnValue(bn, enc) {
27749 var buf = new Buffer(bn.toArray());
27750 if (!enc) {
27751 return buf;
27752 } else {
27753 return buf.toString(enc);
27754 }
27755}
27756
27757}).call(this,require("buffer").Buffer)
27758},{"./generatePrime":136,"bn.js":80,"buffer":114,"miller-rabin":233,"randombytes":278}],136:[function(require,module,exports){
27759var randomBytes = require('randombytes');
27760module.exports = findPrime;
27761findPrime.simpleSieve = simpleSieve;
27762findPrime.fermatTest = fermatTest;
27763var BN = require('bn.js');
27764var TWENTYFOUR = new BN(24);
27765var MillerRabin = require('miller-rabin');
27766var millerRabin = new MillerRabin();
27767var ONE = new BN(1);
27768var TWO = new BN(2);
27769var FIVE = new BN(5);
27770var SIXTEEN = new BN(16);
27771var EIGHT = new BN(8);
27772var TEN = new BN(10);
27773var THREE = new BN(3);
27774var SEVEN = new BN(7);
27775var ELEVEN = new BN(11);
27776var FOUR = new BN(4);
27777var TWELVE = new BN(12);
27778var primes = null;
27779
27780function _getPrimes() {
27781 if (primes !== null)
27782 return primes;
27783
27784 var limit = 0x100000;
27785 var res = [];
27786 res[0] = 2;
27787 for (var i = 1, k = 3; k < limit; k += 2) {
27788 var sqrt = Math.ceil(Math.sqrt(k));
27789 for (var j = 0; j < i && res[j] <= sqrt; j++)
27790 if (k % res[j] === 0)
27791 break;
27792
27793 if (i !== j && res[j] <= sqrt)
27794 continue;
27795
27796 res[i++] = k;
27797 }
27798 primes = res;
27799 return res;
27800}
27801
27802function simpleSieve(p) {
27803 var primes = _getPrimes();
27804
27805 for (var i = 0; i < primes.length; i++)
27806 if (p.modn(primes[i]) === 0) {
27807 if (p.cmpn(primes[i]) === 0) {
27808 return true;
27809 } else {
27810 return false;
27811 }
27812 }
27813
27814 return true;
27815}
27816
27817function fermatTest(p) {
27818 var red = BN.mont(p);
27819 return TWO.toRed(red).redPow(p.subn(1)).fromRed().cmpn(1) === 0;
27820}
27821
27822function findPrime(bits, gen) {
27823 if (bits < 16) {
27824 // this is what openssl does
27825 if (gen === 2 || gen === 5) {
27826 return new BN([0x8c, 0x7b]);
27827 } else {
27828 return new BN([0x8c, 0x27]);
27829 }
27830 }
27831 gen = new BN(gen);
27832
27833 var num, n2;
27834
27835 while (true) {
27836 num = new BN(randomBytes(Math.ceil(bits / 8)));
27837 while (num.bitLength() > bits) {
27838 num.ishrn(1);
27839 }
27840 if (num.isEven()) {
27841 num.iadd(ONE);
27842 }
27843 if (!num.testn(1)) {
27844 num.iadd(TWO);
27845 }
27846 if (!gen.cmp(TWO)) {
27847 while (num.mod(TWENTYFOUR).cmp(ELEVEN)) {
27848 num.iadd(FOUR);
27849 }
27850 } else if (!gen.cmp(FIVE)) {
27851 while (num.mod(TEN).cmp(THREE)) {
27852 num.iadd(FOUR);
27853 }
27854 }
27855 n2 = num.shrn(1);
27856 if (simpleSieve(n2) && simpleSieve(num) &&
27857 fermatTest(n2) && fermatTest(num) &&
27858 millerRabin.test(n2) && millerRabin.test(num)) {
27859 return num;
27860 }
27861 }
27862
27863}
27864
27865},{"bn.js":80,"miller-rabin":233,"randombytes":278}],137:[function(require,module,exports){
27866module.exports={
27867 "modp1": {
27868 "gen": "02",
27869 "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a63a3620ffffffffffffffff"
27870 },
27871 "modp2": {
27872 "gen": "02",
27873 "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece65381ffffffffffffffff"
27874 },
27875 "modp5": {
27876 "gen": "02",
27877 "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca237327ffffffffffffffff"
27878 },
27879 "modp14": {
27880 "gen": "02",
27881 "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aacaa68ffffffffffffffff"
27882 },
27883 "modp15": {
27884 "gen": "02",
27885 "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a93ad2caffffffffffffffff"
27886 },
27887 "modp16": {
27888 "gen": "02",
27889 "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c934063199ffffffffffffffff"
27890 },
27891 "modp17": {
27892 "gen": "02",
27893 "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c93402849236c3fab4d27c7026c1d4dcb2602646dec9751e763dba37bdf8ff9406ad9e530ee5db382f413001aeb06a53ed9027d831179727b0865a8918da3edbebcf9b14ed44ce6cbaced4bb1bdb7f1447e6cc254b332051512bd7af426fb8f401378cd2bf5983ca01c64b92ecf032ea15d1721d03f482d7ce6e74fef6d55e702f46980c82b5a84031900b1c9e59e7c97fbec7e8f323a97a7e36cc88be0f1d45b7ff585ac54bd407b22b4154aacc8f6d7ebf48e1d814cc5ed20f8037e0a79715eef29be32806a1d58bb7c5da76f550aa3d8a1fbff0eb19ccb1a313d55cda56c9ec2ef29632387fe8d76e3c0468043e8f663f4860ee12bf2d5b0b7474d6e694f91e6dcc4024ffffffffffffffff"
27894 },
27895 "modp18": {
27896 "gen": "02",
27897 "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c93402849236c3fab4d27c7026c1d4dcb2602646dec9751e763dba37bdf8ff9406ad9e530ee5db382f413001aeb06a53ed9027d831179727b0865a8918da3edbebcf9b14ed44ce6cbaced4bb1bdb7f1447e6cc254b332051512bd7af426fb8f401378cd2bf5983ca01c64b92ecf032ea15d1721d03f482d7ce6e74fef6d55e702f46980c82b5a84031900b1c9e59e7c97fbec7e8f323a97a7e36cc88be0f1d45b7ff585ac54bd407b22b4154aacc8f6d7ebf48e1d814cc5ed20f8037e0a79715eef29be32806a1d58bb7c5da76f550aa3d8a1fbff0eb19ccb1a313d55cda56c9ec2ef29632387fe8d76e3c0468043e8f663f4860ee12bf2d5b0b7474d6e694f91e6dbe115974a3926f12fee5e438777cb6a932df8cd8bec4d073b931ba3bc832b68d9dd300741fa7bf8afc47ed2576f6936ba424663aab639c5ae4f5683423b4742bf1c978238f16cbe39d652de3fdb8befc848ad922222e04a4037c0713eb57a81a23f0c73473fc646cea306b4bcbc8862f8385ddfa9d4b7fa2c087e879683303ed5bdd3a062b3cf5b3a278a66d2a13f83f44f82ddf310ee074ab6a364597e899a0255dc164f31cc50846851df9ab48195ded7ea1b1d510bd7ee74d73faf36bc31ecfa268359046f4eb879f924009438b481c6cd7889a002ed5ee382bc9190da6fc026e479558e4475677e9aa9e3050e2765694dfc81f56e880b96e7160c980dd98edd3dfffffffffffffffff"
27898 }
27899}
27900},{}],138:[function(require,module,exports){
27901(function (process){
27902/* @flow */
27903/*::
27904
27905type DotenvParseOptions = {
27906 debug?: boolean
27907}
27908
27909// keys and values from src
27910type DotenvParseOutput = { [string]: string }
27911
27912type DotenvConfigOptions = {
27913 path?: string, // path to .env file
27914 encoding?: string, // encoding of .env file
27915 debug?: string // turn on logging for debugging purposes
27916}
27917
27918type DotenvConfigOutput = {
27919 parsed?: DotenvParseOutput,
27920 error?: Error
27921}
27922
27923*/
27924
27925const fs = require('fs')
27926const path = require('path')
27927
27928function log (message /*: string */) {
27929 console.log(`[dotenv][DEBUG] ${message}`)
27930}
27931
27932const NEWLINE = '\n'
27933const RE_INI_KEY_VAL = /^\s*([\w.-]+)\s*=\s*(.*)?\s*$/
27934const RE_NEWLINES = /\\n/g
27935const NEWLINES_MATCH = /\n|\r|\r\n/
27936
27937// Parses src into an Object
27938function parse (src /*: string | Buffer */, options /*: ?DotenvParseOptions */) /*: DotenvParseOutput */ {
27939 const debug = Boolean(options && options.debug)
27940 const obj = {}
27941
27942 // convert Buffers before splitting into lines and processing
27943 src.toString().split(NEWLINES_MATCH).forEach(function (line, idx) {
27944 // matching "KEY' and 'VAL' in 'KEY=VAL'
27945 const keyValueArr = line.match(RE_INI_KEY_VAL)
27946 // matched?
27947 if (keyValueArr != null) {
27948 const key = keyValueArr[1]
27949 // default undefined or missing values to empty string
27950 let val = (keyValueArr[2] || '')
27951 const end = val.length - 1
27952 const isDoubleQuoted = val[0] === '"' && val[end] === '"'
27953 const isSingleQuoted = val[0] === "'" && val[end] === "'"
27954
27955 // if single or double quoted, remove quotes
27956 if (isSingleQuoted || isDoubleQuoted) {
27957 val = val.substring(1, end)
27958
27959 // if double quoted, expand newlines
27960 if (isDoubleQuoted) {
27961 val = val.replace(RE_NEWLINES, NEWLINE)
27962 }
27963 } else {
27964 // remove surrounding whitespace
27965 val = val.trim()
27966 }
27967
27968 obj[key] = val
27969 } else if (debug) {
27970 log(`did not match key and value when parsing line ${idx + 1}: ${line}`)
27971 }
27972 })
27973
27974 return obj
27975}
27976
27977// Populates process.env from .env file
27978function config (options /*: ?DotenvConfigOptions */) /*: DotenvConfigOutput */ {
27979 let dotenvPath = path.resolve(process.cwd(), '.env')
27980 let encoding /*: string */ = 'utf8'
27981 let debug = false
27982
27983 if (options) {
27984 if (options.path != null) {
27985 dotenvPath = options.path
27986 }
27987 if (options.encoding != null) {
27988 encoding = options.encoding
27989 }
27990 if (options.debug != null) {
27991 debug = true
27992 }
27993 }
27994
27995 try {
27996 // specifying an encoding returns a string instead of a buffer
27997 const parsed = parse(fs.readFileSync(dotenvPath, { encoding }), { debug })
27998
27999 Object.keys(parsed).forEach(function (key) {
28000 if (!Object.prototype.hasOwnProperty.call(process.env, key)) {
28001 process.env[key] = parsed[key]
28002 } else if (debug) {
28003 log(`"${key}" is already defined in \`process.env\` and will not be overwritten`)
28004 }
28005 })
28006
28007 return { parsed }
28008 } catch (e) {
28009 return { error: e }
28010 }
28011}
28012
28013module.exports.config = config
28014module.exports.parse = parse
28015
28016}).call(this,require('_process'))
28017},{"_process":265,"fs":112,"path":257}],139:[function(require,module,exports){
28018var crypto = require("crypto");
28019var BigInteger = require("jsbn").BigInteger;
28020var ECPointFp = require("./lib/ec.js").ECPointFp;
28021var Buffer = require("safer-buffer").Buffer;
28022exports.ECCurves = require("./lib/sec.js");
28023
28024// zero prepad
28025function unstupid(hex,len)
28026{
28027 return (hex.length >= len) ? hex : unstupid("0"+hex,len);
28028}
28029
28030exports.ECKey = function(curve, key, isPublic)
28031{
28032 var priv;
28033 var c = curve();
28034 var n = c.getN();
28035 var bytes = Math.floor(n.bitLength()/8);
28036
28037 if(key)
28038 {
28039 if(isPublic)
28040 {
28041 var curve = c.getCurve();
28042// var x = key.slice(1,bytes+1); // skip the 04 for uncompressed format
28043// var y = key.slice(bytes+1);
28044// this.P = new ECPointFp(curve,
28045// curve.fromBigInteger(new BigInteger(x.toString("hex"), 16)),
28046// curve.fromBigInteger(new BigInteger(y.toString("hex"), 16)));
28047 this.P = curve.decodePointHex(key.toString("hex"));
28048 }else{
28049 if(key.length != bytes) return false;
28050 priv = new BigInteger(key.toString("hex"), 16);
28051 }
28052 }else{
28053 var n1 = n.subtract(BigInteger.ONE);
28054 var r = new BigInteger(crypto.randomBytes(n.bitLength()));
28055 priv = r.mod(n1).add(BigInteger.ONE);
28056 this.P = c.getG().multiply(priv);
28057 }
28058 if(this.P)
28059 {
28060// var pubhex = unstupid(this.P.getX().toBigInteger().toString(16),bytes*2)+unstupid(this.P.getY().toBigInteger().toString(16),bytes*2);
28061// this.PublicKey = Buffer.from("04"+pubhex,"hex");
28062 this.PublicKey = Buffer.from(c.getCurve().encodeCompressedPointHex(this.P),"hex");
28063 }
28064 if(priv)
28065 {
28066 this.PrivateKey = Buffer.from(unstupid(priv.toString(16),bytes*2),"hex");
28067 this.deriveSharedSecret = function(key)
28068 {
28069 if(!key || !key.P) return false;
28070 var S = key.P.multiply(priv);
28071 return Buffer.from(unstupid(S.getX().toBigInteger().toString(16),bytes*2),"hex");
28072 }
28073 }
28074}
28075
28076
28077},{"./lib/ec.js":140,"./lib/sec.js":141,"crypto":126,"jsbn":215,"safer-buffer":326}],140:[function(require,module,exports){
28078// Basic Javascript Elliptic Curve implementation
28079// Ported loosely from BouncyCastle's Java EC code
28080// Only Fp curves implemented for now
28081
28082// Requires jsbn.js and jsbn2.js
28083var BigInteger = require('jsbn').BigInteger
28084var Barrett = BigInteger.prototype.Barrett
28085
28086// ----------------
28087// ECFieldElementFp
28088
28089// constructor
28090function ECFieldElementFp(q,x) {
28091 this.x = x;
28092 // TODO if(x.compareTo(q) >= 0) error
28093 this.q = q;
28094}
28095
28096function feFpEquals(other) {
28097 if(other == this) return true;
28098 return (this.q.equals(other.q) && this.x.equals(other.x));
28099}
28100
28101function feFpToBigInteger() {
28102 return this.x;
28103}
28104
28105function feFpNegate() {
28106 return new ECFieldElementFp(this.q, this.x.negate().mod(this.q));
28107}
28108
28109function feFpAdd(b) {
28110 return new ECFieldElementFp(this.q, this.x.add(b.toBigInteger()).mod(this.q));
28111}
28112
28113function feFpSubtract(b) {
28114 return new ECFieldElementFp(this.q, this.x.subtract(b.toBigInteger()).mod(this.q));
28115}
28116
28117function feFpMultiply(b) {
28118 return new ECFieldElementFp(this.q, this.x.multiply(b.toBigInteger()).mod(this.q));
28119}
28120
28121function feFpSquare() {
28122 return new ECFieldElementFp(this.q, this.x.square().mod(this.q));
28123}
28124
28125function feFpDivide(b) {
28126 return new ECFieldElementFp(this.q, this.x.multiply(b.toBigInteger().modInverse(this.q)).mod(this.q));
28127}
28128
28129ECFieldElementFp.prototype.equals = feFpEquals;
28130ECFieldElementFp.prototype.toBigInteger = feFpToBigInteger;
28131ECFieldElementFp.prototype.negate = feFpNegate;
28132ECFieldElementFp.prototype.add = feFpAdd;
28133ECFieldElementFp.prototype.subtract = feFpSubtract;
28134ECFieldElementFp.prototype.multiply = feFpMultiply;
28135ECFieldElementFp.prototype.square = feFpSquare;
28136ECFieldElementFp.prototype.divide = feFpDivide;
28137
28138// ----------------
28139// ECPointFp
28140
28141// constructor
28142function ECPointFp(curve,x,y,z) {
28143 this.curve = curve;
28144 this.x = x;
28145 this.y = y;
28146 // Projective coordinates: either zinv == null or z * zinv == 1
28147 // z and zinv are just BigIntegers, not fieldElements
28148 if(z == null) {
28149 this.z = BigInteger.ONE;
28150 }
28151 else {
28152 this.z = z;
28153 }
28154 this.zinv = null;
28155 //TODO: compression flag
28156}
28157
28158function pointFpGetX() {
28159 if(this.zinv == null) {
28160 this.zinv = this.z.modInverse(this.curve.q);
28161 }
28162 var r = this.x.toBigInteger().multiply(this.zinv);
28163 this.curve.reduce(r);
28164 return this.curve.fromBigInteger(r);
28165}
28166
28167function pointFpGetY() {
28168 if(this.zinv == null) {
28169 this.zinv = this.z.modInverse(this.curve.q);
28170 }
28171 var r = this.y.toBigInteger().multiply(this.zinv);
28172 this.curve.reduce(r);
28173 return this.curve.fromBigInteger(r);
28174}
28175
28176function pointFpEquals(other) {
28177 if(other == this) return true;
28178 if(this.isInfinity()) return other.isInfinity();
28179 if(other.isInfinity()) return this.isInfinity();
28180 var u, v;
28181 // u = Y2 * Z1 - Y1 * Z2
28182 u = other.y.toBigInteger().multiply(this.z).subtract(this.y.toBigInteger().multiply(other.z)).mod(this.curve.q);
28183 if(!u.equals(BigInteger.ZERO)) return false;
28184 // v = X2 * Z1 - X1 * Z2
28185 v = other.x.toBigInteger().multiply(this.z).subtract(this.x.toBigInteger().multiply(other.z)).mod(this.curve.q);
28186 return v.equals(BigInteger.ZERO);
28187}
28188
28189function pointFpIsInfinity() {
28190 if((this.x == null) && (this.y == null)) return true;
28191 return this.z.equals(BigInteger.ZERO) && !this.y.toBigInteger().equals(BigInteger.ZERO);
28192}
28193
28194function pointFpNegate() {
28195 return new ECPointFp(this.curve, this.x, this.y.negate(), this.z);
28196}
28197
28198function pointFpAdd(b) {
28199 if(this.isInfinity()) return b;
28200 if(b.isInfinity()) return this;
28201
28202 // u = Y2 * Z1 - Y1 * Z2
28203 var u = b.y.toBigInteger().multiply(this.z).subtract(this.y.toBigInteger().multiply(b.z)).mod(this.curve.q);
28204 // v = X2 * Z1 - X1 * Z2
28205 var v = b.x.toBigInteger().multiply(this.z).subtract(this.x.toBigInteger().multiply(b.z)).mod(this.curve.q);
28206
28207 if(BigInteger.ZERO.equals(v)) {
28208 if(BigInteger.ZERO.equals(u)) {
28209 return this.twice(); // this == b, so double
28210 }
28211 return this.curve.getInfinity(); // this = -b, so infinity
28212 }
28213
28214 var THREE = new BigInteger("3");
28215 var x1 = this.x.toBigInteger();
28216 var y1 = this.y.toBigInteger();
28217 var x2 = b.x.toBigInteger();
28218 var y2 = b.y.toBigInteger();
28219
28220 var v2 = v.square();
28221 var v3 = v2.multiply(v);
28222 var x1v2 = x1.multiply(v2);
28223 var zu2 = u.square().multiply(this.z);
28224
28225 // x3 = v * (z2 * (z1 * u^2 - 2 * x1 * v^2) - v^3)
28226 var x3 = zu2.subtract(x1v2.shiftLeft(1)).multiply(b.z).subtract(v3).multiply(v).mod(this.curve.q);
28227 // y3 = z2 * (3 * x1 * u * v^2 - y1 * v^3 - z1 * u^3) + u * v^3
28228 var y3 = x1v2.multiply(THREE).multiply(u).subtract(y1.multiply(v3)).subtract(zu2.multiply(u)).multiply(b.z).add(u.multiply(v3)).mod(this.curve.q);
28229 // z3 = v^3 * z1 * z2
28230 var z3 = v3.multiply(this.z).multiply(b.z).mod(this.curve.q);
28231
28232 return new ECPointFp(this.curve, this.curve.fromBigInteger(x3), this.curve.fromBigInteger(y3), z3);
28233}
28234
28235function pointFpTwice() {
28236 if(this.isInfinity()) return this;
28237 if(this.y.toBigInteger().signum() == 0) return this.curve.getInfinity();
28238
28239 // TODO: optimized handling of constants
28240 var THREE = new BigInteger("3");
28241 var x1 = this.x.toBigInteger();
28242 var y1 = this.y.toBigInteger();
28243
28244 var y1z1 = y1.multiply(this.z);
28245 var y1sqz1 = y1z1.multiply(y1).mod(this.curve.q);
28246 var a = this.curve.a.toBigInteger();
28247
28248 // w = 3 * x1^2 + a * z1^2
28249 var w = x1.square().multiply(THREE);
28250 if(!BigInteger.ZERO.equals(a)) {
28251 w = w.add(this.z.square().multiply(a));
28252 }
28253 w = w.mod(this.curve.q);
28254 //this.curve.reduce(w);
28255 // x3 = 2 * y1 * z1 * (w^2 - 8 * x1 * y1^2 * z1)
28256 var x3 = w.square().subtract(x1.shiftLeft(3).multiply(y1sqz1)).shiftLeft(1).multiply(y1z1).mod(this.curve.q);
28257 // y3 = 4 * y1^2 * z1 * (3 * w * x1 - 2 * y1^2 * z1) - w^3
28258 var y3 = w.multiply(THREE).multiply(x1).subtract(y1sqz1.shiftLeft(1)).shiftLeft(2).multiply(y1sqz1).subtract(w.square().multiply(w)).mod(this.curve.q);
28259 // z3 = 8 * (y1 * z1)^3
28260 var z3 = y1z1.square().multiply(y1z1).shiftLeft(3).mod(this.curve.q);
28261
28262 return new ECPointFp(this.curve, this.curve.fromBigInteger(x3), this.curve.fromBigInteger(y3), z3);
28263}
28264
28265// Simple NAF (Non-Adjacent Form) multiplication algorithm
28266// TODO: modularize the multiplication algorithm
28267function pointFpMultiply(k) {
28268 if(this.isInfinity()) return this;
28269 if(k.signum() == 0) return this.curve.getInfinity();
28270
28271 var e = k;
28272 var h = e.multiply(new BigInteger("3"));
28273
28274 var neg = this.negate();
28275 var R = this;
28276
28277 var i;
28278 for(i = h.bitLength() - 2; i > 0; --i) {
28279 R = R.twice();
28280
28281 var hBit = h.testBit(i);
28282 var eBit = e.testBit(i);
28283
28284 if (hBit != eBit) {
28285 R = R.add(hBit ? this : neg);
28286 }
28287 }
28288
28289 return R;
28290}
28291
28292// Compute this*j + x*k (simultaneous multiplication)
28293function pointFpMultiplyTwo(j,x,k) {
28294 var i;
28295 if(j.bitLength() > k.bitLength())
28296 i = j.bitLength() - 1;
28297 else
28298 i = k.bitLength() - 1;
28299
28300 var R = this.curve.getInfinity();
28301 var both = this.add(x);
28302 while(i >= 0) {
28303 R = R.twice();
28304 if(j.testBit(i)) {
28305 if(k.testBit(i)) {
28306 R = R.add(both);
28307 }
28308 else {
28309 R = R.add(this);
28310 }
28311 }
28312 else {
28313 if(k.testBit(i)) {
28314 R = R.add(x);
28315 }
28316 }
28317 --i;
28318 }
28319
28320 return R;
28321}
28322
28323ECPointFp.prototype.getX = pointFpGetX;
28324ECPointFp.prototype.getY = pointFpGetY;
28325ECPointFp.prototype.equals = pointFpEquals;
28326ECPointFp.prototype.isInfinity = pointFpIsInfinity;
28327ECPointFp.prototype.negate = pointFpNegate;
28328ECPointFp.prototype.add = pointFpAdd;
28329ECPointFp.prototype.twice = pointFpTwice;
28330ECPointFp.prototype.multiply = pointFpMultiply;
28331ECPointFp.prototype.multiplyTwo = pointFpMultiplyTwo;
28332
28333// ----------------
28334// ECCurveFp
28335
28336// constructor
28337function ECCurveFp(q,a,b) {
28338 this.q = q;
28339 this.a = this.fromBigInteger(a);
28340 this.b = this.fromBigInteger(b);
28341 this.infinity = new ECPointFp(this, null, null);
28342 this.reducer = new Barrett(this.q);
28343}
28344
28345function curveFpGetQ() {
28346 return this.q;
28347}
28348
28349function curveFpGetA() {
28350 return this.a;
28351}
28352
28353function curveFpGetB() {
28354 return this.b;
28355}
28356
28357function curveFpEquals(other) {
28358 if(other == this) return true;
28359 return(this.q.equals(other.q) && this.a.equals(other.a) && this.b.equals(other.b));
28360}
28361
28362function curveFpGetInfinity() {
28363 return this.infinity;
28364}
28365
28366function curveFpFromBigInteger(x) {
28367 return new ECFieldElementFp(this.q, x);
28368}
28369
28370function curveReduce(x) {
28371 this.reducer.reduce(x);
28372}
28373
28374// for now, work with hex strings because they're easier in JS
28375function curveFpDecodePointHex(s) {
28376 switch(parseInt(s.substr(0,2), 16)) { // first byte
28377 case 0:
28378 return this.infinity;
28379 case 2:
28380 case 3:
28381 // point compression not supported yet
28382 return null;
28383 case 4:
28384 case 6:
28385 case 7:
28386 var len = (s.length - 2) / 2;
28387 var xHex = s.substr(2, len);
28388 var yHex = s.substr(len+2, len);
28389
28390 return new ECPointFp(this,
28391 this.fromBigInteger(new BigInteger(xHex, 16)),
28392 this.fromBigInteger(new BigInteger(yHex, 16)));
28393
28394 default: // unsupported
28395 return null;
28396 }
28397}
28398
28399function curveFpEncodePointHex(p) {
28400 if (p.isInfinity()) return "00";
28401 var xHex = p.getX().toBigInteger().toString(16);
28402 var yHex = p.getY().toBigInteger().toString(16);
28403 var oLen = this.getQ().toString(16).length;
28404 if ((oLen % 2) != 0) oLen++;
28405 while (xHex.length < oLen) {
28406 xHex = "0" + xHex;
28407 }
28408 while (yHex.length < oLen) {
28409 yHex = "0" + yHex;
28410 }
28411 return "04" + xHex + yHex;
28412}
28413
28414ECCurveFp.prototype.getQ = curveFpGetQ;
28415ECCurveFp.prototype.getA = curveFpGetA;
28416ECCurveFp.prototype.getB = curveFpGetB;
28417ECCurveFp.prototype.equals = curveFpEquals;
28418ECCurveFp.prototype.getInfinity = curveFpGetInfinity;
28419ECCurveFp.prototype.fromBigInteger = curveFpFromBigInteger;
28420ECCurveFp.prototype.reduce = curveReduce;
28421//ECCurveFp.prototype.decodePointHex = curveFpDecodePointHex;
28422ECCurveFp.prototype.encodePointHex = curveFpEncodePointHex;
28423
28424// from: https://github.com/kaielvin/jsbn-ec-point-compression
28425ECCurveFp.prototype.decodePointHex = function(s)
28426{
28427 var yIsEven;
28428 switch(parseInt(s.substr(0,2), 16)) { // first byte
28429 case 0:
28430 return this.infinity;
28431 case 2:
28432 yIsEven = false;
28433 case 3:
28434 if(yIsEven == undefined) yIsEven = true;
28435 var len = s.length - 2;
28436 var xHex = s.substr(2, len);
28437 var x = this.fromBigInteger(new BigInteger(xHex,16));
28438 var alpha = x.multiply(x.square().add(this.getA())).add(this.getB());
28439 var beta = alpha.sqrt();
28440
28441 if (beta == null) throw "Invalid point compression";
28442
28443 var betaValue = beta.toBigInteger();
28444 if (betaValue.testBit(0) != yIsEven)
28445 {
28446 // Use the other root
28447 beta = this.fromBigInteger(this.getQ().subtract(betaValue));
28448 }
28449 return new ECPointFp(this,x,beta);
28450 case 4:
28451 case 6:
28452 case 7:
28453 var len = (s.length - 2) / 2;
28454 var xHex = s.substr(2, len);
28455 var yHex = s.substr(len+2, len);
28456
28457 return new ECPointFp(this,
28458 this.fromBigInteger(new BigInteger(xHex, 16)),
28459 this.fromBigInteger(new BigInteger(yHex, 16)));
28460
28461 default: // unsupported
28462 return null;
28463 }
28464}
28465ECCurveFp.prototype.encodeCompressedPointHex = function(p)
28466{
28467 if (p.isInfinity()) return "00";
28468 var xHex = p.getX().toBigInteger().toString(16);
28469 var oLen = this.getQ().toString(16).length;
28470 if ((oLen % 2) != 0) oLen++;
28471 while (xHex.length < oLen)
28472 xHex = "0" + xHex;
28473 var yPrefix;
28474 if(p.getY().toBigInteger().isEven()) yPrefix = "02";
28475 else yPrefix = "03";
28476
28477 return yPrefix + xHex;
28478}
28479
28480
28481ECFieldElementFp.prototype.getR = function()
28482{
28483 if(this.r != undefined) return this.r;
28484
28485 this.r = null;
28486 var bitLength = this.q.bitLength();
28487 if (bitLength > 128)
28488 {
28489 var firstWord = this.q.shiftRight(bitLength - 64);
28490 if (firstWord.intValue() == -1)
28491 {
28492 this.r = BigInteger.ONE.shiftLeft(bitLength).subtract(this.q);
28493 }
28494 }
28495 return this.r;
28496}
28497ECFieldElementFp.prototype.modMult = function(x1,x2)
28498{
28499 return this.modReduce(x1.multiply(x2));
28500}
28501ECFieldElementFp.prototype.modReduce = function(x)
28502{
28503 if (this.getR() != null)
28504 {
28505 var qLen = q.bitLength();
28506 while (x.bitLength() > (qLen + 1))
28507 {
28508 var u = x.shiftRight(qLen);
28509 var v = x.subtract(u.shiftLeft(qLen));
28510 if (!this.getR().equals(BigInteger.ONE))
28511 {
28512 u = u.multiply(this.getR());
28513 }
28514 x = u.add(v);
28515 }
28516 while (x.compareTo(q) >= 0)
28517 {
28518 x = x.subtract(q);
28519 }
28520 }
28521 else
28522 {
28523 x = x.mod(q);
28524 }
28525 return x;
28526}
28527ECFieldElementFp.prototype.sqrt = function()
28528{
28529 if (!this.q.testBit(0)) throw "unsupported";
28530
28531 // p mod 4 == 3
28532 if (this.q.testBit(1))
28533 {
28534 var z = new ECFieldElementFp(this.q,this.x.modPow(this.q.shiftRight(2).add(BigInteger.ONE),this.q));
28535 return z.square().equals(this) ? z : null;
28536 }
28537
28538 // p mod 4 == 1
28539 var qMinusOne = this.q.subtract(BigInteger.ONE);
28540
28541 var legendreExponent = qMinusOne.shiftRight(1);
28542 if (!(this.x.modPow(legendreExponent, this.q).equals(BigInteger.ONE)))
28543 {
28544 return null;
28545 }
28546
28547 var u = qMinusOne.shiftRight(2);
28548 var k = u.shiftLeft(1).add(BigInteger.ONE);
28549
28550 var Q = this.x;
28551 var fourQ = modDouble(modDouble(Q));
28552
28553 var U, V;
28554 do
28555 {
28556 var P;
28557 do
28558 {
28559 P = new BigInteger(this.q.bitLength(), new SecureRandom());
28560 }
28561 while (P.compareTo(this.q) >= 0
28562 || !(P.multiply(P).subtract(fourQ).modPow(legendreExponent, this.q).equals(qMinusOne)));
28563
28564 var result = this.lucasSequence(P, Q, k);
28565 U = result[0];
28566 V = result[1];
28567
28568 if (this.modMult(V, V).equals(fourQ))
28569 {
28570 // Integer division by 2, mod q
28571 if (V.testBit(0))
28572 {
28573 V = V.add(q);
28574 }
28575
28576 V = V.shiftRight(1);
28577
28578 return new ECFieldElementFp(q,V);
28579 }
28580 }
28581 while (U.equals(BigInteger.ONE) || U.equals(qMinusOne));
28582
28583 return null;
28584}
28585ECFieldElementFp.prototype.lucasSequence = function(P,Q,k)
28586{
28587 var n = k.bitLength();
28588 var s = k.getLowestSetBit();
28589
28590 var Uh = BigInteger.ONE;
28591 var Vl = BigInteger.TWO;
28592 var Vh = P;
28593 var Ql = BigInteger.ONE;
28594 var Qh = BigInteger.ONE;
28595
28596 for (var j = n - 1; j >= s + 1; --j)
28597 {
28598 Ql = this.modMult(Ql, Qh);
28599
28600 if (k.testBit(j))
28601 {
28602 Qh = this.modMult(Ql, Q);
28603 Uh = this.modMult(Uh, Vh);
28604 Vl = this.modReduce(Vh.multiply(Vl).subtract(P.multiply(Ql)));
28605 Vh = this.modReduce(Vh.multiply(Vh).subtract(Qh.shiftLeft(1)));
28606 }
28607 else
28608 {
28609 Qh = Ql;
28610 Uh = this.modReduce(Uh.multiply(Vl).subtract(Ql));
28611 Vh = this.modReduce(Vh.multiply(Vl).subtract(P.multiply(Ql)));
28612 Vl = this.modReduce(Vl.multiply(Vl).subtract(Ql.shiftLeft(1)));
28613 }
28614 }
28615
28616 Ql = this.modMult(Ql, Qh);
28617 Qh = this.modMult(Ql, Q);
28618 Uh = this.modReduce(Uh.multiply(Vl).subtract(Ql));
28619 Vl = this.modReduce(Vh.multiply(Vl).subtract(P.multiply(Ql)));
28620 Ql = this.modMult(Ql, Qh);
28621
28622 for (var j = 1; j <= s; ++j)
28623 {
28624 Uh = this.modMult(Uh, Vl);
28625 Vl = this.modReduce(Vl.multiply(Vl).subtract(Ql.shiftLeft(1)));
28626 Ql = this.modMult(Ql, Ql);
28627 }
28628
28629 return [ Uh, Vl ];
28630}
28631
28632var exports = {
28633 ECCurveFp: ECCurveFp,
28634 ECPointFp: ECPointFp,
28635 ECFieldElementFp: ECFieldElementFp
28636}
28637
28638module.exports = exports
28639
28640},{"jsbn":215}],141:[function(require,module,exports){
28641// Named EC curves
28642
28643// Requires ec.js, jsbn.js, and jsbn2.js
28644var BigInteger = require('jsbn').BigInteger
28645var ECCurveFp = require('./ec.js').ECCurveFp
28646
28647
28648// ----------------
28649// X9ECParameters
28650
28651// constructor
28652function X9ECParameters(curve,g,n,h) {
28653 this.curve = curve;
28654 this.g = g;
28655 this.n = n;
28656 this.h = h;
28657}
28658
28659function x9getCurve() {
28660 return this.curve;
28661}
28662
28663function x9getG() {
28664 return this.g;
28665}
28666
28667function x9getN() {
28668 return this.n;
28669}
28670
28671function x9getH() {
28672 return this.h;
28673}
28674
28675X9ECParameters.prototype.getCurve = x9getCurve;
28676X9ECParameters.prototype.getG = x9getG;
28677X9ECParameters.prototype.getN = x9getN;
28678X9ECParameters.prototype.getH = x9getH;
28679
28680// ----------------
28681// SECNamedCurves
28682
28683function fromHex(s) { return new BigInteger(s, 16); }
28684
28685function secp128r1() {
28686 // p = 2^128 - 2^97 - 1
28687 var p = fromHex("FFFFFFFDFFFFFFFFFFFFFFFFFFFFFFFF");
28688 var a = fromHex("FFFFFFFDFFFFFFFFFFFFFFFFFFFFFFFC");
28689 var b = fromHex("E87579C11079F43DD824993C2CEE5ED3");
28690 //byte[] S = Hex.decode("000E0D4D696E6768756151750CC03A4473D03679");
28691 var n = fromHex("FFFFFFFE0000000075A30D1B9038A115");
28692 var h = BigInteger.ONE;
28693 var curve = new ECCurveFp(p, a, b);
28694 var G = curve.decodePointHex("04"
28695 + "161FF7528B899B2D0C28607CA52C5B86"
28696 + "CF5AC8395BAFEB13C02DA292DDED7A83");
28697 return new X9ECParameters(curve, G, n, h);
28698}
28699
28700function secp160k1() {
28701 // p = 2^160 - 2^32 - 2^14 - 2^12 - 2^9 - 2^8 - 2^7 - 2^3 - 2^2 - 1
28702 var p = fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFAC73");
28703 var a = BigInteger.ZERO;
28704 var b = fromHex("7");
28705 //byte[] S = null;
28706 var n = fromHex("0100000000000000000001B8FA16DFAB9ACA16B6B3");
28707 var h = BigInteger.ONE;
28708 var curve = new ECCurveFp(p, a, b);
28709 var G = curve.decodePointHex("04"
28710 + "3B4C382CE37AA192A4019E763036F4F5DD4D7EBB"
28711 + "938CF935318FDCED6BC28286531733C3F03C4FEE");
28712 return new X9ECParameters(curve, G, n, h);
28713}
28714
28715function secp160r1() {
28716 // p = 2^160 - 2^31 - 1
28717 var p = fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF7FFFFFFF");
28718 var a = fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF7FFFFFFC");
28719 var b = fromHex("1C97BEFC54BD7A8B65ACF89F81D4D4ADC565FA45");
28720 //byte[] S = Hex.decode("1053CDE42C14D696E67687561517533BF3F83345");
28721 var n = fromHex("0100000000000000000001F4C8F927AED3CA752257");
28722 var h = BigInteger.ONE;
28723 var curve = new ECCurveFp(p, a, b);
28724 var G = curve.decodePointHex("04"
28725 + "4A96B5688EF573284664698968C38BB913CBFC82"
28726 + "23A628553168947D59DCC912042351377AC5FB32");
28727 return new X9ECParameters(curve, G, n, h);
28728}
28729
28730function secp192k1() {
28731 // p = 2^192 - 2^32 - 2^12 - 2^8 - 2^7 - 2^6 - 2^3 - 1
28732 var p = fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFEE37");
28733 var a = BigInteger.ZERO;
28734 var b = fromHex("3");
28735 //byte[] S = null;
28736 var n = fromHex("FFFFFFFFFFFFFFFFFFFFFFFE26F2FC170F69466A74DEFD8D");
28737 var h = BigInteger.ONE;
28738 var curve = new ECCurveFp(p, a, b);
28739 var G = curve.decodePointHex("04"
28740 + "DB4FF10EC057E9AE26B07D0280B7F4341DA5D1B1EAE06C7D"
28741 + "9B2F2F6D9C5628A7844163D015BE86344082AA88D95E2F9D");
28742 return new X9ECParameters(curve, G, n, h);
28743}
28744
28745function secp192r1() {
28746 // p = 2^192 - 2^64 - 1
28747 var p = fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFF");
28748 var a = fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFC");
28749 var b = fromHex("64210519E59C80E70FA7E9AB72243049FEB8DEECC146B9B1");
28750 //byte[] S = Hex.decode("3045AE6FC8422F64ED579528D38120EAE12196D5");
28751 var n = fromHex("FFFFFFFFFFFFFFFFFFFFFFFF99DEF836146BC9B1B4D22831");
28752 var h = BigInteger.ONE;
28753 var curve = new ECCurveFp(p, a, b);
28754 var G = curve.decodePointHex("04"
28755 + "188DA80EB03090F67CBF20EB43A18800F4FF0AFD82FF1012"
28756 + "07192B95FFC8DA78631011ED6B24CDD573F977A11E794811");
28757 return new X9ECParameters(curve, G, n, h);
28758}
28759
28760function secp224r1() {
28761 // p = 2^224 - 2^96 + 1
28762 var p = fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF000000000000000000000001");
28763 var a = fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFE");
28764 var b = fromHex("B4050A850C04B3ABF54132565044B0B7D7BFD8BA270B39432355FFB4");
28765 //byte[] S = Hex.decode("BD71344799D5C7FCDC45B59FA3B9AB8F6A948BC5");
28766 var n = fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFF16A2E0B8F03E13DD29455C5C2A3D");
28767 var h = BigInteger.ONE;
28768 var curve = new ECCurveFp(p, a, b);
28769 var G = curve.decodePointHex("04"
28770 + "B70E0CBD6BB4BF7F321390B94A03C1D356C21122343280D6115C1D21"
28771 + "BD376388B5F723FB4C22DFE6CD4375A05A07476444D5819985007E34");
28772 return new X9ECParameters(curve, G, n, h);
28773}
28774
28775function secp256r1() {
28776 // p = 2^224 (2^32 - 1) + 2^192 + 2^96 - 1
28777 var p = fromHex("FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFF");
28778 var a = fromHex("FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFC");
28779 var b = fromHex("5AC635D8AA3A93E7B3EBBD55769886BC651D06B0CC53B0F63BCE3C3E27D2604B");
28780 //byte[] S = Hex.decode("C49D360886E704936A6678E1139D26B7819F7E90");
28781 var n = fromHex("FFFFFFFF00000000FFFFFFFFFFFFFFFFBCE6FAADA7179E84F3B9CAC2FC632551");
28782 var h = BigInteger.ONE;
28783 var curve = new ECCurveFp(p, a, b);
28784 var G = curve.decodePointHex("04"
28785 + "6B17D1F2E12C4247F8BCE6E563A440F277037D812DEB33A0F4A13945D898C296"
28786 + "4FE342E2FE1A7F9B8EE7EB4A7C0F9E162BCE33576B315ECECBB6406837BF51F5");
28787 return new X9ECParameters(curve, G, n, h);
28788}
28789
28790// TODO: make this into a proper hashtable
28791function getSECCurveByName(name) {
28792 if(name == "secp128r1") return secp128r1();
28793 if(name == "secp160k1") return secp160k1();
28794 if(name == "secp160r1") return secp160r1();
28795 if(name == "secp192k1") return secp192k1();
28796 if(name == "secp192r1") return secp192r1();
28797 if(name == "secp224r1") return secp224r1();
28798 if(name == "secp256r1") return secp256r1();
28799 return null;
28800}
28801
28802module.exports = {
28803 "secp128r1":secp128r1,
28804 "secp160k1":secp160k1,
28805 "secp160r1":secp160r1,
28806 "secp192k1":secp192k1,
28807 "secp192r1":secp192r1,
28808 "secp224r1":secp224r1,
28809 "secp256r1":secp256r1
28810}
28811
28812},{"./ec.js":140,"jsbn":215}],142:[function(require,module,exports){
28813'use strict';
28814
28815var elliptic = exports;
28816
28817elliptic.version = require('../package.json').version;
28818elliptic.utils = require('./elliptic/utils');
28819elliptic.rand = require('brorand');
28820elliptic.curve = require('./elliptic/curve');
28821elliptic.curves = require('./elliptic/curves');
28822
28823// Protocols
28824elliptic.ec = require('./elliptic/ec');
28825elliptic.eddsa = require('./elliptic/eddsa');
28826
28827},{"../package.json":157,"./elliptic/curve":145,"./elliptic/curves":148,"./elliptic/ec":149,"./elliptic/eddsa":152,"./elliptic/utils":156,"brorand":81}],143:[function(require,module,exports){
28828'use strict';
28829
28830var BN = require('bn.js');
28831var elliptic = require('../../elliptic');
28832var utils = elliptic.utils;
28833var getNAF = utils.getNAF;
28834var getJSF = utils.getJSF;
28835var assert = utils.assert;
28836
28837function BaseCurve(type, conf) {
28838 this.type = type;
28839 this.p = new BN(conf.p, 16);
28840
28841 // Use Montgomery, when there is no fast reduction for the prime
28842 this.red = conf.prime ? BN.red(conf.prime) : BN.mont(this.p);
28843
28844 // Useful for many curves
28845 this.zero = new BN(0).toRed(this.red);
28846 this.one = new BN(1).toRed(this.red);
28847 this.two = new BN(2).toRed(this.red);
28848
28849 // Curve configuration, optional
28850 this.n = conf.n && new BN(conf.n, 16);
28851 this.g = conf.g && this.pointFromJSON(conf.g, conf.gRed);
28852
28853 // Temporary arrays
28854 this._wnafT1 = new Array(4);
28855 this._wnafT2 = new Array(4);
28856 this._wnafT3 = new Array(4);
28857 this._wnafT4 = new Array(4);
28858
28859 // Generalized Greg Maxwell's trick
28860 var adjustCount = this.n && this.p.div(this.n);
28861 if (!adjustCount || adjustCount.cmpn(100) > 0) {
28862 this.redN = null;
28863 } else {
28864 this._maxwellTrick = true;
28865 this.redN = this.n.toRed(this.red);
28866 }
28867}
28868module.exports = BaseCurve;
28869
28870BaseCurve.prototype.point = function point() {
28871 throw new Error('Not implemented');
28872};
28873
28874BaseCurve.prototype.validate = function validate() {
28875 throw new Error('Not implemented');
28876};
28877
28878BaseCurve.prototype._fixedNafMul = function _fixedNafMul(p, k) {
28879 assert(p.precomputed);
28880 var doubles = p._getDoubles();
28881
28882 var naf = getNAF(k, 1);
28883 var I = (1 << (doubles.step + 1)) - (doubles.step % 2 === 0 ? 2 : 1);
28884 I /= 3;
28885
28886 // Translate into more windowed form
28887 var repr = [];
28888 for (var j = 0; j < naf.length; j += doubles.step) {
28889 var nafW = 0;
28890 for (var k = j + doubles.step - 1; k >= j; k--)
28891 nafW = (nafW << 1) + naf[k];
28892 repr.push(nafW);
28893 }
28894
28895 var a = this.jpoint(null, null, null);
28896 var b = this.jpoint(null, null, null);
28897 for (var i = I; i > 0; i--) {
28898 for (var j = 0; j < repr.length; j++) {
28899 var nafW = repr[j];
28900 if (nafW === i)
28901 b = b.mixedAdd(doubles.points[j]);
28902 else if (nafW === -i)
28903 b = b.mixedAdd(doubles.points[j].neg());
28904 }
28905 a = a.add(b);
28906 }
28907 return a.toP();
28908};
28909
28910BaseCurve.prototype._wnafMul = function _wnafMul(p, k) {
28911 var w = 4;
28912
28913 // Precompute window
28914 var nafPoints = p._getNAFPoints(w);
28915 w = nafPoints.wnd;
28916 var wnd = nafPoints.points;
28917
28918 // Get NAF form
28919 var naf = getNAF(k, w);
28920
28921 // Add `this`*(N+1) for every w-NAF index
28922 var acc = this.jpoint(null, null, null);
28923 for (var i = naf.length - 1; i >= 0; i--) {
28924 // Count zeroes
28925 for (var k = 0; i >= 0 && naf[i] === 0; i--)
28926 k++;
28927 if (i >= 0)
28928 k++;
28929 acc = acc.dblp(k);
28930
28931 if (i < 0)
28932 break;
28933 var z = naf[i];
28934 assert(z !== 0);
28935 if (p.type === 'affine') {
28936 // J +- P
28937 if (z > 0)
28938 acc = acc.mixedAdd(wnd[(z - 1) >> 1]);
28939 else
28940 acc = acc.mixedAdd(wnd[(-z - 1) >> 1].neg());
28941 } else {
28942 // J +- J
28943 if (z > 0)
28944 acc = acc.add(wnd[(z - 1) >> 1]);
28945 else
28946 acc = acc.add(wnd[(-z - 1) >> 1].neg());
28947 }
28948 }
28949 return p.type === 'affine' ? acc.toP() : acc;
28950};
28951
28952BaseCurve.prototype._wnafMulAdd = function _wnafMulAdd(defW,
28953 points,
28954 coeffs,
28955 len,
28956 jacobianResult) {
28957 var wndWidth = this._wnafT1;
28958 var wnd = this._wnafT2;
28959 var naf = this._wnafT3;
28960
28961 // Fill all arrays
28962 var max = 0;
28963 for (var i = 0; i < len; i++) {
28964 var p = points[i];
28965 var nafPoints = p._getNAFPoints(defW);
28966 wndWidth[i] = nafPoints.wnd;
28967 wnd[i] = nafPoints.points;
28968 }
28969
28970 // Comb small window NAFs
28971 for (var i = len - 1; i >= 1; i -= 2) {
28972 var a = i - 1;
28973 var b = i;
28974 if (wndWidth[a] !== 1 || wndWidth[b] !== 1) {
28975 naf[a] = getNAF(coeffs[a], wndWidth[a]);
28976 naf[b] = getNAF(coeffs[b], wndWidth[b]);
28977 max = Math.max(naf[a].length, max);
28978 max = Math.max(naf[b].length, max);
28979 continue;
28980 }
28981
28982 var comb = [
28983 points[a], /* 1 */
28984 null, /* 3 */
28985 null, /* 5 */
28986 points[b] /* 7 */
28987 ];
28988
28989 // Try to avoid Projective points, if possible
28990 if (points[a].y.cmp(points[b].y) === 0) {
28991 comb[1] = points[a].add(points[b]);
28992 comb[2] = points[a].toJ().mixedAdd(points[b].neg());
28993 } else if (points[a].y.cmp(points[b].y.redNeg()) === 0) {
28994 comb[1] = points[a].toJ().mixedAdd(points[b]);
28995 comb[2] = points[a].add(points[b].neg());
28996 } else {
28997 comb[1] = points[a].toJ().mixedAdd(points[b]);
28998 comb[2] = points[a].toJ().mixedAdd(points[b].neg());
28999 }
29000
29001 var index = [
29002 -3, /* -1 -1 */
29003 -1, /* -1 0 */
29004 -5, /* -1 1 */
29005 -7, /* 0 -1 */
29006 0, /* 0 0 */
29007 7, /* 0 1 */
29008 5, /* 1 -1 */
29009 1, /* 1 0 */
29010 3 /* 1 1 */
29011 ];
29012
29013 var jsf = getJSF(coeffs[a], coeffs[b]);
29014 max = Math.max(jsf[0].length, max);
29015 naf[a] = new Array(max);
29016 naf[b] = new Array(max);
29017 for (var j = 0; j < max; j++) {
29018 var ja = jsf[0][j] | 0;
29019 var jb = jsf[1][j] | 0;
29020
29021 naf[a][j] = index[(ja + 1) * 3 + (jb + 1)];
29022 naf[b][j] = 0;
29023 wnd[a] = comb;
29024 }
29025 }
29026
29027 var acc = this.jpoint(null, null, null);
29028 var tmp = this._wnafT4;
29029 for (var i = max; i >= 0; i--) {
29030 var k = 0;
29031
29032 while (i >= 0) {
29033 var zero = true;
29034 for (var j = 0; j < len; j++) {
29035 tmp[j] = naf[j][i] | 0;
29036 if (tmp[j] !== 0)
29037 zero = false;
29038 }
29039 if (!zero)
29040 break;
29041 k++;
29042 i--;
29043 }
29044 if (i >= 0)
29045 k++;
29046 acc = acc.dblp(k);
29047 if (i < 0)
29048 break;
29049
29050 for (var j = 0; j < len; j++) {
29051 var z = tmp[j];
29052 var p;
29053 if (z === 0)
29054 continue;
29055 else if (z > 0)
29056 p = wnd[j][(z - 1) >> 1];
29057 else if (z < 0)
29058 p = wnd[j][(-z - 1) >> 1].neg();
29059
29060 if (p.type === 'affine')
29061 acc = acc.mixedAdd(p);
29062 else
29063 acc = acc.add(p);
29064 }
29065 }
29066 // Zeroify references
29067 for (var i = 0; i < len; i++)
29068 wnd[i] = null;
29069
29070 if (jacobianResult)
29071 return acc;
29072 else
29073 return acc.toP();
29074};
29075
29076function BasePoint(curve, type) {
29077 this.curve = curve;
29078 this.type = type;
29079 this.precomputed = null;
29080}
29081BaseCurve.BasePoint = BasePoint;
29082
29083BasePoint.prototype.eq = function eq(/*other*/) {
29084 throw new Error('Not implemented');
29085};
29086
29087BasePoint.prototype.validate = function validate() {
29088 return this.curve.validate(this);
29089};
29090
29091BaseCurve.prototype.decodePoint = function decodePoint(bytes, enc) {
29092 bytes = utils.toArray(bytes, enc);
29093
29094 var len = this.p.byteLength();
29095
29096 // uncompressed, hybrid-odd, hybrid-even
29097 if ((bytes[0] === 0x04 || bytes[0] === 0x06 || bytes[0] === 0x07) &&
29098 bytes.length - 1 === 2 * len) {
29099 if (bytes[0] === 0x06)
29100 assert(bytes[bytes.length - 1] % 2 === 0);
29101 else if (bytes[0] === 0x07)
29102 assert(bytes[bytes.length - 1] % 2 === 1);
29103
29104 var res = this.point(bytes.slice(1, 1 + len),
29105 bytes.slice(1 + len, 1 + 2 * len));
29106
29107 return res;
29108 } else if ((bytes[0] === 0x02 || bytes[0] === 0x03) &&
29109 bytes.length - 1 === len) {
29110 return this.pointFromX(bytes.slice(1, 1 + len), bytes[0] === 0x03);
29111 }
29112 throw new Error('Unknown point format');
29113};
29114
29115BasePoint.prototype.encodeCompressed = function encodeCompressed(enc) {
29116 return this.encode(enc, true);
29117};
29118
29119BasePoint.prototype._encode = function _encode(compact) {
29120 var len = this.curve.p.byteLength();
29121 var x = this.getX().toArray('be', len);
29122
29123 if (compact)
29124 return [ this.getY().isEven() ? 0x02 : 0x03 ].concat(x);
29125
29126 return [ 0x04 ].concat(x, this.getY().toArray('be', len)) ;
29127};
29128
29129BasePoint.prototype.encode = function encode(enc, compact) {
29130 return utils.encode(this._encode(compact), enc);
29131};
29132
29133BasePoint.prototype.precompute = function precompute(power) {
29134 if (this.precomputed)
29135 return this;
29136
29137 var precomputed = {
29138 doubles: null,
29139 naf: null,
29140 beta: null
29141 };
29142 precomputed.naf = this._getNAFPoints(8);
29143 precomputed.doubles = this._getDoubles(4, power);
29144 precomputed.beta = this._getBeta();
29145 this.precomputed = precomputed;
29146
29147 return this;
29148};
29149
29150BasePoint.prototype._hasDoubles = function _hasDoubles(k) {
29151 if (!this.precomputed)
29152 return false;
29153
29154 var doubles = this.precomputed.doubles;
29155 if (!doubles)
29156 return false;
29157
29158 return doubles.points.length >= Math.ceil((k.bitLength() + 1) / doubles.step);
29159};
29160
29161BasePoint.prototype._getDoubles = function _getDoubles(step, power) {
29162 if (this.precomputed && this.precomputed.doubles)
29163 return this.precomputed.doubles;
29164
29165 var doubles = [ this ];
29166 var acc = this;
29167 for (var i = 0; i < power; i += step) {
29168 for (var j = 0; j < step; j++)
29169 acc = acc.dbl();
29170 doubles.push(acc);
29171 }
29172 return {
29173 step: step,
29174 points: doubles
29175 };
29176};
29177
29178BasePoint.prototype._getNAFPoints = function _getNAFPoints(wnd) {
29179 if (this.precomputed && this.precomputed.naf)
29180 return this.precomputed.naf;
29181
29182 var res = [ this ];
29183 var max = (1 << wnd) - 1;
29184 var dbl = max === 1 ? null : this.dbl();
29185 for (var i = 1; i < max; i++)
29186 res[i] = res[i - 1].add(dbl);
29187 return {
29188 wnd: wnd,
29189 points: res
29190 };
29191};
29192
29193BasePoint.prototype._getBeta = function _getBeta() {
29194 return null;
29195};
29196
29197BasePoint.prototype.dblp = function dblp(k) {
29198 var r = this;
29199 for (var i = 0; i < k; i++)
29200 r = r.dbl();
29201 return r;
29202};
29203
29204},{"../../elliptic":142,"bn.js":80}],144:[function(require,module,exports){
29205'use strict';
29206
29207var curve = require('../curve');
29208var elliptic = require('../../elliptic');
29209var BN = require('bn.js');
29210var inherits = require('inherits');
29211var Base = curve.base;
29212
29213var assert = elliptic.utils.assert;
29214
29215function EdwardsCurve(conf) {
29216 // NOTE: Important as we are creating point in Base.call()
29217 this.twisted = (conf.a | 0) !== 1;
29218 this.mOneA = this.twisted && (conf.a | 0) === -1;
29219 this.extended = this.mOneA;
29220
29221 Base.call(this, 'edwards', conf);
29222
29223 this.a = new BN(conf.a, 16).umod(this.red.m);
29224 this.a = this.a.toRed(this.red);
29225 this.c = new BN(conf.c, 16).toRed(this.red);
29226 this.c2 = this.c.redSqr();
29227 this.d = new BN(conf.d, 16).toRed(this.red);
29228 this.dd = this.d.redAdd(this.d);
29229
29230 assert(!this.twisted || this.c.fromRed().cmpn(1) === 0);
29231 this.oneC = (conf.c | 0) === 1;
29232}
29233inherits(EdwardsCurve, Base);
29234module.exports = EdwardsCurve;
29235
29236EdwardsCurve.prototype._mulA = function _mulA(num) {
29237 if (this.mOneA)
29238 return num.redNeg();
29239 else
29240 return this.a.redMul(num);
29241};
29242
29243EdwardsCurve.prototype._mulC = function _mulC(num) {
29244 if (this.oneC)
29245 return num;
29246 else
29247 return this.c.redMul(num);
29248};
29249
29250// Just for compatibility with Short curve
29251EdwardsCurve.prototype.jpoint = function jpoint(x, y, z, t) {
29252 return this.point(x, y, z, t);
29253};
29254
29255EdwardsCurve.prototype.pointFromX = function pointFromX(x, odd) {
29256 x = new BN(x, 16);
29257 if (!x.red)
29258 x = x.toRed(this.red);
29259
29260 var x2 = x.redSqr();
29261 var rhs = this.c2.redSub(this.a.redMul(x2));
29262 var lhs = this.one.redSub(this.c2.redMul(this.d).redMul(x2));
29263
29264 var y2 = rhs.redMul(lhs.redInvm());
29265 var y = y2.redSqrt();
29266 if (y.redSqr().redSub(y2).cmp(this.zero) !== 0)
29267 throw new Error('invalid point');
29268
29269 var isOdd = y.fromRed().isOdd();
29270 if (odd && !isOdd || !odd && isOdd)
29271 y = y.redNeg();
29272
29273 return this.point(x, y);
29274};
29275
29276EdwardsCurve.prototype.pointFromY = function pointFromY(y, odd) {
29277 y = new BN(y, 16);
29278 if (!y.red)
29279 y = y.toRed(this.red);
29280
29281 // x^2 = (y^2 - c^2) / (c^2 d y^2 - a)
29282 var y2 = y.redSqr();
29283 var lhs = y2.redSub(this.c2);
29284 var rhs = y2.redMul(this.d).redMul(this.c2).redSub(this.a);
29285 var x2 = lhs.redMul(rhs.redInvm());
29286
29287 if (x2.cmp(this.zero) === 0) {
29288 if (odd)
29289 throw new Error('invalid point');
29290 else
29291 return this.point(this.zero, y);
29292 }
29293
29294 var x = x2.redSqrt();
29295 if (x.redSqr().redSub(x2).cmp(this.zero) !== 0)
29296 throw new Error('invalid point');
29297
29298 if (x.fromRed().isOdd() !== odd)
29299 x = x.redNeg();
29300
29301 return this.point(x, y);
29302};
29303
29304EdwardsCurve.prototype.validate = function validate(point) {
29305 if (point.isInfinity())
29306 return true;
29307
29308 // Curve: A * X^2 + Y^2 = C^2 * (1 + D * X^2 * Y^2)
29309 point.normalize();
29310
29311 var x2 = point.x.redSqr();
29312 var y2 = point.y.redSqr();
29313 var lhs = x2.redMul(this.a).redAdd(y2);
29314 var rhs = this.c2.redMul(this.one.redAdd(this.d.redMul(x2).redMul(y2)));
29315
29316 return lhs.cmp(rhs) === 0;
29317};
29318
29319function Point(curve, x, y, z, t) {
29320 Base.BasePoint.call(this, curve, 'projective');
29321 if (x === null && y === null && z === null) {
29322 this.x = this.curve.zero;
29323 this.y = this.curve.one;
29324 this.z = this.curve.one;
29325 this.t = this.curve.zero;
29326 this.zOne = true;
29327 } else {
29328 this.x = new BN(x, 16);
29329 this.y = new BN(y, 16);
29330 this.z = z ? new BN(z, 16) : this.curve.one;
29331 this.t = t && new BN(t, 16);
29332 if (!this.x.red)
29333 this.x = this.x.toRed(this.curve.red);
29334 if (!this.y.red)
29335 this.y = this.y.toRed(this.curve.red);
29336 if (!this.z.red)
29337 this.z = this.z.toRed(this.curve.red);
29338 if (this.t && !this.t.red)
29339 this.t = this.t.toRed(this.curve.red);
29340 this.zOne = this.z === this.curve.one;
29341
29342 // Use extended coordinates
29343 if (this.curve.extended && !this.t) {
29344 this.t = this.x.redMul(this.y);
29345 if (!this.zOne)
29346 this.t = this.t.redMul(this.z.redInvm());
29347 }
29348 }
29349}
29350inherits(Point, Base.BasePoint);
29351
29352EdwardsCurve.prototype.pointFromJSON = function pointFromJSON(obj) {
29353 return Point.fromJSON(this, obj);
29354};
29355
29356EdwardsCurve.prototype.point = function point(x, y, z, t) {
29357 return new Point(this, x, y, z, t);
29358};
29359
29360Point.fromJSON = function fromJSON(curve, obj) {
29361 return new Point(curve, obj[0], obj[1], obj[2]);
29362};
29363
29364Point.prototype.inspect = function inspect() {
29365 if (this.isInfinity())
29366 return '<EC Point Infinity>';
29367 return '<EC Point x: ' + this.x.fromRed().toString(16, 2) +
29368 ' y: ' + this.y.fromRed().toString(16, 2) +
29369 ' z: ' + this.z.fromRed().toString(16, 2) + '>';
29370};
29371
29372Point.prototype.isInfinity = function isInfinity() {
29373 // XXX This code assumes that zero is always zero in red
29374 return this.x.cmpn(0) === 0 &&
29375 (this.y.cmp(this.z) === 0 ||
29376 (this.zOne && this.y.cmp(this.curve.c) === 0));
29377};
29378
29379Point.prototype._extDbl = function _extDbl() {
29380 // hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html
29381 // #doubling-dbl-2008-hwcd
29382 // 4M + 4S
29383
29384 // A = X1^2
29385 var a = this.x.redSqr();
29386 // B = Y1^2
29387 var b = this.y.redSqr();
29388 // C = 2 * Z1^2
29389 var c = this.z.redSqr();
29390 c = c.redIAdd(c);
29391 // D = a * A
29392 var d = this.curve._mulA(a);
29393 // E = (X1 + Y1)^2 - A - B
29394 var e = this.x.redAdd(this.y).redSqr().redISub(a).redISub(b);
29395 // G = D + B
29396 var g = d.redAdd(b);
29397 // F = G - C
29398 var f = g.redSub(c);
29399 // H = D - B
29400 var h = d.redSub(b);
29401 // X3 = E * F
29402 var nx = e.redMul(f);
29403 // Y3 = G * H
29404 var ny = g.redMul(h);
29405 // T3 = E * H
29406 var nt = e.redMul(h);
29407 // Z3 = F * G
29408 var nz = f.redMul(g);
29409 return this.curve.point(nx, ny, nz, nt);
29410};
29411
29412Point.prototype._projDbl = function _projDbl() {
29413 // hyperelliptic.org/EFD/g1p/auto-twisted-projective.html
29414 // #doubling-dbl-2008-bbjlp
29415 // #doubling-dbl-2007-bl
29416 // and others
29417 // Generally 3M + 4S or 2M + 4S
29418
29419 // B = (X1 + Y1)^2
29420 var b = this.x.redAdd(this.y).redSqr();
29421 // C = X1^2
29422 var c = this.x.redSqr();
29423 // D = Y1^2
29424 var d = this.y.redSqr();
29425
29426 var nx;
29427 var ny;
29428 var nz;
29429 if (this.curve.twisted) {
29430 // E = a * C
29431 var e = this.curve._mulA(c);
29432 // F = E + D
29433 var f = e.redAdd(d);
29434 if (this.zOne) {
29435 // X3 = (B - C - D) * (F - 2)
29436 nx = b.redSub(c).redSub(d).redMul(f.redSub(this.curve.two));
29437 // Y3 = F * (E - D)
29438 ny = f.redMul(e.redSub(d));
29439 // Z3 = F^2 - 2 * F
29440 nz = f.redSqr().redSub(f).redSub(f);
29441 } else {
29442 // H = Z1^2
29443 var h = this.z.redSqr();
29444 // J = F - 2 * H
29445 var j = f.redSub(h).redISub(h);
29446 // X3 = (B-C-D)*J
29447 nx = b.redSub(c).redISub(d).redMul(j);
29448 // Y3 = F * (E - D)
29449 ny = f.redMul(e.redSub(d));
29450 // Z3 = F * J
29451 nz = f.redMul(j);
29452 }
29453 } else {
29454 // E = C + D
29455 var e = c.redAdd(d);
29456 // H = (c * Z1)^2
29457 var h = this.curve._mulC(this.z).redSqr();
29458 // J = E - 2 * H
29459 var j = e.redSub(h).redSub(h);
29460 // X3 = c * (B - E) * J
29461 nx = this.curve._mulC(b.redISub(e)).redMul(j);
29462 // Y3 = c * E * (C - D)
29463 ny = this.curve._mulC(e).redMul(c.redISub(d));
29464 // Z3 = E * J
29465 nz = e.redMul(j);
29466 }
29467 return this.curve.point(nx, ny, nz);
29468};
29469
29470Point.prototype.dbl = function dbl() {
29471 if (this.isInfinity())
29472 return this;
29473
29474 // Double in extended coordinates
29475 if (this.curve.extended)
29476 return this._extDbl();
29477 else
29478 return this._projDbl();
29479};
29480
29481Point.prototype._extAdd = function _extAdd(p) {
29482 // hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html
29483 // #addition-add-2008-hwcd-3
29484 // 8M
29485
29486 // A = (Y1 - X1) * (Y2 - X2)
29487 var a = this.y.redSub(this.x).redMul(p.y.redSub(p.x));
29488 // B = (Y1 + X1) * (Y2 + X2)
29489 var b = this.y.redAdd(this.x).redMul(p.y.redAdd(p.x));
29490 // C = T1 * k * T2
29491 var c = this.t.redMul(this.curve.dd).redMul(p.t);
29492 // D = Z1 * 2 * Z2
29493 var d = this.z.redMul(p.z.redAdd(p.z));
29494 // E = B - A
29495 var e = b.redSub(a);
29496 // F = D - C
29497 var f = d.redSub(c);
29498 // G = D + C
29499 var g = d.redAdd(c);
29500 // H = B + A
29501 var h = b.redAdd(a);
29502 // X3 = E * F
29503 var nx = e.redMul(f);
29504 // Y3 = G * H
29505 var ny = g.redMul(h);
29506 // T3 = E * H
29507 var nt = e.redMul(h);
29508 // Z3 = F * G
29509 var nz = f.redMul(g);
29510 return this.curve.point(nx, ny, nz, nt);
29511};
29512
29513Point.prototype._projAdd = function _projAdd(p) {
29514 // hyperelliptic.org/EFD/g1p/auto-twisted-projective.html
29515 // #addition-add-2008-bbjlp
29516 // #addition-add-2007-bl
29517 // 10M + 1S
29518
29519 // A = Z1 * Z2
29520 var a = this.z.redMul(p.z);
29521 // B = A^2
29522 var b = a.redSqr();
29523 // C = X1 * X2
29524 var c = this.x.redMul(p.x);
29525 // D = Y1 * Y2
29526 var d = this.y.redMul(p.y);
29527 // E = d * C * D
29528 var e = this.curve.d.redMul(c).redMul(d);
29529 // F = B - E
29530 var f = b.redSub(e);
29531 // G = B + E
29532 var g = b.redAdd(e);
29533 // X3 = A * F * ((X1 + Y1) * (X2 + Y2) - C - D)
29534 var tmp = this.x.redAdd(this.y).redMul(p.x.redAdd(p.y)).redISub(c).redISub(d);
29535 var nx = a.redMul(f).redMul(tmp);
29536 var ny;
29537 var nz;
29538 if (this.curve.twisted) {
29539 // Y3 = A * G * (D - a * C)
29540 ny = a.redMul(g).redMul(d.redSub(this.curve._mulA(c)));
29541 // Z3 = F * G
29542 nz = f.redMul(g);
29543 } else {
29544 // Y3 = A * G * (D - C)
29545 ny = a.redMul(g).redMul(d.redSub(c));
29546 // Z3 = c * F * G
29547 nz = this.curve._mulC(f).redMul(g);
29548 }
29549 return this.curve.point(nx, ny, nz);
29550};
29551
29552Point.prototype.add = function add(p) {
29553 if (this.isInfinity())
29554 return p;
29555 if (p.isInfinity())
29556 return this;
29557
29558 if (this.curve.extended)
29559 return this._extAdd(p);
29560 else
29561 return this._projAdd(p);
29562};
29563
29564Point.prototype.mul = function mul(k) {
29565 if (this._hasDoubles(k))
29566 return this.curve._fixedNafMul(this, k);
29567 else
29568 return this.curve._wnafMul(this, k);
29569};
29570
29571Point.prototype.mulAdd = function mulAdd(k1, p, k2) {
29572 return this.curve._wnafMulAdd(1, [ this, p ], [ k1, k2 ], 2, false);
29573};
29574
29575Point.prototype.jmulAdd = function jmulAdd(k1, p, k2) {
29576 return this.curve._wnafMulAdd(1, [ this, p ], [ k1, k2 ], 2, true);
29577};
29578
29579Point.prototype.normalize = function normalize() {
29580 if (this.zOne)
29581 return this;
29582
29583 // Normalize coordinates
29584 var zi = this.z.redInvm();
29585 this.x = this.x.redMul(zi);
29586 this.y = this.y.redMul(zi);
29587 if (this.t)
29588 this.t = this.t.redMul(zi);
29589 this.z = this.curve.one;
29590 this.zOne = true;
29591 return this;
29592};
29593
29594Point.prototype.neg = function neg() {
29595 return this.curve.point(this.x.redNeg(),
29596 this.y,
29597 this.z,
29598 this.t && this.t.redNeg());
29599};
29600
29601Point.prototype.getX = function getX() {
29602 this.normalize();
29603 return this.x.fromRed();
29604};
29605
29606Point.prototype.getY = function getY() {
29607 this.normalize();
29608 return this.y.fromRed();
29609};
29610
29611Point.prototype.eq = function eq(other) {
29612 return this === other ||
29613 this.getX().cmp(other.getX()) === 0 &&
29614 this.getY().cmp(other.getY()) === 0;
29615};
29616
29617Point.prototype.eqXToP = function eqXToP(x) {
29618 var rx = x.toRed(this.curve.red).redMul(this.z);
29619 if (this.x.cmp(rx) === 0)
29620 return true;
29621
29622 var xc = x.clone();
29623 var t = this.curve.redN.redMul(this.z);
29624 for (;;) {
29625 xc.iadd(this.curve.n);
29626 if (xc.cmp(this.curve.p) >= 0)
29627 return false;
29628
29629 rx.redIAdd(t);
29630 if (this.x.cmp(rx) === 0)
29631 return true;
29632 }
29633};
29634
29635// Compatibility with BaseCurve
29636Point.prototype.toP = Point.prototype.normalize;
29637Point.prototype.mixedAdd = Point.prototype.add;
29638
29639},{"../../elliptic":142,"../curve":145,"bn.js":80,"inherits":210}],145:[function(require,module,exports){
29640'use strict';
29641
29642var curve = exports;
29643
29644curve.base = require('./base');
29645curve.short = require('./short');
29646curve.mont = require('./mont');
29647curve.edwards = require('./edwards');
29648
29649},{"./base":143,"./edwards":144,"./mont":146,"./short":147}],146:[function(require,module,exports){
29650'use strict';
29651
29652var curve = require('../curve');
29653var BN = require('bn.js');
29654var inherits = require('inherits');
29655var Base = curve.base;
29656
29657var elliptic = require('../../elliptic');
29658var utils = elliptic.utils;
29659
29660function MontCurve(conf) {
29661 Base.call(this, 'mont', conf);
29662
29663 this.a = new BN(conf.a, 16).toRed(this.red);
29664 this.b = new BN(conf.b, 16).toRed(this.red);
29665 this.i4 = new BN(4).toRed(this.red).redInvm();
29666 this.two = new BN(2).toRed(this.red);
29667 this.a24 = this.i4.redMul(this.a.redAdd(this.two));
29668}
29669inherits(MontCurve, Base);
29670module.exports = MontCurve;
29671
29672MontCurve.prototype.validate = function validate(point) {
29673 var x = point.normalize().x;
29674 var x2 = x.redSqr();
29675 var rhs = x2.redMul(x).redAdd(x2.redMul(this.a)).redAdd(x);
29676 var y = rhs.redSqrt();
29677
29678 return y.redSqr().cmp(rhs) === 0;
29679};
29680
29681function Point(curve, x, z) {
29682 Base.BasePoint.call(this, curve, 'projective');
29683 if (x === null && z === null) {
29684 this.x = this.curve.one;
29685 this.z = this.curve.zero;
29686 } else {
29687 this.x = new BN(x, 16);
29688 this.z = new BN(z, 16);
29689 if (!this.x.red)
29690 this.x = this.x.toRed(this.curve.red);
29691 if (!this.z.red)
29692 this.z = this.z.toRed(this.curve.red);
29693 }
29694}
29695inherits(Point, Base.BasePoint);
29696
29697MontCurve.prototype.decodePoint = function decodePoint(bytes, enc) {
29698 return this.point(utils.toArray(bytes, enc), 1);
29699};
29700
29701MontCurve.prototype.point = function point(x, z) {
29702 return new Point(this, x, z);
29703};
29704
29705MontCurve.prototype.pointFromJSON = function pointFromJSON(obj) {
29706 return Point.fromJSON(this, obj);
29707};
29708
29709Point.prototype.precompute = function precompute() {
29710 // No-op
29711};
29712
29713Point.prototype._encode = function _encode() {
29714 return this.getX().toArray('be', this.curve.p.byteLength());
29715};
29716
29717Point.fromJSON = function fromJSON(curve, obj) {
29718 return new Point(curve, obj[0], obj[1] || curve.one);
29719};
29720
29721Point.prototype.inspect = function inspect() {
29722 if (this.isInfinity())
29723 return '<EC Point Infinity>';
29724 return '<EC Point x: ' + this.x.fromRed().toString(16, 2) +
29725 ' z: ' + this.z.fromRed().toString(16, 2) + '>';
29726};
29727
29728Point.prototype.isInfinity = function isInfinity() {
29729 // XXX This code assumes that zero is always zero in red
29730 return this.z.cmpn(0) === 0;
29731};
29732
29733Point.prototype.dbl = function dbl() {
29734 // http://hyperelliptic.org/EFD/g1p/auto-montgom-xz.html#doubling-dbl-1987-m-3
29735 // 2M + 2S + 4A
29736
29737 // A = X1 + Z1
29738 var a = this.x.redAdd(this.z);
29739 // AA = A^2
29740 var aa = a.redSqr();
29741 // B = X1 - Z1
29742 var b = this.x.redSub(this.z);
29743 // BB = B^2
29744 var bb = b.redSqr();
29745 // C = AA - BB
29746 var c = aa.redSub(bb);
29747 // X3 = AA * BB
29748 var nx = aa.redMul(bb);
29749 // Z3 = C * (BB + A24 * C)
29750 var nz = c.redMul(bb.redAdd(this.curve.a24.redMul(c)));
29751 return this.curve.point(nx, nz);
29752};
29753
29754Point.prototype.add = function add() {
29755 throw new Error('Not supported on Montgomery curve');
29756};
29757
29758Point.prototype.diffAdd = function diffAdd(p, diff) {
29759 // http://hyperelliptic.org/EFD/g1p/auto-montgom-xz.html#diffadd-dadd-1987-m-3
29760 // 4M + 2S + 6A
29761
29762 // A = X2 + Z2
29763 var a = this.x.redAdd(this.z);
29764 // B = X2 - Z2
29765 var b = this.x.redSub(this.z);
29766 // C = X3 + Z3
29767 var c = p.x.redAdd(p.z);
29768 // D = X3 - Z3
29769 var d = p.x.redSub(p.z);
29770 // DA = D * A
29771 var da = d.redMul(a);
29772 // CB = C * B
29773 var cb = c.redMul(b);
29774 // X5 = Z1 * (DA + CB)^2
29775 var nx = diff.z.redMul(da.redAdd(cb).redSqr());
29776 // Z5 = X1 * (DA - CB)^2
29777 var nz = diff.x.redMul(da.redISub(cb).redSqr());
29778 return this.curve.point(nx, nz);
29779};
29780
29781Point.prototype.mul = function mul(k) {
29782 var t = k.clone();
29783 var a = this; // (N / 2) * Q + Q
29784 var b = this.curve.point(null, null); // (N / 2) * Q
29785 var c = this; // Q
29786
29787 for (var bits = []; t.cmpn(0) !== 0; t.iushrn(1))
29788 bits.push(t.andln(1));
29789
29790 for (var i = bits.length - 1; i >= 0; i--) {
29791 if (bits[i] === 0) {
29792 // N * Q + Q = ((N / 2) * Q + Q)) + (N / 2) * Q
29793 a = a.diffAdd(b, c);
29794 // N * Q = 2 * ((N / 2) * Q + Q))
29795 b = b.dbl();
29796 } else {
29797 // N * Q = ((N / 2) * Q + Q) + ((N / 2) * Q)
29798 b = a.diffAdd(b, c);
29799 // N * Q + Q = 2 * ((N / 2) * Q + Q)
29800 a = a.dbl();
29801 }
29802 }
29803 return b;
29804};
29805
29806Point.prototype.mulAdd = function mulAdd() {
29807 throw new Error('Not supported on Montgomery curve');
29808};
29809
29810Point.prototype.jumlAdd = function jumlAdd() {
29811 throw new Error('Not supported on Montgomery curve');
29812};
29813
29814Point.prototype.eq = function eq(other) {
29815 return this.getX().cmp(other.getX()) === 0;
29816};
29817
29818Point.prototype.normalize = function normalize() {
29819 this.x = this.x.redMul(this.z.redInvm());
29820 this.z = this.curve.one;
29821 return this;
29822};
29823
29824Point.prototype.getX = function getX() {
29825 // Normalize coordinates
29826 this.normalize();
29827
29828 return this.x.fromRed();
29829};
29830
29831},{"../../elliptic":142,"../curve":145,"bn.js":80,"inherits":210}],147:[function(require,module,exports){
29832'use strict';
29833
29834var curve = require('../curve');
29835var elliptic = require('../../elliptic');
29836var BN = require('bn.js');
29837var inherits = require('inherits');
29838var Base = curve.base;
29839
29840var assert = elliptic.utils.assert;
29841
29842function ShortCurve(conf) {
29843 Base.call(this, 'short', conf);
29844
29845 this.a = new BN(conf.a, 16).toRed(this.red);
29846 this.b = new BN(conf.b, 16).toRed(this.red);
29847 this.tinv = this.two.redInvm();
29848
29849 this.zeroA = this.a.fromRed().cmpn(0) === 0;
29850 this.threeA = this.a.fromRed().sub(this.p).cmpn(-3) === 0;
29851
29852 // If the curve is endomorphic, precalculate beta and lambda
29853 this.endo = this._getEndomorphism(conf);
29854 this._endoWnafT1 = new Array(4);
29855 this._endoWnafT2 = new Array(4);
29856}
29857inherits(ShortCurve, Base);
29858module.exports = ShortCurve;
29859
29860ShortCurve.prototype._getEndomorphism = function _getEndomorphism(conf) {
29861 // No efficient endomorphism
29862 if (!this.zeroA || !this.g || !this.n || this.p.modn(3) !== 1)
29863 return;
29864
29865 // Compute beta and lambda, that lambda * P = (beta * Px; Py)
29866 var beta;
29867 var lambda;
29868 if (conf.beta) {
29869 beta = new BN(conf.beta, 16).toRed(this.red);
29870 } else {
29871 var betas = this._getEndoRoots(this.p);
29872 // Choose the smallest beta
29873 beta = betas[0].cmp(betas[1]) < 0 ? betas[0] : betas[1];
29874 beta = beta.toRed(this.red);
29875 }
29876 if (conf.lambda) {
29877 lambda = new BN(conf.lambda, 16);
29878 } else {
29879 // Choose the lambda that is matching selected beta
29880 var lambdas = this._getEndoRoots(this.n);
29881 if (this.g.mul(lambdas[0]).x.cmp(this.g.x.redMul(beta)) === 0) {
29882 lambda = lambdas[0];
29883 } else {
29884 lambda = lambdas[1];
29885 assert(this.g.mul(lambda).x.cmp(this.g.x.redMul(beta)) === 0);
29886 }
29887 }
29888
29889 // Get basis vectors, used for balanced length-two representation
29890 var basis;
29891 if (conf.basis) {
29892 basis = conf.basis.map(function(vec) {
29893 return {
29894 a: new BN(vec.a, 16),
29895 b: new BN(vec.b, 16)
29896 };
29897 });
29898 } else {
29899 basis = this._getEndoBasis(lambda);
29900 }
29901
29902 return {
29903 beta: beta,
29904 lambda: lambda,
29905 basis: basis
29906 };
29907};
29908
29909ShortCurve.prototype._getEndoRoots = function _getEndoRoots(num) {
29910 // Find roots of for x^2 + x + 1 in F
29911 // Root = (-1 +- Sqrt(-3)) / 2
29912 //
29913 var red = num === this.p ? this.red : BN.mont(num);
29914 var tinv = new BN(2).toRed(red).redInvm();
29915 var ntinv = tinv.redNeg();
29916
29917 var s = new BN(3).toRed(red).redNeg().redSqrt().redMul(tinv);
29918
29919 var l1 = ntinv.redAdd(s).fromRed();
29920 var l2 = ntinv.redSub(s).fromRed();
29921 return [ l1, l2 ];
29922};
29923
29924ShortCurve.prototype._getEndoBasis = function _getEndoBasis(lambda) {
29925 // aprxSqrt >= sqrt(this.n)
29926 var aprxSqrt = this.n.ushrn(Math.floor(this.n.bitLength() / 2));
29927
29928 // 3.74
29929 // Run EGCD, until r(L + 1) < aprxSqrt
29930 var u = lambda;
29931 var v = this.n.clone();
29932 var x1 = new BN(1);
29933 var y1 = new BN(0);
29934 var x2 = new BN(0);
29935 var y2 = new BN(1);
29936
29937 // NOTE: all vectors are roots of: a + b * lambda = 0 (mod n)
29938 var a0;
29939 var b0;
29940 // First vector
29941 var a1;
29942 var b1;
29943 // Second vector
29944 var a2;
29945 var b2;
29946
29947 var prevR;
29948 var i = 0;
29949 var r;
29950 var x;
29951 while (u.cmpn(0) !== 0) {
29952 var q = v.div(u);
29953 r = v.sub(q.mul(u));
29954 x = x2.sub(q.mul(x1));
29955 var y = y2.sub(q.mul(y1));
29956
29957 if (!a1 && r.cmp(aprxSqrt) < 0) {
29958 a0 = prevR.neg();
29959 b0 = x1;
29960 a1 = r.neg();
29961 b1 = x;
29962 } else if (a1 && ++i === 2) {
29963 break;
29964 }
29965 prevR = r;
29966
29967 v = u;
29968 u = r;
29969 x2 = x1;
29970 x1 = x;
29971 y2 = y1;
29972 y1 = y;
29973 }
29974 a2 = r.neg();
29975 b2 = x;
29976
29977 var len1 = a1.sqr().add(b1.sqr());
29978 var len2 = a2.sqr().add(b2.sqr());
29979 if (len2.cmp(len1) >= 0) {
29980 a2 = a0;
29981 b2 = b0;
29982 }
29983
29984 // Normalize signs
29985 if (a1.negative) {
29986 a1 = a1.neg();
29987 b1 = b1.neg();
29988 }
29989 if (a2.negative) {
29990 a2 = a2.neg();
29991 b2 = b2.neg();
29992 }
29993
29994 return [
29995 { a: a1, b: b1 },
29996 { a: a2, b: b2 }
29997 ];
29998};
29999
30000ShortCurve.prototype._endoSplit = function _endoSplit(k) {
30001 var basis = this.endo.basis;
30002 var v1 = basis[0];
30003 var v2 = basis[1];
30004
30005 var c1 = v2.b.mul(k).divRound(this.n);
30006 var c2 = v1.b.neg().mul(k).divRound(this.n);
30007
30008 var p1 = c1.mul(v1.a);
30009 var p2 = c2.mul(v2.a);
30010 var q1 = c1.mul(v1.b);
30011 var q2 = c2.mul(v2.b);
30012
30013 // Calculate answer
30014 var k1 = k.sub(p1).sub(p2);
30015 var k2 = q1.add(q2).neg();
30016 return { k1: k1, k2: k2 };
30017};
30018
30019ShortCurve.prototype.pointFromX = function pointFromX(x, odd) {
30020 x = new BN(x, 16);
30021 if (!x.red)
30022 x = x.toRed(this.red);
30023
30024 var y2 = x.redSqr().redMul(x).redIAdd(x.redMul(this.a)).redIAdd(this.b);
30025 var y = y2.redSqrt();
30026 if (y.redSqr().redSub(y2).cmp(this.zero) !== 0)
30027 throw new Error('invalid point');
30028
30029 // XXX Is there any way to tell if the number is odd without converting it
30030 // to non-red form?
30031 var isOdd = y.fromRed().isOdd();
30032 if (odd && !isOdd || !odd && isOdd)
30033 y = y.redNeg();
30034
30035 return this.point(x, y);
30036};
30037
30038ShortCurve.prototype.validate = function validate(point) {
30039 if (point.inf)
30040 return true;
30041
30042 var x = point.x;
30043 var y = point.y;
30044
30045 var ax = this.a.redMul(x);
30046 var rhs = x.redSqr().redMul(x).redIAdd(ax).redIAdd(this.b);
30047 return y.redSqr().redISub(rhs).cmpn(0) === 0;
30048};
30049
30050ShortCurve.prototype._endoWnafMulAdd =
30051 function _endoWnafMulAdd(points, coeffs, jacobianResult) {
30052 var npoints = this._endoWnafT1;
30053 var ncoeffs = this._endoWnafT2;
30054 for (var i = 0; i < points.length; i++) {
30055 var split = this._endoSplit(coeffs[i]);
30056 var p = points[i];
30057 var beta = p._getBeta();
30058
30059 if (split.k1.negative) {
30060 split.k1.ineg();
30061 p = p.neg(true);
30062 }
30063 if (split.k2.negative) {
30064 split.k2.ineg();
30065 beta = beta.neg(true);
30066 }
30067
30068 npoints[i * 2] = p;
30069 npoints[i * 2 + 1] = beta;
30070 ncoeffs[i * 2] = split.k1;
30071 ncoeffs[i * 2 + 1] = split.k2;
30072 }
30073 var res = this._wnafMulAdd(1, npoints, ncoeffs, i * 2, jacobianResult);
30074
30075 // Clean-up references to points and coefficients
30076 for (var j = 0; j < i * 2; j++) {
30077 npoints[j] = null;
30078 ncoeffs[j] = null;
30079 }
30080 return res;
30081};
30082
30083function Point(curve, x, y, isRed) {
30084 Base.BasePoint.call(this, curve, 'affine');
30085 if (x === null && y === null) {
30086 this.x = null;
30087 this.y = null;
30088 this.inf = true;
30089 } else {
30090 this.x = new BN(x, 16);
30091 this.y = new BN(y, 16);
30092 // Force redgomery representation when loading from JSON
30093 if (isRed) {
30094 this.x.forceRed(this.curve.red);
30095 this.y.forceRed(this.curve.red);
30096 }
30097 if (!this.x.red)
30098 this.x = this.x.toRed(this.curve.red);
30099 if (!this.y.red)
30100 this.y = this.y.toRed(this.curve.red);
30101 this.inf = false;
30102 }
30103}
30104inherits(Point, Base.BasePoint);
30105
30106ShortCurve.prototype.point = function point(x, y, isRed) {
30107 return new Point(this, x, y, isRed);
30108};
30109
30110ShortCurve.prototype.pointFromJSON = function pointFromJSON(obj, red) {
30111 return Point.fromJSON(this, obj, red);
30112};
30113
30114Point.prototype._getBeta = function _getBeta() {
30115 if (!this.curve.endo)
30116 return;
30117
30118 var pre = this.precomputed;
30119 if (pre && pre.beta)
30120 return pre.beta;
30121
30122 var beta = this.curve.point(this.x.redMul(this.curve.endo.beta), this.y);
30123 if (pre) {
30124 var curve = this.curve;
30125 var endoMul = function(p) {
30126 return curve.point(p.x.redMul(curve.endo.beta), p.y);
30127 };
30128 pre.beta = beta;
30129 beta.precomputed = {
30130 beta: null,
30131 naf: pre.naf && {
30132 wnd: pre.naf.wnd,
30133 points: pre.naf.points.map(endoMul)
30134 },
30135 doubles: pre.doubles && {
30136 step: pre.doubles.step,
30137 points: pre.doubles.points.map(endoMul)
30138 }
30139 };
30140 }
30141 return beta;
30142};
30143
30144Point.prototype.toJSON = function toJSON() {
30145 if (!this.precomputed)
30146 return [ this.x, this.y ];
30147
30148 return [ this.x, this.y, this.precomputed && {
30149 doubles: this.precomputed.doubles && {
30150 step: this.precomputed.doubles.step,
30151 points: this.precomputed.doubles.points.slice(1)
30152 },
30153 naf: this.precomputed.naf && {
30154 wnd: this.precomputed.naf.wnd,
30155 points: this.precomputed.naf.points.slice(1)
30156 }
30157 } ];
30158};
30159
30160Point.fromJSON = function fromJSON(curve, obj, red) {
30161 if (typeof obj === 'string')
30162 obj = JSON.parse(obj);
30163 var res = curve.point(obj[0], obj[1], red);
30164 if (!obj[2])
30165 return res;
30166
30167 function obj2point(obj) {
30168 return curve.point(obj[0], obj[1], red);
30169 }
30170
30171 var pre = obj[2];
30172 res.precomputed = {
30173 beta: null,
30174 doubles: pre.doubles && {
30175 step: pre.doubles.step,
30176 points: [ res ].concat(pre.doubles.points.map(obj2point))
30177 },
30178 naf: pre.naf && {
30179 wnd: pre.naf.wnd,
30180 points: [ res ].concat(pre.naf.points.map(obj2point))
30181 }
30182 };
30183 return res;
30184};
30185
30186Point.prototype.inspect = function inspect() {
30187 if (this.isInfinity())
30188 return '<EC Point Infinity>';
30189 return '<EC Point x: ' + this.x.fromRed().toString(16, 2) +
30190 ' y: ' + this.y.fromRed().toString(16, 2) + '>';
30191};
30192
30193Point.prototype.isInfinity = function isInfinity() {
30194 return this.inf;
30195};
30196
30197Point.prototype.add = function add(p) {
30198 // O + P = P
30199 if (this.inf)
30200 return p;
30201
30202 // P + O = P
30203 if (p.inf)
30204 return this;
30205
30206 // P + P = 2P
30207 if (this.eq(p))
30208 return this.dbl();
30209
30210 // P + (-P) = O
30211 if (this.neg().eq(p))
30212 return this.curve.point(null, null);
30213
30214 // P + Q = O
30215 if (this.x.cmp(p.x) === 0)
30216 return this.curve.point(null, null);
30217
30218 var c = this.y.redSub(p.y);
30219 if (c.cmpn(0) !== 0)
30220 c = c.redMul(this.x.redSub(p.x).redInvm());
30221 var nx = c.redSqr().redISub(this.x).redISub(p.x);
30222 var ny = c.redMul(this.x.redSub(nx)).redISub(this.y);
30223 return this.curve.point(nx, ny);
30224};
30225
30226Point.prototype.dbl = function dbl() {
30227 if (this.inf)
30228 return this;
30229
30230 // 2P = O
30231 var ys1 = this.y.redAdd(this.y);
30232 if (ys1.cmpn(0) === 0)
30233 return this.curve.point(null, null);
30234
30235 var a = this.curve.a;
30236
30237 var x2 = this.x.redSqr();
30238 var dyinv = ys1.redInvm();
30239 var c = x2.redAdd(x2).redIAdd(x2).redIAdd(a).redMul(dyinv);
30240
30241 var nx = c.redSqr().redISub(this.x.redAdd(this.x));
30242 var ny = c.redMul(this.x.redSub(nx)).redISub(this.y);
30243 return this.curve.point(nx, ny);
30244};
30245
30246Point.prototype.getX = function getX() {
30247 return this.x.fromRed();
30248};
30249
30250Point.prototype.getY = function getY() {
30251 return this.y.fromRed();
30252};
30253
30254Point.prototype.mul = function mul(k) {
30255 k = new BN(k, 16);
30256
30257 if (this._hasDoubles(k))
30258 return this.curve._fixedNafMul(this, k);
30259 else if (this.curve.endo)
30260 return this.curve._endoWnafMulAdd([ this ], [ k ]);
30261 else
30262 return this.curve._wnafMul(this, k);
30263};
30264
30265Point.prototype.mulAdd = function mulAdd(k1, p2, k2) {
30266 var points = [ this, p2 ];
30267 var coeffs = [ k1, k2 ];
30268 if (this.curve.endo)
30269 return this.curve._endoWnafMulAdd(points, coeffs);
30270 else
30271 return this.curve._wnafMulAdd(1, points, coeffs, 2);
30272};
30273
30274Point.prototype.jmulAdd = function jmulAdd(k1, p2, k2) {
30275 var points = [ this, p2 ];
30276 var coeffs = [ k1, k2 ];
30277 if (this.curve.endo)
30278 return this.curve._endoWnafMulAdd(points, coeffs, true);
30279 else
30280 return this.curve._wnafMulAdd(1, points, coeffs, 2, true);
30281};
30282
30283Point.prototype.eq = function eq(p) {
30284 return this === p ||
30285 this.inf === p.inf &&
30286 (this.inf || this.x.cmp(p.x) === 0 && this.y.cmp(p.y) === 0);
30287};
30288
30289Point.prototype.neg = function neg(_precompute) {
30290 if (this.inf)
30291 return this;
30292
30293 var res = this.curve.point(this.x, this.y.redNeg());
30294 if (_precompute && this.precomputed) {
30295 var pre = this.precomputed;
30296 var negate = function(p) {
30297 return p.neg();
30298 };
30299 res.precomputed = {
30300 naf: pre.naf && {
30301 wnd: pre.naf.wnd,
30302 points: pre.naf.points.map(negate)
30303 },
30304 doubles: pre.doubles && {
30305 step: pre.doubles.step,
30306 points: pre.doubles.points.map(negate)
30307 }
30308 };
30309 }
30310 return res;
30311};
30312
30313Point.prototype.toJ = function toJ() {
30314 if (this.inf)
30315 return this.curve.jpoint(null, null, null);
30316
30317 var res = this.curve.jpoint(this.x, this.y, this.curve.one);
30318 return res;
30319};
30320
30321function JPoint(curve, x, y, z) {
30322 Base.BasePoint.call(this, curve, 'jacobian');
30323 if (x === null && y === null && z === null) {
30324 this.x = this.curve.one;
30325 this.y = this.curve.one;
30326 this.z = new BN(0);
30327 } else {
30328 this.x = new BN(x, 16);
30329 this.y = new BN(y, 16);
30330 this.z = new BN(z, 16);
30331 }
30332 if (!this.x.red)
30333 this.x = this.x.toRed(this.curve.red);
30334 if (!this.y.red)
30335 this.y = this.y.toRed(this.curve.red);
30336 if (!this.z.red)
30337 this.z = this.z.toRed(this.curve.red);
30338
30339 this.zOne = this.z === this.curve.one;
30340}
30341inherits(JPoint, Base.BasePoint);
30342
30343ShortCurve.prototype.jpoint = function jpoint(x, y, z) {
30344 return new JPoint(this, x, y, z);
30345};
30346
30347JPoint.prototype.toP = function toP() {
30348 if (this.isInfinity())
30349 return this.curve.point(null, null);
30350
30351 var zinv = this.z.redInvm();
30352 var zinv2 = zinv.redSqr();
30353 var ax = this.x.redMul(zinv2);
30354 var ay = this.y.redMul(zinv2).redMul(zinv);
30355
30356 return this.curve.point(ax, ay);
30357};
30358
30359JPoint.prototype.neg = function neg() {
30360 return this.curve.jpoint(this.x, this.y.redNeg(), this.z);
30361};
30362
30363JPoint.prototype.add = function add(p) {
30364 // O + P = P
30365 if (this.isInfinity())
30366 return p;
30367
30368 // P + O = P
30369 if (p.isInfinity())
30370 return this;
30371
30372 // 12M + 4S + 7A
30373 var pz2 = p.z.redSqr();
30374 var z2 = this.z.redSqr();
30375 var u1 = this.x.redMul(pz2);
30376 var u2 = p.x.redMul(z2);
30377 var s1 = this.y.redMul(pz2.redMul(p.z));
30378 var s2 = p.y.redMul(z2.redMul(this.z));
30379
30380 var h = u1.redSub(u2);
30381 var r = s1.redSub(s2);
30382 if (h.cmpn(0) === 0) {
30383 if (r.cmpn(0) !== 0)
30384 return this.curve.jpoint(null, null, null);
30385 else
30386 return this.dbl();
30387 }
30388
30389 var h2 = h.redSqr();
30390 var h3 = h2.redMul(h);
30391 var v = u1.redMul(h2);
30392
30393 var nx = r.redSqr().redIAdd(h3).redISub(v).redISub(v);
30394 var ny = r.redMul(v.redISub(nx)).redISub(s1.redMul(h3));
30395 var nz = this.z.redMul(p.z).redMul(h);
30396
30397 return this.curve.jpoint(nx, ny, nz);
30398};
30399
30400JPoint.prototype.mixedAdd = function mixedAdd(p) {
30401 // O + P = P
30402 if (this.isInfinity())
30403 return p.toJ();
30404
30405 // P + O = P
30406 if (p.isInfinity())
30407 return this;
30408
30409 // 8M + 3S + 7A
30410 var z2 = this.z.redSqr();
30411 var u1 = this.x;
30412 var u2 = p.x.redMul(z2);
30413 var s1 = this.y;
30414 var s2 = p.y.redMul(z2).redMul(this.z);
30415
30416 var h = u1.redSub(u2);
30417 var r = s1.redSub(s2);
30418 if (h.cmpn(0) === 0) {
30419 if (r.cmpn(0) !== 0)
30420 return this.curve.jpoint(null, null, null);
30421 else
30422 return this.dbl();
30423 }
30424
30425 var h2 = h.redSqr();
30426 var h3 = h2.redMul(h);
30427 var v = u1.redMul(h2);
30428
30429 var nx = r.redSqr().redIAdd(h3).redISub(v).redISub(v);
30430 var ny = r.redMul(v.redISub(nx)).redISub(s1.redMul(h3));
30431 var nz = this.z.redMul(h);
30432
30433 return this.curve.jpoint(nx, ny, nz);
30434};
30435
30436JPoint.prototype.dblp = function dblp(pow) {
30437 if (pow === 0)
30438 return this;
30439 if (this.isInfinity())
30440 return this;
30441 if (!pow)
30442 return this.dbl();
30443
30444 if (this.curve.zeroA || this.curve.threeA) {
30445 var r = this;
30446 for (var i = 0; i < pow; i++)
30447 r = r.dbl();
30448 return r;
30449 }
30450
30451 // 1M + 2S + 1A + N * (4S + 5M + 8A)
30452 // N = 1 => 6M + 6S + 9A
30453 var a = this.curve.a;
30454 var tinv = this.curve.tinv;
30455
30456 var jx = this.x;
30457 var jy = this.y;
30458 var jz = this.z;
30459 var jz4 = jz.redSqr().redSqr();
30460
30461 // Reuse results
30462 var jyd = jy.redAdd(jy);
30463 for (var i = 0; i < pow; i++) {
30464 var jx2 = jx.redSqr();
30465 var jyd2 = jyd.redSqr();
30466 var jyd4 = jyd2.redSqr();
30467 var c = jx2.redAdd(jx2).redIAdd(jx2).redIAdd(a.redMul(jz4));
30468
30469 var t1 = jx.redMul(jyd2);
30470 var nx = c.redSqr().redISub(t1.redAdd(t1));
30471 var t2 = t1.redISub(nx);
30472 var dny = c.redMul(t2);
30473 dny = dny.redIAdd(dny).redISub(jyd4);
30474 var nz = jyd.redMul(jz);
30475 if (i + 1 < pow)
30476 jz4 = jz4.redMul(jyd4);
30477
30478 jx = nx;
30479 jz = nz;
30480 jyd = dny;
30481 }
30482
30483 return this.curve.jpoint(jx, jyd.redMul(tinv), jz);
30484};
30485
30486JPoint.prototype.dbl = function dbl() {
30487 if (this.isInfinity())
30488 return this;
30489
30490 if (this.curve.zeroA)
30491 return this._zeroDbl();
30492 else if (this.curve.threeA)
30493 return this._threeDbl();
30494 else
30495 return this._dbl();
30496};
30497
30498JPoint.prototype._zeroDbl = function _zeroDbl() {
30499 var nx;
30500 var ny;
30501 var nz;
30502 // Z = 1
30503 if (this.zOne) {
30504 // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html
30505 // #doubling-mdbl-2007-bl
30506 // 1M + 5S + 14A
30507
30508 // XX = X1^2
30509 var xx = this.x.redSqr();
30510 // YY = Y1^2
30511 var yy = this.y.redSqr();
30512 // YYYY = YY^2
30513 var yyyy = yy.redSqr();
30514 // S = 2 * ((X1 + YY)^2 - XX - YYYY)
30515 var s = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy);
30516 s = s.redIAdd(s);
30517 // M = 3 * XX + a; a = 0
30518 var m = xx.redAdd(xx).redIAdd(xx);
30519 // T = M ^ 2 - 2*S
30520 var t = m.redSqr().redISub(s).redISub(s);
30521
30522 // 8 * YYYY
30523 var yyyy8 = yyyy.redIAdd(yyyy);
30524 yyyy8 = yyyy8.redIAdd(yyyy8);
30525 yyyy8 = yyyy8.redIAdd(yyyy8);
30526
30527 // X3 = T
30528 nx = t;
30529 // Y3 = M * (S - T) - 8 * YYYY
30530 ny = m.redMul(s.redISub(t)).redISub(yyyy8);
30531 // Z3 = 2*Y1
30532 nz = this.y.redAdd(this.y);
30533 } else {
30534 // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html
30535 // #doubling-dbl-2009-l
30536 // 2M + 5S + 13A
30537
30538 // A = X1^2
30539 var a = this.x.redSqr();
30540 // B = Y1^2
30541 var b = this.y.redSqr();
30542 // C = B^2
30543 var c = b.redSqr();
30544 // D = 2 * ((X1 + B)^2 - A - C)
30545 var d = this.x.redAdd(b).redSqr().redISub(a).redISub(c);
30546 d = d.redIAdd(d);
30547 // E = 3 * A
30548 var e = a.redAdd(a).redIAdd(a);
30549 // F = E^2
30550 var f = e.redSqr();
30551
30552 // 8 * C
30553 var c8 = c.redIAdd(c);
30554 c8 = c8.redIAdd(c8);
30555 c8 = c8.redIAdd(c8);
30556
30557 // X3 = F - 2 * D
30558 nx = f.redISub(d).redISub(d);
30559 // Y3 = E * (D - X3) - 8 * C
30560 ny = e.redMul(d.redISub(nx)).redISub(c8);
30561 // Z3 = 2 * Y1 * Z1
30562 nz = this.y.redMul(this.z);
30563 nz = nz.redIAdd(nz);
30564 }
30565
30566 return this.curve.jpoint(nx, ny, nz);
30567};
30568
30569JPoint.prototype._threeDbl = function _threeDbl() {
30570 var nx;
30571 var ny;
30572 var nz;
30573 // Z = 1
30574 if (this.zOne) {
30575 // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-3.html
30576 // #doubling-mdbl-2007-bl
30577 // 1M + 5S + 15A
30578
30579 // XX = X1^2
30580 var xx = this.x.redSqr();
30581 // YY = Y1^2
30582 var yy = this.y.redSqr();
30583 // YYYY = YY^2
30584 var yyyy = yy.redSqr();
30585 // S = 2 * ((X1 + YY)^2 - XX - YYYY)
30586 var s = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy);
30587 s = s.redIAdd(s);
30588 // M = 3 * XX + a
30589 var m = xx.redAdd(xx).redIAdd(xx).redIAdd(this.curve.a);
30590 // T = M^2 - 2 * S
30591 var t = m.redSqr().redISub(s).redISub(s);
30592 // X3 = T
30593 nx = t;
30594 // Y3 = M * (S - T) - 8 * YYYY
30595 var yyyy8 = yyyy.redIAdd(yyyy);
30596 yyyy8 = yyyy8.redIAdd(yyyy8);
30597 yyyy8 = yyyy8.redIAdd(yyyy8);
30598 ny = m.redMul(s.redISub(t)).redISub(yyyy8);
30599 // Z3 = 2 * Y1
30600 nz = this.y.redAdd(this.y);
30601 } else {
30602 // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-3.html#doubling-dbl-2001-b
30603 // 3M + 5S
30604
30605 // delta = Z1^2
30606 var delta = this.z.redSqr();
30607 // gamma = Y1^2
30608 var gamma = this.y.redSqr();
30609 // beta = X1 * gamma
30610 var beta = this.x.redMul(gamma);
30611 // alpha = 3 * (X1 - delta) * (X1 + delta)
30612 var alpha = this.x.redSub(delta).redMul(this.x.redAdd(delta));
30613 alpha = alpha.redAdd(alpha).redIAdd(alpha);
30614 // X3 = alpha^2 - 8 * beta
30615 var beta4 = beta.redIAdd(beta);
30616 beta4 = beta4.redIAdd(beta4);
30617 var beta8 = beta4.redAdd(beta4);
30618 nx = alpha.redSqr().redISub(beta8);
30619 // Z3 = (Y1 + Z1)^2 - gamma - delta
30620 nz = this.y.redAdd(this.z).redSqr().redISub(gamma).redISub(delta);
30621 // Y3 = alpha * (4 * beta - X3) - 8 * gamma^2
30622 var ggamma8 = gamma.redSqr();
30623 ggamma8 = ggamma8.redIAdd(ggamma8);
30624 ggamma8 = ggamma8.redIAdd(ggamma8);
30625 ggamma8 = ggamma8.redIAdd(ggamma8);
30626 ny = alpha.redMul(beta4.redISub(nx)).redISub(ggamma8);
30627 }
30628
30629 return this.curve.jpoint(nx, ny, nz);
30630};
30631
30632JPoint.prototype._dbl = function _dbl() {
30633 var a = this.curve.a;
30634
30635 // 4M + 6S + 10A
30636 var jx = this.x;
30637 var jy = this.y;
30638 var jz = this.z;
30639 var jz4 = jz.redSqr().redSqr();
30640
30641 var jx2 = jx.redSqr();
30642 var jy2 = jy.redSqr();
30643
30644 var c = jx2.redAdd(jx2).redIAdd(jx2).redIAdd(a.redMul(jz4));
30645
30646 var jxd4 = jx.redAdd(jx);
30647 jxd4 = jxd4.redIAdd(jxd4);
30648 var t1 = jxd4.redMul(jy2);
30649 var nx = c.redSqr().redISub(t1.redAdd(t1));
30650 var t2 = t1.redISub(nx);
30651
30652 var jyd8 = jy2.redSqr();
30653 jyd8 = jyd8.redIAdd(jyd8);
30654 jyd8 = jyd8.redIAdd(jyd8);
30655 jyd8 = jyd8.redIAdd(jyd8);
30656 var ny = c.redMul(t2).redISub(jyd8);
30657 var nz = jy.redAdd(jy).redMul(jz);
30658
30659 return this.curve.jpoint(nx, ny, nz);
30660};
30661
30662JPoint.prototype.trpl = function trpl() {
30663 if (!this.curve.zeroA)
30664 return this.dbl().add(this);
30665
30666 // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#tripling-tpl-2007-bl
30667 // 5M + 10S + ...
30668
30669 // XX = X1^2
30670 var xx = this.x.redSqr();
30671 // YY = Y1^2
30672 var yy = this.y.redSqr();
30673 // ZZ = Z1^2
30674 var zz = this.z.redSqr();
30675 // YYYY = YY^2
30676 var yyyy = yy.redSqr();
30677 // M = 3 * XX + a * ZZ2; a = 0
30678 var m = xx.redAdd(xx).redIAdd(xx);
30679 // MM = M^2
30680 var mm = m.redSqr();
30681 // E = 6 * ((X1 + YY)^2 - XX - YYYY) - MM
30682 var e = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy);
30683 e = e.redIAdd(e);
30684 e = e.redAdd(e).redIAdd(e);
30685 e = e.redISub(mm);
30686 // EE = E^2
30687 var ee = e.redSqr();
30688 // T = 16*YYYY
30689 var t = yyyy.redIAdd(yyyy);
30690 t = t.redIAdd(t);
30691 t = t.redIAdd(t);
30692 t = t.redIAdd(t);
30693 // U = (M + E)^2 - MM - EE - T
30694 var u = m.redIAdd(e).redSqr().redISub(mm).redISub(ee).redISub(t);
30695 // X3 = 4 * (X1 * EE - 4 * YY * U)
30696 var yyu4 = yy.redMul(u);
30697 yyu4 = yyu4.redIAdd(yyu4);
30698 yyu4 = yyu4.redIAdd(yyu4);
30699 var nx = this.x.redMul(ee).redISub(yyu4);
30700 nx = nx.redIAdd(nx);
30701 nx = nx.redIAdd(nx);
30702 // Y3 = 8 * Y1 * (U * (T - U) - E * EE)
30703 var ny = this.y.redMul(u.redMul(t.redISub(u)).redISub(e.redMul(ee)));
30704 ny = ny.redIAdd(ny);
30705 ny = ny.redIAdd(ny);
30706 ny = ny.redIAdd(ny);
30707 // Z3 = (Z1 + E)^2 - ZZ - EE
30708 var nz = this.z.redAdd(e).redSqr().redISub(zz).redISub(ee);
30709
30710 return this.curve.jpoint(nx, ny, nz);
30711};
30712
30713JPoint.prototype.mul = function mul(k, kbase) {
30714 k = new BN(k, kbase);
30715
30716 return this.curve._wnafMul(this, k);
30717};
30718
30719JPoint.prototype.eq = function eq(p) {
30720 if (p.type === 'affine')
30721 return this.eq(p.toJ());
30722
30723 if (this === p)
30724 return true;
30725
30726 // x1 * z2^2 == x2 * z1^2
30727 var z2 = this.z.redSqr();
30728 var pz2 = p.z.redSqr();
30729 if (this.x.redMul(pz2).redISub(p.x.redMul(z2)).cmpn(0) !== 0)
30730 return false;
30731
30732 // y1 * z2^3 == y2 * z1^3
30733 var z3 = z2.redMul(this.z);
30734 var pz3 = pz2.redMul(p.z);
30735 return this.y.redMul(pz3).redISub(p.y.redMul(z3)).cmpn(0) === 0;
30736};
30737
30738JPoint.prototype.eqXToP = function eqXToP(x) {
30739 var zs = this.z.redSqr();
30740 var rx = x.toRed(this.curve.red).redMul(zs);
30741 if (this.x.cmp(rx) === 0)
30742 return true;
30743
30744 var xc = x.clone();
30745 var t = this.curve.redN.redMul(zs);
30746 for (;;) {
30747 xc.iadd(this.curve.n);
30748 if (xc.cmp(this.curve.p) >= 0)
30749 return false;
30750
30751 rx.redIAdd(t);
30752 if (this.x.cmp(rx) === 0)
30753 return true;
30754 }
30755};
30756
30757JPoint.prototype.inspect = function inspect() {
30758 if (this.isInfinity())
30759 return '<EC JPoint Infinity>';
30760 return '<EC JPoint x: ' + this.x.toString(16, 2) +
30761 ' y: ' + this.y.toString(16, 2) +
30762 ' z: ' + this.z.toString(16, 2) + '>';
30763};
30764
30765JPoint.prototype.isInfinity = function isInfinity() {
30766 // XXX This code assumes that zero is always zero in red
30767 return this.z.cmpn(0) === 0;
30768};
30769
30770},{"../../elliptic":142,"../curve":145,"bn.js":80,"inherits":210}],148:[function(require,module,exports){
30771'use strict';
30772
30773var curves = exports;
30774
30775var hash = require('hash.js');
30776var elliptic = require('../elliptic');
30777
30778var assert = elliptic.utils.assert;
30779
30780function PresetCurve(options) {
30781 if (options.type === 'short')
30782 this.curve = new elliptic.curve.short(options);
30783 else if (options.type === 'edwards')
30784 this.curve = new elliptic.curve.edwards(options);
30785 else
30786 this.curve = new elliptic.curve.mont(options);
30787 this.g = this.curve.g;
30788 this.n = this.curve.n;
30789 this.hash = options.hash;
30790
30791 assert(this.g.validate(), 'Invalid curve');
30792 assert(this.g.mul(this.n).isInfinity(), 'Invalid curve, G*N != O');
30793}
30794curves.PresetCurve = PresetCurve;
30795
30796function defineCurve(name, options) {
30797 Object.defineProperty(curves, name, {
30798 configurable: true,
30799 enumerable: true,
30800 get: function() {
30801 var curve = new PresetCurve(options);
30802 Object.defineProperty(curves, name, {
30803 configurable: true,
30804 enumerable: true,
30805 value: curve
30806 });
30807 return curve;
30808 }
30809 });
30810}
30811
30812defineCurve('p192', {
30813 type: 'short',
30814 prime: 'p192',
30815 p: 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff',
30816 a: 'ffffffff ffffffff ffffffff fffffffe ffffffff fffffffc',
30817 b: '64210519 e59c80e7 0fa7e9ab 72243049 feb8deec c146b9b1',
30818 n: 'ffffffff ffffffff ffffffff 99def836 146bc9b1 b4d22831',
30819 hash: hash.sha256,
30820 gRed: false,
30821 g: [
30822 '188da80e b03090f6 7cbf20eb 43a18800 f4ff0afd 82ff1012',
30823 '07192b95 ffc8da78 631011ed 6b24cdd5 73f977a1 1e794811'
30824 ]
30825});
30826
30827defineCurve('p224', {
30828 type: 'short',
30829 prime: 'p224',
30830 p: 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001',
30831 a: 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff fffffffe',
30832 b: 'b4050a85 0c04b3ab f5413256 5044b0b7 d7bfd8ba 270b3943 2355ffb4',
30833 n: 'ffffffff ffffffff ffffffff ffff16a2 e0b8f03e 13dd2945 5c5c2a3d',
30834 hash: hash.sha256,
30835 gRed: false,
30836 g: [
30837 'b70e0cbd 6bb4bf7f 321390b9 4a03c1d3 56c21122 343280d6 115c1d21',
30838 'bd376388 b5f723fb 4c22dfe6 cd4375a0 5a074764 44d58199 85007e34'
30839 ]
30840});
30841
30842defineCurve('p256', {
30843 type: 'short',
30844 prime: null,
30845 p: 'ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff ffffffff',
30846 a: 'ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff fffffffc',
30847 b: '5ac635d8 aa3a93e7 b3ebbd55 769886bc 651d06b0 cc53b0f6 3bce3c3e 27d2604b',
30848 n: 'ffffffff 00000000 ffffffff ffffffff bce6faad a7179e84 f3b9cac2 fc632551',
30849 hash: hash.sha256,
30850 gRed: false,
30851 g: [
30852 '6b17d1f2 e12c4247 f8bce6e5 63a440f2 77037d81 2deb33a0 f4a13945 d898c296',
30853 '4fe342e2 fe1a7f9b 8ee7eb4a 7c0f9e16 2bce3357 6b315ece cbb64068 37bf51f5'
30854 ]
30855});
30856
30857defineCurve('p384', {
30858 type: 'short',
30859 prime: null,
30860 p: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' +
30861 'fffffffe ffffffff 00000000 00000000 ffffffff',
30862 a: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' +
30863 'fffffffe ffffffff 00000000 00000000 fffffffc',
30864 b: 'b3312fa7 e23ee7e4 988e056b e3f82d19 181d9c6e fe814112 0314088f ' +
30865 '5013875a c656398d 8a2ed19d 2a85c8ed d3ec2aef',
30866 n: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff c7634d81 ' +
30867 'f4372ddf 581a0db2 48b0a77a ecec196a ccc52973',
30868 hash: hash.sha384,
30869 gRed: false,
30870 g: [
30871 'aa87ca22 be8b0537 8eb1c71e f320ad74 6e1d3b62 8ba79b98 59f741e0 82542a38 ' +
30872 '5502f25d bf55296c 3a545e38 72760ab7',
30873 '3617de4a 96262c6f 5d9e98bf 9292dc29 f8f41dbd 289a147c e9da3113 b5f0b8c0 ' +
30874 '0a60b1ce 1d7e819d 7a431d7c 90ea0e5f'
30875 ]
30876});
30877
30878defineCurve('p521', {
30879 type: 'short',
30880 prime: null,
30881 p: '000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ' +
30882 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' +
30883 'ffffffff ffffffff ffffffff ffffffff ffffffff',
30884 a: '000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ' +
30885 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' +
30886 'ffffffff ffffffff ffffffff ffffffff fffffffc',
30887 b: '00000051 953eb961 8e1c9a1f 929a21a0 b68540ee a2da725b ' +
30888 '99b315f3 b8b48991 8ef109e1 56193951 ec7e937b 1652c0bd ' +
30889 '3bb1bf07 3573df88 3d2c34f1 ef451fd4 6b503f00',
30890 n: '000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ' +
30891 'ffffffff ffffffff fffffffa 51868783 bf2f966b 7fcc0148 ' +
30892 'f709a5d0 3bb5c9b8 899c47ae bb6fb71e 91386409',
30893 hash: hash.sha512,
30894 gRed: false,
30895 g: [
30896 '000000c6 858e06b7 0404e9cd 9e3ecb66 2395b442 9c648139 ' +
30897 '053fb521 f828af60 6b4d3dba a14b5e77 efe75928 fe1dc127 ' +
30898 'a2ffa8de 3348b3c1 856a429b f97e7e31 c2e5bd66',
30899 '00000118 39296a78 9a3bc004 5c8a5fb4 2c7d1bd9 98f54449 ' +
30900 '579b4468 17afbd17 273e662c 97ee7299 5ef42640 c550b901 ' +
30901 '3fad0761 353c7086 a272c240 88be9476 9fd16650'
30902 ]
30903});
30904
30905defineCurve('curve25519', {
30906 type: 'mont',
30907 prime: 'p25519',
30908 p: '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed',
30909 a: '76d06',
30910 b: '1',
30911 n: '1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed',
30912 hash: hash.sha256,
30913 gRed: false,
30914 g: [
30915 '9'
30916 ]
30917});
30918
30919defineCurve('ed25519', {
30920 type: 'edwards',
30921 prime: 'p25519',
30922 p: '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed',
30923 a: '-1',
30924 c: '1',
30925 // -121665 * (121666^(-1)) (mod P)
30926 d: '52036cee2b6ffe73 8cc740797779e898 00700a4d4141d8ab 75eb4dca135978a3',
30927 n: '1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed',
30928 hash: hash.sha256,
30929 gRed: false,
30930 g: [
30931 '216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a',
30932
30933 // 4/5
30934 '6666666666666666666666666666666666666666666666666666666666666658'
30935 ]
30936});
30937
30938var pre;
30939try {
30940 pre = require('./precomputed/secp256k1');
30941} catch (e) {
30942 pre = undefined;
30943}
30944
30945defineCurve('secp256k1', {
30946 type: 'short',
30947 prime: 'k256',
30948 p: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f',
30949 a: '0',
30950 b: '7',
30951 n: 'ffffffff ffffffff ffffffff fffffffe baaedce6 af48a03b bfd25e8c d0364141',
30952 h: '1',
30953 hash: hash.sha256,
30954
30955 // Precomputed endomorphism
30956 beta: '7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee',
30957 lambda: '5363ad4cc05c30e0a5261c028812645a122e22ea20816678df02967c1b23bd72',
30958 basis: [
30959 {
30960 a: '3086d221a7d46bcde86c90e49284eb15',
30961 b: '-e4437ed6010e88286f547fa90abfe4c3'
30962 },
30963 {
30964 a: '114ca50f7a8e2f3f657c1108d9d44cfd8',
30965 b: '3086d221a7d46bcde86c90e49284eb15'
30966 }
30967 ],
30968
30969 gRed: false,
30970 g: [
30971 '79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798',
30972 '483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8',
30973 pre
30974 ]
30975});
30976
30977},{"../elliptic":142,"./precomputed/secp256k1":155,"hash.js":190}],149:[function(require,module,exports){
30978'use strict';
30979
30980var BN = require('bn.js');
30981var HmacDRBG = require('hmac-drbg');
30982var elliptic = require('../../elliptic');
30983var utils = elliptic.utils;
30984var assert = utils.assert;
30985
30986var KeyPair = require('./key');
30987var Signature = require('./signature');
30988
30989function EC(options) {
30990 if (!(this instanceof EC))
30991 return new EC(options);
30992
30993 // Shortcut `elliptic.ec(curve-name)`
30994 if (typeof options === 'string') {
30995 assert(elliptic.curves.hasOwnProperty(options), 'Unknown curve ' + options);
30996
30997 options = elliptic.curves[options];
30998 }
30999
31000 // Shortcut for `elliptic.ec(elliptic.curves.curveName)`
31001 if (options instanceof elliptic.curves.PresetCurve)
31002 options = { curve: options };
31003
31004 this.curve = options.curve.curve;
31005 this.n = this.curve.n;
31006 this.nh = this.n.ushrn(1);
31007 this.g = this.curve.g;
31008
31009 // Point on curve
31010 this.g = options.curve.g;
31011 this.g.precompute(options.curve.n.bitLength() + 1);
31012
31013 // Hash for function for DRBG
31014 this.hash = options.hash || options.curve.hash;
31015}
31016module.exports = EC;
31017
31018EC.prototype.keyPair = function keyPair(options) {
31019 return new KeyPair(this, options);
31020};
31021
31022EC.prototype.keyFromPrivate = function keyFromPrivate(priv, enc) {
31023 return KeyPair.fromPrivate(this, priv, enc);
31024};
31025
31026EC.prototype.keyFromPublic = function keyFromPublic(pub, enc) {
31027 return KeyPair.fromPublic(this, pub, enc);
31028};
31029
31030EC.prototype.genKeyPair = function genKeyPair(options) {
31031 if (!options)
31032 options = {};
31033
31034 // Instantiate Hmac_DRBG
31035 var drbg = new HmacDRBG({
31036 hash: this.hash,
31037 pers: options.pers,
31038 persEnc: options.persEnc || 'utf8',
31039 entropy: options.entropy || elliptic.rand(this.hash.hmacStrength),
31040 entropyEnc: options.entropy && options.entropyEnc || 'utf8',
31041 nonce: this.n.toArray()
31042 });
31043
31044 var bytes = this.n.byteLength();
31045 var ns2 = this.n.sub(new BN(2));
31046 do {
31047 var priv = new BN(drbg.generate(bytes));
31048 if (priv.cmp(ns2) > 0)
31049 continue;
31050
31051 priv.iaddn(1);
31052 return this.keyFromPrivate(priv);
31053 } while (true);
31054};
31055
31056EC.prototype._truncateToN = function truncateToN(msg, truncOnly) {
31057 var delta = msg.byteLength() * 8 - this.n.bitLength();
31058 if (delta > 0)
31059 msg = msg.ushrn(delta);
31060 if (!truncOnly && msg.cmp(this.n) >= 0)
31061 return msg.sub(this.n);
31062 else
31063 return msg;
31064};
31065
31066EC.prototype.sign = function sign(msg, key, enc, options) {
31067 if (typeof enc === 'object') {
31068 options = enc;
31069 enc = null;
31070 }
31071 if (!options)
31072 options = {};
31073
31074 key = this.keyFromPrivate(key, enc);
31075 msg = this._truncateToN(new BN(msg, 16));
31076
31077 // Zero-extend key to provide enough entropy
31078 var bytes = this.n.byteLength();
31079 var bkey = key.getPrivate().toArray('be', bytes);
31080
31081 // Zero-extend nonce to have the same byte size as N
31082 var nonce = msg.toArray('be', bytes);
31083
31084 // Instantiate Hmac_DRBG
31085 var drbg = new HmacDRBG({
31086 hash: this.hash,
31087 entropy: bkey,
31088 nonce: nonce,
31089 pers: options.pers,
31090 persEnc: options.persEnc || 'utf8'
31091 });
31092
31093 // Number of bytes to generate
31094 var ns1 = this.n.sub(new BN(1));
31095
31096 for (var iter = 0; true; iter++) {
31097 var k = options.k ?
31098 options.k(iter) :
31099 new BN(drbg.generate(this.n.byteLength()));
31100 k = this._truncateToN(k, true);
31101 if (k.cmpn(1) <= 0 || k.cmp(ns1) >= 0)
31102 continue;
31103
31104 var kp = this.g.mul(k);
31105 if (kp.isInfinity())
31106 continue;
31107
31108 var kpX = kp.getX();
31109 var r = kpX.umod(this.n);
31110 if (r.cmpn(0) === 0)
31111 continue;
31112
31113 var s = k.invm(this.n).mul(r.mul(key.getPrivate()).iadd(msg));
31114 s = s.umod(this.n);
31115 if (s.cmpn(0) === 0)
31116 continue;
31117
31118 var recoveryParam = (kp.getY().isOdd() ? 1 : 0) |
31119 (kpX.cmp(r) !== 0 ? 2 : 0);
31120
31121 // Use complement of `s`, if it is > `n / 2`
31122 if (options.canonical && s.cmp(this.nh) > 0) {
31123 s = this.n.sub(s);
31124 recoveryParam ^= 1;
31125 }
31126
31127 return new Signature({ r: r, s: s, recoveryParam: recoveryParam });
31128 }
31129};
31130
31131EC.prototype.verify = function verify(msg, signature, key, enc) {
31132 msg = this._truncateToN(new BN(msg, 16));
31133 key = this.keyFromPublic(key, enc);
31134 signature = new Signature(signature, 'hex');
31135
31136 // Perform primitive values validation
31137 var r = signature.r;
31138 var s = signature.s;
31139 if (r.cmpn(1) < 0 || r.cmp(this.n) >= 0)
31140 return false;
31141 if (s.cmpn(1) < 0 || s.cmp(this.n) >= 0)
31142 return false;
31143
31144 // Validate signature
31145 var sinv = s.invm(this.n);
31146 var u1 = sinv.mul(msg).umod(this.n);
31147 var u2 = sinv.mul(r).umod(this.n);
31148
31149 if (!this.curve._maxwellTrick) {
31150 var p = this.g.mulAdd(u1, key.getPublic(), u2);
31151 if (p.isInfinity())
31152 return false;
31153
31154 return p.getX().umod(this.n).cmp(r) === 0;
31155 }
31156
31157 // NOTE: Greg Maxwell's trick, inspired by:
31158 // https://git.io/vad3K
31159
31160 var p = this.g.jmulAdd(u1, key.getPublic(), u2);
31161 if (p.isInfinity())
31162 return false;
31163
31164 // Compare `p.x` of Jacobian point with `r`,
31165 // this will do `p.x == r * p.z^2` instead of multiplying `p.x` by the
31166 // inverse of `p.z^2`
31167 return p.eqXToP(r);
31168};
31169
31170EC.prototype.recoverPubKey = function(msg, signature, j, enc) {
31171 assert((3 & j) === j, 'The recovery param is more than two bits');
31172 signature = new Signature(signature, enc);
31173
31174 var n = this.n;
31175 var e = new BN(msg);
31176 var r = signature.r;
31177 var s = signature.s;
31178
31179 // A set LSB signifies that the y-coordinate is odd
31180 var isYOdd = j & 1;
31181 var isSecondKey = j >> 1;
31182 if (r.cmp(this.curve.p.umod(this.curve.n)) >= 0 && isSecondKey)
31183 throw new Error('Unable to find sencond key candinate');
31184
31185 // 1.1. Let x = r + jn.
31186 if (isSecondKey)
31187 r = this.curve.pointFromX(r.add(this.curve.n), isYOdd);
31188 else
31189 r = this.curve.pointFromX(r, isYOdd);
31190
31191 var rInv = signature.r.invm(n);
31192 var s1 = n.sub(e).mul(rInv).umod(n);
31193 var s2 = s.mul(rInv).umod(n);
31194
31195 // 1.6.1 Compute Q = r^-1 (sR - eG)
31196 // Q = r^-1 (sR + -eG)
31197 return this.g.mulAdd(s1, r, s2);
31198};
31199
31200EC.prototype.getKeyRecoveryParam = function(e, signature, Q, enc) {
31201 signature = new Signature(signature, enc);
31202 if (signature.recoveryParam !== null)
31203 return signature.recoveryParam;
31204
31205 for (var i = 0; i < 4; i++) {
31206 var Qprime;
31207 try {
31208 Qprime = this.recoverPubKey(e, signature, i);
31209 } catch (e) {
31210 continue;
31211 }
31212
31213 if (Qprime.eq(Q))
31214 return i;
31215 }
31216 throw new Error('Unable to find valid recovery factor');
31217};
31218
31219},{"../../elliptic":142,"./key":150,"./signature":151,"bn.js":80,"hmac-drbg":202}],150:[function(require,module,exports){
31220'use strict';
31221
31222var BN = require('bn.js');
31223var elliptic = require('../../elliptic');
31224var utils = elliptic.utils;
31225var assert = utils.assert;
31226
31227function KeyPair(ec, options) {
31228 this.ec = ec;
31229 this.priv = null;
31230 this.pub = null;
31231
31232 // KeyPair(ec, { priv: ..., pub: ... })
31233 if (options.priv)
31234 this._importPrivate(options.priv, options.privEnc);
31235 if (options.pub)
31236 this._importPublic(options.pub, options.pubEnc);
31237}
31238module.exports = KeyPair;
31239
31240KeyPair.fromPublic = function fromPublic(ec, pub, enc) {
31241 if (pub instanceof KeyPair)
31242 return pub;
31243
31244 return new KeyPair(ec, {
31245 pub: pub,
31246 pubEnc: enc
31247 });
31248};
31249
31250KeyPair.fromPrivate = function fromPrivate(ec, priv, enc) {
31251 if (priv instanceof KeyPair)
31252 return priv;
31253
31254 return new KeyPair(ec, {
31255 priv: priv,
31256 privEnc: enc
31257 });
31258};
31259
31260KeyPair.prototype.validate = function validate() {
31261 var pub = this.getPublic();
31262
31263 if (pub.isInfinity())
31264 return { result: false, reason: 'Invalid public key' };
31265 if (!pub.validate())
31266 return { result: false, reason: 'Public key is not a point' };
31267 if (!pub.mul(this.ec.curve.n).isInfinity())
31268 return { result: false, reason: 'Public key * N != O' };
31269
31270 return { result: true, reason: null };
31271};
31272
31273KeyPair.prototype.getPublic = function getPublic(compact, enc) {
31274 // compact is optional argument
31275 if (typeof compact === 'string') {
31276 enc = compact;
31277 compact = null;
31278 }
31279
31280 if (!this.pub)
31281 this.pub = this.ec.g.mul(this.priv);
31282
31283 if (!enc)
31284 return this.pub;
31285
31286 return this.pub.encode(enc, compact);
31287};
31288
31289KeyPair.prototype.getPrivate = function getPrivate(enc) {
31290 if (enc === 'hex')
31291 return this.priv.toString(16, 2);
31292 else
31293 return this.priv;
31294};
31295
31296KeyPair.prototype._importPrivate = function _importPrivate(key, enc) {
31297 this.priv = new BN(key, enc || 16);
31298
31299 // Ensure that the priv won't be bigger than n, otherwise we may fail
31300 // in fixed multiplication method
31301 this.priv = this.priv.umod(this.ec.curve.n);
31302};
31303
31304KeyPair.prototype._importPublic = function _importPublic(key, enc) {
31305 if (key.x || key.y) {
31306 // Montgomery points only have an `x` coordinate.
31307 // Weierstrass/Edwards points on the other hand have both `x` and
31308 // `y` coordinates.
31309 if (this.ec.curve.type === 'mont') {
31310 assert(key.x, 'Need x coordinate');
31311 } else if (this.ec.curve.type === 'short' ||
31312 this.ec.curve.type === 'edwards') {
31313 assert(key.x && key.y, 'Need both x and y coordinate');
31314 }
31315 this.pub = this.ec.curve.point(key.x, key.y);
31316 return;
31317 }
31318 this.pub = this.ec.curve.decodePoint(key, enc);
31319};
31320
31321// ECDH
31322KeyPair.prototype.derive = function derive(pub) {
31323 return pub.mul(this.priv).getX();
31324};
31325
31326// ECDSA
31327KeyPair.prototype.sign = function sign(msg, enc, options) {
31328 return this.ec.sign(msg, this, enc, options);
31329};
31330
31331KeyPair.prototype.verify = function verify(msg, signature) {
31332 return this.ec.verify(msg, signature, this);
31333};
31334
31335KeyPair.prototype.inspect = function inspect() {
31336 return '<Key priv: ' + (this.priv && this.priv.toString(16, 2)) +
31337 ' pub: ' + (this.pub && this.pub.inspect()) + ' >';
31338};
31339
31340},{"../../elliptic":142,"bn.js":80}],151:[function(require,module,exports){
31341'use strict';
31342
31343var BN = require('bn.js');
31344
31345var elliptic = require('../../elliptic');
31346var utils = elliptic.utils;
31347var assert = utils.assert;
31348
31349function Signature(options, enc) {
31350 if (options instanceof Signature)
31351 return options;
31352
31353 if (this._importDER(options, enc))
31354 return;
31355
31356 assert(options.r && options.s, 'Signature without r or s');
31357 this.r = new BN(options.r, 16);
31358 this.s = new BN(options.s, 16);
31359 if (options.recoveryParam === undefined)
31360 this.recoveryParam = null;
31361 else
31362 this.recoveryParam = options.recoveryParam;
31363}
31364module.exports = Signature;
31365
31366function Position() {
31367 this.place = 0;
31368}
31369
31370function getLength(buf, p) {
31371 var initial = buf[p.place++];
31372 if (!(initial & 0x80)) {
31373 return initial;
31374 }
31375 var octetLen = initial & 0xf;
31376 var val = 0;
31377 for (var i = 0, off = p.place; i < octetLen; i++, off++) {
31378 val <<= 8;
31379 val |= buf[off];
31380 }
31381 p.place = off;
31382 return val;
31383}
31384
31385function rmPadding(buf) {
31386 var i = 0;
31387 var len = buf.length - 1;
31388 while (!buf[i] && !(buf[i + 1] & 0x80) && i < len) {
31389 i++;
31390 }
31391 if (i === 0) {
31392 return buf;
31393 }
31394 return buf.slice(i);
31395}
31396
31397Signature.prototype._importDER = function _importDER(data, enc) {
31398 data = utils.toArray(data, enc);
31399 var p = new Position();
31400 if (data[p.place++] !== 0x30) {
31401 return false;
31402 }
31403 var len = getLength(data, p);
31404 if ((len + p.place) !== data.length) {
31405 return false;
31406 }
31407 if (data[p.place++] !== 0x02) {
31408 return false;
31409 }
31410 var rlen = getLength(data, p);
31411 var r = data.slice(p.place, rlen + p.place);
31412 p.place += rlen;
31413 if (data[p.place++] !== 0x02) {
31414 return false;
31415 }
31416 var slen = getLength(data, p);
31417 if (data.length !== slen + p.place) {
31418 return false;
31419 }
31420 var s = data.slice(p.place, slen + p.place);
31421 if (r[0] === 0 && (r[1] & 0x80)) {
31422 r = r.slice(1);
31423 }
31424 if (s[0] === 0 && (s[1] & 0x80)) {
31425 s = s.slice(1);
31426 }
31427
31428 this.r = new BN(r);
31429 this.s = new BN(s);
31430 this.recoveryParam = null;
31431
31432 return true;
31433};
31434
31435function constructLength(arr, len) {
31436 if (len < 0x80) {
31437 arr.push(len);
31438 return;
31439 }
31440 var octets = 1 + (Math.log(len) / Math.LN2 >>> 3);
31441 arr.push(octets | 0x80);
31442 while (--octets) {
31443 arr.push((len >>> (octets << 3)) & 0xff);
31444 }
31445 arr.push(len);
31446}
31447
31448Signature.prototype.toDER = function toDER(enc) {
31449 var r = this.r.toArray();
31450 var s = this.s.toArray();
31451
31452 // Pad values
31453 if (r[0] & 0x80)
31454 r = [ 0 ].concat(r);
31455 // Pad values
31456 if (s[0] & 0x80)
31457 s = [ 0 ].concat(s);
31458
31459 r = rmPadding(r);
31460 s = rmPadding(s);
31461
31462 while (!s[0] && !(s[1] & 0x80)) {
31463 s = s.slice(1);
31464 }
31465 var arr = [ 0x02 ];
31466 constructLength(arr, r.length);
31467 arr = arr.concat(r);
31468 arr.push(0x02);
31469 constructLength(arr, s.length);
31470 var backHalf = arr.concat(s);
31471 var res = [ 0x30 ];
31472 constructLength(res, backHalf.length);
31473 res = res.concat(backHalf);
31474 return utils.encode(res, enc);
31475};
31476
31477},{"../../elliptic":142,"bn.js":80}],152:[function(require,module,exports){
31478'use strict';
31479
31480var hash = require('hash.js');
31481var elliptic = require('../../elliptic');
31482var utils = elliptic.utils;
31483var assert = utils.assert;
31484var parseBytes = utils.parseBytes;
31485var KeyPair = require('./key');
31486var Signature = require('./signature');
31487
31488function EDDSA(curve) {
31489 assert(curve === 'ed25519', 'only tested with ed25519 so far');
31490
31491 if (!(this instanceof EDDSA))
31492 return new EDDSA(curve);
31493
31494 var curve = elliptic.curves[curve].curve;
31495 this.curve = curve;
31496 this.g = curve.g;
31497 this.g.precompute(curve.n.bitLength() + 1);
31498
31499 this.pointClass = curve.point().constructor;
31500 this.encodingLength = Math.ceil(curve.n.bitLength() / 8);
31501 this.hash = hash.sha512;
31502}
31503
31504module.exports = EDDSA;
31505
31506/**
31507* @param {Array|String} message - message bytes
31508* @param {Array|String|KeyPair} secret - secret bytes or a keypair
31509* @returns {Signature} - signature
31510*/
31511EDDSA.prototype.sign = function sign(message, secret) {
31512 message = parseBytes(message);
31513 var key = this.keyFromSecret(secret);
31514 var r = this.hashInt(key.messagePrefix(), message);
31515 var R = this.g.mul(r);
31516 var Rencoded = this.encodePoint(R);
31517 var s_ = this.hashInt(Rencoded, key.pubBytes(), message)
31518 .mul(key.priv());
31519 var S = r.add(s_).umod(this.curve.n);
31520 return this.makeSignature({ R: R, S: S, Rencoded: Rencoded });
31521};
31522
31523/**
31524* @param {Array} message - message bytes
31525* @param {Array|String|Signature} sig - sig bytes
31526* @param {Array|String|Point|KeyPair} pub - public key
31527* @returns {Boolean} - true if public key matches sig of message
31528*/
31529EDDSA.prototype.verify = function verify(message, sig, pub) {
31530 message = parseBytes(message);
31531 sig = this.makeSignature(sig);
31532 var key = this.keyFromPublic(pub);
31533 var h = this.hashInt(sig.Rencoded(), key.pubBytes(), message);
31534 var SG = this.g.mul(sig.S());
31535 var RplusAh = sig.R().add(key.pub().mul(h));
31536 return RplusAh.eq(SG);
31537};
31538
31539EDDSA.prototype.hashInt = function hashInt() {
31540 var hash = this.hash();
31541 for (var i = 0; i < arguments.length; i++)
31542 hash.update(arguments[i]);
31543 return utils.intFromLE(hash.digest()).umod(this.curve.n);
31544};
31545
31546EDDSA.prototype.keyFromPublic = function keyFromPublic(pub) {
31547 return KeyPair.fromPublic(this, pub);
31548};
31549
31550EDDSA.prototype.keyFromSecret = function keyFromSecret(secret) {
31551 return KeyPair.fromSecret(this, secret);
31552};
31553
31554EDDSA.prototype.makeSignature = function makeSignature(sig) {
31555 if (sig instanceof Signature)
31556 return sig;
31557 return new Signature(this, sig);
31558};
31559
31560/**
31561* * https://tools.ietf.org/html/draft-josefsson-eddsa-ed25519-03#section-5.2
31562*
31563* EDDSA defines methods for encoding and decoding points and integers. These are
31564* helper convenience methods, that pass along to utility functions implied
31565* parameters.
31566*
31567*/
31568EDDSA.prototype.encodePoint = function encodePoint(point) {
31569 var enc = point.getY().toArray('le', this.encodingLength);
31570 enc[this.encodingLength - 1] |= point.getX().isOdd() ? 0x80 : 0;
31571 return enc;
31572};
31573
31574EDDSA.prototype.decodePoint = function decodePoint(bytes) {
31575 bytes = utils.parseBytes(bytes);
31576
31577 var lastIx = bytes.length - 1;
31578 var normed = bytes.slice(0, lastIx).concat(bytes[lastIx] & ~0x80);
31579 var xIsOdd = (bytes[lastIx] & 0x80) !== 0;
31580
31581 var y = utils.intFromLE(normed);
31582 return this.curve.pointFromY(y, xIsOdd);
31583};
31584
31585EDDSA.prototype.encodeInt = function encodeInt(num) {
31586 return num.toArray('le', this.encodingLength);
31587};
31588
31589EDDSA.prototype.decodeInt = function decodeInt(bytes) {
31590 return utils.intFromLE(bytes);
31591};
31592
31593EDDSA.prototype.isPoint = function isPoint(val) {
31594 return val instanceof this.pointClass;
31595};
31596
31597},{"../../elliptic":142,"./key":153,"./signature":154,"hash.js":190}],153:[function(require,module,exports){
31598'use strict';
31599
31600var elliptic = require('../../elliptic');
31601var utils = elliptic.utils;
31602var assert = utils.assert;
31603var parseBytes = utils.parseBytes;
31604var cachedProperty = utils.cachedProperty;
31605
31606/**
31607* @param {EDDSA} eddsa - instance
31608* @param {Object} params - public/private key parameters
31609*
31610* @param {Array<Byte>} [params.secret] - secret seed bytes
31611* @param {Point} [params.pub] - public key point (aka `A` in eddsa terms)
31612* @param {Array<Byte>} [params.pub] - public key point encoded as bytes
31613*
31614*/
31615function KeyPair(eddsa, params) {
31616 this.eddsa = eddsa;
31617 this._secret = parseBytes(params.secret);
31618 if (eddsa.isPoint(params.pub))
31619 this._pub = params.pub;
31620 else
31621 this._pubBytes = parseBytes(params.pub);
31622}
31623
31624KeyPair.fromPublic = function fromPublic(eddsa, pub) {
31625 if (pub instanceof KeyPair)
31626 return pub;
31627 return new KeyPair(eddsa, { pub: pub });
31628};
31629
31630KeyPair.fromSecret = function fromSecret(eddsa, secret) {
31631 if (secret instanceof KeyPair)
31632 return secret;
31633 return new KeyPair(eddsa, { secret: secret });
31634};
31635
31636KeyPair.prototype.secret = function secret() {
31637 return this._secret;
31638};
31639
31640cachedProperty(KeyPair, 'pubBytes', function pubBytes() {
31641 return this.eddsa.encodePoint(this.pub());
31642});
31643
31644cachedProperty(KeyPair, 'pub', function pub() {
31645 if (this._pubBytes)
31646 return this.eddsa.decodePoint(this._pubBytes);
31647 return this.eddsa.g.mul(this.priv());
31648});
31649
31650cachedProperty(KeyPair, 'privBytes', function privBytes() {
31651 var eddsa = this.eddsa;
31652 var hash = this.hash();
31653 var lastIx = eddsa.encodingLength - 1;
31654
31655 var a = hash.slice(0, eddsa.encodingLength);
31656 a[0] &= 248;
31657 a[lastIx] &= 127;
31658 a[lastIx] |= 64;
31659
31660 return a;
31661});
31662
31663cachedProperty(KeyPair, 'priv', function priv() {
31664 return this.eddsa.decodeInt(this.privBytes());
31665});
31666
31667cachedProperty(KeyPair, 'hash', function hash() {
31668 return this.eddsa.hash().update(this.secret()).digest();
31669});
31670
31671cachedProperty(KeyPair, 'messagePrefix', function messagePrefix() {
31672 return this.hash().slice(this.eddsa.encodingLength);
31673});
31674
31675KeyPair.prototype.sign = function sign(message) {
31676 assert(this._secret, 'KeyPair can only verify');
31677 return this.eddsa.sign(message, this);
31678};
31679
31680KeyPair.prototype.verify = function verify(message, sig) {
31681 return this.eddsa.verify(message, sig, this);
31682};
31683
31684KeyPair.prototype.getSecret = function getSecret(enc) {
31685 assert(this._secret, 'KeyPair is public only');
31686 return utils.encode(this.secret(), enc);
31687};
31688
31689KeyPair.prototype.getPublic = function getPublic(enc) {
31690 return utils.encode(this.pubBytes(), enc);
31691};
31692
31693module.exports = KeyPair;
31694
31695},{"../../elliptic":142}],154:[function(require,module,exports){
31696'use strict';
31697
31698var BN = require('bn.js');
31699var elliptic = require('../../elliptic');
31700var utils = elliptic.utils;
31701var assert = utils.assert;
31702var cachedProperty = utils.cachedProperty;
31703var parseBytes = utils.parseBytes;
31704
31705/**
31706* @param {EDDSA} eddsa - eddsa instance
31707* @param {Array<Bytes>|Object} sig -
31708* @param {Array<Bytes>|Point} [sig.R] - R point as Point or bytes
31709* @param {Array<Bytes>|bn} [sig.S] - S scalar as bn or bytes
31710* @param {Array<Bytes>} [sig.Rencoded] - R point encoded
31711* @param {Array<Bytes>} [sig.Sencoded] - S scalar encoded
31712*/
31713function Signature(eddsa, sig) {
31714 this.eddsa = eddsa;
31715
31716 if (typeof sig !== 'object')
31717 sig = parseBytes(sig);
31718
31719 if (Array.isArray(sig)) {
31720 sig = {
31721 R: sig.slice(0, eddsa.encodingLength),
31722 S: sig.slice(eddsa.encodingLength)
31723 };
31724 }
31725
31726 assert(sig.R && sig.S, 'Signature without R or S');
31727
31728 if (eddsa.isPoint(sig.R))
31729 this._R = sig.R;
31730 if (sig.S instanceof BN)
31731 this._S = sig.S;
31732
31733 this._Rencoded = Array.isArray(sig.R) ? sig.R : sig.Rencoded;
31734 this._Sencoded = Array.isArray(sig.S) ? sig.S : sig.Sencoded;
31735}
31736
31737cachedProperty(Signature, 'S', function S() {
31738 return this.eddsa.decodeInt(this.Sencoded());
31739});
31740
31741cachedProperty(Signature, 'R', function R() {
31742 return this.eddsa.decodePoint(this.Rencoded());
31743});
31744
31745cachedProperty(Signature, 'Rencoded', function Rencoded() {
31746 return this.eddsa.encodePoint(this.R());
31747});
31748
31749cachedProperty(Signature, 'Sencoded', function Sencoded() {
31750 return this.eddsa.encodeInt(this.S());
31751});
31752
31753Signature.prototype.toBytes = function toBytes() {
31754 return this.Rencoded().concat(this.Sencoded());
31755};
31756
31757Signature.prototype.toHex = function toHex() {
31758 return utils.encode(this.toBytes(), 'hex').toUpperCase();
31759};
31760
31761module.exports = Signature;
31762
31763},{"../../elliptic":142,"bn.js":80}],155:[function(require,module,exports){
31764module.exports = {
31765 doubles: {
31766 step: 4,
31767 points: [
31768 [
31769 'e60fce93b59e9ec53011aabc21c23e97b2a31369b87a5ae9c44ee89e2a6dec0a',
31770 'f7e3507399e595929db99f34f57937101296891e44d23f0be1f32cce69616821'
31771 ],
31772 [
31773 '8282263212c609d9ea2a6e3e172de238d8c39cabd5ac1ca10646e23fd5f51508',
31774 '11f8a8098557dfe45e8256e830b60ace62d613ac2f7b17bed31b6eaff6e26caf'
31775 ],
31776 [
31777 '175e159f728b865a72f99cc6c6fc846de0b93833fd2222ed73fce5b551e5b739',
31778 'd3506e0d9e3c79eba4ef97a51ff71f5eacb5955add24345c6efa6ffee9fed695'
31779 ],
31780 [
31781 '363d90d447b00c9c99ceac05b6262ee053441c7e55552ffe526bad8f83ff4640',
31782 '4e273adfc732221953b445397f3363145b9a89008199ecb62003c7f3bee9de9'
31783 ],
31784 [
31785 '8b4b5f165df3c2be8c6244b5b745638843e4a781a15bcd1b69f79a55dffdf80c',
31786 '4aad0a6f68d308b4b3fbd7813ab0da04f9e336546162ee56b3eff0c65fd4fd36'
31787 ],
31788 [
31789 '723cbaa6e5db996d6bf771c00bd548c7b700dbffa6c0e77bcb6115925232fcda',
31790 '96e867b5595cc498a921137488824d6e2660a0653779494801dc069d9eb39f5f'
31791 ],
31792 [
31793 'eebfa4d493bebf98ba5feec812c2d3b50947961237a919839a533eca0e7dd7fa',
31794 '5d9a8ca3970ef0f269ee7edaf178089d9ae4cdc3a711f712ddfd4fdae1de8999'
31795 ],
31796 [
31797 '100f44da696e71672791d0a09b7bde459f1215a29b3c03bfefd7835b39a48db0',
31798 'cdd9e13192a00b772ec8f3300c090666b7ff4a18ff5195ac0fbd5cd62bc65a09'
31799 ],
31800 [
31801 'e1031be262c7ed1b1dc9227a4a04c017a77f8d4464f3b3852c8acde6e534fd2d',
31802 '9d7061928940405e6bb6a4176597535af292dd419e1ced79a44f18f29456a00d'
31803 ],
31804 [
31805 'feea6cae46d55b530ac2839f143bd7ec5cf8b266a41d6af52d5e688d9094696d',
31806 'e57c6b6c97dce1bab06e4e12bf3ecd5c981c8957cc41442d3155debf18090088'
31807 ],
31808 [
31809 'da67a91d91049cdcb367be4be6ffca3cfeed657d808583de33fa978bc1ec6cb1',
31810 '9bacaa35481642bc41f463f7ec9780e5dec7adc508f740a17e9ea8e27a68be1d'
31811 ],
31812 [
31813 '53904faa0b334cdda6e000935ef22151ec08d0f7bb11069f57545ccc1a37b7c0',
31814 '5bc087d0bc80106d88c9eccac20d3c1c13999981e14434699dcb096b022771c8'
31815 ],
31816 [
31817 '8e7bcd0bd35983a7719cca7764ca906779b53a043a9b8bcaeff959f43ad86047',
31818 '10b7770b2a3da4b3940310420ca9514579e88e2e47fd68b3ea10047e8460372a'
31819 ],
31820 [
31821 '385eed34c1cdff21e6d0818689b81bde71a7f4f18397e6690a841e1599c43862',
31822 '283bebc3e8ea23f56701de19e9ebf4576b304eec2086dc8cc0458fe5542e5453'
31823 ],
31824 [
31825 '6f9d9b803ecf191637c73a4413dfa180fddf84a5947fbc9c606ed86c3fac3a7',
31826 '7c80c68e603059ba69b8e2a30e45c4d47ea4dd2f5c281002d86890603a842160'
31827 ],
31828 [
31829 '3322d401243c4e2582a2147c104d6ecbf774d163db0f5e5313b7e0e742d0e6bd',
31830 '56e70797e9664ef5bfb019bc4ddaf9b72805f63ea2873af624f3a2e96c28b2a0'
31831 ],
31832 [
31833 '85672c7d2de0b7da2bd1770d89665868741b3f9af7643397721d74d28134ab83',
31834 '7c481b9b5b43b2eb6374049bfa62c2e5e77f17fcc5298f44c8e3094f790313a6'
31835 ],
31836 [
31837 '948bf809b1988a46b06c9f1919413b10f9226c60f668832ffd959af60c82a0a',
31838 '53a562856dcb6646dc6b74c5d1c3418c6d4dff08c97cd2bed4cb7f88d8c8e589'
31839 ],
31840 [
31841 '6260ce7f461801c34f067ce0f02873a8f1b0e44dfc69752accecd819f38fd8e8',
31842 'bc2da82b6fa5b571a7f09049776a1ef7ecd292238051c198c1a84e95b2b4ae17'
31843 ],
31844 [
31845 'e5037de0afc1d8d43d8348414bbf4103043ec8f575bfdc432953cc8d2037fa2d',
31846 '4571534baa94d3b5f9f98d09fb990bddbd5f5b03ec481f10e0e5dc841d755bda'
31847 ],
31848 [
31849 'e06372b0f4a207adf5ea905e8f1771b4e7e8dbd1c6a6c5b725866a0ae4fce725',
31850 '7a908974bce18cfe12a27bb2ad5a488cd7484a7787104870b27034f94eee31dd'
31851 ],
31852 [
31853 '213c7a715cd5d45358d0bbf9dc0ce02204b10bdde2a3f58540ad6908d0559754',
31854 '4b6dad0b5ae462507013ad06245ba190bb4850f5f36a7eeddff2c27534b458f2'
31855 ],
31856 [
31857 '4e7c272a7af4b34e8dbb9352a5419a87e2838c70adc62cddf0cc3a3b08fbd53c',
31858 '17749c766c9d0b18e16fd09f6def681b530b9614bff7dd33e0b3941817dcaae6'
31859 ],
31860 [
31861 'fea74e3dbe778b1b10f238ad61686aa5c76e3db2be43057632427e2840fb27b6',
31862 '6e0568db9b0b13297cf674deccb6af93126b596b973f7b77701d3db7f23cb96f'
31863 ],
31864 [
31865 '76e64113f677cf0e10a2570d599968d31544e179b760432952c02a4417bdde39',
31866 'c90ddf8dee4e95cf577066d70681f0d35e2a33d2b56d2032b4b1752d1901ac01'
31867 ],
31868 [
31869 'c738c56b03b2abe1e8281baa743f8f9a8f7cc643df26cbee3ab150242bcbb891',
31870 '893fb578951ad2537f718f2eacbfbbbb82314eef7880cfe917e735d9699a84c3'
31871 ],
31872 [
31873 'd895626548b65b81e264c7637c972877d1d72e5f3a925014372e9f6588f6c14b',
31874 'febfaa38f2bc7eae728ec60818c340eb03428d632bb067e179363ed75d7d991f'
31875 ],
31876 [
31877 'b8da94032a957518eb0f6433571e8761ceffc73693e84edd49150a564f676e03',
31878 '2804dfa44805a1e4d7c99cc9762808b092cc584d95ff3b511488e4e74efdf6e7'
31879 ],
31880 [
31881 'e80fea14441fb33a7d8adab9475d7fab2019effb5156a792f1a11778e3c0df5d',
31882 'eed1de7f638e00771e89768ca3ca94472d155e80af322ea9fcb4291b6ac9ec78'
31883 ],
31884 [
31885 'a301697bdfcd704313ba48e51d567543f2a182031efd6915ddc07bbcc4e16070',
31886 '7370f91cfb67e4f5081809fa25d40f9b1735dbf7c0a11a130c0d1a041e177ea1'
31887 ],
31888 [
31889 '90ad85b389d6b936463f9d0512678de208cc330b11307fffab7ac63e3fb04ed4',
31890 'e507a3620a38261affdcbd9427222b839aefabe1582894d991d4d48cb6ef150'
31891 ],
31892 [
31893 '8f68b9d2f63b5f339239c1ad981f162ee88c5678723ea3351b7b444c9ec4c0da',
31894 '662a9f2dba063986de1d90c2b6be215dbbea2cfe95510bfdf23cbf79501fff82'
31895 ],
31896 [
31897 'e4f3fb0176af85d65ff99ff9198c36091f48e86503681e3e6686fd5053231e11',
31898 '1e63633ad0ef4f1c1661a6d0ea02b7286cc7e74ec951d1c9822c38576feb73bc'
31899 ],
31900 [
31901 '8c00fa9b18ebf331eb961537a45a4266c7034f2f0d4e1d0716fb6eae20eae29e',
31902 'efa47267fea521a1a9dc343a3736c974c2fadafa81e36c54e7d2a4c66702414b'
31903 ],
31904 [
31905 'e7a26ce69dd4829f3e10cec0a9e98ed3143d084f308b92c0997fddfc60cb3e41',
31906 '2a758e300fa7984b471b006a1aafbb18d0a6b2c0420e83e20e8a9421cf2cfd51'
31907 ],
31908 [
31909 'b6459e0ee3662ec8d23540c223bcbdc571cbcb967d79424f3cf29eb3de6b80ef',
31910 '67c876d06f3e06de1dadf16e5661db3c4b3ae6d48e35b2ff30bf0b61a71ba45'
31911 ],
31912 [
31913 'd68a80c8280bb840793234aa118f06231d6f1fc67e73c5a5deda0f5b496943e8',
31914 'db8ba9fff4b586d00c4b1f9177b0e28b5b0e7b8f7845295a294c84266b133120'
31915 ],
31916 [
31917 '324aed7df65c804252dc0270907a30b09612aeb973449cea4095980fc28d3d5d',
31918 '648a365774b61f2ff130c0c35aec1f4f19213b0c7e332843967224af96ab7c84'
31919 ],
31920 [
31921 '4df9c14919cde61f6d51dfdbe5fee5dceec4143ba8d1ca888e8bd373fd054c96',
31922 '35ec51092d8728050974c23a1d85d4b5d506cdc288490192ebac06cad10d5d'
31923 ],
31924 [
31925 '9c3919a84a474870faed8a9c1cc66021523489054d7f0308cbfc99c8ac1f98cd',
31926 'ddb84f0f4a4ddd57584f044bf260e641905326f76c64c8e6be7e5e03d4fc599d'
31927 ],
31928 [
31929 '6057170b1dd12fdf8de05f281d8e06bb91e1493a8b91d4cc5a21382120a959e5',
31930 '9a1af0b26a6a4807add9a2daf71df262465152bc3ee24c65e899be932385a2a8'
31931 ],
31932 [
31933 'a576df8e23a08411421439a4518da31880cef0fba7d4df12b1a6973eecb94266',
31934 '40a6bf20e76640b2c92b97afe58cd82c432e10a7f514d9f3ee8be11ae1b28ec8'
31935 ],
31936 [
31937 '7778a78c28dec3e30a05fe9629de8c38bb30d1f5cf9a3a208f763889be58ad71',
31938 '34626d9ab5a5b22ff7098e12f2ff580087b38411ff24ac563b513fc1fd9f43ac'
31939 ],
31940 [
31941 '928955ee637a84463729fd30e7afd2ed5f96274e5ad7e5cb09eda9c06d903ac',
31942 'c25621003d3f42a827b78a13093a95eeac3d26efa8a8d83fc5180e935bcd091f'
31943 ],
31944 [
31945 '85d0fef3ec6db109399064f3a0e3b2855645b4a907ad354527aae75163d82751',
31946 '1f03648413a38c0be29d496e582cf5663e8751e96877331582c237a24eb1f962'
31947 ],
31948 [
31949 'ff2b0dce97eece97c1c9b6041798b85dfdfb6d8882da20308f5404824526087e',
31950 '493d13fef524ba188af4c4dc54d07936c7b7ed6fb90e2ceb2c951e01f0c29907'
31951 ],
31952 [
31953 '827fbbe4b1e880ea9ed2b2e6301b212b57f1ee148cd6dd28780e5e2cf856e241',
31954 'c60f9c923c727b0b71bef2c67d1d12687ff7a63186903166d605b68baec293ec'
31955 ],
31956 [
31957 'eaa649f21f51bdbae7be4ae34ce6e5217a58fdce7f47f9aa7f3b58fa2120e2b3',
31958 'be3279ed5bbbb03ac69a80f89879aa5a01a6b965f13f7e59d47a5305ba5ad93d'
31959 ],
31960 [
31961 'e4a42d43c5cf169d9391df6decf42ee541b6d8f0c9a137401e23632dda34d24f',
31962 '4d9f92e716d1c73526fc99ccfb8ad34ce886eedfa8d8e4f13a7f7131deba9414'
31963 ],
31964 [
31965 '1ec80fef360cbdd954160fadab352b6b92b53576a88fea4947173b9d4300bf19',
31966 'aeefe93756b5340d2f3a4958a7abbf5e0146e77f6295a07b671cdc1cc107cefd'
31967 ],
31968 [
31969 '146a778c04670c2f91b00af4680dfa8bce3490717d58ba889ddb5928366642be',
31970 'b318e0ec3354028add669827f9d4b2870aaa971d2f7e5ed1d0b297483d83efd0'
31971 ],
31972 [
31973 'fa50c0f61d22e5f07e3acebb1aa07b128d0012209a28b9776d76a8793180eef9',
31974 '6b84c6922397eba9b72cd2872281a68a5e683293a57a213b38cd8d7d3f4f2811'
31975 ],
31976 [
31977 'da1d61d0ca721a11b1a5bf6b7d88e8421a288ab5d5bba5220e53d32b5f067ec2',
31978 '8157f55a7c99306c79c0766161c91e2966a73899d279b48a655fba0f1ad836f1'
31979 ],
31980 [
31981 'a8e282ff0c9706907215ff98e8fd416615311de0446f1e062a73b0610d064e13',
31982 '7f97355b8db81c09abfb7f3c5b2515888b679a3e50dd6bd6cef7c73111f4cc0c'
31983 ],
31984 [
31985 '174a53b9c9a285872d39e56e6913cab15d59b1fa512508c022f382de8319497c',
31986 'ccc9dc37abfc9c1657b4155f2c47f9e6646b3a1d8cb9854383da13ac079afa73'
31987 ],
31988 [
31989 '959396981943785c3d3e57edf5018cdbe039e730e4918b3d884fdff09475b7ba',
31990 '2e7e552888c331dd8ba0386a4b9cd6849c653f64c8709385e9b8abf87524f2fd'
31991 ],
31992 [
31993 'd2a63a50ae401e56d645a1153b109a8fcca0a43d561fba2dbb51340c9d82b151',
31994 'e82d86fb6443fcb7565aee58b2948220a70f750af484ca52d4142174dcf89405'
31995 ],
31996 [
31997 '64587e2335471eb890ee7896d7cfdc866bacbdbd3839317b3436f9b45617e073',
31998 'd99fcdd5bf6902e2ae96dd6447c299a185b90a39133aeab358299e5e9faf6589'
31999 ],
32000 [
32001 '8481bde0e4e4d885b3a546d3e549de042f0aa6cea250e7fd358d6c86dd45e458',
32002 '38ee7b8cba5404dd84a25bf39cecb2ca900a79c42b262e556d64b1b59779057e'
32003 ],
32004 [
32005 '13464a57a78102aa62b6979ae817f4637ffcfed3c4b1ce30bcd6303f6caf666b',
32006 '69be159004614580ef7e433453ccb0ca48f300a81d0942e13f495a907f6ecc27'
32007 ],
32008 [
32009 'bc4a9df5b713fe2e9aef430bcc1dc97a0cd9ccede2f28588cada3a0d2d83f366',
32010 'd3a81ca6e785c06383937adf4b798caa6e8a9fbfa547b16d758d666581f33c1'
32011 ],
32012 [
32013 '8c28a97bf8298bc0d23d8c749452a32e694b65e30a9472a3954ab30fe5324caa',
32014 '40a30463a3305193378fedf31f7cc0eb7ae784f0451cb9459e71dc73cbef9482'
32015 ],
32016 [
32017 '8ea9666139527a8c1dd94ce4f071fd23c8b350c5a4bb33748c4ba111faccae0',
32018 '620efabbc8ee2782e24e7c0cfb95c5d735b783be9cf0f8e955af34a30e62b945'
32019 ],
32020 [
32021 'dd3625faef5ba06074669716bbd3788d89bdde815959968092f76cc4eb9a9787',
32022 '7a188fa3520e30d461da2501045731ca941461982883395937f68d00c644a573'
32023 ],
32024 [
32025 'f710d79d9eb962297e4f6232b40e8f7feb2bc63814614d692c12de752408221e',
32026 'ea98e67232d3b3295d3b535532115ccac8612c721851617526ae47a9c77bfc82'
32027 ]
32028 ]
32029 },
32030 naf: {
32031 wnd: 7,
32032 points: [
32033 [
32034 'f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9',
32035 '388f7b0f632de8140fe337e62a37f3566500a99934c2231b6cb9fd7584b8e672'
32036 ],
32037 [
32038 '2f8bde4d1a07209355b4a7250a5c5128e88b84bddc619ab7cba8d569b240efe4',
32039 'd8ac222636e5e3d6d4dba9dda6c9c426f788271bab0d6840dca87d3aa6ac62d6'
32040 ],
32041 [
32042 '5cbdf0646e5db4eaa398f365f2ea7a0e3d419b7e0330e39ce92bddedcac4f9bc',
32043 '6aebca40ba255960a3178d6d861a54dba813d0b813fde7b5a5082628087264da'
32044 ],
32045 [
32046 'acd484e2f0c7f65309ad178a9f559abde09796974c57e714c35f110dfc27ccbe',
32047 'cc338921b0a7d9fd64380971763b61e9add888a4375f8e0f05cc262ac64f9c37'
32048 ],
32049 [
32050 '774ae7f858a9411e5ef4246b70c65aac5649980be5c17891bbec17895da008cb',
32051 'd984a032eb6b5e190243dd56d7b7b365372db1e2dff9d6a8301d74c9c953c61b'
32052 ],
32053 [
32054 'f28773c2d975288bc7d1d205c3748651b075fbc6610e58cddeeddf8f19405aa8',
32055 'ab0902e8d880a89758212eb65cdaf473a1a06da521fa91f29b5cb52db03ed81'
32056 ],
32057 [
32058 'd7924d4f7d43ea965a465ae3095ff41131e5946f3c85f79e44adbcf8e27e080e',
32059 '581e2872a86c72a683842ec228cc6defea40af2bd896d3a5c504dc9ff6a26b58'
32060 ],
32061 [
32062 'defdea4cdb677750a420fee807eacf21eb9898ae79b9768766e4faa04a2d4a34',
32063 '4211ab0694635168e997b0ead2a93daeced1f4a04a95c0f6cfb199f69e56eb77'
32064 ],
32065 [
32066 '2b4ea0a797a443d293ef5cff444f4979f06acfebd7e86d277475656138385b6c',
32067 '85e89bc037945d93b343083b5a1c86131a01f60c50269763b570c854e5c09b7a'
32068 ],
32069 [
32070 '352bbf4a4cdd12564f93fa332ce333301d9ad40271f8107181340aef25be59d5',
32071 '321eb4075348f534d59c18259dda3e1f4a1b3b2e71b1039c67bd3d8bcf81998c'
32072 ],
32073 [
32074 '2fa2104d6b38d11b0230010559879124e42ab8dfeff5ff29dc9cdadd4ecacc3f',
32075 '2de1068295dd865b64569335bd5dd80181d70ecfc882648423ba76b532b7d67'
32076 ],
32077 [
32078 '9248279b09b4d68dab21a9b066edda83263c3d84e09572e269ca0cd7f5453714',
32079 '73016f7bf234aade5d1aa71bdea2b1ff3fc0de2a887912ffe54a32ce97cb3402'
32080 ],
32081 [
32082 'daed4f2be3a8bf278e70132fb0beb7522f570e144bf615c07e996d443dee8729',
32083 'a69dce4a7d6c98e8d4a1aca87ef8d7003f83c230f3afa726ab40e52290be1c55'
32084 ],
32085 [
32086 'c44d12c7065d812e8acf28d7cbb19f9011ecd9e9fdf281b0e6a3b5e87d22e7db',
32087 '2119a460ce326cdc76c45926c982fdac0e106e861edf61c5a039063f0e0e6482'
32088 ],
32089 [
32090 '6a245bf6dc698504c89a20cfded60853152b695336c28063b61c65cbd269e6b4',
32091 'e022cf42c2bd4a708b3f5126f16a24ad8b33ba48d0423b6efd5e6348100d8a82'
32092 ],
32093 [
32094 '1697ffa6fd9de627c077e3d2fe541084ce13300b0bec1146f95ae57f0d0bd6a5',
32095 'b9c398f186806f5d27561506e4557433a2cf15009e498ae7adee9d63d01b2396'
32096 ],
32097 [
32098 '605bdb019981718b986d0f07e834cb0d9deb8360ffb7f61df982345ef27a7479',
32099 '2972d2de4f8d20681a78d93ec96fe23c26bfae84fb14db43b01e1e9056b8c49'
32100 ],
32101 [
32102 '62d14dab4150bf497402fdc45a215e10dcb01c354959b10cfe31c7e9d87ff33d',
32103 '80fc06bd8cc5b01098088a1950eed0db01aa132967ab472235f5642483b25eaf'
32104 ],
32105 [
32106 '80c60ad0040f27dade5b4b06c408e56b2c50e9f56b9b8b425e555c2f86308b6f',
32107 '1c38303f1cc5c30f26e66bad7fe72f70a65eed4cbe7024eb1aa01f56430bd57a'
32108 ],
32109 [
32110 '7a9375ad6167ad54aa74c6348cc54d344cc5dc9487d847049d5eabb0fa03c8fb',
32111 'd0e3fa9eca8726909559e0d79269046bdc59ea10c70ce2b02d499ec224dc7f7'
32112 ],
32113 [
32114 'd528ecd9b696b54c907a9ed045447a79bb408ec39b68df504bb51f459bc3ffc9',
32115 'eecf41253136e5f99966f21881fd656ebc4345405c520dbc063465b521409933'
32116 ],
32117 [
32118 '49370a4b5f43412ea25f514e8ecdad05266115e4a7ecb1387231808f8b45963',
32119 '758f3f41afd6ed428b3081b0512fd62a54c3f3afbb5b6764b653052a12949c9a'
32120 ],
32121 [
32122 '77f230936ee88cbbd73df930d64702ef881d811e0e1498e2f1c13eb1fc345d74',
32123 '958ef42a7886b6400a08266e9ba1b37896c95330d97077cbbe8eb3c7671c60d6'
32124 ],
32125 [
32126 'f2dac991cc4ce4b9ea44887e5c7c0bce58c80074ab9d4dbaeb28531b7739f530',
32127 'e0dedc9b3b2f8dad4da1f32dec2531df9eb5fbeb0598e4fd1a117dba703a3c37'
32128 ],
32129 [
32130 '463b3d9f662621fb1b4be8fbbe2520125a216cdfc9dae3debcba4850c690d45b',
32131 '5ed430d78c296c3543114306dd8622d7c622e27c970a1de31cb377b01af7307e'
32132 ],
32133 [
32134 'f16f804244e46e2a09232d4aff3b59976b98fac14328a2d1a32496b49998f247',
32135 'cedabd9b82203f7e13d206fcdf4e33d92a6c53c26e5cce26d6579962c4e31df6'
32136 ],
32137 [
32138 'caf754272dc84563b0352b7a14311af55d245315ace27c65369e15f7151d41d1',
32139 'cb474660ef35f5f2a41b643fa5e460575f4fa9b7962232a5c32f908318a04476'
32140 ],
32141 [
32142 '2600ca4b282cb986f85d0f1709979d8b44a09c07cb86d7c124497bc86f082120',
32143 '4119b88753c15bd6a693b03fcddbb45d5ac6be74ab5f0ef44b0be9475a7e4b40'
32144 ],
32145 [
32146 '7635ca72d7e8432c338ec53cd12220bc01c48685e24f7dc8c602a7746998e435',
32147 '91b649609489d613d1d5e590f78e6d74ecfc061d57048bad9e76f302c5b9c61'
32148 ],
32149 [
32150 '754e3239f325570cdbbf4a87deee8a66b7f2b33479d468fbc1a50743bf56cc18',
32151 '673fb86e5bda30fb3cd0ed304ea49a023ee33d0197a695d0c5d98093c536683'
32152 ],
32153 [
32154 'e3e6bd1071a1e96aff57859c82d570f0330800661d1c952f9fe2694691d9b9e8',
32155 '59c9e0bba394e76f40c0aa58379a3cb6a5a2283993e90c4167002af4920e37f5'
32156 ],
32157 [
32158 '186b483d056a033826ae73d88f732985c4ccb1f32ba35f4b4cc47fdcf04aa6eb',
32159 '3b952d32c67cf77e2e17446e204180ab21fb8090895138b4a4a797f86e80888b'
32160 ],
32161 [
32162 'df9d70a6b9876ce544c98561f4be4f725442e6d2b737d9c91a8321724ce0963f',
32163 '55eb2dafd84d6ccd5f862b785dc39d4ab157222720ef9da217b8c45cf2ba2417'
32164 ],
32165 [
32166 '5edd5cc23c51e87a497ca815d5dce0f8ab52554f849ed8995de64c5f34ce7143',
32167 'efae9c8dbc14130661e8cec030c89ad0c13c66c0d17a2905cdc706ab7399a868'
32168 ],
32169 [
32170 '290798c2b6476830da12fe02287e9e777aa3fba1c355b17a722d362f84614fba',
32171 'e38da76dcd440621988d00bcf79af25d5b29c094db2a23146d003afd41943e7a'
32172 ],
32173 [
32174 'af3c423a95d9f5b3054754efa150ac39cd29552fe360257362dfdecef4053b45',
32175 'f98a3fd831eb2b749a93b0e6f35cfb40c8cd5aa667a15581bc2feded498fd9c6'
32176 ],
32177 [
32178 '766dbb24d134e745cccaa28c99bf274906bb66b26dcf98df8d2fed50d884249a',
32179 '744b1152eacbe5e38dcc887980da38b897584a65fa06cedd2c924f97cbac5996'
32180 ],
32181 [
32182 '59dbf46f8c94759ba21277c33784f41645f7b44f6c596a58ce92e666191abe3e',
32183 'c534ad44175fbc300f4ea6ce648309a042ce739a7919798cd85e216c4a307f6e'
32184 ],
32185 [
32186 'f13ada95103c4537305e691e74e9a4a8dd647e711a95e73cb62dc6018cfd87b8',
32187 'e13817b44ee14de663bf4bc808341f326949e21a6a75c2570778419bdaf5733d'
32188 ],
32189 [
32190 '7754b4fa0e8aced06d4167a2c59cca4cda1869c06ebadfb6488550015a88522c',
32191 '30e93e864e669d82224b967c3020b8fa8d1e4e350b6cbcc537a48b57841163a2'
32192 ],
32193 [
32194 '948dcadf5990e048aa3874d46abef9d701858f95de8041d2a6828c99e2262519',
32195 'e491a42537f6e597d5d28a3224b1bc25df9154efbd2ef1d2cbba2cae5347d57e'
32196 ],
32197 [
32198 '7962414450c76c1689c7b48f8202ec37fb224cf5ac0bfa1570328a8a3d7c77ab',
32199 '100b610ec4ffb4760d5c1fc133ef6f6b12507a051f04ac5760afa5b29db83437'
32200 ],
32201 [
32202 '3514087834964b54b15b160644d915485a16977225b8847bb0dd085137ec47ca',
32203 'ef0afbb2056205448e1652c48e8127fc6039e77c15c2378b7e7d15a0de293311'
32204 ],
32205 [
32206 'd3cc30ad6b483e4bc79ce2c9dd8bc54993e947eb8df787b442943d3f7b527eaf',
32207 '8b378a22d827278d89c5e9be8f9508ae3c2ad46290358630afb34db04eede0a4'
32208 ],
32209 [
32210 '1624d84780732860ce1c78fcbfefe08b2b29823db913f6493975ba0ff4847610',
32211 '68651cf9b6da903e0914448c6cd9d4ca896878f5282be4c8cc06e2a404078575'
32212 ],
32213 [
32214 '733ce80da955a8a26902c95633e62a985192474b5af207da6df7b4fd5fc61cd4',
32215 'f5435a2bd2badf7d485a4d8b8db9fcce3e1ef8e0201e4578c54673bc1dc5ea1d'
32216 ],
32217 [
32218 '15d9441254945064cf1a1c33bbd3b49f8966c5092171e699ef258dfab81c045c',
32219 'd56eb30b69463e7234f5137b73b84177434800bacebfc685fc37bbe9efe4070d'
32220 ],
32221 [
32222 'a1d0fcf2ec9de675b612136e5ce70d271c21417c9d2b8aaaac138599d0717940',
32223 'edd77f50bcb5a3cab2e90737309667f2641462a54070f3d519212d39c197a629'
32224 ],
32225 [
32226 'e22fbe15c0af8ccc5780c0735f84dbe9a790badee8245c06c7ca37331cb36980',
32227 'a855babad5cd60c88b430a69f53a1a7a38289154964799be43d06d77d31da06'
32228 ],
32229 [
32230 '311091dd9860e8e20ee13473c1155f5f69635e394704eaa74009452246cfa9b3',
32231 '66db656f87d1f04fffd1f04788c06830871ec5a64feee685bd80f0b1286d8374'
32232 ],
32233 [
32234 '34c1fd04d301be89b31c0442d3e6ac24883928b45a9340781867d4232ec2dbdf',
32235 '9414685e97b1b5954bd46f730174136d57f1ceeb487443dc5321857ba73abee'
32236 ],
32237 [
32238 'f219ea5d6b54701c1c14de5b557eb42a8d13f3abbcd08affcc2a5e6b049b8d63',
32239 '4cb95957e83d40b0f73af4544cccf6b1f4b08d3c07b27fb8d8c2962a400766d1'
32240 ],
32241 [
32242 'd7b8740f74a8fbaab1f683db8f45de26543a5490bca627087236912469a0b448',
32243 'fa77968128d9c92ee1010f337ad4717eff15db5ed3c049b3411e0315eaa4593b'
32244 ],
32245 [
32246 '32d31c222f8f6f0ef86f7c98d3a3335ead5bcd32abdd94289fe4d3091aa824bf',
32247 '5f3032f5892156e39ccd3d7915b9e1da2e6dac9e6f26e961118d14b8462e1661'
32248 ],
32249 [
32250 '7461f371914ab32671045a155d9831ea8793d77cd59592c4340f86cbc18347b5',
32251 '8ec0ba238b96bec0cbdddcae0aa442542eee1ff50c986ea6b39847b3cc092ff6'
32252 ],
32253 [
32254 'ee079adb1df1860074356a25aa38206a6d716b2c3e67453d287698bad7b2b2d6',
32255 '8dc2412aafe3be5c4c5f37e0ecc5f9f6a446989af04c4e25ebaac479ec1c8c1e'
32256 ],
32257 [
32258 '16ec93e447ec83f0467b18302ee620f7e65de331874c9dc72bfd8616ba9da6b5',
32259 '5e4631150e62fb40d0e8c2a7ca5804a39d58186a50e497139626778e25b0674d'
32260 ],
32261 [
32262 'eaa5f980c245f6f038978290afa70b6bd8855897f98b6aa485b96065d537bd99',
32263 'f65f5d3e292c2e0819a528391c994624d784869d7e6ea67fb18041024edc07dc'
32264 ],
32265 [
32266 '78c9407544ac132692ee1910a02439958ae04877151342ea96c4b6b35a49f51',
32267 'f3e0319169eb9b85d5404795539a5e68fa1fbd583c064d2462b675f194a3ddb4'
32268 ],
32269 [
32270 '494f4be219a1a77016dcd838431aea0001cdc8ae7a6fc688726578d9702857a5',
32271 '42242a969283a5f339ba7f075e36ba2af925ce30d767ed6e55f4b031880d562c'
32272 ],
32273 [
32274 'a598a8030da6d86c6bc7f2f5144ea549d28211ea58faa70ebf4c1e665c1fe9b5',
32275 '204b5d6f84822c307e4b4a7140737aec23fc63b65b35f86a10026dbd2d864e6b'
32276 ],
32277 [
32278 'c41916365abb2b5d09192f5f2dbeafec208f020f12570a184dbadc3e58595997',
32279 '4f14351d0087efa49d245b328984989d5caf9450f34bfc0ed16e96b58fa9913'
32280 ],
32281 [
32282 '841d6063a586fa475a724604da03bc5b92a2e0d2e0a36acfe4c73a5514742881',
32283 '73867f59c0659e81904f9a1c7543698e62562d6744c169ce7a36de01a8d6154'
32284 ],
32285 [
32286 '5e95bb399a6971d376026947f89bde2f282b33810928be4ded112ac4d70e20d5',
32287 '39f23f366809085beebfc71181313775a99c9aed7d8ba38b161384c746012865'
32288 ],
32289 [
32290 '36e4641a53948fd476c39f8a99fd974e5ec07564b5315d8bf99471bca0ef2f66',
32291 'd2424b1b1abe4eb8164227b085c9aa9456ea13493fd563e06fd51cf5694c78fc'
32292 ],
32293 [
32294 '336581ea7bfbbb290c191a2f507a41cf5643842170e914faeab27c2c579f726',
32295 'ead12168595fe1be99252129b6e56b3391f7ab1410cd1e0ef3dcdcabd2fda224'
32296 ],
32297 [
32298 '8ab89816dadfd6b6a1f2634fcf00ec8403781025ed6890c4849742706bd43ede',
32299 '6fdcef09f2f6d0a044e654aef624136f503d459c3e89845858a47a9129cdd24e'
32300 ],
32301 [
32302 '1e33f1a746c9c5778133344d9299fcaa20b0938e8acff2544bb40284b8c5fb94',
32303 '60660257dd11b3aa9c8ed618d24edff2306d320f1d03010e33a7d2057f3b3b6'
32304 ],
32305 [
32306 '85b7c1dcb3cec1b7ee7f30ded79dd20a0ed1f4cc18cbcfcfa410361fd8f08f31',
32307 '3d98a9cdd026dd43f39048f25a8847f4fcafad1895d7a633c6fed3c35e999511'
32308 ],
32309 [
32310 '29df9fbd8d9e46509275f4b125d6d45d7fbe9a3b878a7af872a2800661ac5f51',
32311 'b4c4fe99c775a606e2d8862179139ffda61dc861c019e55cd2876eb2a27d84b'
32312 ],
32313 [
32314 'a0b1cae06b0a847a3fea6e671aaf8adfdfe58ca2f768105c8082b2e449fce252',
32315 'ae434102edde0958ec4b19d917a6a28e6b72da1834aff0e650f049503a296cf2'
32316 ],
32317 [
32318 '4e8ceafb9b3e9a136dc7ff67e840295b499dfb3b2133e4ba113f2e4c0e121e5',
32319 'cf2174118c8b6d7a4b48f6d534ce5c79422c086a63460502b827ce62a326683c'
32320 ],
32321 [
32322 'd24a44e047e19b6f5afb81c7ca2f69080a5076689a010919f42725c2b789a33b',
32323 '6fb8d5591b466f8fc63db50f1c0f1c69013f996887b8244d2cdec417afea8fa3'
32324 ],
32325 [
32326 'ea01606a7a6c9cdd249fdfcfacb99584001edd28abbab77b5104e98e8e3b35d4',
32327 '322af4908c7312b0cfbfe369f7a7b3cdb7d4494bc2823700cfd652188a3ea98d'
32328 ],
32329 [
32330 'af8addbf2b661c8a6c6328655eb96651252007d8c5ea31be4ad196de8ce2131f',
32331 '6749e67c029b85f52a034eafd096836b2520818680e26ac8f3dfbcdb71749700'
32332 ],
32333 [
32334 'e3ae1974566ca06cc516d47e0fb165a674a3dabcfca15e722f0e3450f45889',
32335 '2aeabe7e4531510116217f07bf4d07300de97e4874f81f533420a72eeb0bd6a4'
32336 ],
32337 [
32338 '591ee355313d99721cf6993ffed1e3e301993ff3ed258802075ea8ced397e246',
32339 'b0ea558a113c30bea60fc4775460c7901ff0b053d25ca2bdeee98f1a4be5d196'
32340 ],
32341 [
32342 '11396d55fda54c49f19aa97318d8da61fa8584e47b084945077cf03255b52984',
32343 '998c74a8cd45ac01289d5833a7beb4744ff536b01b257be4c5767bea93ea57a4'
32344 ],
32345 [
32346 '3c5d2a1ba39c5a1790000738c9e0c40b8dcdfd5468754b6405540157e017aa7a',
32347 'b2284279995a34e2f9d4de7396fc18b80f9b8b9fdd270f6661f79ca4c81bd257'
32348 ],
32349 [
32350 'cc8704b8a60a0defa3a99a7299f2e9c3fbc395afb04ac078425ef8a1793cc030',
32351 'bdd46039feed17881d1e0862db347f8cf395b74fc4bcdc4e940b74e3ac1f1b13'
32352 ],
32353 [
32354 'c533e4f7ea8555aacd9777ac5cad29b97dd4defccc53ee7ea204119b2889b197',
32355 '6f0a256bc5efdf429a2fb6242f1a43a2d9b925bb4a4b3a26bb8e0f45eb596096'
32356 ],
32357 [
32358 'c14f8f2ccb27d6f109f6d08d03cc96a69ba8c34eec07bbcf566d48e33da6593',
32359 'c359d6923bb398f7fd4473e16fe1c28475b740dd098075e6c0e8649113dc3a38'
32360 ],
32361 [
32362 'a6cbc3046bc6a450bac24789fa17115a4c9739ed75f8f21ce441f72e0b90e6ef',
32363 '21ae7f4680e889bb130619e2c0f95a360ceb573c70603139862afd617fa9b9f'
32364 ],
32365 [
32366 '347d6d9a02c48927ebfb86c1359b1caf130a3c0267d11ce6344b39f99d43cc38',
32367 '60ea7f61a353524d1c987f6ecec92f086d565ab687870cb12689ff1e31c74448'
32368 ],
32369 [
32370 'da6545d2181db8d983f7dcb375ef5866d47c67b1bf31c8cf855ef7437b72656a',
32371 '49b96715ab6878a79e78f07ce5680c5d6673051b4935bd897fea824b77dc208a'
32372 ],
32373 [
32374 'c40747cc9d012cb1a13b8148309c6de7ec25d6945d657146b9d5994b8feb1111',
32375 '5ca560753be2a12fc6de6caf2cb489565db936156b9514e1bb5e83037e0fa2d4'
32376 ],
32377 [
32378 '4e42c8ec82c99798ccf3a610be870e78338c7f713348bd34c8203ef4037f3502',
32379 '7571d74ee5e0fb92a7a8b33a07783341a5492144cc54bcc40a94473693606437'
32380 ],
32381 [
32382 '3775ab7089bc6af823aba2e1af70b236d251cadb0c86743287522a1b3b0dedea',
32383 'be52d107bcfa09d8bcb9736a828cfa7fac8db17bf7a76a2c42ad961409018cf7'
32384 ],
32385 [
32386 'cee31cbf7e34ec379d94fb814d3d775ad954595d1314ba8846959e3e82f74e26',
32387 '8fd64a14c06b589c26b947ae2bcf6bfa0149ef0be14ed4d80f448a01c43b1c6d'
32388 ],
32389 [
32390 'b4f9eaea09b6917619f6ea6a4eb5464efddb58fd45b1ebefcdc1a01d08b47986',
32391 '39e5c9925b5a54b07433a4f18c61726f8bb131c012ca542eb24a8ac07200682a'
32392 ],
32393 [
32394 'd4263dfc3d2df923a0179a48966d30ce84e2515afc3dccc1b77907792ebcc60e',
32395 '62dfaf07a0f78feb30e30d6295853ce189e127760ad6cf7fae164e122a208d54'
32396 ],
32397 [
32398 '48457524820fa65a4f8d35eb6930857c0032acc0a4a2de422233eeda897612c4',
32399 '25a748ab367979d98733c38a1fa1c2e7dc6cc07db2d60a9ae7a76aaa49bd0f77'
32400 ],
32401 [
32402 'dfeeef1881101f2cb11644f3a2afdfc2045e19919152923f367a1767c11cceda',
32403 'ecfb7056cf1de042f9420bab396793c0c390bde74b4bbdff16a83ae09a9a7517'
32404 ],
32405 [
32406 '6d7ef6b17543f8373c573f44e1f389835d89bcbc6062ced36c82df83b8fae859',
32407 'cd450ec335438986dfefa10c57fea9bcc521a0959b2d80bbf74b190dca712d10'
32408 ],
32409 [
32410 'e75605d59102a5a2684500d3b991f2e3f3c88b93225547035af25af66e04541f',
32411 'f5c54754a8f71ee540b9b48728473e314f729ac5308b06938360990e2bfad125'
32412 ],
32413 [
32414 'eb98660f4c4dfaa06a2be453d5020bc99a0c2e60abe388457dd43fefb1ed620c',
32415 '6cb9a8876d9cb8520609af3add26cd20a0a7cd8a9411131ce85f44100099223e'
32416 ],
32417 [
32418 '13e87b027d8514d35939f2e6892b19922154596941888336dc3563e3b8dba942',
32419 'fef5a3c68059a6dec5d624114bf1e91aac2b9da568d6abeb2570d55646b8adf1'
32420 ],
32421 [
32422 'ee163026e9fd6fe017c38f06a5be6fc125424b371ce2708e7bf4491691e5764a',
32423 '1acb250f255dd61c43d94ccc670d0f58f49ae3fa15b96623e5430da0ad6c62b2'
32424 ],
32425 [
32426 'b268f5ef9ad51e4d78de3a750c2dc89b1e626d43505867999932e5db33af3d80',
32427 '5f310d4b3c99b9ebb19f77d41c1dee018cf0d34fd4191614003e945a1216e423'
32428 ],
32429 [
32430 'ff07f3118a9df035e9fad85eb6c7bfe42b02f01ca99ceea3bf7ffdba93c4750d',
32431 '438136d603e858a3a5c440c38eccbaddc1d2942114e2eddd4740d098ced1f0d8'
32432 ],
32433 [
32434 '8d8b9855c7c052a34146fd20ffb658bea4b9f69e0d825ebec16e8c3ce2b526a1',
32435 'cdb559eedc2d79f926baf44fb84ea4d44bcf50fee51d7ceb30e2e7f463036758'
32436 ],
32437 [
32438 '52db0b5384dfbf05bfa9d472d7ae26dfe4b851ceca91b1eba54263180da32b63',
32439 'c3b997d050ee5d423ebaf66a6db9f57b3180c902875679de924b69d84a7b375'
32440 ],
32441 [
32442 'e62f9490d3d51da6395efd24e80919cc7d0f29c3f3fa48c6fff543becbd43352',
32443 '6d89ad7ba4876b0b22c2ca280c682862f342c8591f1daf5170e07bfd9ccafa7d'
32444 ],
32445 [
32446 '7f30ea2476b399b4957509c88f77d0191afa2ff5cb7b14fd6d8e7d65aaab1193',
32447 'ca5ef7d4b231c94c3b15389a5f6311e9daff7bb67b103e9880ef4bff637acaec'
32448 ],
32449 [
32450 '5098ff1e1d9f14fb46a210fada6c903fef0fb7b4a1dd1d9ac60a0361800b7a00',
32451 '9731141d81fc8f8084d37c6e7542006b3ee1b40d60dfe5362a5b132fd17ddc0'
32452 ],
32453 [
32454 '32b78c7de9ee512a72895be6b9cbefa6e2f3c4ccce445c96b9f2c81e2778ad58',
32455 'ee1849f513df71e32efc3896ee28260c73bb80547ae2275ba497237794c8753c'
32456 ],
32457 [
32458 'e2cb74fddc8e9fbcd076eef2a7c72b0ce37d50f08269dfc074b581550547a4f7',
32459 'd3aa2ed71c9dd2247a62df062736eb0baddea9e36122d2be8641abcb005cc4a4'
32460 ],
32461 [
32462 '8438447566d4d7bedadc299496ab357426009a35f235cb141be0d99cd10ae3a8',
32463 'c4e1020916980a4da5d01ac5e6ad330734ef0d7906631c4f2390426b2edd791f'
32464 ],
32465 [
32466 '4162d488b89402039b584c6fc6c308870587d9c46f660b878ab65c82c711d67e',
32467 '67163e903236289f776f22c25fb8a3afc1732f2b84b4e95dbda47ae5a0852649'
32468 ],
32469 [
32470 '3fad3fa84caf0f34f0f89bfd2dcf54fc175d767aec3e50684f3ba4a4bf5f683d',
32471 'cd1bc7cb6cc407bb2f0ca647c718a730cf71872e7d0d2a53fa20efcdfe61826'
32472 ],
32473 [
32474 '674f2600a3007a00568c1a7ce05d0816c1fb84bf1370798f1c69532faeb1a86b',
32475 '299d21f9413f33b3edf43b257004580b70db57da0b182259e09eecc69e0d38a5'
32476 ],
32477 [
32478 'd32f4da54ade74abb81b815ad1fb3b263d82d6c692714bcff87d29bd5ee9f08f',
32479 'f9429e738b8e53b968e99016c059707782e14f4535359d582fc416910b3eea87'
32480 ],
32481 [
32482 '30e4e670435385556e593657135845d36fbb6931f72b08cb1ed954f1e3ce3ff6',
32483 '462f9bce619898638499350113bbc9b10a878d35da70740dc695a559eb88db7b'
32484 ],
32485 [
32486 'be2062003c51cc3004682904330e4dee7f3dcd10b01e580bf1971b04d4cad297',
32487 '62188bc49d61e5428573d48a74e1c655b1c61090905682a0d5558ed72dccb9bc'
32488 ],
32489 [
32490 '93144423ace3451ed29e0fb9ac2af211cb6e84a601df5993c419859fff5df04a',
32491 '7c10dfb164c3425f5c71a3f9d7992038f1065224f72bb9d1d902a6d13037b47c'
32492 ],
32493 [
32494 'b015f8044f5fcbdcf21ca26d6c34fb8197829205c7b7d2a7cb66418c157b112c',
32495 'ab8c1e086d04e813744a655b2df8d5f83b3cdc6faa3088c1d3aea1454e3a1d5f'
32496 ],
32497 [
32498 'd5e9e1da649d97d89e4868117a465a3a4f8a18de57a140d36b3f2af341a21b52',
32499 '4cb04437f391ed73111a13cc1d4dd0db1693465c2240480d8955e8592f27447a'
32500 ],
32501 [
32502 'd3ae41047dd7ca065dbf8ed77b992439983005cd72e16d6f996a5316d36966bb',
32503 'bd1aeb21ad22ebb22a10f0303417c6d964f8cdd7df0aca614b10dc14d125ac46'
32504 ],
32505 [
32506 '463e2763d885f958fc66cdd22800f0a487197d0a82e377b49f80af87c897b065',
32507 'bfefacdb0e5d0fd7df3a311a94de062b26b80c61fbc97508b79992671ef7ca7f'
32508 ],
32509 [
32510 '7985fdfd127c0567c6f53ec1bb63ec3158e597c40bfe747c83cddfc910641917',
32511 '603c12daf3d9862ef2b25fe1de289aed24ed291e0ec6708703a5bd567f32ed03'
32512 ],
32513 [
32514 '74a1ad6b5f76e39db2dd249410eac7f99e74c59cb83d2d0ed5ff1543da7703e9',
32515 'cc6157ef18c9c63cd6193d83631bbea0093e0968942e8c33d5737fd790e0db08'
32516 ],
32517 [
32518 '30682a50703375f602d416664ba19b7fc9bab42c72747463a71d0896b22f6da3',
32519 '553e04f6b018b4fa6c8f39e7f311d3176290d0e0f19ca73f17714d9977a22ff8'
32520 ],
32521 [
32522 '9e2158f0d7c0d5f26c3791efefa79597654e7a2b2464f52b1ee6c1347769ef57',
32523 '712fcdd1b9053f09003a3481fa7762e9ffd7c8ef35a38509e2fbf2629008373'
32524 ],
32525 [
32526 '176e26989a43c9cfeba4029c202538c28172e566e3c4fce7322857f3be327d66',
32527 'ed8cc9d04b29eb877d270b4878dc43c19aefd31f4eee09ee7b47834c1fa4b1c3'
32528 ],
32529 [
32530 '75d46efea3771e6e68abb89a13ad747ecf1892393dfc4f1b7004788c50374da8',
32531 '9852390a99507679fd0b86fd2b39a868d7efc22151346e1a3ca4726586a6bed8'
32532 ],
32533 [
32534 '809a20c67d64900ffb698c4c825f6d5f2310fb0451c869345b7319f645605721',
32535 '9e994980d9917e22b76b061927fa04143d096ccc54963e6a5ebfa5f3f8e286c1'
32536 ],
32537 [
32538 '1b38903a43f7f114ed4500b4eac7083fdefece1cf29c63528d563446f972c180',
32539 '4036edc931a60ae889353f77fd53de4a2708b26b6f5da72ad3394119daf408f9'
32540 ]
32541 ]
32542 }
32543};
32544
32545},{}],156:[function(require,module,exports){
32546'use strict';
32547
32548var utils = exports;
32549var BN = require('bn.js');
32550var minAssert = require('minimalistic-assert');
32551var minUtils = require('minimalistic-crypto-utils');
32552
32553utils.assert = minAssert;
32554utils.toArray = minUtils.toArray;
32555utils.zero2 = minUtils.zero2;
32556utils.toHex = minUtils.toHex;
32557utils.encode = minUtils.encode;
32558
32559// Represent num in a w-NAF form
32560function getNAF(num, w) {
32561 var naf = [];
32562 var ws = 1 << (w + 1);
32563 var k = num.clone();
32564 while (k.cmpn(1) >= 0) {
32565 var z;
32566 if (k.isOdd()) {
32567 var mod = k.andln(ws - 1);
32568 if (mod > (ws >> 1) - 1)
32569 z = (ws >> 1) - mod;
32570 else
32571 z = mod;
32572 k.isubn(z);
32573 } else {
32574 z = 0;
32575 }
32576 naf.push(z);
32577
32578 // Optimization, shift by word if possible
32579 var shift = (k.cmpn(0) !== 0 && k.andln(ws - 1) === 0) ? (w + 1) : 1;
32580 for (var i = 1; i < shift; i++)
32581 naf.push(0);
32582 k.iushrn(shift);
32583 }
32584
32585 return naf;
32586}
32587utils.getNAF = getNAF;
32588
32589// Represent k1, k2 in a Joint Sparse Form
32590function getJSF(k1, k2) {
32591 var jsf = [
32592 [],
32593 []
32594 ];
32595
32596 k1 = k1.clone();
32597 k2 = k2.clone();
32598 var d1 = 0;
32599 var d2 = 0;
32600 while (k1.cmpn(-d1) > 0 || k2.cmpn(-d2) > 0) {
32601
32602 // First phase
32603 var m14 = (k1.andln(3) + d1) & 3;
32604 var m24 = (k2.andln(3) + d2) & 3;
32605 if (m14 === 3)
32606 m14 = -1;
32607 if (m24 === 3)
32608 m24 = -1;
32609 var u1;
32610 if ((m14 & 1) === 0) {
32611 u1 = 0;
32612 } else {
32613 var m8 = (k1.andln(7) + d1) & 7;
32614 if ((m8 === 3 || m8 === 5) && m24 === 2)
32615 u1 = -m14;
32616 else
32617 u1 = m14;
32618 }
32619 jsf[0].push(u1);
32620
32621 var u2;
32622 if ((m24 & 1) === 0) {
32623 u2 = 0;
32624 } else {
32625 var m8 = (k2.andln(7) + d2) & 7;
32626 if ((m8 === 3 || m8 === 5) && m14 === 2)
32627 u2 = -m24;
32628 else
32629 u2 = m24;
32630 }
32631 jsf[1].push(u2);
32632
32633 // Second phase
32634 if (2 * d1 === u1 + 1)
32635 d1 = 1 - d1;
32636 if (2 * d2 === u2 + 1)
32637 d2 = 1 - d2;
32638 k1.iushrn(1);
32639 k2.iushrn(1);
32640 }
32641
32642 return jsf;
32643}
32644utils.getJSF = getJSF;
32645
32646function cachedProperty(obj, name, computer) {
32647 var key = '_' + name;
32648 obj.prototype[name] = function cachedProperty() {
32649 return this[key] !== undefined ? this[key] :
32650 this[key] = computer.call(this);
32651 };
32652}
32653utils.cachedProperty = cachedProperty;
32654
32655function parseBytes(bytes) {
32656 return typeof bytes === 'string' ? utils.toArray(bytes, 'hex') :
32657 bytes;
32658}
32659utils.parseBytes = parseBytes;
32660
32661function intFromLE(bytes) {
32662 return new BN(bytes, 'hex', 'le');
32663}
32664utils.intFromLE = intFromLE;
32665
32666
32667},{"bn.js":80,"minimalistic-assert":237,"minimalistic-crypto-utils":238}],157:[function(require,module,exports){
32668module.exports={
32669 "name": "elliptic",
32670 "version": "6.4.1",
32671 "description": "EC cryptography",
32672 "main": "lib/elliptic.js",
32673 "files": [
32674 "lib"
32675 ],
32676 "scripts": {
32677 "jscs": "jscs benchmarks/*.js lib/*.js lib/**/*.js lib/**/**/*.js test/index.js",
32678 "jshint": "jscs benchmarks/*.js lib/*.js lib/**/*.js lib/**/**/*.js test/index.js",
32679 "lint": "npm run jscs && npm run jshint",
32680 "unit": "istanbul test _mocha --reporter=spec test/index.js",
32681 "test": "npm run lint && npm run unit",
32682 "version": "grunt dist && git add dist/"
32683 },
32684 "repository": {
32685 "type": "git",
32686 "url": "git@github.com:indutny/elliptic"
32687 },
32688 "keywords": [
32689 "EC",
32690 "Elliptic",
32691 "curve",
32692 "Cryptography"
32693 ],
32694 "author": "Fedor Indutny <fedor@indutny.com>",
32695 "license": "MIT",
32696 "bugs": {
32697 "url": "https://github.com/indutny/elliptic/issues"
32698 },
32699 "homepage": "https://github.com/indutny/elliptic",
32700 "devDependencies": {
32701 "brfs": "^1.4.3",
32702 "coveralls": "^2.11.3",
32703 "grunt": "^0.4.5",
32704 "grunt-browserify": "^5.0.0",
32705 "grunt-cli": "^1.2.0",
32706 "grunt-contrib-connect": "^1.0.0",
32707 "grunt-contrib-copy": "^1.0.0",
32708 "grunt-contrib-uglify": "^1.0.1",
32709 "grunt-mocha-istanbul": "^3.0.1",
32710 "grunt-saucelabs": "^8.6.2",
32711 "istanbul": "^0.4.2",
32712 "jscs": "^2.9.0",
32713 "jshint": "^2.6.0",
32714 "mocha": "^2.1.0"
32715 },
32716 "dependencies": {
32717 "bn.js": "^4.4.0",
32718 "brorand": "^1.0.1",
32719 "hash.js": "^1.0.0",
32720 "hmac-drbg": "^1.0.0",
32721 "inherits": "^2.0.1",
32722 "minimalistic-assert": "^1.0.0",
32723 "minimalistic-crypto-utils": "^1.0.0"
32724 }
32725}
32726
32727},{}],158:[function(require,module,exports){
32728(function (root, factory) {
32729 /* istanbul ignore next */
32730 if (typeof define === 'function' && define.amd) {
32731 define([], factory)
32732 } else if (typeof exports === 'object') {
32733 module.exports = factory()
32734 } else {
32735 root.PromisePool = factory()
32736 // Legacy API
32737 root.promisePool = root.PromisePool
32738 }
32739})(this, function () {
32740 'use strict'
32741
32742 var EventTarget = function () {
32743 this._listeners = {}
32744 }
32745
32746 EventTarget.prototype.addEventListener = function (type, listener) {
32747 this._listeners[type] = this._listeners[type] || []
32748 if (this._listeners[type].indexOf(listener) < 0) {
32749 this._listeners[type].push(listener)
32750 }
32751 }
32752
32753 EventTarget.prototype.removeEventListener = function (type, listener) {
32754 if (this._listeners[type]) {
32755 var p = this._listeners[type].indexOf(listener)
32756 if (p >= 0) {
32757 this._listeners[type].splice(p, 1)
32758 }
32759 }
32760 }
32761
32762 EventTarget.prototype.dispatchEvent = function (evt) {
32763 if (this._listeners[evt.type] && this._listeners[evt.type].length) {
32764 var listeners = this._listeners[evt.type].slice()
32765 for (var i = 0, l = listeners.length; i < l; ++i) {
32766 listeners[i].call(this, evt)
32767 }
32768 }
32769 }
32770
32771 var isGenerator = function (func) {
32772 return (typeof func.constructor === 'function' &&
32773 func.constructor.name === 'GeneratorFunction')
32774 }
32775
32776 var functionToIterator = function (func) {
32777 return {
32778 next: function () {
32779 var promise = func()
32780 return promise ? {value: promise} : {done: true}
32781 }
32782 }
32783 }
32784
32785 var promiseToIterator = function (promise) {
32786 var called = false
32787 return {
32788 next: function () {
32789 if (called) {
32790 return {done: true}
32791 }
32792 called = true
32793 return {value: promise}
32794 }
32795 }
32796 }
32797
32798 var toIterator = function (obj, Promise) {
32799 var type = typeof obj
32800 if (type === 'object') {
32801 if (typeof obj.next === 'function') {
32802 return obj
32803 }
32804 /* istanbul ignore else */
32805 if (typeof obj.then === 'function') {
32806 return promiseToIterator(obj)
32807 }
32808 }
32809 if (type === 'function') {
32810 return isGenerator(obj) ? obj() : functionToIterator(obj)
32811 }
32812 return promiseToIterator(Promise.resolve(obj))
32813 }
32814
32815 var PromisePoolEvent = function (target, type, data) {
32816 this.target = target
32817 this.type = type
32818 this.data = data
32819 }
32820
32821 var PromisePool = function (source, concurrency, options) {
32822 EventTarget.call(this)
32823 if (typeof concurrency !== 'number' ||
32824 Math.floor(concurrency) !== concurrency ||
32825 concurrency < 1) {
32826 throw new Error('Invalid concurrency')
32827 }
32828 this._concurrency = concurrency
32829 this._options = options || {}
32830 this._options.promise = this._options.promise || Promise
32831 this._iterator = toIterator(source, this._options.promise)
32832 this._done = false
32833 this._size = 0
32834 this._promise = null
32835 this._callbacks = null
32836 }
32837 PromisePool.prototype = new EventTarget()
32838 PromisePool.prototype.constructor = PromisePool
32839
32840 PromisePool.prototype.concurrency = function (value) {
32841 if (typeof value !== 'undefined') {
32842 this._concurrency = value
32843 if (this.active()) {
32844 this._proceed()
32845 }
32846 }
32847 return this._concurrency
32848 }
32849
32850 PromisePool.prototype.size = function () {
32851 return this._size
32852 }
32853
32854 PromisePool.prototype.active = function () {
32855 return !!this._promise
32856 }
32857
32858 PromisePool.prototype.promise = function () {
32859 return this._promise
32860 }
32861
32862 PromisePool.prototype.start = function () {
32863 var that = this
32864 var Promise = this._options.promise
32865 this._promise = new Promise(function (resolve, reject) {
32866 that._callbacks = {
32867 reject: reject,
32868 resolve: resolve
32869 }
32870 that._proceed()
32871 })
32872 return this._promise
32873 }
32874
32875 PromisePool.prototype._fireEvent = function (type, data) {
32876 this.dispatchEvent(new PromisePoolEvent(this, type, data))
32877 }
32878
32879 PromisePool.prototype._settle = function (error) {
32880 if (error) {
32881 this._callbacks.reject(error)
32882 } else {
32883 this._callbacks.resolve()
32884 }
32885 this._promise = null
32886 this._callbacks = null
32887 }
32888
32889 PromisePool.prototype._onPooledPromiseFulfilled = function (promise, result) {
32890 this._size--
32891 if (this.active()) {
32892 this._fireEvent('fulfilled', {
32893 promise: promise,
32894 result: result
32895 })
32896 this._proceed()
32897 }
32898 }
32899
32900 PromisePool.prototype._onPooledPromiseRejected = function (promise, error) {
32901 this._size--
32902 if (this.active()) {
32903 this._fireEvent('rejected', {
32904 promise: promise,
32905 error: error
32906 })
32907 this._settle(error || new Error('Unknown error'))
32908 }
32909 }
32910
32911 PromisePool.prototype._trackPromise = function (promise) {
32912 var that = this
32913 promise
32914 .then(function (result) {
32915 that._onPooledPromiseFulfilled(promise, result)
32916 }, function (error) {
32917 that._onPooledPromiseRejected(promise, error)
32918 })['catch'](function (err) {
32919 that._settle(new Error('Promise processing failed: ' + err))
32920 })
32921 }
32922
32923 PromisePool.prototype._proceed = function () {
32924 if (!this._done) {
32925 var result = { done: false }
32926 while (this._size < this._concurrency &&
32927 !(result = this._iterator.next()).done) {
32928 this._size++
32929 this._trackPromise(result.value)
32930 }
32931 this._done = (result === null || !!result.done)
32932 }
32933 if (this._done && this._size === 0) {
32934 this._settle()
32935 }
32936 }
32937
32938 PromisePool.PromisePoolEvent = PromisePoolEvent
32939 // Legacy API
32940 PromisePool.PromisePool = PromisePool
32941
32942 return PromisePool
32943})
32944
32945},{}],159:[function(require,module,exports){
32946// Copyright Joyent, Inc. and other Node contributors.
32947//
32948// Permission is hereby granted, free of charge, to any person obtaining a
32949// copy of this software and associated documentation files (the
32950// "Software"), to deal in the Software without restriction, including
32951// without limitation the rights to use, copy, modify, merge, publish,
32952// distribute, sublicense, and/or sell copies of the Software, and to permit
32953// persons to whom the Software is furnished to do so, subject to the
32954// following conditions:
32955//
32956// The above copyright notice and this permission notice shall be included
32957// in all copies or substantial portions of the Software.
32958//
32959// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
32960// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
32961// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
32962// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
32963// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
32964// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
32965// USE OR OTHER DEALINGS IN THE SOFTWARE.
32966
32967var objectCreate = Object.create || objectCreatePolyfill
32968var objectKeys = Object.keys || objectKeysPolyfill
32969var bind = Function.prototype.bind || functionBindPolyfill
32970
32971function EventEmitter() {
32972 if (!this._events || !Object.prototype.hasOwnProperty.call(this, '_events')) {
32973 this._events = objectCreate(null);
32974 this._eventsCount = 0;
32975 }
32976
32977 this._maxListeners = this._maxListeners || undefined;
32978}
32979module.exports = EventEmitter;
32980
32981// Backwards-compat with node 0.10.x
32982EventEmitter.EventEmitter = EventEmitter;
32983
32984EventEmitter.prototype._events = undefined;
32985EventEmitter.prototype._maxListeners = undefined;
32986
32987// By default EventEmitters will print a warning if more than 10 listeners are
32988// added to it. This is a useful default which helps finding memory leaks.
32989var defaultMaxListeners = 10;
32990
32991var hasDefineProperty;
32992try {
32993 var o = {};
32994 if (Object.defineProperty) Object.defineProperty(o, 'x', { value: 0 });
32995 hasDefineProperty = o.x === 0;
32996} catch (err) { hasDefineProperty = false }
32997if (hasDefineProperty) {
32998 Object.defineProperty(EventEmitter, 'defaultMaxListeners', {
32999 enumerable: true,
33000 get: function() {
33001 return defaultMaxListeners;
33002 },
33003 set: function(arg) {
33004 // check whether the input is a positive number (whose value is zero or
33005 // greater and not a NaN).
33006 if (typeof arg !== 'number' || arg < 0 || arg !== arg)
33007 throw new TypeError('"defaultMaxListeners" must be a positive number');
33008 defaultMaxListeners = arg;
33009 }
33010 });
33011} else {
33012 EventEmitter.defaultMaxListeners = defaultMaxListeners;
33013}
33014
33015// Obviously not all Emitters should be limited to 10. This function allows
33016// that to be increased. Set to zero for unlimited.
33017EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) {
33018 if (typeof n !== 'number' || n < 0 || isNaN(n))
33019 throw new TypeError('"n" argument must be a positive number');
33020 this._maxListeners = n;
33021 return this;
33022};
33023
33024function $getMaxListeners(that) {
33025 if (that._maxListeners === undefined)
33026 return EventEmitter.defaultMaxListeners;
33027 return that._maxListeners;
33028}
33029
33030EventEmitter.prototype.getMaxListeners = function getMaxListeners() {
33031 return $getMaxListeners(this);
33032};
33033
33034// These standalone emit* functions are used to optimize calling of event
33035// handlers for fast cases because emit() itself often has a variable number of
33036// arguments and can be deoptimized because of that. These functions always have
33037// the same number of arguments and thus do not get deoptimized, so the code
33038// inside them can execute faster.
33039function emitNone(handler, isFn, self) {
33040 if (isFn)
33041 handler.call(self);
33042 else {
33043 var len = handler.length;
33044 var listeners = arrayClone(handler, len);
33045 for (var i = 0; i < len; ++i)
33046 listeners[i].call(self);
33047 }
33048}
33049function emitOne(handler, isFn, self, arg1) {
33050 if (isFn)
33051 handler.call(self, arg1);
33052 else {
33053 var len = handler.length;
33054 var listeners = arrayClone(handler, len);
33055 for (var i = 0; i < len; ++i)
33056 listeners[i].call(self, arg1);
33057 }
33058}
33059function emitTwo(handler, isFn, self, arg1, arg2) {
33060 if (isFn)
33061 handler.call(self, arg1, arg2);
33062 else {
33063 var len = handler.length;
33064 var listeners = arrayClone(handler, len);
33065 for (var i = 0; i < len; ++i)
33066 listeners[i].call(self, arg1, arg2);
33067 }
33068}
33069function emitThree(handler, isFn, self, arg1, arg2, arg3) {
33070 if (isFn)
33071 handler.call(self, arg1, arg2, arg3);
33072 else {
33073 var len = handler.length;
33074 var listeners = arrayClone(handler, len);
33075 for (var i = 0; i < len; ++i)
33076 listeners[i].call(self, arg1, arg2, arg3);
33077 }
33078}
33079
33080function emitMany(handler, isFn, self, args) {
33081 if (isFn)
33082 handler.apply(self, args);
33083 else {
33084 var len = handler.length;
33085 var listeners = arrayClone(handler, len);
33086 for (var i = 0; i < len; ++i)
33087 listeners[i].apply(self, args);
33088 }
33089}
33090
33091EventEmitter.prototype.emit = function emit(type) {
33092 var er, handler, len, args, i, events;
33093 var doError = (type === 'error');
33094
33095 events = this._events;
33096 if (events)
33097 doError = (doError && events.error == null);
33098 else if (!doError)
33099 return false;
33100
33101 // If there is no 'error' event listener then throw.
33102 if (doError) {
33103 if (arguments.length > 1)
33104 er = arguments[1];
33105 if (er instanceof Error) {
33106 throw er; // Unhandled 'error' event
33107 } else {
33108 // At least give some kind of context to the user
33109 var err = new Error('Unhandled "error" event. (' + er + ')');
33110 err.context = er;
33111 throw err;
33112 }
33113 return false;
33114 }
33115
33116 handler = events[type];
33117
33118 if (!handler)
33119 return false;
33120
33121 var isFn = typeof handler === 'function';
33122 len = arguments.length;
33123 switch (len) {
33124 // fast cases
33125 case 1:
33126 emitNone(handler, isFn, this);
33127 break;
33128 case 2:
33129 emitOne(handler, isFn, this, arguments[1]);
33130 break;
33131 case 3:
33132 emitTwo(handler, isFn, this, arguments[1], arguments[2]);
33133 break;
33134 case 4:
33135 emitThree(handler, isFn, this, arguments[1], arguments[2], arguments[3]);
33136 break;
33137 // slower
33138 default:
33139 args = new Array(len - 1);
33140 for (i = 1; i < len; i++)
33141 args[i - 1] = arguments[i];
33142 emitMany(handler, isFn, this, args);
33143 }
33144
33145 return true;
33146};
33147
33148function _addListener(target, type, listener, prepend) {
33149 var m;
33150 var events;
33151 var existing;
33152
33153 if (typeof listener !== 'function')
33154 throw new TypeError('"listener" argument must be a function');
33155
33156 events = target._events;
33157 if (!events) {
33158 events = target._events = objectCreate(null);
33159 target._eventsCount = 0;
33160 } else {
33161 // To avoid recursion in the case that type === "newListener"! Before
33162 // adding it to the listeners, first emit "newListener".
33163 if (events.newListener) {
33164 target.emit('newListener', type,
33165 listener.listener ? listener.listener : listener);
33166
33167 // Re-assign `events` because a newListener handler could have caused the
33168 // this._events to be assigned to a new object
33169 events = target._events;
33170 }
33171 existing = events[type];
33172 }
33173
33174 if (!existing) {
33175 // Optimize the case of one listener. Don't need the extra array object.
33176 existing = events[type] = listener;
33177 ++target._eventsCount;
33178 } else {
33179 if (typeof existing === 'function') {
33180 // Adding the second element, need to change to array.
33181 existing = events[type] =
33182 prepend ? [listener, existing] : [existing, listener];
33183 } else {
33184 // If we've already got an array, just append.
33185 if (prepend) {
33186 existing.unshift(listener);
33187 } else {
33188 existing.push(listener);
33189 }
33190 }
33191
33192 // Check for listener leak
33193 if (!existing.warned) {
33194 m = $getMaxListeners(target);
33195 if (m && m > 0 && existing.length > m) {
33196 existing.warned = true;
33197 var w = new Error('Possible EventEmitter memory leak detected. ' +
33198 existing.length + ' "' + String(type) + '" listeners ' +
33199 'added. Use emitter.setMaxListeners() to ' +
33200 'increase limit.');
33201 w.name = 'MaxListenersExceededWarning';
33202 w.emitter = target;
33203 w.type = type;
33204 w.count = existing.length;
33205 if (typeof console === 'object' && console.warn) {
33206 console.warn('%s: %s', w.name, w.message);
33207 }
33208 }
33209 }
33210 }
33211
33212 return target;
33213}
33214
33215EventEmitter.prototype.addListener = function addListener(type, listener) {
33216 return _addListener(this, type, listener, false);
33217};
33218
33219EventEmitter.prototype.on = EventEmitter.prototype.addListener;
33220
33221EventEmitter.prototype.prependListener =
33222 function prependListener(type, listener) {
33223 return _addListener(this, type, listener, true);
33224 };
33225
33226function onceWrapper() {
33227 if (!this.fired) {
33228 this.target.removeListener(this.type, this.wrapFn);
33229 this.fired = true;
33230 switch (arguments.length) {
33231 case 0:
33232 return this.listener.call(this.target);
33233 case 1:
33234 return this.listener.call(this.target, arguments[0]);
33235 case 2:
33236 return this.listener.call(this.target, arguments[0], arguments[1]);
33237 case 3:
33238 return this.listener.call(this.target, arguments[0], arguments[1],
33239 arguments[2]);
33240 default:
33241 var args = new Array(arguments.length);
33242 for (var i = 0; i < args.length; ++i)
33243 args[i] = arguments[i];
33244 this.listener.apply(this.target, args);
33245 }
33246 }
33247}
33248
33249function _onceWrap(target, type, listener) {
33250 var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener };
33251 var wrapped = bind.call(onceWrapper, state);
33252 wrapped.listener = listener;
33253 state.wrapFn = wrapped;
33254 return wrapped;
33255}
33256
33257EventEmitter.prototype.once = function once(type, listener) {
33258 if (typeof listener !== 'function')
33259 throw new TypeError('"listener" argument must be a function');
33260 this.on(type, _onceWrap(this, type, listener));
33261 return this;
33262};
33263
33264EventEmitter.prototype.prependOnceListener =
33265 function prependOnceListener(type, listener) {
33266 if (typeof listener !== 'function')
33267 throw new TypeError('"listener" argument must be a function');
33268 this.prependListener(type, _onceWrap(this, type, listener));
33269 return this;
33270 };
33271
33272// Emits a 'removeListener' event if and only if the listener was removed.
33273EventEmitter.prototype.removeListener =
33274 function removeListener(type, listener) {
33275 var list, events, position, i, originalListener;
33276
33277 if (typeof listener !== 'function')
33278 throw new TypeError('"listener" argument must be a function');
33279
33280 events = this._events;
33281 if (!events)
33282 return this;
33283
33284 list = events[type];
33285 if (!list)
33286 return this;
33287
33288 if (list === listener || list.listener === listener) {
33289 if (--this._eventsCount === 0)
33290 this._events = objectCreate(null);
33291 else {
33292 delete events[type];
33293 if (events.removeListener)
33294 this.emit('removeListener', type, list.listener || listener);
33295 }
33296 } else if (typeof list !== 'function') {
33297 position = -1;
33298
33299 for (i = list.length - 1; i >= 0; i--) {
33300 if (list[i] === listener || list[i].listener === listener) {
33301 originalListener = list[i].listener;
33302 position = i;
33303 break;
33304 }
33305 }
33306
33307 if (position < 0)
33308 return this;
33309
33310 if (position === 0)
33311 list.shift();
33312 else
33313 spliceOne(list, position);
33314
33315 if (list.length === 1)
33316 events[type] = list[0];
33317
33318 if (events.removeListener)
33319 this.emit('removeListener', type, originalListener || listener);
33320 }
33321
33322 return this;
33323 };
33324
33325EventEmitter.prototype.removeAllListeners =
33326 function removeAllListeners(type) {
33327 var listeners, events, i;
33328
33329 events = this._events;
33330 if (!events)
33331 return this;
33332
33333 // not listening for removeListener, no need to emit
33334 if (!events.removeListener) {
33335 if (arguments.length === 0) {
33336 this._events = objectCreate(null);
33337 this._eventsCount = 0;
33338 } else if (events[type]) {
33339 if (--this._eventsCount === 0)
33340 this._events = objectCreate(null);
33341 else
33342 delete events[type];
33343 }
33344 return this;
33345 }
33346
33347 // emit removeListener for all listeners on all events
33348 if (arguments.length === 0) {
33349 var keys = objectKeys(events);
33350 var key;
33351 for (i = 0; i < keys.length; ++i) {
33352 key = keys[i];
33353 if (key === 'removeListener') continue;
33354 this.removeAllListeners(key);
33355 }
33356 this.removeAllListeners('removeListener');
33357 this._events = objectCreate(null);
33358 this._eventsCount = 0;
33359 return this;
33360 }
33361
33362 listeners = events[type];
33363
33364 if (typeof listeners === 'function') {
33365 this.removeListener(type, listeners);
33366 } else if (listeners) {
33367 // LIFO order
33368 for (i = listeners.length - 1; i >= 0; i--) {
33369 this.removeListener(type, listeners[i]);
33370 }
33371 }
33372
33373 return this;
33374 };
33375
33376function _listeners(target, type, unwrap) {
33377 var events = target._events;
33378
33379 if (!events)
33380 return [];
33381
33382 var evlistener = events[type];
33383 if (!evlistener)
33384 return [];
33385
33386 if (typeof evlistener === 'function')
33387 return unwrap ? [evlistener.listener || evlistener] : [evlistener];
33388
33389 return unwrap ? unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length);
33390}
33391
33392EventEmitter.prototype.listeners = function listeners(type) {
33393 return _listeners(this, type, true);
33394};
33395
33396EventEmitter.prototype.rawListeners = function rawListeners(type) {
33397 return _listeners(this, type, false);
33398};
33399
33400EventEmitter.listenerCount = function(emitter, type) {
33401 if (typeof emitter.listenerCount === 'function') {
33402 return emitter.listenerCount(type);
33403 } else {
33404 return listenerCount.call(emitter, type);
33405 }
33406};
33407
33408EventEmitter.prototype.listenerCount = listenerCount;
33409function listenerCount(type) {
33410 var events = this._events;
33411
33412 if (events) {
33413 var evlistener = events[type];
33414
33415 if (typeof evlistener === 'function') {
33416 return 1;
33417 } else if (evlistener) {
33418 return evlistener.length;
33419 }
33420 }
33421
33422 return 0;
33423}
33424
33425EventEmitter.prototype.eventNames = function eventNames() {
33426 return this._eventsCount > 0 ? Reflect.ownKeys(this._events) : [];
33427};
33428
33429// About 1.5x faster than the two-arg version of Array#splice().
33430function spliceOne(list, index) {
33431 for (var i = index, k = i + 1, n = list.length; k < n; i += 1, k += 1)
33432 list[i] = list[k];
33433 list.pop();
33434}
33435
33436function arrayClone(arr, n) {
33437 var copy = new Array(n);
33438 for (var i = 0; i < n; ++i)
33439 copy[i] = arr[i];
33440 return copy;
33441}
33442
33443function unwrapListeners(arr) {
33444 var ret = new Array(arr.length);
33445 for (var i = 0; i < ret.length; ++i) {
33446 ret[i] = arr[i].listener || arr[i];
33447 }
33448 return ret;
33449}
33450
33451function objectCreatePolyfill(proto) {
33452 var F = function() {};
33453 F.prototype = proto;
33454 return new F;
33455}
33456function objectKeysPolyfill(obj) {
33457 var keys = [];
33458 for (var k in obj) if (Object.prototype.hasOwnProperty.call(obj, k)) {
33459 keys.push(k);
33460 }
33461 return k;
33462}
33463function functionBindPolyfill(context) {
33464 var fn = this;
33465 return function () {
33466 return fn.apply(context, arguments);
33467 };
33468}
33469
33470},{}],160:[function(require,module,exports){
33471var Buffer = require('safe-buffer').Buffer
33472var MD5 = require('md5.js')
33473
33474/* eslint-disable camelcase */
33475function EVP_BytesToKey (password, salt, keyBits, ivLen) {
33476 if (!Buffer.isBuffer(password)) password = Buffer.from(password, 'binary')
33477 if (salt) {
33478 if (!Buffer.isBuffer(salt)) salt = Buffer.from(salt, 'binary')
33479 if (salt.length !== 8) throw new RangeError('salt should be Buffer with 8 byte length')
33480 }
33481
33482 var keyLen = keyBits / 8
33483 var key = Buffer.alloc(keyLen)
33484 var iv = Buffer.alloc(ivLen || 0)
33485 var tmp = Buffer.alloc(0)
33486
33487 while (keyLen > 0 || ivLen > 0) {
33488 var hash = new MD5()
33489 hash.update(tmp)
33490 hash.update(password)
33491 if (salt) hash.update(salt)
33492 tmp = hash.digest()
33493
33494 var used = 0
33495
33496 if (keyLen > 0) {
33497 var keyStart = key.length - keyLen
33498 used = Math.min(keyLen, tmp.length)
33499 tmp.copy(key, keyStart, 0, used)
33500 keyLen -= used
33501 }
33502
33503 if (used < tmp.length && ivLen > 0) {
33504 var ivStart = iv.length - ivLen
33505 var length = Math.min(ivLen, tmp.length - used)
33506 tmp.copy(iv, ivStart, used, used + length)
33507 ivLen -= length
33508 }
33509 }
33510
33511 tmp.fill(0)
33512 return { key: key, iv: iv }
33513}
33514
33515module.exports = EVP_BytesToKey
33516
33517},{"md5.js":232,"safe-buffer":325}],161:[function(require,module,exports){
33518'use strict';
33519
33520var hasOwn = Object.prototype.hasOwnProperty;
33521var toStr = Object.prototype.toString;
33522var defineProperty = Object.defineProperty;
33523var gOPD = Object.getOwnPropertyDescriptor;
33524
33525var isArray = function isArray(arr) {
33526 if (typeof Array.isArray === 'function') {
33527 return Array.isArray(arr);
33528 }
33529
33530 return toStr.call(arr) === '[object Array]';
33531};
33532
33533var isPlainObject = function isPlainObject(obj) {
33534 if (!obj || toStr.call(obj) !== '[object Object]') {
33535 return false;
33536 }
33537
33538 var hasOwnConstructor = hasOwn.call(obj, 'constructor');
33539 var hasIsPrototypeOf = obj.constructor && obj.constructor.prototype && hasOwn.call(obj.constructor.prototype, 'isPrototypeOf');
33540 // Not own constructor property must be Object
33541 if (obj.constructor && !hasOwnConstructor && !hasIsPrototypeOf) {
33542 return false;
33543 }
33544
33545 // Own properties are enumerated firstly, so to speed up,
33546 // if last one is own, then all properties are own.
33547 var key;
33548 for (key in obj) { /**/ }
33549
33550 return typeof key === 'undefined' || hasOwn.call(obj, key);
33551};
33552
33553// If name is '__proto__', and Object.defineProperty is available, define __proto__ as an own property on target
33554var setProperty = function setProperty(target, options) {
33555 if (defineProperty && options.name === '__proto__') {
33556 defineProperty(target, options.name, {
33557 enumerable: true,
33558 configurable: true,
33559 value: options.newValue,
33560 writable: true
33561 });
33562 } else {
33563 target[options.name] = options.newValue;
33564 }
33565};
33566
33567// Return undefined instead of __proto__ if '__proto__' is not an own property
33568var getProperty = function getProperty(obj, name) {
33569 if (name === '__proto__') {
33570 if (!hasOwn.call(obj, name)) {
33571 return void 0;
33572 } else if (gOPD) {
33573 // In early versions of node, obj['__proto__'] is buggy when obj has
33574 // __proto__ as an own property. Object.getOwnPropertyDescriptor() works.
33575 return gOPD(obj, name).value;
33576 }
33577 }
33578
33579 return obj[name];
33580};
33581
33582module.exports = function extend() {
33583 var options, name, src, copy, copyIsArray, clone;
33584 var target = arguments[0];
33585 var i = 1;
33586 var length = arguments.length;
33587 var deep = false;
33588
33589 // Handle a deep copy situation
33590 if (typeof target === 'boolean') {
33591 deep = target;
33592 target = arguments[1] || {};
33593 // skip the boolean and the target
33594 i = 2;
33595 }
33596 if (target == null || (typeof target !== 'object' && typeof target !== 'function')) {
33597 target = {};
33598 }
33599
33600 for (; i < length; ++i) {
33601 options = arguments[i];
33602 // Only deal with non-null/undefined values
33603 if (options != null) {
33604 // Extend the base object
33605 for (name in options) {
33606 src = getProperty(target, name);
33607 copy = getProperty(options, name);
33608
33609 // Prevent never-ending loop
33610 if (target !== copy) {
33611 // Recurse if we're merging plain objects or arrays
33612 if (deep && copy && (isPlainObject(copy) || (copyIsArray = isArray(copy)))) {
33613 if (copyIsArray) {
33614 copyIsArray = false;
33615 clone = src && isArray(src) ? src : [];
33616 } else {
33617 clone = src && isPlainObject(src) ? src : {};
33618 }
33619
33620 // Never move original objects, clone them
33621 setProperty(target, { name: name, newValue: extend(deep, clone, copy) });
33622
33623 // Don't bring in undefined values
33624 } else if (typeof copy !== 'undefined') {
33625 setProperty(target, { name: name, newValue: copy });
33626 }
33627 }
33628 }
33629 }
33630 }
33631
33632 // Return the modified object
33633 return target;
33634};
33635
33636},{}],162:[function(require,module,exports){
33637(function (process){
33638/*
33639 * extsprintf.js: extended POSIX-style sprintf
33640 */
33641
33642var mod_assert = require('assert');
33643var mod_util = require('util');
33644
33645/*
33646 * Public interface
33647 */
33648exports.sprintf = jsSprintf;
33649exports.printf = jsPrintf;
33650exports.fprintf = jsFprintf;
33651
33652/*
33653 * Stripped down version of s[n]printf(3c). We make a best effort to throw an
33654 * exception when given a format string we don't understand, rather than
33655 * ignoring it, so that we won't break existing programs if/when we go implement
33656 * the rest of this.
33657 *
33658 * This implementation currently supports specifying
33659 * - field alignment ('-' flag),
33660 * - zero-pad ('0' flag)
33661 * - always show numeric sign ('+' flag),
33662 * - field width
33663 * - conversions for strings, decimal integers, and floats (numbers).
33664 * - argument size specifiers. These are all accepted but ignored, since
33665 * Javascript has no notion of the physical size of an argument.
33666 *
33667 * Everything else is currently unsupported, most notably precision, unsigned
33668 * numbers, non-decimal numbers, and characters.
33669 */
33670function jsSprintf(fmt)
33671{
33672 var regex = [
33673 '([^%]*)', /* normal text */
33674 '%', /* start of format */
33675 '([\'\\-+ #0]*?)', /* flags (optional) */
33676 '([1-9]\\d*)?', /* width (optional) */
33677 '(\\.([1-9]\\d*))?', /* precision (optional) */
33678 '[lhjztL]*?', /* length mods (ignored) */
33679 '([diouxXfFeEgGaAcCsSp%jr])' /* conversion */
33680 ].join('');
33681
33682 var re = new RegExp(regex);
33683 var args = Array.prototype.slice.call(arguments, 1);
33684 var flags, width, precision, conversion;
33685 var left, pad, sign, arg, match;
33686 var ret = '';
33687 var argn = 1;
33688
33689 mod_assert.equal('string', typeof (fmt));
33690
33691 while ((match = re.exec(fmt)) !== null) {
33692 ret += match[1];
33693 fmt = fmt.substring(match[0].length);
33694
33695 flags = match[2] || '';
33696 width = match[3] || 0;
33697 precision = match[4] || '';
33698 conversion = match[6];
33699 left = false;
33700 sign = false;
33701 pad = ' ';
33702
33703 if (conversion == '%') {
33704 ret += '%';
33705 continue;
33706 }
33707
33708 if (args.length === 0)
33709 throw (new Error('too few args to sprintf'));
33710
33711 arg = args.shift();
33712 argn++;
33713
33714 if (flags.match(/[\' #]/))
33715 throw (new Error(
33716 'unsupported flags: ' + flags));
33717
33718 if (precision.length > 0)
33719 throw (new Error(
33720 'non-zero precision not supported'));
33721
33722 if (flags.match(/-/))
33723 left = true;
33724
33725 if (flags.match(/0/))
33726 pad = '0';
33727
33728 if (flags.match(/\+/))
33729 sign = true;
33730
33731 switch (conversion) {
33732 case 's':
33733 if (arg === undefined || arg === null)
33734 throw (new Error('argument ' + argn +
33735 ': attempted to print undefined or null ' +
33736 'as a string'));
33737 ret += doPad(pad, width, left, arg.toString());
33738 break;
33739
33740 case 'd':
33741 arg = Math.floor(arg);
33742 /*jsl:fallthru*/
33743 case 'f':
33744 sign = sign && arg > 0 ? '+' : '';
33745 ret += sign + doPad(pad, width, left,
33746 arg.toString());
33747 break;
33748
33749 case 'x':
33750 ret += doPad(pad, width, left, arg.toString(16));
33751 break;
33752
33753 case 'j': /* non-standard */
33754 if (width === 0)
33755 width = 10;
33756 ret += mod_util.inspect(arg, false, width);
33757 break;
33758
33759 case 'r': /* non-standard */
33760 ret += dumpException(arg);
33761 break;
33762
33763 default:
33764 throw (new Error('unsupported conversion: ' +
33765 conversion));
33766 }
33767 }
33768
33769 ret += fmt;
33770 return (ret);
33771}
33772
33773function jsPrintf() {
33774 var args = Array.prototype.slice.call(arguments);
33775 args.unshift(process.stdout);
33776 jsFprintf.apply(null, args);
33777}
33778
33779function jsFprintf(stream) {
33780 var args = Array.prototype.slice.call(arguments, 1);
33781 return (stream.write(jsSprintf.apply(this, args)));
33782}
33783
33784function doPad(chr, width, left, str)
33785{
33786 var ret = str;
33787
33788 while (ret.length < width) {
33789 if (left)
33790 ret += chr;
33791 else
33792 ret = chr + ret;
33793 }
33794
33795 return (ret);
33796}
33797
33798/*
33799 * This function dumps long stack traces for exceptions having a cause() method.
33800 * See node-verror for an example.
33801 */
33802function dumpException(ex)
33803{
33804 var ret;
33805
33806 if (!(ex instanceof Error))
33807 throw (new Error(jsSprintf('invalid type for %%r: %j', ex)));
33808
33809 /* Note that V8 prepends "ex.stack" with ex.toString(). */
33810 ret = 'EXCEPTION: ' + ex.constructor.name + ': ' + ex.stack;
33811
33812 if (ex.cause && typeof (ex.cause) === 'function') {
33813 var cex = ex.cause();
33814 if (cex) {
33815 ret += '\nCaused by: ' + dumpException(cex);
33816 }
33817 }
33818
33819 return (ret);
33820}
33821
33822}).call(this,require('_process'))
33823},{"_process":265,"assert":68,"util":397}],163:[function(require,module,exports){
33824'use strict';
33825
33826var isArray = Array.isArray;
33827var keyList = Object.keys;
33828var hasProp = Object.prototype.hasOwnProperty;
33829
33830module.exports = function equal(a, b) {
33831 if (a === b) return true;
33832
33833 if (a && b && typeof a == 'object' && typeof b == 'object') {
33834 var arrA = isArray(a)
33835 , arrB = isArray(b)
33836 , i
33837 , length
33838 , key;
33839
33840 if (arrA && arrB) {
33841 length = a.length;
33842 if (length != b.length) return false;
33843 for (i = length; i-- !== 0;)
33844 if (!equal(a[i], b[i])) return false;
33845 return true;
33846 }
33847
33848 if (arrA != arrB) return false;
33849
33850 var dateA = a instanceof Date
33851 , dateB = b instanceof Date;
33852 if (dateA != dateB) return false;
33853 if (dateA && dateB) return a.getTime() == b.getTime();
33854
33855 var regexpA = a instanceof RegExp
33856 , regexpB = b instanceof RegExp;
33857 if (regexpA != regexpB) return false;
33858 if (regexpA && regexpB) return a.toString() == b.toString();
33859
33860 var keys = keyList(a);
33861 length = keys.length;
33862
33863 if (length !== keyList(b).length)
33864 return false;
33865
33866 for (i = length; i-- !== 0;)
33867 if (!hasProp.call(b, keys[i])) return false;
33868
33869 for (i = length; i-- !== 0;) {
33870 key = keys[i];
33871 if (!equal(a[key], b[key])) return false;
33872 }
33873
33874 return true;
33875 }
33876
33877 return a!==a && b!==b;
33878};
33879
33880},{}],164:[function(require,module,exports){
33881'use strict';
33882
33883module.exports = function (data, opts) {
33884 if (!opts) opts = {};
33885 if (typeof opts === 'function') opts = { cmp: opts };
33886 var cycles = (typeof opts.cycles === 'boolean') ? opts.cycles : false;
33887
33888 var cmp = opts.cmp && (function (f) {
33889 return function (node) {
33890 return function (a, b) {
33891 var aobj = { key: a, value: node[a] };
33892 var bobj = { key: b, value: node[b] };
33893 return f(aobj, bobj);
33894 };
33895 };
33896 })(opts.cmp);
33897
33898 var seen = [];
33899 return (function stringify (node) {
33900 if (node && node.toJSON && typeof node.toJSON === 'function') {
33901 node = node.toJSON();
33902 }
33903
33904 if (node === undefined) return;
33905 if (typeof node == 'number') return isFinite(node) ? '' + node : 'null';
33906 if (typeof node !== 'object') return JSON.stringify(node);
33907
33908 var i, out;
33909 if (Array.isArray(node)) {
33910 out = '[';
33911 for (i = 0; i < node.length; i++) {
33912 if (i) out += ',';
33913 out += stringify(node[i]) || 'null';
33914 }
33915 return out + ']';
33916 }
33917
33918 if (node === null) return 'null';
33919
33920 if (seen.indexOf(node) !== -1) {
33921 if (cycles) return JSON.stringify('__cycle__');
33922 throw new TypeError('Converting circular structure to JSON');
33923 }
33924
33925 var seenIndex = seen.push(node) - 1;
33926 var keys = Object.keys(node).sort(cmp && cmp(node));
33927 out = '';
33928 for (i = 0; i < keys.length; i++) {
33929 var key = keys[i];
33930 var value = stringify(node[key]);
33931
33932 if (!value) continue;
33933 if (out) out += ',';
33934 out += JSON.stringify(key) + ':' + value;
33935 }
33936 seen.splice(seenIndex, 1);
33937 return '{' + out + '}';
33938 })(data);
33939};
33940
33941},{}],165:[function(require,module,exports){
33942/*jshint -W054 */
33943;(function (exports) {
33944 'use strict';
33945
33946 function forEachAsync(arr, fn, thisArg) {
33947 var dones = []
33948 , index = -1
33949 ;
33950
33951 function next(BREAK, result) {
33952 index += 1;
33953
33954 if (index === arr.length || BREAK === forEachAsync.__BREAK) {
33955 dones.forEach(function (done) {
33956 done.call(thisArg, result);
33957 });
33958 return;
33959 }
33960
33961 fn.call(thisArg, next, arr[index], index, arr);
33962 }
33963
33964 setTimeout(next, 4);
33965
33966 return {
33967 then: function (_done) {
33968 dones.push(_done);
33969 return this;
33970 }
33971 };
33972 }
33973 forEachAsync.__BREAK = {};
33974
33975 exports.forEachAsync = forEachAsync;
33976}('undefined' !== typeof exports && exports || new Function('return this')()));
33977
33978},{}],166:[function(require,module,exports){
33979module.exports = ForeverAgent
33980ForeverAgent.SSL = ForeverAgentSSL
33981
33982var util = require('util')
33983 , Agent = require('http').Agent
33984 , net = require('net')
33985 , tls = require('tls')
33986 , AgentSSL = require('https').Agent
33987
33988function getConnectionName(host, port) {
33989 var name = ''
33990 if (typeof host === 'string') {
33991 name = host + ':' + port
33992 } else {
33993 // For node.js v012.0 and iojs-v1.5.1, host is an object. And any existing localAddress is part of the connection name.
33994 name = host.host + ':' + host.port + ':' + (host.localAddress ? (host.localAddress + ':') : ':')
33995 }
33996 return name
33997}
33998
33999function ForeverAgent(options) {
34000 var self = this
34001 self.options = options || {}
34002 self.requests = {}
34003 self.sockets = {}
34004 self.freeSockets = {}
34005 self.maxSockets = self.options.maxSockets || Agent.defaultMaxSockets
34006 self.minSockets = self.options.minSockets || ForeverAgent.defaultMinSockets
34007 self.on('free', function(socket, host, port) {
34008 var name = getConnectionName(host, port)
34009
34010 if (self.requests[name] && self.requests[name].length) {
34011 self.requests[name].shift().onSocket(socket)
34012 } else if (self.sockets[name].length < self.minSockets) {
34013 if (!self.freeSockets[name]) self.freeSockets[name] = []
34014 self.freeSockets[name].push(socket)
34015
34016 // if an error happens while we don't use the socket anyway, meh, throw the socket away
34017 var onIdleError = function() {
34018 socket.destroy()
34019 }
34020 socket._onIdleError = onIdleError
34021 socket.on('error', onIdleError)
34022 } else {
34023 // If there are no pending requests just destroy the
34024 // socket and it will get removed from the pool. This
34025 // gets us out of timeout issues and allows us to
34026 // default to Connection:keep-alive.
34027 socket.destroy()
34028 }
34029 })
34030
34031}
34032util.inherits(ForeverAgent, Agent)
34033
34034ForeverAgent.defaultMinSockets = 5
34035
34036
34037ForeverAgent.prototype.createConnection = net.createConnection
34038ForeverAgent.prototype.addRequestNoreuse = Agent.prototype.addRequest
34039ForeverAgent.prototype.addRequest = function(req, host, port) {
34040 var name = getConnectionName(host, port)
34041
34042 if (typeof host !== 'string') {
34043 var options = host
34044 port = options.port
34045 host = options.host
34046 }
34047
34048 if (this.freeSockets[name] && this.freeSockets[name].length > 0 && !req.useChunkedEncodingByDefault) {
34049 var idleSocket = this.freeSockets[name].pop()
34050 idleSocket.removeListener('error', idleSocket._onIdleError)
34051 delete idleSocket._onIdleError
34052 req._reusedSocket = true
34053 req.onSocket(idleSocket)
34054 } else {
34055 this.addRequestNoreuse(req, host, port)
34056 }
34057}
34058
34059ForeverAgent.prototype.removeSocket = function(s, name, host, port) {
34060 if (this.sockets[name]) {
34061 var index = this.sockets[name].indexOf(s)
34062 if (index !== -1) {
34063 this.sockets[name].splice(index, 1)
34064 }
34065 } else if (this.sockets[name] && this.sockets[name].length === 0) {
34066 // don't leak
34067 delete this.sockets[name]
34068 delete this.requests[name]
34069 }
34070
34071 if (this.freeSockets[name]) {
34072 var index = this.freeSockets[name].indexOf(s)
34073 if (index !== -1) {
34074 this.freeSockets[name].splice(index, 1)
34075 if (this.freeSockets[name].length === 0) {
34076 delete this.freeSockets[name]
34077 }
34078 }
34079 }
34080
34081 if (this.requests[name] && this.requests[name].length) {
34082 // If we have pending requests and a socket gets closed a new one
34083 // needs to be created to take over in the pool for the one that closed.
34084 this.createSocket(name, host, port).emit('free')
34085 }
34086}
34087
34088function ForeverAgentSSL (options) {
34089 ForeverAgent.call(this, options)
34090}
34091util.inherits(ForeverAgentSSL, ForeverAgent)
34092
34093ForeverAgentSSL.prototype.createConnection = createConnectionSSL
34094ForeverAgentSSL.prototype.addRequestNoreuse = AgentSSL.prototype.addRequest
34095
34096function createConnectionSSL (port, host, options) {
34097 if (typeof port === 'object') {
34098 options = port;
34099 } else if (typeof host === 'object') {
34100 options = host;
34101 } else if (typeof options === 'object') {
34102 options = options;
34103 } else {
34104 options = {};
34105 }
34106
34107 if (typeof port === 'number') {
34108 options.port = port;
34109 }
34110
34111 if (typeof host === 'string') {
34112 options.host = host;
34113 }
34114
34115 return tls.connect(options);
34116}
34117
34118},{"http":362,"https":208,"net":112,"tls":112,"util":397}],167:[function(require,module,exports){
34119/* eslint-env browser */
34120module.exports = typeof self == 'object' ? self.FormData : window.FormData;
34121
34122},{}],168:[function(require,module,exports){
34123module.exports={
34124 "$id": "afterRequest.json#",
34125 "$schema": "http://json-schema.org/draft-06/schema#",
34126 "type": "object",
34127 "optional": true,
34128 "required": [
34129 "lastAccess",
34130 "eTag",
34131 "hitCount"
34132 ],
34133 "properties": {
34134 "expires": {
34135 "type": "string",
34136 "pattern": "^(\\d{4})(-)?(\\d\\d)(-)?(\\d\\d)(T)?(\\d\\d)(:)?(\\d\\d)(:)?(\\d\\d)(\\.\\d+)?(Z|([+-])(\\d\\d)(:)?(\\d\\d))?"
34137 },
34138 "lastAccess": {
34139 "type": "string",
34140 "pattern": "^(\\d{4})(-)?(\\d\\d)(-)?(\\d\\d)(T)?(\\d\\d)(:)?(\\d\\d)(:)?(\\d\\d)(\\.\\d+)?(Z|([+-])(\\d\\d)(:)?(\\d\\d))?"
34141 },
34142 "eTag": {
34143 "type": "string"
34144 },
34145 "hitCount": {
34146 "type": "integer"
34147 },
34148 "comment": {
34149 "type": "string"
34150 }
34151 }
34152}
34153
34154},{}],169:[function(require,module,exports){
34155module.exports={
34156 "$id": "beforeRequest.json#",
34157 "$schema": "http://json-schema.org/draft-06/schema#",
34158 "type": "object",
34159 "optional": true,
34160 "required": [
34161 "lastAccess",
34162 "eTag",
34163 "hitCount"
34164 ],
34165 "properties": {
34166 "expires": {
34167 "type": "string",
34168 "pattern": "^(\\d{4})(-)?(\\d\\d)(-)?(\\d\\d)(T)?(\\d\\d)(:)?(\\d\\d)(:)?(\\d\\d)(\\.\\d+)?(Z|([+-])(\\d\\d)(:)?(\\d\\d))?"
34169 },
34170 "lastAccess": {
34171 "type": "string",
34172 "pattern": "^(\\d{4})(-)?(\\d\\d)(-)?(\\d\\d)(T)?(\\d\\d)(:)?(\\d\\d)(:)?(\\d\\d)(\\.\\d+)?(Z|([+-])(\\d\\d)(:)?(\\d\\d))?"
34173 },
34174 "eTag": {
34175 "type": "string"
34176 },
34177 "hitCount": {
34178 "type": "integer"
34179 },
34180 "comment": {
34181 "type": "string"
34182 }
34183 }
34184}
34185
34186},{}],170:[function(require,module,exports){
34187module.exports={
34188 "$id": "browser.json#",
34189 "$schema": "http://json-schema.org/draft-06/schema#",
34190 "type": "object",
34191 "required": [
34192 "name",
34193 "version"
34194 ],
34195 "properties": {
34196 "name": {
34197 "type": "string"
34198 },
34199 "version": {
34200 "type": "string"
34201 },
34202 "comment": {
34203 "type": "string"
34204 }
34205 }
34206}
34207
34208},{}],171:[function(require,module,exports){
34209module.exports={
34210 "$id": "cache.json#",
34211 "$schema": "http://json-schema.org/draft-06/schema#",
34212 "properties": {
34213 "beforeRequest": {
34214 "oneOf": [
34215 { "type": "null" },
34216 { "$ref": "beforeRequest.json#" }
34217 ]
34218 },
34219 "afterRequest": {
34220 "oneOf": [
34221 { "type": "null" },
34222 { "$ref": "afterRequest.json#" }
34223 ]
34224 },
34225 "comment": {
34226 "type": "string"
34227 }
34228 }
34229}
34230
34231},{}],172:[function(require,module,exports){
34232module.exports={
34233 "$id": "content.json#",
34234 "$schema": "http://json-schema.org/draft-06/schema#",
34235 "type": "object",
34236 "required": [
34237 "size",
34238 "mimeType"
34239 ],
34240 "properties": {
34241 "size": {
34242 "type": "integer"
34243 },
34244 "compression": {
34245 "type": "integer"
34246 },
34247 "mimeType": {
34248 "type": "string"
34249 },
34250 "text": {
34251 "type": "string"
34252 },
34253 "encoding": {
34254 "type": "string"
34255 },
34256 "comment": {
34257 "type": "string"
34258 }
34259 }
34260}
34261
34262},{}],173:[function(require,module,exports){
34263module.exports={
34264 "$id": "cookie.json#",
34265 "$schema": "http://json-schema.org/draft-06/schema#",
34266 "type": "object",
34267 "required": [
34268 "name",
34269 "value"
34270 ],
34271 "properties": {
34272 "name": {
34273 "type": "string"
34274 },
34275 "value": {
34276 "type": "string"
34277 },
34278 "path": {
34279 "type": "string"
34280 },
34281 "domain": {
34282 "type": "string"
34283 },
34284 "expires": {
34285 "type": ["string", "null"],
34286 "format": "date-time"
34287 },
34288 "httpOnly": {
34289 "type": "boolean"
34290 },
34291 "secure": {
34292 "type": "boolean"
34293 },
34294 "comment": {
34295 "type": "string"
34296 }
34297 }
34298}
34299
34300},{}],174:[function(require,module,exports){
34301module.exports={
34302 "$id": "creator.json#",
34303 "$schema": "http://json-schema.org/draft-06/schema#",
34304 "type": "object",
34305 "required": [
34306 "name",
34307 "version"
34308 ],
34309 "properties": {
34310 "name": {
34311 "type": "string"
34312 },
34313 "version": {
34314 "type": "string"
34315 },
34316 "comment": {
34317 "type": "string"
34318 }
34319 }
34320}
34321
34322},{}],175:[function(require,module,exports){
34323module.exports={
34324 "$id": "entry.json#",
34325 "$schema": "http://json-schema.org/draft-06/schema#",
34326 "type": "object",
34327 "optional": true,
34328 "required": [
34329 "startedDateTime",
34330 "time",
34331 "request",
34332 "response",
34333 "cache",
34334 "timings"
34335 ],
34336 "properties": {
34337 "pageref": {
34338 "type": "string"
34339 },
34340 "startedDateTime": {
34341 "type": "string",
34342 "format": "date-time",
34343 "pattern": "^(\\d{4})(-)?(\\d\\d)(-)?(\\d\\d)(T)?(\\d\\d)(:)?(\\d\\d)(:)?(\\d\\d)(\\.\\d+)?(Z|([+-])(\\d\\d)(:)?(\\d\\d))"
34344 },
34345 "time": {
34346 "type": "number",
34347 "min": 0
34348 },
34349 "request": {
34350 "$ref": "request.json#"
34351 },
34352 "response": {
34353 "$ref": "response.json#"
34354 },
34355 "cache": {
34356 "$ref": "cache.json#"
34357 },
34358 "timings": {
34359 "$ref": "timings.json#"
34360 },
34361 "serverIPAddress": {
34362 "type": "string",
34363 "oneOf": [
34364 { "format": "ipv4" },
34365 { "format": "ipv6" }
34366 ]
34367 },
34368 "connection": {
34369 "type": "string"
34370 },
34371 "comment": {
34372 "type": "string"
34373 }
34374 }
34375}
34376
34377},{}],176:[function(require,module,exports){
34378module.exports={
34379 "$id": "har.json#",
34380 "$schema": "http://json-schema.org/draft-06/schema#",
34381 "type": "object",
34382 "required": [
34383 "log"
34384 ],
34385 "properties": {
34386 "log": {
34387 "$ref": "log.json#"
34388 }
34389 }
34390}
34391
34392},{}],177:[function(require,module,exports){
34393module.exports={
34394 "$id": "header.json#",
34395 "$schema": "http://json-schema.org/draft-06/schema#",
34396 "type": "object",
34397 "required": [
34398 "name",
34399 "value"
34400 ],
34401 "properties": {
34402 "name": {
34403 "type": "string"
34404 },
34405 "value": {
34406 "type": "string"
34407 },
34408 "comment": {
34409 "type": "string"
34410 }
34411 }
34412}
34413
34414},{}],178:[function(require,module,exports){
34415'use strict'
34416
34417module.exports = {
34418 afterRequest: require('./afterRequest.json'),
34419 beforeRequest: require('./beforeRequest.json'),
34420 browser: require('./browser.json'),
34421 cache: require('./cache.json'),
34422 content: require('./content.json'),
34423 cookie: require('./cookie.json'),
34424 creator: require('./creator.json'),
34425 entry: require('./entry.json'),
34426 har: require('./har.json'),
34427 header: require('./header.json'),
34428 log: require('./log.json'),
34429 page: require('./page.json'),
34430 pageTimings: require('./pageTimings.json'),
34431 postData: require('./postData.json'),
34432 query: require('./query.json'),
34433 request: require('./request.json'),
34434 response: require('./response.json'),
34435 timings: require('./timings.json')
34436}
34437
34438},{"./afterRequest.json":168,"./beforeRequest.json":169,"./browser.json":170,"./cache.json":171,"./content.json":172,"./cookie.json":173,"./creator.json":174,"./entry.json":175,"./har.json":176,"./header.json":177,"./log.json":179,"./page.json":180,"./pageTimings.json":181,"./postData.json":182,"./query.json":183,"./request.json":184,"./response.json":185,"./timings.json":186}],179:[function(require,module,exports){
34439module.exports={
34440 "$id": "log.json#",
34441 "$schema": "http://json-schema.org/draft-06/schema#",
34442 "type": "object",
34443 "required": [
34444 "version",
34445 "creator",
34446 "entries"
34447 ],
34448 "properties": {
34449 "version": {
34450 "type": "string"
34451 },
34452 "creator": {
34453 "$ref": "creator.json#"
34454 },
34455 "browser": {
34456 "$ref": "browser.json#"
34457 },
34458 "pages": {
34459 "type": "array",
34460 "items": {
34461 "$ref": "page.json#"
34462 }
34463 },
34464 "entries": {
34465 "type": "array",
34466 "items": {
34467 "$ref": "entry.json#"
34468 }
34469 },
34470 "comment": {
34471 "type": "string"
34472 }
34473 }
34474}
34475
34476},{}],180:[function(require,module,exports){
34477module.exports={
34478 "$id": "page.json#",
34479 "$schema": "http://json-schema.org/draft-06/schema#",
34480 "type": "object",
34481 "optional": true,
34482 "required": [
34483 "startedDateTime",
34484 "id",
34485 "title",
34486 "pageTimings"
34487 ],
34488 "properties": {
34489 "startedDateTime": {
34490 "type": "string",
34491 "format": "date-time",
34492 "pattern": "^(\\d{4})(-)?(\\d\\d)(-)?(\\d\\d)(T)?(\\d\\d)(:)?(\\d\\d)(:)?(\\d\\d)(\\.\\d+)?(Z|([+-])(\\d\\d)(:)?(\\d\\d))"
34493 },
34494 "id": {
34495 "type": "string",
34496 "unique": true
34497 },
34498 "title": {
34499 "type": "string"
34500 },
34501 "pageTimings": {
34502 "$ref": "pageTimings.json#"
34503 },
34504 "comment": {
34505 "type": "string"
34506 }
34507 }
34508}
34509
34510},{}],181:[function(require,module,exports){
34511module.exports={
34512 "$id": "pageTimings.json#",
34513 "$schema": "http://json-schema.org/draft-06/schema#",
34514 "type": "object",
34515 "properties": {
34516 "onContentLoad": {
34517 "type": "number",
34518 "min": -1
34519 },
34520 "onLoad": {
34521 "type": "number",
34522 "min": -1
34523 },
34524 "comment": {
34525 "type": "string"
34526 }
34527 }
34528}
34529
34530},{}],182:[function(require,module,exports){
34531module.exports={
34532 "$id": "postData.json#",
34533 "$schema": "http://json-schema.org/draft-06/schema#",
34534 "type": "object",
34535 "optional": true,
34536 "required": [
34537 "mimeType"
34538 ],
34539 "properties": {
34540 "mimeType": {
34541 "type": "string"
34542 },
34543 "text": {
34544 "type": "string"
34545 },
34546 "params": {
34547 "type": "array",
34548 "required": [
34549 "name"
34550 ],
34551 "properties": {
34552 "name": {
34553 "type": "string"
34554 },
34555 "value": {
34556 "type": "string"
34557 },
34558 "fileName": {
34559 "type": "string"
34560 },
34561 "contentType": {
34562 "type": "string"
34563 },
34564 "comment": {
34565 "type": "string"
34566 }
34567 }
34568 },
34569 "comment": {
34570 "type": "string"
34571 }
34572 }
34573}
34574
34575},{}],183:[function(require,module,exports){
34576module.exports={
34577 "$id": "query.json#",
34578 "$schema": "http://json-schema.org/draft-06/schema#",
34579 "type": "object",
34580 "required": [
34581 "name",
34582 "value"
34583 ],
34584 "properties": {
34585 "name": {
34586 "type": "string"
34587 },
34588 "value": {
34589 "type": "string"
34590 },
34591 "comment": {
34592 "type": "string"
34593 }
34594 }
34595}
34596
34597},{}],184:[function(require,module,exports){
34598module.exports={
34599 "$id": "request.json#",
34600 "$schema": "http://json-schema.org/draft-06/schema#",
34601 "type": "object",
34602 "required": [
34603 "method",
34604 "url",
34605 "httpVersion",
34606 "cookies",
34607 "headers",
34608 "queryString",
34609 "headersSize",
34610 "bodySize"
34611 ],
34612 "properties": {
34613 "method": {
34614 "type": "string"
34615 },
34616 "url": {
34617 "type": "string",
34618 "format": "uri"
34619 },
34620 "httpVersion": {
34621 "type": "string"
34622 },
34623 "cookies": {
34624 "type": "array",
34625 "items": {
34626 "$ref": "cookie.json#"
34627 }
34628 },
34629 "headers": {
34630 "type": "array",
34631 "items": {
34632 "$ref": "header.json#"
34633 }
34634 },
34635 "queryString": {
34636 "type": "array",
34637 "items": {
34638 "$ref": "query.json#"
34639 }
34640 },
34641 "postData": {
34642 "$ref": "postData.json#"
34643 },
34644 "headersSize": {
34645 "type": "integer"
34646 },
34647 "bodySize": {
34648 "type": "integer"
34649 },
34650 "comment": {
34651 "type": "string"
34652 }
34653 }
34654}
34655
34656},{}],185:[function(require,module,exports){
34657module.exports={
34658 "$id": "response.json#",
34659 "$schema": "http://json-schema.org/draft-06/schema#",
34660 "type": "object",
34661 "required": [
34662 "status",
34663 "statusText",
34664 "httpVersion",
34665 "cookies",
34666 "headers",
34667 "content",
34668 "redirectURL",
34669 "headersSize",
34670 "bodySize"
34671 ],
34672 "properties": {
34673 "status": {
34674 "type": "integer"
34675 },
34676 "statusText": {
34677 "type": "string"
34678 },
34679 "httpVersion": {
34680 "type": "string"
34681 },
34682 "cookies": {
34683 "type": "array",
34684 "items": {
34685 "$ref": "cookie.json#"
34686 }
34687 },
34688 "headers": {
34689 "type": "array",
34690 "items": {
34691 "$ref": "header.json#"
34692 }
34693 },
34694 "content": {
34695 "$ref": "content.json#"
34696 },
34697 "redirectURL": {
34698 "type": "string"
34699 },
34700 "headersSize": {
34701 "type": "integer"
34702 },
34703 "bodySize": {
34704 "type": "integer"
34705 },
34706 "comment": {
34707 "type": "string"
34708 }
34709 }
34710}
34711
34712},{}],186:[function(require,module,exports){
34713module.exports={
34714 "$id": "timings.json#",
34715 "$schema": "http://json-schema.org/draft-06/schema#",
34716 "required": [
34717 "send",
34718 "wait",
34719 "receive"
34720 ],
34721 "properties": {
34722 "dns": {
34723 "type": "number",
34724 "min": -1
34725 },
34726 "connect": {
34727 "type": "number",
34728 "min": -1
34729 },
34730 "blocked": {
34731 "type": "number",
34732 "min": -1
34733 },
34734 "send": {
34735 "type": "number",
34736 "min": -1
34737 },
34738 "wait": {
34739 "type": "number",
34740 "min": -1
34741 },
34742 "receive": {
34743 "type": "number",
34744 "min": -1
34745 },
34746 "ssl": {
34747 "type": "number",
34748 "min": -1
34749 },
34750 "comment": {
34751 "type": "string"
34752 }
34753 }
34754}
34755
34756},{}],187:[function(require,module,exports){
34757function HARError (errors) {
34758 var message = 'validation failed'
34759
34760 this.name = 'HARError'
34761 this.message = message
34762 this.errors = errors
34763
34764 if (typeof Error.captureStackTrace === 'function') {
34765 Error.captureStackTrace(this, this.constructor)
34766 } else {
34767 this.stack = (new Error(message)).stack
34768 }
34769}
34770
34771HARError.prototype = Error.prototype
34772
34773module.exports = HARError
34774
34775},{}],188:[function(require,module,exports){
34776var Ajv = require('ajv')
34777var HARError = require('./error')
34778var schemas = require('har-schema')
34779
34780var ajv
34781
34782function createAjvInstance () {
34783 var ajv = new Ajv({
34784 allErrors: true
34785 })
34786 ajv.addMetaSchema(require('ajv/lib/refs/json-schema-draft-06.json'))
34787 ajv.addSchema(schemas)
34788
34789 return ajv
34790}
34791
34792function validate (name, data) {
34793 data = data || {}
34794
34795 // validator config
34796 ajv = ajv || createAjvInstance()
34797
34798 var validate = ajv.getSchema(name + '.json')
34799
34800 return new Promise(function (resolve, reject) {
34801 var valid = validate(data)
34802
34803 !valid ? reject(new HARError(validate.errors)) : resolve(data)
34804 })
34805}
34806
34807exports.afterRequest = function (data) {
34808 return validate('afterRequest', data)
34809}
34810
34811exports.beforeRequest = function (data) {
34812 return validate('beforeRequest', data)
34813}
34814
34815exports.browser = function (data) {
34816 return validate('browser', data)
34817}
34818
34819exports.cache = function (data) {
34820 return validate('cache', data)
34821}
34822
34823exports.content = function (data) {
34824 return validate('content', data)
34825}
34826
34827exports.cookie = function (data) {
34828 return validate('cookie', data)
34829}
34830
34831exports.creator = function (data) {
34832 return validate('creator', data)
34833}
34834
34835exports.entry = function (data) {
34836 return validate('entry', data)
34837}
34838
34839exports.har = function (data) {
34840 return validate('har', data)
34841}
34842
34843exports.header = function (data) {
34844 return validate('header', data)
34845}
34846
34847exports.log = function (data) {
34848 return validate('log', data)
34849}
34850
34851exports.page = function (data) {
34852 return validate('page', data)
34853}
34854
34855exports.pageTimings = function (data) {
34856 return validate('pageTimings', data)
34857}
34858
34859exports.postData = function (data) {
34860 return validate('postData', data)
34861}
34862
34863exports.query = function (data) {
34864 return validate('query', data)
34865}
34866
34867exports.request = function (data) {
34868 return validate('request', data)
34869}
34870
34871exports.response = function (data) {
34872 return validate('response', data)
34873}
34874
34875exports.timings = function (data) {
34876 return validate('timings', data)
34877}
34878
34879},{"./error":187,"ajv":5,"ajv/lib/refs/json-schema-draft-06.json":45,"har-schema":178}],189:[function(require,module,exports){
34880'use strict'
34881var Buffer = require('safe-buffer').Buffer
34882var Transform = require('stream').Transform
34883var inherits = require('inherits')
34884
34885function throwIfNotStringOrBuffer (val, prefix) {
34886 if (!Buffer.isBuffer(val) && typeof val !== 'string') {
34887 throw new TypeError(prefix + ' must be a string or a buffer')
34888 }
34889}
34890
34891function HashBase (blockSize) {
34892 Transform.call(this)
34893
34894 this._block = Buffer.allocUnsafe(blockSize)
34895 this._blockSize = blockSize
34896 this._blockOffset = 0
34897 this._length = [0, 0, 0, 0]
34898
34899 this._finalized = false
34900}
34901
34902inherits(HashBase, Transform)
34903
34904HashBase.prototype._transform = function (chunk, encoding, callback) {
34905 var error = null
34906 try {
34907 this.update(chunk, encoding)
34908 } catch (err) {
34909 error = err
34910 }
34911
34912 callback(error)
34913}
34914
34915HashBase.prototype._flush = function (callback) {
34916 var error = null
34917 try {
34918 this.push(this.digest())
34919 } catch (err) {
34920 error = err
34921 }
34922
34923 callback(error)
34924}
34925
34926HashBase.prototype.update = function (data, encoding) {
34927 throwIfNotStringOrBuffer(data, 'Data')
34928 if (this._finalized) throw new Error('Digest already called')
34929 if (!Buffer.isBuffer(data)) data = Buffer.from(data, encoding)
34930
34931 // consume data
34932 var block = this._block
34933 var offset = 0
34934 while (this._blockOffset + data.length - offset >= this._blockSize) {
34935 for (var i = this._blockOffset; i < this._blockSize;) block[i++] = data[offset++]
34936 this._update()
34937 this._blockOffset = 0
34938 }
34939 while (offset < data.length) block[this._blockOffset++] = data[offset++]
34940
34941 // update length
34942 for (var j = 0, carry = data.length * 8; carry > 0; ++j) {
34943 this._length[j] += carry
34944 carry = (this._length[j] / 0x0100000000) | 0
34945 if (carry > 0) this._length[j] -= 0x0100000000 * carry
34946 }
34947
34948 return this
34949}
34950
34951HashBase.prototype._update = function () {
34952 throw new Error('_update is not implemented')
34953}
34954
34955HashBase.prototype.digest = function (encoding) {
34956 if (this._finalized) throw new Error('Digest already called')
34957 this._finalized = true
34958
34959 var digest = this._digest()
34960 if (encoding !== undefined) digest = digest.toString(encoding)
34961
34962 // reset state
34963 this._block.fill(0)
34964 this._blockOffset = 0
34965 for (var i = 0; i < 4; ++i) this._length[i] = 0
34966
34967 return digest
34968}
34969
34970HashBase.prototype._digest = function () {
34971 throw new Error('_digest is not implemented')
34972}
34973
34974module.exports = HashBase
34975
34976},{"inherits":210,"safe-buffer":325,"stream":361}],190:[function(require,module,exports){
34977var hash = exports;
34978
34979hash.utils = require('./hash/utils');
34980hash.common = require('./hash/common');
34981hash.sha = require('./hash/sha');
34982hash.ripemd = require('./hash/ripemd');
34983hash.hmac = require('./hash/hmac');
34984
34985// Proxy hash functions to the main object
34986hash.sha1 = hash.sha.sha1;
34987hash.sha256 = hash.sha.sha256;
34988hash.sha224 = hash.sha.sha224;
34989hash.sha384 = hash.sha.sha384;
34990hash.sha512 = hash.sha.sha512;
34991hash.ripemd160 = hash.ripemd.ripemd160;
34992
34993},{"./hash/common":191,"./hash/hmac":192,"./hash/ripemd":193,"./hash/sha":194,"./hash/utils":201}],191:[function(require,module,exports){
34994'use strict';
34995
34996var utils = require('./utils');
34997var assert = require('minimalistic-assert');
34998
34999function BlockHash() {
35000 this.pending = null;
35001 this.pendingTotal = 0;
35002 this.blockSize = this.constructor.blockSize;
35003 this.outSize = this.constructor.outSize;
35004 this.hmacStrength = this.constructor.hmacStrength;
35005 this.padLength = this.constructor.padLength / 8;
35006 this.endian = 'big';
35007
35008 this._delta8 = this.blockSize / 8;
35009 this._delta32 = this.blockSize / 32;
35010}
35011exports.BlockHash = BlockHash;
35012
35013BlockHash.prototype.update = function update(msg, enc) {
35014 // Convert message to array, pad it, and join into 32bit blocks
35015 msg = utils.toArray(msg, enc);
35016 if (!this.pending)
35017 this.pending = msg;
35018 else
35019 this.pending = this.pending.concat(msg);
35020 this.pendingTotal += msg.length;
35021
35022 // Enough data, try updating
35023 if (this.pending.length >= this._delta8) {
35024 msg = this.pending;
35025
35026 // Process pending data in blocks
35027 var r = msg.length % this._delta8;
35028 this.pending = msg.slice(msg.length - r, msg.length);
35029 if (this.pending.length === 0)
35030 this.pending = null;
35031
35032 msg = utils.join32(msg, 0, msg.length - r, this.endian);
35033 for (var i = 0; i < msg.length; i += this._delta32)
35034 this._update(msg, i, i + this._delta32);
35035 }
35036
35037 return this;
35038};
35039
35040BlockHash.prototype.digest = function digest(enc) {
35041 this.update(this._pad());
35042 assert(this.pending === null);
35043
35044 return this._digest(enc);
35045};
35046
35047BlockHash.prototype._pad = function pad() {
35048 var len = this.pendingTotal;
35049 var bytes = this._delta8;
35050 var k = bytes - ((len + this.padLength) % bytes);
35051 var res = new Array(k + this.padLength);
35052 res[0] = 0x80;
35053 for (var i = 1; i < k; i++)
35054 res[i] = 0;
35055
35056 // Append length
35057 len <<= 3;
35058 if (this.endian === 'big') {
35059 for (var t = 8; t < this.padLength; t++)
35060 res[i++] = 0;
35061
35062 res[i++] = 0;
35063 res[i++] = 0;
35064 res[i++] = 0;
35065 res[i++] = 0;
35066 res[i++] = (len >>> 24) & 0xff;
35067 res[i++] = (len >>> 16) & 0xff;
35068 res[i++] = (len >>> 8) & 0xff;
35069 res[i++] = len & 0xff;
35070 } else {
35071 res[i++] = len & 0xff;
35072 res[i++] = (len >>> 8) & 0xff;
35073 res[i++] = (len >>> 16) & 0xff;
35074 res[i++] = (len >>> 24) & 0xff;
35075 res[i++] = 0;
35076 res[i++] = 0;
35077 res[i++] = 0;
35078 res[i++] = 0;
35079
35080 for (t = 8; t < this.padLength; t++)
35081 res[i++] = 0;
35082 }
35083
35084 return res;
35085};
35086
35087},{"./utils":201,"minimalistic-assert":237}],192:[function(require,module,exports){
35088'use strict';
35089
35090var utils = require('./utils');
35091var assert = require('minimalistic-assert');
35092
35093function Hmac(hash, key, enc) {
35094 if (!(this instanceof Hmac))
35095 return new Hmac(hash, key, enc);
35096 this.Hash = hash;
35097 this.blockSize = hash.blockSize / 8;
35098 this.outSize = hash.outSize / 8;
35099 this.inner = null;
35100 this.outer = null;
35101
35102 this._init(utils.toArray(key, enc));
35103}
35104module.exports = Hmac;
35105
35106Hmac.prototype._init = function init(key) {
35107 // Shorten key, if needed
35108 if (key.length > this.blockSize)
35109 key = new this.Hash().update(key).digest();
35110 assert(key.length <= this.blockSize);
35111
35112 // Add padding to key
35113 for (var i = key.length; i < this.blockSize; i++)
35114 key.push(0);
35115
35116 for (i = 0; i < key.length; i++)
35117 key[i] ^= 0x36;
35118 this.inner = new this.Hash().update(key);
35119
35120 // 0x36 ^ 0x5c = 0x6a
35121 for (i = 0; i < key.length; i++)
35122 key[i] ^= 0x6a;
35123 this.outer = new this.Hash().update(key);
35124};
35125
35126Hmac.prototype.update = function update(msg, enc) {
35127 this.inner.update(msg, enc);
35128 return this;
35129};
35130
35131Hmac.prototype.digest = function digest(enc) {
35132 this.outer.update(this.inner.digest());
35133 return this.outer.digest(enc);
35134};
35135
35136},{"./utils":201,"minimalistic-assert":237}],193:[function(require,module,exports){
35137'use strict';
35138
35139var utils = require('./utils');
35140var common = require('./common');
35141
35142var rotl32 = utils.rotl32;
35143var sum32 = utils.sum32;
35144var sum32_3 = utils.sum32_3;
35145var sum32_4 = utils.sum32_4;
35146var BlockHash = common.BlockHash;
35147
35148function RIPEMD160() {
35149 if (!(this instanceof RIPEMD160))
35150 return new RIPEMD160();
35151
35152 BlockHash.call(this);
35153
35154 this.h = [ 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0 ];
35155 this.endian = 'little';
35156}
35157utils.inherits(RIPEMD160, BlockHash);
35158exports.ripemd160 = RIPEMD160;
35159
35160RIPEMD160.blockSize = 512;
35161RIPEMD160.outSize = 160;
35162RIPEMD160.hmacStrength = 192;
35163RIPEMD160.padLength = 64;
35164
35165RIPEMD160.prototype._update = function update(msg, start) {
35166 var A = this.h[0];
35167 var B = this.h[1];
35168 var C = this.h[2];
35169 var D = this.h[3];
35170 var E = this.h[4];
35171 var Ah = A;
35172 var Bh = B;
35173 var Ch = C;
35174 var Dh = D;
35175 var Eh = E;
35176 for (var j = 0; j < 80; j++) {
35177 var T = sum32(
35178 rotl32(
35179 sum32_4(A, f(j, B, C, D), msg[r[j] + start], K(j)),
35180 s[j]),
35181 E);
35182 A = E;
35183 E = D;
35184 D = rotl32(C, 10);
35185 C = B;
35186 B = T;
35187 T = sum32(
35188 rotl32(
35189 sum32_4(Ah, f(79 - j, Bh, Ch, Dh), msg[rh[j] + start], Kh(j)),
35190 sh[j]),
35191 Eh);
35192 Ah = Eh;
35193 Eh = Dh;
35194 Dh = rotl32(Ch, 10);
35195 Ch = Bh;
35196 Bh = T;
35197 }
35198 T = sum32_3(this.h[1], C, Dh);
35199 this.h[1] = sum32_3(this.h[2], D, Eh);
35200 this.h[2] = sum32_3(this.h[3], E, Ah);
35201 this.h[3] = sum32_3(this.h[4], A, Bh);
35202 this.h[4] = sum32_3(this.h[0], B, Ch);
35203 this.h[0] = T;
35204};
35205
35206RIPEMD160.prototype._digest = function digest(enc) {
35207 if (enc === 'hex')
35208 return utils.toHex32(this.h, 'little');
35209 else
35210 return utils.split32(this.h, 'little');
35211};
35212
35213function f(j, x, y, z) {
35214 if (j <= 15)
35215 return x ^ y ^ z;
35216 else if (j <= 31)
35217 return (x & y) | ((~x) & z);
35218 else if (j <= 47)
35219 return (x | (~y)) ^ z;
35220 else if (j <= 63)
35221 return (x & z) | (y & (~z));
35222 else
35223 return x ^ (y | (~z));
35224}
35225
35226function K(j) {
35227 if (j <= 15)
35228 return 0x00000000;
35229 else if (j <= 31)
35230 return 0x5a827999;
35231 else if (j <= 47)
35232 return 0x6ed9eba1;
35233 else if (j <= 63)
35234 return 0x8f1bbcdc;
35235 else
35236 return 0xa953fd4e;
35237}
35238
35239function Kh(j) {
35240 if (j <= 15)
35241 return 0x50a28be6;
35242 else if (j <= 31)
35243 return 0x5c4dd124;
35244 else if (j <= 47)
35245 return 0x6d703ef3;
35246 else if (j <= 63)
35247 return 0x7a6d76e9;
35248 else
35249 return 0x00000000;
35250}
35251
35252var r = [
35253 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
35254 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8,
35255 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12,
35256 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2,
35257 4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13
35258];
35259
35260var rh = [
35261 5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12,
35262 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2,
35263 15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13,
35264 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14,
35265 12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11
35266];
35267
35268var s = [
35269 11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8,
35270 7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12,
35271 11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5,
35272 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12,
35273 9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6
35274];
35275
35276var sh = [
35277 8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6,
35278 9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11,
35279 9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5,
35280 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8,
35281 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11
35282];
35283
35284},{"./common":191,"./utils":201}],194:[function(require,module,exports){
35285'use strict';
35286
35287exports.sha1 = require('./sha/1');
35288exports.sha224 = require('./sha/224');
35289exports.sha256 = require('./sha/256');
35290exports.sha384 = require('./sha/384');
35291exports.sha512 = require('./sha/512');
35292
35293},{"./sha/1":195,"./sha/224":196,"./sha/256":197,"./sha/384":198,"./sha/512":199}],195:[function(require,module,exports){
35294'use strict';
35295
35296var utils = require('../utils');
35297var common = require('../common');
35298var shaCommon = require('./common');
35299
35300var rotl32 = utils.rotl32;
35301var sum32 = utils.sum32;
35302var sum32_5 = utils.sum32_5;
35303var ft_1 = shaCommon.ft_1;
35304var BlockHash = common.BlockHash;
35305
35306var sha1_K = [
35307 0x5A827999, 0x6ED9EBA1,
35308 0x8F1BBCDC, 0xCA62C1D6
35309];
35310
35311function SHA1() {
35312 if (!(this instanceof SHA1))
35313 return new SHA1();
35314
35315 BlockHash.call(this);
35316 this.h = [
35317 0x67452301, 0xefcdab89, 0x98badcfe,
35318 0x10325476, 0xc3d2e1f0 ];
35319 this.W = new Array(80);
35320}
35321
35322utils.inherits(SHA1, BlockHash);
35323module.exports = SHA1;
35324
35325SHA1.blockSize = 512;
35326SHA1.outSize = 160;
35327SHA1.hmacStrength = 80;
35328SHA1.padLength = 64;
35329
35330SHA1.prototype._update = function _update(msg, start) {
35331 var W = this.W;
35332
35333 for (var i = 0; i < 16; i++)
35334 W[i] = msg[start + i];
35335
35336 for(; i < W.length; i++)
35337 W[i] = rotl32(W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16], 1);
35338
35339 var a = this.h[0];
35340 var b = this.h[1];
35341 var c = this.h[2];
35342 var d = this.h[3];
35343 var e = this.h[4];
35344
35345 for (i = 0; i < W.length; i++) {
35346 var s = ~~(i / 20);
35347 var t = sum32_5(rotl32(a, 5), ft_1(s, b, c, d), e, W[i], sha1_K[s]);
35348 e = d;
35349 d = c;
35350 c = rotl32(b, 30);
35351 b = a;
35352 a = t;
35353 }
35354
35355 this.h[0] = sum32(this.h[0], a);
35356 this.h[1] = sum32(this.h[1], b);
35357 this.h[2] = sum32(this.h[2], c);
35358 this.h[3] = sum32(this.h[3], d);
35359 this.h[4] = sum32(this.h[4], e);
35360};
35361
35362SHA1.prototype._digest = function digest(enc) {
35363 if (enc === 'hex')
35364 return utils.toHex32(this.h, 'big');
35365 else
35366 return utils.split32(this.h, 'big');
35367};
35368
35369},{"../common":191,"../utils":201,"./common":200}],196:[function(require,module,exports){
35370'use strict';
35371
35372var utils = require('../utils');
35373var SHA256 = require('./256');
35374
35375function SHA224() {
35376 if (!(this instanceof SHA224))
35377 return new SHA224();
35378
35379 SHA256.call(this);
35380 this.h = [
35381 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939,
35382 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4 ];
35383}
35384utils.inherits(SHA224, SHA256);
35385module.exports = SHA224;
35386
35387SHA224.blockSize = 512;
35388SHA224.outSize = 224;
35389SHA224.hmacStrength = 192;
35390SHA224.padLength = 64;
35391
35392SHA224.prototype._digest = function digest(enc) {
35393 // Just truncate output
35394 if (enc === 'hex')
35395 return utils.toHex32(this.h.slice(0, 7), 'big');
35396 else
35397 return utils.split32(this.h.slice(0, 7), 'big');
35398};
35399
35400
35401},{"../utils":201,"./256":197}],197:[function(require,module,exports){
35402'use strict';
35403
35404var utils = require('../utils');
35405var common = require('../common');
35406var shaCommon = require('./common');
35407var assert = require('minimalistic-assert');
35408
35409var sum32 = utils.sum32;
35410var sum32_4 = utils.sum32_4;
35411var sum32_5 = utils.sum32_5;
35412var ch32 = shaCommon.ch32;
35413var maj32 = shaCommon.maj32;
35414var s0_256 = shaCommon.s0_256;
35415var s1_256 = shaCommon.s1_256;
35416var g0_256 = shaCommon.g0_256;
35417var g1_256 = shaCommon.g1_256;
35418
35419var BlockHash = common.BlockHash;
35420
35421var sha256_K = [
35422 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5,
35423 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
35424 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3,
35425 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
35426 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc,
35427 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
35428 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7,
35429 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
35430 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13,
35431 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
35432 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3,
35433 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
35434 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5,
35435 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
35436 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,
35437 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
35438];
35439
35440function SHA256() {
35441 if (!(this instanceof SHA256))
35442 return new SHA256();
35443
35444 BlockHash.call(this);
35445 this.h = [
35446 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a,
35447 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19
35448 ];
35449 this.k = sha256_K;
35450 this.W = new Array(64);
35451}
35452utils.inherits(SHA256, BlockHash);
35453module.exports = SHA256;
35454
35455SHA256.blockSize = 512;
35456SHA256.outSize = 256;
35457SHA256.hmacStrength = 192;
35458SHA256.padLength = 64;
35459
35460SHA256.prototype._update = function _update(msg, start) {
35461 var W = this.W;
35462
35463 for (var i = 0; i < 16; i++)
35464 W[i] = msg[start + i];
35465 for (; i < W.length; i++)
35466 W[i] = sum32_4(g1_256(W[i - 2]), W[i - 7], g0_256(W[i - 15]), W[i - 16]);
35467
35468 var a = this.h[0];
35469 var b = this.h[1];
35470 var c = this.h[2];
35471 var d = this.h[3];
35472 var e = this.h[4];
35473 var f = this.h[5];
35474 var g = this.h[6];
35475 var h = this.h[7];
35476
35477 assert(this.k.length === W.length);
35478 for (i = 0; i < W.length; i++) {
35479 var T1 = sum32_5(h, s1_256(e), ch32(e, f, g), this.k[i], W[i]);
35480 var T2 = sum32(s0_256(a), maj32(a, b, c));
35481 h = g;
35482 g = f;
35483 f = e;
35484 e = sum32(d, T1);
35485 d = c;
35486 c = b;
35487 b = a;
35488 a = sum32(T1, T2);
35489 }
35490
35491 this.h[0] = sum32(this.h[0], a);
35492 this.h[1] = sum32(this.h[1], b);
35493 this.h[2] = sum32(this.h[2], c);
35494 this.h[3] = sum32(this.h[3], d);
35495 this.h[4] = sum32(this.h[4], e);
35496 this.h[5] = sum32(this.h[5], f);
35497 this.h[6] = sum32(this.h[6], g);
35498 this.h[7] = sum32(this.h[7], h);
35499};
35500
35501SHA256.prototype._digest = function digest(enc) {
35502 if (enc === 'hex')
35503 return utils.toHex32(this.h, 'big');
35504 else
35505 return utils.split32(this.h, 'big');
35506};
35507
35508},{"../common":191,"../utils":201,"./common":200,"minimalistic-assert":237}],198:[function(require,module,exports){
35509'use strict';
35510
35511var utils = require('../utils');
35512
35513var SHA512 = require('./512');
35514
35515function SHA384() {
35516 if (!(this instanceof SHA384))
35517 return new SHA384();
35518
35519 SHA512.call(this);
35520 this.h = [
35521 0xcbbb9d5d, 0xc1059ed8,
35522 0x629a292a, 0x367cd507,
35523 0x9159015a, 0x3070dd17,
35524 0x152fecd8, 0xf70e5939,
35525 0x67332667, 0xffc00b31,
35526 0x8eb44a87, 0x68581511,
35527 0xdb0c2e0d, 0x64f98fa7,
35528 0x47b5481d, 0xbefa4fa4 ];
35529}
35530utils.inherits(SHA384, SHA512);
35531module.exports = SHA384;
35532
35533SHA384.blockSize = 1024;
35534SHA384.outSize = 384;
35535SHA384.hmacStrength = 192;
35536SHA384.padLength = 128;
35537
35538SHA384.prototype._digest = function digest(enc) {
35539 if (enc === 'hex')
35540 return utils.toHex32(this.h.slice(0, 12), 'big');
35541 else
35542 return utils.split32(this.h.slice(0, 12), 'big');
35543};
35544
35545},{"../utils":201,"./512":199}],199:[function(require,module,exports){
35546'use strict';
35547
35548var utils = require('../utils');
35549var common = require('../common');
35550var assert = require('minimalistic-assert');
35551
35552var rotr64_hi = utils.rotr64_hi;
35553var rotr64_lo = utils.rotr64_lo;
35554var shr64_hi = utils.shr64_hi;
35555var shr64_lo = utils.shr64_lo;
35556var sum64 = utils.sum64;
35557var sum64_hi = utils.sum64_hi;
35558var sum64_lo = utils.sum64_lo;
35559var sum64_4_hi = utils.sum64_4_hi;
35560var sum64_4_lo = utils.sum64_4_lo;
35561var sum64_5_hi = utils.sum64_5_hi;
35562var sum64_5_lo = utils.sum64_5_lo;
35563
35564var BlockHash = common.BlockHash;
35565
35566var sha512_K = [
35567 0x428a2f98, 0xd728ae22, 0x71374491, 0x23ef65cd,
35568 0xb5c0fbcf, 0xec4d3b2f, 0xe9b5dba5, 0x8189dbbc,
35569 0x3956c25b, 0xf348b538, 0x59f111f1, 0xb605d019,
35570 0x923f82a4, 0xaf194f9b, 0xab1c5ed5, 0xda6d8118,
35571 0xd807aa98, 0xa3030242, 0x12835b01, 0x45706fbe,
35572 0x243185be, 0x4ee4b28c, 0x550c7dc3, 0xd5ffb4e2,
35573 0x72be5d74, 0xf27b896f, 0x80deb1fe, 0x3b1696b1,
35574 0x9bdc06a7, 0x25c71235, 0xc19bf174, 0xcf692694,
35575 0xe49b69c1, 0x9ef14ad2, 0xefbe4786, 0x384f25e3,
35576 0x0fc19dc6, 0x8b8cd5b5, 0x240ca1cc, 0x77ac9c65,
35577 0x2de92c6f, 0x592b0275, 0x4a7484aa, 0x6ea6e483,
35578 0x5cb0a9dc, 0xbd41fbd4, 0x76f988da, 0x831153b5,
35579 0x983e5152, 0xee66dfab, 0xa831c66d, 0x2db43210,
35580 0xb00327c8, 0x98fb213f, 0xbf597fc7, 0xbeef0ee4,
35581 0xc6e00bf3, 0x3da88fc2, 0xd5a79147, 0x930aa725,
35582 0x06ca6351, 0xe003826f, 0x14292967, 0x0a0e6e70,
35583 0x27b70a85, 0x46d22ffc, 0x2e1b2138, 0x5c26c926,
35584 0x4d2c6dfc, 0x5ac42aed, 0x53380d13, 0x9d95b3df,
35585 0x650a7354, 0x8baf63de, 0x766a0abb, 0x3c77b2a8,
35586 0x81c2c92e, 0x47edaee6, 0x92722c85, 0x1482353b,
35587 0xa2bfe8a1, 0x4cf10364, 0xa81a664b, 0xbc423001,
35588 0xc24b8b70, 0xd0f89791, 0xc76c51a3, 0x0654be30,
35589 0xd192e819, 0xd6ef5218, 0xd6990624, 0x5565a910,
35590 0xf40e3585, 0x5771202a, 0x106aa070, 0x32bbd1b8,
35591 0x19a4c116, 0xb8d2d0c8, 0x1e376c08, 0x5141ab53,
35592 0x2748774c, 0xdf8eeb99, 0x34b0bcb5, 0xe19b48a8,
35593 0x391c0cb3, 0xc5c95a63, 0x4ed8aa4a, 0xe3418acb,
35594 0x5b9cca4f, 0x7763e373, 0x682e6ff3, 0xd6b2b8a3,
35595 0x748f82ee, 0x5defb2fc, 0x78a5636f, 0x43172f60,
35596 0x84c87814, 0xa1f0ab72, 0x8cc70208, 0x1a6439ec,
35597 0x90befffa, 0x23631e28, 0xa4506ceb, 0xde82bde9,
35598 0xbef9a3f7, 0xb2c67915, 0xc67178f2, 0xe372532b,
35599 0xca273ece, 0xea26619c, 0xd186b8c7, 0x21c0c207,
35600 0xeada7dd6, 0xcde0eb1e, 0xf57d4f7f, 0xee6ed178,
35601 0x06f067aa, 0x72176fba, 0x0a637dc5, 0xa2c898a6,
35602 0x113f9804, 0xbef90dae, 0x1b710b35, 0x131c471b,
35603 0x28db77f5, 0x23047d84, 0x32caab7b, 0x40c72493,
35604 0x3c9ebe0a, 0x15c9bebc, 0x431d67c4, 0x9c100d4c,
35605 0x4cc5d4be, 0xcb3e42b6, 0x597f299c, 0xfc657e2a,
35606 0x5fcb6fab, 0x3ad6faec, 0x6c44198c, 0x4a475817
35607];
35608
35609function SHA512() {
35610 if (!(this instanceof SHA512))
35611 return new SHA512();
35612
35613 BlockHash.call(this);
35614 this.h = [
35615 0x6a09e667, 0xf3bcc908,
35616 0xbb67ae85, 0x84caa73b,
35617 0x3c6ef372, 0xfe94f82b,
35618 0xa54ff53a, 0x5f1d36f1,
35619 0x510e527f, 0xade682d1,
35620 0x9b05688c, 0x2b3e6c1f,
35621 0x1f83d9ab, 0xfb41bd6b,
35622 0x5be0cd19, 0x137e2179 ];
35623 this.k = sha512_K;
35624 this.W = new Array(160);
35625}
35626utils.inherits(SHA512, BlockHash);
35627module.exports = SHA512;
35628
35629SHA512.blockSize = 1024;
35630SHA512.outSize = 512;
35631SHA512.hmacStrength = 192;
35632SHA512.padLength = 128;
35633
35634SHA512.prototype._prepareBlock = function _prepareBlock(msg, start) {
35635 var W = this.W;
35636
35637 // 32 x 32bit words
35638 for (var i = 0; i < 32; i++)
35639 W[i] = msg[start + i];
35640 for (; i < W.length; i += 2) {
35641 var c0_hi = g1_512_hi(W[i - 4], W[i - 3]); // i - 2
35642 var c0_lo = g1_512_lo(W[i - 4], W[i - 3]);
35643 var c1_hi = W[i - 14]; // i - 7
35644 var c1_lo = W[i - 13];
35645 var c2_hi = g0_512_hi(W[i - 30], W[i - 29]); // i - 15
35646 var c2_lo = g0_512_lo(W[i - 30], W[i - 29]);
35647 var c3_hi = W[i - 32]; // i - 16
35648 var c3_lo = W[i - 31];
35649
35650 W[i] = sum64_4_hi(
35651 c0_hi, c0_lo,
35652 c1_hi, c1_lo,
35653 c2_hi, c2_lo,
35654 c3_hi, c3_lo);
35655 W[i + 1] = sum64_4_lo(
35656 c0_hi, c0_lo,
35657 c1_hi, c1_lo,
35658 c2_hi, c2_lo,
35659 c3_hi, c3_lo);
35660 }
35661};
35662
35663SHA512.prototype._update = function _update(msg, start) {
35664 this._prepareBlock(msg, start);
35665
35666 var W = this.W;
35667
35668 var ah = this.h[0];
35669 var al = this.h[1];
35670 var bh = this.h[2];
35671 var bl = this.h[3];
35672 var ch = this.h[4];
35673 var cl = this.h[5];
35674 var dh = this.h[6];
35675 var dl = this.h[7];
35676 var eh = this.h[8];
35677 var el = this.h[9];
35678 var fh = this.h[10];
35679 var fl = this.h[11];
35680 var gh = this.h[12];
35681 var gl = this.h[13];
35682 var hh = this.h[14];
35683 var hl = this.h[15];
35684
35685 assert(this.k.length === W.length);
35686 for (var i = 0; i < W.length; i += 2) {
35687 var c0_hi = hh;
35688 var c0_lo = hl;
35689 var c1_hi = s1_512_hi(eh, el);
35690 var c1_lo = s1_512_lo(eh, el);
35691 var c2_hi = ch64_hi(eh, el, fh, fl, gh, gl);
35692 var c2_lo = ch64_lo(eh, el, fh, fl, gh, gl);
35693 var c3_hi = this.k[i];
35694 var c3_lo = this.k[i + 1];
35695 var c4_hi = W[i];
35696 var c4_lo = W[i + 1];
35697
35698 var T1_hi = sum64_5_hi(
35699 c0_hi, c0_lo,
35700 c1_hi, c1_lo,
35701 c2_hi, c2_lo,
35702 c3_hi, c3_lo,
35703 c4_hi, c4_lo);
35704 var T1_lo = sum64_5_lo(
35705 c0_hi, c0_lo,
35706 c1_hi, c1_lo,
35707 c2_hi, c2_lo,
35708 c3_hi, c3_lo,
35709 c4_hi, c4_lo);
35710
35711 c0_hi = s0_512_hi(ah, al);
35712 c0_lo = s0_512_lo(ah, al);
35713 c1_hi = maj64_hi(ah, al, bh, bl, ch, cl);
35714 c1_lo = maj64_lo(ah, al, bh, bl, ch, cl);
35715
35716 var T2_hi = sum64_hi(c0_hi, c0_lo, c1_hi, c1_lo);
35717 var T2_lo = sum64_lo(c0_hi, c0_lo, c1_hi, c1_lo);
35718
35719 hh = gh;
35720 hl = gl;
35721
35722 gh = fh;
35723 gl = fl;
35724
35725 fh = eh;
35726 fl = el;
35727
35728 eh = sum64_hi(dh, dl, T1_hi, T1_lo);
35729 el = sum64_lo(dl, dl, T1_hi, T1_lo);
35730
35731 dh = ch;
35732 dl = cl;
35733
35734 ch = bh;
35735 cl = bl;
35736
35737 bh = ah;
35738 bl = al;
35739
35740 ah = sum64_hi(T1_hi, T1_lo, T2_hi, T2_lo);
35741 al = sum64_lo(T1_hi, T1_lo, T2_hi, T2_lo);
35742 }
35743
35744 sum64(this.h, 0, ah, al);
35745 sum64(this.h, 2, bh, bl);
35746 sum64(this.h, 4, ch, cl);
35747 sum64(this.h, 6, dh, dl);
35748 sum64(this.h, 8, eh, el);
35749 sum64(this.h, 10, fh, fl);
35750 sum64(this.h, 12, gh, gl);
35751 sum64(this.h, 14, hh, hl);
35752};
35753
35754SHA512.prototype._digest = function digest(enc) {
35755 if (enc === 'hex')
35756 return utils.toHex32(this.h, 'big');
35757 else
35758 return utils.split32(this.h, 'big');
35759};
35760
35761function ch64_hi(xh, xl, yh, yl, zh) {
35762 var r = (xh & yh) ^ ((~xh) & zh);
35763 if (r < 0)
35764 r += 0x100000000;
35765 return r;
35766}
35767
35768function ch64_lo(xh, xl, yh, yl, zh, zl) {
35769 var r = (xl & yl) ^ ((~xl) & zl);
35770 if (r < 0)
35771 r += 0x100000000;
35772 return r;
35773}
35774
35775function maj64_hi(xh, xl, yh, yl, zh) {
35776 var r = (xh & yh) ^ (xh & zh) ^ (yh & zh);
35777 if (r < 0)
35778 r += 0x100000000;
35779 return r;
35780}
35781
35782function maj64_lo(xh, xl, yh, yl, zh, zl) {
35783 var r = (xl & yl) ^ (xl & zl) ^ (yl & zl);
35784 if (r < 0)
35785 r += 0x100000000;
35786 return r;
35787}
35788
35789function s0_512_hi(xh, xl) {
35790 var c0_hi = rotr64_hi(xh, xl, 28);
35791 var c1_hi = rotr64_hi(xl, xh, 2); // 34
35792 var c2_hi = rotr64_hi(xl, xh, 7); // 39
35793
35794 var r = c0_hi ^ c1_hi ^ c2_hi;
35795 if (r < 0)
35796 r += 0x100000000;
35797 return r;
35798}
35799
35800function s0_512_lo(xh, xl) {
35801 var c0_lo = rotr64_lo(xh, xl, 28);
35802 var c1_lo = rotr64_lo(xl, xh, 2); // 34
35803 var c2_lo = rotr64_lo(xl, xh, 7); // 39
35804
35805 var r = c0_lo ^ c1_lo ^ c2_lo;
35806 if (r < 0)
35807 r += 0x100000000;
35808 return r;
35809}
35810
35811function s1_512_hi(xh, xl) {
35812 var c0_hi = rotr64_hi(xh, xl, 14);
35813 var c1_hi = rotr64_hi(xh, xl, 18);
35814 var c2_hi = rotr64_hi(xl, xh, 9); // 41
35815
35816 var r = c0_hi ^ c1_hi ^ c2_hi;
35817 if (r < 0)
35818 r += 0x100000000;
35819 return r;
35820}
35821
35822function s1_512_lo(xh, xl) {
35823 var c0_lo = rotr64_lo(xh, xl, 14);
35824 var c1_lo = rotr64_lo(xh, xl, 18);
35825 var c2_lo = rotr64_lo(xl, xh, 9); // 41
35826
35827 var r = c0_lo ^ c1_lo ^ c2_lo;
35828 if (r < 0)
35829 r += 0x100000000;
35830 return r;
35831}
35832
35833function g0_512_hi(xh, xl) {
35834 var c0_hi = rotr64_hi(xh, xl, 1);
35835 var c1_hi = rotr64_hi(xh, xl, 8);
35836 var c2_hi = shr64_hi(xh, xl, 7);
35837
35838 var r = c0_hi ^ c1_hi ^ c2_hi;
35839 if (r < 0)
35840 r += 0x100000000;
35841 return r;
35842}
35843
35844function g0_512_lo(xh, xl) {
35845 var c0_lo = rotr64_lo(xh, xl, 1);
35846 var c1_lo = rotr64_lo(xh, xl, 8);
35847 var c2_lo = shr64_lo(xh, xl, 7);
35848
35849 var r = c0_lo ^ c1_lo ^ c2_lo;
35850 if (r < 0)
35851 r += 0x100000000;
35852 return r;
35853}
35854
35855function g1_512_hi(xh, xl) {
35856 var c0_hi = rotr64_hi(xh, xl, 19);
35857 var c1_hi = rotr64_hi(xl, xh, 29); // 61
35858 var c2_hi = shr64_hi(xh, xl, 6);
35859
35860 var r = c0_hi ^ c1_hi ^ c2_hi;
35861 if (r < 0)
35862 r += 0x100000000;
35863 return r;
35864}
35865
35866function g1_512_lo(xh, xl) {
35867 var c0_lo = rotr64_lo(xh, xl, 19);
35868 var c1_lo = rotr64_lo(xl, xh, 29); // 61
35869 var c2_lo = shr64_lo(xh, xl, 6);
35870
35871 var r = c0_lo ^ c1_lo ^ c2_lo;
35872 if (r < 0)
35873 r += 0x100000000;
35874 return r;
35875}
35876
35877},{"../common":191,"../utils":201,"minimalistic-assert":237}],200:[function(require,module,exports){
35878'use strict';
35879
35880var utils = require('../utils');
35881var rotr32 = utils.rotr32;
35882
35883function ft_1(s, x, y, z) {
35884 if (s === 0)
35885 return ch32(x, y, z);
35886 if (s === 1 || s === 3)
35887 return p32(x, y, z);
35888 if (s === 2)
35889 return maj32(x, y, z);
35890}
35891exports.ft_1 = ft_1;
35892
35893function ch32(x, y, z) {
35894 return (x & y) ^ ((~x) & z);
35895}
35896exports.ch32 = ch32;
35897
35898function maj32(x, y, z) {
35899 return (x & y) ^ (x & z) ^ (y & z);
35900}
35901exports.maj32 = maj32;
35902
35903function p32(x, y, z) {
35904 return x ^ y ^ z;
35905}
35906exports.p32 = p32;
35907
35908function s0_256(x) {
35909 return rotr32(x, 2) ^ rotr32(x, 13) ^ rotr32(x, 22);
35910}
35911exports.s0_256 = s0_256;
35912
35913function s1_256(x) {
35914 return rotr32(x, 6) ^ rotr32(x, 11) ^ rotr32(x, 25);
35915}
35916exports.s1_256 = s1_256;
35917
35918function g0_256(x) {
35919 return rotr32(x, 7) ^ rotr32(x, 18) ^ (x >>> 3);
35920}
35921exports.g0_256 = g0_256;
35922
35923function g1_256(x) {
35924 return rotr32(x, 17) ^ rotr32(x, 19) ^ (x >>> 10);
35925}
35926exports.g1_256 = g1_256;
35927
35928},{"../utils":201}],201:[function(require,module,exports){
35929'use strict';
35930
35931var assert = require('minimalistic-assert');
35932var inherits = require('inherits');
35933
35934exports.inherits = inherits;
35935
35936function isSurrogatePair(msg, i) {
35937 if ((msg.charCodeAt(i) & 0xFC00) !== 0xD800) {
35938 return false;
35939 }
35940 if (i < 0 || i + 1 >= msg.length) {
35941 return false;
35942 }
35943 return (msg.charCodeAt(i + 1) & 0xFC00) === 0xDC00;
35944}
35945
35946function toArray(msg, enc) {
35947 if (Array.isArray(msg))
35948 return msg.slice();
35949 if (!msg)
35950 return [];
35951 var res = [];
35952 if (typeof msg === 'string') {
35953 if (!enc) {
35954 // Inspired by stringToUtf8ByteArray() in closure-library by Google
35955 // https://github.com/google/closure-library/blob/8598d87242af59aac233270742c8984e2b2bdbe0/closure/goog/crypt/crypt.js#L117-L143
35956 // Apache License 2.0
35957 // https://github.com/google/closure-library/blob/master/LICENSE
35958 var p = 0;
35959 for (var i = 0; i < msg.length; i++) {
35960 var c = msg.charCodeAt(i);
35961 if (c < 128) {
35962 res[p++] = c;
35963 } else if (c < 2048) {
35964 res[p++] = (c >> 6) | 192;
35965 res[p++] = (c & 63) | 128;
35966 } else if (isSurrogatePair(msg, i)) {
35967 c = 0x10000 + ((c & 0x03FF) << 10) + (msg.charCodeAt(++i) & 0x03FF);
35968 res[p++] = (c >> 18) | 240;
35969 res[p++] = ((c >> 12) & 63) | 128;
35970 res[p++] = ((c >> 6) & 63) | 128;
35971 res[p++] = (c & 63) | 128;
35972 } else {
35973 res[p++] = (c >> 12) | 224;
35974 res[p++] = ((c >> 6) & 63) | 128;
35975 res[p++] = (c & 63) | 128;
35976 }
35977 }
35978 } else if (enc === 'hex') {
35979 msg = msg.replace(/[^a-z0-9]+/ig, '');
35980 if (msg.length % 2 !== 0)
35981 msg = '0' + msg;
35982 for (i = 0; i < msg.length; i += 2)
35983 res.push(parseInt(msg[i] + msg[i + 1], 16));
35984 }
35985 } else {
35986 for (i = 0; i < msg.length; i++)
35987 res[i] = msg[i] | 0;
35988 }
35989 return res;
35990}
35991exports.toArray = toArray;
35992
35993function toHex(msg) {
35994 var res = '';
35995 for (var i = 0; i < msg.length; i++)
35996 res += zero2(msg[i].toString(16));
35997 return res;
35998}
35999exports.toHex = toHex;
36000
36001function htonl(w) {
36002 var res = (w >>> 24) |
36003 ((w >>> 8) & 0xff00) |
36004 ((w << 8) & 0xff0000) |
36005 ((w & 0xff) << 24);
36006 return res >>> 0;
36007}
36008exports.htonl = htonl;
36009
36010function toHex32(msg, endian) {
36011 var res = '';
36012 for (var i = 0; i < msg.length; i++) {
36013 var w = msg[i];
36014 if (endian === 'little')
36015 w = htonl(w);
36016 res += zero8(w.toString(16));
36017 }
36018 return res;
36019}
36020exports.toHex32 = toHex32;
36021
36022function zero2(word) {
36023 if (word.length === 1)
36024 return '0' + word;
36025 else
36026 return word;
36027}
36028exports.zero2 = zero2;
36029
36030function zero8(word) {
36031 if (word.length === 7)
36032 return '0' + word;
36033 else if (word.length === 6)
36034 return '00' + word;
36035 else if (word.length === 5)
36036 return '000' + word;
36037 else if (word.length === 4)
36038 return '0000' + word;
36039 else if (word.length === 3)
36040 return '00000' + word;
36041 else if (word.length === 2)
36042 return '000000' + word;
36043 else if (word.length === 1)
36044 return '0000000' + word;
36045 else
36046 return word;
36047}
36048exports.zero8 = zero8;
36049
36050function join32(msg, start, end, endian) {
36051 var len = end - start;
36052 assert(len % 4 === 0);
36053 var res = new Array(len / 4);
36054 for (var i = 0, k = start; i < res.length; i++, k += 4) {
36055 var w;
36056 if (endian === 'big')
36057 w = (msg[k] << 24) | (msg[k + 1] << 16) | (msg[k + 2] << 8) | msg[k + 3];
36058 else
36059 w = (msg[k + 3] << 24) | (msg[k + 2] << 16) | (msg[k + 1] << 8) | msg[k];
36060 res[i] = w >>> 0;
36061 }
36062 return res;
36063}
36064exports.join32 = join32;
36065
36066function split32(msg, endian) {
36067 var res = new Array(msg.length * 4);
36068 for (var i = 0, k = 0; i < msg.length; i++, k += 4) {
36069 var m = msg[i];
36070 if (endian === 'big') {
36071 res[k] = m >>> 24;
36072 res[k + 1] = (m >>> 16) & 0xff;
36073 res[k + 2] = (m >>> 8) & 0xff;
36074 res[k + 3] = m & 0xff;
36075 } else {
36076 res[k + 3] = m >>> 24;
36077 res[k + 2] = (m >>> 16) & 0xff;
36078 res[k + 1] = (m >>> 8) & 0xff;
36079 res[k] = m & 0xff;
36080 }
36081 }
36082 return res;
36083}
36084exports.split32 = split32;
36085
36086function rotr32(w, b) {
36087 return (w >>> b) | (w << (32 - b));
36088}
36089exports.rotr32 = rotr32;
36090
36091function rotl32(w, b) {
36092 return (w << b) | (w >>> (32 - b));
36093}
36094exports.rotl32 = rotl32;
36095
36096function sum32(a, b) {
36097 return (a + b) >>> 0;
36098}
36099exports.sum32 = sum32;
36100
36101function sum32_3(a, b, c) {
36102 return (a + b + c) >>> 0;
36103}
36104exports.sum32_3 = sum32_3;
36105
36106function sum32_4(a, b, c, d) {
36107 return (a + b + c + d) >>> 0;
36108}
36109exports.sum32_4 = sum32_4;
36110
36111function sum32_5(a, b, c, d, e) {
36112 return (a + b + c + d + e) >>> 0;
36113}
36114exports.sum32_5 = sum32_5;
36115
36116function sum64(buf, pos, ah, al) {
36117 var bh = buf[pos];
36118 var bl = buf[pos + 1];
36119
36120 var lo = (al + bl) >>> 0;
36121 var hi = (lo < al ? 1 : 0) + ah + bh;
36122 buf[pos] = hi >>> 0;
36123 buf[pos + 1] = lo;
36124}
36125exports.sum64 = sum64;
36126
36127function sum64_hi(ah, al, bh, bl) {
36128 var lo = (al + bl) >>> 0;
36129 var hi = (lo < al ? 1 : 0) + ah + bh;
36130 return hi >>> 0;
36131}
36132exports.sum64_hi = sum64_hi;
36133
36134function sum64_lo(ah, al, bh, bl) {
36135 var lo = al + bl;
36136 return lo >>> 0;
36137}
36138exports.sum64_lo = sum64_lo;
36139
36140function sum64_4_hi(ah, al, bh, bl, ch, cl, dh, dl) {
36141 var carry = 0;
36142 var lo = al;
36143 lo = (lo + bl) >>> 0;
36144 carry += lo < al ? 1 : 0;
36145 lo = (lo + cl) >>> 0;
36146 carry += lo < cl ? 1 : 0;
36147 lo = (lo + dl) >>> 0;
36148 carry += lo < dl ? 1 : 0;
36149
36150 var hi = ah + bh + ch + dh + carry;
36151 return hi >>> 0;
36152}
36153exports.sum64_4_hi = sum64_4_hi;
36154
36155function sum64_4_lo(ah, al, bh, bl, ch, cl, dh, dl) {
36156 var lo = al + bl + cl + dl;
36157 return lo >>> 0;
36158}
36159exports.sum64_4_lo = sum64_4_lo;
36160
36161function sum64_5_hi(ah, al, bh, bl, ch, cl, dh, dl, eh, el) {
36162 var carry = 0;
36163 var lo = al;
36164 lo = (lo + bl) >>> 0;
36165 carry += lo < al ? 1 : 0;
36166 lo = (lo + cl) >>> 0;
36167 carry += lo < cl ? 1 : 0;
36168 lo = (lo + dl) >>> 0;
36169 carry += lo < dl ? 1 : 0;
36170 lo = (lo + el) >>> 0;
36171 carry += lo < el ? 1 : 0;
36172
36173 var hi = ah + bh + ch + dh + eh + carry;
36174 return hi >>> 0;
36175}
36176exports.sum64_5_hi = sum64_5_hi;
36177
36178function sum64_5_lo(ah, al, bh, bl, ch, cl, dh, dl, eh, el) {
36179 var lo = al + bl + cl + dl + el;
36180
36181 return lo >>> 0;
36182}
36183exports.sum64_5_lo = sum64_5_lo;
36184
36185function rotr64_hi(ah, al, num) {
36186 var r = (al << (32 - num)) | (ah >>> num);
36187 return r >>> 0;
36188}
36189exports.rotr64_hi = rotr64_hi;
36190
36191function rotr64_lo(ah, al, num) {
36192 var r = (ah << (32 - num)) | (al >>> num);
36193 return r >>> 0;
36194}
36195exports.rotr64_lo = rotr64_lo;
36196
36197function shr64_hi(ah, al, num) {
36198 return ah >>> num;
36199}
36200exports.shr64_hi = shr64_hi;
36201
36202function shr64_lo(ah, al, num) {
36203 var r = (ah << (32 - num)) | (al >>> num);
36204 return r >>> 0;
36205}
36206exports.shr64_lo = shr64_lo;
36207
36208},{"inherits":210,"minimalistic-assert":237}],202:[function(require,module,exports){
36209'use strict';
36210
36211var hash = require('hash.js');
36212var utils = require('minimalistic-crypto-utils');
36213var assert = require('minimalistic-assert');
36214
36215function HmacDRBG(options) {
36216 if (!(this instanceof HmacDRBG))
36217 return new HmacDRBG(options);
36218 this.hash = options.hash;
36219 this.predResist = !!options.predResist;
36220
36221 this.outLen = this.hash.outSize;
36222 this.minEntropy = options.minEntropy || this.hash.hmacStrength;
36223
36224 this._reseed = null;
36225 this.reseedInterval = null;
36226 this.K = null;
36227 this.V = null;
36228
36229 var entropy = utils.toArray(options.entropy, options.entropyEnc || 'hex');
36230 var nonce = utils.toArray(options.nonce, options.nonceEnc || 'hex');
36231 var pers = utils.toArray(options.pers, options.persEnc || 'hex');
36232 assert(entropy.length >= (this.minEntropy / 8),
36233 'Not enough entropy. Minimum is: ' + this.minEntropy + ' bits');
36234 this._init(entropy, nonce, pers);
36235}
36236module.exports = HmacDRBG;
36237
36238HmacDRBG.prototype._init = function init(entropy, nonce, pers) {
36239 var seed = entropy.concat(nonce).concat(pers);
36240
36241 this.K = new Array(this.outLen / 8);
36242 this.V = new Array(this.outLen / 8);
36243 for (var i = 0; i < this.V.length; i++) {
36244 this.K[i] = 0x00;
36245 this.V[i] = 0x01;
36246 }
36247
36248 this._update(seed);
36249 this._reseed = 1;
36250 this.reseedInterval = 0x1000000000000; // 2^48
36251};
36252
36253HmacDRBG.prototype._hmac = function hmac() {
36254 return new hash.hmac(this.hash, this.K);
36255};
36256
36257HmacDRBG.prototype._update = function update(seed) {
36258 var kmac = this._hmac()
36259 .update(this.V)
36260 .update([ 0x00 ]);
36261 if (seed)
36262 kmac = kmac.update(seed);
36263 this.K = kmac.digest();
36264 this.V = this._hmac().update(this.V).digest();
36265 if (!seed)
36266 return;
36267
36268 this.K = this._hmac()
36269 .update(this.V)
36270 .update([ 0x01 ])
36271 .update(seed)
36272 .digest();
36273 this.V = this._hmac().update(this.V).digest();
36274};
36275
36276HmacDRBG.prototype.reseed = function reseed(entropy, entropyEnc, add, addEnc) {
36277 // Optional entropy enc
36278 if (typeof entropyEnc !== 'string') {
36279 addEnc = add;
36280 add = entropyEnc;
36281 entropyEnc = null;
36282 }
36283
36284 entropy = utils.toArray(entropy, entropyEnc);
36285 add = utils.toArray(add, addEnc);
36286
36287 assert(entropy.length >= (this.minEntropy / 8),
36288 'Not enough entropy. Minimum is: ' + this.minEntropy + ' bits');
36289
36290 this._update(entropy.concat(add || []));
36291 this._reseed = 1;
36292};
36293
36294HmacDRBG.prototype.generate = function generate(len, enc, add, addEnc) {
36295 if (this._reseed > this.reseedInterval)
36296 throw new Error('Reseed is required');
36297
36298 // Optional encoding
36299 if (typeof enc !== 'string') {
36300 addEnc = add;
36301 add = enc;
36302 enc = null;
36303 }
36304
36305 // Optional additional data
36306 if (add) {
36307 add = utils.toArray(add, addEnc || 'hex');
36308 this._update(add);
36309 }
36310
36311 var temp = [];
36312 while (temp.length < len) {
36313 this.V = this._hmac().update(this.V).digest();
36314 temp = temp.concat(this.V);
36315 }
36316
36317 var res = temp.slice(0, len);
36318 this._update(add);
36319 this._reseed++;
36320 return utils.encode(res, enc);
36321};
36322
36323},{"hash.js":190,"minimalistic-assert":237,"minimalistic-crypto-utils":238}],203:[function(require,module,exports){
36324// Copyright 2015 Joyent, Inc.
36325
36326var parser = require('./parser');
36327var signer = require('./signer');
36328var verify = require('./verify');
36329var utils = require('./utils');
36330
36331
36332
36333///--- API
36334
36335module.exports = {
36336
36337 parse: parser.parseRequest,
36338 parseRequest: parser.parseRequest,
36339
36340 sign: signer.signRequest,
36341 signRequest: signer.signRequest,
36342 createSigner: signer.createSigner,
36343 isSigner: signer.isSigner,
36344
36345 sshKeyToPEM: utils.sshKeyToPEM,
36346 sshKeyFingerprint: utils.fingerprint,
36347 pemToRsaSSHKey: utils.pemToRsaSSHKey,
36348
36349 verify: verify.verifySignature,
36350 verifySignature: verify.verifySignature,
36351 verifyHMAC: verify.verifyHMAC
36352};
36353
36354},{"./parser":204,"./signer":205,"./utils":206,"./verify":207}],204:[function(require,module,exports){
36355// Copyright 2012 Joyent, Inc. All rights reserved.
36356
36357var assert = require('assert-plus');
36358var util = require('util');
36359var utils = require('./utils');
36360
36361
36362
36363///--- Globals
36364
36365var HASH_ALGOS = utils.HASH_ALGOS;
36366var PK_ALGOS = utils.PK_ALGOS;
36367var HttpSignatureError = utils.HttpSignatureError;
36368var InvalidAlgorithmError = utils.InvalidAlgorithmError;
36369var validateAlgorithm = utils.validateAlgorithm;
36370
36371var State = {
36372 New: 0,
36373 Params: 1
36374};
36375
36376var ParamsState = {
36377 Name: 0,
36378 Quote: 1,
36379 Value: 2,
36380 Comma: 3
36381};
36382
36383
36384///--- Specific Errors
36385
36386
36387function ExpiredRequestError(message) {
36388 HttpSignatureError.call(this, message, ExpiredRequestError);
36389}
36390util.inherits(ExpiredRequestError, HttpSignatureError);
36391
36392
36393function InvalidHeaderError(message) {
36394 HttpSignatureError.call(this, message, InvalidHeaderError);
36395}
36396util.inherits(InvalidHeaderError, HttpSignatureError);
36397
36398
36399function InvalidParamsError(message) {
36400 HttpSignatureError.call(this, message, InvalidParamsError);
36401}
36402util.inherits(InvalidParamsError, HttpSignatureError);
36403
36404
36405function MissingHeaderError(message) {
36406 HttpSignatureError.call(this, message, MissingHeaderError);
36407}
36408util.inherits(MissingHeaderError, HttpSignatureError);
36409
36410function StrictParsingError(message) {
36411 HttpSignatureError.call(this, message, StrictParsingError);
36412}
36413util.inherits(StrictParsingError, HttpSignatureError);
36414
36415///--- Exported API
36416
36417module.exports = {
36418
36419 /**
36420 * Parses the 'Authorization' header out of an http.ServerRequest object.
36421 *
36422 * Note that this API will fully validate the Authorization header, and throw
36423 * on any error. It will not however check the signature, or the keyId format
36424 * as those are specific to your environment. You can use the options object
36425 * to pass in extra constraints.
36426 *
36427 * As a response object you can expect this:
36428 *
36429 * {
36430 * "scheme": "Signature",
36431 * "params": {
36432 * "keyId": "foo",
36433 * "algorithm": "rsa-sha256",
36434 * "headers": [
36435 * "date" or "x-date",
36436 * "digest"
36437 * ],
36438 * "signature": "base64"
36439 * },
36440 * "signingString": "ready to be passed to crypto.verify()"
36441 * }
36442 *
36443 * @param {Object} request an http.ServerRequest.
36444 * @param {Object} options an optional options object with:
36445 * - clockSkew: allowed clock skew in seconds (default 300).
36446 * - headers: required header names (def: date or x-date)
36447 * - algorithms: algorithms to support (default: all).
36448 * - strict: should enforce latest spec parsing
36449 * (default: false).
36450 * @return {Object} parsed out object (see above).
36451 * @throws {TypeError} on invalid input.
36452 * @throws {InvalidHeaderError} on an invalid Authorization header error.
36453 * @throws {InvalidParamsError} if the params in the scheme are invalid.
36454 * @throws {MissingHeaderError} if the params indicate a header not present,
36455 * either in the request headers from the params,
36456 * or not in the params from a required header
36457 * in options.
36458 * @throws {StrictParsingError} if old attributes are used in strict parsing
36459 * mode.
36460 * @throws {ExpiredRequestError} if the value of date or x-date exceeds skew.
36461 */
36462 parseRequest: function parseRequest(request, options) {
36463 assert.object(request, 'request');
36464 assert.object(request.headers, 'request.headers');
36465 if (options === undefined) {
36466 options = {};
36467 }
36468 if (options.headers === undefined) {
36469 options.headers = [request.headers['x-date'] ? 'x-date' : 'date'];
36470 }
36471 assert.object(options, 'options');
36472 assert.arrayOfString(options.headers, 'options.headers');
36473 assert.optionalFinite(options.clockSkew, 'options.clockSkew');
36474
36475 var authzHeaderName = options.authorizationHeaderName || 'authorization';
36476
36477 if (!request.headers[authzHeaderName]) {
36478 throw new MissingHeaderError('no ' + authzHeaderName + ' header ' +
36479 'present in the request');
36480 }
36481
36482 options.clockSkew = options.clockSkew || 300;
36483
36484
36485 var i = 0;
36486 var state = State.New;
36487 var substate = ParamsState.Name;
36488 var tmpName = '';
36489 var tmpValue = '';
36490
36491 var parsed = {
36492 scheme: '',
36493 params: {},
36494 signingString: ''
36495 };
36496
36497 var authz = request.headers[authzHeaderName];
36498 for (i = 0; i < authz.length; i++) {
36499 var c = authz.charAt(i);
36500
36501 switch (Number(state)) {
36502
36503 case State.New:
36504 if (c !== ' ') parsed.scheme += c;
36505 else state = State.Params;
36506 break;
36507
36508 case State.Params:
36509 switch (Number(substate)) {
36510
36511 case ParamsState.Name:
36512 var code = c.charCodeAt(0);
36513 // restricted name of A-Z / a-z
36514 if ((code >= 0x41 && code <= 0x5a) || // A-Z
36515 (code >= 0x61 && code <= 0x7a)) { // a-z
36516 tmpName += c;
36517 } else if (c === '=') {
36518 if (tmpName.length === 0)
36519 throw new InvalidHeaderError('bad param format');
36520 substate = ParamsState.Quote;
36521 } else {
36522 throw new InvalidHeaderError('bad param format');
36523 }
36524 break;
36525
36526 case ParamsState.Quote:
36527 if (c === '"') {
36528 tmpValue = '';
36529 substate = ParamsState.Value;
36530 } else {
36531 throw new InvalidHeaderError('bad param format');
36532 }
36533 break;
36534
36535 case ParamsState.Value:
36536 if (c === '"') {
36537 parsed.params[tmpName] = tmpValue;
36538 substate = ParamsState.Comma;
36539 } else {
36540 tmpValue += c;
36541 }
36542 break;
36543
36544 case ParamsState.Comma:
36545 if (c === ',') {
36546 tmpName = '';
36547 substate = ParamsState.Name;
36548 } else {
36549 throw new InvalidHeaderError('bad param format');
36550 }
36551 break;
36552
36553 default:
36554 throw new Error('Invalid substate');
36555 }
36556 break;
36557
36558 default:
36559 throw new Error('Invalid substate');
36560 }
36561
36562 }
36563
36564 if (!parsed.params.headers || parsed.params.headers === '') {
36565 if (request.headers['x-date']) {
36566 parsed.params.headers = ['x-date'];
36567 } else {
36568 parsed.params.headers = ['date'];
36569 }
36570 } else {
36571 parsed.params.headers = parsed.params.headers.split(' ');
36572 }
36573
36574 // Minimally validate the parsed object
36575 if (!parsed.scheme || parsed.scheme !== 'Signature')
36576 throw new InvalidHeaderError('scheme was not "Signature"');
36577
36578 if (!parsed.params.keyId)
36579 throw new InvalidHeaderError('keyId was not specified');
36580
36581 if (!parsed.params.algorithm)
36582 throw new InvalidHeaderError('algorithm was not specified');
36583
36584 if (!parsed.params.signature)
36585 throw new InvalidHeaderError('signature was not specified');
36586
36587 // Check the algorithm against the official list
36588 parsed.params.algorithm = parsed.params.algorithm.toLowerCase();
36589 try {
36590 validateAlgorithm(parsed.params.algorithm);
36591 } catch (e) {
36592 if (e instanceof InvalidAlgorithmError)
36593 throw (new InvalidParamsError(parsed.params.algorithm + ' is not ' +
36594 'supported'));
36595 else
36596 throw (e);
36597 }
36598
36599 // Build the signingString
36600 for (i = 0; i < parsed.params.headers.length; i++) {
36601 var h = parsed.params.headers[i].toLowerCase();
36602 parsed.params.headers[i] = h;
36603
36604 if (h === 'request-line') {
36605 if (!options.strict) {
36606 /*
36607 * We allow headers from the older spec drafts if strict parsing isn't
36608 * specified in options.
36609 */
36610 parsed.signingString +=
36611 request.method + ' ' + request.url + ' HTTP/' + request.httpVersion;
36612 } else {
36613 /* Strict parsing doesn't allow older draft headers. */
36614 throw (new StrictParsingError('request-line is not a valid header ' +
36615 'with strict parsing enabled.'));
36616 }
36617 } else if (h === '(request-target)') {
36618 parsed.signingString +=
36619 '(request-target): ' + request.method.toLowerCase() + ' ' +
36620 request.url;
36621 } else {
36622 var value = request.headers[h];
36623 if (value === undefined)
36624 throw new MissingHeaderError(h + ' was not in the request');
36625 parsed.signingString += h + ': ' + value;
36626 }
36627
36628 if ((i + 1) < parsed.params.headers.length)
36629 parsed.signingString += '\n';
36630 }
36631
36632 // Check against the constraints
36633 var date;
36634 if (request.headers.date || request.headers['x-date']) {
36635 if (request.headers['x-date']) {
36636 date = new Date(request.headers['x-date']);
36637 } else {
36638 date = new Date(request.headers.date);
36639 }
36640 var now = new Date();
36641 var skew = Math.abs(now.getTime() - date.getTime());
36642
36643 if (skew > options.clockSkew * 1000) {
36644 throw new ExpiredRequestError('clock skew of ' +
36645 (skew / 1000) +
36646 's was greater than ' +
36647 options.clockSkew + 's');
36648 }
36649 }
36650
36651 options.headers.forEach(function (hdr) {
36652 // Remember that we already checked any headers in the params
36653 // were in the request, so if this passes we're good.
36654 if (parsed.params.headers.indexOf(hdr.toLowerCase()) < 0)
36655 throw new MissingHeaderError(hdr + ' was not a signed header');
36656 });
36657
36658 if (options.algorithms) {
36659 if (options.algorithms.indexOf(parsed.params.algorithm) === -1)
36660 throw new InvalidParamsError(parsed.params.algorithm +
36661 ' is not a supported algorithm');
36662 }
36663
36664 parsed.algorithm = parsed.params.algorithm.toUpperCase();
36665 parsed.keyId = parsed.params.keyId;
36666 return parsed;
36667 }
36668
36669};
36670
36671},{"./utils":206,"assert-plus":67,"util":397}],205:[function(require,module,exports){
36672(function (Buffer){
36673// Copyright 2012 Joyent, Inc. All rights reserved.
36674
36675var assert = require('assert-plus');
36676var crypto = require('crypto');
36677var http = require('http');
36678var util = require('util');
36679var sshpk = require('sshpk');
36680var jsprim = require('jsprim');
36681var utils = require('./utils');
36682
36683var sprintf = require('util').format;
36684
36685var HASH_ALGOS = utils.HASH_ALGOS;
36686var PK_ALGOS = utils.PK_ALGOS;
36687var InvalidAlgorithmError = utils.InvalidAlgorithmError;
36688var HttpSignatureError = utils.HttpSignatureError;
36689var validateAlgorithm = utils.validateAlgorithm;
36690
36691///--- Globals
36692
36693var AUTHZ_FMT =
36694 'Signature keyId="%s",algorithm="%s",headers="%s",signature="%s"';
36695
36696///--- Specific Errors
36697
36698function MissingHeaderError(message) {
36699 HttpSignatureError.call(this, message, MissingHeaderError);
36700}
36701util.inherits(MissingHeaderError, HttpSignatureError);
36702
36703function StrictParsingError(message) {
36704 HttpSignatureError.call(this, message, StrictParsingError);
36705}
36706util.inherits(StrictParsingError, HttpSignatureError);
36707
36708/* See createSigner() */
36709function RequestSigner(options) {
36710 assert.object(options, 'options');
36711
36712 var alg = [];
36713 if (options.algorithm !== undefined) {
36714 assert.string(options.algorithm, 'options.algorithm');
36715 alg = validateAlgorithm(options.algorithm);
36716 }
36717 this.rs_alg = alg;
36718
36719 /*
36720 * RequestSigners come in two varieties: ones with an rs_signFunc, and ones
36721 * with an rs_signer.
36722 *
36723 * rs_signFunc-based RequestSigners have to build up their entire signing
36724 * string within the rs_lines array and give it to rs_signFunc as a single
36725 * concat'd blob. rs_signer-based RequestSigners can add a line at a time to
36726 * their signing state by using rs_signer.update(), thus only needing to
36727 * buffer the hash function state and one line at a time.
36728 */
36729 if (options.sign !== undefined) {
36730 assert.func(options.sign, 'options.sign');
36731 this.rs_signFunc = options.sign;
36732
36733 } else if (alg[0] === 'hmac' && options.key !== undefined) {
36734 assert.string(options.keyId, 'options.keyId');
36735 this.rs_keyId = options.keyId;
36736
36737 if (typeof (options.key) !== 'string' && !Buffer.isBuffer(options.key))
36738 throw (new TypeError('options.key for HMAC must be a string or Buffer'));
36739
36740 /*
36741 * Make an rs_signer for HMACs, not a rs_signFunc -- HMACs digest their
36742 * data in chunks rather than requiring it all to be given in one go
36743 * at the end, so they are more similar to signers than signFuncs.
36744 */
36745 this.rs_signer = crypto.createHmac(alg[1].toUpperCase(), options.key);
36746 this.rs_signer.sign = function () {
36747 var digest = this.digest('base64');
36748 return ({
36749 hashAlgorithm: alg[1],
36750 toString: function () { return (digest); }
36751 });
36752 };
36753
36754 } else if (options.key !== undefined) {
36755 var key = options.key;
36756 if (typeof (key) === 'string' || Buffer.isBuffer(key))
36757 key = sshpk.parsePrivateKey(key);
36758
36759 assert.ok(sshpk.PrivateKey.isPrivateKey(key, [1, 2]),
36760 'options.key must be a sshpk.PrivateKey');
36761 this.rs_key = key;
36762
36763 assert.string(options.keyId, 'options.keyId');
36764 this.rs_keyId = options.keyId;
36765
36766 if (!PK_ALGOS[key.type]) {
36767 throw (new InvalidAlgorithmError(key.type.toUpperCase() + ' type ' +
36768 'keys are not supported'));
36769 }
36770
36771 if (alg[0] !== undefined && key.type !== alg[0]) {
36772 throw (new InvalidAlgorithmError('options.key must be a ' +
36773 alg[0].toUpperCase() + ' key, was given a ' +
36774 key.type.toUpperCase() + ' key instead'));
36775 }
36776
36777 this.rs_signer = key.createSign(alg[1]);
36778
36779 } else {
36780 throw (new TypeError('options.sign (func) or options.key is required'));
36781 }
36782
36783 this.rs_headers = [];
36784 this.rs_lines = [];
36785}
36786
36787/**
36788 * Adds a header to be signed, with its value, into this signer.
36789 *
36790 * @param {String} header
36791 * @param {String} value
36792 * @return {String} value written
36793 */
36794RequestSigner.prototype.writeHeader = function (header, value) {
36795 assert.string(header, 'header');
36796 header = header.toLowerCase();
36797 assert.string(value, 'value');
36798
36799 this.rs_headers.push(header);
36800
36801 if (this.rs_signFunc) {
36802 this.rs_lines.push(header + ': ' + value);
36803
36804 } else {
36805 var line = header + ': ' + value;
36806 if (this.rs_headers.length > 0)
36807 line = '\n' + line;
36808 this.rs_signer.update(line);
36809 }
36810
36811 return (value);
36812};
36813
36814/**
36815 * Adds a default Date header, returning its value.
36816 *
36817 * @return {String}
36818 */
36819RequestSigner.prototype.writeDateHeader = function () {
36820 return (this.writeHeader('date', jsprim.rfc1123(new Date())));
36821};
36822
36823/**
36824 * Adds the request target line to be signed.
36825 *
36826 * @param {String} method, HTTP method (e.g. 'get', 'post', 'put')
36827 * @param {String} path
36828 */
36829RequestSigner.prototype.writeTarget = function (method, path) {
36830 assert.string(method, 'method');
36831 assert.string(path, 'path');
36832 method = method.toLowerCase();
36833 this.writeHeader('(request-target)', method + ' ' + path);
36834};
36835
36836/**
36837 * Calculate the value for the Authorization header on this request
36838 * asynchronously.
36839 *
36840 * @param {Func} callback (err, authz)
36841 */
36842RequestSigner.prototype.sign = function (cb) {
36843 assert.func(cb, 'callback');
36844
36845 if (this.rs_headers.length < 1)
36846 throw (new Error('At least one header must be signed'));
36847
36848 var alg, authz;
36849 if (this.rs_signFunc) {
36850 var data = this.rs_lines.join('\n');
36851 var self = this;
36852 this.rs_signFunc(data, function (err, sig) {
36853 if (err) {
36854 cb(err);
36855 return;
36856 }
36857 try {
36858 assert.object(sig, 'signature');
36859 assert.string(sig.keyId, 'signature.keyId');
36860 assert.string(sig.algorithm, 'signature.algorithm');
36861 assert.string(sig.signature, 'signature.signature');
36862 alg = validateAlgorithm(sig.algorithm);
36863
36864 authz = sprintf(AUTHZ_FMT,
36865 sig.keyId,
36866 sig.algorithm,
36867 self.rs_headers.join(' '),
36868 sig.signature);
36869 } catch (e) {
36870 cb(e);
36871 return;
36872 }
36873 cb(null, authz);
36874 });
36875
36876 } else {
36877 try {
36878 var sigObj = this.rs_signer.sign();
36879 } catch (e) {
36880 cb(e);
36881 return;
36882 }
36883 alg = (this.rs_alg[0] || this.rs_key.type) + '-' + sigObj.hashAlgorithm;
36884 var signature = sigObj.toString();
36885 authz = sprintf(AUTHZ_FMT,
36886 this.rs_keyId,
36887 alg,
36888 this.rs_headers.join(' '),
36889 signature);
36890 cb(null, authz);
36891 }
36892};
36893
36894///--- Exported API
36895
36896module.exports = {
36897 /**
36898 * Identifies whether a given object is a request signer or not.
36899 *
36900 * @param {Object} object, the object to identify
36901 * @returns {Boolean}
36902 */
36903 isSigner: function (obj) {
36904 if (typeof (obj) === 'object' && obj instanceof RequestSigner)
36905 return (true);
36906 return (false);
36907 },
36908
36909 /**
36910 * Creates a request signer, used to asynchronously build a signature
36911 * for a request (does not have to be an http.ClientRequest).
36912 *
36913 * @param {Object} options, either:
36914 * - {String} keyId
36915 * - {String|Buffer} key
36916 * - {String} algorithm (optional, required for HMAC)
36917 * or:
36918 * - {Func} sign (data, cb)
36919 * @return {RequestSigner}
36920 */
36921 createSigner: function createSigner(options) {
36922 return (new RequestSigner(options));
36923 },
36924
36925 /**
36926 * Adds an 'Authorization' header to an http.ClientRequest object.
36927 *
36928 * Note that this API will add a Date header if it's not already set. Any
36929 * other headers in the options.headers array MUST be present, or this
36930 * will throw.
36931 *
36932 * You shouldn't need to check the return type; it's just there if you want
36933 * to be pedantic.
36934 *
36935 * The optional flag indicates whether parsing should use strict enforcement
36936 * of the version draft-cavage-http-signatures-04 of the spec or beyond.
36937 * The default is to be loose and support
36938 * older versions for compatibility.
36939 *
36940 * @param {Object} request an instance of http.ClientRequest.
36941 * @param {Object} options signing parameters object:
36942 * - {String} keyId required.
36943 * - {String} key required (either a PEM or HMAC key).
36944 * - {Array} headers optional; defaults to ['date'].
36945 * - {String} algorithm optional (unless key is HMAC);
36946 * default is the same as the sshpk default
36947 * signing algorithm for the type of key given
36948 * - {String} httpVersion optional; defaults to '1.1'.
36949 * - {Boolean} strict optional; defaults to 'false'.
36950 * @return {Boolean} true if Authorization (and optionally Date) were added.
36951 * @throws {TypeError} on bad parameter types (input).
36952 * @throws {InvalidAlgorithmError} if algorithm was bad or incompatible with
36953 * the given key.
36954 * @throws {sshpk.KeyParseError} if key was bad.
36955 * @throws {MissingHeaderError} if a header to be signed was specified but
36956 * was not present.
36957 */
36958 signRequest: function signRequest(request, options) {
36959 assert.object(request, 'request');
36960 assert.object(options, 'options');
36961 assert.optionalString(options.algorithm, 'options.algorithm');
36962 assert.string(options.keyId, 'options.keyId');
36963 assert.optionalArrayOfString(options.headers, 'options.headers');
36964 assert.optionalString(options.httpVersion, 'options.httpVersion');
36965
36966 if (!request.getHeader('Date'))
36967 request.setHeader('Date', jsprim.rfc1123(new Date()));
36968 if (!options.headers)
36969 options.headers = ['date'];
36970 if (!options.httpVersion)
36971 options.httpVersion = '1.1';
36972
36973 var alg = [];
36974 if (options.algorithm) {
36975 options.algorithm = options.algorithm.toLowerCase();
36976 alg = validateAlgorithm(options.algorithm);
36977 }
36978
36979 var i;
36980 var stringToSign = '';
36981 for (i = 0; i < options.headers.length; i++) {
36982 if (typeof (options.headers[i]) !== 'string')
36983 throw new TypeError('options.headers must be an array of Strings');
36984
36985 var h = options.headers[i].toLowerCase();
36986
36987 if (h === 'request-line') {
36988 if (!options.strict) {
36989 /**
36990 * We allow headers from the older spec drafts if strict parsing isn't
36991 * specified in options.
36992 */
36993 stringToSign +=
36994 request.method + ' ' + request.path + ' HTTP/' +
36995 options.httpVersion;
36996 } else {
36997 /* Strict parsing doesn't allow older draft headers. */
36998 throw (new StrictParsingError('request-line is not a valid header ' +
36999 'with strict parsing enabled.'));
37000 }
37001 } else if (h === '(request-target)') {
37002 stringToSign +=
37003 '(request-target): ' + request.method.toLowerCase() + ' ' +
37004 request.path;
37005 } else {
37006 var value = request.getHeader(h);
37007 if (value === undefined || value === '') {
37008 throw new MissingHeaderError(h + ' was not in the request');
37009 }
37010 stringToSign += h + ': ' + value;
37011 }
37012
37013 if ((i + 1) < options.headers.length)
37014 stringToSign += '\n';
37015 }
37016
37017 /* This is just for unit tests. */
37018 if (request.hasOwnProperty('_stringToSign')) {
37019 request._stringToSign = stringToSign;
37020 }
37021
37022 var signature;
37023 if (alg[0] === 'hmac') {
37024 if (typeof (options.key) !== 'string' && !Buffer.isBuffer(options.key))
37025 throw (new TypeError('options.key must be a string or Buffer'));
37026
37027 var hmac = crypto.createHmac(alg[1].toUpperCase(), options.key);
37028 hmac.update(stringToSign);
37029 signature = hmac.digest('base64');
37030
37031 } else {
37032 var key = options.key;
37033 if (typeof (key) === 'string' || Buffer.isBuffer(key))
37034 key = sshpk.parsePrivateKey(options.key);
37035
37036 assert.ok(sshpk.PrivateKey.isPrivateKey(key, [1, 2]),
37037 'options.key must be a sshpk.PrivateKey');
37038
37039 if (!PK_ALGOS[key.type]) {
37040 throw (new InvalidAlgorithmError(key.type.toUpperCase() + ' type ' +
37041 'keys are not supported'));
37042 }
37043
37044 if (alg[0] !== undefined && key.type !== alg[0]) {
37045 throw (new InvalidAlgorithmError('options.key must be a ' +
37046 alg[0].toUpperCase() + ' key, was given a ' +
37047 key.type.toUpperCase() + ' key instead'));
37048 }
37049
37050 var signer = key.createSign(alg[1]);
37051 signer.update(stringToSign);
37052 var sigObj = signer.sign();
37053 if (!HASH_ALGOS[sigObj.hashAlgorithm]) {
37054 throw (new InvalidAlgorithmError(sigObj.hashAlgorithm.toUpperCase() +
37055 ' is not a supported hash algorithm'));
37056 }
37057 options.algorithm = key.type + '-' + sigObj.hashAlgorithm;
37058 signature = sigObj.toString();
37059 assert.notStrictEqual(signature, '', 'empty signature produced');
37060 }
37061
37062 var authzHeaderName = options.authorizationHeaderName || 'Authorization';
37063
37064 request.setHeader(authzHeaderName, sprintf(AUTHZ_FMT,
37065 options.keyId,
37066 options.algorithm,
37067 options.headers.join(' '),
37068 signature));
37069
37070 return true;
37071 }
37072
37073};
37074
37075}).call(this,{"isBuffer":require("../../is-buffer/index.js")})
37076},{"../../is-buffer/index.js":211,"./utils":206,"assert-plus":67,"crypto":126,"http":362,"jsprim":219,"sshpk":354,"util":397}],206:[function(require,module,exports){
37077// Copyright 2012 Joyent, Inc. All rights reserved.
37078
37079var assert = require('assert-plus');
37080var sshpk = require('sshpk');
37081var util = require('util');
37082
37083var HASH_ALGOS = {
37084 'sha1': true,
37085 'sha256': true,
37086 'sha512': true
37087};
37088
37089var PK_ALGOS = {
37090 'rsa': true,
37091 'dsa': true,
37092 'ecdsa': true
37093};
37094
37095function HttpSignatureError(message, caller) {
37096 if (Error.captureStackTrace)
37097 Error.captureStackTrace(this, caller || HttpSignatureError);
37098
37099 this.message = message;
37100 this.name = caller.name;
37101}
37102util.inherits(HttpSignatureError, Error);
37103
37104function InvalidAlgorithmError(message) {
37105 HttpSignatureError.call(this, message, InvalidAlgorithmError);
37106}
37107util.inherits(InvalidAlgorithmError, HttpSignatureError);
37108
37109function validateAlgorithm(algorithm) {
37110 var alg = algorithm.toLowerCase().split('-');
37111
37112 if (alg.length !== 2) {
37113 throw (new InvalidAlgorithmError(alg[0].toUpperCase() + ' is not a ' +
37114 'valid algorithm'));
37115 }
37116
37117 if (alg[0] !== 'hmac' && !PK_ALGOS[alg[0]]) {
37118 throw (new InvalidAlgorithmError(alg[0].toUpperCase() + ' type keys ' +
37119 'are not supported'));
37120 }
37121
37122 if (!HASH_ALGOS[alg[1]]) {
37123 throw (new InvalidAlgorithmError(alg[1].toUpperCase() + ' is not a ' +
37124 'supported hash algorithm'));
37125 }
37126
37127 return (alg);
37128}
37129
37130///--- API
37131
37132module.exports = {
37133
37134 HASH_ALGOS: HASH_ALGOS,
37135 PK_ALGOS: PK_ALGOS,
37136
37137 HttpSignatureError: HttpSignatureError,
37138 InvalidAlgorithmError: InvalidAlgorithmError,
37139
37140 validateAlgorithm: validateAlgorithm,
37141
37142 /**
37143 * Converts an OpenSSH public key (rsa only) to a PKCS#8 PEM file.
37144 *
37145 * The intent of this module is to interoperate with OpenSSL only,
37146 * specifically the node crypto module's `verify` method.
37147 *
37148 * @param {String} key an OpenSSH public key.
37149 * @return {String} PEM encoded form of the RSA public key.
37150 * @throws {TypeError} on bad input.
37151 * @throws {Error} on invalid ssh key formatted data.
37152 */
37153 sshKeyToPEM: function sshKeyToPEM(key) {
37154 assert.string(key, 'ssh_key');
37155
37156 var k = sshpk.parseKey(key, 'ssh');
37157 return (k.toString('pem'));
37158 },
37159
37160
37161 /**
37162 * Generates an OpenSSH fingerprint from an ssh public key.
37163 *
37164 * @param {String} key an OpenSSH public key.
37165 * @return {String} key fingerprint.
37166 * @throws {TypeError} on bad input.
37167 * @throws {Error} if what you passed doesn't look like an ssh public key.
37168 */
37169 fingerprint: function fingerprint(key) {
37170 assert.string(key, 'ssh_key');
37171
37172 var k = sshpk.parseKey(key, 'ssh');
37173 return (k.fingerprint('md5').toString('hex'));
37174 },
37175
37176 /**
37177 * Converts a PKGCS#8 PEM file to an OpenSSH public key (rsa)
37178 *
37179 * The reverse of the above function.
37180 */
37181 pemToRsaSSHKey: function pemToRsaSSHKey(pem, comment) {
37182 assert.equal('string', typeof (pem), 'typeof pem');
37183
37184 var k = sshpk.parseKey(pem, 'pem');
37185 k.comment = comment;
37186 return (k.toString('ssh'));
37187 }
37188};
37189
37190},{"assert-plus":67,"sshpk":354,"util":397}],207:[function(require,module,exports){
37191(function (Buffer){
37192// Copyright 2015 Joyent, Inc.
37193
37194var assert = require('assert-plus');
37195var crypto = require('crypto');
37196var sshpk = require('sshpk');
37197var utils = require('./utils');
37198
37199var HASH_ALGOS = utils.HASH_ALGOS;
37200var PK_ALGOS = utils.PK_ALGOS;
37201var InvalidAlgorithmError = utils.InvalidAlgorithmError;
37202var HttpSignatureError = utils.HttpSignatureError;
37203var validateAlgorithm = utils.validateAlgorithm;
37204
37205///--- Exported API
37206
37207module.exports = {
37208 /**
37209 * Verify RSA/DSA signature against public key. You are expected to pass in
37210 * an object that was returned from `parse()`.
37211 *
37212 * @param {Object} parsedSignature the object you got from `parse`.
37213 * @param {String} pubkey RSA/DSA private key PEM.
37214 * @return {Boolean} true if valid, false otherwise.
37215 * @throws {TypeError} if you pass in bad arguments.
37216 * @throws {InvalidAlgorithmError}
37217 */
37218 verifySignature: function verifySignature(parsedSignature, pubkey) {
37219 assert.object(parsedSignature, 'parsedSignature');
37220 if (typeof (pubkey) === 'string' || Buffer.isBuffer(pubkey))
37221 pubkey = sshpk.parseKey(pubkey);
37222 assert.ok(sshpk.Key.isKey(pubkey, [1, 1]), 'pubkey must be a sshpk.Key');
37223
37224 var alg = validateAlgorithm(parsedSignature.algorithm);
37225 if (alg[0] === 'hmac' || alg[0] !== pubkey.type)
37226 return (false);
37227
37228 var v = pubkey.createVerify(alg[1]);
37229 v.update(parsedSignature.signingString);
37230 return (v.verify(parsedSignature.params.signature, 'base64'));
37231 },
37232
37233 /**
37234 * Verify HMAC against shared secret. You are expected to pass in an object
37235 * that was returned from `parse()`.
37236 *
37237 * @param {Object} parsedSignature the object you got from `parse`.
37238 * @param {String} secret HMAC shared secret.
37239 * @return {Boolean} true if valid, false otherwise.
37240 * @throws {TypeError} if you pass in bad arguments.
37241 * @throws {InvalidAlgorithmError}
37242 */
37243 verifyHMAC: function verifyHMAC(parsedSignature, secret) {
37244 assert.object(parsedSignature, 'parsedHMAC');
37245 assert.string(secret, 'secret');
37246
37247 var alg = validateAlgorithm(parsedSignature.algorithm);
37248 if (alg[0] !== 'hmac')
37249 return (false);
37250
37251 var hashAlg = alg[1].toUpperCase();
37252
37253 var hmac = crypto.createHmac(hashAlg, secret);
37254 hmac.update(parsedSignature.signingString);
37255
37256 /*
37257 * Now double-hash to avoid leaking timing information - there's
37258 * no easy constant-time compare in JS, so we use this approach
37259 * instead. See for more info:
37260 * https://www.isecpartners.com/blog/2011/february/double-hmac-
37261 * verification.aspx
37262 */
37263 var h1 = crypto.createHmac(hashAlg, secret);
37264 h1.update(hmac.digest());
37265 h1 = h1.digest();
37266 var h2 = crypto.createHmac(hashAlg, secret);
37267 h2.update(new Buffer(parsedSignature.params.signature, 'base64'));
37268 h2 = h2.digest();
37269
37270 /* Node 0.8 returns strings from .digest(). */
37271 if (typeof (h1) === 'string')
37272 return (h1 === h2);
37273 /* And node 0.10 lacks the .equals() method on Buffers. */
37274 if (Buffer.isBuffer(h1) && !h1.equals)
37275 return (h1.toString('binary') === h2.toString('binary'));
37276
37277 return (h1.equals(h2));
37278 }
37279};
37280
37281}).call(this,require("buffer").Buffer)
37282},{"./utils":206,"assert-plus":67,"buffer":114,"crypto":126,"sshpk":354}],208:[function(require,module,exports){
37283var http = require('http')
37284var url = require('url')
37285
37286var https = module.exports
37287
37288for (var key in http) {
37289 if (http.hasOwnProperty(key)) https[key] = http[key]
37290}
37291
37292https.request = function (params, cb) {
37293 params = validateParams(params)
37294 return http.request.call(this, params, cb)
37295}
37296
37297https.get = function (params, cb) {
37298 params = validateParams(params)
37299 return http.get.call(this, params, cb)
37300}
37301
37302function validateParams (params) {
37303 if (typeof params === 'string') {
37304 params = url.parse(params)
37305 }
37306 if (!params.protocol) {
37307 params.protocol = 'https:'
37308 }
37309 if (params.protocol !== 'https:') {
37310 throw new Error('Protocol "' + params.protocol + '" not supported. Expected "https:"')
37311 }
37312 return params
37313}
37314
37315},{"http":362,"url":393}],209:[function(require,module,exports){
37316exports.read = function (buffer, offset, isLE, mLen, nBytes) {
37317 var e, m
37318 var eLen = (nBytes * 8) - mLen - 1
37319 var eMax = (1 << eLen) - 1
37320 var eBias = eMax >> 1
37321 var nBits = -7
37322 var i = isLE ? (nBytes - 1) : 0
37323 var d = isLE ? -1 : 1
37324 var s = buffer[offset + i]
37325
37326 i += d
37327
37328 e = s & ((1 << (-nBits)) - 1)
37329 s >>= (-nBits)
37330 nBits += eLen
37331 for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {}
37332
37333 m = e & ((1 << (-nBits)) - 1)
37334 e >>= (-nBits)
37335 nBits += mLen
37336 for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {}
37337
37338 if (e === 0) {
37339 e = 1 - eBias
37340 } else if (e === eMax) {
37341 return m ? NaN : ((s ? -1 : 1) * Infinity)
37342 } else {
37343 m = m + Math.pow(2, mLen)
37344 e = e - eBias
37345 }
37346 return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
37347}
37348
37349exports.write = function (buffer, value, offset, isLE, mLen, nBytes) {
37350 var e, m, c
37351 var eLen = (nBytes * 8) - mLen - 1
37352 var eMax = (1 << eLen) - 1
37353 var eBias = eMax >> 1
37354 var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)
37355 var i = isLE ? 0 : (nBytes - 1)
37356 var d = isLE ? 1 : -1
37357 var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0
37358
37359 value = Math.abs(value)
37360
37361 if (isNaN(value) || value === Infinity) {
37362 m = isNaN(value) ? 1 : 0
37363 e = eMax
37364 } else {
37365 e = Math.floor(Math.log(value) / Math.LN2)
37366 if (value * (c = Math.pow(2, -e)) < 1) {
37367 e--
37368 c *= 2
37369 }
37370 if (e + eBias >= 1) {
37371 value += rt / c
37372 } else {
37373 value += rt * Math.pow(2, 1 - eBias)
37374 }
37375 if (value * c >= 2) {
37376 e++
37377 c /= 2
37378 }
37379
37380 if (e + eBias >= eMax) {
37381 m = 0
37382 e = eMax
37383 } else if (e + eBias >= 1) {
37384 m = ((value * c) - 1) * Math.pow(2, mLen)
37385 e = e + eBias
37386 } else {
37387 m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)
37388 e = 0
37389 }
37390 }
37391
37392 for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
37393
37394 e = (e << mLen) | m
37395 eLen += mLen
37396 for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
37397
37398 buffer[offset + i - d] |= s * 128
37399}
37400
37401},{}],210:[function(require,module,exports){
37402arguments[4][69][0].apply(exports,arguments)
37403},{"dup":69}],211:[function(require,module,exports){
37404/*!
37405 * Determine if an object is a Buffer
37406 *
37407 * @author Feross Aboukhadijeh <https://feross.org>
37408 * @license MIT
37409 */
37410
37411// The _isBuffer check is for Safari 5-7 support, because it's missing
37412// Object.prototype.constructor. Remove this eventually
37413module.exports = function (obj) {
37414 return obj != null && (isBuffer(obj) || isSlowBuffer(obj) || !!obj._isBuffer)
37415}
37416
37417function isBuffer (obj) {
37418 return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj)
37419}
37420
37421// For Node v0.10 support. Remove this eventually.
37422function isSlowBuffer (obj) {
37423 return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isBuffer(obj.slice(0, 0))
37424}
37425
37426},{}],212:[function(require,module,exports){
37427module.exports = isTypedArray
37428isTypedArray.strict = isStrictTypedArray
37429isTypedArray.loose = isLooseTypedArray
37430
37431var toString = Object.prototype.toString
37432var names = {
37433 '[object Int8Array]': true
37434 , '[object Int16Array]': true
37435 , '[object Int32Array]': true
37436 , '[object Uint8Array]': true
37437 , '[object Uint8ClampedArray]': true
37438 , '[object Uint16Array]': true
37439 , '[object Uint32Array]': true
37440 , '[object Float32Array]': true
37441 , '[object Float64Array]': true
37442}
37443
37444function isTypedArray(arr) {
37445 return (
37446 isStrictTypedArray(arr)
37447 || isLooseTypedArray(arr)
37448 )
37449}
37450
37451function isStrictTypedArray(arr) {
37452 return (
37453 arr instanceof Int8Array
37454 || arr instanceof Int16Array
37455 || arr instanceof Int32Array
37456 || arr instanceof Uint8Array
37457 || arr instanceof Uint8ClampedArray
37458 || arr instanceof Uint16Array
37459 || arr instanceof Uint32Array
37460 || arr instanceof Float32Array
37461 || arr instanceof Float64Array
37462 )
37463}
37464
37465function isLooseTypedArray(arr) {
37466 return names[toString.call(arr)]
37467}
37468
37469},{}],213:[function(require,module,exports){
37470var toString = {}.toString;
37471
37472module.exports = Array.isArray || function (arr) {
37473 return toString.call(arr) == '[object Array]';
37474};
37475
37476},{}],214:[function(require,module,exports){
37477var stream = require('stream')
37478
37479
37480function isStream (obj) {
37481 return obj instanceof stream.Stream
37482}
37483
37484
37485function isReadable (obj) {
37486 return isStream(obj) && typeof obj._read == 'function' && typeof obj._readableState == 'object'
37487}
37488
37489
37490function isWritable (obj) {
37491 return isStream(obj) && typeof obj._write == 'function' && typeof obj._writableState == 'object'
37492}
37493
37494
37495function isDuplex (obj) {
37496 return isReadable(obj) && isWritable(obj)
37497}
37498
37499
37500module.exports = isStream
37501module.exports.isReadable = isReadable
37502module.exports.isWritable = isWritable
37503module.exports.isDuplex = isDuplex
37504
37505},{"stream":361}],215:[function(require,module,exports){
37506(function(){
37507
37508 // Copyright (c) 2005 Tom Wu
37509 // All Rights Reserved.
37510 // See "LICENSE" for details.
37511
37512 // Basic JavaScript BN library - subset useful for RSA encryption.
37513
37514 // Bits per digit
37515 var dbits;
37516
37517 // JavaScript engine analysis
37518 var canary = 0xdeadbeefcafe;
37519 var j_lm = ((canary&0xffffff)==0xefcafe);
37520
37521 // (public) Constructor
37522 function BigInteger(a,b,c) {
37523 if(a != null)
37524 if("number" == typeof a) this.fromNumber(a,b,c);
37525 else if(b == null && "string" != typeof a) this.fromString(a,256);
37526 else this.fromString(a,b);
37527 }
37528
37529 // return new, unset BigInteger
37530 function nbi() { return new BigInteger(null); }
37531
37532 // am: Compute w_j += (x*this_i), propagate carries,
37533 // c is initial carry, returns final carry.
37534 // c < 3*dvalue, x < 2*dvalue, this_i < dvalue
37535 // We need to select the fastest one that works in this environment.
37536
37537 // am1: use a single mult and divide to get the high bits,
37538 // max digit bits should be 26 because
37539 // max internal value = 2*dvalue^2-2*dvalue (< 2^53)
37540 function am1(i,x,w,j,c,n) {
37541 while(--n >= 0) {
37542 var v = x*this[i++]+w[j]+c;
37543 c = Math.floor(v/0x4000000);
37544 w[j++] = v&0x3ffffff;
37545 }
37546 return c;
37547 }
37548 // am2 avoids a big mult-and-extract completely.
37549 // Max digit bits should be <= 30 because we do bitwise ops
37550 // on values up to 2*hdvalue^2-hdvalue-1 (< 2^31)
37551 function am2(i,x,w,j,c,n) {
37552 var xl = x&0x7fff, xh = x>>15;
37553 while(--n >= 0) {
37554 var l = this[i]&0x7fff;
37555 var h = this[i++]>>15;
37556 var m = xh*l+h*xl;
37557 l = xl*l+((m&0x7fff)<<15)+w[j]+(c&0x3fffffff);
37558 c = (l>>>30)+(m>>>15)+xh*h+(c>>>30);
37559 w[j++] = l&0x3fffffff;
37560 }
37561 return c;
37562 }
37563 // Alternately, set max digit bits to 28 since some
37564 // browsers slow down when dealing with 32-bit numbers.
37565 function am3(i,x,w,j,c,n) {
37566 var xl = x&0x3fff, xh = x>>14;
37567 while(--n >= 0) {
37568 var l = this[i]&0x3fff;
37569 var h = this[i++]>>14;
37570 var m = xh*l+h*xl;
37571 l = xl*l+((m&0x3fff)<<14)+w[j]+c;
37572 c = (l>>28)+(m>>14)+xh*h;
37573 w[j++] = l&0xfffffff;
37574 }
37575 return c;
37576 }
37577 var inBrowser = typeof navigator !== "undefined";
37578 if(inBrowser && j_lm && (navigator.appName == "Microsoft Internet Explorer")) {
37579 BigInteger.prototype.am = am2;
37580 dbits = 30;
37581 }
37582 else if(inBrowser && j_lm && (navigator.appName != "Netscape")) {
37583 BigInteger.prototype.am = am1;
37584 dbits = 26;
37585 }
37586 else { // Mozilla/Netscape seems to prefer am3
37587 BigInteger.prototype.am = am3;
37588 dbits = 28;
37589 }
37590
37591 BigInteger.prototype.DB = dbits;
37592 BigInteger.prototype.DM = ((1<<dbits)-1);
37593 BigInteger.prototype.DV = (1<<dbits);
37594
37595 var BI_FP = 52;
37596 BigInteger.prototype.FV = Math.pow(2,BI_FP);
37597 BigInteger.prototype.F1 = BI_FP-dbits;
37598 BigInteger.prototype.F2 = 2*dbits-BI_FP;
37599
37600 // Digit conversions
37601 var BI_RM = "0123456789abcdefghijklmnopqrstuvwxyz";
37602 var BI_RC = new Array();
37603 var rr,vv;
37604 rr = "0".charCodeAt(0);
37605 for(vv = 0; vv <= 9; ++vv) BI_RC[rr++] = vv;
37606 rr = "a".charCodeAt(0);
37607 for(vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv;
37608 rr = "A".charCodeAt(0);
37609 for(vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv;
37610
37611 function int2char(n) { return BI_RM.charAt(n); }
37612 function intAt(s,i) {
37613 var c = BI_RC[s.charCodeAt(i)];
37614 return (c==null)?-1:c;
37615 }
37616
37617 // (protected) copy this to r
37618 function bnpCopyTo(r) {
37619 for(var i = this.t-1; i >= 0; --i) r[i] = this[i];
37620 r.t = this.t;
37621 r.s = this.s;
37622 }
37623
37624 // (protected) set from integer value x, -DV <= x < DV
37625 function bnpFromInt(x) {
37626 this.t = 1;
37627 this.s = (x<0)?-1:0;
37628 if(x > 0) this[0] = x;
37629 else if(x < -1) this[0] = x+this.DV;
37630 else this.t = 0;
37631 }
37632
37633 // return bigint initialized to value
37634 function nbv(i) { var r = nbi(); r.fromInt(i); return r; }
37635
37636 // (protected) set from string and radix
37637 function bnpFromString(s,b) {
37638 var k;
37639 if(b == 16) k = 4;
37640 else if(b == 8) k = 3;
37641 else if(b == 256) k = 8; // byte array
37642 else if(b == 2) k = 1;
37643 else if(b == 32) k = 5;
37644 else if(b == 4) k = 2;
37645 else { this.fromRadix(s,b); return; }
37646 this.t = 0;
37647 this.s = 0;
37648 var i = s.length, mi = false, sh = 0;
37649 while(--i >= 0) {
37650 var x = (k==8)?s[i]&0xff:intAt(s,i);
37651 if(x < 0) {
37652 if(s.charAt(i) == "-") mi = true;
37653 continue;
37654 }
37655 mi = false;
37656 if(sh == 0)
37657 this[this.t++] = x;
37658 else if(sh+k > this.DB) {
37659 this[this.t-1] |= (x&((1<<(this.DB-sh))-1))<<sh;
37660 this[this.t++] = (x>>(this.DB-sh));
37661 }
37662 else
37663 this[this.t-1] |= x<<sh;
37664 sh += k;
37665 if(sh >= this.DB) sh -= this.DB;
37666 }
37667 if(k == 8 && (s[0]&0x80) != 0) {
37668 this.s = -1;
37669 if(sh > 0) this[this.t-1] |= ((1<<(this.DB-sh))-1)<<sh;
37670 }
37671 this.clamp();
37672 if(mi) BigInteger.ZERO.subTo(this,this);
37673 }
37674
37675 // (protected) clamp off excess high words
37676 function bnpClamp() {
37677 var c = this.s&this.DM;
37678 while(this.t > 0 && this[this.t-1] == c) --this.t;
37679 }
37680
37681 // (public) return string representation in given radix
37682 function bnToString(b) {
37683 if(this.s < 0) return "-"+this.negate().toString(b);
37684 var k;
37685 if(b == 16) k = 4;
37686 else if(b == 8) k = 3;
37687 else if(b == 2) k = 1;
37688 else if(b == 32) k = 5;
37689 else if(b == 4) k = 2;
37690 else return this.toRadix(b);
37691 var km = (1<<k)-1, d, m = false, r = "", i = this.t;
37692 var p = this.DB-(i*this.DB)%k;
37693 if(i-- > 0) {
37694 if(p < this.DB && (d = this[i]>>p) > 0) { m = true; r = int2char(d); }
37695 while(i >= 0) {
37696 if(p < k) {
37697 d = (this[i]&((1<<p)-1))<<(k-p);
37698 d |= this[--i]>>(p+=this.DB-k);
37699 }
37700 else {
37701 d = (this[i]>>(p-=k))&km;
37702 if(p <= 0) { p += this.DB; --i; }
37703 }
37704 if(d > 0) m = true;
37705 if(m) r += int2char(d);
37706 }
37707 }
37708 return m?r:"0";
37709 }
37710
37711 // (public) -this
37712 function bnNegate() { var r = nbi(); BigInteger.ZERO.subTo(this,r); return r; }
37713
37714 // (public) |this|
37715 function bnAbs() { return (this.s<0)?this.negate():this; }
37716
37717 // (public) return + if this > a, - if this < a, 0 if equal
37718 function bnCompareTo(a) {
37719 var r = this.s-a.s;
37720 if(r != 0) return r;
37721 var i = this.t;
37722 r = i-a.t;
37723 if(r != 0) return (this.s<0)?-r:r;
37724 while(--i >= 0) if((r=this[i]-a[i]) != 0) return r;
37725 return 0;
37726 }
37727
37728 // returns bit length of the integer x
37729 function nbits(x) {
37730 var r = 1, t;
37731 if((t=x>>>16) != 0) { x = t; r += 16; }
37732 if((t=x>>8) != 0) { x = t; r += 8; }
37733 if((t=x>>4) != 0) { x = t; r += 4; }
37734 if((t=x>>2) != 0) { x = t; r += 2; }
37735 if((t=x>>1) != 0) { x = t; r += 1; }
37736 return r;
37737 }
37738
37739 // (public) return the number of bits in "this"
37740 function bnBitLength() {
37741 if(this.t <= 0) return 0;
37742 return this.DB*(this.t-1)+nbits(this[this.t-1]^(this.s&this.DM));
37743 }
37744
37745 // (protected) r = this << n*DB
37746 function bnpDLShiftTo(n,r) {
37747 var i;
37748 for(i = this.t-1; i >= 0; --i) r[i+n] = this[i];
37749 for(i = n-1; i >= 0; --i) r[i] = 0;
37750 r.t = this.t+n;
37751 r.s = this.s;
37752 }
37753
37754 // (protected) r = this >> n*DB
37755 function bnpDRShiftTo(n,r) {
37756 for(var i = n; i < this.t; ++i) r[i-n] = this[i];
37757 r.t = Math.max(this.t-n,0);
37758 r.s = this.s;
37759 }
37760
37761 // (protected) r = this << n
37762 function bnpLShiftTo(n,r) {
37763 var bs = n%this.DB;
37764 var cbs = this.DB-bs;
37765 var bm = (1<<cbs)-1;
37766 var ds = Math.floor(n/this.DB), c = (this.s<<bs)&this.DM, i;
37767 for(i = this.t-1; i >= 0; --i) {
37768 r[i+ds+1] = (this[i]>>cbs)|c;
37769 c = (this[i]&bm)<<bs;
37770 }
37771 for(i = ds-1; i >= 0; --i) r[i] = 0;
37772 r[ds] = c;
37773 r.t = this.t+ds+1;
37774 r.s = this.s;
37775 r.clamp();
37776 }
37777
37778 // (protected) r = this >> n
37779 function bnpRShiftTo(n,r) {
37780 r.s = this.s;
37781 var ds = Math.floor(n/this.DB);
37782 if(ds >= this.t) { r.t = 0; return; }
37783 var bs = n%this.DB;
37784 var cbs = this.DB-bs;
37785 var bm = (1<<bs)-1;
37786 r[0] = this[ds]>>bs;
37787 for(var i = ds+1; i < this.t; ++i) {
37788 r[i-ds-1] |= (this[i]&bm)<<cbs;
37789 r[i-ds] = this[i]>>bs;
37790 }
37791 if(bs > 0) r[this.t-ds-1] |= (this.s&bm)<<cbs;
37792 r.t = this.t-ds;
37793 r.clamp();
37794 }
37795
37796 // (protected) r = this - a
37797 function bnpSubTo(a,r) {
37798 var i = 0, c = 0, m = Math.min(a.t,this.t);
37799 while(i < m) {
37800 c += this[i]-a[i];
37801 r[i++] = c&this.DM;
37802 c >>= this.DB;
37803 }
37804 if(a.t < this.t) {
37805 c -= a.s;
37806 while(i < this.t) {
37807 c += this[i];
37808 r[i++] = c&this.DM;
37809 c >>= this.DB;
37810 }
37811 c += this.s;
37812 }
37813 else {
37814 c += this.s;
37815 while(i < a.t) {
37816 c -= a[i];
37817 r[i++] = c&this.DM;
37818 c >>= this.DB;
37819 }
37820 c -= a.s;
37821 }
37822 r.s = (c<0)?-1:0;
37823 if(c < -1) r[i++] = this.DV+c;
37824 else if(c > 0) r[i++] = c;
37825 r.t = i;
37826 r.clamp();
37827 }
37828
37829 // (protected) r = this * a, r != this,a (HAC 14.12)
37830 // "this" should be the larger one if appropriate.
37831 function bnpMultiplyTo(a,r) {
37832 var x = this.abs(), y = a.abs();
37833 var i = x.t;
37834 r.t = i+y.t;
37835 while(--i >= 0) r[i] = 0;
37836 for(i = 0; i < y.t; ++i) r[i+x.t] = x.am(0,y[i],r,i,0,x.t);
37837 r.s = 0;
37838 r.clamp();
37839 if(this.s != a.s) BigInteger.ZERO.subTo(r,r);
37840 }
37841
37842 // (protected) r = this^2, r != this (HAC 14.16)
37843 function bnpSquareTo(r) {
37844 var x = this.abs();
37845 var i = r.t = 2*x.t;
37846 while(--i >= 0) r[i] = 0;
37847 for(i = 0; i < x.t-1; ++i) {
37848 var c = x.am(i,x[i],r,2*i,0,1);
37849 if((r[i+x.t]+=x.am(i+1,2*x[i],r,2*i+1,c,x.t-i-1)) >= x.DV) {
37850 r[i+x.t] -= x.DV;
37851 r[i+x.t+1] = 1;
37852 }
37853 }
37854 if(r.t > 0) r[r.t-1] += x.am(i,x[i],r,2*i,0,1);
37855 r.s = 0;
37856 r.clamp();
37857 }
37858
37859 // (protected) divide this by m, quotient and remainder to q, r (HAC 14.20)
37860 // r != q, this != m. q or r may be null.
37861 function bnpDivRemTo(m,q,r) {
37862 var pm = m.abs();
37863 if(pm.t <= 0) return;
37864 var pt = this.abs();
37865 if(pt.t < pm.t) {
37866 if(q != null) q.fromInt(0);
37867 if(r != null) this.copyTo(r);
37868 return;
37869 }
37870 if(r == null) r = nbi();
37871 var y = nbi(), ts = this.s, ms = m.s;
37872 var nsh = this.DB-nbits(pm[pm.t-1]); // normalize modulus
37873 if(nsh > 0) { pm.lShiftTo(nsh,y); pt.lShiftTo(nsh,r); }
37874 else { pm.copyTo(y); pt.copyTo(r); }
37875 var ys = y.t;
37876 var y0 = y[ys-1];
37877 if(y0 == 0) return;
37878 var yt = y0*(1<<this.F1)+((ys>1)?y[ys-2]>>this.F2:0);
37879 var d1 = this.FV/yt, d2 = (1<<this.F1)/yt, e = 1<<this.F2;
37880 var i = r.t, j = i-ys, t = (q==null)?nbi():q;
37881 y.dlShiftTo(j,t);
37882 if(r.compareTo(t) >= 0) {
37883 r[r.t++] = 1;
37884 r.subTo(t,r);
37885 }
37886 BigInteger.ONE.dlShiftTo(ys,t);
37887 t.subTo(y,y); // "negative" y so we can replace sub with am later
37888 while(y.t < ys) y[y.t++] = 0;
37889 while(--j >= 0) {
37890 // Estimate quotient digit
37891 var qd = (r[--i]==y0)?this.DM:Math.floor(r[i]*d1+(r[i-1]+e)*d2);
37892 if((r[i]+=y.am(0,qd,r,j,0,ys)) < qd) { // Try it out
37893 y.dlShiftTo(j,t);
37894 r.subTo(t,r);
37895 while(r[i] < --qd) r.subTo(t,r);
37896 }
37897 }
37898 if(q != null) {
37899 r.drShiftTo(ys,q);
37900 if(ts != ms) BigInteger.ZERO.subTo(q,q);
37901 }
37902 r.t = ys;
37903 r.clamp();
37904 if(nsh > 0) r.rShiftTo(nsh,r); // Denormalize remainder
37905 if(ts < 0) BigInteger.ZERO.subTo(r,r);
37906 }
37907
37908 // (public) this mod a
37909 function bnMod(a) {
37910 var r = nbi();
37911 this.abs().divRemTo(a,null,r);
37912 if(this.s < 0 && r.compareTo(BigInteger.ZERO) > 0) a.subTo(r,r);
37913 return r;
37914 }
37915
37916 // Modular reduction using "classic" algorithm
37917 function Classic(m) { this.m = m; }
37918 function cConvert(x) {
37919 if(x.s < 0 || x.compareTo(this.m) >= 0) return x.mod(this.m);
37920 else return x;
37921 }
37922 function cRevert(x) { return x; }
37923 function cReduce(x) { x.divRemTo(this.m,null,x); }
37924 function cMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); }
37925 function cSqrTo(x,r) { x.squareTo(r); this.reduce(r); }
37926
37927 Classic.prototype.convert = cConvert;
37928 Classic.prototype.revert = cRevert;
37929 Classic.prototype.reduce = cReduce;
37930 Classic.prototype.mulTo = cMulTo;
37931 Classic.prototype.sqrTo = cSqrTo;
37932
37933 // (protected) return "-1/this % 2^DB"; useful for Mont. reduction
37934 // justification:
37935 // xy == 1 (mod m)
37936 // xy = 1+km
37937 // xy(2-xy) = (1+km)(1-km)
37938 // x[y(2-xy)] = 1-k^2m^2
37939 // x[y(2-xy)] == 1 (mod m^2)
37940 // if y is 1/x mod m, then y(2-xy) is 1/x mod m^2
37941 // should reduce x and y(2-xy) by m^2 at each step to keep size bounded.
37942 // JS multiply "overflows" differently from C/C++, so care is needed here.
37943 function bnpInvDigit() {
37944 if(this.t < 1) return 0;
37945 var x = this[0];
37946 if((x&1) == 0) return 0;
37947 var y = x&3; // y == 1/x mod 2^2
37948 y = (y*(2-(x&0xf)*y))&0xf; // y == 1/x mod 2^4
37949 y = (y*(2-(x&0xff)*y))&0xff; // y == 1/x mod 2^8
37950 y = (y*(2-(((x&0xffff)*y)&0xffff)))&0xffff; // y == 1/x mod 2^16
37951 // last step - calculate inverse mod DV directly;
37952 // assumes 16 < DB <= 32 and assumes ability to handle 48-bit ints
37953 y = (y*(2-x*y%this.DV))%this.DV; // y == 1/x mod 2^dbits
37954 // we really want the negative inverse, and -DV < y < DV
37955 return (y>0)?this.DV-y:-y;
37956 }
37957
37958 // Montgomery reduction
37959 function Montgomery(m) {
37960 this.m = m;
37961 this.mp = m.invDigit();
37962 this.mpl = this.mp&0x7fff;
37963 this.mph = this.mp>>15;
37964 this.um = (1<<(m.DB-15))-1;
37965 this.mt2 = 2*m.t;
37966 }
37967
37968 // xR mod m
37969 function montConvert(x) {
37970 var r = nbi();
37971 x.abs().dlShiftTo(this.m.t,r);
37972 r.divRemTo(this.m,null,r);
37973 if(x.s < 0 && r.compareTo(BigInteger.ZERO) > 0) this.m.subTo(r,r);
37974 return r;
37975 }
37976
37977 // x/R mod m
37978 function montRevert(x) {
37979 var r = nbi();
37980 x.copyTo(r);
37981 this.reduce(r);
37982 return r;
37983 }
37984
37985 // x = x/R mod m (HAC 14.32)
37986 function montReduce(x) {
37987 while(x.t <= this.mt2) // pad x so am has enough room later
37988 x[x.t++] = 0;
37989 for(var i = 0; i < this.m.t; ++i) {
37990 // faster way of calculating u0 = x[i]*mp mod DV
37991 var j = x[i]&0x7fff;
37992 var u0 = (j*this.mpl+(((j*this.mph+(x[i]>>15)*this.mpl)&this.um)<<15))&x.DM;
37993 // use am to combine the multiply-shift-add into one call
37994 j = i+this.m.t;
37995 x[j] += this.m.am(0,u0,x,i,0,this.m.t);
37996 // propagate carry
37997 while(x[j] >= x.DV) { x[j] -= x.DV; x[++j]++; }
37998 }
37999 x.clamp();
38000 x.drShiftTo(this.m.t,x);
38001 if(x.compareTo(this.m) >= 0) x.subTo(this.m,x);
38002 }
38003
38004 // r = "x^2/R mod m"; x != r
38005 function montSqrTo(x,r) { x.squareTo(r); this.reduce(r); }
38006
38007 // r = "xy/R mod m"; x,y != r
38008 function montMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); }
38009
38010 Montgomery.prototype.convert = montConvert;
38011 Montgomery.prototype.revert = montRevert;
38012 Montgomery.prototype.reduce = montReduce;
38013 Montgomery.prototype.mulTo = montMulTo;
38014 Montgomery.prototype.sqrTo = montSqrTo;
38015
38016 // (protected) true iff this is even
38017 function bnpIsEven() { return ((this.t>0)?(this[0]&1):this.s) == 0; }
38018
38019 // (protected) this^e, e < 2^32, doing sqr and mul with "r" (HAC 14.79)
38020 function bnpExp(e,z) {
38021 if(e > 0xffffffff || e < 1) return BigInteger.ONE;
38022 var r = nbi(), r2 = nbi(), g = z.convert(this), i = nbits(e)-1;
38023 g.copyTo(r);
38024 while(--i >= 0) {
38025 z.sqrTo(r,r2);
38026 if((e&(1<<i)) > 0) z.mulTo(r2,g,r);
38027 else { var t = r; r = r2; r2 = t; }
38028 }
38029 return z.revert(r);
38030 }
38031
38032 // (public) this^e % m, 0 <= e < 2^32
38033 function bnModPowInt(e,m) {
38034 var z;
38035 if(e < 256 || m.isEven()) z = new Classic(m); else z = new Montgomery(m);
38036 return this.exp(e,z);
38037 }
38038
38039 // protected
38040 BigInteger.prototype.copyTo = bnpCopyTo;
38041 BigInteger.prototype.fromInt = bnpFromInt;
38042 BigInteger.prototype.fromString = bnpFromString;
38043 BigInteger.prototype.clamp = bnpClamp;
38044 BigInteger.prototype.dlShiftTo = bnpDLShiftTo;
38045 BigInteger.prototype.drShiftTo = bnpDRShiftTo;
38046 BigInteger.prototype.lShiftTo = bnpLShiftTo;
38047 BigInteger.prototype.rShiftTo = bnpRShiftTo;
38048 BigInteger.prototype.subTo = bnpSubTo;
38049 BigInteger.prototype.multiplyTo = bnpMultiplyTo;
38050 BigInteger.prototype.squareTo = bnpSquareTo;
38051 BigInteger.prototype.divRemTo = bnpDivRemTo;
38052 BigInteger.prototype.invDigit = bnpInvDigit;
38053 BigInteger.prototype.isEven = bnpIsEven;
38054 BigInteger.prototype.exp = bnpExp;
38055
38056 // public
38057 BigInteger.prototype.toString = bnToString;
38058 BigInteger.prototype.negate = bnNegate;
38059 BigInteger.prototype.abs = bnAbs;
38060 BigInteger.prototype.compareTo = bnCompareTo;
38061 BigInteger.prototype.bitLength = bnBitLength;
38062 BigInteger.prototype.mod = bnMod;
38063 BigInteger.prototype.modPowInt = bnModPowInt;
38064
38065 // "constants"
38066 BigInteger.ZERO = nbv(0);
38067 BigInteger.ONE = nbv(1);
38068
38069 // Copyright (c) 2005-2009 Tom Wu
38070 // All Rights Reserved.
38071 // See "LICENSE" for details.
38072
38073 // Extended JavaScript BN functions, required for RSA private ops.
38074
38075 // Version 1.1: new BigInteger("0", 10) returns "proper" zero
38076 // Version 1.2: square() API, isProbablePrime fix
38077
38078 // (public)
38079 function bnClone() { var r = nbi(); this.copyTo(r); return r; }
38080
38081 // (public) return value as integer
38082 function bnIntValue() {
38083 if(this.s < 0) {
38084 if(this.t == 1) return this[0]-this.DV;
38085 else if(this.t == 0) return -1;
38086 }
38087 else if(this.t == 1) return this[0];
38088 else if(this.t == 0) return 0;
38089 // assumes 16 < DB < 32
38090 return ((this[1]&((1<<(32-this.DB))-1))<<this.DB)|this[0];
38091 }
38092
38093 // (public) return value as byte
38094 function bnByteValue() { return (this.t==0)?this.s:(this[0]<<24)>>24; }
38095
38096 // (public) return value as short (assumes DB>=16)
38097 function bnShortValue() { return (this.t==0)?this.s:(this[0]<<16)>>16; }
38098
38099 // (protected) return x s.t. r^x < DV
38100 function bnpChunkSize(r) { return Math.floor(Math.LN2*this.DB/Math.log(r)); }
38101
38102 // (public) 0 if this == 0, 1 if this > 0
38103 function bnSigNum() {
38104 if(this.s < 0) return -1;
38105 else if(this.t <= 0 || (this.t == 1 && this[0] <= 0)) return 0;
38106 else return 1;
38107 }
38108
38109 // (protected) convert to radix string
38110 function bnpToRadix(b) {
38111 if(b == null) b = 10;
38112 if(this.signum() == 0 || b < 2 || b > 36) return "0";
38113 var cs = this.chunkSize(b);
38114 var a = Math.pow(b,cs);
38115 var d = nbv(a), y = nbi(), z = nbi(), r = "";
38116 this.divRemTo(d,y,z);
38117 while(y.signum() > 0) {
38118 r = (a+z.intValue()).toString(b).substr(1) + r;
38119 y.divRemTo(d,y,z);
38120 }
38121 return z.intValue().toString(b) + r;
38122 }
38123
38124 // (protected) convert from radix string
38125 function bnpFromRadix(s,b) {
38126 this.fromInt(0);
38127 if(b == null) b = 10;
38128 var cs = this.chunkSize(b);
38129 var d = Math.pow(b,cs), mi = false, j = 0, w = 0;
38130 for(var i = 0; i < s.length; ++i) {
38131 var x = intAt(s,i);
38132 if(x < 0) {
38133 if(s.charAt(i) == "-" && this.signum() == 0) mi = true;
38134 continue;
38135 }
38136 w = b*w+x;
38137 if(++j >= cs) {
38138 this.dMultiply(d);
38139 this.dAddOffset(w,0);
38140 j = 0;
38141 w = 0;
38142 }
38143 }
38144 if(j > 0) {
38145 this.dMultiply(Math.pow(b,j));
38146 this.dAddOffset(w,0);
38147 }
38148 if(mi) BigInteger.ZERO.subTo(this,this);
38149 }
38150
38151 // (protected) alternate constructor
38152 function bnpFromNumber(a,b,c) {
38153 if("number" == typeof b) {
38154 // new BigInteger(int,int,RNG)
38155 if(a < 2) this.fromInt(1);
38156 else {
38157 this.fromNumber(a,c);
38158 if(!this.testBit(a-1)) // force MSB set
38159 this.bitwiseTo(BigInteger.ONE.shiftLeft(a-1),op_or,this);
38160 if(this.isEven()) this.dAddOffset(1,0); // force odd
38161 while(!this.isProbablePrime(b)) {
38162 this.dAddOffset(2,0);
38163 if(this.bitLength() > a) this.subTo(BigInteger.ONE.shiftLeft(a-1),this);
38164 }
38165 }
38166 }
38167 else {
38168 // new BigInteger(int,RNG)
38169 var x = new Array(), t = a&7;
38170 x.length = (a>>3)+1;
38171 b.nextBytes(x);
38172 if(t > 0) x[0] &= ((1<<t)-1); else x[0] = 0;
38173 this.fromString(x,256);
38174 }
38175 }
38176
38177 // (public) convert to bigendian byte array
38178 function bnToByteArray() {
38179 var i = this.t, r = new Array();
38180 r[0] = this.s;
38181 var p = this.DB-(i*this.DB)%8, d, k = 0;
38182 if(i-- > 0) {
38183 if(p < this.DB && (d = this[i]>>p) != (this.s&this.DM)>>p)
38184 r[k++] = d|(this.s<<(this.DB-p));
38185 while(i >= 0) {
38186 if(p < 8) {
38187 d = (this[i]&((1<<p)-1))<<(8-p);
38188 d |= this[--i]>>(p+=this.DB-8);
38189 }
38190 else {
38191 d = (this[i]>>(p-=8))&0xff;
38192 if(p <= 0) { p += this.DB; --i; }
38193 }
38194 if((d&0x80) != 0) d |= -256;
38195 if(k == 0 && (this.s&0x80) != (d&0x80)) ++k;
38196 if(k > 0 || d != this.s) r[k++] = d;
38197 }
38198 }
38199 return r;
38200 }
38201
38202 function bnEquals(a) { return(this.compareTo(a)==0); }
38203 function bnMin(a) { return(this.compareTo(a)<0)?this:a; }
38204 function bnMax(a) { return(this.compareTo(a)>0)?this:a; }
38205
38206 // (protected) r = this op a (bitwise)
38207 function bnpBitwiseTo(a,op,r) {
38208 var i, f, m = Math.min(a.t,this.t);
38209 for(i = 0; i < m; ++i) r[i] = op(this[i],a[i]);
38210 if(a.t < this.t) {
38211 f = a.s&this.DM;
38212 for(i = m; i < this.t; ++i) r[i] = op(this[i],f);
38213 r.t = this.t;
38214 }
38215 else {
38216 f = this.s&this.DM;
38217 for(i = m; i < a.t; ++i) r[i] = op(f,a[i]);
38218 r.t = a.t;
38219 }
38220 r.s = op(this.s,a.s);
38221 r.clamp();
38222 }
38223
38224 // (public) this & a
38225 function op_and(x,y) { return x&y; }
38226 function bnAnd(a) { var r = nbi(); this.bitwiseTo(a,op_and,r); return r; }
38227
38228 // (public) this | a
38229 function op_or(x,y) { return x|y; }
38230 function bnOr(a) { var r = nbi(); this.bitwiseTo(a,op_or,r); return r; }
38231
38232 // (public) this ^ a
38233 function op_xor(x,y) { return x^y; }
38234 function bnXor(a) { var r = nbi(); this.bitwiseTo(a,op_xor,r); return r; }
38235
38236 // (public) this & ~a
38237 function op_andnot(x,y) { return x&~y; }
38238 function bnAndNot(a) { var r = nbi(); this.bitwiseTo(a,op_andnot,r); return r; }
38239
38240 // (public) ~this
38241 function bnNot() {
38242 var r = nbi();
38243 for(var i = 0; i < this.t; ++i) r[i] = this.DM&~this[i];
38244 r.t = this.t;
38245 r.s = ~this.s;
38246 return r;
38247 }
38248
38249 // (public) this << n
38250 function bnShiftLeft(n) {
38251 var r = nbi();
38252 if(n < 0) this.rShiftTo(-n,r); else this.lShiftTo(n,r);
38253 return r;
38254 }
38255
38256 // (public) this >> n
38257 function bnShiftRight(n) {
38258 var r = nbi();
38259 if(n < 0) this.lShiftTo(-n,r); else this.rShiftTo(n,r);
38260 return r;
38261 }
38262
38263 // return index of lowest 1-bit in x, x < 2^31
38264 function lbit(x) {
38265 if(x == 0) return -1;
38266 var r = 0;
38267 if((x&0xffff) == 0) { x >>= 16; r += 16; }
38268 if((x&0xff) == 0) { x >>= 8; r += 8; }
38269 if((x&0xf) == 0) { x >>= 4; r += 4; }
38270 if((x&3) == 0) { x >>= 2; r += 2; }
38271 if((x&1) == 0) ++r;
38272 return r;
38273 }
38274
38275 // (public) returns index of lowest 1-bit (or -1 if none)
38276 function bnGetLowestSetBit() {
38277 for(var i = 0; i < this.t; ++i)
38278 if(this[i] != 0) return i*this.DB+lbit(this[i]);
38279 if(this.s < 0) return this.t*this.DB;
38280 return -1;
38281 }
38282
38283 // return number of 1 bits in x
38284 function cbit(x) {
38285 var r = 0;
38286 while(x != 0) { x &= x-1; ++r; }
38287 return r;
38288 }
38289
38290 // (public) return number of set bits
38291 function bnBitCount() {
38292 var r = 0, x = this.s&this.DM;
38293 for(var i = 0; i < this.t; ++i) r += cbit(this[i]^x);
38294 return r;
38295 }
38296
38297 // (public) true iff nth bit is set
38298 function bnTestBit(n) {
38299 var j = Math.floor(n/this.DB);
38300 if(j >= this.t) return(this.s!=0);
38301 return((this[j]&(1<<(n%this.DB)))!=0);
38302 }
38303
38304 // (protected) this op (1<<n)
38305 function bnpChangeBit(n,op) {
38306 var r = BigInteger.ONE.shiftLeft(n);
38307 this.bitwiseTo(r,op,r);
38308 return r;
38309 }
38310
38311 // (public) this | (1<<n)
38312 function bnSetBit(n) { return this.changeBit(n,op_or); }
38313
38314 // (public) this & ~(1<<n)
38315 function bnClearBit(n) { return this.changeBit(n,op_andnot); }
38316
38317 // (public) this ^ (1<<n)
38318 function bnFlipBit(n) { return this.changeBit(n,op_xor); }
38319
38320 // (protected) r = this + a
38321 function bnpAddTo(a,r) {
38322 var i = 0, c = 0, m = Math.min(a.t,this.t);
38323 while(i < m) {
38324 c += this[i]+a[i];
38325 r[i++] = c&this.DM;
38326 c >>= this.DB;
38327 }
38328 if(a.t < this.t) {
38329 c += a.s;
38330 while(i < this.t) {
38331 c += this[i];
38332 r[i++] = c&this.DM;
38333 c >>= this.DB;
38334 }
38335 c += this.s;
38336 }
38337 else {
38338 c += this.s;
38339 while(i < a.t) {
38340 c += a[i];
38341 r[i++] = c&this.DM;
38342 c >>= this.DB;
38343 }
38344 c += a.s;
38345 }
38346 r.s = (c<0)?-1:0;
38347 if(c > 0) r[i++] = c;
38348 else if(c < -1) r[i++] = this.DV+c;
38349 r.t = i;
38350 r.clamp();
38351 }
38352
38353 // (public) this + a
38354 function bnAdd(a) { var r = nbi(); this.addTo(a,r); return r; }
38355
38356 // (public) this - a
38357 function bnSubtract(a) { var r = nbi(); this.subTo(a,r); return r; }
38358
38359 // (public) this * a
38360 function bnMultiply(a) { var r = nbi(); this.multiplyTo(a,r); return r; }
38361
38362 // (public) this^2
38363 function bnSquare() { var r = nbi(); this.squareTo(r); return r; }
38364
38365 // (public) this / a
38366 function bnDivide(a) { var r = nbi(); this.divRemTo(a,r,null); return r; }
38367
38368 // (public) this % a
38369 function bnRemainder(a) { var r = nbi(); this.divRemTo(a,null,r); return r; }
38370
38371 // (public) [this/a,this%a]
38372 function bnDivideAndRemainder(a) {
38373 var q = nbi(), r = nbi();
38374 this.divRemTo(a,q,r);
38375 return new Array(q,r);
38376 }
38377
38378 // (protected) this *= n, this >= 0, 1 < n < DV
38379 function bnpDMultiply(n) {
38380 this[this.t] = this.am(0,n-1,this,0,0,this.t);
38381 ++this.t;
38382 this.clamp();
38383 }
38384
38385 // (protected) this += n << w words, this >= 0
38386 function bnpDAddOffset(n,w) {
38387 if(n == 0) return;
38388 while(this.t <= w) this[this.t++] = 0;
38389 this[w] += n;
38390 while(this[w] >= this.DV) {
38391 this[w] -= this.DV;
38392 if(++w >= this.t) this[this.t++] = 0;
38393 ++this[w];
38394 }
38395 }
38396
38397 // A "null" reducer
38398 function NullExp() {}
38399 function nNop(x) { return x; }
38400 function nMulTo(x,y,r) { x.multiplyTo(y,r); }
38401 function nSqrTo(x,r) { x.squareTo(r); }
38402
38403 NullExp.prototype.convert = nNop;
38404 NullExp.prototype.revert = nNop;
38405 NullExp.prototype.mulTo = nMulTo;
38406 NullExp.prototype.sqrTo = nSqrTo;
38407
38408 // (public) this^e
38409 function bnPow(e) { return this.exp(e,new NullExp()); }
38410
38411 // (protected) r = lower n words of "this * a", a.t <= n
38412 // "this" should be the larger one if appropriate.
38413 function bnpMultiplyLowerTo(a,n,r) {
38414 var i = Math.min(this.t+a.t,n);
38415 r.s = 0; // assumes a,this >= 0
38416 r.t = i;
38417 while(i > 0) r[--i] = 0;
38418 var j;
38419 for(j = r.t-this.t; i < j; ++i) r[i+this.t] = this.am(0,a[i],r,i,0,this.t);
38420 for(j = Math.min(a.t,n); i < j; ++i) this.am(0,a[i],r,i,0,n-i);
38421 r.clamp();
38422 }
38423
38424 // (protected) r = "this * a" without lower n words, n > 0
38425 // "this" should be the larger one if appropriate.
38426 function bnpMultiplyUpperTo(a,n,r) {
38427 --n;
38428 var i = r.t = this.t+a.t-n;
38429 r.s = 0; // assumes a,this >= 0
38430 while(--i >= 0) r[i] = 0;
38431 for(i = Math.max(n-this.t,0); i < a.t; ++i)
38432 r[this.t+i-n] = this.am(n-i,a[i],r,0,0,this.t+i-n);
38433 r.clamp();
38434 r.drShiftTo(1,r);
38435 }
38436
38437 // Barrett modular reduction
38438 function Barrett(m) {
38439 // setup Barrett
38440 this.r2 = nbi();
38441 this.q3 = nbi();
38442 BigInteger.ONE.dlShiftTo(2*m.t,this.r2);
38443 this.mu = this.r2.divide(m);
38444 this.m = m;
38445 }
38446
38447 function barrettConvert(x) {
38448 if(x.s < 0 || x.t > 2*this.m.t) return x.mod(this.m);
38449 else if(x.compareTo(this.m) < 0) return x;
38450 else { var r = nbi(); x.copyTo(r); this.reduce(r); return r; }
38451 }
38452
38453 function barrettRevert(x) { return x; }
38454
38455 // x = x mod m (HAC 14.42)
38456 function barrettReduce(x) {
38457 x.drShiftTo(this.m.t-1,this.r2);
38458 if(x.t > this.m.t+1) { x.t = this.m.t+1; x.clamp(); }
38459 this.mu.multiplyUpperTo(this.r2,this.m.t+1,this.q3);
38460 this.m.multiplyLowerTo(this.q3,this.m.t+1,this.r2);
38461 while(x.compareTo(this.r2) < 0) x.dAddOffset(1,this.m.t+1);
38462 x.subTo(this.r2,x);
38463 while(x.compareTo(this.m) >= 0) x.subTo(this.m,x);
38464 }
38465
38466 // r = x^2 mod m; x != r
38467 function barrettSqrTo(x,r) { x.squareTo(r); this.reduce(r); }
38468
38469 // r = x*y mod m; x,y != r
38470 function barrettMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); }
38471
38472 Barrett.prototype.convert = barrettConvert;
38473 Barrett.prototype.revert = barrettRevert;
38474 Barrett.prototype.reduce = barrettReduce;
38475 Barrett.prototype.mulTo = barrettMulTo;
38476 Barrett.prototype.sqrTo = barrettSqrTo;
38477
38478 // (public) this^e % m (HAC 14.85)
38479 function bnModPow(e,m) {
38480 var i = e.bitLength(), k, r = nbv(1), z;
38481 if(i <= 0) return r;
38482 else if(i < 18) k = 1;
38483 else if(i < 48) k = 3;
38484 else if(i < 144) k = 4;
38485 else if(i < 768) k = 5;
38486 else k = 6;
38487 if(i < 8)
38488 z = new Classic(m);
38489 else if(m.isEven())
38490 z = new Barrett(m);
38491 else
38492 z = new Montgomery(m);
38493
38494 // precomputation
38495 var g = new Array(), n = 3, k1 = k-1, km = (1<<k)-1;
38496 g[1] = z.convert(this);
38497 if(k > 1) {
38498 var g2 = nbi();
38499 z.sqrTo(g[1],g2);
38500 while(n <= km) {
38501 g[n] = nbi();
38502 z.mulTo(g2,g[n-2],g[n]);
38503 n += 2;
38504 }
38505 }
38506
38507 var j = e.t-1, w, is1 = true, r2 = nbi(), t;
38508 i = nbits(e[j])-1;
38509 while(j >= 0) {
38510 if(i >= k1) w = (e[j]>>(i-k1))&km;
38511 else {
38512 w = (e[j]&((1<<(i+1))-1))<<(k1-i);
38513 if(j > 0) w |= e[j-1]>>(this.DB+i-k1);
38514 }
38515
38516 n = k;
38517 while((w&1) == 0) { w >>= 1; --n; }
38518 if((i -= n) < 0) { i += this.DB; --j; }
38519 if(is1) { // ret == 1, don't bother squaring or multiplying it
38520 g[w].copyTo(r);
38521 is1 = false;
38522 }
38523 else {
38524 while(n > 1) { z.sqrTo(r,r2); z.sqrTo(r2,r); n -= 2; }
38525 if(n > 0) z.sqrTo(r,r2); else { t = r; r = r2; r2 = t; }
38526 z.mulTo(r2,g[w],r);
38527 }
38528
38529 while(j >= 0 && (e[j]&(1<<i)) == 0) {
38530 z.sqrTo(r,r2); t = r; r = r2; r2 = t;
38531 if(--i < 0) { i = this.DB-1; --j; }
38532 }
38533 }
38534 return z.revert(r);
38535 }
38536
38537 // (public) gcd(this,a) (HAC 14.54)
38538 function bnGCD(a) {
38539 var x = (this.s<0)?this.negate():this.clone();
38540 var y = (a.s<0)?a.negate():a.clone();
38541 if(x.compareTo(y) < 0) { var t = x; x = y; y = t; }
38542 var i = x.getLowestSetBit(), g = y.getLowestSetBit();
38543 if(g < 0) return x;
38544 if(i < g) g = i;
38545 if(g > 0) {
38546 x.rShiftTo(g,x);
38547 y.rShiftTo(g,y);
38548 }
38549 while(x.signum() > 0) {
38550 if((i = x.getLowestSetBit()) > 0) x.rShiftTo(i,x);
38551 if((i = y.getLowestSetBit()) > 0) y.rShiftTo(i,y);
38552 if(x.compareTo(y) >= 0) {
38553 x.subTo(y,x);
38554 x.rShiftTo(1,x);
38555 }
38556 else {
38557 y.subTo(x,y);
38558 y.rShiftTo(1,y);
38559 }
38560 }
38561 if(g > 0) y.lShiftTo(g,y);
38562 return y;
38563 }
38564
38565 // (protected) this % n, n < 2^26
38566 function bnpModInt(n) {
38567 if(n <= 0) return 0;
38568 var d = this.DV%n, r = (this.s<0)?n-1:0;
38569 if(this.t > 0)
38570 if(d == 0) r = this[0]%n;
38571 else for(var i = this.t-1; i >= 0; --i) r = (d*r+this[i])%n;
38572 return r;
38573 }
38574
38575 // (public) 1/this % m (HAC 14.61)
38576 function bnModInverse(m) {
38577 var ac = m.isEven();
38578 if((this.isEven() && ac) || m.signum() == 0) return BigInteger.ZERO;
38579 var u = m.clone(), v = this.clone();
38580 var a = nbv(1), b = nbv(0), c = nbv(0), d = nbv(1);
38581 while(u.signum() != 0) {
38582 while(u.isEven()) {
38583 u.rShiftTo(1,u);
38584 if(ac) {
38585 if(!a.isEven() || !b.isEven()) { a.addTo(this,a); b.subTo(m,b); }
38586 a.rShiftTo(1,a);
38587 }
38588 else if(!b.isEven()) b.subTo(m,b);
38589 b.rShiftTo(1,b);
38590 }
38591 while(v.isEven()) {
38592 v.rShiftTo(1,v);
38593 if(ac) {
38594 if(!c.isEven() || !d.isEven()) { c.addTo(this,c); d.subTo(m,d); }
38595 c.rShiftTo(1,c);
38596 }
38597 else if(!d.isEven()) d.subTo(m,d);
38598 d.rShiftTo(1,d);
38599 }
38600 if(u.compareTo(v) >= 0) {
38601 u.subTo(v,u);
38602 if(ac) a.subTo(c,a);
38603 b.subTo(d,b);
38604 }
38605 else {
38606 v.subTo(u,v);
38607 if(ac) c.subTo(a,c);
38608 d.subTo(b,d);
38609 }
38610 }
38611 if(v.compareTo(BigInteger.ONE) != 0) return BigInteger.ZERO;
38612 if(d.compareTo(m) >= 0) return d.subtract(m);
38613 if(d.signum() < 0) d.addTo(m,d); else return d;
38614 if(d.signum() < 0) return d.add(m); else return d;
38615 }
38616
38617 var lowprimes = [2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,251,257,263,269,271,277,281,283,293,307,311,313,317,331,337,347,349,353,359,367,373,379,383,389,397,401,409,419,421,431,433,439,443,449,457,461,463,467,479,487,491,499,503,509,521,523,541,547,557,563,569,571,577,587,593,599,601,607,613,617,619,631,641,643,647,653,659,661,673,677,683,691,701,709,719,727,733,739,743,751,757,761,769,773,787,797,809,811,821,823,827,829,839,853,857,859,863,877,881,883,887,907,911,919,929,937,941,947,953,967,971,977,983,991,997];
38618 var lplim = (1<<26)/lowprimes[lowprimes.length-1];
38619
38620 // (public) test primality with certainty >= 1-.5^t
38621 function bnIsProbablePrime(t) {
38622 var i, x = this.abs();
38623 if(x.t == 1 && x[0] <= lowprimes[lowprimes.length-1]) {
38624 for(i = 0; i < lowprimes.length; ++i)
38625 if(x[0] == lowprimes[i]) return true;
38626 return false;
38627 }
38628 if(x.isEven()) return false;
38629 i = 1;
38630 while(i < lowprimes.length) {
38631 var m = lowprimes[i], j = i+1;
38632 while(j < lowprimes.length && m < lplim) m *= lowprimes[j++];
38633 m = x.modInt(m);
38634 while(i < j) if(m%lowprimes[i++] == 0) return false;
38635 }
38636 return x.millerRabin(t);
38637 }
38638
38639 // (protected) true if probably prime (HAC 4.24, Miller-Rabin)
38640 function bnpMillerRabin(t) {
38641 var n1 = this.subtract(BigInteger.ONE);
38642 var k = n1.getLowestSetBit();
38643 if(k <= 0) return false;
38644 var r = n1.shiftRight(k);
38645 t = (t+1)>>1;
38646 if(t > lowprimes.length) t = lowprimes.length;
38647 var a = nbi();
38648 for(var i = 0; i < t; ++i) {
38649 //Pick bases at random, instead of starting at 2
38650 a.fromInt(lowprimes[Math.floor(Math.random()*lowprimes.length)]);
38651 var y = a.modPow(r,this);
38652 if(y.compareTo(BigInteger.ONE) != 0 && y.compareTo(n1) != 0) {
38653 var j = 1;
38654 while(j++ < k && y.compareTo(n1) != 0) {
38655 y = y.modPowInt(2,this);
38656 if(y.compareTo(BigInteger.ONE) == 0) return false;
38657 }
38658 if(y.compareTo(n1) != 0) return false;
38659 }
38660 }
38661 return true;
38662 }
38663
38664 // protected
38665 BigInteger.prototype.chunkSize = bnpChunkSize;
38666 BigInteger.prototype.toRadix = bnpToRadix;
38667 BigInteger.prototype.fromRadix = bnpFromRadix;
38668 BigInteger.prototype.fromNumber = bnpFromNumber;
38669 BigInteger.prototype.bitwiseTo = bnpBitwiseTo;
38670 BigInteger.prototype.changeBit = bnpChangeBit;
38671 BigInteger.prototype.addTo = bnpAddTo;
38672 BigInteger.prototype.dMultiply = bnpDMultiply;
38673 BigInteger.prototype.dAddOffset = bnpDAddOffset;
38674 BigInteger.prototype.multiplyLowerTo = bnpMultiplyLowerTo;
38675 BigInteger.prototype.multiplyUpperTo = bnpMultiplyUpperTo;
38676 BigInteger.prototype.modInt = bnpModInt;
38677 BigInteger.prototype.millerRabin = bnpMillerRabin;
38678
38679 // public
38680 BigInteger.prototype.clone = bnClone;
38681 BigInteger.prototype.intValue = bnIntValue;
38682 BigInteger.prototype.byteValue = bnByteValue;
38683 BigInteger.prototype.shortValue = bnShortValue;
38684 BigInteger.prototype.signum = bnSigNum;
38685 BigInteger.prototype.toByteArray = bnToByteArray;
38686 BigInteger.prototype.equals = bnEquals;
38687 BigInteger.prototype.min = bnMin;
38688 BigInteger.prototype.max = bnMax;
38689 BigInteger.prototype.and = bnAnd;
38690 BigInteger.prototype.or = bnOr;
38691 BigInteger.prototype.xor = bnXor;
38692 BigInteger.prototype.andNot = bnAndNot;
38693 BigInteger.prototype.not = bnNot;
38694 BigInteger.prototype.shiftLeft = bnShiftLeft;
38695 BigInteger.prototype.shiftRight = bnShiftRight;
38696 BigInteger.prototype.getLowestSetBit = bnGetLowestSetBit;
38697 BigInteger.prototype.bitCount = bnBitCount;
38698 BigInteger.prototype.testBit = bnTestBit;
38699 BigInteger.prototype.setBit = bnSetBit;
38700 BigInteger.prototype.clearBit = bnClearBit;
38701 BigInteger.prototype.flipBit = bnFlipBit;
38702 BigInteger.prototype.add = bnAdd;
38703 BigInteger.prototype.subtract = bnSubtract;
38704 BigInteger.prototype.multiply = bnMultiply;
38705 BigInteger.prototype.divide = bnDivide;
38706 BigInteger.prototype.remainder = bnRemainder;
38707 BigInteger.prototype.divideAndRemainder = bnDivideAndRemainder;
38708 BigInteger.prototype.modPow = bnModPow;
38709 BigInteger.prototype.modInverse = bnModInverse;
38710 BigInteger.prototype.pow = bnPow;
38711 BigInteger.prototype.gcd = bnGCD;
38712 BigInteger.prototype.isProbablePrime = bnIsProbablePrime;
38713
38714 // JSBN-specific extension
38715 BigInteger.prototype.square = bnSquare;
38716
38717 // Expose the Barrett function
38718 BigInteger.prototype.Barrett = Barrett
38719
38720 // BigInteger interfaces not implemented in jsbn:
38721
38722 // BigInteger(int signum, byte[] magnitude)
38723 // double doubleValue()
38724 // float floatValue()
38725 // int hashCode()
38726 // long longValue()
38727 // static BigInteger valueOf(long val)
38728
38729 // Random number generator - requires a PRNG backend, e.g. prng4.js
38730
38731 // For best results, put code like
38732 // <body onClick='rng_seed_time();' onKeyPress='rng_seed_time();'>
38733 // in your main HTML document.
38734
38735 var rng_state;
38736 var rng_pool;
38737 var rng_pptr;
38738
38739 // Mix in a 32-bit integer into the pool
38740 function rng_seed_int(x) {
38741 rng_pool[rng_pptr++] ^= x & 255;
38742 rng_pool[rng_pptr++] ^= (x >> 8) & 255;
38743 rng_pool[rng_pptr++] ^= (x >> 16) & 255;
38744 rng_pool[rng_pptr++] ^= (x >> 24) & 255;
38745 if(rng_pptr >= rng_psize) rng_pptr -= rng_psize;
38746 }
38747
38748 // Mix in the current time (w/milliseconds) into the pool
38749 function rng_seed_time() {
38750 rng_seed_int(new Date().getTime());
38751 }
38752
38753 // Initialize the pool with junk if needed.
38754 if(rng_pool == null) {
38755 rng_pool = new Array();
38756 rng_pptr = 0;
38757 var t;
38758 if(typeof window !== "undefined" && window.crypto) {
38759 if (window.crypto.getRandomValues) {
38760 // Use webcrypto if available
38761 var ua = new Uint8Array(32);
38762 window.crypto.getRandomValues(ua);
38763 for(t = 0; t < 32; ++t)
38764 rng_pool[rng_pptr++] = ua[t];
38765 }
38766 else if(navigator.appName == "Netscape" && navigator.appVersion < "5") {
38767 // Extract entropy (256 bits) from NS4 RNG if available
38768 var z = window.crypto.random(32);
38769 for(t = 0; t < z.length; ++t)
38770 rng_pool[rng_pptr++] = z.charCodeAt(t) & 255;
38771 }
38772 }
38773 while(rng_pptr < rng_psize) { // extract some randomness from Math.random()
38774 t = Math.floor(65536 * Math.random());
38775 rng_pool[rng_pptr++] = t >>> 8;
38776 rng_pool[rng_pptr++] = t & 255;
38777 }
38778 rng_pptr = 0;
38779 rng_seed_time();
38780 //rng_seed_int(window.screenX);
38781 //rng_seed_int(window.screenY);
38782 }
38783
38784 function rng_get_byte() {
38785 if(rng_state == null) {
38786 rng_seed_time();
38787 rng_state = prng_newstate();
38788 rng_state.init(rng_pool);
38789 for(rng_pptr = 0; rng_pptr < rng_pool.length; ++rng_pptr)
38790 rng_pool[rng_pptr] = 0;
38791 rng_pptr = 0;
38792 //rng_pool = null;
38793 }
38794 // TODO: allow reseeding after first request
38795 return rng_state.next();
38796 }
38797
38798 function rng_get_bytes(ba) {
38799 var i;
38800 for(i = 0; i < ba.length; ++i) ba[i] = rng_get_byte();
38801 }
38802
38803 function SecureRandom() {}
38804
38805 SecureRandom.prototype.nextBytes = rng_get_bytes;
38806
38807 // prng4.js - uses Arcfour as a PRNG
38808
38809 function Arcfour() {
38810 this.i = 0;
38811 this.j = 0;
38812 this.S = new Array();
38813 }
38814
38815 // Initialize arcfour context from key, an array of ints, each from [0..255]
38816 function ARC4init(key) {
38817 var i, j, t;
38818 for(i = 0; i < 256; ++i)
38819 this.S[i] = i;
38820 j = 0;
38821 for(i = 0; i < 256; ++i) {
38822 j = (j + this.S[i] + key[i % key.length]) & 255;
38823 t = this.S[i];
38824 this.S[i] = this.S[j];
38825 this.S[j] = t;
38826 }
38827 this.i = 0;
38828 this.j = 0;
38829 }
38830
38831 function ARC4next() {
38832 var t;
38833 this.i = (this.i + 1) & 255;
38834 this.j = (this.j + this.S[this.i]) & 255;
38835 t = this.S[this.i];
38836 this.S[this.i] = this.S[this.j];
38837 this.S[this.j] = t;
38838 return this.S[(t + this.S[this.i]) & 255];
38839 }
38840
38841 Arcfour.prototype.init = ARC4init;
38842 Arcfour.prototype.next = ARC4next;
38843
38844 // Plug in your RNG constructor here
38845 function prng_newstate() {
38846 return new Arcfour();
38847 }
38848
38849 // Pool size must be a multiple of 4 and greater than 32.
38850 // An array of bytes the size of the pool will be passed to init()
38851 var rng_psize = 256;
38852
38853 BigInteger.SecureRandom = SecureRandom;
38854 BigInteger.BigInteger = BigInteger;
38855 if (typeof exports !== 'undefined') {
38856 exports = module.exports = BigInteger;
38857 } else {
38858 this.BigInteger = BigInteger;
38859 this.SecureRandom = SecureRandom;
38860 }
38861
38862}).call(this);
38863
38864},{}],216:[function(require,module,exports){
38865'use strict';
38866
38867var traverse = module.exports = function (schema, opts, cb) {
38868 // Legacy support for v0.3.1 and earlier.
38869 if (typeof opts == 'function') {
38870 cb = opts;
38871 opts = {};
38872 }
38873
38874 cb = opts.cb || cb;
38875 var pre = (typeof cb == 'function') ? cb : cb.pre || function() {};
38876 var post = cb.post || function() {};
38877
38878 _traverse(opts, pre, post, schema, '', schema);
38879};
38880
38881
38882traverse.keywords = {
38883 additionalItems: true,
38884 items: true,
38885 contains: true,
38886 additionalProperties: true,
38887 propertyNames: true,
38888 not: true
38889};
38890
38891traverse.arrayKeywords = {
38892 items: true,
38893 allOf: true,
38894 anyOf: true,
38895 oneOf: true
38896};
38897
38898traverse.propsKeywords = {
38899 definitions: true,
38900 properties: true,
38901 patternProperties: true,
38902 dependencies: true
38903};
38904
38905traverse.skipKeywords = {
38906 default: true,
38907 enum: true,
38908 const: true,
38909 required: true,
38910 maximum: true,
38911 minimum: true,
38912 exclusiveMaximum: true,
38913 exclusiveMinimum: true,
38914 multipleOf: true,
38915 maxLength: true,
38916 minLength: true,
38917 pattern: true,
38918 format: true,
38919 maxItems: true,
38920 minItems: true,
38921 uniqueItems: true,
38922 maxProperties: true,
38923 minProperties: true
38924};
38925
38926
38927function _traverse(opts, pre, post, schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex) {
38928 if (schema && typeof schema == 'object' && !Array.isArray(schema)) {
38929 pre(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex);
38930 for (var key in schema) {
38931 var sch = schema[key];
38932 if (Array.isArray(sch)) {
38933 if (key in traverse.arrayKeywords) {
38934 for (var i=0; i<sch.length; i++)
38935 _traverse(opts, pre, post, sch[i], jsonPtr + '/' + key + '/' + i, rootSchema, jsonPtr, key, schema, i);
38936 }
38937 } else if (key in traverse.propsKeywords) {
38938 if (sch && typeof sch == 'object') {
38939 for (var prop in sch)
38940 _traverse(opts, pre, post, sch[prop], jsonPtr + '/' + key + '/' + escapeJsonPtr(prop), rootSchema, jsonPtr, key, schema, prop);
38941 }
38942 } else if (key in traverse.keywords || (opts.allKeys && !(key in traverse.skipKeywords))) {
38943 _traverse(opts, pre, post, sch, jsonPtr + '/' + key, rootSchema, jsonPtr, key, schema);
38944 }
38945 }
38946 post(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex);
38947 }
38948}
38949
38950
38951function escapeJsonPtr(str) {
38952 return str.replace(/~/g, '~0').replace(/\//g, '~1');
38953}
38954
38955},{}],217:[function(require,module,exports){
38956/**
38957 * JSONSchema Validator - Validates JavaScript objects using JSON Schemas
38958 * (http://www.json.com/json-schema-proposal/)
38959 *
38960 * Copyright (c) 2007 Kris Zyp SitePen (www.sitepen.com)
38961 * Licensed under the MIT (MIT-LICENSE.txt) license.
38962To use the validator call the validate function with an instance object and an optional schema object.
38963If a schema is provided, it will be used to validate. If the instance object refers to a schema (self-validating),
38964that schema will be used to validate and the schema parameter is not necessary (if both exist,
38965both validations will occur).
38966The validate method will return an array of validation errors. If there are no errors, then an
38967empty list will be returned. A validation error will have two properties:
38968"property" which indicates which property had the error
38969"message" which indicates what the error was
38970 */
38971(function (root, factory) {
38972 if (typeof define === 'function' && define.amd) {
38973 // AMD. Register as an anonymous module.
38974 define([], function () {
38975 return factory();
38976 });
38977 } else if (typeof module === 'object' && module.exports) {
38978 // Node. Does not work with strict CommonJS, but
38979 // only CommonJS-like environments that support module.exports,
38980 // like Node.
38981 module.exports = factory();
38982 } else {
38983 // Browser globals
38984 root.jsonSchema = factory();
38985 }
38986}(this, function () {// setup primitive classes to be JSON Schema types
38987var exports = validate
38988exports.Integer = {type:"integer"};
38989var primitiveConstructors = {
38990 String: String,
38991 Boolean: Boolean,
38992 Number: Number,
38993 Object: Object,
38994 Array: Array,
38995 Date: Date
38996}
38997exports.validate = validate;
38998function validate(/*Any*/instance,/*Object*/schema) {
38999 // Summary:
39000 // To use the validator call JSONSchema.validate with an instance object and an optional schema object.
39001 // If a schema is provided, it will be used to validate. If the instance object refers to a schema (self-validating),
39002 // that schema will be used to validate and the schema parameter is not necessary (if both exist,
39003 // both validations will occur).
39004 // The validate method will return an object with two properties:
39005 // valid: A boolean indicating if the instance is valid by the schema
39006 // errors: An array of validation errors. If there are no errors, then an
39007 // empty list will be returned. A validation error will have two properties:
39008 // property: which indicates which property had the error
39009 // message: which indicates what the error was
39010 //
39011 return validate(instance, schema, {changing: false});//, coerce: false, existingOnly: false});
39012 };
39013exports.checkPropertyChange = function(/*Any*/value,/*Object*/schema, /*String*/property) {
39014 // Summary:
39015 // The checkPropertyChange method will check to see if an value can legally be in property with the given schema
39016 // This is slightly different than the validate method in that it will fail if the schema is readonly and it will
39017 // not check for self-validation, it is assumed that the passed in value is already internally valid.
39018 // The checkPropertyChange method will return the same object type as validate, see JSONSchema.validate for
39019 // information.
39020 //
39021 return validate(value, schema, {changing: property || "property"});
39022 };
39023var validate = exports._validate = function(/*Any*/instance,/*Object*/schema,/*Object*/options) {
39024
39025 if (!options) options = {};
39026 var _changing = options.changing;
39027
39028 function getType(schema){
39029 return schema.type || (primitiveConstructors[schema.name] == schema && schema.name.toLowerCase());
39030 }
39031 var errors = [];
39032 // validate a value against a property definition
39033 function checkProp(value, schema, path,i){
39034
39035 var l;
39036 path += path ? typeof i == 'number' ? '[' + i + ']' : typeof i == 'undefined' ? '' : '.' + i : i;
39037 function addError(message){
39038 errors.push({property:path,message:message});
39039 }
39040
39041 if((typeof schema != 'object' || schema instanceof Array) && (path || typeof schema != 'function') && !(schema && getType(schema))){
39042 if(typeof schema == 'function'){
39043 if(!(value instanceof schema)){
39044 addError("is not an instance of the class/constructor " + schema.name);
39045 }
39046 }else if(schema){
39047 addError("Invalid schema/property definition " + schema);
39048 }
39049 return null;
39050 }
39051 if(_changing && schema.readonly){
39052 addError("is a readonly field, it can not be changed");
39053 }
39054 if(schema['extends']){ // if it extends another schema, it must pass that schema as well
39055 checkProp(value,schema['extends'],path,i);
39056 }
39057 // validate a value against a type definition
39058 function checkType(type,value){
39059 if(type){
39060 if(typeof type == 'string' && type != 'any' &&
39061 (type == 'null' ? value !== null : typeof value != type) &&
39062 !(value instanceof Array && type == 'array') &&
39063 !(value instanceof Date && type == 'date') &&
39064 !(type == 'integer' && value%1===0)){
39065 return [{property:path,message:(typeof value) + " value found, but a " + type + " is required"}];
39066 }
39067 if(type instanceof Array){
39068 var unionErrors=[];
39069 for(var j = 0; j < type.length; j++){ // a union type
39070 if(!(unionErrors=checkType(type[j],value)).length){
39071 break;
39072 }
39073 }
39074 if(unionErrors.length){
39075 return unionErrors;
39076 }
39077 }else if(typeof type == 'object'){
39078 var priorErrors = errors;
39079 errors = [];
39080 checkProp(value,type,path);
39081 var theseErrors = errors;
39082 errors = priorErrors;
39083 return theseErrors;
39084 }
39085 }
39086 return [];
39087 }
39088 if(value === undefined){
39089 if(schema.required){
39090 addError("is missing and it is required");
39091 }
39092 }else{
39093 errors = errors.concat(checkType(getType(schema),value));
39094 if(schema.disallow && !checkType(schema.disallow,value).length){
39095 addError(" disallowed value was matched");
39096 }
39097 if(value !== null){
39098 if(value instanceof Array){
39099 if(schema.items){
39100 var itemsIsArray = schema.items instanceof Array;
39101 var propDef = schema.items;
39102 for (i = 0, l = value.length; i < l; i += 1) {
39103 if (itemsIsArray)
39104 propDef = schema.items[i];
39105 if (options.coerce)
39106 value[i] = options.coerce(value[i], propDef);
39107 errors.concat(checkProp(value[i],propDef,path,i));
39108 }
39109 }
39110 if(schema.minItems && value.length < schema.minItems){
39111 addError("There must be a minimum of " + schema.minItems + " in the array");
39112 }
39113 if(schema.maxItems && value.length > schema.maxItems){
39114 addError("There must be a maximum of " + schema.maxItems + " in the array");
39115 }
39116 }else if(schema.properties || schema.additionalProperties){
39117 errors.concat(checkObj(value, schema.properties, path, schema.additionalProperties));
39118 }
39119 if(schema.pattern && typeof value == 'string' && !value.match(schema.pattern)){
39120 addError("does not match the regex pattern " + schema.pattern);
39121 }
39122 if(schema.maxLength && typeof value == 'string' && value.length > schema.maxLength){
39123 addError("may only be " + schema.maxLength + " characters long");
39124 }
39125 if(schema.minLength && typeof value == 'string' && value.length < schema.minLength){
39126 addError("must be at least " + schema.minLength + " characters long");
39127 }
39128 if(typeof schema.minimum !== undefined && typeof value == typeof schema.minimum &&
39129 schema.minimum > value){
39130 addError("must have a minimum value of " + schema.minimum);
39131 }
39132 if(typeof schema.maximum !== undefined && typeof value == typeof schema.maximum &&
39133 schema.maximum < value){
39134 addError("must have a maximum value of " + schema.maximum);
39135 }
39136 if(schema['enum']){
39137 var enumer = schema['enum'];
39138 l = enumer.length;
39139 var found;
39140 for(var j = 0; j < l; j++){
39141 if(enumer[j]===value){
39142 found=1;
39143 break;
39144 }
39145 }
39146 if(!found){
39147 addError("does not have a value in the enumeration " + enumer.join(", "));
39148 }
39149 }
39150 if(typeof schema.maxDecimal == 'number' &&
39151 (value.toString().match(new RegExp("\\.[0-9]{" + (schema.maxDecimal + 1) + ",}")))){
39152 addError("may only have " + schema.maxDecimal + " digits of decimal places");
39153 }
39154 }
39155 }
39156 return null;
39157 }
39158 // validate an object against a schema
39159 function checkObj(instance,objTypeDef,path,additionalProp){
39160
39161 if(typeof objTypeDef =='object'){
39162 if(typeof instance != 'object' || instance instanceof Array){
39163 errors.push({property:path,message:"an object is required"});
39164 }
39165
39166 for(var i in objTypeDef){
39167 if(objTypeDef.hasOwnProperty(i)){
39168 var value = instance[i];
39169 // skip _not_ specified properties
39170 if (value === undefined && options.existingOnly) continue;
39171 var propDef = objTypeDef[i];
39172 // set default
39173 if(value === undefined && propDef["default"]){
39174 value = instance[i] = propDef["default"];
39175 }
39176 if(options.coerce && i in instance){
39177 value = instance[i] = options.coerce(value, propDef);
39178 }
39179 checkProp(value,propDef,path,i);
39180 }
39181 }
39182 }
39183 for(i in instance){
39184 if(instance.hasOwnProperty(i) && !(i.charAt(0) == '_' && i.charAt(1) == '_') && objTypeDef && !objTypeDef[i] && additionalProp===false){
39185 if (options.filter) {
39186 delete instance[i];
39187 continue;
39188 } else {
39189 errors.push({property:path,message:(typeof value) + "The property " + i +
39190 " is not defined in the schema and the schema does not allow additional properties"});
39191 }
39192 }
39193 var requires = objTypeDef && objTypeDef[i] && objTypeDef[i].requires;
39194 if(requires && !(requires in instance)){
39195 errors.push({property:path,message:"the presence of the property " + i + " requires that " + requires + " also be present"});
39196 }
39197 value = instance[i];
39198 if(additionalProp && (!(objTypeDef && typeof objTypeDef == 'object') || !(i in objTypeDef))){
39199 if(options.coerce){
39200 value = instance[i] = options.coerce(value, additionalProp);
39201 }
39202 checkProp(value,additionalProp,path,i);
39203 }
39204 if(!_changing && value && value.$schema){
39205 errors = errors.concat(checkProp(value,value.$schema,path,i));
39206 }
39207 }
39208 return errors;
39209 }
39210 if(schema){
39211 checkProp(instance,schema,'',_changing || '');
39212 }
39213 if(!_changing && instance && instance.$schema){
39214 checkProp(instance,instance.$schema,'','');
39215 }
39216 return {valid:!errors.length,errors:errors};
39217};
39218exports.mustBeValid = function(result){
39219 // summary:
39220 // This checks to ensure that the result is valid and will throw an appropriate error message if it is not
39221 // result: the result returned from checkPropertyChange or validate
39222 if(!result.valid){
39223 throw new TypeError(result.errors.map(function(error){return "for property " + error.property + ': ' + error.message;}).join(", \n"));
39224 }
39225}
39226
39227return exports;
39228}));
39229
39230},{}],218:[function(require,module,exports){
39231exports = module.exports = stringify
39232exports.getSerialize = serializer
39233
39234function stringify(obj, replacer, spaces, cycleReplacer) {
39235 return JSON.stringify(obj, serializer(replacer, cycleReplacer), spaces)
39236}
39237
39238function serializer(replacer, cycleReplacer) {
39239 var stack = [], keys = []
39240
39241 if (cycleReplacer == null) cycleReplacer = function(key, value) {
39242 if (stack[0] === value) return "[Circular ~]"
39243 return "[Circular ~." + keys.slice(0, stack.indexOf(value)).join(".") + "]"
39244 }
39245
39246 return function(key, value) {
39247 if (stack.length > 0) {
39248 var thisPos = stack.indexOf(this)
39249 ~thisPos ? stack.splice(thisPos + 1) : stack.push(this)
39250 ~thisPos ? keys.splice(thisPos, Infinity, key) : keys.push(key)
39251 if (~stack.indexOf(value)) value = cycleReplacer.call(this, key, value)
39252 }
39253 else stack.push(value)
39254
39255 return replacer == null ? value : replacer.call(this, key, value)
39256 }
39257}
39258
39259},{}],219:[function(require,module,exports){
39260/*
39261 * lib/jsprim.js: utilities for primitive JavaScript types
39262 */
39263
39264var mod_assert = require('assert-plus');
39265var mod_util = require('util');
39266
39267var mod_extsprintf = require('extsprintf');
39268var mod_verror = require('verror');
39269var mod_jsonschema = require('json-schema');
39270
39271/*
39272 * Public interface
39273 */
39274exports.deepCopy = deepCopy;
39275exports.deepEqual = deepEqual;
39276exports.isEmpty = isEmpty;
39277exports.hasKey = hasKey;
39278exports.forEachKey = forEachKey;
39279exports.pluck = pluck;
39280exports.flattenObject = flattenObject;
39281exports.flattenIter = flattenIter;
39282exports.validateJsonObject = validateJsonObjectJS;
39283exports.validateJsonObjectJS = validateJsonObjectJS;
39284exports.randElt = randElt;
39285exports.extraProperties = extraProperties;
39286exports.mergeObjects = mergeObjects;
39287
39288exports.startsWith = startsWith;
39289exports.endsWith = endsWith;
39290
39291exports.parseInteger = parseInteger;
39292
39293exports.iso8601 = iso8601;
39294exports.rfc1123 = rfc1123;
39295exports.parseDateTime = parseDateTime;
39296
39297exports.hrtimediff = hrtimeDiff;
39298exports.hrtimeDiff = hrtimeDiff;
39299exports.hrtimeAccum = hrtimeAccum;
39300exports.hrtimeAdd = hrtimeAdd;
39301exports.hrtimeNanosec = hrtimeNanosec;
39302exports.hrtimeMicrosec = hrtimeMicrosec;
39303exports.hrtimeMillisec = hrtimeMillisec;
39304
39305
39306/*
39307 * Deep copy an acyclic *basic* Javascript object. This only handles basic
39308 * scalars (strings, numbers, booleans) and arbitrarily deep arrays and objects
39309 * containing these. This does *not* handle instances of other classes.
39310 */
39311function deepCopy(obj)
39312{
39313 var ret, key;
39314 var marker = '__deepCopy';
39315
39316 if (obj && obj[marker])
39317 throw (new Error('attempted deep copy of cyclic object'));
39318
39319 if (obj && obj.constructor == Object) {
39320 ret = {};
39321 obj[marker] = true;
39322
39323 for (key in obj) {
39324 if (key == marker)
39325 continue;
39326
39327 ret[key] = deepCopy(obj[key]);
39328 }
39329
39330 delete (obj[marker]);
39331 return (ret);
39332 }
39333
39334 if (obj && obj.constructor == Array) {
39335 ret = [];
39336 obj[marker] = true;
39337
39338 for (key = 0; key < obj.length; key++)
39339 ret.push(deepCopy(obj[key]));
39340
39341 delete (obj[marker]);
39342 return (ret);
39343 }
39344
39345 /*
39346 * It must be a primitive type -- just return it.
39347 */
39348 return (obj);
39349}
39350
39351function deepEqual(obj1, obj2)
39352{
39353 if (typeof (obj1) != typeof (obj2))
39354 return (false);
39355
39356 if (obj1 === null || obj2 === null || typeof (obj1) != 'object')
39357 return (obj1 === obj2);
39358
39359 if (obj1.constructor != obj2.constructor)
39360 return (false);
39361
39362 var k;
39363 for (k in obj1) {
39364 if (!obj2.hasOwnProperty(k))
39365 return (false);
39366
39367 if (!deepEqual(obj1[k], obj2[k]))
39368 return (false);
39369 }
39370
39371 for (k in obj2) {
39372 if (!obj1.hasOwnProperty(k))
39373 return (false);
39374 }
39375
39376 return (true);
39377}
39378
39379function isEmpty(obj)
39380{
39381 var key;
39382 for (key in obj)
39383 return (false);
39384 return (true);
39385}
39386
39387function hasKey(obj, key)
39388{
39389 mod_assert.equal(typeof (key), 'string');
39390 return (Object.prototype.hasOwnProperty.call(obj, key));
39391}
39392
39393function forEachKey(obj, callback)
39394{
39395 for (var key in obj) {
39396 if (hasKey(obj, key)) {
39397 callback(key, obj[key]);
39398 }
39399 }
39400}
39401
39402function pluck(obj, key)
39403{
39404 mod_assert.equal(typeof (key), 'string');
39405 return (pluckv(obj, key));
39406}
39407
39408function pluckv(obj, key)
39409{
39410 if (obj === null || typeof (obj) !== 'object')
39411 return (undefined);
39412
39413 if (obj.hasOwnProperty(key))
39414 return (obj[key]);
39415
39416 var i = key.indexOf('.');
39417 if (i == -1)
39418 return (undefined);
39419
39420 var key1 = key.substr(0, i);
39421 if (!obj.hasOwnProperty(key1))
39422 return (undefined);
39423
39424 return (pluckv(obj[key1], key.substr(i + 1)));
39425}
39426
39427/*
39428 * Invoke callback(row) for each entry in the array that would be returned by
39429 * flattenObject(data, depth). This is just like flattenObject(data,
39430 * depth).forEach(callback), except that the intermediate array is never
39431 * created.
39432 */
39433function flattenIter(data, depth, callback)
39434{
39435 doFlattenIter(data, depth, [], callback);
39436}
39437
39438function doFlattenIter(data, depth, accum, callback)
39439{
39440 var each;
39441 var key;
39442
39443 if (depth === 0) {
39444 each = accum.slice(0);
39445 each.push(data);
39446 callback(each);
39447 return;
39448 }
39449
39450 mod_assert.ok(data !== null);
39451 mod_assert.equal(typeof (data), 'object');
39452 mod_assert.equal(typeof (depth), 'number');
39453 mod_assert.ok(depth >= 0);
39454
39455 for (key in data) {
39456 each = accum.slice(0);
39457 each.push(key);
39458 doFlattenIter(data[key], depth - 1, each, callback);
39459 }
39460}
39461
39462function flattenObject(data, depth)
39463{
39464 if (depth === 0)
39465 return ([ data ]);
39466
39467 mod_assert.ok(data !== null);
39468 mod_assert.equal(typeof (data), 'object');
39469 mod_assert.equal(typeof (depth), 'number');
39470 mod_assert.ok(depth >= 0);
39471
39472 var rv = [];
39473 var key;
39474
39475 for (key in data) {
39476 flattenObject(data[key], depth - 1).forEach(function (p) {
39477 rv.push([ key ].concat(p));
39478 });
39479 }
39480
39481 return (rv);
39482}
39483
39484function startsWith(str, prefix)
39485{
39486 return (str.substr(0, prefix.length) == prefix);
39487}
39488
39489function endsWith(str, suffix)
39490{
39491 return (str.substr(
39492 str.length - suffix.length, suffix.length) == suffix);
39493}
39494
39495function iso8601(d)
39496{
39497 if (typeof (d) == 'number')
39498 d = new Date(d);
39499 mod_assert.ok(d.constructor === Date);
39500 return (mod_extsprintf.sprintf('%4d-%02d-%02dT%02d:%02d:%02d.%03dZ',
39501 d.getUTCFullYear(), d.getUTCMonth() + 1, d.getUTCDate(),
39502 d.getUTCHours(), d.getUTCMinutes(), d.getUTCSeconds(),
39503 d.getUTCMilliseconds()));
39504}
39505
39506var RFC1123_MONTHS = [
39507 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
39508 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
39509var RFC1123_DAYS = [
39510 'Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
39511
39512function rfc1123(date) {
39513 return (mod_extsprintf.sprintf('%s, %02d %s %04d %02d:%02d:%02d GMT',
39514 RFC1123_DAYS[date.getUTCDay()], date.getUTCDate(),
39515 RFC1123_MONTHS[date.getUTCMonth()], date.getUTCFullYear(),
39516 date.getUTCHours(), date.getUTCMinutes(),
39517 date.getUTCSeconds()));
39518}
39519
39520/*
39521 * Parses a date expressed as a string, as either a number of milliseconds since
39522 * the epoch or any string format that Date accepts, giving preference to the
39523 * former where these two sets overlap (e.g., small numbers).
39524 */
39525function parseDateTime(str)
39526{
39527 /*
39528 * This is irritatingly implicit, but significantly more concise than
39529 * alternatives. The "+str" will convert a string containing only a
39530 * number directly to a Number, or NaN for other strings. Thus, if the
39531 * conversion succeeds, we use it (this is the milliseconds-since-epoch
39532 * case). Otherwise, we pass the string directly to the Date
39533 * constructor to parse.
39534 */
39535 var numeric = +str;
39536 if (!isNaN(numeric)) {
39537 return (new Date(numeric));
39538 } else {
39539 return (new Date(str));
39540 }
39541}
39542
39543
39544/*
39545 * Number.*_SAFE_INTEGER isn't present before node v0.12, so we hardcode
39546 * the ES6 definitions here, while allowing for them to someday be higher.
39547 */
39548var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || 9007199254740991;
39549var MIN_SAFE_INTEGER = Number.MIN_SAFE_INTEGER || -9007199254740991;
39550
39551
39552/*
39553 * Default options for parseInteger().
39554 */
39555var PI_DEFAULTS = {
39556 base: 10,
39557 allowSign: true,
39558 allowPrefix: false,
39559 allowTrailing: false,
39560 allowImprecise: false,
39561 trimWhitespace: false,
39562 leadingZeroIsOctal: false
39563};
39564
39565var CP_0 = 0x30;
39566var CP_9 = 0x39;
39567
39568var CP_A = 0x41;
39569var CP_B = 0x42;
39570var CP_O = 0x4f;
39571var CP_T = 0x54;
39572var CP_X = 0x58;
39573var CP_Z = 0x5a;
39574
39575var CP_a = 0x61;
39576var CP_b = 0x62;
39577var CP_o = 0x6f;
39578var CP_t = 0x74;
39579var CP_x = 0x78;
39580var CP_z = 0x7a;
39581
39582var PI_CONV_DEC = 0x30;
39583var PI_CONV_UC = 0x37;
39584var PI_CONV_LC = 0x57;
39585
39586
39587/*
39588 * A stricter version of parseInt() that provides options for changing what
39589 * is an acceptable string (for example, disallowing trailing characters).
39590 */
39591function parseInteger(str, uopts)
39592{
39593 mod_assert.string(str, 'str');
39594 mod_assert.optionalObject(uopts, 'options');
39595
39596 var baseOverride = false;
39597 var options = PI_DEFAULTS;
39598
39599 if (uopts) {
39600 baseOverride = hasKey(uopts, 'base');
39601 options = mergeObjects(options, uopts);
39602 mod_assert.number(options.base, 'options.base');
39603 mod_assert.ok(options.base >= 2, 'options.base >= 2');
39604 mod_assert.ok(options.base <= 36, 'options.base <= 36');
39605 mod_assert.bool(options.allowSign, 'options.allowSign');
39606 mod_assert.bool(options.allowPrefix, 'options.allowPrefix');
39607 mod_assert.bool(options.allowTrailing,
39608 'options.allowTrailing');
39609 mod_assert.bool(options.allowImprecise,
39610 'options.allowImprecise');
39611 mod_assert.bool(options.trimWhitespace,
39612 'options.trimWhitespace');
39613 mod_assert.bool(options.leadingZeroIsOctal,
39614 'options.leadingZeroIsOctal');
39615
39616 if (options.leadingZeroIsOctal) {
39617 mod_assert.ok(!baseOverride,
39618 '"base" and "leadingZeroIsOctal" are ' +
39619 'mutually exclusive');
39620 }
39621 }
39622
39623 var c;
39624 var pbase = -1;
39625 var base = options.base;
39626 var start;
39627 var mult = 1;
39628 var value = 0;
39629 var idx = 0;
39630 var len = str.length;
39631
39632 /* Trim any whitespace on the left side. */
39633 if (options.trimWhitespace) {
39634 while (idx < len && isSpace(str.charCodeAt(idx))) {
39635 ++idx;
39636 }
39637 }
39638
39639 /* Check the number for a leading sign. */
39640 if (options.allowSign) {
39641 if (str[idx] === '-') {
39642 idx += 1;
39643 mult = -1;
39644 } else if (str[idx] === '+') {
39645 idx += 1;
39646 }
39647 }
39648
39649 /* Parse the base-indicating prefix if there is one. */
39650 if (str[idx] === '0') {
39651 if (options.allowPrefix) {
39652 pbase = prefixToBase(str.charCodeAt(idx + 1));
39653 if (pbase !== -1 && (!baseOverride || pbase === base)) {
39654 base = pbase;
39655 idx += 2;
39656 }
39657 }
39658
39659 if (pbase === -1 && options.leadingZeroIsOctal) {
39660 base = 8;
39661 }
39662 }
39663
39664 /* Parse the actual digits. */
39665 for (start = idx; idx < len; ++idx) {
39666 c = translateDigit(str.charCodeAt(idx));
39667 if (c !== -1 && c < base) {
39668 value *= base;
39669 value += c;
39670 } else {
39671 break;
39672 }
39673 }
39674
39675 /* If we didn't parse any digits, we have an invalid number. */
39676 if (start === idx) {
39677 return (new Error('invalid number: ' + JSON.stringify(str)));
39678 }
39679
39680 /* Trim any whitespace on the right side. */
39681 if (options.trimWhitespace) {
39682 while (idx < len && isSpace(str.charCodeAt(idx))) {
39683 ++idx;
39684 }
39685 }
39686
39687 /* Check for trailing characters. */
39688 if (idx < len && !options.allowTrailing) {
39689 return (new Error('trailing characters after number: ' +
39690 JSON.stringify(str.slice(idx))));
39691 }
39692
39693 /* If our value is 0, we return now, to avoid returning -0. */
39694 if (value === 0) {
39695 return (0);
39696 }
39697
39698 /* Calculate our final value. */
39699 var result = value * mult;
39700
39701 /*
39702 * If the string represents a value that cannot be precisely represented
39703 * by JavaScript, then we want to check that:
39704 *
39705 * - We never increased the value past MAX_SAFE_INTEGER
39706 * - We don't make the result negative and below MIN_SAFE_INTEGER
39707 *
39708 * Because we only ever increment the value during parsing, there's no
39709 * chance of moving past MAX_SAFE_INTEGER and then dropping below it
39710 * again, losing precision in the process. This means that we only need
39711 * to do our checks here, at the end.
39712 */
39713 if (!options.allowImprecise &&
39714 (value > MAX_SAFE_INTEGER || result < MIN_SAFE_INTEGER)) {
39715 return (new Error('number is outside of the supported range: ' +
39716 JSON.stringify(str.slice(start, idx))));
39717 }
39718
39719 return (result);
39720}
39721
39722
39723/*
39724 * Interpret a character code as a base-36 digit.
39725 */
39726function translateDigit(d)
39727{
39728 if (d >= CP_0 && d <= CP_9) {
39729 /* '0' to '9' -> 0 to 9 */
39730 return (d - PI_CONV_DEC);
39731 } else if (d >= CP_A && d <= CP_Z) {
39732 /* 'A' - 'Z' -> 10 to 35 */
39733 return (d - PI_CONV_UC);
39734 } else if (d >= CP_a && d <= CP_z) {
39735 /* 'a' - 'z' -> 10 to 35 */
39736 return (d - PI_CONV_LC);
39737 } else {
39738 /* Invalid character code */
39739 return (-1);
39740 }
39741}
39742
39743
39744/*
39745 * Test if a value matches the ECMAScript definition of trimmable whitespace.
39746 */
39747function isSpace(c)
39748{
39749 return (c === 0x20) ||
39750 (c >= 0x0009 && c <= 0x000d) ||
39751 (c === 0x00a0) ||
39752 (c === 0x1680) ||
39753 (c === 0x180e) ||
39754 (c >= 0x2000 && c <= 0x200a) ||
39755 (c === 0x2028) ||
39756 (c === 0x2029) ||
39757 (c === 0x202f) ||
39758 (c === 0x205f) ||
39759 (c === 0x3000) ||
39760 (c === 0xfeff);
39761}
39762
39763
39764/*
39765 * Determine which base a character indicates (e.g., 'x' indicates hex).
39766 */
39767function prefixToBase(c)
39768{
39769 if (c === CP_b || c === CP_B) {
39770 /* 0b/0B (binary) */
39771 return (2);
39772 } else if (c === CP_o || c === CP_O) {
39773 /* 0o/0O (octal) */
39774 return (8);
39775 } else if (c === CP_t || c === CP_T) {
39776 /* 0t/0T (decimal) */
39777 return (10);
39778 } else if (c === CP_x || c === CP_X) {
39779 /* 0x/0X (hexadecimal) */
39780 return (16);
39781 } else {
39782 /* Not a meaningful character */
39783 return (-1);
39784 }
39785}
39786
39787
39788function validateJsonObjectJS(schema, input)
39789{
39790 var report = mod_jsonschema.validate(input, schema);
39791
39792 if (report.errors.length === 0)
39793 return (null);
39794
39795 /* Currently, we only do anything useful with the first error. */
39796 var error = report.errors[0];
39797
39798 /* The failed property is given by a URI with an irrelevant prefix. */
39799 var propname = error['property'];
39800 var reason = error['message'].toLowerCase();
39801 var i, j;
39802
39803 /*
39804 * There's at least one case where the property error message is
39805 * confusing at best. We work around this here.
39806 */
39807 if ((i = reason.indexOf('the property ')) != -1 &&
39808 (j = reason.indexOf(' is not defined in the schema and the ' +
39809 'schema does not allow additional properties')) != -1) {
39810 i += 'the property '.length;
39811 if (propname === '')
39812 propname = reason.substr(i, j - i);
39813 else
39814 propname = propname + '.' + reason.substr(i, j - i);
39815
39816 reason = 'unsupported property';
39817 }
39818
39819 var rv = new mod_verror.VError('property "%s": %s', propname, reason);
39820 rv.jsv_details = error;
39821 return (rv);
39822}
39823
39824function randElt(arr)
39825{
39826 mod_assert.ok(Array.isArray(arr) && arr.length > 0,
39827 'randElt argument must be a non-empty array');
39828
39829 return (arr[Math.floor(Math.random() * arr.length)]);
39830}
39831
39832function assertHrtime(a)
39833{
39834 mod_assert.ok(a[0] >= 0 && a[1] >= 0,
39835 'negative numbers not allowed in hrtimes');
39836 mod_assert.ok(a[1] < 1e9, 'nanoseconds column overflow');
39837}
39838
39839/*
39840 * Compute the time elapsed between hrtime readings A and B, where A is later
39841 * than B. hrtime readings come from Node's process.hrtime(). There is no
39842 * defined way to represent negative deltas, so it's illegal to diff B from A
39843 * where the time denoted by B is later than the time denoted by A. If this
39844 * becomes valuable, we can define a representation and extend the
39845 * implementation to support it.
39846 */
39847function hrtimeDiff(a, b)
39848{
39849 assertHrtime(a);
39850 assertHrtime(b);
39851 mod_assert.ok(a[0] > b[0] || (a[0] == b[0] && a[1] >= b[1]),
39852 'negative differences not allowed');
39853
39854 var rv = [ a[0] - b[0], 0 ];
39855
39856 if (a[1] >= b[1]) {
39857 rv[1] = a[1] - b[1];
39858 } else {
39859 rv[0]--;
39860 rv[1] = 1e9 - (b[1] - a[1]);
39861 }
39862
39863 return (rv);
39864}
39865
39866/*
39867 * Convert a hrtime reading from the array format returned by Node's
39868 * process.hrtime() into a scalar number of nanoseconds.
39869 */
39870function hrtimeNanosec(a)
39871{
39872 assertHrtime(a);
39873
39874 return (Math.floor(a[0] * 1e9 + a[1]));
39875}
39876
39877/*
39878 * Convert a hrtime reading from the array format returned by Node's
39879 * process.hrtime() into a scalar number of microseconds.
39880 */
39881function hrtimeMicrosec(a)
39882{
39883 assertHrtime(a);
39884
39885 return (Math.floor(a[0] * 1e6 + a[1] / 1e3));
39886}
39887
39888/*
39889 * Convert a hrtime reading from the array format returned by Node's
39890 * process.hrtime() into a scalar number of milliseconds.
39891 */
39892function hrtimeMillisec(a)
39893{
39894 assertHrtime(a);
39895
39896 return (Math.floor(a[0] * 1e3 + a[1] / 1e6));
39897}
39898
39899/*
39900 * Add two hrtime readings A and B, overwriting A with the result of the
39901 * addition. This function is useful for accumulating several hrtime intervals
39902 * into a counter. Returns A.
39903 */
39904function hrtimeAccum(a, b)
39905{
39906 assertHrtime(a);
39907 assertHrtime(b);
39908
39909 /*
39910 * Accumulate the nanosecond component.
39911 */
39912 a[1] += b[1];
39913 if (a[1] >= 1e9) {
39914 /*
39915 * The nanosecond component overflowed, so carry to the seconds
39916 * field.
39917 */
39918 a[0]++;
39919 a[1] -= 1e9;
39920 }
39921
39922 /*
39923 * Accumulate the seconds component.
39924 */
39925 a[0] += b[0];
39926
39927 return (a);
39928}
39929
39930/*
39931 * Add two hrtime readings A and B, returning the result as a new hrtime array.
39932 * Does not modify either input argument.
39933 */
39934function hrtimeAdd(a, b)
39935{
39936 assertHrtime(a);
39937
39938 var rv = [ a[0], a[1] ];
39939
39940 return (hrtimeAccum(rv, b));
39941}
39942
39943
39944/*
39945 * Check an object for unexpected properties. Accepts the object to check, and
39946 * an array of allowed property names (strings). Returns an array of key names
39947 * that were found on the object, but did not appear in the list of allowed
39948 * properties. If no properties were found, the returned array will be of
39949 * zero length.
39950 */
39951function extraProperties(obj, allowed)
39952{
39953 mod_assert.ok(typeof (obj) === 'object' && obj !== null,
39954 'obj argument must be a non-null object');
39955 mod_assert.ok(Array.isArray(allowed),
39956 'allowed argument must be an array of strings');
39957 for (var i = 0; i < allowed.length; i++) {
39958 mod_assert.ok(typeof (allowed[i]) === 'string',
39959 'allowed argument must be an array of strings');
39960 }
39961
39962 return (Object.keys(obj).filter(function (key) {
39963 return (allowed.indexOf(key) === -1);
39964 }));
39965}
39966
39967/*
39968 * Given three sets of properties "provided" (may be undefined), "overrides"
39969 * (required), and "defaults" (may be undefined), construct an object containing
39970 * the union of these sets with "overrides" overriding "provided", and
39971 * "provided" overriding "defaults". None of the input objects are modified.
39972 */
39973function mergeObjects(provided, overrides, defaults)
39974{
39975 var rv, k;
39976
39977 rv = {};
39978 if (defaults) {
39979 for (k in defaults)
39980 rv[k] = defaults[k];
39981 }
39982
39983 if (provided) {
39984 for (k in provided)
39985 rv[k] = provided[k];
39986 }
39987
39988 if (overrides) {
39989 for (k in overrides)
39990 rv[k] = overrides[k];
39991 }
39992
39993 return (rv);
39994}
39995
39996},{"assert-plus":67,"extsprintf":162,"json-schema":217,"util":397,"verror":401}],220:[function(require,module,exports){
39997var root = require('./_root');
39998
39999/** Built-in value references. */
40000var Symbol = root.Symbol;
40001
40002module.exports = Symbol;
40003
40004},{"./_root":225}],221:[function(require,module,exports){
40005var Symbol = require('./_Symbol'),
40006 getRawTag = require('./_getRawTag'),
40007 objectToString = require('./_objectToString');
40008
40009/** `Object#toString` result references. */
40010var nullTag = '[object Null]',
40011 undefinedTag = '[object Undefined]';
40012
40013/** Built-in value references. */
40014var symToStringTag = Symbol ? Symbol.toStringTag : undefined;
40015
40016/**
40017 * The base implementation of `getTag` without fallbacks for buggy environments.
40018 *
40019 * @private
40020 * @param {*} value The value to query.
40021 * @returns {string} Returns the `toStringTag`.
40022 */
40023function baseGetTag(value) {
40024 if (value == null) {
40025 return value === undefined ? undefinedTag : nullTag;
40026 }
40027 return (symToStringTag && symToStringTag in Object(value))
40028 ? getRawTag(value)
40029 : objectToString(value);
40030}
40031
40032module.exports = baseGetTag;
40033
40034},{"./_Symbol":220,"./_getRawTag":223,"./_objectToString":224}],222:[function(require,module,exports){
40035(function (global){
40036/** Detect free variable `global` from Node.js. */
40037var freeGlobal = typeof global == 'object' && global && global.Object === Object && global;
40038
40039module.exports = freeGlobal;
40040
40041}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
40042},{}],223:[function(require,module,exports){
40043var Symbol = require('./_Symbol');
40044
40045/** Used for built-in method references. */
40046var objectProto = Object.prototype;
40047
40048/** Used to check objects for own properties. */
40049var hasOwnProperty = objectProto.hasOwnProperty;
40050
40051/**
40052 * Used to resolve the
40053 * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
40054 * of values.
40055 */
40056var nativeObjectToString = objectProto.toString;
40057
40058/** Built-in value references. */
40059var symToStringTag = Symbol ? Symbol.toStringTag : undefined;
40060
40061/**
40062 * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values.
40063 *
40064 * @private
40065 * @param {*} value The value to query.
40066 * @returns {string} Returns the raw `toStringTag`.
40067 */
40068function getRawTag(value) {
40069 var isOwn = hasOwnProperty.call(value, symToStringTag),
40070 tag = value[symToStringTag];
40071
40072 try {
40073 value[symToStringTag] = undefined;
40074 var unmasked = true;
40075 } catch (e) {}
40076
40077 var result = nativeObjectToString.call(value);
40078 if (unmasked) {
40079 if (isOwn) {
40080 value[symToStringTag] = tag;
40081 } else {
40082 delete value[symToStringTag];
40083 }
40084 }
40085 return result;
40086}
40087
40088module.exports = getRawTag;
40089
40090},{"./_Symbol":220}],224:[function(require,module,exports){
40091/** Used for built-in method references. */
40092var objectProto = Object.prototype;
40093
40094/**
40095 * Used to resolve the
40096 * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
40097 * of values.
40098 */
40099var nativeObjectToString = objectProto.toString;
40100
40101/**
40102 * Converts `value` to a string using `Object.prototype.toString`.
40103 *
40104 * @private
40105 * @param {*} value The value to convert.
40106 * @returns {string} Returns the converted string.
40107 */
40108function objectToString(value) {
40109 return nativeObjectToString.call(value);
40110}
40111
40112module.exports = objectToString;
40113
40114},{}],225:[function(require,module,exports){
40115var freeGlobal = require('./_freeGlobal');
40116
40117/** Detect free variable `self`. */
40118var freeSelf = typeof self == 'object' && self && self.Object === Object && self;
40119
40120/** Used as a reference to the global object. */
40121var root = freeGlobal || freeSelf || Function('return this')();
40122
40123module.exports = root;
40124
40125},{"./_freeGlobal":222}],226:[function(require,module,exports){
40126/**
40127 * Checks if `value` is classified as an `Array` object.
40128 *
40129 * @static
40130 * @memberOf _
40131 * @since 0.1.0
40132 * @category Lang
40133 * @param {*} value The value to check.
40134 * @returns {boolean} Returns `true` if `value` is an array, else `false`.
40135 * @example
40136 *
40137 * _.isArray([1, 2, 3]);
40138 * // => true
40139 *
40140 * _.isArray(document.body.children);
40141 * // => false
40142 *
40143 * _.isArray('abc');
40144 * // => false
40145 *
40146 * _.isArray(_.noop);
40147 * // => false
40148 */
40149var isArray = Array.isArray;
40150
40151module.exports = isArray;
40152
40153},{}],227:[function(require,module,exports){
40154var baseGetTag = require('./_baseGetTag'),
40155 isObject = require('./isObject');
40156
40157/** `Object#toString` result references. */
40158var asyncTag = '[object AsyncFunction]',
40159 funcTag = '[object Function]',
40160 genTag = '[object GeneratorFunction]',
40161 proxyTag = '[object Proxy]';
40162
40163/**
40164 * Checks if `value` is classified as a `Function` object.
40165 *
40166 * @static
40167 * @memberOf _
40168 * @since 0.1.0
40169 * @category Lang
40170 * @param {*} value The value to check.
40171 * @returns {boolean} Returns `true` if `value` is a function, else `false`.
40172 * @example
40173 *
40174 * _.isFunction(_);
40175 * // => true
40176 *
40177 * _.isFunction(/abc/);
40178 * // => false
40179 */
40180function isFunction(value) {
40181 if (!isObject(value)) {
40182 return false;
40183 }
40184 // The use of `Object#toString` avoids issues with the `typeof` operator
40185 // in Safari 9 which returns 'object' for typed arrays and other constructors.
40186 var tag = baseGetTag(value);
40187 return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag;
40188}
40189
40190module.exports = isFunction;
40191
40192},{"./_baseGetTag":221,"./isObject":228}],228:[function(require,module,exports){
40193/**
40194 * Checks if `value` is the
40195 * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)
40196 * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
40197 *
40198 * @static
40199 * @memberOf _
40200 * @since 0.1.0
40201 * @category Lang
40202 * @param {*} value The value to check.
40203 * @returns {boolean} Returns `true` if `value` is an object, else `false`.
40204 * @example
40205 *
40206 * _.isObject({});
40207 * // => true
40208 *
40209 * _.isObject([1, 2, 3]);
40210 * // => true
40211 *
40212 * _.isObject(_.noop);
40213 * // => true
40214 *
40215 * _.isObject(null);
40216 * // => false
40217 */
40218function isObject(value) {
40219 var type = typeof value;
40220 return value != null && (type == 'object' || type == 'function');
40221}
40222
40223module.exports = isObject;
40224
40225},{}],229:[function(require,module,exports){
40226/**
40227 * Checks if `value` is object-like. A value is object-like if it's not `null`
40228 * and has a `typeof` result of "object".
40229 *
40230 * @static
40231 * @memberOf _
40232 * @since 4.0.0
40233 * @category Lang
40234 * @param {*} value The value to check.
40235 * @returns {boolean} Returns `true` if `value` is object-like, else `false`.
40236 * @example
40237 *
40238 * _.isObjectLike({});
40239 * // => true
40240 *
40241 * _.isObjectLike([1, 2, 3]);
40242 * // => true
40243 *
40244 * _.isObjectLike(_.noop);
40245 * // => false
40246 *
40247 * _.isObjectLike(null);
40248 * // => false
40249 */
40250function isObjectLike(value) {
40251 return value != null && typeof value == 'object';
40252}
40253
40254module.exports = isObjectLike;
40255
40256},{}],230:[function(require,module,exports){
40257var baseGetTag = require('./_baseGetTag'),
40258 isArray = require('./isArray'),
40259 isObjectLike = require('./isObjectLike');
40260
40261/** `Object#toString` result references. */
40262var stringTag = '[object String]';
40263
40264/**
40265 * Checks if `value` is classified as a `String` primitive or object.
40266 *
40267 * @static
40268 * @since 0.1.0
40269 * @memberOf _
40270 * @category Lang
40271 * @param {*} value The value to check.
40272 * @returns {boolean} Returns `true` if `value` is a string, else `false`.
40273 * @example
40274 *
40275 * _.isString('abc');
40276 * // => true
40277 *
40278 * _.isString(1);
40279 * // => false
40280 */
40281function isString(value) {
40282 return typeof value == 'string' ||
40283 (!isArray(value) && isObjectLike(value) && baseGetTag(value) == stringTag);
40284}
40285
40286module.exports = isString;
40287
40288},{"./_baseGetTag":221,"./isArray":226,"./isObjectLike":229}],231:[function(require,module,exports){
40289/**
40290 * Checks if `value` is `undefined`.
40291 *
40292 * @static
40293 * @since 0.1.0
40294 * @memberOf _
40295 * @category Lang
40296 * @param {*} value The value to check.
40297 * @returns {boolean} Returns `true` if `value` is `undefined`, else `false`.
40298 * @example
40299 *
40300 * _.isUndefined(void 0);
40301 * // => true
40302 *
40303 * _.isUndefined(null);
40304 * // => false
40305 */
40306function isUndefined(value) {
40307 return value === undefined;
40308}
40309
40310module.exports = isUndefined;
40311
40312},{}],232:[function(require,module,exports){
40313'use strict'
40314var inherits = require('inherits')
40315var HashBase = require('hash-base')
40316var Buffer = require('safe-buffer').Buffer
40317
40318var ARRAY16 = new Array(16)
40319
40320function MD5 () {
40321 HashBase.call(this, 64)
40322
40323 // state
40324 this._a = 0x67452301
40325 this._b = 0xefcdab89
40326 this._c = 0x98badcfe
40327 this._d = 0x10325476
40328}
40329
40330inherits(MD5, HashBase)
40331
40332MD5.prototype._update = function () {
40333 var M = ARRAY16
40334 for (var i = 0; i < 16; ++i) M[i] = this._block.readInt32LE(i * 4)
40335
40336 var a = this._a
40337 var b = this._b
40338 var c = this._c
40339 var d = this._d
40340
40341 a = fnF(a, b, c, d, M[0], 0xd76aa478, 7)
40342 d = fnF(d, a, b, c, M[1], 0xe8c7b756, 12)
40343 c = fnF(c, d, a, b, M[2], 0x242070db, 17)
40344 b = fnF(b, c, d, a, M[3], 0xc1bdceee, 22)
40345 a = fnF(a, b, c, d, M[4], 0xf57c0faf, 7)
40346 d = fnF(d, a, b, c, M[5], 0x4787c62a, 12)
40347 c = fnF(c, d, a, b, M[6], 0xa8304613, 17)
40348 b = fnF(b, c, d, a, M[7], 0xfd469501, 22)
40349 a = fnF(a, b, c, d, M[8], 0x698098d8, 7)
40350 d = fnF(d, a, b, c, M[9], 0x8b44f7af, 12)
40351 c = fnF(c, d, a, b, M[10], 0xffff5bb1, 17)
40352 b = fnF(b, c, d, a, M[11], 0x895cd7be, 22)
40353 a = fnF(a, b, c, d, M[12], 0x6b901122, 7)
40354 d = fnF(d, a, b, c, M[13], 0xfd987193, 12)
40355 c = fnF(c, d, a, b, M[14], 0xa679438e, 17)
40356 b = fnF(b, c, d, a, M[15], 0x49b40821, 22)
40357
40358 a = fnG(a, b, c, d, M[1], 0xf61e2562, 5)
40359 d = fnG(d, a, b, c, M[6], 0xc040b340, 9)
40360 c = fnG(c, d, a, b, M[11], 0x265e5a51, 14)
40361 b = fnG(b, c, d, a, M[0], 0xe9b6c7aa, 20)
40362 a = fnG(a, b, c, d, M[5], 0xd62f105d, 5)
40363 d = fnG(d, a, b, c, M[10], 0x02441453, 9)
40364 c = fnG(c, d, a, b, M[15], 0xd8a1e681, 14)
40365 b = fnG(b, c, d, a, M[4], 0xe7d3fbc8, 20)
40366 a = fnG(a, b, c, d, M[9], 0x21e1cde6, 5)
40367 d = fnG(d, a, b, c, M[14], 0xc33707d6, 9)
40368 c = fnG(c, d, a, b, M[3], 0xf4d50d87, 14)
40369 b = fnG(b, c, d, a, M[8], 0x455a14ed, 20)
40370 a = fnG(a, b, c, d, M[13], 0xa9e3e905, 5)
40371 d = fnG(d, a, b, c, M[2], 0xfcefa3f8, 9)
40372 c = fnG(c, d, a, b, M[7], 0x676f02d9, 14)
40373 b = fnG(b, c, d, a, M[12], 0x8d2a4c8a, 20)
40374
40375 a = fnH(a, b, c, d, M[5], 0xfffa3942, 4)
40376 d = fnH(d, a, b, c, M[8], 0x8771f681, 11)
40377 c = fnH(c, d, a, b, M[11], 0x6d9d6122, 16)
40378 b = fnH(b, c, d, a, M[14], 0xfde5380c, 23)
40379 a = fnH(a, b, c, d, M[1], 0xa4beea44, 4)
40380 d = fnH(d, a, b, c, M[4], 0x4bdecfa9, 11)
40381 c = fnH(c, d, a, b, M[7], 0xf6bb4b60, 16)
40382 b = fnH(b, c, d, a, M[10], 0xbebfbc70, 23)
40383 a = fnH(a, b, c, d, M[13], 0x289b7ec6, 4)
40384 d = fnH(d, a, b, c, M[0], 0xeaa127fa, 11)
40385 c = fnH(c, d, a, b, M[3], 0xd4ef3085, 16)
40386 b = fnH(b, c, d, a, M[6], 0x04881d05, 23)
40387 a = fnH(a, b, c, d, M[9], 0xd9d4d039, 4)
40388 d = fnH(d, a, b, c, M[12], 0xe6db99e5, 11)
40389 c = fnH(c, d, a, b, M[15], 0x1fa27cf8, 16)
40390 b = fnH(b, c, d, a, M[2], 0xc4ac5665, 23)
40391
40392 a = fnI(a, b, c, d, M[0], 0xf4292244, 6)
40393 d = fnI(d, a, b, c, M[7], 0x432aff97, 10)
40394 c = fnI(c, d, a, b, M[14], 0xab9423a7, 15)
40395 b = fnI(b, c, d, a, M[5], 0xfc93a039, 21)
40396 a = fnI(a, b, c, d, M[12], 0x655b59c3, 6)
40397 d = fnI(d, a, b, c, M[3], 0x8f0ccc92, 10)
40398 c = fnI(c, d, a, b, M[10], 0xffeff47d, 15)
40399 b = fnI(b, c, d, a, M[1], 0x85845dd1, 21)
40400 a = fnI(a, b, c, d, M[8], 0x6fa87e4f, 6)
40401 d = fnI(d, a, b, c, M[15], 0xfe2ce6e0, 10)
40402 c = fnI(c, d, a, b, M[6], 0xa3014314, 15)
40403 b = fnI(b, c, d, a, M[13], 0x4e0811a1, 21)
40404 a = fnI(a, b, c, d, M[4], 0xf7537e82, 6)
40405 d = fnI(d, a, b, c, M[11], 0xbd3af235, 10)
40406 c = fnI(c, d, a, b, M[2], 0x2ad7d2bb, 15)
40407 b = fnI(b, c, d, a, M[9], 0xeb86d391, 21)
40408
40409 this._a = (this._a + a) | 0
40410 this._b = (this._b + b) | 0
40411 this._c = (this._c + c) | 0
40412 this._d = (this._d + d) | 0
40413}
40414
40415MD5.prototype._digest = function () {
40416 // create padding and handle blocks
40417 this._block[this._blockOffset++] = 0x80
40418 if (this._blockOffset > 56) {
40419 this._block.fill(0, this._blockOffset, 64)
40420 this._update()
40421 this._blockOffset = 0
40422 }
40423
40424 this._block.fill(0, this._blockOffset, 56)
40425 this._block.writeUInt32LE(this._length[0], 56)
40426 this._block.writeUInt32LE(this._length[1], 60)
40427 this._update()
40428
40429 // produce result
40430 var buffer = Buffer.allocUnsafe(16)
40431 buffer.writeInt32LE(this._a, 0)
40432 buffer.writeInt32LE(this._b, 4)
40433 buffer.writeInt32LE(this._c, 8)
40434 buffer.writeInt32LE(this._d, 12)
40435 return buffer
40436}
40437
40438function rotl (x, n) {
40439 return (x << n) | (x >>> (32 - n))
40440}
40441
40442function fnF (a, b, c, d, m, k, s) {
40443 return (rotl((a + ((b & c) | ((~b) & d)) + m + k) | 0, s) + b) | 0
40444}
40445
40446function fnG (a, b, c, d, m, k, s) {
40447 return (rotl((a + ((b & d) | (c & (~d))) + m + k) | 0, s) + b) | 0
40448}
40449
40450function fnH (a, b, c, d, m, k, s) {
40451 return (rotl((a + (b ^ c ^ d) + m + k) | 0, s) + b) | 0
40452}
40453
40454function fnI (a, b, c, d, m, k, s) {
40455 return (rotl((a + ((c ^ (b | (~d)))) + m + k) | 0, s) + b) | 0
40456}
40457
40458module.exports = MD5
40459
40460},{"hash-base":189,"inherits":210,"safe-buffer":325}],233:[function(require,module,exports){
40461var bn = require('bn.js');
40462var brorand = require('brorand');
40463
40464function MillerRabin(rand) {
40465 this.rand = rand || new brorand.Rand();
40466}
40467module.exports = MillerRabin;
40468
40469MillerRabin.create = function create(rand) {
40470 return new MillerRabin(rand);
40471};
40472
40473MillerRabin.prototype._randbelow = function _randbelow(n) {
40474 var len = n.bitLength();
40475 var min_bytes = Math.ceil(len / 8);
40476
40477 // Generage random bytes until a number less than n is found.
40478 // This ensures that 0..n-1 have an equal probability of being selected.
40479 do
40480 var a = new bn(this.rand.generate(min_bytes));
40481 while (a.cmp(n) >= 0);
40482
40483 return a;
40484};
40485
40486MillerRabin.prototype._randrange = function _randrange(start, stop) {
40487 // Generate a random number greater than or equal to start and less than stop.
40488 var size = stop.sub(start);
40489 return start.add(this._randbelow(size));
40490};
40491
40492MillerRabin.prototype.test = function test(n, k, cb) {
40493 var len = n.bitLength();
40494 var red = bn.mont(n);
40495 var rone = new bn(1).toRed(red);
40496
40497 if (!k)
40498 k = Math.max(1, (len / 48) | 0);
40499
40500 // Find d and s, (n - 1) = (2 ^ s) * d;
40501 var n1 = n.subn(1);
40502 for (var s = 0; !n1.testn(s); s++) {}
40503 var d = n.shrn(s);
40504
40505 var rn1 = n1.toRed(red);
40506
40507 var prime = true;
40508 for (; k > 0; k--) {
40509 var a = this._randrange(new bn(2), n1);
40510 if (cb)
40511 cb(a);
40512
40513 var x = a.toRed(red).redPow(d);
40514 if (x.cmp(rone) === 0 || x.cmp(rn1) === 0)
40515 continue;
40516
40517 for (var i = 1; i < s; i++) {
40518 x = x.redSqr();
40519
40520 if (x.cmp(rone) === 0)
40521 return false;
40522 if (x.cmp(rn1) === 0)
40523 break;
40524 }
40525
40526 if (i === s)
40527 return false;
40528 }
40529
40530 return prime;
40531};
40532
40533MillerRabin.prototype.getDivisor = function getDivisor(n, k) {
40534 var len = n.bitLength();
40535 var red = bn.mont(n);
40536 var rone = new bn(1).toRed(red);
40537
40538 if (!k)
40539 k = Math.max(1, (len / 48) | 0);
40540
40541 // Find d and s, (n - 1) = (2 ^ s) * d;
40542 var n1 = n.subn(1);
40543 for (var s = 0; !n1.testn(s); s++) {}
40544 var d = n.shrn(s);
40545
40546 var rn1 = n1.toRed(red);
40547
40548 for (; k > 0; k--) {
40549 var a = this._randrange(new bn(2), n1);
40550
40551 var g = n.gcd(a);
40552 if (g.cmpn(1) !== 0)
40553 return g;
40554
40555 var x = a.toRed(red).redPow(d);
40556 if (x.cmp(rone) === 0 || x.cmp(rn1) === 0)
40557 continue;
40558
40559 for (var i = 1; i < s; i++) {
40560 x = x.redSqr();
40561
40562 if (x.cmp(rone) === 0)
40563 return x.fromRed().subn(1).gcd(n);
40564 if (x.cmp(rn1) === 0)
40565 break;
40566 }
40567
40568 if (i === s) {
40569 x = x.redSqr();
40570 return x.fromRed().subn(1).gcd(n);
40571 }
40572 }
40573
40574 return false;
40575};
40576
40577},{"bn.js":80,"brorand":81}],234:[function(require,module,exports){
40578module.exports={
40579 "application/1d-interleaved-parityfec": {
40580 "source": "iana"
40581 },
40582 "application/3gpdash-qoe-report+xml": {
40583 "source": "iana",
40584 "compressible": true
40585 },
40586 "application/3gpp-ims+xml": {
40587 "source": "iana",
40588 "compressible": true
40589 },
40590 "application/a2l": {
40591 "source": "iana"
40592 },
40593 "application/activemessage": {
40594 "source": "iana"
40595 },
40596 "application/activity+json": {
40597 "source": "iana",
40598 "compressible": true
40599 },
40600 "application/alto-costmap+json": {
40601 "source": "iana",
40602 "compressible": true
40603 },
40604 "application/alto-costmapfilter+json": {
40605 "source": "iana",
40606 "compressible": true
40607 },
40608 "application/alto-directory+json": {
40609 "source": "iana",
40610 "compressible": true
40611 },
40612 "application/alto-endpointcost+json": {
40613 "source": "iana",
40614 "compressible": true
40615 },
40616 "application/alto-endpointcostparams+json": {
40617 "source": "iana",
40618 "compressible": true
40619 },
40620 "application/alto-endpointprop+json": {
40621 "source": "iana",
40622 "compressible": true
40623 },
40624 "application/alto-endpointpropparams+json": {
40625 "source": "iana",
40626 "compressible": true
40627 },
40628 "application/alto-error+json": {
40629 "source": "iana",
40630 "compressible": true
40631 },
40632 "application/alto-networkmap+json": {
40633 "source": "iana",
40634 "compressible": true
40635 },
40636 "application/alto-networkmapfilter+json": {
40637 "source": "iana",
40638 "compressible": true
40639 },
40640 "application/aml": {
40641 "source": "iana"
40642 },
40643 "application/andrew-inset": {
40644 "source": "iana",
40645 "extensions": ["ez"]
40646 },
40647 "application/applefile": {
40648 "source": "iana"
40649 },
40650 "application/applixware": {
40651 "source": "apache",
40652 "extensions": ["aw"]
40653 },
40654 "application/atf": {
40655 "source": "iana"
40656 },
40657 "application/atfx": {
40658 "source": "iana"
40659 },
40660 "application/atom+xml": {
40661 "source": "iana",
40662 "compressible": true,
40663 "extensions": ["atom"]
40664 },
40665 "application/atomcat+xml": {
40666 "source": "iana",
40667 "compressible": true,
40668 "extensions": ["atomcat"]
40669 },
40670 "application/atomdeleted+xml": {
40671 "source": "iana",
40672 "compressible": true
40673 },
40674 "application/atomicmail": {
40675 "source": "iana"
40676 },
40677 "application/atomsvc+xml": {
40678 "source": "iana",
40679 "compressible": true,
40680 "extensions": ["atomsvc"]
40681 },
40682 "application/atsc-dwd+xml": {
40683 "source": "iana",
40684 "compressible": true
40685 },
40686 "application/atsc-held+xml": {
40687 "source": "iana",
40688 "compressible": true
40689 },
40690 "application/atsc-rsat+xml": {
40691 "source": "iana",
40692 "compressible": true
40693 },
40694 "application/atxml": {
40695 "source": "iana"
40696 },
40697 "application/auth-policy+xml": {
40698 "source": "iana",
40699 "compressible": true
40700 },
40701 "application/bacnet-xdd+zip": {
40702 "source": "iana",
40703 "compressible": false
40704 },
40705 "application/batch-smtp": {
40706 "source": "iana"
40707 },
40708 "application/bdoc": {
40709 "compressible": false,
40710 "extensions": ["bdoc"]
40711 },
40712 "application/beep+xml": {
40713 "source": "iana",
40714 "compressible": true
40715 },
40716 "application/calendar+json": {
40717 "source": "iana",
40718 "compressible": true
40719 },
40720 "application/calendar+xml": {
40721 "source": "iana",
40722 "compressible": true
40723 },
40724 "application/call-completion": {
40725 "source": "iana"
40726 },
40727 "application/cals-1840": {
40728 "source": "iana"
40729 },
40730 "application/cbor": {
40731 "source": "iana"
40732 },
40733 "application/cccex": {
40734 "source": "iana"
40735 },
40736 "application/ccmp+xml": {
40737 "source": "iana",
40738 "compressible": true
40739 },
40740 "application/ccxml+xml": {
40741 "source": "iana",
40742 "compressible": true,
40743 "extensions": ["ccxml"]
40744 },
40745 "application/cdfx+xml": {
40746 "source": "iana",
40747 "compressible": true
40748 },
40749 "application/cdmi-capability": {
40750 "source": "iana",
40751 "extensions": ["cdmia"]
40752 },
40753 "application/cdmi-container": {
40754 "source": "iana",
40755 "extensions": ["cdmic"]
40756 },
40757 "application/cdmi-domain": {
40758 "source": "iana",
40759 "extensions": ["cdmid"]
40760 },
40761 "application/cdmi-object": {
40762 "source": "iana",
40763 "extensions": ["cdmio"]
40764 },
40765 "application/cdmi-queue": {
40766 "source": "iana",
40767 "extensions": ["cdmiq"]
40768 },
40769 "application/cdni": {
40770 "source": "iana"
40771 },
40772 "application/cea": {
40773 "source": "iana"
40774 },
40775 "application/cea-2018+xml": {
40776 "source": "iana",
40777 "compressible": true
40778 },
40779 "application/cellml+xml": {
40780 "source": "iana",
40781 "compressible": true
40782 },
40783 "application/cfw": {
40784 "source": "iana"
40785 },
40786 "application/clue_info+xml": {
40787 "source": "iana",
40788 "compressible": true
40789 },
40790 "application/cms": {
40791 "source": "iana"
40792 },
40793 "application/cnrp+xml": {
40794 "source": "iana",
40795 "compressible": true
40796 },
40797 "application/coap-group+json": {
40798 "source": "iana",
40799 "compressible": true
40800 },
40801 "application/coap-payload": {
40802 "source": "iana"
40803 },
40804 "application/commonground": {
40805 "source": "iana"
40806 },
40807 "application/conference-info+xml": {
40808 "source": "iana",
40809 "compressible": true
40810 },
40811 "application/cose": {
40812 "source": "iana"
40813 },
40814 "application/cose-key": {
40815 "source": "iana"
40816 },
40817 "application/cose-key-set": {
40818 "source": "iana"
40819 },
40820 "application/cpl+xml": {
40821 "source": "iana",
40822 "compressible": true
40823 },
40824 "application/csrattrs": {
40825 "source": "iana"
40826 },
40827 "application/csta+xml": {
40828 "source": "iana",
40829 "compressible": true
40830 },
40831 "application/cstadata+xml": {
40832 "source": "iana",
40833 "compressible": true
40834 },
40835 "application/csvm+json": {
40836 "source": "iana",
40837 "compressible": true
40838 },
40839 "application/cu-seeme": {
40840 "source": "apache",
40841 "extensions": ["cu"]
40842 },
40843 "application/cwt": {
40844 "source": "iana"
40845 },
40846 "application/cybercash": {
40847 "source": "iana"
40848 },
40849 "application/dart": {
40850 "compressible": true
40851 },
40852 "application/dash+xml": {
40853 "source": "iana",
40854 "compressible": true,
40855 "extensions": ["mpd"]
40856 },
40857 "application/dashdelta": {
40858 "source": "iana"
40859 },
40860 "application/davmount+xml": {
40861 "source": "iana",
40862 "compressible": true,
40863 "extensions": ["davmount"]
40864 },
40865 "application/dca-rft": {
40866 "source": "iana"
40867 },
40868 "application/dcd": {
40869 "source": "iana"
40870 },
40871 "application/dec-dx": {
40872 "source": "iana"
40873 },
40874 "application/dialog-info+xml": {
40875 "source": "iana",
40876 "compressible": true
40877 },
40878 "application/dicom": {
40879 "source": "iana"
40880 },
40881 "application/dicom+json": {
40882 "source": "iana",
40883 "compressible": true
40884 },
40885 "application/dicom+xml": {
40886 "source": "iana",
40887 "compressible": true
40888 },
40889 "application/dii": {
40890 "source": "iana"
40891 },
40892 "application/dit": {
40893 "source": "iana"
40894 },
40895 "application/dns": {
40896 "source": "iana"
40897 },
40898 "application/dns+json": {
40899 "source": "iana",
40900 "compressible": true
40901 },
40902 "application/dns-message": {
40903 "source": "iana"
40904 },
40905 "application/docbook+xml": {
40906 "source": "apache",
40907 "compressible": true,
40908 "extensions": ["dbk"]
40909 },
40910 "application/dskpp+xml": {
40911 "source": "iana",
40912 "compressible": true
40913 },
40914 "application/dssc+der": {
40915 "source": "iana",
40916 "extensions": ["dssc"]
40917 },
40918 "application/dssc+xml": {
40919 "source": "iana",
40920 "compressible": true,
40921 "extensions": ["xdssc"]
40922 },
40923 "application/dvcs": {
40924 "source": "iana"
40925 },
40926 "application/ecmascript": {
40927 "source": "iana",
40928 "compressible": true,
40929 "extensions": ["ecma","es"]
40930 },
40931 "application/edi-consent": {
40932 "source": "iana"
40933 },
40934 "application/edi-x12": {
40935 "source": "iana",
40936 "compressible": false
40937 },
40938 "application/edifact": {
40939 "source": "iana",
40940 "compressible": false
40941 },
40942 "application/efi": {
40943 "source": "iana"
40944 },
40945 "application/emergencycalldata.comment+xml": {
40946 "source": "iana",
40947 "compressible": true
40948 },
40949 "application/emergencycalldata.control+xml": {
40950 "source": "iana",
40951 "compressible": true
40952 },
40953 "application/emergencycalldata.deviceinfo+xml": {
40954 "source": "iana",
40955 "compressible": true
40956 },
40957 "application/emergencycalldata.ecall.msd": {
40958 "source": "iana"
40959 },
40960 "application/emergencycalldata.providerinfo+xml": {
40961 "source": "iana",
40962 "compressible": true
40963 },
40964 "application/emergencycalldata.serviceinfo+xml": {
40965 "source": "iana",
40966 "compressible": true
40967 },
40968 "application/emergencycalldata.subscriberinfo+xml": {
40969 "source": "iana",
40970 "compressible": true
40971 },
40972 "application/emergencycalldata.veds+xml": {
40973 "source": "iana",
40974 "compressible": true
40975 },
40976 "application/emma+xml": {
40977 "source": "iana",
40978 "compressible": true,
40979 "extensions": ["emma"]
40980 },
40981 "application/emotionml+xml": {
40982 "source": "iana",
40983 "compressible": true
40984 },
40985 "application/encaprtp": {
40986 "source": "iana"
40987 },
40988 "application/epp+xml": {
40989 "source": "iana",
40990 "compressible": true
40991 },
40992 "application/epub+zip": {
40993 "source": "iana",
40994 "compressible": false,
40995 "extensions": ["epub"]
40996 },
40997 "application/eshop": {
40998 "source": "iana"
40999 },
41000 "application/exi": {
41001 "source": "iana",
41002 "extensions": ["exi"]
41003 },
41004 "application/expect-ct-report+json": {
41005 "source": "iana",
41006 "compressible": true
41007 },
41008 "application/fastinfoset": {
41009 "source": "iana"
41010 },
41011 "application/fastsoap": {
41012 "source": "iana"
41013 },
41014 "application/fdt+xml": {
41015 "source": "iana",
41016 "compressible": true
41017 },
41018 "application/fhir+json": {
41019 "source": "iana",
41020 "compressible": true
41021 },
41022 "application/fhir+xml": {
41023 "source": "iana",
41024 "compressible": true
41025 },
41026 "application/fido.trusted-apps+json": {
41027 "compressible": true
41028 },
41029 "application/fits": {
41030 "source": "iana"
41031 },
41032 "application/font-sfnt": {
41033 "source": "iana"
41034 },
41035 "application/font-tdpfr": {
41036 "source": "iana",
41037 "extensions": ["pfr"]
41038 },
41039 "application/font-woff": {
41040 "source": "iana",
41041 "compressible": false
41042 },
41043 "application/framework-attributes+xml": {
41044 "source": "iana",
41045 "compressible": true
41046 },
41047 "application/geo+json": {
41048 "source": "iana",
41049 "compressible": true,
41050 "extensions": ["geojson"]
41051 },
41052 "application/geo+json-seq": {
41053 "source": "iana"
41054 },
41055 "application/geopackage+sqlite3": {
41056 "source": "iana"
41057 },
41058 "application/geoxacml+xml": {
41059 "source": "iana",
41060 "compressible": true
41061 },
41062 "application/gltf-buffer": {
41063 "source": "iana"
41064 },
41065 "application/gml+xml": {
41066 "source": "iana",
41067 "compressible": true,
41068 "extensions": ["gml"]
41069 },
41070 "application/gpx+xml": {
41071 "source": "apache",
41072 "compressible": true,
41073 "extensions": ["gpx"]
41074 },
41075 "application/gxf": {
41076 "source": "apache",
41077 "extensions": ["gxf"]
41078 },
41079 "application/gzip": {
41080 "source": "iana",
41081 "compressible": false,
41082 "extensions": ["gz"]
41083 },
41084 "application/h224": {
41085 "source": "iana"
41086 },
41087 "application/held+xml": {
41088 "source": "iana",
41089 "compressible": true
41090 },
41091 "application/hjson": {
41092 "extensions": ["hjson"]
41093 },
41094 "application/http": {
41095 "source": "iana"
41096 },
41097 "application/hyperstudio": {
41098 "source": "iana",
41099 "extensions": ["stk"]
41100 },
41101 "application/ibe-key-request+xml": {
41102 "source": "iana",
41103 "compressible": true
41104 },
41105 "application/ibe-pkg-reply+xml": {
41106 "source": "iana",
41107 "compressible": true
41108 },
41109 "application/ibe-pp-data": {
41110 "source": "iana"
41111 },
41112 "application/iges": {
41113 "source": "iana"
41114 },
41115 "application/im-iscomposing+xml": {
41116 "source": "iana",
41117 "compressible": true
41118 },
41119 "application/index": {
41120 "source": "iana"
41121 },
41122 "application/index.cmd": {
41123 "source": "iana"
41124 },
41125 "application/index.obj": {
41126 "source": "iana"
41127 },
41128 "application/index.response": {
41129 "source": "iana"
41130 },
41131 "application/index.vnd": {
41132 "source": "iana"
41133 },
41134 "application/inkml+xml": {
41135 "source": "iana",
41136 "compressible": true,
41137 "extensions": ["ink","inkml"]
41138 },
41139 "application/iotp": {
41140 "source": "iana"
41141 },
41142 "application/ipfix": {
41143 "source": "iana",
41144 "extensions": ["ipfix"]
41145 },
41146 "application/ipp": {
41147 "source": "iana"
41148 },
41149 "application/isup": {
41150 "source": "iana"
41151 },
41152 "application/its+xml": {
41153 "source": "iana",
41154 "compressible": true
41155 },
41156 "application/java-archive": {
41157 "source": "apache",
41158 "compressible": false,
41159 "extensions": ["jar","war","ear"]
41160 },
41161 "application/java-serialized-object": {
41162 "source": "apache",
41163 "compressible": false,
41164 "extensions": ["ser"]
41165 },
41166 "application/java-vm": {
41167 "source": "apache",
41168 "compressible": false,
41169 "extensions": ["class"]
41170 },
41171 "application/javascript": {
41172 "source": "iana",
41173 "charset": "UTF-8",
41174 "compressible": true,
41175 "extensions": ["js","mjs"]
41176 },
41177 "application/jf2feed+json": {
41178 "source": "iana",
41179 "compressible": true
41180 },
41181 "application/jose": {
41182 "source": "iana"
41183 },
41184 "application/jose+json": {
41185 "source": "iana",
41186 "compressible": true
41187 },
41188 "application/jrd+json": {
41189 "source": "iana",
41190 "compressible": true
41191 },
41192 "application/json": {
41193 "source": "iana",
41194 "charset": "UTF-8",
41195 "compressible": true,
41196 "extensions": ["json","map"]
41197 },
41198 "application/json-patch+json": {
41199 "source": "iana",
41200 "compressible": true
41201 },
41202 "application/json-seq": {
41203 "source": "iana"
41204 },
41205 "application/json5": {
41206 "extensions": ["json5"]
41207 },
41208 "application/jsonml+json": {
41209 "source": "apache",
41210 "compressible": true,
41211 "extensions": ["jsonml"]
41212 },
41213 "application/jwk+json": {
41214 "source": "iana",
41215 "compressible": true
41216 },
41217 "application/jwk-set+json": {
41218 "source": "iana",
41219 "compressible": true
41220 },
41221 "application/jwt": {
41222 "source": "iana"
41223 },
41224 "application/kpml-request+xml": {
41225 "source": "iana",
41226 "compressible": true
41227 },
41228 "application/kpml-response+xml": {
41229 "source": "iana",
41230 "compressible": true
41231 },
41232 "application/ld+json": {
41233 "source": "iana",
41234 "compressible": true,
41235 "extensions": ["jsonld"]
41236 },
41237 "application/lgr+xml": {
41238 "source": "iana",
41239 "compressible": true
41240 },
41241 "application/link-format": {
41242 "source": "iana"
41243 },
41244 "application/load-control+xml": {
41245 "source": "iana",
41246 "compressible": true
41247 },
41248 "application/lost+xml": {
41249 "source": "iana",
41250 "compressible": true,
41251 "extensions": ["lostxml"]
41252 },
41253 "application/lostsync+xml": {
41254 "source": "iana",
41255 "compressible": true
41256 },
41257 "application/lxf": {
41258 "source": "iana"
41259 },
41260 "application/mac-binhex40": {
41261 "source": "iana",
41262 "extensions": ["hqx"]
41263 },
41264 "application/mac-compactpro": {
41265 "source": "apache",
41266 "extensions": ["cpt"]
41267 },
41268 "application/macwriteii": {
41269 "source": "iana"
41270 },
41271 "application/mads+xml": {
41272 "source": "iana",
41273 "compressible": true,
41274 "extensions": ["mads"]
41275 },
41276 "application/manifest+json": {
41277 "charset": "UTF-8",
41278 "compressible": true,
41279 "extensions": ["webmanifest"]
41280 },
41281 "application/marc": {
41282 "source": "iana",
41283 "extensions": ["mrc"]
41284 },
41285 "application/marcxml+xml": {
41286 "source": "iana",
41287 "compressible": true,
41288 "extensions": ["mrcx"]
41289 },
41290 "application/mathematica": {
41291 "source": "iana",
41292 "extensions": ["ma","nb","mb"]
41293 },
41294 "application/mathml+xml": {
41295 "source": "iana",
41296 "compressible": true,
41297 "extensions": ["mathml"]
41298 },
41299 "application/mathml-content+xml": {
41300 "source": "iana",
41301 "compressible": true
41302 },
41303 "application/mathml-presentation+xml": {
41304 "source": "iana",
41305 "compressible": true
41306 },
41307 "application/mbms-associated-procedure-description+xml": {
41308 "source": "iana",
41309 "compressible": true
41310 },
41311 "application/mbms-deregister+xml": {
41312 "source": "iana",
41313 "compressible": true
41314 },
41315 "application/mbms-envelope+xml": {
41316 "source": "iana",
41317 "compressible": true
41318 },
41319 "application/mbms-msk+xml": {
41320 "source": "iana",
41321 "compressible": true
41322 },
41323 "application/mbms-msk-response+xml": {
41324 "source": "iana",
41325 "compressible": true
41326 },
41327 "application/mbms-protection-description+xml": {
41328 "source": "iana",
41329 "compressible": true
41330 },
41331 "application/mbms-reception-report+xml": {
41332 "source": "iana",
41333 "compressible": true
41334 },
41335 "application/mbms-register+xml": {
41336 "source": "iana",
41337 "compressible": true
41338 },
41339 "application/mbms-register-response+xml": {
41340 "source": "iana",
41341 "compressible": true
41342 },
41343 "application/mbms-schedule+xml": {
41344 "source": "iana",
41345 "compressible": true
41346 },
41347 "application/mbms-user-service-description+xml": {
41348 "source": "iana",
41349 "compressible": true
41350 },
41351 "application/mbox": {
41352 "source": "iana",
41353 "extensions": ["mbox"]
41354 },
41355 "application/media-policy-dataset+xml": {
41356 "source": "iana",
41357 "compressible": true
41358 },
41359 "application/media_control+xml": {
41360 "source": "iana",
41361 "compressible": true
41362 },
41363 "application/mediaservercontrol+xml": {
41364 "source": "iana",
41365 "compressible": true,
41366 "extensions": ["mscml"]
41367 },
41368 "application/merge-patch+json": {
41369 "source": "iana",
41370 "compressible": true
41371 },
41372 "application/metalink+xml": {
41373 "source": "apache",
41374 "compressible": true,
41375 "extensions": ["metalink"]
41376 },
41377 "application/metalink4+xml": {
41378 "source": "iana",
41379 "compressible": true,
41380 "extensions": ["meta4"]
41381 },
41382 "application/mets+xml": {
41383 "source": "iana",
41384 "compressible": true,
41385 "extensions": ["mets"]
41386 },
41387 "application/mf4": {
41388 "source": "iana"
41389 },
41390 "application/mikey": {
41391 "source": "iana"
41392 },
41393 "application/mmt-aei+xml": {
41394 "source": "iana",
41395 "compressible": true
41396 },
41397 "application/mmt-usd+xml": {
41398 "source": "iana",
41399 "compressible": true
41400 },
41401 "application/mods+xml": {
41402 "source": "iana",
41403 "compressible": true,
41404 "extensions": ["mods"]
41405 },
41406 "application/moss-keys": {
41407 "source": "iana"
41408 },
41409 "application/moss-signature": {
41410 "source": "iana"
41411 },
41412 "application/mosskey-data": {
41413 "source": "iana"
41414 },
41415 "application/mosskey-request": {
41416 "source": "iana"
41417 },
41418 "application/mp21": {
41419 "source": "iana",
41420 "extensions": ["m21","mp21"]
41421 },
41422 "application/mp4": {
41423 "source": "iana",
41424 "extensions": ["mp4s","m4p"]
41425 },
41426 "application/mpeg4-generic": {
41427 "source": "iana"
41428 },
41429 "application/mpeg4-iod": {
41430 "source": "iana"
41431 },
41432 "application/mpeg4-iod-xmt": {
41433 "source": "iana"
41434 },
41435 "application/mrb-consumer+xml": {
41436 "source": "iana",
41437 "compressible": true
41438 },
41439 "application/mrb-publish+xml": {
41440 "source": "iana",
41441 "compressible": true
41442 },
41443 "application/msc-ivr+xml": {
41444 "source": "iana",
41445 "compressible": true
41446 },
41447 "application/msc-mixer+xml": {
41448 "source": "iana",
41449 "compressible": true
41450 },
41451 "application/msword": {
41452 "source": "iana",
41453 "compressible": false,
41454 "extensions": ["doc","dot"]
41455 },
41456 "application/mud+json": {
41457 "source": "iana",
41458 "compressible": true
41459 },
41460 "application/mxf": {
41461 "source": "iana",
41462 "extensions": ["mxf"]
41463 },
41464 "application/n-quads": {
41465 "source": "iana",
41466 "extensions": ["nq"]
41467 },
41468 "application/n-triples": {
41469 "source": "iana",
41470 "extensions": ["nt"]
41471 },
41472 "application/nasdata": {
41473 "source": "iana"
41474 },
41475 "application/news-checkgroups": {
41476 "source": "iana"
41477 },
41478 "application/news-groupinfo": {
41479 "source": "iana"
41480 },
41481 "application/news-transmission": {
41482 "source": "iana"
41483 },
41484 "application/nlsml+xml": {
41485 "source": "iana",
41486 "compressible": true
41487 },
41488 "application/node": {
41489 "source": "iana"
41490 },
41491 "application/nss": {
41492 "source": "iana"
41493 },
41494 "application/ocsp-request": {
41495 "source": "iana"
41496 },
41497 "application/ocsp-response": {
41498 "source": "iana"
41499 },
41500 "application/octet-stream": {
41501 "source": "iana",
41502 "compressible": false,
41503 "extensions": ["bin","dms","lrf","mar","so","dist","distz","pkg","bpk","dump","elc","deploy","exe","dll","deb","dmg","iso","img","msi","msp","msm","buffer"]
41504 },
41505 "application/oda": {
41506 "source": "iana",
41507 "extensions": ["oda"]
41508 },
41509 "application/odm+xml": {
41510 "source": "iana",
41511 "compressible": true
41512 },
41513 "application/odx": {
41514 "source": "iana"
41515 },
41516 "application/oebps-package+xml": {
41517 "source": "iana",
41518 "compressible": true,
41519 "extensions": ["opf"]
41520 },
41521 "application/ogg": {
41522 "source": "iana",
41523 "compressible": false,
41524 "extensions": ["ogx"]
41525 },
41526 "application/omdoc+xml": {
41527 "source": "apache",
41528 "compressible": true,
41529 "extensions": ["omdoc"]
41530 },
41531 "application/onenote": {
41532 "source": "apache",
41533 "extensions": ["onetoc","onetoc2","onetmp","onepkg"]
41534 },
41535 "application/oscore": {
41536 "source": "iana"
41537 },
41538 "application/oxps": {
41539 "source": "iana",
41540 "extensions": ["oxps"]
41541 },
41542 "application/p2p-overlay+xml": {
41543 "source": "iana",
41544 "compressible": true
41545 },
41546 "application/parityfec": {
41547 "source": "iana"
41548 },
41549 "application/passport": {
41550 "source": "iana"
41551 },
41552 "application/patch-ops-error+xml": {
41553 "source": "iana",
41554 "compressible": true,
41555 "extensions": ["xer"]
41556 },
41557 "application/pdf": {
41558 "source": "iana",
41559 "compressible": false,
41560 "extensions": ["pdf"]
41561 },
41562 "application/pdx": {
41563 "source": "iana"
41564 },
41565 "application/pem-certificate-chain": {
41566 "source": "iana"
41567 },
41568 "application/pgp-encrypted": {
41569 "source": "iana",
41570 "compressible": false,
41571 "extensions": ["pgp"]
41572 },
41573 "application/pgp-keys": {
41574 "source": "iana"
41575 },
41576 "application/pgp-signature": {
41577 "source": "iana",
41578 "extensions": ["asc","sig"]
41579 },
41580 "application/pics-rules": {
41581 "source": "apache",
41582 "extensions": ["prf"]
41583 },
41584 "application/pidf+xml": {
41585 "source": "iana",
41586 "compressible": true
41587 },
41588 "application/pidf-diff+xml": {
41589 "source": "iana",
41590 "compressible": true
41591 },
41592 "application/pkcs10": {
41593 "source": "iana",
41594 "extensions": ["p10"]
41595 },
41596 "application/pkcs12": {
41597 "source": "iana"
41598 },
41599 "application/pkcs7-mime": {
41600 "source": "iana",
41601 "extensions": ["p7m","p7c"]
41602 },
41603 "application/pkcs7-signature": {
41604 "source": "iana",
41605 "extensions": ["p7s"]
41606 },
41607 "application/pkcs8": {
41608 "source": "iana",
41609 "extensions": ["p8"]
41610 },
41611 "application/pkcs8-encrypted": {
41612 "source": "iana"
41613 },
41614 "application/pkix-attr-cert": {
41615 "source": "iana",
41616 "extensions": ["ac"]
41617 },
41618 "application/pkix-cert": {
41619 "source": "iana",
41620 "extensions": ["cer"]
41621 },
41622 "application/pkix-crl": {
41623 "source": "iana",
41624 "extensions": ["crl"]
41625 },
41626 "application/pkix-pkipath": {
41627 "source": "iana",
41628 "extensions": ["pkipath"]
41629 },
41630 "application/pkixcmp": {
41631 "source": "iana",
41632 "extensions": ["pki"]
41633 },
41634 "application/pls+xml": {
41635 "source": "iana",
41636 "compressible": true,
41637 "extensions": ["pls"]
41638 },
41639 "application/poc-settings+xml": {
41640 "source": "iana",
41641 "compressible": true
41642 },
41643 "application/postscript": {
41644 "source": "iana",
41645 "compressible": true,
41646 "extensions": ["ai","eps","ps"]
41647 },
41648 "application/ppsp-tracker+json": {
41649 "source": "iana",
41650 "compressible": true
41651 },
41652 "application/problem+json": {
41653 "source": "iana",
41654 "compressible": true
41655 },
41656 "application/problem+xml": {
41657 "source": "iana",
41658 "compressible": true
41659 },
41660 "application/provenance+xml": {
41661 "source": "iana",
41662 "compressible": true
41663 },
41664 "application/prs.alvestrand.titrax-sheet": {
41665 "source": "iana"
41666 },
41667 "application/prs.cww": {
41668 "source": "iana",
41669 "extensions": ["cww"]
41670 },
41671 "application/prs.hpub+zip": {
41672 "source": "iana",
41673 "compressible": false
41674 },
41675 "application/prs.nprend": {
41676 "source": "iana"
41677 },
41678 "application/prs.plucker": {
41679 "source": "iana"
41680 },
41681 "application/prs.rdf-xml-crypt": {
41682 "source": "iana"
41683 },
41684 "application/prs.xsf+xml": {
41685 "source": "iana",
41686 "compressible": true
41687 },
41688 "application/pskc+xml": {
41689 "source": "iana",
41690 "compressible": true,
41691 "extensions": ["pskcxml"]
41692 },
41693 "application/qsig": {
41694 "source": "iana"
41695 },
41696 "application/raml+yaml": {
41697 "compressible": true,
41698 "extensions": ["raml"]
41699 },
41700 "application/raptorfec": {
41701 "source": "iana"
41702 },
41703 "application/rdap+json": {
41704 "source": "iana",
41705 "compressible": true
41706 },
41707 "application/rdf+xml": {
41708 "source": "iana",
41709 "compressible": true,
41710 "extensions": ["rdf","owl"]
41711 },
41712 "application/reginfo+xml": {
41713 "source": "iana",
41714 "compressible": true,
41715 "extensions": ["rif"]
41716 },
41717 "application/relax-ng-compact-syntax": {
41718 "source": "iana",
41719 "extensions": ["rnc"]
41720 },
41721 "application/remote-printing": {
41722 "source": "iana"
41723 },
41724 "application/reputon+json": {
41725 "source": "iana",
41726 "compressible": true
41727 },
41728 "application/resource-lists+xml": {
41729 "source": "iana",
41730 "compressible": true,
41731 "extensions": ["rl"]
41732 },
41733 "application/resource-lists-diff+xml": {
41734 "source": "iana",
41735 "compressible": true,
41736 "extensions": ["rld"]
41737 },
41738 "application/rfc+xml": {
41739 "source": "iana",
41740 "compressible": true
41741 },
41742 "application/riscos": {
41743 "source": "iana"
41744 },
41745 "application/rlmi+xml": {
41746 "source": "iana",
41747 "compressible": true
41748 },
41749 "application/rls-services+xml": {
41750 "source": "iana",
41751 "compressible": true,
41752 "extensions": ["rs"]
41753 },
41754 "application/route-apd+xml": {
41755 "source": "iana",
41756 "compressible": true
41757 },
41758 "application/route-s-tsid+xml": {
41759 "source": "iana",
41760 "compressible": true
41761 },
41762 "application/route-usd+xml": {
41763 "source": "iana",
41764 "compressible": true
41765 },
41766 "application/rpki-ghostbusters": {
41767 "source": "iana",
41768 "extensions": ["gbr"]
41769 },
41770 "application/rpki-manifest": {
41771 "source": "iana",
41772 "extensions": ["mft"]
41773 },
41774 "application/rpki-publication": {
41775 "source": "iana"
41776 },
41777 "application/rpki-roa": {
41778 "source": "iana",
41779 "extensions": ["roa"]
41780 },
41781 "application/rpki-updown": {
41782 "source": "iana"
41783 },
41784 "application/rsd+xml": {
41785 "source": "apache",
41786 "compressible": true,
41787 "extensions": ["rsd"]
41788 },
41789 "application/rss+xml": {
41790 "source": "apache",
41791 "compressible": true,
41792 "extensions": ["rss"]
41793 },
41794 "application/rtf": {
41795 "source": "iana",
41796 "compressible": true,
41797 "extensions": ["rtf"]
41798 },
41799 "application/rtploopback": {
41800 "source": "iana"
41801 },
41802 "application/rtx": {
41803 "source": "iana"
41804 },
41805 "application/samlassertion+xml": {
41806 "source": "iana",
41807 "compressible": true
41808 },
41809 "application/samlmetadata+xml": {
41810 "source": "iana",
41811 "compressible": true
41812 },
41813 "application/sbml+xml": {
41814 "source": "iana",
41815 "compressible": true,
41816 "extensions": ["sbml"]
41817 },
41818 "application/scaip+xml": {
41819 "source": "iana",
41820 "compressible": true
41821 },
41822 "application/scim+json": {
41823 "source": "iana",
41824 "compressible": true
41825 },
41826 "application/scvp-cv-request": {
41827 "source": "iana",
41828 "extensions": ["scq"]
41829 },
41830 "application/scvp-cv-response": {
41831 "source": "iana",
41832 "extensions": ["scs"]
41833 },
41834 "application/scvp-vp-request": {
41835 "source": "iana",
41836 "extensions": ["spq"]
41837 },
41838 "application/scvp-vp-response": {
41839 "source": "iana",
41840 "extensions": ["spp"]
41841 },
41842 "application/sdp": {
41843 "source": "iana",
41844 "extensions": ["sdp"]
41845 },
41846 "application/secevent+jwt": {
41847 "source": "iana"
41848 },
41849 "application/senml+cbor": {
41850 "source": "iana"
41851 },
41852 "application/senml+json": {
41853 "source": "iana",
41854 "compressible": true
41855 },
41856 "application/senml+xml": {
41857 "source": "iana",
41858 "compressible": true
41859 },
41860 "application/senml-exi": {
41861 "source": "iana"
41862 },
41863 "application/sensml+cbor": {
41864 "source": "iana"
41865 },
41866 "application/sensml+json": {
41867 "source": "iana",
41868 "compressible": true
41869 },
41870 "application/sensml+xml": {
41871 "source": "iana",
41872 "compressible": true
41873 },
41874 "application/sensml-exi": {
41875 "source": "iana"
41876 },
41877 "application/sep+xml": {
41878 "source": "iana",
41879 "compressible": true
41880 },
41881 "application/sep-exi": {
41882 "source": "iana"
41883 },
41884 "application/session-info": {
41885 "source": "iana"
41886 },
41887 "application/set-payment": {
41888 "source": "iana"
41889 },
41890 "application/set-payment-initiation": {
41891 "source": "iana",
41892 "extensions": ["setpay"]
41893 },
41894 "application/set-registration": {
41895 "source": "iana"
41896 },
41897 "application/set-registration-initiation": {
41898 "source": "iana",
41899 "extensions": ["setreg"]
41900 },
41901 "application/sgml": {
41902 "source": "iana"
41903 },
41904 "application/sgml-open-catalog": {
41905 "source": "iana"
41906 },
41907 "application/shf+xml": {
41908 "source": "iana",
41909 "compressible": true,
41910 "extensions": ["shf"]
41911 },
41912 "application/sieve": {
41913 "source": "iana",
41914 "extensions": ["siv","sieve"]
41915 },
41916 "application/simple-filter+xml": {
41917 "source": "iana",
41918 "compressible": true
41919 },
41920 "application/simple-message-summary": {
41921 "source": "iana"
41922 },
41923 "application/simplesymbolcontainer": {
41924 "source": "iana"
41925 },
41926 "application/slate": {
41927 "source": "iana"
41928 },
41929 "application/smil": {
41930 "source": "iana"
41931 },
41932 "application/smil+xml": {
41933 "source": "iana",
41934 "compressible": true,
41935 "extensions": ["smi","smil"]
41936 },
41937 "application/smpte336m": {
41938 "source": "iana"
41939 },
41940 "application/soap+fastinfoset": {
41941 "source": "iana"
41942 },
41943 "application/soap+xml": {
41944 "source": "iana",
41945 "compressible": true
41946 },
41947 "application/sparql-query": {
41948 "source": "iana",
41949 "extensions": ["rq"]
41950 },
41951 "application/sparql-results+xml": {
41952 "source": "iana",
41953 "compressible": true,
41954 "extensions": ["srx"]
41955 },
41956 "application/spirits-event+xml": {
41957 "source": "iana",
41958 "compressible": true
41959 },
41960 "application/sql": {
41961 "source": "iana"
41962 },
41963 "application/srgs": {
41964 "source": "iana",
41965 "extensions": ["gram"]
41966 },
41967 "application/srgs+xml": {
41968 "source": "iana",
41969 "compressible": true,
41970 "extensions": ["grxml"]
41971 },
41972 "application/sru+xml": {
41973 "source": "iana",
41974 "compressible": true,
41975 "extensions": ["sru"]
41976 },
41977 "application/ssdl+xml": {
41978 "source": "apache",
41979 "compressible": true,
41980 "extensions": ["ssdl"]
41981 },
41982 "application/ssml+xml": {
41983 "source": "iana",
41984 "compressible": true,
41985 "extensions": ["ssml"]
41986 },
41987 "application/stix+json": {
41988 "source": "iana",
41989 "compressible": true
41990 },
41991 "application/tamp-apex-update": {
41992 "source": "iana"
41993 },
41994 "application/tamp-apex-update-confirm": {
41995 "source": "iana"
41996 },
41997 "application/tamp-community-update": {
41998 "source": "iana"
41999 },
42000 "application/tamp-community-update-confirm": {
42001 "source": "iana"
42002 },
42003 "application/tamp-error": {
42004 "source": "iana"
42005 },
42006 "application/tamp-sequence-adjust": {
42007 "source": "iana"
42008 },
42009 "application/tamp-sequence-adjust-confirm": {
42010 "source": "iana"
42011 },
42012 "application/tamp-status-query": {
42013 "source": "iana"
42014 },
42015 "application/tamp-status-response": {
42016 "source": "iana"
42017 },
42018 "application/tamp-update": {
42019 "source": "iana"
42020 },
42021 "application/tamp-update-confirm": {
42022 "source": "iana"
42023 },
42024 "application/tar": {
42025 "compressible": true
42026 },
42027 "application/taxii+json": {
42028 "source": "iana",
42029 "compressible": true
42030 },
42031 "application/tei+xml": {
42032 "source": "iana",
42033 "compressible": true,
42034 "extensions": ["tei","teicorpus"]
42035 },
42036 "application/tetra_isi": {
42037 "source": "iana"
42038 },
42039 "application/thraud+xml": {
42040 "source": "iana",
42041 "compressible": true,
42042 "extensions": ["tfi"]
42043 },
42044 "application/timestamp-query": {
42045 "source": "iana"
42046 },
42047 "application/timestamp-reply": {
42048 "source": "iana"
42049 },
42050 "application/timestamped-data": {
42051 "source": "iana",
42052 "extensions": ["tsd"]
42053 },
42054 "application/tlsrpt+gzip": {
42055 "source": "iana"
42056 },
42057 "application/tlsrpt+json": {
42058 "source": "iana",
42059 "compressible": true
42060 },
42061 "application/tnauthlist": {
42062 "source": "iana"
42063 },
42064 "application/trickle-ice-sdpfrag": {
42065 "source": "iana"
42066 },
42067 "application/trig": {
42068 "source": "iana"
42069 },
42070 "application/ttml+xml": {
42071 "source": "iana",
42072 "compressible": true
42073 },
42074 "application/tve-trigger": {
42075 "source": "iana"
42076 },
42077 "application/tzif": {
42078 "source": "iana"
42079 },
42080 "application/tzif-leap": {
42081 "source": "iana"
42082 },
42083 "application/ulpfec": {
42084 "source": "iana"
42085 },
42086 "application/urc-grpsheet+xml": {
42087 "source": "iana",
42088 "compressible": true
42089 },
42090 "application/urc-ressheet+xml": {
42091 "source": "iana",
42092 "compressible": true
42093 },
42094 "application/urc-targetdesc+xml": {
42095 "source": "iana",
42096 "compressible": true
42097 },
42098 "application/urc-uisocketdesc+xml": {
42099 "source": "iana",
42100 "compressible": true
42101 },
42102 "application/vcard+json": {
42103 "source": "iana",
42104 "compressible": true
42105 },
42106 "application/vcard+xml": {
42107 "source": "iana",
42108 "compressible": true
42109 },
42110 "application/vemmi": {
42111 "source": "iana"
42112 },
42113 "application/vividence.scriptfile": {
42114 "source": "apache"
42115 },
42116 "application/vnd.1000minds.decision-model+xml": {
42117 "source": "iana",
42118 "compressible": true
42119 },
42120 "application/vnd.3gpp-prose+xml": {
42121 "source": "iana",
42122 "compressible": true
42123 },
42124 "application/vnd.3gpp-prose-pc3ch+xml": {
42125 "source": "iana",
42126 "compressible": true
42127 },
42128 "application/vnd.3gpp-v2x-local-service-information": {
42129 "source": "iana"
42130 },
42131 "application/vnd.3gpp.access-transfer-events+xml": {
42132 "source": "iana",
42133 "compressible": true
42134 },
42135 "application/vnd.3gpp.bsf+xml": {
42136 "source": "iana",
42137 "compressible": true
42138 },
42139 "application/vnd.3gpp.gmop+xml": {
42140 "source": "iana",
42141 "compressible": true
42142 },
42143 "application/vnd.3gpp.mc-signalling-ear": {
42144 "source": "iana"
42145 },
42146 "application/vnd.3gpp.mcdata-affiliation-command+xml": {
42147 "source": "iana",
42148 "compressible": true
42149 },
42150 "application/vnd.3gpp.mcdata-info+xml": {
42151 "source": "iana",
42152 "compressible": true
42153 },
42154 "application/vnd.3gpp.mcdata-payload": {
42155 "source": "iana"
42156 },
42157 "application/vnd.3gpp.mcdata-service-config+xml": {
42158 "source": "iana",
42159 "compressible": true
42160 },
42161 "application/vnd.3gpp.mcdata-signalling": {
42162 "source": "iana"
42163 },
42164 "application/vnd.3gpp.mcdata-ue-config+xml": {
42165 "source": "iana",
42166 "compressible": true
42167 },
42168 "application/vnd.3gpp.mcdata-user-profile+xml": {
42169 "source": "iana",
42170 "compressible": true
42171 },
42172 "application/vnd.3gpp.mcptt-affiliation-command+xml": {
42173 "source": "iana",
42174 "compressible": true
42175 },
42176 "application/vnd.3gpp.mcptt-floor-request+xml": {
42177 "source": "iana",
42178 "compressible": true
42179 },
42180 "application/vnd.3gpp.mcptt-info+xml": {
42181 "source": "iana",
42182 "compressible": true
42183 },
42184 "application/vnd.3gpp.mcptt-location-info+xml": {
42185 "source": "iana",
42186 "compressible": true
42187 },
42188 "application/vnd.3gpp.mcptt-mbms-usage-info+xml": {
42189 "source": "iana",
42190 "compressible": true
42191 },
42192 "application/vnd.3gpp.mcptt-service-config+xml": {
42193 "source": "iana",
42194 "compressible": true
42195 },
42196 "application/vnd.3gpp.mcptt-signed+xml": {
42197 "source": "iana",
42198 "compressible": true
42199 },
42200 "application/vnd.3gpp.mcptt-ue-config+xml": {
42201 "source": "iana",
42202 "compressible": true
42203 },
42204 "application/vnd.3gpp.mcptt-ue-init-config+xml": {
42205 "source": "iana",
42206 "compressible": true
42207 },
42208 "application/vnd.3gpp.mcptt-user-profile+xml": {
42209 "source": "iana",
42210 "compressible": true
42211 },
42212 "application/vnd.3gpp.mcvideo-affiliation-command+xml": {
42213 "source": "iana",
42214 "compressible": true
42215 },
42216 "application/vnd.3gpp.mcvideo-affiliation-info+xml": {
42217 "source": "iana",
42218 "compressible": true
42219 },
42220 "application/vnd.3gpp.mcvideo-location-info+xml": {
42221 "source": "iana",
42222 "compressible": true
42223 },
42224 "application/vnd.3gpp.mcvideo-mbms-usage-info+xml": {
42225 "source": "iana",
42226 "compressible": true
42227 },
42228 "application/vnd.3gpp.mcvideo-service-config+xml": {
42229 "source": "iana",
42230 "compressible": true
42231 },
42232 "application/vnd.3gpp.mcvideo-transmission-request+xml": {
42233 "source": "iana",
42234 "compressible": true
42235 },
42236 "application/vnd.3gpp.mcvideo-ue-config+xml": {
42237 "source": "iana",
42238 "compressible": true
42239 },
42240 "application/vnd.3gpp.mcvideo-user-profile+xml": {
42241 "source": "iana",
42242 "compressible": true
42243 },
42244 "application/vnd.3gpp.mid-call+xml": {
42245 "source": "iana",
42246 "compressible": true
42247 },
42248 "application/vnd.3gpp.pic-bw-large": {
42249 "source": "iana",
42250 "extensions": ["plb"]
42251 },
42252 "application/vnd.3gpp.pic-bw-small": {
42253 "source": "iana",
42254 "extensions": ["psb"]
42255 },
42256 "application/vnd.3gpp.pic-bw-var": {
42257 "source": "iana",
42258 "extensions": ["pvb"]
42259 },
42260 "application/vnd.3gpp.sms": {
42261 "source": "iana"
42262 },
42263 "application/vnd.3gpp.sms+xml": {
42264 "source": "iana",
42265 "compressible": true
42266 },
42267 "application/vnd.3gpp.srvcc-ext+xml": {
42268 "source": "iana",
42269 "compressible": true
42270 },
42271 "application/vnd.3gpp.srvcc-info+xml": {
42272 "source": "iana",
42273 "compressible": true
42274 },
42275 "application/vnd.3gpp.state-and-event-info+xml": {
42276 "source": "iana",
42277 "compressible": true
42278 },
42279 "application/vnd.3gpp.ussd+xml": {
42280 "source": "iana",
42281 "compressible": true
42282 },
42283 "application/vnd.3gpp2.bcmcsinfo+xml": {
42284 "source": "iana",
42285 "compressible": true
42286 },
42287 "application/vnd.3gpp2.sms": {
42288 "source": "iana"
42289 },
42290 "application/vnd.3gpp2.tcap": {
42291 "source": "iana",
42292 "extensions": ["tcap"]
42293 },
42294 "application/vnd.3lightssoftware.imagescal": {
42295 "source": "iana"
42296 },
42297 "application/vnd.3m.post-it-notes": {
42298 "source": "iana",
42299 "extensions": ["pwn"]
42300 },
42301 "application/vnd.accpac.simply.aso": {
42302 "source": "iana",
42303 "extensions": ["aso"]
42304 },
42305 "application/vnd.accpac.simply.imp": {
42306 "source": "iana",
42307 "extensions": ["imp"]
42308 },
42309 "application/vnd.acucobol": {
42310 "source": "iana",
42311 "extensions": ["acu"]
42312 },
42313 "application/vnd.acucorp": {
42314 "source": "iana",
42315 "extensions": ["atc","acutc"]
42316 },
42317 "application/vnd.adobe.air-application-installer-package+zip": {
42318 "source": "apache",
42319 "compressible": false,
42320 "extensions": ["air"]
42321 },
42322 "application/vnd.adobe.flash.movie": {
42323 "source": "iana"
42324 },
42325 "application/vnd.adobe.formscentral.fcdt": {
42326 "source": "iana",
42327 "extensions": ["fcdt"]
42328 },
42329 "application/vnd.adobe.fxp": {
42330 "source": "iana",
42331 "extensions": ["fxp","fxpl"]
42332 },
42333 "application/vnd.adobe.partial-upload": {
42334 "source": "iana"
42335 },
42336 "application/vnd.adobe.xdp+xml": {
42337 "source": "iana",
42338 "compressible": true,
42339 "extensions": ["xdp"]
42340 },
42341 "application/vnd.adobe.xfdf": {
42342 "source": "iana",
42343 "extensions": ["xfdf"]
42344 },
42345 "application/vnd.aether.imp": {
42346 "source": "iana"
42347 },
42348 "application/vnd.afpc.afplinedata": {
42349 "source": "iana"
42350 },
42351 "application/vnd.afpc.modca": {
42352 "source": "iana"
42353 },
42354 "application/vnd.ah-barcode": {
42355 "source": "iana"
42356 },
42357 "application/vnd.ahead.space": {
42358 "source": "iana",
42359 "extensions": ["ahead"]
42360 },
42361 "application/vnd.airzip.filesecure.azf": {
42362 "source": "iana",
42363 "extensions": ["azf"]
42364 },
42365 "application/vnd.airzip.filesecure.azs": {
42366 "source": "iana",
42367 "extensions": ["azs"]
42368 },
42369 "application/vnd.amadeus+json": {
42370 "source": "iana",
42371 "compressible": true
42372 },
42373 "application/vnd.amazon.ebook": {
42374 "source": "apache",
42375 "extensions": ["azw"]
42376 },
42377 "application/vnd.amazon.mobi8-ebook": {
42378 "source": "iana"
42379 },
42380 "application/vnd.americandynamics.acc": {
42381 "source": "iana",
42382 "extensions": ["acc"]
42383 },
42384 "application/vnd.amiga.ami": {
42385 "source": "iana",
42386 "extensions": ["ami"]
42387 },
42388 "application/vnd.amundsen.maze+xml": {
42389 "source": "iana",
42390 "compressible": true
42391 },
42392 "application/vnd.android.package-archive": {
42393 "source": "apache",
42394 "compressible": false,
42395 "extensions": ["apk"]
42396 },
42397 "application/vnd.anki": {
42398 "source": "iana"
42399 },
42400 "application/vnd.anser-web-certificate-issue-initiation": {
42401 "source": "iana",
42402 "extensions": ["cii"]
42403 },
42404 "application/vnd.anser-web-funds-transfer-initiation": {
42405 "source": "apache",
42406 "extensions": ["fti"]
42407 },
42408 "application/vnd.antix.game-component": {
42409 "source": "iana",
42410 "extensions": ["atx"]
42411 },
42412 "application/vnd.apache.thrift.binary": {
42413 "source": "iana"
42414 },
42415 "application/vnd.apache.thrift.compact": {
42416 "source": "iana"
42417 },
42418 "application/vnd.apache.thrift.json": {
42419 "source": "iana"
42420 },
42421 "application/vnd.api+json": {
42422 "source": "iana",
42423 "compressible": true
42424 },
42425 "application/vnd.apothekende.reservation+json": {
42426 "source": "iana",
42427 "compressible": true
42428 },
42429 "application/vnd.apple.installer+xml": {
42430 "source": "iana",
42431 "compressible": true,
42432 "extensions": ["mpkg"]
42433 },
42434 "application/vnd.apple.keynote": {
42435 "source": "iana",
42436 "extensions": ["keynote"]
42437 },
42438 "application/vnd.apple.mpegurl": {
42439 "source": "iana",
42440 "extensions": ["m3u8"]
42441 },
42442 "application/vnd.apple.numbers": {
42443 "source": "iana",
42444 "extensions": ["numbers"]
42445 },
42446 "application/vnd.apple.pages": {
42447 "source": "iana",
42448 "extensions": ["pages"]
42449 },
42450 "application/vnd.apple.pkpass": {
42451 "compressible": false,
42452 "extensions": ["pkpass"]
42453 },
42454 "application/vnd.arastra.swi": {
42455 "source": "iana"
42456 },
42457 "application/vnd.aristanetworks.swi": {
42458 "source": "iana",
42459 "extensions": ["swi"]
42460 },
42461 "application/vnd.artisan+json": {
42462 "source": "iana",
42463 "compressible": true
42464 },
42465 "application/vnd.artsquare": {
42466 "source": "iana"
42467 },
42468 "application/vnd.astraea-software.iota": {
42469 "source": "iana",
42470 "extensions": ["iota"]
42471 },
42472 "application/vnd.audiograph": {
42473 "source": "iana",
42474 "extensions": ["aep"]
42475 },
42476 "application/vnd.autopackage": {
42477 "source": "iana"
42478 },
42479 "application/vnd.avalon+json": {
42480 "source": "iana",
42481 "compressible": true
42482 },
42483 "application/vnd.avistar+xml": {
42484 "source": "iana",
42485 "compressible": true
42486 },
42487 "application/vnd.balsamiq.bmml+xml": {
42488 "source": "iana",
42489 "compressible": true
42490 },
42491 "application/vnd.balsamiq.bmpr": {
42492 "source": "iana"
42493 },
42494 "application/vnd.banana-accounting": {
42495 "source": "iana"
42496 },
42497 "application/vnd.bbf.usp.msg": {
42498 "source": "iana"
42499 },
42500 "application/vnd.bbf.usp.msg+json": {
42501 "source": "iana",
42502 "compressible": true
42503 },
42504 "application/vnd.bekitzur-stech+json": {
42505 "source": "iana",
42506 "compressible": true
42507 },
42508 "application/vnd.bint.med-content": {
42509 "source": "iana"
42510 },
42511 "application/vnd.biopax.rdf+xml": {
42512 "source": "iana",
42513 "compressible": true
42514 },
42515 "application/vnd.blink-idb-value-wrapper": {
42516 "source": "iana"
42517 },
42518 "application/vnd.blueice.multipass": {
42519 "source": "iana",
42520 "extensions": ["mpm"]
42521 },
42522 "application/vnd.bluetooth.ep.oob": {
42523 "source": "iana"
42524 },
42525 "application/vnd.bluetooth.le.oob": {
42526 "source": "iana"
42527 },
42528 "application/vnd.bmi": {
42529 "source": "iana",
42530 "extensions": ["bmi"]
42531 },
42532 "application/vnd.businessobjects": {
42533 "source": "iana",
42534 "extensions": ["rep"]
42535 },
42536 "application/vnd.byu.uapi+json": {
42537 "source": "iana",
42538 "compressible": true
42539 },
42540 "application/vnd.cab-jscript": {
42541 "source": "iana"
42542 },
42543 "application/vnd.canon-cpdl": {
42544 "source": "iana"
42545 },
42546 "application/vnd.canon-lips": {
42547 "source": "iana"
42548 },
42549 "application/vnd.capasystems-pg+json": {
42550 "source": "iana",
42551 "compressible": true
42552 },
42553 "application/vnd.cendio.thinlinc.clientconf": {
42554 "source": "iana"
42555 },
42556 "application/vnd.century-systems.tcp_stream": {
42557 "source": "iana"
42558 },
42559 "application/vnd.chemdraw+xml": {
42560 "source": "iana",
42561 "compressible": true,
42562 "extensions": ["cdxml"]
42563 },
42564 "application/vnd.chess-pgn": {
42565 "source": "iana"
42566 },
42567 "application/vnd.chipnuts.karaoke-mmd": {
42568 "source": "iana",
42569 "extensions": ["mmd"]
42570 },
42571 "application/vnd.cinderella": {
42572 "source": "iana",
42573 "extensions": ["cdy"]
42574 },
42575 "application/vnd.cirpack.isdn-ext": {
42576 "source": "iana"
42577 },
42578 "application/vnd.citationstyles.style+xml": {
42579 "source": "iana",
42580 "compressible": true,
42581 "extensions": ["csl"]
42582 },
42583 "application/vnd.claymore": {
42584 "source": "iana",
42585 "extensions": ["cla"]
42586 },
42587 "application/vnd.cloanto.rp9": {
42588 "source": "iana",
42589 "extensions": ["rp9"]
42590 },
42591 "application/vnd.clonk.c4group": {
42592 "source": "iana",
42593 "extensions": ["c4g","c4d","c4f","c4p","c4u"]
42594 },
42595 "application/vnd.cluetrust.cartomobile-config": {
42596 "source": "iana",
42597 "extensions": ["c11amc"]
42598 },
42599 "application/vnd.cluetrust.cartomobile-config-pkg": {
42600 "source": "iana",
42601 "extensions": ["c11amz"]
42602 },
42603 "application/vnd.coffeescript": {
42604 "source": "iana"
42605 },
42606 "application/vnd.collabio.xodocuments.document": {
42607 "source": "iana"
42608 },
42609 "application/vnd.collabio.xodocuments.document-template": {
42610 "source": "iana"
42611 },
42612 "application/vnd.collabio.xodocuments.presentation": {
42613 "source": "iana"
42614 },
42615 "application/vnd.collabio.xodocuments.presentation-template": {
42616 "source": "iana"
42617 },
42618 "application/vnd.collabio.xodocuments.spreadsheet": {
42619 "source": "iana"
42620 },
42621 "application/vnd.collabio.xodocuments.spreadsheet-template": {
42622 "source": "iana"
42623 },
42624 "application/vnd.collection+json": {
42625 "source": "iana",
42626 "compressible": true
42627 },
42628 "application/vnd.collection.doc+json": {
42629 "source": "iana",
42630 "compressible": true
42631 },
42632 "application/vnd.collection.next+json": {
42633 "source": "iana",
42634 "compressible": true
42635 },
42636 "application/vnd.comicbook+zip": {
42637 "source": "iana",
42638 "compressible": false
42639 },
42640 "application/vnd.comicbook-rar": {
42641 "source": "iana"
42642 },
42643 "application/vnd.commerce-battelle": {
42644 "source": "iana"
42645 },
42646 "application/vnd.commonspace": {
42647 "source": "iana",
42648 "extensions": ["csp"]
42649 },
42650 "application/vnd.contact.cmsg": {
42651 "source": "iana",
42652 "extensions": ["cdbcmsg"]
42653 },
42654 "application/vnd.coreos.ignition+json": {
42655 "source": "iana",
42656 "compressible": true
42657 },
42658 "application/vnd.cosmocaller": {
42659 "source": "iana",
42660 "extensions": ["cmc"]
42661 },
42662 "application/vnd.crick.clicker": {
42663 "source": "iana",
42664 "extensions": ["clkx"]
42665 },
42666 "application/vnd.crick.clicker.keyboard": {
42667 "source": "iana",
42668 "extensions": ["clkk"]
42669 },
42670 "application/vnd.crick.clicker.palette": {
42671 "source": "iana",
42672 "extensions": ["clkp"]
42673 },
42674 "application/vnd.crick.clicker.template": {
42675 "source": "iana",
42676 "extensions": ["clkt"]
42677 },
42678 "application/vnd.crick.clicker.wordbank": {
42679 "source": "iana",
42680 "extensions": ["clkw"]
42681 },
42682 "application/vnd.criticaltools.wbs+xml": {
42683 "source": "iana",
42684 "compressible": true,
42685 "extensions": ["wbs"]
42686 },
42687 "application/vnd.ctc-posml": {
42688 "source": "iana",
42689 "extensions": ["pml"]
42690 },
42691 "application/vnd.ctct.ws+xml": {
42692 "source": "iana",
42693 "compressible": true
42694 },
42695 "application/vnd.cups-pdf": {
42696 "source": "iana"
42697 },
42698 "application/vnd.cups-postscript": {
42699 "source": "iana"
42700 },
42701 "application/vnd.cups-ppd": {
42702 "source": "iana",
42703 "extensions": ["ppd"]
42704 },
42705 "application/vnd.cups-raster": {
42706 "source": "iana"
42707 },
42708 "application/vnd.cups-raw": {
42709 "source": "iana"
42710 },
42711 "application/vnd.curl": {
42712 "source": "iana"
42713 },
42714 "application/vnd.curl.car": {
42715 "source": "apache",
42716 "extensions": ["car"]
42717 },
42718 "application/vnd.curl.pcurl": {
42719 "source": "apache",
42720 "extensions": ["pcurl"]
42721 },
42722 "application/vnd.cyan.dean.root+xml": {
42723 "source": "iana",
42724 "compressible": true
42725 },
42726 "application/vnd.cybank": {
42727 "source": "iana"
42728 },
42729 "application/vnd.d2l.coursepackage1p0+zip": {
42730 "source": "iana",
42731 "compressible": false
42732 },
42733 "application/vnd.dart": {
42734 "source": "iana",
42735 "compressible": true,
42736 "extensions": ["dart"]
42737 },
42738 "application/vnd.data-vision.rdz": {
42739 "source": "iana",
42740 "extensions": ["rdz"]
42741 },
42742 "application/vnd.datapackage+json": {
42743 "source": "iana",
42744 "compressible": true
42745 },
42746 "application/vnd.dataresource+json": {
42747 "source": "iana",
42748 "compressible": true
42749 },
42750 "application/vnd.debian.binary-package": {
42751 "source": "iana"
42752 },
42753 "application/vnd.dece.data": {
42754 "source": "iana",
42755 "extensions": ["uvf","uvvf","uvd","uvvd"]
42756 },
42757 "application/vnd.dece.ttml+xml": {
42758 "source": "iana",
42759 "compressible": true,
42760 "extensions": ["uvt","uvvt"]
42761 },
42762 "application/vnd.dece.unspecified": {
42763 "source": "iana",
42764 "extensions": ["uvx","uvvx"]
42765 },
42766 "application/vnd.dece.zip": {
42767 "source": "iana",
42768 "extensions": ["uvz","uvvz"]
42769 },
42770 "application/vnd.denovo.fcselayout-link": {
42771 "source": "iana",
42772 "extensions": ["fe_launch"]
42773 },
42774 "application/vnd.desmume.movie": {
42775 "source": "iana"
42776 },
42777 "application/vnd.dir-bi.plate-dl-nosuffix": {
42778 "source": "iana"
42779 },
42780 "application/vnd.dm.delegation+xml": {
42781 "source": "iana",
42782 "compressible": true
42783 },
42784 "application/vnd.dna": {
42785 "source": "iana",
42786 "extensions": ["dna"]
42787 },
42788 "application/vnd.document+json": {
42789 "source": "iana",
42790 "compressible": true
42791 },
42792 "application/vnd.dolby.mlp": {
42793 "source": "apache",
42794 "extensions": ["mlp"]
42795 },
42796 "application/vnd.dolby.mobile.1": {
42797 "source": "iana"
42798 },
42799 "application/vnd.dolby.mobile.2": {
42800 "source": "iana"
42801 },
42802 "application/vnd.doremir.scorecloud-binary-document": {
42803 "source": "iana"
42804 },
42805 "application/vnd.dpgraph": {
42806 "source": "iana",
42807 "extensions": ["dpg"]
42808 },
42809 "application/vnd.dreamfactory": {
42810 "source": "iana",
42811 "extensions": ["dfac"]
42812 },
42813 "application/vnd.drive+json": {
42814 "source": "iana",
42815 "compressible": true
42816 },
42817 "application/vnd.ds-keypoint": {
42818 "source": "apache",
42819 "extensions": ["kpxx"]
42820 },
42821 "application/vnd.dtg.local": {
42822 "source": "iana"
42823 },
42824 "application/vnd.dtg.local.flash": {
42825 "source": "iana"
42826 },
42827 "application/vnd.dtg.local.html": {
42828 "source": "iana"
42829 },
42830 "application/vnd.dvb.ait": {
42831 "source": "iana",
42832 "extensions": ["ait"]
42833 },
42834 "application/vnd.dvb.dvbj": {
42835 "source": "iana"
42836 },
42837 "application/vnd.dvb.esgcontainer": {
42838 "source": "iana"
42839 },
42840 "application/vnd.dvb.ipdcdftnotifaccess": {
42841 "source": "iana"
42842 },
42843 "application/vnd.dvb.ipdcesgaccess": {
42844 "source": "iana"
42845 },
42846 "application/vnd.dvb.ipdcesgaccess2": {
42847 "source": "iana"
42848 },
42849 "application/vnd.dvb.ipdcesgpdd": {
42850 "source": "iana"
42851 },
42852 "application/vnd.dvb.ipdcroaming": {
42853 "source": "iana"
42854 },
42855 "application/vnd.dvb.iptv.alfec-base": {
42856 "source": "iana"
42857 },
42858 "application/vnd.dvb.iptv.alfec-enhancement": {
42859 "source": "iana"
42860 },
42861 "application/vnd.dvb.notif-aggregate-root+xml": {
42862 "source": "iana",
42863 "compressible": true
42864 },
42865 "application/vnd.dvb.notif-container+xml": {
42866 "source": "iana",
42867 "compressible": true
42868 },
42869 "application/vnd.dvb.notif-generic+xml": {
42870 "source": "iana",
42871 "compressible": true
42872 },
42873 "application/vnd.dvb.notif-ia-msglist+xml": {
42874 "source": "iana",
42875 "compressible": true
42876 },
42877 "application/vnd.dvb.notif-ia-registration-request+xml": {
42878 "source": "iana",
42879 "compressible": true
42880 },
42881 "application/vnd.dvb.notif-ia-registration-response+xml": {
42882 "source": "iana",
42883 "compressible": true
42884 },
42885 "application/vnd.dvb.notif-init+xml": {
42886 "source": "iana",
42887 "compressible": true
42888 },
42889 "application/vnd.dvb.pfr": {
42890 "source": "iana"
42891 },
42892 "application/vnd.dvb.service": {
42893 "source": "iana",
42894 "extensions": ["svc"]
42895 },
42896 "application/vnd.dxr": {
42897 "source": "iana"
42898 },
42899 "application/vnd.dynageo": {
42900 "source": "iana",
42901 "extensions": ["geo"]
42902 },
42903 "application/vnd.dzr": {
42904 "source": "iana"
42905 },
42906 "application/vnd.easykaraoke.cdgdownload": {
42907 "source": "iana"
42908 },
42909 "application/vnd.ecdis-update": {
42910 "source": "iana"
42911 },
42912 "application/vnd.ecip.rlp": {
42913 "source": "iana"
42914 },
42915 "application/vnd.ecowin.chart": {
42916 "source": "iana",
42917 "extensions": ["mag"]
42918 },
42919 "application/vnd.ecowin.filerequest": {
42920 "source": "iana"
42921 },
42922 "application/vnd.ecowin.fileupdate": {
42923 "source": "iana"
42924 },
42925 "application/vnd.ecowin.series": {
42926 "source": "iana"
42927 },
42928 "application/vnd.ecowin.seriesrequest": {
42929 "source": "iana"
42930 },
42931 "application/vnd.ecowin.seriesupdate": {
42932 "source": "iana"
42933 },
42934 "application/vnd.efi.img": {
42935 "source": "iana"
42936 },
42937 "application/vnd.efi.iso": {
42938 "source": "iana"
42939 },
42940 "application/vnd.emclient.accessrequest+xml": {
42941 "source": "iana",
42942 "compressible": true
42943 },
42944 "application/vnd.enliven": {
42945 "source": "iana",
42946 "extensions": ["nml"]
42947 },
42948 "application/vnd.enphase.envoy": {
42949 "source": "iana"
42950 },
42951 "application/vnd.eprints.data+xml": {
42952 "source": "iana",
42953 "compressible": true
42954 },
42955 "application/vnd.epson.esf": {
42956 "source": "iana",
42957 "extensions": ["esf"]
42958 },
42959 "application/vnd.epson.msf": {
42960 "source": "iana",
42961 "extensions": ["msf"]
42962 },
42963 "application/vnd.epson.quickanime": {
42964 "source": "iana",
42965 "extensions": ["qam"]
42966 },
42967 "application/vnd.epson.salt": {
42968 "source": "iana",
42969 "extensions": ["slt"]
42970 },
42971 "application/vnd.epson.ssf": {
42972 "source": "iana",
42973 "extensions": ["ssf"]
42974 },
42975 "application/vnd.ericsson.quickcall": {
42976 "source": "iana"
42977 },
42978 "application/vnd.espass-espass+zip": {
42979 "source": "iana",
42980 "compressible": false
42981 },
42982 "application/vnd.eszigno3+xml": {
42983 "source": "iana",
42984 "compressible": true,
42985 "extensions": ["es3","et3"]
42986 },
42987 "application/vnd.etsi.aoc+xml": {
42988 "source": "iana",
42989 "compressible": true
42990 },
42991 "application/vnd.etsi.asic-e+zip": {
42992 "source": "iana",
42993 "compressible": false
42994 },
42995 "application/vnd.etsi.asic-s+zip": {
42996 "source": "iana",
42997 "compressible": false
42998 },
42999 "application/vnd.etsi.cug+xml": {
43000 "source": "iana",
43001 "compressible": true
43002 },
43003 "application/vnd.etsi.iptvcommand+xml": {
43004 "source": "iana",
43005 "compressible": true
43006 },
43007 "application/vnd.etsi.iptvdiscovery+xml": {
43008 "source": "iana",
43009 "compressible": true
43010 },
43011 "application/vnd.etsi.iptvprofile+xml": {
43012 "source": "iana",
43013 "compressible": true
43014 },
43015 "application/vnd.etsi.iptvsad-bc+xml": {
43016 "source": "iana",
43017 "compressible": true
43018 },
43019 "application/vnd.etsi.iptvsad-cod+xml": {
43020 "source": "iana",
43021 "compressible": true
43022 },
43023 "application/vnd.etsi.iptvsad-npvr+xml": {
43024 "source": "iana",
43025 "compressible": true
43026 },
43027 "application/vnd.etsi.iptvservice+xml": {
43028 "source": "iana",
43029 "compressible": true
43030 },
43031 "application/vnd.etsi.iptvsync+xml": {
43032 "source": "iana",
43033 "compressible": true
43034 },
43035 "application/vnd.etsi.iptvueprofile+xml": {
43036 "source": "iana",
43037 "compressible": true
43038 },
43039 "application/vnd.etsi.mcid+xml": {
43040 "source": "iana",
43041 "compressible": true
43042 },
43043 "application/vnd.etsi.mheg5": {
43044 "source": "iana"
43045 },
43046 "application/vnd.etsi.overload-control-policy-dataset+xml": {
43047 "source": "iana",
43048 "compressible": true
43049 },
43050 "application/vnd.etsi.pstn+xml": {
43051 "source": "iana",
43052 "compressible": true
43053 },
43054 "application/vnd.etsi.sci+xml": {
43055 "source": "iana",
43056 "compressible": true
43057 },
43058 "application/vnd.etsi.simservs+xml": {
43059 "source": "iana",
43060 "compressible": true
43061 },
43062 "application/vnd.etsi.timestamp-token": {
43063 "source": "iana"
43064 },
43065 "application/vnd.etsi.tsl+xml": {
43066 "source": "iana",
43067 "compressible": true
43068 },
43069 "application/vnd.etsi.tsl.der": {
43070 "source": "iana"
43071 },
43072 "application/vnd.eudora.data": {
43073 "source": "iana"
43074 },
43075 "application/vnd.evolv.ecig.profile": {
43076 "source": "iana"
43077 },
43078 "application/vnd.evolv.ecig.settings": {
43079 "source": "iana"
43080 },
43081 "application/vnd.evolv.ecig.theme": {
43082 "source": "iana"
43083 },
43084 "application/vnd.exstream-empower+zip": {
43085 "source": "iana",
43086 "compressible": false
43087 },
43088 "application/vnd.exstream-package": {
43089 "source": "iana"
43090 },
43091 "application/vnd.ezpix-album": {
43092 "source": "iana",
43093 "extensions": ["ez2"]
43094 },
43095 "application/vnd.ezpix-package": {
43096 "source": "iana",
43097 "extensions": ["ez3"]
43098 },
43099 "application/vnd.f-secure.mobile": {
43100 "source": "iana"
43101 },
43102 "application/vnd.fastcopy-disk-image": {
43103 "source": "iana"
43104 },
43105 "application/vnd.fdf": {
43106 "source": "iana",
43107 "extensions": ["fdf"]
43108 },
43109 "application/vnd.fdsn.mseed": {
43110 "source": "iana",
43111 "extensions": ["mseed"]
43112 },
43113 "application/vnd.fdsn.seed": {
43114 "source": "iana",
43115 "extensions": ["seed","dataless"]
43116 },
43117 "application/vnd.ffsns": {
43118 "source": "iana"
43119 },
43120 "application/vnd.filmit.zfc": {
43121 "source": "iana"
43122 },
43123 "application/vnd.fints": {
43124 "source": "iana"
43125 },
43126 "application/vnd.firemonkeys.cloudcell": {
43127 "source": "iana"
43128 },
43129 "application/vnd.flographit": {
43130 "source": "iana",
43131 "extensions": ["gph"]
43132 },
43133 "application/vnd.fluxtime.clip": {
43134 "source": "iana",
43135 "extensions": ["ftc"]
43136 },
43137 "application/vnd.font-fontforge-sfd": {
43138 "source": "iana"
43139 },
43140 "application/vnd.framemaker": {
43141 "source": "iana",
43142 "extensions": ["fm","frame","maker","book"]
43143 },
43144 "application/vnd.frogans.fnc": {
43145 "source": "iana",
43146 "extensions": ["fnc"]
43147 },
43148 "application/vnd.frogans.ltf": {
43149 "source": "iana",
43150 "extensions": ["ltf"]
43151 },
43152 "application/vnd.fsc.weblaunch": {
43153 "source": "iana",
43154 "extensions": ["fsc"]
43155 },
43156 "application/vnd.fujitsu.oasys": {
43157 "source": "iana",
43158 "extensions": ["oas"]
43159 },
43160 "application/vnd.fujitsu.oasys2": {
43161 "source": "iana",
43162 "extensions": ["oa2"]
43163 },
43164 "application/vnd.fujitsu.oasys3": {
43165 "source": "iana",
43166 "extensions": ["oa3"]
43167 },
43168 "application/vnd.fujitsu.oasysgp": {
43169 "source": "iana",
43170 "extensions": ["fg5"]
43171 },
43172 "application/vnd.fujitsu.oasysprs": {
43173 "source": "iana",
43174 "extensions": ["bh2"]
43175 },
43176 "application/vnd.fujixerox.art-ex": {
43177 "source": "iana"
43178 },
43179 "application/vnd.fujixerox.art4": {
43180 "source": "iana"
43181 },
43182 "application/vnd.fujixerox.ddd": {
43183 "source": "iana",
43184 "extensions": ["ddd"]
43185 },
43186 "application/vnd.fujixerox.docuworks": {
43187 "source": "iana",
43188 "extensions": ["xdw"]
43189 },
43190 "application/vnd.fujixerox.docuworks.binder": {
43191 "source": "iana",
43192 "extensions": ["xbd"]
43193 },
43194 "application/vnd.fujixerox.docuworks.container": {
43195 "source": "iana"
43196 },
43197 "application/vnd.fujixerox.hbpl": {
43198 "source": "iana"
43199 },
43200 "application/vnd.fut-misnet": {
43201 "source": "iana"
43202 },
43203 "application/vnd.futoin+cbor": {
43204 "source": "iana"
43205 },
43206 "application/vnd.futoin+json": {
43207 "source": "iana",
43208 "compressible": true
43209 },
43210 "application/vnd.fuzzysheet": {
43211 "source": "iana",
43212 "extensions": ["fzs"]
43213 },
43214 "application/vnd.genomatix.tuxedo": {
43215 "source": "iana",
43216 "extensions": ["txd"]
43217 },
43218 "application/vnd.geo+json": {
43219 "source": "iana",
43220 "compressible": true
43221 },
43222 "application/vnd.geocube+xml": {
43223 "source": "iana",
43224 "compressible": true
43225 },
43226 "application/vnd.geogebra.file": {
43227 "source": "iana",
43228 "extensions": ["ggb"]
43229 },
43230 "application/vnd.geogebra.tool": {
43231 "source": "iana",
43232 "extensions": ["ggt"]
43233 },
43234 "application/vnd.geometry-explorer": {
43235 "source": "iana",
43236 "extensions": ["gex","gre"]
43237 },
43238 "application/vnd.geonext": {
43239 "source": "iana",
43240 "extensions": ["gxt"]
43241 },
43242 "application/vnd.geoplan": {
43243 "source": "iana",
43244 "extensions": ["g2w"]
43245 },
43246 "application/vnd.geospace": {
43247 "source": "iana",
43248 "extensions": ["g3w"]
43249 },
43250 "application/vnd.gerber": {
43251 "source": "iana"
43252 },
43253 "application/vnd.globalplatform.card-content-mgt": {
43254 "source": "iana"
43255 },
43256 "application/vnd.globalplatform.card-content-mgt-response": {
43257 "source": "iana"
43258 },
43259 "application/vnd.gmx": {
43260 "source": "iana",
43261 "extensions": ["gmx"]
43262 },
43263 "application/vnd.google-apps.document": {
43264 "compressible": false,
43265 "extensions": ["gdoc"]
43266 },
43267 "application/vnd.google-apps.presentation": {
43268 "compressible": false,
43269 "extensions": ["gslides"]
43270 },
43271 "application/vnd.google-apps.spreadsheet": {
43272 "compressible": false,
43273 "extensions": ["gsheet"]
43274 },
43275 "application/vnd.google-earth.kml+xml": {
43276 "source": "iana",
43277 "compressible": true,
43278 "extensions": ["kml"]
43279 },
43280 "application/vnd.google-earth.kmz": {
43281 "source": "iana",
43282 "compressible": false,
43283 "extensions": ["kmz"]
43284 },
43285 "application/vnd.gov.sk.e-form+xml": {
43286 "source": "iana",
43287 "compressible": true
43288 },
43289 "application/vnd.gov.sk.e-form+zip": {
43290 "source": "iana",
43291 "compressible": false
43292 },
43293 "application/vnd.gov.sk.xmldatacontainer+xml": {
43294 "source": "iana",
43295 "compressible": true
43296 },
43297 "application/vnd.grafeq": {
43298 "source": "iana",
43299 "extensions": ["gqf","gqs"]
43300 },
43301 "application/vnd.gridmp": {
43302 "source": "iana"
43303 },
43304 "application/vnd.groove-account": {
43305 "source": "iana",
43306 "extensions": ["gac"]
43307 },
43308 "application/vnd.groove-help": {
43309 "source": "iana",
43310 "extensions": ["ghf"]
43311 },
43312 "application/vnd.groove-identity-message": {
43313 "source": "iana",
43314 "extensions": ["gim"]
43315 },
43316 "application/vnd.groove-injector": {
43317 "source": "iana",
43318 "extensions": ["grv"]
43319 },
43320 "application/vnd.groove-tool-message": {
43321 "source": "iana",
43322 "extensions": ["gtm"]
43323 },
43324 "application/vnd.groove-tool-template": {
43325 "source": "iana",
43326 "extensions": ["tpl"]
43327 },
43328 "application/vnd.groove-vcard": {
43329 "source": "iana",
43330 "extensions": ["vcg"]
43331 },
43332 "application/vnd.hal+json": {
43333 "source": "iana",
43334 "compressible": true
43335 },
43336 "application/vnd.hal+xml": {
43337 "source": "iana",
43338 "compressible": true,
43339 "extensions": ["hal"]
43340 },
43341 "application/vnd.handheld-entertainment+xml": {
43342 "source": "iana",
43343 "compressible": true,
43344 "extensions": ["zmm"]
43345 },
43346 "application/vnd.hbci": {
43347 "source": "iana",
43348 "extensions": ["hbci"]
43349 },
43350 "application/vnd.hc+json": {
43351 "source": "iana",
43352 "compressible": true
43353 },
43354 "application/vnd.hcl-bireports": {
43355 "source": "iana"
43356 },
43357 "application/vnd.hdt": {
43358 "source": "iana"
43359 },
43360 "application/vnd.heroku+json": {
43361 "source": "iana",
43362 "compressible": true
43363 },
43364 "application/vnd.hhe.lesson-player": {
43365 "source": "iana",
43366 "extensions": ["les"]
43367 },
43368 "application/vnd.hp-hpgl": {
43369 "source": "iana",
43370 "extensions": ["hpgl"]
43371 },
43372 "application/vnd.hp-hpid": {
43373 "source": "iana",
43374 "extensions": ["hpid"]
43375 },
43376 "application/vnd.hp-hps": {
43377 "source": "iana",
43378 "extensions": ["hps"]
43379 },
43380 "application/vnd.hp-jlyt": {
43381 "source": "iana",
43382 "extensions": ["jlt"]
43383 },
43384 "application/vnd.hp-pcl": {
43385 "source": "iana",
43386 "extensions": ["pcl"]
43387 },
43388 "application/vnd.hp-pclxl": {
43389 "source": "iana",
43390 "extensions": ["pclxl"]
43391 },
43392 "application/vnd.httphone": {
43393 "source": "iana"
43394 },
43395 "application/vnd.hydrostatix.sof-data": {
43396 "source": "iana",
43397 "extensions": ["sfd-hdstx"]
43398 },
43399 "application/vnd.hyper+json": {
43400 "source": "iana",
43401 "compressible": true
43402 },
43403 "application/vnd.hyper-item+json": {
43404 "source": "iana",
43405 "compressible": true
43406 },
43407 "application/vnd.hyperdrive+json": {
43408 "source": "iana",
43409 "compressible": true
43410 },
43411 "application/vnd.hzn-3d-crossword": {
43412 "source": "iana"
43413 },
43414 "application/vnd.ibm.afplinedata": {
43415 "source": "iana"
43416 },
43417 "application/vnd.ibm.electronic-media": {
43418 "source": "iana"
43419 },
43420 "application/vnd.ibm.minipay": {
43421 "source": "iana",
43422 "extensions": ["mpy"]
43423 },
43424 "application/vnd.ibm.modcap": {
43425 "source": "iana",
43426 "extensions": ["afp","listafp","list3820"]
43427 },
43428 "application/vnd.ibm.rights-management": {
43429 "source": "iana",
43430 "extensions": ["irm"]
43431 },
43432 "application/vnd.ibm.secure-container": {
43433 "source": "iana",
43434 "extensions": ["sc"]
43435 },
43436 "application/vnd.iccprofile": {
43437 "source": "iana",
43438 "extensions": ["icc","icm"]
43439 },
43440 "application/vnd.ieee.1905": {
43441 "source": "iana"
43442 },
43443 "application/vnd.igloader": {
43444 "source": "iana",
43445 "extensions": ["igl"]
43446 },
43447 "application/vnd.imagemeter.folder+zip": {
43448 "source": "iana",
43449 "compressible": false
43450 },
43451 "application/vnd.imagemeter.image+zip": {
43452 "source": "iana",
43453 "compressible": false
43454 },
43455 "application/vnd.immervision-ivp": {
43456 "source": "iana",
43457 "extensions": ["ivp"]
43458 },
43459 "application/vnd.immervision-ivu": {
43460 "source": "iana",
43461 "extensions": ["ivu"]
43462 },
43463 "application/vnd.ims.imsccv1p1": {
43464 "source": "iana"
43465 },
43466 "application/vnd.ims.imsccv1p2": {
43467 "source": "iana"
43468 },
43469 "application/vnd.ims.imsccv1p3": {
43470 "source": "iana"
43471 },
43472 "application/vnd.ims.lis.v2.result+json": {
43473 "source": "iana",
43474 "compressible": true
43475 },
43476 "application/vnd.ims.lti.v2.toolconsumerprofile+json": {
43477 "source": "iana",
43478 "compressible": true
43479 },
43480 "application/vnd.ims.lti.v2.toolproxy+json": {
43481 "source": "iana",
43482 "compressible": true
43483 },
43484 "application/vnd.ims.lti.v2.toolproxy.id+json": {
43485 "source": "iana",
43486 "compressible": true
43487 },
43488 "application/vnd.ims.lti.v2.toolsettings+json": {
43489 "source": "iana",
43490 "compressible": true
43491 },
43492 "application/vnd.ims.lti.v2.toolsettings.simple+json": {
43493 "source": "iana",
43494 "compressible": true
43495 },
43496 "application/vnd.informedcontrol.rms+xml": {
43497 "source": "iana",
43498 "compressible": true
43499 },
43500 "application/vnd.informix-visionary": {
43501 "source": "iana"
43502 },
43503 "application/vnd.infotech.project": {
43504 "source": "iana"
43505 },
43506 "application/vnd.infotech.project+xml": {
43507 "source": "iana",
43508 "compressible": true
43509 },
43510 "application/vnd.innopath.wamp.notification": {
43511 "source": "iana"
43512 },
43513 "application/vnd.insors.igm": {
43514 "source": "iana",
43515 "extensions": ["igm"]
43516 },
43517 "application/vnd.intercon.formnet": {
43518 "source": "iana",
43519 "extensions": ["xpw","xpx"]
43520 },
43521 "application/vnd.intergeo": {
43522 "source": "iana",
43523 "extensions": ["i2g"]
43524 },
43525 "application/vnd.intertrust.digibox": {
43526 "source": "iana"
43527 },
43528 "application/vnd.intertrust.nncp": {
43529 "source": "iana"
43530 },
43531 "application/vnd.intu.qbo": {
43532 "source": "iana",
43533 "extensions": ["qbo"]
43534 },
43535 "application/vnd.intu.qfx": {
43536 "source": "iana",
43537 "extensions": ["qfx"]
43538 },
43539 "application/vnd.iptc.g2.catalogitem+xml": {
43540 "source": "iana",
43541 "compressible": true
43542 },
43543 "application/vnd.iptc.g2.conceptitem+xml": {
43544 "source": "iana",
43545 "compressible": true
43546 },
43547 "application/vnd.iptc.g2.knowledgeitem+xml": {
43548 "source": "iana",
43549 "compressible": true
43550 },
43551 "application/vnd.iptc.g2.newsitem+xml": {
43552 "source": "iana",
43553 "compressible": true
43554 },
43555 "application/vnd.iptc.g2.newsmessage+xml": {
43556 "source": "iana",
43557 "compressible": true
43558 },
43559 "application/vnd.iptc.g2.packageitem+xml": {
43560 "source": "iana",
43561 "compressible": true
43562 },
43563 "application/vnd.iptc.g2.planningitem+xml": {
43564 "source": "iana",
43565 "compressible": true
43566 },
43567 "application/vnd.ipunplugged.rcprofile": {
43568 "source": "iana",
43569 "extensions": ["rcprofile"]
43570 },
43571 "application/vnd.irepository.package+xml": {
43572 "source": "iana",
43573 "compressible": true,
43574 "extensions": ["irp"]
43575 },
43576 "application/vnd.is-xpr": {
43577 "source": "iana",
43578 "extensions": ["xpr"]
43579 },
43580 "application/vnd.isac.fcs": {
43581 "source": "iana",
43582 "extensions": ["fcs"]
43583 },
43584 "application/vnd.jam": {
43585 "source": "iana",
43586 "extensions": ["jam"]
43587 },
43588 "application/vnd.japannet-directory-service": {
43589 "source": "iana"
43590 },
43591 "application/vnd.japannet-jpnstore-wakeup": {
43592 "source": "iana"
43593 },
43594 "application/vnd.japannet-payment-wakeup": {
43595 "source": "iana"
43596 },
43597 "application/vnd.japannet-registration": {
43598 "source": "iana"
43599 },
43600 "application/vnd.japannet-registration-wakeup": {
43601 "source": "iana"
43602 },
43603 "application/vnd.japannet-setstore-wakeup": {
43604 "source": "iana"
43605 },
43606 "application/vnd.japannet-verification": {
43607 "source": "iana"
43608 },
43609 "application/vnd.japannet-verification-wakeup": {
43610 "source": "iana"
43611 },
43612 "application/vnd.jcp.javame.midlet-rms": {
43613 "source": "iana",
43614 "extensions": ["rms"]
43615 },
43616 "application/vnd.jisp": {
43617 "source": "iana",
43618 "extensions": ["jisp"]
43619 },
43620 "application/vnd.joost.joda-archive": {
43621 "source": "iana",
43622 "extensions": ["joda"]
43623 },
43624 "application/vnd.jsk.isdn-ngn": {
43625 "source": "iana"
43626 },
43627 "application/vnd.kahootz": {
43628 "source": "iana",
43629 "extensions": ["ktz","ktr"]
43630 },
43631 "application/vnd.kde.karbon": {
43632 "source": "iana",
43633 "extensions": ["karbon"]
43634 },
43635 "application/vnd.kde.kchart": {
43636 "source": "iana",
43637 "extensions": ["chrt"]
43638 },
43639 "application/vnd.kde.kformula": {
43640 "source": "iana",
43641 "extensions": ["kfo"]
43642 },
43643 "application/vnd.kde.kivio": {
43644 "source": "iana",
43645 "extensions": ["flw"]
43646 },
43647 "application/vnd.kde.kontour": {
43648 "source": "iana",
43649 "extensions": ["kon"]
43650 },
43651 "application/vnd.kde.kpresenter": {
43652 "source": "iana",
43653 "extensions": ["kpr","kpt"]
43654 },
43655 "application/vnd.kde.kspread": {
43656 "source": "iana",
43657 "extensions": ["ksp"]
43658 },
43659 "application/vnd.kde.kword": {
43660 "source": "iana",
43661 "extensions": ["kwd","kwt"]
43662 },
43663 "application/vnd.kenameaapp": {
43664 "source": "iana",
43665 "extensions": ["htke"]
43666 },
43667 "application/vnd.kidspiration": {
43668 "source": "iana",
43669 "extensions": ["kia"]
43670 },
43671 "application/vnd.kinar": {
43672 "source": "iana",
43673 "extensions": ["kne","knp"]
43674 },
43675 "application/vnd.koan": {
43676 "source": "iana",
43677 "extensions": ["skp","skd","skt","skm"]
43678 },
43679 "application/vnd.kodak-descriptor": {
43680 "source": "iana",
43681 "extensions": ["sse"]
43682 },
43683 "application/vnd.las.las+json": {
43684 "source": "iana",
43685 "compressible": true
43686 },
43687 "application/vnd.las.las+xml": {
43688 "source": "iana",
43689 "compressible": true,
43690 "extensions": ["lasxml"]
43691 },
43692 "application/vnd.leap+json": {
43693 "source": "iana",
43694 "compressible": true
43695 },
43696 "application/vnd.liberty-request+xml": {
43697 "source": "iana",
43698 "compressible": true
43699 },
43700 "application/vnd.llamagraphics.life-balance.desktop": {
43701 "source": "iana",
43702 "extensions": ["lbd"]
43703 },
43704 "application/vnd.llamagraphics.life-balance.exchange+xml": {
43705 "source": "iana",
43706 "compressible": true,
43707 "extensions": ["lbe"]
43708 },
43709 "application/vnd.lotus-1-2-3": {
43710 "source": "iana",
43711 "extensions": ["123"]
43712 },
43713 "application/vnd.lotus-approach": {
43714 "source": "iana",
43715 "extensions": ["apr"]
43716 },
43717 "application/vnd.lotus-freelance": {
43718 "source": "iana",
43719 "extensions": ["pre"]
43720 },
43721 "application/vnd.lotus-notes": {
43722 "source": "iana",
43723 "extensions": ["nsf"]
43724 },
43725 "application/vnd.lotus-organizer": {
43726 "source": "iana",
43727 "extensions": ["org"]
43728 },
43729 "application/vnd.lotus-screencam": {
43730 "source": "iana",
43731 "extensions": ["scm"]
43732 },
43733 "application/vnd.lotus-wordpro": {
43734 "source": "iana",
43735 "extensions": ["lwp"]
43736 },
43737 "application/vnd.macports.portpkg": {
43738 "source": "iana",
43739 "extensions": ["portpkg"]
43740 },
43741 "application/vnd.mapbox-vector-tile": {
43742 "source": "iana"
43743 },
43744 "application/vnd.marlin.drm.actiontoken+xml": {
43745 "source": "iana",
43746 "compressible": true
43747 },
43748 "application/vnd.marlin.drm.conftoken+xml": {
43749 "source": "iana",
43750 "compressible": true
43751 },
43752 "application/vnd.marlin.drm.license+xml": {
43753 "source": "iana",
43754 "compressible": true
43755 },
43756 "application/vnd.marlin.drm.mdcf": {
43757 "source": "iana"
43758 },
43759 "application/vnd.mason+json": {
43760 "source": "iana",
43761 "compressible": true
43762 },
43763 "application/vnd.maxmind.maxmind-db": {
43764 "source": "iana"
43765 },
43766 "application/vnd.mcd": {
43767 "source": "iana",
43768 "extensions": ["mcd"]
43769 },
43770 "application/vnd.medcalcdata": {
43771 "source": "iana",
43772 "extensions": ["mc1"]
43773 },
43774 "application/vnd.mediastation.cdkey": {
43775 "source": "iana",
43776 "extensions": ["cdkey"]
43777 },
43778 "application/vnd.meridian-slingshot": {
43779 "source": "iana"
43780 },
43781 "application/vnd.mfer": {
43782 "source": "iana",
43783 "extensions": ["mwf"]
43784 },
43785 "application/vnd.mfmp": {
43786 "source": "iana",
43787 "extensions": ["mfm"]
43788 },
43789 "application/vnd.micro+json": {
43790 "source": "iana",
43791 "compressible": true
43792 },
43793 "application/vnd.micrografx.flo": {
43794 "source": "iana",
43795 "extensions": ["flo"]
43796 },
43797 "application/vnd.micrografx.igx": {
43798 "source": "iana",
43799 "extensions": ["igx"]
43800 },
43801 "application/vnd.microsoft.portable-executable": {
43802 "source": "iana"
43803 },
43804 "application/vnd.microsoft.windows.thumbnail-cache": {
43805 "source": "iana"
43806 },
43807 "application/vnd.miele+json": {
43808 "source": "iana",
43809 "compressible": true
43810 },
43811 "application/vnd.mif": {
43812 "source": "iana",
43813 "extensions": ["mif"]
43814 },
43815 "application/vnd.minisoft-hp3000-save": {
43816 "source": "iana"
43817 },
43818 "application/vnd.mitsubishi.misty-guard.trustweb": {
43819 "source": "iana"
43820 },
43821 "application/vnd.mobius.daf": {
43822 "source": "iana",
43823 "extensions": ["daf"]
43824 },
43825 "application/vnd.mobius.dis": {
43826 "source": "iana",
43827 "extensions": ["dis"]
43828 },
43829 "application/vnd.mobius.mbk": {
43830 "source": "iana",
43831 "extensions": ["mbk"]
43832 },
43833 "application/vnd.mobius.mqy": {
43834 "source": "iana",
43835 "extensions": ["mqy"]
43836 },
43837 "application/vnd.mobius.msl": {
43838 "source": "iana",
43839 "extensions": ["msl"]
43840 },
43841 "application/vnd.mobius.plc": {
43842 "source": "iana",
43843 "extensions": ["plc"]
43844 },
43845 "application/vnd.mobius.txf": {
43846 "source": "iana",
43847 "extensions": ["txf"]
43848 },
43849 "application/vnd.mophun.application": {
43850 "source": "iana",
43851 "extensions": ["mpn"]
43852 },
43853 "application/vnd.mophun.certificate": {
43854 "source": "iana",
43855 "extensions": ["mpc"]
43856 },
43857 "application/vnd.motorola.flexsuite": {
43858 "source": "iana"
43859 },
43860 "application/vnd.motorola.flexsuite.adsi": {
43861 "source": "iana"
43862 },
43863 "application/vnd.motorola.flexsuite.fis": {
43864 "source": "iana"
43865 },
43866 "application/vnd.motorola.flexsuite.gotap": {
43867 "source": "iana"
43868 },
43869 "application/vnd.motorola.flexsuite.kmr": {
43870 "source": "iana"
43871 },
43872 "application/vnd.motorola.flexsuite.ttc": {
43873 "source": "iana"
43874 },
43875 "application/vnd.motorola.flexsuite.wem": {
43876 "source": "iana"
43877 },
43878 "application/vnd.motorola.iprm": {
43879 "source": "iana"
43880 },
43881 "application/vnd.mozilla.xul+xml": {
43882 "source": "iana",
43883 "compressible": true,
43884 "extensions": ["xul"]
43885 },
43886 "application/vnd.ms-3mfdocument": {
43887 "source": "iana"
43888 },
43889 "application/vnd.ms-artgalry": {
43890 "source": "iana",
43891 "extensions": ["cil"]
43892 },
43893 "application/vnd.ms-asf": {
43894 "source": "iana"
43895 },
43896 "application/vnd.ms-cab-compressed": {
43897 "source": "iana",
43898 "extensions": ["cab"]
43899 },
43900 "application/vnd.ms-color.iccprofile": {
43901 "source": "apache"
43902 },
43903 "application/vnd.ms-excel": {
43904 "source": "iana",
43905 "compressible": false,
43906 "extensions": ["xls","xlm","xla","xlc","xlt","xlw"]
43907 },
43908 "application/vnd.ms-excel.addin.macroenabled.12": {
43909 "source": "iana",
43910 "extensions": ["xlam"]
43911 },
43912 "application/vnd.ms-excel.sheet.binary.macroenabled.12": {
43913 "source": "iana",
43914 "extensions": ["xlsb"]
43915 },
43916 "application/vnd.ms-excel.sheet.macroenabled.12": {
43917 "source": "iana",
43918 "extensions": ["xlsm"]
43919 },
43920 "application/vnd.ms-excel.template.macroenabled.12": {
43921 "source": "iana",
43922 "extensions": ["xltm"]
43923 },
43924 "application/vnd.ms-fontobject": {
43925 "source": "iana",
43926 "compressible": true,
43927 "extensions": ["eot"]
43928 },
43929 "application/vnd.ms-htmlhelp": {
43930 "source": "iana",
43931 "extensions": ["chm"]
43932 },
43933 "application/vnd.ms-ims": {
43934 "source": "iana",
43935 "extensions": ["ims"]
43936 },
43937 "application/vnd.ms-lrm": {
43938 "source": "iana",
43939 "extensions": ["lrm"]
43940 },
43941 "application/vnd.ms-office.activex+xml": {
43942 "source": "iana",
43943 "compressible": true
43944 },
43945 "application/vnd.ms-officetheme": {
43946 "source": "iana",
43947 "extensions": ["thmx"]
43948 },
43949 "application/vnd.ms-opentype": {
43950 "source": "apache",
43951 "compressible": true
43952 },
43953 "application/vnd.ms-outlook": {
43954 "compressible": false,
43955 "extensions": ["msg"]
43956 },
43957 "application/vnd.ms-package.obfuscated-opentype": {
43958 "source": "apache"
43959 },
43960 "application/vnd.ms-pki.seccat": {
43961 "source": "apache",
43962 "extensions": ["cat"]
43963 },
43964 "application/vnd.ms-pki.stl": {
43965 "source": "apache",
43966 "extensions": ["stl"]
43967 },
43968 "application/vnd.ms-playready.initiator+xml": {
43969 "source": "iana",
43970 "compressible": true
43971 },
43972 "application/vnd.ms-powerpoint": {
43973 "source": "iana",
43974 "compressible": false,
43975 "extensions": ["ppt","pps","pot"]
43976 },
43977 "application/vnd.ms-powerpoint.addin.macroenabled.12": {
43978 "source": "iana",
43979 "extensions": ["ppam"]
43980 },
43981 "application/vnd.ms-powerpoint.presentation.macroenabled.12": {
43982 "source": "iana",
43983 "extensions": ["pptm"]
43984 },
43985 "application/vnd.ms-powerpoint.slide.macroenabled.12": {
43986 "source": "iana",
43987 "extensions": ["sldm"]
43988 },
43989 "application/vnd.ms-powerpoint.slideshow.macroenabled.12": {
43990 "source": "iana",
43991 "extensions": ["ppsm"]
43992 },
43993 "application/vnd.ms-powerpoint.template.macroenabled.12": {
43994 "source": "iana",
43995 "extensions": ["potm"]
43996 },
43997 "application/vnd.ms-printdevicecapabilities+xml": {
43998 "source": "iana",
43999 "compressible": true
44000 },
44001 "application/vnd.ms-printing.printticket+xml": {
44002 "source": "apache",
44003 "compressible": true
44004 },
44005 "application/vnd.ms-printschematicket+xml": {
44006 "source": "iana",
44007 "compressible": true
44008 },
44009 "application/vnd.ms-project": {
44010 "source": "iana",
44011 "extensions": ["mpp","mpt"]
44012 },
44013 "application/vnd.ms-tnef": {
44014 "source": "iana"
44015 },
44016 "application/vnd.ms-windows.devicepairing": {
44017 "source": "iana"
44018 },
44019 "application/vnd.ms-windows.nwprinting.oob": {
44020 "source": "iana"
44021 },
44022 "application/vnd.ms-windows.printerpairing": {
44023 "source": "iana"
44024 },
44025 "application/vnd.ms-windows.wsd.oob": {
44026 "source": "iana"
44027 },
44028 "application/vnd.ms-wmdrm.lic-chlg-req": {
44029 "source": "iana"
44030 },
44031 "application/vnd.ms-wmdrm.lic-resp": {
44032 "source": "iana"
44033 },
44034 "application/vnd.ms-wmdrm.meter-chlg-req": {
44035 "source": "iana"
44036 },
44037 "application/vnd.ms-wmdrm.meter-resp": {
44038 "source": "iana"
44039 },
44040 "application/vnd.ms-word.document.macroenabled.12": {
44041 "source": "iana",
44042 "extensions": ["docm"]
44043 },
44044 "application/vnd.ms-word.template.macroenabled.12": {
44045 "source": "iana",
44046 "extensions": ["dotm"]
44047 },
44048 "application/vnd.ms-works": {
44049 "source": "iana",
44050 "extensions": ["wps","wks","wcm","wdb"]
44051 },
44052 "application/vnd.ms-wpl": {
44053 "source": "iana",
44054 "extensions": ["wpl"]
44055 },
44056 "application/vnd.ms-xpsdocument": {
44057 "source": "iana",
44058 "compressible": false,
44059 "extensions": ["xps"]
44060 },
44061 "application/vnd.msa-disk-image": {
44062 "source": "iana"
44063 },
44064 "application/vnd.mseq": {
44065 "source": "iana",
44066 "extensions": ["mseq"]
44067 },
44068 "application/vnd.msign": {
44069 "source": "iana"
44070 },
44071 "application/vnd.multiad.creator": {
44072 "source": "iana"
44073 },
44074 "application/vnd.multiad.creator.cif": {
44075 "source": "iana"
44076 },
44077 "application/vnd.music-niff": {
44078 "source": "iana"
44079 },
44080 "application/vnd.musician": {
44081 "source": "iana",
44082 "extensions": ["mus"]
44083 },
44084 "application/vnd.muvee.style": {
44085 "source": "iana",
44086 "extensions": ["msty"]
44087 },
44088 "application/vnd.mynfc": {
44089 "source": "iana",
44090 "extensions": ["taglet"]
44091 },
44092 "application/vnd.ncd.control": {
44093 "source": "iana"
44094 },
44095 "application/vnd.ncd.reference": {
44096 "source": "iana"
44097 },
44098 "application/vnd.nearst.inv+json": {
44099 "source": "iana",
44100 "compressible": true
44101 },
44102 "application/vnd.nervana": {
44103 "source": "iana"
44104 },
44105 "application/vnd.netfpx": {
44106 "source": "iana"
44107 },
44108 "application/vnd.neurolanguage.nlu": {
44109 "source": "iana",
44110 "extensions": ["nlu"]
44111 },
44112 "application/vnd.nimn": {
44113 "source": "iana"
44114 },
44115 "application/vnd.nintendo.nitro.rom": {
44116 "source": "iana"
44117 },
44118 "application/vnd.nintendo.snes.rom": {
44119 "source": "iana"
44120 },
44121 "application/vnd.nitf": {
44122 "source": "iana",
44123 "extensions": ["ntf","nitf"]
44124 },
44125 "application/vnd.noblenet-directory": {
44126 "source": "iana",
44127 "extensions": ["nnd"]
44128 },
44129 "application/vnd.noblenet-sealer": {
44130 "source": "iana",
44131 "extensions": ["nns"]
44132 },
44133 "application/vnd.noblenet-web": {
44134 "source": "iana",
44135 "extensions": ["nnw"]
44136 },
44137 "application/vnd.nokia.catalogs": {
44138 "source": "iana"
44139 },
44140 "application/vnd.nokia.conml+wbxml": {
44141 "source": "iana"
44142 },
44143 "application/vnd.nokia.conml+xml": {
44144 "source": "iana",
44145 "compressible": true
44146 },
44147 "application/vnd.nokia.iptv.config+xml": {
44148 "source": "iana",
44149 "compressible": true
44150 },
44151 "application/vnd.nokia.isds-radio-presets": {
44152 "source": "iana"
44153 },
44154 "application/vnd.nokia.landmark+wbxml": {
44155 "source": "iana"
44156 },
44157 "application/vnd.nokia.landmark+xml": {
44158 "source": "iana",
44159 "compressible": true
44160 },
44161 "application/vnd.nokia.landmarkcollection+xml": {
44162 "source": "iana",
44163 "compressible": true
44164 },
44165 "application/vnd.nokia.n-gage.ac+xml": {
44166 "source": "iana",
44167 "compressible": true
44168 },
44169 "application/vnd.nokia.n-gage.data": {
44170 "source": "iana",
44171 "extensions": ["ngdat"]
44172 },
44173 "application/vnd.nokia.n-gage.symbian.install": {
44174 "source": "iana",
44175 "extensions": ["n-gage"]
44176 },
44177 "application/vnd.nokia.ncd": {
44178 "source": "iana"
44179 },
44180 "application/vnd.nokia.pcd+wbxml": {
44181 "source": "iana"
44182 },
44183 "application/vnd.nokia.pcd+xml": {
44184 "source": "iana",
44185 "compressible": true
44186 },
44187 "application/vnd.nokia.radio-preset": {
44188 "source": "iana",
44189 "extensions": ["rpst"]
44190 },
44191 "application/vnd.nokia.radio-presets": {
44192 "source": "iana",
44193 "extensions": ["rpss"]
44194 },
44195 "application/vnd.novadigm.edm": {
44196 "source": "iana",
44197 "extensions": ["edm"]
44198 },
44199 "application/vnd.novadigm.edx": {
44200 "source": "iana",
44201 "extensions": ["edx"]
44202 },
44203 "application/vnd.novadigm.ext": {
44204 "source": "iana",
44205 "extensions": ["ext"]
44206 },
44207 "application/vnd.ntt-local.content-share": {
44208 "source": "iana"
44209 },
44210 "application/vnd.ntt-local.file-transfer": {
44211 "source": "iana"
44212 },
44213 "application/vnd.ntt-local.ogw_remote-access": {
44214 "source": "iana"
44215 },
44216 "application/vnd.ntt-local.sip-ta_remote": {
44217 "source": "iana"
44218 },
44219 "application/vnd.ntt-local.sip-ta_tcp_stream": {
44220 "source": "iana"
44221 },
44222 "application/vnd.oasis.opendocument.chart": {
44223 "source": "iana",
44224 "extensions": ["odc"]
44225 },
44226 "application/vnd.oasis.opendocument.chart-template": {
44227 "source": "iana",
44228 "extensions": ["otc"]
44229 },
44230 "application/vnd.oasis.opendocument.database": {
44231 "source": "iana",
44232 "extensions": ["odb"]
44233 },
44234 "application/vnd.oasis.opendocument.formula": {
44235 "source": "iana",
44236 "extensions": ["odf"]
44237 },
44238 "application/vnd.oasis.opendocument.formula-template": {
44239 "source": "iana",
44240 "extensions": ["odft"]
44241 },
44242 "application/vnd.oasis.opendocument.graphics": {
44243 "source": "iana",
44244 "compressible": false,
44245 "extensions": ["odg"]
44246 },
44247 "application/vnd.oasis.opendocument.graphics-template": {
44248 "source": "iana",
44249 "extensions": ["otg"]
44250 },
44251 "application/vnd.oasis.opendocument.image": {
44252 "source": "iana",
44253 "extensions": ["odi"]
44254 },
44255 "application/vnd.oasis.opendocument.image-template": {
44256 "source": "iana",
44257 "extensions": ["oti"]
44258 },
44259 "application/vnd.oasis.opendocument.presentation": {
44260 "source": "iana",
44261 "compressible": false,
44262 "extensions": ["odp"]
44263 },
44264 "application/vnd.oasis.opendocument.presentation-template": {
44265 "source": "iana",
44266 "extensions": ["otp"]
44267 },
44268 "application/vnd.oasis.opendocument.spreadsheet": {
44269 "source": "iana",
44270 "compressible": false,
44271 "extensions": ["ods"]
44272 },
44273 "application/vnd.oasis.opendocument.spreadsheet-template": {
44274 "source": "iana",
44275 "extensions": ["ots"]
44276 },
44277 "application/vnd.oasis.opendocument.text": {
44278 "source": "iana",
44279 "compressible": false,
44280 "extensions": ["odt"]
44281 },
44282 "application/vnd.oasis.opendocument.text-master": {
44283 "source": "iana",
44284 "extensions": ["odm"]
44285 },
44286 "application/vnd.oasis.opendocument.text-template": {
44287 "source": "iana",
44288 "extensions": ["ott"]
44289 },
44290 "application/vnd.oasis.opendocument.text-web": {
44291 "source": "iana",
44292 "extensions": ["oth"]
44293 },
44294 "application/vnd.obn": {
44295 "source": "iana"
44296 },
44297 "application/vnd.ocf+cbor": {
44298 "source": "iana"
44299 },
44300 "application/vnd.oftn.l10n+json": {
44301 "source": "iana",
44302 "compressible": true
44303 },
44304 "application/vnd.oipf.contentaccessdownload+xml": {
44305 "source": "iana",
44306 "compressible": true
44307 },
44308 "application/vnd.oipf.contentaccessstreaming+xml": {
44309 "source": "iana",
44310 "compressible": true
44311 },
44312 "application/vnd.oipf.cspg-hexbinary": {
44313 "source": "iana"
44314 },
44315 "application/vnd.oipf.dae.svg+xml": {
44316 "source": "iana",
44317 "compressible": true
44318 },
44319 "application/vnd.oipf.dae.xhtml+xml": {
44320 "source": "iana",
44321 "compressible": true
44322 },
44323 "application/vnd.oipf.mippvcontrolmessage+xml": {
44324 "source": "iana",
44325 "compressible": true
44326 },
44327 "application/vnd.oipf.pae.gem": {
44328 "source": "iana"
44329 },
44330 "application/vnd.oipf.spdiscovery+xml": {
44331 "source": "iana",
44332 "compressible": true
44333 },
44334 "application/vnd.oipf.spdlist+xml": {
44335 "source": "iana",
44336 "compressible": true
44337 },
44338 "application/vnd.oipf.ueprofile+xml": {
44339 "source": "iana",
44340 "compressible": true
44341 },
44342 "application/vnd.oipf.userprofile+xml": {
44343 "source": "iana",
44344 "compressible": true
44345 },
44346 "application/vnd.olpc-sugar": {
44347 "source": "iana",
44348 "extensions": ["xo"]
44349 },
44350 "application/vnd.oma-scws-config": {
44351 "source": "iana"
44352 },
44353 "application/vnd.oma-scws-http-request": {
44354 "source": "iana"
44355 },
44356 "application/vnd.oma-scws-http-response": {
44357 "source": "iana"
44358 },
44359 "application/vnd.oma.bcast.associated-procedure-parameter+xml": {
44360 "source": "iana",
44361 "compressible": true
44362 },
44363 "application/vnd.oma.bcast.drm-trigger+xml": {
44364 "source": "iana",
44365 "compressible": true
44366 },
44367 "application/vnd.oma.bcast.imd+xml": {
44368 "source": "iana",
44369 "compressible": true
44370 },
44371 "application/vnd.oma.bcast.ltkm": {
44372 "source": "iana"
44373 },
44374 "application/vnd.oma.bcast.notification+xml": {
44375 "source": "iana",
44376 "compressible": true
44377 },
44378 "application/vnd.oma.bcast.provisioningtrigger": {
44379 "source": "iana"
44380 },
44381 "application/vnd.oma.bcast.sgboot": {
44382 "source": "iana"
44383 },
44384 "application/vnd.oma.bcast.sgdd+xml": {
44385 "source": "iana",
44386 "compressible": true
44387 },
44388 "application/vnd.oma.bcast.sgdu": {
44389 "source": "iana"
44390 },
44391 "application/vnd.oma.bcast.simple-symbol-container": {
44392 "source": "iana"
44393 },
44394 "application/vnd.oma.bcast.smartcard-trigger+xml": {
44395 "source": "iana",
44396 "compressible": true
44397 },
44398 "application/vnd.oma.bcast.sprov+xml": {
44399 "source": "iana",
44400 "compressible": true
44401 },
44402 "application/vnd.oma.bcast.stkm": {
44403 "source": "iana"
44404 },
44405 "application/vnd.oma.cab-address-book+xml": {
44406 "source": "iana",
44407 "compressible": true
44408 },
44409 "application/vnd.oma.cab-feature-handler+xml": {
44410 "source": "iana",
44411 "compressible": true
44412 },
44413 "application/vnd.oma.cab-pcc+xml": {
44414 "source": "iana",
44415 "compressible": true
44416 },
44417 "application/vnd.oma.cab-subs-invite+xml": {
44418 "source": "iana",
44419 "compressible": true
44420 },
44421 "application/vnd.oma.cab-user-prefs+xml": {
44422 "source": "iana",
44423 "compressible": true
44424 },
44425 "application/vnd.oma.dcd": {
44426 "source": "iana"
44427 },
44428 "application/vnd.oma.dcdc": {
44429 "source": "iana"
44430 },
44431 "application/vnd.oma.dd2+xml": {
44432 "source": "iana",
44433 "compressible": true,
44434 "extensions": ["dd2"]
44435 },
44436 "application/vnd.oma.drm.risd+xml": {
44437 "source": "iana",
44438 "compressible": true
44439 },
44440 "application/vnd.oma.group-usage-list+xml": {
44441 "source": "iana",
44442 "compressible": true
44443 },
44444 "application/vnd.oma.lwm2m+json": {
44445 "source": "iana",
44446 "compressible": true
44447 },
44448 "application/vnd.oma.lwm2m+tlv": {
44449 "source": "iana"
44450 },
44451 "application/vnd.oma.pal+xml": {
44452 "source": "iana",
44453 "compressible": true
44454 },
44455 "application/vnd.oma.poc.detailed-progress-report+xml": {
44456 "source": "iana",
44457 "compressible": true
44458 },
44459 "application/vnd.oma.poc.final-report+xml": {
44460 "source": "iana",
44461 "compressible": true
44462 },
44463 "application/vnd.oma.poc.groups+xml": {
44464 "source": "iana",
44465 "compressible": true
44466 },
44467 "application/vnd.oma.poc.invocation-descriptor+xml": {
44468 "source": "iana",
44469 "compressible": true
44470 },
44471 "application/vnd.oma.poc.optimized-progress-report+xml": {
44472 "source": "iana",
44473 "compressible": true
44474 },
44475 "application/vnd.oma.push": {
44476 "source": "iana"
44477 },
44478 "application/vnd.oma.scidm.messages+xml": {
44479 "source": "iana",
44480 "compressible": true
44481 },
44482 "application/vnd.oma.xcap-directory+xml": {
44483 "source": "iana",
44484 "compressible": true
44485 },
44486 "application/vnd.omads-email+xml": {
44487 "source": "iana",
44488 "compressible": true
44489 },
44490 "application/vnd.omads-file+xml": {
44491 "source": "iana",
44492 "compressible": true
44493 },
44494 "application/vnd.omads-folder+xml": {
44495 "source": "iana",
44496 "compressible": true
44497 },
44498 "application/vnd.omaloc-supl-init": {
44499 "source": "iana"
44500 },
44501 "application/vnd.onepager": {
44502 "source": "iana"
44503 },
44504 "application/vnd.onepagertamp": {
44505 "source": "iana"
44506 },
44507 "application/vnd.onepagertamx": {
44508 "source": "iana"
44509 },
44510 "application/vnd.onepagertat": {
44511 "source": "iana"
44512 },
44513 "application/vnd.onepagertatp": {
44514 "source": "iana"
44515 },
44516 "application/vnd.onepagertatx": {
44517 "source": "iana"
44518 },
44519 "application/vnd.openblox.game+xml": {
44520 "source": "iana",
44521 "compressible": true
44522 },
44523 "application/vnd.openblox.game-binary": {
44524 "source": "iana"
44525 },
44526 "application/vnd.openeye.oeb": {
44527 "source": "iana"
44528 },
44529 "application/vnd.openofficeorg.extension": {
44530 "source": "apache",
44531 "extensions": ["oxt"]
44532 },
44533 "application/vnd.openstreetmap.data+xml": {
44534 "source": "iana",
44535 "compressible": true
44536 },
44537 "application/vnd.openxmlformats-officedocument.custom-properties+xml": {
44538 "source": "iana",
44539 "compressible": true
44540 },
44541 "application/vnd.openxmlformats-officedocument.customxmlproperties+xml": {
44542 "source": "iana",
44543 "compressible": true
44544 },
44545 "application/vnd.openxmlformats-officedocument.drawing+xml": {
44546 "source": "iana",
44547 "compressible": true
44548 },
44549 "application/vnd.openxmlformats-officedocument.drawingml.chart+xml": {
44550 "source": "iana",
44551 "compressible": true
44552 },
44553 "application/vnd.openxmlformats-officedocument.drawingml.chartshapes+xml": {
44554 "source": "iana",
44555 "compressible": true
44556 },
44557 "application/vnd.openxmlformats-officedocument.drawingml.diagramcolors+xml": {
44558 "source": "iana",
44559 "compressible": true
44560 },
44561 "application/vnd.openxmlformats-officedocument.drawingml.diagramdata+xml": {
44562 "source": "iana",
44563 "compressible": true
44564 },
44565 "application/vnd.openxmlformats-officedocument.drawingml.diagramlayout+xml": {
44566 "source": "iana",
44567 "compressible": true
44568 },
44569 "application/vnd.openxmlformats-officedocument.drawingml.diagramstyle+xml": {
44570 "source": "iana",
44571 "compressible": true
44572 },
44573 "application/vnd.openxmlformats-officedocument.extended-properties+xml": {
44574 "source": "iana",
44575 "compressible": true
44576 },
44577 "application/vnd.openxmlformats-officedocument.presentationml.commentauthors+xml": {
44578 "source": "iana",
44579 "compressible": true
44580 },
44581 "application/vnd.openxmlformats-officedocument.presentationml.comments+xml": {
44582 "source": "iana",
44583 "compressible": true
44584 },
44585 "application/vnd.openxmlformats-officedocument.presentationml.handoutmaster+xml": {
44586 "source": "iana",
44587 "compressible": true
44588 },
44589 "application/vnd.openxmlformats-officedocument.presentationml.notesmaster+xml": {
44590 "source": "iana",
44591 "compressible": true
44592 },
44593 "application/vnd.openxmlformats-officedocument.presentationml.notesslide+xml": {
44594 "source": "iana",
44595 "compressible": true
44596 },
44597 "application/vnd.openxmlformats-officedocument.presentationml.presentation": {
44598 "source": "iana",
44599 "compressible": false,
44600 "extensions": ["pptx"]
44601 },
44602 "application/vnd.openxmlformats-officedocument.presentationml.presentation.main+xml": {
44603 "source": "iana",
44604 "compressible": true
44605 },
44606 "application/vnd.openxmlformats-officedocument.presentationml.presprops+xml": {
44607 "source": "iana",
44608 "compressible": true
44609 },
44610 "application/vnd.openxmlformats-officedocument.presentationml.slide": {
44611 "source": "iana",
44612 "extensions": ["sldx"]
44613 },
44614 "application/vnd.openxmlformats-officedocument.presentationml.slide+xml": {
44615 "source": "iana",
44616 "compressible": true
44617 },
44618 "application/vnd.openxmlformats-officedocument.presentationml.slidelayout+xml": {
44619 "source": "iana",
44620 "compressible": true
44621 },
44622 "application/vnd.openxmlformats-officedocument.presentationml.slidemaster+xml": {
44623 "source": "iana",
44624 "compressible": true
44625 },
44626 "application/vnd.openxmlformats-officedocument.presentationml.slideshow": {
44627 "source": "iana",
44628 "extensions": ["ppsx"]
44629 },
44630 "application/vnd.openxmlformats-officedocument.presentationml.slideshow.main+xml": {
44631 "source": "iana",
44632 "compressible": true
44633 },
44634 "application/vnd.openxmlformats-officedocument.presentationml.slideupdateinfo+xml": {
44635 "source": "iana",
44636 "compressible": true
44637 },
44638 "application/vnd.openxmlformats-officedocument.presentationml.tablestyles+xml": {
44639 "source": "iana",
44640 "compressible": true
44641 },
44642 "application/vnd.openxmlformats-officedocument.presentationml.tags+xml": {
44643 "source": "iana",
44644 "compressible": true
44645 },
44646 "application/vnd.openxmlformats-officedocument.presentationml.template": {
44647 "source": "iana",
44648 "extensions": ["potx"]
44649 },
44650 "application/vnd.openxmlformats-officedocument.presentationml.template.main+xml": {
44651 "source": "iana",
44652 "compressible": true
44653 },
44654 "application/vnd.openxmlformats-officedocument.presentationml.viewprops+xml": {
44655 "source": "iana",
44656 "compressible": true
44657 },
44658 "application/vnd.openxmlformats-officedocument.spreadsheetml.calcchain+xml": {
44659 "source": "iana",
44660 "compressible": true
44661 },
44662 "application/vnd.openxmlformats-officedocument.spreadsheetml.chartsheet+xml": {
44663 "source": "iana",
44664 "compressible": true
44665 },
44666 "application/vnd.openxmlformats-officedocument.spreadsheetml.comments+xml": {
44667 "source": "iana",
44668 "compressible": true
44669 },
44670 "application/vnd.openxmlformats-officedocument.spreadsheetml.connections+xml": {
44671 "source": "iana",
44672 "compressible": true
44673 },
44674 "application/vnd.openxmlformats-officedocument.spreadsheetml.dialogsheet+xml": {
44675 "source": "iana",
44676 "compressible": true
44677 },
44678 "application/vnd.openxmlformats-officedocument.spreadsheetml.externallink+xml": {
44679 "source": "iana",
44680 "compressible": true
44681 },
44682 "application/vnd.openxmlformats-officedocument.spreadsheetml.pivotcachedefinition+xml": {
44683 "source": "iana",
44684 "compressible": true
44685 },
44686 "application/vnd.openxmlformats-officedocument.spreadsheetml.pivotcacherecords+xml": {
44687 "source": "iana",
44688 "compressible": true
44689 },
44690 "application/vnd.openxmlformats-officedocument.spreadsheetml.pivottable+xml": {
44691 "source": "iana",
44692 "compressible": true
44693 },
44694 "application/vnd.openxmlformats-officedocument.spreadsheetml.querytable+xml": {
44695 "source": "iana",
44696 "compressible": true
44697 },
44698 "application/vnd.openxmlformats-officedocument.spreadsheetml.revisionheaders+xml": {
44699 "source": "iana",
44700 "compressible": true
44701 },
44702 "application/vnd.openxmlformats-officedocument.spreadsheetml.revisionlog+xml": {
44703 "source": "iana",
44704 "compressible": true
44705 },
44706 "application/vnd.openxmlformats-officedocument.spreadsheetml.sharedstrings+xml": {
44707 "source": "iana",
44708 "compressible": true
44709 },
44710 "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": {
44711 "source": "iana",
44712 "compressible": false,
44713 "extensions": ["xlsx"]
44714 },
44715 "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml": {
44716 "source": "iana",
44717 "compressible": true
44718 },
44719 "application/vnd.openxmlformats-officedocument.spreadsheetml.sheetmetadata+xml": {
44720 "source": "iana",
44721 "compressible": true
44722 },
44723 "application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml": {
44724 "source": "iana",
44725 "compressible": true
44726 },
44727 "application/vnd.openxmlformats-officedocument.spreadsheetml.table+xml": {
44728 "source": "iana",
44729 "compressible": true
44730 },
44731 "application/vnd.openxmlformats-officedocument.spreadsheetml.tablesinglecells+xml": {
44732 "source": "iana",
44733 "compressible": true
44734 },
44735 "application/vnd.openxmlformats-officedocument.spreadsheetml.template": {
44736 "source": "iana",
44737 "extensions": ["xltx"]
44738 },
44739 "application/vnd.openxmlformats-officedocument.spreadsheetml.template.main+xml": {
44740 "source": "iana",
44741 "compressible": true
44742 },
44743 "application/vnd.openxmlformats-officedocument.spreadsheetml.usernames+xml": {
44744 "source": "iana",
44745 "compressible": true
44746 },
44747 "application/vnd.openxmlformats-officedocument.spreadsheetml.volatiledependencies+xml": {
44748 "source": "iana",
44749 "compressible": true
44750 },
44751 "application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml": {
44752 "source": "iana",
44753 "compressible": true
44754 },
44755 "application/vnd.openxmlformats-officedocument.theme+xml": {
44756 "source": "iana",
44757 "compressible": true
44758 },
44759 "application/vnd.openxmlformats-officedocument.themeoverride+xml": {
44760 "source": "iana",
44761 "compressible": true
44762 },
44763 "application/vnd.openxmlformats-officedocument.vmldrawing": {
44764 "source": "iana"
44765 },
44766 "application/vnd.openxmlformats-officedocument.wordprocessingml.comments+xml": {
44767 "source": "iana",
44768 "compressible": true
44769 },
44770 "application/vnd.openxmlformats-officedocument.wordprocessingml.document": {
44771 "source": "iana",
44772 "compressible": false,
44773 "extensions": ["docx"]
44774 },
44775 "application/vnd.openxmlformats-officedocument.wordprocessingml.document.glossary+xml": {
44776 "source": "iana",
44777 "compressible": true
44778 },
44779 "application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml": {
44780 "source": "iana",
44781 "compressible": true
44782 },
44783 "application/vnd.openxmlformats-officedocument.wordprocessingml.endnotes+xml": {
44784 "source": "iana",
44785 "compressible": true
44786 },
44787 "application/vnd.openxmlformats-officedocument.wordprocessingml.fonttable+xml": {
44788 "source": "iana",
44789 "compressible": true
44790 },
44791 "application/vnd.openxmlformats-officedocument.wordprocessingml.footer+xml": {
44792 "source": "iana",
44793 "compressible": true
44794 },
44795 "application/vnd.openxmlformats-officedocument.wordprocessingml.footnotes+xml": {
44796 "source": "iana",
44797 "compressible": true
44798 },
44799 "application/vnd.openxmlformats-officedocument.wordprocessingml.numbering+xml": {
44800 "source": "iana",
44801 "compressible": true
44802 },
44803 "application/vnd.openxmlformats-officedocument.wordprocessingml.settings+xml": {
44804 "source": "iana",
44805 "compressible": true
44806 },
44807 "application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml": {
44808 "source": "iana",
44809 "compressible": true
44810 },
44811 "application/vnd.openxmlformats-officedocument.wordprocessingml.template": {
44812 "source": "iana",
44813 "extensions": ["dotx"]
44814 },
44815 "application/vnd.openxmlformats-officedocument.wordprocessingml.template.main+xml": {
44816 "source": "iana",
44817 "compressible": true
44818 },
44819 "application/vnd.openxmlformats-officedocument.wordprocessingml.websettings+xml": {
44820 "source": "iana",
44821 "compressible": true
44822 },
44823 "application/vnd.openxmlformats-package.core-properties+xml": {
44824 "source": "iana",
44825 "compressible": true
44826 },
44827 "application/vnd.openxmlformats-package.digital-signature-xmlsignature+xml": {
44828 "source": "iana",
44829 "compressible": true
44830 },
44831 "application/vnd.openxmlformats-package.relationships+xml": {
44832 "source": "iana",
44833 "compressible": true
44834 },
44835 "application/vnd.oracle.resource+json": {
44836 "source": "iana",
44837 "compressible": true
44838 },
44839 "application/vnd.orange.indata": {
44840 "source": "iana"
44841 },
44842 "application/vnd.osa.netdeploy": {
44843 "source": "iana"
44844 },
44845 "application/vnd.osgeo.mapguide.package": {
44846 "source": "iana",
44847 "extensions": ["mgp"]
44848 },
44849 "application/vnd.osgi.bundle": {
44850 "source": "iana"
44851 },
44852 "application/vnd.osgi.dp": {
44853 "source": "iana",
44854 "extensions": ["dp"]
44855 },
44856 "application/vnd.osgi.subsystem": {
44857 "source": "iana",
44858 "extensions": ["esa"]
44859 },
44860 "application/vnd.otps.ct-kip+xml": {
44861 "source": "iana",
44862 "compressible": true
44863 },
44864 "application/vnd.oxli.countgraph": {
44865 "source": "iana"
44866 },
44867 "application/vnd.pagerduty+json": {
44868 "source": "iana",
44869 "compressible": true
44870 },
44871 "application/vnd.palm": {
44872 "source": "iana",
44873 "extensions": ["pdb","pqa","oprc"]
44874 },
44875 "application/vnd.panoply": {
44876 "source": "iana"
44877 },
44878 "application/vnd.paos.xml": {
44879 "source": "iana"
44880 },
44881 "application/vnd.patentdive": {
44882 "source": "iana"
44883 },
44884 "application/vnd.patientecommsdoc": {
44885 "source": "iana"
44886 },
44887 "application/vnd.pawaafile": {
44888 "source": "iana",
44889 "extensions": ["paw"]
44890 },
44891 "application/vnd.pcos": {
44892 "source": "iana"
44893 },
44894 "application/vnd.pg.format": {
44895 "source": "iana",
44896 "extensions": ["str"]
44897 },
44898 "application/vnd.pg.osasli": {
44899 "source": "iana",
44900 "extensions": ["ei6"]
44901 },
44902 "application/vnd.piaccess.application-licence": {
44903 "source": "iana"
44904 },
44905 "application/vnd.picsel": {
44906 "source": "iana",
44907 "extensions": ["efif"]
44908 },
44909 "application/vnd.pmi.widget": {
44910 "source": "iana",
44911 "extensions": ["wg"]
44912 },
44913 "application/vnd.poc.group-advertisement+xml": {
44914 "source": "iana",
44915 "compressible": true
44916 },
44917 "application/vnd.pocketlearn": {
44918 "source": "iana",
44919 "extensions": ["plf"]
44920 },
44921 "application/vnd.powerbuilder6": {
44922 "source": "iana",
44923 "extensions": ["pbd"]
44924 },
44925 "application/vnd.powerbuilder6-s": {
44926 "source": "iana"
44927 },
44928 "application/vnd.powerbuilder7": {
44929 "source": "iana"
44930 },
44931 "application/vnd.powerbuilder7-s": {
44932 "source": "iana"
44933 },
44934 "application/vnd.powerbuilder75": {
44935 "source": "iana"
44936 },
44937 "application/vnd.powerbuilder75-s": {
44938 "source": "iana"
44939 },
44940 "application/vnd.preminet": {
44941 "source": "iana"
44942 },
44943 "application/vnd.previewsystems.box": {
44944 "source": "iana",
44945 "extensions": ["box"]
44946 },
44947 "application/vnd.proteus.magazine": {
44948 "source": "iana",
44949 "extensions": ["mgz"]
44950 },
44951 "application/vnd.psfs": {
44952 "source": "iana"
44953 },
44954 "application/vnd.publishare-delta-tree": {
44955 "source": "iana",
44956 "extensions": ["qps"]
44957 },
44958 "application/vnd.pvi.ptid1": {
44959 "source": "iana",
44960 "extensions": ["ptid"]
44961 },
44962 "application/vnd.pwg-multiplexed": {
44963 "source": "iana"
44964 },
44965 "application/vnd.pwg-xhtml-print+xml": {
44966 "source": "iana",
44967 "compressible": true
44968 },
44969 "application/vnd.qualcomm.brew-app-res": {
44970 "source": "iana"
44971 },
44972 "application/vnd.quarantainenet": {
44973 "source": "iana"
44974 },
44975 "application/vnd.quark.quarkxpress": {
44976 "source": "iana",
44977 "extensions": ["qxd","qxt","qwd","qwt","qxl","qxb"]
44978 },
44979 "application/vnd.quobject-quoxdocument": {
44980 "source": "iana"
44981 },
44982 "application/vnd.radisys.moml+xml": {
44983 "source": "iana",
44984 "compressible": true
44985 },
44986 "application/vnd.radisys.msml+xml": {
44987 "source": "iana",
44988 "compressible": true
44989 },
44990 "application/vnd.radisys.msml-audit+xml": {
44991 "source": "iana",
44992 "compressible": true
44993 },
44994 "application/vnd.radisys.msml-audit-conf+xml": {
44995 "source": "iana",
44996 "compressible": true
44997 },
44998 "application/vnd.radisys.msml-audit-conn+xml": {
44999 "source": "iana",
45000 "compressible": true
45001 },
45002 "application/vnd.radisys.msml-audit-dialog+xml": {
45003 "source": "iana",
45004 "compressible": true
45005 },
45006 "application/vnd.radisys.msml-audit-stream+xml": {
45007 "source": "iana",
45008 "compressible": true
45009 },
45010 "application/vnd.radisys.msml-conf+xml": {
45011 "source": "iana",
45012 "compressible": true
45013 },
45014 "application/vnd.radisys.msml-dialog+xml": {
45015 "source": "iana",
45016 "compressible": true
45017 },
45018 "application/vnd.radisys.msml-dialog-base+xml": {
45019 "source": "iana",
45020 "compressible": true
45021 },
45022 "application/vnd.radisys.msml-dialog-fax-detect+xml": {
45023 "source": "iana",
45024 "compressible": true
45025 },
45026 "application/vnd.radisys.msml-dialog-fax-sendrecv+xml": {
45027 "source": "iana",
45028 "compressible": true
45029 },
45030 "application/vnd.radisys.msml-dialog-group+xml": {
45031 "source": "iana",
45032 "compressible": true
45033 },
45034 "application/vnd.radisys.msml-dialog-speech+xml": {
45035 "source": "iana",
45036 "compressible": true
45037 },
45038 "application/vnd.radisys.msml-dialog-transform+xml": {
45039 "source": "iana",
45040 "compressible": true
45041 },
45042 "application/vnd.rainstor.data": {
45043 "source": "iana"
45044 },
45045 "application/vnd.rapid": {
45046 "source": "iana"
45047 },
45048 "application/vnd.rar": {
45049 "source": "iana"
45050 },
45051 "application/vnd.realvnc.bed": {
45052 "source": "iana",
45053 "extensions": ["bed"]
45054 },
45055 "application/vnd.recordare.musicxml": {
45056 "source": "iana",
45057 "extensions": ["mxl"]
45058 },
45059 "application/vnd.recordare.musicxml+xml": {
45060 "source": "iana",
45061 "compressible": true,
45062 "extensions": ["musicxml"]
45063 },
45064 "application/vnd.renlearn.rlprint": {
45065 "source": "iana"
45066 },
45067 "application/vnd.restful+json": {
45068 "source": "iana",
45069 "compressible": true
45070 },
45071 "application/vnd.rig.cryptonote": {
45072 "source": "iana",
45073 "extensions": ["cryptonote"]
45074 },
45075 "application/vnd.rim.cod": {
45076 "source": "apache",
45077 "extensions": ["cod"]
45078 },
45079 "application/vnd.rn-realmedia": {
45080 "source": "apache",
45081 "extensions": ["rm"]
45082 },
45083 "application/vnd.rn-realmedia-vbr": {
45084 "source": "apache",
45085 "extensions": ["rmvb"]
45086 },
45087 "application/vnd.route66.link66+xml": {
45088 "source": "iana",
45089 "compressible": true,
45090 "extensions": ["link66"]
45091 },
45092 "application/vnd.rs-274x": {
45093 "source": "iana"
45094 },
45095 "application/vnd.ruckus.download": {
45096 "source": "iana"
45097 },
45098 "application/vnd.s3sms": {
45099 "source": "iana"
45100 },
45101 "application/vnd.sailingtracker.track": {
45102 "source": "iana",
45103 "extensions": ["st"]
45104 },
45105 "application/vnd.sbm.cid": {
45106 "source": "iana"
45107 },
45108 "application/vnd.sbm.mid2": {
45109 "source": "iana"
45110 },
45111 "application/vnd.scribus": {
45112 "source": "iana"
45113 },
45114 "application/vnd.sealed.3df": {
45115 "source": "iana"
45116 },
45117 "application/vnd.sealed.csf": {
45118 "source": "iana"
45119 },
45120 "application/vnd.sealed.doc": {
45121 "source": "iana"
45122 },
45123 "application/vnd.sealed.eml": {
45124 "source": "iana"
45125 },
45126 "application/vnd.sealed.mht": {
45127 "source": "iana"
45128 },
45129 "application/vnd.sealed.net": {
45130 "source": "iana"
45131 },
45132 "application/vnd.sealed.ppt": {
45133 "source": "iana"
45134 },
45135 "application/vnd.sealed.tiff": {
45136 "source": "iana"
45137 },
45138 "application/vnd.sealed.xls": {
45139 "source": "iana"
45140 },
45141 "application/vnd.sealedmedia.softseal.html": {
45142 "source": "iana"
45143 },
45144 "application/vnd.sealedmedia.softseal.pdf": {
45145 "source": "iana"
45146 },
45147 "application/vnd.seemail": {
45148 "source": "iana",
45149 "extensions": ["see"]
45150 },
45151 "application/vnd.sema": {
45152 "source": "iana",
45153 "extensions": ["sema"]
45154 },
45155 "application/vnd.semd": {
45156 "source": "iana",
45157 "extensions": ["semd"]
45158 },
45159 "application/vnd.semf": {
45160 "source": "iana",
45161 "extensions": ["semf"]
45162 },
45163 "application/vnd.shana.informed.formdata": {
45164 "source": "iana",
45165 "extensions": ["ifm"]
45166 },
45167 "application/vnd.shana.informed.formtemplate": {
45168 "source": "iana",
45169 "extensions": ["itp"]
45170 },
45171 "application/vnd.shana.informed.interchange": {
45172 "source": "iana",
45173 "extensions": ["iif"]
45174 },
45175 "application/vnd.shana.informed.package": {
45176 "source": "iana",
45177 "extensions": ["ipk"]
45178 },
45179 "application/vnd.shootproof+json": {
45180 "source": "iana",
45181 "compressible": true
45182 },
45183 "application/vnd.sigrok.session": {
45184 "source": "iana"
45185 },
45186 "application/vnd.simtech-mindmapper": {
45187 "source": "iana",
45188 "extensions": ["twd","twds"]
45189 },
45190 "application/vnd.siren+json": {
45191 "source": "iana",
45192 "compressible": true
45193 },
45194 "application/vnd.smaf": {
45195 "source": "iana",
45196 "extensions": ["mmf"]
45197 },
45198 "application/vnd.smart.notebook": {
45199 "source": "iana"
45200 },
45201 "application/vnd.smart.teacher": {
45202 "source": "iana",
45203 "extensions": ["teacher"]
45204 },
45205 "application/vnd.software602.filler.form+xml": {
45206 "source": "iana",
45207 "compressible": true
45208 },
45209 "application/vnd.software602.filler.form-xml-zip": {
45210 "source": "iana"
45211 },
45212 "application/vnd.solent.sdkm+xml": {
45213 "source": "iana",
45214 "compressible": true,
45215 "extensions": ["sdkm","sdkd"]
45216 },
45217 "application/vnd.spotfire.dxp": {
45218 "source": "iana",
45219 "extensions": ["dxp"]
45220 },
45221 "application/vnd.spotfire.sfs": {
45222 "source": "iana",
45223 "extensions": ["sfs"]
45224 },
45225 "application/vnd.sqlite3": {
45226 "source": "iana"
45227 },
45228 "application/vnd.sss-cod": {
45229 "source": "iana"
45230 },
45231 "application/vnd.sss-dtf": {
45232 "source": "iana"
45233 },
45234 "application/vnd.sss-ntf": {
45235 "source": "iana"
45236 },
45237 "application/vnd.stardivision.calc": {
45238 "source": "apache",
45239 "extensions": ["sdc"]
45240 },
45241 "application/vnd.stardivision.draw": {
45242 "source": "apache",
45243 "extensions": ["sda"]
45244 },
45245 "application/vnd.stardivision.impress": {
45246 "source": "apache",
45247 "extensions": ["sdd"]
45248 },
45249 "application/vnd.stardivision.math": {
45250 "source": "apache",
45251 "extensions": ["smf"]
45252 },
45253 "application/vnd.stardivision.writer": {
45254 "source": "apache",
45255 "extensions": ["sdw","vor"]
45256 },
45257 "application/vnd.stardivision.writer-global": {
45258 "source": "apache",
45259 "extensions": ["sgl"]
45260 },
45261 "application/vnd.stepmania.package": {
45262 "source": "iana",
45263 "extensions": ["smzip"]
45264 },
45265 "application/vnd.stepmania.stepchart": {
45266 "source": "iana",
45267 "extensions": ["sm"]
45268 },
45269 "application/vnd.street-stream": {
45270 "source": "iana"
45271 },
45272 "application/vnd.sun.wadl+xml": {
45273 "source": "iana",
45274 "compressible": true,
45275 "extensions": ["wadl"]
45276 },
45277 "application/vnd.sun.xml.calc": {
45278 "source": "apache",
45279 "extensions": ["sxc"]
45280 },
45281 "application/vnd.sun.xml.calc.template": {
45282 "source": "apache",
45283 "extensions": ["stc"]
45284 },
45285 "application/vnd.sun.xml.draw": {
45286 "source": "apache",
45287 "extensions": ["sxd"]
45288 },
45289 "application/vnd.sun.xml.draw.template": {
45290 "source": "apache",
45291 "extensions": ["std"]
45292 },
45293 "application/vnd.sun.xml.impress": {
45294 "source": "apache",
45295 "extensions": ["sxi"]
45296 },
45297 "application/vnd.sun.xml.impress.template": {
45298 "source": "apache",
45299 "extensions": ["sti"]
45300 },
45301 "application/vnd.sun.xml.math": {
45302 "source": "apache",
45303 "extensions": ["sxm"]
45304 },
45305 "application/vnd.sun.xml.writer": {
45306 "source": "apache",
45307 "extensions": ["sxw"]
45308 },
45309 "application/vnd.sun.xml.writer.global": {
45310 "source": "apache",
45311 "extensions": ["sxg"]
45312 },
45313 "application/vnd.sun.xml.writer.template": {
45314 "source": "apache",
45315 "extensions": ["stw"]
45316 },
45317 "application/vnd.sus-calendar": {
45318 "source": "iana",
45319 "extensions": ["sus","susp"]
45320 },
45321 "application/vnd.svd": {
45322 "source": "iana",
45323 "extensions": ["svd"]
45324 },
45325 "application/vnd.swiftview-ics": {
45326 "source": "iana"
45327 },
45328 "application/vnd.symbian.install": {
45329 "source": "apache",
45330 "extensions": ["sis","sisx"]
45331 },
45332 "application/vnd.syncml+xml": {
45333 "source": "iana",
45334 "compressible": true,
45335 "extensions": ["xsm"]
45336 },
45337 "application/vnd.syncml.dm+wbxml": {
45338 "source": "iana",
45339 "extensions": ["bdm"]
45340 },
45341 "application/vnd.syncml.dm+xml": {
45342 "source": "iana",
45343 "compressible": true,
45344 "extensions": ["xdm"]
45345 },
45346 "application/vnd.syncml.dm.notification": {
45347 "source": "iana"
45348 },
45349 "application/vnd.syncml.dmddf+wbxml": {
45350 "source": "iana"
45351 },
45352 "application/vnd.syncml.dmddf+xml": {
45353 "source": "iana",
45354 "compressible": true
45355 },
45356 "application/vnd.syncml.dmtnds+wbxml": {
45357 "source": "iana"
45358 },
45359 "application/vnd.syncml.dmtnds+xml": {
45360 "source": "iana",
45361 "compressible": true
45362 },
45363 "application/vnd.syncml.ds.notification": {
45364 "source": "iana"
45365 },
45366 "application/vnd.tableschema+json": {
45367 "source": "iana",
45368 "compressible": true
45369 },
45370 "application/vnd.tao.intent-module-archive": {
45371 "source": "iana",
45372 "extensions": ["tao"]
45373 },
45374 "application/vnd.tcpdump.pcap": {
45375 "source": "iana",
45376 "extensions": ["pcap","cap","dmp"]
45377 },
45378 "application/vnd.think-cell.ppttc+json": {
45379 "source": "iana",
45380 "compressible": true
45381 },
45382 "application/vnd.tmd.mediaflex.api+xml": {
45383 "source": "iana",
45384 "compressible": true
45385 },
45386 "application/vnd.tml": {
45387 "source": "iana"
45388 },
45389 "application/vnd.tmobile-livetv": {
45390 "source": "iana",
45391 "extensions": ["tmo"]
45392 },
45393 "application/vnd.tri.onesource": {
45394 "source": "iana"
45395 },
45396 "application/vnd.trid.tpt": {
45397 "source": "iana",
45398 "extensions": ["tpt"]
45399 },
45400 "application/vnd.triscape.mxs": {
45401 "source": "iana",
45402 "extensions": ["mxs"]
45403 },
45404 "application/vnd.trueapp": {
45405 "source": "iana",
45406 "extensions": ["tra"]
45407 },
45408 "application/vnd.truedoc": {
45409 "source": "iana"
45410 },
45411 "application/vnd.ubisoft.webplayer": {
45412 "source": "iana"
45413 },
45414 "application/vnd.ufdl": {
45415 "source": "iana",
45416 "extensions": ["ufd","ufdl"]
45417 },
45418 "application/vnd.uiq.theme": {
45419 "source": "iana",
45420 "extensions": ["utz"]
45421 },
45422 "application/vnd.umajin": {
45423 "source": "iana",
45424 "extensions": ["umj"]
45425 },
45426 "application/vnd.unity": {
45427 "source": "iana",
45428 "extensions": ["unityweb"]
45429 },
45430 "application/vnd.uoml+xml": {
45431 "source": "iana",
45432 "compressible": true,
45433 "extensions": ["uoml"]
45434 },
45435 "application/vnd.uplanet.alert": {
45436 "source": "iana"
45437 },
45438 "application/vnd.uplanet.alert-wbxml": {
45439 "source": "iana"
45440 },
45441 "application/vnd.uplanet.bearer-choice": {
45442 "source": "iana"
45443 },
45444 "application/vnd.uplanet.bearer-choice-wbxml": {
45445 "source": "iana"
45446 },
45447 "application/vnd.uplanet.cacheop": {
45448 "source": "iana"
45449 },
45450 "application/vnd.uplanet.cacheop-wbxml": {
45451 "source": "iana"
45452 },
45453 "application/vnd.uplanet.channel": {
45454 "source": "iana"
45455 },
45456 "application/vnd.uplanet.channel-wbxml": {
45457 "source": "iana"
45458 },
45459 "application/vnd.uplanet.list": {
45460 "source": "iana"
45461 },
45462 "application/vnd.uplanet.list-wbxml": {
45463 "source": "iana"
45464 },
45465 "application/vnd.uplanet.listcmd": {
45466 "source": "iana"
45467 },
45468 "application/vnd.uplanet.listcmd-wbxml": {
45469 "source": "iana"
45470 },
45471 "application/vnd.uplanet.signal": {
45472 "source": "iana"
45473 },
45474 "application/vnd.uri-map": {
45475 "source": "iana"
45476 },
45477 "application/vnd.valve.source.material": {
45478 "source": "iana"
45479 },
45480 "application/vnd.vcx": {
45481 "source": "iana",
45482 "extensions": ["vcx"]
45483 },
45484 "application/vnd.vd-study": {
45485 "source": "iana"
45486 },
45487 "application/vnd.vectorworks": {
45488 "source": "iana"
45489 },
45490 "application/vnd.vel+json": {
45491 "source": "iana",
45492 "compressible": true
45493 },
45494 "application/vnd.verimatrix.vcas": {
45495 "source": "iana"
45496 },
45497 "application/vnd.veryant.thin": {
45498 "source": "iana"
45499 },
45500 "application/vnd.vidsoft.vidconference": {
45501 "source": "iana"
45502 },
45503 "application/vnd.visio": {
45504 "source": "iana",
45505 "extensions": ["vsd","vst","vss","vsw"]
45506 },
45507 "application/vnd.visionary": {
45508 "source": "iana",
45509 "extensions": ["vis"]
45510 },
45511 "application/vnd.vividence.scriptfile": {
45512 "source": "iana"
45513 },
45514 "application/vnd.vsf": {
45515 "source": "iana",
45516 "extensions": ["vsf"]
45517 },
45518 "application/vnd.wap.sic": {
45519 "source": "iana"
45520 },
45521 "application/vnd.wap.slc": {
45522 "source": "iana"
45523 },
45524 "application/vnd.wap.wbxml": {
45525 "source": "iana",
45526 "extensions": ["wbxml"]
45527 },
45528 "application/vnd.wap.wmlc": {
45529 "source": "iana",
45530 "extensions": ["wmlc"]
45531 },
45532 "application/vnd.wap.wmlscriptc": {
45533 "source": "iana",
45534 "extensions": ["wmlsc"]
45535 },
45536 "application/vnd.webturbo": {
45537 "source": "iana",
45538 "extensions": ["wtb"]
45539 },
45540 "application/vnd.wfa.p2p": {
45541 "source": "iana"
45542 },
45543 "application/vnd.wfa.wsc": {
45544 "source": "iana"
45545 },
45546 "application/vnd.windows.devicepairing": {
45547 "source": "iana"
45548 },
45549 "application/vnd.wmc": {
45550 "source": "iana"
45551 },
45552 "application/vnd.wmf.bootstrap": {
45553 "source": "iana"
45554 },
45555 "application/vnd.wolfram.mathematica": {
45556 "source": "iana"
45557 },
45558 "application/vnd.wolfram.mathematica.package": {
45559 "source": "iana"
45560 },
45561 "application/vnd.wolfram.player": {
45562 "source": "iana",
45563 "extensions": ["nbp"]
45564 },
45565 "application/vnd.wordperfect": {
45566 "source": "iana",
45567 "extensions": ["wpd"]
45568 },
45569 "application/vnd.wqd": {
45570 "source": "iana",
45571 "extensions": ["wqd"]
45572 },
45573 "application/vnd.wrq-hp3000-labelled": {
45574 "source": "iana"
45575 },
45576 "application/vnd.wt.stf": {
45577 "source": "iana",
45578 "extensions": ["stf"]
45579 },
45580 "application/vnd.wv.csp+wbxml": {
45581 "source": "iana"
45582 },
45583 "application/vnd.wv.csp+xml": {
45584 "source": "iana",
45585 "compressible": true
45586 },
45587 "application/vnd.wv.ssp+xml": {
45588 "source": "iana",
45589 "compressible": true
45590 },
45591 "application/vnd.xacml+json": {
45592 "source": "iana",
45593 "compressible": true
45594 },
45595 "application/vnd.xara": {
45596 "source": "iana",
45597 "extensions": ["xar"]
45598 },
45599 "application/vnd.xfdl": {
45600 "source": "iana",
45601 "extensions": ["xfdl"]
45602 },
45603 "application/vnd.xfdl.webform": {
45604 "source": "iana"
45605 },
45606 "application/vnd.xmi+xml": {
45607 "source": "iana",
45608 "compressible": true
45609 },
45610 "application/vnd.xmpie.cpkg": {
45611 "source": "iana"
45612 },
45613 "application/vnd.xmpie.dpkg": {
45614 "source": "iana"
45615 },
45616 "application/vnd.xmpie.plan": {
45617 "source": "iana"
45618 },
45619 "application/vnd.xmpie.ppkg": {
45620 "source": "iana"
45621 },
45622 "application/vnd.xmpie.xlim": {
45623 "source": "iana"
45624 },
45625 "application/vnd.yamaha.hv-dic": {
45626 "source": "iana",
45627 "extensions": ["hvd"]
45628 },
45629 "application/vnd.yamaha.hv-script": {
45630 "source": "iana",
45631 "extensions": ["hvs"]
45632 },
45633 "application/vnd.yamaha.hv-voice": {
45634 "source": "iana",
45635 "extensions": ["hvp"]
45636 },
45637 "application/vnd.yamaha.openscoreformat": {
45638 "source": "iana",
45639 "extensions": ["osf"]
45640 },
45641 "application/vnd.yamaha.openscoreformat.osfpvg+xml": {
45642 "source": "iana",
45643 "compressible": true,
45644 "extensions": ["osfpvg"]
45645 },
45646 "application/vnd.yamaha.remote-setup": {
45647 "source": "iana"
45648 },
45649 "application/vnd.yamaha.smaf-audio": {
45650 "source": "iana",
45651 "extensions": ["saf"]
45652 },
45653 "application/vnd.yamaha.smaf-phrase": {
45654 "source": "iana",
45655 "extensions": ["spf"]
45656 },
45657 "application/vnd.yamaha.through-ngn": {
45658 "source": "iana"
45659 },
45660 "application/vnd.yamaha.tunnel-udpencap": {
45661 "source": "iana"
45662 },
45663 "application/vnd.yaoweme": {
45664 "source": "iana"
45665 },
45666 "application/vnd.yellowriver-custom-menu": {
45667 "source": "iana",
45668 "extensions": ["cmp"]
45669 },
45670 "application/vnd.youtube.yt": {
45671 "source": "iana"
45672 },
45673 "application/vnd.zul": {
45674 "source": "iana",
45675 "extensions": ["zir","zirz"]
45676 },
45677 "application/vnd.zzazz.deck+xml": {
45678 "source": "iana",
45679 "compressible": true,
45680 "extensions": ["zaz"]
45681 },
45682 "application/voicexml+xml": {
45683 "source": "iana",
45684 "compressible": true,
45685 "extensions": ["vxml"]
45686 },
45687 "application/voucher-cms+json": {
45688 "source": "iana",
45689 "compressible": true
45690 },
45691 "application/vq-rtcpxr": {
45692 "source": "iana"
45693 },
45694 "application/wasm": {
45695 "compressible": true,
45696 "extensions": ["wasm"]
45697 },
45698 "application/watcherinfo+xml": {
45699 "source": "iana",
45700 "compressible": true
45701 },
45702 "application/webpush-options+json": {
45703 "source": "iana",
45704 "compressible": true
45705 },
45706 "application/whoispp-query": {
45707 "source": "iana"
45708 },
45709 "application/whoispp-response": {
45710 "source": "iana"
45711 },
45712 "application/widget": {
45713 "source": "iana",
45714 "extensions": ["wgt"]
45715 },
45716 "application/winhlp": {
45717 "source": "apache",
45718 "extensions": ["hlp"]
45719 },
45720 "application/wita": {
45721 "source": "iana"
45722 },
45723 "application/wordperfect5.1": {
45724 "source": "iana"
45725 },
45726 "application/wsdl+xml": {
45727 "source": "iana",
45728 "compressible": true,
45729 "extensions": ["wsdl"]
45730 },
45731 "application/wspolicy+xml": {
45732 "source": "iana",
45733 "compressible": true,
45734 "extensions": ["wspolicy"]
45735 },
45736 "application/x-7z-compressed": {
45737 "source": "apache",
45738 "compressible": false,
45739 "extensions": ["7z"]
45740 },
45741 "application/x-abiword": {
45742 "source": "apache",
45743 "extensions": ["abw"]
45744 },
45745 "application/x-ace-compressed": {
45746 "source": "apache",
45747 "extensions": ["ace"]
45748 },
45749 "application/x-amf": {
45750 "source": "apache"
45751 },
45752 "application/x-apple-diskimage": {
45753 "source": "apache",
45754 "extensions": ["dmg"]
45755 },
45756 "application/x-arj": {
45757 "compressible": false,
45758 "extensions": ["arj"]
45759 },
45760 "application/x-authorware-bin": {
45761 "source": "apache",
45762 "extensions": ["aab","x32","u32","vox"]
45763 },
45764 "application/x-authorware-map": {
45765 "source": "apache",
45766 "extensions": ["aam"]
45767 },
45768 "application/x-authorware-seg": {
45769 "source": "apache",
45770 "extensions": ["aas"]
45771 },
45772 "application/x-bcpio": {
45773 "source": "apache",
45774 "extensions": ["bcpio"]
45775 },
45776 "application/x-bdoc": {
45777 "compressible": false,
45778 "extensions": ["bdoc"]
45779 },
45780 "application/x-bittorrent": {
45781 "source": "apache",
45782 "extensions": ["torrent"]
45783 },
45784 "application/x-blorb": {
45785 "source": "apache",
45786 "extensions": ["blb","blorb"]
45787 },
45788 "application/x-bzip": {
45789 "source": "apache",
45790 "compressible": false,
45791 "extensions": ["bz"]
45792 },
45793 "application/x-bzip2": {
45794 "source": "apache",
45795 "compressible": false,
45796 "extensions": ["bz2","boz"]
45797 },
45798 "application/x-cbr": {
45799 "source": "apache",
45800 "extensions": ["cbr","cba","cbt","cbz","cb7"]
45801 },
45802 "application/x-cdlink": {
45803 "source": "apache",
45804 "extensions": ["vcd"]
45805 },
45806 "application/x-cfs-compressed": {
45807 "source": "apache",
45808 "extensions": ["cfs"]
45809 },
45810 "application/x-chat": {
45811 "source": "apache",
45812 "extensions": ["chat"]
45813 },
45814 "application/x-chess-pgn": {
45815 "source": "apache",
45816 "extensions": ["pgn"]
45817 },
45818 "application/x-chrome-extension": {
45819 "extensions": ["crx"]
45820 },
45821 "application/x-cocoa": {
45822 "source": "nginx",
45823 "extensions": ["cco"]
45824 },
45825 "application/x-compress": {
45826 "source": "apache"
45827 },
45828 "application/x-conference": {
45829 "source": "apache",
45830 "extensions": ["nsc"]
45831 },
45832 "application/x-cpio": {
45833 "source": "apache",
45834 "extensions": ["cpio"]
45835 },
45836 "application/x-csh": {
45837 "source": "apache",
45838 "extensions": ["csh"]
45839 },
45840 "application/x-deb": {
45841 "compressible": false
45842 },
45843 "application/x-debian-package": {
45844 "source": "apache",
45845 "extensions": ["deb","udeb"]
45846 },
45847 "application/x-dgc-compressed": {
45848 "source": "apache",
45849 "extensions": ["dgc"]
45850 },
45851 "application/x-director": {
45852 "source": "apache",
45853 "extensions": ["dir","dcr","dxr","cst","cct","cxt","w3d","fgd","swa"]
45854 },
45855 "application/x-doom": {
45856 "source": "apache",
45857 "extensions": ["wad"]
45858 },
45859 "application/x-dtbncx+xml": {
45860 "source": "apache",
45861 "compressible": true,
45862 "extensions": ["ncx"]
45863 },
45864 "application/x-dtbook+xml": {
45865 "source": "apache",
45866 "compressible": true,
45867 "extensions": ["dtb"]
45868 },
45869 "application/x-dtbresource+xml": {
45870 "source": "apache",
45871 "compressible": true,
45872 "extensions": ["res"]
45873 },
45874 "application/x-dvi": {
45875 "source": "apache",
45876 "compressible": false,
45877 "extensions": ["dvi"]
45878 },
45879 "application/x-envoy": {
45880 "source": "apache",
45881 "extensions": ["evy"]
45882 },
45883 "application/x-eva": {
45884 "source": "apache",
45885 "extensions": ["eva"]
45886 },
45887 "application/x-font-bdf": {
45888 "source": "apache",
45889 "extensions": ["bdf"]
45890 },
45891 "application/x-font-dos": {
45892 "source": "apache"
45893 },
45894 "application/x-font-framemaker": {
45895 "source": "apache"
45896 },
45897 "application/x-font-ghostscript": {
45898 "source": "apache",
45899 "extensions": ["gsf"]
45900 },
45901 "application/x-font-libgrx": {
45902 "source": "apache"
45903 },
45904 "application/x-font-linux-psf": {
45905 "source": "apache",
45906 "extensions": ["psf"]
45907 },
45908 "application/x-font-pcf": {
45909 "source": "apache",
45910 "extensions": ["pcf"]
45911 },
45912 "application/x-font-snf": {
45913 "source": "apache",
45914 "extensions": ["snf"]
45915 },
45916 "application/x-font-speedo": {
45917 "source": "apache"
45918 },
45919 "application/x-font-sunos-news": {
45920 "source": "apache"
45921 },
45922 "application/x-font-type1": {
45923 "source": "apache",
45924 "extensions": ["pfa","pfb","pfm","afm"]
45925 },
45926 "application/x-font-vfont": {
45927 "source": "apache"
45928 },
45929 "application/x-freearc": {
45930 "source": "apache",
45931 "extensions": ["arc"]
45932 },
45933 "application/x-futuresplash": {
45934 "source": "apache",
45935 "extensions": ["spl"]
45936 },
45937 "application/x-gca-compressed": {
45938 "source": "apache",
45939 "extensions": ["gca"]
45940 },
45941 "application/x-glulx": {
45942 "source": "apache",
45943 "extensions": ["ulx"]
45944 },
45945 "application/x-gnumeric": {
45946 "source": "apache",
45947 "extensions": ["gnumeric"]
45948 },
45949 "application/x-gramps-xml": {
45950 "source": "apache",
45951 "extensions": ["gramps"]
45952 },
45953 "application/x-gtar": {
45954 "source": "apache",
45955 "extensions": ["gtar"]
45956 },
45957 "application/x-gzip": {
45958 "source": "apache"
45959 },
45960 "application/x-hdf": {
45961 "source": "apache",
45962 "extensions": ["hdf"]
45963 },
45964 "application/x-httpd-php": {
45965 "compressible": true,
45966 "extensions": ["php"]
45967 },
45968 "application/x-install-instructions": {
45969 "source": "apache",
45970 "extensions": ["install"]
45971 },
45972 "application/x-iso9660-image": {
45973 "source": "apache",
45974 "extensions": ["iso"]
45975 },
45976 "application/x-java-archive-diff": {
45977 "source": "nginx",
45978 "extensions": ["jardiff"]
45979 },
45980 "application/x-java-jnlp-file": {
45981 "source": "apache",
45982 "compressible": false,
45983 "extensions": ["jnlp"]
45984 },
45985 "application/x-javascript": {
45986 "compressible": true
45987 },
45988 "application/x-latex": {
45989 "source": "apache",
45990 "compressible": false,
45991 "extensions": ["latex"]
45992 },
45993 "application/x-lua-bytecode": {
45994 "extensions": ["luac"]
45995 },
45996 "application/x-lzh-compressed": {
45997 "source": "apache",
45998 "extensions": ["lzh","lha"]
45999 },
46000 "application/x-makeself": {
46001 "source": "nginx",
46002 "extensions": ["run"]
46003 },
46004 "application/x-mie": {
46005 "source": "apache",
46006 "extensions": ["mie"]
46007 },
46008 "application/x-mobipocket-ebook": {
46009 "source": "apache",
46010 "extensions": ["prc","mobi"]
46011 },
46012 "application/x-mpegurl": {
46013 "compressible": false
46014 },
46015 "application/x-ms-application": {
46016 "source": "apache",
46017 "extensions": ["application"]
46018 },
46019 "application/x-ms-shortcut": {
46020 "source": "apache",
46021 "extensions": ["lnk"]
46022 },
46023 "application/x-ms-wmd": {
46024 "source": "apache",
46025 "extensions": ["wmd"]
46026 },
46027 "application/x-ms-wmz": {
46028 "source": "apache",
46029 "extensions": ["wmz"]
46030 },
46031 "application/x-ms-xbap": {
46032 "source": "apache",
46033 "extensions": ["xbap"]
46034 },
46035 "application/x-msaccess": {
46036 "source": "apache",
46037 "extensions": ["mdb"]
46038 },
46039 "application/x-msbinder": {
46040 "source": "apache",
46041 "extensions": ["obd"]
46042 },
46043 "application/x-mscardfile": {
46044 "source": "apache",
46045 "extensions": ["crd"]
46046 },
46047 "application/x-msclip": {
46048 "source": "apache",
46049 "extensions": ["clp"]
46050 },
46051 "application/x-msdos-program": {
46052 "extensions": ["exe"]
46053 },
46054 "application/x-msdownload": {
46055 "source": "apache",
46056 "extensions": ["exe","dll","com","bat","msi"]
46057 },
46058 "application/x-msmediaview": {
46059 "source": "apache",
46060 "extensions": ["mvb","m13","m14"]
46061 },
46062 "application/x-msmetafile": {
46063 "source": "apache",
46064 "extensions": ["wmf","wmz","emf","emz"]
46065 },
46066 "application/x-msmoney": {
46067 "source": "apache",
46068 "extensions": ["mny"]
46069 },
46070 "application/x-mspublisher": {
46071 "source": "apache",
46072 "extensions": ["pub"]
46073 },
46074 "application/x-msschedule": {
46075 "source": "apache",
46076 "extensions": ["scd"]
46077 },
46078 "application/x-msterminal": {
46079 "source": "apache",
46080 "extensions": ["trm"]
46081 },
46082 "application/x-mswrite": {
46083 "source": "apache",
46084 "extensions": ["wri"]
46085 },
46086 "application/x-netcdf": {
46087 "source": "apache",
46088 "extensions": ["nc","cdf"]
46089 },
46090 "application/x-ns-proxy-autoconfig": {
46091 "compressible": true,
46092 "extensions": ["pac"]
46093 },
46094 "application/x-nzb": {
46095 "source": "apache",
46096 "extensions": ["nzb"]
46097 },
46098 "application/x-perl": {
46099 "source": "nginx",
46100 "extensions": ["pl","pm"]
46101 },
46102 "application/x-pilot": {
46103 "source": "nginx",
46104 "extensions": ["prc","pdb"]
46105 },
46106 "application/x-pkcs12": {
46107 "source": "apache",
46108 "compressible": false,
46109 "extensions": ["p12","pfx"]
46110 },
46111 "application/x-pkcs7-certificates": {
46112 "source": "apache",
46113 "extensions": ["p7b","spc"]
46114 },
46115 "application/x-pkcs7-certreqresp": {
46116 "source": "apache",
46117 "extensions": ["p7r"]
46118 },
46119 "application/x-rar-compressed": {
46120 "source": "apache",
46121 "compressible": false,
46122 "extensions": ["rar"]
46123 },
46124 "application/x-redhat-package-manager": {
46125 "source": "nginx",
46126 "extensions": ["rpm"]
46127 },
46128 "application/x-research-info-systems": {
46129 "source": "apache",
46130 "extensions": ["ris"]
46131 },
46132 "application/x-sea": {
46133 "source": "nginx",
46134 "extensions": ["sea"]
46135 },
46136 "application/x-sh": {
46137 "source": "apache",
46138 "compressible": true,
46139 "extensions": ["sh"]
46140 },
46141 "application/x-shar": {
46142 "source": "apache",
46143 "extensions": ["shar"]
46144 },
46145 "application/x-shockwave-flash": {
46146 "source": "apache",
46147 "compressible": false,
46148 "extensions": ["swf"]
46149 },
46150 "application/x-silverlight-app": {
46151 "source": "apache",
46152 "extensions": ["xap"]
46153 },
46154 "application/x-sql": {
46155 "source": "apache",
46156 "extensions": ["sql"]
46157 },
46158 "application/x-stuffit": {
46159 "source": "apache",
46160 "compressible": false,
46161 "extensions": ["sit"]
46162 },
46163 "application/x-stuffitx": {
46164 "source": "apache",
46165 "extensions": ["sitx"]
46166 },
46167 "application/x-subrip": {
46168 "source": "apache",
46169 "extensions": ["srt"]
46170 },
46171 "application/x-sv4cpio": {
46172 "source": "apache",
46173 "extensions": ["sv4cpio"]
46174 },
46175 "application/x-sv4crc": {
46176 "source": "apache",
46177 "extensions": ["sv4crc"]
46178 },
46179 "application/x-t3vm-image": {
46180 "source": "apache",
46181 "extensions": ["t3"]
46182 },
46183 "application/x-tads": {
46184 "source": "apache",
46185 "extensions": ["gam"]
46186 },
46187 "application/x-tar": {
46188 "source": "apache",
46189 "compressible": true,
46190 "extensions": ["tar"]
46191 },
46192 "application/x-tcl": {
46193 "source": "apache",
46194 "extensions": ["tcl","tk"]
46195 },
46196 "application/x-tex": {
46197 "source": "apache",
46198 "extensions": ["tex"]
46199 },
46200 "application/x-tex-tfm": {
46201 "source": "apache",
46202 "extensions": ["tfm"]
46203 },
46204 "application/x-texinfo": {
46205 "source": "apache",
46206 "extensions": ["texinfo","texi"]
46207 },
46208 "application/x-tgif": {
46209 "source": "apache",
46210 "extensions": ["obj"]
46211 },
46212 "application/x-ustar": {
46213 "source": "apache",
46214 "extensions": ["ustar"]
46215 },
46216 "application/x-virtualbox-hdd": {
46217 "compressible": true,
46218 "extensions": ["hdd"]
46219 },
46220 "application/x-virtualbox-ova": {
46221 "compressible": true,
46222 "extensions": ["ova"]
46223 },
46224 "application/x-virtualbox-ovf": {
46225 "compressible": true,
46226 "extensions": ["ovf"]
46227 },
46228 "application/x-virtualbox-vbox": {
46229 "compressible": true,
46230 "extensions": ["vbox"]
46231 },
46232 "application/x-virtualbox-vbox-extpack": {
46233 "compressible": false,
46234 "extensions": ["vbox-extpack"]
46235 },
46236 "application/x-virtualbox-vdi": {
46237 "compressible": true,
46238 "extensions": ["vdi"]
46239 },
46240 "application/x-virtualbox-vhd": {
46241 "compressible": true,
46242 "extensions": ["vhd"]
46243 },
46244 "application/x-virtualbox-vmdk": {
46245 "compressible": true,
46246 "extensions": ["vmdk"]
46247 },
46248 "application/x-wais-source": {
46249 "source": "apache",
46250 "extensions": ["src"]
46251 },
46252 "application/x-web-app-manifest+json": {
46253 "compressible": true,
46254 "extensions": ["webapp"]
46255 },
46256 "application/x-www-form-urlencoded": {
46257 "source": "iana",
46258 "compressible": true
46259 },
46260 "application/x-x509-ca-cert": {
46261 "source": "apache",
46262 "extensions": ["der","crt","pem"]
46263 },
46264 "application/x-xfig": {
46265 "source": "apache",
46266 "extensions": ["fig"]
46267 },
46268 "application/x-xliff+xml": {
46269 "source": "apache",
46270 "compressible": true,
46271 "extensions": ["xlf"]
46272 },
46273 "application/x-xpinstall": {
46274 "source": "apache",
46275 "compressible": false,
46276 "extensions": ["xpi"]
46277 },
46278 "application/x-xz": {
46279 "source": "apache",
46280 "extensions": ["xz"]
46281 },
46282 "application/x-zmachine": {
46283 "source": "apache",
46284 "extensions": ["z1","z2","z3","z4","z5","z6","z7","z8"]
46285 },
46286 "application/x400-bp": {
46287 "source": "iana"
46288 },
46289 "application/xacml+xml": {
46290 "source": "iana",
46291 "compressible": true
46292 },
46293 "application/xaml+xml": {
46294 "source": "apache",
46295 "compressible": true,
46296 "extensions": ["xaml"]
46297 },
46298 "application/xcap-att+xml": {
46299 "source": "iana",
46300 "compressible": true
46301 },
46302 "application/xcap-caps+xml": {
46303 "source": "iana",
46304 "compressible": true
46305 },
46306 "application/xcap-diff+xml": {
46307 "source": "iana",
46308 "compressible": true,
46309 "extensions": ["xdf"]
46310 },
46311 "application/xcap-el+xml": {
46312 "source": "iana",
46313 "compressible": true
46314 },
46315 "application/xcap-error+xml": {
46316 "source": "iana",
46317 "compressible": true
46318 },
46319 "application/xcap-ns+xml": {
46320 "source": "iana",
46321 "compressible": true
46322 },
46323 "application/xcon-conference-info+xml": {
46324 "source": "iana",
46325 "compressible": true
46326 },
46327 "application/xcon-conference-info-diff+xml": {
46328 "source": "iana",
46329 "compressible": true
46330 },
46331 "application/xenc+xml": {
46332 "source": "iana",
46333 "compressible": true,
46334 "extensions": ["xenc"]
46335 },
46336 "application/xhtml+xml": {
46337 "source": "iana",
46338 "compressible": true,
46339 "extensions": ["xhtml","xht"]
46340 },
46341 "application/xhtml-voice+xml": {
46342 "source": "apache",
46343 "compressible": true
46344 },
46345 "application/xliff+xml": {
46346 "source": "iana",
46347 "compressible": true
46348 },
46349 "application/xml": {
46350 "source": "iana",
46351 "compressible": true,
46352 "extensions": ["xml","xsl","xsd","rng"]
46353 },
46354 "application/xml-dtd": {
46355 "source": "iana",
46356 "compressible": true,
46357 "extensions": ["dtd"]
46358 },
46359 "application/xml-external-parsed-entity": {
46360 "source": "iana"
46361 },
46362 "application/xml-patch+xml": {
46363 "source": "iana",
46364 "compressible": true
46365 },
46366 "application/xmpp+xml": {
46367 "source": "iana",
46368 "compressible": true
46369 },
46370 "application/xop+xml": {
46371 "source": "iana",
46372 "compressible": true,
46373 "extensions": ["xop"]
46374 },
46375 "application/xproc+xml": {
46376 "source": "apache",
46377 "compressible": true,
46378 "extensions": ["xpl"]
46379 },
46380 "application/xslt+xml": {
46381 "source": "iana",
46382 "compressible": true,
46383 "extensions": ["xslt"]
46384 },
46385 "application/xspf+xml": {
46386 "source": "apache",
46387 "compressible": true,
46388 "extensions": ["xspf"]
46389 },
46390 "application/xv+xml": {
46391 "source": "iana",
46392 "compressible": true,
46393 "extensions": ["mxml","xhvml","xvml","xvm"]
46394 },
46395 "application/yang": {
46396 "source": "iana",
46397 "extensions": ["yang"]
46398 },
46399 "application/yang-data+json": {
46400 "source": "iana",
46401 "compressible": true
46402 },
46403 "application/yang-data+xml": {
46404 "source": "iana",
46405 "compressible": true
46406 },
46407 "application/yang-patch+json": {
46408 "source": "iana",
46409 "compressible": true
46410 },
46411 "application/yang-patch+xml": {
46412 "source": "iana",
46413 "compressible": true
46414 },
46415 "application/yin+xml": {
46416 "source": "iana",
46417 "compressible": true,
46418 "extensions": ["yin"]
46419 },
46420 "application/zip": {
46421 "source": "iana",
46422 "compressible": false,
46423 "extensions": ["zip"]
46424 },
46425 "application/zlib": {
46426 "source": "iana"
46427 },
46428 "application/zstd": {
46429 "source": "iana"
46430 },
46431 "audio/1d-interleaved-parityfec": {
46432 "source": "iana"
46433 },
46434 "audio/32kadpcm": {
46435 "source": "iana"
46436 },
46437 "audio/3gpp": {
46438 "source": "iana",
46439 "compressible": false,
46440 "extensions": ["3gpp"]
46441 },
46442 "audio/3gpp2": {
46443 "source": "iana"
46444 },
46445 "audio/aac": {
46446 "source": "iana"
46447 },
46448 "audio/ac3": {
46449 "source": "iana"
46450 },
46451 "audio/adpcm": {
46452 "source": "apache",
46453 "extensions": ["adp"]
46454 },
46455 "audio/amr": {
46456 "source": "iana"
46457 },
46458 "audio/amr-wb": {
46459 "source": "iana"
46460 },
46461 "audio/amr-wb+": {
46462 "source": "iana"
46463 },
46464 "audio/aptx": {
46465 "source": "iana"
46466 },
46467 "audio/asc": {
46468 "source": "iana"
46469 },
46470 "audio/atrac-advanced-lossless": {
46471 "source": "iana"
46472 },
46473 "audio/atrac-x": {
46474 "source": "iana"
46475 },
46476 "audio/atrac3": {
46477 "source": "iana"
46478 },
46479 "audio/basic": {
46480 "source": "iana",
46481 "compressible": false,
46482 "extensions": ["au","snd"]
46483 },
46484 "audio/bv16": {
46485 "source": "iana"
46486 },
46487 "audio/bv32": {
46488 "source": "iana"
46489 },
46490 "audio/clearmode": {
46491 "source": "iana"
46492 },
46493 "audio/cn": {
46494 "source": "iana"
46495 },
46496 "audio/dat12": {
46497 "source": "iana"
46498 },
46499 "audio/dls": {
46500 "source": "iana"
46501 },
46502 "audio/dsr-es201108": {
46503 "source": "iana"
46504 },
46505 "audio/dsr-es202050": {
46506 "source": "iana"
46507 },
46508 "audio/dsr-es202211": {
46509 "source": "iana"
46510 },
46511 "audio/dsr-es202212": {
46512 "source": "iana"
46513 },
46514 "audio/dv": {
46515 "source": "iana"
46516 },
46517 "audio/dvi4": {
46518 "source": "iana"
46519 },
46520 "audio/eac3": {
46521 "source": "iana"
46522 },
46523 "audio/encaprtp": {
46524 "source": "iana"
46525 },
46526 "audio/evrc": {
46527 "source": "iana"
46528 },
46529 "audio/evrc-qcp": {
46530 "source": "iana"
46531 },
46532 "audio/evrc0": {
46533 "source": "iana"
46534 },
46535 "audio/evrc1": {
46536 "source": "iana"
46537 },
46538 "audio/evrcb": {
46539 "source": "iana"
46540 },
46541 "audio/evrcb0": {
46542 "source": "iana"
46543 },
46544 "audio/evrcb1": {
46545 "source": "iana"
46546 },
46547 "audio/evrcnw": {
46548 "source": "iana"
46549 },
46550 "audio/evrcnw0": {
46551 "source": "iana"
46552 },
46553 "audio/evrcnw1": {
46554 "source": "iana"
46555 },
46556 "audio/evrcwb": {
46557 "source": "iana"
46558 },
46559 "audio/evrcwb0": {
46560 "source": "iana"
46561 },
46562 "audio/evrcwb1": {
46563 "source": "iana"
46564 },
46565 "audio/evs": {
46566 "source": "iana"
46567 },
46568 "audio/fwdred": {
46569 "source": "iana"
46570 },
46571 "audio/g711-0": {
46572 "source": "iana"
46573 },
46574 "audio/g719": {
46575 "source": "iana"
46576 },
46577 "audio/g722": {
46578 "source": "iana"
46579 },
46580 "audio/g7221": {
46581 "source": "iana"
46582 },
46583 "audio/g723": {
46584 "source": "iana"
46585 },
46586 "audio/g726-16": {
46587 "source": "iana"
46588 },
46589 "audio/g726-24": {
46590 "source": "iana"
46591 },
46592 "audio/g726-32": {
46593 "source": "iana"
46594 },
46595 "audio/g726-40": {
46596 "source": "iana"
46597 },
46598 "audio/g728": {
46599 "source": "iana"
46600 },
46601 "audio/g729": {
46602 "source": "iana"
46603 },
46604 "audio/g7291": {
46605 "source": "iana"
46606 },
46607 "audio/g729d": {
46608 "source": "iana"
46609 },
46610 "audio/g729e": {
46611 "source": "iana"
46612 },
46613 "audio/gsm": {
46614 "source": "iana"
46615 },
46616 "audio/gsm-efr": {
46617 "source": "iana"
46618 },
46619 "audio/gsm-hr-08": {
46620 "source": "iana"
46621 },
46622 "audio/ilbc": {
46623 "source": "iana"
46624 },
46625 "audio/ip-mr_v2.5": {
46626 "source": "iana"
46627 },
46628 "audio/isac": {
46629 "source": "apache"
46630 },
46631 "audio/l16": {
46632 "source": "iana"
46633 },
46634 "audio/l20": {
46635 "source": "iana"
46636 },
46637 "audio/l24": {
46638 "source": "iana",
46639 "compressible": false
46640 },
46641 "audio/l8": {
46642 "source": "iana"
46643 },
46644 "audio/lpc": {
46645 "source": "iana"
46646 },
46647 "audio/melp": {
46648 "source": "iana"
46649 },
46650 "audio/melp1200": {
46651 "source": "iana"
46652 },
46653 "audio/melp2400": {
46654 "source": "iana"
46655 },
46656 "audio/melp600": {
46657 "source": "iana"
46658 },
46659 "audio/midi": {
46660 "source": "apache",
46661 "extensions": ["mid","midi","kar","rmi"]
46662 },
46663 "audio/mobile-xmf": {
46664 "source": "iana"
46665 },
46666 "audio/mp3": {
46667 "compressible": false,
46668 "extensions": ["mp3"]
46669 },
46670 "audio/mp4": {
46671 "source": "iana",
46672 "compressible": false,
46673 "extensions": ["m4a","mp4a"]
46674 },
46675 "audio/mp4a-latm": {
46676 "source": "iana"
46677 },
46678 "audio/mpa": {
46679 "source": "iana"
46680 },
46681 "audio/mpa-robust": {
46682 "source": "iana"
46683 },
46684 "audio/mpeg": {
46685 "source": "iana",
46686 "compressible": false,
46687 "extensions": ["mpga","mp2","mp2a","mp3","m2a","m3a"]
46688 },
46689 "audio/mpeg4-generic": {
46690 "source": "iana"
46691 },
46692 "audio/musepack": {
46693 "source": "apache"
46694 },
46695 "audio/ogg": {
46696 "source": "iana",
46697 "compressible": false,
46698 "extensions": ["oga","ogg","spx"]
46699 },
46700 "audio/opus": {
46701 "source": "iana"
46702 },
46703 "audio/parityfec": {
46704 "source": "iana"
46705 },
46706 "audio/pcma": {
46707 "source": "iana"
46708 },
46709 "audio/pcma-wb": {
46710 "source": "iana"
46711 },
46712 "audio/pcmu": {
46713 "source": "iana"
46714 },
46715 "audio/pcmu-wb": {
46716 "source": "iana"
46717 },
46718 "audio/prs.sid": {
46719 "source": "iana"
46720 },
46721 "audio/qcelp": {
46722 "source": "iana"
46723 },
46724 "audio/raptorfec": {
46725 "source": "iana"
46726 },
46727 "audio/red": {
46728 "source": "iana"
46729 },
46730 "audio/rtp-enc-aescm128": {
46731 "source": "iana"
46732 },
46733 "audio/rtp-midi": {
46734 "source": "iana"
46735 },
46736 "audio/rtploopback": {
46737 "source": "iana"
46738 },
46739 "audio/rtx": {
46740 "source": "iana"
46741 },
46742 "audio/s3m": {
46743 "source": "apache",
46744 "extensions": ["s3m"]
46745 },
46746 "audio/silk": {
46747 "source": "apache",
46748 "extensions": ["sil"]
46749 },
46750 "audio/smv": {
46751 "source": "iana"
46752 },
46753 "audio/smv-qcp": {
46754 "source": "iana"
46755 },
46756 "audio/smv0": {
46757 "source": "iana"
46758 },
46759 "audio/sp-midi": {
46760 "source": "iana"
46761 },
46762 "audio/speex": {
46763 "source": "iana"
46764 },
46765 "audio/t140c": {
46766 "source": "iana"
46767 },
46768 "audio/t38": {
46769 "source": "iana"
46770 },
46771 "audio/telephone-event": {
46772 "source": "iana"
46773 },
46774 "audio/tetra_acelp": {
46775 "source": "iana"
46776 },
46777 "audio/tone": {
46778 "source": "iana"
46779 },
46780 "audio/uemclip": {
46781 "source": "iana"
46782 },
46783 "audio/ulpfec": {
46784 "source": "iana"
46785 },
46786 "audio/usac": {
46787 "source": "iana"
46788 },
46789 "audio/vdvi": {
46790 "source": "iana"
46791 },
46792 "audio/vmr-wb": {
46793 "source": "iana"
46794 },
46795 "audio/vnd.3gpp.iufp": {
46796 "source": "iana"
46797 },
46798 "audio/vnd.4sb": {
46799 "source": "iana"
46800 },
46801 "audio/vnd.audiokoz": {
46802 "source": "iana"
46803 },
46804 "audio/vnd.celp": {
46805 "source": "iana"
46806 },
46807 "audio/vnd.cisco.nse": {
46808 "source": "iana"
46809 },
46810 "audio/vnd.cmles.radio-events": {
46811 "source": "iana"
46812 },
46813 "audio/vnd.cns.anp1": {
46814 "source": "iana"
46815 },
46816 "audio/vnd.cns.inf1": {
46817 "source": "iana"
46818 },
46819 "audio/vnd.dece.audio": {
46820 "source": "iana",
46821 "extensions": ["uva","uvva"]
46822 },
46823 "audio/vnd.digital-winds": {
46824 "source": "iana",
46825 "extensions": ["eol"]
46826 },
46827 "audio/vnd.dlna.adts": {
46828 "source": "iana"
46829 },
46830 "audio/vnd.dolby.heaac.1": {
46831 "source": "iana"
46832 },
46833 "audio/vnd.dolby.heaac.2": {
46834 "source": "iana"
46835 },
46836 "audio/vnd.dolby.mlp": {
46837 "source": "iana"
46838 },
46839 "audio/vnd.dolby.mps": {
46840 "source": "iana"
46841 },
46842 "audio/vnd.dolby.pl2": {
46843 "source": "iana"
46844 },
46845 "audio/vnd.dolby.pl2x": {
46846 "source": "iana"
46847 },
46848 "audio/vnd.dolby.pl2z": {
46849 "source": "iana"
46850 },
46851 "audio/vnd.dolby.pulse.1": {
46852 "source": "iana"
46853 },
46854 "audio/vnd.dra": {
46855 "source": "iana",
46856 "extensions": ["dra"]
46857 },
46858 "audio/vnd.dts": {
46859 "source": "iana",
46860 "extensions": ["dts"]
46861 },
46862 "audio/vnd.dts.hd": {
46863 "source": "iana",
46864 "extensions": ["dtshd"]
46865 },
46866 "audio/vnd.dts.uhd": {
46867 "source": "iana"
46868 },
46869 "audio/vnd.dvb.file": {
46870 "source": "iana"
46871 },
46872 "audio/vnd.everad.plj": {
46873 "source": "iana"
46874 },
46875 "audio/vnd.hns.audio": {
46876 "source": "iana"
46877 },
46878 "audio/vnd.lucent.voice": {
46879 "source": "iana",
46880 "extensions": ["lvp"]
46881 },
46882 "audio/vnd.ms-playready.media.pya": {
46883 "source": "iana",
46884 "extensions": ["pya"]
46885 },
46886 "audio/vnd.nokia.mobile-xmf": {
46887 "source": "iana"
46888 },
46889 "audio/vnd.nortel.vbk": {
46890 "source": "iana"
46891 },
46892 "audio/vnd.nuera.ecelp4800": {
46893 "source": "iana",
46894 "extensions": ["ecelp4800"]
46895 },
46896 "audio/vnd.nuera.ecelp7470": {
46897 "source": "iana",
46898 "extensions": ["ecelp7470"]
46899 },
46900 "audio/vnd.nuera.ecelp9600": {
46901 "source": "iana",
46902 "extensions": ["ecelp9600"]
46903 },
46904 "audio/vnd.octel.sbc": {
46905 "source": "iana"
46906 },
46907 "audio/vnd.presonus.multitrack": {
46908 "source": "iana"
46909 },
46910 "audio/vnd.qcelp": {
46911 "source": "iana"
46912 },
46913 "audio/vnd.rhetorex.32kadpcm": {
46914 "source": "iana"
46915 },
46916 "audio/vnd.rip": {
46917 "source": "iana",
46918 "extensions": ["rip"]
46919 },
46920 "audio/vnd.rn-realaudio": {
46921 "compressible": false
46922 },
46923 "audio/vnd.sealedmedia.softseal.mpeg": {
46924 "source": "iana"
46925 },
46926 "audio/vnd.vmx.cvsd": {
46927 "source": "iana"
46928 },
46929 "audio/vnd.wave": {
46930 "compressible": false
46931 },
46932 "audio/vorbis": {
46933 "source": "iana",
46934 "compressible": false
46935 },
46936 "audio/vorbis-config": {
46937 "source": "iana"
46938 },
46939 "audio/wav": {
46940 "compressible": false,
46941 "extensions": ["wav"]
46942 },
46943 "audio/wave": {
46944 "compressible": false,
46945 "extensions": ["wav"]
46946 },
46947 "audio/webm": {
46948 "source": "apache",
46949 "compressible": false,
46950 "extensions": ["weba"]
46951 },
46952 "audio/x-aac": {
46953 "source": "apache",
46954 "compressible": false,
46955 "extensions": ["aac"]
46956 },
46957 "audio/x-aiff": {
46958 "source": "apache",
46959 "extensions": ["aif","aiff","aifc"]
46960 },
46961 "audio/x-caf": {
46962 "source": "apache",
46963 "compressible": false,
46964 "extensions": ["caf"]
46965 },
46966 "audio/x-flac": {
46967 "source": "apache",
46968 "extensions": ["flac"]
46969 },
46970 "audio/x-m4a": {
46971 "source": "nginx",
46972 "extensions": ["m4a"]
46973 },
46974 "audio/x-matroska": {
46975 "source": "apache",
46976 "extensions": ["mka"]
46977 },
46978 "audio/x-mpegurl": {
46979 "source": "apache",
46980 "extensions": ["m3u"]
46981 },
46982 "audio/x-ms-wax": {
46983 "source": "apache",
46984 "extensions": ["wax"]
46985 },
46986 "audio/x-ms-wma": {
46987 "source": "apache",
46988 "extensions": ["wma"]
46989 },
46990 "audio/x-pn-realaudio": {
46991 "source": "apache",
46992 "extensions": ["ram","ra"]
46993 },
46994 "audio/x-pn-realaudio-plugin": {
46995 "source": "apache",
46996 "extensions": ["rmp"]
46997 },
46998 "audio/x-realaudio": {
46999 "source": "nginx",
47000 "extensions": ["ra"]
47001 },
47002 "audio/x-tta": {
47003 "source": "apache"
47004 },
47005 "audio/x-wav": {
47006 "source": "apache",
47007 "extensions": ["wav"]
47008 },
47009 "audio/xm": {
47010 "source": "apache",
47011 "extensions": ["xm"]
47012 },
47013 "chemical/x-cdx": {
47014 "source": "apache",
47015 "extensions": ["cdx"]
47016 },
47017 "chemical/x-cif": {
47018 "source": "apache",
47019 "extensions": ["cif"]
47020 },
47021 "chemical/x-cmdf": {
47022 "source": "apache",
47023 "extensions": ["cmdf"]
47024 },
47025 "chemical/x-cml": {
47026 "source": "apache",
47027 "extensions": ["cml"]
47028 },
47029 "chemical/x-csml": {
47030 "source": "apache",
47031 "extensions": ["csml"]
47032 },
47033 "chemical/x-pdb": {
47034 "source": "apache"
47035 },
47036 "chemical/x-xyz": {
47037 "source": "apache",
47038 "extensions": ["xyz"]
47039 },
47040 "font/collection": {
47041 "source": "iana",
47042 "extensions": ["ttc"]
47043 },
47044 "font/otf": {
47045 "source": "iana",
47046 "compressible": true,
47047 "extensions": ["otf"]
47048 },
47049 "font/sfnt": {
47050 "source": "iana"
47051 },
47052 "font/ttf": {
47053 "source": "iana",
47054 "extensions": ["ttf"]
47055 },
47056 "font/woff": {
47057 "source": "iana",
47058 "extensions": ["woff"]
47059 },
47060 "font/woff2": {
47061 "source": "iana",
47062 "extensions": ["woff2"]
47063 },
47064 "image/aces": {
47065 "source": "iana",
47066 "extensions": ["exr"]
47067 },
47068 "image/apng": {
47069 "compressible": false,
47070 "extensions": ["apng"]
47071 },
47072 "image/avci": {
47073 "source": "iana"
47074 },
47075 "image/avcs": {
47076 "source": "iana"
47077 },
47078 "image/bmp": {
47079 "source": "iana",
47080 "compressible": true,
47081 "extensions": ["bmp"]
47082 },
47083 "image/cgm": {
47084 "source": "iana",
47085 "extensions": ["cgm"]
47086 },
47087 "image/dicom-rle": {
47088 "source": "iana",
47089 "extensions": ["drle"]
47090 },
47091 "image/emf": {
47092 "source": "iana",
47093 "extensions": ["emf"]
47094 },
47095 "image/fits": {
47096 "source": "iana",
47097 "extensions": ["fits"]
47098 },
47099 "image/g3fax": {
47100 "source": "iana",
47101 "extensions": ["g3"]
47102 },
47103 "image/gif": {
47104 "source": "iana",
47105 "compressible": false,
47106 "extensions": ["gif"]
47107 },
47108 "image/heic": {
47109 "source": "iana",
47110 "extensions": ["heic"]
47111 },
47112 "image/heic-sequence": {
47113 "source": "iana",
47114 "extensions": ["heics"]
47115 },
47116 "image/heif": {
47117 "source": "iana",
47118 "extensions": ["heif"]
47119 },
47120 "image/heif-sequence": {
47121 "source": "iana",
47122 "extensions": ["heifs"]
47123 },
47124 "image/ief": {
47125 "source": "iana",
47126 "extensions": ["ief"]
47127 },
47128 "image/jls": {
47129 "source": "iana",
47130 "extensions": ["jls"]
47131 },
47132 "image/jp2": {
47133 "source": "iana",
47134 "compressible": false,
47135 "extensions": ["jp2","jpg2"]
47136 },
47137 "image/jpeg": {
47138 "source": "iana",
47139 "compressible": false,
47140 "extensions": ["jpeg","jpg","jpe"]
47141 },
47142 "image/jpm": {
47143 "source": "iana",
47144 "compressible": false,
47145 "extensions": ["jpm"]
47146 },
47147 "image/jpx": {
47148 "source": "iana",
47149 "compressible": false,
47150 "extensions": ["jpx","jpf"]
47151 },
47152 "image/jxr": {
47153 "source": "iana",
47154 "extensions": ["jxr"]
47155 },
47156 "image/ktx": {
47157 "source": "iana",
47158 "extensions": ["ktx"]
47159 },
47160 "image/naplps": {
47161 "source": "iana"
47162 },
47163 "image/pjpeg": {
47164 "compressible": false
47165 },
47166 "image/png": {
47167 "source": "iana",
47168 "compressible": false,
47169 "extensions": ["png"]
47170 },
47171 "image/prs.btif": {
47172 "source": "iana",
47173 "extensions": ["btif"]
47174 },
47175 "image/prs.pti": {
47176 "source": "iana",
47177 "extensions": ["pti"]
47178 },
47179 "image/pwg-raster": {
47180 "source": "iana"
47181 },
47182 "image/sgi": {
47183 "source": "apache",
47184 "extensions": ["sgi"]
47185 },
47186 "image/svg+xml": {
47187 "source": "iana",
47188 "compressible": true,
47189 "extensions": ["svg","svgz"]
47190 },
47191 "image/t38": {
47192 "source": "iana",
47193 "extensions": ["t38"]
47194 },
47195 "image/tiff": {
47196 "source": "iana",
47197 "compressible": false,
47198 "extensions": ["tif","tiff"]
47199 },
47200 "image/tiff-fx": {
47201 "source": "iana",
47202 "extensions": ["tfx"]
47203 },
47204 "image/vnd.adobe.photoshop": {
47205 "source": "iana",
47206 "compressible": true,
47207 "extensions": ["psd"]
47208 },
47209 "image/vnd.airzip.accelerator.azv": {
47210 "source": "iana",
47211 "extensions": ["azv"]
47212 },
47213 "image/vnd.cns.inf2": {
47214 "source": "iana"
47215 },
47216 "image/vnd.dece.graphic": {
47217 "source": "iana",
47218 "extensions": ["uvi","uvvi","uvg","uvvg"]
47219 },
47220 "image/vnd.djvu": {
47221 "source": "iana",
47222 "extensions": ["djvu","djv"]
47223 },
47224 "image/vnd.dvb.subtitle": {
47225 "source": "iana",
47226 "extensions": ["sub"]
47227 },
47228 "image/vnd.dwg": {
47229 "source": "iana",
47230 "extensions": ["dwg"]
47231 },
47232 "image/vnd.dxf": {
47233 "source": "iana",
47234 "extensions": ["dxf"]
47235 },
47236 "image/vnd.fastbidsheet": {
47237 "source": "iana",
47238 "extensions": ["fbs"]
47239 },
47240 "image/vnd.fpx": {
47241 "source": "iana",
47242 "extensions": ["fpx"]
47243 },
47244 "image/vnd.fst": {
47245 "source": "iana",
47246 "extensions": ["fst"]
47247 },
47248 "image/vnd.fujixerox.edmics-mmr": {
47249 "source": "iana",
47250 "extensions": ["mmr"]
47251 },
47252 "image/vnd.fujixerox.edmics-rlc": {
47253 "source": "iana",
47254 "extensions": ["rlc"]
47255 },
47256 "image/vnd.globalgraphics.pgb": {
47257 "source": "iana"
47258 },
47259 "image/vnd.microsoft.icon": {
47260 "source": "iana",
47261 "extensions": ["ico"]
47262 },
47263 "image/vnd.mix": {
47264 "source": "iana"
47265 },
47266 "image/vnd.mozilla.apng": {
47267 "source": "iana"
47268 },
47269 "image/vnd.ms-modi": {
47270 "source": "iana",
47271 "extensions": ["mdi"]
47272 },
47273 "image/vnd.ms-photo": {
47274 "source": "apache",
47275 "extensions": ["wdp"]
47276 },
47277 "image/vnd.net-fpx": {
47278 "source": "iana",
47279 "extensions": ["npx"]
47280 },
47281 "image/vnd.radiance": {
47282 "source": "iana"
47283 },
47284 "image/vnd.sealed.png": {
47285 "source": "iana"
47286 },
47287 "image/vnd.sealedmedia.softseal.gif": {
47288 "source": "iana"
47289 },
47290 "image/vnd.sealedmedia.softseal.jpg": {
47291 "source": "iana"
47292 },
47293 "image/vnd.svf": {
47294 "source": "iana"
47295 },
47296 "image/vnd.tencent.tap": {
47297 "source": "iana",
47298 "extensions": ["tap"]
47299 },
47300 "image/vnd.valve.source.texture": {
47301 "source": "iana",
47302 "extensions": ["vtf"]
47303 },
47304 "image/vnd.wap.wbmp": {
47305 "source": "iana",
47306 "extensions": ["wbmp"]
47307 },
47308 "image/vnd.xiff": {
47309 "source": "iana",
47310 "extensions": ["xif"]
47311 },
47312 "image/vnd.zbrush.pcx": {
47313 "source": "iana",
47314 "extensions": ["pcx"]
47315 },
47316 "image/webp": {
47317 "source": "apache",
47318 "extensions": ["webp"]
47319 },
47320 "image/wmf": {
47321 "source": "iana",
47322 "extensions": ["wmf"]
47323 },
47324 "image/x-3ds": {
47325 "source": "apache",
47326 "extensions": ["3ds"]
47327 },
47328 "image/x-cmu-raster": {
47329 "source": "apache",
47330 "extensions": ["ras"]
47331 },
47332 "image/x-cmx": {
47333 "source": "apache",
47334 "extensions": ["cmx"]
47335 },
47336 "image/x-freehand": {
47337 "source": "apache",
47338 "extensions": ["fh","fhc","fh4","fh5","fh7"]
47339 },
47340 "image/x-icon": {
47341 "source": "apache",
47342 "compressible": true,
47343 "extensions": ["ico"]
47344 },
47345 "image/x-jng": {
47346 "source": "nginx",
47347 "extensions": ["jng"]
47348 },
47349 "image/x-mrsid-image": {
47350 "source": "apache",
47351 "extensions": ["sid"]
47352 },
47353 "image/x-ms-bmp": {
47354 "source": "nginx",
47355 "compressible": true,
47356 "extensions": ["bmp"]
47357 },
47358 "image/x-pcx": {
47359 "source": "apache",
47360 "extensions": ["pcx"]
47361 },
47362 "image/x-pict": {
47363 "source": "apache",
47364 "extensions": ["pic","pct"]
47365 },
47366 "image/x-portable-anymap": {
47367 "source": "apache",
47368 "extensions": ["pnm"]
47369 },
47370 "image/x-portable-bitmap": {
47371 "source": "apache",
47372 "extensions": ["pbm"]
47373 },
47374 "image/x-portable-graymap": {
47375 "source": "apache",
47376 "extensions": ["pgm"]
47377 },
47378 "image/x-portable-pixmap": {
47379 "source": "apache",
47380 "extensions": ["ppm"]
47381 },
47382 "image/x-rgb": {
47383 "source": "apache",
47384 "extensions": ["rgb"]
47385 },
47386 "image/x-tga": {
47387 "source": "apache",
47388 "extensions": ["tga"]
47389 },
47390 "image/x-xbitmap": {
47391 "source": "apache",
47392 "extensions": ["xbm"]
47393 },
47394 "image/x-xcf": {
47395 "compressible": false
47396 },
47397 "image/x-xpixmap": {
47398 "source": "apache",
47399 "extensions": ["xpm"]
47400 },
47401 "image/x-xwindowdump": {
47402 "source": "apache",
47403 "extensions": ["xwd"]
47404 },
47405 "message/cpim": {
47406 "source": "iana"
47407 },
47408 "message/delivery-status": {
47409 "source": "iana"
47410 },
47411 "message/disposition-notification": {
47412 "source": "iana",
47413 "extensions": [
47414 "disposition-notification"
47415 ]
47416 },
47417 "message/external-body": {
47418 "source": "iana"
47419 },
47420 "message/feedback-report": {
47421 "source": "iana"
47422 },
47423 "message/global": {
47424 "source": "iana",
47425 "extensions": ["u8msg"]
47426 },
47427 "message/global-delivery-status": {
47428 "source": "iana",
47429 "extensions": ["u8dsn"]
47430 },
47431 "message/global-disposition-notification": {
47432 "source": "iana",
47433 "extensions": ["u8mdn"]
47434 },
47435 "message/global-headers": {
47436 "source": "iana",
47437 "extensions": ["u8hdr"]
47438 },
47439 "message/http": {
47440 "source": "iana",
47441 "compressible": false
47442 },
47443 "message/imdn+xml": {
47444 "source": "iana",
47445 "compressible": true
47446 },
47447 "message/news": {
47448 "source": "iana"
47449 },
47450 "message/partial": {
47451 "source": "iana",
47452 "compressible": false
47453 },
47454 "message/rfc822": {
47455 "source": "iana",
47456 "compressible": true,
47457 "extensions": ["eml","mime"]
47458 },
47459 "message/s-http": {
47460 "source": "iana"
47461 },
47462 "message/sip": {
47463 "source": "iana"
47464 },
47465 "message/sipfrag": {
47466 "source": "iana"
47467 },
47468 "message/tracking-status": {
47469 "source": "iana"
47470 },
47471 "message/vnd.si.simp": {
47472 "source": "iana"
47473 },
47474 "message/vnd.wfa.wsc": {
47475 "source": "iana",
47476 "extensions": ["wsc"]
47477 },
47478 "model/3mf": {
47479 "source": "iana",
47480 "extensions": ["3mf"]
47481 },
47482 "model/gltf+json": {
47483 "source": "iana",
47484 "compressible": true,
47485 "extensions": ["gltf"]
47486 },
47487 "model/gltf-binary": {
47488 "source": "iana",
47489 "compressible": true,
47490 "extensions": ["glb"]
47491 },
47492 "model/iges": {
47493 "source": "iana",
47494 "compressible": false,
47495 "extensions": ["igs","iges"]
47496 },
47497 "model/mesh": {
47498 "source": "iana",
47499 "compressible": false,
47500 "extensions": ["msh","mesh","silo"]
47501 },
47502 "model/stl": {
47503 "source": "iana",
47504 "extensions": ["stl"]
47505 },
47506 "model/vnd.collada+xml": {
47507 "source": "iana",
47508 "compressible": true,
47509 "extensions": ["dae"]
47510 },
47511 "model/vnd.dwf": {
47512 "source": "iana",
47513 "extensions": ["dwf"]
47514 },
47515 "model/vnd.flatland.3dml": {
47516 "source": "iana"
47517 },
47518 "model/vnd.gdl": {
47519 "source": "iana",
47520 "extensions": ["gdl"]
47521 },
47522 "model/vnd.gs-gdl": {
47523 "source": "apache"
47524 },
47525 "model/vnd.gs.gdl": {
47526 "source": "iana"
47527 },
47528 "model/vnd.gtw": {
47529 "source": "iana",
47530 "extensions": ["gtw"]
47531 },
47532 "model/vnd.moml+xml": {
47533 "source": "iana",
47534 "compressible": true
47535 },
47536 "model/vnd.mts": {
47537 "source": "iana",
47538 "extensions": ["mts"]
47539 },
47540 "model/vnd.opengex": {
47541 "source": "iana",
47542 "extensions": ["ogex"]
47543 },
47544 "model/vnd.parasolid.transmit.binary": {
47545 "source": "iana",
47546 "extensions": ["x_b"]
47547 },
47548 "model/vnd.parasolid.transmit.text": {
47549 "source": "iana",
47550 "extensions": ["x_t"]
47551 },
47552 "model/vnd.rosette.annotated-data-model": {
47553 "source": "iana"
47554 },
47555 "model/vnd.usdz+zip": {
47556 "source": "iana",
47557 "compressible": false,
47558 "extensions": ["usdz"]
47559 },
47560 "model/vnd.valve.source.compiled-map": {
47561 "source": "iana",
47562 "extensions": ["bsp"]
47563 },
47564 "model/vnd.vtu": {
47565 "source": "iana",
47566 "extensions": ["vtu"]
47567 },
47568 "model/vrml": {
47569 "source": "iana",
47570 "compressible": false,
47571 "extensions": ["wrl","vrml"]
47572 },
47573 "model/x3d+binary": {
47574 "source": "apache",
47575 "compressible": false,
47576 "extensions": ["x3db","x3dbz"]
47577 },
47578 "model/x3d+fastinfoset": {
47579 "source": "iana",
47580 "extensions": ["x3db"]
47581 },
47582 "model/x3d+vrml": {
47583 "source": "apache",
47584 "compressible": false,
47585 "extensions": ["x3dv","x3dvz"]
47586 },
47587 "model/x3d+xml": {
47588 "source": "iana",
47589 "compressible": true,
47590 "extensions": ["x3d","x3dz"]
47591 },
47592 "model/x3d-vrml": {
47593 "source": "iana",
47594 "extensions": ["x3dv"]
47595 },
47596 "multipart/alternative": {
47597 "source": "iana",
47598 "compressible": false
47599 },
47600 "multipart/appledouble": {
47601 "source": "iana"
47602 },
47603 "multipart/byteranges": {
47604 "source": "iana"
47605 },
47606 "multipart/digest": {
47607 "source": "iana"
47608 },
47609 "multipart/encrypted": {
47610 "source": "iana",
47611 "compressible": false
47612 },
47613 "multipart/form-data": {
47614 "source": "iana",
47615 "compressible": false
47616 },
47617 "multipart/header-set": {
47618 "source": "iana"
47619 },
47620 "multipart/mixed": {
47621 "source": "iana",
47622 "compressible": false
47623 },
47624 "multipart/multilingual": {
47625 "source": "iana"
47626 },
47627 "multipart/parallel": {
47628 "source": "iana"
47629 },
47630 "multipart/related": {
47631 "source": "iana",
47632 "compressible": false
47633 },
47634 "multipart/report": {
47635 "source": "iana"
47636 },
47637 "multipart/signed": {
47638 "source": "iana",
47639 "compressible": false
47640 },
47641 "multipart/vnd.bint.med-plus": {
47642 "source": "iana"
47643 },
47644 "multipart/voice-message": {
47645 "source": "iana"
47646 },
47647 "multipart/x-mixed-replace": {
47648 "source": "iana"
47649 },
47650 "text/1d-interleaved-parityfec": {
47651 "source": "iana"
47652 },
47653 "text/cache-manifest": {
47654 "source": "iana",
47655 "compressible": true,
47656 "extensions": ["appcache","manifest"]
47657 },
47658 "text/calendar": {
47659 "source": "iana",
47660 "extensions": ["ics","ifb"]
47661 },
47662 "text/calender": {
47663 "compressible": true
47664 },
47665 "text/cmd": {
47666 "compressible": true
47667 },
47668 "text/coffeescript": {
47669 "extensions": ["coffee","litcoffee"]
47670 },
47671 "text/css": {
47672 "source": "iana",
47673 "charset": "UTF-8",
47674 "compressible": true,
47675 "extensions": ["css"]
47676 },
47677 "text/csv": {
47678 "source": "iana",
47679 "compressible": true,
47680 "extensions": ["csv"]
47681 },
47682 "text/csv-schema": {
47683 "source": "iana"
47684 },
47685 "text/directory": {
47686 "source": "iana"
47687 },
47688 "text/dns": {
47689 "source": "iana"
47690 },
47691 "text/ecmascript": {
47692 "source": "iana"
47693 },
47694 "text/encaprtp": {
47695 "source": "iana"
47696 },
47697 "text/enriched": {
47698 "source": "iana"
47699 },
47700 "text/fwdred": {
47701 "source": "iana"
47702 },
47703 "text/grammar-ref-list": {
47704 "source": "iana"
47705 },
47706 "text/html": {
47707 "source": "iana",
47708 "compressible": true,
47709 "extensions": ["html","htm","shtml"]
47710 },
47711 "text/jade": {
47712 "extensions": ["jade"]
47713 },
47714 "text/javascript": {
47715 "source": "iana",
47716 "compressible": true
47717 },
47718 "text/jcr-cnd": {
47719 "source": "iana"
47720 },
47721 "text/jsx": {
47722 "compressible": true,
47723 "extensions": ["jsx"]
47724 },
47725 "text/less": {
47726 "compressible": true,
47727 "extensions": ["less"]
47728 },
47729 "text/markdown": {
47730 "source": "iana",
47731 "compressible": true,
47732 "extensions": ["markdown","md"]
47733 },
47734 "text/mathml": {
47735 "source": "nginx",
47736 "extensions": ["mml"]
47737 },
47738 "text/mdx": {
47739 "compressible": true,
47740 "extensions": ["mdx"]
47741 },
47742 "text/mizar": {
47743 "source": "iana"
47744 },
47745 "text/n3": {
47746 "source": "iana",
47747 "compressible": true,
47748 "extensions": ["n3"]
47749 },
47750 "text/parameters": {
47751 "source": "iana"
47752 },
47753 "text/parityfec": {
47754 "source": "iana"
47755 },
47756 "text/plain": {
47757 "source": "iana",
47758 "compressible": true,
47759 "extensions": ["txt","text","conf","def","list","log","in","ini"]
47760 },
47761 "text/provenance-notation": {
47762 "source": "iana"
47763 },
47764 "text/prs.fallenstein.rst": {
47765 "source": "iana"
47766 },
47767 "text/prs.lines.tag": {
47768 "source": "iana",
47769 "extensions": ["dsc"]
47770 },
47771 "text/prs.prop.logic": {
47772 "source": "iana"
47773 },
47774 "text/raptorfec": {
47775 "source": "iana"
47776 },
47777 "text/red": {
47778 "source": "iana"
47779 },
47780 "text/rfc822-headers": {
47781 "source": "iana"
47782 },
47783 "text/richtext": {
47784 "source": "iana",
47785 "compressible": true,
47786 "extensions": ["rtx"]
47787 },
47788 "text/rtf": {
47789 "source": "iana",
47790 "compressible": true,
47791 "extensions": ["rtf"]
47792 },
47793 "text/rtp-enc-aescm128": {
47794 "source": "iana"
47795 },
47796 "text/rtploopback": {
47797 "source": "iana"
47798 },
47799 "text/rtx": {
47800 "source": "iana"
47801 },
47802 "text/sgml": {
47803 "source": "iana",
47804 "extensions": ["sgml","sgm"]
47805 },
47806 "text/shex": {
47807 "extensions": ["shex"]
47808 },
47809 "text/slim": {
47810 "extensions": ["slim","slm"]
47811 },
47812 "text/strings": {
47813 "source": "iana"
47814 },
47815 "text/stylus": {
47816 "extensions": ["stylus","styl"]
47817 },
47818 "text/t140": {
47819 "source": "iana"
47820 },
47821 "text/tab-separated-values": {
47822 "source": "iana",
47823 "compressible": true,
47824 "extensions": ["tsv"]
47825 },
47826 "text/troff": {
47827 "source": "iana",
47828 "extensions": ["t","tr","roff","man","me","ms"]
47829 },
47830 "text/turtle": {
47831 "source": "iana",
47832 "charset": "UTF-8",
47833 "extensions": ["ttl"]
47834 },
47835 "text/ulpfec": {
47836 "source": "iana"
47837 },
47838 "text/uri-list": {
47839 "source": "iana",
47840 "compressible": true,
47841 "extensions": ["uri","uris","urls"]
47842 },
47843 "text/vcard": {
47844 "source": "iana",
47845 "compressible": true,
47846 "extensions": ["vcard"]
47847 },
47848 "text/vnd.a": {
47849 "source": "iana"
47850 },
47851 "text/vnd.abc": {
47852 "source": "iana"
47853 },
47854 "text/vnd.ascii-art": {
47855 "source": "iana"
47856 },
47857 "text/vnd.curl": {
47858 "source": "iana",
47859 "extensions": ["curl"]
47860 },
47861 "text/vnd.curl.dcurl": {
47862 "source": "apache",
47863 "extensions": ["dcurl"]
47864 },
47865 "text/vnd.curl.mcurl": {
47866 "source": "apache",
47867 "extensions": ["mcurl"]
47868 },
47869 "text/vnd.curl.scurl": {
47870 "source": "apache",
47871 "extensions": ["scurl"]
47872 },
47873 "text/vnd.debian.copyright": {
47874 "source": "iana"
47875 },
47876 "text/vnd.dmclientscript": {
47877 "source": "iana"
47878 },
47879 "text/vnd.dvb.subtitle": {
47880 "source": "iana",
47881 "extensions": ["sub"]
47882 },
47883 "text/vnd.esmertec.theme-descriptor": {
47884 "source": "iana"
47885 },
47886 "text/vnd.fly": {
47887 "source": "iana",
47888 "extensions": ["fly"]
47889 },
47890 "text/vnd.fmi.flexstor": {
47891 "source": "iana",
47892 "extensions": ["flx"]
47893 },
47894 "text/vnd.gml": {
47895 "source": "iana"
47896 },
47897 "text/vnd.graphviz": {
47898 "source": "iana",
47899 "extensions": ["gv"]
47900 },
47901 "text/vnd.hgl": {
47902 "source": "iana"
47903 },
47904 "text/vnd.in3d.3dml": {
47905 "source": "iana",
47906 "extensions": ["3dml"]
47907 },
47908 "text/vnd.in3d.spot": {
47909 "source": "iana",
47910 "extensions": ["spot"]
47911 },
47912 "text/vnd.iptc.newsml": {
47913 "source": "iana"
47914 },
47915 "text/vnd.iptc.nitf": {
47916 "source": "iana"
47917 },
47918 "text/vnd.latex-z": {
47919 "source": "iana"
47920 },
47921 "text/vnd.motorola.reflex": {
47922 "source": "iana"
47923 },
47924 "text/vnd.ms-mediapackage": {
47925 "source": "iana"
47926 },
47927 "text/vnd.net2phone.commcenter.command": {
47928 "source": "iana"
47929 },
47930 "text/vnd.radisys.msml-basic-layout": {
47931 "source": "iana"
47932 },
47933 "text/vnd.senx.warpscript": {
47934 "source": "iana"
47935 },
47936 "text/vnd.si.uricatalogue": {
47937 "source": "iana"
47938 },
47939 "text/vnd.sun.j2me.app-descriptor": {
47940 "source": "iana",
47941 "extensions": ["jad"]
47942 },
47943 "text/vnd.trolltech.linguist": {
47944 "source": "iana"
47945 },
47946 "text/vnd.wap.si": {
47947 "source": "iana"
47948 },
47949 "text/vnd.wap.sl": {
47950 "source": "iana"
47951 },
47952 "text/vnd.wap.wml": {
47953 "source": "iana",
47954 "extensions": ["wml"]
47955 },
47956 "text/vnd.wap.wmlscript": {
47957 "source": "iana",
47958 "extensions": ["wmls"]
47959 },
47960 "text/vtt": {
47961 "charset": "UTF-8",
47962 "compressible": true,
47963 "extensions": ["vtt"]
47964 },
47965 "text/x-asm": {
47966 "source": "apache",
47967 "extensions": ["s","asm"]
47968 },
47969 "text/x-c": {
47970 "source": "apache",
47971 "extensions": ["c","cc","cxx","cpp","h","hh","dic"]
47972 },
47973 "text/x-component": {
47974 "source": "nginx",
47975 "extensions": ["htc"]
47976 },
47977 "text/x-fortran": {
47978 "source": "apache",
47979 "extensions": ["f","for","f77","f90"]
47980 },
47981 "text/x-gwt-rpc": {
47982 "compressible": true
47983 },
47984 "text/x-handlebars-template": {
47985 "extensions": ["hbs"]
47986 },
47987 "text/x-java-source": {
47988 "source": "apache",
47989 "extensions": ["java"]
47990 },
47991 "text/x-jquery-tmpl": {
47992 "compressible": true
47993 },
47994 "text/x-lua": {
47995 "extensions": ["lua"]
47996 },
47997 "text/x-markdown": {
47998 "compressible": true,
47999 "extensions": ["mkd"]
48000 },
48001 "text/x-nfo": {
48002 "source": "apache",
48003 "extensions": ["nfo"]
48004 },
48005 "text/x-opml": {
48006 "source": "apache",
48007 "extensions": ["opml"]
48008 },
48009 "text/x-org": {
48010 "compressible": true,
48011 "extensions": ["org"]
48012 },
48013 "text/x-pascal": {
48014 "source": "apache",
48015 "extensions": ["p","pas"]
48016 },
48017 "text/x-processing": {
48018 "compressible": true,
48019 "extensions": ["pde"]
48020 },
48021 "text/x-sass": {
48022 "extensions": ["sass"]
48023 },
48024 "text/x-scss": {
48025 "extensions": ["scss"]
48026 },
48027 "text/x-setext": {
48028 "source": "apache",
48029 "extensions": ["etx"]
48030 },
48031 "text/x-sfv": {
48032 "source": "apache",
48033 "extensions": ["sfv"]
48034 },
48035 "text/x-suse-ymp": {
48036 "compressible": true,
48037 "extensions": ["ymp"]
48038 },
48039 "text/x-uuencode": {
48040 "source": "apache",
48041 "extensions": ["uu"]
48042 },
48043 "text/x-vcalendar": {
48044 "source": "apache",
48045 "extensions": ["vcs"]
48046 },
48047 "text/x-vcard": {
48048 "source": "apache",
48049 "extensions": ["vcf"]
48050 },
48051 "text/xml": {
48052 "source": "iana",
48053 "compressible": true,
48054 "extensions": ["xml"]
48055 },
48056 "text/xml-external-parsed-entity": {
48057 "source": "iana"
48058 },
48059 "text/yaml": {
48060 "extensions": ["yaml","yml"]
48061 },
48062 "video/1d-interleaved-parityfec": {
48063 "source": "iana"
48064 },
48065 "video/3gpp": {
48066 "source": "iana",
48067 "extensions": ["3gp","3gpp"]
48068 },
48069 "video/3gpp-tt": {
48070 "source": "iana"
48071 },
48072 "video/3gpp2": {
48073 "source": "iana",
48074 "extensions": ["3g2"]
48075 },
48076 "video/bmpeg": {
48077 "source": "iana"
48078 },
48079 "video/bt656": {
48080 "source": "iana"
48081 },
48082 "video/celb": {
48083 "source": "iana"
48084 },
48085 "video/dv": {
48086 "source": "iana"
48087 },
48088 "video/encaprtp": {
48089 "source": "iana"
48090 },
48091 "video/h261": {
48092 "source": "iana",
48093 "extensions": ["h261"]
48094 },
48095 "video/h263": {
48096 "source": "iana",
48097 "extensions": ["h263"]
48098 },
48099 "video/h263-1998": {
48100 "source": "iana"
48101 },
48102 "video/h263-2000": {
48103 "source": "iana"
48104 },
48105 "video/h264": {
48106 "source": "iana",
48107 "extensions": ["h264"]
48108 },
48109 "video/h264-rcdo": {
48110 "source": "iana"
48111 },
48112 "video/h264-svc": {
48113 "source": "iana"
48114 },
48115 "video/h265": {
48116 "source": "iana"
48117 },
48118 "video/iso.segment": {
48119 "source": "iana"
48120 },
48121 "video/jpeg": {
48122 "source": "iana",
48123 "extensions": ["jpgv"]
48124 },
48125 "video/jpeg2000": {
48126 "source": "iana"
48127 },
48128 "video/jpm": {
48129 "source": "apache",
48130 "extensions": ["jpm","jpgm"]
48131 },
48132 "video/mj2": {
48133 "source": "iana",
48134 "extensions": ["mj2","mjp2"]
48135 },
48136 "video/mp1s": {
48137 "source": "iana"
48138 },
48139 "video/mp2p": {
48140 "source": "iana"
48141 },
48142 "video/mp2t": {
48143 "source": "iana",
48144 "extensions": ["ts"]
48145 },
48146 "video/mp4": {
48147 "source": "iana",
48148 "compressible": false,
48149 "extensions": ["mp4","mp4v","mpg4"]
48150 },
48151 "video/mp4v-es": {
48152 "source": "iana"
48153 },
48154 "video/mpeg": {
48155 "source": "iana",
48156 "compressible": false,
48157 "extensions": ["mpeg","mpg","mpe","m1v","m2v"]
48158 },
48159 "video/mpeg4-generic": {
48160 "source": "iana"
48161 },
48162 "video/mpv": {
48163 "source": "iana"
48164 },
48165 "video/nv": {
48166 "source": "iana"
48167 },
48168 "video/ogg": {
48169 "source": "iana",
48170 "compressible": false,
48171 "extensions": ["ogv"]
48172 },
48173 "video/parityfec": {
48174 "source": "iana"
48175 },
48176 "video/pointer": {
48177 "source": "iana"
48178 },
48179 "video/quicktime": {
48180 "source": "iana",
48181 "compressible": false,
48182 "extensions": ["qt","mov"]
48183 },
48184 "video/raptorfec": {
48185 "source": "iana"
48186 },
48187 "video/raw": {
48188 "source": "iana"
48189 },
48190 "video/rtp-enc-aescm128": {
48191 "source": "iana"
48192 },
48193 "video/rtploopback": {
48194 "source": "iana"
48195 },
48196 "video/rtx": {
48197 "source": "iana"
48198 },
48199 "video/smpte291": {
48200 "source": "iana"
48201 },
48202 "video/smpte292m": {
48203 "source": "iana"
48204 },
48205 "video/ulpfec": {
48206 "source": "iana"
48207 },
48208 "video/vc1": {
48209 "source": "iana"
48210 },
48211 "video/vc2": {
48212 "source": "iana"
48213 },
48214 "video/vnd.cctv": {
48215 "source": "iana"
48216 },
48217 "video/vnd.dece.hd": {
48218 "source": "iana",
48219 "extensions": ["uvh","uvvh"]
48220 },
48221 "video/vnd.dece.mobile": {
48222 "source": "iana",
48223 "extensions": ["uvm","uvvm"]
48224 },
48225 "video/vnd.dece.mp4": {
48226 "source": "iana"
48227 },
48228 "video/vnd.dece.pd": {
48229 "source": "iana",
48230 "extensions": ["uvp","uvvp"]
48231 },
48232 "video/vnd.dece.sd": {
48233 "source": "iana",
48234 "extensions": ["uvs","uvvs"]
48235 },
48236 "video/vnd.dece.video": {
48237 "source": "iana",
48238 "extensions": ["uvv","uvvv"]
48239 },
48240 "video/vnd.directv.mpeg": {
48241 "source": "iana"
48242 },
48243 "video/vnd.directv.mpeg-tts": {
48244 "source": "iana"
48245 },
48246 "video/vnd.dlna.mpeg-tts": {
48247 "source": "iana"
48248 },
48249 "video/vnd.dvb.file": {
48250 "source": "iana",
48251 "extensions": ["dvb"]
48252 },
48253 "video/vnd.fvt": {
48254 "source": "iana",
48255 "extensions": ["fvt"]
48256 },
48257 "video/vnd.hns.video": {
48258 "source": "iana"
48259 },
48260 "video/vnd.iptvforum.1dparityfec-1010": {
48261 "source": "iana"
48262 },
48263 "video/vnd.iptvforum.1dparityfec-2005": {
48264 "source": "iana"
48265 },
48266 "video/vnd.iptvforum.2dparityfec-1010": {
48267 "source": "iana"
48268 },
48269 "video/vnd.iptvforum.2dparityfec-2005": {
48270 "source": "iana"
48271 },
48272 "video/vnd.iptvforum.ttsavc": {
48273 "source": "iana"
48274 },
48275 "video/vnd.iptvforum.ttsmpeg2": {
48276 "source": "iana"
48277 },
48278 "video/vnd.motorola.video": {
48279 "source": "iana"
48280 },
48281 "video/vnd.motorola.videop": {
48282 "source": "iana"
48283 },
48284 "video/vnd.mpegurl": {
48285 "source": "iana",
48286 "extensions": ["mxu","m4u"]
48287 },
48288 "video/vnd.ms-playready.media.pyv": {
48289 "source": "iana",
48290 "extensions": ["pyv"]
48291 },
48292 "video/vnd.nokia.interleaved-multimedia": {
48293 "source": "iana"
48294 },
48295 "video/vnd.nokia.mp4vr": {
48296 "source": "iana"
48297 },
48298 "video/vnd.nokia.videovoip": {
48299 "source": "iana"
48300 },
48301 "video/vnd.objectvideo": {
48302 "source": "iana"
48303 },
48304 "video/vnd.radgamettools.bink": {
48305 "source": "iana"
48306 },
48307 "video/vnd.radgamettools.smacker": {
48308 "source": "iana"
48309 },
48310 "video/vnd.sealed.mpeg1": {
48311 "source": "iana"
48312 },
48313 "video/vnd.sealed.mpeg4": {
48314 "source": "iana"
48315 },
48316 "video/vnd.sealed.swf": {
48317 "source": "iana"
48318 },
48319 "video/vnd.sealedmedia.softseal.mov": {
48320 "source": "iana"
48321 },
48322 "video/vnd.uvvu.mp4": {
48323 "source": "iana",
48324 "extensions": ["uvu","uvvu"]
48325 },
48326 "video/vnd.vivo": {
48327 "source": "iana",
48328 "extensions": ["viv"]
48329 },
48330 "video/vp8": {
48331 "source": "iana"
48332 },
48333 "video/webm": {
48334 "source": "apache",
48335 "compressible": false,
48336 "extensions": ["webm"]
48337 },
48338 "video/x-f4v": {
48339 "source": "apache",
48340 "extensions": ["f4v"]
48341 },
48342 "video/x-fli": {
48343 "source": "apache",
48344 "extensions": ["fli"]
48345 },
48346 "video/x-flv": {
48347 "source": "apache",
48348 "compressible": false,
48349 "extensions": ["flv"]
48350 },
48351 "video/x-m4v": {
48352 "source": "apache",
48353 "extensions": ["m4v"]
48354 },
48355 "video/x-matroska": {
48356 "source": "apache",
48357 "compressible": false,
48358 "extensions": ["mkv","mk3d","mks"]
48359 },
48360 "video/x-mng": {
48361 "source": "apache",
48362 "extensions": ["mng"]
48363 },
48364 "video/x-ms-asf": {
48365 "source": "apache",
48366 "extensions": ["asf","asx"]
48367 },
48368 "video/x-ms-vob": {
48369 "source": "apache",
48370 "extensions": ["vob"]
48371 },
48372 "video/x-ms-wm": {
48373 "source": "apache",
48374 "extensions": ["wm"]
48375 },
48376 "video/x-ms-wmv": {
48377 "source": "apache",
48378 "compressible": false,
48379 "extensions": ["wmv"]
48380 },
48381 "video/x-ms-wmx": {
48382 "source": "apache",
48383 "extensions": ["wmx"]
48384 },
48385 "video/x-ms-wvx": {
48386 "source": "apache",
48387 "extensions": ["wvx"]
48388 },
48389 "video/x-msvideo": {
48390 "source": "apache",
48391 "extensions": ["avi"]
48392 },
48393 "video/x-sgi-movie": {
48394 "source": "apache",
48395 "extensions": ["movie"]
48396 },
48397 "video/x-smv": {
48398 "source": "apache",
48399 "extensions": ["smv"]
48400 },
48401 "x-conference/x-cooltalk": {
48402 "source": "apache",
48403 "extensions": ["ice"]
48404 },
48405 "x-shader/x-fragment": {
48406 "compressible": true
48407 },
48408 "x-shader/x-vertex": {
48409 "compressible": true
48410 }
48411}
48412
48413},{}],235:[function(require,module,exports){
48414/*!
48415 * mime-db
48416 * Copyright(c) 2014 Jonathan Ong
48417 * MIT Licensed
48418 */
48419
48420/**
48421 * Module exports.
48422 */
48423
48424module.exports = require('./db.json')
48425
48426},{"./db.json":234}],236:[function(require,module,exports){
48427/*!
48428 * mime-types
48429 * Copyright(c) 2014 Jonathan Ong
48430 * Copyright(c) 2015 Douglas Christopher Wilson
48431 * MIT Licensed
48432 */
48433
48434'use strict'
48435
48436/**
48437 * Module dependencies.
48438 * @private
48439 */
48440
48441var db = require('mime-db')
48442var extname = require('path').extname
48443
48444/**
48445 * Module variables.
48446 * @private
48447 */
48448
48449var EXTRACT_TYPE_REGEXP = /^\s*([^;\s]*)(?:;|\s|$)/
48450var TEXT_TYPE_REGEXP = /^text\//i
48451
48452/**
48453 * Module exports.
48454 * @public
48455 */
48456
48457exports.charset = charset
48458exports.charsets = { lookup: charset }
48459exports.contentType = contentType
48460exports.extension = extension
48461exports.extensions = Object.create(null)
48462exports.lookup = lookup
48463exports.types = Object.create(null)
48464
48465// Populate the extensions/types maps
48466populateMaps(exports.extensions, exports.types)
48467
48468/**
48469 * Get the default charset for a MIME type.
48470 *
48471 * @param {string} type
48472 * @return {boolean|string}
48473 */
48474
48475function charset (type) {
48476 if (!type || typeof type !== 'string') {
48477 return false
48478 }
48479
48480 // TODO: use media-typer
48481 var match = EXTRACT_TYPE_REGEXP.exec(type)
48482 var mime = match && db[match[1].toLowerCase()]
48483
48484 if (mime && mime.charset) {
48485 return mime.charset
48486 }
48487
48488 // default text/* to utf-8
48489 if (match && TEXT_TYPE_REGEXP.test(match[1])) {
48490 return 'UTF-8'
48491 }
48492
48493 return false
48494}
48495
48496/**
48497 * Create a full Content-Type header given a MIME type or extension.
48498 *
48499 * @param {string} str
48500 * @return {boolean|string}
48501 */
48502
48503function contentType (str) {
48504 // TODO: should this even be in this module?
48505 if (!str || typeof str !== 'string') {
48506 return false
48507 }
48508
48509 var mime = str.indexOf('/') === -1
48510 ? exports.lookup(str)
48511 : str
48512
48513 if (!mime) {
48514 return false
48515 }
48516
48517 // TODO: use content-type or other module
48518 if (mime.indexOf('charset') === -1) {
48519 var charset = exports.charset(mime)
48520 if (charset) mime += '; charset=' + charset.toLowerCase()
48521 }
48522
48523 return mime
48524}
48525
48526/**
48527 * Get the default extension for a MIME type.
48528 *
48529 * @param {string} type
48530 * @return {boolean|string}
48531 */
48532
48533function extension (type) {
48534 if (!type || typeof type !== 'string') {
48535 return false
48536 }
48537
48538 // TODO: use media-typer
48539 var match = EXTRACT_TYPE_REGEXP.exec(type)
48540
48541 // get extensions
48542 var exts = match && exports.extensions[match[1].toLowerCase()]
48543
48544 if (!exts || !exts.length) {
48545 return false
48546 }
48547
48548 return exts[0]
48549}
48550
48551/**
48552 * Lookup the MIME type for a file path/extension.
48553 *
48554 * @param {string} path
48555 * @return {boolean|string}
48556 */
48557
48558function lookup (path) {
48559 if (!path || typeof path !== 'string') {
48560 return false
48561 }
48562
48563 // get the extension ("ext" or ".ext" or full path)
48564 var extension = extname('x.' + path)
48565 .toLowerCase()
48566 .substr(1)
48567
48568 if (!extension) {
48569 return false
48570 }
48571
48572 return exports.types[extension] || false
48573}
48574
48575/**
48576 * Populate the extensions and types maps.
48577 * @private
48578 */
48579
48580function populateMaps (extensions, types) {
48581 // source preference (least -> most)
48582 var preference = ['nginx', 'apache', undefined, 'iana']
48583
48584 Object.keys(db).forEach(function forEachMimeType (type) {
48585 var mime = db[type]
48586 var exts = mime.extensions
48587
48588 if (!exts || !exts.length) {
48589 return
48590 }
48591
48592 // mime -> extensions
48593 extensions[type] = exts
48594
48595 // extension -> mime
48596 for (var i = 0; i < exts.length; i++) {
48597 var extension = exts[i]
48598
48599 if (types[extension]) {
48600 var from = preference.indexOf(db[types[extension]].source)
48601 var to = preference.indexOf(mime.source)
48602
48603 if (types[extension] !== 'application/octet-stream' &&
48604 (from > to || (from === to && types[extension].substr(0, 12) === 'application/'))) {
48605 // skip the remapping
48606 continue
48607 }
48608 }
48609
48610 // set the extension -> mime
48611 types[extension] = type
48612 }
48613 })
48614}
48615
48616},{"mime-db":235,"path":257}],237:[function(require,module,exports){
48617module.exports = assert;
48618
48619function assert(val, msg) {
48620 if (!val)
48621 throw new Error(msg || 'Assertion failed');
48622}
48623
48624assert.equal = function assertEqual(l, r, msg) {
48625 if (l != r)
48626 throw new Error(msg || ('Assertion failed: ' + l + ' != ' + r));
48627};
48628
48629},{}],238:[function(require,module,exports){
48630'use strict';
48631
48632var utils = exports;
48633
48634function toArray(msg, enc) {
48635 if (Array.isArray(msg))
48636 return msg.slice();
48637 if (!msg)
48638 return [];
48639 var res = [];
48640 if (typeof msg !== 'string') {
48641 for (var i = 0; i < msg.length; i++)
48642 res[i] = msg[i] | 0;
48643 return res;
48644 }
48645 if (enc === 'hex') {
48646 msg = msg.replace(/[^a-z0-9]+/ig, '');
48647 if (msg.length % 2 !== 0)
48648 msg = '0' + msg;
48649 for (var i = 0; i < msg.length; i += 2)
48650 res.push(parseInt(msg[i] + msg[i + 1], 16));
48651 } else {
48652 for (var i = 0; i < msg.length; i++) {
48653 var c = msg.charCodeAt(i);
48654 var hi = c >> 8;
48655 var lo = c & 0xff;
48656 if (hi)
48657 res.push(hi, lo);
48658 else
48659 res.push(lo);
48660 }
48661 }
48662 return res;
48663}
48664utils.toArray = toArray;
48665
48666function zero2(word) {
48667 if (word.length === 1)
48668 return '0' + word;
48669 else
48670 return word;
48671}
48672utils.zero2 = zero2;
48673
48674function toHex(msg) {
48675 var res = '';
48676 for (var i = 0; i < msg.length; i++)
48677 res += zero2(msg[i].toString(16));
48678 return res;
48679}
48680utils.toHex = toHex;
48681
48682utils.encode = function encode(arr, enc) {
48683 if (enc === 'hex')
48684 return toHex(arr);
48685 else
48686 return arr;
48687};
48688
48689},{}],239:[function(require,module,exports){
48690var crypto = require('crypto')
48691
48692function sha (key, body, algorithm) {
48693 return crypto.createHmac(algorithm, key).update(body).digest('base64')
48694}
48695
48696function rsa (key, body) {
48697 return crypto.createSign('RSA-SHA1').update(body).sign(key, 'base64')
48698}
48699
48700function rfc3986 (str) {
48701 return encodeURIComponent(str)
48702 .replace(/!/g,'%21')
48703 .replace(/\*/g,'%2A')
48704 .replace(/\(/g,'%28')
48705 .replace(/\)/g,'%29')
48706 .replace(/'/g,'%27')
48707}
48708
48709// Maps object to bi-dimensional array
48710// Converts { foo: 'A', bar: [ 'b', 'B' ]} to
48711// [ ['foo', 'A'], ['bar', 'b'], ['bar', 'B'] ]
48712function map (obj) {
48713 var key, val, arr = []
48714 for (key in obj) {
48715 val = obj[key]
48716 if (Array.isArray(val))
48717 for (var i = 0; i < val.length; i++)
48718 arr.push([key, val[i]])
48719 else if (typeof val === 'object')
48720 for (var prop in val)
48721 arr.push([key + '[' + prop + ']', val[prop]])
48722 else
48723 arr.push([key, val])
48724 }
48725 return arr
48726}
48727
48728// Compare function for sort
48729function compare (a, b) {
48730 return a > b ? 1 : a < b ? -1 : 0
48731}
48732
48733function generateBase (httpMethod, base_uri, params) {
48734 // adapted from https://dev.twitter.com/docs/auth/oauth and
48735 // https://dev.twitter.com/docs/auth/creating-signature
48736
48737 // Parameter normalization
48738 // http://tools.ietf.org/html/rfc5849#section-3.4.1.3.2
48739 var normalized = map(params)
48740 // 1. First, the name and value of each parameter are encoded
48741 .map(function (p) {
48742 return [ rfc3986(p[0]), rfc3986(p[1] || '') ]
48743 })
48744 // 2. The parameters are sorted by name, using ascending byte value
48745 // ordering. If two or more parameters share the same name, they
48746 // are sorted by their value.
48747 .sort(function (a, b) {
48748 return compare(a[0], b[0]) || compare(a[1], b[1])
48749 })
48750 // 3. The name of each parameter is concatenated to its corresponding
48751 // value using an "=" character (ASCII code 61) as a separator, even
48752 // if the value is empty.
48753 .map(function (p) { return p.join('=') })
48754 // 4. The sorted name/value pairs are concatenated together into a
48755 // single string by using an "&" character (ASCII code 38) as
48756 // separator.
48757 .join('&')
48758
48759 var base = [
48760 rfc3986(httpMethod ? httpMethod.toUpperCase() : 'GET'),
48761 rfc3986(base_uri),
48762 rfc3986(normalized)
48763 ].join('&')
48764
48765 return base
48766}
48767
48768function hmacsign (httpMethod, base_uri, params, consumer_secret, token_secret) {
48769 var base = generateBase(httpMethod, base_uri, params)
48770 var key = [
48771 consumer_secret || '',
48772 token_secret || ''
48773 ].map(rfc3986).join('&')
48774
48775 return sha(key, base, 'sha1')
48776}
48777
48778function hmacsign256 (httpMethod, base_uri, params, consumer_secret, token_secret) {
48779 var base = generateBase(httpMethod, base_uri, params)
48780 var key = [
48781 consumer_secret || '',
48782 token_secret || ''
48783 ].map(rfc3986).join('&')
48784
48785 return sha(key, base, 'sha256')
48786}
48787
48788function rsasign (httpMethod, base_uri, params, private_key, token_secret) {
48789 var base = generateBase(httpMethod, base_uri, params)
48790 var key = private_key || ''
48791
48792 return rsa(key, base)
48793}
48794
48795function plaintext (consumer_secret, token_secret) {
48796 var key = [
48797 consumer_secret || '',
48798 token_secret || ''
48799 ].map(rfc3986).join('&')
48800
48801 return key
48802}
48803
48804function sign (signMethod, httpMethod, base_uri, params, consumer_secret, token_secret) {
48805 var method
48806 var skipArgs = 1
48807
48808 switch (signMethod) {
48809 case 'RSA-SHA1':
48810 method = rsasign
48811 break
48812 case 'HMAC-SHA1':
48813 method = hmacsign
48814 break
48815 case 'HMAC-SHA256':
48816 method = hmacsign256
48817 break
48818 case 'PLAINTEXT':
48819 method = plaintext
48820 skipArgs = 4
48821 break
48822 default:
48823 throw new Error('Signature method not supported: ' + signMethod)
48824 }
48825
48826 return method.apply(null, [].slice.call(arguments, skipArgs))
48827}
48828
48829exports.hmacsign = hmacsign
48830exports.hmacsign256 = hmacsign256
48831exports.rsasign = rsasign
48832exports.plaintext = plaintext
48833exports.sign = sign
48834exports.rfc3986 = rfc3986
48835exports.generateBase = generateBase
48836},{"crypto":126}],240:[function(require,module,exports){
48837exports.endianness = function () { return 'LE' };
48838
48839exports.hostname = function () {
48840 if (typeof location !== 'undefined') {
48841 return location.hostname
48842 }
48843 else return '';
48844};
48845
48846exports.loadavg = function () { return [] };
48847
48848exports.uptime = function () { return 0 };
48849
48850exports.freemem = function () {
48851 return Number.MAX_VALUE;
48852};
48853
48854exports.totalmem = function () {
48855 return Number.MAX_VALUE;
48856};
48857
48858exports.cpus = function () { return [] };
48859
48860exports.type = function () { return 'Browser' };
48861
48862exports.release = function () {
48863 if (typeof navigator !== 'undefined') {
48864 return navigator.appVersion;
48865 }
48866 return '';
48867};
48868
48869exports.networkInterfaces
48870= exports.getNetworkInterfaces
48871= function () { return {} };
48872
48873exports.arch = function () { return 'javascript' };
48874
48875exports.platform = function () { return 'browser' };
48876
48877exports.tmpdir = exports.tmpDir = function () {
48878 return '/tmp';
48879};
48880
48881exports.EOL = '\n';
48882
48883exports.homedir = function () {
48884 return '/'
48885};
48886
48887},{}],241:[function(require,module,exports){
48888'use strict';
48889
48890
48891var TYPED_OK = (typeof Uint8Array !== 'undefined') &&
48892 (typeof Uint16Array !== 'undefined') &&
48893 (typeof Int32Array !== 'undefined');
48894
48895function _has(obj, key) {
48896 return Object.prototype.hasOwnProperty.call(obj, key);
48897}
48898
48899exports.assign = function (obj /*from1, from2, from3, ...*/) {
48900 var sources = Array.prototype.slice.call(arguments, 1);
48901 while (sources.length) {
48902 var source = sources.shift();
48903 if (!source) { continue; }
48904
48905 if (typeof source !== 'object') {
48906 throw new TypeError(source + 'must be non-object');
48907 }
48908
48909 for (var p in source) {
48910 if (_has(source, p)) {
48911 obj[p] = source[p];
48912 }
48913 }
48914 }
48915
48916 return obj;
48917};
48918
48919
48920// reduce buffer size, avoiding mem copy
48921exports.shrinkBuf = function (buf, size) {
48922 if (buf.length === size) { return buf; }
48923 if (buf.subarray) { return buf.subarray(0, size); }
48924 buf.length = size;
48925 return buf;
48926};
48927
48928
48929var fnTyped = {
48930 arraySet: function (dest, src, src_offs, len, dest_offs) {
48931 if (src.subarray && dest.subarray) {
48932 dest.set(src.subarray(src_offs, src_offs + len), dest_offs);
48933 return;
48934 }
48935 // Fallback to ordinary array
48936 for (var i = 0; i < len; i++) {
48937 dest[dest_offs + i] = src[src_offs + i];
48938 }
48939 },
48940 // Join array of chunks to single array.
48941 flattenChunks: function (chunks) {
48942 var i, l, len, pos, chunk, result;
48943
48944 // calculate data length
48945 len = 0;
48946 for (i = 0, l = chunks.length; i < l; i++) {
48947 len += chunks[i].length;
48948 }
48949
48950 // join chunks
48951 result = new Uint8Array(len);
48952 pos = 0;
48953 for (i = 0, l = chunks.length; i < l; i++) {
48954 chunk = chunks[i];
48955 result.set(chunk, pos);
48956 pos += chunk.length;
48957 }
48958
48959 return result;
48960 }
48961};
48962
48963var fnUntyped = {
48964 arraySet: function (dest, src, src_offs, len, dest_offs) {
48965 for (var i = 0; i < len; i++) {
48966 dest[dest_offs + i] = src[src_offs + i];
48967 }
48968 },
48969 // Join array of chunks to single array.
48970 flattenChunks: function (chunks) {
48971 return [].concat.apply([], chunks);
48972 }
48973};
48974
48975
48976// Enable/Disable typed arrays use, for testing
48977//
48978exports.setTyped = function (on) {
48979 if (on) {
48980 exports.Buf8 = Uint8Array;
48981 exports.Buf16 = Uint16Array;
48982 exports.Buf32 = Int32Array;
48983 exports.assign(exports, fnTyped);
48984 } else {
48985 exports.Buf8 = Array;
48986 exports.Buf16 = Array;
48987 exports.Buf32 = Array;
48988 exports.assign(exports, fnUntyped);
48989 }
48990};
48991
48992exports.setTyped(TYPED_OK);
48993
48994},{}],242:[function(require,module,exports){
48995'use strict';
48996
48997// Note: adler32 takes 12% for level 0 and 2% for level 6.
48998// It isn't worth it to make additional optimizations as in original.
48999// Small size is preferable.
49000
49001// (C) 1995-2013 Jean-loup Gailly and Mark Adler
49002// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
49003//
49004// This software is provided 'as-is', without any express or implied
49005// warranty. In no event will the authors be held liable for any damages
49006// arising from the use of this software.
49007//
49008// Permission is granted to anyone to use this software for any purpose,
49009// including commercial applications, and to alter it and redistribute it
49010// freely, subject to the following restrictions:
49011//
49012// 1. The origin of this software must not be misrepresented; you must not
49013// claim that you wrote the original software. If you use this software
49014// in a product, an acknowledgment in the product documentation would be
49015// appreciated but is not required.
49016// 2. Altered source versions must be plainly marked as such, and must not be
49017// misrepresented as being the original software.
49018// 3. This notice may not be removed or altered from any source distribution.
49019
49020function adler32(adler, buf, len, pos) {
49021 var s1 = (adler & 0xffff) |0,
49022 s2 = ((adler >>> 16) & 0xffff) |0,
49023 n = 0;
49024
49025 while (len !== 0) {
49026 // Set limit ~ twice less than 5552, to keep
49027 // s2 in 31-bits, because we force signed ints.
49028 // in other case %= will fail.
49029 n = len > 2000 ? 2000 : len;
49030 len -= n;
49031
49032 do {
49033 s1 = (s1 + buf[pos++]) |0;
49034 s2 = (s2 + s1) |0;
49035 } while (--n);
49036
49037 s1 %= 65521;
49038 s2 %= 65521;
49039 }
49040
49041 return (s1 | (s2 << 16)) |0;
49042}
49043
49044
49045module.exports = adler32;
49046
49047},{}],243:[function(require,module,exports){
49048'use strict';
49049
49050// (C) 1995-2013 Jean-loup Gailly and Mark Adler
49051// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
49052//
49053// This software is provided 'as-is', without any express or implied
49054// warranty. In no event will the authors be held liable for any damages
49055// arising from the use of this software.
49056//
49057// Permission is granted to anyone to use this software for any purpose,
49058// including commercial applications, and to alter it and redistribute it
49059// freely, subject to the following restrictions:
49060//
49061// 1. The origin of this software must not be misrepresented; you must not
49062// claim that you wrote the original software. If you use this software
49063// in a product, an acknowledgment in the product documentation would be
49064// appreciated but is not required.
49065// 2. Altered source versions must be plainly marked as such, and must not be
49066// misrepresented as being the original software.
49067// 3. This notice may not be removed or altered from any source distribution.
49068
49069module.exports = {
49070
49071 /* Allowed flush values; see deflate() and inflate() below for details */
49072 Z_NO_FLUSH: 0,
49073 Z_PARTIAL_FLUSH: 1,
49074 Z_SYNC_FLUSH: 2,
49075 Z_FULL_FLUSH: 3,
49076 Z_FINISH: 4,
49077 Z_BLOCK: 5,
49078 Z_TREES: 6,
49079
49080 /* Return codes for the compression/decompression functions. Negative values
49081 * are errors, positive values are used for special but normal events.
49082 */
49083 Z_OK: 0,
49084 Z_STREAM_END: 1,
49085 Z_NEED_DICT: 2,
49086 Z_ERRNO: -1,
49087 Z_STREAM_ERROR: -2,
49088 Z_DATA_ERROR: -3,
49089 //Z_MEM_ERROR: -4,
49090 Z_BUF_ERROR: -5,
49091 //Z_VERSION_ERROR: -6,
49092
49093 /* compression levels */
49094 Z_NO_COMPRESSION: 0,
49095 Z_BEST_SPEED: 1,
49096 Z_BEST_COMPRESSION: 9,
49097 Z_DEFAULT_COMPRESSION: -1,
49098
49099
49100 Z_FILTERED: 1,
49101 Z_HUFFMAN_ONLY: 2,
49102 Z_RLE: 3,
49103 Z_FIXED: 4,
49104 Z_DEFAULT_STRATEGY: 0,
49105
49106 /* Possible values of the data_type field (though see inflate()) */
49107 Z_BINARY: 0,
49108 Z_TEXT: 1,
49109 //Z_ASCII: 1, // = Z_TEXT (deprecated)
49110 Z_UNKNOWN: 2,
49111
49112 /* The deflate compression method */
49113 Z_DEFLATED: 8
49114 //Z_NULL: null // Use -1 or null inline, depending on var type
49115};
49116
49117},{}],244:[function(require,module,exports){
49118'use strict';
49119
49120// Note: we can't get significant speed boost here.
49121// So write code to minimize size - no pregenerated tables
49122// and array tools dependencies.
49123
49124// (C) 1995-2013 Jean-loup Gailly and Mark Adler
49125// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
49126//
49127// This software is provided 'as-is', without any express or implied
49128// warranty. In no event will the authors be held liable for any damages
49129// arising from the use of this software.
49130//
49131// Permission is granted to anyone to use this software for any purpose,
49132// including commercial applications, and to alter it and redistribute it
49133// freely, subject to the following restrictions:
49134//
49135// 1. The origin of this software must not be misrepresented; you must not
49136// claim that you wrote the original software. If you use this software
49137// in a product, an acknowledgment in the product documentation would be
49138// appreciated but is not required.
49139// 2. Altered source versions must be plainly marked as such, and must not be
49140// misrepresented as being the original software.
49141// 3. This notice may not be removed or altered from any source distribution.
49142
49143// Use ordinary array, since untyped makes no boost here
49144function makeTable() {
49145 var c, table = [];
49146
49147 for (var n = 0; n < 256; n++) {
49148 c = n;
49149 for (var k = 0; k < 8; k++) {
49150 c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
49151 }
49152 table[n] = c;
49153 }
49154
49155 return table;
49156}
49157
49158// Create table on load. Just 255 signed longs. Not a problem.
49159var crcTable = makeTable();
49160
49161
49162function crc32(crc, buf, len, pos) {
49163 var t = crcTable,
49164 end = pos + len;
49165
49166 crc ^= -1;
49167
49168 for (var i = pos; i < end; i++) {
49169 crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];
49170 }
49171
49172 return (crc ^ (-1)); // >>> 0;
49173}
49174
49175
49176module.exports = crc32;
49177
49178},{}],245:[function(require,module,exports){
49179'use strict';
49180
49181// (C) 1995-2013 Jean-loup Gailly and Mark Adler
49182// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
49183//
49184// This software is provided 'as-is', without any express or implied
49185// warranty. In no event will the authors be held liable for any damages
49186// arising from the use of this software.
49187//
49188// Permission is granted to anyone to use this software for any purpose,
49189// including commercial applications, and to alter it and redistribute it
49190// freely, subject to the following restrictions:
49191//
49192// 1. The origin of this software must not be misrepresented; you must not
49193// claim that you wrote the original software. If you use this software
49194// in a product, an acknowledgment in the product documentation would be
49195// appreciated but is not required.
49196// 2. Altered source versions must be plainly marked as such, and must not be
49197// misrepresented as being the original software.
49198// 3. This notice may not be removed or altered from any source distribution.
49199
49200var utils = require('../utils/common');
49201var trees = require('./trees');
49202var adler32 = require('./adler32');
49203var crc32 = require('./crc32');
49204var msg = require('./messages');
49205
49206/* Public constants ==========================================================*/
49207/* ===========================================================================*/
49208
49209
49210/* Allowed flush values; see deflate() and inflate() below for details */
49211var Z_NO_FLUSH = 0;
49212var Z_PARTIAL_FLUSH = 1;
49213//var Z_SYNC_FLUSH = 2;
49214var Z_FULL_FLUSH = 3;
49215var Z_FINISH = 4;
49216var Z_BLOCK = 5;
49217//var Z_TREES = 6;
49218
49219
49220/* Return codes for the compression/decompression functions. Negative values
49221 * are errors, positive values are used for special but normal events.
49222 */
49223var Z_OK = 0;
49224var Z_STREAM_END = 1;
49225//var Z_NEED_DICT = 2;
49226//var Z_ERRNO = -1;
49227var Z_STREAM_ERROR = -2;
49228var Z_DATA_ERROR = -3;
49229//var Z_MEM_ERROR = -4;
49230var Z_BUF_ERROR = -5;
49231//var Z_VERSION_ERROR = -6;
49232
49233
49234/* compression levels */
49235//var Z_NO_COMPRESSION = 0;
49236//var Z_BEST_SPEED = 1;
49237//var Z_BEST_COMPRESSION = 9;
49238var Z_DEFAULT_COMPRESSION = -1;
49239
49240
49241var Z_FILTERED = 1;
49242var Z_HUFFMAN_ONLY = 2;
49243var Z_RLE = 3;
49244var Z_FIXED = 4;
49245var Z_DEFAULT_STRATEGY = 0;
49246
49247/* Possible values of the data_type field (though see inflate()) */
49248//var Z_BINARY = 0;
49249//var Z_TEXT = 1;
49250//var Z_ASCII = 1; // = Z_TEXT
49251var Z_UNKNOWN = 2;
49252
49253
49254/* The deflate compression method */
49255var Z_DEFLATED = 8;
49256
49257/*============================================================================*/
49258
49259
49260var MAX_MEM_LEVEL = 9;
49261/* Maximum value for memLevel in deflateInit2 */
49262var MAX_WBITS = 15;
49263/* 32K LZ77 window */
49264var DEF_MEM_LEVEL = 8;
49265
49266
49267var LENGTH_CODES = 29;
49268/* number of length codes, not counting the special END_BLOCK code */
49269var LITERALS = 256;
49270/* number of literal bytes 0..255 */
49271var L_CODES = LITERALS + 1 + LENGTH_CODES;
49272/* number of Literal or Length codes, including the END_BLOCK code */
49273var D_CODES = 30;
49274/* number of distance codes */
49275var BL_CODES = 19;
49276/* number of codes used to transfer the bit lengths */
49277var HEAP_SIZE = 2 * L_CODES + 1;
49278/* maximum heap size */
49279var MAX_BITS = 15;
49280/* All codes must not exceed MAX_BITS bits */
49281
49282var MIN_MATCH = 3;
49283var MAX_MATCH = 258;
49284var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);
49285
49286var PRESET_DICT = 0x20;
49287
49288var INIT_STATE = 42;
49289var EXTRA_STATE = 69;
49290var NAME_STATE = 73;
49291var COMMENT_STATE = 91;
49292var HCRC_STATE = 103;
49293var BUSY_STATE = 113;
49294var FINISH_STATE = 666;
49295
49296var BS_NEED_MORE = 1; /* block not completed, need more input or more output */
49297var BS_BLOCK_DONE = 2; /* block flush performed */
49298var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */
49299var BS_FINISH_DONE = 4; /* finish done, accept no more input or output */
49300
49301var OS_CODE = 0x03; // Unix :) . Don't detect, use this default.
49302
49303function err(strm, errorCode) {
49304 strm.msg = msg[errorCode];
49305 return errorCode;
49306}
49307
49308function rank(f) {
49309 return ((f) << 1) - ((f) > 4 ? 9 : 0);
49310}
49311
49312function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
49313
49314
49315/* =========================================================================
49316 * Flush as much pending output as possible. All deflate() output goes
49317 * through this function so some applications may wish to modify it
49318 * to avoid allocating a large strm->output buffer and copying into it.
49319 * (See also read_buf()).
49320 */
49321function flush_pending(strm) {
49322 var s = strm.state;
49323
49324 //_tr_flush_bits(s);
49325 var len = s.pending;
49326 if (len > strm.avail_out) {
49327 len = strm.avail_out;
49328 }
49329 if (len === 0) { return; }
49330
49331 utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out);
49332 strm.next_out += len;
49333 s.pending_out += len;
49334 strm.total_out += len;
49335 strm.avail_out -= len;
49336 s.pending -= len;
49337 if (s.pending === 0) {
49338 s.pending_out = 0;
49339 }
49340}
49341
49342
49343function flush_block_only(s, last) {
49344 trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last);
49345 s.block_start = s.strstart;
49346 flush_pending(s.strm);
49347}
49348
49349
49350function put_byte(s, b) {
49351 s.pending_buf[s.pending++] = b;
49352}
49353
49354
49355/* =========================================================================
49356 * Put a short in the pending buffer. The 16-bit value is put in MSB order.
49357 * IN assertion: the stream state is correct and there is enough room in
49358 * pending_buf.
49359 */
49360function putShortMSB(s, b) {
49361// put_byte(s, (Byte)(b >> 8));
49362// put_byte(s, (Byte)(b & 0xff));
49363 s.pending_buf[s.pending++] = (b >>> 8) & 0xff;
49364 s.pending_buf[s.pending++] = b & 0xff;
49365}
49366
49367
49368/* ===========================================================================
49369 * Read a new buffer from the current input stream, update the adler32
49370 * and total number of bytes read. All deflate() input goes through
49371 * this function so some applications may wish to modify it to avoid
49372 * allocating a large strm->input buffer and copying from it.
49373 * (See also flush_pending()).
49374 */
49375function read_buf(strm, buf, start, size) {
49376 var len = strm.avail_in;
49377
49378 if (len > size) { len = size; }
49379 if (len === 0) { return 0; }
49380
49381 strm.avail_in -= len;
49382
49383 // zmemcpy(buf, strm->next_in, len);
49384 utils.arraySet(buf, strm.input, strm.next_in, len, start);
49385 if (strm.state.wrap === 1) {
49386 strm.adler = adler32(strm.adler, buf, len, start);
49387 }
49388
49389 else if (strm.state.wrap === 2) {
49390 strm.adler = crc32(strm.adler, buf, len, start);
49391 }
49392
49393 strm.next_in += len;
49394 strm.total_in += len;
49395
49396 return len;
49397}
49398
49399
49400/* ===========================================================================
49401 * Set match_start to the longest match starting at the given string and
49402 * return its length. Matches shorter or equal to prev_length are discarded,
49403 * in which case the result is equal to prev_length and match_start is
49404 * garbage.
49405 * IN assertions: cur_match is the head of the hash chain for the current
49406 * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
49407 * OUT assertion: the match length is not greater than s->lookahead.
49408 */
49409function longest_match(s, cur_match) {
49410 var chain_length = s.max_chain_length; /* max hash chain length */
49411 var scan = s.strstart; /* current string */
49412 var match; /* matched string */
49413 var len; /* length of current match */
49414 var best_len = s.prev_length; /* best match length so far */
49415 var nice_match = s.nice_match; /* stop if match long enough */
49416 var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?
49417 s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;
49418
49419 var _win = s.window; // shortcut
49420
49421 var wmask = s.w_mask;
49422 var prev = s.prev;
49423
49424 /* Stop when cur_match becomes <= limit. To simplify the code,
49425 * we prevent matches with the string of window index 0.
49426 */
49427
49428 var strend = s.strstart + MAX_MATCH;
49429 var scan_end1 = _win[scan + best_len - 1];
49430 var scan_end = _win[scan + best_len];
49431
49432 /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
49433 * It is easy to get rid of this optimization if necessary.
49434 */
49435 // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
49436
49437 /* Do not waste too much time if we already have a good match: */
49438 if (s.prev_length >= s.good_match) {
49439 chain_length >>= 2;
49440 }
49441 /* Do not look for matches beyond the end of the input. This is necessary
49442 * to make deflate deterministic.
49443 */
49444 if (nice_match > s.lookahead) { nice_match = s.lookahead; }
49445
49446 // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
49447
49448 do {
49449 // Assert(cur_match < s->strstart, "no future");
49450 match = cur_match;
49451
49452 /* Skip to next match if the match length cannot increase
49453 * or if the match length is less than 2. Note that the checks below
49454 * for insufficient lookahead only occur occasionally for performance
49455 * reasons. Therefore uninitialized memory will be accessed, and
49456 * conditional jumps will be made that depend on those values.
49457 * However the length of the match is limited to the lookahead, so
49458 * the output of deflate is not affected by the uninitialized values.
49459 */
49460
49461 if (_win[match + best_len] !== scan_end ||
49462 _win[match + best_len - 1] !== scan_end1 ||
49463 _win[match] !== _win[scan] ||
49464 _win[++match] !== _win[scan + 1]) {
49465 continue;
49466 }
49467
49468 /* The check at best_len-1 can be removed because it will be made
49469 * again later. (This heuristic is not always a win.)
49470 * It is not necessary to compare scan[2] and match[2] since they
49471 * are always equal when the other bytes match, given that
49472 * the hash keys are equal and that HASH_BITS >= 8.
49473 */
49474 scan += 2;
49475 match++;
49476 // Assert(*scan == *match, "match[2]?");
49477
49478 /* We check for insufficient lookahead only every 8th comparison;
49479 * the 256th check will be made at strstart+258.
49480 */
49481 do {
49482 /*jshint noempty:false*/
49483 } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
49484 _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
49485 _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
49486 _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
49487 scan < strend);
49488
49489 // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
49490
49491 len = MAX_MATCH - (strend - scan);
49492 scan = strend - MAX_MATCH;
49493
49494 if (len > best_len) {
49495 s.match_start = cur_match;
49496 best_len = len;
49497 if (len >= nice_match) {
49498 break;
49499 }
49500 scan_end1 = _win[scan + best_len - 1];
49501 scan_end = _win[scan + best_len];
49502 }
49503 } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);
49504
49505 if (best_len <= s.lookahead) {
49506 return best_len;
49507 }
49508 return s.lookahead;
49509}
49510
49511
49512/* ===========================================================================
49513 * Fill the window when the lookahead becomes insufficient.
49514 * Updates strstart and lookahead.
49515 *
49516 * IN assertion: lookahead < MIN_LOOKAHEAD
49517 * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
49518 * At least one byte has been read, or avail_in == 0; reads are
49519 * performed for at least two bytes (required for the zip translate_eol
49520 * option -- not supported here).
49521 */
49522function fill_window(s) {
49523 var _w_size = s.w_size;
49524 var p, n, m, more, str;
49525
49526 //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");
49527
49528 do {
49529 more = s.window_size - s.lookahead - s.strstart;
49530
49531 // JS ints have 32 bit, block below not needed
49532 /* Deal with !@#$% 64K limit: */
49533 //if (sizeof(int) <= 2) {
49534 // if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
49535 // more = wsize;
49536 //
49537 // } else if (more == (unsigned)(-1)) {
49538 // /* Very unlikely, but possible on 16 bit machine if
49539 // * strstart == 0 && lookahead == 1 (input done a byte at time)
49540 // */
49541 // more--;
49542 // }
49543 //}
49544
49545
49546 /* If the window is almost full and there is insufficient lookahead,
49547 * move the upper half to the lower one to make room in the upper half.
49548 */
49549 if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {
49550
49551 utils.arraySet(s.window, s.window, _w_size, _w_size, 0);
49552 s.match_start -= _w_size;
49553 s.strstart -= _w_size;
49554 /* we now have strstart >= MAX_DIST */
49555 s.block_start -= _w_size;
49556
49557 /* Slide the hash table (could be avoided with 32 bit values
49558 at the expense of memory usage). We slide even when level == 0
49559 to keep the hash table consistent if we switch back to level > 0
49560 later. (Using level 0 permanently is not an optimal usage of
49561 zlib, so we don't care about this pathological case.)
49562 */
49563
49564 n = s.hash_size;
49565 p = n;
49566 do {
49567 m = s.head[--p];
49568 s.head[p] = (m >= _w_size ? m - _w_size : 0);
49569 } while (--n);
49570
49571 n = _w_size;
49572 p = n;
49573 do {
49574 m = s.prev[--p];
49575 s.prev[p] = (m >= _w_size ? m - _w_size : 0);
49576 /* If n is not on any hash chain, prev[n] is garbage but
49577 * its value will never be used.
49578 */
49579 } while (--n);
49580
49581 more += _w_size;
49582 }
49583 if (s.strm.avail_in === 0) {
49584 break;
49585 }
49586
49587 /* If there was no sliding:
49588 * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
49589 * more == window_size - lookahead - strstart
49590 * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
49591 * => more >= window_size - 2*WSIZE + 2
49592 * In the BIG_MEM or MMAP case (not yet supported),
49593 * window_size == input_size + MIN_LOOKAHEAD &&
49594 * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
49595 * Otherwise, window_size == 2*WSIZE so more >= 2.
49596 * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
49597 */
49598 //Assert(more >= 2, "more < 2");
49599 n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);
49600 s.lookahead += n;
49601
49602 /* Initialize the hash value now that we have some input: */
49603 if (s.lookahead + s.insert >= MIN_MATCH) {
49604 str = s.strstart - s.insert;
49605 s.ins_h = s.window[str];
49606
49607 /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */
49608 s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask;
49609//#if MIN_MATCH != 3
49610// Call update_hash() MIN_MATCH-3 more times
49611//#endif
49612 while (s.insert) {
49613 /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
49614 s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH - 1]) & s.hash_mask;
49615
49616 s.prev[str & s.w_mask] = s.head[s.ins_h];
49617 s.head[s.ins_h] = str;
49618 str++;
49619 s.insert--;
49620 if (s.lookahead + s.insert < MIN_MATCH) {
49621 break;
49622 }
49623 }
49624 }
49625 /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
49626 * but this is not important since only literal bytes will be emitted.
49627 */
49628
49629 } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);
49630
49631 /* If the WIN_INIT bytes after the end of the current data have never been
49632 * written, then zero those bytes in order to avoid memory check reports of
49633 * the use of uninitialized (or uninitialised as Julian writes) bytes by
49634 * the longest match routines. Update the high water mark for the next
49635 * time through here. WIN_INIT is set to MAX_MATCH since the longest match
49636 * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
49637 */
49638// if (s.high_water < s.window_size) {
49639// var curr = s.strstart + s.lookahead;
49640// var init = 0;
49641//
49642// if (s.high_water < curr) {
49643// /* Previous high water mark below current data -- zero WIN_INIT
49644// * bytes or up to end of window, whichever is less.
49645// */
49646// init = s.window_size - curr;
49647// if (init > WIN_INIT)
49648// init = WIN_INIT;
49649// zmemzero(s->window + curr, (unsigned)init);
49650// s->high_water = curr + init;
49651// }
49652// else if (s->high_water < (ulg)curr + WIN_INIT) {
49653// /* High water mark at or above current data, but below current data
49654// * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
49655// * to end of window, whichever is less.
49656// */
49657// init = (ulg)curr + WIN_INIT - s->high_water;
49658// if (init > s->window_size - s->high_water)
49659// init = s->window_size - s->high_water;
49660// zmemzero(s->window + s->high_water, (unsigned)init);
49661// s->high_water += init;
49662// }
49663// }
49664//
49665// Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
49666// "not enough room for search");
49667}
49668
49669/* ===========================================================================
49670 * Copy without compression as much as possible from the input stream, return
49671 * the current block state.
49672 * This function does not insert new strings in the dictionary since
49673 * uncompressible data is probably not useful. This function is used
49674 * only for the level=0 compression option.
49675 * NOTE: this function should be optimized to avoid extra copying from
49676 * window to pending_buf.
49677 */
49678function deflate_stored(s, flush) {
49679 /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
49680 * to pending_buf_size, and each stored block has a 5 byte header:
49681 */
49682 var max_block_size = 0xffff;
49683
49684 if (max_block_size > s.pending_buf_size - 5) {
49685 max_block_size = s.pending_buf_size - 5;
49686 }
49687
49688 /* Copy as much as possible from input to output: */
49689 for (;;) {
49690 /* Fill the window as much as possible: */
49691 if (s.lookahead <= 1) {
49692
49693 //Assert(s->strstart < s->w_size+MAX_DIST(s) ||
49694 // s->block_start >= (long)s->w_size, "slide too late");
49695// if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) ||
49696// s.block_start >= s.w_size)) {
49697// throw new Error("slide too late");
49698// }
49699
49700 fill_window(s);
49701 if (s.lookahead === 0 && flush === Z_NO_FLUSH) {
49702 return BS_NEED_MORE;
49703 }
49704
49705 if (s.lookahead === 0) {
49706 break;
49707 }
49708 /* flush the current block */
49709 }
49710 //Assert(s->block_start >= 0L, "block gone");
49711// if (s.block_start < 0) throw new Error("block gone");
49712
49713 s.strstart += s.lookahead;
49714 s.lookahead = 0;
49715
49716 /* Emit a stored block if pending_buf will be full: */
49717 var max_start = s.block_start + max_block_size;
49718
49719 if (s.strstart === 0 || s.strstart >= max_start) {
49720 /* strstart == 0 is possible when wraparound on 16-bit machine */
49721 s.lookahead = s.strstart - max_start;
49722 s.strstart = max_start;
49723 /*** FLUSH_BLOCK(s, 0); ***/
49724 flush_block_only(s, false);
49725 if (s.strm.avail_out === 0) {
49726 return BS_NEED_MORE;
49727 }
49728 /***/
49729
49730
49731 }
49732 /* Flush if we may have to slide, otherwise block_start may become
49733 * negative and the data will be gone:
49734 */
49735 if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) {
49736 /*** FLUSH_BLOCK(s, 0); ***/
49737 flush_block_only(s, false);
49738 if (s.strm.avail_out === 0) {
49739 return BS_NEED_MORE;
49740 }
49741 /***/
49742 }
49743 }
49744
49745 s.insert = 0;
49746
49747 if (flush === Z_FINISH) {
49748 /*** FLUSH_BLOCK(s, 1); ***/
49749 flush_block_only(s, true);
49750 if (s.strm.avail_out === 0) {
49751 return BS_FINISH_STARTED;
49752 }
49753 /***/
49754 return BS_FINISH_DONE;
49755 }
49756
49757 if (s.strstart > s.block_start) {
49758 /*** FLUSH_BLOCK(s, 0); ***/
49759 flush_block_only(s, false);
49760 if (s.strm.avail_out === 0) {
49761 return BS_NEED_MORE;
49762 }
49763 /***/
49764 }
49765
49766 return BS_NEED_MORE;
49767}
49768
49769/* ===========================================================================
49770 * Compress as much as possible from the input stream, return the current
49771 * block state.
49772 * This function does not perform lazy evaluation of matches and inserts
49773 * new strings in the dictionary only for unmatched strings or for short
49774 * matches. It is used only for the fast compression options.
49775 */
49776function deflate_fast(s, flush) {
49777 var hash_head; /* head of the hash chain */
49778 var bflush; /* set if current block must be flushed */
49779
49780 for (;;) {
49781 /* Make sure that we always have enough lookahead, except
49782 * at the end of the input file. We need MAX_MATCH bytes
49783 * for the next match, plus MIN_MATCH bytes to insert the
49784 * string following the next match.
49785 */
49786 if (s.lookahead < MIN_LOOKAHEAD) {
49787 fill_window(s);
49788 if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
49789 return BS_NEED_MORE;
49790 }
49791 if (s.lookahead === 0) {
49792 break; /* flush the current block */
49793 }
49794 }
49795
49796 /* Insert the string window[strstart .. strstart+2] in the
49797 * dictionary, and set hash_head to the head of the hash chain:
49798 */
49799 hash_head = 0/*NIL*/;
49800 if (s.lookahead >= MIN_MATCH) {
49801 /*** INSERT_STRING(s, s.strstart, hash_head); ***/
49802 s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
49803 hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
49804 s.head[s.ins_h] = s.strstart;
49805 /***/
49806 }
49807
49808 /* Find the longest match, discarding those <= prev_length.
49809 * At this point we have always match_length < MIN_MATCH
49810 */
49811 if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) {
49812 /* To simplify the code, we prevent matches with the string
49813 * of window index 0 (in particular we have to avoid a match
49814 * of the string with itself at the start of the input file).
49815 */
49816 s.match_length = longest_match(s, hash_head);
49817 /* longest_match() sets match_start */
49818 }
49819 if (s.match_length >= MIN_MATCH) {
49820 // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only
49821
49822 /*** _tr_tally_dist(s, s.strstart - s.match_start,
49823 s.match_length - MIN_MATCH, bflush); ***/
49824 bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH);
49825
49826 s.lookahead -= s.match_length;
49827
49828 /* Insert new strings in the hash table only if the match length
49829 * is not too large. This saves time but degrades compression.
49830 */
49831 if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) {
49832 s.match_length--; /* string at strstart already in table */
49833 do {
49834 s.strstart++;
49835 /*** INSERT_STRING(s, s.strstart, hash_head); ***/
49836 s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
49837 hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
49838 s.head[s.ins_h] = s.strstart;
49839 /***/
49840 /* strstart never exceeds WSIZE-MAX_MATCH, so there are
49841 * always MIN_MATCH bytes ahead.
49842 */
49843 } while (--s.match_length !== 0);
49844 s.strstart++;
49845 } else
49846 {
49847 s.strstart += s.match_length;
49848 s.match_length = 0;
49849 s.ins_h = s.window[s.strstart];
49850 /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */
49851 s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask;
49852
49853//#if MIN_MATCH != 3
49854// Call UPDATE_HASH() MIN_MATCH-3 more times
49855//#endif
49856 /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
49857 * matter since it will be recomputed at next deflate call.
49858 */
49859 }
49860 } else {
49861 /* No match, output a literal byte */
49862 //Tracevv((stderr,"%c", s.window[s.strstart]));
49863 /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
49864 bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
49865
49866 s.lookahead--;
49867 s.strstart++;
49868 }
49869 if (bflush) {
49870 /*** FLUSH_BLOCK(s, 0); ***/
49871 flush_block_only(s, false);
49872 if (s.strm.avail_out === 0) {
49873 return BS_NEED_MORE;
49874 }
49875 /***/
49876 }
49877 }
49878 s.insert = ((s.strstart < (MIN_MATCH - 1)) ? s.strstart : MIN_MATCH - 1);
49879 if (flush === Z_FINISH) {
49880 /*** FLUSH_BLOCK(s, 1); ***/
49881 flush_block_only(s, true);
49882 if (s.strm.avail_out === 0) {
49883 return BS_FINISH_STARTED;
49884 }
49885 /***/
49886 return BS_FINISH_DONE;
49887 }
49888 if (s.last_lit) {
49889 /*** FLUSH_BLOCK(s, 0); ***/
49890 flush_block_only(s, false);
49891 if (s.strm.avail_out === 0) {
49892 return BS_NEED_MORE;
49893 }
49894 /***/
49895 }
49896 return BS_BLOCK_DONE;
49897}
49898
49899/* ===========================================================================
49900 * Same as above, but achieves better compression. We use a lazy
49901 * evaluation for matches: a match is finally adopted only if there is
49902 * no better match at the next window position.
49903 */
49904function deflate_slow(s, flush) {
49905 var hash_head; /* head of hash chain */
49906 var bflush; /* set if current block must be flushed */
49907
49908 var max_insert;
49909
49910 /* Process the input block. */
49911 for (;;) {
49912 /* Make sure that we always have enough lookahead, except
49913 * at the end of the input file. We need MAX_MATCH bytes
49914 * for the next match, plus MIN_MATCH bytes to insert the
49915 * string following the next match.
49916 */
49917 if (s.lookahead < MIN_LOOKAHEAD) {
49918 fill_window(s);
49919 if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
49920 return BS_NEED_MORE;
49921 }
49922 if (s.lookahead === 0) { break; } /* flush the current block */
49923 }
49924
49925 /* Insert the string window[strstart .. strstart+2] in the
49926 * dictionary, and set hash_head to the head of the hash chain:
49927 */
49928 hash_head = 0/*NIL*/;
49929 if (s.lookahead >= MIN_MATCH) {
49930 /*** INSERT_STRING(s, s.strstart, hash_head); ***/
49931 s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
49932 hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
49933 s.head[s.ins_h] = s.strstart;
49934 /***/
49935 }
49936
49937 /* Find the longest match, discarding those <= prev_length.
49938 */
49939 s.prev_length = s.match_length;
49940 s.prev_match = s.match_start;
49941 s.match_length = MIN_MATCH - 1;
49942
49943 if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match &&
49944 s.strstart - hash_head <= (s.w_size - MIN_LOOKAHEAD)/*MAX_DIST(s)*/) {
49945 /* To simplify the code, we prevent matches with the string
49946 * of window index 0 (in particular we have to avoid a match
49947 * of the string with itself at the start of the input file).
49948 */
49949 s.match_length = longest_match(s, hash_head);
49950 /* longest_match() sets match_start */
49951
49952 if (s.match_length <= 5 &&
49953 (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) {
49954
49955 /* If prev_match is also MIN_MATCH, match_start is garbage
49956 * but we will ignore the current match anyway.
49957 */
49958 s.match_length = MIN_MATCH - 1;
49959 }
49960 }
49961 /* If there was a match at the previous step and the current
49962 * match is not better, output the previous match:
49963 */
49964 if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) {
49965 max_insert = s.strstart + s.lookahead - MIN_MATCH;
49966 /* Do not insert strings in hash table beyond this. */
49967
49968 //check_match(s, s.strstart-1, s.prev_match, s.prev_length);
49969
49970 /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,
49971 s.prev_length - MIN_MATCH, bflush);***/
49972 bflush = trees._tr_tally(s, s.strstart - 1 - s.prev_match, s.prev_length - MIN_MATCH);
49973 /* Insert in hash table all strings up to the end of the match.
49974 * strstart-1 and strstart are already inserted. If there is not
49975 * enough lookahead, the last two strings are not inserted in
49976 * the hash table.
49977 */
49978 s.lookahead -= s.prev_length - 1;
49979 s.prev_length -= 2;
49980 do {
49981 if (++s.strstart <= max_insert) {
49982 /*** INSERT_STRING(s, s.strstart, hash_head); ***/
49983 s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
49984 hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
49985 s.head[s.ins_h] = s.strstart;
49986 /***/
49987 }
49988 } while (--s.prev_length !== 0);
49989 s.match_available = 0;
49990 s.match_length = MIN_MATCH - 1;
49991 s.strstart++;
49992
49993 if (bflush) {
49994 /*** FLUSH_BLOCK(s, 0); ***/
49995 flush_block_only(s, false);
49996 if (s.strm.avail_out === 0) {
49997 return BS_NEED_MORE;
49998 }
49999 /***/
50000 }
50001
50002 } else if (s.match_available) {
50003 /* If there was no match at the previous position, output a
50004 * single literal. If there was a match but the current match
50005 * is longer, truncate the previous match to a single literal.
50006 */
50007 //Tracevv((stderr,"%c", s->window[s->strstart-1]));
50008 /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
50009 bflush = trees._tr_tally(s, 0, s.window[s.strstart - 1]);
50010
50011 if (bflush) {
50012 /*** FLUSH_BLOCK_ONLY(s, 0) ***/
50013 flush_block_only(s, false);
50014 /***/
50015 }
50016 s.strstart++;
50017 s.lookahead--;
50018 if (s.strm.avail_out === 0) {
50019 return BS_NEED_MORE;
50020 }
50021 } else {
50022 /* There is no previous match to compare with, wait for
50023 * the next step to decide.
50024 */
50025 s.match_available = 1;
50026 s.strstart++;
50027 s.lookahead--;
50028 }
50029 }
50030 //Assert (flush != Z_NO_FLUSH, "no flush?");
50031 if (s.match_available) {
50032 //Tracevv((stderr,"%c", s->window[s->strstart-1]));
50033 /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
50034 bflush = trees._tr_tally(s, 0, s.window[s.strstart - 1]);
50035
50036 s.match_available = 0;
50037 }
50038 s.insert = s.strstart < MIN_MATCH - 1 ? s.strstart : MIN_MATCH - 1;
50039 if (flush === Z_FINISH) {
50040 /*** FLUSH_BLOCK(s, 1); ***/
50041 flush_block_only(s, true);
50042 if (s.strm.avail_out === 0) {
50043 return BS_FINISH_STARTED;
50044 }
50045 /***/
50046 return BS_FINISH_DONE;
50047 }
50048 if (s.last_lit) {
50049 /*** FLUSH_BLOCK(s, 0); ***/
50050 flush_block_only(s, false);
50051 if (s.strm.avail_out === 0) {
50052 return BS_NEED_MORE;
50053 }
50054 /***/
50055 }
50056
50057 return BS_BLOCK_DONE;
50058}
50059
50060
50061/* ===========================================================================
50062 * For Z_RLE, simply look for runs of bytes, generate matches only of distance
50063 * one. Do not maintain a hash table. (It will be regenerated if this run of
50064 * deflate switches away from Z_RLE.)
50065 */
50066function deflate_rle(s, flush) {
50067 var bflush; /* set if current block must be flushed */
50068 var prev; /* byte at distance one to match */
50069 var scan, strend; /* scan goes up to strend for length of run */
50070
50071 var _win = s.window;
50072
50073 for (;;) {
50074 /* Make sure that we always have enough lookahead, except
50075 * at the end of the input file. We need MAX_MATCH bytes
50076 * for the longest run, plus one for the unrolled loop.
50077 */
50078 if (s.lookahead <= MAX_MATCH) {
50079 fill_window(s);
50080 if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) {
50081 return BS_NEED_MORE;
50082 }
50083 if (s.lookahead === 0) { break; } /* flush the current block */
50084 }
50085
50086 /* See how many times the previous byte repeats */
50087 s.match_length = 0;
50088 if (s.lookahead >= MIN_MATCH && s.strstart > 0) {
50089 scan = s.strstart - 1;
50090 prev = _win[scan];
50091 if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {
50092 strend = s.strstart + MAX_MATCH;
50093 do {
50094 /*jshint noempty:false*/
50095 } while (prev === _win[++scan] && prev === _win[++scan] &&
50096 prev === _win[++scan] && prev === _win[++scan] &&
50097 prev === _win[++scan] && prev === _win[++scan] &&
50098 prev === _win[++scan] && prev === _win[++scan] &&
50099 scan < strend);
50100 s.match_length = MAX_MATCH - (strend - scan);
50101 if (s.match_length > s.lookahead) {
50102 s.match_length = s.lookahead;
50103 }
50104 }
50105 //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan");
50106 }
50107
50108 /* Emit match if have run of MIN_MATCH or longer, else emit literal */
50109 if (s.match_length >= MIN_MATCH) {
50110 //check_match(s, s.strstart, s.strstart - 1, s.match_length);
50111
50112 /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/
50113 bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH);
50114
50115 s.lookahead -= s.match_length;
50116 s.strstart += s.match_length;
50117 s.match_length = 0;
50118 } else {
50119 /* No match, output a literal byte */
50120 //Tracevv((stderr,"%c", s->window[s->strstart]));
50121 /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
50122 bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
50123
50124 s.lookahead--;
50125 s.strstart++;
50126 }
50127 if (bflush) {
50128 /*** FLUSH_BLOCK(s, 0); ***/
50129 flush_block_only(s, false);
50130 if (s.strm.avail_out === 0) {
50131 return BS_NEED_MORE;
50132 }
50133 /***/
50134 }
50135 }
50136 s.insert = 0;
50137 if (flush === Z_FINISH) {
50138 /*** FLUSH_BLOCK(s, 1); ***/
50139 flush_block_only(s, true);
50140 if (s.strm.avail_out === 0) {
50141 return BS_FINISH_STARTED;
50142 }
50143 /***/
50144 return BS_FINISH_DONE;
50145 }
50146 if (s.last_lit) {
50147 /*** FLUSH_BLOCK(s, 0); ***/
50148 flush_block_only(s, false);
50149 if (s.strm.avail_out === 0) {
50150 return BS_NEED_MORE;
50151 }
50152 /***/
50153 }
50154 return BS_BLOCK_DONE;
50155}
50156
50157/* ===========================================================================
50158 * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.
50159 * (It will be regenerated if this run of deflate switches away from Huffman.)
50160 */
50161function deflate_huff(s, flush) {
50162 var bflush; /* set if current block must be flushed */
50163
50164 for (;;) {
50165 /* Make sure that we have a literal to write. */
50166 if (s.lookahead === 0) {
50167 fill_window(s);
50168 if (s.lookahead === 0) {
50169 if (flush === Z_NO_FLUSH) {
50170 return BS_NEED_MORE;
50171 }
50172 break; /* flush the current block */
50173 }
50174 }
50175
50176 /* Output a literal byte */
50177 s.match_length = 0;
50178 //Tracevv((stderr,"%c", s->window[s->strstart]));
50179 /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
50180 bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
50181 s.lookahead--;
50182 s.strstart++;
50183 if (bflush) {
50184 /*** FLUSH_BLOCK(s, 0); ***/
50185 flush_block_only(s, false);
50186 if (s.strm.avail_out === 0) {
50187 return BS_NEED_MORE;
50188 }
50189 /***/
50190 }
50191 }
50192 s.insert = 0;
50193 if (flush === Z_FINISH) {
50194 /*** FLUSH_BLOCK(s, 1); ***/
50195 flush_block_only(s, true);
50196 if (s.strm.avail_out === 0) {
50197 return BS_FINISH_STARTED;
50198 }
50199 /***/
50200 return BS_FINISH_DONE;
50201 }
50202 if (s.last_lit) {
50203 /*** FLUSH_BLOCK(s, 0); ***/
50204 flush_block_only(s, false);
50205 if (s.strm.avail_out === 0) {
50206 return BS_NEED_MORE;
50207 }
50208 /***/
50209 }
50210 return BS_BLOCK_DONE;
50211}
50212
50213/* Values for max_lazy_match, good_match and max_chain_length, depending on
50214 * the desired pack level (0..9). The values given below have been tuned to
50215 * exclude worst case performance for pathological files. Better values may be
50216 * found for specific files.
50217 */
50218function Config(good_length, max_lazy, nice_length, max_chain, func) {
50219 this.good_length = good_length;
50220 this.max_lazy = max_lazy;
50221 this.nice_length = nice_length;
50222 this.max_chain = max_chain;
50223 this.func = func;
50224}
50225
50226var configuration_table;
50227
50228configuration_table = [
50229 /* good lazy nice chain */
50230 new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */
50231 new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */
50232 new Config(4, 5, 16, 8, deflate_fast), /* 2 */
50233 new Config(4, 6, 32, 32, deflate_fast), /* 3 */
50234
50235 new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */
50236 new Config(8, 16, 32, 32, deflate_slow), /* 5 */
50237 new Config(8, 16, 128, 128, deflate_slow), /* 6 */
50238 new Config(8, 32, 128, 256, deflate_slow), /* 7 */
50239 new Config(32, 128, 258, 1024, deflate_slow), /* 8 */
50240 new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */
50241];
50242
50243
50244/* ===========================================================================
50245 * Initialize the "longest match" routines for a new zlib stream
50246 */
50247function lm_init(s) {
50248 s.window_size = 2 * s.w_size;
50249
50250 /*** CLEAR_HASH(s); ***/
50251 zero(s.head); // Fill with NIL (= 0);
50252
50253 /* Set the default configuration parameters:
50254 */
50255 s.max_lazy_match = configuration_table[s.level].max_lazy;
50256 s.good_match = configuration_table[s.level].good_length;
50257 s.nice_match = configuration_table[s.level].nice_length;
50258 s.max_chain_length = configuration_table[s.level].max_chain;
50259
50260 s.strstart = 0;
50261 s.block_start = 0;
50262 s.lookahead = 0;
50263 s.insert = 0;
50264 s.match_length = s.prev_length = MIN_MATCH - 1;
50265 s.match_available = 0;
50266 s.ins_h = 0;
50267}
50268
50269
50270function DeflateState() {
50271 this.strm = null; /* pointer back to this zlib stream */
50272 this.status = 0; /* as the name implies */
50273 this.pending_buf = null; /* output still pending */
50274 this.pending_buf_size = 0; /* size of pending_buf */
50275 this.pending_out = 0; /* next pending byte to output to the stream */
50276 this.pending = 0; /* nb of bytes in the pending buffer */
50277 this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
50278 this.gzhead = null; /* gzip header information to write */
50279 this.gzindex = 0; /* where in extra, name, or comment */
50280 this.method = Z_DEFLATED; /* can only be DEFLATED */
50281 this.last_flush = -1; /* value of flush param for previous deflate call */
50282
50283 this.w_size = 0; /* LZ77 window size (32K by default) */
50284 this.w_bits = 0; /* log2(w_size) (8..16) */
50285 this.w_mask = 0; /* w_size - 1 */
50286
50287 this.window = null;
50288 /* Sliding window. Input bytes are read into the second half of the window,
50289 * and move to the first half later to keep a dictionary of at least wSize
50290 * bytes. With this organization, matches are limited to a distance of
50291 * wSize-MAX_MATCH bytes, but this ensures that IO is always
50292 * performed with a length multiple of the block size.
50293 */
50294
50295 this.window_size = 0;
50296 /* Actual size of window: 2*wSize, except when the user input buffer
50297 * is directly used as sliding window.
50298 */
50299
50300 this.prev = null;
50301 /* Link to older string with same hash index. To limit the size of this
50302 * array to 64K, this link is maintained only for the last 32K strings.
50303 * An index in this array is thus a window index modulo 32K.
50304 */
50305
50306 this.head = null; /* Heads of the hash chains or NIL. */
50307
50308 this.ins_h = 0; /* hash index of string to be inserted */
50309 this.hash_size = 0; /* number of elements in hash table */
50310 this.hash_bits = 0; /* log2(hash_size) */
50311 this.hash_mask = 0; /* hash_size-1 */
50312
50313 this.hash_shift = 0;
50314 /* Number of bits by which ins_h must be shifted at each input
50315 * step. It must be such that after MIN_MATCH steps, the oldest
50316 * byte no longer takes part in the hash key, that is:
50317 * hash_shift * MIN_MATCH >= hash_bits
50318 */
50319
50320 this.block_start = 0;
50321 /* Window position at the beginning of the current output block. Gets
50322 * negative when the window is moved backwards.
50323 */
50324
50325 this.match_length = 0; /* length of best match */
50326 this.prev_match = 0; /* previous match */
50327 this.match_available = 0; /* set if previous match exists */
50328 this.strstart = 0; /* start of string to insert */
50329 this.match_start = 0; /* start of matching string */
50330 this.lookahead = 0; /* number of valid bytes ahead in window */
50331
50332 this.prev_length = 0;
50333 /* Length of the best match at previous step. Matches not greater than this
50334 * are discarded. This is used in the lazy match evaluation.
50335 */
50336
50337 this.max_chain_length = 0;
50338 /* To speed up deflation, hash chains are never searched beyond this
50339 * length. A higher limit improves compression ratio but degrades the
50340 * speed.
50341 */
50342
50343 this.max_lazy_match = 0;
50344 /* Attempt to find a better match only when the current match is strictly
50345 * smaller than this value. This mechanism is used only for compression
50346 * levels >= 4.
50347 */
50348 // That's alias to max_lazy_match, don't use directly
50349 //this.max_insert_length = 0;
50350 /* Insert new strings in the hash table only if the match length is not
50351 * greater than this length. This saves time but degrades compression.
50352 * max_insert_length is used only for compression levels <= 3.
50353 */
50354
50355 this.level = 0; /* compression level (1..9) */
50356 this.strategy = 0; /* favor or force Huffman coding*/
50357
50358 this.good_match = 0;
50359 /* Use a faster search when the previous match is longer than this */
50360
50361 this.nice_match = 0; /* Stop searching when current match exceeds this */
50362
50363 /* used by trees.c: */
50364
50365 /* Didn't use ct_data typedef below to suppress compiler warning */
50366
50367 // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
50368 // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
50369 // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
50370
50371 // Use flat array of DOUBLE size, with interleaved fata,
50372 // because JS does not support effective
50373 this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2);
50374 this.dyn_dtree = new utils.Buf16((2 * D_CODES + 1) * 2);
50375 this.bl_tree = new utils.Buf16((2 * BL_CODES + 1) * 2);
50376 zero(this.dyn_ltree);
50377 zero(this.dyn_dtree);
50378 zero(this.bl_tree);
50379
50380 this.l_desc = null; /* desc. for literal tree */
50381 this.d_desc = null; /* desc. for distance tree */
50382 this.bl_desc = null; /* desc. for bit length tree */
50383
50384 //ush bl_count[MAX_BITS+1];
50385 this.bl_count = new utils.Buf16(MAX_BITS + 1);
50386 /* number of codes at each bit length for an optimal tree */
50387
50388 //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
50389 this.heap = new utils.Buf16(2 * L_CODES + 1); /* heap used to build the Huffman trees */
50390 zero(this.heap);
50391
50392 this.heap_len = 0; /* number of elements in the heap */
50393 this.heap_max = 0; /* element of largest frequency */
50394 /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
50395 * The same heap array is used to build all trees.
50396 */
50397
50398 this.depth = new utils.Buf16(2 * L_CODES + 1); //uch depth[2*L_CODES+1];
50399 zero(this.depth);
50400 /* Depth of each subtree used as tie breaker for trees of equal frequency
50401 */
50402
50403 this.l_buf = 0; /* buffer index for literals or lengths */
50404
50405 this.lit_bufsize = 0;
50406 /* Size of match buffer for literals/lengths. There are 4 reasons for
50407 * limiting lit_bufsize to 64K:
50408 * - frequencies can be kept in 16 bit counters
50409 * - if compression is not successful for the first block, all input
50410 * data is still in the window so we can still emit a stored block even
50411 * when input comes from standard input. (This can also be done for
50412 * all blocks if lit_bufsize is not greater than 32K.)
50413 * - if compression is not successful for a file smaller than 64K, we can
50414 * even emit a stored file instead of a stored block (saving 5 bytes).
50415 * This is applicable only for zip (not gzip or zlib).
50416 * - creating new Huffman trees less frequently may not provide fast
50417 * adaptation to changes in the input data statistics. (Take for
50418 * example a binary file with poorly compressible code followed by
50419 * a highly compressible string table.) Smaller buffer sizes give
50420 * fast adaptation but have of course the overhead of transmitting
50421 * trees more frequently.
50422 * - I can't count above 4
50423 */
50424
50425 this.last_lit = 0; /* running index in l_buf */
50426
50427 this.d_buf = 0;
50428 /* Buffer index for distances. To simplify the code, d_buf and l_buf have
50429 * the same number of elements. To use different lengths, an extra flag
50430 * array would be necessary.
50431 */
50432
50433 this.opt_len = 0; /* bit length of current block with optimal trees */
50434 this.static_len = 0; /* bit length of current block with static trees */
50435 this.matches = 0; /* number of string matches in current block */
50436 this.insert = 0; /* bytes at end of window left to insert */
50437
50438
50439 this.bi_buf = 0;
50440 /* Output buffer. bits are inserted starting at the bottom (least
50441 * significant bits).
50442 */
50443 this.bi_valid = 0;
50444 /* Number of valid bits in bi_buf. All bits above the last valid bit
50445 * are always zero.
50446 */
50447
50448 // Used for window memory init. We safely ignore it for JS. That makes
50449 // sense only for pointers and memory check tools.
50450 //this.high_water = 0;
50451 /* High water mark offset in window for initialized bytes -- bytes above
50452 * this are set to zero in order to avoid memory check warnings when
50453 * longest match routines access bytes past the input. This is then
50454 * updated to the new high water mark.
50455 */
50456}
50457
50458
50459function deflateResetKeep(strm) {
50460 var s;
50461
50462 if (!strm || !strm.state) {
50463 return err(strm, Z_STREAM_ERROR);
50464 }
50465
50466 strm.total_in = strm.total_out = 0;
50467 strm.data_type = Z_UNKNOWN;
50468
50469 s = strm.state;
50470 s.pending = 0;
50471 s.pending_out = 0;
50472
50473 if (s.wrap < 0) {
50474 s.wrap = -s.wrap;
50475 /* was made negative by deflate(..., Z_FINISH); */
50476 }
50477 s.status = (s.wrap ? INIT_STATE : BUSY_STATE);
50478 strm.adler = (s.wrap === 2) ?
50479 0 // crc32(0, Z_NULL, 0)
50480 :
50481 1; // adler32(0, Z_NULL, 0)
50482 s.last_flush = Z_NO_FLUSH;
50483 trees._tr_init(s);
50484 return Z_OK;
50485}
50486
50487
50488function deflateReset(strm) {
50489 var ret = deflateResetKeep(strm);
50490 if (ret === Z_OK) {
50491 lm_init(strm.state);
50492 }
50493 return ret;
50494}
50495
50496
50497function deflateSetHeader(strm, head) {
50498 if (!strm || !strm.state) { return Z_STREAM_ERROR; }
50499 if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; }
50500 strm.state.gzhead = head;
50501 return Z_OK;
50502}
50503
50504
50505function deflateInit2(strm, level, method, windowBits, memLevel, strategy) {
50506 if (!strm) { // === Z_NULL
50507 return Z_STREAM_ERROR;
50508 }
50509 var wrap = 1;
50510
50511 if (level === Z_DEFAULT_COMPRESSION) {
50512 level = 6;
50513 }
50514
50515 if (windowBits < 0) { /* suppress zlib wrapper */
50516 wrap = 0;
50517 windowBits = -windowBits;
50518 }
50519
50520 else if (windowBits > 15) {
50521 wrap = 2; /* write gzip wrapper instead */
50522 windowBits -= 16;
50523 }
50524
50525
50526 if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED ||
50527 windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
50528 strategy < 0 || strategy > Z_FIXED) {
50529 return err(strm, Z_STREAM_ERROR);
50530 }
50531
50532
50533 if (windowBits === 8) {
50534 windowBits = 9;
50535 }
50536 /* until 256-byte window bug fixed */
50537
50538 var s = new DeflateState();
50539
50540 strm.state = s;
50541 s.strm = strm;
50542
50543 s.wrap = wrap;
50544 s.gzhead = null;
50545 s.w_bits = windowBits;
50546 s.w_size = 1 << s.w_bits;
50547 s.w_mask = s.w_size - 1;
50548
50549 s.hash_bits = memLevel + 7;
50550 s.hash_size = 1 << s.hash_bits;
50551 s.hash_mask = s.hash_size - 1;
50552 s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH);
50553
50554 s.window = new utils.Buf8(s.w_size * 2);
50555 s.head = new utils.Buf16(s.hash_size);
50556 s.prev = new utils.Buf16(s.w_size);
50557
50558 // Don't need mem init magic for JS.
50559 //s.high_water = 0; /* nothing written to s->window yet */
50560
50561 s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
50562
50563 s.pending_buf_size = s.lit_bufsize * 4;
50564
50565 //overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2);
50566 //s->pending_buf = (uchf *) overlay;
50567 s.pending_buf = new utils.Buf8(s.pending_buf_size);
50568
50569 // It is offset from `s.pending_buf` (size is `s.lit_bufsize * 2`)
50570 //s->d_buf = overlay + s->lit_bufsize/sizeof(ush);
50571 s.d_buf = 1 * s.lit_bufsize;
50572
50573 //s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize;
50574 s.l_buf = (1 + 2) * s.lit_bufsize;
50575
50576 s.level = level;
50577 s.strategy = strategy;
50578 s.method = method;
50579
50580 return deflateReset(strm);
50581}
50582
50583function deflateInit(strm, level) {
50584 return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
50585}
50586
50587
50588function deflate(strm, flush) {
50589 var old_flush, s;
50590 var beg, val; // for gzip header write only
50591
50592 if (!strm || !strm.state ||
50593 flush > Z_BLOCK || flush < 0) {
50594 return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR;
50595 }
50596
50597 s = strm.state;
50598
50599 if (!strm.output ||
50600 (!strm.input && strm.avail_in !== 0) ||
50601 (s.status === FINISH_STATE && flush !== Z_FINISH)) {
50602 return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR);
50603 }
50604
50605 s.strm = strm; /* just in case */
50606 old_flush = s.last_flush;
50607 s.last_flush = flush;
50608
50609 /* Write the header */
50610 if (s.status === INIT_STATE) {
50611
50612 if (s.wrap === 2) { // GZIP header
50613 strm.adler = 0; //crc32(0L, Z_NULL, 0);
50614 put_byte(s, 31);
50615 put_byte(s, 139);
50616 put_byte(s, 8);
50617 if (!s.gzhead) { // s->gzhead == Z_NULL
50618 put_byte(s, 0);
50619 put_byte(s, 0);
50620 put_byte(s, 0);
50621 put_byte(s, 0);
50622 put_byte(s, 0);
50623 put_byte(s, s.level === 9 ? 2 :
50624 (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
50625 4 : 0));
50626 put_byte(s, OS_CODE);
50627 s.status = BUSY_STATE;
50628 }
50629 else {
50630 put_byte(s, (s.gzhead.text ? 1 : 0) +
50631 (s.gzhead.hcrc ? 2 : 0) +
50632 (!s.gzhead.extra ? 0 : 4) +
50633 (!s.gzhead.name ? 0 : 8) +
50634 (!s.gzhead.comment ? 0 : 16)
50635 );
50636 put_byte(s, s.gzhead.time & 0xff);
50637 put_byte(s, (s.gzhead.time >> 8) & 0xff);
50638 put_byte(s, (s.gzhead.time >> 16) & 0xff);
50639 put_byte(s, (s.gzhead.time >> 24) & 0xff);
50640 put_byte(s, s.level === 9 ? 2 :
50641 (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
50642 4 : 0));
50643 put_byte(s, s.gzhead.os & 0xff);
50644 if (s.gzhead.extra && s.gzhead.extra.length) {
50645 put_byte(s, s.gzhead.extra.length & 0xff);
50646 put_byte(s, (s.gzhead.extra.length >> 8) & 0xff);
50647 }
50648 if (s.gzhead.hcrc) {
50649 strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0);
50650 }
50651 s.gzindex = 0;
50652 s.status = EXTRA_STATE;
50653 }
50654 }
50655 else // DEFLATE header
50656 {
50657 var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8;
50658 var level_flags = -1;
50659
50660 if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {
50661 level_flags = 0;
50662 } else if (s.level < 6) {
50663 level_flags = 1;
50664 } else if (s.level === 6) {
50665 level_flags = 2;
50666 } else {
50667 level_flags = 3;
50668 }
50669 header |= (level_flags << 6);
50670 if (s.strstart !== 0) { header |= PRESET_DICT; }
50671 header += 31 - (header % 31);
50672
50673 s.status = BUSY_STATE;
50674 putShortMSB(s, header);
50675
50676 /* Save the adler32 of the preset dictionary: */
50677 if (s.strstart !== 0) {
50678 putShortMSB(s, strm.adler >>> 16);
50679 putShortMSB(s, strm.adler & 0xffff);
50680 }
50681 strm.adler = 1; // adler32(0L, Z_NULL, 0);
50682 }
50683 }
50684
50685//#ifdef GZIP
50686 if (s.status === EXTRA_STATE) {
50687 if (s.gzhead.extra/* != Z_NULL*/) {
50688 beg = s.pending; /* start of bytes to update crc */
50689
50690 while (s.gzindex < (s.gzhead.extra.length & 0xffff)) {
50691 if (s.pending === s.pending_buf_size) {
50692 if (s.gzhead.hcrc && s.pending > beg) {
50693 strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
50694 }
50695 flush_pending(strm);
50696 beg = s.pending;
50697 if (s.pending === s.pending_buf_size) {
50698 break;
50699 }
50700 }
50701 put_byte(s, s.gzhead.extra[s.gzindex] & 0xff);
50702 s.gzindex++;
50703 }
50704 if (s.gzhead.hcrc && s.pending > beg) {
50705 strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
50706 }
50707 if (s.gzindex === s.gzhead.extra.length) {
50708 s.gzindex = 0;
50709 s.status = NAME_STATE;
50710 }
50711 }
50712 else {
50713 s.status = NAME_STATE;
50714 }
50715 }
50716 if (s.status === NAME_STATE) {
50717 if (s.gzhead.name/* != Z_NULL*/) {
50718 beg = s.pending; /* start of bytes to update crc */
50719 //int val;
50720
50721 do {
50722 if (s.pending === s.pending_buf_size) {
50723 if (s.gzhead.hcrc && s.pending > beg) {
50724 strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
50725 }
50726 flush_pending(strm);
50727 beg = s.pending;
50728 if (s.pending === s.pending_buf_size) {
50729 val = 1;
50730 break;
50731 }
50732 }
50733 // JS specific: little magic to add zero terminator to end of string
50734 if (s.gzindex < s.gzhead.name.length) {
50735 val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;
50736 } else {
50737 val = 0;
50738 }
50739 put_byte(s, val);
50740 } while (val !== 0);
50741
50742 if (s.gzhead.hcrc && s.pending > beg) {
50743 strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
50744 }
50745 if (val === 0) {
50746 s.gzindex = 0;
50747 s.status = COMMENT_STATE;
50748 }
50749 }
50750 else {
50751 s.status = COMMENT_STATE;
50752 }
50753 }
50754 if (s.status === COMMENT_STATE) {
50755 if (s.gzhead.comment/* != Z_NULL*/) {
50756 beg = s.pending; /* start of bytes to update crc */
50757 //int val;
50758
50759 do {
50760 if (s.pending === s.pending_buf_size) {
50761 if (s.gzhead.hcrc && s.pending > beg) {
50762 strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
50763 }
50764 flush_pending(strm);
50765 beg = s.pending;
50766 if (s.pending === s.pending_buf_size) {
50767 val = 1;
50768 break;
50769 }
50770 }
50771 // JS specific: little magic to add zero terminator to end of string
50772 if (s.gzindex < s.gzhead.comment.length) {
50773 val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;
50774 } else {
50775 val = 0;
50776 }
50777 put_byte(s, val);
50778 } while (val !== 0);
50779
50780 if (s.gzhead.hcrc && s.pending > beg) {
50781 strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
50782 }
50783 if (val === 0) {
50784 s.status = HCRC_STATE;
50785 }
50786 }
50787 else {
50788 s.status = HCRC_STATE;
50789 }
50790 }
50791 if (s.status === HCRC_STATE) {
50792 if (s.gzhead.hcrc) {
50793 if (s.pending + 2 > s.pending_buf_size) {
50794 flush_pending(strm);
50795 }
50796 if (s.pending + 2 <= s.pending_buf_size) {
50797 put_byte(s, strm.adler & 0xff);
50798 put_byte(s, (strm.adler >> 8) & 0xff);
50799 strm.adler = 0; //crc32(0L, Z_NULL, 0);
50800 s.status = BUSY_STATE;
50801 }
50802 }
50803 else {
50804 s.status = BUSY_STATE;
50805 }
50806 }
50807//#endif
50808
50809 /* Flush as much pending output as possible */
50810 if (s.pending !== 0) {
50811 flush_pending(strm);
50812 if (strm.avail_out === 0) {
50813 /* Since avail_out is 0, deflate will be called again with
50814 * more output space, but possibly with both pending and
50815 * avail_in equal to zero. There won't be anything to do,
50816 * but this is not an error situation so make sure we
50817 * return OK instead of BUF_ERROR at next call of deflate:
50818 */
50819 s.last_flush = -1;
50820 return Z_OK;
50821 }
50822
50823 /* Make sure there is something to do and avoid duplicate consecutive
50824 * flushes. For repeated and useless calls with Z_FINISH, we keep
50825 * returning Z_STREAM_END instead of Z_BUF_ERROR.
50826 */
50827 } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&
50828 flush !== Z_FINISH) {
50829 return err(strm, Z_BUF_ERROR);
50830 }
50831
50832 /* User must not provide more input after the first FINISH: */
50833 if (s.status === FINISH_STATE && strm.avail_in !== 0) {
50834 return err(strm, Z_BUF_ERROR);
50835 }
50836
50837 /* Start a new block or continue the current one.
50838 */
50839 if (strm.avail_in !== 0 || s.lookahead !== 0 ||
50840 (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) {
50841 var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) :
50842 (s.strategy === Z_RLE ? deflate_rle(s, flush) :
50843 configuration_table[s.level].func(s, flush));
50844
50845 if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {
50846 s.status = FINISH_STATE;
50847 }
50848 if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {
50849 if (strm.avail_out === 0) {
50850 s.last_flush = -1;
50851 /* avoid BUF_ERROR next call, see above */
50852 }
50853 return Z_OK;
50854 /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
50855 * of deflate should use the same flush parameter to make sure
50856 * that the flush is complete. So we don't have to output an
50857 * empty block here, this will be done at next call. This also
50858 * ensures that for a very small output buffer, we emit at most
50859 * one empty block.
50860 */
50861 }
50862 if (bstate === BS_BLOCK_DONE) {
50863 if (flush === Z_PARTIAL_FLUSH) {
50864 trees._tr_align(s);
50865 }
50866 else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */
50867
50868 trees._tr_stored_block(s, 0, 0, false);
50869 /* For a full flush, this empty block will be recognized
50870 * as a special marker by inflate_sync().
50871 */
50872 if (flush === Z_FULL_FLUSH) {
50873 /*** CLEAR_HASH(s); ***/ /* forget history */
50874 zero(s.head); // Fill with NIL (= 0);
50875
50876 if (s.lookahead === 0) {
50877 s.strstart = 0;
50878 s.block_start = 0;
50879 s.insert = 0;
50880 }
50881 }
50882 }
50883 flush_pending(strm);
50884 if (strm.avail_out === 0) {
50885 s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */
50886 return Z_OK;
50887 }
50888 }
50889 }
50890 //Assert(strm->avail_out > 0, "bug2");
50891 //if (strm.avail_out <= 0) { throw new Error("bug2");}
50892
50893 if (flush !== Z_FINISH) { return Z_OK; }
50894 if (s.wrap <= 0) { return Z_STREAM_END; }
50895
50896 /* Write the trailer */
50897 if (s.wrap === 2) {
50898 put_byte(s, strm.adler & 0xff);
50899 put_byte(s, (strm.adler >> 8) & 0xff);
50900 put_byte(s, (strm.adler >> 16) & 0xff);
50901 put_byte(s, (strm.adler >> 24) & 0xff);
50902 put_byte(s, strm.total_in & 0xff);
50903 put_byte(s, (strm.total_in >> 8) & 0xff);
50904 put_byte(s, (strm.total_in >> 16) & 0xff);
50905 put_byte(s, (strm.total_in >> 24) & 0xff);
50906 }
50907 else
50908 {
50909 putShortMSB(s, strm.adler >>> 16);
50910 putShortMSB(s, strm.adler & 0xffff);
50911 }
50912
50913 flush_pending(strm);
50914 /* If avail_out is zero, the application will call deflate again
50915 * to flush the rest.
50916 */
50917 if (s.wrap > 0) { s.wrap = -s.wrap; }
50918 /* write the trailer only once! */
50919 return s.pending !== 0 ? Z_OK : Z_STREAM_END;
50920}
50921
50922function deflateEnd(strm) {
50923 var status;
50924
50925 if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
50926 return Z_STREAM_ERROR;
50927 }
50928
50929 status = strm.state.status;
50930 if (status !== INIT_STATE &&
50931 status !== EXTRA_STATE &&
50932 status !== NAME_STATE &&
50933 status !== COMMENT_STATE &&
50934 status !== HCRC_STATE &&
50935 status !== BUSY_STATE &&
50936 status !== FINISH_STATE
50937 ) {
50938 return err(strm, Z_STREAM_ERROR);
50939 }
50940
50941 strm.state = null;
50942
50943 return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK;
50944}
50945
50946
50947/* =========================================================================
50948 * Initializes the compression dictionary from the given byte
50949 * sequence without producing any compressed output.
50950 */
50951function deflateSetDictionary(strm, dictionary) {
50952 var dictLength = dictionary.length;
50953
50954 var s;
50955 var str, n;
50956 var wrap;
50957 var avail;
50958 var next;
50959 var input;
50960 var tmpDict;
50961
50962 if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
50963 return Z_STREAM_ERROR;
50964 }
50965
50966 s = strm.state;
50967 wrap = s.wrap;
50968
50969 if (wrap === 2 || (wrap === 1 && s.status !== INIT_STATE) || s.lookahead) {
50970 return Z_STREAM_ERROR;
50971 }
50972
50973 /* when using zlib wrappers, compute Adler-32 for provided dictionary */
50974 if (wrap === 1) {
50975 /* adler32(strm->adler, dictionary, dictLength); */
50976 strm.adler = adler32(strm.adler, dictionary, dictLength, 0);
50977 }
50978
50979 s.wrap = 0; /* avoid computing Adler-32 in read_buf */
50980
50981 /* if dictionary would fill window, just replace the history */
50982 if (dictLength >= s.w_size) {
50983 if (wrap === 0) { /* already empty otherwise */
50984 /*** CLEAR_HASH(s); ***/
50985 zero(s.head); // Fill with NIL (= 0);
50986 s.strstart = 0;
50987 s.block_start = 0;
50988 s.insert = 0;
50989 }
50990 /* use the tail */
50991 // dictionary = dictionary.slice(dictLength - s.w_size);
50992 tmpDict = new utils.Buf8(s.w_size);
50993 utils.arraySet(tmpDict, dictionary, dictLength - s.w_size, s.w_size, 0);
50994 dictionary = tmpDict;
50995 dictLength = s.w_size;
50996 }
50997 /* insert dictionary into window and hash */
50998 avail = strm.avail_in;
50999 next = strm.next_in;
51000 input = strm.input;
51001 strm.avail_in = dictLength;
51002 strm.next_in = 0;
51003 strm.input = dictionary;
51004 fill_window(s);
51005 while (s.lookahead >= MIN_MATCH) {
51006 str = s.strstart;
51007 n = s.lookahead - (MIN_MATCH - 1);
51008 do {
51009 /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
51010 s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH - 1]) & s.hash_mask;
51011
51012 s.prev[str & s.w_mask] = s.head[s.ins_h];
51013
51014 s.head[s.ins_h] = str;
51015 str++;
51016 } while (--n);
51017 s.strstart = str;
51018 s.lookahead = MIN_MATCH - 1;
51019 fill_window(s);
51020 }
51021 s.strstart += s.lookahead;
51022 s.block_start = s.strstart;
51023 s.insert = s.lookahead;
51024 s.lookahead = 0;
51025 s.match_length = s.prev_length = MIN_MATCH - 1;
51026 s.match_available = 0;
51027 strm.next_in = next;
51028 strm.input = input;
51029 strm.avail_in = avail;
51030 s.wrap = wrap;
51031 return Z_OK;
51032}
51033
51034
51035exports.deflateInit = deflateInit;
51036exports.deflateInit2 = deflateInit2;
51037exports.deflateReset = deflateReset;
51038exports.deflateResetKeep = deflateResetKeep;
51039exports.deflateSetHeader = deflateSetHeader;
51040exports.deflate = deflate;
51041exports.deflateEnd = deflateEnd;
51042exports.deflateSetDictionary = deflateSetDictionary;
51043exports.deflateInfo = 'pako deflate (from Nodeca project)';
51044
51045/* Not implemented
51046exports.deflateBound = deflateBound;
51047exports.deflateCopy = deflateCopy;
51048exports.deflateParams = deflateParams;
51049exports.deflatePending = deflatePending;
51050exports.deflatePrime = deflatePrime;
51051exports.deflateTune = deflateTune;
51052*/
51053
51054},{"../utils/common":241,"./adler32":242,"./crc32":244,"./messages":249,"./trees":250}],246:[function(require,module,exports){
51055'use strict';
51056
51057// (C) 1995-2013 Jean-loup Gailly and Mark Adler
51058// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
51059//
51060// This software is provided 'as-is', without any express or implied
51061// warranty. In no event will the authors be held liable for any damages
51062// arising from the use of this software.
51063//
51064// Permission is granted to anyone to use this software for any purpose,
51065// including commercial applications, and to alter it and redistribute it
51066// freely, subject to the following restrictions:
51067//
51068// 1. The origin of this software must not be misrepresented; you must not
51069// claim that you wrote the original software. If you use this software
51070// in a product, an acknowledgment in the product documentation would be
51071// appreciated but is not required.
51072// 2. Altered source versions must be plainly marked as such, and must not be
51073// misrepresented as being the original software.
51074// 3. This notice may not be removed or altered from any source distribution.
51075
51076// See state defs from inflate.js
51077var BAD = 30; /* got a data error -- remain here until reset */
51078var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
51079
51080/*
51081 Decode literal, length, and distance codes and write out the resulting
51082 literal and match bytes until either not enough input or output is
51083 available, an end-of-block is encountered, or a data error is encountered.
51084 When large enough input and output buffers are supplied to inflate(), for
51085 example, a 16K input buffer and a 64K output buffer, more than 95% of the
51086 inflate execution time is spent in this routine.
51087
51088 Entry assumptions:
51089
51090 state.mode === LEN
51091 strm.avail_in >= 6
51092 strm.avail_out >= 258
51093 start >= strm.avail_out
51094 state.bits < 8
51095
51096 On return, state.mode is one of:
51097
51098 LEN -- ran out of enough output space or enough available input
51099 TYPE -- reached end of block code, inflate() to interpret next block
51100 BAD -- error in block data
51101
51102 Notes:
51103
51104 - The maximum input bits used by a length/distance pair is 15 bits for the
51105 length code, 5 bits for the length extra, 15 bits for the distance code,
51106 and 13 bits for the distance extra. This totals 48 bits, or six bytes.
51107 Therefore if strm.avail_in >= 6, then there is enough input to avoid
51108 checking for available input while decoding.
51109
51110 - The maximum bytes that a single length/distance pair can output is 258
51111 bytes, which is the maximum length that can be coded. inflate_fast()
51112 requires strm.avail_out >= 258 for each loop to avoid checking for
51113 output space.
51114 */
51115module.exports = function inflate_fast(strm, start) {
51116 var state;
51117 var _in; /* local strm.input */
51118 var last; /* have enough input while in < last */
51119 var _out; /* local strm.output */
51120 var beg; /* inflate()'s initial strm.output */
51121 var end; /* while out < end, enough space available */
51122//#ifdef INFLATE_STRICT
51123 var dmax; /* maximum distance from zlib header */
51124//#endif
51125 var wsize; /* window size or zero if not using window */
51126 var whave; /* valid bytes in the window */
51127 var wnext; /* window write index */
51128 // Use `s_window` instead `window`, avoid conflict with instrumentation tools
51129 var s_window; /* allocated sliding window, if wsize != 0 */
51130 var hold; /* local strm.hold */
51131 var bits; /* local strm.bits */
51132 var lcode; /* local strm.lencode */
51133 var dcode; /* local strm.distcode */
51134 var lmask; /* mask for first level of length codes */
51135 var dmask; /* mask for first level of distance codes */
51136 var here; /* retrieved table entry */
51137 var op; /* code bits, operation, extra bits, or */
51138 /* window position, window bytes to copy */
51139 var len; /* match length, unused bytes */
51140 var dist; /* match distance */
51141 var from; /* where to copy match from */
51142 var from_source;
51143
51144
51145 var input, output; // JS specific, because we have no pointers
51146
51147 /* copy state to local variables */
51148 state = strm.state;
51149 //here = state.here;
51150 _in = strm.next_in;
51151 input = strm.input;
51152 last = _in + (strm.avail_in - 5);
51153 _out = strm.next_out;
51154 output = strm.output;
51155 beg = _out - (start - strm.avail_out);
51156 end = _out + (strm.avail_out - 257);
51157//#ifdef INFLATE_STRICT
51158 dmax = state.dmax;
51159//#endif
51160 wsize = state.wsize;
51161 whave = state.whave;
51162 wnext = state.wnext;
51163 s_window = state.window;
51164 hold = state.hold;
51165 bits = state.bits;
51166 lcode = state.lencode;
51167 dcode = state.distcode;
51168 lmask = (1 << state.lenbits) - 1;
51169 dmask = (1 << state.distbits) - 1;
51170
51171
51172 /* decode literals and length/distances until end-of-block or not enough
51173 input data or output space */
51174
51175 top:
51176 do {
51177 if (bits < 15) {
51178 hold += input[_in++] << bits;
51179 bits += 8;
51180 hold += input[_in++] << bits;
51181 bits += 8;
51182 }
51183
51184 here = lcode[hold & lmask];
51185
51186 dolen:
51187 for (;;) { // Goto emulation
51188 op = here >>> 24/*here.bits*/;
51189 hold >>>= op;
51190 bits -= op;
51191 op = (here >>> 16) & 0xff/*here.op*/;
51192 if (op === 0) { /* literal */
51193 //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
51194 // "inflate: literal '%c'\n" :
51195 // "inflate: literal 0x%02x\n", here.val));
51196 output[_out++] = here & 0xffff/*here.val*/;
51197 }
51198 else if (op & 16) { /* length base */
51199 len = here & 0xffff/*here.val*/;
51200 op &= 15; /* number of extra bits */
51201 if (op) {
51202 if (bits < op) {
51203 hold += input[_in++] << bits;
51204 bits += 8;
51205 }
51206 len += hold & ((1 << op) - 1);
51207 hold >>>= op;
51208 bits -= op;
51209 }
51210 //Tracevv((stderr, "inflate: length %u\n", len));
51211 if (bits < 15) {
51212 hold += input[_in++] << bits;
51213 bits += 8;
51214 hold += input[_in++] << bits;
51215 bits += 8;
51216 }
51217 here = dcode[hold & dmask];
51218
51219 dodist:
51220 for (;;) { // goto emulation
51221 op = here >>> 24/*here.bits*/;
51222 hold >>>= op;
51223 bits -= op;
51224 op = (here >>> 16) & 0xff/*here.op*/;
51225
51226 if (op & 16) { /* distance base */
51227 dist = here & 0xffff/*here.val*/;
51228 op &= 15; /* number of extra bits */
51229 if (bits < op) {
51230 hold += input[_in++] << bits;
51231 bits += 8;
51232 if (bits < op) {
51233 hold += input[_in++] << bits;
51234 bits += 8;
51235 }
51236 }
51237 dist += hold & ((1 << op) - 1);
51238//#ifdef INFLATE_STRICT
51239 if (dist > dmax) {
51240 strm.msg = 'invalid distance too far back';
51241 state.mode = BAD;
51242 break top;
51243 }
51244//#endif
51245 hold >>>= op;
51246 bits -= op;
51247 //Tracevv((stderr, "inflate: distance %u\n", dist));
51248 op = _out - beg; /* max distance in output */
51249 if (dist > op) { /* see if copy from window */
51250 op = dist - op; /* distance back in window */
51251 if (op > whave) {
51252 if (state.sane) {
51253 strm.msg = 'invalid distance too far back';
51254 state.mode = BAD;
51255 break top;
51256 }
51257
51258// (!) This block is disabled in zlib defaults,
51259// don't enable it for binary compatibility
51260//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
51261// if (len <= op - whave) {
51262// do {
51263// output[_out++] = 0;
51264// } while (--len);
51265// continue top;
51266// }
51267// len -= op - whave;
51268// do {
51269// output[_out++] = 0;
51270// } while (--op > whave);
51271// if (op === 0) {
51272// from = _out - dist;
51273// do {
51274// output[_out++] = output[from++];
51275// } while (--len);
51276// continue top;
51277// }
51278//#endif
51279 }
51280 from = 0; // window index
51281 from_source = s_window;
51282 if (wnext === 0) { /* very common case */
51283 from += wsize - op;
51284 if (op < len) { /* some from window */
51285 len -= op;
51286 do {
51287 output[_out++] = s_window[from++];
51288 } while (--op);
51289 from = _out - dist; /* rest from output */
51290 from_source = output;
51291 }
51292 }
51293 else if (wnext < op) { /* wrap around window */
51294 from += wsize + wnext - op;
51295 op -= wnext;
51296 if (op < len) { /* some from end of window */
51297 len -= op;
51298 do {
51299 output[_out++] = s_window[from++];
51300 } while (--op);
51301 from = 0;
51302 if (wnext < len) { /* some from start of window */
51303 op = wnext;
51304 len -= op;
51305 do {
51306 output[_out++] = s_window[from++];
51307 } while (--op);
51308 from = _out - dist; /* rest from output */
51309 from_source = output;
51310 }
51311 }
51312 }
51313 else { /* contiguous in window */
51314 from += wnext - op;
51315 if (op < len) { /* some from window */
51316 len -= op;
51317 do {
51318 output[_out++] = s_window[from++];
51319 } while (--op);
51320 from = _out - dist; /* rest from output */
51321 from_source = output;
51322 }
51323 }
51324 while (len > 2) {
51325 output[_out++] = from_source[from++];
51326 output[_out++] = from_source[from++];
51327 output[_out++] = from_source[from++];
51328 len -= 3;
51329 }
51330 if (len) {
51331 output[_out++] = from_source[from++];
51332 if (len > 1) {
51333 output[_out++] = from_source[from++];
51334 }
51335 }
51336 }
51337 else {
51338 from = _out - dist; /* copy direct from output */
51339 do { /* minimum length is three */
51340 output[_out++] = output[from++];
51341 output[_out++] = output[from++];
51342 output[_out++] = output[from++];
51343 len -= 3;
51344 } while (len > 2);
51345 if (len) {
51346 output[_out++] = output[from++];
51347 if (len > 1) {
51348 output[_out++] = output[from++];
51349 }
51350 }
51351 }
51352 }
51353 else if ((op & 64) === 0) { /* 2nd level distance code */
51354 here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
51355 continue dodist;
51356 }
51357 else {
51358 strm.msg = 'invalid distance code';
51359 state.mode = BAD;
51360 break top;
51361 }
51362
51363 break; // need to emulate goto via "continue"
51364 }
51365 }
51366 else if ((op & 64) === 0) { /* 2nd level length code */
51367 here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
51368 continue dolen;
51369 }
51370 else if (op & 32) { /* end-of-block */
51371 //Tracevv((stderr, "inflate: end of block\n"));
51372 state.mode = TYPE;
51373 break top;
51374 }
51375 else {
51376 strm.msg = 'invalid literal/length code';
51377 state.mode = BAD;
51378 break top;
51379 }
51380
51381 break; // need to emulate goto via "continue"
51382 }
51383 } while (_in < last && _out < end);
51384
51385 /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
51386 len = bits >> 3;
51387 _in -= len;
51388 bits -= len << 3;
51389 hold &= (1 << bits) - 1;
51390
51391 /* update state and return */
51392 strm.next_in = _in;
51393 strm.next_out = _out;
51394 strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));
51395 strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));
51396 state.hold = hold;
51397 state.bits = bits;
51398 return;
51399};
51400
51401},{}],247:[function(require,module,exports){
51402'use strict';
51403
51404// (C) 1995-2013 Jean-loup Gailly and Mark Adler
51405// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
51406//
51407// This software is provided 'as-is', without any express or implied
51408// warranty. In no event will the authors be held liable for any damages
51409// arising from the use of this software.
51410//
51411// Permission is granted to anyone to use this software for any purpose,
51412// including commercial applications, and to alter it and redistribute it
51413// freely, subject to the following restrictions:
51414//
51415// 1. The origin of this software must not be misrepresented; you must not
51416// claim that you wrote the original software. If you use this software
51417// in a product, an acknowledgment in the product documentation would be
51418// appreciated but is not required.
51419// 2. Altered source versions must be plainly marked as such, and must not be
51420// misrepresented as being the original software.
51421// 3. This notice may not be removed or altered from any source distribution.
51422
51423var utils = require('../utils/common');
51424var adler32 = require('./adler32');
51425var crc32 = require('./crc32');
51426var inflate_fast = require('./inffast');
51427var inflate_table = require('./inftrees');
51428
51429var CODES = 0;
51430var LENS = 1;
51431var DISTS = 2;
51432
51433/* Public constants ==========================================================*/
51434/* ===========================================================================*/
51435
51436
51437/* Allowed flush values; see deflate() and inflate() below for details */
51438//var Z_NO_FLUSH = 0;
51439//var Z_PARTIAL_FLUSH = 1;
51440//var Z_SYNC_FLUSH = 2;
51441//var Z_FULL_FLUSH = 3;
51442var Z_FINISH = 4;
51443var Z_BLOCK = 5;
51444var Z_TREES = 6;
51445
51446
51447/* Return codes for the compression/decompression functions. Negative values
51448 * are errors, positive values are used for special but normal events.
51449 */
51450var Z_OK = 0;
51451var Z_STREAM_END = 1;
51452var Z_NEED_DICT = 2;
51453//var Z_ERRNO = -1;
51454var Z_STREAM_ERROR = -2;
51455var Z_DATA_ERROR = -3;
51456var Z_MEM_ERROR = -4;
51457var Z_BUF_ERROR = -5;
51458//var Z_VERSION_ERROR = -6;
51459
51460/* The deflate compression method */
51461var Z_DEFLATED = 8;
51462
51463
51464/* STATES ====================================================================*/
51465/* ===========================================================================*/
51466
51467
51468var HEAD = 1; /* i: waiting for magic header */
51469var FLAGS = 2; /* i: waiting for method and flags (gzip) */
51470var TIME = 3; /* i: waiting for modification time (gzip) */
51471var OS = 4; /* i: waiting for extra flags and operating system (gzip) */
51472var EXLEN = 5; /* i: waiting for extra length (gzip) */
51473var EXTRA = 6; /* i: waiting for extra bytes (gzip) */
51474var NAME = 7; /* i: waiting for end of file name (gzip) */
51475var COMMENT = 8; /* i: waiting for end of comment (gzip) */
51476var HCRC = 9; /* i: waiting for header crc (gzip) */
51477var DICTID = 10; /* i: waiting for dictionary check value */
51478var DICT = 11; /* waiting for inflateSetDictionary() call */
51479var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
51480var TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */
51481var STORED = 14; /* i: waiting for stored size (length and complement) */
51482var COPY_ = 15; /* i/o: same as COPY below, but only first time in */
51483var COPY = 16; /* i/o: waiting for input or output to copy stored block */
51484var TABLE = 17; /* i: waiting for dynamic block table lengths */
51485var LENLENS = 18; /* i: waiting for code length code lengths */
51486var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */
51487var LEN_ = 20; /* i: same as LEN below, but only first time in */
51488var LEN = 21; /* i: waiting for length/lit/eob code */
51489var LENEXT = 22; /* i: waiting for length extra bits */
51490var DIST = 23; /* i: waiting for distance code */
51491var DISTEXT = 24; /* i: waiting for distance extra bits */
51492var MATCH = 25; /* o: waiting for output space to copy string */
51493var LIT = 26; /* o: waiting for output space to write literal */
51494var CHECK = 27; /* i: waiting for 32-bit check value */
51495var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */
51496var DONE = 29; /* finished check, done -- remain here until reset */
51497var BAD = 30; /* got a data error -- remain here until reset */
51498var MEM = 31; /* got an inflate() memory error -- remain here until reset */
51499var SYNC = 32; /* looking for synchronization bytes to restart inflate() */
51500
51501/* ===========================================================================*/
51502
51503
51504
51505var ENOUGH_LENS = 852;
51506var ENOUGH_DISTS = 592;
51507//var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
51508
51509var MAX_WBITS = 15;
51510/* 32K LZ77 window */
51511var DEF_WBITS = MAX_WBITS;
51512
51513
51514function zswap32(q) {
51515 return (((q >>> 24) & 0xff) +
51516 ((q >>> 8) & 0xff00) +
51517 ((q & 0xff00) << 8) +
51518 ((q & 0xff) << 24));
51519}
51520
51521
51522function InflateState() {
51523 this.mode = 0; /* current inflate mode */
51524 this.last = false; /* true if processing last block */
51525 this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
51526 this.havedict = false; /* true if dictionary provided */
51527 this.flags = 0; /* gzip header method and flags (0 if zlib) */
51528 this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */
51529 this.check = 0; /* protected copy of check value */
51530 this.total = 0; /* protected copy of output count */
51531 // TODO: may be {}
51532 this.head = null; /* where to save gzip header information */
51533
51534 /* sliding window */
51535 this.wbits = 0; /* log base 2 of requested window size */
51536 this.wsize = 0; /* window size or zero if not using window */
51537 this.whave = 0; /* valid bytes in the window */
51538 this.wnext = 0; /* window write index */
51539 this.window = null; /* allocated sliding window, if needed */
51540
51541 /* bit accumulator */
51542 this.hold = 0; /* input bit accumulator */
51543 this.bits = 0; /* number of bits in "in" */
51544
51545 /* for string and stored block copying */
51546 this.length = 0; /* literal or length of data to copy */
51547 this.offset = 0; /* distance back to copy string from */
51548
51549 /* for table and code decoding */
51550 this.extra = 0; /* extra bits needed */
51551
51552 /* fixed and dynamic code tables */
51553 this.lencode = null; /* starting table for length/literal codes */
51554 this.distcode = null; /* starting table for distance codes */
51555 this.lenbits = 0; /* index bits for lencode */
51556 this.distbits = 0; /* index bits for distcode */
51557
51558 /* dynamic table building */
51559 this.ncode = 0; /* number of code length code lengths */
51560 this.nlen = 0; /* number of length code lengths */
51561 this.ndist = 0; /* number of distance code lengths */
51562 this.have = 0; /* number of code lengths in lens[] */
51563 this.next = null; /* next available space in codes[] */
51564
51565 this.lens = new utils.Buf16(320); /* temporary storage for code lengths */
51566 this.work = new utils.Buf16(288); /* work area for code table building */
51567
51568 /*
51569 because we don't have pointers in js, we use lencode and distcode directly
51570 as buffers so we don't need codes
51571 */
51572 //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */
51573 this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */
51574 this.distdyn = null; /* dynamic table for distance codes (JS specific) */
51575 this.sane = 0; /* if false, allow invalid distance too far */
51576 this.back = 0; /* bits back of last unprocessed length/lit */
51577 this.was = 0; /* initial length of match */
51578}
51579
51580function inflateResetKeep(strm) {
51581 var state;
51582
51583 if (!strm || !strm.state) { return Z_STREAM_ERROR; }
51584 state = strm.state;
51585 strm.total_in = strm.total_out = state.total = 0;
51586 strm.msg = ''; /*Z_NULL*/
51587 if (state.wrap) { /* to support ill-conceived Java test suite */
51588 strm.adler = state.wrap & 1;
51589 }
51590 state.mode = HEAD;
51591 state.last = 0;
51592 state.havedict = 0;
51593 state.dmax = 32768;
51594 state.head = null/*Z_NULL*/;
51595 state.hold = 0;
51596 state.bits = 0;
51597 //state.lencode = state.distcode = state.next = state.codes;
51598 state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS);
51599 state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS);
51600
51601 state.sane = 1;
51602 state.back = -1;
51603 //Tracev((stderr, "inflate: reset\n"));
51604 return Z_OK;
51605}
51606
51607function inflateReset(strm) {
51608 var state;
51609
51610 if (!strm || !strm.state) { return Z_STREAM_ERROR; }
51611 state = strm.state;
51612 state.wsize = 0;
51613 state.whave = 0;
51614 state.wnext = 0;
51615 return inflateResetKeep(strm);
51616
51617}
51618
51619function inflateReset2(strm, windowBits) {
51620 var wrap;
51621 var state;
51622
51623 /* get the state */
51624 if (!strm || !strm.state) { return Z_STREAM_ERROR; }
51625 state = strm.state;
51626
51627 /* extract wrap request from windowBits parameter */
51628 if (windowBits < 0) {
51629 wrap = 0;
51630 windowBits = -windowBits;
51631 }
51632 else {
51633 wrap = (windowBits >> 4) + 1;
51634 if (windowBits < 48) {
51635 windowBits &= 15;
51636 }
51637 }
51638
51639 /* set number of window bits, free window if different */
51640 if (windowBits && (windowBits < 8 || windowBits > 15)) {
51641 return Z_STREAM_ERROR;
51642 }
51643 if (state.window !== null && state.wbits !== windowBits) {
51644 state.window = null;
51645 }
51646
51647 /* update state and reset the rest of it */
51648 state.wrap = wrap;
51649 state.wbits = windowBits;
51650 return inflateReset(strm);
51651}
51652
51653function inflateInit2(strm, windowBits) {
51654 var ret;
51655 var state;
51656
51657 if (!strm) { return Z_STREAM_ERROR; }
51658 //strm.msg = Z_NULL; /* in case we return an error */
51659
51660 state = new InflateState();
51661
51662 //if (state === Z_NULL) return Z_MEM_ERROR;
51663 //Tracev((stderr, "inflate: allocated\n"));
51664 strm.state = state;
51665 state.window = null/*Z_NULL*/;
51666 ret = inflateReset2(strm, windowBits);
51667 if (ret !== Z_OK) {
51668 strm.state = null/*Z_NULL*/;
51669 }
51670 return ret;
51671}
51672
51673function inflateInit(strm) {
51674 return inflateInit2(strm, DEF_WBITS);
51675}
51676
51677
51678/*
51679 Return state with length and distance decoding tables and index sizes set to
51680 fixed code decoding. Normally this returns fixed tables from inffixed.h.
51681 If BUILDFIXED is defined, then instead this routine builds the tables the
51682 first time it's called, and returns those tables the first time and
51683 thereafter. This reduces the size of the code by about 2K bytes, in
51684 exchange for a little execution time. However, BUILDFIXED should not be
51685 used for threaded applications, since the rewriting of the tables and virgin
51686 may not be thread-safe.
51687 */
51688var virgin = true;
51689
51690var lenfix, distfix; // We have no pointers in JS, so keep tables separate
51691
51692function fixedtables(state) {
51693 /* build fixed huffman tables if first call (may not be thread safe) */
51694 if (virgin) {
51695 var sym;
51696
51697 lenfix = new utils.Buf32(512);
51698 distfix = new utils.Buf32(32);
51699
51700 /* literal/length table */
51701 sym = 0;
51702 while (sym < 144) { state.lens[sym++] = 8; }
51703 while (sym < 256) { state.lens[sym++] = 9; }
51704 while (sym < 280) { state.lens[sym++] = 7; }
51705 while (sym < 288) { state.lens[sym++] = 8; }
51706
51707 inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, { bits: 9 });
51708
51709 /* distance table */
51710 sym = 0;
51711 while (sym < 32) { state.lens[sym++] = 5; }
51712
51713 inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, { bits: 5 });
51714
51715 /* do this just once */
51716 virgin = false;
51717 }
51718
51719 state.lencode = lenfix;
51720 state.lenbits = 9;
51721 state.distcode = distfix;
51722 state.distbits = 5;
51723}
51724
51725
51726/*
51727 Update the window with the last wsize (normally 32K) bytes written before
51728 returning. If window does not exist yet, create it. This is only called
51729 when a window is already in use, or when output has been written during this
51730 inflate call, but the end of the deflate stream has not been reached yet.
51731 It is also called to create a window for dictionary data when a dictionary
51732 is loaded.
51733
51734 Providing output buffers larger than 32K to inflate() should provide a speed
51735 advantage, since only the last 32K of output is copied to the sliding window
51736 upon return from inflate(), and since all distances after the first 32K of
51737 output will fall in the output data, making match copies simpler and faster.
51738 The advantage may be dependent on the size of the processor's data caches.
51739 */
51740function updatewindow(strm, src, end, copy) {
51741 var dist;
51742 var state = strm.state;
51743
51744 /* if it hasn't been done already, allocate space for the window */
51745 if (state.window === null) {
51746 state.wsize = 1 << state.wbits;
51747 state.wnext = 0;
51748 state.whave = 0;
51749
51750 state.window = new utils.Buf8(state.wsize);
51751 }
51752
51753 /* copy state->wsize or less output bytes into the circular window */
51754 if (copy >= state.wsize) {
51755 utils.arraySet(state.window, src, end - state.wsize, state.wsize, 0);
51756 state.wnext = 0;
51757 state.whave = state.wsize;
51758 }
51759 else {
51760 dist = state.wsize - state.wnext;
51761 if (dist > copy) {
51762 dist = copy;
51763 }
51764 //zmemcpy(state->window + state->wnext, end - copy, dist);
51765 utils.arraySet(state.window, src, end - copy, dist, state.wnext);
51766 copy -= dist;
51767 if (copy) {
51768 //zmemcpy(state->window, end - copy, copy);
51769 utils.arraySet(state.window, src, end - copy, copy, 0);
51770 state.wnext = copy;
51771 state.whave = state.wsize;
51772 }
51773 else {
51774 state.wnext += dist;
51775 if (state.wnext === state.wsize) { state.wnext = 0; }
51776 if (state.whave < state.wsize) { state.whave += dist; }
51777 }
51778 }
51779 return 0;
51780}
51781
51782function inflate(strm, flush) {
51783 var state;
51784 var input, output; // input/output buffers
51785 var next; /* next input INDEX */
51786 var put; /* next output INDEX */
51787 var have, left; /* available input and output */
51788 var hold; /* bit buffer */
51789 var bits; /* bits in bit buffer */
51790 var _in, _out; /* save starting available input and output */
51791 var copy; /* number of stored or match bytes to copy */
51792 var from; /* where to copy match bytes from */
51793 var from_source;
51794 var here = 0; /* current decoding table entry */
51795 var here_bits, here_op, here_val; // paked "here" denormalized (JS specific)
51796 //var last; /* parent table entry */
51797 var last_bits, last_op, last_val; // paked "last" denormalized (JS specific)
51798 var len; /* length to copy for repeats, bits to drop */
51799 var ret; /* return code */
51800 var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */
51801 var opts;
51802
51803 var n; // temporary var for NEED_BITS
51804
51805 var order = /* permutation of code lengths */
51806 [ 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 ];
51807
51808
51809 if (!strm || !strm.state || !strm.output ||
51810 (!strm.input && strm.avail_in !== 0)) {
51811 return Z_STREAM_ERROR;
51812 }
51813
51814 state = strm.state;
51815 if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */
51816
51817
51818 //--- LOAD() ---
51819 put = strm.next_out;
51820 output = strm.output;
51821 left = strm.avail_out;
51822 next = strm.next_in;
51823 input = strm.input;
51824 have = strm.avail_in;
51825 hold = state.hold;
51826 bits = state.bits;
51827 //---
51828
51829 _in = have;
51830 _out = left;
51831 ret = Z_OK;
51832
51833 inf_leave: // goto emulation
51834 for (;;) {
51835 switch (state.mode) {
51836 case HEAD:
51837 if (state.wrap === 0) {
51838 state.mode = TYPEDO;
51839 break;
51840 }
51841 //=== NEEDBITS(16);
51842 while (bits < 16) {
51843 if (have === 0) { break inf_leave; }
51844 have--;
51845 hold += input[next++] << bits;
51846 bits += 8;
51847 }
51848 //===//
51849 if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */
51850 state.check = 0/*crc32(0L, Z_NULL, 0)*/;
51851 //=== CRC2(state.check, hold);
51852 hbuf[0] = hold & 0xff;
51853 hbuf[1] = (hold >>> 8) & 0xff;
51854 state.check = crc32(state.check, hbuf, 2, 0);
51855 //===//
51856
51857 //=== INITBITS();
51858 hold = 0;
51859 bits = 0;
51860 //===//
51861 state.mode = FLAGS;
51862 break;
51863 }
51864 state.flags = 0; /* expect zlib header */
51865 if (state.head) {
51866 state.head.done = false;
51867 }
51868 if (!(state.wrap & 1) || /* check if zlib header allowed */
51869 (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {
51870 strm.msg = 'incorrect header check';
51871 state.mode = BAD;
51872 break;
51873 }
51874 if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {
51875 strm.msg = 'unknown compression method';
51876 state.mode = BAD;
51877 break;
51878 }
51879 //--- DROPBITS(4) ---//
51880 hold >>>= 4;
51881 bits -= 4;
51882 //---//
51883 len = (hold & 0x0f)/*BITS(4)*/ + 8;
51884 if (state.wbits === 0) {
51885 state.wbits = len;
51886 }
51887 else if (len > state.wbits) {
51888 strm.msg = 'invalid window size';
51889 state.mode = BAD;
51890 break;
51891 }
51892 state.dmax = 1 << len;
51893 //Tracev((stderr, "inflate: zlib header ok\n"));
51894 strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
51895 state.mode = hold & 0x200 ? DICTID : TYPE;
51896 //=== INITBITS();
51897 hold = 0;
51898 bits = 0;
51899 //===//
51900 break;
51901 case FLAGS:
51902 //=== NEEDBITS(16); */
51903 while (bits < 16) {
51904 if (have === 0) { break inf_leave; }
51905 have--;
51906 hold += input[next++] << bits;
51907 bits += 8;
51908 }
51909 //===//
51910 state.flags = hold;
51911 if ((state.flags & 0xff) !== Z_DEFLATED) {
51912 strm.msg = 'unknown compression method';
51913 state.mode = BAD;
51914 break;
51915 }
51916 if (state.flags & 0xe000) {
51917 strm.msg = 'unknown header flags set';
51918 state.mode = BAD;
51919 break;
51920 }
51921 if (state.head) {
51922 state.head.text = ((hold >> 8) & 1);
51923 }
51924 if (state.flags & 0x0200) {
51925 //=== CRC2(state.check, hold);
51926 hbuf[0] = hold & 0xff;
51927 hbuf[1] = (hold >>> 8) & 0xff;
51928 state.check = crc32(state.check, hbuf, 2, 0);
51929 //===//
51930 }
51931 //=== INITBITS();
51932 hold = 0;
51933 bits = 0;
51934 //===//
51935 state.mode = TIME;
51936 /* falls through */
51937 case TIME:
51938 //=== NEEDBITS(32); */
51939 while (bits < 32) {
51940 if (have === 0) { break inf_leave; }
51941 have--;
51942 hold += input[next++] << bits;
51943 bits += 8;
51944 }
51945 //===//
51946 if (state.head) {
51947 state.head.time = hold;
51948 }
51949 if (state.flags & 0x0200) {
51950 //=== CRC4(state.check, hold)
51951 hbuf[0] = hold & 0xff;
51952 hbuf[1] = (hold >>> 8) & 0xff;
51953 hbuf[2] = (hold >>> 16) & 0xff;
51954 hbuf[3] = (hold >>> 24) & 0xff;
51955 state.check = crc32(state.check, hbuf, 4, 0);
51956 //===
51957 }
51958 //=== INITBITS();
51959 hold = 0;
51960 bits = 0;
51961 //===//
51962 state.mode = OS;
51963 /* falls through */
51964 case OS:
51965 //=== NEEDBITS(16); */
51966 while (bits < 16) {
51967 if (have === 0) { break inf_leave; }
51968 have--;
51969 hold += input[next++] << bits;
51970 bits += 8;
51971 }
51972 //===//
51973 if (state.head) {
51974 state.head.xflags = (hold & 0xff);
51975 state.head.os = (hold >> 8);
51976 }
51977 if (state.flags & 0x0200) {
51978 //=== CRC2(state.check, hold);
51979 hbuf[0] = hold & 0xff;
51980 hbuf[1] = (hold >>> 8) & 0xff;
51981 state.check = crc32(state.check, hbuf, 2, 0);
51982 //===//
51983 }
51984 //=== INITBITS();
51985 hold = 0;
51986 bits = 0;
51987 //===//
51988 state.mode = EXLEN;
51989 /* falls through */
51990 case EXLEN:
51991 if (state.flags & 0x0400) {
51992 //=== NEEDBITS(16); */
51993 while (bits < 16) {
51994 if (have === 0) { break inf_leave; }
51995 have--;
51996 hold += input[next++] << bits;
51997 bits += 8;
51998 }
51999 //===//
52000 state.length = hold;
52001 if (state.head) {
52002 state.head.extra_len = hold;
52003 }
52004 if (state.flags & 0x0200) {
52005 //=== CRC2(state.check, hold);
52006 hbuf[0] = hold & 0xff;
52007 hbuf[1] = (hold >>> 8) & 0xff;
52008 state.check = crc32(state.check, hbuf, 2, 0);
52009 //===//
52010 }
52011 //=== INITBITS();
52012 hold = 0;
52013 bits = 0;
52014 //===//
52015 }
52016 else if (state.head) {
52017 state.head.extra = null/*Z_NULL*/;
52018 }
52019 state.mode = EXTRA;
52020 /* falls through */
52021 case EXTRA:
52022 if (state.flags & 0x0400) {
52023 copy = state.length;
52024 if (copy > have) { copy = have; }
52025 if (copy) {
52026 if (state.head) {
52027 len = state.head.extra_len - state.length;
52028 if (!state.head.extra) {
52029 // Use untyped array for more convenient processing later
52030 state.head.extra = new Array(state.head.extra_len);
52031 }
52032 utils.arraySet(
52033 state.head.extra,
52034 input,
52035 next,
52036 // extra field is limited to 65536 bytes
52037 // - no need for additional size check
52038 copy,
52039 /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/
52040 len
52041 );
52042 //zmemcpy(state.head.extra + len, next,
52043 // len + copy > state.head.extra_max ?
52044 // state.head.extra_max - len : copy);
52045 }
52046 if (state.flags & 0x0200) {
52047 state.check = crc32(state.check, input, copy, next);
52048 }
52049 have -= copy;
52050 next += copy;
52051 state.length -= copy;
52052 }
52053 if (state.length) { break inf_leave; }
52054 }
52055 state.length = 0;
52056 state.mode = NAME;
52057 /* falls through */
52058 case NAME:
52059 if (state.flags & 0x0800) {
52060 if (have === 0) { break inf_leave; }
52061 copy = 0;
52062 do {
52063 // TODO: 2 or 1 bytes?
52064 len = input[next + copy++];
52065 /* use constant limit because in js we should not preallocate memory */
52066 if (state.head && len &&
52067 (state.length < 65536 /*state.head.name_max*/)) {
52068 state.head.name += String.fromCharCode(len);
52069 }
52070 } while (len && copy < have);
52071
52072 if (state.flags & 0x0200) {
52073 state.check = crc32(state.check, input, copy, next);
52074 }
52075 have -= copy;
52076 next += copy;
52077 if (len) { break inf_leave; }
52078 }
52079 else if (state.head) {
52080 state.head.name = null;
52081 }
52082 state.length = 0;
52083 state.mode = COMMENT;
52084 /* falls through */
52085 case COMMENT:
52086 if (state.flags & 0x1000) {
52087 if (have === 0) { break inf_leave; }
52088 copy = 0;
52089 do {
52090 len = input[next + copy++];
52091 /* use constant limit because in js we should not preallocate memory */
52092 if (state.head && len &&
52093 (state.length < 65536 /*state.head.comm_max*/)) {
52094 state.head.comment += String.fromCharCode(len);
52095 }
52096 } while (len && copy < have);
52097 if (state.flags & 0x0200) {
52098 state.check = crc32(state.check, input, copy, next);
52099 }
52100 have -= copy;
52101 next += copy;
52102 if (len) { break inf_leave; }
52103 }
52104 else if (state.head) {
52105 state.head.comment = null;
52106 }
52107 state.mode = HCRC;
52108 /* falls through */
52109 case HCRC:
52110 if (state.flags & 0x0200) {
52111 //=== NEEDBITS(16); */
52112 while (bits < 16) {
52113 if (have === 0) { break inf_leave; }
52114 have--;
52115 hold += input[next++] << bits;
52116 bits += 8;
52117 }
52118 //===//
52119 if (hold !== (state.check & 0xffff)) {
52120 strm.msg = 'header crc mismatch';
52121 state.mode = BAD;
52122 break;
52123 }
52124 //=== INITBITS();
52125 hold = 0;
52126 bits = 0;
52127 //===//
52128 }
52129 if (state.head) {
52130 state.head.hcrc = ((state.flags >> 9) & 1);
52131 state.head.done = true;
52132 }
52133 strm.adler = state.check = 0;
52134 state.mode = TYPE;
52135 break;
52136 case DICTID:
52137 //=== NEEDBITS(32); */
52138 while (bits < 32) {
52139 if (have === 0) { break inf_leave; }
52140 have--;
52141 hold += input[next++] << bits;
52142 bits += 8;
52143 }
52144 //===//
52145 strm.adler = state.check = zswap32(hold);
52146 //=== INITBITS();
52147 hold = 0;
52148 bits = 0;
52149 //===//
52150 state.mode = DICT;
52151 /* falls through */
52152 case DICT:
52153 if (state.havedict === 0) {
52154 //--- RESTORE() ---
52155 strm.next_out = put;
52156 strm.avail_out = left;
52157 strm.next_in = next;
52158 strm.avail_in = have;
52159 state.hold = hold;
52160 state.bits = bits;
52161 //---
52162 return Z_NEED_DICT;
52163 }
52164 strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
52165 state.mode = TYPE;
52166 /* falls through */
52167 case TYPE:
52168 if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }
52169 /* falls through */
52170 case TYPEDO:
52171 if (state.last) {
52172 //--- BYTEBITS() ---//
52173 hold >>>= bits & 7;
52174 bits -= bits & 7;
52175 //---//
52176 state.mode = CHECK;
52177 break;
52178 }
52179 //=== NEEDBITS(3); */
52180 while (bits < 3) {
52181 if (have === 0) { break inf_leave; }
52182 have--;
52183 hold += input[next++] << bits;
52184 bits += 8;
52185 }
52186 //===//
52187 state.last = (hold & 0x01)/*BITS(1)*/;
52188 //--- DROPBITS(1) ---//
52189 hold >>>= 1;
52190 bits -= 1;
52191 //---//
52192
52193 switch ((hold & 0x03)/*BITS(2)*/) {
52194 case 0: /* stored block */
52195 //Tracev((stderr, "inflate: stored block%s\n",
52196 // state.last ? " (last)" : ""));
52197 state.mode = STORED;
52198 break;
52199 case 1: /* fixed block */
52200 fixedtables(state);
52201 //Tracev((stderr, "inflate: fixed codes block%s\n",
52202 // state.last ? " (last)" : ""));
52203 state.mode = LEN_; /* decode codes */
52204 if (flush === Z_TREES) {
52205 //--- DROPBITS(2) ---//
52206 hold >>>= 2;
52207 bits -= 2;
52208 //---//
52209 break inf_leave;
52210 }
52211 break;
52212 case 2: /* dynamic block */
52213 //Tracev((stderr, "inflate: dynamic codes block%s\n",
52214 // state.last ? " (last)" : ""));
52215 state.mode = TABLE;
52216 break;
52217 case 3:
52218 strm.msg = 'invalid block type';
52219 state.mode = BAD;
52220 }
52221 //--- DROPBITS(2) ---//
52222 hold >>>= 2;
52223 bits -= 2;
52224 //---//
52225 break;
52226 case STORED:
52227 //--- BYTEBITS() ---// /* go to byte boundary */
52228 hold >>>= bits & 7;
52229 bits -= bits & 7;
52230 //---//
52231 //=== NEEDBITS(32); */
52232 while (bits < 32) {
52233 if (have === 0) { break inf_leave; }
52234 have--;
52235 hold += input[next++] << bits;
52236 bits += 8;
52237 }
52238 //===//
52239 if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {
52240 strm.msg = 'invalid stored block lengths';
52241 state.mode = BAD;
52242 break;
52243 }
52244 state.length = hold & 0xffff;
52245 //Tracev((stderr, "inflate: stored length %u\n",
52246 // state.length));
52247 //=== INITBITS();
52248 hold = 0;
52249 bits = 0;
52250 //===//
52251 state.mode = COPY_;
52252 if (flush === Z_TREES) { break inf_leave; }
52253 /* falls through */
52254 case COPY_:
52255 state.mode = COPY;
52256 /* falls through */
52257 case COPY:
52258 copy = state.length;
52259 if (copy) {
52260 if (copy > have) { copy = have; }
52261 if (copy > left) { copy = left; }
52262 if (copy === 0) { break inf_leave; }
52263 //--- zmemcpy(put, next, copy); ---
52264 utils.arraySet(output, input, next, copy, put);
52265 //---//
52266 have -= copy;
52267 next += copy;
52268 left -= copy;
52269 put += copy;
52270 state.length -= copy;
52271 break;
52272 }
52273 //Tracev((stderr, "inflate: stored end\n"));
52274 state.mode = TYPE;
52275 break;
52276 case TABLE:
52277 //=== NEEDBITS(14); */
52278 while (bits < 14) {
52279 if (have === 0) { break inf_leave; }
52280 have--;
52281 hold += input[next++] << bits;
52282 bits += 8;
52283 }
52284 //===//
52285 state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;
52286 //--- DROPBITS(5) ---//
52287 hold >>>= 5;
52288 bits -= 5;
52289 //---//
52290 state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;
52291 //--- DROPBITS(5) ---//
52292 hold >>>= 5;
52293 bits -= 5;
52294 //---//
52295 state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;
52296 //--- DROPBITS(4) ---//
52297 hold >>>= 4;
52298 bits -= 4;
52299 //---//
52300//#ifndef PKZIP_BUG_WORKAROUND
52301 if (state.nlen > 286 || state.ndist > 30) {
52302 strm.msg = 'too many length or distance symbols';
52303 state.mode = BAD;
52304 break;
52305 }
52306//#endif
52307 //Tracev((stderr, "inflate: table sizes ok\n"));
52308 state.have = 0;
52309 state.mode = LENLENS;
52310 /* falls through */
52311 case LENLENS:
52312 while (state.have < state.ncode) {
52313 //=== NEEDBITS(3);
52314 while (bits < 3) {
52315 if (have === 0) { break inf_leave; }
52316 have--;
52317 hold += input[next++] << bits;
52318 bits += 8;
52319 }
52320 //===//
52321 state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);
52322 //--- DROPBITS(3) ---//
52323 hold >>>= 3;
52324 bits -= 3;
52325 //---//
52326 }
52327 while (state.have < 19) {
52328 state.lens[order[state.have++]] = 0;
52329 }
52330 // We have separate tables & no pointers. 2 commented lines below not needed.
52331 //state.next = state.codes;
52332 //state.lencode = state.next;
52333 // Switch to use dynamic table
52334 state.lencode = state.lendyn;
52335 state.lenbits = 7;
52336
52337 opts = { bits: state.lenbits };
52338 ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);
52339 state.lenbits = opts.bits;
52340
52341 if (ret) {
52342 strm.msg = 'invalid code lengths set';
52343 state.mode = BAD;
52344 break;
52345 }
52346 //Tracev((stderr, "inflate: code lengths ok\n"));
52347 state.have = 0;
52348 state.mode = CODELENS;
52349 /* falls through */
52350 case CODELENS:
52351 while (state.have < state.nlen + state.ndist) {
52352 for (;;) {
52353 here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/
52354 here_bits = here >>> 24;
52355 here_op = (here >>> 16) & 0xff;
52356 here_val = here & 0xffff;
52357
52358 if ((here_bits) <= bits) { break; }
52359 //--- PULLBYTE() ---//
52360 if (have === 0) { break inf_leave; }
52361 have--;
52362 hold += input[next++] << bits;
52363 bits += 8;
52364 //---//
52365 }
52366 if (here_val < 16) {
52367 //--- DROPBITS(here.bits) ---//
52368 hold >>>= here_bits;
52369 bits -= here_bits;
52370 //---//
52371 state.lens[state.have++] = here_val;
52372 }
52373 else {
52374 if (here_val === 16) {
52375 //=== NEEDBITS(here.bits + 2);
52376 n = here_bits + 2;
52377 while (bits < n) {
52378 if (have === 0) { break inf_leave; }
52379 have--;
52380 hold += input[next++] << bits;
52381 bits += 8;
52382 }
52383 //===//
52384 //--- DROPBITS(here.bits) ---//
52385 hold >>>= here_bits;
52386 bits -= here_bits;
52387 //---//
52388 if (state.have === 0) {
52389 strm.msg = 'invalid bit length repeat';
52390 state.mode = BAD;
52391 break;
52392 }
52393 len = state.lens[state.have - 1];
52394 copy = 3 + (hold & 0x03);//BITS(2);
52395 //--- DROPBITS(2) ---//
52396 hold >>>= 2;
52397 bits -= 2;
52398 //---//
52399 }
52400 else if (here_val === 17) {
52401 //=== NEEDBITS(here.bits + 3);
52402 n = here_bits + 3;
52403 while (bits < n) {
52404 if (have === 0) { break inf_leave; }
52405 have--;
52406 hold += input[next++] << bits;
52407 bits += 8;
52408 }
52409 //===//
52410 //--- DROPBITS(here.bits) ---//
52411 hold >>>= here_bits;
52412 bits -= here_bits;
52413 //---//
52414 len = 0;
52415 copy = 3 + (hold & 0x07);//BITS(3);
52416 //--- DROPBITS(3) ---//
52417 hold >>>= 3;
52418 bits -= 3;
52419 //---//
52420 }
52421 else {
52422 //=== NEEDBITS(here.bits + 7);
52423 n = here_bits + 7;
52424 while (bits < n) {
52425 if (have === 0) { break inf_leave; }
52426 have--;
52427 hold += input[next++] << bits;
52428 bits += 8;
52429 }
52430 //===//
52431 //--- DROPBITS(here.bits) ---//
52432 hold >>>= here_bits;
52433 bits -= here_bits;
52434 //---//
52435 len = 0;
52436 copy = 11 + (hold & 0x7f);//BITS(7);
52437 //--- DROPBITS(7) ---//
52438 hold >>>= 7;
52439 bits -= 7;
52440 //---//
52441 }
52442 if (state.have + copy > state.nlen + state.ndist) {
52443 strm.msg = 'invalid bit length repeat';
52444 state.mode = BAD;
52445 break;
52446 }
52447 while (copy--) {
52448 state.lens[state.have++] = len;
52449 }
52450 }
52451 }
52452
52453 /* handle error breaks in while */
52454 if (state.mode === BAD) { break; }
52455
52456 /* check for end-of-block code (better have one) */
52457 if (state.lens[256] === 0) {
52458 strm.msg = 'invalid code -- missing end-of-block';
52459 state.mode = BAD;
52460 break;
52461 }
52462
52463 /* build code tables -- note: do not change the lenbits or distbits
52464 values here (9 and 6) without reading the comments in inftrees.h
52465 concerning the ENOUGH constants, which depend on those values */
52466 state.lenbits = 9;
52467
52468 opts = { bits: state.lenbits };
52469 ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);
52470 // We have separate tables & no pointers. 2 commented lines below not needed.
52471 // state.next_index = opts.table_index;
52472 state.lenbits = opts.bits;
52473 // state.lencode = state.next;
52474
52475 if (ret) {
52476 strm.msg = 'invalid literal/lengths set';
52477 state.mode = BAD;
52478 break;
52479 }
52480
52481 state.distbits = 6;
52482 //state.distcode.copy(state.codes);
52483 // Switch to use dynamic table
52484 state.distcode = state.distdyn;
52485 opts = { bits: state.distbits };
52486 ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);
52487 // We have separate tables & no pointers. 2 commented lines below not needed.
52488 // state.next_index = opts.table_index;
52489 state.distbits = opts.bits;
52490 // state.distcode = state.next;
52491
52492 if (ret) {
52493 strm.msg = 'invalid distances set';
52494 state.mode = BAD;
52495 break;
52496 }
52497 //Tracev((stderr, 'inflate: codes ok\n'));
52498 state.mode = LEN_;
52499 if (flush === Z_TREES) { break inf_leave; }
52500 /* falls through */
52501 case LEN_:
52502 state.mode = LEN;
52503 /* falls through */
52504 case LEN:
52505 if (have >= 6 && left >= 258) {
52506 //--- RESTORE() ---
52507 strm.next_out = put;
52508 strm.avail_out = left;
52509 strm.next_in = next;
52510 strm.avail_in = have;
52511 state.hold = hold;
52512 state.bits = bits;
52513 //---
52514 inflate_fast(strm, _out);
52515 //--- LOAD() ---
52516 put = strm.next_out;
52517 output = strm.output;
52518 left = strm.avail_out;
52519 next = strm.next_in;
52520 input = strm.input;
52521 have = strm.avail_in;
52522 hold = state.hold;
52523 bits = state.bits;
52524 //---
52525
52526 if (state.mode === TYPE) {
52527 state.back = -1;
52528 }
52529 break;
52530 }
52531 state.back = 0;
52532 for (;;) {
52533 here = state.lencode[hold & ((1 << state.lenbits) - 1)]; /*BITS(state.lenbits)*/
52534 here_bits = here >>> 24;
52535 here_op = (here >>> 16) & 0xff;
52536 here_val = here & 0xffff;
52537
52538 if (here_bits <= bits) { break; }
52539 //--- PULLBYTE() ---//
52540 if (have === 0) { break inf_leave; }
52541 have--;
52542 hold += input[next++] << bits;
52543 bits += 8;
52544 //---//
52545 }
52546 if (here_op && (here_op & 0xf0) === 0) {
52547 last_bits = here_bits;
52548 last_op = here_op;
52549 last_val = here_val;
52550 for (;;) {
52551 here = state.lencode[last_val +
52552 ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)];
52553 here_bits = here >>> 24;
52554 here_op = (here >>> 16) & 0xff;
52555 here_val = here & 0xffff;
52556
52557 if ((last_bits + here_bits) <= bits) { break; }
52558 //--- PULLBYTE() ---//
52559 if (have === 0) { break inf_leave; }
52560 have--;
52561 hold += input[next++] << bits;
52562 bits += 8;
52563 //---//
52564 }
52565 //--- DROPBITS(last.bits) ---//
52566 hold >>>= last_bits;
52567 bits -= last_bits;
52568 //---//
52569 state.back += last_bits;
52570 }
52571 //--- DROPBITS(here.bits) ---//
52572 hold >>>= here_bits;
52573 bits -= here_bits;
52574 //---//
52575 state.back += here_bits;
52576 state.length = here_val;
52577 if (here_op === 0) {
52578 //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
52579 // "inflate: literal '%c'\n" :
52580 // "inflate: literal 0x%02x\n", here.val));
52581 state.mode = LIT;
52582 break;
52583 }
52584 if (here_op & 32) {
52585 //Tracevv((stderr, "inflate: end of block\n"));
52586 state.back = -1;
52587 state.mode = TYPE;
52588 break;
52589 }
52590 if (here_op & 64) {
52591 strm.msg = 'invalid literal/length code';
52592 state.mode = BAD;
52593 break;
52594 }
52595 state.extra = here_op & 15;
52596 state.mode = LENEXT;
52597 /* falls through */
52598 case LENEXT:
52599 if (state.extra) {
52600 //=== NEEDBITS(state.extra);
52601 n = state.extra;
52602 while (bits < n) {
52603 if (have === 0) { break inf_leave; }
52604 have--;
52605 hold += input[next++] << bits;
52606 bits += 8;
52607 }
52608 //===//
52609 state.length += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/;
52610 //--- DROPBITS(state.extra) ---//
52611 hold >>>= state.extra;
52612 bits -= state.extra;
52613 //---//
52614 state.back += state.extra;
52615 }
52616 //Tracevv((stderr, "inflate: length %u\n", state.length));
52617 state.was = state.length;
52618 state.mode = DIST;
52619 /* falls through */
52620 case DIST:
52621 for (;;) {
52622 here = state.distcode[hold & ((1 << state.distbits) - 1)];/*BITS(state.distbits)*/
52623 here_bits = here >>> 24;
52624 here_op = (here >>> 16) & 0xff;
52625 here_val = here & 0xffff;
52626
52627 if ((here_bits) <= bits) { break; }
52628 //--- PULLBYTE() ---//
52629 if (have === 0) { break inf_leave; }
52630 have--;
52631 hold += input[next++] << bits;
52632 bits += 8;
52633 //---//
52634 }
52635 if ((here_op & 0xf0) === 0) {
52636 last_bits = here_bits;
52637 last_op = here_op;
52638 last_val = here_val;
52639 for (;;) {
52640 here = state.distcode[last_val +
52641 ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)];
52642 here_bits = here >>> 24;
52643 here_op = (here >>> 16) & 0xff;
52644 here_val = here & 0xffff;
52645
52646 if ((last_bits + here_bits) <= bits) { break; }
52647 //--- PULLBYTE() ---//
52648 if (have === 0) { break inf_leave; }
52649 have--;
52650 hold += input[next++] << bits;
52651 bits += 8;
52652 //---//
52653 }
52654 //--- DROPBITS(last.bits) ---//
52655 hold >>>= last_bits;
52656 bits -= last_bits;
52657 //---//
52658 state.back += last_bits;
52659 }
52660 //--- DROPBITS(here.bits) ---//
52661 hold >>>= here_bits;
52662 bits -= here_bits;
52663 //---//
52664 state.back += here_bits;
52665 if (here_op & 64) {
52666 strm.msg = 'invalid distance code';
52667 state.mode = BAD;
52668 break;
52669 }
52670 state.offset = here_val;
52671 state.extra = (here_op) & 15;
52672 state.mode = DISTEXT;
52673 /* falls through */
52674 case DISTEXT:
52675 if (state.extra) {
52676 //=== NEEDBITS(state.extra);
52677 n = state.extra;
52678 while (bits < n) {
52679 if (have === 0) { break inf_leave; }
52680 have--;
52681 hold += input[next++] << bits;
52682 bits += 8;
52683 }
52684 //===//
52685 state.offset += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/;
52686 //--- DROPBITS(state.extra) ---//
52687 hold >>>= state.extra;
52688 bits -= state.extra;
52689 //---//
52690 state.back += state.extra;
52691 }
52692//#ifdef INFLATE_STRICT
52693 if (state.offset > state.dmax) {
52694 strm.msg = 'invalid distance too far back';
52695 state.mode = BAD;
52696 break;
52697 }
52698//#endif
52699 //Tracevv((stderr, "inflate: distance %u\n", state.offset));
52700 state.mode = MATCH;
52701 /* falls through */
52702 case MATCH:
52703 if (left === 0) { break inf_leave; }
52704 copy = _out - left;
52705 if (state.offset > copy) { /* copy from window */
52706 copy = state.offset - copy;
52707 if (copy > state.whave) {
52708 if (state.sane) {
52709 strm.msg = 'invalid distance too far back';
52710 state.mode = BAD;
52711 break;
52712 }
52713// (!) This block is disabled in zlib defaults,
52714// don't enable it for binary compatibility
52715//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
52716// Trace((stderr, "inflate.c too far\n"));
52717// copy -= state.whave;
52718// if (copy > state.length) { copy = state.length; }
52719// if (copy > left) { copy = left; }
52720// left -= copy;
52721// state.length -= copy;
52722// do {
52723// output[put++] = 0;
52724// } while (--copy);
52725// if (state.length === 0) { state.mode = LEN; }
52726// break;
52727//#endif
52728 }
52729 if (copy > state.wnext) {
52730 copy -= state.wnext;
52731 from = state.wsize - copy;
52732 }
52733 else {
52734 from = state.wnext - copy;
52735 }
52736 if (copy > state.length) { copy = state.length; }
52737 from_source = state.window;
52738 }
52739 else { /* copy from output */
52740 from_source = output;
52741 from = put - state.offset;
52742 copy = state.length;
52743 }
52744 if (copy > left) { copy = left; }
52745 left -= copy;
52746 state.length -= copy;
52747 do {
52748 output[put++] = from_source[from++];
52749 } while (--copy);
52750 if (state.length === 0) { state.mode = LEN; }
52751 break;
52752 case LIT:
52753 if (left === 0) { break inf_leave; }
52754 output[put++] = state.length;
52755 left--;
52756 state.mode = LEN;
52757 break;
52758 case CHECK:
52759 if (state.wrap) {
52760 //=== NEEDBITS(32);
52761 while (bits < 32) {
52762 if (have === 0) { break inf_leave; }
52763 have--;
52764 // Use '|' instead of '+' to make sure that result is signed
52765 hold |= input[next++] << bits;
52766 bits += 8;
52767 }
52768 //===//
52769 _out -= left;
52770 strm.total_out += _out;
52771 state.total += _out;
52772 if (_out) {
52773 strm.adler = state.check =
52774 /*UPDATE(state.check, put - _out, _out);*/
52775 (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out));
52776
52777 }
52778 _out = left;
52779 // NB: crc32 stored as signed 32-bit int, zswap32 returns signed too
52780 if ((state.flags ? hold : zswap32(hold)) !== state.check) {
52781 strm.msg = 'incorrect data check';
52782 state.mode = BAD;
52783 break;
52784 }
52785 //=== INITBITS();
52786 hold = 0;
52787 bits = 0;
52788 //===//
52789 //Tracev((stderr, "inflate: check matches trailer\n"));
52790 }
52791 state.mode = LENGTH;
52792 /* falls through */
52793 case LENGTH:
52794 if (state.wrap && state.flags) {
52795 //=== NEEDBITS(32);
52796 while (bits < 32) {
52797 if (have === 0) { break inf_leave; }
52798 have--;
52799 hold += input[next++] << bits;
52800 bits += 8;
52801 }
52802 //===//
52803 if (hold !== (state.total & 0xffffffff)) {
52804 strm.msg = 'incorrect length check';
52805 state.mode = BAD;
52806 break;
52807 }
52808 //=== INITBITS();
52809 hold = 0;
52810 bits = 0;
52811 //===//
52812 //Tracev((stderr, "inflate: length matches trailer\n"));
52813 }
52814 state.mode = DONE;
52815 /* falls through */
52816 case DONE:
52817 ret = Z_STREAM_END;
52818 break inf_leave;
52819 case BAD:
52820 ret = Z_DATA_ERROR;
52821 break inf_leave;
52822 case MEM:
52823 return Z_MEM_ERROR;
52824 case SYNC:
52825 /* falls through */
52826 default:
52827 return Z_STREAM_ERROR;
52828 }
52829 }
52830
52831 // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave"
52832
52833 /*
52834 Return from inflate(), updating the total counts and the check value.
52835 If there was no progress during the inflate() call, return a buffer
52836 error. Call updatewindow() to create and/or update the window state.
52837 Note: a memory error from inflate() is non-recoverable.
52838 */
52839
52840 //--- RESTORE() ---
52841 strm.next_out = put;
52842 strm.avail_out = left;
52843 strm.next_in = next;
52844 strm.avail_in = have;
52845 state.hold = hold;
52846 state.bits = bits;
52847 //---
52848
52849 if (state.wsize || (_out !== strm.avail_out && state.mode < BAD &&
52850 (state.mode < CHECK || flush !== Z_FINISH))) {
52851 if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) {
52852 state.mode = MEM;
52853 return Z_MEM_ERROR;
52854 }
52855 }
52856 _in -= strm.avail_in;
52857 _out -= strm.avail_out;
52858 strm.total_in += _in;
52859 strm.total_out += _out;
52860 state.total += _out;
52861 if (state.wrap && _out) {
52862 strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/
52863 (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out));
52864 }
52865 strm.data_type = state.bits + (state.last ? 64 : 0) +
52866 (state.mode === TYPE ? 128 : 0) +
52867 (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);
52868 if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) {
52869 ret = Z_BUF_ERROR;
52870 }
52871 return ret;
52872}
52873
52874function inflateEnd(strm) {
52875
52876 if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) {
52877 return Z_STREAM_ERROR;
52878 }
52879
52880 var state = strm.state;
52881 if (state.window) {
52882 state.window = null;
52883 }
52884 strm.state = null;
52885 return Z_OK;
52886}
52887
52888function inflateGetHeader(strm, head) {
52889 var state;
52890
52891 /* check state */
52892 if (!strm || !strm.state) { return Z_STREAM_ERROR; }
52893 state = strm.state;
52894 if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; }
52895
52896 /* save header structure */
52897 state.head = head;
52898 head.done = false;
52899 return Z_OK;
52900}
52901
52902function inflateSetDictionary(strm, dictionary) {
52903 var dictLength = dictionary.length;
52904
52905 var state;
52906 var dictid;
52907 var ret;
52908
52909 /* check state */
52910 if (!strm /* == Z_NULL */ || !strm.state /* == Z_NULL */) { return Z_STREAM_ERROR; }
52911 state = strm.state;
52912
52913 if (state.wrap !== 0 && state.mode !== DICT) {
52914 return Z_STREAM_ERROR;
52915 }
52916
52917 /* check for correct dictionary identifier */
52918 if (state.mode === DICT) {
52919 dictid = 1; /* adler32(0, null, 0)*/
52920 /* dictid = adler32(dictid, dictionary, dictLength); */
52921 dictid = adler32(dictid, dictionary, dictLength, 0);
52922 if (dictid !== state.check) {
52923 return Z_DATA_ERROR;
52924 }
52925 }
52926 /* copy dictionary to window using updatewindow(), which will amend the
52927 existing dictionary if appropriate */
52928 ret = updatewindow(strm, dictionary, dictLength, dictLength);
52929 if (ret) {
52930 state.mode = MEM;
52931 return Z_MEM_ERROR;
52932 }
52933 state.havedict = 1;
52934 // Tracev((stderr, "inflate: dictionary set\n"));
52935 return Z_OK;
52936}
52937
52938exports.inflateReset = inflateReset;
52939exports.inflateReset2 = inflateReset2;
52940exports.inflateResetKeep = inflateResetKeep;
52941exports.inflateInit = inflateInit;
52942exports.inflateInit2 = inflateInit2;
52943exports.inflate = inflate;
52944exports.inflateEnd = inflateEnd;
52945exports.inflateGetHeader = inflateGetHeader;
52946exports.inflateSetDictionary = inflateSetDictionary;
52947exports.inflateInfo = 'pako inflate (from Nodeca project)';
52948
52949/* Not implemented
52950exports.inflateCopy = inflateCopy;
52951exports.inflateGetDictionary = inflateGetDictionary;
52952exports.inflateMark = inflateMark;
52953exports.inflatePrime = inflatePrime;
52954exports.inflateSync = inflateSync;
52955exports.inflateSyncPoint = inflateSyncPoint;
52956exports.inflateUndermine = inflateUndermine;
52957*/
52958
52959},{"../utils/common":241,"./adler32":242,"./crc32":244,"./inffast":246,"./inftrees":248}],248:[function(require,module,exports){
52960'use strict';
52961
52962// (C) 1995-2013 Jean-loup Gailly and Mark Adler
52963// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
52964//
52965// This software is provided 'as-is', without any express or implied
52966// warranty. In no event will the authors be held liable for any damages
52967// arising from the use of this software.
52968//
52969// Permission is granted to anyone to use this software for any purpose,
52970// including commercial applications, and to alter it and redistribute it
52971// freely, subject to the following restrictions:
52972//
52973// 1. The origin of this software must not be misrepresented; you must not
52974// claim that you wrote the original software. If you use this software
52975// in a product, an acknowledgment in the product documentation would be
52976// appreciated but is not required.
52977// 2. Altered source versions must be plainly marked as such, and must not be
52978// misrepresented as being the original software.
52979// 3. This notice may not be removed or altered from any source distribution.
52980
52981var utils = require('../utils/common');
52982
52983var MAXBITS = 15;
52984var ENOUGH_LENS = 852;
52985var ENOUGH_DISTS = 592;
52986//var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
52987
52988var CODES = 0;
52989var LENS = 1;
52990var DISTS = 2;
52991
52992var lbase = [ /* Length codes 257..285 base */
52993 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
52994 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0
52995];
52996
52997var lext = [ /* Length codes 257..285 extra */
52998 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
52999 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78
53000];
53001
53002var dbase = [ /* Distance codes 0..29 base */
53003 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
53004 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
53005 8193, 12289, 16385, 24577, 0, 0
53006];
53007
53008var dext = [ /* Distance codes 0..29 extra */
53009 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
53010 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
53011 28, 28, 29, 29, 64, 64
53012];
53013
53014module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts)
53015{
53016 var bits = opts.bits;
53017 //here = opts.here; /* table entry for duplication */
53018
53019 var len = 0; /* a code's length in bits */
53020 var sym = 0; /* index of code symbols */
53021 var min = 0, max = 0; /* minimum and maximum code lengths */
53022 var root = 0; /* number of index bits for root table */
53023 var curr = 0; /* number of index bits for current table */
53024 var drop = 0; /* code bits to drop for sub-table */
53025 var left = 0; /* number of prefix codes available */
53026 var used = 0; /* code entries in table used */
53027 var huff = 0; /* Huffman code */
53028 var incr; /* for incrementing code, index */
53029 var fill; /* index for replicating entries */
53030 var low; /* low bits for current root entry */
53031 var mask; /* mask for low root bits */
53032 var next; /* next available space in table */
53033 var base = null; /* base value table to use */
53034 var base_index = 0;
53035// var shoextra; /* extra bits table to use */
53036 var end; /* use base and extra for symbol > end */
53037 var count = new utils.Buf16(MAXBITS + 1); //[MAXBITS+1]; /* number of codes of each length */
53038 var offs = new utils.Buf16(MAXBITS + 1); //[MAXBITS+1]; /* offsets in table for each length */
53039 var extra = null;
53040 var extra_index = 0;
53041
53042 var here_bits, here_op, here_val;
53043
53044 /*
53045 Process a set of code lengths to create a canonical Huffman code. The
53046 code lengths are lens[0..codes-1]. Each length corresponds to the
53047 symbols 0..codes-1. The Huffman code is generated by first sorting the
53048 symbols by length from short to long, and retaining the symbol order
53049 for codes with equal lengths. Then the code starts with all zero bits
53050 for the first code of the shortest length, and the codes are integer
53051 increments for the same length, and zeros are appended as the length
53052 increases. For the deflate format, these bits are stored backwards
53053 from their more natural integer increment ordering, and so when the
53054 decoding tables are built in the large loop below, the integer codes
53055 are incremented backwards.
53056
53057 This routine assumes, but does not check, that all of the entries in
53058 lens[] are in the range 0..MAXBITS. The caller must assure this.
53059 1..MAXBITS is interpreted as that code length. zero means that that
53060 symbol does not occur in this code.
53061
53062 The codes are sorted by computing a count of codes for each length,
53063 creating from that a table of starting indices for each length in the
53064 sorted table, and then entering the symbols in order in the sorted
53065 table. The sorted table is work[], with that space being provided by
53066 the caller.
53067
53068 The length counts are used for other purposes as well, i.e. finding
53069 the minimum and maximum length codes, determining if there are any
53070 codes at all, checking for a valid set of lengths, and looking ahead
53071 at length counts to determine sub-table sizes when building the
53072 decoding tables.
53073 */
53074
53075 /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
53076 for (len = 0; len <= MAXBITS; len++) {
53077 count[len] = 0;
53078 }
53079 for (sym = 0; sym < codes; sym++) {
53080 count[lens[lens_index + sym]]++;
53081 }
53082
53083 /* bound code lengths, force root to be within code lengths */
53084 root = bits;
53085 for (max = MAXBITS; max >= 1; max--) {
53086 if (count[max] !== 0) { break; }
53087 }
53088 if (root > max) {
53089 root = max;
53090 }
53091 if (max === 0) { /* no symbols to code at all */
53092 //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */
53093 //table.bits[opts.table_index] = 1; //here.bits = (var char)1;
53094 //table.val[opts.table_index++] = 0; //here.val = (var short)0;
53095 table[table_index++] = (1 << 24) | (64 << 16) | 0;
53096
53097
53098 //table.op[opts.table_index] = 64;
53099 //table.bits[opts.table_index] = 1;
53100 //table.val[opts.table_index++] = 0;
53101 table[table_index++] = (1 << 24) | (64 << 16) | 0;
53102
53103 opts.bits = 1;
53104 return 0; /* no symbols, but wait for decoding to report error */
53105 }
53106 for (min = 1; min < max; min++) {
53107 if (count[min] !== 0) { break; }
53108 }
53109 if (root < min) {
53110 root = min;
53111 }
53112
53113 /* check for an over-subscribed or incomplete set of lengths */
53114 left = 1;
53115 for (len = 1; len <= MAXBITS; len++) {
53116 left <<= 1;
53117 left -= count[len];
53118 if (left < 0) {
53119 return -1;
53120 } /* over-subscribed */
53121 }
53122 if (left > 0 && (type === CODES || max !== 1)) {
53123 return -1; /* incomplete set */
53124 }
53125
53126 /* generate offsets into symbol table for each length for sorting */
53127 offs[1] = 0;
53128 for (len = 1; len < MAXBITS; len++) {
53129 offs[len + 1] = offs[len] + count[len];
53130 }
53131
53132 /* sort symbols by length, by symbol order within each length */
53133 for (sym = 0; sym < codes; sym++) {
53134 if (lens[lens_index + sym] !== 0) {
53135 work[offs[lens[lens_index + sym]]++] = sym;
53136 }
53137 }
53138
53139 /*
53140 Create and fill in decoding tables. In this loop, the table being
53141 filled is at next and has curr index bits. The code being used is huff
53142 with length len. That code is converted to an index by dropping drop
53143 bits off of the bottom. For codes where len is less than drop + curr,
53144 those top drop + curr - len bits are incremented through all values to
53145 fill the table with replicated entries.
53146
53147 root is the number of index bits for the root table. When len exceeds
53148 root, sub-tables are created pointed to by the root entry with an index
53149 of the low root bits of huff. This is saved in low to check for when a
53150 new sub-table should be started. drop is zero when the root table is
53151 being filled, and drop is root when sub-tables are being filled.
53152
53153 When a new sub-table is needed, it is necessary to look ahead in the
53154 code lengths to determine what size sub-table is needed. The length
53155 counts are used for this, and so count[] is decremented as codes are
53156 entered in the tables.
53157
53158 used keeps track of how many table entries have been allocated from the
53159 provided *table space. It is checked for LENS and DIST tables against
53160 the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in
53161 the initial root table size constants. See the comments in inftrees.h
53162 for more information.
53163
53164 sym increments through all symbols, and the loop terminates when
53165 all codes of length max, i.e. all codes, have been processed. This
53166 routine permits incomplete codes, so another loop after this one fills
53167 in the rest of the decoding tables with invalid code markers.
53168 */
53169
53170 /* set up for code type */
53171 // poor man optimization - use if-else instead of switch,
53172 // to avoid deopts in old v8
53173 if (type === CODES) {
53174 base = extra = work; /* dummy value--not used */
53175 end = 19;
53176
53177 } else if (type === LENS) {
53178 base = lbase;
53179 base_index -= 257;
53180 extra = lext;
53181 extra_index -= 257;
53182 end = 256;
53183
53184 } else { /* DISTS */
53185 base = dbase;
53186 extra = dext;
53187 end = -1;
53188 }
53189
53190 /* initialize opts for loop */
53191 huff = 0; /* starting code */
53192 sym = 0; /* starting code symbol */
53193 len = min; /* starting code length */
53194 next = table_index; /* current table to fill in */
53195 curr = root; /* current table index bits */
53196 drop = 0; /* current bits to drop from code for index */
53197 low = -1; /* trigger new sub-table when len > root */
53198 used = 1 << root; /* use root table entries */
53199 mask = used - 1; /* mask for comparing low */
53200
53201 /* check available table space */
53202 if ((type === LENS && used > ENOUGH_LENS) ||
53203 (type === DISTS && used > ENOUGH_DISTS)) {
53204 return 1;
53205 }
53206
53207 /* process all codes and make table entries */
53208 for (;;) {
53209 /* create table entry */
53210 here_bits = len - drop;
53211 if (work[sym] < end) {
53212 here_op = 0;
53213 here_val = work[sym];
53214 }
53215 else if (work[sym] > end) {
53216 here_op = extra[extra_index + work[sym]];
53217 here_val = base[base_index + work[sym]];
53218 }
53219 else {
53220 here_op = 32 + 64; /* end of block */
53221 here_val = 0;
53222 }
53223
53224 /* replicate for those indices with low len bits equal to huff */
53225 incr = 1 << (len - drop);
53226 fill = 1 << curr;
53227 min = fill; /* save offset to next table */
53228 do {
53229 fill -= incr;
53230 table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0;
53231 } while (fill !== 0);
53232
53233 /* backwards increment the len-bit code huff */
53234 incr = 1 << (len - 1);
53235 while (huff & incr) {
53236 incr >>= 1;
53237 }
53238 if (incr !== 0) {
53239 huff &= incr - 1;
53240 huff += incr;
53241 } else {
53242 huff = 0;
53243 }
53244
53245 /* go to next symbol, update count, len */
53246 sym++;
53247 if (--count[len] === 0) {
53248 if (len === max) { break; }
53249 len = lens[lens_index + work[sym]];
53250 }
53251
53252 /* create new sub-table if needed */
53253 if (len > root && (huff & mask) !== low) {
53254 /* if first time, transition to sub-tables */
53255 if (drop === 0) {
53256 drop = root;
53257 }
53258
53259 /* increment past last table */
53260 next += min; /* here min is 1 << curr */
53261
53262 /* determine length of next table */
53263 curr = len - drop;
53264 left = 1 << curr;
53265 while (curr + drop < max) {
53266 left -= count[curr + drop];
53267 if (left <= 0) { break; }
53268 curr++;
53269 left <<= 1;
53270 }
53271
53272 /* check for enough space */
53273 used += 1 << curr;
53274 if ((type === LENS && used > ENOUGH_LENS) ||
53275 (type === DISTS && used > ENOUGH_DISTS)) {
53276 return 1;
53277 }
53278
53279 /* point entry in root table to sub-table */
53280 low = huff & mask;
53281 /*table.op[low] = curr;
53282 table.bits[low] = root;
53283 table.val[low] = next - opts.table_index;*/
53284 table[low] = (root << 24) | (curr << 16) | (next - table_index) |0;
53285 }
53286 }
53287
53288 /* fill in remaining table entry if code is incomplete (guaranteed to have
53289 at most one remaining entry, since if the code is incomplete, the
53290 maximum code length that was allowed to get this far is one bit) */
53291 if (huff !== 0) {
53292 //table.op[next + huff] = 64; /* invalid code marker */
53293 //table.bits[next + huff] = len - drop;
53294 //table.val[next + huff] = 0;
53295 table[next + huff] = ((len - drop) << 24) | (64 << 16) |0;
53296 }
53297
53298 /* set return parameters */
53299 //opts.table_index += used;
53300 opts.bits = root;
53301 return 0;
53302};
53303
53304},{"../utils/common":241}],249:[function(require,module,exports){
53305'use strict';
53306
53307// (C) 1995-2013 Jean-loup Gailly and Mark Adler
53308// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
53309//
53310// This software is provided 'as-is', without any express or implied
53311// warranty. In no event will the authors be held liable for any damages
53312// arising from the use of this software.
53313//
53314// Permission is granted to anyone to use this software for any purpose,
53315// including commercial applications, and to alter it and redistribute it
53316// freely, subject to the following restrictions:
53317//
53318// 1. The origin of this software must not be misrepresented; you must not
53319// claim that you wrote the original software. If you use this software
53320// in a product, an acknowledgment in the product documentation would be
53321// appreciated but is not required.
53322// 2. Altered source versions must be plainly marked as such, and must not be
53323// misrepresented as being the original software.
53324// 3. This notice may not be removed or altered from any source distribution.
53325
53326module.exports = {
53327 2: 'need dictionary', /* Z_NEED_DICT 2 */
53328 1: 'stream end', /* Z_STREAM_END 1 */
53329 0: '', /* Z_OK 0 */
53330 '-1': 'file error', /* Z_ERRNO (-1) */
53331 '-2': 'stream error', /* Z_STREAM_ERROR (-2) */
53332 '-3': 'data error', /* Z_DATA_ERROR (-3) */
53333 '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */
53334 '-5': 'buffer error', /* Z_BUF_ERROR (-5) */
53335 '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */
53336};
53337
53338},{}],250:[function(require,module,exports){
53339'use strict';
53340
53341// (C) 1995-2013 Jean-loup Gailly and Mark Adler
53342// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
53343//
53344// This software is provided 'as-is', without any express or implied
53345// warranty. In no event will the authors be held liable for any damages
53346// arising from the use of this software.
53347//
53348// Permission is granted to anyone to use this software for any purpose,
53349// including commercial applications, and to alter it and redistribute it
53350// freely, subject to the following restrictions:
53351//
53352// 1. The origin of this software must not be misrepresented; you must not
53353// claim that you wrote the original software. If you use this software
53354// in a product, an acknowledgment in the product documentation would be
53355// appreciated but is not required.
53356// 2. Altered source versions must be plainly marked as such, and must not be
53357// misrepresented as being the original software.
53358// 3. This notice may not be removed or altered from any source distribution.
53359
53360/* eslint-disable space-unary-ops */
53361
53362var utils = require('../utils/common');
53363
53364/* Public constants ==========================================================*/
53365/* ===========================================================================*/
53366
53367
53368//var Z_FILTERED = 1;
53369//var Z_HUFFMAN_ONLY = 2;
53370//var Z_RLE = 3;
53371var Z_FIXED = 4;
53372//var Z_DEFAULT_STRATEGY = 0;
53373
53374/* Possible values of the data_type field (though see inflate()) */
53375var Z_BINARY = 0;
53376var Z_TEXT = 1;
53377//var Z_ASCII = 1; // = Z_TEXT
53378var Z_UNKNOWN = 2;
53379
53380/*============================================================================*/
53381
53382
53383function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
53384
53385// From zutil.h
53386
53387var STORED_BLOCK = 0;
53388var STATIC_TREES = 1;
53389var DYN_TREES = 2;
53390/* The three kinds of block type */
53391
53392var MIN_MATCH = 3;
53393var MAX_MATCH = 258;
53394/* The minimum and maximum match lengths */
53395
53396// From deflate.h
53397/* ===========================================================================
53398 * Internal compression state.
53399 */
53400
53401var LENGTH_CODES = 29;
53402/* number of length codes, not counting the special END_BLOCK code */
53403
53404var LITERALS = 256;
53405/* number of literal bytes 0..255 */
53406
53407var L_CODES = LITERALS + 1 + LENGTH_CODES;
53408/* number of Literal or Length codes, including the END_BLOCK code */
53409
53410var D_CODES = 30;
53411/* number of distance codes */
53412
53413var BL_CODES = 19;
53414/* number of codes used to transfer the bit lengths */
53415
53416var HEAP_SIZE = 2 * L_CODES + 1;
53417/* maximum heap size */
53418
53419var MAX_BITS = 15;
53420/* All codes must not exceed MAX_BITS bits */
53421
53422var Buf_size = 16;
53423/* size of bit buffer in bi_buf */
53424
53425
53426/* ===========================================================================
53427 * Constants
53428 */
53429
53430var MAX_BL_BITS = 7;
53431/* Bit length codes must not exceed MAX_BL_BITS bits */
53432
53433var END_BLOCK = 256;
53434/* end of block literal code */
53435
53436var REP_3_6 = 16;
53437/* repeat previous bit length 3-6 times (2 bits of repeat count) */
53438
53439var REPZ_3_10 = 17;
53440/* repeat a zero length 3-10 times (3 bits of repeat count) */
53441
53442var REPZ_11_138 = 18;
53443/* repeat a zero length 11-138 times (7 bits of repeat count) */
53444
53445/* eslint-disable comma-spacing,array-bracket-spacing */
53446var extra_lbits = /* extra bits for each length code */
53447 [0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0];
53448
53449var extra_dbits = /* extra bits for each distance code */
53450 [0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13];
53451
53452var extra_blbits = /* extra bits for each bit length code */
53453 [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7];
53454
53455var bl_order =
53456 [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];
53457/* eslint-enable comma-spacing,array-bracket-spacing */
53458
53459/* The lengths of the bit length codes are sent in order of decreasing
53460 * probability, to avoid transmitting the lengths for unused bit length codes.
53461 */
53462
53463/* ===========================================================================
53464 * Local data. These are initialized only once.
53465 */
53466
53467// We pre-fill arrays with 0 to avoid uninitialized gaps
53468
53469var DIST_CODE_LEN = 512; /* see definition of array dist_code below */
53470
53471// !!!! Use flat array instead of structure, Freq = i*2, Len = i*2+1
53472var static_ltree = new Array((L_CODES + 2) * 2);
53473zero(static_ltree);
53474/* The static literal tree. Since the bit lengths are imposed, there is no
53475 * need for the L_CODES extra codes used during heap construction. However
53476 * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
53477 * below).
53478 */
53479
53480var static_dtree = new Array(D_CODES * 2);
53481zero(static_dtree);
53482/* The static distance tree. (Actually a trivial tree since all codes use
53483 * 5 bits.)
53484 */
53485
53486var _dist_code = new Array(DIST_CODE_LEN);
53487zero(_dist_code);
53488/* Distance codes. The first 256 values correspond to the distances
53489 * 3 .. 258, the last 256 values correspond to the top 8 bits of
53490 * the 15 bit distances.
53491 */
53492
53493var _length_code = new Array(MAX_MATCH - MIN_MATCH + 1);
53494zero(_length_code);
53495/* length code for each normalized match length (0 == MIN_MATCH) */
53496
53497var base_length = new Array(LENGTH_CODES);
53498zero(base_length);
53499/* First normalized length for each code (0 = MIN_MATCH) */
53500
53501var base_dist = new Array(D_CODES);
53502zero(base_dist);
53503/* First normalized distance for each code (0 = distance of 1) */
53504
53505
53506function StaticTreeDesc(static_tree, extra_bits, extra_base, elems, max_length) {
53507
53508 this.static_tree = static_tree; /* static tree or NULL */
53509 this.extra_bits = extra_bits; /* extra bits for each code or NULL */
53510 this.extra_base = extra_base; /* base index for extra_bits */
53511 this.elems = elems; /* max number of elements in the tree */
53512 this.max_length = max_length; /* max bit length for the codes */
53513
53514 // show if `static_tree` has data or dummy - needed for monomorphic objects
53515 this.has_stree = static_tree && static_tree.length;
53516}
53517
53518
53519var static_l_desc;
53520var static_d_desc;
53521var static_bl_desc;
53522
53523
53524function TreeDesc(dyn_tree, stat_desc) {
53525 this.dyn_tree = dyn_tree; /* the dynamic tree */
53526 this.max_code = 0; /* largest code with non zero frequency */
53527 this.stat_desc = stat_desc; /* the corresponding static tree */
53528}
53529
53530
53531
53532function d_code(dist) {
53533 return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];
53534}
53535
53536
53537/* ===========================================================================
53538 * Output a short LSB first on the stream.
53539 * IN assertion: there is enough room in pendingBuf.
53540 */
53541function put_short(s, w) {
53542// put_byte(s, (uch)((w) & 0xff));
53543// put_byte(s, (uch)((ush)(w) >> 8));
53544 s.pending_buf[s.pending++] = (w) & 0xff;
53545 s.pending_buf[s.pending++] = (w >>> 8) & 0xff;
53546}
53547
53548
53549/* ===========================================================================
53550 * Send a value on a given number of bits.
53551 * IN assertion: length <= 16 and value fits in length bits.
53552 */
53553function send_bits(s, value, length) {
53554 if (s.bi_valid > (Buf_size - length)) {
53555 s.bi_buf |= (value << s.bi_valid) & 0xffff;
53556 put_short(s, s.bi_buf);
53557 s.bi_buf = value >> (Buf_size - s.bi_valid);
53558 s.bi_valid += length - Buf_size;
53559 } else {
53560 s.bi_buf |= (value << s.bi_valid) & 0xffff;
53561 s.bi_valid += length;
53562 }
53563}
53564
53565
53566function send_code(s, c, tree) {
53567 send_bits(s, tree[c * 2]/*.Code*/, tree[c * 2 + 1]/*.Len*/);
53568}
53569
53570
53571/* ===========================================================================
53572 * Reverse the first len bits of a code, using straightforward code (a faster
53573 * method would use a table)
53574 * IN assertion: 1 <= len <= 15
53575 */
53576function bi_reverse(code, len) {
53577 var res = 0;
53578 do {
53579 res |= code & 1;
53580 code >>>= 1;
53581 res <<= 1;
53582 } while (--len > 0);
53583 return res >>> 1;
53584}
53585
53586
53587/* ===========================================================================
53588 * Flush the bit buffer, keeping at most 7 bits in it.
53589 */
53590function bi_flush(s) {
53591 if (s.bi_valid === 16) {
53592 put_short(s, s.bi_buf);
53593 s.bi_buf = 0;
53594 s.bi_valid = 0;
53595
53596 } else if (s.bi_valid >= 8) {
53597 s.pending_buf[s.pending++] = s.bi_buf & 0xff;
53598 s.bi_buf >>= 8;
53599 s.bi_valid -= 8;
53600 }
53601}
53602
53603
53604/* ===========================================================================
53605 * Compute the optimal bit lengths for a tree and update the total bit length
53606 * for the current block.
53607 * IN assertion: the fields freq and dad are set, heap[heap_max] and
53608 * above are the tree nodes sorted by increasing frequency.
53609 * OUT assertions: the field len is set to the optimal bit length, the
53610 * array bl_count contains the frequencies for each bit length.
53611 * The length opt_len is updated; static_len is also updated if stree is
53612 * not null.
53613 */
53614function gen_bitlen(s, desc)
53615// deflate_state *s;
53616// tree_desc *desc; /* the tree descriptor */
53617{
53618 var tree = desc.dyn_tree;
53619 var max_code = desc.max_code;
53620 var stree = desc.stat_desc.static_tree;
53621 var has_stree = desc.stat_desc.has_stree;
53622 var extra = desc.stat_desc.extra_bits;
53623 var base = desc.stat_desc.extra_base;
53624 var max_length = desc.stat_desc.max_length;
53625 var h; /* heap index */
53626 var n, m; /* iterate over the tree elements */
53627 var bits; /* bit length */
53628 var xbits; /* extra bits */
53629 var f; /* frequency */
53630 var overflow = 0; /* number of elements with bit length too large */
53631
53632 for (bits = 0; bits <= MAX_BITS; bits++) {
53633 s.bl_count[bits] = 0;
53634 }
53635
53636 /* In a first pass, compute the optimal bit lengths (which may
53637 * overflow in the case of the bit length tree).
53638 */
53639 tree[s.heap[s.heap_max] * 2 + 1]/*.Len*/ = 0; /* root of the heap */
53640
53641 for (h = s.heap_max + 1; h < HEAP_SIZE; h++) {
53642 n = s.heap[h];
53643 bits = tree[tree[n * 2 + 1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1;
53644 if (bits > max_length) {
53645 bits = max_length;
53646 overflow++;
53647 }
53648 tree[n * 2 + 1]/*.Len*/ = bits;
53649 /* We overwrite tree[n].Dad which is no longer needed */
53650
53651 if (n > max_code) { continue; } /* not a leaf node */
53652
53653 s.bl_count[bits]++;
53654 xbits = 0;
53655 if (n >= base) {
53656 xbits = extra[n - base];
53657 }
53658 f = tree[n * 2]/*.Freq*/;
53659 s.opt_len += f * (bits + xbits);
53660 if (has_stree) {
53661 s.static_len += f * (stree[n * 2 + 1]/*.Len*/ + xbits);
53662 }
53663 }
53664 if (overflow === 0) { return; }
53665
53666 // Trace((stderr,"\nbit length overflow\n"));
53667 /* This happens for example on obj2 and pic of the Calgary corpus */
53668
53669 /* Find the first bit length which could increase: */
53670 do {
53671 bits = max_length - 1;
53672 while (s.bl_count[bits] === 0) { bits--; }
53673 s.bl_count[bits]--; /* move one leaf down the tree */
53674 s.bl_count[bits + 1] += 2; /* move one overflow item as its brother */
53675 s.bl_count[max_length]--;
53676 /* The brother of the overflow item also moves one step up,
53677 * but this does not affect bl_count[max_length]
53678 */
53679 overflow -= 2;
53680 } while (overflow > 0);
53681
53682 /* Now recompute all bit lengths, scanning in increasing frequency.
53683 * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
53684 * lengths instead of fixing only the wrong ones. This idea is taken
53685 * from 'ar' written by Haruhiko Okumura.)
53686 */
53687 for (bits = max_length; bits !== 0; bits--) {
53688 n = s.bl_count[bits];
53689 while (n !== 0) {
53690 m = s.heap[--h];
53691 if (m > max_code) { continue; }
53692 if (tree[m * 2 + 1]/*.Len*/ !== bits) {
53693 // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
53694 s.opt_len += (bits - tree[m * 2 + 1]/*.Len*/) * tree[m * 2]/*.Freq*/;
53695 tree[m * 2 + 1]/*.Len*/ = bits;
53696 }
53697 n--;
53698 }
53699 }
53700}
53701
53702
53703/* ===========================================================================
53704 * Generate the codes for a given tree and bit counts (which need not be
53705 * optimal).
53706 * IN assertion: the array bl_count contains the bit length statistics for
53707 * the given tree and the field len is set for all tree elements.
53708 * OUT assertion: the field code is set for all tree elements of non
53709 * zero code length.
53710 */
53711function gen_codes(tree, max_code, bl_count)
53712// ct_data *tree; /* the tree to decorate */
53713// int max_code; /* largest code with non zero frequency */
53714// ushf *bl_count; /* number of codes at each bit length */
53715{
53716 var next_code = new Array(MAX_BITS + 1); /* next code value for each bit length */
53717 var code = 0; /* running code value */
53718 var bits; /* bit index */
53719 var n; /* code index */
53720
53721 /* The distribution counts are first used to generate the code values
53722 * without bit reversal.
53723 */
53724 for (bits = 1; bits <= MAX_BITS; bits++) {
53725 next_code[bits] = code = (code + bl_count[bits - 1]) << 1;
53726 }
53727 /* Check that the bit counts in bl_count are consistent. The last code
53728 * must be all ones.
53729 */
53730 //Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
53731 // "inconsistent bit counts");
53732 //Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
53733
53734 for (n = 0; n <= max_code; n++) {
53735 var len = tree[n * 2 + 1]/*.Len*/;
53736 if (len === 0) { continue; }
53737 /* Now reverse the bits */
53738 tree[n * 2]/*.Code*/ = bi_reverse(next_code[len]++, len);
53739
53740 //Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
53741 // n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
53742 }
53743}
53744
53745
53746/* ===========================================================================
53747 * Initialize the various 'constant' tables.
53748 */
53749function tr_static_init() {
53750 var n; /* iterates over tree elements */
53751 var bits; /* bit counter */
53752 var length; /* length value */
53753 var code; /* code value */
53754 var dist; /* distance index */
53755 var bl_count = new Array(MAX_BITS + 1);
53756 /* number of codes at each bit length for an optimal tree */
53757
53758 // do check in _tr_init()
53759 //if (static_init_done) return;
53760
53761 /* For some embedded targets, global variables are not initialized: */
53762/*#ifdef NO_INIT_GLOBAL_POINTERS
53763 static_l_desc.static_tree = static_ltree;
53764 static_l_desc.extra_bits = extra_lbits;
53765 static_d_desc.static_tree = static_dtree;
53766 static_d_desc.extra_bits = extra_dbits;
53767 static_bl_desc.extra_bits = extra_blbits;
53768#endif*/
53769
53770 /* Initialize the mapping length (0..255) -> length code (0..28) */
53771 length = 0;
53772 for (code = 0; code < LENGTH_CODES - 1; code++) {
53773 base_length[code] = length;
53774 for (n = 0; n < (1 << extra_lbits[code]); n++) {
53775 _length_code[length++] = code;
53776 }
53777 }
53778 //Assert (length == 256, "tr_static_init: length != 256");
53779 /* Note that the length 255 (match length 258) can be represented
53780 * in two different ways: code 284 + 5 bits or code 285, so we
53781 * overwrite length_code[255] to use the best encoding:
53782 */
53783 _length_code[length - 1] = code;
53784
53785 /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
53786 dist = 0;
53787 for (code = 0; code < 16; code++) {
53788 base_dist[code] = dist;
53789 for (n = 0; n < (1 << extra_dbits[code]); n++) {
53790 _dist_code[dist++] = code;
53791 }
53792 }
53793 //Assert (dist == 256, "tr_static_init: dist != 256");
53794 dist >>= 7; /* from now on, all distances are divided by 128 */
53795 for (; code < D_CODES; code++) {
53796 base_dist[code] = dist << 7;
53797 for (n = 0; n < (1 << (extra_dbits[code] - 7)); n++) {
53798 _dist_code[256 + dist++] = code;
53799 }
53800 }
53801 //Assert (dist == 256, "tr_static_init: 256+dist != 512");
53802
53803 /* Construct the codes of the static literal tree */
53804 for (bits = 0; bits <= MAX_BITS; bits++) {
53805 bl_count[bits] = 0;
53806 }
53807
53808 n = 0;
53809 while (n <= 143) {
53810 static_ltree[n * 2 + 1]/*.Len*/ = 8;
53811 n++;
53812 bl_count[8]++;
53813 }
53814 while (n <= 255) {
53815 static_ltree[n * 2 + 1]/*.Len*/ = 9;
53816 n++;
53817 bl_count[9]++;
53818 }
53819 while (n <= 279) {
53820 static_ltree[n * 2 + 1]/*.Len*/ = 7;
53821 n++;
53822 bl_count[7]++;
53823 }
53824 while (n <= 287) {
53825 static_ltree[n * 2 + 1]/*.Len*/ = 8;
53826 n++;
53827 bl_count[8]++;
53828 }
53829 /* Codes 286 and 287 do not exist, but we must include them in the
53830 * tree construction to get a canonical Huffman tree (longest code
53831 * all ones)
53832 */
53833 gen_codes(static_ltree, L_CODES + 1, bl_count);
53834
53835 /* The static distance tree is trivial: */
53836 for (n = 0; n < D_CODES; n++) {
53837 static_dtree[n * 2 + 1]/*.Len*/ = 5;
53838 static_dtree[n * 2]/*.Code*/ = bi_reverse(n, 5);
53839 }
53840
53841 // Now data ready and we can init static trees
53842 static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS + 1, L_CODES, MAX_BITS);
53843 static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS);
53844 static_bl_desc = new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS);
53845
53846 //static_init_done = true;
53847}
53848
53849
53850/* ===========================================================================
53851 * Initialize a new block.
53852 */
53853function init_block(s) {
53854 var n; /* iterates over tree elements */
53855
53856 /* Initialize the trees. */
53857 for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n * 2]/*.Freq*/ = 0; }
53858 for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n * 2]/*.Freq*/ = 0; }
53859 for (n = 0; n < BL_CODES; n++) { s.bl_tree[n * 2]/*.Freq*/ = 0; }
53860
53861 s.dyn_ltree[END_BLOCK * 2]/*.Freq*/ = 1;
53862 s.opt_len = s.static_len = 0;
53863 s.last_lit = s.matches = 0;
53864}
53865
53866
53867/* ===========================================================================
53868 * Flush the bit buffer and align the output on a byte boundary
53869 */
53870function bi_windup(s)
53871{
53872 if (s.bi_valid > 8) {
53873 put_short(s, s.bi_buf);
53874 } else if (s.bi_valid > 0) {
53875 //put_byte(s, (Byte)s->bi_buf);
53876 s.pending_buf[s.pending++] = s.bi_buf;
53877 }
53878 s.bi_buf = 0;
53879 s.bi_valid = 0;
53880}
53881
53882/* ===========================================================================
53883 * Copy a stored block, storing first the length and its
53884 * one's complement if requested.
53885 */
53886function copy_block(s, buf, len, header)
53887//DeflateState *s;
53888//charf *buf; /* the input data */
53889//unsigned len; /* its length */
53890//int header; /* true if block header must be written */
53891{
53892 bi_windup(s); /* align on byte boundary */
53893
53894 if (header) {
53895 put_short(s, len);
53896 put_short(s, ~len);
53897 }
53898// while (len--) {
53899// put_byte(s, *buf++);
53900// }
53901 utils.arraySet(s.pending_buf, s.window, buf, len, s.pending);
53902 s.pending += len;
53903}
53904
53905/* ===========================================================================
53906 * Compares to subtrees, using the tree depth as tie breaker when
53907 * the subtrees have equal frequency. This minimizes the worst case length.
53908 */
53909function smaller(tree, n, m, depth) {
53910 var _n2 = n * 2;
53911 var _m2 = m * 2;
53912 return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ ||
53913 (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m]));
53914}
53915
53916/* ===========================================================================
53917 * Restore the heap property by moving down the tree starting at node k,
53918 * exchanging a node with the smallest of its two sons if necessary, stopping
53919 * when the heap property is re-established (each father smaller than its
53920 * two sons).
53921 */
53922function pqdownheap(s, tree, k)
53923// deflate_state *s;
53924// ct_data *tree; /* the tree to restore */
53925// int k; /* node to move down */
53926{
53927 var v = s.heap[k];
53928 var j = k << 1; /* left son of k */
53929 while (j <= s.heap_len) {
53930 /* Set j to the smallest of the two sons: */
53931 if (j < s.heap_len &&
53932 smaller(tree, s.heap[j + 1], s.heap[j], s.depth)) {
53933 j++;
53934 }
53935 /* Exit if v is smaller than both sons */
53936 if (smaller(tree, v, s.heap[j], s.depth)) { break; }
53937
53938 /* Exchange v with the smallest son */
53939 s.heap[k] = s.heap[j];
53940 k = j;
53941
53942 /* And continue down the tree, setting j to the left son of k */
53943 j <<= 1;
53944 }
53945 s.heap[k] = v;
53946}
53947
53948
53949// inlined manually
53950// var SMALLEST = 1;
53951
53952/* ===========================================================================
53953 * Send the block data compressed using the given Huffman trees
53954 */
53955function compress_block(s, ltree, dtree)
53956// deflate_state *s;
53957// const ct_data *ltree; /* literal tree */
53958// const ct_data *dtree; /* distance tree */
53959{
53960 var dist; /* distance of matched string */
53961 var lc; /* match length or unmatched char (if dist == 0) */
53962 var lx = 0; /* running index in l_buf */
53963 var code; /* the code to send */
53964 var extra; /* number of extra bits to send */
53965
53966 if (s.last_lit !== 0) {
53967 do {
53968 dist = (s.pending_buf[s.d_buf + lx * 2] << 8) | (s.pending_buf[s.d_buf + lx * 2 + 1]);
53969 lc = s.pending_buf[s.l_buf + lx];
53970 lx++;
53971
53972 if (dist === 0) {
53973 send_code(s, lc, ltree); /* send a literal byte */
53974 //Tracecv(isgraph(lc), (stderr," '%c' ", lc));
53975 } else {
53976 /* Here, lc is the match length - MIN_MATCH */
53977 code = _length_code[lc];
53978 send_code(s, code + LITERALS + 1, ltree); /* send the length code */
53979 extra = extra_lbits[code];
53980 if (extra !== 0) {
53981 lc -= base_length[code];
53982 send_bits(s, lc, extra); /* send the extra length bits */
53983 }
53984 dist--; /* dist is now the match distance - 1 */
53985 code = d_code(dist);
53986 //Assert (code < D_CODES, "bad d_code");
53987
53988 send_code(s, code, dtree); /* send the distance code */
53989 extra = extra_dbits[code];
53990 if (extra !== 0) {
53991 dist -= base_dist[code];
53992 send_bits(s, dist, extra); /* send the extra distance bits */
53993 }
53994 } /* literal or match pair ? */
53995
53996 /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
53997 //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
53998 // "pendingBuf overflow");
53999
54000 } while (lx < s.last_lit);
54001 }
54002
54003 send_code(s, END_BLOCK, ltree);
54004}
54005
54006
54007/* ===========================================================================
54008 * Construct one Huffman tree and assigns the code bit strings and lengths.
54009 * Update the total bit length for the current block.
54010 * IN assertion: the field freq is set for all tree elements.
54011 * OUT assertions: the fields len and code are set to the optimal bit length
54012 * and corresponding code. The length opt_len is updated; static_len is
54013 * also updated if stree is not null. The field max_code is set.
54014 */
54015function build_tree(s, desc)
54016// deflate_state *s;
54017// tree_desc *desc; /* the tree descriptor */
54018{
54019 var tree = desc.dyn_tree;
54020 var stree = desc.stat_desc.static_tree;
54021 var has_stree = desc.stat_desc.has_stree;
54022 var elems = desc.stat_desc.elems;
54023 var n, m; /* iterate over heap elements */
54024 var max_code = -1; /* largest code with non zero frequency */
54025 var node; /* new node being created */
54026
54027 /* Construct the initial heap, with least frequent element in
54028 * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
54029 * heap[0] is not used.
54030 */
54031 s.heap_len = 0;
54032 s.heap_max = HEAP_SIZE;
54033
54034 for (n = 0; n < elems; n++) {
54035 if (tree[n * 2]/*.Freq*/ !== 0) {
54036 s.heap[++s.heap_len] = max_code = n;
54037 s.depth[n] = 0;
54038
54039 } else {
54040 tree[n * 2 + 1]/*.Len*/ = 0;
54041 }
54042 }
54043
54044 /* The pkzip format requires that at least one distance code exists,
54045 * and that at least one bit should be sent even if there is only one
54046 * possible code. So to avoid special checks later on we force at least
54047 * two codes of non zero frequency.
54048 */
54049 while (s.heap_len < 2) {
54050 node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0);
54051 tree[node * 2]/*.Freq*/ = 1;
54052 s.depth[node] = 0;
54053 s.opt_len--;
54054
54055 if (has_stree) {
54056 s.static_len -= stree[node * 2 + 1]/*.Len*/;
54057 }
54058 /* node is 0 or 1 so it does not have extra bits */
54059 }
54060 desc.max_code = max_code;
54061
54062 /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
54063 * establish sub-heaps of increasing lengths:
54064 */
54065 for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); }
54066
54067 /* Construct the Huffman tree by repeatedly combining the least two
54068 * frequent nodes.
54069 */
54070 node = elems; /* next internal node of the tree */
54071 do {
54072 //pqremove(s, tree, n); /* n = node of least frequency */
54073 /*** pqremove ***/
54074 n = s.heap[1/*SMALLEST*/];
54075 s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--];
54076 pqdownheap(s, tree, 1/*SMALLEST*/);
54077 /***/
54078
54079 m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */
54080
54081 s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */
54082 s.heap[--s.heap_max] = m;
54083
54084 /* Create a new node father of n and m */
54085 tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/;
54086 s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;
54087 tree[n * 2 + 1]/*.Dad*/ = tree[m * 2 + 1]/*.Dad*/ = node;
54088
54089 /* and insert the new node in the heap */
54090 s.heap[1/*SMALLEST*/] = node++;
54091 pqdownheap(s, tree, 1/*SMALLEST*/);
54092
54093 } while (s.heap_len >= 2);
54094
54095 s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/];
54096
54097 /* At this point, the fields freq and dad are set. We can now
54098 * generate the bit lengths.
54099 */
54100 gen_bitlen(s, desc);
54101
54102 /* The field len is now set, we can generate the bit codes */
54103 gen_codes(tree, max_code, s.bl_count);
54104}
54105
54106
54107/* ===========================================================================
54108 * Scan a literal or distance tree to determine the frequencies of the codes
54109 * in the bit length tree.
54110 */
54111function scan_tree(s, tree, max_code)
54112// deflate_state *s;
54113// ct_data *tree; /* the tree to be scanned */
54114// int max_code; /* and its largest code of non zero frequency */
54115{
54116 var n; /* iterates over all tree elements */
54117 var prevlen = -1; /* last emitted length */
54118 var curlen; /* length of current code */
54119
54120 var nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */
54121
54122 var count = 0; /* repeat count of the current code */
54123 var max_count = 7; /* max repeat count */
54124 var min_count = 4; /* min repeat count */
54125
54126 if (nextlen === 0) {
54127 max_count = 138;
54128 min_count = 3;
54129 }
54130 tree[(max_code + 1) * 2 + 1]/*.Len*/ = 0xffff; /* guard */
54131
54132 for (n = 0; n <= max_code; n++) {
54133 curlen = nextlen;
54134 nextlen = tree[(n + 1) * 2 + 1]/*.Len*/;
54135
54136 if (++count < max_count && curlen === nextlen) {
54137 continue;
54138
54139 } else if (count < min_count) {
54140 s.bl_tree[curlen * 2]/*.Freq*/ += count;
54141
54142 } else if (curlen !== 0) {
54143
54144 if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; }
54145 s.bl_tree[REP_3_6 * 2]/*.Freq*/++;
54146
54147 } else if (count <= 10) {
54148 s.bl_tree[REPZ_3_10 * 2]/*.Freq*/++;
54149
54150 } else {
54151 s.bl_tree[REPZ_11_138 * 2]/*.Freq*/++;
54152 }
54153
54154 count = 0;
54155 prevlen = curlen;
54156
54157 if (nextlen === 0) {
54158 max_count = 138;
54159 min_count = 3;
54160
54161 } else if (curlen === nextlen) {
54162 max_count = 6;
54163 min_count = 3;
54164
54165 } else {
54166 max_count = 7;
54167 min_count = 4;
54168 }
54169 }
54170}
54171
54172
54173/* ===========================================================================
54174 * Send a literal or distance tree in compressed form, using the codes in
54175 * bl_tree.
54176 */
54177function send_tree(s, tree, max_code)
54178// deflate_state *s;
54179// ct_data *tree; /* the tree to be scanned */
54180// int max_code; /* and its largest code of non zero frequency */
54181{
54182 var n; /* iterates over all tree elements */
54183 var prevlen = -1; /* last emitted length */
54184 var curlen; /* length of current code */
54185
54186 var nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */
54187
54188 var count = 0; /* repeat count of the current code */
54189 var max_count = 7; /* max repeat count */
54190 var min_count = 4; /* min repeat count */
54191
54192 /* tree[max_code+1].Len = -1; */ /* guard already set */
54193 if (nextlen === 0) {
54194 max_count = 138;
54195 min_count = 3;
54196 }
54197
54198 for (n = 0; n <= max_code; n++) {
54199 curlen = nextlen;
54200 nextlen = tree[(n + 1) * 2 + 1]/*.Len*/;
54201
54202 if (++count < max_count && curlen === nextlen) {
54203 continue;
54204
54205 } else if (count < min_count) {
54206 do { send_code(s, curlen, s.bl_tree); } while (--count !== 0);
54207
54208 } else if (curlen !== 0) {
54209 if (curlen !== prevlen) {
54210 send_code(s, curlen, s.bl_tree);
54211 count--;
54212 }
54213 //Assert(count >= 3 && count <= 6, " 3_6?");
54214 send_code(s, REP_3_6, s.bl_tree);
54215 send_bits(s, count - 3, 2);
54216
54217 } else if (count <= 10) {
54218 send_code(s, REPZ_3_10, s.bl_tree);
54219 send_bits(s, count - 3, 3);
54220
54221 } else {
54222 send_code(s, REPZ_11_138, s.bl_tree);
54223 send_bits(s, count - 11, 7);
54224 }
54225
54226 count = 0;
54227 prevlen = curlen;
54228 if (nextlen === 0) {
54229 max_count = 138;
54230 min_count = 3;
54231
54232 } else if (curlen === nextlen) {
54233 max_count = 6;
54234 min_count = 3;
54235
54236 } else {
54237 max_count = 7;
54238 min_count = 4;
54239 }
54240 }
54241}
54242
54243
54244/* ===========================================================================
54245 * Construct the Huffman tree for the bit lengths and return the index in
54246 * bl_order of the last bit length code to send.
54247 */
54248function build_bl_tree(s) {
54249 var max_blindex; /* index of last bit length code of non zero freq */
54250
54251 /* Determine the bit length frequencies for literal and distance trees */
54252 scan_tree(s, s.dyn_ltree, s.l_desc.max_code);
54253 scan_tree(s, s.dyn_dtree, s.d_desc.max_code);
54254
54255 /* Build the bit length tree: */
54256 build_tree(s, s.bl_desc);
54257 /* opt_len now includes the length of the tree representations, except
54258 * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
54259 */
54260
54261 /* Determine the number of bit length codes to send. The pkzip format
54262 * requires that at least 4 bit length codes be sent. (appnote.txt says
54263 * 3 but the actual value used is 4.)
54264 */
54265 for (max_blindex = BL_CODES - 1; max_blindex >= 3; max_blindex--) {
54266 if (s.bl_tree[bl_order[max_blindex] * 2 + 1]/*.Len*/ !== 0) {
54267 break;
54268 }
54269 }
54270 /* Update opt_len to include the bit length tree and counts */
54271 s.opt_len += 3 * (max_blindex + 1) + 5 + 5 + 4;
54272 //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
54273 // s->opt_len, s->static_len));
54274
54275 return max_blindex;
54276}
54277
54278
54279/* ===========================================================================
54280 * Send the header for a block using dynamic Huffman trees: the counts, the
54281 * lengths of the bit length codes, the literal tree and the distance tree.
54282 * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
54283 */
54284function send_all_trees(s, lcodes, dcodes, blcodes)
54285// deflate_state *s;
54286// int lcodes, dcodes, blcodes; /* number of codes for each tree */
54287{
54288 var rank; /* index in bl_order */
54289
54290 //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
54291 //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
54292 // "too many codes");
54293 //Tracev((stderr, "\nbl counts: "));
54294 send_bits(s, lcodes - 257, 5); /* not +255 as stated in appnote.txt */
54295 send_bits(s, dcodes - 1, 5);
54296 send_bits(s, blcodes - 4, 4); /* not -3 as stated in appnote.txt */
54297 for (rank = 0; rank < blcodes; rank++) {
54298 //Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
54299 send_bits(s, s.bl_tree[bl_order[rank] * 2 + 1]/*.Len*/, 3);
54300 }
54301 //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
54302
54303 send_tree(s, s.dyn_ltree, lcodes - 1); /* literal tree */
54304 //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
54305
54306 send_tree(s, s.dyn_dtree, dcodes - 1); /* distance tree */
54307 //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
54308}
54309
54310
54311/* ===========================================================================
54312 * Check if the data type is TEXT or BINARY, using the following algorithm:
54313 * - TEXT if the two conditions below are satisfied:
54314 * a) There are no non-portable control characters belonging to the
54315 * "black list" (0..6, 14..25, 28..31).
54316 * b) There is at least one printable character belonging to the
54317 * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
54318 * - BINARY otherwise.
54319 * - The following partially-portable control characters form a
54320 * "gray list" that is ignored in this detection algorithm:
54321 * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
54322 * IN assertion: the fields Freq of dyn_ltree are set.
54323 */
54324function detect_data_type(s) {
54325 /* black_mask is the bit mask of black-listed bytes
54326 * set bits 0..6, 14..25, and 28..31
54327 * 0xf3ffc07f = binary 11110011111111111100000001111111
54328 */
54329 var black_mask = 0xf3ffc07f;
54330 var n;
54331
54332 /* Check for non-textual ("black-listed") bytes. */
54333 for (n = 0; n <= 31; n++, black_mask >>>= 1) {
54334 if ((black_mask & 1) && (s.dyn_ltree[n * 2]/*.Freq*/ !== 0)) {
54335 return Z_BINARY;
54336 }
54337 }
54338
54339 /* Check for textual ("white-listed") bytes. */
54340 if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 ||
54341 s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) {
54342 return Z_TEXT;
54343 }
54344 for (n = 32; n < LITERALS; n++) {
54345 if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {
54346 return Z_TEXT;
54347 }
54348 }
54349
54350 /* There are no "black-listed" or "white-listed" bytes:
54351 * this stream either is empty or has tolerated ("gray-listed") bytes only.
54352 */
54353 return Z_BINARY;
54354}
54355
54356
54357var static_init_done = false;
54358
54359/* ===========================================================================
54360 * Initialize the tree data structures for a new zlib stream.
54361 */
54362function _tr_init(s)
54363{
54364
54365 if (!static_init_done) {
54366 tr_static_init();
54367 static_init_done = true;
54368 }
54369
54370 s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc);
54371 s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc);
54372 s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);
54373
54374 s.bi_buf = 0;
54375 s.bi_valid = 0;
54376
54377 /* Initialize the first block of the first file: */
54378 init_block(s);
54379}
54380
54381
54382/* ===========================================================================
54383 * Send a stored block
54384 */
54385function _tr_stored_block(s, buf, stored_len, last)
54386//DeflateState *s;
54387//charf *buf; /* input block */
54388//ulg stored_len; /* length of input block */
54389//int last; /* one if this is the last block for a file */
54390{
54391 send_bits(s, (STORED_BLOCK << 1) + (last ? 1 : 0), 3); /* send block type */
54392 copy_block(s, buf, stored_len, true); /* with header */
54393}
54394
54395
54396/* ===========================================================================
54397 * Send one empty static block to give enough lookahead for inflate.
54398 * This takes 10 bits, of which 7 may remain in the bit buffer.
54399 */
54400function _tr_align(s) {
54401 send_bits(s, STATIC_TREES << 1, 3);
54402 send_code(s, END_BLOCK, static_ltree);
54403 bi_flush(s);
54404}
54405
54406
54407/* ===========================================================================
54408 * Determine the best encoding for the current block: dynamic trees, static
54409 * trees or store, and output the encoded block to the zip file.
54410 */
54411function _tr_flush_block(s, buf, stored_len, last)
54412//DeflateState *s;
54413//charf *buf; /* input block, or NULL if too old */
54414//ulg stored_len; /* length of input block */
54415//int last; /* one if this is the last block for a file */
54416{
54417 var opt_lenb, static_lenb; /* opt_len and static_len in bytes */
54418 var max_blindex = 0; /* index of last bit length code of non zero freq */
54419
54420 /* Build the Huffman trees unless a stored block is forced */
54421 if (s.level > 0) {
54422
54423 /* Check if the file is binary or text */
54424 if (s.strm.data_type === Z_UNKNOWN) {
54425 s.strm.data_type = detect_data_type(s);
54426 }
54427
54428 /* Construct the literal and distance trees */
54429 build_tree(s, s.l_desc);
54430 // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
54431 // s->static_len));
54432
54433 build_tree(s, s.d_desc);
54434 // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
54435 // s->static_len));
54436 /* At this point, opt_len and static_len are the total bit lengths of
54437 * the compressed block data, excluding the tree representations.
54438 */
54439
54440 /* Build the bit length tree for the above two trees, and get the index
54441 * in bl_order of the last bit length code to send.
54442 */
54443 max_blindex = build_bl_tree(s);
54444
54445 /* Determine the best encoding. Compute the block lengths in bytes. */
54446 opt_lenb = (s.opt_len + 3 + 7) >>> 3;
54447 static_lenb = (s.static_len + 3 + 7) >>> 3;
54448
54449 // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
54450 // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
54451 // s->last_lit));
54452
54453 if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; }
54454
54455 } else {
54456 // Assert(buf != (char*)0, "lost buf");
54457 opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
54458 }
54459
54460 if ((stored_len + 4 <= opt_lenb) && (buf !== -1)) {
54461 /* 4: two words for the lengths */
54462
54463 /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
54464 * Otherwise we can't have processed more than WSIZE input bytes since
54465 * the last block flush, because compression would have been
54466 * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
54467 * transform a block into a stored block.
54468 */
54469 _tr_stored_block(s, buf, stored_len, last);
54470
54471 } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) {
54472
54473 send_bits(s, (STATIC_TREES << 1) + (last ? 1 : 0), 3);
54474 compress_block(s, static_ltree, static_dtree);
54475
54476 } else {
54477 send_bits(s, (DYN_TREES << 1) + (last ? 1 : 0), 3);
54478 send_all_trees(s, s.l_desc.max_code + 1, s.d_desc.max_code + 1, max_blindex + 1);
54479 compress_block(s, s.dyn_ltree, s.dyn_dtree);
54480 }
54481 // Assert (s->compressed_len == s->bits_sent, "bad compressed size");
54482 /* The above check is made mod 2^32, for files larger than 512 MB
54483 * and uLong implemented on 32 bits.
54484 */
54485 init_block(s);
54486
54487 if (last) {
54488 bi_windup(s);
54489 }
54490 // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
54491 // s->compressed_len-7*last));
54492}
54493
54494/* ===========================================================================
54495 * Save the match info and tally the frequency counts. Return true if
54496 * the current block must be flushed.
54497 */
54498function _tr_tally(s, dist, lc)
54499// deflate_state *s;
54500// unsigned dist; /* distance of matched string */
54501// unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */
54502{
54503 //var out_length, in_length, dcode;
54504
54505 s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff;
54506 s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff;
54507
54508 s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff;
54509 s.last_lit++;
54510
54511 if (dist === 0) {
54512 /* lc is the unmatched char */
54513 s.dyn_ltree[lc * 2]/*.Freq*/++;
54514 } else {
54515 s.matches++;
54516 /* Here, lc is the match length - MIN_MATCH */
54517 dist--; /* dist = match distance - 1 */
54518 //Assert((ush)dist < (ush)MAX_DIST(s) &&
54519 // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
54520 // (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
54521
54522 s.dyn_ltree[(_length_code[lc] + LITERALS + 1) * 2]/*.Freq*/++;
54523 s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++;
54524 }
54525
54526// (!) This block is disabled in zlib defaults,
54527// don't enable it for binary compatibility
54528
54529//#ifdef TRUNCATE_BLOCK
54530// /* Try to guess if it is profitable to stop the current block here */
54531// if ((s.last_lit & 0x1fff) === 0 && s.level > 2) {
54532// /* Compute an upper bound for the compressed length */
54533// out_length = s.last_lit*8;
54534// in_length = s.strstart - s.block_start;
54535//
54536// for (dcode = 0; dcode < D_CODES; dcode++) {
54537// out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]);
54538// }
54539// out_length >>>= 3;
54540// //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
54541// // s->last_lit, in_length, out_length,
54542// // 100L - out_length*100L/in_length));
54543// if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) {
54544// return true;
54545// }
54546// }
54547//#endif
54548
54549 return (s.last_lit === s.lit_bufsize - 1);
54550 /* We avoid equality with lit_bufsize because of wraparound at 64K
54551 * on 16 bit machines and because stored blocks are restricted to
54552 * 64K-1 bytes.
54553 */
54554}
54555
54556exports._tr_init = _tr_init;
54557exports._tr_stored_block = _tr_stored_block;
54558exports._tr_flush_block = _tr_flush_block;
54559exports._tr_tally = _tr_tally;
54560exports._tr_align = _tr_align;
54561
54562},{"../utils/common":241}],251:[function(require,module,exports){
54563'use strict';
54564
54565// (C) 1995-2013 Jean-loup Gailly and Mark Adler
54566// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
54567//
54568// This software is provided 'as-is', without any express or implied
54569// warranty. In no event will the authors be held liable for any damages
54570// arising from the use of this software.
54571//
54572// Permission is granted to anyone to use this software for any purpose,
54573// including commercial applications, and to alter it and redistribute it
54574// freely, subject to the following restrictions:
54575//
54576// 1. The origin of this software must not be misrepresented; you must not
54577// claim that you wrote the original software. If you use this software
54578// in a product, an acknowledgment in the product documentation would be
54579// appreciated but is not required.
54580// 2. Altered source versions must be plainly marked as such, and must not be
54581// misrepresented as being the original software.
54582// 3. This notice may not be removed or altered from any source distribution.
54583
54584function ZStream() {
54585 /* next input byte */
54586 this.input = null; // JS specific, because we have no pointers
54587 this.next_in = 0;
54588 /* number of bytes available at input */
54589 this.avail_in = 0;
54590 /* total number of input bytes read so far */
54591 this.total_in = 0;
54592 /* next output byte should be put there */
54593 this.output = null; // JS specific, because we have no pointers
54594 this.next_out = 0;
54595 /* remaining free space at output */
54596 this.avail_out = 0;
54597 /* total number of bytes output so far */
54598 this.total_out = 0;
54599 /* last error message, NULL if no error */
54600 this.msg = ''/*Z_NULL*/;
54601 /* not visible by applications */
54602 this.state = null;
54603 /* best guess about the data type: binary or text */
54604 this.data_type = 2/*Z_UNKNOWN*/;
54605 /* adler32 value of the uncompressed data */
54606 this.adler = 0;
54607}
54608
54609module.exports = ZStream;
54610
54611},{}],252:[function(require,module,exports){
54612module.exports={"2.16.840.1.101.3.4.1.1": "aes-128-ecb",
54613"2.16.840.1.101.3.4.1.2": "aes-128-cbc",
54614"2.16.840.1.101.3.4.1.3": "aes-128-ofb",
54615"2.16.840.1.101.3.4.1.4": "aes-128-cfb",
54616"2.16.840.1.101.3.4.1.21": "aes-192-ecb",
54617"2.16.840.1.101.3.4.1.22": "aes-192-cbc",
54618"2.16.840.1.101.3.4.1.23": "aes-192-ofb",
54619"2.16.840.1.101.3.4.1.24": "aes-192-cfb",
54620"2.16.840.1.101.3.4.1.41": "aes-256-ecb",
54621"2.16.840.1.101.3.4.1.42": "aes-256-cbc",
54622"2.16.840.1.101.3.4.1.43": "aes-256-ofb",
54623"2.16.840.1.101.3.4.1.44": "aes-256-cfb"
54624}
54625},{}],253:[function(require,module,exports){
54626// from https://github.com/indutny/self-signed/blob/gh-pages/lib/asn1.js
54627// Fedor, you are amazing.
54628'use strict'
54629
54630var asn1 = require('asn1.js')
54631
54632exports.certificate = require('./certificate')
54633
54634var RSAPrivateKey = asn1.define('RSAPrivateKey', function () {
54635 this.seq().obj(
54636 this.key('version').int(),
54637 this.key('modulus').int(),
54638 this.key('publicExponent').int(),
54639 this.key('privateExponent').int(),
54640 this.key('prime1').int(),
54641 this.key('prime2').int(),
54642 this.key('exponent1').int(),
54643 this.key('exponent2').int(),
54644 this.key('coefficient').int()
54645 )
54646})
54647exports.RSAPrivateKey = RSAPrivateKey
54648
54649var RSAPublicKey = asn1.define('RSAPublicKey', function () {
54650 this.seq().obj(
54651 this.key('modulus').int(),
54652 this.key('publicExponent').int()
54653 )
54654})
54655exports.RSAPublicKey = RSAPublicKey
54656
54657var PublicKey = asn1.define('SubjectPublicKeyInfo', function () {
54658 this.seq().obj(
54659 this.key('algorithm').use(AlgorithmIdentifier),
54660 this.key('subjectPublicKey').bitstr()
54661 )
54662})
54663exports.PublicKey = PublicKey
54664
54665var AlgorithmIdentifier = asn1.define('AlgorithmIdentifier', function () {
54666 this.seq().obj(
54667 this.key('algorithm').objid(),
54668 this.key('none').null_().optional(),
54669 this.key('curve').objid().optional(),
54670 this.key('params').seq().obj(
54671 this.key('p').int(),
54672 this.key('q').int(),
54673 this.key('g').int()
54674 ).optional()
54675 )
54676})
54677
54678var PrivateKeyInfo = asn1.define('PrivateKeyInfo', function () {
54679 this.seq().obj(
54680 this.key('version').int(),
54681 this.key('algorithm').use(AlgorithmIdentifier),
54682 this.key('subjectPrivateKey').octstr()
54683 )
54684})
54685exports.PrivateKey = PrivateKeyInfo
54686var EncryptedPrivateKeyInfo = asn1.define('EncryptedPrivateKeyInfo', function () {
54687 this.seq().obj(
54688 this.key('algorithm').seq().obj(
54689 this.key('id').objid(),
54690 this.key('decrypt').seq().obj(
54691 this.key('kde').seq().obj(
54692 this.key('id').objid(),
54693 this.key('kdeparams').seq().obj(
54694 this.key('salt').octstr(),
54695 this.key('iters').int()
54696 )
54697 ),
54698 this.key('cipher').seq().obj(
54699 this.key('algo').objid(),
54700 this.key('iv').octstr()
54701 )
54702 )
54703 ),
54704 this.key('subjectPrivateKey').octstr()
54705 )
54706})
54707
54708exports.EncryptedPrivateKey = EncryptedPrivateKeyInfo
54709
54710var DSAPrivateKey = asn1.define('DSAPrivateKey', function () {
54711 this.seq().obj(
54712 this.key('version').int(),
54713 this.key('p').int(),
54714 this.key('q').int(),
54715 this.key('g').int(),
54716 this.key('pub_key').int(),
54717 this.key('priv_key').int()
54718 )
54719})
54720exports.DSAPrivateKey = DSAPrivateKey
54721
54722exports.DSAparam = asn1.define('DSAparam', function () {
54723 this.int()
54724})
54725
54726var ECPrivateKey = asn1.define('ECPrivateKey', function () {
54727 this.seq().obj(
54728 this.key('version').int(),
54729 this.key('privateKey').octstr(),
54730 this.key('parameters').optional().explicit(0).use(ECParameters),
54731 this.key('publicKey').optional().explicit(1).bitstr()
54732 )
54733})
54734exports.ECPrivateKey = ECPrivateKey
54735
54736var ECParameters = asn1.define('ECParameters', function () {
54737 this.choice({
54738 namedCurve: this.objid()
54739 })
54740})
54741
54742exports.signature = asn1.define('signature', function () {
54743 this.seq().obj(
54744 this.key('r').int(),
54745 this.key('s').int()
54746 )
54747})
54748
54749},{"./certificate":254,"asn1.js":47}],254:[function(require,module,exports){
54750// from https://github.com/Rantanen/node-dtls/blob/25a7dc861bda38cfeac93a723500eea4f0ac2e86/Certificate.js
54751// thanks to @Rantanen
54752
54753'use strict'
54754
54755var asn = require('asn1.js')
54756
54757var Time = asn.define('Time', function () {
54758 this.choice({
54759 utcTime: this.utctime(),
54760 generalTime: this.gentime()
54761 })
54762})
54763
54764var AttributeTypeValue = asn.define('AttributeTypeValue', function () {
54765 this.seq().obj(
54766 this.key('type').objid(),
54767 this.key('value').any()
54768 )
54769})
54770
54771var AlgorithmIdentifier = asn.define('AlgorithmIdentifier', function () {
54772 this.seq().obj(
54773 this.key('algorithm').objid(),
54774 this.key('parameters').optional(),
54775 this.key('curve').objid().optional()
54776 )
54777})
54778
54779var SubjectPublicKeyInfo = asn.define('SubjectPublicKeyInfo', function () {
54780 this.seq().obj(
54781 this.key('algorithm').use(AlgorithmIdentifier),
54782 this.key('subjectPublicKey').bitstr()
54783 )
54784})
54785
54786var RelativeDistinguishedName = asn.define('RelativeDistinguishedName', function () {
54787 this.setof(AttributeTypeValue)
54788})
54789
54790var RDNSequence = asn.define('RDNSequence', function () {
54791 this.seqof(RelativeDistinguishedName)
54792})
54793
54794var Name = asn.define('Name', function () {
54795 this.choice({
54796 rdnSequence: this.use(RDNSequence)
54797 })
54798})
54799
54800var Validity = asn.define('Validity', function () {
54801 this.seq().obj(
54802 this.key('notBefore').use(Time),
54803 this.key('notAfter').use(Time)
54804 )
54805})
54806
54807var Extension = asn.define('Extension', function () {
54808 this.seq().obj(
54809 this.key('extnID').objid(),
54810 this.key('critical').bool().def(false),
54811 this.key('extnValue').octstr()
54812 )
54813})
54814
54815var TBSCertificate = asn.define('TBSCertificate', function () {
54816 this.seq().obj(
54817 this.key('version').explicit(0).int().optional(),
54818 this.key('serialNumber').int(),
54819 this.key('signature').use(AlgorithmIdentifier),
54820 this.key('issuer').use(Name),
54821 this.key('validity').use(Validity),
54822 this.key('subject').use(Name),
54823 this.key('subjectPublicKeyInfo').use(SubjectPublicKeyInfo),
54824 this.key('issuerUniqueID').implicit(1).bitstr().optional(),
54825 this.key('subjectUniqueID').implicit(2).bitstr().optional(),
54826 this.key('extensions').explicit(3).seqof(Extension).optional()
54827 )
54828})
54829
54830var X509Certificate = asn.define('X509Certificate', function () {
54831 this.seq().obj(
54832 this.key('tbsCertificate').use(TBSCertificate),
54833 this.key('signatureAlgorithm').use(AlgorithmIdentifier),
54834 this.key('signatureValue').bitstr()
54835 )
54836})
54837
54838module.exports = X509Certificate
54839
54840},{"asn1.js":47}],255:[function(require,module,exports){
54841// adapted from https://github.com/apatil/pemstrip
54842var findProc = /Proc-Type: 4,ENCRYPTED[\n\r]+DEK-Info: AES-((?:128)|(?:192)|(?:256))-CBC,([0-9A-H]+)[\n\r]+([0-9A-z\n\r\+\/\=]+)[\n\r]+/m
54843var startRegex = /^-----BEGIN ((?:.*? KEY)|CERTIFICATE)-----/m
54844var fullRegex = /^-----BEGIN ((?:.*? KEY)|CERTIFICATE)-----([0-9A-z\n\r\+\/\=]+)-----END \1-----$/m
54845var evp = require('evp_bytestokey')
54846var ciphers = require('browserify-aes')
54847var Buffer = require('safe-buffer').Buffer
54848module.exports = function (okey, password) {
54849 var key = okey.toString()
54850 var match = key.match(findProc)
54851 var decrypted
54852 if (!match) {
54853 var match2 = key.match(fullRegex)
54854 decrypted = new Buffer(match2[2].replace(/[\r\n]/g, ''), 'base64')
54855 } else {
54856 var suite = 'aes' + match[1]
54857 var iv = Buffer.from(match[2], 'hex')
54858 var cipherText = Buffer.from(match[3].replace(/[\r\n]/g, ''), 'base64')
54859 var cipherKey = evp(password, iv.slice(0, 8), parseInt(match[1], 10)).key
54860 var out = []
54861 var cipher = ciphers.createDecipheriv(suite, cipherKey, iv)
54862 out.push(cipher.update(cipherText))
54863 out.push(cipher.final())
54864 decrypted = Buffer.concat(out)
54865 }
54866 var tag = key.match(startRegex)[1]
54867 return {
54868 tag: tag,
54869 data: decrypted
54870 }
54871}
54872
54873},{"browserify-aes":85,"evp_bytestokey":160,"safe-buffer":325}],256:[function(require,module,exports){
54874var asn1 = require('./asn1')
54875var aesid = require('./aesid.json')
54876var fixProc = require('./fixProc')
54877var ciphers = require('browserify-aes')
54878var compat = require('pbkdf2')
54879var Buffer = require('safe-buffer').Buffer
54880module.exports = parseKeys
54881
54882function parseKeys (buffer) {
54883 var password
54884 if (typeof buffer === 'object' && !Buffer.isBuffer(buffer)) {
54885 password = buffer.passphrase
54886 buffer = buffer.key
54887 }
54888 if (typeof buffer === 'string') {
54889 buffer = Buffer.from(buffer)
54890 }
54891
54892 var stripped = fixProc(buffer, password)
54893
54894 var type = stripped.tag
54895 var data = stripped.data
54896 var subtype, ndata
54897 switch (type) {
54898 case 'CERTIFICATE':
54899 ndata = asn1.certificate.decode(data, 'der').tbsCertificate.subjectPublicKeyInfo
54900 // falls through
54901 case 'PUBLIC KEY':
54902 if (!ndata) {
54903 ndata = asn1.PublicKey.decode(data, 'der')
54904 }
54905 subtype = ndata.algorithm.algorithm.join('.')
54906 switch (subtype) {
54907 case '1.2.840.113549.1.1.1':
54908 return asn1.RSAPublicKey.decode(ndata.subjectPublicKey.data, 'der')
54909 case '1.2.840.10045.2.1':
54910 ndata.subjectPrivateKey = ndata.subjectPublicKey
54911 return {
54912 type: 'ec',
54913 data: ndata
54914 }
54915 case '1.2.840.10040.4.1':
54916 ndata.algorithm.params.pub_key = asn1.DSAparam.decode(ndata.subjectPublicKey.data, 'der')
54917 return {
54918 type: 'dsa',
54919 data: ndata.algorithm.params
54920 }
54921 default: throw new Error('unknown key id ' + subtype)
54922 }
54923 throw new Error('unknown key type ' + type)
54924 case 'ENCRYPTED PRIVATE KEY':
54925 data = asn1.EncryptedPrivateKey.decode(data, 'der')
54926 data = decrypt(data, password)
54927 // falls through
54928 case 'PRIVATE KEY':
54929 ndata = asn1.PrivateKey.decode(data, 'der')
54930 subtype = ndata.algorithm.algorithm.join('.')
54931 switch (subtype) {
54932 case '1.2.840.113549.1.1.1':
54933 return asn1.RSAPrivateKey.decode(ndata.subjectPrivateKey, 'der')
54934 case '1.2.840.10045.2.1':
54935 return {
54936 curve: ndata.algorithm.curve,
54937 privateKey: asn1.ECPrivateKey.decode(ndata.subjectPrivateKey, 'der').privateKey
54938 }
54939 case '1.2.840.10040.4.1':
54940 ndata.algorithm.params.priv_key = asn1.DSAparam.decode(ndata.subjectPrivateKey, 'der')
54941 return {
54942 type: 'dsa',
54943 params: ndata.algorithm.params
54944 }
54945 default: throw new Error('unknown key id ' + subtype)
54946 }
54947 throw new Error('unknown key type ' + type)
54948 case 'RSA PUBLIC KEY':
54949 return asn1.RSAPublicKey.decode(data, 'der')
54950 case 'RSA PRIVATE KEY':
54951 return asn1.RSAPrivateKey.decode(data, 'der')
54952 case 'DSA PRIVATE KEY':
54953 return {
54954 type: 'dsa',
54955 params: asn1.DSAPrivateKey.decode(data, 'der')
54956 }
54957 case 'EC PRIVATE KEY':
54958 data = asn1.ECPrivateKey.decode(data, 'der')
54959 return {
54960 curve: data.parameters.value,
54961 privateKey: data.privateKey
54962 }
54963 default: throw new Error('unknown key type ' + type)
54964 }
54965}
54966parseKeys.signature = asn1.signature
54967function decrypt (data, password) {
54968 var salt = data.algorithm.decrypt.kde.kdeparams.salt
54969 var iters = parseInt(data.algorithm.decrypt.kde.kdeparams.iters.toString(), 10)
54970 var algo = aesid[data.algorithm.decrypt.cipher.algo.join('.')]
54971 var iv = data.algorithm.decrypt.cipher.iv
54972 var cipherText = data.subjectPrivateKey
54973 var keylen = parseInt(algo.split('-')[1], 10) / 8
54974 var key = compat.pbkdf2Sync(password, salt, iters, keylen, 'sha1')
54975 var cipher = ciphers.createDecipheriv(algo, key, iv)
54976 var out = []
54977 out.push(cipher.update(cipherText))
54978 out.push(cipher.final())
54979 return Buffer.concat(out)
54980}
54981
54982},{"./aesid.json":252,"./asn1":253,"./fixProc":255,"browserify-aes":85,"pbkdf2":258,"safe-buffer":325}],257:[function(require,module,exports){
54983(function (process){
54984// .dirname, .basename, and .extname methods are extracted from Node.js v8.11.1,
54985// backported and transplited with Babel, with backwards-compat fixes
54986
54987// Copyright Joyent, Inc. and other Node contributors.
54988//
54989// Permission is hereby granted, free of charge, to any person obtaining a
54990// copy of this software and associated documentation files (the
54991// "Software"), to deal in the Software without restriction, including
54992// without limitation the rights to use, copy, modify, merge, publish,
54993// distribute, sublicense, and/or sell copies of the Software, and to permit
54994// persons to whom the Software is furnished to do so, subject to the
54995// following conditions:
54996//
54997// The above copyright notice and this permission notice shall be included
54998// in all copies or substantial portions of the Software.
54999//
55000// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
55001// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
55002// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
55003// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
55004// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
55005// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
55006// USE OR OTHER DEALINGS IN THE SOFTWARE.
55007
55008// resolves . and .. elements in a path array with directory names there
55009// must be no slashes, empty elements, or device names (c:\) in the array
55010// (so also no leading and trailing slashes - it does not distinguish
55011// relative and absolute paths)
55012function normalizeArray(parts, allowAboveRoot) {
55013 // if the path tries to go above the root, `up` ends up > 0
55014 var up = 0;
55015 for (var i = parts.length - 1; i >= 0; i--) {
55016 var last = parts[i];
55017 if (last === '.') {
55018 parts.splice(i, 1);
55019 } else if (last === '..') {
55020 parts.splice(i, 1);
55021 up++;
55022 } else if (up) {
55023 parts.splice(i, 1);
55024 up--;
55025 }
55026 }
55027
55028 // if the path is allowed to go above the root, restore leading ..s
55029 if (allowAboveRoot) {
55030 for (; up--; up) {
55031 parts.unshift('..');
55032 }
55033 }
55034
55035 return parts;
55036}
55037
55038// path.resolve([from ...], to)
55039// posix version
55040exports.resolve = function() {
55041 var resolvedPath = '',
55042 resolvedAbsolute = false;
55043
55044 for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) {
55045 var path = (i >= 0) ? arguments[i] : process.cwd();
55046
55047 // Skip empty and invalid entries
55048 if (typeof path !== 'string') {
55049 throw new TypeError('Arguments to path.resolve must be strings');
55050 } else if (!path) {
55051 continue;
55052 }
55053
55054 resolvedPath = path + '/' + resolvedPath;
55055 resolvedAbsolute = path.charAt(0) === '/';
55056 }
55057
55058 // At this point the path should be resolved to a full absolute path, but
55059 // handle relative paths to be safe (might happen when process.cwd() fails)
55060
55061 // Normalize the path
55062 resolvedPath = normalizeArray(filter(resolvedPath.split('/'), function(p) {
55063 return !!p;
55064 }), !resolvedAbsolute).join('/');
55065
55066 return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.';
55067};
55068
55069// path.normalize(path)
55070// posix version
55071exports.normalize = function(path) {
55072 var isAbsolute = exports.isAbsolute(path),
55073 trailingSlash = substr(path, -1) === '/';
55074
55075 // Normalize the path
55076 path = normalizeArray(filter(path.split('/'), function(p) {
55077 return !!p;
55078 }), !isAbsolute).join('/');
55079
55080 if (!path && !isAbsolute) {
55081 path = '.';
55082 }
55083 if (path && trailingSlash) {
55084 path += '/';
55085 }
55086
55087 return (isAbsolute ? '/' : '') + path;
55088};
55089
55090// posix version
55091exports.isAbsolute = function(path) {
55092 return path.charAt(0) === '/';
55093};
55094
55095// posix version
55096exports.join = function() {
55097 var paths = Array.prototype.slice.call(arguments, 0);
55098 return exports.normalize(filter(paths, function(p, index) {
55099 if (typeof p !== 'string') {
55100 throw new TypeError('Arguments to path.join must be strings');
55101 }
55102 return p;
55103 }).join('/'));
55104};
55105
55106
55107// path.relative(from, to)
55108// posix version
55109exports.relative = function(from, to) {
55110 from = exports.resolve(from).substr(1);
55111 to = exports.resolve(to).substr(1);
55112
55113 function trim(arr) {
55114 var start = 0;
55115 for (; start < arr.length; start++) {
55116 if (arr[start] !== '') break;
55117 }
55118
55119 var end = arr.length - 1;
55120 for (; end >= 0; end--) {
55121 if (arr[end] !== '') break;
55122 }
55123
55124 if (start > end) return [];
55125 return arr.slice(start, end - start + 1);
55126 }
55127
55128 var fromParts = trim(from.split('/'));
55129 var toParts = trim(to.split('/'));
55130
55131 var length = Math.min(fromParts.length, toParts.length);
55132 var samePartsLength = length;
55133 for (var i = 0; i < length; i++) {
55134 if (fromParts[i] !== toParts[i]) {
55135 samePartsLength = i;
55136 break;
55137 }
55138 }
55139
55140 var outputParts = [];
55141 for (var i = samePartsLength; i < fromParts.length; i++) {
55142 outputParts.push('..');
55143 }
55144
55145 outputParts = outputParts.concat(toParts.slice(samePartsLength));
55146
55147 return outputParts.join('/');
55148};
55149
55150exports.sep = '/';
55151exports.delimiter = ':';
55152
55153exports.dirname = function (path) {
55154 if (typeof path !== 'string') path = path + '';
55155 if (path.length === 0) return '.';
55156 var code = path.charCodeAt(0);
55157 var hasRoot = code === 47 /*/*/;
55158 var end = -1;
55159 var matchedSlash = true;
55160 for (var i = path.length - 1; i >= 1; --i) {
55161 code = path.charCodeAt(i);
55162 if (code === 47 /*/*/) {
55163 if (!matchedSlash) {
55164 end = i;
55165 break;
55166 }
55167 } else {
55168 // We saw the first non-path separator
55169 matchedSlash = false;
55170 }
55171 }
55172
55173 if (end === -1) return hasRoot ? '/' : '.';
55174 if (hasRoot && end === 1) {
55175 // return '//';
55176 // Backwards-compat fix:
55177 return '/';
55178 }
55179 return path.slice(0, end);
55180};
55181
55182function basename(path) {
55183 if (typeof path !== 'string') path = path + '';
55184
55185 var start = 0;
55186 var end = -1;
55187 var matchedSlash = true;
55188 var i;
55189
55190 for (i = path.length - 1; i >= 0; --i) {
55191 if (path.charCodeAt(i) === 47 /*/*/) {
55192 // If we reached a path separator that was not part of a set of path
55193 // separators at the end of the string, stop now
55194 if (!matchedSlash) {
55195 start = i + 1;
55196 break;
55197 }
55198 } else if (end === -1) {
55199 // We saw the first non-path separator, mark this as the end of our
55200 // path component
55201 matchedSlash = false;
55202 end = i + 1;
55203 }
55204 }
55205
55206 if (end === -1) return '';
55207 return path.slice(start, end);
55208}
55209
55210// Uses a mixed approach for backwards-compatibility, as ext behavior changed
55211// in new Node.js versions, so only basename() above is backported here
55212exports.basename = function (path, ext) {
55213 var f = basename(path);
55214 if (ext && f.substr(-1 * ext.length) === ext) {
55215 f = f.substr(0, f.length - ext.length);
55216 }
55217 return f;
55218};
55219
55220exports.extname = function (path) {
55221 if (typeof path !== 'string') path = path + '';
55222 var startDot = -1;
55223 var startPart = 0;
55224 var end = -1;
55225 var matchedSlash = true;
55226 // Track the state of characters (if any) we see before our first dot and
55227 // after any path separator we find
55228 var preDotState = 0;
55229 for (var i = path.length - 1; i >= 0; --i) {
55230 var code = path.charCodeAt(i);
55231 if (code === 47 /*/*/) {
55232 // If we reached a path separator that was not part of a set of path
55233 // separators at the end of the string, stop now
55234 if (!matchedSlash) {
55235 startPart = i + 1;
55236 break;
55237 }
55238 continue;
55239 }
55240 if (end === -1) {
55241 // We saw the first non-path separator, mark this as the end of our
55242 // extension
55243 matchedSlash = false;
55244 end = i + 1;
55245 }
55246 if (code === 46 /*.*/) {
55247 // If this is our first dot, mark it as the start of our extension
55248 if (startDot === -1)
55249 startDot = i;
55250 else if (preDotState !== 1)
55251 preDotState = 1;
55252 } else if (startDot !== -1) {
55253 // We saw a non-dot and non-path separator before our dot, so we should
55254 // have a good chance at having a non-empty extension
55255 preDotState = -1;
55256 }
55257 }
55258
55259 if (startDot === -1 || end === -1 ||
55260 // We saw a non-dot character immediately before the dot
55261 preDotState === 0 ||
55262 // The (right-most) trimmed path component is exactly '..'
55263 preDotState === 1 && startDot === end - 1 && startDot === startPart + 1) {
55264 return '';
55265 }
55266 return path.slice(startDot, end);
55267};
55268
55269function filter (xs, f) {
55270 if (xs.filter) return xs.filter(f);
55271 var res = [];
55272 for (var i = 0; i < xs.length; i++) {
55273 if (f(xs[i], i, xs)) res.push(xs[i]);
55274 }
55275 return res;
55276}
55277
55278// String.prototype.substr - negative index don't work in IE8
55279var substr = 'ab'.substr(-1) === 'b'
55280 ? function (str, start, len) { return str.substr(start, len) }
55281 : function (str, start, len) {
55282 if (start < 0) start = str.length + start;
55283 return str.substr(start, len);
55284 }
55285;
55286
55287}).call(this,require('_process'))
55288},{"_process":265}],258:[function(require,module,exports){
55289exports.pbkdf2 = require('./lib/async')
55290exports.pbkdf2Sync = require('./lib/sync')
55291
55292},{"./lib/async":259,"./lib/sync":262}],259:[function(require,module,exports){
55293(function (process,global){
55294var checkParameters = require('./precondition')
55295var defaultEncoding = require('./default-encoding')
55296var sync = require('./sync')
55297var Buffer = require('safe-buffer').Buffer
55298
55299var ZERO_BUF
55300var subtle = global.crypto && global.crypto.subtle
55301var toBrowser = {
55302 'sha': 'SHA-1',
55303 'sha-1': 'SHA-1',
55304 'sha1': 'SHA-1',
55305 'sha256': 'SHA-256',
55306 'sha-256': 'SHA-256',
55307 'sha384': 'SHA-384',
55308 'sha-384': 'SHA-384',
55309 'sha-512': 'SHA-512',
55310 'sha512': 'SHA-512'
55311}
55312var checks = []
55313function checkNative (algo) {
55314 if (global.process && !global.process.browser) {
55315 return Promise.resolve(false)
55316 }
55317 if (!subtle || !subtle.importKey || !subtle.deriveBits) {
55318 return Promise.resolve(false)
55319 }
55320 if (checks[algo] !== undefined) {
55321 return checks[algo]
55322 }
55323 ZERO_BUF = ZERO_BUF || Buffer.alloc(8)
55324 var prom = browserPbkdf2(ZERO_BUF, ZERO_BUF, 10, 128, algo)
55325 .then(function () {
55326 return true
55327 }).catch(function () {
55328 return false
55329 })
55330 checks[algo] = prom
55331 return prom
55332}
55333
55334function browserPbkdf2 (password, salt, iterations, length, algo) {
55335 return subtle.importKey(
55336 'raw', password, {name: 'PBKDF2'}, false, ['deriveBits']
55337 ).then(function (key) {
55338 return subtle.deriveBits({
55339 name: 'PBKDF2',
55340 salt: salt,
55341 iterations: iterations,
55342 hash: {
55343 name: algo
55344 }
55345 }, key, length << 3)
55346 }).then(function (res) {
55347 return Buffer.from(res)
55348 })
55349}
55350
55351function resolvePromise (promise, callback) {
55352 promise.then(function (out) {
55353 process.nextTick(function () {
55354 callback(null, out)
55355 })
55356 }, function (e) {
55357 process.nextTick(function () {
55358 callback(e)
55359 })
55360 })
55361}
55362module.exports = function (password, salt, iterations, keylen, digest, callback) {
55363 if (typeof digest === 'function') {
55364 callback = digest
55365 digest = undefined
55366 }
55367
55368 digest = digest || 'sha1'
55369 var algo = toBrowser[digest.toLowerCase()]
55370
55371 if (!algo || typeof global.Promise !== 'function') {
55372 return process.nextTick(function () {
55373 var out
55374 try {
55375 out = sync(password, salt, iterations, keylen, digest)
55376 } catch (e) {
55377 return callback(e)
55378 }
55379 callback(null, out)
55380 })
55381 }
55382
55383 checkParameters(password, salt, iterations, keylen)
55384 if (typeof callback !== 'function') throw new Error('No callback provided to pbkdf2')
55385 if (!Buffer.isBuffer(password)) password = Buffer.from(password, defaultEncoding)
55386 if (!Buffer.isBuffer(salt)) salt = Buffer.from(salt, defaultEncoding)
55387
55388 resolvePromise(checkNative(algo).then(function (resp) {
55389 if (resp) return browserPbkdf2(password, salt, iterations, keylen, algo)
55390
55391 return sync(password, salt, iterations, keylen, digest)
55392 }), callback)
55393}
55394
55395}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
55396},{"./default-encoding":260,"./precondition":261,"./sync":262,"_process":265,"safe-buffer":325}],260:[function(require,module,exports){
55397(function (process){
55398var defaultEncoding
55399/* istanbul ignore next */
55400if (process.browser) {
55401 defaultEncoding = 'utf-8'
55402} else {
55403 var pVersionMajor = parseInt(process.version.split('.')[0].slice(1), 10)
55404
55405 defaultEncoding = pVersionMajor >= 6 ? 'utf-8' : 'binary'
55406}
55407module.exports = defaultEncoding
55408
55409}).call(this,require('_process'))
55410},{"_process":265}],261:[function(require,module,exports){
55411(function (Buffer){
55412var MAX_ALLOC = Math.pow(2, 30) - 1 // default in iojs
55413
55414function checkBuffer (buf, name) {
55415 if (typeof buf !== 'string' && !Buffer.isBuffer(buf)) {
55416 throw new TypeError(name + ' must be a buffer or string')
55417 }
55418}
55419
55420module.exports = function (password, salt, iterations, keylen) {
55421 checkBuffer(password, 'Password')
55422 checkBuffer(salt, 'Salt')
55423
55424 if (typeof iterations !== 'number') {
55425 throw new TypeError('Iterations not a number')
55426 }
55427
55428 if (iterations < 0) {
55429 throw new TypeError('Bad iterations')
55430 }
55431
55432 if (typeof keylen !== 'number') {
55433 throw new TypeError('Key length not a number')
55434 }
55435
55436 if (keylen < 0 || keylen > MAX_ALLOC || keylen !== keylen) { /* eslint no-self-compare: 0 */
55437 throw new TypeError('Bad key length')
55438 }
55439}
55440
55441}).call(this,{"isBuffer":require("../../is-buffer/index.js")})
55442},{"../../is-buffer/index.js":211}],262:[function(require,module,exports){
55443var md5 = require('create-hash/md5')
55444var RIPEMD160 = require('ripemd160')
55445var sha = require('sha.js')
55446
55447var checkParameters = require('./precondition')
55448var defaultEncoding = require('./default-encoding')
55449var Buffer = require('safe-buffer').Buffer
55450var ZEROS = Buffer.alloc(128)
55451var sizes = {
55452 md5: 16,
55453 sha1: 20,
55454 sha224: 28,
55455 sha256: 32,
55456 sha384: 48,
55457 sha512: 64,
55458 rmd160: 20,
55459 ripemd160: 20
55460}
55461
55462function Hmac (alg, key, saltLen) {
55463 var hash = getDigest(alg)
55464 var blocksize = (alg === 'sha512' || alg === 'sha384') ? 128 : 64
55465
55466 if (key.length > blocksize) {
55467 key = hash(key)
55468 } else if (key.length < blocksize) {
55469 key = Buffer.concat([key, ZEROS], blocksize)
55470 }
55471
55472 var ipad = Buffer.allocUnsafe(blocksize + sizes[alg])
55473 var opad = Buffer.allocUnsafe(blocksize + sizes[alg])
55474 for (var i = 0; i < blocksize; i++) {
55475 ipad[i] = key[i] ^ 0x36
55476 opad[i] = key[i] ^ 0x5C
55477 }
55478
55479 var ipad1 = Buffer.allocUnsafe(blocksize + saltLen + 4)
55480 ipad.copy(ipad1, 0, 0, blocksize)
55481 this.ipad1 = ipad1
55482 this.ipad2 = ipad
55483 this.opad = opad
55484 this.alg = alg
55485 this.blocksize = blocksize
55486 this.hash = hash
55487 this.size = sizes[alg]
55488}
55489
55490Hmac.prototype.run = function (data, ipad) {
55491 data.copy(ipad, this.blocksize)
55492 var h = this.hash(ipad)
55493 h.copy(this.opad, this.blocksize)
55494 return this.hash(this.opad)
55495}
55496
55497function getDigest (alg) {
55498 function shaFunc (data) {
55499 return sha(alg).update(data).digest()
55500 }
55501 function rmd160Func (data) {
55502 return new RIPEMD160().update(data).digest()
55503 }
55504
55505 if (alg === 'rmd160' || alg === 'ripemd160') return rmd160Func
55506 if (alg === 'md5') return md5
55507 return shaFunc
55508}
55509
55510function pbkdf2 (password, salt, iterations, keylen, digest) {
55511 checkParameters(password, salt, iterations, keylen)
55512
55513 if (!Buffer.isBuffer(password)) password = Buffer.from(password, defaultEncoding)
55514 if (!Buffer.isBuffer(salt)) salt = Buffer.from(salt, defaultEncoding)
55515
55516 digest = digest || 'sha1'
55517
55518 var hmac = new Hmac(digest, password, salt.length)
55519
55520 var DK = Buffer.allocUnsafe(keylen)
55521 var block1 = Buffer.allocUnsafe(salt.length + 4)
55522 salt.copy(block1, 0, 0, salt.length)
55523
55524 var destPos = 0
55525 var hLen = sizes[digest]
55526 var l = Math.ceil(keylen / hLen)
55527
55528 for (var i = 1; i <= l; i++) {
55529 block1.writeUInt32BE(i, salt.length)
55530
55531 var T = hmac.run(block1, hmac.ipad1)
55532 var U = T
55533
55534 for (var j = 1; j < iterations; j++) {
55535 U = hmac.run(U, hmac.ipad2)
55536 for (var k = 0; k < hLen; k++) T[k] ^= U[k]
55537 }
55538
55539 T.copy(DK, destPos)
55540 destPos += hLen
55541 }
55542
55543 return DK
55544}
55545
55546module.exports = pbkdf2
55547
55548},{"./default-encoding":260,"./precondition":261,"create-hash/md5":123,"ripemd160":324,"safe-buffer":325,"sha.js":328}],263:[function(require,module,exports){
55549(function (process){
55550// Generated by CoffeeScript 1.12.2
55551(function() {
55552 var getNanoSeconds, hrtime, loadTime, moduleLoadTime, nodeLoadTime, upTime;
55553
55554 if ((typeof performance !== "undefined" && performance !== null) && performance.now) {
55555 module.exports = function() {
55556 return performance.now();
55557 };
55558 } else if ((typeof process !== "undefined" && process !== null) && process.hrtime) {
55559 module.exports = function() {
55560 return (getNanoSeconds() - nodeLoadTime) / 1e6;
55561 };
55562 hrtime = process.hrtime;
55563 getNanoSeconds = function() {
55564 var hr;
55565 hr = hrtime();
55566 return hr[0] * 1e9 + hr[1];
55567 };
55568 moduleLoadTime = getNanoSeconds();
55569 upTime = process.uptime() * 1e9;
55570 nodeLoadTime = moduleLoadTime - upTime;
55571 } else if (Date.now) {
55572 module.exports = function() {
55573 return Date.now() - loadTime;
55574 };
55575 loadTime = Date.now();
55576 } else {
55577 module.exports = function() {
55578 return new Date().getTime() - loadTime;
55579 };
55580 loadTime = new Date().getTime();
55581 }
55582
55583}).call(this);
55584
55585
55586
55587}).call(this,require('_process'))
55588},{"_process":265}],264:[function(require,module,exports){
55589(function (process){
55590'use strict';
55591
55592if (!process.version ||
55593 process.version.indexOf('v0.') === 0 ||
55594 process.version.indexOf('v1.') === 0 && process.version.indexOf('v1.8.') !== 0) {
55595 module.exports = { nextTick: nextTick };
55596} else {
55597 module.exports = process
55598}
55599
55600function nextTick(fn, arg1, arg2, arg3) {
55601 if (typeof fn !== 'function') {
55602 throw new TypeError('"callback" argument must be a function');
55603 }
55604 var len = arguments.length;
55605 var args, i;
55606 switch (len) {
55607 case 0:
55608 case 1:
55609 return process.nextTick(fn);
55610 case 2:
55611 return process.nextTick(function afterTickOne() {
55612 fn.call(null, arg1);
55613 });
55614 case 3:
55615 return process.nextTick(function afterTickTwo() {
55616 fn.call(null, arg1, arg2);
55617 });
55618 case 4:
55619 return process.nextTick(function afterTickThree() {
55620 fn.call(null, arg1, arg2, arg3);
55621 });
55622 default:
55623 args = new Array(len - 1);
55624 i = 0;
55625 while (i < args.length) {
55626 args[i++] = arguments[i];
55627 }
55628 return process.nextTick(function afterTick() {
55629 fn.apply(null, args);
55630 });
55631 }
55632}
55633
55634
55635}).call(this,require('_process'))
55636},{"_process":265}],265:[function(require,module,exports){
55637// shim for using process in browser
55638var process = module.exports = {};
55639
55640// cached from whatever global is present so that test runners that stub it
55641// don't break things. But we need to wrap it in a try catch in case it is
55642// wrapped in strict mode code which doesn't define any globals. It's inside a
55643// function because try/catches deoptimize in certain engines.
55644
55645var cachedSetTimeout;
55646var cachedClearTimeout;
55647
55648function defaultSetTimout() {
55649 throw new Error('setTimeout has not been defined');
55650}
55651function defaultClearTimeout () {
55652 throw new Error('clearTimeout has not been defined');
55653}
55654(function () {
55655 try {
55656 if (typeof setTimeout === 'function') {
55657 cachedSetTimeout = setTimeout;
55658 } else {
55659 cachedSetTimeout = defaultSetTimout;
55660 }
55661 } catch (e) {
55662 cachedSetTimeout = defaultSetTimout;
55663 }
55664 try {
55665 if (typeof clearTimeout === 'function') {
55666 cachedClearTimeout = clearTimeout;
55667 } else {
55668 cachedClearTimeout = defaultClearTimeout;
55669 }
55670 } catch (e) {
55671 cachedClearTimeout = defaultClearTimeout;
55672 }
55673} ())
55674function runTimeout(fun) {
55675 if (cachedSetTimeout === setTimeout) {
55676 //normal enviroments in sane situations
55677 return setTimeout(fun, 0);
55678 }
55679 // if setTimeout wasn't available but was latter defined
55680 if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
55681 cachedSetTimeout = setTimeout;
55682 return setTimeout(fun, 0);
55683 }
55684 try {
55685 // when when somebody has screwed with setTimeout but no I.E. maddness
55686 return cachedSetTimeout(fun, 0);
55687 } catch(e){
55688 try {
55689 // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
55690 return cachedSetTimeout.call(null, fun, 0);
55691 } catch(e){
55692 // 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
55693 return cachedSetTimeout.call(this, fun, 0);
55694 }
55695 }
55696
55697
55698}
55699function runClearTimeout(marker) {
55700 if (cachedClearTimeout === clearTimeout) {
55701 //normal enviroments in sane situations
55702 return clearTimeout(marker);
55703 }
55704 // if clearTimeout wasn't available but was latter defined
55705 if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
55706 cachedClearTimeout = clearTimeout;
55707 return clearTimeout(marker);
55708 }
55709 try {
55710 // when when somebody has screwed with setTimeout but no I.E. maddness
55711 return cachedClearTimeout(marker);
55712 } catch (e){
55713 try {
55714 // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
55715 return cachedClearTimeout.call(null, marker);
55716 } catch (e){
55717 // 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.
55718 // Some versions of I.E. have different rules for clearTimeout vs setTimeout
55719 return cachedClearTimeout.call(this, marker);
55720 }
55721 }
55722
55723
55724
55725}
55726var queue = [];
55727var draining = false;
55728var currentQueue;
55729var queueIndex = -1;
55730
55731function cleanUpNextTick() {
55732 if (!draining || !currentQueue) {
55733 return;
55734 }
55735 draining = false;
55736 if (currentQueue.length) {
55737 queue = currentQueue.concat(queue);
55738 } else {
55739 queueIndex = -1;
55740 }
55741 if (queue.length) {
55742 drainQueue();
55743 }
55744}
55745
55746function drainQueue() {
55747 if (draining) {
55748 return;
55749 }
55750 var timeout = runTimeout(cleanUpNextTick);
55751 draining = true;
55752
55753 var len = queue.length;
55754 while(len) {
55755 currentQueue = queue;
55756 queue = [];
55757 while (++queueIndex < len) {
55758 if (currentQueue) {
55759 currentQueue[queueIndex].run();
55760 }
55761 }
55762 queueIndex = -1;
55763 len = queue.length;
55764 }
55765 currentQueue = null;
55766 draining = false;
55767 runClearTimeout(timeout);
55768}
55769
55770process.nextTick = function (fun) {
55771 var args = new Array(arguments.length - 1);
55772 if (arguments.length > 1) {
55773 for (var i = 1; i < arguments.length; i++) {
55774 args[i - 1] = arguments[i];
55775 }
55776 }
55777 queue.push(new Item(fun, args));
55778 if (queue.length === 1 && !draining) {
55779 runTimeout(drainQueue);
55780 }
55781};
55782
55783// v8 likes predictible objects
55784function Item(fun, array) {
55785 this.fun = fun;
55786 this.array = array;
55787}
55788Item.prototype.run = function () {
55789 this.fun.apply(null, this.array);
55790};
55791process.title = 'browser';
55792process.browser = true;
55793process.env = {};
55794process.argv = [];
55795process.version = ''; // empty string to avoid regexp issues
55796process.versions = {};
55797
55798function noop() {}
55799
55800process.on = noop;
55801process.addListener = noop;
55802process.once = noop;
55803process.off = noop;
55804process.removeListener = noop;
55805process.removeAllListeners = noop;
55806process.emit = noop;
55807process.prependListener = noop;
55808process.prependOnceListener = noop;
55809
55810process.listeners = function (name) { return [] }
55811
55812process.binding = function (name) {
55813 throw new Error('process.binding is not supported');
55814};
55815
55816process.cwd = function () { return '/' };
55817process.chdir = function (dir) {
55818 throw new Error('process.chdir is not supported');
55819};
55820process.umask = function() { return 0; };
55821
55822},{}],266:[function(require,module,exports){
55823module.exports=["ac","com.ac","edu.ac","gov.ac","net.ac","mil.ac","org.ac","ad","nom.ad","ae","co.ae","net.ae","org.ae","sch.ae","ac.ae","gov.ae","mil.ae","aero","accident-investigation.aero","accident-prevention.aero","aerobatic.aero","aeroclub.aero","aerodrome.aero","agents.aero","aircraft.aero","airline.aero","airport.aero","air-surveillance.aero","airtraffic.aero","air-traffic-control.aero","ambulance.aero","amusement.aero","association.aero","author.aero","ballooning.aero","broker.aero","caa.aero","cargo.aero","catering.aero","certification.aero","championship.aero","charter.aero","civilaviation.aero","club.aero","conference.aero","consultant.aero","consulting.aero","control.aero","council.aero","crew.aero","design.aero","dgca.aero","educator.aero","emergency.aero","engine.aero","engineer.aero","entertainment.aero","equipment.aero","exchange.aero","express.aero","federation.aero","flight.aero","freight.aero","fuel.aero","gliding.aero","government.aero","groundhandling.aero","group.aero","hanggliding.aero","homebuilt.aero","insurance.aero","journal.aero","journalist.aero","leasing.aero","logistics.aero","magazine.aero","maintenance.aero","media.aero","microlight.aero","modelling.aero","navigation.aero","parachuting.aero","paragliding.aero","passenger-association.aero","pilot.aero","press.aero","production.aero","recreation.aero","repbody.aero","res.aero","research.aero","rotorcraft.aero","safety.aero","scientist.aero","services.aero","show.aero","skydiving.aero","software.aero","student.aero","trader.aero","trading.aero","trainer.aero","union.aero","workinggroup.aero","works.aero","af","gov.af","com.af","org.af","net.af","edu.af","ag","com.ag","org.ag","net.ag","co.ag","nom.ag","ai","off.ai","com.ai","net.ai","org.ai","al","com.al","edu.al","gov.al","mil.al","net.al","org.al","am","ao","ed.ao","gv.ao","og.ao","co.ao","pb.ao","it.ao","aq","ar","com.ar","edu.ar","gob.ar","gov.ar","int.ar","mil.ar","musica.ar","net.ar","org.ar","tur.ar","arpa","e164.arpa","in-addr.arpa","ip6.arpa","iris.arpa","uri.arpa","urn.arpa","as","gov.as","asia","at","ac.at","co.at","gv.at","or.at","au","com.au","net.au","org.au","edu.au","gov.au","asn.au","id.au","info.au","conf.au","oz.au","act.au","nsw.au","nt.au","qld.au","sa.au","tas.au","vic.au","wa.au","act.edu.au","nsw.edu.au","nt.edu.au","qld.edu.au","sa.edu.au","tas.edu.au","vic.edu.au","wa.edu.au","qld.gov.au","sa.gov.au","tas.gov.au","vic.gov.au","wa.gov.au","aw","com.aw","ax","az","com.az","net.az","int.az","gov.az","org.az","edu.az","info.az","pp.az","mil.az","name.az","pro.az","biz.az","ba","com.ba","edu.ba","gov.ba","mil.ba","net.ba","org.ba","bb","biz.bb","co.bb","com.bb","edu.bb","gov.bb","info.bb","net.bb","org.bb","store.bb","tv.bb","*.bd","be","ac.be","bf","gov.bf","bg","a.bg","b.bg","c.bg","d.bg","e.bg","f.bg","g.bg","h.bg","i.bg","j.bg","k.bg","l.bg","m.bg","n.bg","o.bg","p.bg","q.bg","r.bg","s.bg","t.bg","u.bg","v.bg","w.bg","x.bg","y.bg","z.bg","0.bg","1.bg","2.bg","3.bg","4.bg","5.bg","6.bg","7.bg","8.bg","9.bg","bh","com.bh","edu.bh","net.bh","org.bh","gov.bh","bi","co.bi","com.bi","edu.bi","or.bi","org.bi","biz","bj","asso.bj","barreau.bj","gouv.bj","bm","com.bm","edu.bm","gov.bm","net.bm","org.bm","bn","com.bn","edu.bn","gov.bn","net.bn","org.bn","bo","com.bo","edu.bo","gob.bo","int.bo","org.bo","net.bo","mil.bo","tv.bo","web.bo","academia.bo","agro.bo","arte.bo","blog.bo","bolivia.bo","ciencia.bo","cooperativa.bo","democracia.bo","deporte.bo","ecologia.bo","economia.bo","empresa.bo","indigena.bo","industria.bo","info.bo","medicina.bo","movimiento.bo","musica.bo","natural.bo","nombre.bo","noticias.bo","patria.bo","politica.bo","profesional.bo","plurinacional.bo","pueblo.bo","revista.bo","salud.bo","tecnologia.bo","tksat.bo","transporte.bo","wiki.bo","br","9guacu.br","abc.br","adm.br","adv.br","agr.br","aju.br","am.br","anani.br","aparecida.br","arq.br","art.br","ato.br","b.br","barueri.br","belem.br","bhz.br","bio.br","blog.br","bmd.br","boavista.br","bsb.br","campinagrande.br","campinas.br","caxias.br","cim.br","cng.br","cnt.br","com.br","contagem.br","coop.br","cri.br","cuiaba.br","curitiba.br","def.br","ecn.br","eco.br","edu.br","emp.br","eng.br","esp.br","etc.br","eti.br","far.br","feira.br","flog.br","floripa.br","fm.br","fnd.br","fortal.br","fot.br","foz.br","fst.br","g12.br","ggf.br","goiania.br","gov.br","ac.gov.br","al.gov.br","am.gov.br","ap.gov.br","ba.gov.br","ce.gov.br","df.gov.br","es.gov.br","go.gov.br","ma.gov.br","mg.gov.br","ms.gov.br","mt.gov.br","pa.gov.br","pb.gov.br","pe.gov.br","pi.gov.br","pr.gov.br","rj.gov.br","rn.gov.br","ro.gov.br","rr.gov.br","rs.gov.br","sc.gov.br","se.gov.br","sp.gov.br","to.gov.br","gru.br","imb.br","ind.br","inf.br","jab.br","jampa.br","jdf.br","joinville.br","jor.br","jus.br","leg.br","lel.br","londrina.br","macapa.br","maceio.br","manaus.br","maringa.br","mat.br","med.br","mil.br","morena.br","mp.br","mus.br","natal.br","net.br","niteroi.br","*.nom.br","not.br","ntr.br","odo.br","ong.br","org.br","osasco.br","palmas.br","poa.br","ppg.br","pro.br","psc.br","psi.br","pvh.br","qsl.br","radio.br","rec.br","recife.br","ribeirao.br","rio.br","riobranco.br","riopreto.br","salvador.br","sampa.br","santamaria.br","santoandre.br","saobernardo.br","saogonca.br","sjc.br","slg.br","slz.br","sorocaba.br","srv.br","taxi.br","teo.br","the.br","tmp.br","trd.br","tur.br","tv.br","udi.br","vet.br","vix.br","vlog.br","wiki.br","zlg.br","bs","com.bs","net.bs","org.bs","edu.bs","gov.bs","bt","com.bt","edu.bt","gov.bt","net.bt","org.bt","bv","bw","co.bw","org.bw","by","gov.by","mil.by","com.by","of.by","bz","com.bz","net.bz","org.bz","edu.bz","gov.bz","ca","ab.ca","bc.ca","mb.ca","nb.ca","nf.ca","nl.ca","ns.ca","nt.ca","nu.ca","on.ca","pe.ca","qc.ca","sk.ca","yk.ca","gc.ca","cat","cc","cd","gov.cd","cf","cg","ch","ci","org.ci","or.ci","com.ci","co.ci","edu.ci","ed.ci","ac.ci","net.ci","go.ci","asso.ci","aéroport.ci","int.ci","presse.ci","md.ci","gouv.ci","*.ck","!www.ck","cl","gov.cl","gob.cl","co.cl","mil.cl","cm","co.cm","com.cm","gov.cm","net.cm","cn","ac.cn","com.cn","edu.cn","gov.cn","net.cn","org.cn","mil.cn","公司.cn","网络.cn","網絡.cn","ah.cn","bj.cn","cq.cn","fj.cn","gd.cn","gs.cn","gz.cn","gx.cn","ha.cn","hb.cn","he.cn","hi.cn","hl.cn","hn.cn","jl.cn","js.cn","jx.cn","ln.cn","nm.cn","nx.cn","qh.cn","sc.cn","sd.cn","sh.cn","sn.cn","sx.cn","tj.cn","xj.cn","xz.cn","yn.cn","zj.cn","hk.cn","mo.cn","tw.cn","co","arts.co","com.co","edu.co","firm.co","gov.co","info.co","int.co","mil.co","net.co","nom.co","org.co","rec.co","web.co","com","coop","cr","ac.cr","co.cr","ed.cr","fi.cr","go.cr","or.cr","sa.cr","cu","com.cu","edu.cu","org.cu","net.cu","gov.cu","inf.cu","cv","cw","com.cw","edu.cw","net.cw","org.cw","cx","gov.cx","cy","ac.cy","biz.cy","com.cy","ekloges.cy","gov.cy","ltd.cy","name.cy","net.cy","org.cy","parliament.cy","press.cy","pro.cy","tm.cy","cz","de","dj","dk","dm","com.dm","net.dm","org.dm","edu.dm","gov.dm","do","art.do","com.do","edu.do","gob.do","gov.do","mil.do","net.do","org.do","sld.do","web.do","dz","com.dz","org.dz","net.dz","gov.dz","edu.dz","asso.dz","pol.dz","art.dz","ec","com.ec","info.ec","net.ec","fin.ec","k12.ec","med.ec","pro.ec","org.ec","edu.ec","gov.ec","gob.ec","mil.ec","edu","ee","edu.ee","gov.ee","riik.ee","lib.ee","med.ee","com.ee","pri.ee","aip.ee","org.ee","fie.ee","eg","com.eg","edu.eg","eun.eg","gov.eg","mil.eg","name.eg","net.eg","org.eg","sci.eg","*.er","es","com.es","nom.es","org.es","gob.es","edu.es","et","com.et","gov.et","org.et","edu.et","biz.et","name.et","info.et","net.et","eu","fi","aland.fi","*.fj","*.fk","fm","fo","fr","com.fr","asso.fr","nom.fr","prd.fr","presse.fr","tm.fr","aeroport.fr","assedic.fr","avocat.fr","avoues.fr","cci.fr","chambagri.fr","chirurgiens-dentistes.fr","experts-comptables.fr","geometre-expert.fr","gouv.fr","greta.fr","huissier-justice.fr","medecin.fr","notaires.fr","pharmacien.fr","port.fr","veterinaire.fr","ga","gb","gd","ge","com.ge","edu.ge","gov.ge","org.ge","mil.ge","net.ge","pvt.ge","gf","gg","co.gg","net.gg","org.gg","gh","com.gh","edu.gh","gov.gh","org.gh","mil.gh","gi","com.gi","ltd.gi","gov.gi","mod.gi","edu.gi","org.gi","gl","co.gl","com.gl","edu.gl","net.gl","org.gl","gm","gn","ac.gn","com.gn","edu.gn","gov.gn","org.gn","net.gn","gov","gp","com.gp","net.gp","mobi.gp","edu.gp","org.gp","asso.gp","gq","gr","com.gr","edu.gr","net.gr","org.gr","gov.gr","gs","gt","com.gt","edu.gt","gob.gt","ind.gt","mil.gt","net.gt","org.gt","gu","com.gu","edu.gu","gov.gu","guam.gu","info.gu","net.gu","org.gu","web.gu","gw","gy","co.gy","com.gy","edu.gy","gov.gy","net.gy","org.gy","hk","com.hk","edu.hk","gov.hk","idv.hk","net.hk","org.hk","公司.hk","教育.hk","敎育.hk","政府.hk","個人.hk","个人.hk","箇人.hk","網络.hk","网络.hk","组織.hk","網絡.hk","网絡.hk","组织.hk","組織.hk","組织.hk","hm","hn","com.hn","edu.hn","org.hn","net.hn","mil.hn","gob.hn","hr","iz.hr","from.hr","name.hr","com.hr","ht","com.ht","shop.ht","firm.ht","info.ht","adult.ht","net.ht","pro.ht","org.ht","med.ht","art.ht","coop.ht","pol.ht","asso.ht","edu.ht","rel.ht","gouv.ht","perso.ht","hu","co.hu","info.hu","org.hu","priv.hu","sport.hu","tm.hu","2000.hu","agrar.hu","bolt.hu","casino.hu","city.hu","erotica.hu","erotika.hu","film.hu","forum.hu","games.hu","hotel.hu","ingatlan.hu","jogasz.hu","konyvelo.hu","lakas.hu","media.hu","news.hu","reklam.hu","sex.hu","shop.hu","suli.hu","szex.hu","tozsde.hu","utazas.hu","video.hu","id","ac.id","biz.id","co.id","desa.id","go.id","mil.id","my.id","net.id","or.id","ponpes.id","sch.id","web.id","ie","gov.ie","il","ac.il","co.il","gov.il","idf.il","k12.il","muni.il","net.il","org.il","im","ac.im","co.im","com.im","ltd.co.im","net.im","org.im","plc.co.im","tt.im","tv.im","in","co.in","firm.in","net.in","org.in","gen.in","ind.in","nic.in","ac.in","edu.in","res.in","gov.in","mil.in","info","int","eu.int","io","com.io","iq","gov.iq","edu.iq","mil.iq","com.iq","org.iq","net.iq","ir","ac.ir","co.ir","gov.ir","id.ir","net.ir","org.ir","sch.ir","ایران.ir","ايران.ir","is","net.is","com.is","edu.is","gov.is","org.is","int.is","it","gov.it","edu.it","abr.it","abruzzo.it","aosta-valley.it","aostavalley.it","bas.it","basilicata.it","cal.it","calabria.it","cam.it","campania.it","emilia-romagna.it","emiliaromagna.it","emr.it","friuli-v-giulia.it","friuli-ve-giulia.it","friuli-vegiulia.it","friuli-venezia-giulia.it","friuli-veneziagiulia.it","friuli-vgiulia.it","friuliv-giulia.it","friulive-giulia.it","friulivegiulia.it","friulivenezia-giulia.it","friuliveneziagiulia.it","friulivgiulia.it","fvg.it","laz.it","lazio.it","lig.it","liguria.it","lom.it","lombardia.it","lombardy.it","lucania.it","mar.it","marche.it","mol.it","molise.it","piedmont.it","piemonte.it","pmn.it","pug.it","puglia.it","sar.it","sardegna.it","sardinia.it","sic.it","sicilia.it","sicily.it","taa.it","tos.it","toscana.it","trentin-sud-tirol.it","trentin-süd-tirol.it","trentin-sudtirol.it","trentin-südtirol.it","trentin-sued-tirol.it","trentin-suedtirol.it","trentino-a-adige.it","trentino-aadige.it","trentino-alto-adige.it","trentino-altoadige.it","trentino-s-tirol.it","trentino-stirol.it","trentino-sud-tirol.it","trentino-süd-tirol.it","trentino-sudtirol.it","trentino-südtirol.it","trentino-sued-tirol.it","trentino-suedtirol.it","trentino.it","trentinoa-adige.it","trentinoaadige.it","trentinoalto-adige.it","trentinoaltoadige.it","trentinos-tirol.it","trentinostirol.it","trentinosud-tirol.it","trentinosüd-tirol.it","trentinosudtirol.it","trentinosüdtirol.it","trentinosued-tirol.it","trentinosuedtirol.it","trentinsud-tirol.it","trentinsüd-tirol.it","trentinsudtirol.it","trentinsüdtirol.it","trentinsued-tirol.it","trentinsuedtirol.it","tuscany.it","umb.it","umbria.it","val-d-aosta.it","val-daosta.it","vald-aosta.it","valdaosta.it","valle-aosta.it","valle-d-aosta.it","valle-daosta.it","valleaosta.it","valled-aosta.it","valledaosta.it","vallee-aoste.it","vallée-aoste.it","vallee-d-aoste.it","vallée-d-aoste.it","valleeaoste.it","valléeaoste.it","valleedaoste.it","valléedaoste.it","vao.it","vda.it","ven.it","veneto.it","ag.it","agrigento.it","al.it","alessandria.it","alto-adige.it","altoadige.it","an.it","ancona.it","andria-barletta-trani.it","andria-trani-barletta.it","andriabarlettatrani.it","andriatranibarletta.it","ao.it","aosta.it","aoste.it","ap.it","aq.it","aquila.it","ar.it","arezzo.it","ascoli-piceno.it","ascolipiceno.it","asti.it","at.it","av.it","avellino.it","ba.it","balsan-sudtirol.it","balsan-südtirol.it","balsan-suedtirol.it","balsan.it","bari.it","barletta-trani-andria.it","barlettatraniandria.it","belluno.it","benevento.it","bergamo.it","bg.it","bi.it","biella.it","bl.it","bn.it","bo.it","bologna.it","bolzano-altoadige.it","bolzano.it","bozen-sudtirol.it","bozen-südtirol.it","bozen-suedtirol.it","bozen.it","br.it","brescia.it","brindisi.it","bs.it","bt.it","bulsan-sudtirol.it","bulsan-südtirol.it","bulsan-suedtirol.it","bulsan.it","bz.it","ca.it","cagliari.it","caltanissetta.it","campidano-medio.it","campidanomedio.it","campobasso.it","carbonia-iglesias.it","carboniaiglesias.it","carrara-massa.it","carraramassa.it","caserta.it","catania.it","catanzaro.it","cb.it","ce.it","cesena-forli.it","cesena-forlì.it","cesenaforli.it","cesenaforlì.it","ch.it","chieti.it","ci.it","cl.it","cn.it","co.it","como.it","cosenza.it","cr.it","cremona.it","crotone.it","cs.it","ct.it","cuneo.it","cz.it","dell-ogliastra.it","dellogliastra.it","en.it","enna.it","fc.it","fe.it","fermo.it","ferrara.it","fg.it","fi.it","firenze.it","florence.it","fm.it","foggia.it","forli-cesena.it","forlì-cesena.it","forlicesena.it","forlìcesena.it","fr.it","frosinone.it","ge.it","genoa.it","genova.it","go.it","gorizia.it","gr.it","grosseto.it","iglesias-carbonia.it","iglesiascarbonia.it","im.it","imperia.it","is.it","isernia.it","kr.it","la-spezia.it","laquila.it","laspezia.it","latina.it","lc.it","le.it","lecce.it","lecco.it","li.it","livorno.it","lo.it","lodi.it","lt.it","lu.it","lucca.it","macerata.it","mantova.it","massa-carrara.it","massacarrara.it","matera.it","mb.it","mc.it","me.it","medio-campidano.it","mediocampidano.it","messina.it","mi.it","milan.it","milano.it","mn.it","mo.it","modena.it","monza-brianza.it","monza-e-della-brianza.it","monza.it","monzabrianza.it","monzaebrianza.it","monzaedellabrianza.it","ms.it","mt.it","na.it","naples.it","napoli.it","no.it","novara.it","nu.it","nuoro.it","og.it","ogliastra.it","olbia-tempio.it","olbiatempio.it","or.it","oristano.it","ot.it","pa.it","padova.it","padua.it","palermo.it","parma.it","pavia.it","pc.it","pd.it","pe.it","perugia.it","pesaro-urbino.it","pesarourbino.it","pescara.it","pg.it","pi.it","piacenza.it","pisa.it","pistoia.it","pn.it","po.it","pordenone.it","potenza.it","pr.it","prato.it","pt.it","pu.it","pv.it","pz.it","ra.it","ragusa.it","ravenna.it","rc.it","re.it","reggio-calabria.it","reggio-emilia.it","reggiocalabria.it","reggioemilia.it","rg.it","ri.it","rieti.it","rimini.it","rm.it","rn.it","ro.it","roma.it","rome.it","rovigo.it","sa.it","salerno.it","sassari.it","savona.it","si.it","siena.it","siracusa.it","so.it","sondrio.it","sp.it","sr.it","ss.it","suedtirol.it","südtirol.it","sv.it","ta.it","taranto.it","te.it","tempio-olbia.it","tempioolbia.it","teramo.it","terni.it","tn.it","to.it","torino.it","tp.it","tr.it","trani-andria-barletta.it","trani-barletta-andria.it","traniandriabarletta.it","tranibarlettaandria.it","trapani.it","trento.it","treviso.it","trieste.it","ts.it","turin.it","tv.it","ud.it","udine.it","urbino-pesaro.it","urbinopesaro.it","va.it","varese.it","vb.it","vc.it","ve.it","venezia.it","venice.it","verbania.it","vercelli.it","verona.it","vi.it","vibo-valentia.it","vibovalentia.it","vicenza.it","viterbo.it","vr.it","vs.it","vt.it","vv.it","je","co.je","net.je","org.je","*.jm","jo","com.jo","org.jo","net.jo","edu.jo","sch.jo","gov.jo","mil.jo","name.jo","jobs","jp","ac.jp","ad.jp","co.jp","ed.jp","go.jp","gr.jp","lg.jp","ne.jp","or.jp","aichi.jp","akita.jp","aomori.jp","chiba.jp","ehime.jp","fukui.jp","fukuoka.jp","fukushima.jp","gifu.jp","gunma.jp","hiroshima.jp","hokkaido.jp","hyogo.jp","ibaraki.jp","ishikawa.jp","iwate.jp","kagawa.jp","kagoshima.jp","kanagawa.jp","kochi.jp","kumamoto.jp","kyoto.jp","mie.jp","miyagi.jp","miyazaki.jp","nagano.jp","nagasaki.jp","nara.jp","niigata.jp","oita.jp","okayama.jp","okinawa.jp","osaka.jp","saga.jp","saitama.jp","shiga.jp","shimane.jp","shizuoka.jp","tochigi.jp","tokushima.jp","tokyo.jp","tottori.jp","toyama.jp","wakayama.jp","yamagata.jp","yamaguchi.jp","yamanashi.jp","栃木.jp","愛知.jp","愛媛.jp","兵庫.jp","熊本.jp","茨城.jp","北海道.jp","千葉.jp","和歌山.jp","長崎.jp","長野.jp","新潟.jp","青森.jp","静岡.jp","東京.jp","石川.jp","埼玉.jp","三重.jp","京都.jp","佐賀.jp","大分.jp","大阪.jp","奈良.jp","宮城.jp","宮崎.jp","富山.jp","山口.jp","山形.jp","山梨.jp","岩手.jp","岐阜.jp","岡山.jp","島根.jp","広島.jp","徳島.jp","沖縄.jp","滋賀.jp","神奈川.jp","福井.jp","福岡.jp","福島.jp","秋田.jp","群馬.jp","香川.jp","高知.jp","鳥取.jp","鹿児島.jp","*.kawasaki.jp","*.kitakyushu.jp","*.kobe.jp","*.nagoya.jp","*.sapporo.jp","*.sendai.jp","*.yokohama.jp","!city.kawasaki.jp","!city.kitakyushu.jp","!city.kobe.jp","!city.nagoya.jp","!city.sapporo.jp","!city.sendai.jp","!city.yokohama.jp","aisai.aichi.jp","ama.aichi.jp","anjo.aichi.jp","asuke.aichi.jp","chiryu.aichi.jp","chita.aichi.jp","fuso.aichi.jp","gamagori.aichi.jp","handa.aichi.jp","hazu.aichi.jp","hekinan.aichi.jp","higashiura.aichi.jp","ichinomiya.aichi.jp","inazawa.aichi.jp","inuyama.aichi.jp","isshiki.aichi.jp","iwakura.aichi.jp","kanie.aichi.jp","kariya.aichi.jp","kasugai.aichi.jp","kira.aichi.jp","kiyosu.aichi.jp","komaki.aichi.jp","konan.aichi.jp","kota.aichi.jp","mihama.aichi.jp","miyoshi.aichi.jp","nishio.aichi.jp","nisshin.aichi.jp","obu.aichi.jp","oguchi.aichi.jp","oharu.aichi.jp","okazaki.aichi.jp","owariasahi.aichi.jp","seto.aichi.jp","shikatsu.aichi.jp","shinshiro.aichi.jp","shitara.aichi.jp","tahara.aichi.jp","takahama.aichi.jp","tobishima.aichi.jp","toei.aichi.jp","togo.aichi.jp","tokai.aichi.jp","tokoname.aichi.jp","toyoake.aichi.jp","toyohashi.aichi.jp","toyokawa.aichi.jp","toyone.aichi.jp","toyota.aichi.jp","tsushima.aichi.jp","yatomi.aichi.jp","akita.akita.jp","daisen.akita.jp","fujisato.akita.jp","gojome.akita.jp","hachirogata.akita.jp","happou.akita.jp","higashinaruse.akita.jp","honjo.akita.jp","honjyo.akita.jp","ikawa.akita.jp","kamikoani.akita.jp","kamioka.akita.jp","katagami.akita.jp","kazuno.akita.jp","kitaakita.akita.jp","kosaka.akita.jp","kyowa.akita.jp","misato.akita.jp","mitane.akita.jp","moriyoshi.akita.jp","nikaho.akita.jp","noshiro.akita.jp","odate.akita.jp","oga.akita.jp","ogata.akita.jp","semboku.akita.jp","yokote.akita.jp","yurihonjo.akita.jp","aomori.aomori.jp","gonohe.aomori.jp","hachinohe.aomori.jp","hashikami.aomori.jp","hiranai.aomori.jp","hirosaki.aomori.jp","itayanagi.aomori.jp","kuroishi.aomori.jp","misawa.aomori.jp","mutsu.aomori.jp","nakadomari.aomori.jp","noheji.aomori.jp","oirase.aomori.jp","owani.aomori.jp","rokunohe.aomori.jp","sannohe.aomori.jp","shichinohe.aomori.jp","shingo.aomori.jp","takko.aomori.jp","towada.aomori.jp","tsugaru.aomori.jp","tsuruta.aomori.jp","abiko.chiba.jp","asahi.chiba.jp","chonan.chiba.jp","chosei.chiba.jp","choshi.chiba.jp","chuo.chiba.jp","funabashi.chiba.jp","futtsu.chiba.jp","hanamigawa.chiba.jp","ichihara.chiba.jp","ichikawa.chiba.jp","ichinomiya.chiba.jp","inzai.chiba.jp","isumi.chiba.jp","kamagaya.chiba.jp","kamogawa.chiba.jp","kashiwa.chiba.jp","katori.chiba.jp","katsuura.chiba.jp","kimitsu.chiba.jp","kisarazu.chiba.jp","kozaki.chiba.jp","kujukuri.chiba.jp","kyonan.chiba.jp","matsudo.chiba.jp","midori.chiba.jp","mihama.chiba.jp","minamiboso.chiba.jp","mobara.chiba.jp","mutsuzawa.chiba.jp","nagara.chiba.jp","nagareyama.chiba.jp","narashino.chiba.jp","narita.chiba.jp","noda.chiba.jp","oamishirasato.chiba.jp","omigawa.chiba.jp","onjuku.chiba.jp","otaki.chiba.jp","sakae.chiba.jp","sakura.chiba.jp","shimofusa.chiba.jp","shirako.chiba.jp","shiroi.chiba.jp","shisui.chiba.jp","sodegaura.chiba.jp","sosa.chiba.jp","tako.chiba.jp","tateyama.chiba.jp","togane.chiba.jp","tohnosho.chiba.jp","tomisato.chiba.jp","urayasu.chiba.jp","yachimata.chiba.jp","yachiyo.chiba.jp","yokaichiba.chiba.jp","yokoshibahikari.chiba.jp","yotsukaido.chiba.jp","ainan.ehime.jp","honai.ehime.jp","ikata.ehime.jp","imabari.ehime.jp","iyo.ehime.jp","kamijima.ehime.jp","kihoku.ehime.jp","kumakogen.ehime.jp","masaki.ehime.jp","matsuno.ehime.jp","matsuyama.ehime.jp","namikata.ehime.jp","niihama.ehime.jp","ozu.ehime.jp","saijo.ehime.jp","seiyo.ehime.jp","shikokuchuo.ehime.jp","tobe.ehime.jp","toon.ehime.jp","uchiko.ehime.jp","uwajima.ehime.jp","yawatahama.ehime.jp","echizen.fukui.jp","eiheiji.fukui.jp","fukui.fukui.jp","ikeda.fukui.jp","katsuyama.fukui.jp","mihama.fukui.jp","minamiechizen.fukui.jp","obama.fukui.jp","ohi.fukui.jp","ono.fukui.jp","sabae.fukui.jp","sakai.fukui.jp","takahama.fukui.jp","tsuruga.fukui.jp","wakasa.fukui.jp","ashiya.fukuoka.jp","buzen.fukuoka.jp","chikugo.fukuoka.jp","chikuho.fukuoka.jp","chikujo.fukuoka.jp","chikushino.fukuoka.jp","chikuzen.fukuoka.jp","chuo.fukuoka.jp","dazaifu.fukuoka.jp","fukuchi.fukuoka.jp","hakata.fukuoka.jp","higashi.fukuoka.jp","hirokawa.fukuoka.jp","hisayama.fukuoka.jp","iizuka.fukuoka.jp","inatsuki.fukuoka.jp","kaho.fukuoka.jp","kasuga.fukuoka.jp","kasuya.fukuoka.jp","kawara.fukuoka.jp","keisen.fukuoka.jp","koga.fukuoka.jp","kurate.fukuoka.jp","kurogi.fukuoka.jp","kurume.fukuoka.jp","minami.fukuoka.jp","miyako.fukuoka.jp","miyama.fukuoka.jp","miyawaka.fukuoka.jp","mizumaki.fukuoka.jp","munakata.fukuoka.jp","nakagawa.fukuoka.jp","nakama.fukuoka.jp","nishi.fukuoka.jp","nogata.fukuoka.jp","ogori.fukuoka.jp","okagaki.fukuoka.jp","okawa.fukuoka.jp","oki.fukuoka.jp","omuta.fukuoka.jp","onga.fukuoka.jp","onojo.fukuoka.jp","oto.fukuoka.jp","saigawa.fukuoka.jp","sasaguri.fukuoka.jp","shingu.fukuoka.jp","shinyoshitomi.fukuoka.jp","shonai.fukuoka.jp","soeda.fukuoka.jp","sue.fukuoka.jp","tachiarai.fukuoka.jp","tagawa.fukuoka.jp","takata.fukuoka.jp","toho.fukuoka.jp","toyotsu.fukuoka.jp","tsuiki.fukuoka.jp","ukiha.fukuoka.jp","umi.fukuoka.jp","usui.fukuoka.jp","yamada.fukuoka.jp","yame.fukuoka.jp","yanagawa.fukuoka.jp","yukuhashi.fukuoka.jp","aizubange.fukushima.jp","aizumisato.fukushima.jp","aizuwakamatsu.fukushima.jp","asakawa.fukushima.jp","bandai.fukushima.jp","date.fukushima.jp","fukushima.fukushima.jp","furudono.fukushima.jp","futaba.fukushima.jp","hanawa.fukushima.jp","higashi.fukushima.jp","hirata.fukushima.jp","hirono.fukushima.jp","iitate.fukushima.jp","inawashiro.fukushima.jp","ishikawa.fukushima.jp","iwaki.fukushima.jp","izumizaki.fukushima.jp","kagamiishi.fukushima.jp","kaneyama.fukushima.jp","kawamata.fukushima.jp","kitakata.fukushima.jp","kitashiobara.fukushima.jp","koori.fukushima.jp","koriyama.fukushima.jp","kunimi.fukushima.jp","miharu.fukushima.jp","mishima.fukushima.jp","namie.fukushima.jp","nango.fukushima.jp","nishiaizu.fukushima.jp","nishigo.fukushima.jp","okuma.fukushima.jp","omotego.fukushima.jp","ono.fukushima.jp","otama.fukushima.jp","samegawa.fukushima.jp","shimogo.fukushima.jp","shirakawa.fukushima.jp","showa.fukushima.jp","soma.fukushima.jp","sukagawa.fukushima.jp","taishin.fukushima.jp","tamakawa.fukushima.jp","tanagura.fukushima.jp","tenei.fukushima.jp","yabuki.fukushima.jp","yamato.fukushima.jp","yamatsuri.fukushima.jp","yanaizu.fukushima.jp","yugawa.fukushima.jp","anpachi.gifu.jp","ena.gifu.jp","gifu.gifu.jp","ginan.gifu.jp","godo.gifu.jp","gujo.gifu.jp","hashima.gifu.jp","hichiso.gifu.jp","hida.gifu.jp","higashishirakawa.gifu.jp","ibigawa.gifu.jp","ikeda.gifu.jp","kakamigahara.gifu.jp","kani.gifu.jp","kasahara.gifu.jp","kasamatsu.gifu.jp","kawaue.gifu.jp","kitagata.gifu.jp","mino.gifu.jp","minokamo.gifu.jp","mitake.gifu.jp","mizunami.gifu.jp","motosu.gifu.jp","nakatsugawa.gifu.jp","ogaki.gifu.jp","sakahogi.gifu.jp","seki.gifu.jp","sekigahara.gifu.jp","shirakawa.gifu.jp","tajimi.gifu.jp","takayama.gifu.jp","tarui.gifu.jp","toki.gifu.jp","tomika.gifu.jp","wanouchi.gifu.jp","yamagata.gifu.jp","yaotsu.gifu.jp","yoro.gifu.jp","annaka.gunma.jp","chiyoda.gunma.jp","fujioka.gunma.jp","higashiagatsuma.gunma.jp","isesaki.gunma.jp","itakura.gunma.jp","kanna.gunma.jp","kanra.gunma.jp","katashina.gunma.jp","kawaba.gunma.jp","kiryu.gunma.jp","kusatsu.gunma.jp","maebashi.gunma.jp","meiwa.gunma.jp","midori.gunma.jp","minakami.gunma.jp","naganohara.gunma.jp","nakanojo.gunma.jp","nanmoku.gunma.jp","numata.gunma.jp","oizumi.gunma.jp","ora.gunma.jp","ota.gunma.jp","shibukawa.gunma.jp","shimonita.gunma.jp","shinto.gunma.jp","showa.gunma.jp","takasaki.gunma.jp","takayama.gunma.jp","tamamura.gunma.jp","tatebayashi.gunma.jp","tomioka.gunma.jp","tsukiyono.gunma.jp","tsumagoi.gunma.jp","ueno.gunma.jp","yoshioka.gunma.jp","asaminami.hiroshima.jp","daiwa.hiroshima.jp","etajima.hiroshima.jp","fuchu.hiroshima.jp","fukuyama.hiroshima.jp","hatsukaichi.hiroshima.jp","higashihiroshima.hiroshima.jp","hongo.hiroshima.jp","jinsekikogen.hiroshima.jp","kaita.hiroshima.jp","kui.hiroshima.jp","kumano.hiroshima.jp","kure.hiroshima.jp","mihara.hiroshima.jp","miyoshi.hiroshima.jp","naka.hiroshima.jp","onomichi.hiroshima.jp","osakikamijima.hiroshima.jp","otake.hiroshima.jp","saka.hiroshima.jp","sera.hiroshima.jp","seranishi.hiroshima.jp","shinichi.hiroshima.jp","shobara.hiroshima.jp","takehara.hiroshima.jp","abashiri.hokkaido.jp","abira.hokkaido.jp","aibetsu.hokkaido.jp","akabira.hokkaido.jp","akkeshi.hokkaido.jp","asahikawa.hokkaido.jp","ashibetsu.hokkaido.jp","ashoro.hokkaido.jp","assabu.hokkaido.jp","atsuma.hokkaido.jp","bibai.hokkaido.jp","biei.hokkaido.jp","bifuka.hokkaido.jp","bihoro.hokkaido.jp","biratori.hokkaido.jp","chippubetsu.hokkaido.jp","chitose.hokkaido.jp","date.hokkaido.jp","ebetsu.hokkaido.jp","embetsu.hokkaido.jp","eniwa.hokkaido.jp","erimo.hokkaido.jp","esan.hokkaido.jp","esashi.hokkaido.jp","fukagawa.hokkaido.jp","fukushima.hokkaido.jp","furano.hokkaido.jp","furubira.hokkaido.jp","haboro.hokkaido.jp","hakodate.hokkaido.jp","hamatonbetsu.hokkaido.jp","hidaka.hokkaido.jp","higashikagura.hokkaido.jp","higashikawa.hokkaido.jp","hiroo.hokkaido.jp","hokuryu.hokkaido.jp","hokuto.hokkaido.jp","honbetsu.hokkaido.jp","horokanai.hokkaido.jp","horonobe.hokkaido.jp","ikeda.hokkaido.jp","imakane.hokkaido.jp","ishikari.hokkaido.jp","iwamizawa.hokkaido.jp","iwanai.hokkaido.jp","kamifurano.hokkaido.jp","kamikawa.hokkaido.jp","kamishihoro.hokkaido.jp","kamisunagawa.hokkaido.jp","kamoenai.hokkaido.jp","kayabe.hokkaido.jp","kembuchi.hokkaido.jp","kikonai.hokkaido.jp","kimobetsu.hokkaido.jp","kitahiroshima.hokkaido.jp","kitami.hokkaido.jp","kiyosato.hokkaido.jp","koshimizu.hokkaido.jp","kunneppu.hokkaido.jp","kuriyama.hokkaido.jp","kuromatsunai.hokkaido.jp","kushiro.hokkaido.jp","kutchan.hokkaido.jp","kyowa.hokkaido.jp","mashike.hokkaido.jp","matsumae.hokkaido.jp","mikasa.hokkaido.jp","minamifurano.hokkaido.jp","mombetsu.hokkaido.jp","moseushi.hokkaido.jp","mukawa.hokkaido.jp","muroran.hokkaido.jp","naie.hokkaido.jp","nakagawa.hokkaido.jp","nakasatsunai.hokkaido.jp","nakatombetsu.hokkaido.jp","nanae.hokkaido.jp","nanporo.hokkaido.jp","nayoro.hokkaido.jp","nemuro.hokkaido.jp","niikappu.hokkaido.jp","niki.hokkaido.jp","nishiokoppe.hokkaido.jp","noboribetsu.hokkaido.jp","numata.hokkaido.jp","obihiro.hokkaido.jp","obira.hokkaido.jp","oketo.hokkaido.jp","okoppe.hokkaido.jp","otaru.hokkaido.jp","otobe.hokkaido.jp","otofuke.hokkaido.jp","otoineppu.hokkaido.jp","oumu.hokkaido.jp","ozora.hokkaido.jp","pippu.hokkaido.jp","rankoshi.hokkaido.jp","rebun.hokkaido.jp","rikubetsu.hokkaido.jp","rishiri.hokkaido.jp","rishirifuji.hokkaido.jp","saroma.hokkaido.jp","sarufutsu.hokkaido.jp","shakotan.hokkaido.jp","shari.hokkaido.jp","shibecha.hokkaido.jp","shibetsu.hokkaido.jp","shikabe.hokkaido.jp","shikaoi.hokkaido.jp","shimamaki.hokkaido.jp","shimizu.hokkaido.jp","shimokawa.hokkaido.jp","shinshinotsu.hokkaido.jp","shintoku.hokkaido.jp","shiranuka.hokkaido.jp","shiraoi.hokkaido.jp","shiriuchi.hokkaido.jp","sobetsu.hokkaido.jp","sunagawa.hokkaido.jp","taiki.hokkaido.jp","takasu.hokkaido.jp","takikawa.hokkaido.jp","takinoue.hokkaido.jp","teshikaga.hokkaido.jp","tobetsu.hokkaido.jp","tohma.hokkaido.jp","tomakomai.hokkaido.jp","tomari.hokkaido.jp","toya.hokkaido.jp","toyako.hokkaido.jp","toyotomi.hokkaido.jp","toyoura.hokkaido.jp","tsubetsu.hokkaido.jp","tsukigata.hokkaido.jp","urakawa.hokkaido.jp","urausu.hokkaido.jp","uryu.hokkaido.jp","utashinai.hokkaido.jp","wakkanai.hokkaido.jp","wassamu.hokkaido.jp","yakumo.hokkaido.jp","yoichi.hokkaido.jp","aioi.hyogo.jp","akashi.hyogo.jp","ako.hyogo.jp","amagasaki.hyogo.jp","aogaki.hyogo.jp","asago.hyogo.jp","ashiya.hyogo.jp","awaji.hyogo.jp","fukusaki.hyogo.jp","goshiki.hyogo.jp","harima.hyogo.jp","himeji.hyogo.jp","ichikawa.hyogo.jp","inagawa.hyogo.jp","itami.hyogo.jp","kakogawa.hyogo.jp","kamigori.hyogo.jp","kamikawa.hyogo.jp","kasai.hyogo.jp","kasuga.hyogo.jp","kawanishi.hyogo.jp","miki.hyogo.jp","minamiawaji.hyogo.jp","nishinomiya.hyogo.jp","nishiwaki.hyogo.jp","ono.hyogo.jp","sanda.hyogo.jp","sannan.hyogo.jp","sasayama.hyogo.jp","sayo.hyogo.jp","shingu.hyogo.jp","shinonsen.hyogo.jp","shiso.hyogo.jp","sumoto.hyogo.jp","taishi.hyogo.jp","taka.hyogo.jp","takarazuka.hyogo.jp","takasago.hyogo.jp","takino.hyogo.jp","tamba.hyogo.jp","tatsuno.hyogo.jp","toyooka.hyogo.jp","yabu.hyogo.jp","yashiro.hyogo.jp","yoka.hyogo.jp","yokawa.hyogo.jp","ami.ibaraki.jp","asahi.ibaraki.jp","bando.ibaraki.jp","chikusei.ibaraki.jp","daigo.ibaraki.jp","fujishiro.ibaraki.jp","hitachi.ibaraki.jp","hitachinaka.ibaraki.jp","hitachiomiya.ibaraki.jp","hitachiota.ibaraki.jp","ibaraki.ibaraki.jp","ina.ibaraki.jp","inashiki.ibaraki.jp","itako.ibaraki.jp","iwama.ibaraki.jp","joso.ibaraki.jp","kamisu.ibaraki.jp","kasama.ibaraki.jp","kashima.ibaraki.jp","kasumigaura.ibaraki.jp","koga.ibaraki.jp","miho.ibaraki.jp","mito.ibaraki.jp","moriya.ibaraki.jp","naka.ibaraki.jp","namegata.ibaraki.jp","oarai.ibaraki.jp","ogawa.ibaraki.jp","omitama.ibaraki.jp","ryugasaki.ibaraki.jp","sakai.ibaraki.jp","sakuragawa.ibaraki.jp","shimodate.ibaraki.jp","shimotsuma.ibaraki.jp","shirosato.ibaraki.jp","sowa.ibaraki.jp","suifu.ibaraki.jp","takahagi.ibaraki.jp","tamatsukuri.ibaraki.jp","tokai.ibaraki.jp","tomobe.ibaraki.jp","tone.ibaraki.jp","toride.ibaraki.jp","tsuchiura.ibaraki.jp","tsukuba.ibaraki.jp","uchihara.ibaraki.jp","ushiku.ibaraki.jp","yachiyo.ibaraki.jp","yamagata.ibaraki.jp","yawara.ibaraki.jp","yuki.ibaraki.jp","anamizu.ishikawa.jp","hakui.ishikawa.jp","hakusan.ishikawa.jp","kaga.ishikawa.jp","kahoku.ishikawa.jp","kanazawa.ishikawa.jp","kawakita.ishikawa.jp","komatsu.ishikawa.jp","nakanoto.ishikawa.jp","nanao.ishikawa.jp","nomi.ishikawa.jp","nonoichi.ishikawa.jp","noto.ishikawa.jp","shika.ishikawa.jp","suzu.ishikawa.jp","tsubata.ishikawa.jp","tsurugi.ishikawa.jp","uchinada.ishikawa.jp","wajima.ishikawa.jp","fudai.iwate.jp","fujisawa.iwate.jp","hanamaki.iwate.jp","hiraizumi.iwate.jp","hirono.iwate.jp","ichinohe.iwate.jp","ichinoseki.iwate.jp","iwaizumi.iwate.jp","iwate.iwate.jp","joboji.iwate.jp","kamaishi.iwate.jp","kanegasaki.iwate.jp","karumai.iwate.jp","kawai.iwate.jp","kitakami.iwate.jp","kuji.iwate.jp","kunohe.iwate.jp","kuzumaki.iwate.jp","miyako.iwate.jp","mizusawa.iwate.jp","morioka.iwate.jp","ninohe.iwate.jp","noda.iwate.jp","ofunato.iwate.jp","oshu.iwate.jp","otsuchi.iwate.jp","rikuzentakata.iwate.jp","shiwa.iwate.jp","shizukuishi.iwate.jp","sumita.iwate.jp","tanohata.iwate.jp","tono.iwate.jp","yahaba.iwate.jp","yamada.iwate.jp","ayagawa.kagawa.jp","higashikagawa.kagawa.jp","kanonji.kagawa.jp","kotohira.kagawa.jp","manno.kagawa.jp","marugame.kagawa.jp","mitoyo.kagawa.jp","naoshima.kagawa.jp","sanuki.kagawa.jp","tadotsu.kagawa.jp","takamatsu.kagawa.jp","tonosho.kagawa.jp","uchinomi.kagawa.jp","utazu.kagawa.jp","zentsuji.kagawa.jp","akune.kagoshima.jp","amami.kagoshima.jp","hioki.kagoshima.jp","isa.kagoshima.jp","isen.kagoshima.jp","izumi.kagoshima.jp","kagoshima.kagoshima.jp","kanoya.kagoshima.jp","kawanabe.kagoshima.jp","kinko.kagoshima.jp","kouyama.kagoshima.jp","makurazaki.kagoshima.jp","matsumoto.kagoshima.jp","minamitane.kagoshima.jp","nakatane.kagoshima.jp","nishinoomote.kagoshima.jp","satsumasendai.kagoshima.jp","soo.kagoshima.jp","tarumizu.kagoshima.jp","yusui.kagoshima.jp","aikawa.kanagawa.jp","atsugi.kanagawa.jp","ayase.kanagawa.jp","chigasaki.kanagawa.jp","ebina.kanagawa.jp","fujisawa.kanagawa.jp","hadano.kanagawa.jp","hakone.kanagawa.jp","hiratsuka.kanagawa.jp","isehara.kanagawa.jp","kaisei.kanagawa.jp","kamakura.kanagawa.jp","kiyokawa.kanagawa.jp","matsuda.kanagawa.jp","minamiashigara.kanagawa.jp","miura.kanagawa.jp","nakai.kanagawa.jp","ninomiya.kanagawa.jp","odawara.kanagawa.jp","oi.kanagawa.jp","oiso.kanagawa.jp","sagamihara.kanagawa.jp","samukawa.kanagawa.jp","tsukui.kanagawa.jp","yamakita.kanagawa.jp","yamato.kanagawa.jp","yokosuka.kanagawa.jp","yugawara.kanagawa.jp","zama.kanagawa.jp","zushi.kanagawa.jp","aki.kochi.jp","geisei.kochi.jp","hidaka.kochi.jp","higashitsuno.kochi.jp","ino.kochi.jp","kagami.kochi.jp","kami.kochi.jp","kitagawa.kochi.jp","kochi.kochi.jp","mihara.kochi.jp","motoyama.kochi.jp","muroto.kochi.jp","nahari.kochi.jp","nakamura.kochi.jp","nankoku.kochi.jp","nishitosa.kochi.jp","niyodogawa.kochi.jp","ochi.kochi.jp","okawa.kochi.jp","otoyo.kochi.jp","otsuki.kochi.jp","sakawa.kochi.jp","sukumo.kochi.jp","susaki.kochi.jp","tosa.kochi.jp","tosashimizu.kochi.jp","toyo.kochi.jp","tsuno.kochi.jp","umaji.kochi.jp","yasuda.kochi.jp","yusuhara.kochi.jp","amakusa.kumamoto.jp","arao.kumamoto.jp","aso.kumamoto.jp","choyo.kumamoto.jp","gyokuto.kumamoto.jp","kamiamakusa.kumamoto.jp","kikuchi.kumamoto.jp","kumamoto.kumamoto.jp","mashiki.kumamoto.jp","mifune.kumamoto.jp","minamata.kumamoto.jp","minamioguni.kumamoto.jp","nagasu.kumamoto.jp","nishihara.kumamoto.jp","oguni.kumamoto.jp","ozu.kumamoto.jp","sumoto.kumamoto.jp","takamori.kumamoto.jp","uki.kumamoto.jp","uto.kumamoto.jp","yamaga.kumamoto.jp","yamato.kumamoto.jp","yatsushiro.kumamoto.jp","ayabe.kyoto.jp","fukuchiyama.kyoto.jp","higashiyama.kyoto.jp","ide.kyoto.jp","ine.kyoto.jp","joyo.kyoto.jp","kameoka.kyoto.jp","kamo.kyoto.jp","kita.kyoto.jp","kizu.kyoto.jp","kumiyama.kyoto.jp","kyotamba.kyoto.jp","kyotanabe.kyoto.jp","kyotango.kyoto.jp","maizuru.kyoto.jp","minami.kyoto.jp","minamiyamashiro.kyoto.jp","miyazu.kyoto.jp","muko.kyoto.jp","nagaokakyo.kyoto.jp","nakagyo.kyoto.jp","nantan.kyoto.jp","oyamazaki.kyoto.jp","sakyo.kyoto.jp","seika.kyoto.jp","tanabe.kyoto.jp","uji.kyoto.jp","ujitawara.kyoto.jp","wazuka.kyoto.jp","yamashina.kyoto.jp","yawata.kyoto.jp","asahi.mie.jp","inabe.mie.jp","ise.mie.jp","kameyama.mie.jp","kawagoe.mie.jp","kiho.mie.jp","kisosaki.mie.jp","kiwa.mie.jp","komono.mie.jp","kumano.mie.jp","kuwana.mie.jp","matsusaka.mie.jp","meiwa.mie.jp","mihama.mie.jp","minamiise.mie.jp","misugi.mie.jp","miyama.mie.jp","nabari.mie.jp","shima.mie.jp","suzuka.mie.jp","tado.mie.jp","taiki.mie.jp","taki.mie.jp","tamaki.mie.jp","toba.mie.jp","tsu.mie.jp","udono.mie.jp","ureshino.mie.jp","watarai.mie.jp","yokkaichi.mie.jp","furukawa.miyagi.jp","higashimatsushima.miyagi.jp","ishinomaki.miyagi.jp","iwanuma.miyagi.jp","kakuda.miyagi.jp","kami.miyagi.jp","kawasaki.miyagi.jp","marumori.miyagi.jp","matsushima.miyagi.jp","minamisanriku.miyagi.jp","misato.miyagi.jp","murata.miyagi.jp","natori.miyagi.jp","ogawara.miyagi.jp","ohira.miyagi.jp","onagawa.miyagi.jp","osaki.miyagi.jp","rifu.miyagi.jp","semine.miyagi.jp","shibata.miyagi.jp","shichikashuku.miyagi.jp","shikama.miyagi.jp","shiogama.miyagi.jp","shiroishi.miyagi.jp","tagajo.miyagi.jp","taiwa.miyagi.jp","tome.miyagi.jp","tomiya.miyagi.jp","wakuya.miyagi.jp","watari.miyagi.jp","yamamoto.miyagi.jp","zao.miyagi.jp","aya.miyazaki.jp","ebino.miyazaki.jp","gokase.miyazaki.jp","hyuga.miyazaki.jp","kadogawa.miyazaki.jp","kawaminami.miyazaki.jp","kijo.miyazaki.jp","kitagawa.miyazaki.jp","kitakata.miyazaki.jp","kitaura.miyazaki.jp","kobayashi.miyazaki.jp","kunitomi.miyazaki.jp","kushima.miyazaki.jp","mimata.miyazaki.jp","miyakonojo.miyazaki.jp","miyazaki.miyazaki.jp","morotsuka.miyazaki.jp","nichinan.miyazaki.jp","nishimera.miyazaki.jp","nobeoka.miyazaki.jp","saito.miyazaki.jp","shiiba.miyazaki.jp","shintomi.miyazaki.jp","takaharu.miyazaki.jp","takanabe.miyazaki.jp","takazaki.miyazaki.jp","tsuno.miyazaki.jp","achi.nagano.jp","agematsu.nagano.jp","anan.nagano.jp","aoki.nagano.jp","asahi.nagano.jp","azumino.nagano.jp","chikuhoku.nagano.jp","chikuma.nagano.jp","chino.nagano.jp","fujimi.nagano.jp","hakuba.nagano.jp","hara.nagano.jp","hiraya.nagano.jp","iida.nagano.jp","iijima.nagano.jp","iiyama.nagano.jp","iizuna.nagano.jp","ikeda.nagano.jp","ikusaka.nagano.jp","ina.nagano.jp","karuizawa.nagano.jp","kawakami.nagano.jp","kiso.nagano.jp","kisofukushima.nagano.jp","kitaaiki.nagano.jp","komagane.nagano.jp","komoro.nagano.jp","matsukawa.nagano.jp","matsumoto.nagano.jp","miasa.nagano.jp","minamiaiki.nagano.jp","minamimaki.nagano.jp","minamiminowa.nagano.jp","minowa.nagano.jp","miyada.nagano.jp","miyota.nagano.jp","mochizuki.nagano.jp","nagano.nagano.jp","nagawa.nagano.jp","nagiso.nagano.jp","nakagawa.nagano.jp","nakano.nagano.jp","nozawaonsen.nagano.jp","obuse.nagano.jp","ogawa.nagano.jp","okaya.nagano.jp","omachi.nagano.jp","omi.nagano.jp","ookuwa.nagano.jp","ooshika.nagano.jp","otaki.nagano.jp","otari.nagano.jp","sakae.nagano.jp","sakaki.nagano.jp","saku.nagano.jp","sakuho.nagano.jp","shimosuwa.nagano.jp","shinanomachi.nagano.jp","shiojiri.nagano.jp","suwa.nagano.jp","suzaka.nagano.jp","takagi.nagano.jp","takamori.nagano.jp","takayama.nagano.jp","tateshina.nagano.jp","tatsuno.nagano.jp","togakushi.nagano.jp","togura.nagano.jp","tomi.nagano.jp","ueda.nagano.jp","wada.nagano.jp","yamagata.nagano.jp","yamanouchi.nagano.jp","yasaka.nagano.jp","yasuoka.nagano.jp","chijiwa.nagasaki.jp","futsu.nagasaki.jp","goto.nagasaki.jp","hasami.nagasaki.jp","hirado.nagasaki.jp","iki.nagasaki.jp","isahaya.nagasaki.jp","kawatana.nagasaki.jp","kuchinotsu.nagasaki.jp","matsuura.nagasaki.jp","nagasaki.nagasaki.jp","obama.nagasaki.jp","omura.nagasaki.jp","oseto.nagasaki.jp","saikai.nagasaki.jp","sasebo.nagasaki.jp","seihi.nagasaki.jp","shimabara.nagasaki.jp","shinkamigoto.nagasaki.jp","togitsu.nagasaki.jp","tsushima.nagasaki.jp","unzen.nagasaki.jp","ando.nara.jp","gose.nara.jp","heguri.nara.jp","higashiyoshino.nara.jp","ikaruga.nara.jp","ikoma.nara.jp","kamikitayama.nara.jp","kanmaki.nara.jp","kashiba.nara.jp","kashihara.nara.jp","katsuragi.nara.jp","kawai.nara.jp","kawakami.nara.jp","kawanishi.nara.jp","koryo.nara.jp","kurotaki.nara.jp","mitsue.nara.jp","miyake.nara.jp","nara.nara.jp","nosegawa.nara.jp","oji.nara.jp","ouda.nara.jp","oyodo.nara.jp","sakurai.nara.jp","sango.nara.jp","shimoichi.nara.jp","shimokitayama.nara.jp","shinjo.nara.jp","soni.nara.jp","takatori.nara.jp","tawaramoto.nara.jp","tenkawa.nara.jp","tenri.nara.jp","uda.nara.jp","yamatokoriyama.nara.jp","yamatotakada.nara.jp","yamazoe.nara.jp","yoshino.nara.jp","aga.niigata.jp","agano.niigata.jp","gosen.niigata.jp","itoigawa.niigata.jp","izumozaki.niigata.jp","joetsu.niigata.jp","kamo.niigata.jp","kariwa.niigata.jp","kashiwazaki.niigata.jp","minamiuonuma.niigata.jp","mitsuke.niigata.jp","muika.niigata.jp","murakami.niigata.jp","myoko.niigata.jp","nagaoka.niigata.jp","niigata.niigata.jp","ojiya.niigata.jp","omi.niigata.jp","sado.niigata.jp","sanjo.niigata.jp","seiro.niigata.jp","seirou.niigata.jp","sekikawa.niigata.jp","shibata.niigata.jp","tagami.niigata.jp","tainai.niigata.jp","tochio.niigata.jp","tokamachi.niigata.jp","tsubame.niigata.jp","tsunan.niigata.jp","uonuma.niigata.jp","yahiko.niigata.jp","yoita.niigata.jp","yuzawa.niigata.jp","beppu.oita.jp","bungoono.oita.jp","bungotakada.oita.jp","hasama.oita.jp","hiji.oita.jp","himeshima.oita.jp","hita.oita.jp","kamitsue.oita.jp","kokonoe.oita.jp","kuju.oita.jp","kunisaki.oita.jp","kusu.oita.jp","oita.oita.jp","saiki.oita.jp","taketa.oita.jp","tsukumi.oita.jp","usa.oita.jp","usuki.oita.jp","yufu.oita.jp","akaiwa.okayama.jp","asakuchi.okayama.jp","bizen.okayama.jp","hayashima.okayama.jp","ibara.okayama.jp","kagamino.okayama.jp","kasaoka.okayama.jp","kibichuo.okayama.jp","kumenan.okayama.jp","kurashiki.okayama.jp","maniwa.okayama.jp","misaki.okayama.jp","nagi.okayama.jp","niimi.okayama.jp","nishiawakura.okayama.jp","okayama.okayama.jp","satosho.okayama.jp","setouchi.okayama.jp","shinjo.okayama.jp","shoo.okayama.jp","soja.okayama.jp","takahashi.okayama.jp","tamano.okayama.jp","tsuyama.okayama.jp","wake.okayama.jp","yakage.okayama.jp","aguni.okinawa.jp","ginowan.okinawa.jp","ginoza.okinawa.jp","gushikami.okinawa.jp","haebaru.okinawa.jp","higashi.okinawa.jp","hirara.okinawa.jp","iheya.okinawa.jp","ishigaki.okinawa.jp","ishikawa.okinawa.jp","itoman.okinawa.jp","izena.okinawa.jp","kadena.okinawa.jp","kin.okinawa.jp","kitadaito.okinawa.jp","kitanakagusuku.okinawa.jp","kumejima.okinawa.jp","kunigami.okinawa.jp","minamidaito.okinawa.jp","motobu.okinawa.jp","nago.okinawa.jp","naha.okinawa.jp","nakagusuku.okinawa.jp","nakijin.okinawa.jp","nanjo.okinawa.jp","nishihara.okinawa.jp","ogimi.okinawa.jp","okinawa.okinawa.jp","onna.okinawa.jp","shimoji.okinawa.jp","taketomi.okinawa.jp","tarama.okinawa.jp","tokashiki.okinawa.jp","tomigusuku.okinawa.jp","tonaki.okinawa.jp","urasoe.okinawa.jp","uruma.okinawa.jp","yaese.okinawa.jp","yomitan.okinawa.jp","yonabaru.okinawa.jp","yonaguni.okinawa.jp","zamami.okinawa.jp","abeno.osaka.jp","chihayaakasaka.osaka.jp","chuo.osaka.jp","daito.osaka.jp","fujiidera.osaka.jp","habikino.osaka.jp","hannan.osaka.jp","higashiosaka.osaka.jp","higashisumiyoshi.osaka.jp","higashiyodogawa.osaka.jp","hirakata.osaka.jp","ibaraki.osaka.jp","ikeda.osaka.jp","izumi.osaka.jp","izumiotsu.osaka.jp","izumisano.osaka.jp","kadoma.osaka.jp","kaizuka.osaka.jp","kanan.osaka.jp","kashiwara.osaka.jp","katano.osaka.jp","kawachinagano.osaka.jp","kishiwada.osaka.jp","kita.osaka.jp","kumatori.osaka.jp","matsubara.osaka.jp","minato.osaka.jp","minoh.osaka.jp","misaki.osaka.jp","moriguchi.osaka.jp","neyagawa.osaka.jp","nishi.osaka.jp","nose.osaka.jp","osakasayama.osaka.jp","sakai.osaka.jp","sayama.osaka.jp","sennan.osaka.jp","settsu.osaka.jp","shijonawate.osaka.jp","shimamoto.osaka.jp","suita.osaka.jp","tadaoka.osaka.jp","taishi.osaka.jp","tajiri.osaka.jp","takaishi.osaka.jp","takatsuki.osaka.jp","tondabayashi.osaka.jp","toyonaka.osaka.jp","toyono.osaka.jp","yao.osaka.jp","ariake.saga.jp","arita.saga.jp","fukudomi.saga.jp","genkai.saga.jp","hamatama.saga.jp","hizen.saga.jp","imari.saga.jp","kamimine.saga.jp","kanzaki.saga.jp","karatsu.saga.jp","kashima.saga.jp","kitagata.saga.jp","kitahata.saga.jp","kiyama.saga.jp","kouhoku.saga.jp","kyuragi.saga.jp","nishiarita.saga.jp","ogi.saga.jp","omachi.saga.jp","ouchi.saga.jp","saga.saga.jp","shiroishi.saga.jp","taku.saga.jp","tara.saga.jp","tosu.saga.jp","yoshinogari.saga.jp","arakawa.saitama.jp","asaka.saitama.jp","chichibu.saitama.jp","fujimi.saitama.jp","fujimino.saitama.jp","fukaya.saitama.jp","hanno.saitama.jp","hanyu.saitama.jp","hasuda.saitama.jp","hatogaya.saitama.jp","hatoyama.saitama.jp","hidaka.saitama.jp","higashichichibu.saitama.jp","higashimatsuyama.saitama.jp","honjo.saitama.jp","ina.saitama.jp","iruma.saitama.jp","iwatsuki.saitama.jp","kamiizumi.saitama.jp","kamikawa.saitama.jp","kamisato.saitama.jp","kasukabe.saitama.jp","kawagoe.saitama.jp","kawaguchi.saitama.jp","kawajima.saitama.jp","kazo.saitama.jp","kitamoto.saitama.jp","koshigaya.saitama.jp","kounosu.saitama.jp","kuki.saitama.jp","kumagaya.saitama.jp","matsubushi.saitama.jp","minano.saitama.jp","misato.saitama.jp","miyashiro.saitama.jp","miyoshi.saitama.jp","moroyama.saitama.jp","nagatoro.saitama.jp","namegawa.saitama.jp","niiza.saitama.jp","ogano.saitama.jp","ogawa.saitama.jp","ogose.saitama.jp","okegawa.saitama.jp","omiya.saitama.jp","otaki.saitama.jp","ranzan.saitama.jp","ryokami.saitama.jp","saitama.saitama.jp","sakado.saitama.jp","satte.saitama.jp","sayama.saitama.jp","shiki.saitama.jp","shiraoka.saitama.jp","soka.saitama.jp","sugito.saitama.jp","toda.saitama.jp","tokigawa.saitama.jp","tokorozawa.saitama.jp","tsurugashima.saitama.jp","urawa.saitama.jp","warabi.saitama.jp","yashio.saitama.jp","yokoze.saitama.jp","yono.saitama.jp","yorii.saitama.jp","yoshida.saitama.jp","yoshikawa.saitama.jp","yoshimi.saitama.jp","aisho.shiga.jp","gamo.shiga.jp","higashiomi.shiga.jp","hikone.shiga.jp","koka.shiga.jp","konan.shiga.jp","kosei.shiga.jp","koto.shiga.jp","kusatsu.shiga.jp","maibara.shiga.jp","moriyama.shiga.jp","nagahama.shiga.jp","nishiazai.shiga.jp","notogawa.shiga.jp","omihachiman.shiga.jp","otsu.shiga.jp","ritto.shiga.jp","ryuoh.shiga.jp","takashima.shiga.jp","takatsuki.shiga.jp","torahime.shiga.jp","toyosato.shiga.jp","yasu.shiga.jp","akagi.shimane.jp","ama.shimane.jp","gotsu.shimane.jp","hamada.shimane.jp","higashiizumo.shimane.jp","hikawa.shimane.jp","hikimi.shimane.jp","izumo.shimane.jp","kakinoki.shimane.jp","masuda.shimane.jp","matsue.shimane.jp","misato.shimane.jp","nishinoshima.shimane.jp","ohda.shimane.jp","okinoshima.shimane.jp","okuizumo.shimane.jp","shimane.shimane.jp","tamayu.shimane.jp","tsuwano.shimane.jp","unnan.shimane.jp","yakumo.shimane.jp","yasugi.shimane.jp","yatsuka.shimane.jp","arai.shizuoka.jp","atami.shizuoka.jp","fuji.shizuoka.jp","fujieda.shizuoka.jp","fujikawa.shizuoka.jp","fujinomiya.shizuoka.jp","fukuroi.shizuoka.jp","gotemba.shizuoka.jp","haibara.shizuoka.jp","hamamatsu.shizuoka.jp","higashiizu.shizuoka.jp","ito.shizuoka.jp","iwata.shizuoka.jp","izu.shizuoka.jp","izunokuni.shizuoka.jp","kakegawa.shizuoka.jp","kannami.shizuoka.jp","kawanehon.shizuoka.jp","kawazu.shizuoka.jp","kikugawa.shizuoka.jp","kosai.shizuoka.jp","makinohara.shizuoka.jp","matsuzaki.shizuoka.jp","minamiizu.shizuoka.jp","mishima.shizuoka.jp","morimachi.shizuoka.jp","nishiizu.shizuoka.jp","numazu.shizuoka.jp","omaezaki.shizuoka.jp","shimada.shizuoka.jp","shimizu.shizuoka.jp","shimoda.shizuoka.jp","shizuoka.shizuoka.jp","susono.shizuoka.jp","yaizu.shizuoka.jp","yoshida.shizuoka.jp","ashikaga.tochigi.jp","bato.tochigi.jp","haga.tochigi.jp","ichikai.tochigi.jp","iwafune.tochigi.jp","kaminokawa.tochigi.jp","kanuma.tochigi.jp","karasuyama.tochigi.jp","kuroiso.tochigi.jp","mashiko.tochigi.jp","mibu.tochigi.jp","moka.tochigi.jp","motegi.tochigi.jp","nasu.tochigi.jp","nasushiobara.tochigi.jp","nikko.tochigi.jp","nishikata.tochigi.jp","nogi.tochigi.jp","ohira.tochigi.jp","ohtawara.tochigi.jp","oyama.tochigi.jp","sakura.tochigi.jp","sano.tochigi.jp","shimotsuke.tochigi.jp","shioya.tochigi.jp","takanezawa.tochigi.jp","tochigi.tochigi.jp","tsuga.tochigi.jp","ujiie.tochigi.jp","utsunomiya.tochigi.jp","yaita.tochigi.jp","aizumi.tokushima.jp","anan.tokushima.jp","ichiba.tokushima.jp","itano.tokushima.jp","kainan.tokushima.jp","komatsushima.tokushima.jp","matsushige.tokushima.jp","mima.tokushima.jp","minami.tokushima.jp","miyoshi.tokushima.jp","mugi.tokushima.jp","nakagawa.tokushima.jp","naruto.tokushima.jp","sanagochi.tokushima.jp","shishikui.tokushima.jp","tokushima.tokushima.jp","wajiki.tokushima.jp","adachi.tokyo.jp","akiruno.tokyo.jp","akishima.tokyo.jp","aogashima.tokyo.jp","arakawa.tokyo.jp","bunkyo.tokyo.jp","chiyoda.tokyo.jp","chofu.tokyo.jp","chuo.tokyo.jp","edogawa.tokyo.jp","fuchu.tokyo.jp","fussa.tokyo.jp","hachijo.tokyo.jp","hachioji.tokyo.jp","hamura.tokyo.jp","higashikurume.tokyo.jp","higashimurayama.tokyo.jp","higashiyamato.tokyo.jp","hino.tokyo.jp","hinode.tokyo.jp","hinohara.tokyo.jp","inagi.tokyo.jp","itabashi.tokyo.jp","katsushika.tokyo.jp","kita.tokyo.jp","kiyose.tokyo.jp","kodaira.tokyo.jp","koganei.tokyo.jp","kokubunji.tokyo.jp","komae.tokyo.jp","koto.tokyo.jp","kouzushima.tokyo.jp","kunitachi.tokyo.jp","machida.tokyo.jp","meguro.tokyo.jp","minato.tokyo.jp","mitaka.tokyo.jp","mizuho.tokyo.jp","musashimurayama.tokyo.jp","musashino.tokyo.jp","nakano.tokyo.jp","nerima.tokyo.jp","ogasawara.tokyo.jp","okutama.tokyo.jp","ome.tokyo.jp","oshima.tokyo.jp","ota.tokyo.jp","setagaya.tokyo.jp","shibuya.tokyo.jp","shinagawa.tokyo.jp","shinjuku.tokyo.jp","suginami.tokyo.jp","sumida.tokyo.jp","tachikawa.tokyo.jp","taito.tokyo.jp","tama.tokyo.jp","toshima.tokyo.jp","chizu.tottori.jp","hino.tottori.jp","kawahara.tottori.jp","koge.tottori.jp","kotoura.tottori.jp","misasa.tottori.jp","nanbu.tottori.jp","nichinan.tottori.jp","sakaiminato.tottori.jp","tottori.tottori.jp","wakasa.tottori.jp","yazu.tottori.jp","yonago.tottori.jp","asahi.toyama.jp","fuchu.toyama.jp","fukumitsu.toyama.jp","funahashi.toyama.jp","himi.toyama.jp","imizu.toyama.jp","inami.toyama.jp","johana.toyama.jp","kamiichi.toyama.jp","kurobe.toyama.jp","nakaniikawa.toyama.jp","namerikawa.toyama.jp","nanto.toyama.jp","nyuzen.toyama.jp","oyabe.toyama.jp","taira.toyama.jp","takaoka.toyama.jp","tateyama.toyama.jp","toga.toyama.jp","tonami.toyama.jp","toyama.toyama.jp","unazuki.toyama.jp","uozu.toyama.jp","yamada.toyama.jp","arida.wakayama.jp","aridagawa.wakayama.jp","gobo.wakayama.jp","hashimoto.wakayama.jp","hidaka.wakayama.jp","hirogawa.wakayama.jp","inami.wakayama.jp","iwade.wakayama.jp","kainan.wakayama.jp","kamitonda.wakayama.jp","katsuragi.wakayama.jp","kimino.wakayama.jp","kinokawa.wakayama.jp","kitayama.wakayama.jp","koya.wakayama.jp","koza.wakayama.jp","kozagawa.wakayama.jp","kudoyama.wakayama.jp","kushimoto.wakayama.jp","mihama.wakayama.jp","misato.wakayama.jp","nachikatsuura.wakayama.jp","shingu.wakayama.jp","shirahama.wakayama.jp","taiji.wakayama.jp","tanabe.wakayama.jp","wakayama.wakayama.jp","yuasa.wakayama.jp","yura.wakayama.jp","asahi.yamagata.jp","funagata.yamagata.jp","higashine.yamagata.jp","iide.yamagata.jp","kahoku.yamagata.jp","kaminoyama.yamagata.jp","kaneyama.yamagata.jp","kawanishi.yamagata.jp","mamurogawa.yamagata.jp","mikawa.yamagata.jp","murayama.yamagata.jp","nagai.yamagata.jp","nakayama.yamagata.jp","nanyo.yamagata.jp","nishikawa.yamagata.jp","obanazawa.yamagata.jp","oe.yamagata.jp","oguni.yamagata.jp","ohkura.yamagata.jp","oishida.yamagata.jp","sagae.yamagata.jp","sakata.yamagata.jp","sakegawa.yamagata.jp","shinjo.yamagata.jp","shirataka.yamagata.jp","shonai.yamagata.jp","takahata.yamagata.jp","tendo.yamagata.jp","tozawa.yamagata.jp","tsuruoka.yamagata.jp","yamagata.yamagata.jp","yamanobe.yamagata.jp","yonezawa.yamagata.jp","yuza.yamagata.jp","abu.yamaguchi.jp","hagi.yamaguchi.jp","hikari.yamaguchi.jp","hofu.yamaguchi.jp","iwakuni.yamaguchi.jp","kudamatsu.yamaguchi.jp","mitou.yamaguchi.jp","nagato.yamaguchi.jp","oshima.yamaguchi.jp","shimonoseki.yamaguchi.jp","shunan.yamaguchi.jp","tabuse.yamaguchi.jp","tokuyama.yamaguchi.jp","toyota.yamaguchi.jp","ube.yamaguchi.jp","yuu.yamaguchi.jp","chuo.yamanashi.jp","doshi.yamanashi.jp","fuefuki.yamanashi.jp","fujikawa.yamanashi.jp","fujikawaguchiko.yamanashi.jp","fujiyoshida.yamanashi.jp","hayakawa.yamanashi.jp","hokuto.yamanashi.jp","ichikawamisato.yamanashi.jp","kai.yamanashi.jp","kofu.yamanashi.jp","koshu.yamanashi.jp","kosuge.yamanashi.jp","minami-alps.yamanashi.jp","minobu.yamanashi.jp","nakamichi.yamanashi.jp","nanbu.yamanashi.jp","narusawa.yamanashi.jp","nirasaki.yamanashi.jp","nishikatsura.yamanashi.jp","oshino.yamanashi.jp","otsuki.yamanashi.jp","showa.yamanashi.jp","tabayama.yamanashi.jp","tsuru.yamanashi.jp","uenohara.yamanashi.jp","yamanakako.yamanashi.jp","yamanashi.yamanashi.jp","ke","ac.ke","co.ke","go.ke","info.ke","me.ke","mobi.ke","ne.ke","or.ke","sc.ke","kg","org.kg","net.kg","com.kg","edu.kg","gov.kg","mil.kg","*.kh","ki","edu.ki","biz.ki","net.ki","org.ki","gov.ki","info.ki","com.ki","km","org.km","nom.km","gov.km","prd.km","tm.km","edu.km","mil.km","ass.km","com.km","coop.km","asso.km","presse.km","medecin.km","notaires.km","pharmaciens.km","veterinaire.km","gouv.km","kn","net.kn","org.kn","edu.kn","gov.kn","kp","com.kp","edu.kp","gov.kp","org.kp","rep.kp","tra.kp","kr","ac.kr","co.kr","es.kr","go.kr","hs.kr","kg.kr","mil.kr","ms.kr","ne.kr","or.kr","pe.kr","re.kr","sc.kr","busan.kr","chungbuk.kr","chungnam.kr","daegu.kr","daejeon.kr","gangwon.kr","gwangju.kr","gyeongbuk.kr","gyeonggi.kr","gyeongnam.kr","incheon.kr","jeju.kr","jeonbuk.kr","jeonnam.kr","seoul.kr","ulsan.kr","kw","com.kw","edu.kw","emb.kw","gov.kw","ind.kw","net.kw","org.kw","ky","edu.ky","gov.ky","com.ky","org.ky","net.ky","kz","org.kz","edu.kz","net.kz","gov.kz","mil.kz","com.kz","la","int.la","net.la","info.la","edu.la","gov.la","per.la","com.la","org.la","lb","com.lb","edu.lb","gov.lb","net.lb","org.lb","lc","com.lc","net.lc","co.lc","org.lc","edu.lc","gov.lc","li","lk","gov.lk","sch.lk","net.lk","int.lk","com.lk","org.lk","edu.lk","ngo.lk","soc.lk","web.lk","ltd.lk","assn.lk","grp.lk","hotel.lk","ac.lk","lr","com.lr","edu.lr","gov.lr","org.lr","net.lr","ls","co.ls","org.ls","lt","gov.lt","lu","lv","com.lv","edu.lv","gov.lv","org.lv","mil.lv","id.lv","net.lv","asn.lv","conf.lv","ly","com.ly","net.ly","gov.ly","plc.ly","edu.ly","sch.ly","med.ly","org.ly","id.ly","ma","co.ma","net.ma","gov.ma","org.ma","ac.ma","press.ma","mc","tm.mc","asso.mc","md","me","co.me","net.me","org.me","edu.me","ac.me","gov.me","its.me","priv.me","mg","org.mg","nom.mg","gov.mg","prd.mg","tm.mg","edu.mg","mil.mg","com.mg","co.mg","mh","mil","mk","com.mk","org.mk","net.mk","edu.mk","gov.mk","inf.mk","name.mk","ml","com.ml","edu.ml","gouv.ml","gov.ml","net.ml","org.ml","presse.ml","*.mm","mn","gov.mn","edu.mn","org.mn","mo","com.mo","net.mo","org.mo","edu.mo","gov.mo","mobi","mp","mq","mr","gov.mr","ms","com.ms","edu.ms","gov.ms","net.ms","org.ms","mt","com.mt","edu.mt","net.mt","org.mt","mu","com.mu","net.mu","org.mu","gov.mu","ac.mu","co.mu","or.mu","museum","academy.museum","agriculture.museum","air.museum","airguard.museum","alabama.museum","alaska.museum","amber.museum","ambulance.museum","american.museum","americana.museum","americanantiques.museum","americanart.museum","amsterdam.museum","and.museum","annefrank.museum","anthro.museum","anthropology.museum","antiques.museum","aquarium.museum","arboretum.museum","archaeological.museum","archaeology.museum","architecture.museum","art.museum","artanddesign.museum","artcenter.museum","artdeco.museum","arteducation.museum","artgallery.museum","arts.museum","artsandcrafts.museum","asmatart.museum","assassination.museum","assisi.museum","association.museum","astronomy.museum","atlanta.museum","austin.museum","australia.museum","automotive.museum","aviation.museum","axis.museum","badajoz.museum","baghdad.museum","bahn.museum","bale.museum","baltimore.museum","barcelona.museum","baseball.museum","basel.museum","baths.museum","bauern.museum","beauxarts.museum","beeldengeluid.museum","bellevue.museum","bergbau.museum","berkeley.museum","berlin.museum","bern.museum","bible.museum","bilbao.museum","bill.museum","birdart.museum","birthplace.museum","bonn.museum","boston.museum","botanical.museum","botanicalgarden.museum","botanicgarden.museum","botany.museum","brandywinevalley.museum","brasil.museum","bristol.museum","british.museum","britishcolumbia.museum","broadcast.museum","brunel.museum","brussel.museum","brussels.museum","bruxelles.museum","building.museum","burghof.museum","bus.museum","bushey.museum","cadaques.museum","california.museum","cambridge.museum","can.museum","canada.museum","capebreton.museum","carrier.museum","cartoonart.museum","casadelamoneda.museum","castle.museum","castres.museum","celtic.museum","center.museum","chattanooga.museum","cheltenham.museum","chesapeakebay.museum","chicago.museum","children.museum","childrens.museum","childrensgarden.museum","chiropractic.museum","chocolate.museum","christiansburg.museum","cincinnati.museum","cinema.museum","circus.museum","civilisation.museum","civilization.museum","civilwar.museum","clinton.museum","clock.museum","coal.museum","coastaldefence.museum","cody.museum","coldwar.museum","collection.museum","colonialwilliamsburg.museum","coloradoplateau.museum","columbia.museum","columbus.museum","communication.museum","communications.museum","community.museum","computer.museum","computerhistory.museum","comunicações.museum","contemporary.museum","contemporaryart.museum","convent.museum","copenhagen.museum","corporation.museum","correios-e-telecomunicações.museum","corvette.museum","costume.museum","countryestate.museum","county.museum","crafts.museum","cranbrook.museum","creation.museum","cultural.museum","culturalcenter.museum","culture.museum","cyber.museum","cymru.museum","dali.museum","dallas.museum","database.museum","ddr.museum","decorativearts.museum","delaware.museum","delmenhorst.museum","denmark.museum","depot.museum","design.museum","detroit.museum","dinosaur.museum","discovery.museum","dolls.museum","donostia.museum","durham.museum","eastafrica.museum","eastcoast.museum","education.museum","educational.museum","egyptian.museum","eisenbahn.museum","elburg.museum","elvendrell.museum","embroidery.museum","encyclopedic.museum","england.museum","entomology.museum","environment.museum","environmentalconservation.museum","epilepsy.museum","essex.museum","estate.museum","ethnology.museum","exeter.museum","exhibition.museum","family.museum","farm.museum","farmequipment.museum","farmers.museum","farmstead.museum","field.museum","figueres.museum","filatelia.museum","film.museum","fineart.museum","finearts.museum","finland.museum","flanders.museum","florida.museum","force.museum","fortmissoula.museum","fortworth.museum","foundation.museum","francaise.museum","frankfurt.museum","franziskaner.museum","freemasonry.museum","freiburg.museum","fribourg.museum","frog.museum","fundacio.museum","furniture.museum","gallery.museum","garden.museum","gateway.museum","geelvinck.museum","gemological.museum","geology.museum","georgia.museum","giessen.museum","glas.museum","glass.museum","gorge.museum","grandrapids.museum","graz.museum","guernsey.museum","halloffame.museum","hamburg.museum","handson.museum","harvestcelebration.museum","hawaii.museum","health.museum","heimatunduhren.museum","hellas.museum","helsinki.museum","hembygdsforbund.museum","heritage.museum","histoire.museum","historical.museum","historicalsociety.museum","historichouses.museum","historisch.museum","historisches.museum","history.museum","historyofscience.museum","horology.museum","house.museum","humanities.museum","illustration.museum","imageandsound.museum","indian.museum","indiana.museum","indianapolis.museum","indianmarket.museum","intelligence.museum","interactive.museum","iraq.museum","iron.museum","isleofman.museum","jamison.museum","jefferson.museum","jerusalem.museum","jewelry.museum","jewish.museum","jewishart.museum","jfk.museum","journalism.museum","judaica.museum","judygarland.museum","juedisches.museum","juif.museum","karate.museum","karikatur.museum","kids.museum","koebenhavn.museum","koeln.museum","kunst.museum","kunstsammlung.museum","kunstunddesign.museum","labor.museum","labour.museum","lajolla.museum","lancashire.museum","landes.museum","lans.museum","läns.museum","larsson.museum","lewismiller.museum","lincoln.museum","linz.museum","living.museum","livinghistory.museum","localhistory.museum","london.museum","losangeles.museum","louvre.museum","loyalist.museum","lucerne.museum","luxembourg.museum","luzern.museum","mad.museum","madrid.museum","mallorca.museum","manchester.museum","mansion.museum","mansions.museum","manx.museum","marburg.museum","maritime.museum","maritimo.museum","maryland.museum","marylhurst.museum","media.museum","medical.museum","medizinhistorisches.museum","meeres.museum","memorial.museum","mesaverde.museum","michigan.museum","midatlantic.museum","military.museum","mill.museum","miners.museum","mining.museum","minnesota.museum","missile.museum","missoula.museum","modern.museum","moma.museum","money.museum","monmouth.museum","monticello.museum","montreal.museum","moscow.museum","motorcycle.museum","muenchen.museum","muenster.museum","mulhouse.museum","muncie.museum","museet.museum","museumcenter.museum","museumvereniging.museum","music.museum","national.museum","nationalfirearms.museum","nationalheritage.museum","nativeamerican.museum","naturalhistory.museum","naturalhistorymuseum.museum","naturalsciences.museum","nature.museum","naturhistorisches.museum","natuurwetenschappen.museum","naumburg.museum","naval.museum","nebraska.museum","neues.museum","newhampshire.museum","newjersey.museum","newmexico.museum","newport.museum","newspaper.museum","newyork.museum","niepce.museum","norfolk.museum","north.museum","nrw.museum","nuernberg.museum","nuremberg.museum","nyc.museum","nyny.museum","oceanographic.museum","oceanographique.museum","omaha.museum","online.museum","ontario.museum","openair.museum","oregon.museum","oregontrail.museum","otago.museum","oxford.museum","pacific.museum","paderborn.museum","palace.museum","paleo.museum","palmsprings.museum","panama.museum","paris.museum","pasadena.museum","pharmacy.museum","philadelphia.museum","philadelphiaarea.museum","philately.museum","phoenix.museum","photography.museum","pilots.museum","pittsburgh.museum","planetarium.museum","plantation.museum","plants.museum","plaza.museum","portal.museum","portland.museum","portlligat.museum","posts-and-telecommunications.museum","preservation.museum","presidio.museum","press.museum","project.museum","public.museum","pubol.museum","quebec.museum","railroad.museum","railway.museum","research.museum","resistance.museum","riodejaneiro.museum","rochester.museum","rockart.museum","roma.museum","russia.museum","saintlouis.museum","salem.museum","salvadordali.museum","salzburg.museum","sandiego.museum","sanfrancisco.museum","santabarbara.museum","santacruz.museum","santafe.museum","saskatchewan.museum","satx.museum","savannahga.museum","schlesisches.museum","schoenbrunn.museum","schokoladen.museum","school.museum","schweiz.museum","science.museum","scienceandhistory.museum","scienceandindustry.museum","sciencecenter.museum","sciencecenters.museum","science-fiction.museum","sciencehistory.museum","sciences.museum","sciencesnaturelles.museum","scotland.museum","seaport.museum","settlement.museum","settlers.museum","shell.museum","sherbrooke.museum","sibenik.museum","silk.museum","ski.museum","skole.museum","society.museum","sologne.museum","soundandvision.museum","southcarolina.museum","southwest.museum","space.museum","spy.museum","square.museum","stadt.museum","stalbans.museum","starnberg.museum","state.museum","stateofdelaware.museum","station.museum","steam.museum","steiermark.museum","stjohn.museum","stockholm.museum","stpetersburg.museum","stuttgart.museum","suisse.museum","surgeonshall.museum","surrey.museum","svizzera.museum","sweden.museum","sydney.museum","tank.museum","tcm.museum","technology.museum","telekommunikation.museum","television.museum","texas.museum","textile.museum","theater.museum","time.museum","timekeeping.museum","topology.museum","torino.museum","touch.museum","town.museum","transport.museum","tree.museum","trolley.museum","trust.museum","trustee.museum","uhren.museum","ulm.museum","undersea.museum","university.museum","usa.museum","usantiques.museum","usarts.museum","uscountryestate.museum","usculture.museum","usdecorativearts.museum","usgarden.museum","ushistory.museum","ushuaia.museum","uslivinghistory.museum","utah.museum","uvic.museum","valley.museum","vantaa.museum","versailles.museum","viking.museum","village.museum","virginia.museum","virtual.museum","virtuel.museum","vlaanderen.museum","volkenkunde.museum","wales.museum","wallonie.museum","war.museum","washingtondc.museum","watchandclock.museum","watch-and-clock.museum","western.museum","westfalen.museum","whaling.museum","wildlife.museum","williamsburg.museum","windmill.museum","workshop.museum","york.museum","yorkshire.museum","yosemite.museum","youth.museum","zoological.museum","zoology.museum","ירושלים.museum","иком.museum","mv","aero.mv","biz.mv","com.mv","coop.mv","edu.mv","gov.mv","info.mv","int.mv","mil.mv","museum.mv","name.mv","net.mv","org.mv","pro.mv","mw","ac.mw","biz.mw","co.mw","com.mw","coop.mw","edu.mw","gov.mw","int.mw","museum.mw","net.mw","org.mw","mx","com.mx","org.mx","gob.mx","edu.mx","net.mx","my","com.my","net.my","org.my","gov.my","edu.my","mil.my","name.my","mz","ac.mz","adv.mz","co.mz","edu.mz","gov.mz","mil.mz","net.mz","org.mz","na","info.na","pro.na","name.na","school.na","or.na","dr.na","us.na","mx.na","ca.na","in.na","cc.na","tv.na","ws.na","mobi.na","co.na","com.na","org.na","name","nc","asso.nc","nom.nc","ne","net","nf","com.nf","net.nf","per.nf","rec.nf","web.nf","arts.nf","firm.nf","info.nf","other.nf","store.nf","ng","com.ng","edu.ng","gov.ng","i.ng","mil.ng","mobi.ng","name.ng","net.ng","org.ng","sch.ng","ni","ac.ni","biz.ni","co.ni","com.ni","edu.ni","gob.ni","in.ni","info.ni","int.ni","mil.ni","net.ni","nom.ni","org.ni","web.ni","nl","bv.nl","no","fhs.no","vgs.no","fylkesbibl.no","folkebibl.no","museum.no","idrett.no","priv.no","mil.no","stat.no","dep.no","kommune.no","herad.no","aa.no","ah.no","bu.no","fm.no","hl.no","hm.no","jan-mayen.no","mr.no","nl.no","nt.no","of.no","ol.no","oslo.no","rl.no","sf.no","st.no","svalbard.no","tm.no","tr.no","va.no","vf.no","gs.aa.no","gs.ah.no","gs.bu.no","gs.fm.no","gs.hl.no","gs.hm.no","gs.jan-mayen.no","gs.mr.no","gs.nl.no","gs.nt.no","gs.of.no","gs.ol.no","gs.oslo.no","gs.rl.no","gs.sf.no","gs.st.no","gs.svalbard.no","gs.tm.no","gs.tr.no","gs.va.no","gs.vf.no","akrehamn.no","åkrehamn.no","algard.no","ålgård.no","arna.no","brumunddal.no","bryne.no","bronnoysund.no","brønnøysund.no","drobak.no","drøbak.no","egersund.no","fetsund.no","floro.no","florø.no","fredrikstad.no","hokksund.no","honefoss.no","hønefoss.no","jessheim.no","jorpeland.no","jørpeland.no","kirkenes.no","kopervik.no","krokstadelva.no","langevag.no","langevåg.no","leirvik.no","mjondalen.no","mjøndalen.no","mo-i-rana.no","mosjoen.no","mosjøen.no","nesoddtangen.no","orkanger.no","osoyro.no","osøyro.no","raholt.no","råholt.no","sandnessjoen.no","sandnessjøen.no","skedsmokorset.no","slattum.no","spjelkavik.no","stathelle.no","stavern.no","stjordalshalsen.no","stjørdalshalsen.no","tananger.no","tranby.no","vossevangen.no","afjord.no","åfjord.no","agdenes.no","al.no","ål.no","alesund.no","ålesund.no","alstahaug.no","alta.no","áltá.no","alaheadju.no","álaheadju.no","alvdal.no","amli.no","åmli.no","amot.no","åmot.no","andebu.no","andoy.no","andøy.no","andasuolo.no","ardal.no","årdal.no","aremark.no","arendal.no","ås.no","aseral.no","åseral.no","asker.no","askim.no","askvoll.no","askoy.no","askøy.no","asnes.no","åsnes.no","audnedaln.no","aukra.no","aure.no","aurland.no","aurskog-holand.no","aurskog-høland.no","austevoll.no","austrheim.no","averoy.no","averøy.no","balestrand.no","ballangen.no","balat.no","bálát.no","balsfjord.no","bahccavuotna.no","báhccavuotna.no","bamble.no","bardu.no","beardu.no","beiarn.no","bajddar.no","bájddar.no","baidar.no","báidár.no","berg.no","bergen.no","berlevag.no","berlevåg.no","bearalvahki.no","bearalváhki.no","bindal.no","birkenes.no","bjarkoy.no","bjarkøy.no","bjerkreim.no","bjugn.no","bodo.no","bodø.no","badaddja.no","bådåddjå.no","budejju.no","bokn.no","bremanger.no","bronnoy.no","brønnøy.no","bygland.no","bykle.no","barum.no","bærum.no","bo.telemark.no","bø.telemark.no","bo.nordland.no","bø.nordland.no","bievat.no","bievát.no","bomlo.no","bømlo.no","batsfjord.no","båtsfjord.no","bahcavuotna.no","báhcavuotna.no","dovre.no","drammen.no","drangedal.no","dyroy.no","dyrøy.no","donna.no","dønna.no","eid.no","eidfjord.no","eidsberg.no","eidskog.no","eidsvoll.no","eigersund.no","elverum.no","enebakk.no","engerdal.no","etne.no","etnedal.no","evenes.no","evenassi.no","evenášši.no","evje-og-hornnes.no","farsund.no","fauske.no","fuossko.no","fuoisku.no","fedje.no","fet.no","finnoy.no","finnøy.no","fitjar.no","fjaler.no","fjell.no","flakstad.no","flatanger.no","flekkefjord.no","flesberg.no","flora.no","fla.no","flå.no","folldal.no","forsand.no","fosnes.no","frei.no","frogn.no","froland.no","frosta.no","frana.no","fræna.no","froya.no","frøya.no","fusa.no","fyresdal.no","forde.no","førde.no","gamvik.no","gangaviika.no","gáŋgaviika.no","gaular.no","gausdal.no","gildeskal.no","gildeskål.no","giske.no","gjemnes.no","gjerdrum.no","gjerstad.no","gjesdal.no","gjovik.no","gjøvik.no","gloppen.no","gol.no","gran.no","grane.no","granvin.no","gratangen.no","grimstad.no","grong.no","kraanghke.no","kråanghke.no","grue.no","gulen.no","hadsel.no","halden.no","halsa.no","hamar.no","hamaroy.no","habmer.no","hábmer.no","hapmir.no","hápmir.no","hammerfest.no","hammarfeasta.no","hámmárfeasta.no","haram.no","hareid.no","harstad.no","hasvik.no","aknoluokta.no","ákŋoluokta.no","hattfjelldal.no","aarborte.no","haugesund.no","hemne.no","hemnes.no","hemsedal.no","heroy.more-og-romsdal.no","herøy.møre-og-romsdal.no","heroy.nordland.no","herøy.nordland.no","hitra.no","hjartdal.no","hjelmeland.no","hobol.no","hobøl.no","hof.no","hol.no","hole.no","holmestrand.no","holtalen.no","holtålen.no","hornindal.no","horten.no","hurdal.no","hurum.no","hvaler.no","hyllestad.no","hagebostad.no","hægebostad.no","hoyanger.no","høyanger.no","hoylandet.no","høylandet.no","ha.no","hå.no","ibestad.no","inderoy.no","inderøy.no","iveland.no","jevnaker.no","jondal.no","jolster.no","jølster.no","karasjok.no","karasjohka.no","kárášjohka.no","karlsoy.no","galsa.no","gálsá.no","karmoy.no","karmøy.no","kautokeino.no","guovdageaidnu.no","klepp.no","klabu.no","klæbu.no","kongsberg.no","kongsvinger.no","kragero.no","kragerø.no","kristiansand.no","kristiansund.no","krodsherad.no","krødsherad.no","kvalsund.no","rahkkeravju.no","ráhkkerávju.no","kvam.no","kvinesdal.no","kvinnherad.no","kviteseid.no","kvitsoy.no","kvitsøy.no","kvafjord.no","kvæfjord.no","giehtavuoatna.no","kvanangen.no","kvænangen.no","navuotna.no","návuotna.no","kafjord.no","kåfjord.no","gaivuotna.no","gáivuotna.no","larvik.no","lavangen.no","lavagis.no","loabat.no","loabát.no","lebesby.no","davvesiida.no","leikanger.no","leirfjord.no","leka.no","leksvik.no","lenvik.no","leangaviika.no","leaŋgaviika.no","lesja.no","levanger.no","lier.no","lierne.no","lillehammer.no","lillesand.no","lindesnes.no","lindas.no","lindås.no","lom.no","loppa.no","lahppi.no","láhppi.no","lund.no","lunner.no","luroy.no","lurøy.no","luster.no","lyngdal.no","lyngen.no","ivgu.no","lardal.no","lerdal.no","lærdal.no","lodingen.no","lødingen.no","lorenskog.no","lørenskog.no","loten.no","løten.no","malvik.no","masoy.no","måsøy.no","muosat.no","muosát.no","mandal.no","marker.no","marnardal.no","masfjorden.no","meland.no","meldal.no","melhus.no","meloy.no","meløy.no","meraker.no","meråker.no","moareke.no","moåreke.no","midsund.no","midtre-gauldal.no","modalen.no","modum.no","molde.no","moskenes.no","moss.no","mosvik.no","malselv.no","målselv.no","malatvuopmi.no","málatvuopmi.no","namdalseid.no","aejrie.no","namsos.no","namsskogan.no","naamesjevuemie.no","nååmesjevuemie.no","laakesvuemie.no","nannestad.no","narvik.no","narviika.no","naustdal.no","nedre-eiker.no","nes.akershus.no","nes.buskerud.no","nesna.no","nesodden.no","nesseby.no","unjarga.no","unjárga.no","nesset.no","nissedal.no","nittedal.no","nord-aurdal.no","nord-fron.no","nord-odal.no","norddal.no","nordkapp.no","davvenjarga.no","davvenjárga.no","nordre-land.no","nordreisa.no","raisa.no","ráisa.no","nore-og-uvdal.no","notodden.no","naroy.no","nærøy.no","notteroy.no","nøtterøy.no","odda.no","oksnes.no","øksnes.no","oppdal.no","oppegard.no","oppegård.no","orkdal.no","orland.no","ørland.no","orskog.no","ørskog.no","orsta.no","ørsta.no","os.hedmark.no","os.hordaland.no","osen.no","osteroy.no","osterøy.no","ostre-toten.no","østre-toten.no","overhalla.no","ovre-eiker.no","øvre-eiker.no","oyer.no","øyer.no","oygarden.no","øygarden.no","oystre-slidre.no","øystre-slidre.no","porsanger.no","porsangu.no","porsáŋgu.no","porsgrunn.no","radoy.no","radøy.no","rakkestad.no","rana.no","ruovat.no","randaberg.no","rauma.no","rendalen.no","rennebu.no","rennesoy.no","rennesøy.no","rindal.no","ringebu.no","ringerike.no","ringsaker.no","rissa.no","risor.no","risør.no","roan.no","rollag.no","rygge.no","ralingen.no","rælingen.no","rodoy.no","rødøy.no","romskog.no","rømskog.no","roros.no","røros.no","rost.no","røst.no","royken.no","røyken.no","royrvik.no","røyrvik.no","rade.no","råde.no","salangen.no","siellak.no","saltdal.no","salat.no","sálát.no","sálat.no","samnanger.no","sande.more-og-romsdal.no","sande.møre-og-romsdal.no","sande.vestfold.no","sandefjord.no","sandnes.no","sandoy.no","sandøy.no","sarpsborg.no","sauda.no","sauherad.no","sel.no","selbu.no","selje.no","seljord.no","sigdal.no","siljan.no","sirdal.no","skaun.no","skedsmo.no","ski.no","skien.no","skiptvet.no","skjervoy.no","skjervøy.no","skierva.no","skiervá.no","skjak.no","skjåk.no","skodje.no","skanland.no","skånland.no","skanit.no","skánit.no","smola.no","smøla.no","snillfjord.no","snasa.no","snåsa.no","snoasa.no","snaase.no","snåase.no","sogndal.no","sokndal.no","sola.no","solund.no","songdalen.no","sortland.no","spydeberg.no","stange.no","stavanger.no","steigen.no","steinkjer.no","stjordal.no","stjørdal.no","stokke.no","stor-elvdal.no","stord.no","stordal.no","storfjord.no","omasvuotna.no","strand.no","stranda.no","stryn.no","sula.no","suldal.no","sund.no","sunndal.no","surnadal.no","sveio.no","svelvik.no","sykkylven.no","sogne.no","søgne.no","somna.no","sømna.no","sondre-land.no","søndre-land.no","sor-aurdal.no","sør-aurdal.no","sor-fron.no","sør-fron.no","sor-odal.no","sør-odal.no","sor-varanger.no","sør-varanger.no","matta-varjjat.no","mátta-várjjat.no","sorfold.no","sørfold.no","sorreisa.no","sørreisa.no","sorum.no","sørum.no","tana.no","deatnu.no","time.no","tingvoll.no","tinn.no","tjeldsund.no","dielddanuorri.no","tjome.no","tjøme.no","tokke.no","tolga.no","torsken.no","tranoy.no","tranøy.no","tromso.no","tromsø.no","tromsa.no","romsa.no","trondheim.no","troandin.no","trysil.no","trana.no","træna.no","trogstad.no","trøgstad.no","tvedestrand.no","tydal.no","tynset.no","tysfjord.no","divtasvuodna.no","divttasvuotna.no","tysnes.no","tysvar.no","tysvær.no","tonsberg.no","tønsberg.no","ullensaker.no","ullensvang.no","ulvik.no","utsira.no","vadso.no","vadsø.no","cahcesuolo.no","čáhcesuolo.no","vaksdal.no","valle.no","vang.no","vanylven.no","vardo.no","vardø.no","varggat.no","várggát.no","vefsn.no","vaapste.no","vega.no","vegarshei.no","vegårshei.no","vennesla.no","verdal.no","verran.no","vestby.no","vestnes.no","vestre-slidre.no","vestre-toten.no","vestvagoy.no","vestvågøy.no","vevelstad.no","vik.no","vikna.no","vindafjord.no","volda.no","voss.no","varoy.no","værøy.no","vagan.no","vågan.no","voagat.no","vagsoy.no","vågsøy.no","vaga.no","vågå.no","valer.ostfold.no","våler.østfold.no","valer.hedmark.no","våler.hedmark.no","*.np","nr","biz.nr","info.nr","gov.nr","edu.nr","org.nr","net.nr","com.nr","nu","nz","ac.nz","co.nz","cri.nz","geek.nz","gen.nz","govt.nz","health.nz","iwi.nz","kiwi.nz","maori.nz","mil.nz","māori.nz","net.nz","org.nz","parliament.nz","school.nz","om","co.om","com.om","edu.om","gov.om","med.om","museum.om","net.om","org.om","pro.om","onion","org","pa","ac.pa","gob.pa","com.pa","org.pa","sld.pa","edu.pa","net.pa","ing.pa","abo.pa","med.pa","nom.pa","pe","edu.pe","gob.pe","nom.pe","mil.pe","org.pe","com.pe","net.pe","pf","com.pf","org.pf","edu.pf","*.pg","ph","com.ph","net.ph","org.ph","gov.ph","edu.ph","ngo.ph","mil.ph","i.ph","pk","com.pk","net.pk","edu.pk","org.pk","fam.pk","biz.pk","web.pk","gov.pk","gob.pk","gok.pk","gon.pk","gop.pk","gos.pk","info.pk","pl","com.pl","net.pl","org.pl","aid.pl","agro.pl","atm.pl","auto.pl","biz.pl","edu.pl","gmina.pl","gsm.pl","info.pl","mail.pl","miasta.pl","media.pl","mil.pl","nieruchomosci.pl","nom.pl","pc.pl","powiat.pl","priv.pl","realestate.pl","rel.pl","sex.pl","shop.pl","sklep.pl","sos.pl","szkola.pl","targi.pl","tm.pl","tourism.pl","travel.pl","turystyka.pl","gov.pl","ap.gov.pl","ic.gov.pl","is.gov.pl","us.gov.pl","kmpsp.gov.pl","kppsp.gov.pl","kwpsp.gov.pl","psp.gov.pl","wskr.gov.pl","kwp.gov.pl","mw.gov.pl","ug.gov.pl","um.gov.pl","umig.gov.pl","ugim.gov.pl","upow.gov.pl","uw.gov.pl","starostwo.gov.pl","pa.gov.pl","po.gov.pl","psse.gov.pl","pup.gov.pl","rzgw.gov.pl","sa.gov.pl","so.gov.pl","sr.gov.pl","wsa.gov.pl","sko.gov.pl","uzs.gov.pl","wiih.gov.pl","winb.gov.pl","pinb.gov.pl","wios.gov.pl","witd.gov.pl","wzmiuw.gov.pl","piw.gov.pl","wiw.gov.pl","griw.gov.pl","wif.gov.pl","oum.gov.pl","sdn.gov.pl","zp.gov.pl","uppo.gov.pl","mup.gov.pl","wuoz.gov.pl","konsulat.gov.pl","oirm.gov.pl","augustow.pl","babia-gora.pl","bedzin.pl","beskidy.pl","bialowieza.pl","bialystok.pl","bielawa.pl","bieszczady.pl","boleslawiec.pl","bydgoszcz.pl","bytom.pl","cieszyn.pl","czeladz.pl","czest.pl","dlugoleka.pl","elblag.pl","elk.pl","glogow.pl","gniezno.pl","gorlice.pl","grajewo.pl","ilawa.pl","jaworzno.pl","jelenia-gora.pl","jgora.pl","kalisz.pl","kazimierz-dolny.pl","karpacz.pl","kartuzy.pl","kaszuby.pl","katowice.pl","kepno.pl","ketrzyn.pl","klodzko.pl","kobierzyce.pl","kolobrzeg.pl","konin.pl","konskowola.pl","kutno.pl","lapy.pl","lebork.pl","legnica.pl","lezajsk.pl","limanowa.pl","lomza.pl","lowicz.pl","lubin.pl","lukow.pl","malbork.pl","malopolska.pl","mazowsze.pl","mazury.pl","mielec.pl","mielno.pl","mragowo.pl","naklo.pl","nowaruda.pl","nysa.pl","olawa.pl","olecko.pl","olkusz.pl","olsztyn.pl","opoczno.pl","opole.pl","ostroda.pl","ostroleka.pl","ostrowiec.pl","ostrowwlkp.pl","pila.pl","pisz.pl","podhale.pl","podlasie.pl","polkowice.pl","pomorze.pl","pomorskie.pl","prochowice.pl","pruszkow.pl","przeworsk.pl","pulawy.pl","radom.pl","rawa-maz.pl","rybnik.pl","rzeszow.pl","sanok.pl","sejny.pl","slask.pl","slupsk.pl","sosnowiec.pl","stalowa-wola.pl","skoczow.pl","starachowice.pl","stargard.pl","suwalki.pl","swidnica.pl","swiebodzin.pl","swinoujscie.pl","szczecin.pl","szczytno.pl","tarnobrzeg.pl","tgory.pl","turek.pl","tychy.pl","ustka.pl","walbrzych.pl","warmia.pl","warszawa.pl","waw.pl","wegrow.pl","wielun.pl","wlocl.pl","wloclawek.pl","wodzislaw.pl","wolomin.pl","wroclaw.pl","zachpomor.pl","zagan.pl","zarow.pl","zgora.pl","zgorzelec.pl","pm","pn","gov.pn","co.pn","org.pn","edu.pn","net.pn","post","pr","com.pr","net.pr","org.pr","gov.pr","edu.pr","isla.pr","pro.pr","biz.pr","info.pr","name.pr","est.pr","prof.pr","ac.pr","pro","aaa.pro","aca.pro","acct.pro","avocat.pro","bar.pro","cpa.pro","eng.pro","jur.pro","law.pro","med.pro","recht.pro","ps","edu.ps","gov.ps","sec.ps","plo.ps","com.ps","org.ps","net.ps","pt","net.pt","gov.pt","org.pt","edu.pt","int.pt","publ.pt","com.pt","nome.pt","pw","co.pw","ne.pw","or.pw","ed.pw","go.pw","belau.pw","py","com.py","coop.py","edu.py","gov.py","mil.py","net.py","org.py","qa","com.qa","edu.qa","gov.qa","mil.qa","name.qa","net.qa","org.qa","sch.qa","re","asso.re","com.re","nom.re","ro","arts.ro","com.ro","firm.ro","info.ro","nom.ro","nt.ro","org.ro","rec.ro","store.ro","tm.ro","www.ro","rs","ac.rs","co.rs","edu.rs","gov.rs","in.rs","org.rs","ru","ac.ru","edu.ru","gov.ru","int.ru","mil.ru","test.ru","rw","gov.rw","net.rw","edu.rw","ac.rw","com.rw","co.rw","int.rw","mil.rw","gouv.rw","sa","com.sa","net.sa","org.sa","gov.sa","med.sa","pub.sa","edu.sa","sch.sa","sb","com.sb","edu.sb","gov.sb","net.sb","org.sb","sc","com.sc","gov.sc","net.sc","org.sc","edu.sc","sd","com.sd","net.sd","org.sd","edu.sd","med.sd","tv.sd","gov.sd","info.sd","se","a.se","ac.se","b.se","bd.se","brand.se","c.se","d.se","e.se","f.se","fh.se","fhsk.se","fhv.se","g.se","h.se","i.se","k.se","komforb.se","kommunalforbund.se","komvux.se","l.se","lanbib.se","m.se","n.se","naturbruksgymn.se","o.se","org.se","p.se","parti.se","pp.se","press.se","r.se","s.se","t.se","tm.se","u.se","w.se","x.se","y.se","z.se","sg","com.sg","net.sg","org.sg","gov.sg","edu.sg","per.sg","sh","com.sh","net.sh","gov.sh","org.sh","mil.sh","si","sj","sk","sl","com.sl","net.sl","edu.sl","gov.sl","org.sl","sm","sn","art.sn","com.sn","edu.sn","gouv.sn","org.sn","perso.sn","univ.sn","so","com.so","net.so","org.so","sr","st","co.st","com.st","consulado.st","edu.st","embaixada.st","gov.st","mil.st","net.st","org.st","principe.st","saotome.st","store.st","su","sv","com.sv","edu.sv","gob.sv","org.sv","red.sv","sx","gov.sx","sy","edu.sy","gov.sy","net.sy","mil.sy","com.sy","org.sy","sz","co.sz","ac.sz","org.sz","tc","td","tel","tf","tg","th","ac.th","co.th","go.th","in.th","mi.th","net.th","or.th","tj","ac.tj","biz.tj","co.tj","com.tj","edu.tj","go.tj","gov.tj","int.tj","mil.tj","name.tj","net.tj","nic.tj","org.tj","test.tj","web.tj","tk","tl","gov.tl","tm","com.tm","co.tm","org.tm","net.tm","nom.tm","gov.tm","mil.tm","edu.tm","tn","com.tn","ens.tn","fin.tn","gov.tn","ind.tn","intl.tn","nat.tn","net.tn","org.tn","info.tn","perso.tn","tourism.tn","edunet.tn","rnrt.tn","rns.tn","rnu.tn","mincom.tn","agrinet.tn","defense.tn","turen.tn","to","com.to","gov.to","net.to","org.to","edu.to","mil.to","tr","com.tr","info.tr","biz.tr","net.tr","org.tr","web.tr","gen.tr","tv.tr","av.tr","dr.tr","bbs.tr","name.tr","tel.tr","gov.tr","bel.tr","pol.tr","mil.tr","k12.tr","edu.tr","kep.tr","nc.tr","gov.nc.tr","tt","co.tt","com.tt","org.tt","net.tt","biz.tt","info.tt","pro.tt","int.tt","coop.tt","jobs.tt","mobi.tt","travel.tt","museum.tt","aero.tt","name.tt","gov.tt","edu.tt","tv","tw","edu.tw","gov.tw","mil.tw","com.tw","net.tw","org.tw","idv.tw","game.tw","ebiz.tw","club.tw","網路.tw","組織.tw","商業.tw","tz","ac.tz","co.tz","go.tz","hotel.tz","info.tz","me.tz","mil.tz","mobi.tz","ne.tz","or.tz","sc.tz","tv.tz","ua","com.ua","edu.ua","gov.ua","in.ua","net.ua","org.ua","cherkassy.ua","cherkasy.ua","chernigov.ua","chernihiv.ua","chernivtsi.ua","chernovtsy.ua","ck.ua","cn.ua","cr.ua","crimea.ua","cv.ua","dn.ua","dnepropetrovsk.ua","dnipropetrovsk.ua","dominic.ua","donetsk.ua","dp.ua","if.ua","ivano-frankivsk.ua","kh.ua","kharkiv.ua","kharkov.ua","kherson.ua","khmelnitskiy.ua","khmelnytskyi.ua","kiev.ua","kirovograd.ua","km.ua","kr.ua","krym.ua","ks.ua","kv.ua","kyiv.ua","lg.ua","lt.ua","lugansk.ua","lutsk.ua","lv.ua","lviv.ua","mk.ua","mykolaiv.ua","nikolaev.ua","od.ua","odesa.ua","odessa.ua","pl.ua","poltava.ua","rivne.ua","rovno.ua","rv.ua","sb.ua","sebastopol.ua","sevastopol.ua","sm.ua","sumy.ua","te.ua","ternopil.ua","uz.ua","uzhgorod.ua","vinnica.ua","vinnytsia.ua","vn.ua","volyn.ua","yalta.ua","zaporizhzhe.ua","zaporizhzhia.ua","zhitomir.ua","zhytomyr.ua","zp.ua","zt.ua","ug","co.ug","or.ug","ac.ug","sc.ug","go.ug","ne.ug","com.ug","org.ug","uk","ac.uk","co.uk","gov.uk","ltd.uk","me.uk","net.uk","nhs.uk","org.uk","plc.uk","police.uk","*.sch.uk","us","dni.us","fed.us","isa.us","kids.us","nsn.us","ak.us","al.us","ar.us","as.us","az.us","ca.us","co.us","ct.us","dc.us","de.us","fl.us","ga.us","gu.us","hi.us","ia.us","id.us","il.us","in.us","ks.us","ky.us","la.us","ma.us","md.us","me.us","mi.us","mn.us","mo.us","ms.us","mt.us","nc.us","nd.us","ne.us","nh.us","nj.us","nm.us","nv.us","ny.us","oh.us","ok.us","or.us","pa.us","pr.us","ri.us","sc.us","sd.us","tn.us","tx.us","ut.us","vi.us","vt.us","va.us","wa.us","wi.us","wv.us","wy.us","k12.ak.us","k12.al.us","k12.ar.us","k12.as.us","k12.az.us","k12.ca.us","k12.co.us","k12.ct.us","k12.dc.us","k12.de.us","k12.fl.us","k12.ga.us","k12.gu.us","k12.ia.us","k12.id.us","k12.il.us","k12.in.us","k12.ks.us","k12.ky.us","k12.la.us","k12.ma.us","k12.md.us","k12.me.us","k12.mi.us","k12.mn.us","k12.mo.us","k12.ms.us","k12.mt.us","k12.nc.us","k12.ne.us","k12.nh.us","k12.nj.us","k12.nm.us","k12.nv.us","k12.ny.us","k12.oh.us","k12.ok.us","k12.or.us","k12.pa.us","k12.pr.us","k12.ri.us","k12.sc.us","k12.tn.us","k12.tx.us","k12.ut.us","k12.vi.us","k12.vt.us","k12.va.us","k12.wa.us","k12.wi.us","k12.wy.us","cc.ak.us","cc.al.us","cc.ar.us","cc.as.us","cc.az.us","cc.ca.us","cc.co.us","cc.ct.us","cc.dc.us","cc.de.us","cc.fl.us","cc.ga.us","cc.gu.us","cc.hi.us","cc.ia.us","cc.id.us","cc.il.us","cc.in.us","cc.ks.us","cc.ky.us","cc.la.us","cc.ma.us","cc.md.us","cc.me.us","cc.mi.us","cc.mn.us","cc.mo.us","cc.ms.us","cc.mt.us","cc.nc.us","cc.nd.us","cc.ne.us","cc.nh.us","cc.nj.us","cc.nm.us","cc.nv.us","cc.ny.us","cc.oh.us","cc.ok.us","cc.or.us","cc.pa.us","cc.pr.us","cc.ri.us","cc.sc.us","cc.sd.us","cc.tn.us","cc.tx.us","cc.ut.us","cc.vi.us","cc.vt.us","cc.va.us","cc.wa.us","cc.wi.us","cc.wv.us","cc.wy.us","lib.ak.us","lib.al.us","lib.ar.us","lib.as.us","lib.az.us","lib.ca.us","lib.co.us","lib.ct.us","lib.dc.us","lib.fl.us","lib.ga.us","lib.gu.us","lib.hi.us","lib.ia.us","lib.id.us","lib.il.us","lib.in.us","lib.ks.us","lib.ky.us","lib.la.us","lib.ma.us","lib.md.us","lib.me.us","lib.mi.us","lib.mn.us","lib.mo.us","lib.ms.us","lib.mt.us","lib.nc.us","lib.nd.us","lib.ne.us","lib.nh.us","lib.nj.us","lib.nm.us","lib.nv.us","lib.ny.us","lib.oh.us","lib.ok.us","lib.or.us","lib.pa.us","lib.pr.us","lib.ri.us","lib.sc.us","lib.sd.us","lib.tn.us","lib.tx.us","lib.ut.us","lib.vi.us","lib.vt.us","lib.va.us","lib.wa.us","lib.wi.us","lib.wy.us","pvt.k12.ma.us","chtr.k12.ma.us","paroch.k12.ma.us","ann-arbor.mi.us","cog.mi.us","dst.mi.us","eaton.mi.us","gen.mi.us","mus.mi.us","tec.mi.us","washtenaw.mi.us","uy","com.uy","edu.uy","gub.uy","mil.uy","net.uy","org.uy","uz","co.uz","com.uz","net.uz","org.uz","va","vc","com.vc","net.vc","org.vc","gov.vc","mil.vc","edu.vc","ve","arts.ve","co.ve","com.ve","e12.ve","edu.ve","firm.ve","gob.ve","gov.ve","info.ve","int.ve","mil.ve","net.ve","org.ve","rec.ve","store.ve","tec.ve","web.ve","vg","vi","co.vi","com.vi","k12.vi","net.vi","org.vi","vn","com.vn","net.vn","org.vn","edu.vn","gov.vn","int.vn","ac.vn","biz.vn","info.vn","name.vn","pro.vn","health.vn","vu","com.vu","edu.vu","net.vu","org.vu","wf","ws","com.ws","net.ws","org.ws","gov.ws","edu.ws","yt","امارات","հայ","বাংলা","бг","бел","中国","中國","الجزائر","مصر","ею","გე","ελ","香港","公司.香港","教育.香港","政府.香港","個人.香港","網絡.香港","組織.香港","ಭಾರತ","ଭାରତ","ভাৰত","भारतम्","भारोत","ڀارت","ഭാരതം","भारत","بارت","بھارت","భారత్","ભારત","ਭਾਰਤ","ভারত","இந்தியா","ایران","ايران","عراق","الاردن","한국","қаз","ලංකා","இலங்கை","المغرب","мкд","мон","澳門","澳门","مليسيا","عمان","پاکستان","پاكستان","فلسطين","срб","пр.срб","орг.срб","обр.срб","од.срб","упр.срб","ак.срб","рф","قطر","السعودية","السعودیة","السعودیۃ","السعوديه","سودان","新加坡","சிங்கப்பூர்","سورية","سوريا","ไทย","ศึกษา.ไทย","ธุรกิจ.ไทย","รัฐบาล.ไทย","ทหาร.ไทย","เน็ต.ไทย","องค์กร.ไทย","تونس","台灣","台湾","臺灣","укр","اليمن","xxx","*.ye","ac.za","agric.za","alt.za","co.za","edu.za","gov.za","grondar.za","law.za","mil.za","net.za","ngo.za","nis.za","nom.za","org.za","school.za","tm.za","web.za","zm","ac.zm","biz.zm","co.zm","com.zm","edu.zm","gov.zm","info.zm","mil.zm","net.zm","org.zm","sch.zm","zw","ac.zw","co.zw","gov.zw","mil.zw","org.zw","aaa","aarp","abarth","abb","abbott","abbvie","abc","able","abogado","abudhabi","academy","accenture","accountant","accountants","aco","active","actor","adac","ads","adult","aeg","aetna","afamilycompany","afl","africa","agakhan","agency","aig","aigo","airbus","airforce","airtel","akdn","alfaromeo","alibaba","alipay","allfinanz","allstate","ally","alsace","alstom","americanexpress","americanfamily","amex","amfam","amica","amsterdam","analytics","android","anquan","anz","aol","apartments","app","apple","aquarelle","arab","aramco","archi","army","art","arte","asda","associates","athleta","attorney","auction","audi","audible","audio","auspost","author","auto","autos","avianca","aws","axa","azure","baby","baidu","banamex","bananarepublic","band","bank","bar","barcelona","barclaycard","barclays","barefoot","bargains","baseball","basketball","bauhaus","bayern","bbc","bbt","bbva","bcg","bcn","beats","beauty","beer","bentley","berlin","best","bestbuy","bet","bharti","bible","bid","bike","bing","bingo","bio","black","blackfriday","blanco","blockbuster","blog","bloomberg","blue","bms","bmw","bnl","bnpparibas","boats","boehringer","bofa","bom","bond","boo","book","booking","bosch","bostik","boston","bot","boutique","box","bradesco","bridgestone","broadway","broker","brother","brussels","budapest","bugatti","build","builders","business","buy","buzz","bzh","cab","cafe","cal","call","calvinklein","cam","camera","camp","cancerresearch","canon","capetown","capital","capitalone","car","caravan","cards","care","career","careers","cars","cartier","casa","case","caseih","cash","casino","catering","catholic","cba","cbn","cbre","cbs","ceb","center","ceo","cern","cfa","cfd","chanel","channel","charity","chase","chat","cheap","chintai","christmas","chrome","chrysler","church","cipriani","circle","cisco","citadel","citi","citic","city","cityeats","claims","cleaning","click","clinic","clinique","clothing","cloud","club","clubmed","coach","codes","coffee","college","cologne","comcast","commbank","community","company","compare","computer","comsec","condos","construction","consulting","contact","contractors","cooking","cookingchannel","cool","corsica","country","coupon","coupons","courses","credit","creditcard","creditunion","cricket","crown","crs","cruise","cruises","csc","cuisinella","cymru","cyou","dabur","dad","dance","data","date","dating","datsun","day","dclk","dds","deal","dealer","deals","degree","delivery","dell","deloitte","delta","democrat","dental","dentist","desi","design","dev","dhl","diamonds","diet","digital","direct","directory","discount","discover","dish","diy","dnp","docs","doctor","dodge","dog","doha","domains","dot","download","drive","dtv","dubai","duck","dunlop","duns","dupont","durban","dvag","dvr","earth","eat","eco","edeka","education","email","emerck","energy","engineer","engineering","enterprises","epost","epson","equipment","ericsson","erni","esq","estate","esurance","etisalat","eurovision","eus","events","everbank","exchange","expert","exposed","express","extraspace","fage","fail","fairwinds","faith","family","fan","fans","farm","farmers","fashion","fast","fedex","feedback","ferrari","ferrero","fiat","fidelity","fido","film","final","finance","financial","fire","firestone","firmdale","fish","fishing","fit","fitness","flickr","flights","flir","florist","flowers","fly","foo","food","foodnetwork","football","ford","forex","forsale","forum","foundation","fox","free","fresenius","frl","frogans","frontdoor","frontier","ftr","fujitsu","fujixerox","fun","fund","furniture","futbol","fyi","gal","gallery","gallo","gallup","game","games","gap","garden","gbiz","gdn","gea","gent","genting","george","ggee","gift","gifts","gives","giving","glade","glass","gle","global","globo","gmail","gmbh","gmo","gmx","godaddy","gold","goldpoint","golf","goo","goodyear","goog","google","gop","got","grainger","graphics","gratis","green","gripe","grocery","group","guardian","gucci","guge","guide","guitars","guru","hair","hamburg","hangout","haus","hbo","hdfc","hdfcbank","health","healthcare","help","helsinki","here","hermes","hgtv","hiphop","hisamitsu","hitachi","hiv","hkt","hockey","holdings","holiday","homedepot","homegoods","homes","homesense","honda","honeywell","horse","hospital","host","hosting","hot","hoteles","hotels","hotmail","house","how","hsbc","hughes","hyatt","hyundai","ibm","icbc","ice","icu","ieee","ifm","ikano","imamat","imdb","immo","immobilien","inc","industries","infiniti","ing","ink","institute","insurance","insure","intel","international","intuit","investments","ipiranga","irish","iselect","ismaili","ist","istanbul","itau","itv","iveco","jaguar","java","jcb","jcp","jeep","jetzt","jewelry","jio","jll","jmp","jnj","joburg","jot","joy","jpmorgan","jprs","juegos","juniper","kaufen","kddi","kerryhotels","kerrylogistics","kerryproperties","kfh","kia","kim","kinder","kindle","kitchen","kiwi","koeln","komatsu","kosher","kpmg","kpn","krd","kred","kuokgroup","kyoto","lacaixa","ladbrokes","lamborghini","lamer","lancaster","lancia","lancome","land","landrover","lanxess","lasalle","lat","latino","latrobe","law","lawyer","lds","lease","leclerc","lefrak","legal","lego","lexus","lgbt","liaison","lidl","life","lifeinsurance","lifestyle","lighting","like","lilly","limited","limo","lincoln","linde","link","lipsy","live","living","lixil","llc","loan","loans","locker","locus","loft","lol","london","lotte","lotto","love","lpl","lplfinancial","ltd","ltda","lundbeck","lupin","luxe","luxury","macys","madrid","maif","maison","makeup","man","management","mango","map","market","marketing","markets","marriott","marshalls","maserati","mattel","mba","mckinsey","med","media","meet","melbourne","meme","memorial","men","menu","merckmsd","metlife","miami","microsoft","mini","mint","mit","mitsubishi","mlb","mls","mma","mobile","mobily","moda","moe","moi","mom","monash","money","monster","mopar","mormon","mortgage","moscow","moto","motorcycles","mov","movie","movistar","msd","mtn","mtr","mutual","nab","nadex","nagoya","nationwide","natura","navy","nba","nec","netbank","netflix","network","neustar","new","newholland","news","next","nextdirect","nexus","nfl","ngo","nhk","nico","nike","nikon","ninja","nissan","nissay","nokia","northwesternmutual","norton","now","nowruz","nowtv","nra","nrw","ntt","nyc","obi","observer","off","office","okinawa","olayan","olayangroup","oldnavy","ollo","omega","one","ong","onl","online","onyourside","ooo","open","oracle","orange","organic","origins","osaka","otsuka","ott","ovh","page","panasonic","paris","pars","partners","parts","party","passagens","pay","pccw","pet","pfizer","pharmacy","phd","philips","phone","photo","photography","photos","physio","piaget","pics","pictet","pictures","pid","pin","ping","pink","pioneer","pizza","place","play","playstation","plumbing","plus","pnc","pohl","poker","politie","porn","pramerica","praxi","press","prime","prod","productions","prof","progressive","promo","properties","property","protection","pru","prudential","pub","pwc","qpon","quebec","quest","qvc","racing","radio","raid","read","realestate","realtor","realty","recipes","red","redstone","redumbrella","rehab","reise","reisen","reit","reliance","ren","rent","rentals","repair","report","republican","rest","restaurant","review","reviews","rexroth","rich","richardli","ricoh","rightathome","ril","rio","rip","rmit","rocher","rocks","rodeo","rogers","room","rsvp","rugby","ruhr","run","rwe","ryukyu","saarland","safe","safety","sakura","sale","salon","samsclub","samsung","sandvik","sandvikcoromant","sanofi","sap","sarl","sas","save","saxo","sbi","sbs","sca","scb","schaeffler","schmidt","scholarships","school","schule","schwarz","science","scjohnson","scor","scot","search","seat","secure","security","seek","select","sener","services","ses","seven","sew","sex","sexy","sfr","shangrila","sharp","shaw","shell","shia","shiksha","shoes","shop","shopping","shouji","show","showtime","shriram","silk","sina","singles","site","ski","skin","sky","skype","sling","smart","smile","sncf","soccer","social","softbank","software","sohu","solar","solutions","song","sony","soy","space","spiegel","sport","spot","spreadbetting","srl","srt","stada","staples","star","starhub","statebank","statefarm","statoil","stc","stcgroup","stockholm","storage","store","stream","studio","study","style","sucks","supplies","supply","support","surf","surgery","suzuki","swatch","swiftcover","swiss","sydney","symantec","systems","tab","taipei","talk","taobao","target","tatamotors","tatar","tattoo","tax","taxi","tci","tdk","team","tech","technology","telefonica","temasek","tennis","teva","thd","theater","theatre","tiaa","tickets","tienda","tiffany","tips","tires","tirol","tjmaxx","tjx","tkmaxx","tmall","today","tokyo","tools","top","toray","toshiba","total","tours","town","toyota","toys","trade","trading","training","travel","travelchannel","travelers","travelersinsurance","trust","trv","tube","tui","tunes","tushu","tvs","ubank","ubs","uconnect","unicom","university","uno","uol","ups","vacations","vana","vanguard","vegas","ventures","verisign","versicherung","vet","viajes","video","vig","viking","villas","vin","vip","virgin","visa","vision","vistaprint","viva","vivo","vlaanderen","vodka","volkswagen","volvo","vote","voting","voto","voyage","vuelos","wales","walmart","walter","wang","wanggou","warman","watch","watches","weather","weatherchannel","webcam","weber","website","wed","wedding","weibo","weir","whoswho","wien","wiki","williamhill","win","windows","wine","winners","wme","wolterskluwer","woodside","work","works","world","wow","wtc","wtf","xbox","xerox","xfinity","xihuan","xin","कॉम","セール","佛山","慈善","集团","在线","大众汽车","点看","คอม","八卦","موقع","公益","公司","香格里拉","网站","移动","我爱你","москва","католик","онлайн","сайт","联通","קום","时尚","微博","淡马锡","ファッション","орг","नेट","ストア","삼성","商标","商店","商城","дети","ポイント","新闻","工行","家電","كوم","中文网","中信","娱乐","谷歌","電訊盈科","购物","クラウド","通販","网店","संगठन","餐厅","网络","ком","诺基亚","食品","飞利浦","手表","手机","ارامكو","العليان","اتصالات","بازار","موبايلي","ابوظبي","كاثوليك","همراه","닷컴","政府","شبكة","بيتك","عرب","机构","组织机构","健康","招聘","рус","珠宝","大拿","みんな","グーグル","世界","書籍","网址","닷넷","コム","天主教","游戏","vermögensberater","vermögensberatung","企业","信息","嘉里大酒店","嘉里","广东","政务","xyz","yachts","yahoo","yamaxun","yandex","yodobashi","yoga","yokohama","you","youtube","yun","zappos","zara","zero","zip","zippo","zone","zuerich","cc.ua","inf.ua","ltd.ua","beep.pl","*.compute.estate","*.alces.network","alwaysdata.net","cloudfront.net","*.compute.amazonaws.com","*.compute-1.amazonaws.com","*.compute.amazonaws.com.cn","us-east-1.amazonaws.com","cn-north-1.eb.amazonaws.com.cn","cn-northwest-1.eb.amazonaws.com.cn","elasticbeanstalk.com","ap-northeast-1.elasticbeanstalk.com","ap-northeast-2.elasticbeanstalk.com","ap-northeast-3.elasticbeanstalk.com","ap-south-1.elasticbeanstalk.com","ap-southeast-1.elasticbeanstalk.com","ap-southeast-2.elasticbeanstalk.com","ca-central-1.elasticbeanstalk.com","eu-central-1.elasticbeanstalk.com","eu-west-1.elasticbeanstalk.com","eu-west-2.elasticbeanstalk.com","eu-west-3.elasticbeanstalk.com","sa-east-1.elasticbeanstalk.com","us-east-1.elasticbeanstalk.com","us-east-2.elasticbeanstalk.com","us-gov-west-1.elasticbeanstalk.com","us-west-1.elasticbeanstalk.com","us-west-2.elasticbeanstalk.com","*.elb.amazonaws.com","*.elb.amazonaws.com.cn","s3.amazonaws.com","s3-ap-northeast-1.amazonaws.com","s3-ap-northeast-2.amazonaws.com","s3-ap-south-1.amazonaws.com","s3-ap-southeast-1.amazonaws.com","s3-ap-southeast-2.amazonaws.com","s3-ca-central-1.amazonaws.com","s3-eu-central-1.amazonaws.com","s3-eu-west-1.amazonaws.com","s3-eu-west-2.amazonaws.com","s3-eu-west-3.amazonaws.com","s3-external-1.amazonaws.com","s3-fips-us-gov-west-1.amazonaws.com","s3-sa-east-1.amazonaws.com","s3-us-gov-west-1.amazonaws.com","s3-us-east-2.amazonaws.com","s3-us-west-1.amazonaws.com","s3-us-west-2.amazonaws.com","s3.ap-northeast-2.amazonaws.com","s3.ap-south-1.amazonaws.com","s3.cn-north-1.amazonaws.com.cn","s3.ca-central-1.amazonaws.com","s3.eu-central-1.amazonaws.com","s3.eu-west-2.amazonaws.com","s3.eu-west-3.amazonaws.com","s3.us-east-2.amazonaws.com","s3.dualstack.ap-northeast-1.amazonaws.com","s3.dualstack.ap-northeast-2.amazonaws.com","s3.dualstack.ap-south-1.amazonaws.com","s3.dualstack.ap-southeast-1.amazonaws.com","s3.dualstack.ap-southeast-2.amazonaws.com","s3.dualstack.ca-central-1.amazonaws.com","s3.dualstack.eu-central-1.amazonaws.com","s3.dualstack.eu-west-1.amazonaws.com","s3.dualstack.eu-west-2.amazonaws.com","s3.dualstack.eu-west-3.amazonaws.com","s3.dualstack.sa-east-1.amazonaws.com","s3.dualstack.us-east-1.amazonaws.com","s3.dualstack.us-east-2.amazonaws.com","s3-website-us-east-1.amazonaws.com","s3-website-us-west-1.amazonaws.com","s3-website-us-west-2.amazonaws.com","s3-website-ap-northeast-1.amazonaws.com","s3-website-ap-southeast-1.amazonaws.com","s3-website-ap-southeast-2.amazonaws.com","s3-website-eu-west-1.amazonaws.com","s3-website-sa-east-1.amazonaws.com","s3-website.ap-northeast-2.amazonaws.com","s3-website.ap-south-1.amazonaws.com","s3-website.ca-central-1.amazonaws.com","s3-website.eu-central-1.amazonaws.com","s3-website.eu-west-2.amazonaws.com","s3-website.eu-west-3.amazonaws.com","s3-website.us-east-2.amazonaws.com","t3l3p0rt.net","tele.amune.org","apigee.io","on-aptible.com","user.party.eus","pimienta.org","poivron.org","potager.org","sweetpepper.org","myasustor.com","myfritz.net","*.awdev.ca","*.advisor.ws","backplaneapp.io","betainabox.com","bnr.la","blackbaudcdn.net","boomla.net","boxfuse.io","square7.ch","bplaced.com","bplaced.de","square7.de","bplaced.net","square7.net","browsersafetymark.io","mycd.eu","ae.org","ar.com","br.com","cn.com","com.de","com.se","de.com","eu.com","gb.com","gb.net","hu.com","hu.net","jp.net","jpn.com","kr.com","mex.com","no.com","qc.com","ru.com","sa.com","se.net","uk.com","uk.net","us.com","uy.com","za.bz","za.com","africa.com","gr.com","in.net","us.org","co.com","c.la","certmgr.org","xenapponazure.com","virtueeldomein.nl","cleverapps.io","c66.me","cloud66.ws","jdevcloud.com","wpdevcloud.com","cloudaccess.host","freesite.host","cloudaccess.net","cloudcontrolled.com","cloudcontrolapp.com","co.ca","*.otap.co","co.cz","c.cdn77.org","cdn77-ssl.net","r.cdn77.net","rsc.cdn77.org","ssl.origin.cdn77-secure.org","cloudns.asia","cloudns.biz","cloudns.club","cloudns.cc","cloudns.eu","cloudns.in","cloudns.info","cloudns.org","cloudns.pro","cloudns.pw","cloudns.us","cloudeity.net","cnpy.gdn","co.nl","co.no","webhosting.be","hosting-cluster.nl","dyn.cosidns.de","dynamisches-dns.de","dnsupdater.de","internet-dns.de","l-o-g-i-n.de","dynamic-dns.info","feste-ip.net","knx-server.net","static-access.net","realm.cz","*.cryptonomic.net","cupcake.is","cyon.link","cyon.site","daplie.me","localhost.daplie.me","dattolocal.com","dattorelay.com","dattoweb.com","mydatto.com","dattolocal.net","mydatto.net","biz.dk","co.dk","firm.dk","reg.dk","store.dk","debian.net","dedyn.io","dnshome.de","drayddns.com","dreamhosters.com","mydrobo.com","drud.io","drud.us","duckdns.org","dy.fi","tunk.org","dyndns-at-home.com","dyndns-at-work.com","dyndns-blog.com","dyndns-free.com","dyndns-home.com","dyndns-ip.com","dyndns-mail.com","dyndns-office.com","dyndns-pics.com","dyndns-remote.com","dyndns-server.com","dyndns-web.com","dyndns-wiki.com","dyndns-work.com","dyndns.biz","dyndns.info","dyndns.org","dyndns.tv","at-band-camp.net","ath.cx","barrel-of-knowledge.info","barrell-of-knowledge.info","better-than.tv","blogdns.com","blogdns.net","blogdns.org","blogsite.org","boldlygoingnowhere.org","broke-it.net","buyshouses.net","cechire.com","dnsalias.com","dnsalias.net","dnsalias.org","dnsdojo.com","dnsdojo.net","dnsdojo.org","does-it.net","doesntexist.com","doesntexist.org","dontexist.com","dontexist.net","dontexist.org","doomdns.com","doomdns.org","dvrdns.org","dyn-o-saur.com","dynalias.com","dynalias.net","dynalias.org","dynathome.net","dyndns.ws","endofinternet.net","endofinternet.org","endoftheinternet.org","est-a-la-maison.com","est-a-la-masion.com","est-le-patron.com","est-mon-blogueur.com","for-better.biz","for-more.biz","for-our.info","for-some.biz","for-the.biz","forgot.her.name","forgot.his.name","from-ak.com","from-al.com","from-ar.com","from-az.net","from-ca.com","from-co.net","from-ct.com","from-dc.com","from-de.com","from-fl.com","from-ga.com","from-hi.com","from-ia.com","from-id.com","from-il.com","from-in.com","from-ks.com","from-ky.com","from-la.net","from-ma.com","from-md.com","from-me.org","from-mi.com","from-mn.com","from-mo.com","from-ms.com","from-mt.com","from-nc.com","from-nd.com","from-ne.com","from-nh.com","from-nj.com","from-nm.com","from-nv.com","from-ny.net","from-oh.com","from-ok.com","from-or.com","from-pa.com","from-pr.com","from-ri.com","from-sc.com","from-sd.com","from-tn.com","from-tx.com","from-ut.com","from-va.com","from-vt.com","from-wa.com","from-wi.com","from-wv.com","from-wy.com","ftpaccess.cc","fuettertdasnetz.de","game-host.org","game-server.cc","getmyip.com","gets-it.net","go.dyndns.org","gotdns.com","gotdns.org","groks-the.info","groks-this.info","ham-radio-op.net","here-for-more.info","hobby-site.com","hobby-site.org","home.dyndns.org","homedns.org","homeftp.net","homeftp.org","homeip.net","homelinux.com","homelinux.net","homelinux.org","homeunix.com","homeunix.net","homeunix.org","iamallama.com","in-the-band.net","is-a-anarchist.com","is-a-blogger.com","is-a-bookkeeper.com","is-a-bruinsfan.org","is-a-bulls-fan.com","is-a-candidate.org","is-a-caterer.com","is-a-celticsfan.org","is-a-chef.com","is-a-chef.net","is-a-chef.org","is-a-conservative.com","is-a-cpa.com","is-a-cubicle-slave.com","is-a-democrat.com","is-a-designer.com","is-a-doctor.com","is-a-financialadvisor.com","is-a-geek.com","is-a-geek.net","is-a-geek.org","is-a-green.com","is-a-guru.com","is-a-hard-worker.com","is-a-hunter.com","is-a-knight.org","is-a-landscaper.com","is-a-lawyer.com","is-a-liberal.com","is-a-libertarian.com","is-a-linux-user.org","is-a-llama.com","is-a-musician.com","is-a-nascarfan.com","is-a-nurse.com","is-a-painter.com","is-a-patsfan.org","is-a-personaltrainer.com","is-a-photographer.com","is-a-player.com","is-a-republican.com","is-a-rockstar.com","is-a-socialist.com","is-a-soxfan.org","is-a-student.com","is-a-teacher.com","is-a-techie.com","is-a-therapist.com","is-an-accountant.com","is-an-actor.com","is-an-actress.com","is-an-anarchist.com","is-an-artist.com","is-an-engineer.com","is-an-entertainer.com","is-by.us","is-certified.com","is-found.org","is-gone.com","is-into-anime.com","is-into-cars.com","is-into-cartoons.com","is-into-games.com","is-leet.com","is-lost.org","is-not-certified.com","is-saved.org","is-slick.com","is-uberleet.com","is-very-bad.org","is-very-evil.org","is-very-good.org","is-very-nice.org","is-very-sweet.org","is-with-theband.com","isa-geek.com","isa-geek.net","isa-geek.org","isa-hockeynut.com","issmarterthanyou.com","isteingeek.de","istmein.de","kicks-ass.net","kicks-ass.org","knowsitall.info","land-4-sale.us","lebtimnetz.de","leitungsen.de","likes-pie.com","likescandy.com","merseine.nu","mine.nu","misconfused.org","mypets.ws","myphotos.cc","neat-url.com","office-on-the.net","on-the-web.tv","podzone.net","podzone.org","readmyblog.org","saves-the-whales.com","scrapper-site.net","scrapping.cc","selfip.biz","selfip.com","selfip.info","selfip.net","selfip.org","sells-for-less.com","sells-for-u.com","sells-it.net","sellsyourhome.org","servebbs.com","servebbs.net","servebbs.org","serveftp.net","serveftp.org","servegame.org","shacknet.nu","simple-url.com","space-to-rent.com","stuff-4-sale.org","stuff-4-sale.us","teaches-yoga.com","thruhere.net","traeumtgerade.de","webhop.biz","webhop.info","webhop.net","webhop.org","worse-than.tv","writesthisblog.com","ddnss.de","dyn.ddnss.de","dyndns.ddnss.de","dyndns1.de","dyn-ip24.de","home-webserver.de","dyn.home-webserver.de","myhome-server.de","ddnss.org","definima.net","definima.io","bci.dnstrace.pro","ddnsfree.com","ddnsgeek.com","giize.com","gleeze.com","kozow.com","loseyourip.com","ooguy.com","theworkpc.com","casacam.net","dynu.net","accesscam.org","camdvr.org","freeddns.org","mywire.org","webredirect.org","myddns.rocks","blogsite.xyz","dynv6.net","e4.cz","mytuleap.com","enonic.io","customer.enonic.io","eu.org","al.eu.org","asso.eu.org","at.eu.org","au.eu.org","be.eu.org","bg.eu.org","ca.eu.org","cd.eu.org","ch.eu.org","cn.eu.org","cy.eu.org","cz.eu.org","de.eu.org","dk.eu.org","edu.eu.org","ee.eu.org","es.eu.org","fi.eu.org","fr.eu.org","gr.eu.org","hr.eu.org","hu.eu.org","ie.eu.org","il.eu.org","in.eu.org","int.eu.org","is.eu.org","it.eu.org","jp.eu.org","kr.eu.org","lt.eu.org","lu.eu.org","lv.eu.org","mc.eu.org","me.eu.org","mk.eu.org","mt.eu.org","my.eu.org","net.eu.org","ng.eu.org","nl.eu.org","no.eu.org","nz.eu.org","paris.eu.org","pl.eu.org","pt.eu.org","q-a.eu.org","ro.eu.org","ru.eu.org","se.eu.org","si.eu.org","sk.eu.org","tr.eu.org","uk.eu.org","us.eu.org","eu-1.evennode.com","eu-2.evennode.com","eu-3.evennode.com","eu-4.evennode.com","us-1.evennode.com","us-2.evennode.com","us-3.evennode.com","us-4.evennode.com","twmail.cc","twmail.net","twmail.org","mymailer.com.tw","url.tw","apps.fbsbx.com","ru.net","adygeya.ru","bashkiria.ru","bir.ru","cbg.ru","com.ru","dagestan.ru","grozny.ru","kalmykia.ru","kustanai.ru","marine.ru","mordovia.ru","msk.ru","mytis.ru","nalchik.ru","nov.ru","pyatigorsk.ru","spb.ru","vladikavkaz.ru","vladimir.ru","abkhazia.su","adygeya.su","aktyubinsk.su","arkhangelsk.su","armenia.su","ashgabad.su","azerbaijan.su","balashov.su","bashkiria.su","bryansk.su","bukhara.su","chimkent.su","dagestan.su","east-kazakhstan.su","exnet.su","georgia.su","grozny.su","ivanovo.su","jambyl.su","kalmykia.su","kaluga.su","karacol.su","karaganda.su","karelia.su","khakassia.su","krasnodar.su","kurgan.su","kustanai.su","lenug.su","mangyshlak.su","mordovia.su","msk.su","murmansk.su","nalchik.su","navoi.su","north-kazakhstan.su","nov.su","obninsk.su","penza.su","pokrovsk.su","sochi.su","spb.su","tashkent.su","termez.su","togliatti.su","troitsk.su","tselinograd.su","tula.su","tuva.su","vladikavkaz.su","vladimir.su","vologda.su","channelsdvr.net","fastlylb.net","map.fastlylb.net","freetls.fastly.net","map.fastly.net","a.prod.fastly.net","global.prod.fastly.net","a.ssl.fastly.net","b.ssl.fastly.net","global.ssl.fastly.net","fastpanel.direct","fastvps-server.com","fhapp.xyz","fedorainfracloud.org","fedorapeople.org","cloud.fedoraproject.org","app.os.fedoraproject.org","app.os.stg.fedoraproject.org","filegear.me","firebaseapp.com","flynnhub.com","flynnhosting.net","freebox-os.com","freeboxos.com","fbx-os.fr","fbxos.fr","freebox-os.fr","freeboxos.fr","freedesktop.org","*.futurecms.at","*.ex.futurecms.at","*.in.futurecms.at","futurehosting.at","futuremailing.at","*.ex.ortsinfo.at","*.kunden.ortsinfo.at","*.statics.cloud","service.gov.uk","github.io","githubusercontent.com","gitlab.io","homeoffice.gov.uk","ro.im","shop.ro","goip.de","*.0emm.com","appspot.com","blogspot.ae","blogspot.al","blogspot.am","blogspot.ba","blogspot.be","blogspot.bg","blogspot.bj","blogspot.ca","blogspot.cf","blogspot.ch","blogspot.cl","blogspot.co.at","blogspot.co.id","blogspot.co.il","blogspot.co.ke","blogspot.co.nz","blogspot.co.uk","blogspot.co.za","blogspot.com","blogspot.com.ar","blogspot.com.au","blogspot.com.br","blogspot.com.by","blogspot.com.co","blogspot.com.cy","blogspot.com.ee","blogspot.com.eg","blogspot.com.es","blogspot.com.mt","blogspot.com.ng","blogspot.com.tr","blogspot.com.uy","blogspot.cv","blogspot.cz","blogspot.de","blogspot.dk","blogspot.fi","blogspot.fr","blogspot.gr","blogspot.hk","blogspot.hr","blogspot.hu","blogspot.ie","blogspot.in","blogspot.is","blogspot.it","blogspot.jp","blogspot.kr","blogspot.li","blogspot.lt","blogspot.lu","blogspot.md","blogspot.mk","blogspot.mr","blogspot.mx","blogspot.my","blogspot.nl","blogspot.no","blogspot.pe","blogspot.pt","blogspot.qa","blogspot.re","blogspot.ro","blogspot.rs","blogspot.ru","blogspot.se","blogspot.sg","blogspot.si","blogspot.sk","blogspot.sn","blogspot.td","blogspot.tw","blogspot.ug","blogspot.vn","cloudfunctions.net","cloud.goog","codespot.com","googleapis.com","googlecode.com","pagespeedmobilizer.com","publishproxy.com","withgoogle.com","withyoutube.com","hashbang.sh","hasura.app","hasura-app.io","hepforge.org","herokuapp.com","herokussl.com","myravendb.com","ravendb.community","ravendb.me","development.run","ravendb.run","moonscale.net","iki.fi","biz.at","info.at","info.cx","ac.leg.br","al.leg.br","am.leg.br","ap.leg.br","ba.leg.br","ce.leg.br","df.leg.br","es.leg.br","go.leg.br","ma.leg.br","mg.leg.br","ms.leg.br","mt.leg.br","pa.leg.br","pb.leg.br","pe.leg.br","pi.leg.br","pr.leg.br","rj.leg.br","rn.leg.br","ro.leg.br","rr.leg.br","rs.leg.br","sc.leg.br","se.leg.br","sp.leg.br","to.leg.br","pixolino.com","ipifony.net","mein-iserv.de","test-iserv.de","myjino.ru","*.hosting.myjino.ru","*.landing.myjino.ru","*.spectrum.myjino.ru","*.vps.myjino.ru","*.triton.zone","*.cns.joyent.com","js.org","keymachine.de","knightpoint.systems","co.krd","edu.krd","git-repos.de","lcube-server.de","svn-repos.de","app.lmpm.com","linkitools.space","linkyard.cloud","linkyard-cloud.ch","we.bs","uklugs.org","glug.org.uk","lug.org.uk","lugs.org.uk","barsy.bg","barsy.co.uk","barsyonline.co.uk","barsycenter.com","barsyonline.com","barsy.club","barsy.de","barsy.eu","barsy.in","barsy.info","barsy.io","barsy.me","barsy.menu","barsy.mobi","barsy.net","barsy.online","barsy.org","barsy.pro","barsy.pub","barsy.shop","barsy.site","barsy.support","barsy.uk","*.magentosite.cloud","mayfirst.info","mayfirst.org","hb.cldmail.ru","miniserver.com","memset.net","cloud.metacentrum.cz","custom.metacentrum.cz","flt.cloud.muni.cz","usr.cloud.muni.cz","meteorapp.com","eu.meteorapp.com","co.pl","azurecontainer.io","azurewebsites.net","azure-mobile.net","cloudapp.net","mozilla-iot.org","bmoattachments.org","net.ru","org.ru","pp.ru","bitballoon.com","netlify.com","4u.com","ngrok.io","nh-serv.co.uk","nfshost.com","dnsking.ch","mypi.co","n4t.co","001www.com","ddnslive.com","myiphost.com","forumz.info","16-b.it","32-b.it","64-b.it","soundcast.me","tcp4.me","dnsup.net","hicam.net","now-dns.net","ownip.net","vpndns.net","dynserv.org","now-dns.org","x443.pw","now-dns.top","ntdll.top","freeddns.us","crafting.xyz","zapto.xyz","nsupdate.info","nerdpol.ovh","blogsyte.com","brasilia.me","cable-modem.org","ciscofreak.com","collegefan.org","couchpotatofries.org","damnserver.com","ddns.me","ditchyourip.com","dnsfor.me","dnsiskinky.com","dvrcam.info","dynns.com","eating-organic.net","fantasyleague.cc","geekgalaxy.com","golffan.us","health-carereform.com","homesecuritymac.com","homesecuritypc.com","hopto.me","ilovecollege.info","loginto.me","mlbfan.org","mmafan.biz","myactivedirectory.com","mydissent.net","myeffect.net","mymediapc.net","mypsx.net","mysecuritycamera.com","mysecuritycamera.net","mysecuritycamera.org","net-freaks.com","nflfan.org","nhlfan.net","no-ip.ca","no-ip.co.uk","no-ip.net","noip.us","onthewifi.com","pgafan.net","point2this.com","pointto.us","privatizehealthinsurance.net","quicksytes.com","read-books.org","securitytactics.com","serveexchange.com","servehumour.com","servep2p.com","servesarcasm.com","stufftoread.com","ufcfan.org","unusualperson.com","workisboring.com","3utilities.com","bounceme.net","ddns.net","ddnsking.com","gotdns.ch","hopto.org","myftp.biz","myftp.org","myvnc.com","no-ip.biz","no-ip.info","no-ip.org","noip.me","redirectme.net","servebeer.com","serveblog.net","servecounterstrike.com","serveftp.com","servegame.com","servehalflife.com","servehttp.com","serveirc.com","serveminecraft.net","servemp3.com","servepics.com","servequake.com","sytes.net","webhop.me","zapto.org","stage.nodeart.io","nodum.co","nodum.io","pcloud.host","nyc.mn","nom.ae","nom.af","nom.ai","nom.al","nym.by","nym.bz","nom.cl","nom.gd","nom.ge","nom.gl","nym.gr","nom.gt","nym.gy","nom.hn","nym.ie","nom.im","nom.ke","nym.kz","nym.la","nym.lc","nom.li","nym.li","nym.lt","nym.lu","nym.me","nom.mk","nym.mn","nym.mx","nom.nu","nym.nz","nym.pe","nym.pt","nom.pw","nom.qa","nym.ro","nom.rs","nom.si","nym.sk","nom.st","nym.su","nym.sx","nom.tj","nym.tw","nom.ug","nom.uy","nom.vc","nom.vg","cya.gg","cloudycluster.net","nid.io","opencraft.hosting","operaunite.com","outsystemscloud.com","ownprovider.com","own.pm","ox.rs","oy.lc","pgfog.com","pagefrontapp.com","art.pl","gliwice.pl","krakow.pl","poznan.pl","wroc.pl","zakopane.pl","pantheonsite.io","gotpantheon.com","mypep.link","on-web.fr","*.platform.sh","*.platformsh.site","xen.prgmr.com","priv.at","protonet.io","chirurgiens-dentistes-en-france.fr","byen.site","ras.ru","qa2.com","dev-myqnapcloud.com","alpha-myqnapcloud.com","myqnapcloud.com","*.quipelements.com","vapor.cloud","vaporcloud.io","rackmaze.com","rackmaze.net","rhcloud.com","resindevice.io","devices.resinstaging.io","hzc.io","wellbeingzone.eu","ptplus.fit","wellbeingzone.co.uk","sandcats.io","logoip.de","logoip.com","schokokeks.net","scrysec.com","firewall-gateway.com","firewall-gateway.de","my-gateway.de","my-router.de","spdns.de","spdns.eu","firewall-gateway.net","my-firewall.org","myfirewall.org","spdns.org","*.s5y.io","*.sensiosite.cloud","biz.ua","co.ua","pp.ua","shiftedit.io","myshopblocks.com","1kapp.com","appchizi.com","applinzi.com","sinaapp.com","vipsinaapp.com","bounty-full.com","alpha.bounty-full.com","beta.bounty-full.com","static.land","dev.static.land","sites.static.land","apps.lair.io","*.stolos.io","spacekit.io","customer.speedpartner.de","storj.farm","utwente.io","temp-dns.com","diskstation.me","dscloud.biz","dscloud.me","dscloud.mobi","dsmynas.com","dsmynas.net","dsmynas.org","familyds.com","familyds.net","familyds.org","i234.me","myds.me","synology.me","vpnplus.to","taifun-dns.de","gda.pl","gdansk.pl","gdynia.pl","med.pl","sopot.pl","gwiddle.co.uk","cust.dev.thingdust.io","cust.disrec.thingdust.io","cust.prod.thingdust.io","cust.testing.thingdust.io","bloxcms.com","townnews-staging.com","12hp.at","2ix.at","4lima.at","lima-city.at","12hp.ch","2ix.ch","4lima.ch","lima-city.ch","trafficplex.cloud","de.cool","12hp.de","2ix.de","4lima.de","lima-city.de","1337.pictures","clan.rip","lima-city.rocks","webspace.rocks","lima.zone","*.transurl.be","*.transurl.eu","*.transurl.nl","tuxfamily.org","dd-dns.de","diskstation.eu","diskstation.org","dray-dns.de","draydns.de","dyn-vpn.de","dynvpn.de","mein-vigor.de","my-vigor.de","my-wan.de","syno-ds.de","synology-diskstation.de","synology-ds.de","uber.space","*.uberspace.de","hk.com","hk.org","ltd.hk","inc.hk","virtualuser.de","virtual-user.de","lib.de.us","2038.io","router.management","v-info.info","wedeploy.io","wedeploy.me","wedeploy.sh","remotewd.com","wmflabs.org","half.host","xnbay.com","u2.xnbay.com","u2-local.xnbay.com","cistron.nl","demon.nl","xs4all.space","official.academy","yolasite.com","ybo.faith","yombo.me","homelink.one","ybo.party","ybo.review","ybo.science","ybo.trade","nohost.me","noho.st","za.net","za.org","now.sh","zone.id"]
55824},{}],267:[function(require,module,exports){
55825/*eslint no-var:0, prefer-arrow-callback: 0, object-shorthand: 0 */
55826'use strict';
55827
55828
55829var Punycode = require('punycode');
55830
55831
55832var internals = {};
55833
55834
55835//
55836// Read rules from file.
55837//
55838internals.rules = require('./data/rules.json').map(function (rule) {
55839
55840 return {
55841 rule: rule,
55842 suffix: rule.replace(/^(\*\.|\!)/, ''),
55843 punySuffix: -1,
55844 wildcard: rule.charAt(0) === '*',
55845 exception: rule.charAt(0) === '!'
55846 };
55847});
55848
55849
55850//
55851// Check is given string ends with `suffix`.
55852//
55853internals.endsWith = function (str, suffix) {
55854
55855 return str.indexOf(suffix, str.length - suffix.length) !== -1;
55856};
55857
55858
55859//
55860// Find rule for a given domain.
55861//
55862internals.findRule = function (domain) {
55863
55864 var punyDomain = Punycode.toASCII(domain);
55865 return internals.rules.reduce(function (memo, rule) {
55866
55867 if (rule.punySuffix === -1){
55868 rule.punySuffix = Punycode.toASCII(rule.suffix);
55869 }
55870 if (!internals.endsWith(punyDomain, '.' + rule.punySuffix) && punyDomain !== rule.punySuffix) {
55871 return memo;
55872 }
55873 // This has been commented out as it never seems to run. This is because
55874 // sub tlds always appear after their parents and we never find a shorter
55875 // match.
55876 //if (memo) {
55877 // var memoSuffix = Punycode.toASCII(memo.suffix);
55878 // if (memoSuffix.length >= punySuffix.length) {
55879 // return memo;
55880 // }
55881 //}
55882 return rule;
55883 }, null);
55884};
55885
55886
55887//
55888// Error codes and messages.
55889//
55890exports.errorCodes = {
55891 DOMAIN_TOO_SHORT: 'Domain name too short.',
55892 DOMAIN_TOO_LONG: 'Domain name too long. It should be no more than 255 chars.',
55893 LABEL_STARTS_WITH_DASH: 'Domain name label can not start with a dash.',
55894 LABEL_ENDS_WITH_DASH: 'Domain name label can not end with a dash.',
55895 LABEL_TOO_LONG: 'Domain name label should be at most 63 chars long.',
55896 LABEL_TOO_SHORT: 'Domain name label should be at least 1 character long.',
55897 LABEL_INVALID_CHARS: 'Domain name label can only contain alphanumeric characters or dashes.'
55898};
55899
55900
55901//
55902// Validate domain name and throw if not valid.
55903//
55904// From wikipedia:
55905//
55906// Hostnames are composed of series of labels concatenated with dots, as are all
55907// domain names. Each label must be between 1 and 63 characters long, and the
55908// entire hostname (including the delimiting dots) has a maximum of 255 chars.
55909//
55910// Allowed chars:
55911//
55912// * `a-z`
55913// * `0-9`
55914// * `-` but not as a starting or ending character
55915// * `.` as a separator for the textual portions of a domain name
55916//
55917// * http://en.wikipedia.org/wiki/Domain_name
55918// * http://en.wikipedia.org/wiki/Hostname
55919//
55920internals.validate = function (input) {
55921
55922 // Before we can validate we need to take care of IDNs with unicode chars.
55923 var ascii = Punycode.toASCII(input);
55924
55925 if (ascii.length < 1) {
55926 return 'DOMAIN_TOO_SHORT';
55927 }
55928 if (ascii.length > 255) {
55929 return 'DOMAIN_TOO_LONG';
55930 }
55931
55932 // Check each part's length and allowed chars.
55933 var labels = ascii.split('.');
55934 var label;
55935
55936 for (var i = 0; i < labels.length; ++i) {
55937 label = labels[i];
55938 if (!label.length) {
55939 return 'LABEL_TOO_SHORT';
55940 }
55941 if (label.length > 63) {
55942 return 'LABEL_TOO_LONG';
55943 }
55944 if (label.charAt(0) === '-') {
55945 return 'LABEL_STARTS_WITH_DASH';
55946 }
55947 if (label.charAt(label.length - 1) === '-') {
55948 return 'LABEL_ENDS_WITH_DASH';
55949 }
55950 if (!/^[a-z0-9\-]+$/.test(label)) {
55951 return 'LABEL_INVALID_CHARS';
55952 }
55953 }
55954};
55955
55956
55957//
55958// Public API
55959//
55960
55961
55962//
55963// Parse domain.
55964//
55965exports.parse = function (input) {
55966
55967 if (typeof input !== 'string') {
55968 throw new TypeError('Domain name must be a string.');
55969 }
55970
55971 // Force domain to lowercase.
55972 var domain = input.slice(0).toLowerCase();
55973
55974 // Handle FQDN.
55975 // TODO: Simply remove trailing dot?
55976 if (domain.charAt(domain.length - 1) === '.') {
55977 domain = domain.slice(0, domain.length - 1);
55978 }
55979
55980 // Validate and sanitise input.
55981 var error = internals.validate(domain);
55982 if (error) {
55983 return {
55984 input: input,
55985 error: {
55986 message: exports.errorCodes[error],
55987 code: error
55988 }
55989 };
55990 }
55991
55992 var parsed = {
55993 input: input,
55994 tld: null,
55995 sld: null,
55996 domain: null,
55997 subdomain: null,
55998 listed: false
55999 };
56000
56001 var domainParts = domain.split('.');
56002
56003 // Non-Internet TLD
56004 if (domainParts[domainParts.length - 1] === 'local') {
56005 return parsed;
56006 }
56007
56008 var handlePunycode = function () {
56009
56010 if (!/xn--/.test(domain)) {
56011 return parsed;
56012 }
56013 if (parsed.domain) {
56014 parsed.domain = Punycode.toASCII(parsed.domain);
56015 }
56016 if (parsed.subdomain) {
56017 parsed.subdomain = Punycode.toASCII(parsed.subdomain);
56018 }
56019 return parsed;
56020 };
56021
56022 var rule = internals.findRule(domain);
56023
56024 // Unlisted tld.
56025 if (!rule) {
56026 if (domainParts.length < 2) {
56027 return parsed;
56028 }
56029 parsed.tld = domainParts.pop();
56030 parsed.sld = domainParts.pop();
56031 parsed.domain = [parsed.sld, parsed.tld].join('.');
56032 if (domainParts.length) {
56033 parsed.subdomain = domainParts.pop();
56034 }
56035 return handlePunycode();
56036 }
56037
56038 // At this point we know the public suffix is listed.
56039 parsed.listed = true;
56040
56041 var tldParts = rule.suffix.split('.');
56042 var privateParts = domainParts.slice(0, domainParts.length - tldParts.length);
56043
56044 if (rule.exception) {
56045 privateParts.push(tldParts.shift());
56046 }
56047
56048 parsed.tld = tldParts.join('.');
56049
56050 if (!privateParts.length) {
56051 return handlePunycode();
56052 }
56053
56054 if (rule.wildcard) {
56055 tldParts.unshift(privateParts.pop());
56056 parsed.tld = tldParts.join('.');
56057 }
56058
56059 if (!privateParts.length) {
56060 return handlePunycode();
56061 }
56062
56063 parsed.sld = privateParts.pop();
56064 parsed.domain = [parsed.sld, parsed.tld].join('.');
56065
56066 if (privateParts.length) {
56067 parsed.subdomain = privateParts.join('.');
56068 }
56069
56070 return handlePunycode();
56071};
56072
56073
56074//
56075// Get domain.
56076//
56077exports.get = function (domain) {
56078
56079 if (!domain) {
56080 return null;
56081 }
56082 return exports.parse(domain).domain || null;
56083};
56084
56085
56086//
56087// Check whether domain belongs to a known public suffix.
56088//
56089exports.isValid = function (domain) {
56090
56091 var parsed = exports.parse(domain);
56092 return Boolean(parsed.domain && parsed.listed);
56093};
56094
56095},{"./data/rules.json":266,"punycode":274}],268:[function(require,module,exports){
56096exports.publicEncrypt = require('./publicEncrypt')
56097exports.privateDecrypt = require('./privateDecrypt')
56098
56099exports.privateEncrypt = function privateEncrypt (key, buf) {
56100 return exports.publicEncrypt(key, buf, true)
56101}
56102
56103exports.publicDecrypt = function publicDecrypt (key, buf) {
56104 return exports.privateDecrypt(key, buf, true)
56105}
56106
56107},{"./privateDecrypt":270,"./publicEncrypt":271}],269:[function(require,module,exports){
56108var createHash = require('create-hash')
56109var Buffer = require('safe-buffer').Buffer
56110
56111module.exports = function (seed, len) {
56112 var t = Buffer.alloc(0)
56113 var i = 0
56114 var c
56115 while (t.length < len) {
56116 c = i2ops(i++)
56117 t = Buffer.concat([t, createHash('sha1').update(seed).update(c).digest()])
56118 }
56119 return t.slice(0, len)
56120}
56121
56122function i2ops (c) {
56123 var out = Buffer.allocUnsafe(4)
56124 out.writeUInt32BE(c, 0)
56125 return out
56126}
56127
56128},{"create-hash":122,"safe-buffer":325}],270:[function(require,module,exports){
56129var parseKeys = require('parse-asn1')
56130var mgf = require('./mgf')
56131var xor = require('./xor')
56132var BN = require('bn.js')
56133var crt = require('browserify-rsa')
56134var createHash = require('create-hash')
56135var withPublic = require('./withPublic')
56136var Buffer = require('safe-buffer').Buffer
56137
56138module.exports = function privateDecrypt (privateKey, enc, reverse) {
56139 var padding
56140 if (privateKey.padding) {
56141 padding = privateKey.padding
56142 } else if (reverse) {
56143 padding = 1
56144 } else {
56145 padding = 4
56146 }
56147
56148 var key = parseKeys(privateKey)
56149 var k = key.modulus.byteLength()
56150 if (enc.length > k || new BN(enc).cmp(key.modulus) >= 0) {
56151 throw new Error('decryption error')
56152 }
56153 var msg
56154 if (reverse) {
56155 msg = withPublic(new BN(enc), key)
56156 } else {
56157 msg = crt(enc, key)
56158 }
56159 var zBuffer = Buffer.alloc(k - msg.length)
56160 msg = Buffer.concat([zBuffer, msg], k)
56161 if (padding === 4) {
56162 return oaep(key, msg)
56163 } else if (padding === 1) {
56164 return pkcs1(key, msg, reverse)
56165 } else if (padding === 3) {
56166 return msg
56167 } else {
56168 throw new Error('unknown padding')
56169 }
56170}
56171
56172function oaep (key, msg) {
56173 var k = key.modulus.byteLength()
56174 var iHash = createHash('sha1').update(Buffer.alloc(0)).digest()
56175 var hLen = iHash.length
56176 if (msg[0] !== 0) {
56177 throw new Error('decryption error')
56178 }
56179 var maskedSeed = msg.slice(1, hLen + 1)
56180 var maskedDb = msg.slice(hLen + 1)
56181 var seed = xor(maskedSeed, mgf(maskedDb, hLen))
56182 var db = xor(maskedDb, mgf(seed, k - hLen - 1))
56183 if (compare(iHash, db.slice(0, hLen))) {
56184 throw new Error('decryption error')
56185 }
56186 var i = hLen
56187 while (db[i] === 0) {
56188 i++
56189 }
56190 if (db[i++] !== 1) {
56191 throw new Error('decryption error')
56192 }
56193 return db.slice(i)
56194}
56195
56196function pkcs1 (key, msg, reverse) {
56197 var p1 = msg.slice(0, 2)
56198 var i = 2
56199 var status = 0
56200 while (msg[i++] !== 0) {
56201 if (i >= msg.length) {
56202 status++
56203 break
56204 }
56205 }
56206 var ps = msg.slice(2, i - 1)
56207
56208 if ((p1.toString('hex') !== '0002' && !reverse) || (p1.toString('hex') !== '0001' && reverse)) {
56209 status++
56210 }
56211 if (ps.length < 8) {
56212 status++
56213 }
56214 if (status) {
56215 throw new Error('decryption error')
56216 }
56217 return msg.slice(i)
56218}
56219function compare (a, b) {
56220 a = Buffer.from(a)
56221 b = Buffer.from(b)
56222 var dif = 0
56223 var len = a.length
56224 if (a.length !== b.length) {
56225 dif++
56226 len = Math.min(a.length, b.length)
56227 }
56228 var i = -1
56229 while (++i < len) {
56230 dif += (a[i] ^ b[i])
56231 }
56232 return dif
56233}
56234
56235},{"./mgf":269,"./withPublic":272,"./xor":273,"bn.js":80,"browserify-rsa":103,"create-hash":122,"parse-asn1":256,"safe-buffer":325}],271:[function(require,module,exports){
56236var parseKeys = require('parse-asn1')
56237var randomBytes = require('randombytes')
56238var createHash = require('create-hash')
56239var mgf = require('./mgf')
56240var xor = require('./xor')
56241var BN = require('bn.js')
56242var withPublic = require('./withPublic')
56243var crt = require('browserify-rsa')
56244var Buffer = require('safe-buffer').Buffer
56245
56246module.exports = function publicEncrypt (publicKey, msg, reverse) {
56247 var padding
56248 if (publicKey.padding) {
56249 padding = publicKey.padding
56250 } else if (reverse) {
56251 padding = 1
56252 } else {
56253 padding = 4
56254 }
56255 var key = parseKeys(publicKey)
56256 var paddedMsg
56257 if (padding === 4) {
56258 paddedMsg = oaep(key, msg)
56259 } else if (padding === 1) {
56260 paddedMsg = pkcs1(key, msg, reverse)
56261 } else if (padding === 3) {
56262 paddedMsg = new BN(msg)
56263 if (paddedMsg.cmp(key.modulus) >= 0) {
56264 throw new Error('data too long for modulus')
56265 }
56266 } else {
56267 throw new Error('unknown padding')
56268 }
56269 if (reverse) {
56270 return crt(paddedMsg, key)
56271 } else {
56272 return withPublic(paddedMsg, key)
56273 }
56274}
56275
56276function oaep (key, msg) {
56277 var k = key.modulus.byteLength()
56278 var mLen = msg.length
56279 var iHash = createHash('sha1').update(Buffer.alloc(0)).digest()
56280 var hLen = iHash.length
56281 var hLen2 = 2 * hLen
56282 if (mLen > k - hLen2 - 2) {
56283 throw new Error('message too long')
56284 }
56285 var ps = Buffer.alloc(k - mLen - hLen2 - 2)
56286 var dblen = k - hLen - 1
56287 var seed = randomBytes(hLen)
56288 var maskedDb = xor(Buffer.concat([iHash, ps, Buffer.alloc(1, 1), msg], dblen), mgf(seed, dblen))
56289 var maskedSeed = xor(seed, mgf(maskedDb, hLen))
56290 return new BN(Buffer.concat([Buffer.alloc(1), maskedSeed, maskedDb], k))
56291}
56292function pkcs1 (key, msg, reverse) {
56293 var mLen = msg.length
56294 var k = key.modulus.byteLength()
56295 if (mLen > k - 11) {
56296 throw new Error('message too long')
56297 }
56298 var ps
56299 if (reverse) {
56300 ps = Buffer.alloc(k - mLen - 3, 0xff)
56301 } else {
56302 ps = nonZero(k - mLen - 3)
56303 }
56304 return new BN(Buffer.concat([Buffer.from([0, reverse ? 1 : 2]), ps, Buffer.alloc(1), msg], k))
56305}
56306function nonZero (len) {
56307 var out = Buffer.allocUnsafe(len)
56308 var i = 0
56309 var cache = randomBytes(len * 2)
56310 var cur = 0
56311 var num
56312 while (i < len) {
56313 if (cur === cache.length) {
56314 cache = randomBytes(len * 2)
56315 cur = 0
56316 }
56317 num = cache[cur++]
56318 if (num) {
56319 out[i++] = num
56320 }
56321 }
56322 return out
56323}
56324
56325},{"./mgf":269,"./withPublic":272,"./xor":273,"bn.js":80,"browserify-rsa":103,"create-hash":122,"parse-asn1":256,"randombytes":278,"safe-buffer":325}],272:[function(require,module,exports){
56326var BN = require('bn.js')
56327var Buffer = require('safe-buffer').Buffer
56328
56329function withPublic (paddedMsg, key) {
56330 return Buffer.from(paddedMsg
56331 .toRed(BN.mont(key.modulus))
56332 .redPow(new BN(key.publicExponent))
56333 .fromRed()
56334 .toArray())
56335}
56336
56337module.exports = withPublic
56338
56339},{"bn.js":80,"safe-buffer":325}],273:[function(require,module,exports){
56340module.exports = function xor (a, b) {
56341 var len = a.length
56342 var i = -1
56343 while (++i < len) {
56344 a[i] ^= b[i]
56345 }
56346 return a
56347}
56348
56349},{}],274:[function(require,module,exports){
56350(function (global){
56351/*! https://mths.be/punycode v1.4.1 by @mathias */
56352;(function(root) {
56353
56354 /** Detect free variables */
56355 var freeExports = typeof exports == 'object' && exports &&
56356 !exports.nodeType && exports;
56357 var freeModule = typeof module == 'object' && module &&
56358 !module.nodeType && module;
56359 var freeGlobal = typeof global == 'object' && global;
56360 if (
56361 freeGlobal.global === freeGlobal ||
56362 freeGlobal.window === freeGlobal ||
56363 freeGlobal.self === freeGlobal
56364 ) {
56365 root = freeGlobal;
56366 }
56367
56368 /**
56369 * The `punycode` object.
56370 * @name punycode
56371 * @type Object
56372 */
56373 var punycode,
56374
56375 /** Highest positive signed 32-bit float value */
56376 maxInt = 2147483647, // aka. 0x7FFFFFFF or 2^31-1
56377
56378 /** Bootstring parameters */
56379 base = 36,
56380 tMin = 1,
56381 tMax = 26,
56382 skew = 38,
56383 damp = 700,
56384 initialBias = 72,
56385 initialN = 128, // 0x80
56386 delimiter = '-', // '\x2D'
56387
56388 /** Regular expressions */
56389 regexPunycode = /^xn--/,
56390 regexNonASCII = /[^\x20-\x7E]/, // unprintable ASCII chars + non-ASCII chars
56391 regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g, // RFC 3490 separators
56392
56393 /** Error messages */
56394 errors = {
56395 'overflow': 'Overflow: input needs wider integers to process',
56396 'not-basic': 'Illegal input >= 0x80 (not a basic code point)',
56397 'invalid-input': 'Invalid input'
56398 },
56399
56400 /** Convenience shortcuts */
56401 baseMinusTMin = base - tMin,
56402 floor = Math.floor,
56403 stringFromCharCode = String.fromCharCode,
56404
56405 /** Temporary variable */
56406 key;
56407
56408 /*--------------------------------------------------------------------------*/
56409
56410 /**
56411 * A generic error utility function.
56412 * @private
56413 * @param {String} type The error type.
56414 * @returns {Error} Throws a `RangeError` with the applicable error message.
56415 */
56416 function error(type) {
56417 throw new RangeError(errors[type]);
56418 }
56419
56420 /**
56421 * A generic `Array#map` utility function.
56422 * @private
56423 * @param {Array} array The array to iterate over.
56424 * @param {Function} callback The function that gets called for every array
56425 * item.
56426 * @returns {Array} A new array of values returned by the callback function.
56427 */
56428 function map(array, fn) {
56429 var length = array.length;
56430 var result = [];
56431 while (length--) {
56432 result[length] = fn(array[length]);
56433 }
56434 return result;
56435 }
56436
56437 /**
56438 * A simple `Array#map`-like wrapper to work with domain name strings or email
56439 * addresses.
56440 * @private
56441 * @param {String} domain The domain name or email address.
56442 * @param {Function} callback The function that gets called for every
56443 * character.
56444 * @returns {Array} A new string of characters returned by the callback
56445 * function.
56446 */
56447 function mapDomain(string, fn) {
56448 var parts = string.split('@');
56449 var result = '';
56450 if (parts.length > 1) {
56451 // In email addresses, only the domain name should be punycoded. Leave
56452 // the local part (i.e. everything up to `@`) intact.
56453 result = parts[0] + '@';
56454 string = parts[1];
56455 }
56456 // Avoid `split(regex)` for IE8 compatibility. See #17.
56457 string = string.replace(regexSeparators, '\x2E');
56458 var labels = string.split('.');
56459 var encoded = map(labels, fn).join('.');
56460 return result + encoded;
56461 }
56462
56463 /**
56464 * Creates an array containing the numeric code points of each Unicode
56465 * character in the string. While JavaScript uses UCS-2 internally,
56466 * this function will convert a pair of surrogate halves (each of which
56467 * UCS-2 exposes as separate characters) into a single code point,
56468 * matching UTF-16.
56469 * @see `punycode.ucs2.encode`
56470 * @see <https://mathiasbynens.be/notes/javascript-encoding>
56471 * @memberOf punycode.ucs2
56472 * @name decode
56473 * @param {String} string The Unicode input string (UCS-2).
56474 * @returns {Array} The new array of code points.
56475 */
56476 function ucs2decode(string) {
56477 var output = [],
56478 counter = 0,
56479 length = string.length,
56480 value,
56481 extra;
56482 while (counter < length) {
56483 value = string.charCodeAt(counter++);
56484 if (value >= 0xD800 && value <= 0xDBFF && counter < length) {
56485 // high surrogate, and there is a next character
56486 extra = string.charCodeAt(counter++);
56487 if ((extra & 0xFC00) == 0xDC00) { // low surrogate
56488 output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000);
56489 } else {
56490 // unmatched surrogate; only append this code unit, in case the next
56491 // code unit is the high surrogate of a surrogate pair
56492 output.push(value);
56493 counter--;
56494 }
56495 } else {
56496 output.push(value);
56497 }
56498 }
56499 return output;
56500 }
56501
56502 /**
56503 * Creates a string based on an array of numeric code points.
56504 * @see `punycode.ucs2.decode`
56505 * @memberOf punycode.ucs2
56506 * @name encode
56507 * @param {Array} codePoints The array of numeric code points.
56508 * @returns {String} The new Unicode string (UCS-2).
56509 */
56510 function ucs2encode(array) {
56511 return map(array, function(value) {
56512 var output = '';
56513 if (value > 0xFFFF) {
56514 value -= 0x10000;
56515 output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800);
56516 value = 0xDC00 | value & 0x3FF;
56517 }
56518 output += stringFromCharCode(value);
56519 return output;
56520 }).join('');
56521 }
56522
56523 /**
56524 * Converts a basic code point into a digit/integer.
56525 * @see `digitToBasic()`
56526 * @private
56527 * @param {Number} codePoint The basic numeric code point value.
56528 * @returns {Number} The numeric value of a basic code point (for use in
56529 * representing integers) in the range `0` to `base - 1`, or `base` if
56530 * the code point does not represent a value.
56531 */
56532 function basicToDigit(codePoint) {
56533 if (codePoint - 48 < 10) {
56534 return codePoint - 22;
56535 }
56536 if (codePoint - 65 < 26) {
56537 return codePoint - 65;
56538 }
56539 if (codePoint - 97 < 26) {
56540 return codePoint - 97;
56541 }
56542 return base;
56543 }
56544
56545 /**
56546 * Converts a digit/integer into a basic code point.
56547 * @see `basicToDigit()`
56548 * @private
56549 * @param {Number} digit The numeric value of a basic code point.
56550 * @returns {Number} The basic code point whose value (when used for
56551 * representing integers) is `digit`, which needs to be in the range
56552 * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is
56553 * used; else, the lowercase form is used. The behavior is undefined
56554 * if `flag` is non-zero and `digit` has no uppercase form.
56555 */
56556 function digitToBasic(digit, flag) {
56557 // 0..25 map to ASCII a..z or A..Z
56558 // 26..35 map to ASCII 0..9
56559 return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5);
56560 }
56561
56562 /**
56563 * Bias adaptation function as per section 3.4 of RFC 3492.
56564 * https://tools.ietf.org/html/rfc3492#section-3.4
56565 * @private
56566 */
56567 function adapt(delta, numPoints, firstTime) {
56568 var k = 0;
56569 delta = firstTime ? floor(delta / damp) : delta >> 1;
56570 delta += floor(delta / numPoints);
56571 for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) {
56572 delta = floor(delta / baseMinusTMin);
56573 }
56574 return floor(k + (baseMinusTMin + 1) * delta / (delta + skew));
56575 }
56576
56577 /**
56578 * Converts a Punycode string of ASCII-only symbols to a string of Unicode
56579 * symbols.
56580 * @memberOf punycode
56581 * @param {String} input The Punycode string of ASCII-only symbols.
56582 * @returns {String} The resulting string of Unicode symbols.
56583 */
56584 function decode(input) {
56585 // Don't use UCS-2
56586 var output = [],
56587 inputLength = input.length,
56588 out,
56589 i = 0,
56590 n = initialN,
56591 bias = initialBias,
56592 basic,
56593 j,
56594 index,
56595 oldi,
56596 w,
56597 k,
56598 digit,
56599 t,
56600 /** Cached calculation results */
56601 baseMinusT;
56602
56603 // Handle the basic code points: let `basic` be the number of input code
56604 // points before the last delimiter, or `0` if there is none, then copy
56605 // the first basic code points to the output.
56606
56607 basic = input.lastIndexOf(delimiter);
56608 if (basic < 0) {
56609 basic = 0;
56610 }
56611
56612 for (j = 0; j < basic; ++j) {
56613 // if it's not a basic code point
56614 if (input.charCodeAt(j) >= 0x80) {
56615 error('not-basic');
56616 }
56617 output.push(input.charCodeAt(j));
56618 }
56619
56620 // Main decoding loop: start just after the last delimiter if any basic code
56621 // points were copied; start at the beginning otherwise.
56622
56623 for (index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) {
56624
56625 // `index` is the index of the next character to be consumed.
56626 // Decode a generalized variable-length integer into `delta`,
56627 // which gets added to `i`. The overflow checking is easier
56628 // if we increase `i` as we go, then subtract off its starting
56629 // value at the end to obtain `delta`.
56630 for (oldi = i, w = 1, k = base; /* no condition */; k += base) {
56631
56632 if (index >= inputLength) {
56633 error('invalid-input');
56634 }
56635
56636 digit = basicToDigit(input.charCodeAt(index++));
56637
56638 if (digit >= base || digit > floor((maxInt - i) / w)) {
56639 error('overflow');
56640 }
56641
56642 i += digit * w;
56643 t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
56644
56645 if (digit < t) {
56646 break;
56647 }
56648
56649 baseMinusT = base - t;
56650 if (w > floor(maxInt / baseMinusT)) {
56651 error('overflow');
56652 }
56653
56654 w *= baseMinusT;
56655
56656 }
56657
56658 out = output.length + 1;
56659 bias = adapt(i - oldi, out, oldi == 0);
56660
56661 // `i` was supposed to wrap around from `out` to `0`,
56662 // incrementing `n` each time, so we'll fix that now:
56663 if (floor(i / out) > maxInt - n) {
56664 error('overflow');
56665 }
56666
56667 n += floor(i / out);
56668 i %= out;
56669
56670 // Insert `n` at position `i` of the output
56671 output.splice(i++, 0, n);
56672
56673 }
56674
56675 return ucs2encode(output);
56676 }
56677
56678 /**
56679 * Converts a string of Unicode symbols (e.g. a domain name label) to a
56680 * Punycode string of ASCII-only symbols.
56681 * @memberOf punycode
56682 * @param {String} input The string of Unicode symbols.
56683 * @returns {String} The resulting Punycode string of ASCII-only symbols.
56684 */
56685 function encode(input) {
56686 var n,
56687 delta,
56688 handledCPCount,
56689 basicLength,
56690 bias,
56691 j,
56692 m,
56693 q,
56694 k,
56695 t,
56696 currentValue,
56697 output = [],
56698 /** `inputLength` will hold the number of code points in `input`. */
56699 inputLength,
56700 /** Cached calculation results */
56701 handledCPCountPlusOne,
56702 baseMinusT,
56703 qMinusT;
56704
56705 // Convert the input in UCS-2 to Unicode
56706 input = ucs2decode(input);
56707
56708 // Cache the length
56709 inputLength = input.length;
56710
56711 // Initialize the state
56712 n = initialN;
56713 delta = 0;
56714 bias = initialBias;
56715
56716 // Handle the basic code points
56717 for (j = 0; j < inputLength; ++j) {
56718 currentValue = input[j];
56719 if (currentValue < 0x80) {
56720 output.push(stringFromCharCode(currentValue));
56721 }
56722 }
56723
56724 handledCPCount = basicLength = output.length;
56725
56726 // `handledCPCount` is the number of code points that have been handled;
56727 // `basicLength` is the number of basic code points.
56728
56729 // Finish the basic string - if it is not empty - with a delimiter
56730 if (basicLength) {
56731 output.push(delimiter);
56732 }
56733
56734 // Main encoding loop:
56735 while (handledCPCount < inputLength) {
56736
56737 // All non-basic code points < n have been handled already. Find the next
56738 // larger one:
56739 for (m = maxInt, j = 0; j < inputLength; ++j) {
56740 currentValue = input[j];
56741 if (currentValue >= n && currentValue < m) {
56742 m = currentValue;
56743 }
56744 }
56745
56746 // Increase `delta` enough to advance the decoder's <n,i> state to <m,0>,
56747 // but guard against overflow
56748 handledCPCountPlusOne = handledCPCount + 1;
56749 if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) {
56750 error('overflow');
56751 }
56752
56753 delta += (m - n) * handledCPCountPlusOne;
56754 n = m;
56755
56756 for (j = 0; j < inputLength; ++j) {
56757 currentValue = input[j];
56758
56759 if (currentValue < n && ++delta > maxInt) {
56760 error('overflow');
56761 }
56762
56763 if (currentValue == n) {
56764 // Represent delta as a generalized variable-length integer
56765 for (q = delta, k = base; /* no condition */; k += base) {
56766 t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
56767 if (q < t) {
56768 break;
56769 }
56770 qMinusT = q - t;
56771 baseMinusT = base - t;
56772 output.push(
56773 stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0))
56774 );
56775 q = floor(qMinusT / baseMinusT);
56776 }
56777
56778 output.push(stringFromCharCode(digitToBasic(q, 0)));
56779 bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength);
56780 delta = 0;
56781 ++handledCPCount;
56782 }
56783 }
56784
56785 ++delta;
56786 ++n;
56787
56788 }
56789 return output.join('');
56790 }
56791
56792 /**
56793 * Converts a Punycode string representing a domain name or an email address
56794 * to Unicode. Only the Punycoded parts of the input will be converted, i.e.
56795 * it doesn't matter if you call it on a string that has already been
56796 * converted to Unicode.
56797 * @memberOf punycode
56798 * @param {String} input The Punycoded domain name or email address to
56799 * convert to Unicode.
56800 * @returns {String} The Unicode representation of the given Punycode
56801 * string.
56802 */
56803 function toUnicode(input) {
56804 return mapDomain(input, function(string) {
56805 return regexPunycode.test(string)
56806 ? decode(string.slice(4).toLowerCase())
56807 : string;
56808 });
56809 }
56810
56811 /**
56812 * Converts a Unicode string representing a domain name or an email address to
56813 * Punycode. Only the non-ASCII parts of the domain name will be converted,
56814 * i.e. it doesn't matter if you call it with a domain that's already in
56815 * ASCII.
56816 * @memberOf punycode
56817 * @param {String} input The domain name or email address to convert, as a
56818 * Unicode string.
56819 * @returns {String} The Punycode representation of the given domain name or
56820 * email address.
56821 */
56822 function toASCII(input) {
56823 return mapDomain(input, function(string) {
56824 return regexNonASCII.test(string)
56825 ? 'xn--' + encode(string)
56826 : string;
56827 });
56828 }
56829
56830 /*--------------------------------------------------------------------------*/
56831
56832 /** Define the public API */
56833 punycode = {
56834 /**
56835 * A string representing the current Punycode.js version number.
56836 * @memberOf punycode
56837 * @type String
56838 */
56839 'version': '1.4.1',
56840 /**
56841 * An object of methods to convert from JavaScript's internal character
56842 * representation (UCS-2) to Unicode code points, and back.
56843 * @see <https://mathiasbynens.be/notes/javascript-encoding>
56844 * @memberOf punycode
56845 * @type Object
56846 */
56847 'ucs2': {
56848 'decode': ucs2decode,
56849 'encode': ucs2encode
56850 },
56851 'decode': decode,
56852 'encode': encode,
56853 'toASCII': toASCII,
56854 'toUnicode': toUnicode
56855 };
56856
56857 /** Expose `punycode` */
56858 // Some AMD build optimizers, like r.js, check for specific condition patterns
56859 // like the following:
56860 if (
56861 typeof define == 'function' &&
56862 typeof define.amd == 'object' &&
56863 define.amd
56864 ) {
56865 define('punycode', function() {
56866 return punycode;
56867 });
56868 } else if (freeExports && freeModule) {
56869 if (module.exports == freeExports) {
56870 // in Node.js, io.js, or RingoJS v0.8.0+
56871 freeModule.exports = punycode;
56872 } else {
56873 // in Narwhal or RingoJS v0.7.0-
56874 for (key in punycode) {
56875 punycode.hasOwnProperty(key) && (freeExports[key] = punycode[key]);
56876 }
56877 }
56878 } else {
56879 // in Rhino or a web browser
56880 root.punycode = punycode;
56881 }
56882
56883}(this));
56884
56885}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
56886},{}],275:[function(require,module,exports){
56887// Copyright Joyent, Inc. and other Node contributors.
56888//
56889// Permission is hereby granted, free of charge, to any person obtaining a
56890// copy of this software and associated documentation files (the
56891// "Software"), to deal in the Software without restriction, including
56892// without limitation the rights to use, copy, modify, merge, publish,
56893// distribute, sublicense, and/or sell copies of the Software, and to permit
56894// persons to whom the Software is furnished to do so, subject to the
56895// following conditions:
56896//
56897// The above copyright notice and this permission notice shall be included
56898// in all copies or substantial portions of the Software.
56899//
56900// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
56901// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
56902// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
56903// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
56904// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
56905// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
56906// USE OR OTHER DEALINGS IN THE SOFTWARE.
56907
56908'use strict';
56909
56910// If obj.hasOwnProperty has been overridden, then calling
56911// obj.hasOwnProperty(prop) will break.
56912// See: https://github.com/joyent/node/issues/1707
56913function hasOwnProperty(obj, prop) {
56914 return Object.prototype.hasOwnProperty.call(obj, prop);
56915}
56916
56917module.exports = function(qs, sep, eq, options) {
56918 sep = sep || '&';
56919 eq = eq || '=';
56920 var obj = {};
56921
56922 if (typeof qs !== 'string' || qs.length === 0) {
56923 return obj;
56924 }
56925
56926 var regexp = /\+/g;
56927 qs = qs.split(sep);
56928
56929 var maxKeys = 1000;
56930 if (options && typeof options.maxKeys === 'number') {
56931 maxKeys = options.maxKeys;
56932 }
56933
56934 var len = qs.length;
56935 // maxKeys <= 0 means that we should not limit keys count
56936 if (maxKeys > 0 && len > maxKeys) {
56937 len = maxKeys;
56938 }
56939
56940 for (var i = 0; i < len; ++i) {
56941 var x = qs[i].replace(regexp, '%20'),
56942 idx = x.indexOf(eq),
56943 kstr, vstr, k, v;
56944
56945 if (idx >= 0) {
56946 kstr = x.substr(0, idx);
56947 vstr = x.substr(idx + 1);
56948 } else {
56949 kstr = x;
56950 vstr = '';
56951 }
56952
56953 k = decodeURIComponent(kstr);
56954 v = decodeURIComponent(vstr);
56955
56956 if (!hasOwnProperty(obj, k)) {
56957 obj[k] = v;
56958 } else if (isArray(obj[k])) {
56959 obj[k].push(v);
56960 } else {
56961 obj[k] = [obj[k], v];
56962 }
56963 }
56964
56965 return obj;
56966};
56967
56968var isArray = Array.isArray || function (xs) {
56969 return Object.prototype.toString.call(xs) === '[object Array]';
56970};
56971
56972},{}],276:[function(require,module,exports){
56973// Copyright Joyent, Inc. and other Node contributors.
56974//
56975// Permission is hereby granted, free of charge, to any person obtaining a
56976// copy of this software and associated documentation files (the
56977// "Software"), to deal in the Software without restriction, including
56978// without limitation the rights to use, copy, modify, merge, publish,
56979// distribute, sublicense, and/or sell copies of the Software, and to permit
56980// persons to whom the Software is furnished to do so, subject to the
56981// following conditions:
56982//
56983// The above copyright notice and this permission notice shall be included
56984// in all copies or substantial portions of the Software.
56985//
56986// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
56987// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
56988// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
56989// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
56990// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
56991// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
56992// USE OR OTHER DEALINGS IN THE SOFTWARE.
56993
56994'use strict';
56995
56996var stringifyPrimitive = function(v) {
56997 switch (typeof v) {
56998 case 'string':
56999 return v;
57000
57001 case 'boolean':
57002 return v ? 'true' : 'false';
57003
57004 case 'number':
57005 return isFinite(v) ? v : '';
57006
57007 default:
57008 return '';
57009 }
57010};
57011
57012module.exports = function(obj, sep, eq, name) {
57013 sep = sep || '&';
57014 eq = eq || '=';
57015 if (obj === null) {
57016 obj = undefined;
57017 }
57018
57019 if (typeof obj === 'object') {
57020 return map(objectKeys(obj), function(k) {
57021 var ks = encodeURIComponent(stringifyPrimitive(k)) + eq;
57022 if (isArray(obj[k])) {
57023 return map(obj[k], function(v) {
57024 return ks + encodeURIComponent(stringifyPrimitive(v));
57025 }).join(sep);
57026 } else {
57027 return ks + encodeURIComponent(stringifyPrimitive(obj[k]));
57028 }
57029 }).join(sep);
57030
57031 }
57032
57033 if (!name) return '';
57034 return encodeURIComponent(stringifyPrimitive(name)) + eq +
57035 encodeURIComponent(stringifyPrimitive(obj));
57036};
57037
57038var isArray = Array.isArray || function (xs) {
57039 return Object.prototype.toString.call(xs) === '[object Array]';
57040};
57041
57042function map (xs, f) {
57043 if (xs.map) return xs.map(f);
57044 var res = [];
57045 for (var i = 0; i < xs.length; i++) {
57046 res.push(f(xs[i], i));
57047 }
57048 return res;
57049}
57050
57051var objectKeys = Object.keys || function (obj) {
57052 var res = [];
57053 for (var key in obj) {
57054 if (Object.prototype.hasOwnProperty.call(obj, key)) res.push(key);
57055 }
57056 return res;
57057};
57058
57059},{}],277:[function(require,module,exports){
57060'use strict';
57061
57062exports.decode = exports.parse = require('./decode');
57063exports.encode = exports.stringify = require('./encode');
57064
57065},{"./decode":275,"./encode":276}],278:[function(require,module,exports){
57066(function (process,global){
57067'use strict'
57068
57069// limit of Crypto.getRandomValues()
57070// https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues
57071var MAX_BYTES = 65536
57072
57073// Node supports requesting up to this number of bytes
57074// https://github.com/nodejs/node/blob/master/lib/internal/crypto/random.js#L48
57075var MAX_UINT32 = 4294967295
57076
57077function oldBrowser () {
57078 throw new Error('Secure random number generation is not supported by this browser.\nUse Chrome, Firefox or Internet Explorer 11')
57079}
57080
57081var Buffer = require('safe-buffer').Buffer
57082var crypto = global.crypto || global.msCrypto
57083
57084if (crypto && crypto.getRandomValues) {
57085 module.exports = randomBytes
57086} else {
57087 module.exports = oldBrowser
57088}
57089
57090function randomBytes (size, cb) {
57091 // phantomjs needs to throw
57092 if (size > MAX_UINT32) throw new RangeError('requested too many random bytes')
57093
57094 var bytes = Buffer.allocUnsafe(size)
57095
57096 if (size > 0) { // getRandomValues fails on IE if size == 0
57097 if (size > MAX_BYTES) { // this is the max bytes crypto.getRandomValues
57098 // can do at once see https://developer.mozilla.org/en-US/docs/Web/API/window.crypto.getRandomValues
57099 for (var generated = 0; generated < size; generated += MAX_BYTES) {
57100 // buffer.slice automatically checks if the end is past the end of
57101 // the buffer so we don't have to here
57102 crypto.getRandomValues(bytes.slice(generated, generated + MAX_BYTES))
57103 }
57104 } else {
57105 crypto.getRandomValues(bytes)
57106 }
57107 }
57108
57109 if (typeof cb === 'function') {
57110 return process.nextTick(function () {
57111 cb(null, bytes)
57112 })
57113 }
57114
57115 return bytes
57116}
57117
57118}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
57119},{"_process":265,"safe-buffer":325}],279:[function(require,module,exports){
57120(function (process,global){
57121'use strict'
57122
57123function oldBrowser () {
57124 throw new Error('secure random number generation not supported by this browser\nuse chrome, FireFox or Internet Explorer 11')
57125}
57126var safeBuffer = require('safe-buffer')
57127var randombytes = require('randombytes')
57128var Buffer = safeBuffer.Buffer
57129var kBufferMaxLength = safeBuffer.kMaxLength
57130var crypto = global.crypto || global.msCrypto
57131var kMaxUint32 = Math.pow(2, 32) - 1
57132function assertOffset (offset, length) {
57133 if (typeof offset !== 'number' || offset !== offset) { // eslint-disable-line no-self-compare
57134 throw new TypeError('offset must be a number')
57135 }
57136
57137 if (offset > kMaxUint32 || offset < 0) {
57138 throw new TypeError('offset must be a uint32')
57139 }
57140
57141 if (offset > kBufferMaxLength || offset > length) {
57142 throw new RangeError('offset out of range')
57143 }
57144}
57145
57146function assertSize (size, offset, length) {
57147 if (typeof size !== 'number' || size !== size) { // eslint-disable-line no-self-compare
57148 throw new TypeError('size must be a number')
57149 }
57150
57151 if (size > kMaxUint32 || size < 0) {
57152 throw new TypeError('size must be a uint32')
57153 }
57154
57155 if (size + offset > length || size > kBufferMaxLength) {
57156 throw new RangeError('buffer too small')
57157 }
57158}
57159if ((crypto && crypto.getRandomValues) || !process.browser) {
57160 exports.randomFill = randomFill
57161 exports.randomFillSync = randomFillSync
57162} else {
57163 exports.randomFill = oldBrowser
57164 exports.randomFillSync = oldBrowser
57165}
57166function randomFill (buf, offset, size, cb) {
57167 if (!Buffer.isBuffer(buf) && !(buf instanceof global.Uint8Array)) {
57168 throw new TypeError('"buf" argument must be a Buffer or Uint8Array')
57169 }
57170
57171 if (typeof offset === 'function') {
57172 cb = offset
57173 offset = 0
57174 size = buf.length
57175 } else if (typeof size === 'function') {
57176 cb = size
57177 size = buf.length - offset
57178 } else if (typeof cb !== 'function') {
57179 throw new TypeError('"cb" argument must be a function')
57180 }
57181 assertOffset(offset, buf.length)
57182 assertSize(size, offset, buf.length)
57183 return actualFill(buf, offset, size, cb)
57184}
57185
57186function actualFill (buf, offset, size, cb) {
57187 if (process.browser) {
57188 var ourBuf = buf.buffer
57189 var uint = new Uint8Array(ourBuf, offset, size)
57190 crypto.getRandomValues(uint)
57191 if (cb) {
57192 process.nextTick(function () {
57193 cb(null, buf)
57194 })
57195 return
57196 }
57197 return buf
57198 }
57199 if (cb) {
57200 randombytes(size, function (err, bytes) {
57201 if (err) {
57202 return cb(err)
57203 }
57204 bytes.copy(buf, offset)
57205 cb(null, buf)
57206 })
57207 return
57208 }
57209 var bytes = randombytes(size)
57210 bytes.copy(buf, offset)
57211 return buf
57212}
57213function randomFillSync (buf, offset, size) {
57214 if (typeof offset === 'undefined') {
57215 offset = 0
57216 }
57217 if (!Buffer.isBuffer(buf) && !(buf instanceof global.Uint8Array)) {
57218 throw new TypeError('"buf" argument must be a Buffer or Uint8Array')
57219 }
57220
57221 assertOffset(offset, buf.length)
57222
57223 if (size === undefined) size = buf.length - offset
57224
57225 assertSize(size, offset, buf.length)
57226
57227 return actualFill(buf, offset, size)
57228}
57229
57230}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
57231},{"_process":265,"randombytes":278,"safe-buffer":325}],280:[function(require,module,exports){
57232module.exports = require('./lib/_stream_duplex.js');
57233
57234},{"./lib/_stream_duplex.js":281}],281:[function(require,module,exports){
57235// Copyright Joyent, Inc. and other Node contributors.
57236//
57237// Permission is hereby granted, free of charge, to any person obtaining a
57238// copy of this software and associated documentation files (the
57239// "Software"), to deal in the Software without restriction, including
57240// without limitation the rights to use, copy, modify, merge, publish,
57241// distribute, sublicense, and/or sell copies of the Software, and to permit
57242// persons to whom the Software is furnished to do so, subject to the
57243// following conditions:
57244//
57245// The above copyright notice and this permission notice shall be included
57246// in all copies or substantial portions of the Software.
57247//
57248// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
57249// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
57250// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
57251// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
57252// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
57253// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
57254// USE OR OTHER DEALINGS IN THE SOFTWARE.
57255
57256// a duplex stream is just a stream that is both readable and writable.
57257// Since JS doesn't have multiple prototypal inheritance, this class
57258// prototypally inherits from Readable, and then parasitically from
57259// Writable.
57260
57261'use strict';
57262
57263/*<replacement>*/
57264
57265var pna = require('process-nextick-args');
57266/*</replacement>*/
57267
57268/*<replacement>*/
57269var objectKeys = Object.keys || function (obj) {
57270 var keys = [];
57271 for (var key in obj) {
57272 keys.push(key);
57273 }return keys;
57274};
57275/*</replacement>*/
57276
57277module.exports = Duplex;
57278
57279/*<replacement>*/
57280var util = require('core-util-is');
57281util.inherits = require('inherits');
57282/*</replacement>*/
57283
57284var Readable = require('./_stream_readable');
57285var Writable = require('./_stream_writable');
57286
57287util.inherits(Duplex, Readable);
57288
57289{
57290 // avoid scope creep, the keys array can then be collected
57291 var keys = objectKeys(Writable.prototype);
57292 for (var v = 0; v < keys.length; v++) {
57293 var method = keys[v];
57294 if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method];
57295 }
57296}
57297
57298function Duplex(options) {
57299 if (!(this instanceof Duplex)) return new Duplex(options);
57300
57301 Readable.call(this, options);
57302 Writable.call(this, options);
57303
57304 if (options && options.readable === false) this.readable = false;
57305
57306 if (options && options.writable === false) this.writable = false;
57307
57308 this.allowHalfOpen = true;
57309 if (options && options.allowHalfOpen === false) this.allowHalfOpen = false;
57310
57311 this.once('end', onend);
57312}
57313
57314Object.defineProperty(Duplex.prototype, 'writableHighWaterMark', {
57315 // making it explicit this property is not enumerable
57316 // because otherwise some prototype manipulation in
57317 // userland will fail
57318 enumerable: false,
57319 get: function () {
57320 return this._writableState.highWaterMark;
57321 }
57322});
57323
57324// the no-half-open enforcer
57325function onend() {
57326 // if we allow half-open state, or if the writable side ended,
57327 // then we're ok.
57328 if (this.allowHalfOpen || this._writableState.ended) return;
57329
57330 // no more data can be written.
57331 // But allow more writes to happen in this tick.
57332 pna.nextTick(onEndNT, this);
57333}
57334
57335function onEndNT(self) {
57336 self.end();
57337}
57338
57339Object.defineProperty(Duplex.prototype, 'destroyed', {
57340 get: function () {
57341 if (this._readableState === undefined || this._writableState === undefined) {
57342 return false;
57343 }
57344 return this._readableState.destroyed && this._writableState.destroyed;
57345 },
57346 set: function (value) {
57347 // we ignore the value if the stream
57348 // has not been initialized yet
57349 if (this._readableState === undefined || this._writableState === undefined) {
57350 return;
57351 }
57352
57353 // backward compatibility, the user is explicitly
57354 // managing destroyed
57355 this._readableState.destroyed = value;
57356 this._writableState.destroyed = value;
57357 }
57358});
57359
57360Duplex.prototype._destroy = function (err, cb) {
57361 this.push(null);
57362 this.end();
57363
57364 pna.nextTick(cb, err);
57365};
57366},{"./_stream_readable":283,"./_stream_writable":285,"core-util-is":120,"inherits":210,"process-nextick-args":264}],282:[function(require,module,exports){
57367// Copyright Joyent, Inc. and other Node contributors.
57368//
57369// Permission is hereby granted, free of charge, to any person obtaining a
57370// copy of this software and associated documentation files (the
57371// "Software"), to deal in the Software without restriction, including
57372// without limitation the rights to use, copy, modify, merge, publish,
57373// distribute, sublicense, and/or sell copies of the Software, and to permit
57374// persons to whom the Software is furnished to do so, subject to the
57375// following conditions:
57376//
57377// The above copyright notice and this permission notice shall be included
57378// in all copies or substantial portions of the Software.
57379//
57380// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
57381// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
57382// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
57383// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
57384// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
57385// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
57386// USE OR OTHER DEALINGS IN THE SOFTWARE.
57387
57388// a passthrough stream.
57389// basically just the most minimal sort of Transform stream.
57390// Every written chunk gets output as-is.
57391
57392'use strict';
57393
57394module.exports = PassThrough;
57395
57396var Transform = require('./_stream_transform');
57397
57398/*<replacement>*/
57399var util = require('core-util-is');
57400util.inherits = require('inherits');
57401/*</replacement>*/
57402
57403util.inherits(PassThrough, Transform);
57404
57405function PassThrough(options) {
57406 if (!(this instanceof PassThrough)) return new PassThrough(options);
57407
57408 Transform.call(this, options);
57409}
57410
57411PassThrough.prototype._transform = function (chunk, encoding, cb) {
57412 cb(null, chunk);
57413};
57414},{"./_stream_transform":284,"core-util-is":120,"inherits":210}],283:[function(require,module,exports){
57415(function (process,global){
57416// Copyright Joyent, Inc. and other Node contributors.
57417//
57418// Permission is hereby granted, free of charge, to any person obtaining a
57419// copy of this software and associated documentation files (the
57420// "Software"), to deal in the Software without restriction, including
57421// without limitation the rights to use, copy, modify, merge, publish,
57422// distribute, sublicense, and/or sell copies of the Software, and to permit
57423// persons to whom the Software is furnished to do so, subject to the
57424// following conditions:
57425//
57426// The above copyright notice and this permission notice shall be included
57427// in all copies or substantial portions of the Software.
57428//
57429// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
57430// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
57431// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
57432// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
57433// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
57434// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
57435// USE OR OTHER DEALINGS IN THE SOFTWARE.
57436
57437'use strict';
57438
57439/*<replacement>*/
57440
57441var pna = require('process-nextick-args');
57442/*</replacement>*/
57443
57444module.exports = Readable;
57445
57446/*<replacement>*/
57447var isArray = require('isarray');
57448/*</replacement>*/
57449
57450/*<replacement>*/
57451var Duplex;
57452/*</replacement>*/
57453
57454Readable.ReadableState = ReadableState;
57455
57456/*<replacement>*/
57457var EE = require('events').EventEmitter;
57458
57459var EElistenerCount = function (emitter, type) {
57460 return emitter.listeners(type).length;
57461};
57462/*</replacement>*/
57463
57464/*<replacement>*/
57465var Stream = require('./internal/streams/stream');
57466/*</replacement>*/
57467
57468/*<replacement>*/
57469
57470var Buffer = require('safe-buffer').Buffer;
57471var OurUint8Array = global.Uint8Array || function () {};
57472function _uint8ArrayToBuffer(chunk) {
57473 return Buffer.from(chunk);
57474}
57475function _isUint8Array(obj) {
57476 return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
57477}
57478
57479/*</replacement>*/
57480
57481/*<replacement>*/
57482var util = require('core-util-is');
57483util.inherits = require('inherits');
57484/*</replacement>*/
57485
57486/*<replacement>*/
57487var debugUtil = require('util');
57488var debug = void 0;
57489if (debugUtil && debugUtil.debuglog) {
57490 debug = debugUtil.debuglog('stream');
57491} else {
57492 debug = function () {};
57493}
57494/*</replacement>*/
57495
57496var BufferList = require('./internal/streams/BufferList');
57497var destroyImpl = require('./internal/streams/destroy');
57498var StringDecoder;
57499
57500util.inherits(Readable, Stream);
57501
57502var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume'];
57503
57504function prependListener(emitter, event, fn) {
57505 // Sadly this is not cacheable as some libraries bundle their own
57506 // event emitter implementation with them.
57507 if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn);
57508
57509 // This is a hack to make sure that our error handler is attached before any
57510 // userland ones. NEVER DO THIS. This is here only because this code needs
57511 // to continue to work with older versions of Node.js that do not include
57512 // the prependListener() method. The goal is to eventually remove this hack.
57513 if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]];
57514}
57515
57516function ReadableState(options, stream) {
57517 Duplex = Duplex || require('./_stream_duplex');
57518
57519 options = options || {};
57520
57521 // Duplex streams are both readable and writable, but share
57522 // the same options object.
57523 // However, some cases require setting options to different
57524 // values for the readable and the writable sides of the duplex stream.
57525 // These options can be provided separately as readableXXX and writableXXX.
57526 var isDuplex = stream instanceof Duplex;
57527
57528 // object stream flag. Used to make read(n) ignore n and to
57529 // make all the buffer merging and length checks go away
57530 this.objectMode = !!options.objectMode;
57531
57532 if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode;
57533
57534 // the point at which it stops calling _read() to fill the buffer
57535 // Note: 0 is a valid value, means "don't call _read preemptively ever"
57536 var hwm = options.highWaterMark;
57537 var readableHwm = options.readableHighWaterMark;
57538 var defaultHwm = this.objectMode ? 16 : 16 * 1024;
57539
57540 if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (readableHwm || readableHwm === 0)) this.highWaterMark = readableHwm;else this.highWaterMark = defaultHwm;
57541
57542 // cast to ints.
57543 this.highWaterMark = Math.floor(this.highWaterMark);
57544
57545 // A linked list is used to store data chunks instead of an array because the
57546 // linked list can remove elements from the beginning faster than
57547 // array.shift()
57548 this.buffer = new BufferList();
57549 this.length = 0;
57550 this.pipes = null;
57551 this.pipesCount = 0;
57552 this.flowing = null;
57553 this.ended = false;
57554 this.endEmitted = false;
57555 this.reading = false;
57556
57557 // a flag to be able to tell if the event 'readable'/'data' is emitted
57558 // immediately, or on a later tick. We set this to true at first, because
57559 // any actions that shouldn't happen until "later" should generally also
57560 // not happen before the first read call.
57561 this.sync = true;
57562
57563 // whenever we return null, then we set a flag to say
57564 // that we're awaiting a 'readable' event emission.
57565 this.needReadable = false;
57566 this.emittedReadable = false;
57567 this.readableListening = false;
57568 this.resumeScheduled = false;
57569
57570 // has it been destroyed
57571 this.destroyed = false;
57572
57573 // Crypto is kind of old and crusty. Historically, its default string
57574 // encoding is 'binary' so we have to make this configurable.
57575 // Everything else in the universe uses 'utf8', though.
57576 this.defaultEncoding = options.defaultEncoding || 'utf8';
57577
57578 // the number of writers that are awaiting a drain event in .pipe()s
57579 this.awaitDrain = 0;
57580
57581 // if true, a maybeReadMore has been scheduled
57582 this.readingMore = false;
57583
57584 this.decoder = null;
57585 this.encoding = null;
57586 if (options.encoding) {
57587 if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;
57588 this.decoder = new StringDecoder(options.encoding);
57589 this.encoding = options.encoding;
57590 }
57591}
57592
57593function Readable(options) {
57594 Duplex = Duplex || require('./_stream_duplex');
57595
57596 if (!(this instanceof Readable)) return new Readable(options);
57597
57598 this._readableState = new ReadableState(options, this);
57599
57600 // legacy
57601 this.readable = true;
57602
57603 if (options) {
57604 if (typeof options.read === 'function') this._read = options.read;
57605
57606 if (typeof options.destroy === 'function') this._destroy = options.destroy;
57607 }
57608
57609 Stream.call(this);
57610}
57611
57612Object.defineProperty(Readable.prototype, 'destroyed', {
57613 get: function () {
57614 if (this._readableState === undefined) {
57615 return false;
57616 }
57617 return this._readableState.destroyed;
57618 },
57619 set: function (value) {
57620 // we ignore the value if the stream
57621 // has not been initialized yet
57622 if (!this._readableState) {
57623 return;
57624 }
57625
57626 // backward compatibility, the user is explicitly
57627 // managing destroyed
57628 this._readableState.destroyed = value;
57629 }
57630});
57631
57632Readable.prototype.destroy = destroyImpl.destroy;
57633Readable.prototype._undestroy = destroyImpl.undestroy;
57634Readable.prototype._destroy = function (err, cb) {
57635 this.push(null);
57636 cb(err);
57637};
57638
57639// Manually shove something into the read() buffer.
57640// This returns true if the highWaterMark has not been hit yet,
57641// similar to how Writable.write() returns true if you should
57642// write() some more.
57643Readable.prototype.push = function (chunk, encoding) {
57644 var state = this._readableState;
57645 var skipChunkCheck;
57646
57647 if (!state.objectMode) {
57648 if (typeof chunk === 'string') {
57649 encoding = encoding || state.defaultEncoding;
57650 if (encoding !== state.encoding) {
57651 chunk = Buffer.from(chunk, encoding);
57652 encoding = '';
57653 }
57654 skipChunkCheck = true;
57655 }
57656 } else {
57657 skipChunkCheck = true;
57658 }
57659
57660 return readableAddChunk(this, chunk, encoding, false, skipChunkCheck);
57661};
57662
57663// Unshift should *always* be something directly out of read()
57664Readable.prototype.unshift = function (chunk) {
57665 return readableAddChunk(this, chunk, null, true, false);
57666};
57667
57668function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) {
57669 var state = stream._readableState;
57670 if (chunk === null) {
57671 state.reading = false;
57672 onEofChunk(stream, state);
57673 } else {
57674 var er;
57675 if (!skipChunkCheck) er = chunkInvalid(state, chunk);
57676 if (er) {
57677 stream.emit('error', er);
57678 } else if (state.objectMode || chunk && chunk.length > 0) {
57679 if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) {
57680 chunk = _uint8ArrayToBuffer(chunk);
57681 }
57682
57683 if (addToFront) {
57684 if (state.endEmitted) stream.emit('error', new Error('stream.unshift() after end event'));else addChunk(stream, state, chunk, true);
57685 } else if (state.ended) {
57686 stream.emit('error', new Error('stream.push() after EOF'));
57687 } else {
57688 state.reading = false;
57689 if (state.decoder && !encoding) {
57690 chunk = state.decoder.write(chunk);
57691 if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state);
57692 } else {
57693 addChunk(stream, state, chunk, false);
57694 }
57695 }
57696 } else if (!addToFront) {
57697 state.reading = false;
57698 }
57699 }
57700
57701 return needMoreData(state);
57702}
57703
57704function addChunk(stream, state, chunk, addToFront) {
57705 if (state.flowing && state.length === 0 && !state.sync) {
57706 stream.emit('data', chunk);
57707 stream.read(0);
57708 } else {
57709 // update the buffer info.
57710 state.length += state.objectMode ? 1 : chunk.length;
57711 if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk);
57712
57713 if (state.needReadable) emitReadable(stream);
57714 }
57715 maybeReadMore(stream, state);
57716}
57717
57718function chunkInvalid(state, chunk) {
57719 var er;
57720 if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
57721 er = new TypeError('Invalid non-string/buffer chunk');
57722 }
57723 return er;
57724}
57725
57726// if it's past the high water mark, we can push in some more.
57727// Also, if we have no data yet, we can stand some
57728// more bytes. This is to work around cases where hwm=0,
57729// such as the repl. Also, if the push() triggered a
57730// readable event, and the user called read(largeNumber) such that
57731// needReadable was set, then we ought to push more, so that another
57732// 'readable' event will be triggered.
57733function needMoreData(state) {
57734 return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0);
57735}
57736
57737Readable.prototype.isPaused = function () {
57738 return this._readableState.flowing === false;
57739};
57740
57741// backwards compatibility.
57742Readable.prototype.setEncoding = function (enc) {
57743 if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;
57744 this._readableState.decoder = new StringDecoder(enc);
57745 this._readableState.encoding = enc;
57746 return this;
57747};
57748
57749// Don't raise the hwm > 8MB
57750var MAX_HWM = 0x800000;
57751function computeNewHighWaterMark(n) {
57752 if (n >= MAX_HWM) {
57753 n = MAX_HWM;
57754 } else {
57755 // Get the next highest power of 2 to prevent increasing hwm excessively in
57756 // tiny amounts
57757 n--;
57758 n |= n >>> 1;
57759 n |= n >>> 2;
57760 n |= n >>> 4;
57761 n |= n >>> 8;
57762 n |= n >>> 16;
57763 n++;
57764 }
57765 return n;
57766}
57767
57768// This function is designed to be inlinable, so please take care when making
57769// changes to the function body.
57770function howMuchToRead(n, state) {
57771 if (n <= 0 || state.length === 0 && state.ended) return 0;
57772 if (state.objectMode) return 1;
57773 if (n !== n) {
57774 // Only flow one buffer at a time
57775 if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length;
57776 }
57777 // If we're asking for more than the current hwm, then raise the hwm.
57778 if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n);
57779 if (n <= state.length) return n;
57780 // Don't have enough
57781 if (!state.ended) {
57782 state.needReadable = true;
57783 return 0;
57784 }
57785 return state.length;
57786}
57787
57788// you can override either this method, or the async _read(n) below.
57789Readable.prototype.read = function (n) {
57790 debug('read', n);
57791 n = parseInt(n, 10);
57792 var state = this._readableState;
57793 var nOrig = n;
57794
57795 if (n !== 0) state.emittedReadable = false;
57796
57797 // if we're doing read(0) to trigger a readable event, but we
57798 // already have a bunch of data in the buffer, then just trigger
57799 // the 'readable' event and move on.
57800 if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) {
57801 debug('read: emitReadable', state.length, state.ended);
57802 if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this);
57803 return null;
57804 }
57805
57806 n = howMuchToRead(n, state);
57807
57808 // if we've ended, and we're now clear, then finish it up.
57809 if (n === 0 && state.ended) {
57810 if (state.length === 0) endReadable(this);
57811 return null;
57812 }
57813
57814 // All the actual chunk generation logic needs to be
57815 // *below* the call to _read. The reason is that in certain
57816 // synthetic stream cases, such as passthrough streams, _read
57817 // may be a completely synchronous operation which may change
57818 // the state of the read buffer, providing enough data when
57819 // before there was *not* enough.
57820 //
57821 // So, the steps are:
57822 // 1. Figure out what the state of things will be after we do
57823 // a read from the buffer.
57824 //
57825 // 2. If that resulting state will trigger a _read, then call _read.
57826 // Note that this may be asynchronous, or synchronous. Yes, it is
57827 // deeply ugly to write APIs this way, but that still doesn't mean
57828 // that the Readable class should behave improperly, as streams are
57829 // designed to be sync/async agnostic.
57830 // Take note if the _read call is sync or async (ie, if the read call
57831 // has returned yet), so that we know whether or not it's safe to emit
57832 // 'readable' etc.
57833 //
57834 // 3. Actually pull the requested chunks out of the buffer and return.
57835
57836 // if we need a readable event, then we need to do some reading.
57837 var doRead = state.needReadable;
57838 debug('need readable', doRead);
57839
57840 // if we currently have less than the highWaterMark, then also read some
57841 if (state.length === 0 || state.length - n < state.highWaterMark) {
57842 doRead = true;
57843 debug('length less than watermark', doRead);
57844 }
57845
57846 // however, if we've ended, then there's no point, and if we're already
57847 // reading, then it's unnecessary.
57848 if (state.ended || state.reading) {
57849 doRead = false;
57850 debug('reading or ended', doRead);
57851 } else if (doRead) {
57852 debug('do read');
57853 state.reading = true;
57854 state.sync = true;
57855 // if the length is currently zero, then we *need* a readable event.
57856 if (state.length === 0) state.needReadable = true;
57857 // call internal read method
57858 this._read(state.highWaterMark);
57859 state.sync = false;
57860 // If _read pushed data synchronously, then `reading` will be false,
57861 // and we need to re-evaluate how much data we can return to the user.
57862 if (!state.reading) n = howMuchToRead(nOrig, state);
57863 }
57864
57865 var ret;
57866 if (n > 0) ret = fromList(n, state);else ret = null;
57867
57868 if (ret === null) {
57869 state.needReadable = true;
57870 n = 0;
57871 } else {
57872 state.length -= n;
57873 }
57874
57875 if (state.length === 0) {
57876 // If we have nothing in the buffer, then we want to know
57877 // as soon as we *do* get something into the buffer.
57878 if (!state.ended) state.needReadable = true;
57879
57880 // If we tried to read() past the EOF, then emit end on the next tick.
57881 if (nOrig !== n && state.ended) endReadable(this);
57882 }
57883
57884 if (ret !== null) this.emit('data', ret);
57885
57886 return ret;
57887};
57888
57889function onEofChunk(stream, state) {
57890 if (state.ended) return;
57891 if (state.decoder) {
57892 var chunk = state.decoder.end();
57893 if (chunk && chunk.length) {
57894 state.buffer.push(chunk);
57895 state.length += state.objectMode ? 1 : chunk.length;
57896 }
57897 }
57898 state.ended = true;
57899
57900 // emit 'readable' now to make sure it gets picked up.
57901 emitReadable(stream);
57902}
57903
57904// Don't emit readable right away in sync mode, because this can trigger
57905// another read() call => stack overflow. This way, it might trigger
57906// a nextTick recursion warning, but that's not so bad.
57907function emitReadable(stream) {
57908 var state = stream._readableState;
57909 state.needReadable = false;
57910 if (!state.emittedReadable) {
57911 debug('emitReadable', state.flowing);
57912 state.emittedReadable = true;
57913 if (state.sync) pna.nextTick(emitReadable_, stream);else emitReadable_(stream);
57914 }
57915}
57916
57917function emitReadable_(stream) {
57918 debug('emit readable');
57919 stream.emit('readable');
57920 flow(stream);
57921}
57922
57923// at this point, the user has presumably seen the 'readable' event,
57924// and called read() to consume some data. that may have triggered
57925// in turn another _read(n) call, in which case reading = true if
57926// it's in progress.
57927// However, if we're not ended, or reading, and the length < hwm,
57928// then go ahead and try to read some more preemptively.
57929function maybeReadMore(stream, state) {
57930 if (!state.readingMore) {
57931 state.readingMore = true;
57932 pna.nextTick(maybeReadMore_, stream, state);
57933 }
57934}
57935
57936function maybeReadMore_(stream, state) {
57937 var len = state.length;
57938 while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) {
57939 debug('maybeReadMore read 0');
57940 stream.read(0);
57941 if (len === state.length)
57942 // didn't get any data, stop spinning.
57943 break;else len = state.length;
57944 }
57945 state.readingMore = false;
57946}
57947
57948// abstract method. to be overridden in specific implementation classes.
57949// call cb(er, data) where data is <= n in length.
57950// for virtual (non-string, non-buffer) streams, "length" is somewhat
57951// arbitrary, and perhaps not very meaningful.
57952Readable.prototype._read = function (n) {
57953 this.emit('error', new Error('_read() is not implemented'));
57954};
57955
57956Readable.prototype.pipe = function (dest, pipeOpts) {
57957 var src = this;
57958 var state = this._readableState;
57959
57960 switch (state.pipesCount) {
57961 case 0:
57962 state.pipes = dest;
57963 break;
57964 case 1:
57965 state.pipes = [state.pipes, dest];
57966 break;
57967 default:
57968 state.pipes.push(dest);
57969 break;
57970 }
57971 state.pipesCount += 1;
57972 debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);
57973
57974 var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr;
57975
57976 var endFn = doEnd ? onend : unpipe;
57977 if (state.endEmitted) pna.nextTick(endFn);else src.once('end', endFn);
57978
57979 dest.on('unpipe', onunpipe);
57980 function onunpipe(readable, unpipeInfo) {
57981 debug('onunpipe');
57982 if (readable === src) {
57983 if (unpipeInfo && unpipeInfo.hasUnpiped === false) {
57984 unpipeInfo.hasUnpiped = true;
57985 cleanup();
57986 }
57987 }
57988 }
57989
57990 function onend() {
57991 debug('onend');
57992 dest.end();
57993 }
57994
57995 // when the dest drains, it reduces the awaitDrain counter
57996 // on the source. This would be more elegant with a .once()
57997 // handler in flow(), but adding and removing repeatedly is
57998 // too slow.
57999 var ondrain = pipeOnDrain(src);
58000 dest.on('drain', ondrain);
58001
58002 var cleanedUp = false;
58003 function cleanup() {
58004 debug('cleanup');
58005 // cleanup event handlers once the pipe is broken
58006 dest.removeListener('close', onclose);
58007 dest.removeListener('finish', onfinish);
58008 dest.removeListener('drain', ondrain);
58009 dest.removeListener('error', onerror);
58010 dest.removeListener('unpipe', onunpipe);
58011 src.removeListener('end', onend);
58012 src.removeListener('end', unpipe);
58013 src.removeListener('data', ondata);
58014
58015 cleanedUp = true;
58016
58017 // if the reader is waiting for a drain event from this
58018 // specific writer, then it would cause it to never start
58019 // flowing again.
58020 // So, if this is awaiting a drain, then we just call it now.
58021 // If we don't know, then assume that we are waiting for one.
58022 if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain();
58023 }
58024
58025 // If the user pushes more data while we're writing to dest then we'll end up
58026 // in ondata again. However, we only want to increase awaitDrain once because
58027 // dest will only emit one 'drain' event for the multiple writes.
58028 // => Introduce a guard on increasing awaitDrain.
58029 var increasedAwaitDrain = false;
58030 src.on('data', ondata);
58031 function ondata(chunk) {
58032 debug('ondata');
58033 increasedAwaitDrain = false;
58034 var ret = dest.write(chunk);
58035 if (false === ret && !increasedAwaitDrain) {
58036 // If the user unpiped during `dest.write()`, it is possible
58037 // to get stuck in a permanently paused state if that write
58038 // also returned false.
58039 // => Check whether `dest` is still a piping destination.
58040 if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) {
58041 debug('false write response, pause', src._readableState.awaitDrain);
58042 src._readableState.awaitDrain++;
58043 increasedAwaitDrain = true;
58044 }
58045 src.pause();
58046 }
58047 }
58048
58049 // if the dest has an error, then stop piping into it.
58050 // however, don't suppress the throwing behavior for this.
58051 function onerror(er) {
58052 debug('onerror', er);
58053 unpipe();
58054 dest.removeListener('error', onerror);
58055 if (EElistenerCount(dest, 'error') === 0) dest.emit('error', er);
58056 }
58057
58058 // Make sure our error handler is attached before userland ones.
58059 prependListener(dest, 'error', onerror);
58060
58061 // Both close and finish should trigger unpipe, but only once.
58062 function onclose() {
58063 dest.removeListener('finish', onfinish);
58064 unpipe();
58065 }
58066 dest.once('close', onclose);
58067 function onfinish() {
58068 debug('onfinish');
58069 dest.removeListener('close', onclose);
58070 unpipe();
58071 }
58072 dest.once('finish', onfinish);
58073
58074 function unpipe() {
58075 debug('unpipe');
58076 src.unpipe(dest);
58077 }
58078
58079 // tell the dest that it's being piped to
58080 dest.emit('pipe', src);
58081
58082 // start the flow if it hasn't been started already.
58083 if (!state.flowing) {
58084 debug('pipe resume');
58085 src.resume();
58086 }
58087
58088 return dest;
58089};
58090
58091function pipeOnDrain(src) {
58092 return function () {
58093 var state = src._readableState;
58094 debug('pipeOnDrain', state.awaitDrain);
58095 if (state.awaitDrain) state.awaitDrain--;
58096 if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) {
58097 state.flowing = true;
58098 flow(src);
58099 }
58100 };
58101}
58102
58103Readable.prototype.unpipe = function (dest) {
58104 var state = this._readableState;
58105 var unpipeInfo = { hasUnpiped: false };
58106
58107 // if we're not piping anywhere, then do nothing.
58108 if (state.pipesCount === 0) return this;
58109
58110 // just one destination. most common case.
58111 if (state.pipesCount === 1) {
58112 // passed in one, but it's not the right one.
58113 if (dest && dest !== state.pipes) return this;
58114
58115 if (!dest) dest = state.pipes;
58116
58117 // got a match.
58118 state.pipes = null;
58119 state.pipesCount = 0;
58120 state.flowing = false;
58121 if (dest) dest.emit('unpipe', this, unpipeInfo);
58122 return this;
58123 }
58124
58125 // slow case. multiple pipe destinations.
58126
58127 if (!dest) {
58128 // remove all.
58129 var dests = state.pipes;
58130 var len = state.pipesCount;
58131 state.pipes = null;
58132 state.pipesCount = 0;
58133 state.flowing = false;
58134
58135 for (var i = 0; i < len; i++) {
58136 dests[i].emit('unpipe', this, unpipeInfo);
58137 }return this;
58138 }
58139
58140 // try to find the right one.
58141 var index = indexOf(state.pipes, dest);
58142 if (index === -1) return this;
58143
58144 state.pipes.splice(index, 1);
58145 state.pipesCount -= 1;
58146 if (state.pipesCount === 1) state.pipes = state.pipes[0];
58147
58148 dest.emit('unpipe', this, unpipeInfo);
58149
58150 return this;
58151};
58152
58153// set up data events if they are asked for
58154// Ensure readable listeners eventually get something
58155Readable.prototype.on = function (ev, fn) {
58156 var res = Stream.prototype.on.call(this, ev, fn);
58157
58158 if (ev === 'data') {
58159 // Start flowing on next tick if stream isn't explicitly paused
58160 if (this._readableState.flowing !== false) this.resume();
58161 } else if (ev === 'readable') {
58162 var state = this._readableState;
58163 if (!state.endEmitted && !state.readableListening) {
58164 state.readableListening = state.needReadable = true;
58165 state.emittedReadable = false;
58166 if (!state.reading) {
58167 pna.nextTick(nReadingNextTick, this);
58168 } else if (state.length) {
58169 emitReadable(this);
58170 }
58171 }
58172 }
58173
58174 return res;
58175};
58176Readable.prototype.addListener = Readable.prototype.on;
58177
58178function nReadingNextTick(self) {
58179 debug('readable nexttick read 0');
58180 self.read(0);
58181}
58182
58183// pause() and resume() are remnants of the legacy readable stream API
58184// If the user uses them, then switch into old mode.
58185Readable.prototype.resume = function () {
58186 var state = this._readableState;
58187 if (!state.flowing) {
58188 debug('resume');
58189 state.flowing = true;
58190 resume(this, state);
58191 }
58192 return this;
58193};
58194
58195function resume(stream, state) {
58196 if (!state.resumeScheduled) {
58197 state.resumeScheduled = true;
58198 pna.nextTick(resume_, stream, state);
58199 }
58200}
58201
58202function resume_(stream, state) {
58203 if (!state.reading) {
58204 debug('resume read 0');
58205 stream.read(0);
58206 }
58207
58208 state.resumeScheduled = false;
58209 state.awaitDrain = 0;
58210 stream.emit('resume');
58211 flow(stream);
58212 if (state.flowing && !state.reading) stream.read(0);
58213}
58214
58215Readable.prototype.pause = function () {
58216 debug('call pause flowing=%j', this._readableState.flowing);
58217 if (false !== this._readableState.flowing) {
58218 debug('pause');
58219 this._readableState.flowing = false;
58220 this.emit('pause');
58221 }
58222 return this;
58223};
58224
58225function flow(stream) {
58226 var state = stream._readableState;
58227 debug('flow', state.flowing);
58228 while (state.flowing && stream.read() !== null) {}
58229}
58230
58231// wrap an old-style stream as the async data source.
58232// This is *not* part of the readable stream interface.
58233// It is an ugly unfortunate mess of history.
58234Readable.prototype.wrap = function (stream) {
58235 var _this = this;
58236
58237 var state = this._readableState;
58238 var paused = false;
58239
58240 stream.on('end', function () {
58241 debug('wrapped end');
58242 if (state.decoder && !state.ended) {
58243 var chunk = state.decoder.end();
58244 if (chunk && chunk.length) _this.push(chunk);
58245 }
58246
58247 _this.push(null);
58248 });
58249
58250 stream.on('data', function (chunk) {
58251 debug('wrapped data');
58252 if (state.decoder) chunk = state.decoder.write(chunk);
58253
58254 // don't skip over falsy values in objectMode
58255 if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return;
58256
58257 var ret = _this.push(chunk);
58258 if (!ret) {
58259 paused = true;
58260 stream.pause();
58261 }
58262 });
58263
58264 // proxy all the other methods.
58265 // important when wrapping filters and duplexes.
58266 for (var i in stream) {
58267 if (this[i] === undefined && typeof stream[i] === 'function') {
58268 this[i] = function (method) {
58269 return function () {
58270 return stream[method].apply(stream, arguments);
58271 };
58272 }(i);
58273 }
58274 }
58275
58276 // proxy certain important events.
58277 for (var n = 0; n < kProxyEvents.length; n++) {
58278 stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n]));
58279 }
58280
58281 // when we try to consume some more bytes, simply unpause the
58282 // underlying stream.
58283 this._read = function (n) {
58284 debug('wrapped _read', n);
58285 if (paused) {
58286 paused = false;
58287 stream.resume();
58288 }
58289 };
58290
58291 return this;
58292};
58293
58294Object.defineProperty(Readable.prototype, 'readableHighWaterMark', {
58295 // making it explicit this property is not enumerable
58296 // because otherwise some prototype manipulation in
58297 // userland will fail
58298 enumerable: false,
58299 get: function () {
58300 return this._readableState.highWaterMark;
58301 }
58302});
58303
58304// exposed for testing purposes only.
58305Readable._fromList = fromList;
58306
58307// Pluck off n bytes from an array of buffers.
58308// Length is the combined lengths of all the buffers in the list.
58309// This function is designed to be inlinable, so please take care when making
58310// changes to the function body.
58311function fromList(n, state) {
58312 // nothing buffered
58313 if (state.length === 0) return null;
58314
58315 var ret;
58316 if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) {
58317 // read it all, truncate the list
58318 if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.head.data;else ret = state.buffer.concat(state.length);
58319 state.buffer.clear();
58320 } else {
58321 // read part of list
58322 ret = fromListPartial(n, state.buffer, state.decoder);
58323 }
58324
58325 return ret;
58326}
58327
58328// Extracts only enough buffered data to satisfy the amount requested.
58329// This function is designed to be inlinable, so please take care when making
58330// changes to the function body.
58331function fromListPartial(n, list, hasStrings) {
58332 var ret;
58333 if (n < list.head.data.length) {
58334 // slice is the same for buffers and strings
58335 ret = list.head.data.slice(0, n);
58336 list.head.data = list.head.data.slice(n);
58337 } else if (n === list.head.data.length) {
58338 // first chunk is a perfect match
58339 ret = list.shift();
58340 } else {
58341 // result spans more than one buffer
58342 ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list);
58343 }
58344 return ret;
58345}
58346
58347// Copies a specified amount of characters from the list of buffered data
58348// chunks.
58349// This function is designed to be inlinable, so please take care when making
58350// changes to the function body.
58351function copyFromBufferString(n, list) {
58352 var p = list.head;
58353 var c = 1;
58354 var ret = p.data;
58355 n -= ret.length;
58356 while (p = p.next) {
58357 var str = p.data;
58358 var nb = n > str.length ? str.length : n;
58359 if (nb === str.length) ret += str;else ret += str.slice(0, n);
58360 n -= nb;
58361 if (n === 0) {
58362 if (nb === str.length) {
58363 ++c;
58364 if (p.next) list.head = p.next;else list.head = list.tail = null;
58365 } else {
58366 list.head = p;
58367 p.data = str.slice(nb);
58368 }
58369 break;
58370 }
58371 ++c;
58372 }
58373 list.length -= c;
58374 return ret;
58375}
58376
58377// Copies a specified amount of bytes from the list of buffered data chunks.
58378// This function is designed to be inlinable, so please take care when making
58379// changes to the function body.
58380function copyFromBuffer(n, list) {
58381 var ret = Buffer.allocUnsafe(n);
58382 var p = list.head;
58383 var c = 1;
58384 p.data.copy(ret);
58385 n -= p.data.length;
58386 while (p = p.next) {
58387 var buf = p.data;
58388 var nb = n > buf.length ? buf.length : n;
58389 buf.copy(ret, ret.length - n, 0, nb);
58390 n -= nb;
58391 if (n === 0) {
58392 if (nb === buf.length) {
58393 ++c;
58394 if (p.next) list.head = p.next;else list.head = list.tail = null;
58395 } else {
58396 list.head = p;
58397 p.data = buf.slice(nb);
58398 }
58399 break;
58400 }
58401 ++c;
58402 }
58403 list.length -= c;
58404 return ret;
58405}
58406
58407function endReadable(stream) {
58408 var state = stream._readableState;
58409
58410 // If we get here before consuming all the bytes, then that is a
58411 // bug in node. Should never happen.
58412 if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream');
58413
58414 if (!state.endEmitted) {
58415 state.ended = true;
58416 pna.nextTick(endReadableNT, state, stream);
58417 }
58418}
58419
58420function endReadableNT(state, stream) {
58421 // Check that we didn't get one last unshift.
58422 if (!state.endEmitted && state.length === 0) {
58423 state.endEmitted = true;
58424 stream.readable = false;
58425 stream.emit('end');
58426 }
58427}
58428
58429function indexOf(xs, x) {
58430 for (var i = 0, l = xs.length; i < l; i++) {
58431 if (xs[i] === x) return i;
58432 }
58433 return -1;
58434}
58435}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
58436},{"./_stream_duplex":281,"./internal/streams/BufferList":286,"./internal/streams/destroy":287,"./internal/streams/stream":288,"_process":265,"core-util-is":120,"events":159,"inherits":210,"isarray":213,"process-nextick-args":264,"safe-buffer":325,"string_decoder/":289,"util":82}],284:[function(require,module,exports){
58437// Copyright Joyent, Inc. and other Node contributors.
58438//
58439// Permission is hereby granted, free of charge, to any person obtaining a
58440// copy of this software and associated documentation files (the
58441// "Software"), to deal in the Software without restriction, including
58442// without limitation the rights to use, copy, modify, merge, publish,
58443// distribute, sublicense, and/or sell copies of the Software, and to permit
58444// persons to whom the Software is furnished to do so, subject to the
58445// following conditions:
58446//
58447// The above copyright notice and this permission notice shall be included
58448// in all copies or substantial portions of the Software.
58449//
58450// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
58451// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
58452// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
58453// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
58454// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
58455// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
58456// USE OR OTHER DEALINGS IN THE SOFTWARE.
58457
58458// a transform stream is a readable/writable stream where you do
58459// something with the data. Sometimes it's called a "filter",
58460// but that's not a great name for it, since that implies a thing where
58461// some bits pass through, and others are simply ignored. (That would
58462// be a valid example of a transform, of course.)
58463//
58464// While the output is causally related to the input, it's not a
58465// necessarily symmetric or synchronous transformation. For example,
58466// a zlib stream might take multiple plain-text writes(), and then
58467// emit a single compressed chunk some time in the future.
58468//
58469// Here's how this works:
58470//
58471// The Transform stream has all the aspects of the readable and writable
58472// stream classes. When you write(chunk), that calls _write(chunk,cb)
58473// internally, and returns false if there's a lot of pending writes
58474// buffered up. When you call read(), that calls _read(n) until
58475// there's enough pending readable data buffered up.
58476//
58477// In a transform stream, the written data is placed in a buffer. When
58478// _read(n) is called, it transforms the queued up data, calling the
58479// buffered _write cb's as it consumes chunks. If consuming a single
58480// written chunk would result in multiple output chunks, then the first
58481// outputted bit calls the readcb, and subsequent chunks just go into
58482// the read buffer, and will cause it to emit 'readable' if necessary.
58483//
58484// This way, back-pressure is actually determined by the reading side,
58485// since _read has to be called to start processing a new chunk. However,
58486// a pathological inflate type of transform can cause excessive buffering
58487// here. For example, imagine a stream where every byte of input is
58488// interpreted as an integer from 0-255, and then results in that many
58489// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in
58490// 1kb of data being output. In this case, you could write a very small
58491// amount of input, and end up with a very large amount of output. In
58492// such a pathological inflating mechanism, there'd be no way to tell
58493// the system to stop doing the transform. A single 4MB write could
58494// cause the system to run out of memory.
58495//
58496// However, even in such a pathological case, only a single written chunk
58497// would be consumed, and then the rest would wait (un-transformed) until
58498// the results of the previous transformed chunk were consumed.
58499
58500'use strict';
58501
58502module.exports = Transform;
58503
58504var Duplex = require('./_stream_duplex');
58505
58506/*<replacement>*/
58507var util = require('core-util-is');
58508util.inherits = require('inherits');
58509/*</replacement>*/
58510
58511util.inherits(Transform, Duplex);
58512
58513function afterTransform(er, data) {
58514 var ts = this._transformState;
58515 ts.transforming = false;
58516
58517 var cb = ts.writecb;
58518
58519 if (!cb) {
58520 return this.emit('error', new Error('write callback called multiple times'));
58521 }
58522
58523 ts.writechunk = null;
58524 ts.writecb = null;
58525
58526 if (data != null) // single equals check for both `null` and `undefined`
58527 this.push(data);
58528
58529 cb(er);
58530
58531 var rs = this._readableState;
58532 rs.reading = false;
58533 if (rs.needReadable || rs.length < rs.highWaterMark) {
58534 this._read(rs.highWaterMark);
58535 }
58536}
58537
58538function Transform(options) {
58539 if (!(this instanceof Transform)) return new Transform(options);
58540
58541 Duplex.call(this, options);
58542
58543 this._transformState = {
58544 afterTransform: afterTransform.bind(this),
58545 needTransform: false,
58546 transforming: false,
58547 writecb: null,
58548 writechunk: null,
58549 writeencoding: null
58550 };
58551
58552 // start out asking for a readable event once data is transformed.
58553 this._readableState.needReadable = true;
58554
58555 // we have implemented the _read method, and done the other things
58556 // that Readable wants before the first _read call, so unset the
58557 // sync guard flag.
58558 this._readableState.sync = false;
58559
58560 if (options) {
58561 if (typeof options.transform === 'function') this._transform = options.transform;
58562
58563 if (typeof options.flush === 'function') this._flush = options.flush;
58564 }
58565
58566 // When the writable side finishes, then flush out anything remaining.
58567 this.on('prefinish', prefinish);
58568}
58569
58570function prefinish() {
58571 var _this = this;
58572
58573 if (typeof this._flush === 'function') {
58574 this._flush(function (er, data) {
58575 done(_this, er, data);
58576 });
58577 } else {
58578 done(this, null, null);
58579 }
58580}
58581
58582Transform.prototype.push = function (chunk, encoding) {
58583 this._transformState.needTransform = false;
58584 return Duplex.prototype.push.call(this, chunk, encoding);
58585};
58586
58587// This is the part where you do stuff!
58588// override this function in implementation classes.
58589// 'chunk' is an input chunk.
58590//
58591// Call `push(newChunk)` to pass along transformed output
58592// to the readable side. You may call 'push' zero or more times.
58593//
58594// Call `cb(err)` when you are done with this chunk. If you pass
58595// an error, then that'll put the hurt on the whole operation. If you
58596// never call cb(), then you'll never get another chunk.
58597Transform.prototype._transform = function (chunk, encoding, cb) {
58598 throw new Error('_transform() is not implemented');
58599};
58600
58601Transform.prototype._write = function (chunk, encoding, cb) {
58602 var ts = this._transformState;
58603 ts.writecb = cb;
58604 ts.writechunk = chunk;
58605 ts.writeencoding = encoding;
58606 if (!ts.transforming) {
58607 var rs = this._readableState;
58608 if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark);
58609 }
58610};
58611
58612// Doesn't matter what the args are here.
58613// _transform does all the work.
58614// That we got here means that the readable side wants more data.
58615Transform.prototype._read = function (n) {
58616 var ts = this._transformState;
58617
58618 if (ts.writechunk !== null && ts.writecb && !ts.transforming) {
58619 ts.transforming = true;
58620 this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);
58621 } else {
58622 // mark that we need a transform, so that any data that comes in
58623 // will get processed, now that we've asked for it.
58624 ts.needTransform = true;
58625 }
58626};
58627
58628Transform.prototype._destroy = function (err, cb) {
58629 var _this2 = this;
58630
58631 Duplex.prototype._destroy.call(this, err, function (err2) {
58632 cb(err2);
58633 _this2.emit('close');
58634 });
58635};
58636
58637function done(stream, er, data) {
58638 if (er) return stream.emit('error', er);
58639
58640 if (data != null) // single equals check for both `null` and `undefined`
58641 stream.push(data);
58642
58643 // if there's nothing in the write buffer, then that means
58644 // that nothing more will ever be provided
58645 if (stream._writableState.length) throw new Error('Calling transform done when ws.length != 0');
58646
58647 if (stream._transformState.transforming) throw new Error('Calling transform done when still transforming');
58648
58649 return stream.push(null);
58650}
58651},{"./_stream_duplex":281,"core-util-is":120,"inherits":210}],285:[function(require,module,exports){
58652(function (process,global,setImmediate){
58653// Copyright Joyent, Inc. and other Node contributors.
58654//
58655// Permission is hereby granted, free of charge, to any person obtaining a
58656// copy of this software and associated documentation files (the
58657// "Software"), to deal in the Software without restriction, including
58658// without limitation the rights to use, copy, modify, merge, publish,
58659// distribute, sublicense, and/or sell copies of the Software, and to permit
58660// persons to whom the Software is furnished to do so, subject to the
58661// following conditions:
58662//
58663// The above copyright notice and this permission notice shall be included
58664// in all copies or substantial portions of the Software.
58665//
58666// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
58667// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
58668// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
58669// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
58670// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
58671// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
58672// USE OR OTHER DEALINGS IN THE SOFTWARE.
58673
58674// A bit simpler than readable streams.
58675// Implement an async ._write(chunk, encoding, cb), and it'll handle all
58676// the drain event emission and buffering.
58677
58678'use strict';
58679
58680/*<replacement>*/
58681
58682var pna = require('process-nextick-args');
58683/*</replacement>*/
58684
58685module.exports = Writable;
58686
58687/* <replacement> */
58688function WriteReq(chunk, encoding, cb) {
58689 this.chunk = chunk;
58690 this.encoding = encoding;
58691 this.callback = cb;
58692 this.next = null;
58693}
58694
58695// It seems a linked list but it is not
58696// there will be only 2 of these for each stream
58697function CorkedRequest(state) {
58698 var _this = this;
58699
58700 this.next = null;
58701 this.entry = null;
58702 this.finish = function () {
58703 onCorkedFinish(_this, state);
58704 };
58705}
58706/* </replacement> */
58707
58708/*<replacement>*/
58709var asyncWrite = !process.browser && ['v0.10', 'v0.9.'].indexOf(process.version.slice(0, 5)) > -1 ? setImmediate : pna.nextTick;
58710/*</replacement>*/
58711
58712/*<replacement>*/
58713var Duplex;
58714/*</replacement>*/
58715
58716Writable.WritableState = WritableState;
58717
58718/*<replacement>*/
58719var util = require('core-util-is');
58720util.inherits = require('inherits');
58721/*</replacement>*/
58722
58723/*<replacement>*/
58724var internalUtil = {
58725 deprecate: require('util-deprecate')
58726};
58727/*</replacement>*/
58728
58729/*<replacement>*/
58730var Stream = require('./internal/streams/stream');
58731/*</replacement>*/
58732
58733/*<replacement>*/
58734
58735var Buffer = require('safe-buffer').Buffer;
58736var OurUint8Array = global.Uint8Array || function () {};
58737function _uint8ArrayToBuffer(chunk) {
58738 return Buffer.from(chunk);
58739}
58740function _isUint8Array(obj) {
58741 return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
58742}
58743
58744/*</replacement>*/
58745
58746var destroyImpl = require('./internal/streams/destroy');
58747
58748util.inherits(Writable, Stream);
58749
58750function nop() {}
58751
58752function WritableState(options, stream) {
58753 Duplex = Duplex || require('./_stream_duplex');
58754
58755 options = options || {};
58756
58757 // Duplex streams are both readable and writable, but share
58758 // the same options object.
58759 // However, some cases require setting options to different
58760 // values for the readable and the writable sides of the duplex stream.
58761 // These options can be provided separately as readableXXX and writableXXX.
58762 var isDuplex = stream instanceof Duplex;
58763
58764 // object stream flag to indicate whether or not this stream
58765 // contains buffers or objects.
58766 this.objectMode = !!options.objectMode;
58767
58768 if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode;
58769
58770 // the point at which write() starts returning false
58771 // Note: 0 is a valid value, means that we always return false if
58772 // the entire buffer is not flushed immediately on write()
58773 var hwm = options.highWaterMark;
58774 var writableHwm = options.writableHighWaterMark;
58775 var defaultHwm = this.objectMode ? 16 : 16 * 1024;
58776
58777 if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (writableHwm || writableHwm === 0)) this.highWaterMark = writableHwm;else this.highWaterMark = defaultHwm;
58778
58779 // cast to ints.
58780 this.highWaterMark = Math.floor(this.highWaterMark);
58781
58782 // if _final has been called
58783 this.finalCalled = false;
58784
58785 // drain event flag.
58786 this.needDrain = false;
58787 // at the start of calling end()
58788 this.ending = false;
58789 // when end() has been called, and returned
58790 this.ended = false;
58791 // when 'finish' is emitted
58792 this.finished = false;
58793
58794 // has it been destroyed
58795 this.destroyed = false;
58796
58797 // should we decode strings into buffers before passing to _write?
58798 // this is here so that some node-core streams can optimize string
58799 // handling at a lower level.
58800 var noDecode = options.decodeStrings === false;
58801 this.decodeStrings = !noDecode;
58802
58803 // Crypto is kind of old and crusty. Historically, its default string
58804 // encoding is 'binary' so we have to make this configurable.
58805 // Everything else in the universe uses 'utf8', though.
58806 this.defaultEncoding = options.defaultEncoding || 'utf8';
58807
58808 // not an actual buffer we keep track of, but a measurement
58809 // of how much we're waiting to get pushed to some underlying
58810 // socket or file.
58811 this.length = 0;
58812
58813 // a flag to see when we're in the middle of a write.
58814 this.writing = false;
58815
58816 // when true all writes will be buffered until .uncork() call
58817 this.corked = 0;
58818
58819 // a flag to be able to tell if the onwrite cb is called immediately,
58820 // or on a later tick. We set this to true at first, because any
58821 // actions that shouldn't happen until "later" should generally also
58822 // not happen before the first write call.
58823 this.sync = true;
58824
58825 // a flag to know if we're processing previously buffered items, which
58826 // may call the _write() callback in the same tick, so that we don't
58827 // end up in an overlapped onwrite situation.
58828 this.bufferProcessing = false;
58829
58830 // the callback that's passed to _write(chunk,cb)
58831 this.onwrite = function (er) {
58832 onwrite(stream, er);
58833 };
58834
58835 // the callback that the user supplies to write(chunk,encoding,cb)
58836 this.writecb = null;
58837
58838 // the amount that is being written when _write is called.
58839 this.writelen = 0;
58840
58841 this.bufferedRequest = null;
58842 this.lastBufferedRequest = null;
58843
58844 // number of pending user-supplied write callbacks
58845 // this must be 0 before 'finish' can be emitted
58846 this.pendingcb = 0;
58847
58848 // emit prefinish if the only thing we're waiting for is _write cbs
58849 // This is relevant for synchronous Transform streams
58850 this.prefinished = false;
58851
58852 // True if the error was already emitted and should not be thrown again
58853 this.errorEmitted = false;
58854
58855 // count buffered requests
58856 this.bufferedRequestCount = 0;
58857
58858 // allocate the first CorkedRequest, there is always
58859 // one allocated and free to use, and we maintain at most two
58860 this.corkedRequestsFree = new CorkedRequest(this);
58861}
58862
58863WritableState.prototype.getBuffer = function getBuffer() {
58864 var current = this.bufferedRequest;
58865 var out = [];
58866 while (current) {
58867 out.push(current);
58868 current = current.next;
58869 }
58870 return out;
58871};
58872
58873(function () {
58874 try {
58875 Object.defineProperty(WritableState.prototype, 'buffer', {
58876 get: internalUtil.deprecate(function () {
58877 return this.getBuffer();
58878 }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003')
58879 });
58880 } catch (_) {}
58881})();
58882
58883// Test _writableState for inheritance to account for Duplex streams,
58884// whose prototype chain only points to Readable.
58885var realHasInstance;
58886if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') {
58887 realHasInstance = Function.prototype[Symbol.hasInstance];
58888 Object.defineProperty(Writable, Symbol.hasInstance, {
58889 value: function (object) {
58890 if (realHasInstance.call(this, object)) return true;
58891 if (this !== Writable) return false;
58892
58893 return object && object._writableState instanceof WritableState;
58894 }
58895 });
58896} else {
58897 realHasInstance = function (object) {
58898 return object instanceof this;
58899 };
58900}
58901
58902function Writable(options) {
58903 Duplex = Duplex || require('./_stream_duplex');
58904
58905 // Writable ctor is applied to Duplexes, too.
58906 // `realHasInstance` is necessary because using plain `instanceof`
58907 // would return false, as no `_writableState` property is attached.
58908
58909 // Trying to use the custom `instanceof` for Writable here will also break the
58910 // Node.js LazyTransform implementation, which has a non-trivial getter for
58911 // `_writableState` that would lead to infinite recursion.
58912 if (!realHasInstance.call(Writable, this) && !(this instanceof Duplex)) {
58913 return new Writable(options);
58914 }
58915
58916 this._writableState = new WritableState(options, this);
58917
58918 // legacy.
58919 this.writable = true;
58920
58921 if (options) {
58922 if (typeof options.write === 'function') this._write = options.write;
58923
58924 if (typeof options.writev === 'function') this._writev = options.writev;
58925
58926 if (typeof options.destroy === 'function') this._destroy = options.destroy;
58927
58928 if (typeof options.final === 'function') this._final = options.final;
58929 }
58930
58931 Stream.call(this);
58932}
58933
58934// Otherwise people can pipe Writable streams, which is just wrong.
58935Writable.prototype.pipe = function () {
58936 this.emit('error', new Error('Cannot pipe, not readable'));
58937};
58938
58939function writeAfterEnd(stream, cb) {
58940 var er = new Error('write after end');
58941 // TODO: defer error events consistently everywhere, not just the cb
58942 stream.emit('error', er);
58943 pna.nextTick(cb, er);
58944}
58945
58946// Checks that a user-supplied chunk is valid, especially for the particular
58947// mode the stream is in. Currently this means that `null` is never accepted
58948// and undefined/non-string values are only allowed in object mode.
58949function validChunk(stream, state, chunk, cb) {
58950 var valid = true;
58951 var er = false;
58952
58953 if (chunk === null) {
58954 er = new TypeError('May not write null values to stream');
58955 } else if (typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
58956 er = new TypeError('Invalid non-string/buffer chunk');
58957 }
58958 if (er) {
58959 stream.emit('error', er);
58960 pna.nextTick(cb, er);
58961 valid = false;
58962 }
58963 return valid;
58964}
58965
58966Writable.prototype.write = function (chunk, encoding, cb) {
58967 var state = this._writableState;
58968 var ret = false;
58969 var isBuf = !state.objectMode && _isUint8Array(chunk);
58970
58971 if (isBuf && !Buffer.isBuffer(chunk)) {
58972 chunk = _uint8ArrayToBuffer(chunk);
58973 }
58974
58975 if (typeof encoding === 'function') {
58976 cb = encoding;
58977 encoding = null;
58978 }
58979
58980 if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding;
58981
58982 if (typeof cb !== 'function') cb = nop;
58983
58984 if (state.ended) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) {
58985 state.pendingcb++;
58986 ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb);
58987 }
58988
58989 return ret;
58990};
58991
58992Writable.prototype.cork = function () {
58993 var state = this._writableState;
58994
58995 state.corked++;
58996};
58997
58998Writable.prototype.uncork = function () {
58999 var state = this._writableState;
59000
59001 if (state.corked) {
59002 state.corked--;
59003
59004 if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state);
59005 }
59006};
59007
59008Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) {
59009 // node::ParseEncoding() requires lower case.
59010 if (typeof encoding === 'string') encoding = encoding.toLowerCase();
59011 if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new TypeError('Unknown encoding: ' + encoding);
59012 this._writableState.defaultEncoding = encoding;
59013 return this;
59014};
59015
59016function decodeChunk(state, chunk, encoding) {
59017 if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') {
59018 chunk = Buffer.from(chunk, encoding);
59019 }
59020 return chunk;
59021}
59022
59023Object.defineProperty(Writable.prototype, 'writableHighWaterMark', {
59024 // making it explicit this property is not enumerable
59025 // because otherwise some prototype manipulation in
59026 // userland will fail
59027 enumerable: false,
59028 get: function () {
59029 return this._writableState.highWaterMark;
59030 }
59031});
59032
59033// if we're already writing something, then just put this
59034// in the queue, and wait our turn. Otherwise, call _write
59035// If we return false, then we need a drain event, so set that flag.
59036function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) {
59037 if (!isBuf) {
59038 var newChunk = decodeChunk(state, chunk, encoding);
59039 if (chunk !== newChunk) {
59040 isBuf = true;
59041 encoding = 'buffer';
59042 chunk = newChunk;
59043 }
59044 }
59045 var len = state.objectMode ? 1 : chunk.length;
59046
59047 state.length += len;
59048
59049 var ret = state.length < state.highWaterMark;
59050 // we must ensure that previous needDrain will not be reset to false.
59051 if (!ret) state.needDrain = true;
59052
59053 if (state.writing || state.corked) {
59054 var last = state.lastBufferedRequest;
59055 state.lastBufferedRequest = {
59056 chunk: chunk,
59057 encoding: encoding,
59058 isBuf: isBuf,
59059 callback: cb,
59060 next: null
59061 };
59062 if (last) {
59063 last.next = state.lastBufferedRequest;
59064 } else {
59065 state.bufferedRequest = state.lastBufferedRequest;
59066 }
59067 state.bufferedRequestCount += 1;
59068 } else {
59069 doWrite(stream, state, false, len, chunk, encoding, cb);
59070 }
59071
59072 return ret;
59073}
59074
59075function doWrite(stream, state, writev, len, chunk, encoding, cb) {
59076 state.writelen = len;
59077 state.writecb = cb;
59078 state.writing = true;
59079 state.sync = true;
59080 if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite);
59081 state.sync = false;
59082}
59083
59084function onwriteError(stream, state, sync, er, cb) {
59085 --state.pendingcb;
59086
59087 if (sync) {
59088 // defer the callback if we are being called synchronously
59089 // to avoid piling up things on the stack
59090 pna.nextTick(cb, er);
59091 // this can emit finish, and it will always happen
59092 // after error
59093 pna.nextTick(finishMaybe, stream, state);
59094 stream._writableState.errorEmitted = true;
59095 stream.emit('error', er);
59096 } else {
59097 // the caller expect this to happen before if
59098 // it is async
59099 cb(er);
59100 stream._writableState.errorEmitted = true;
59101 stream.emit('error', er);
59102 // this can emit finish, but finish must
59103 // always follow error
59104 finishMaybe(stream, state);
59105 }
59106}
59107
59108function onwriteStateUpdate(state) {
59109 state.writing = false;
59110 state.writecb = null;
59111 state.length -= state.writelen;
59112 state.writelen = 0;
59113}
59114
59115function onwrite(stream, er) {
59116 var state = stream._writableState;
59117 var sync = state.sync;
59118 var cb = state.writecb;
59119
59120 onwriteStateUpdate(state);
59121
59122 if (er) onwriteError(stream, state, sync, er, cb);else {
59123 // Check if we're actually ready to finish, but don't emit yet
59124 var finished = needFinish(state);
59125
59126 if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) {
59127 clearBuffer(stream, state);
59128 }
59129
59130 if (sync) {
59131 /*<replacement>*/
59132 asyncWrite(afterWrite, stream, state, finished, cb);
59133 /*</replacement>*/
59134 } else {
59135 afterWrite(stream, state, finished, cb);
59136 }
59137 }
59138}
59139
59140function afterWrite(stream, state, finished, cb) {
59141 if (!finished) onwriteDrain(stream, state);
59142 state.pendingcb--;
59143 cb();
59144 finishMaybe(stream, state);
59145}
59146
59147// Must force callback to be called on nextTick, so that we don't
59148// emit 'drain' before the write() consumer gets the 'false' return
59149// value, and has a chance to attach a 'drain' listener.
59150function onwriteDrain(stream, state) {
59151 if (state.length === 0 && state.needDrain) {
59152 state.needDrain = false;
59153 stream.emit('drain');
59154 }
59155}
59156
59157// if there's something in the buffer waiting, then process it
59158function clearBuffer(stream, state) {
59159 state.bufferProcessing = true;
59160 var entry = state.bufferedRequest;
59161
59162 if (stream._writev && entry && entry.next) {
59163 // Fast case, write everything using _writev()
59164 var l = state.bufferedRequestCount;
59165 var buffer = new Array(l);
59166 var holder = state.corkedRequestsFree;
59167 holder.entry = entry;
59168
59169 var count = 0;
59170 var allBuffers = true;
59171 while (entry) {
59172 buffer[count] = entry;
59173 if (!entry.isBuf) allBuffers = false;
59174 entry = entry.next;
59175 count += 1;
59176 }
59177 buffer.allBuffers = allBuffers;
59178
59179 doWrite(stream, state, true, state.length, buffer, '', holder.finish);
59180
59181 // doWrite is almost always async, defer these to save a bit of time
59182 // as the hot path ends with doWrite
59183 state.pendingcb++;
59184 state.lastBufferedRequest = null;
59185 if (holder.next) {
59186 state.corkedRequestsFree = holder.next;
59187 holder.next = null;
59188 } else {
59189 state.corkedRequestsFree = new CorkedRequest(state);
59190 }
59191 state.bufferedRequestCount = 0;
59192 } else {
59193 // Slow case, write chunks one-by-one
59194 while (entry) {
59195 var chunk = entry.chunk;
59196 var encoding = entry.encoding;
59197 var cb = entry.callback;
59198 var len = state.objectMode ? 1 : chunk.length;
59199
59200 doWrite(stream, state, false, len, chunk, encoding, cb);
59201 entry = entry.next;
59202 state.bufferedRequestCount--;
59203 // if we didn't call the onwrite immediately, then
59204 // it means that we need to wait until it does.
59205 // also, that means that the chunk and cb are currently
59206 // being processed, so move the buffer counter past them.
59207 if (state.writing) {
59208 break;
59209 }
59210 }
59211
59212 if (entry === null) state.lastBufferedRequest = null;
59213 }
59214
59215 state.bufferedRequest = entry;
59216 state.bufferProcessing = false;
59217}
59218
59219Writable.prototype._write = function (chunk, encoding, cb) {
59220 cb(new Error('_write() is not implemented'));
59221};
59222
59223Writable.prototype._writev = null;
59224
59225Writable.prototype.end = function (chunk, encoding, cb) {
59226 var state = this._writableState;
59227
59228 if (typeof chunk === 'function') {
59229 cb = chunk;
59230 chunk = null;
59231 encoding = null;
59232 } else if (typeof encoding === 'function') {
59233 cb = encoding;
59234 encoding = null;
59235 }
59236
59237 if (chunk !== null && chunk !== undefined) this.write(chunk, encoding);
59238
59239 // .end() fully uncorks
59240 if (state.corked) {
59241 state.corked = 1;
59242 this.uncork();
59243 }
59244
59245 // ignore unnecessary end() calls.
59246 if (!state.ending && !state.finished) endWritable(this, state, cb);
59247};
59248
59249function needFinish(state) {
59250 return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing;
59251}
59252function callFinal(stream, state) {
59253 stream._final(function (err) {
59254 state.pendingcb--;
59255 if (err) {
59256 stream.emit('error', err);
59257 }
59258 state.prefinished = true;
59259 stream.emit('prefinish');
59260 finishMaybe(stream, state);
59261 });
59262}
59263function prefinish(stream, state) {
59264 if (!state.prefinished && !state.finalCalled) {
59265 if (typeof stream._final === 'function') {
59266 state.pendingcb++;
59267 state.finalCalled = true;
59268 pna.nextTick(callFinal, stream, state);
59269 } else {
59270 state.prefinished = true;
59271 stream.emit('prefinish');
59272 }
59273 }
59274}
59275
59276function finishMaybe(stream, state) {
59277 var need = needFinish(state);
59278 if (need) {
59279 prefinish(stream, state);
59280 if (state.pendingcb === 0) {
59281 state.finished = true;
59282 stream.emit('finish');
59283 }
59284 }
59285 return need;
59286}
59287
59288function endWritable(stream, state, cb) {
59289 state.ending = true;
59290 finishMaybe(stream, state);
59291 if (cb) {
59292 if (state.finished) pna.nextTick(cb);else stream.once('finish', cb);
59293 }
59294 state.ended = true;
59295 stream.writable = false;
59296}
59297
59298function onCorkedFinish(corkReq, state, err) {
59299 var entry = corkReq.entry;
59300 corkReq.entry = null;
59301 while (entry) {
59302 var cb = entry.callback;
59303 state.pendingcb--;
59304 cb(err);
59305 entry = entry.next;
59306 }
59307 if (state.corkedRequestsFree) {
59308 state.corkedRequestsFree.next = corkReq;
59309 } else {
59310 state.corkedRequestsFree = corkReq;
59311 }
59312}
59313
59314Object.defineProperty(Writable.prototype, 'destroyed', {
59315 get: function () {
59316 if (this._writableState === undefined) {
59317 return false;
59318 }
59319 return this._writableState.destroyed;
59320 },
59321 set: function (value) {
59322 // we ignore the value if the stream
59323 // has not been initialized yet
59324 if (!this._writableState) {
59325 return;
59326 }
59327
59328 // backward compatibility, the user is explicitly
59329 // managing destroyed
59330 this._writableState.destroyed = value;
59331 }
59332});
59333
59334Writable.prototype.destroy = destroyImpl.destroy;
59335Writable.prototype._undestroy = destroyImpl.undestroy;
59336Writable.prototype._destroy = function (err, cb) {
59337 this.end();
59338 cb(err);
59339};
59340}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},require("timers").setImmediate)
59341},{"./_stream_duplex":281,"./internal/streams/destroy":287,"./internal/streams/stream":288,"_process":265,"core-util-is":120,"inherits":210,"process-nextick-args":264,"safe-buffer":325,"timers":382,"util-deprecate":395}],286:[function(require,module,exports){
59342'use strict';
59343
59344function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
59345
59346var Buffer = require('safe-buffer').Buffer;
59347var util = require('util');
59348
59349function copyBuffer(src, target, offset) {
59350 src.copy(target, offset);
59351}
59352
59353module.exports = function () {
59354 function BufferList() {
59355 _classCallCheck(this, BufferList);
59356
59357 this.head = null;
59358 this.tail = null;
59359 this.length = 0;
59360 }
59361
59362 BufferList.prototype.push = function push(v) {
59363 var entry = { data: v, next: null };
59364 if (this.length > 0) this.tail.next = entry;else this.head = entry;
59365 this.tail = entry;
59366 ++this.length;
59367 };
59368
59369 BufferList.prototype.unshift = function unshift(v) {
59370 var entry = { data: v, next: this.head };
59371 if (this.length === 0) this.tail = entry;
59372 this.head = entry;
59373 ++this.length;
59374 };
59375
59376 BufferList.prototype.shift = function shift() {
59377 if (this.length === 0) return;
59378 var ret = this.head.data;
59379 if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next;
59380 --this.length;
59381 return ret;
59382 };
59383
59384 BufferList.prototype.clear = function clear() {
59385 this.head = this.tail = null;
59386 this.length = 0;
59387 };
59388
59389 BufferList.prototype.join = function join(s) {
59390 if (this.length === 0) return '';
59391 var p = this.head;
59392 var ret = '' + p.data;
59393 while (p = p.next) {
59394 ret += s + p.data;
59395 }return ret;
59396 };
59397
59398 BufferList.prototype.concat = function concat(n) {
59399 if (this.length === 0) return Buffer.alloc(0);
59400 if (this.length === 1) return this.head.data;
59401 var ret = Buffer.allocUnsafe(n >>> 0);
59402 var p = this.head;
59403 var i = 0;
59404 while (p) {
59405 copyBuffer(p.data, ret, i);
59406 i += p.data.length;
59407 p = p.next;
59408 }
59409 return ret;
59410 };
59411
59412 return BufferList;
59413}();
59414
59415if (util && util.inspect && util.inspect.custom) {
59416 module.exports.prototype[util.inspect.custom] = function () {
59417 var obj = util.inspect({ length: this.length });
59418 return this.constructor.name + ' ' + obj;
59419 };
59420}
59421},{"safe-buffer":325,"util":82}],287:[function(require,module,exports){
59422'use strict';
59423
59424/*<replacement>*/
59425
59426var pna = require('process-nextick-args');
59427/*</replacement>*/
59428
59429// undocumented cb() API, needed for core, not for public API
59430function destroy(err, cb) {
59431 var _this = this;
59432
59433 var readableDestroyed = this._readableState && this._readableState.destroyed;
59434 var writableDestroyed = this._writableState && this._writableState.destroyed;
59435
59436 if (readableDestroyed || writableDestroyed) {
59437 if (cb) {
59438 cb(err);
59439 } else if (err && (!this._writableState || !this._writableState.errorEmitted)) {
59440 pna.nextTick(emitErrorNT, this, err);
59441 }
59442 return this;
59443 }
59444
59445 // we set destroyed to true before firing error callbacks in order
59446 // to make it re-entrance safe in case destroy() is called within callbacks
59447
59448 if (this._readableState) {
59449 this._readableState.destroyed = true;
59450 }
59451
59452 // if this is a duplex stream mark the writable part as destroyed as well
59453 if (this._writableState) {
59454 this._writableState.destroyed = true;
59455 }
59456
59457 this._destroy(err || null, function (err) {
59458 if (!cb && err) {
59459 pna.nextTick(emitErrorNT, _this, err);
59460 if (_this._writableState) {
59461 _this._writableState.errorEmitted = true;
59462 }
59463 } else if (cb) {
59464 cb(err);
59465 }
59466 });
59467
59468 return this;
59469}
59470
59471function undestroy() {
59472 if (this._readableState) {
59473 this._readableState.destroyed = false;
59474 this._readableState.reading = false;
59475 this._readableState.ended = false;
59476 this._readableState.endEmitted = false;
59477 }
59478
59479 if (this._writableState) {
59480 this._writableState.destroyed = false;
59481 this._writableState.ended = false;
59482 this._writableState.ending = false;
59483 this._writableState.finished = false;
59484 this._writableState.errorEmitted = false;
59485 }
59486}
59487
59488function emitErrorNT(self, err) {
59489 self.emit('error', err);
59490}
59491
59492module.exports = {
59493 destroy: destroy,
59494 undestroy: undestroy
59495};
59496},{"process-nextick-args":264}],288:[function(require,module,exports){
59497module.exports = require('events').EventEmitter;
59498
59499},{"events":159}],289:[function(require,module,exports){
59500// Copyright Joyent, Inc. and other Node contributors.
59501//
59502// Permission is hereby granted, free of charge, to any person obtaining a
59503// copy of this software and associated documentation files (the
59504// "Software"), to deal in the Software without restriction, including
59505// without limitation the rights to use, copy, modify, merge, publish,
59506// distribute, sublicense, and/or sell copies of the Software, and to permit
59507// persons to whom the Software is furnished to do so, subject to the
59508// following conditions:
59509//
59510// The above copyright notice and this permission notice shall be included
59511// in all copies or substantial portions of the Software.
59512//
59513// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
59514// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
59515// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
59516// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
59517// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
59518// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
59519// USE OR OTHER DEALINGS IN THE SOFTWARE.
59520
59521'use strict';
59522
59523/*<replacement>*/
59524
59525var Buffer = require('safe-buffer').Buffer;
59526/*</replacement>*/
59527
59528var isEncoding = Buffer.isEncoding || function (encoding) {
59529 encoding = '' + encoding;
59530 switch (encoding && encoding.toLowerCase()) {
59531 case 'hex':case 'utf8':case 'utf-8':case 'ascii':case 'binary':case 'base64':case 'ucs2':case 'ucs-2':case 'utf16le':case 'utf-16le':case 'raw':
59532 return true;
59533 default:
59534 return false;
59535 }
59536};
59537
59538function _normalizeEncoding(enc) {
59539 if (!enc) return 'utf8';
59540 var retried;
59541 while (true) {
59542 switch (enc) {
59543 case 'utf8':
59544 case 'utf-8':
59545 return 'utf8';
59546 case 'ucs2':
59547 case 'ucs-2':
59548 case 'utf16le':
59549 case 'utf-16le':
59550 return 'utf16le';
59551 case 'latin1':
59552 case 'binary':
59553 return 'latin1';
59554 case 'base64':
59555 case 'ascii':
59556 case 'hex':
59557 return enc;
59558 default:
59559 if (retried) return; // undefined
59560 enc = ('' + enc).toLowerCase();
59561 retried = true;
59562 }
59563 }
59564};
59565
59566// Do not cache `Buffer.isEncoding` when checking encoding names as some
59567// modules monkey-patch it to support additional encodings
59568function normalizeEncoding(enc) {
59569 var nenc = _normalizeEncoding(enc);
59570 if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc);
59571 return nenc || enc;
59572}
59573
59574// StringDecoder provides an interface for efficiently splitting a series of
59575// buffers into a series of JS strings without breaking apart multi-byte
59576// characters.
59577exports.StringDecoder = StringDecoder;
59578function StringDecoder(encoding) {
59579 this.encoding = normalizeEncoding(encoding);
59580 var nb;
59581 switch (this.encoding) {
59582 case 'utf16le':
59583 this.text = utf16Text;
59584 this.end = utf16End;
59585 nb = 4;
59586 break;
59587 case 'utf8':
59588 this.fillLast = utf8FillLast;
59589 nb = 4;
59590 break;
59591 case 'base64':
59592 this.text = base64Text;
59593 this.end = base64End;
59594 nb = 3;
59595 break;
59596 default:
59597 this.write = simpleWrite;
59598 this.end = simpleEnd;
59599 return;
59600 }
59601 this.lastNeed = 0;
59602 this.lastTotal = 0;
59603 this.lastChar = Buffer.allocUnsafe(nb);
59604}
59605
59606StringDecoder.prototype.write = function (buf) {
59607 if (buf.length === 0) return '';
59608 var r;
59609 var i;
59610 if (this.lastNeed) {
59611 r = this.fillLast(buf);
59612 if (r === undefined) return '';
59613 i = this.lastNeed;
59614 this.lastNeed = 0;
59615 } else {
59616 i = 0;
59617 }
59618 if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i);
59619 return r || '';
59620};
59621
59622StringDecoder.prototype.end = utf8End;
59623
59624// Returns only complete characters in a Buffer
59625StringDecoder.prototype.text = utf8Text;
59626
59627// Attempts to complete a partial non-UTF-8 character using bytes from a Buffer
59628StringDecoder.prototype.fillLast = function (buf) {
59629 if (this.lastNeed <= buf.length) {
59630 buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed);
59631 return this.lastChar.toString(this.encoding, 0, this.lastTotal);
59632 }
59633 buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length);
59634 this.lastNeed -= buf.length;
59635};
59636
59637// Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a
59638// continuation byte. If an invalid byte is detected, -2 is returned.
59639function utf8CheckByte(byte) {
59640 if (byte <= 0x7F) return 0;else if (byte >> 5 === 0x06) return 2;else if (byte >> 4 === 0x0E) return 3;else if (byte >> 3 === 0x1E) return 4;
59641 return byte >> 6 === 0x02 ? -1 : -2;
59642}
59643
59644// Checks at most 3 bytes at the end of a Buffer in order to detect an
59645// incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4)
59646// needed to complete the UTF-8 character (if applicable) are returned.
59647function utf8CheckIncomplete(self, buf, i) {
59648 var j = buf.length - 1;
59649 if (j < i) return 0;
59650 var nb = utf8CheckByte(buf[j]);
59651 if (nb >= 0) {
59652 if (nb > 0) self.lastNeed = nb - 1;
59653 return nb;
59654 }
59655 if (--j < i || nb === -2) return 0;
59656 nb = utf8CheckByte(buf[j]);
59657 if (nb >= 0) {
59658 if (nb > 0) self.lastNeed = nb - 2;
59659 return nb;
59660 }
59661 if (--j < i || nb === -2) return 0;
59662 nb = utf8CheckByte(buf[j]);
59663 if (nb >= 0) {
59664 if (nb > 0) {
59665 if (nb === 2) nb = 0;else self.lastNeed = nb - 3;
59666 }
59667 return nb;
59668 }
59669 return 0;
59670}
59671
59672// Validates as many continuation bytes for a multi-byte UTF-8 character as
59673// needed or are available. If we see a non-continuation byte where we expect
59674// one, we "replace" the validated continuation bytes we've seen so far with
59675// a single UTF-8 replacement character ('\ufffd'), to match v8's UTF-8 decoding
59676// behavior. The continuation byte check is included three times in the case
59677// where all of the continuation bytes for a character exist in the same buffer.
59678// It is also done this way as a slight performance increase instead of using a
59679// loop.
59680function utf8CheckExtraBytes(self, buf, p) {
59681 if ((buf[0] & 0xC0) !== 0x80) {
59682 self.lastNeed = 0;
59683 return '\ufffd';
59684 }
59685 if (self.lastNeed > 1 && buf.length > 1) {
59686 if ((buf[1] & 0xC0) !== 0x80) {
59687 self.lastNeed = 1;
59688 return '\ufffd';
59689 }
59690 if (self.lastNeed > 2 && buf.length > 2) {
59691 if ((buf[2] & 0xC0) !== 0x80) {
59692 self.lastNeed = 2;
59693 return '\ufffd';
59694 }
59695 }
59696 }
59697}
59698
59699// Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer.
59700function utf8FillLast(buf) {
59701 var p = this.lastTotal - this.lastNeed;
59702 var r = utf8CheckExtraBytes(this, buf, p);
59703 if (r !== undefined) return r;
59704 if (this.lastNeed <= buf.length) {
59705 buf.copy(this.lastChar, p, 0, this.lastNeed);
59706 return this.lastChar.toString(this.encoding, 0, this.lastTotal);
59707 }
59708 buf.copy(this.lastChar, p, 0, buf.length);
59709 this.lastNeed -= buf.length;
59710}
59711
59712// Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a
59713// partial character, the character's bytes are buffered until the required
59714// number of bytes are available.
59715function utf8Text(buf, i) {
59716 var total = utf8CheckIncomplete(this, buf, i);
59717 if (!this.lastNeed) return buf.toString('utf8', i);
59718 this.lastTotal = total;
59719 var end = buf.length - (total - this.lastNeed);
59720 buf.copy(this.lastChar, 0, end);
59721 return buf.toString('utf8', i, end);
59722}
59723
59724// For UTF-8, a replacement character is added when ending on a partial
59725// character.
59726function utf8End(buf) {
59727 var r = buf && buf.length ? this.write(buf) : '';
59728 if (this.lastNeed) return r + '\ufffd';
59729 return r;
59730}
59731
59732// UTF-16LE typically needs two bytes per character, but even if we have an even
59733// number of bytes available, we need to check if we end on a leading/high
59734// surrogate. In that case, we need to wait for the next two bytes in order to
59735// decode the last character properly.
59736function utf16Text(buf, i) {
59737 if ((buf.length - i) % 2 === 0) {
59738 var r = buf.toString('utf16le', i);
59739 if (r) {
59740 var c = r.charCodeAt(r.length - 1);
59741 if (c >= 0xD800 && c <= 0xDBFF) {
59742 this.lastNeed = 2;
59743 this.lastTotal = 4;
59744 this.lastChar[0] = buf[buf.length - 2];
59745 this.lastChar[1] = buf[buf.length - 1];
59746 return r.slice(0, -1);
59747 }
59748 }
59749 return r;
59750 }
59751 this.lastNeed = 1;
59752 this.lastTotal = 2;
59753 this.lastChar[0] = buf[buf.length - 1];
59754 return buf.toString('utf16le', i, buf.length - 1);
59755}
59756
59757// For UTF-16LE we do not explicitly append special replacement characters if we
59758// end on a partial character, we simply let v8 handle that.
59759function utf16End(buf) {
59760 var r = buf && buf.length ? this.write(buf) : '';
59761 if (this.lastNeed) {
59762 var end = this.lastTotal - this.lastNeed;
59763 return r + this.lastChar.toString('utf16le', 0, end);
59764 }
59765 return r;
59766}
59767
59768function base64Text(buf, i) {
59769 var n = (buf.length - i) % 3;
59770 if (n === 0) return buf.toString('base64', i);
59771 this.lastNeed = 3 - n;
59772 this.lastTotal = 3;
59773 if (n === 1) {
59774 this.lastChar[0] = buf[buf.length - 1];
59775 } else {
59776 this.lastChar[0] = buf[buf.length - 2];
59777 this.lastChar[1] = buf[buf.length - 1];
59778 }
59779 return buf.toString('base64', i, buf.length - n);
59780}
59781
59782function base64End(buf) {
59783 var r = buf && buf.length ? this.write(buf) : '';
59784 if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed);
59785 return r;
59786}
59787
59788// Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex)
59789function simpleWrite(buf) {
59790 return buf.toString(this.encoding);
59791}
59792
59793function simpleEnd(buf) {
59794 return buf && buf.length ? this.write(buf) : '';
59795}
59796},{"safe-buffer":325}],290:[function(require,module,exports){
59797module.exports = require('./readable').PassThrough
59798
59799},{"./readable":291}],291:[function(require,module,exports){
59800exports = module.exports = require('./lib/_stream_readable.js');
59801exports.Stream = exports;
59802exports.Readable = exports;
59803exports.Writable = require('./lib/_stream_writable.js');
59804exports.Duplex = require('./lib/_stream_duplex.js');
59805exports.Transform = require('./lib/_stream_transform.js');
59806exports.PassThrough = require('./lib/_stream_passthrough.js');
59807
59808},{"./lib/_stream_duplex.js":281,"./lib/_stream_passthrough.js":282,"./lib/_stream_readable.js":283,"./lib/_stream_transform.js":284,"./lib/_stream_writable.js":285}],292:[function(require,module,exports){
59809module.exports = require('./readable').Transform
59810
59811},{"./readable":291}],293:[function(require,module,exports){
59812module.exports = require('./lib/_stream_writable.js');
59813
59814},{"./lib/_stream_writable.js":285}],294:[function(require,module,exports){
59815/**
59816 * Copyright (c) 2014-present, Facebook, Inc.
59817 *
59818 * This source code is licensed under the MIT license found in the
59819 * LICENSE file in the root directory of this source tree.
59820 */
59821
59822var runtime = (function (exports) {
59823 "use strict";
59824
59825 var Op = Object.prototype;
59826 var hasOwn = Op.hasOwnProperty;
59827 var undefined; // More compressible than void 0.
59828 var $Symbol = typeof Symbol === "function" ? Symbol : {};
59829 var iteratorSymbol = $Symbol.iterator || "@@iterator";
59830 var asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator";
59831 var toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag";
59832
59833 function wrap(innerFn, outerFn, self, tryLocsList) {
59834 // If outerFn provided and outerFn.prototype is a Generator, then outerFn.prototype instanceof Generator.
59835 var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator;
59836 var generator = Object.create(protoGenerator.prototype);
59837 var context = new Context(tryLocsList || []);
59838
59839 // The ._invoke method unifies the implementations of the .next,
59840 // .throw, and .return methods.
59841 generator._invoke = makeInvokeMethod(innerFn, self, context);
59842
59843 return generator;
59844 }
59845 exports.wrap = wrap;
59846
59847 // Try/catch helper to minimize deoptimizations. Returns a completion
59848 // record like context.tryEntries[i].completion. This interface could
59849 // have been (and was previously) designed to take a closure to be
59850 // invoked without arguments, but in all the cases we care about we
59851 // already have an existing method we want to call, so there's no need
59852 // to create a new function object. We can even get away with assuming
59853 // the method takes exactly one argument, since that happens to be true
59854 // in every case, so we don't have to touch the arguments object. The
59855 // only additional allocation required is the completion record, which
59856 // has a stable shape and so hopefully should be cheap to allocate.
59857 function tryCatch(fn, obj, arg) {
59858 try {
59859 return { type: "normal", arg: fn.call(obj, arg) };
59860 } catch (err) {
59861 return { type: "throw", arg: err };
59862 }
59863 }
59864
59865 var GenStateSuspendedStart = "suspendedStart";
59866 var GenStateSuspendedYield = "suspendedYield";
59867 var GenStateExecuting = "executing";
59868 var GenStateCompleted = "completed";
59869
59870 // Returning this object from the innerFn has the same effect as
59871 // breaking out of the dispatch switch statement.
59872 var ContinueSentinel = {};
59873
59874 // Dummy constructor functions that we use as the .constructor and
59875 // .constructor.prototype properties for functions that return Generator
59876 // objects. For full spec compliance, you may wish to configure your
59877 // minifier not to mangle the names of these two functions.
59878 function Generator() {}
59879 function GeneratorFunction() {}
59880 function GeneratorFunctionPrototype() {}
59881
59882 // This is a polyfill for %IteratorPrototype% for environments that
59883 // don't natively support it.
59884 var IteratorPrototype = {};
59885 IteratorPrototype[iteratorSymbol] = function () {
59886 return this;
59887 };
59888
59889 var getProto = Object.getPrototypeOf;
59890 var NativeIteratorPrototype = getProto && getProto(getProto(values([])));
59891 if (NativeIteratorPrototype &&
59892 NativeIteratorPrototype !== Op &&
59893 hasOwn.call(NativeIteratorPrototype, iteratorSymbol)) {
59894 // This environment has a native %IteratorPrototype%; use it instead
59895 // of the polyfill.
59896 IteratorPrototype = NativeIteratorPrototype;
59897 }
59898
59899 var Gp = GeneratorFunctionPrototype.prototype =
59900 Generator.prototype = Object.create(IteratorPrototype);
59901 GeneratorFunction.prototype = Gp.constructor = GeneratorFunctionPrototype;
59902 GeneratorFunctionPrototype.constructor = GeneratorFunction;
59903 GeneratorFunctionPrototype[toStringTagSymbol] =
59904 GeneratorFunction.displayName = "GeneratorFunction";
59905
59906 // Helper for defining the .next, .throw, and .return methods of the
59907 // Iterator interface in terms of a single ._invoke method.
59908 function defineIteratorMethods(prototype) {
59909 ["next", "throw", "return"].forEach(function(method) {
59910 prototype[method] = function(arg) {
59911 return this._invoke(method, arg);
59912 };
59913 });
59914 }
59915
59916 exports.isGeneratorFunction = function(genFun) {
59917 var ctor = typeof genFun === "function" && genFun.constructor;
59918 return ctor
59919 ? ctor === GeneratorFunction ||
59920 // For the native GeneratorFunction constructor, the best we can
59921 // do is to check its .name property.
59922 (ctor.displayName || ctor.name) === "GeneratorFunction"
59923 : false;
59924 };
59925
59926 exports.mark = function(genFun) {
59927 if (Object.setPrototypeOf) {
59928 Object.setPrototypeOf(genFun, GeneratorFunctionPrototype);
59929 } else {
59930 genFun.__proto__ = GeneratorFunctionPrototype;
59931 if (!(toStringTagSymbol in genFun)) {
59932 genFun[toStringTagSymbol] = "GeneratorFunction";
59933 }
59934 }
59935 genFun.prototype = Object.create(Gp);
59936 return genFun;
59937 };
59938
59939 // Within the body of any async function, `await x` is transformed to
59940 // `yield regeneratorRuntime.awrap(x)`, so that the runtime can test
59941 // `hasOwn.call(value, "__await")` to determine if the yielded value is
59942 // meant to be awaited.
59943 exports.awrap = function(arg) {
59944 return { __await: arg };
59945 };
59946
59947 function AsyncIterator(generator) {
59948 function invoke(method, arg, resolve, reject) {
59949 var record = tryCatch(generator[method], generator, arg);
59950 if (record.type === "throw") {
59951 reject(record.arg);
59952 } else {
59953 var result = record.arg;
59954 var value = result.value;
59955 if (value &&
59956 typeof value === "object" &&
59957 hasOwn.call(value, "__await")) {
59958 return Promise.resolve(value.__await).then(function(value) {
59959 invoke("next", value, resolve, reject);
59960 }, function(err) {
59961 invoke("throw", err, resolve, reject);
59962 });
59963 }
59964
59965 return Promise.resolve(value).then(function(unwrapped) {
59966 // When a yielded Promise is resolved, its final value becomes
59967 // the .value of the Promise<{value,done}> result for the
59968 // current iteration.
59969 result.value = unwrapped;
59970 resolve(result);
59971 }, function(error) {
59972 // If a rejected Promise was yielded, throw the rejection back
59973 // into the async generator function so it can be handled there.
59974 return invoke("throw", error, resolve, reject);
59975 });
59976 }
59977 }
59978
59979 var previousPromise;
59980
59981 function enqueue(method, arg) {
59982 function callInvokeWithMethodAndArg() {
59983 return new Promise(function(resolve, reject) {
59984 invoke(method, arg, resolve, reject);
59985 });
59986 }
59987
59988 return previousPromise =
59989 // If enqueue has been called before, then we want to wait until
59990 // all previous Promises have been resolved before calling invoke,
59991 // so that results are always delivered in the correct order. If
59992 // enqueue has not been called before, then it is important to
59993 // call invoke immediately, without waiting on a callback to fire,
59994 // so that the async generator function has the opportunity to do
59995 // any necessary setup in a predictable way. This predictability
59996 // is why the Promise constructor synchronously invokes its
59997 // executor callback, and why async functions synchronously
59998 // execute code before the first await. Since we implement simple
59999 // async functions in terms of async generators, it is especially
60000 // important to get this right, even though it requires care.
60001 previousPromise ? previousPromise.then(
60002 callInvokeWithMethodAndArg,
60003 // Avoid propagating failures to Promises returned by later
60004 // invocations of the iterator.
60005 callInvokeWithMethodAndArg
60006 ) : callInvokeWithMethodAndArg();
60007 }
60008
60009 // Define the unified helper method that is used to implement .next,
60010 // .throw, and .return (see defineIteratorMethods).
60011 this._invoke = enqueue;
60012 }
60013
60014 defineIteratorMethods(AsyncIterator.prototype);
60015 AsyncIterator.prototype[asyncIteratorSymbol] = function () {
60016 return this;
60017 };
60018 exports.AsyncIterator = AsyncIterator;
60019
60020 // Note that simple async functions are implemented on top of
60021 // AsyncIterator objects; they just return a Promise for the value of
60022 // the final result produced by the iterator.
60023 exports.async = function(innerFn, outerFn, self, tryLocsList) {
60024 var iter = new AsyncIterator(
60025 wrap(innerFn, outerFn, self, tryLocsList)
60026 );
60027
60028 return exports.isGeneratorFunction(outerFn)
60029 ? iter // If outerFn is a generator, return the full iterator.
60030 : iter.next().then(function(result) {
60031 return result.done ? result.value : iter.next();
60032 });
60033 };
60034
60035 function makeInvokeMethod(innerFn, self, context) {
60036 var state = GenStateSuspendedStart;
60037
60038 return function invoke(method, arg) {
60039 if (state === GenStateExecuting) {
60040 throw new Error("Generator is already running");
60041 }
60042
60043 if (state === GenStateCompleted) {
60044 if (method === "throw") {
60045 throw arg;
60046 }
60047
60048 // Be forgiving, per 25.3.3.3.3 of the spec:
60049 // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-generatorresume
60050 return doneResult();
60051 }
60052
60053 context.method = method;
60054 context.arg = arg;
60055
60056 while (true) {
60057 var delegate = context.delegate;
60058 if (delegate) {
60059 var delegateResult = maybeInvokeDelegate(delegate, context);
60060 if (delegateResult) {
60061 if (delegateResult === ContinueSentinel) continue;
60062 return delegateResult;
60063 }
60064 }
60065
60066 if (context.method === "next") {
60067 // Setting context._sent for legacy support of Babel's
60068 // function.sent implementation.
60069 context.sent = context._sent = context.arg;
60070
60071 } else if (context.method === "throw") {
60072 if (state === GenStateSuspendedStart) {
60073 state = GenStateCompleted;
60074 throw context.arg;
60075 }
60076
60077 context.dispatchException(context.arg);
60078
60079 } else if (context.method === "return") {
60080 context.abrupt("return", context.arg);
60081 }
60082
60083 state = GenStateExecuting;
60084
60085 var record = tryCatch(innerFn, self, context);
60086 if (record.type === "normal") {
60087 // If an exception is thrown from innerFn, we leave state ===
60088 // GenStateExecuting and loop back for another invocation.
60089 state = context.done
60090 ? GenStateCompleted
60091 : GenStateSuspendedYield;
60092
60093 if (record.arg === ContinueSentinel) {
60094 continue;
60095 }
60096
60097 return {
60098 value: record.arg,
60099 done: context.done
60100 };
60101
60102 } else if (record.type === "throw") {
60103 state = GenStateCompleted;
60104 // Dispatch the exception by looping back around to the
60105 // context.dispatchException(context.arg) call above.
60106 context.method = "throw";
60107 context.arg = record.arg;
60108 }
60109 }
60110 };
60111 }
60112
60113 // Call delegate.iterator[context.method](context.arg) and handle the
60114 // result, either by returning a { value, done } result from the
60115 // delegate iterator, or by modifying context.method and context.arg,
60116 // setting context.delegate to null, and returning the ContinueSentinel.
60117 function maybeInvokeDelegate(delegate, context) {
60118 var method = delegate.iterator[context.method];
60119 if (method === undefined) {
60120 // A .throw or .return when the delegate iterator has no .throw
60121 // method always terminates the yield* loop.
60122 context.delegate = null;
60123
60124 if (context.method === "throw") {
60125 // Note: ["return"] must be used for ES3 parsing compatibility.
60126 if (delegate.iterator["return"]) {
60127 // If the delegate iterator has a return method, give it a
60128 // chance to clean up.
60129 context.method = "return";
60130 context.arg = undefined;
60131 maybeInvokeDelegate(delegate, context);
60132
60133 if (context.method === "throw") {
60134 // If maybeInvokeDelegate(context) changed context.method from
60135 // "return" to "throw", let that override the TypeError below.
60136 return ContinueSentinel;
60137 }
60138 }
60139
60140 context.method = "throw";
60141 context.arg = new TypeError(
60142 "The iterator does not provide a 'throw' method");
60143 }
60144
60145 return ContinueSentinel;
60146 }
60147
60148 var record = tryCatch(method, delegate.iterator, context.arg);
60149
60150 if (record.type === "throw") {
60151 context.method = "throw";
60152 context.arg = record.arg;
60153 context.delegate = null;
60154 return ContinueSentinel;
60155 }
60156
60157 var info = record.arg;
60158
60159 if (! info) {
60160 context.method = "throw";
60161 context.arg = new TypeError("iterator result is not an object");
60162 context.delegate = null;
60163 return ContinueSentinel;
60164 }
60165
60166 if (info.done) {
60167 // Assign the result of the finished delegate to the temporary
60168 // variable specified by delegate.resultName (see delegateYield).
60169 context[delegate.resultName] = info.value;
60170
60171 // Resume execution at the desired location (see delegateYield).
60172 context.next = delegate.nextLoc;
60173
60174 // If context.method was "throw" but the delegate handled the
60175 // exception, let the outer generator proceed normally. If
60176 // context.method was "next", forget context.arg since it has been
60177 // "consumed" by the delegate iterator. If context.method was
60178 // "return", allow the original .return call to continue in the
60179 // outer generator.
60180 if (context.method !== "return") {
60181 context.method = "next";
60182 context.arg = undefined;
60183 }
60184
60185 } else {
60186 // Re-yield the result returned by the delegate method.
60187 return info;
60188 }
60189
60190 // The delegate iterator is finished, so forget it and continue with
60191 // the outer generator.
60192 context.delegate = null;
60193 return ContinueSentinel;
60194 }
60195
60196 // Define Generator.prototype.{next,throw,return} in terms of the
60197 // unified ._invoke helper method.
60198 defineIteratorMethods(Gp);
60199
60200 Gp[toStringTagSymbol] = "Generator";
60201
60202 // A Generator should always return itself as the iterator object when the
60203 // @@iterator function is called on it. Some browsers' implementations of the
60204 // iterator prototype chain incorrectly implement this, causing the Generator
60205 // object to not be returned from this call. This ensures that doesn't happen.
60206 // See https://github.com/facebook/regenerator/issues/274 for more details.
60207 Gp[iteratorSymbol] = function() {
60208 return this;
60209 };
60210
60211 Gp.toString = function() {
60212 return "[object Generator]";
60213 };
60214
60215 function pushTryEntry(locs) {
60216 var entry = { tryLoc: locs[0] };
60217
60218 if (1 in locs) {
60219 entry.catchLoc = locs[1];
60220 }
60221
60222 if (2 in locs) {
60223 entry.finallyLoc = locs[2];
60224 entry.afterLoc = locs[3];
60225 }
60226
60227 this.tryEntries.push(entry);
60228 }
60229
60230 function resetTryEntry(entry) {
60231 var record = entry.completion || {};
60232 record.type = "normal";
60233 delete record.arg;
60234 entry.completion = record;
60235 }
60236
60237 function Context(tryLocsList) {
60238 // The root entry object (effectively a try statement without a catch
60239 // or a finally block) gives us a place to store values thrown from
60240 // locations where there is no enclosing try statement.
60241 this.tryEntries = [{ tryLoc: "root" }];
60242 tryLocsList.forEach(pushTryEntry, this);
60243 this.reset(true);
60244 }
60245
60246 exports.keys = function(object) {
60247 var keys = [];
60248 for (var key in object) {
60249 keys.push(key);
60250 }
60251 keys.reverse();
60252
60253 // Rather than returning an object with a next method, we keep
60254 // things simple and return the next function itself.
60255 return function next() {
60256 while (keys.length) {
60257 var key = keys.pop();
60258 if (key in object) {
60259 next.value = key;
60260 next.done = false;
60261 return next;
60262 }
60263 }
60264
60265 // To avoid creating an additional object, we just hang the .value
60266 // and .done properties off the next function object itself. This
60267 // also ensures that the minifier will not anonymize the function.
60268 next.done = true;
60269 return next;
60270 };
60271 };
60272
60273 function values(iterable) {
60274 if (iterable) {
60275 var iteratorMethod = iterable[iteratorSymbol];
60276 if (iteratorMethod) {
60277 return iteratorMethod.call(iterable);
60278 }
60279
60280 if (typeof iterable.next === "function") {
60281 return iterable;
60282 }
60283
60284 if (!isNaN(iterable.length)) {
60285 var i = -1, next = function next() {
60286 while (++i < iterable.length) {
60287 if (hasOwn.call(iterable, i)) {
60288 next.value = iterable[i];
60289 next.done = false;
60290 return next;
60291 }
60292 }
60293
60294 next.value = undefined;
60295 next.done = true;
60296
60297 return next;
60298 };
60299
60300 return next.next = next;
60301 }
60302 }
60303
60304 // Return an iterator with no values.
60305 return { next: doneResult };
60306 }
60307 exports.values = values;
60308
60309 function doneResult() {
60310 return { value: undefined, done: true };
60311 }
60312
60313 Context.prototype = {
60314 constructor: Context,
60315
60316 reset: function(skipTempReset) {
60317 this.prev = 0;
60318 this.next = 0;
60319 // Resetting context._sent for legacy support of Babel's
60320 // function.sent implementation.
60321 this.sent = this._sent = undefined;
60322 this.done = false;
60323 this.delegate = null;
60324
60325 this.method = "next";
60326 this.arg = undefined;
60327
60328 this.tryEntries.forEach(resetTryEntry);
60329
60330 if (!skipTempReset) {
60331 for (var name in this) {
60332 // Not sure about the optimal order of these conditions:
60333 if (name.charAt(0) === "t" &&
60334 hasOwn.call(this, name) &&
60335 !isNaN(+name.slice(1))) {
60336 this[name] = undefined;
60337 }
60338 }
60339 }
60340 },
60341
60342 stop: function() {
60343 this.done = true;
60344
60345 var rootEntry = this.tryEntries[0];
60346 var rootRecord = rootEntry.completion;
60347 if (rootRecord.type === "throw") {
60348 throw rootRecord.arg;
60349 }
60350
60351 return this.rval;
60352 },
60353
60354 dispatchException: function(exception) {
60355 if (this.done) {
60356 throw exception;
60357 }
60358
60359 var context = this;
60360 function handle(loc, caught) {
60361 record.type = "throw";
60362 record.arg = exception;
60363 context.next = loc;
60364
60365 if (caught) {
60366 // If the dispatched exception was caught by a catch block,
60367 // then let that catch block handle the exception normally.
60368 context.method = "next";
60369 context.arg = undefined;
60370 }
60371
60372 return !! caught;
60373 }
60374
60375 for (var i = this.tryEntries.length - 1; i >= 0; --i) {
60376 var entry = this.tryEntries[i];
60377 var record = entry.completion;
60378
60379 if (entry.tryLoc === "root") {
60380 // Exception thrown outside of any try block that could handle
60381 // it, so set the completion value of the entire function to
60382 // throw the exception.
60383 return handle("end");
60384 }
60385
60386 if (entry.tryLoc <= this.prev) {
60387 var hasCatch = hasOwn.call(entry, "catchLoc");
60388 var hasFinally = hasOwn.call(entry, "finallyLoc");
60389
60390 if (hasCatch && hasFinally) {
60391 if (this.prev < entry.catchLoc) {
60392 return handle(entry.catchLoc, true);
60393 } else if (this.prev < entry.finallyLoc) {
60394 return handle(entry.finallyLoc);
60395 }
60396
60397 } else if (hasCatch) {
60398 if (this.prev < entry.catchLoc) {
60399 return handle(entry.catchLoc, true);
60400 }
60401
60402 } else if (hasFinally) {
60403 if (this.prev < entry.finallyLoc) {
60404 return handle(entry.finallyLoc);
60405 }
60406
60407 } else {
60408 throw new Error("try statement without catch or finally");
60409 }
60410 }
60411 }
60412 },
60413
60414 abrupt: function(type, arg) {
60415 for (var i = this.tryEntries.length - 1; i >= 0; --i) {
60416 var entry = this.tryEntries[i];
60417 if (entry.tryLoc <= this.prev &&
60418 hasOwn.call(entry, "finallyLoc") &&
60419 this.prev < entry.finallyLoc) {
60420 var finallyEntry = entry;
60421 break;
60422 }
60423 }
60424
60425 if (finallyEntry &&
60426 (type === "break" ||
60427 type === "continue") &&
60428 finallyEntry.tryLoc <= arg &&
60429 arg <= finallyEntry.finallyLoc) {
60430 // Ignore the finally entry if control is not jumping to a
60431 // location outside the try/catch block.
60432 finallyEntry = null;
60433 }
60434
60435 var record = finallyEntry ? finallyEntry.completion : {};
60436 record.type = type;
60437 record.arg = arg;
60438
60439 if (finallyEntry) {
60440 this.method = "next";
60441 this.next = finallyEntry.finallyLoc;
60442 return ContinueSentinel;
60443 }
60444
60445 return this.complete(record);
60446 },
60447
60448 complete: function(record, afterLoc) {
60449 if (record.type === "throw") {
60450 throw record.arg;
60451 }
60452
60453 if (record.type === "break" ||
60454 record.type === "continue") {
60455 this.next = record.arg;
60456 } else if (record.type === "return") {
60457 this.rval = this.arg = record.arg;
60458 this.method = "return";
60459 this.next = "end";
60460 } else if (record.type === "normal" && afterLoc) {
60461 this.next = afterLoc;
60462 }
60463
60464 return ContinueSentinel;
60465 },
60466
60467 finish: function(finallyLoc) {
60468 for (var i = this.tryEntries.length - 1; i >= 0; --i) {
60469 var entry = this.tryEntries[i];
60470 if (entry.finallyLoc === finallyLoc) {
60471 this.complete(entry.completion, entry.afterLoc);
60472 resetTryEntry(entry);
60473 return ContinueSentinel;
60474 }
60475 }
60476 },
60477
60478 "catch": function(tryLoc) {
60479 for (var i = this.tryEntries.length - 1; i >= 0; --i) {
60480 var entry = this.tryEntries[i];
60481 if (entry.tryLoc === tryLoc) {
60482 var record = entry.completion;
60483 if (record.type === "throw") {
60484 var thrown = record.arg;
60485 resetTryEntry(entry);
60486 }
60487 return thrown;
60488 }
60489 }
60490
60491 // The context.catch method must only be called with a location
60492 // argument that corresponds to a known catch block.
60493 throw new Error("illegal catch attempt");
60494 },
60495
60496 delegateYield: function(iterable, resultName, nextLoc) {
60497 this.delegate = {
60498 iterator: values(iterable),
60499 resultName: resultName,
60500 nextLoc: nextLoc
60501 };
60502
60503 if (this.method === "next") {
60504 // Deliberately forget the last sent value so that we don't
60505 // accidentally pass it on to the delegate.
60506 this.arg = undefined;
60507 }
60508
60509 return ContinueSentinel;
60510 }
60511 };
60512
60513 // Regardless of whether this script is executing as a CommonJS module
60514 // or not, return the runtime object so that we can declare the variable
60515 // regeneratorRuntime in the outer scope, which allows this module to be
60516 // injected easily by `bin/regenerator --include-runtime script.js`.
60517 return exports;
60518
60519}(
60520 // If this script is executing as a CommonJS module, use module.exports
60521 // as the regeneratorRuntime namespace. Otherwise create a new empty
60522 // object. Either way, the resulting object will be used to initialize
60523 // the regeneratorRuntime variable at the top of this file.
60524 typeof module === "object" ? module.exports : {}
60525));
60526
60527try {
60528 regeneratorRuntime = runtime;
60529} catch (accidentalStrictMode) {
60530 // This module should not be running in strict mode, so the above
60531 // assignment should always work unless something is misconfigured. Just
60532 // in case runtime.js accidentally runs in strict mode, we can escape
60533 // strict mode using a global Function call. This could conceivably fail
60534 // if a Content Security Policy forbids using Function, but in that case
60535 // the proper solution is to fix the accidental strict mode problem. If
60536 // you've misconfigured your bundler to force strict mode and applied a
60537 // CSP to forbid Function, and you're not willing to fix either of those
60538 // problems, please detail your unique predicament in a GitHub issue.
60539 Function("r", "regeneratorRuntime = r")(runtime);
60540}
60541
60542},{}],295:[function(require,module,exports){
60543'use strict';
60544
60545var core = require('../'),
60546 isArray = require('lodash/isArray'),
60547 isFunction = require('lodash/isFunction'),
60548 isObjectLike = require('lodash/isObjectLike');
60549
60550
60551module.exports = function (options) {
60552
60553 var errorText = 'Please verify options'; // For better minification because this string is repeating
60554
60555 if (!isObjectLike(options)) {
60556 throw new TypeError(errorText);
60557 }
60558
60559 if (!isFunction(options.request)) {
60560 throw new TypeError(errorText + '.request');
60561 }
60562
60563 if (!isArray(options.expose) || options.expose.length === 0) {
60564 throw new TypeError(errorText + '.expose');
60565 }
60566
60567
60568 var plumbing = core({
60569 PromiseImpl: options.PromiseImpl,
60570 constructorMixin: options.constructorMixin
60571 });
60572
60573
60574 // Intercepting Request's init method
60575
60576 var originalInit = options.request.Request.prototype.init;
60577
60578 options.request.Request.prototype.init = function RP$initInterceptor(requestOptions) {
60579
60580 // Init may be called again - currently in case of redirects
60581 if (isObjectLike(requestOptions) && !this._callback && !this._rp_promise) {
60582
60583 plumbing.init.call(this, requestOptions);
60584
60585 }
60586
60587 return originalInit.apply(this, arguments);
60588
60589 };
60590
60591
60592 // Exposing the Promise capabilities
60593
60594 var thenExposed = false;
60595 for ( var i = 0; i < options.expose.length; i+=1 ) {
60596
60597 var method = options.expose[i];
60598
60599 plumbing[ method === 'promise' ? 'exposePromise' : 'exposePromiseMethod' ](
60600 options.request.Request.prototype,
60601 null,
60602 '_rp_promise',
60603 method
60604 );
60605
60606 if (method === 'then') {
60607 thenExposed = true;
60608 }
60609
60610 }
60611
60612 if (!thenExposed) {
60613 throw new Error('Please expose "then"');
60614 }
60615
60616};
60617
60618},{"../":297,"lodash/isArray":226,"lodash/isFunction":227,"lodash/isObjectLike":229}],296:[function(require,module,exports){
60619'use strict';
60620
60621
60622function RequestError(cause, options, response) {
60623
60624 this.name = 'RequestError';
60625 this.message = String(cause);
60626 this.cause = cause;
60627 this.error = cause; // legacy attribute
60628 this.options = options;
60629 this.response = response;
60630
60631 if (Error.captureStackTrace) { // required for non-V8 environments
60632 Error.captureStackTrace(this);
60633 }
60634
60635}
60636RequestError.prototype = Object.create(Error.prototype);
60637RequestError.prototype.constructor = RequestError;
60638
60639
60640function StatusCodeError(statusCode, body, options, response) {
60641
60642 this.name = 'StatusCodeError';
60643 this.statusCode = statusCode;
60644 this.message = statusCode + ' - ' + (JSON && JSON.stringify ? JSON.stringify(body) : body);
60645 this.error = body; // legacy attribute
60646 this.options = options;
60647 this.response = response;
60648
60649 if (Error.captureStackTrace) { // required for non-V8 environments
60650 Error.captureStackTrace(this);
60651 }
60652
60653}
60654StatusCodeError.prototype = Object.create(Error.prototype);
60655StatusCodeError.prototype.constructor = StatusCodeError;
60656
60657
60658function TransformError(cause, options, response) {
60659
60660 this.name = 'TransformError';
60661 this.message = String(cause);
60662 this.cause = cause;
60663 this.error = cause; // legacy attribute
60664 this.options = options;
60665 this.response = response;
60666
60667 if (Error.captureStackTrace) { // required for non-V8 environments
60668 Error.captureStackTrace(this);
60669 }
60670
60671}
60672TransformError.prototype = Object.create(Error.prototype);
60673TransformError.prototype.constructor = TransformError;
60674
60675
60676module.exports = {
60677 RequestError: RequestError,
60678 StatusCodeError: StatusCodeError,
60679 TransformError: TransformError
60680};
60681
60682},{}],297:[function(require,module,exports){
60683'use strict';
60684
60685var errors = require('./errors.js'),
60686 isFunction = require('lodash/isFunction'),
60687 isObjectLike = require('lodash/isObjectLike'),
60688 isString = require('lodash/isString'),
60689 isUndefined = require('lodash/isUndefined');
60690
60691
60692module.exports = function (options) {
60693
60694 var errorText = 'Please verify options'; // For better minification because this string is repeating
60695
60696 if (!isObjectLike(options)) {
60697 throw new TypeError(errorText);
60698 }
60699
60700 if (!isFunction(options.PromiseImpl)) {
60701 throw new TypeError(errorText + '.PromiseImpl');
60702 }
60703
60704 if (!isUndefined(options.constructorMixin) && !isFunction(options.constructorMixin)) {
60705 throw new TypeError(errorText + '.PromiseImpl');
60706 }
60707
60708 var PromiseImpl = options.PromiseImpl;
60709 var constructorMixin = options.constructorMixin;
60710
60711
60712 var plumbing = {};
60713
60714 plumbing.init = function (requestOptions) {
60715
60716 var self = this;
60717
60718 self._rp_promise = new PromiseImpl(function (resolve, reject) {
60719 self._rp_resolve = resolve;
60720 self._rp_reject = reject;
60721 if (constructorMixin) {
60722 constructorMixin.apply(self, arguments); // Using arguments since specific Promise libraries may pass additional parameters
60723 }
60724 });
60725
60726 self._rp_callbackOrig = requestOptions.callback;
60727 requestOptions.callback = self.callback = function RP$callback(err, response, body) {
60728 plumbing.callback.call(self, err, response, body);
60729 };
60730
60731 if (isString(requestOptions.method)) {
60732 requestOptions.method = requestOptions.method.toUpperCase();
60733 }
60734
60735 requestOptions.transform = requestOptions.transform || plumbing.defaultTransformations[requestOptions.method];
60736
60737 self._rp_options = requestOptions;
60738 self._rp_options.simple = requestOptions.simple !== false;
60739 self._rp_options.resolveWithFullResponse = requestOptions.resolveWithFullResponse === true;
60740 self._rp_options.transform2xxOnly = requestOptions.transform2xxOnly === true;
60741
60742 };
60743
60744 plumbing.defaultTransformations = {
60745 HEAD: function (body, response, resolveWithFullResponse) {
60746 return resolveWithFullResponse ? response : response.headers;
60747 }
60748 };
60749
60750 plumbing.callback = function (err, response, body) {
60751
60752 var self = this;
60753
60754 var origCallbackThrewException = false, thrownException = null;
60755
60756 if (isFunction(self._rp_callbackOrig)) {
60757 try {
60758 self._rp_callbackOrig.apply(self, arguments); // TODO: Apply to self mimics behavior of request@2. Is that also right for request@next?
60759 } catch (e) {
60760 origCallbackThrewException = true;
60761 thrownException = e;
60762 }
60763 }
60764
60765 var is2xx = !err && /^2/.test('' + response.statusCode);
60766
60767 if (err) {
60768
60769 self._rp_reject(new errors.RequestError(err, self._rp_options, response));
60770
60771 } else if (self._rp_options.simple && !is2xx) {
60772
60773 if (isFunction(self._rp_options.transform) && self._rp_options.transform2xxOnly === false) {
60774
60775 (new PromiseImpl(function (resolve) {
60776 resolve(self._rp_options.transform(body, response, self._rp_options.resolveWithFullResponse)); // transform may return a Promise
60777 }))
60778 .then(function (transformedResponse) {
60779 self._rp_reject(new errors.StatusCodeError(response.statusCode, body, self._rp_options, transformedResponse));
60780 })
60781 .catch(function (transformErr) {
60782 self._rp_reject(new errors.TransformError(transformErr, self._rp_options, response));
60783 });
60784
60785 } else {
60786 self._rp_reject(new errors.StatusCodeError(response.statusCode, body, self._rp_options, response));
60787 }
60788
60789 } else {
60790
60791 if (isFunction(self._rp_options.transform) && (is2xx || self._rp_options.transform2xxOnly === false)) {
60792
60793 (new PromiseImpl(function (resolve) {
60794 resolve(self._rp_options.transform(body, response, self._rp_options.resolveWithFullResponse)); // transform may return a Promise
60795 }))
60796 .then(function (transformedResponse) {
60797 self._rp_resolve(transformedResponse);
60798 })
60799 .catch(function (transformErr) {
60800 self._rp_reject(new errors.TransformError(transformErr, self._rp_options, response));
60801 });
60802
60803 } else if (self._rp_options.resolveWithFullResponse) {
60804 self._rp_resolve(response);
60805 } else {
60806 self._rp_resolve(body);
60807 }
60808
60809 }
60810
60811 if (origCallbackThrewException) {
60812 throw thrownException;
60813 }
60814
60815 };
60816
60817 plumbing.exposePromiseMethod = function (exposeTo, bindTo, promisePropertyKey, methodToExpose, exposeAs) {
60818
60819 exposeAs = exposeAs || methodToExpose;
60820
60821 if (exposeAs in exposeTo) {
60822 throw new Error('Unable to expose method "' + exposeAs + '"');
60823 }
60824
60825 exposeTo[exposeAs] = function RP$exposed() {
60826 var self = bindTo || this;
60827 return self[promisePropertyKey][methodToExpose].apply(self[promisePropertyKey], arguments);
60828 };
60829
60830 };
60831
60832 plumbing.exposePromise = function (exposeTo, bindTo, promisePropertyKey, exposeAs) {
60833
60834 exposeAs = exposeAs || 'promise';
60835
60836 if (exposeAs in exposeTo) {
60837 throw new Error('Unable to expose method "' + exposeAs + '"');
60838 }
60839
60840 exposeTo[exposeAs] = function RP$promise() {
60841 var self = bindTo || this;
60842 return self[promisePropertyKey];
60843 };
60844
60845 };
60846
60847 return plumbing;
60848
60849};
60850
60851},{"./errors.js":296,"lodash/isFunction":227,"lodash/isObjectLike":229,"lodash/isString":230,"lodash/isUndefined":231}],298:[function(require,module,exports){
60852'use strict';
60853
60854var Bluebird = require('bluebird').getNewLibraryCopy(),
60855 configure = require('request-promise-core/configure/request2'),
60856 stealthyRequire = require('stealthy-require');
60857
60858try {
60859
60860 // Load Request freshly - so that users can require an unaltered request instance!
60861 var request = stealthyRequire(require.cache, function () {
60862 return require('request');
60863 },
60864 function () {
60865 require('tough-cookie');
60866 }, module);
60867
60868} catch (err) {
60869 /* istanbul ignore next */
60870 var EOL = require('os').EOL;
60871 /* istanbul ignore next */
60872 console.error(EOL + '###' + EOL + '### The "request" library is not installed automatically anymore.' + EOL + '### But is a dependency of "request-promise".' + EOL + '### Please install it with:' + EOL + '### npm install request --save' + EOL + '###' + EOL);
60873 /* istanbul ignore next */
60874 throw err;
60875}
60876
60877Bluebird.config({cancellation: true});
60878
60879configure({
60880 request: request,
60881 PromiseImpl: Bluebird,
60882 expose: [
60883 'then',
60884 'catch',
60885 'finally',
60886 'cancel',
60887 'promise'
60888 // Would you like to expose more Bluebird methods? Try e.g. `rp(...).promise().tap(...)` first. `.promise()` returns the full-fledged Bluebird promise.
60889 ],
60890 constructorMixin: function (resolve, reject, onCancel) {
60891 var self = this;
60892 onCancel(function () {
60893 self.abort();
60894 });
60895 }
60896});
60897
60898request.bindCLS = function RP$bindCLS() {
60899 throw new Error('CLS support was dropped. To get it back read: https://github.com/request/request-promise/wiki/Getting-Back-Support-for-Continuation-Local-Storage');
60900};
60901
60902
60903module.exports = request;
60904
60905},{"bluebird":79,"os":240,"request":299,"request-promise-core/configure/request2":295,"stealthy-require":360,"tough-cookie":383}],299:[function(require,module,exports){
60906// Copyright 2010-2012 Mikeal Rogers
60907//
60908// Licensed under the Apache License, Version 2.0 (the "License");
60909// you may not use this file except in compliance with the License.
60910// You may obtain a copy of the License at
60911//
60912// http://www.apache.org/licenses/LICENSE-2.0
60913//
60914// Unless required by applicable law or agreed to in writing, software
60915// distributed under the License is distributed on an "AS IS" BASIS,
60916// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
60917// See the License for the specific language governing permissions and
60918// limitations under the License.
60919
60920'use strict'
60921
60922var extend = require('extend')
60923var cookies = require('./lib/cookies')
60924var helpers = require('./lib/helpers')
60925
60926var paramsHaveRequestBody = helpers.paramsHaveRequestBody
60927
60928// organize params for patch, post, put, head, del
60929function initParams (uri, options, callback) {
60930 if (typeof options === 'function') {
60931 callback = options
60932 }
60933
60934 var params = {}
60935 if (typeof options === 'object') {
60936 extend(params, options, {uri: uri})
60937 } else if (typeof uri === 'string') {
60938 extend(params, {uri: uri})
60939 } else {
60940 extend(params, uri)
60941 }
60942
60943 params.callback = callback || params.callback
60944 return params
60945}
60946
60947function request (uri, options, callback) {
60948 if (typeof uri === 'undefined') {
60949 throw new Error('undefined is not a valid uri or options object.')
60950 }
60951
60952 var params = initParams(uri, options, callback)
60953
60954 if (params.method === 'HEAD' && paramsHaveRequestBody(params)) {
60955 throw new Error('HTTP HEAD requests MUST NOT include a request body.')
60956 }
60957
60958 return new request.Request(params)
60959}
60960
60961function verbFunc (verb) {
60962 var method = verb.toUpperCase()
60963 return function (uri, options, callback) {
60964 var params = initParams(uri, options, callback)
60965 params.method = method
60966 return request(params, params.callback)
60967 }
60968}
60969
60970// define like this to please codeintel/intellisense IDEs
60971request.get = verbFunc('get')
60972request.head = verbFunc('head')
60973request.options = verbFunc('options')
60974request.post = verbFunc('post')
60975request.put = verbFunc('put')
60976request.patch = verbFunc('patch')
60977request.del = verbFunc('delete')
60978request['delete'] = verbFunc('delete')
60979
60980request.jar = function (store) {
60981 return cookies.jar(store)
60982}
60983
60984request.cookie = function (str) {
60985 return cookies.parse(str)
60986}
60987
60988function wrapRequestMethod (method, options, requester, verb) {
60989 return function (uri, opts, callback) {
60990 var params = initParams(uri, opts, callback)
60991
60992 var target = {}
60993 extend(true, target, options, params)
60994
60995 target.pool = params.pool || options.pool
60996
60997 if (verb) {
60998 target.method = verb.toUpperCase()
60999 }
61000
61001 if (typeof requester === 'function') {
61002 method = requester
61003 }
61004
61005 return method(target, target.callback)
61006 }
61007}
61008
61009request.defaults = function (options, requester) {
61010 var self = this
61011
61012 options = options || {}
61013
61014 if (typeof options === 'function') {
61015 requester = options
61016 options = {}
61017 }
61018
61019 var defaults = wrapRequestMethod(self, options, requester)
61020
61021 var verbs = ['get', 'head', 'post', 'put', 'patch', 'del', 'delete']
61022 verbs.forEach(function (verb) {
61023 defaults[verb] = wrapRequestMethod(self[verb], options, requester, verb)
61024 })
61025
61026 defaults.cookie = wrapRequestMethod(self.cookie, options, requester)
61027 defaults.jar = self.jar
61028 defaults.defaults = self.defaults
61029 return defaults
61030}
61031
61032request.forever = function (agentOptions, optionsArg) {
61033 var options = {}
61034 if (optionsArg) {
61035 extend(options, optionsArg)
61036 }
61037 if (agentOptions) {
61038 options.agentOptions = agentOptions
61039 }
61040
61041 options.forever = true
61042 return request.defaults(options)
61043}
61044
61045// Exports
61046
61047module.exports = request
61048request.Request = require('./request')
61049request.initParams = initParams
61050
61051// Backwards compatibility for request.debug
61052Object.defineProperty(request, 'debug', {
61053 enumerable: true,
61054 get: function () {
61055 return request.Request.debug
61056 },
61057 set: function (debug) {
61058 request.Request.debug = debug
61059 }
61060})
61061
61062},{"./lib/cookies":301,"./lib/helpers":305,"./request":323,"extend":161}],300:[function(require,module,exports){
61063'use strict'
61064
61065var caseless = require('caseless')
61066var uuid = require('uuid/v4')
61067var helpers = require('./helpers')
61068
61069var md5 = helpers.md5
61070var toBase64 = helpers.toBase64
61071
61072function Auth (request) {
61073 // define all public properties here
61074 this.request = request
61075 this.hasAuth = false
61076 this.sentAuth = false
61077 this.bearerToken = null
61078 this.user = null
61079 this.pass = null
61080}
61081
61082Auth.prototype.basic = function (user, pass, sendImmediately) {
61083 var self = this
61084 if (typeof user !== 'string' || (pass !== undefined && typeof pass !== 'string')) {
61085 self.request.emit('error', new Error('auth() received invalid user or password'))
61086 }
61087 self.user = user
61088 self.pass = pass
61089 self.hasAuth = true
61090 var header = user + ':' + (pass || '')
61091 if (sendImmediately || typeof sendImmediately === 'undefined') {
61092 var authHeader = 'Basic ' + toBase64(header)
61093 self.sentAuth = true
61094 return authHeader
61095 }
61096}
61097
61098Auth.prototype.bearer = function (bearer, sendImmediately) {
61099 var self = this
61100 self.bearerToken = bearer
61101 self.hasAuth = true
61102 if (sendImmediately || typeof sendImmediately === 'undefined') {
61103 if (typeof bearer === 'function') {
61104 bearer = bearer()
61105 }
61106 var authHeader = 'Bearer ' + (bearer || '')
61107 self.sentAuth = true
61108 return authHeader
61109 }
61110}
61111
61112Auth.prototype.digest = function (method, path, authHeader) {
61113 // TODO: More complete implementation of RFC 2617.
61114 // - handle challenge.domain
61115 // - support qop="auth-int" only
61116 // - handle Authentication-Info (not necessarily?)
61117 // - check challenge.stale (not necessarily?)
61118 // - increase nc (not necessarily?)
61119 // For reference:
61120 // http://tools.ietf.org/html/rfc2617#section-3
61121 // https://github.com/bagder/curl/blob/master/lib/http_digest.c
61122
61123 var self = this
61124
61125 var challenge = {}
61126 var re = /([a-z0-9_-]+)=(?:"([^"]+)"|([a-z0-9_-]+))/gi
61127 for (;;) {
61128 var match = re.exec(authHeader)
61129 if (!match) {
61130 break
61131 }
61132 challenge[match[1]] = match[2] || match[3]
61133 }
61134
61135 /**
61136 * RFC 2617: handle both MD5 and MD5-sess algorithms.
61137 *
61138 * If the algorithm directive's value is "MD5" or unspecified, then HA1 is
61139 * HA1=MD5(username:realm:password)
61140 * If the algorithm directive's value is "MD5-sess", then HA1 is
61141 * HA1=MD5(MD5(username:realm:password):nonce:cnonce)
61142 */
61143 var ha1Compute = function (algorithm, user, realm, pass, nonce, cnonce) {
61144 var ha1 = md5(user + ':' + realm + ':' + pass)
61145 if (algorithm && algorithm.toLowerCase() === 'md5-sess') {
61146 return md5(ha1 + ':' + nonce + ':' + cnonce)
61147 } else {
61148 return ha1
61149 }
61150 }
61151
61152 var qop = /(^|,)\s*auth\s*($|,)/.test(challenge.qop) && 'auth'
61153 var nc = qop && '00000001'
61154 var cnonce = qop && uuid().replace(/-/g, '')
61155 var ha1 = ha1Compute(challenge.algorithm, self.user, challenge.realm, self.pass, challenge.nonce, cnonce)
61156 var ha2 = md5(method + ':' + path)
61157 var digestResponse = qop
61158 ? md5(ha1 + ':' + challenge.nonce + ':' + nc + ':' + cnonce + ':' + qop + ':' + ha2)
61159 : md5(ha1 + ':' + challenge.nonce + ':' + ha2)
61160 var authValues = {
61161 username: self.user,
61162 realm: challenge.realm,
61163 nonce: challenge.nonce,
61164 uri: path,
61165 qop: qop,
61166 response: digestResponse,
61167 nc: nc,
61168 cnonce: cnonce,
61169 algorithm: challenge.algorithm,
61170 opaque: challenge.opaque
61171 }
61172
61173 authHeader = []
61174 for (var k in authValues) {
61175 if (authValues[k]) {
61176 if (k === 'qop' || k === 'nc' || k === 'algorithm') {
61177 authHeader.push(k + '=' + authValues[k])
61178 } else {
61179 authHeader.push(k + '="' + authValues[k] + '"')
61180 }
61181 }
61182 }
61183 authHeader = 'Digest ' + authHeader.join(', ')
61184 self.sentAuth = true
61185 return authHeader
61186}
61187
61188Auth.prototype.onRequest = function (user, pass, sendImmediately, bearer) {
61189 var self = this
61190 var request = self.request
61191
61192 var authHeader
61193 if (bearer === undefined && user === undefined) {
61194 self.request.emit('error', new Error('no auth mechanism defined'))
61195 } else if (bearer !== undefined) {
61196 authHeader = self.bearer(bearer, sendImmediately)
61197 } else {
61198 authHeader = self.basic(user, pass, sendImmediately)
61199 }
61200 if (authHeader) {
61201 request.setHeader('authorization', authHeader)
61202 }
61203}
61204
61205Auth.prototype.onResponse = function (response) {
61206 var self = this
61207 var request = self.request
61208
61209 if (!self.hasAuth || self.sentAuth) { return null }
61210
61211 var c = caseless(response.headers)
61212
61213 var authHeader = c.get('www-authenticate')
61214 var authVerb = authHeader && authHeader.split(' ')[0].toLowerCase()
61215 request.debug('reauth', authVerb)
61216
61217 switch (authVerb) {
61218 case 'basic':
61219 return self.basic(self.user, self.pass, true)
61220
61221 case 'bearer':
61222 return self.bearer(self.bearerToken, true)
61223
61224 case 'digest':
61225 return self.digest(request.method, request.path, authHeader)
61226 }
61227}
61228
61229exports.Auth = Auth
61230
61231},{"./helpers":305,"caseless":116,"uuid/v4":400}],301:[function(require,module,exports){
61232'use strict'
61233
61234var tough = require('tough-cookie')
61235
61236var Cookie = tough.Cookie
61237var CookieJar = tough.CookieJar
61238
61239exports.parse = function (str) {
61240 if (str && str.uri) {
61241 str = str.uri
61242 }
61243 if (typeof str !== 'string') {
61244 throw new Error('The cookie function only accepts STRING as param')
61245 }
61246 return Cookie.parse(str, {loose: true})
61247}
61248
61249// Adapt the sometimes-Async api of tough.CookieJar to our requirements
61250function RequestJar (store) {
61251 var self = this
61252 self._jar = new CookieJar(store, {looseMode: true})
61253}
61254RequestJar.prototype.setCookie = function (cookieOrStr, uri, options) {
61255 var self = this
61256 return self._jar.setCookieSync(cookieOrStr, uri, options || {})
61257}
61258RequestJar.prototype.getCookieString = function (uri) {
61259 var self = this
61260 return self._jar.getCookieStringSync(uri)
61261}
61262RequestJar.prototype.getCookies = function (uri) {
61263 var self = this
61264 return self._jar.getCookiesSync(uri)
61265}
61266
61267exports.jar = function (store) {
61268 return new RequestJar(store)
61269}
61270
61271},{"tough-cookie":316}],302:[function(require,module,exports){
61272(function (process){
61273'use strict'
61274
61275function formatHostname (hostname) {
61276 // canonicalize the hostname, so that 'oogle.com' won't match 'google.com'
61277 return hostname.replace(/^\.*/, '.').toLowerCase()
61278}
61279
61280function parseNoProxyZone (zone) {
61281 zone = zone.trim().toLowerCase()
61282
61283 var zoneParts = zone.split(':', 2)
61284 var zoneHost = formatHostname(zoneParts[0])
61285 var zonePort = zoneParts[1]
61286 var hasPort = zone.indexOf(':') > -1
61287
61288 return {hostname: zoneHost, port: zonePort, hasPort: hasPort}
61289}
61290
61291function uriInNoProxy (uri, noProxy) {
61292 var port = uri.port || (uri.protocol === 'https:' ? '443' : '80')
61293 var hostname = formatHostname(uri.hostname)
61294 var noProxyList = noProxy.split(',')
61295
61296 // iterate through the noProxyList until it finds a match.
61297 return noProxyList.map(parseNoProxyZone).some(function (noProxyZone) {
61298 var isMatchedAt = hostname.indexOf(noProxyZone.hostname)
61299 var hostnameMatched = (
61300 isMatchedAt > -1 &&
61301 (isMatchedAt === hostname.length - noProxyZone.hostname.length)
61302 )
61303
61304 if (noProxyZone.hasPort) {
61305 return (port === noProxyZone.port) && hostnameMatched
61306 }
61307
61308 return hostnameMatched
61309 })
61310}
61311
61312function getProxyFromURI (uri) {
61313 // Decide the proper request proxy to use based on the request URI object and the
61314 // environmental variables (NO_PROXY, HTTP_PROXY, etc.)
61315 // respect NO_PROXY environment variables (see: http://lynx.isc.org/current/breakout/lynx_help/keystrokes/environments.html)
61316
61317 var noProxy = process.env.NO_PROXY || process.env.no_proxy || ''
61318
61319 // if the noProxy is a wildcard then return null
61320
61321 if (noProxy === '*') {
61322 return null
61323 }
61324
61325 // if the noProxy is not empty and the uri is found return null
61326
61327 if (noProxy !== '' && uriInNoProxy(uri, noProxy)) {
61328 return null
61329 }
61330
61331 // Check for HTTP or HTTPS Proxy in environment Else default to null
61332
61333 if (uri.protocol === 'http:') {
61334 return process.env.HTTP_PROXY ||
61335 process.env.http_proxy || null
61336 }
61337
61338 if (uri.protocol === 'https:') {
61339 return process.env.HTTPS_PROXY ||
61340 process.env.https_proxy ||
61341 process.env.HTTP_PROXY ||
61342 process.env.http_proxy || null
61343 }
61344
61345 // if none of that works, return null
61346 // (What uri protocol are you using then?)
61347
61348 return null
61349}
61350
61351module.exports = getProxyFromURI
61352
61353}).call(this,require('_process'))
61354},{"_process":265}],303:[function(require,module,exports){
61355'use strict'
61356
61357var fs = require('fs')
61358var qs = require('querystring')
61359var validate = require('har-validator')
61360var extend = require('extend')
61361
61362function Har (request) {
61363 this.request = request
61364}
61365
61366Har.prototype.reducer = function (obj, pair) {
61367 // new property ?
61368 if (obj[pair.name] === undefined) {
61369 obj[pair.name] = pair.value
61370 return obj
61371 }
61372
61373 // existing? convert to array
61374 var arr = [
61375 obj[pair.name],
61376 pair.value
61377 ]
61378
61379 obj[pair.name] = arr
61380
61381 return obj
61382}
61383
61384Har.prototype.prep = function (data) {
61385 // construct utility properties
61386 data.queryObj = {}
61387 data.headersObj = {}
61388 data.postData.jsonObj = false
61389 data.postData.paramsObj = false
61390
61391 // construct query objects
61392 if (data.queryString && data.queryString.length) {
61393 data.queryObj = data.queryString.reduce(this.reducer, {})
61394 }
61395
61396 // construct headers objects
61397 if (data.headers && data.headers.length) {
61398 // loweCase header keys
61399 data.headersObj = data.headers.reduceRight(function (headers, header) {
61400 headers[header.name] = header.value
61401 return headers
61402 }, {})
61403 }
61404
61405 // construct Cookie header
61406 if (data.cookies && data.cookies.length) {
61407 var cookies = data.cookies.map(function (cookie) {
61408 return cookie.name + '=' + cookie.value
61409 })
61410
61411 if (cookies.length) {
61412 data.headersObj.cookie = cookies.join('; ')
61413 }
61414 }
61415
61416 // prep body
61417 function some (arr) {
61418 return arr.some(function (type) {
61419 return data.postData.mimeType.indexOf(type) === 0
61420 })
61421 }
61422
61423 if (some([
61424 'multipart/mixed',
61425 'multipart/related',
61426 'multipart/form-data',
61427 'multipart/alternative'])) {
61428 // reset values
61429 data.postData.mimeType = 'multipart/form-data'
61430 } else if (some([
61431 'application/x-www-form-urlencoded'])) {
61432 if (!data.postData.params) {
61433 data.postData.text = ''
61434 } else {
61435 data.postData.paramsObj = data.postData.params.reduce(this.reducer, {})
61436
61437 // always overwrite
61438 data.postData.text = qs.stringify(data.postData.paramsObj)
61439 }
61440 } else if (some([
61441 'text/json',
61442 'text/x-json',
61443 'application/json',
61444 'application/x-json'])) {
61445 data.postData.mimeType = 'application/json'
61446
61447 if (data.postData.text) {
61448 try {
61449 data.postData.jsonObj = JSON.parse(data.postData.text)
61450 } catch (e) {
61451 this.request.debug(e)
61452
61453 // force back to text/plain
61454 data.postData.mimeType = 'text/plain'
61455 }
61456 }
61457 }
61458
61459 return data
61460}
61461
61462Har.prototype.options = function (options) {
61463 // skip if no har property defined
61464 if (!options.har) {
61465 return options
61466 }
61467
61468 var har = {}
61469 extend(har, options.har)
61470
61471 // only process the first entry
61472 if (har.log && har.log.entries) {
61473 har = har.log.entries[0]
61474 }
61475
61476 // add optional properties to make validation successful
61477 har.url = har.url || options.url || options.uri || options.baseUrl || '/'
61478 har.httpVersion = har.httpVersion || 'HTTP/1.1'
61479 har.queryString = har.queryString || []
61480 har.headers = har.headers || []
61481 har.cookies = har.cookies || []
61482 har.postData = har.postData || {}
61483 har.postData.mimeType = har.postData.mimeType || 'application/octet-stream'
61484
61485 har.bodySize = 0
61486 har.headersSize = 0
61487 har.postData.size = 0
61488
61489 if (!validate.request(har)) {
61490 return options
61491 }
61492
61493 // clean up and get some utility properties
61494 var req = this.prep(har)
61495
61496 // construct new options
61497 if (req.url) {
61498 options.url = req.url
61499 }
61500
61501 if (req.method) {
61502 options.method = req.method
61503 }
61504
61505 if (Object.keys(req.queryObj).length) {
61506 options.qs = req.queryObj
61507 }
61508
61509 if (Object.keys(req.headersObj).length) {
61510 options.headers = req.headersObj
61511 }
61512
61513 function test (type) {
61514 return req.postData.mimeType.indexOf(type) === 0
61515 }
61516 if (test('application/x-www-form-urlencoded')) {
61517 options.form = req.postData.paramsObj
61518 } else if (test('application/json')) {
61519 if (req.postData.jsonObj) {
61520 options.body = req.postData.jsonObj
61521 options.json = true
61522 }
61523 } else if (test('multipart/form-data')) {
61524 options.formData = {}
61525
61526 req.postData.params.forEach(function (param) {
61527 var attachment = {}
61528
61529 if (!param.fileName && !param.fileName && !param.contentType) {
61530 options.formData[param.name] = param.value
61531 return
61532 }
61533
61534 // attempt to read from disk!
61535 if (param.fileName && !param.value) {
61536 attachment.value = fs.createReadStream(param.fileName)
61537 } else if (param.value) {
61538 attachment.value = param.value
61539 }
61540
61541 if (param.fileName) {
61542 attachment.options = {
61543 filename: param.fileName,
61544 contentType: param.contentType ? param.contentType : null
61545 }
61546 }
61547
61548 options.formData[param.name] = attachment
61549 })
61550 } else {
61551 if (req.postData.text) {
61552 options.body = req.postData.text
61553 }
61554 }
61555
61556 return options
61557}
61558
61559exports.Har = Har
61560
61561},{"extend":161,"fs":112,"har-validator":188,"querystring":277}],304:[function(require,module,exports){
61562'use strict'
61563
61564var crypto = require('crypto')
61565
61566function randomString (size) {
61567 var bits = (size + 1) * 6
61568 var buffer = crypto.randomBytes(Math.ceil(bits / 8))
61569 var string = buffer.toString('base64').replace(/\+/g, '-').replace(/\//g, '_').replace(/=/g, '')
61570 return string.slice(0, size)
61571}
61572
61573function calculatePayloadHash (payload, algorithm, contentType) {
61574 var hash = crypto.createHash(algorithm)
61575 hash.update('hawk.1.payload\n')
61576 hash.update((contentType ? contentType.split(';')[0].trim().toLowerCase() : '') + '\n')
61577 hash.update(payload || '')
61578 hash.update('\n')
61579 return hash.digest('base64')
61580}
61581
61582exports.calculateMac = function (credentials, opts) {
61583 var normalized = 'hawk.1.header\n' +
61584 opts.ts + '\n' +
61585 opts.nonce + '\n' +
61586 (opts.method || '').toUpperCase() + '\n' +
61587 opts.resource + '\n' +
61588 opts.host.toLowerCase() + '\n' +
61589 opts.port + '\n' +
61590 (opts.hash || '') + '\n'
61591
61592 if (opts.ext) {
61593 normalized = normalized + opts.ext.replace('\\', '\\\\').replace('\n', '\\n')
61594 }
61595
61596 normalized = normalized + '\n'
61597
61598 if (opts.app) {
61599 normalized = normalized + opts.app + '\n' + (opts.dlg || '') + '\n'
61600 }
61601
61602 var hmac = crypto.createHmac(credentials.algorithm, credentials.key).update(normalized)
61603 var digest = hmac.digest('base64')
61604 return digest
61605}
61606
61607exports.header = function (uri, method, opts) {
61608 var timestamp = opts.timestamp || Math.floor((Date.now() + (opts.localtimeOffsetMsec || 0)) / 1000)
61609 var credentials = opts.credentials
61610 if (!credentials || !credentials.id || !credentials.key || !credentials.algorithm) {
61611 return ''
61612 }
61613
61614 if (['sha1', 'sha256'].indexOf(credentials.algorithm) === -1) {
61615 return ''
61616 }
61617
61618 var artifacts = {
61619 ts: timestamp,
61620 nonce: opts.nonce || randomString(6),
61621 method: method,
61622 resource: uri.pathname + (uri.search || ''),
61623 host: uri.hostname,
61624 port: uri.port || (uri.protocol === 'http:' ? 80 : 443),
61625 hash: opts.hash,
61626 ext: opts.ext,
61627 app: opts.app,
61628 dlg: opts.dlg
61629 }
61630
61631 if (!artifacts.hash && (opts.payload || opts.payload === '')) {
61632 artifacts.hash = calculatePayloadHash(opts.payload, credentials.algorithm, opts.contentType)
61633 }
61634
61635 var mac = exports.calculateMac(credentials, artifacts)
61636
61637 var hasExt = artifacts.ext !== null && artifacts.ext !== undefined && artifacts.ext !== ''
61638 var header = 'Hawk id="' + credentials.id +
61639 '", ts="' + artifacts.ts +
61640 '", nonce="' + artifacts.nonce +
61641 (artifacts.hash ? '", hash="' + artifacts.hash : '') +
61642 (hasExt ? '", ext="' + artifacts.ext.replace(/\\/g, '\\\\').replace(/"/g, '\\"') : '') +
61643 '", mac="' + mac + '"'
61644
61645 if (artifacts.app) {
61646 header = header + ', app="' + artifacts.app + (artifacts.dlg ? '", dlg="' + artifacts.dlg : '') + '"'
61647 }
61648
61649 return header
61650}
61651
61652},{"crypto":126}],305:[function(require,module,exports){
61653(function (process,setImmediate){
61654'use strict'
61655
61656var jsonSafeStringify = require('json-stringify-safe')
61657var crypto = require('crypto')
61658var Buffer = require('safe-buffer').Buffer
61659
61660var defer = typeof setImmediate === 'undefined'
61661 ? process.nextTick
61662 : setImmediate
61663
61664function paramsHaveRequestBody (params) {
61665 return (
61666 params.body ||
61667 params.requestBodyStream ||
61668 (params.json && typeof params.json !== 'boolean') ||
61669 params.multipart
61670 )
61671}
61672
61673function safeStringify (obj, replacer) {
61674 var ret
61675 try {
61676 ret = JSON.stringify(obj, replacer)
61677 } catch (e) {
61678 ret = jsonSafeStringify(obj, replacer)
61679 }
61680 return ret
61681}
61682
61683function md5 (str) {
61684 return crypto.createHash('md5').update(str).digest('hex')
61685}
61686
61687function isReadStream (rs) {
61688 return rs.readable && rs.path && rs.mode
61689}
61690
61691function toBase64 (str) {
61692 return Buffer.from(str || '', 'utf8').toString('base64')
61693}
61694
61695function copy (obj) {
61696 var o = {}
61697 Object.keys(obj).forEach(function (i) {
61698 o[i] = obj[i]
61699 })
61700 return o
61701}
61702
61703function version () {
61704 var numbers = process.version.replace('v', '').split('.')
61705 return {
61706 major: parseInt(numbers[0], 10),
61707 minor: parseInt(numbers[1], 10),
61708 patch: parseInt(numbers[2], 10)
61709 }
61710}
61711
61712exports.paramsHaveRequestBody = paramsHaveRequestBody
61713exports.safeStringify = safeStringify
61714exports.md5 = md5
61715exports.isReadStream = isReadStream
61716exports.toBase64 = toBase64
61717exports.copy = copy
61718exports.version = version
61719exports.defer = defer
61720
61721}).call(this,require('_process'),require("timers").setImmediate)
61722},{"_process":265,"crypto":126,"json-stringify-safe":218,"safe-buffer":325,"timers":382}],306:[function(require,module,exports){
61723'use strict'
61724
61725var uuid = require('uuid/v4')
61726var CombinedStream = require('combined-stream')
61727var isstream = require('isstream')
61728var Buffer = require('safe-buffer').Buffer
61729
61730function Multipart (request) {
61731 this.request = request
61732 this.boundary = uuid()
61733 this.chunked = false
61734 this.body = null
61735}
61736
61737Multipart.prototype.isChunked = function (options) {
61738 var self = this
61739 var chunked = false
61740 var parts = options.data || options
61741
61742 if (!parts.forEach) {
61743 self.request.emit('error', new Error('Argument error, options.multipart.'))
61744 }
61745
61746 if (options.chunked !== undefined) {
61747 chunked = options.chunked
61748 }
61749
61750 if (self.request.getHeader('transfer-encoding') === 'chunked') {
61751 chunked = true
61752 }
61753
61754 if (!chunked) {
61755 parts.forEach(function (part) {
61756 if (typeof part.body === 'undefined') {
61757 self.request.emit('error', new Error('Body attribute missing in multipart.'))
61758 }
61759 if (isstream(part.body)) {
61760 chunked = true
61761 }
61762 })
61763 }
61764
61765 return chunked
61766}
61767
61768Multipart.prototype.setHeaders = function (chunked) {
61769 var self = this
61770
61771 if (chunked && !self.request.hasHeader('transfer-encoding')) {
61772 self.request.setHeader('transfer-encoding', 'chunked')
61773 }
61774
61775 var header = self.request.getHeader('content-type')
61776
61777 if (!header || header.indexOf('multipart') === -1) {
61778 self.request.setHeader('content-type', 'multipart/related; boundary=' + self.boundary)
61779 } else {
61780 if (header.indexOf('boundary') !== -1) {
61781 self.boundary = header.replace(/.*boundary=([^\s;]+).*/, '$1')
61782 } else {
61783 self.request.setHeader('content-type', header + '; boundary=' + self.boundary)
61784 }
61785 }
61786}
61787
61788Multipart.prototype.build = function (parts, chunked) {
61789 var self = this
61790 var body = chunked ? new CombinedStream() : []
61791
61792 function add (part) {
61793 if (typeof part === 'number') {
61794 part = part.toString()
61795 }
61796 return chunked ? body.append(part) : body.push(Buffer.from(part))
61797 }
61798
61799 if (self.request.preambleCRLF) {
61800 add('\r\n')
61801 }
61802
61803 parts.forEach(function (part) {
61804 var preamble = '--' + self.boundary + '\r\n'
61805 Object.keys(part).forEach(function (key) {
61806 if (key === 'body') { return }
61807 preamble += key + ': ' + part[key] + '\r\n'
61808 })
61809 preamble += '\r\n'
61810 add(preamble)
61811 add(part.body)
61812 add('\r\n')
61813 })
61814 add('--' + self.boundary + '--')
61815
61816 if (self.request.postambleCRLF) {
61817 add('\r\n')
61818 }
61819
61820 return body
61821}
61822
61823Multipart.prototype.onRequest = function (options) {
61824 var self = this
61825
61826 var chunked = self.isChunked(options)
61827 var parts = options.data || options
61828
61829 self.setHeaders(chunked)
61830 self.chunked = chunked
61831 self.body = self.build(parts, chunked)
61832}
61833
61834exports.Multipart = Multipart
61835
61836},{"combined-stream":118,"isstream":214,"safe-buffer":325,"uuid/v4":400}],307:[function(require,module,exports){
61837'use strict'
61838
61839var url = require('url')
61840var qs = require('qs')
61841var caseless = require('caseless')
61842var uuid = require('uuid/v4')
61843var oauth = require('oauth-sign')
61844var crypto = require('crypto')
61845var Buffer = require('safe-buffer').Buffer
61846
61847function OAuth (request) {
61848 this.request = request
61849 this.params = null
61850}
61851
61852OAuth.prototype.buildParams = function (_oauth, uri, method, query, form, qsLib) {
61853 var oa = {}
61854 for (var i in _oauth) {
61855 oa['oauth_' + i] = _oauth[i]
61856 }
61857 if (!oa.oauth_version) {
61858 oa.oauth_version = '1.0'
61859 }
61860 if (!oa.oauth_timestamp) {
61861 oa.oauth_timestamp = Math.floor(Date.now() / 1000).toString()
61862 }
61863 if (!oa.oauth_nonce) {
61864 oa.oauth_nonce = uuid().replace(/-/g, '')
61865 }
61866 if (!oa.oauth_signature_method) {
61867 oa.oauth_signature_method = 'HMAC-SHA1'
61868 }
61869
61870 var consumer_secret_or_private_key = oa.oauth_consumer_secret || oa.oauth_private_key // eslint-disable-line camelcase
61871 delete oa.oauth_consumer_secret
61872 delete oa.oauth_private_key
61873
61874 var token_secret = oa.oauth_token_secret // eslint-disable-line camelcase
61875 delete oa.oauth_token_secret
61876
61877 var realm = oa.oauth_realm
61878 delete oa.oauth_realm
61879 delete oa.oauth_transport_method
61880
61881 var baseurl = uri.protocol + '//' + uri.host + uri.pathname
61882 var params = qsLib.parse([].concat(query, form, qsLib.stringify(oa)).join('&'))
61883
61884 oa.oauth_signature = oauth.sign(
61885 oa.oauth_signature_method,
61886 method,
61887 baseurl,
61888 params,
61889 consumer_secret_or_private_key, // eslint-disable-line camelcase
61890 token_secret // eslint-disable-line camelcase
61891 )
61892
61893 if (realm) {
61894 oa.realm = realm
61895 }
61896
61897 return oa
61898}
61899
61900OAuth.prototype.buildBodyHash = function (_oauth, body) {
61901 if (['HMAC-SHA1', 'RSA-SHA1'].indexOf(_oauth.signature_method || 'HMAC-SHA1') < 0) {
61902 this.request.emit('error', new Error('oauth: ' + _oauth.signature_method +
61903 ' signature_method not supported with body_hash signing.'))
61904 }
61905
61906 var shasum = crypto.createHash('sha1')
61907 shasum.update(body || '')
61908 var sha1 = shasum.digest('hex')
61909
61910 return Buffer.from(sha1, 'hex').toString('base64')
61911}
61912
61913OAuth.prototype.concatParams = function (oa, sep, wrap) {
61914 wrap = wrap || ''
61915
61916 var params = Object.keys(oa).filter(function (i) {
61917 return i !== 'realm' && i !== 'oauth_signature'
61918 }).sort()
61919
61920 if (oa.realm) {
61921 params.splice(0, 0, 'realm')
61922 }
61923 params.push('oauth_signature')
61924
61925 return params.map(function (i) {
61926 return i + '=' + wrap + oauth.rfc3986(oa[i]) + wrap
61927 }).join(sep)
61928}
61929
61930OAuth.prototype.onRequest = function (_oauth) {
61931 var self = this
61932 self.params = _oauth
61933
61934 var uri = self.request.uri || {}
61935 var method = self.request.method || ''
61936 var headers = caseless(self.request.headers)
61937 var body = self.request.body || ''
61938 var qsLib = self.request.qsLib || qs
61939
61940 var form
61941 var query
61942 var contentType = headers.get('content-type') || ''
61943 var formContentType = 'application/x-www-form-urlencoded'
61944 var transport = _oauth.transport_method || 'header'
61945
61946 if (contentType.slice(0, formContentType.length) === formContentType) {
61947 contentType = formContentType
61948 form = body
61949 }
61950 if (uri.query) {
61951 query = uri.query
61952 }
61953 if (transport === 'body' && (method !== 'POST' || contentType !== formContentType)) {
61954 self.request.emit('error', new Error('oauth: transport_method of body requires POST ' +
61955 'and content-type ' + formContentType))
61956 }
61957
61958 if (!form && typeof _oauth.body_hash === 'boolean') {
61959 _oauth.body_hash = self.buildBodyHash(_oauth, self.request.body.toString())
61960 }
61961
61962 var oa = self.buildParams(_oauth, uri, method, query, form, qsLib)
61963
61964 switch (transport) {
61965 case 'header':
61966 self.request.setHeader('Authorization', 'OAuth ' + self.concatParams(oa, ',', '"'))
61967 break
61968
61969 case 'query':
61970 var href = self.request.uri.href += (query ? '&' : '?') + self.concatParams(oa, '&')
61971 self.request.uri = url.parse(href)
61972 self.request.path = self.request.uri.path
61973 break
61974
61975 case 'body':
61976 self.request.body = (form ? form + '&' : '') + self.concatParams(oa, '&')
61977 break
61978
61979 default:
61980 self.request.emit('error', new Error('oauth: transport_method invalid'))
61981 }
61982}
61983
61984exports.OAuth = OAuth
61985
61986},{"caseless":116,"crypto":126,"oauth-sign":239,"qs":312,"safe-buffer":325,"url":393,"uuid/v4":400}],308:[function(require,module,exports){
61987'use strict'
61988
61989var qs = require('qs')
61990var querystring = require('querystring')
61991
61992function Querystring (request) {
61993 this.request = request
61994 this.lib = null
61995 this.useQuerystring = null
61996 this.parseOptions = null
61997 this.stringifyOptions = null
61998}
61999
62000Querystring.prototype.init = function (options) {
62001 if (this.lib) { return }
62002
62003 this.useQuerystring = options.useQuerystring
62004 this.lib = (this.useQuerystring ? querystring : qs)
62005
62006 this.parseOptions = options.qsParseOptions || {}
62007 this.stringifyOptions = options.qsStringifyOptions || {}
62008}
62009
62010Querystring.prototype.stringify = function (obj) {
62011 return (this.useQuerystring)
62012 ? this.rfc3986(this.lib.stringify(obj,
62013 this.stringifyOptions.sep || null,
62014 this.stringifyOptions.eq || null,
62015 this.stringifyOptions))
62016 : this.lib.stringify(obj, this.stringifyOptions)
62017}
62018
62019Querystring.prototype.parse = function (str) {
62020 return (this.useQuerystring)
62021 ? this.lib.parse(str,
62022 this.parseOptions.sep || null,
62023 this.parseOptions.eq || null,
62024 this.parseOptions)
62025 : this.lib.parse(str, this.parseOptions)
62026}
62027
62028Querystring.prototype.rfc3986 = function (str) {
62029 return str.replace(/[!'()*]/g, function (c) {
62030 return '%' + c.charCodeAt(0).toString(16).toUpperCase()
62031 })
62032}
62033
62034Querystring.prototype.unescape = querystring.unescape
62035
62036exports.Querystring = Querystring
62037
62038},{"qs":312,"querystring":277}],309:[function(require,module,exports){
62039'use strict'
62040
62041var url = require('url')
62042var isUrl = /^https?:/
62043
62044function Redirect (request) {
62045 this.request = request
62046 this.followRedirect = true
62047 this.followRedirects = true
62048 this.followAllRedirects = false
62049 this.followOriginalHttpMethod = false
62050 this.allowRedirect = function () { return true }
62051 this.maxRedirects = 10
62052 this.redirects = []
62053 this.redirectsFollowed = 0
62054 this.removeRefererHeader = false
62055}
62056
62057Redirect.prototype.onRequest = function (options) {
62058 var self = this
62059
62060 if (options.maxRedirects !== undefined) {
62061 self.maxRedirects = options.maxRedirects
62062 }
62063 if (typeof options.followRedirect === 'function') {
62064 self.allowRedirect = options.followRedirect
62065 }
62066 if (options.followRedirect !== undefined) {
62067 self.followRedirects = !!options.followRedirect
62068 }
62069 if (options.followAllRedirects !== undefined) {
62070 self.followAllRedirects = options.followAllRedirects
62071 }
62072 if (self.followRedirects || self.followAllRedirects) {
62073 self.redirects = self.redirects || []
62074 }
62075 if (options.removeRefererHeader !== undefined) {
62076 self.removeRefererHeader = options.removeRefererHeader
62077 }
62078 if (options.followOriginalHttpMethod !== undefined) {
62079 self.followOriginalHttpMethod = options.followOriginalHttpMethod
62080 }
62081}
62082
62083Redirect.prototype.redirectTo = function (response) {
62084 var self = this
62085 var request = self.request
62086
62087 var redirectTo = null
62088 if (response.statusCode >= 300 && response.statusCode < 400 && response.caseless.has('location')) {
62089 var location = response.caseless.get('location')
62090 request.debug('redirect', location)
62091
62092 if (self.followAllRedirects) {
62093 redirectTo = location
62094 } else if (self.followRedirects) {
62095 switch (request.method) {
62096 case 'PATCH':
62097 case 'PUT':
62098 case 'POST':
62099 case 'DELETE':
62100 // Do not follow redirects
62101 break
62102 default:
62103 redirectTo = location
62104 break
62105 }
62106 }
62107 } else if (response.statusCode === 401) {
62108 var authHeader = request._auth.onResponse(response)
62109 if (authHeader) {
62110 request.setHeader('authorization', authHeader)
62111 redirectTo = request.uri
62112 }
62113 }
62114 return redirectTo
62115}
62116
62117Redirect.prototype.onResponse = function (response) {
62118 var self = this
62119 var request = self.request
62120
62121 var redirectTo = self.redirectTo(response)
62122 if (!redirectTo || !self.allowRedirect.call(request, response)) {
62123 return false
62124 }
62125
62126 request.debug('redirect to', redirectTo)
62127
62128 // ignore any potential response body. it cannot possibly be useful
62129 // to us at this point.
62130 // response.resume should be defined, but check anyway before calling. Workaround for browserify.
62131 if (response.resume) {
62132 response.resume()
62133 }
62134
62135 if (self.redirectsFollowed >= self.maxRedirects) {
62136 request.emit('error', new Error('Exceeded maxRedirects. Probably stuck in a redirect loop ' + request.uri.href))
62137 return false
62138 }
62139 self.redirectsFollowed += 1
62140
62141 if (!isUrl.test(redirectTo)) {
62142 redirectTo = url.resolve(request.uri.href, redirectTo)
62143 }
62144
62145 var uriPrev = request.uri
62146 request.uri = url.parse(redirectTo)
62147
62148 // handle the case where we change protocol from https to http or vice versa
62149 if (request.uri.protocol !== uriPrev.protocol) {
62150 delete request.agent
62151 }
62152
62153 self.redirects.push({ statusCode: response.statusCode, redirectUri: redirectTo })
62154
62155 if (self.followAllRedirects && request.method !== 'HEAD' &&
62156 response.statusCode !== 401 && response.statusCode !== 307) {
62157 request.method = self.followOriginalHttpMethod ? request.method : 'GET'
62158 }
62159 // request.method = 'GET' // Force all redirects to use GET || commented out fixes #215
62160 delete request.src
62161 delete request.req
62162 delete request._started
62163 if (response.statusCode !== 401 && response.statusCode !== 307) {
62164 // Remove parameters from the previous response, unless this is the second request
62165 // for a server that requires digest authentication.
62166 delete request.body
62167 delete request._form
62168 if (request.headers) {
62169 request.removeHeader('host')
62170 request.removeHeader('content-type')
62171 request.removeHeader('content-length')
62172 if (request.uri.hostname !== request.originalHost.split(':')[0]) {
62173 // Remove authorization if changing hostnames (but not if just
62174 // changing ports or protocols). This matches the behavior of curl:
62175 // https://github.com/bagder/curl/blob/6beb0eee/lib/http.c#L710
62176 request.removeHeader('authorization')
62177 }
62178 }
62179 }
62180
62181 if (!self.removeRefererHeader) {
62182 request.setHeader('referer', uriPrev.href)
62183 }
62184
62185 request.emit('redirect')
62186
62187 request.init()
62188
62189 return true
62190}
62191
62192exports.Redirect = Redirect
62193
62194},{"url":393}],310:[function(require,module,exports){
62195'use strict'
62196
62197var url = require('url')
62198var tunnel = require('tunnel-agent')
62199
62200var defaultProxyHeaderWhiteList = [
62201 'accept',
62202 'accept-charset',
62203 'accept-encoding',
62204 'accept-language',
62205 'accept-ranges',
62206 'cache-control',
62207 'content-encoding',
62208 'content-language',
62209 'content-location',
62210 'content-md5',
62211 'content-range',
62212 'content-type',
62213 'connection',
62214 'date',
62215 'expect',
62216 'max-forwards',
62217 'pragma',
62218 'referer',
62219 'te',
62220 'user-agent',
62221 'via'
62222]
62223
62224var defaultProxyHeaderExclusiveList = [
62225 'proxy-authorization'
62226]
62227
62228function constructProxyHost (uriObject) {
62229 var port = uriObject.port
62230 var protocol = uriObject.protocol
62231 var proxyHost = uriObject.hostname + ':'
62232
62233 if (port) {
62234 proxyHost += port
62235 } else if (protocol === 'https:') {
62236 proxyHost += '443'
62237 } else {
62238 proxyHost += '80'
62239 }
62240
62241 return proxyHost
62242}
62243
62244function constructProxyHeaderWhiteList (headers, proxyHeaderWhiteList) {
62245 var whiteList = proxyHeaderWhiteList
62246 .reduce(function (set, header) {
62247 set[header.toLowerCase()] = true
62248 return set
62249 }, {})
62250
62251 return Object.keys(headers)
62252 .filter(function (header) {
62253 return whiteList[header.toLowerCase()]
62254 })
62255 .reduce(function (set, header) {
62256 set[header] = headers[header]
62257 return set
62258 }, {})
62259}
62260
62261function constructTunnelOptions (request, proxyHeaders) {
62262 var proxy = request.proxy
62263
62264 var tunnelOptions = {
62265 proxy: {
62266 host: proxy.hostname,
62267 port: +proxy.port,
62268 proxyAuth: proxy.auth,
62269 headers: proxyHeaders
62270 },
62271 headers: request.headers,
62272 ca: request.ca,
62273 cert: request.cert,
62274 key: request.key,
62275 passphrase: request.passphrase,
62276 pfx: request.pfx,
62277 ciphers: request.ciphers,
62278 rejectUnauthorized: request.rejectUnauthorized,
62279 secureOptions: request.secureOptions,
62280 secureProtocol: request.secureProtocol
62281 }
62282
62283 return tunnelOptions
62284}
62285
62286function constructTunnelFnName (uri, proxy) {
62287 var uriProtocol = (uri.protocol === 'https:' ? 'https' : 'http')
62288 var proxyProtocol = (proxy.protocol === 'https:' ? 'Https' : 'Http')
62289 return [uriProtocol, proxyProtocol].join('Over')
62290}
62291
62292function getTunnelFn (request) {
62293 var uri = request.uri
62294 var proxy = request.proxy
62295 var tunnelFnName = constructTunnelFnName(uri, proxy)
62296 return tunnel[tunnelFnName]
62297}
62298
62299function Tunnel (request) {
62300 this.request = request
62301 this.proxyHeaderWhiteList = defaultProxyHeaderWhiteList
62302 this.proxyHeaderExclusiveList = []
62303 if (typeof request.tunnel !== 'undefined') {
62304 this.tunnelOverride = request.tunnel
62305 }
62306}
62307
62308Tunnel.prototype.isEnabled = function () {
62309 var self = this
62310 var request = self.request
62311 // Tunnel HTTPS by default. Allow the user to override this setting.
62312
62313 // If self.tunnelOverride is set (the user specified a value), use it.
62314 if (typeof self.tunnelOverride !== 'undefined') {
62315 return self.tunnelOverride
62316 }
62317
62318 // If the destination is HTTPS, tunnel.
62319 if (request.uri.protocol === 'https:') {
62320 return true
62321 }
62322
62323 // Otherwise, do not use tunnel.
62324 return false
62325}
62326
62327Tunnel.prototype.setup = function (options) {
62328 var self = this
62329 var request = self.request
62330
62331 options = options || {}
62332
62333 if (typeof request.proxy === 'string') {
62334 request.proxy = url.parse(request.proxy)
62335 }
62336
62337 if (!request.proxy || !request.tunnel) {
62338 return false
62339 }
62340
62341 // Setup Proxy Header Exclusive List and White List
62342 if (options.proxyHeaderWhiteList) {
62343 self.proxyHeaderWhiteList = options.proxyHeaderWhiteList
62344 }
62345 if (options.proxyHeaderExclusiveList) {
62346 self.proxyHeaderExclusiveList = options.proxyHeaderExclusiveList
62347 }
62348
62349 var proxyHeaderExclusiveList = self.proxyHeaderExclusiveList.concat(defaultProxyHeaderExclusiveList)
62350 var proxyHeaderWhiteList = self.proxyHeaderWhiteList.concat(proxyHeaderExclusiveList)
62351
62352 // Setup Proxy Headers and Proxy Headers Host
62353 // Only send the Proxy White Listed Header names
62354 var proxyHeaders = constructProxyHeaderWhiteList(request.headers, proxyHeaderWhiteList)
62355 proxyHeaders.host = constructProxyHost(request.uri)
62356
62357 proxyHeaderExclusiveList.forEach(request.removeHeader, request)
62358
62359 // Set Agent from Tunnel Data
62360 var tunnelFn = getTunnelFn(request)
62361 var tunnelOptions = constructTunnelOptions(request, proxyHeaders)
62362 request.agent = tunnelFn(tunnelOptions)
62363
62364 return true
62365}
62366
62367Tunnel.defaultProxyHeaderWhiteList = defaultProxyHeaderWhiteList
62368Tunnel.defaultProxyHeaderExclusiveList = defaultProxyHeaderExclusiveList
62369exports.Tunnel = Tunnel
62370
62371},{"tunnel-agent":390,"url":393}],311:[function(require,module,exports){
62372'use strict';
62373
62374var replace = String.prototype.replace;
62375var percentTwenties = /%20/g;
62376
62377module.exports = {
62378 'default': 'RFC3986',
62379 formatters: {
62380 RFC1738: function (value) {
62381 return replace.call(value, percentTwenties, '+');
62382 },
62383 RFC3986: function (value) {
62384 return value;
62385 }
62386 },
62387 RFC1738: 'RFC1738',
62388 RFC3986: 'RFC3986'
62389};
62390
62391},{}],312:[function(require,module,exports){
62392'use strict';
62393
62394var stringify = require('./stringify');
62395var parse = require('./parse');
62396var formats = require('./formats');
62397
62398module.exports = {
62399 formats: formats,
62400 parse: parse,
62401 stringify: stringify
62402};
62403
62404},{"./formats":311,"./parse":313,"./stringify":314}],313:[function(require,module,exports){
62405'use strict';
62406
62407var utils = require('./utils');
62408
62409var has = Object.prototype.hasOwnProperty;
62410
62411var defaults = {
62412 allowDots: false,
62413 allowPrototypes: false,
62414 arrayLimit: 20,
62415 decoder: utils.decode,
62416 delimiter: '&',
62417 depth: 5,
62418 parameterLimit: 1000,
62419 plainObjects: false,
62420 strictNullHandling: false
62421};
62422
62423var parseValues = function parseQueryStringValues(str, options) {
62424 var obj = {};
62425 var cleanStr = options.ignoreQueryPrefix ? str.replace(/^\?/, '') : str;
62426 var limit = options.parameterLimit === Infinity ? undefined : options.parameterLimit;
62427 var parts = cleanStr.split(options.delimiter, limit);
62428
62429 for (var i = 0; i < parts.length; ++i) {
62430 var part = parts[i];
62431
62432 var bracketEqualsPos = part.indexOf(']=');
62433 var pos = bracketEqualsPos === -1 ? part.indexOf('=') : bracketEqualsPos + 1;
62434
62435 var key, val;
62436 if (pos === -1) {
62437 key = options.decoder(part, defaults.decoder);
62438 val = options.strictNullHandling ? null : '';
62439 } else {
62440 key = options.decoder(part.slice(0, pos), defaults.decoder);
62441 val = options.decoder(part.slice(pos + 1), defaults.decoder);
62442 }
62443 if (has.call(obj, key)) {
62444 obj[key] = [].concat(obj[key]).concat(val);
62445 } else {
62446 obj[key] = val;
62447 }
62448 }
62449
62450 return obj;
62451};
62452
62453var parseObject = function (chain, val, options) {
62454 var leaf = val;
62455
62456 for (var i = chain.length - 1; i >= 0; --i) {
62457 var obj;
62458 var root = chain[i];
62459
62460 if (root === '[]') {
62461 obj = [];
62462 obj = obj.concat(leaf);
62463 } else {
62464 obj = options.plainObjects ? Object.create(null) : {};
62465 var cleanRoot = root.charAt(0) === '[' && root.charAt(root.length - 1) === ']' ? root.slice(1, -1) : root;
62466 var index = parseInt(cleanRoot, 10);
62467 if (
62468 !isNaN(index)
62469 && root !== cleanRoot
62470 && String(index) === cleanRoot
62471 && index >= 0
62472 && (options.parseArrays && index <= options.arrayLimit)
62473 ) {
62474 obj = [];
62475 obj[index] = leaf;
62476 } else {
62477 obj[cleanRoot] = leaf;
62478 }
62479 }
62480
62481 leaf = obj;
62482 }
62483
62484 return leaf;
62485};
62486
62487var parseKeys = function parseQueryStringKeys(givenKey, val, options) {
62488 if (!givenKey) {
62489 return;
62490 }
62491
62492 // Transform dot notation to bracket notation
62493 var key = options.allowDots ? givenKey.replace(/\.([^.[]+)/g, '[$1]') : givenKey;
62494
62495 // The regex chunks
62496
62497 var brackets = /(\[[^[\]]*])/;
62498 var child = /(\[[^[\]]*])/g;
62499
62500 // Get the parent
62501
62502 var segment = brackets.exec(key);
62503 var parent = segment ? key.slice(0, segment.index) : key;
62504
62505 // Stash the parent if it exists
62506
62507 var keys = [];
62508 if (parent) {
62509 // If we aren't using plain objects, optionally prefix keys
62510 // that would overwrite object prototype properties
62511 if (!options.plainObjects && has.call(Object.prototype, parent)) {
62512 if (!options.allowPrototypes) {
62513 return;
62514 }
62515 }
62516
62517 keys.push(parent);
62518 }
62519
62520 // Loop through children appending to the array until we hit depth
62521
62522 var i = 0;
62523 while ((segment = child.exec(key)) !== null && i < options.depth) {
62524 i += 1;
62525 if (!options.plainObjects && has.call(Object.prototype, segment[1].slice(1, -1))) {
62526 if (!options.allowPrototypes) {
62527 return;
62528 }
62529 }
62530 keys.push(segment[1]);
62531 }
62532
62533 // If there's a remainder, just add whatever is left
62534
62535 if (segment) {
62536 keys.push('[' + key.slice(segment.index) + ']');
62537 }
62538
62539 return parseObject(keys, val, options);
62540};
62541
62542module.exports = function (str, opts) {
62543 var options = opts ? utils.assign({}, opts) : {};
62544
62545 if (options.decoder !== null && options.decoder !== undefined && typeof options.decoder !== 'function') {
62546 throw new TypeError('Decoder has to be a function.');
62547 }
62548
62549 options.ignoreQueryPrefix = options.ignoreQueryPrefix === true;
62550 options.delimiter = typeof options.delimiter === 'string' || utils.isRegExp(options.delimiter) ? options.delimiter : defaults.delimiter;
62551 options.depth = typeof options.depth === 'number' ? options.depth : defaults.depth;
62552 options.arrayLimit = typeof options.arrayLimit === 'number' ? options.arrayLimit : defaults.arrayLimit;
62553 options.parseArrays = options.parseArrays !== false;
62554 options.decoder = typeof options.decoder === 'function' ? options.decoder : defaults.decoder;
62555 options.allowDots = typeof options.allowDots === 'boolean' ? options.allowDots : defaults.allowDots;
62556 options.plainObjects = typeof options.plainObjects === 'boolean' ? options.plainObjects : defaults.plainObjects;
62557 options.allowPrototypes = typeof options.allowPrototypes === 'boolean' ? options.allowPrototypes : defaults.allowPrototypes;
62558 options.parameterLimit = typeof options.parameterLimit === 'number' ? options.parameterLimit : defaults.parameterLimit;
62559 options.strictNullHandling = typeof options.strictNullHandling === 'boolean' ? options.strictNullHandling : defaults.strictNullHandling;
62560
62561 if (str === '' || str === null || typeof str === 'undefined') {
62562 return options.plainObjects ? Object.create(null) : {};
62563 }
62564
62565 var tempObj = typeof str === 'string' ? parseValues(str, options) : str;
62566 var obj = options.plainObjects ? Object.create(null) : {};
62567
62568 // Iterate over the keys and setup the new object
62569
62570 var keys = Object.keys(tempObj);
62571 for (var i = 0; i < keys.length; ++i) {
62572 var key = keys[i];
62573 var newObj = parseKeys(key, tempObj[key], options);
62574 obj = utils.merge(obj, newObj, options);
62575 }
62576
62577 return utils.compact(obj);
62578};
62579
62580},{"./utils":315}],314:[function(require,module,exports){
62581'use strict';
62582
62583var utils = require('./utils');
62584var formats = require('./formats');
62585
62586var arrayPrefixGenerators = {
62587 brackets: function brackets(prefix) { // eslint-disable-line func-name-matching
62588 return prefix + '[]';
62589 },
62590 indices: function indices(prefix, key) { // eslint-disable-line func-name-matching
62591 return prefix + '[' + key + ']';
62592 },
62593 repeat: function repeat(prefix) { // eslint-disable-line func-name-matching
62594 return prefix;
62595 }
62596};
62597
62598var toISO = Date.prototype.toISOString;
62599
62600var defaults = {
62601 delimiter: '&',
62602 encode: true,
62603 encoder: utils.encode,
62604 encodeValuesOnly: false,
62605 serializeDate: function serializeDate(date) { // eslint-disable-line func-name-matching
62606 return toISO.call(date);
62607 },
62608 skipNulls: false,
62609 strictNullHandling: false
62610};
62611
62612var stringify = function stringify( // eslint-disable-line func-name-matching
62613 object,
62614 prefix,
62615 generateArrayPrefix,
62616 strictNullHandling,
62617 skipNulls,
62618 encoder,
62619 filter,
62620 sort,
62621 allowDots,
62622 serializeDate,
62623 formatter,
62624 encodeValuesOnly
62625) {
62626 var obj = object;
62627 if (typeof filter === 'function') {
62628 obj = filter(prefix, obj);
62629 } else if (obj instanceof Date) {
62630 obj = serializeDate(obj);
62631 } else if (obj === null) {
62632 if (strictNullHandling) {
62633 return encoder && !encodeValuesOnly ? encoder(prefix, defaults.encoder) : prefix;
62634 }
62635
62636 obj = '';
62637 }
62638
62639 if (typeof obj === 'string' || typeof obj === 'number' || typeof obj === 'boolean' || utils.isBuffer(obj)) {
62640 if (encoder) {
62641 var keyValue = encodeValuesOnly ? prefix : encoder(prefix, defaults.encoder);
62642 return [formatter(keyValue) + '=' + formatter(encoder(obj, defaults.encoder))];
62643 }
62644 return [formatter(prefix) + '=' + formatter(String(obj))];
62645 }
62646
62647 var values = [];
62648
62649 if (typeof obj === 'undefined') {
62650 return values;
62651 }
62652
62653 var objKeys;
62654 if (Array.isArray(filter)) {
62655 objKeys = filter;
62656 } else {
62657 var keys = Object.keys(obj);
62658 objKeys = sort ? keys.sort(sort) : keys;
62659 }
62660
62661 for (var i = 0; i < objKeys.length; ++i) {
62662 var key = objKeys[i];
62663
62664 if (skipNulls && obj[key] === null) {
62665 continue;
62666 }
62667
62668 if (Array.isArray(obj)) {
62669 values = values.concat(stringify(
62670 obj[key],
62671 generateArrayPrefix(prefix, key),
62672 generateArrayPrefix,
62673 strictNullHandling,
62674 skipNulls,
62675 encoder,
62676 filter,
62677 sort,
62678 allowDots,
62679 serializeDate,
62680 formatter,
62681 encodeValuesOnly
62682 ));
62683 } else {
62684 values = values.concat(stringify(
62685 obj[key],
62686 prefix + (allowDots ? '.' + key : '[' + key + ']'),
62687 generateArrayPrefix,
62688 strictNullHandling,
62689 skipNulls,
62690 encoder,
62691 filter,
62692 sort,
62693 allowDots,
62694 serializeDate,
62695 formatter,
62696 encodeValuesOnly
62697 ));
62698 }
62699 }
62700
62701 return values;
62702};
62703
62704module.exports = function (object, opts) {
62705 var obj = object;
62706 var options = opts ? utils.assign({}, opts) : {};
62707
62708 if (options.encoder !== null && options.encoder !== undefined && typeof options.encoder !== 'function') {
62709 throw new TypeError('Encoder has to be a function.');
62710 }
62711
62712 var delimiter = typeof options.delimiter === 'undefined' ? defaults.delimiter : options.delimiter;
62713 var strictNullHandling = typeof options.strictNullHandling === 'boolean' ? options.strictNullHandling : defaults.strictNullHandling;
62714 var skipNulls = typeof options.skipNulls === 'boolean' ? options.skipNulls : defaults.skipNulls;
62715 var encode = typeof options.encode === 'boolean' ? options.encode : defaults.encode;
62716 var encoder = typeof options.encoder === 'function' ? options.encoder : defaults.encoder;
62717 var sort = typeof options.sort === 'function' ? options.sort : null;
62718 var allowDots = typeof options.allowDots === 'undefined' ? false : options.allowDots;
62719 var serializeDate = typeof options.serializeDate === 'function' ? options.serializeDate : defaults.serializeDate;
62720 var encodeValuesOnly = typeof options.encodeValuesOnly === 'boolean' ? options.encodeValuesOnly : defaults.encodeValuesOnly;
62721 if (typeof options.format === 'undefined') {
62722 options.format = formats['default'];
62723 } else if (!Object.prototype.hasOwnProperty.call(formats.formatters, options.format)) {
62724 throw new TypeError('Unknown format option provided.');
62725 }
62726 var formatter = formats.formatters[options.format];
62727 var objKeys;
62728 var filter;
62729
62730 if (typeof options.filter === 'function') {
62731 filter = options.filter;
62732 obj = filter('', obj);
62733 } else if (Array.isArray(options.filter)) {
62734 filter = options.filter;
62735 objKeys = filter;
62736 }
62737
62738 var keys = [];
62739
62740 if (typeof obj !== 'object' || obj === null) {
62741 return '';
62742 }
62743
62744 var arrayFormat;
62745 if (options.arrayFormat in arrayPrefixGenerators) {
62746 arrayFormat = options.arrayFormat;
62747 } else if ('indices' in options) {
62748 arrayFormat = options.indices ? 'indices' : 'repeat';
62749 } else {
62750 arrayFormat = 'indices';
62751 }
62752
62753 var generateArrayPrefix = arrayPrefixGenerators[arrayFormat];
62754
62755 if (!objKeys) {
62756 objKeys = Object.keys(obj);
62757 }
62758
62759 if (sort) {
62760 objKeys.sort(sort);
62761 }
62762
62763 for (var i = 0; i < objKeys.length; ++i) {
62764 var key = objKeys[i];
62765
62766 if (skipNulls && obj[key] === null) {
62767 continue;
62768 }
62769
62770 keys = keys.concat(stringify(
62771 obj[key],
62772 key,
62773 generateArrayPrefix,
62774 strictNullHandling,
62775 skipNulls,
62776 encode ? encoder : null,
62777 filter,
62778 sort,
62779 allowDots,
62780 serializeDate,
62781 formatter,
62782 encodeValuesOnly
62783 ));
62784 }
62785
62786 var joined = keys.join(delimiter);
62787 var prefix = options.addQueryPrefix === true ? '?' : '';
62788
62789 return joined.length > 0 ? prefix + joined : '';
62790};
62791
62792},{"./formats":311,"./utils":315}],315:[function(require,module,exports){
62793'use strict';
62794
62795var has = Object.prototype.hasOwnProperty;
62796
62797var hexTable = (function () {
62798 var array = [];
62799 for (var i = 0; i < 256; ++i) {
62800 array.push('%' + ((i < 16 ? '0' : '') + i.toString(16)).toUpperCase());
62801 }
62802
62803 return array;
62804}());
62805
62806var compactQueue = function compactQueue(queue) {
62807 var obj;
62808
62809 while (queue.length) {
62810 var item = queue.pop();
62811 obj = item.obj[item.prop];
62812
62813 if (Array.isArray(obj)) {
62814 var compacted = [];
62815
62816 for (var j = 0; j < obj.length; ++j) {
62817 if (typeof obj[j] !== 'undefined') {
62818 compacted.push(obj[j]);
62819 }
62820 }
62821
62822 item.obj[item.prop] = compacted;
62823 }
62824 }
62825
62826 return obj;
62827};
62828
62829var arrayToObject = function arrayToObject(source, options) {
62830 var obj = options && options.plainObjects ? Object.create(null) : {};
62831 for (var i = 0; i < source.length; ++i) {
62832 if (typeof source[i] !== 'undefined') {
62833 obj[i] = source[i];
62834 }
62835 }
62836
62837 return obj;
62838};
62839
62840var merge = function merge(target, source, options) {
62841 if (!source) {
62842 return target;
62843 }
62844
62845 if (typeof source !== 'object') {
62846 if (Array.isArray(target)) {
62847 target.push(source);
62848 } else if (typeof target === 'object') {
62849 if (options.plainObjects || options.allowPrototypes || !has.call(Object.prototype, source)) {
62850 target[source] = true;
62851 }
62852 } else {
62853 return [target, source];
62854 }
62855
62856 return target;
62857 }
62858
62859 if (typeof target !== 'object') {
62860 return [target].concat(source);
62861 }
62862
62863 var mergeTarget = target;
62864 if (Array.isArray(target) && !Array.isArray(source)) {
62865 mergeTarget = arrayToObject(target, options);
62866 }
62867
62868 if (Array.isArray(target) && Array.isArray(source)) {
62869 source.forEach(function (item, i) {
62870 if (has.call(target, i)) {
62871 if (target[i] && typeof target[i] === 'object') {
62872 target[i] = merge(target[i], item, options);
62873 } else {
62874 target.push(item);
62875 }
62876 } else {
62877 target[i] = item;
62878 }
62879 });
62880 return target;
62881 }
62882
62883 return Object.keys(source).reduce(function (acc, key) {
62884 var value = source[key];
62885
62886 if (has.call(acc, key)) {
62887 acc[key] = merge(acc[key], value, options);
62888 } else {
62889 acc[key] = value;
62890 }
62891 return acc;
62892 }, mergeTarget);
62893};
62894
62895var assign = function assignSingleSource(target, source) {
62896 return Object.keys(source).reduce(function (acc, key) {
62897 acc[key] = source[key];
62898 return acc;
62899 }, target);
62900};
62901
62902var decode = function (str) {
62903 try {
62904 return decodeURIComponent(str.replace(/\+/g, ' '));
62905 } catch (e) {
62906 return str;
62907 }
62908};
62909
62910var encode = function encode(str) {
62911 // This code was originally written by Brian White (mscdex) for the io.js core querystring library.
62912 // It has been adapted here for stricter adherence to RFC 3986
62913 if (str.length === 0) {
62914 return str;
62915 }
62916
62917 var string = typeof str === 'string' ? str : String(str);
62918
62919 var out = '';
62920 for (var i = 0; i < string.length; ++i) {
62921 var c = string.charCodeAt(i);
62922
62923 if (
62924 c === 0x2D // -
62925 || c === 0x2E // .
62926 || c === 0x5F // _
62927 || c === 0x7E // ~
62928 || (c >= 0x30 && c <= 0x39) // 0-9
62929 || (c >= 0x41 && c <= 0x5A) // a-z
62930 || (c >= 0x61 && c <= 0x7A) // A-Z
62931 ) {
62932 out += string.charAt(i);
62933 continue;
62934 }
62935
62936 if (c < 0x80) {
62937 out = out + hexTable[c];
62938 continue;
62939 }
62940
62941 if (c < 0x800) {
62942 out = out + (hexTable[0xC0 | (c >> 6)] + hexTable[0x80 | (c & 0x3F)]);
62943 continue;
62944 }
62945
62946 if (c < 0xD800 || c >= 0xE000) {
62947 out = out + (hexTable[0xE0 | (c >> 12)] + hexTable[0x80 | ((c >> 6) & 0x3F)] + hexTable[0x80 | (c & 0x3F)]);
62948 continue;
62949 }
62950
62951 i += 1;
62952 c = 0x10000 + (((c & 0x3FF) << 10) | (string.charCodeAt(i) & 0x3FF));
62953 out += hexTable[0xF0 | (c >> 18)]
62954 + hexTable[0x80 | ((c >> 12) & 0x3F)]
62955 + hexTable[0x80 | ((c >> 6) & 0x3F)]
62956 + hexTable[0x80 | (c & 0x3F)];
62957 }
62958
62959 return out;
62960};
62961
62962var compact = function compact(value) {
62963 var queue = [{ obj: { o: value }, prop: 'o' }];
62964 var refs = [];
62965
62966 for (var i = 0; i < queue.length; ++i) {
62967 var item = queue[i];
62968 var obj = item.obj[item.prop];
62969
62970 var keys = Object.keys(obj);
62971 for (var j = 0; j < keys.length; ++j) {
62972 var key = keys[j];
62973 var val = obj[key];
62974 if (typeof val === 'object' && val !== null && refs.indexOf(val) === -1) {
62975 queue.push({ obj: obj, prop: key });
62976 refs.push(val);
62977 }
62978 }
62979 }
62980
62981 return compactQueue(queue);
62982};
62983
62984var isRegExp = function isRegExp(obj) {
62985 return Object.prototype.toString.call(obj) === '[object RegExp]';
62986};
62987
62988var isBuffer = function isBuffer(obj) {
62989 if (obj === null || typeof obj === 'undefined') {
62990 return false;
62991 }
62992
62993 return !!(obj.constructor && obj.constructor.isBuffer && obj.constructor.isBuffer(obj));
62994};
62995
62996module.exports = {
62997 arrayToObject: arrayToObject,
62998 assign: assign,
62999 compact: compact,
63000 decode: decode,
63001 encode: encode,
63002 isBuffer: isBuffer,
63003 isRegExp: isRegExp,
63004 merge: merge
63005};
63006
63007},{}],316:[function(require,module,exports){
63008/*!
63009 * Copyright (c) 2015, Salesforce.com, Inc.
63010 * All rights reserved.
63011 *
63012 * Redistribution and use in source and binary forms, with or without
63013 * modification, are permitted provided that the following conditions are met:
63014 *
63015 * 1. Redistributions of source code must retain the above copyright notice,
63016 * this list of conditions and the following disclaimer.
63017 *
63018 * 2. Redistributions in binary form must reproduce the above copyright notice,
63019 * this list of conditions and the following disclaimer in the documentation
63020 * and/or other materials provided with the distribution.
63021 *
63022 * 3. Neither the name of Salesforce.com nor the names of its contributors may
63023 * be used to endorse or promote products derived from this software without
63024 * specific prior written permission.
63025 *
63026 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
63027 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
63028 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
63029 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
63030 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
63031 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
63032 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
63033 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
63034 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
63035 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
63036 * POSSIBILITY OF SUCH DAMAGE.
63037 */
63038'use strict';
63039var net = require('net');
63040var urlParse = require('url').parse;
63041var util = require('util');
63042var pubsuffix = require('./pubsuffix-psl');
63043var Store = require('./store').Store;
63044var MemoryCookieStore = require('./memstore').MemoryCookieStore;
63045var pathMatch = require('./pathMatch').pathMatch;
63046var VERSION = require('../package.json').version;
63047
63048var punycode;
63049try {
63050 punycode = require('punycode');
63051} catch(e) {
63052 console.warn("tough-cookie: can't load punycode; won't use punycode for domain normalization");
63053}
63054
63055// From RFC6265 S4.1.1
63056// note that it excludes \x3B ";"
63057var COOKIE_OCTETS = /^[\x21\x23-\x2B\x2D-\x3A\x3C-\x5B\x5D-\x7E]+$/;
63058
63059var CONTROL_CHARS = /[\x00-\x1F]/;
63060
63061// From Chromium // '\r', '\n' and '\0' should be treated as a terminator in
63062// the "relaxed" mode, see:
63063// https://github.com/ChromiumWebApps/chromium/blob/b3d3b4da8bb94c1b2e061600df106d590fda3620/net/cookies/parsed_cookie.cc#L60
63064var TERMINATORS = ['\n', '\r', '\0'];
63065
63066// RFC6265 S4.1.1 defines path value as 'any CHAR except CTLs or ";"'
63067// Note ';' is \x3B
63068var PATH_VALUE = /[\x20-\x3A\x3C-\x7E]+/;
63069
63070// date-time parsing constants (RFC6265 S5.1.1)
63071
63072var DATE_DELIM = /[\x09\x20-\x2F\x3B-\x40\x5B-\x60\x7B-\x7E]/;
63073
63074var MONTH_TO_NUM = {
63075 jan:0, feb:1, mar:2, apr:3, may:4, jun:5,
63076 jul:6, aug:7, sep:8, oct:9, nov:10, dec:11
63077};
63078var NUM_TO_MONTH = [
63079 'Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'
63080];
63081var NUM_TO_DAY = [
63082 'Sun','Mon','Tue','Wed','Thu','Fri','Sat'
63083];
63084
63085var MAX_TIME = 2147483647000; // 31-bit max
63086var MIN_TIME = 0; // 31-bit min
63087
63088/*
63089 * Parses a Natural number (i.e., non-negative integer) with either the
63090 * <min>*<max>DIGIT ( non-digit *OCTET )
63091 * or
63092 * <min>*<max>DIGIT
63093 * grammar (RFC6265 S5.1.1).
63094 *
63095 * The "trailingOK" boolean controls if the grammar accepts a
63096 * "( non-digit *OCTET )" trailer.
63097 */
63098function parseDigits(token, minDigits, maxDigits, trailingOK) {
63099 var count = 0;
63100 while (count < token.length) {
63101 var c = token.charCodeAt(count);
63102 // "non-digit = %x00-2F / %x3A-FF"
63103 if (c <= 0x2F || c >= 0x3A) {
63104 break;
63105 }
63106 count++;
63107 }
63108
63109 // constrain to a minimum and maximum number of digits.
63110 if (count < minDigits || count > maxDigits) {
63111 return null;
63112 }
63113
63114 if (!trailingOK && count != token.length) {
63115 return null;
63116 }
63117
63118 return parseInt(token.substr(0,count), 10);
63119}
63120
63121function parseTime(token) {
63122 var parts = token.split(':');
63123 var result = [0,0,0];
63124
63125 /* RF6256 S5.1.1:
63126 * time = hms-time ( non-digit *OCTET )
63127 * hms-time = time-field ":" time-field ":" time-field
63128 * time-field = 1*2DIGIT
63129 */
63130
63131 if (parts.length !== 3) {
63132 return null;
63133 }
63134
63135 for (var i = 0; i < 3; i++) {
63136 // "time-field" must be strictly "1*2DIGIT", HOWEVER, "hms-time" can be
63137 // followed by "( non-digit *OCTET )" so therefore the last time-field can
63138 // have a trailer
63139 var trailingOK = (i == 2);
63140 var num = parseDigits(parts[i], 1, 2, trailingOK);
63141 if (num === null) {
63142 return null;
63143 }
63144 result[i] = num;
63145 }
63146
63147 return result;
63148}
63149
63150function parseMonth(token) {
63151 token = String(token).substr(0,3).toLowerCase();
63152 var num = MONTH_TO_NUM[token];
63153 return num >= 0 ? num : null;
63154}
63155
63156/*
63157 * RFC6265 S5.1.1 date parser (see RFC for full grammar)
63158 */
63159function parseDate(str) {
63160 if (!str) {
63161 return;
63162 }
63163
63164 /* RFC6265 S5.1.1:
63165 * 2. Process each date-token sequentially in the order the date-tokens
63166 * appear in the cookie-date
63167 */
63168 var tokens = str.split(DATE_DELIM);
63169 if (!tokens) {
63170 return;
63171 }
63172
63173 var hour = null;
63174 var minute = null;
63175 var second = null;
63176 var dayOfMonth = null;
63177 var month = null;
63178 var year = null;
63179
63180 for (var i=0; i<tokens.length; i++) {
63181 var token = tokens[i].trim();
63182 if (!token.length) {
63183 continue;
63184 }
63185
63186 var result;
63187
63188 /* 2.1. If the found-time flag is not set and the token matches the time
63189 * production, set the found-time flag and set the hour- value,
63190 * minute-value, and second-value to the numbers denoted by the digits in
63191 * the date-token, respectively. Skip the remaining sub-steps and continue
63192 * to the next date-token.
63193 */
63194 if (second === null) {
63195 result = parseTime(token);
63196 if (result) {
63197 hour = result[0];
63198 minute = result[1];
63199 second = result[2];
63200 continue;
63201 }
63202 }
63203
63204 /* 2.2. If the found-day-of-month flag is not set and the date-token matches
63205 * the day-of-month production, set the found-day-of- month flag and set
63206 * the day-of-month-value to the number denoted by the date-token. Skip
63207 * the remaining sub-steps and continue to the next date-token.
63208 */
63209 if (dayOfMonth === null) {
63210 // "day-of-month = 1*2DIGIT ( non-digit *OCTET )"
63211 result = parseDigits(token, 1, 2, true);
63212 if (result !== null) {
63213 dayOfMonth = result;
63214 continue;
63215 }
63216 }
63217
63218 /* 2.3. If the found-month flag is not set and the date-token matches the
63219 * month production, set the found-month flag and set the month-value to
63220 * the month denoted by the date-token. Skip the remaining sub-steps and
63221 * continue to the next date-token.
63222 */
63223 if (month === null) {
63224 result = parseMonth(token);
63225 if (result !== null) {
63226 month = result;
63227 continue;
63228 }
63229 }
63230
63231 /* 2.4. If the found-year flag is not set and the date-token matches the
63232 * year production, set the found-year flag and set the year-value to the
63233 * number denoted by the date-token. Skip the remaining sub-steps and
63234 * continue to the next date-token.
63235 */
63236 if (year === null) {
63237 // "year = 2*4DIGIT ( non-digit *OCTET )"
63238 result = parseDigits(token, 2, 4, true);
63239 if (result !== null) {
63240 year = result;
63241 /* From S5.1.1:
63242 * 3. If the year-value is greater than or equal to 70 and less
63243 * than or equal to 99, increment the year-value by 1900.
63244 * 4. If the year-value is greater than or equal to 0 and less
63245 * than or equal to 69, increment the year-value by 2000.
63246 */
63247 if (year >= 70 && year <= 99) {
63248 year += 1900;
63249 } else if (year >= 0 && year <= 69) {
63250 year += 2000;
63251 }
63252 }
63253 }
63254 }
63255
63256 /* RFC 6265 S5.1.1
63257 * "5. Abort these steps and fail to parse the cookie-date if:
63258 * * at least one of the found-day-of-month, found-month, found-
63259 * year, or found-time flags is not set,
63260 * * the day-of-month-value is less than 1 or greater than 31,
63261 * * the year-value is less than 1601,
63262 * * the hour-value is greater than 23,
63263 * * the minute-value is greater than 59, or
63264 * * the second-value is greater than 59.
63265 * (Note that leap seconds cannot be represented in this syntax.)"
63266 *
63267 * So, in order as above:
63268 */
63269 if (
63270 dayOfMonth === null || month === null || year === null || second === null ||
63271 dayOfMonth < 1 || dayOfMonth > 31 ||
63272 year < 1601 ||
63273 hour > 23 ||
63274 minute > 59 ||
63275 second > 59
63276 ) {
63277 return;
63278 }
63279
63280 return new Date(Date.UTC(year, month, dayOfMonth, hour, minute, second));
63281}
63282
63283function formatDate(date) {
63284 var d = date.getUTCDate(); d = d >= 10 ? d : '0'+d;
63285 var h = date.getUTCHours(); h = h >= 10 ? h : '0'+h;
63286 var m = date.getUTCMinutes(); m = m >= 10 ? m : '0'+m;
63287 var s = date.getUTCSeconds(); s = s >= 10 ? s : '0'+s;
63288 return NUM_TO_DAY[date.getUTCDay()] + ', ' +
63289 d+' '+ NUM_TO_MONTH[date.getUTCMonth()] +' '+ date.getUTCFullYear() +' '+
63290 h+':'+m+':'+s+' GMT';
63291}
63292
63293// S5.1.2 Canonicalized Host Names
63294function canonicalDomain(str) {
63295 if (str == null) {
63296 return null;
63297 }
63298 str = str.trim().replace(/^\./,''); // S4.1.2.3 & S5.2.3: ignore leading .
63299
63300 // convert to IDN if any non-ASCII characters
63301 if (punycode && /[^\u0001-\u007f]/.test(str)) {
63302 str = punycode.toASCII(str);
63303 }
63304
63305 return str.toLowerCase();
63306}
63307
63308// S5.1.3 Domain Matching
63309function domainMatch(str, domStr, canonicalize) {
63310 if (str == null || domStr == null) {
63311 return null;
63312 }
63313 if (canonicalize !== false) {
63314 str = canonicalDomain(str);
63315 domStr = canonicalDomain(domStr);
63316 }
63317
63318 /*
63319 * "The domain string and the string are identical. (Note that both the
63320 * domain string and the string will have been canonicalized to lower case at
63321 * this point)"
63322 */
63323 if (str == domStr) {
63324 return true;
63325 }
63326
63327 /* "All of the following [three] conditions hold:" (order adjusted from the RFC) */
63328
63329 /* "* The string is a host name (i.e., not an IP address)." */
63330 if (net.isIP(str)) {
63331 return false;
63332 }
63333
63334 /* "* The domain string is a suffix of the string" */
63335 var idx = str.indexOf(domStr);
63336 if (idx <= 0) {
63337 return false; // it's a non-match (-1) or prefix (0)
63338 }
63339
63340 // e.g "a.b.c".indexOf("b.c") === 2
63341 // 5 === 3+2
63342 if (str.length !== domStr.length + idx) { // it's not a suffix
63343 return false;
63344 }
63345
63346 /* "* The last character of the string that is not included in the domain
63347 * string is a %x2E (".") character." */
63348 if (str.substr(idx-1,1) !== '.') {
63349 return false;
63350 }
63351
63352 return true;
63353}
63354
63355
63356// RFC6265 S5.1.4 Paths and Path-Match
63357
63358/*
63359 * "The user agent MUST use an algorithm equivalent to the following algorithm
63360 * to compute the default-path of a cookie:"
63361 *
63362 * Assumption: the path (and not query part or absolute uri) is passed in.
63363 */
63364function defaultPath(path) {
63365 // "2. If the uri-path is empty or if the first character of the uri-path is not
63366 // a %x2F ("/") character, output %x2F ("/") and skip the remaining steps.
63367 if (!path || path.substr(0,1) !== "/") {
63368 return "/";
63369 }
63370
63371 // "3. If the uri-path contains no more than one %x2F ("/") character, output
63372 // %x2F ("/") and skip the remaining step."
63373 if (path === "/") {
63374 return path;
63375 }
63376
63377 var rightSlash = path.lastIndexOf("/");
63378 if (rightSlash === 0) {
63379 return "/";
63380 }
63381
63382 // "4. Output the characters of the uri-path from the first character up to,
63383 // but not including, the right-most %x2F ("/")."
63384 return path.slice(0, rightSlash);
63385}
63386
63387function trimTerminator(str) {
63388 for (var t = 0; t < TERMINATORS.length; t++) {
63389 var terminatorIdx = str.indexOf(TERMINATORS[t]);
63390 if (terminatorIdx !== -1) {
63391 str = str.substr(0,terminatorIdx);
63392 }
63393 }
63394
63395 return str;
63396}
63397
63398function parseCookiePair(cookiePair, looseMode) {
63399 cookiePair = trimTerminator(cookiePair);
63400
63401 var firstEq = cookiePair.indexOf('=');
63402 if (looseMode) {
63403 if (firstEq === 0) { // '=' is immediately at start
63404 cookiePair = cookiePair.substr(1);
63405 firstEq = cookiePair.indexOf('='); // might still need to split on '='
63406 }
63407 } else { // non-loose mode
63408 if (firstEq <= 0) { // no '=' or is at start
63409 return; // needs to have non-empty "cookie-name"
63410 }
63411 }
63412
63413 var cookieName, cookieValue;
63414 if (firstEq <= 0) {
63415 cookieName = "";
63416 cookieValue = cookiePair.trim();
63417 } else {
63418 cookieName = cookiePair.substr(0, firstEq).trim();
63419 cookieValue = cookiePair.substr(firstEq+1).trim();
63420 }
63421
63422 if (CONTROL_CHARS.test(cookieName) || CONTROL_CHARS.test(cookieValue)) {
63423 return;
63424 }
63425
63426 var c = new Cookie();
63427 c.key = cookieName;
63428 c.value = cookieValue;
63429 return c;
63430}
63431
63432function parse(str, options) {
63433 if (!options || typeof options !== 'object') {
63434 options = {};
63435 }
63436 str = str.trim();
63437
63438 // We use a regex to parse the "name-value-pair" part of S5.2
63439 var firstSemi = str.indexOf(';'); // S5.2 step 1
63440 var cookiePair = (firstSemi === -1) ? str : str.substr(0, firstSemi);
63441 var c = parseCookiePair(cookiePair, !!options.loose);
63442 if (!c) {
63443 return;
63444 }
63445
63446 if (firstSemi === -1) {
63447 return c;
63448 }
63449
63450 // S5.2.3 "unparsed-attributes consist of the remainder of the set-cookie-string
63451 // (including the %x3B (";") in question)." plus later on in the same section
63452 // "discard the first ";" and trim".
63453 var unparsed = str.slice(firstSemi + 1).trim();
63454
63455 // "If the unparsed-attributes string is empty, skip the rest of these
63456 // steps."
63457 if (unparsed.length === 0) {
63458 return c;
63459 }
63460
63461 /*
63462 * S5.2 says that when looping over the items "[p]rocess the attribute-name
63463 * and attribute-value according to the requirements in the following
63464 * subsections" for every item. Plus, for many of the individual attributes
63465 * in S5.3 it says to use the "attribute-value of the last attribute in the
63466 * cookie-attribute-list". Therefore, in this implementation, we overwrite
63467 * the previous value.
63468 */
63469 var cookie_avs = unparsed.split(';');
63470 while (cookie_avs.length) {
63471 var av = cookie_avs.shift().trim();
63472 if (av.length === 0) { // happens if ";;" appears
63473 continue;
63474 }
63475 var av_sep = av.indexOf('=');
63476 var av_key, av_value;
63477
63478 if (av_sep === -1) {
63479 av_key = av;
63480 av_value = null;
63481 } else {
63482 av_key = av.substr(0,av_sep);
63483 av_value = av.substr(av_sep+1);
63484 }
63485
63486 av_key = av_key.trim().toLowerCase();
63487
63488 if (av_value) {
63489 av_value = av_value.trim();
63490 }
63491
63492 switch(av_key) {
63493 case 'expires': // S5.2.1
63494 if (av_value) {
63495 var exp = parseDate(av_value);
63496 // "If the attribute-value failed to parse as a cookie date, ignore the
63497 // cookie-av."
63498 if (exp) {
63499 // over and underflow not realistically a concern: V8's getTime() seems to
63500 // store something larger than a 32-bit time_t (even with 32-bit node)
63501 c.expires = exp;
63502 }
63503 }
63504 break;
63505
63506 case 'max-age': // S5.2.2
63507 if (av_value) {
63508 // "If the first character of the attribute-value is not a DIGIT or a "-"
63509 // character ...[or]... If the remainder of attribute-value contains a
63510 // non-DIGIT character, ignore the cookie-av."
63511 if (/^-?[0-9]+$/.test(av_value)) {
63512 var delta = parseInt(av_value, 10);
63513 // "If delta-seconds is less than or equal to zero (0), let expiry-time
63514 // be the earliest representable date and time."
63515 c.setMaxAge(delta);
63516 }
63517 }
63518 break;
63519
63520 case 'domain': // S5.2.3
63521 // "If the attribute-value is empty, the behavior is undefined. However,
63522 // the user agent SHOULD ignore the cookie-av entirely."
63523 if (av_value) {
63524 // S5.2.3 "Let cookie-domain be the attribute-value without the leading %x2E
63525 // (".") character."
63526 var domain = av_value.trim().replace(/^\./, '');
63527 if (domain) {
63528 // "Convert the cookie-domain to lower case."
63529 c.domain = domain.toLowerCase();
63530 }
63531 }
63532 break;
63533
63534 case 'path': // S5.2.4
63535 /*
63536 * "If the attribute-value is empty or if the first character of the
63537 * attribute-value is not %x2F ("/"):
63538 * Let cookie-path be the default-path.
63539 * Otherwise:
63540 * Let cookie-path be the attribute-value."
63541 *
63542 * We'll represent the default-path as null since it depends on the
63543 * context of the parsing.
63544 */
63545 c.path = av_value && av_value[0] === "/" ? av_value : null;
63546 break;
63547
63548 case 'secure': // S5.2.5
63549 /*
63550 * "If the attribute-name case-insensitively matches the string "Secure",
63551 * the user agent MUST append an attribute to the cookie-attribute-list
63552 * with an attribute-name of Secure and an empty attribute-value."
63553 */
63554 c.secure = true;
63555 break;
63556
63557 case 'httponly': // S5.2.6 -- effectively the same as 'secure'
63558 c.httpOnly = true;
63559 break;
63560
63561 default:
63562 c.extensions = c.extensions || [];
63563 c.extensions.push(av);
63564 break;
63565 }
63566 }
63567
63568 return c;
63569}
63570
63571// avoid the V8 deoptimization monster!
63572function jsonParse(str) {
63573 var obj;
63574 try {
63575 obj = JSON.parse(str);
63576 } catch (e) {
63577 return e;
63578 }
63579 return obj;
63580}
63581
63582function fromJSON(str) {
63583 if (!str) {
63584 return null;
63585 }
63586
63587 var obj;
63588 if (typeof str === 'string') {
63589 obj = jsonParse(str);
63590 if (obj instanceof Error) {
63591 return null;
63592 }
63593 } else {
63594 // assume it's an Object
63595 obj = str;
63596 }
63597
63598 var c = new Cookie();
63599 for (var i=0; i<Cookie.serializableProperties.length; i++) {
63600 var prop = Cookie.serializableProperties[i];
63601 if (obj[prop] === undefined ||
63602 obj[prop] === Cookie.prototype[prop])
63603 {
63604 continue; // leave as prototype default
63605 }
63606
63607 if (prop === 'expires' ||
63608 prop === 'creation' ||
63609 prop === 'lastAccessed')
63610 {
63611 if (obj[prop] === null) {
63612 c[prop] = null;
63613 } else {
63614 c[prop] = obj[prop] == "Infinity" ?
63615 "Infinity" : new Date(obj[prop]);
63616 }
63617 } else {
63618 c[prop] = obj[prop];
63619 }
63620 }
63621
63622 return c;
63623}
63624
63625/* Section 5.4 part 2:
63626 * "* Cookies with longer paths are listed before cookies with
63627 * shorter paths.
63628 *
63629 * * Among cookies that have equal-length path fields, cookies with
63630 * earlier creation-times are listed before cookies with later
63631 * creation-times."
63632 */
63633
63634function cookieCompare(a,b) {
63635 var cmp = 0;
63636
63637 // descending for length: b CMP a
63638 var aPathLen = a.path ? a.path.length : 0;
63639 var bPathLen = b.path ? b.path.length : 0;
63640 cmp = bPathLen - aPathLen;
63641 if (cmp !== 0) {
63642 return cmp;
63643 }
63644
63645 // ascending for time: a CMP b
63646 var aTime = a.creation ? a.creation.getTime() : MAX_TIME;
63647 var bTime = b.creation ? b.creation.getTime() : MAX_TIME;
63648 cmp = aTime - bTime;
63649 if (cmp !== 0) {
63650 return cmp;
63651 }
63652
63653 // break ties for the same millisecond (precision of JavaScript's clock)
63654 cmp = a.creationIndex - b.creationIndex;
63655
63656 return cmp;
63657}
63658
63659// Gives the permutation of all possible pathMatch()es of a given path. The
63660// array is in longest-to-shortest order. Handy for indexing.
63661function permutePath(path) {
63662 if (path === '/') {
63663 return ['/'];
63664 }
63665 if (path.lastIndexOf('/') === path.length-1) {
63666 path = path.substr(0,path.length-1);
63667 }
63668 var permutations = [path];
63669 while (path.length > 1) {
63670 var lindex = path.lastIndexOf('/');
63671 if (lindex === 0) {
63672 break;
63673 }
63674 path = path.substr(0,lindex);
63675 permutations.push(path);
63676 }
63677 permutations.push('/');
63678 return permutations;
63679}
63680
63681function getCookieContext(url) {
63682 if (url instanceof Object) {
63683 return url;
63684 }
63685 // NOTE: decodeURI will throw on malformed URIs (see GH-32).
63686 // Therefore, we will just skip decoding for such URIs.
63687 try {
63688 url = decodeURI(url);
63689 }
63690 catch(err) {
63691 // Silently swallow error
63692 }
63693
63694 return urlParse(url);
63695}
63696
63697function Cookie(options) {
63698 options = options || {};
63699
63700 Object.keys(options).forEach(function(prop) {
63701 if (Cookie.prototype.hasOwnProperty(prop) &&
63702 Cookie.prototype[prop] !== options[prop] &&
63703 prop.substr(0,1) !== '_')
63704 {
63705 this[prop] = options[prop];
63706 }
63707 }, this);
63708
63709 this.creation = this.creation || new Date();
63710
63711 // used to break creation ties in cookieCompare():
63712 Object.defineProperty(this, 'creationIndex', {
63713 configurable: false,
63714 enumerable: false, // important for assert.deepEqual checks
63715 writable: true,
63716 value: ++Cookie.cookiesCreated
63717 });
63718}
63719
63720Cookie.cookiesCreated = 0; // incremented each time a cookie is created
63721
63722Cookie.parse = parse;
63723Cookie.fromJSON = fromJSON;
63724
63725Cookie.prototype.key = "";
63726Cookie.prototype.value = "";
63727
63728// the order in which the RFC has them:
63729Cookie.prototype.expires = "Infinity"; // coerces to literal Infinity
63730Cookie.prototype.maxAge = null; // takes precedence over expires for TTL
63731Cookie.prototype.domain = null;
63732Cookie.prototype.path = null;
63733Cookie.prototype.secure = false;
63734Cookie.prototype.httpOnly = false;
63735Cookie.prototype.extensions = null;
63736
63737// set by the CookieJar:
63738Cookie.prototype.hostOnly = null; // boolean when set
63739Cookie.prototype.pathIsDefault = null; // boolean when set
63740Cookie.prototype.creation = null; // Date when set; defaulted by Cookie.parse
63741Cookie.prototype.lastAccessed = null; // Date when set
63742Object.defineProperty(Cookie.prototype, 'creationIndex', {
63743 configurable: true,
63744 enumerable: false,
63745 writable: true,
63746 value: 0
63747});
63748
63749Cookie.serializableProperties = Object.keys(Cookie.prototype)
63750 .filter(function(prop) {
63751 return !(
63752 Cookie.prototype[prop] instanceof Function ||
63753 prop === 'creationIndex' ||
63754 prop.substr(0,1) === '_'
63755 );
63756 });
63757
63758Cookie.prototype.inspect = function inspect() {
63759 var now = Date.now();
63760 return 'Cookie="'+this.toString() +
63761 '; hostOnly='+(this.hostOnly != null ? this.hostOnly : '?') +
63762 '; aAge='+(this.lastAccessed ? (now-this.lastAccessed.getTime())+'ms' : '?') +
63763 '; cAge='+(this.creation ? (now-this.creation.getTime())+'ms' : '?') +
63764 '"';
63765};
63766
63767// Use the new custom inspection symbol to add the custom inspect function if
63768// available.
63769if (util.inspect.custom) {
63770 Cookie.prototype[util.inspect.custom] = Cookie.prototype.inspect;
63771}
63772
63773Cookie.prototype.toJSON = function() {
63774 var obj = {};
63775
63776 var props = Cookie.serializableProperties;
63777 for (var i=0; i<props.length; i++) {
63778 var prop = props[i];
63779 if (this[prop] === Cookie.prototype[prop]) {
63780 continue; // leave as prototype default
63781 }
63782
63783 if (prop === 'expires' ||
63784 prop === 'creation' ||
63785 prop === 'lastAccessed')
63786 {
63787 if (this[prop] === null) {
63788 obj[prop] = null;
63789 } else {
63790 obj[prop] = this[prop] == "Infinity" ? // intentionally not ===
63791 "Infinity" : this[prop].toISOString();
63792 }
63793 } else if (prop === 'maxAge') {
63794 if (this[prop] !== null) {
63795 // again, intentionally not ===
63796 obj[prop] = (this[prop] == Infinity || this[prop] == -Infinity) ?
63797 this[prop].toString() : this[prop];
63798 }
63799 } else {
63800 if (this[prop] !== Cookie.prototype[prop]) {
63801 obj[prop] = this[prop];
63802 }
63803 }
63804 }
63805
63806 return obj;
63807};
63808
63809Cookie.prototype.clone = function() {
63810 return fromJSON(this.toJSON());
63811};
63812
63813Cookie.prototype.validate = function validate() {
63814 if (!COOKIE_OCTETS.test(this.value)) {
63815 return false;
63816 }
63817 if (this.expires != Infinity && !(this.expires instanceof Date) && !parseDate(this.expires)) {
63818 return false;
63819 }
63820 if (this.maxAge != null && this.maxAge <= 0) {
63821 return false; // "Max-Age=" non-zero-digit *DIGIT
63822 }
63823 if (this.path != null && !PATH_VALUE.test(this.path)) {
63824 return false;
63825 }
63826
63827 var cdomain = this.cdomain();
63828 if (cdomain) {
63829 if (cdomain.match(/\.$/)) {
63830 return false; // S4.1.2.3 suggests that this is bad. domainMatch() tests confirm this
63831 }
63832 var suffix = pubsuffix.getPublicSuffix(cdomain);
63833 if (suffix == null) { // it's a public suffix
63834 return false;
63835 }
63836 }
63837 return true;
63838};
63839
63840Cookie.prototype.setExpires = function setExpires(exp) {
63841 if (exp instanceof Date) {
63842 this.expires = exp;
63843 } else {
63844 this.expires = parseDate(exp) || "Infinity";
63845 }
63846};
63847
63848Cookie.prototype.setMaxAge = function setMaxAge(age) {
63849 if (age === Infinity || age === -Infinity) {
63850 this.maxAge = age.toString(); // so JSON.stringify() works
63851 } else {
63852 this.maxAge = age;
63853 }
63854};
63855
63856// gives Cookie header format
63857Cookie.prototype.cookieString = function cookieString() {
63858 var val = this.value;
63859 if (val == null) {
63860 val = '';
63861 }
63862 if (this.key === '') {
63863 return val;
63864 }
63865 return this.key+'='+val;
63866};
63867
63868// gives Set-Cookie header format
63869Cookie.prototype.toString = function toString() {
63870 var str = this.cookieString();
63871
63872 if (this.expires != Infinity) {
63873 if (this.expires instanceof Date) {
63874 str += '; Expires='+formatDate(this.expires);
63875 } else {
63876 str += '; Expires='+this.expires;
63877 }
63878 }
63879
63880 if (this.maxAge != null && this.maxAge != Infinity) {
63881 str += '; Max-Age='+this.maxAge;
63882 }
63883
63884 if (this.domain && !this.hostOnly) {
63885 str += '; Domain='+this.domain;
63886 }
63887 if (this.path) {
63888 str += '; Path='+this.path;
63889 }
63890
63891 if (this.secure) {
63892 str += '; Secure';
63893 }
63894 if (this.httpOnly) {
63895 str += '; HttpOnly';
63896 }
63897 if (this.extensions) {
63898 this.extensions.forEach(function(ext) {
63899 str += '; '+ext;
63900 });
63901 }
63902
63903 return str;
63904};
63905
63906// TTL() partially replaces the "expiry-time" parts of S5.3 step 3 (setCookie()
63907// elsewhere)
63908// S5.3 says to give the "latest representable date" for which we use Infinity
63909// For "expired" we use 0
63910Cookie.prototype.TTL = function TTL(now) {
63911 /* RFC6265 S4.1.2.2 If a cookie has both the Max-Age and the Expires
63912 * attribute, the Max-Age attribute has precedence and controls the
63913 * expiration date of the cookie.
63914 * (Concurs with S5.3 step 3)
63915 */
63916 if (this.maxAge != null) {
63917 return this.maxAge<=0 ? 0 : this.maxAge*1000;
63918 }
63919
63920 var expires = this.expires;
63921 if (expires != Infinity) {
63922 if (!(expires instanceof Date)) {
63923 expires = parseDate(expires) || Infinity;
63924 }
63925
63926 if (expires == Infinity) {
63927 return Infinity;
63928 }
63929
63930 return expires.getTime() - (now || Date.now());
63931 }
63932
63933 return Infinity;
63934};
63935
63936// expiryTime() replaces the "expiry-time" parts of S5.3 step 3 (setCookie()
63937// elsewhere)
63938Cookie.prototype.expiryTime = function expiryTime(now) {
63939 if (this.maxAge != null) {
63940 var relativeTo = now || this.creation || new Date();
63941 var age = (this.maxAge <= 0) ? -Infinity : this.maxAge*1000;
63942 return relativeTo.getTime() + age;
63943 }
63944
63945 if (this.expires == Infinity) {
63946 return Infinity;
63947 }
63948 return this.expires.getTime();
63949};
63950
63951// expiryDate() replaces the "expiry-time" parts of S5.3 step 3 (setCookie()
63952// elsewhere), except it returns a Date
63953Cookie.prototype.expiryDate = function expiryDate(now) {
63954 var millisec = this.expiryTime(now);
63955 if (millisec == Infinity) {
63956 return new Date(MAX_TIME);
63957 } else if (millisec == -Infinity) {
63958 return new Date(MIN_TIME);
63959 } else {
63960 return new Date(millisec);
63961 }
63962};
63963
63964// This replaces the "persistent-flag" parts of S5.3 step 3
63965Cookie.prototype.isPersistent = function isPersistent() {
63966 return (this.maxAge != null || this.expires != Infinity);
63967};
63968
63969// Mostly S5.1.2 and S5.2.3:
63970Cookie.prototype.cdomain =
63971Cookie.prototype.canonicalizedDomain = function canonicalizedDomain() {
63972 if (this.domain == null) {
63973 return null;
63974 }
63975 return canonicalDomain(this.domain);
63976};
63977
63978function CookieJar(store, options) {
63979 if (typeof options === "boolean") {
63980 options = {rejectPublicSuffixes: options};
63981 } else if (options == null) {
63982 options = {};
63983 }
63984 if (options.rejectPublicSuffixes != null) {
63985 this.rejectPublicSuffixes = options.rejectPublicSuffixes;
63986 }
63987 if (options.looseMode != null) {
63988 this.enableLooseMode = options.looseMode;
63989 }
63990
63991 if (!store) {
63992 store = new MemoryCookieStore();
63993 }
63994 this.store = store;
63995}
63996CookieJar.prototype.store = null;
63997CookieJar.prototype.rejectPublicSuffixes = true;
63998CookieJar.prototype.enableLooseMode = false;
63999var CAN_BE_SYNC = [];
64000
64001CAN_BE_SYNC.push('setCookie');
64002CookieJar.prototype.setCookie = function(cookie, url, options, cb) {
64003 var err;
64004 var context = getCookieContext(url);
64005 if (options instanceof Function) {
64006 cb = options;
64007 options = {};
64008 }
64009
64010 var host = canonicalDomain(context.hostname);
64011 var loose = this.enableLooseMode;
64012 if (options.loose != null) {
64013 loose = options.loose;
64014 }
64015
64016 // S5.3 step 1
64017 if (!(cookie instanceof Cookie)) {
64018 cookie = Cookie.parse(cookie, { loose: loose });
64019 }
64020 if (!cookie) {
64021 err = new Error("Cookie failed to parse");
64022 return cb(options.ignoreError ? null : err);
64023 }
64024
64025 // S5.3 step 2
64026 var now = options.now || new Date(); // will assign later to save effort in the face of errors
64027
64028 // S5.3 step 3: NOOP; persistent-flag and expiry-time is handled by getCookie()
64029
64030 // S5.3 step 4: NOOP; domain is null by default
64031
64032 // S5.3 step 5: public suffixes
64033 if (this.rejectPublicSuffixes && cookie.domain) {
64034 var suffix = pubsuffix.getPublicSuffix(cookie.cdomain());
64035 if (suffix == null) { // e.g. "com"
64036 err = new Error("Cookie has domain set to a public suffix");
64037 return cb(options.ignoreError ? null : err);
64038 }
64039 }
64040
64041 // S5.3 step 6:
64042 if (cookie.domain) {
64043 if (!domainMatch(host, cookie.cdomain(), false)) {
64044 err = new Error("Cookie not in this host's domain. Cookie:"+cookie.cdomain()+" Request:"+host);
64045 return cb(options.ignoreError ? null : err);
64046 }
64047
64048 if (cookie.hostOnly == null) { // don't reset if already set
64049 cookie.hostOnly = false;
64050 }
64051
64052 } else {
64053 cookie.hostOnly = true;
64054 cookie.domain = host;
64055 }
64056
64057 //S5.2.4 If the attribute-value is empty or if the first character of the
64058 //attribute-value is not %x2F ("/"):
64059 //Let cookie-path be the default-path.
64060 if (!cookie.path || cookie.path[0] !== '/') {
64061 cookie.path = defaultPath(context.pathname);
64062 cookie.pathIsDefault = true;
64063 }
64064
64065 // S5.3 step 8: NOOP; secure attribute
64066 // S5.3 step 9: NOOP; httpOnly attribute
64067
64068 // S5.3 step 10
64069 if (options.http === false && cookie.httpOnly) {
64070 err = new Error("Cookie is HttpOnly and this isn't an HTTP API");
64071 return cb(options.ignoreError ? null : err);
64072 }
64073
64074 var store = this.store;
64075
64076 if (!store.updateCookie) {
64077 store.updateCookie = function(oldCookie, newCookie, cb) {
64078 this.putCookie(newCookie, cb);
64079 };
64080 }
64081
64082 function withCookie(err, oldCookie) {
64083 if (err) {
64084 return cb(err);
64085 }
64086
64087 var next = function(err) {
64088 if (err) {
64089 return cb(err);
64090 } else {
64091 cb(null, cookie);
64092 }
64093 };
64094
64095 if (oldCookie) {
64096 // S5.3 step 11 - "If the cookie store contains a cookie with the same name,
64097 // domain, and path as the newly created cookie:"
64098 if (options.http === false && oldCookie.httpOnly) { // step 11.2
64099 err = new Error("old Cookie is HttpOnly and this isn't an HTTP API");
64100 return cb(options.ignoreError ? null : err);
64101 }
64102 cookie.creation = oldCookie.creation; // step 11.3
64103 cookie.creationIndex = oldCookie.creationIndex; // preserve tie-breaker
64104 cookie.lastAccessed = now;
64105 // Step 11.4 (delete cookie) is implied by just setting the new one:
64106 store.updateCookie(oldCookie, cookie, next); // step 12
64107
64108 } else {
64109 cookie.creation = cookie.lastAccessed = now;
64110 store.putCookie(cookie, next); // step 12
64111 }
64112 }
64113
64114 store.findCookie(cookie.domain, cookie.path, cookie.key, withCookie);
64115};
64116
64117// RFC6365 S5.4
64118CAN_BE_SYNC.push('getCookies');
64119CookieJar.prototype.getCookies = function(url, options, cb) {
64120 var context = getCookieContext(url);
64121 if (options instanceof Function) {
64122 cb = options;
64123 options = {};
64124 }
64125
64126 var host = canonicalDomain(context.hostname);
64127 var path = context.pathname || '/';
64128
64129 var secure = options.secure;
64130 if (secure == null && context.protocol &&
64131 (context.protocol == 'https:' || context.protocol == 'wss:'))
64132 {
64133 secure = true;
64134 }
64135
64136 var http = options.http;
64137 if (http == null) {
64138 http = true;
64139 }
64140
64141 var now = options.now || Date.now();
64142 var expireCheck = options.expire !== false;
64143 var allPaths = !!options.allPaths;
64144 var store = this.store;
64145
64146 function matchingCookie(c) {
64147 // "Either:
64148 // The cookie's host-only-flag is true and the canonicalized
64149 // request-host is identical to the cookie's domain.
64150 // Or:
64151 // The cookie's host-only-flag is false and the canonicalized
64152 // request-host domain-matches the cookie's domain."
64153 if (c.hostOnly) {
64154 if (c.domain != host) {
64155 return false;
64156 }
64157 } else {
64158 if (!domainMatch(host, c.domain, false)) {
64159 return false;
64160 }
64161 }
64162
64163 // "The request-uri's path path-matches the cookie's path."
64164 if (!allPaths && !pathMatch(path, c.path)) {
64165 return false;
64166 }
64167
64168 // "If the cookie's secure-only-flag is true, then the request-uri's
64169 // scheme must denote a "secure" protocol"
64170 if (c.secure && !secure) {
64171 return false;
64172 }
64173
64174 // "If the cookie's http-only-flag is true, then exclude the cookie if the
64175 // cookie-string is being generated for a "non-HTTP" API"
64176 if (c.httpOnly && !http) {
64177 return false;
64178 }
64179
64180 // deferred from S5.3
64181 // non-RFC: allow retention of expired cookies by choice
64182 if (expireCheck && c.expiryTime() <= now) {
64183 store.removeCookie(c.domain, c.path, c.key, function(){}); // result ignored
64184 return false;
64185 }
64186
64187 return true;
64188 }
64189
64190 store.findCookies(host, allPaths ? null : path, function(err,cookies) {
64191 if (err) {
64192 return cb(err);
64193 }
64194
64195 cookies = cookies.filter(matchingCookie);
64196
64197 // sorting of S5.4 part 2
64198 if (options.sort !== false) {
64199 cookies = cookies.sort(cookieCompare);
64200 }
64201
64202 // S5.4 part 3
64203 var now = new Date();
64204 cookies.forEach(function(c) {
64205 c.lastAccessed = now;
64206 });
64207 // TODO persist lastAccessed
64208
64209 cb(null,cookies);
64210 });
64211};
64212
64213CAN_BE_SYNC.push('getCookieString');
64214CookieJar.prototype.getCookieString = function(/*..., cb*/) {
64215 var args = Array.prototype.slice.call(arguments,0);
64216 var cb = args.pop();
64217 var next = function(err,cookies) {
64218 if (err) {
64219 cb(err);
64220 } else {
64221 cb(null, cookies
64222 .sort(cookieCompare)
64223 .map(function(c){
64224 return c.cookieString();
64225 })
64226 .join('; '));
64227 }
64228 };
64229 args.push(next);
64230 this.getCookies.apply(this,args);
64231};
64232
64233CAN_BE_SYNC.push('getSetCookieStrings');
64234CookieJar.prototype.getSetCookieStrings = function(/*..., cb*/) {
64235 var args = Array.prototype.slice.call(arguments,0);
64236 var cb = args.pop();
64237 var next = function(err,cookies) {
64238 if (err) {
64239 cb(err);
64240 } else {
64241 cb(null, cookies.map(function(c){
64242 return c.toString();
64243 }));
64244 }
64245 };
64246 args.push(next);
64247 this.getCookies.apply(this,args);
64248};
64249
64250CAN_BE_SYNC.push('serialize');
64251CookieJar.prototype.serialize = function(cb) {
64252 var type = this.store.constructor.name;
64253 if (type === 'Object') {
64254 type = null;
64255 }
64256
64257 // update README.md "Serialization Format" if you change this, please!
64258 var serialized = {
64259 // The version of tough-cookie that serialized this jar. Generally a good
64260 // practice since future versions can make data import decisions based on
64261 // known past behavior. When/if this matters, use `semver`.
64262 version: 'tough-cookie@'+VERSION,
64263
64264 // add the store type, to make humans happy:
64265 storeType: type,
64266
64267 // CookieJar configuration:
64268 rejectPublicSuffixes: !!this.rejectPublicSuffixes,
64269
64270 // this gets filled from getAllCookies:
64271 cookies: []
64272 };
64273
64274 if (!(this.store.getAllCookies &&
64275 typeof this.store.getAllCookies === 'function'))
64276 {
64277 return cb(new Error('store does not support getAllCookies and cannot be serialized'));
64278 }
64279
64280 this.store.getAllCookies(function(err,cookies) {
64281 if (err) {
64282 return cb(err);
64283 }
64284
64285 serialized.cookies = cookies.map(function(cookie) {
64286 // convert to serialized 'raw' cookies
64287 cookie = (cookie instanceof Cookie) ? cookie.toJSON() : cookie;
64288
64289 // Remove the index so new ones get assigned during deserialization
64290 delete cookie.creationIndex;
64291
64292 return cookie;
64293 });
64294
64295 return cb(null, serialized);
64296 });
64297};
64298
64299// well-known name that JSON.stringify calls
64300CookieJar.prototype.toJSON = function() {
64301 return this.serializeSync();
64302};
64303
64304// use the class method CookieJar.deserialize instead of calling this directly
64305CAN_BE_SYNC.push('_importCookies');
64306CookieJar.prototype._importCookies = function(serialized, cb) {
64307 var jar = this;
64308 var cookies = serialized.cookies;
64309 if (!cookies || !Array.isArray(cookies)) {
64310 return cb(new Error('serialized jar has no cookies array'));
64311 }
64312 cookies = cookies.slice(); // do not modify the original
64313
64314 function putNext(err) {
64315 if (err) {
64316 return cb(err);
64317 }
64318
64319 if (!cookies.length) {
64320 return cb(err, jar);
64321 }
64322
64323 var cookie;
64324 try {
64325 cookie = fromJSON(cookies.shift());
64326 } catch (e) {
64327 return cb(e);
64328 }
64329
64330 if (cookie === null) {
64331 return putNext(null); // skip this cookie
64332 }
64333
64334 jar.store.putCookie(cookie, putNext);
64335 }
64336
64337 putNext();
64338};
64339
64340CookieJar.deserialize = function(strOrObj, store, cb) {
64341 if (arguments.length !== 3) {
64342 // store is optional
64343 cb = store;
64344 store = null;
64345 }
64346
64347 var serialized;
64348 if (typeof strOrObj === 'string') {
64349 serialized = jsonParse(strOrObj);
64350 if (serialized instanceof Error) {
64351 return cb(serialized);
64352 }
64353 } else {
64354 serialized = strOrObj;
64355 }
64356
64357 var jar = new CookieJar(store, serialized.rejectPublicSuffixes);
64358 jar._importCookies(serialized, function(err) {
64359 if (err) {
64360 return cb(err);
64361 }
64362 cb(null, jar);
64363 });
64364};
64365
64366CookieJar.deserializeSync = function(strOrObj, store) {
64367 var serialized = typeof strOrObj === 'string' ?
64368 JSON.parse(strOrObj) : strOrObj;
64369 var jar = new CookieJar(store, serialized.rejectPublicSuffixes);
64370
64371 // catch this mistake early:
64372 if (!jar.store.synchronous) {
64373 throw new Error('CookieJar store is not synchronous; use async API instead.');
64374 }
64375
64376 jar._importCookiesSync(serialized);
64377 return jar;
64378};
64379CookieJar.fromJSON = CookieJar.deserializeSync;
64380
64381CAN_BE_SYNC.push('clone');
64382CookieJar.prototype.clone = function(newStore, cb) {
64383 if (arguments.length === 1) {
64384 cb = newStore;
64385 newStore = null;
64386 }
64387
64388 this.serialize(function(err,serialized) {
64389 if (err) {
64390 return cb(err);
64391 }
64392 CookieJar.deserialize(newStore, serialized, cb);
64393 });
64394};
64395
64396// Use a closure to provide a true imperative API for synchronous stores.
64397function syncWrap(method) {
64398 return function() {
64399 if (!this.store.synchronous) {
64400 throw new Error('CookieJar store is not synchronous; use async API instead.');
64401 }
64402
64403 var args = Array.prototype.slice.call(arguments);
64404 var syncErr, syncResult;
64405 args.push(function syncCb(err, result) {
64406 syncErr = err;
64407 syncResult = result;
64408 });
64409 this[method].apply(this, args);
64410
64411 if (syncErr) {
64412 throw syncErr;
64413 }
64414 return syncResult;
64415 };
64416}
64417
64418// wrap all declared CAN_BE_SYNC methods in the sync wrapper
64419CAN_BE_SYNC.forEach(function(method) {
64420 CookieJar.prototype[method+'Sync'] = syncWrap(method);
64421});
64422
64423exports.CookieJar = CookieJar;
64424exports.Cookie = Cookie;
64425exports.Store = Store;
64426exports.MemoryCookieStore = MemoryCookieStore;
64427exports.parseDate = parseDate;
64428exports.formatDate = formatDate;
64429exports.parse = parse;
64430exports.fromJSON = fromJSON;
64431exports.domainMatch = domainMatch;
64432exports.defaultPath = defaultPath;
64433exports.pathMatch = pathMatch;
64434exports.getPublicSuffix = pubsuffix.getPublicSuffix;
64435exports.cookieCompare = cookieCompare;
64436exports.permuteDomain = require('./permuteDomain').permuteDomain;
64437exports.permutePath = permutePath;
64438exports.canonicalDomain = canonicalDomain;
64439
64440},{"../package.json":322,"./memstore":317,"./pathMatch":318,"./permuteDomain":319,"./pubsuffix-psl":320,"./store":321,"net":112,"punycode":274,"url":393,"util":397}],317:[function(require,module,exports){
64441/*!
64442 * Copyright (c) 2015, Salesforce.com, Inc.
64443 * All rights reserved.
64444 *
64445 * Redistribution and use in source and binary forms, with or without
64446 * modification, are permitted provided that the following conditions are met:
64447 *
64448 * 1. Redistributions of source code must retain the above copyright notice,
64449 * this list of conditions and the following disclaimer.
64450 *
64451 * 2. Redistributions in binary form must reproduce the above copyright notice,
64452 * this list of conditions and the following disclaimer in the documentation
64453 * and/or other materials provided with the distribution.
64454 *
64455 * 3. Neither the name of Salesforce.com nor the names of its contributors may
64456 * be used to endorse or promote products derived from this software without
64457 * specific prior written permission.
64458 *
64459 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
64460 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
64461 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
64462 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
64463 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
64464 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
64465 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
64466 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
64467 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
64468 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
64469 * POSSIBILITY OF SUCH DAMAGE.
64470 */
64471'use strict';
64472var Store = require('./store').Store;
64473var permuteDomain = require('./permuteDomain').permuteDomain;
64474var pathMatch = require('./pathMatch').pathMatch;
64475var util = require('util');
64476
64477function MemoryCookieStore() {
64478 Store.call(this);
64479 this.idx = {};
64480}
64481util.inherits(MemoryCookieStore, Store);
64482exports.MemoryCookieStore = MemoryCookieStore;
64483MemoryCookieStore.prototype.idx = null;
64484
64485// Since it's just a struct in RAM, this Store is synchronous
64486MemoryCookieStore.prototype.synchronous = true;
64487
64488// force a default depth:
64489MemoryCookieStore.prototype.inspect = function() {
64490 return "{ idx: "+util.inspect(this.idx, false, 2)+' }';
64491};
64492
64493// Use the new custom inspection symbol to add the custom inspect function if
64494// available.
64495if (util.inspect.custom) {
64496 MemoryCookieStore.prototype[util.inspect.custom] = MemoryCookieStore.prototype.inspect;
64497}
64498
64499MemoryCookieStore.prototype.findCookie = function(domain, path, key, cb) {
64500 if (!this.idx[domain]) {
64501 return cb(null,undefined);
64502 }
64503 if (!this.idx[domain][path]) {
64504 return cb(null,undefined);
64505 }
64506 return cb(null,this.idx[domain][path][key]||null);
64507};
64508
64509MemoryCookieStore.prototype.findCookies = function(domain, path, cb) {
64510 var results = [];
64511 if (!domain) {
64512 return cb(null,[]);
64513 }
64514
64515 var pathMatcher;
64516 if (!path) {
64517 // null means "all paths"
64518 pathMatcher = function matchAll(domainIndex) {
64519 for (var curPath in domainIndex) {
64520 var pathIndex = domainIndex[curPath];
64521 for (var key in pathIndex) {
64522 results.push(pathIndex[key]);
64523 }
64524 }
64525 };
64526
64527 } else {
64528 pathMatcher = function matchRFC(domainIndex) {
64529 //NOTE: we should use path-match algorithm from S5.1.4 here
64530 //(see : https://github.com/ChromiumWebApps/chromium/blob/b3d3b4da8bb94c1b2e061600df106d590fda3620/net/cookies/canonical_cookie.cc#L299)
64531 Object.keys(domainIndex).forEach(function (cookiePath) {
64532 if (pathMatch(path, cookiePath)) {
64533 var pathIndex = domainIndex[cookiePath];
64534
64535 for (var key in pathIndex) {
64536 results.push(pathIndex[key]);
64537 }
64538 }
64539 });
64540 };
64541 }
64542
64543 var domains = permuteDomain(domain) || [domain];
64544 var idx = this.idx;
64545 domains.forEach(function(curDomain) {
64546 var domainIndex = idx[curDomain];
64547 if (!domainIndex) {
64548 return;
64549 }
64550 pathMatcher(domainIndex);
64551 });
64552
64553 cb(null,results);
64554};
64555
64556MemoryCookieStore.prototype.putCookie = function(cookie, cb) {
64557 if (!this.idx[cookie.domain]) {
64558 this.idx[cookie.domain] = {};
64559 }
64560 if (!this.idx[cookie.domain][cookie.path]) {
64561 this.idx[cookie.domain][cookie.path] = {};
64562 }
64563 this.idx[cookie.domain][cookie.path][cookie.key] = cookie;
64564 cb(null);
64565};
64566
64567MemoryCookieStore.prototype.updateCookie = function(oldCookie, newCookie, cb) {
64568 // updateCookie() may avoid updating cookies that are identical. For example,
64569 // lastAccessed may not be important to some stores and an equality
64570 // comparison could exclude that field.
64571 this.putCookie(newCookie,cb);
64572};
64573
64574MemoryCookieStore.prototype.removeCookie = function(domain, path, key, cb) {
64575 if (this.idx[domain] && this.idx[domain][path] && this.idx[domain][path][key]) {
64576 delete this.idx[domain][path][key];
64577 }
64578 cb(null);
64579};
64580
64581MemoryCookieStore.prototype.removeCookies = function(domain, path, cb) {
64582 if (this.idx[domain]) {
64583 if (path) {
64584 delete this.idx[domain][path];
64585 } else {
64586 delete this.idx[domain];
64587 }
64588 }
64589 return cb(null);
64590};
64591
64592MemoryCookieStore.prototype.getAllCookies = function(cb) {
64593 var cookies = [];
64594 var idx = this.idx;
64595
64596 var domains = Object.keys(idx);
64597 domains.forEach(function(domain) {
64598 var paths = Object.keys(idx[domain]);
64599 paths.forEach(function(path) {
64600 var keys = Object.keys(idx[domain][path]);
64601 keys.forEach(function(key) {
64602 if (key !== null) {
64603 cookies.push(idx[domain][path][key]);
64604 }
64605 });
64606 });
64607 });
64608
64609 // Sort by creationIndex so deserializing retains the creation order.
64610 // When implementing your own store, this SHOULD retain the order too
64611 cookies.sort(function(a,b) {
64612 return (a.creationIndex||0) - (b.creationIndex||0);
64613 });
64614
64615 cb(null, cookies);
64616};
64617
64618},{"./pathMatch":318,"./permuteDomain":319,"./store":321,"util":397}],318:[function(require,module,exports){
64619/*!
64620 * Copyright (c) 2015, Salesforce.com, Inc.
64621 * All rights reserved.
64622 *
64623 * Redistribution and use in source and binary forms, with or without
64624 * modification, are permitted provided that the following conditions are met:
64625 *
64626 * 1. Redistributions of source code must retain the above copyright notice,
64627 * this list of conditions and the following disclaimer.
64628 *
64629 * 2. Redistributions in binary form must reproduce the above copyright notice,
64630 * this list of conditions and the following disclaimer in the documentation
64631 * and/or other materials provided with the distribution.
64632 *
64633 * 3. Neither the name of Salesforce.com nor the names of its contributors may
64634 * be used to endorse or promote products derived from this software without
64635 * specific prior written permission.
64636 *
64637 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
64638 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
64639 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
64640 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
64641 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
64642 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
64643 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
64644 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
64645 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
64646 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
64647 * POSSIBILITY OF SUCH DAMAGE.
64648 */
64649"use strict";
64650/*
64651 * "A request-path path-matches a given cookie-path if at least one of the
64652 * following conditions holds:"
64653 */
64654function pathMatch (reqPath, cookiePath) {
64655 // "o The cookie-path and the request-path are identical."
64656 if (cookiePath === reqPath) {
64657 return true;
64658 }
64659
64660 var idx = reqPath.indexOf(cookiePath);
64661 if (idx === 0) {
64662 // "o The cookie-path is a prefix of the request-path, and the last
64663 // character of the cookie-path is %x2F ("/")."
64664 if (cookiePath.substr(-1) === "/") {
64665 return true;
64666 }
64667
64668 // " o The cookie-path is a prefix of the request-path, and the first
64669 // character of the request-path that is not included in the cookie- path
64670 // is a %x2F ("/") character."
64671 if (reqPath.substr(cookiePath.length, 1) === "/") {
64672 return true;
64673 }
64674 }
64675
64676 return false;
64677}
64678
64679exports.pathMatch = pathMatch;
64680
64681},{}],319:[function(require,module,exports){
64682/*!
64683 * Copyright (c) 2015, Salesforce.com, Inc.
64684 * All rights reserved.
64685 *
64686 * Redistribution and use in source and binary forms, with or without
64687 * modification, are permitted provided that the following conditions are met:
64688 *
64689 * 1. Redistributions of source code must retain the above copyright notice,
64690 * this list of conditions and the following disclaimer.
64691 *
64692 * 2. Redistributions in binary form must reproduce the above copyright notice,
64693 * this list of conditions and the following disclaimer in the documentation
64694 * and/or other materials provided with the distribution.
64695 *
64696 * 3. Neither the name of Salesforce.com nor the names of its contributors may
64697 * be used to endorse or promote products derived from this software without
64698 * specific prior written permission.
64699 *
64700 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
64701 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
64702 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
64703 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
64704 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
64705 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
64706 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
64707 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
64708 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
64709 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
64710 * POSSIBILITY OF SUCH DAMAGE.
64711 */
64712"use strict";
64713var pubsuffix = require('./pubsuffix-psl');
64714
64715// Gives the permutation of all possible domainMatch()es of a given domain. The
64716// array is in shortest-to-longest order. Handy for indexing.
64717function permuteDomain (domain) {
64718 var pubSuf = pubsuffix.getPublicSuffix(domain);
64719 if (!pubSuf) {
64720 return null;
64721 }
64722 if (pubSuf == domain) {
64723 return [domain];
64724 }
64725
64726 var prefix = domain.slice(0, -(pubSuf.length + 1)); // ".example.com"
64727 var parts = prefix.split('.').reverse();
64728 var cur = pubSuf;
64729 var permutations = [cur];
64730 while (parts.length) {
64731 cur = parts.shift() + '.' + cur;
64732 permutations.push(cur);
64733 }
64734 return permutations;
64735}
64736
64737exports.permuteDomain = permuteDomain;
64738
64739},{"./pubsuffix-psl":320}],320:[function(require,module,exports){
64740/*!
64741 * Copyright (c) 2018, Salesforce.com, Inc.
64742 * All rights reserved.
64743 *
64744 * Redistribution and use in source and binary forms, with or without
64745 * modification, are permitted provided that the following conditions are met:
64746 *
64747 * 1. Redistributions of source code must retain the above copyright notice,
64748 * this list of conditions and the following disclaimer.
64749 *
64750 * 2. Redistributions in binary form must reproduce the above copyright notice,
64751 * this list of conditions and the following disclaimer in the documentation
64752 * and/or other materials provided with the distribution.
64753 *
64754 * 3. Neither the name of Salesforce.com nor the names of its contributors may
64755 * be used to endorse or promote products derived from this software without
64756 * specific prior written permission.
64757 *
64758 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
64759 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
64760 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
64761 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
64762 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
64763 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
64764 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
64765 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
64766 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
64767 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
64768 * POSSIBILITY OF SUCH DAMAGE.
64769 */
64770'use strict';
64771var psl = require('psl');
64772
64773function getPublicSuffix(domain) {
64774 return psl.get(domain);
64775}
64776
64777exports.getPublicSuffix = getPublicSuffix;
64778
64779},{"psl":267}],321:[function(require,module,exports){
64780/*!
64781 * Copyright (c) 2015, Salesforce.com, Inc.
64782 * All rights reserved.
64783 *
64784 * Redistribution and use in source and binary forms, with or without
64785 * modification, are permitted provided that the following conditions are met:
64786 *
64787 * 1. Redistributions of source code must retain the above copyright notice,
64788 * this list of conditions and the following disclaimer.
64789 *
64790 * 2. Redistributions in binary form must reproduce the above copyright notice,
64791 * this list of conditions and the following disclaimer in the documentation
64792 * and/or other materials provided with the distribution.
64793 *
64794 * 3. Neither the name of Salesforce.com nor the names of its contributors may
64795 * be used to endorse or promote products derived from this software without
64796 * specific prior written permission.
64797 *
64798 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
64799 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
64800 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
64801 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
64802 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
64803 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
64804 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
64805 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
64806 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
64807 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
64808 * POSSIBILITY OF SUCH DAMAGE.
64809 */
64810'use strict';
64811/*jshint unused:false */
64812
64813function Store() {
64814}
64815exports.Store = Store;
64816
64817// Stores may be synchronous, but are still required to use a
64818// Continuation-Passing Style API. The CookieJar itself will expose a "*Sync"
64819// API that converts from synchronous-callbacks to imperative style.
64820Store.prototype.synchronous = false;
64821
64822Store.prototype.findCookie = function(domain, path, key, cb) {
64823 throw new Error('findCookie is not implemented');
64824};
64825
64826Store.prototype.findCookies = function(domain, path, cb) {
64827 throw new Error('findCookies is not implemented');
64828};
64829
64830Store.prototype.putCookie = function(cookie, cb) {
64831 throw new Error('putCookie is not implemented');
64832};
64833
64834Store.prototype.updateCookie = function(oldCookie, newCookie, cb) {
64835 // recommended default implementation:
64836 // return this.putCookie(newCookie, cb);
64837 throw new Error('updateCookie is not implemented');
64838};
64839
64840Store.prototype.removeCookie = function(domain, path, key, cb) {
64841 throw new Error('removeCookie is not implemented');
64842};
64843
64844Store.prototype.removeCookies = function(domain, path, cb) {
64845 throw new Error('removeCookies is not implemented');
64846};
64847
64848Store.prototype.getAllCookies = function(cb) {
64849 throw new Error('getAllCookies is not implemented (therefore jar cannot be serialized)');
64850};
64851
64852},{}],322:[function(require,module,exports){
64853module.exports={
64854 "author": {
64855 "name": "Jeremy Stashewsky",
64856 "email": "jstash@gmail.com",
64857 "website": "https://github.com/stash"
64858 },
64859 "contributors": [
64860 {
64861 "name": "Alexander Savin",
64862 "website": "https://github.com/apsavin"
64863 },
64864 {
64865 "name": "Ian Livingstone",
64866 "website": "https://github.com/ianlivingstone"
64867 },
64868 {
64869 "name": "Ivan Nikulin",
64870 "website": "https://github.com/inikulin"
64871 },
64872 {
64873 "name": "Lalit Kapoor",
64874 "website": "https://github.com/lalitkapoor"
64875 },
64876 {
64877 "name": "Sam Thompson",
64878 "website": "https://github.com/sambthompson"
64879 },
64880 {
64881 "name": "Sebastian Mayr",
64882 "website": "https://github.com/Sebmaster"
64883 }
64884 ],
64885 "license": "BSD-3-Clause",
64886 "name": "tough-cookie",
64887 "description": "RFC6265 Cookies and Cookie Jar for node.js",
64888 "keywords": [
64889 "HTTP",
64890 "cookie",
64891 "cookies",
64892 "set-cookie",
64893 "cookiejar",
64894 "jar",
64895 "RFC6265",
64896 "RFC2965"
64897 ],
64898 "version": "2.4.3",
64899 "homepage": "https://github.com/salesforce/tough-cookie",
64900 "repository": {
64901 "type": "git",
64902 "url": "git://github.com/salesforce/tough-cookie.git"
64903 },
64904 "bugs": {
64905 "url": "https://github.com/salesforce/tough-cookie/issues"
64906 },
64907 "main": "./lib/cookie",
64908 "files": [
64909 "lib"
64910 ],
64911 "scripts": {
64912 "test": "vows test/*_test.js",
64913 "cover": "nyc --reporter=lcov --reporter=html vows test/*_test.js"
64914 },
64915 "engines": {
64916 "node": ">=0.8"
64917 },
64918 "devDependencies": {
64919 "async": "^1.4.2",
64920 "nyc": "^11.6.0",
64921 "string.prototype.repeat": "^0.2.0",
64922 "vows": "^0.8.1"
64923 },
64924 "dependencies": {
64925 "psl": "^1.1.24",
64926 "punycode": "^1.4.1"
64927 }
64928}
64929
64930},{}],323:[function(require,module,exports){
64931(function (process){
64932'use strict'
64933
64934var http = require('http')
64935var https = require('https')
64936var url = require('url')
64937var util = require('util')
64938var stream = require('stream')
64939var zlib = require('zlib')
64940var aws2 = require('aws-sign2')
64941var aws4 = require('aws4')
64942var httpSignature = require('http-signature')
64943var mime = require('mime-types')
64944var caseless = require('caseless')
64945var ForeverAgent = require('forever-agent')
64946var FormData = require('form-data')
64947var extend = require('extend')
64948var isstream = require('isstream')
64949var isTypedArray = require('is-typedarray').strict
64950var helpers = require('./lib/helpers')
64951var cookies = require('./lib/cookies')
64952var getProxyFromURI = require('./lib/getProxyFromURI')
64953var Querystring = require('./lib/querystring').Querystring
64954var Har = require('./lib/har').Har
64955var Auth = require('./lib/auth').Auth
64956var OAuth = require('./lib/oauth').OAuth
64957var hawk = require('./lib/hawk')
64958var Multipart = require('./lib/multipart').Multipart
64959var Redirect = require('./lib/redirect').Redirect
64960var Tunnel = require('./lib/tunnel').Tunnel
64961var now = require('performance-now')
64962var Buffer = require('safe-buffer').Buffer
64963
64964var safeStringify = helpers.safeStringify
64965var isReadStream = helpers.isReadStream
64966var toBase64 = helpers.toBase64
64967var defer = helpers.defer
64968var copy = helpers.copy
64969var version = helpers.version
64970var globalCookieJar = cookies.jar()
64971
64972var globalPool = {}
64973
64974function filterForNonReserved (reserved, options) {
64975 // Filter out properties that are not reserved.
64976 // Reserved values are passed in at call site.
64977
64978 var object = {}
64979 for (var i in options) {
64980 var notReserved = (reserved.indexOf(i) === -1)
64981 if (notReserved) {
64982 object[i] = options[i]
64983 }
64984 }
64985 return object
64986}
64987
64988function filterOutReservedFunctions (reserved, options) {
64989 // Filter out properties that are functions and are reserved.
64990 // Reserved values are passed in at call site.
64991
64992 var object = {}
64993 for (var i in options) {
64994 var isReserved = !(reserved.indexOf(i) === -1)
64995 var isFunction = (typeof options[i] === 'function')
64996 if (!(isReserved && isFunction)) {
64997 object[i] = options[i]
64998 }
64999 }
65000 return object
65001}
65002
65003// Return a simpler request object to allow serialization
65004function requestToJSON () {
65005 var self = this
65006 return {
65007 uri: self.uri,
65008 method: self.method,
65009 headers: self.headers
65010 }
65011}
65012
65013// Return a simpler response object to allow serialization
65014function responseToJSON () {
65015 var self = this
65016 return {
65017 statusCode: self.statusCode,
65018 body: self.body,
65019 headers: self.headers,
65020 request: requestToJSON.call(self.request)
65021 }
65022}
65023
65024function Request (options) {
65025 // if given the method property in options, set property explicitMethod to true
65026
65027 // extend the Request instance with any non-reserved properties
65028 // remove any reserved functions from the options object
65029 // set Request instance to be readable and writable
65030 // call init
65031
65032 var self = this
65033
65034 // start with HAR, then override with additional options
65035 if (options.har) {
65036 self._har = new Har(self)
65037 options = self._har.options(options)
65038 }
65039
65040 stream.Stream.call(self)
65041 var reserved = Object.keys(Request.prototype)
65042 var nonReserved = filterForNonReserved(reserved, options)
65043
65044 extend(self, nonReserved)
65045 options = filterOutReservedFunctions(reserved, options)
65046
65047 self.readable = true
65048 self.writable = true
65049 if (options.method) {
65050 self.explicitMethod = true
65051 }
65052 self._qs = new Querystring(self)
65053 self._auth = new Auth(self)
65054 self._oauth = new OAuth(self)
65055 self._multipart = new Multipart(self)
65056 self._redirect = new Redirect(self)
65057 self._tunnel = new Tunnel(self)
65058 self.init(options)
65059}
65060
65061util.inherits(Request, stream.Stream)
65062
65063// Debugging
65064Request.debug = process.env.NODE_DEBUG && /\brequest\b/.test(process.env.NODE_DEBUG)
65065function debug () {
65066 if (Request.debug) {
65067 console.error('REQUEST %s', util.format.apply(util, arguments))
65068 }
65069}
65070Request.prototype.debug = debug
65071
65072Request.prototype.init = function (options) {
65073 // init() contains all the code to setup the request object.
65074 // the actual outgoing request is not started until start() is called
65075 // this function is called from both the constructor and on redirect.
65076 var self = this
65077 if (!options) {
65078 options = {}
65079 }
65080 self.headers = self.headers ? copy(self.headers) : {}
65081
65082 // Delete headers with value undefined since they break
65083 // ClientRequest.OutgoingMessage.setHeader in node 0.12
65084 for (var headerName in self.headers) {
65085 if (typeof self.headers[headerName] === 'undefined') {
65086 delete self.headers[headerName]
65087 }
65088 }
65089
65090 caseless.httpify(self, self.headers)
65091
65092 if (!self.method) {
65093 self.method = options.method || 'GET'
65094 }
65095 if (!self.localAddress) {
65096 self.localAddress = options.localAddress
65097 }
65098
65099 self._qs.init(options)
65100
65101 debug(options)
65102 if (!self.pool && self.pool !== false) {
65103 self.pool = globalPool
65104 }
65105 self.dests = self.dests || []
65106 self.__isRequestRequest = true
65107
65108 // Protect against double callback
65109 if (!self._callback && self.callback) {
65110 self._callback = self.callback
65111 self.callback = function () {
65112 if (self._callbackCalled) {
65113 return // Print a warning maybe?
65114 }
65115 self._callbackCalled = true
65116 self._callback.apply(self, arguments)
65117 }
65118 self.on('error', self.callback.bind())
65119 self.on('complete', self.callback.bind(self, null))
65120 }
65121
65122 // People use this property instead all the time, so support it
65123 if (!self.uri && self.url) {
65124 self.uri = self.url
65125 delete self.url
65126 }
65127
65128 // If there's a baseUrl, then use it as the base URL (i.e. uri must be
65129 // specified as a relative path and is appended to baseUrl).
65130 if (self.baseUrl) {
65131 if (typeof self.baseUrl !== 'string') {
65132 return self.emit('error', new Error('options.baseUrl must be a string'))
65133 }
65134
65135 if (typeof self.uri !== 'string') {
65136 return self.emit('error', new Error('options.uri must be a string when using options.baseUrl'))
65137 }
65138
65139 if (self.uri.indexOf('//') === 0 || self.uri.indexOf('://') !== -1) {
65140 return self.emit('error', new Error('options.uri must be a path when using options.baseUrl'))
65141 }
65142
65143 // Handle all cases to make sure that there's only one slash between
65144 // baseUrl and uri.
65145 var baseUrlEndsWithSlash = self.baseUrl.lastIndexOf('/') === self.baseUrl.length - 1
65146 var uriStartsWithSlash = self.uri.indexOf('/') === 0
65147
65148 if (baseUrlEndsWithSlash && uriStartsWithSlash) {
65149 self.uri = self.baseUrl + self.uri.slice(1)
65150 } else if (baseUrlEndsWithSlash || uriStartsWithSlash) {
65151 self.uri = self.baseUrl + self.uri
65152 } else if (self.uri === '') {
65153 self.uri = self.baseUrl
65154 } else {
65155 self.uri = self.baseUrl + '/' + self.uri
65156 }
65157 delete self.baseUrl
65158 }
65159
65160 // A URI is needed by this point, emit error if we haven't been able to get one
65161 if (!self.uri) {
65162 return self.emit('error', new Error('options.uri is a required argument'))
65163 }
65164
65165 // If a string URI/URL was given, parse it into a URL object
65166 if (typeof self.uri === 'string') {
65167 self.uri = url.parse(self.uri)
65168 }
65169
65170 // Some URL objects are not from a URL parsed string and need href added
65171 if (!self.uri.href) {
65172 self.uri.href = url.format(self.uri)
65173 }
65174
65175 // DEPRECATED: Warning for users of the old Unix Sockets URL Scheme
65176 if (self.uri.protocol === 'unix:') {
65177 return self.emit('error', new Error('`unix://` URL scheme is no longer supported. Please use the format `http://unix:SOCKET:PATH`'))
65178 }
65179
65180 // Support Unix Sockets
65181 if (self.uri.host === 'unix') {
65182 self.enableUnixSocket()
65183 }
65184
65185 if (self.strictSSL === false) {
65186 self.rejectUnauthorized = false
65187 }
65188
65189 if (!self.uri.pathname) { self.uri.pathname = '/' }
65190
65191 if (!(self.uri.host || (self.uri.hostname && self.uri.port)) && !self.uri.isUnix) {
65192 // Invalid URI: it may generate lot of bad errors, like 'TypeError: Cannot call method `indexOf` of undefined' in CookieJar
65193 // Detect and reject it as soon as possible
65194 var faultyUri = url.format(self.uri)
65195 var message = 'Invalid URI "' + faultyUri + '"'
65196 if (Object.keys(options).length === 0) {
65197 // No option ? This can be the sign of a redirect
65198 // As this is a case where the user cannot do anything (they didn't call request directly with this URL)
65199 // they should be warned that it can be caused by a redirection (can save some hair)
65200 message += '. This can be caused by a crappy redirection.'
65201 }
65202 // This error was fatal
65203 self.abort()
65204 return self.emit('error', new Error(message))
65205 }
65206
65207 if (!self.hasOwnProperty('proxy')) {
65208 self.proxy = getProxyFromURI(self.uri)
65209 }
65210
65211 self.tunnel = self._tunnel.isEnabled()
65212 if (self.proxy) {
65213 self._tunnel.setup(options)
65214 }
65215
65216 self._redirect.onRequest(options)
65217
65218 self.setHost = false
65219 if (!self.hasHeader('host')) {
65220 var hostHeaderName = self.originalHostHeaderName || 'host'
65221 self.setHeader(hostHeaderName, self.uri.host)
65222 // Drop :port suffix from Host header if known protocol.
65223 if (self.uri.port) {
65224 if ((self.uri.port === '80' && self.uri.protocol === 'http:') ||
65225 (self.uri.port === '443' && self.uri.protocol === 'https:')) {
65226 self.setHeader(hostHeaderName, self.uri.hostname)
65227 }
65228 }
65229 self.setHost = true
65230 }
65231
65232 self.jar(self._jar || options.jar)
65233
65234 if (!self.uri.port) {
65235 if (self.uri.protocol === 'http:') { self.uri.port = 80 } else if (self.uri.protocol === 'https:') { self.uri.port = 443 }
65236 }
65237
65238 if (self.proxy && !self.tunnel) {
65239 self.port = self.proxy.port
65240 self.host = self.proxy.hostname
65241 } else {
65242 self.port = self.uri.port
65243 self.host = self.uri.hostname
65244 }
65245
65246 if (options.form) {
65247 self.form(options.form)
65248 }
65249
65250 if (options.formData) {
65251 var formData = options.formData
65252 var requestForm = self.form()
65253 var appendFormValue = function (key, value) {
65254 if (value && value.hasOwnProperty('value') && value.hasOwnProperty('options')) {
65255 requestForm.append(key, value.value, value.options)
65256 } else {
65257 requestForm.append(key, value)
65258 }
65259 }
65260 for (var formKey in formData) {
65261 if (formData.hasOwnProperty(formKey)) {
65262 var formValue = formData[formKey]
65263 if (formValue instanceof Array) {
65264 for (var j = 0; j < formValue.length; j++) {
65265 appendFormValue(formKey, formValue[j])
65266 }
65267 } else {
65268 appendFormValue(formKey, formValue)
65269 }
65270 }
65271 }
65272 }
65273
65274 if (options.qs) {
65275 self.qs(options.qs)
65276 }
65277
65278 if (self.uri.path) {
65279 self.path = self.uri.path
65280 } else {
65281 self.path = self.uri.pathname + (self.uri.search || '')
65282 }
65283
65284 if (self.path.length === 0) {
65285 self.path = '/'
65286 }
65287
65288 // Auth must happen last in case signing is dependent on other headers
65289 if (options.aws) {
65290 self.aws(options.aws)
65291 }
65292
65293 if (options.hawk) {
65294 self.hawk(options.hawk)
65295 }
65296
65297 if (options.httpSignature) {
65298 self.httpSignature(options.httpSignature)
65299 }
65300
65301 if (options.auth) {
65302 if (Object.prototype.hasOwnProperty.call(options.auth, 'username')) {
65303 options.auth.user = options.auth.username
65304 }
65305 if (Object.prototype.hasOwnProperty.call(options.auth, 'password')) {
65306 options.auth.pass = options.auth.password
65307 }
65308
65309 self.auth(
65310 options.auth.user,
65311 options.auth.pass,
65312 options.auth.sendImmediately,
65313 options.auth.bearer
65314 )
65315 }
65316
65317 if (self.gzip && !self.hasHeader('accept-encoding')) {
65318 self.setHeader('accept-encoding', 'gzip, deflate')
65319 }
65320
65321 if (self.uri.auth && !self.hasHeader('authorization')) {
65322 var uriAuthPieces = self.uri.auth.split(':').map(function (item) { return self._qs.unescape(item) })
65323 self.auth(uriAuthPieces[0], uriAuthPieces.slice(1).join(':'), true)
65324 }
65325
65326 if (!self.tunnel && self.proxy && self.proxy.auth && !self.hasHeader('proxy-authorization')) {
65327 var proxyAuthPieces = self.proxy.auth.split(':').map(function (item) { return self._qs.unescape(item) })
65328 var authHeader = 'Basic ' + toBase64(proxyAuthPieces.join(':'))
65329 self.setHeader('proxy-authorization', authHeader)
65330 }
65331
65332 if (self.proxy && !self.tunnel) {
65333 self.path = (self.uri.protocol + '//' + self.uri.host + self.path)
65334 }
65335
65336 if (options.json) {
65337 self.json(options.json)
65338 }
65339 if (options.multipart) {
65340 self.multipart(options.multipart)
65341 }
65342
65343 if (options.time) {
65344 self.timing = true
65345
65346 // NOTE: elapsedTime is deprecated in favor of .timings
65347 self.elapsedTime = self.elapsedTime || 0
65348 }
65349
65350 function setContentLength () {
65351 if (isTypedArray(self.body)) {
65352 self.body = Buffer.from(self.body)
65353 }
65354
65355 if (!self.hasHeader('content-length')) {
65356 var length
65357 if (typeof self.body === 'string') {
65358 length = Buffer.byteLength(self.body)
65359 } else if (Array.isArray(self.body)) {
65360 length = self.body.reduce(function (a, b) { return a + b.length }, 0)
65361 } else {
65362 length = self.body.length
65363 }
65364
65365 if (length) {
65366 self.setHeader('content-length', length)
65367 } else {
65368 self.emit('error', new Error('Argument error, options.body.'))
65369 }
65370 }
65371 }
65372 if (self.body && !isstream(self.body)) {
65373 setContentLength()
65374 }
65375
65376 if (options.oauth) {
65377 self.oauth(options.oauth)
65378 } else if (self._oauth.params && self.hasHeader('authorization')) {
65379 self.oauth(self._oauth.params)
65380 }
65381
65382 var protocol = self.proxy && !self.tunnel ? self.proxy.protocol : self.uri.protocol
65383 var defaultModules = {'http:': http, 'https:': https}
65384 var httpModules = self.httpModules || {}
65385
65386 self.httpModule = httpModules[protocol] || defaultModules[protocol]
65387
65388 if (!self.httpModule) {
65389 return self.emit('error', new Error('Invalid protocol: ' + protocol))
65390 }
65391
65392 if (options.ca) {
65393 self.ca = options.ca
65394 }
65395
65396 if (!self.agent) {
65397 if (options.agentOptions) {
65398 self.agentOptions = options.agentOptions
65399 }
65400
65401 if (options.agentClass) {
65402 self.agentClass = options.agentClass
65403 } else if (options.forever) {
65404 var v = version()
65405 // use ForeverAgent in node 0.10- only
65406 if (v.major === 0 && v.minor <= 10) {
65407 self.agentClass = protocol === 'http:' ? ForeverAgent : ForeverAgent.SSL
65408 } else {
65409 self.agentClass = self.httpModule.Agent
65410 self.agentOptions = self.agentOptions || {}
65411 self.agentOptions.keepAlive = true
65412 }
65413 } else {
65414 self.agentClass = self.httpModule.Agent
65415 }
65416 }
65417
65418 if (self.pool === false) {
65419 self.agent = false
65420 } else {
65421 self.agent = self.agent || self.getNewAgent()
65422 }
65423
65424 self.on('pipe', function (src) {
65425 if (self.ntick && self._started) {
65426 self.emit('error', new Error('You cannot pipe to this stream after the outbound request has started.'))
65427 }
65428 self.src = src
65429 if (isReadStream(src)) {
65430 if (!self.hasHeader('content-type')) {
65431 self.setHeader('content-type', mime.lookup(src.path))
65432 }
65433 } else {
65434 if (src.headers) {
65435 for (var i in src.headers) {
65436 if (!self.hasHeader(i)) {
65437 self.setHeader(i, src.headers[i])
65438 }
65439 }
65440 }
65441 if (self._json && !self.hasHeader('content-type')) {
65442 self.setHeader('content-type', 'application/json')
65443 }
65444 if (src.method && !self.explicitMethod) {
65445 self.method = src.method
65446 }
65447 }
65448
65449 // self.on('pipe', function () {
65450 // console.error('You have already piped to this stream. Pipeing twice is likely to break the request.')
65451 // })
65452 })
65453
65454 defer(function () {
65455 if (self._aborted) {
65456 return
65457 }
65458
65459 var end = function () {
65460 if (self._form) {
65461 if (!self._auth.hasAuth) {
65462 self._form.pipe(self)
65463 } else if (self._auth.hasAuth && self._auth.sentAuth) {
65464 self._form.pipe(self)
65465 }
65466 }
65467 if (self._multipart && self._multipart.chunked) {
65468 self._multipart.body.pipe(self)
65469 }
65470 if (self.body) {
65471 if (isstream(self.body)) {
65472 self.body.pipe(self)
65473 } else {
65474 setContentLength()
65475 if (Array.isArray(self.body)) {
65476 self.body.forEach(function (part) {
65477 self.write(part)
65478 })
65479 } else {
65480 self.write(self.body)
65481 }
65482 self.end()
65483 }
65484 } else if (self.requestBodyStream) {
65485 console.warn('options.requestBodyStream is deprecated, please pass the request object to stream.pipe.')
65486 self.requestBodyStream.pipe(self)
65487 } else if (!self.src) {
65488 if (self._auth.hasAuth && !self._auth.sentAuth) {
65489 self.end()
65490 return
65491 }
65492 if (self.method !== 'GET' && typeof self.method !== 'undefined') {
65493 self.setHeader('content-length', 0)
65494 }
65495 self.end()
65496 }
65497 }
65498
65499 if (self._form && !self.hasHeader('content-length')) {
65500 // Before ending the request, we had to compute the length of the whole form, asyncly
65501 self.setHeader(self._form.getHeaders(), true)
65502 self._form.getLength(function (err, length) {
65503 if (!err && !isNaN(length)) {
65504 self.setHeader('content-length', length)
65505 }
65506 end()
65507 })
65508 } else {
65509 end()
65510 }
65511
65512 self.ntick = true
65513 })
65514}
65515
65516Request.prototype.getNewAgent = function () {
65517 var self = this
65518 var Agent = self.agentClass
65519 var options = {}
65520 if (self.agentOptions) {
65521 for (var i in self.agentOptions) {
65522 options[i] = self.agentOptions[i]
65523 }
65524 }
65525 if (self.ca) {
65526 options.ca = self.ca
65527 }
65528 if (self.ciphers) {
65529 options.ciphers = self.ciphers
65530 }
65531 if (self.secureProtocol) {
65532 options.secureProtocol = self.secureProtocol
65533 }
65534 if (self.secureOptions) {
65535 options.secureOptions = self.secureOptions
65536 }
65537 if (typeof self.rejectUnauthorized !== 'undefined') {
65538 options.rejectUnauthorized = self.rejectUnauthorized
65539 }
65540
65541 if (self.cert && self.key) {
65542 options.key = self.key
65543 options.cert = self.cert
65544 }
65545
65546 if (self.pfx) {
65547 options.pfx = self.pfx
65548 }
65549
65550 if (self.passphrase) {
65551 options.passphrase = self.passphrase
65552 }
65553
65554 var poolKey = ''
65555
65556 // different types of agents are in different pools
65557 if (Agent !== self.httpModule.Agent) {
65558 poolKey += Agent.name
65559 }
65560
65561 // ca option is only relevant if proxy or destination are https
65562 var proxy = self.proxy
65563 if (typeof proxy === 'string') {
65564 proxy = url.parse(proxy)
65565 }
65566 var isHttps = (proxy && proxy.protocol === 'https:') || this.uri.protocol === 'https:'
65567
65568 if (isHttps) {
65569 if (options.ca) {
65570 if (poolKey) {
65571 poolKey += ':'
65572 }
65573 poolKey += options.ca
65574 }
65575
65576 if (typeof options.rejectUnauthorized !== 'undefined') {
65577 if (poolKey) {
65578 poolKey += ':'
65579 }
65580 poolKey += options.rejectUnauthorized
65581 }
65582
65583 if (options.cert) {
65584 if (poolKey) {
65585 poolKey += ':'
65586 }
65587 poolKey += options.cert.toString('ascii') + options.key.toString('ascii')
65588 }
65589
65590 if (options.pfx) {
65591 if (poolKey) {
65592 poolKey += ':'
65593 }
65594 poolKey += options.pfx.toString('ascii')
65595 }
65596
65597 if (options.ciphers) {
65598 if (poolKey) {
65599 poolKey += ':'
65600 }
65601 poolKey += options.ciphers
65602 }
65603
65604 if (options.secureProtocol) {
65605 if (poolKey) {
65606 poolKey += ':'
65607 }
65608 poolKey += options.secureProtocol
65609 }
65610
65611 if (options.secureOptions) {
65612 if (poolKey) {
65613 poolKey += ':'
65614 }
65615 poolKey += options.secureOptions
65616 }
65617 }
65618
65619 if (self.pool === globalPool && !poolKey && Object.keys(options).length === 0 && self.httpModule.globalAgent) {
65620 // not doing anything special. Use the globalAgent
65621 return self.httpModule.globalAgent
65622 }
65623
65624 // we're using a stored agent. Make sure it's protocol-specific
65625 poolKey = self.uri.protocol + poolKey
65626
65627 // generate a new agent for this setting if none yet exists
65628 if (!self.pool[poolKey]) {
65629 self.pool[poolKey] = new Agent(options)
65630 // properly set maxSockets on new agents
65631 if (self.pool.maxSockets) {
65632 self.pool[poolKey].maxSockets = self.pool.maxSockets
65633 }
65634 }
65635
65636 return self.pool[poolKey]
65637}
65638
65639Request.prototype.start = function () {
65640 // start() is called once we are ready to send the outgoing HTTP request.
65641 // this is usually called on the first write(), end() or on nextTick()
65642 var self = this
65643
65644 if (self.timing) {
65645 // All timings will be relative to this request's startTime. In order to do this,
65646 // we need to capture the wall-clock start time (via Date), immediately followed
65647 // by the high-resolution timer (via now()). While these two won't be set
65648 // at the _exact_ same time, they should be close enough to be able to calculate
65649 // high-resolution, monotonically non-decreasing timestamps relative to startTime.
65650 var startTime = new Date().getTime()
65651 var startTimeNow = now()
65652 }
65653
65654 if (self._aborted) {
65655 return
65656 }
65657
65658 self._started = true
65659 self.method = self.method || 'GET'
65660 self.href = self.uri.href
65661
65662 if (self.src && self.src.stat && self.src.stat.size && !self.hasHeader('content-length')) {
65663 self.setHeader('content-length', self.src.stat.size)
65664 }
65665 if (self._aws) {
65666 self.aws(self._aws, true)
65667 }
65668
65669 // We have a method named auth, which is completely different from the http.request
65670 // auth option. If we don't remove it, we're gonna have a bad time.
65671 var reqOptions = copy(self)
65672 delete reqOptions.auth
65673
65674 debug('make request', self.uri.href)
65675
65676 // node v6.8.0 now supports a `timeout` value in `http.request()`, but we
65677 // should delete it for now since we handle timeouts manually for better
65678 // consistency with node versions before v6.8.0
65679 delete reqOptions.timeout
65680
65681 try {
65682 self.req = self.httpModule.request(reqOptions)
65683 } catch (err) {
65684 self.emit('error', err)
65685 return
65686 }
65687
65688 if (self.timing) {
65689 self.startTime = startTime
65690 self.startTimeNow = startTimeNow
65691
65692 // Timing values will all be relative to startTime (by comparing to startTimeNow
65693 // so we have an accurate clock)
65694 self.timings = {}
65695 }
65696
65697 var timeout
65698 if (self.timeout && !self.timeoutTimer) {
65699 if (self.timeout < 0) {
65700 timeout = 0
65701 } else if (typeof self.timeout === 'number' && isFinite(self.timeout)) {
65702 timeout = self.timeout
65703 }
65704 }
65705
65706 self.req.on('response', self.onRequestResponse.bind(self))
65707 self.req.on('error', self.onRequestError.bind(self))
65708 self.req.on('drain', function () {
65709 self.emit('drain')
65710 })
65711
65712 self.req.on('socket', function (socket) {
65713 // `._connecting` was the old property which was made public in node v6.1.0
65714 var isConnecting = socket._connecting || socket.connecting
65715 if (self.timing) {
65716 self.timings.socket = now() - self.startTimeNow
65717
65718 if (isConnecting) {
65719 var onLookupTiming = function () {
65720 self.timings.lookup = now() - self.startTimeNow
65721 }
65722
65723 var onConnectTiming = function () {
65724 self.timings.connect = now() - self.startTimeNow
65725 }
65726
65727 socket.once('lookup', onLookupTiming)
65728 socket.once('connect', onConnectTiming)
65729
65730 // clean up timing event listeners if needed on error
65731 self.req.once('error', function () {
65732 socket.removeListener('lookup', onLookupTiming)
65733 socket.removeListener('connect', onConnectTiming)
65734 })
65735 }
65736 }
65737
65738 var setReqTimeout = function () {
65739 // This timeout sets the amount of time to wait *between* bytes sent
65740 // from the server once connected.
65741 //
65742 // In particular, it's useful for erroring if the server fails to send
65743 // data halfway through streaming a response.
65744 self.req.setTimeout(timeout, function () {
65745 if (self.req) {
65746 self.abort()
65747 var e = new Error('ESOCKETTIMEDOUT')
65748 e.code = 'ESOCKETTIMEDOUT'
65749 e.connect = false
65750 self.emit('error', e)
65751 }
65752 })
65753 }
65754 if (timeout !== undefined) {
65755 // Only start the connection timer if we're actually connecting a new
65756 // socket, otherwise if we're already connected (because this is a
65757 // keep-alive connection) do not bother. This is important since we won't
65758 // get a 'connect' event for an already connected socket.
65759 if (isConnecting) {
65760 var onReqSockConnect = function () {
65761 socket.removeListener('connect', onReqSockConnect)
65762 clearTimeout(self.timeoutTimer)
65763 self.timeoutTimer = null
65764 setReqTimeout()
65765 }
65766
65767 socket.on('connect', onReqSockConnect)
65768
65769 self.req.on('error', function (err) { // eslint-disable-line handle-callback-err
65770 socket.removeListener('connect', onReqSockConnect)
65771 })
65772
65773 // Set a timeout in memory - this block will throw if the server takes more
65774 // than `timeout` to write the HTTP status and headers (corresponding to
65775 // the on('response') event on the client). NB: this measures wall-clock
65776 // time, not the time between bytes sent by the server.
65777 self.timeoutTimer = setTimeout(function () {
65778 socket.removeListener('connect', onReqSockConnect)
65779 self.abort()
65780 var e = new Error('ETIMEDOUT')
65781 e.code = 'ETIMEDOUT'
65782 e.connect = true
65783 self.emit('error', e)
65784 }, timeout)
65785 } else {
65786 // We're already connected
65787 setReqTimeout()
65788 }
65789 }
65790 self.emit('socket', socket)
65791 })
65792
65793 self.emit('request', self.req)
65794}
65795
65796Request.prototype.onRequestError = function (error) {
65797 var self = this
65798 if (self._aborted) {
65799 return
65800 }
65801 if (self.req && self.req._reusedSocket && error.code === 'ECONNRESET' &&
65802 self.agent.addRequestNoreuse) {
65803 self.agent = { addRequest: self.agent.addRequestNoreuse.bind(self.agent) }
65804 self.start()
65805 self.req.end()
65806 return
65807 }
65808 if (self.timeout && self.timeoutTimer) {
65809 clearTimeout(self.timeoutTimer)
65810 self.timeoutTimer = null
65811 }
65812 self.emit('error', error)
65813}
65814
65815Request.prototype.onRequestResponse = function (response) {
65816 var self = this
65817
65818 if (self.timing) {
65819 self.timings.response = now() - self.startTimeNow
65820 }
65821
65822 debug('onRequestResponse', self.uri.href, response.statusCode, response.headers)
65823 response.on('end', function () {
65824 if (self.timing) {
65825 self.timings.end = now() - self.startTimeNow
65826 response.timingStart = self.startTime
65827
65828 // fill in the blanks for any periods that didn't trigger, such as
65829 // no lookup or connect due to keep alive
65830 if (!self.timings.socket) {
65831 self.timings.socket = 0
65832 }
65833 if (!self.timings.lookup) {
65834 self.timings.lookup = self.timings.socket
65835 }
65836 if (!self.timings.connect) {
65837 self.timings.connect = self.timings.lookup
65838 }
65839 if (!self.timings.response) {
65840 self.timings.response = self.timings.connect
65841 }
65842
65843 debug('elapsed time', self.timings.end)
65844
65845 // elapsedTime includes all redirects
65846 self.elapsedTime += Math.round(self.timings.end)
65847
65848 // NOTE: elapsedTime is deprecated in favor of .timings
65849 response.elapsedTime = self.elapsedTime
65850
65851 // timings is just for the final fetch
65852 response.timings = self.timings
65853
65854 // pre-calculate phase timings as well
65855 response.timingPhases = {
65856 wait: self.timings.socket,
65857 dns: self.timings.lookup - self.timings.socket,
65858 tcp: self.timings.connect - self.timings.lookup,
65859 firstByte: self.timings.response - self.timings.connect,
65860 download: self.timings.end - self.timings.response,
65861 total: self.timings.end
65862 }
65863 }
65864 debug('response end', self.uri.href, response.statusCode, response.headers)
65865 })
65866
65867 if (self._aborted) {
65868 debug('aborted', self.uri.href)
65869 response.resume()
65870 return
65871 }
65872
65873 self.response = response
65874 response.request = self
65875 response.toJSON = responseToJSON
65876
65877 // XXX This is different on 0.10, because SSL is strict by default
65878 if (self.httpModule === https &&
65879 self.strictSSL && (!response.hasOwnProperty('socket') ||
65880 !response.socket.authorized)) {
65881 debug('strict ssl error', self.uri.href)
65882 var sslErr = response.hasOwnProperty('socket') ? response.socket.authorizationError : self.uri.href + ' does not support SSL'
65883 self.emit('error', new Error('SSL Error: ' + sslErr))
65884 return
65885 }
65886
65887 // Save the original host before any redirect (if it changes, we need to
65888 // remove any authorization headers). Also remember the case of the header
65889 // name because lots of broken servers expect Host instead of host and we
65890 // want the caller to be able to specify this.
65891 self.originalHost = self.getHeader('host')
65892 if (!self.originalHostHeaderName) {
65893 self.originalHostHeaderName = self.hasHeader('host')
65894 }
65895 if (self.setHost) {
65896 self.removeHeader('host')
65897 }
65898 if (self.timeout && self.timeoutTimer) {
65899 clearTimeout(self.timeoutTimer)
65900 self.timeoutTimer = null
65901 }
65902
65903 var targetCookieJar = (self._jar && self._jar.setCookie) ? self._jar : globalCookieJar
65904 var addCookie = function (cookie) {
65905 // set the cookie if it's domain in the href's domain.
65906 try {
65907 targetCookieJar.setCookie(cookie, self.uri.href, {ignoreError: true})
65908 } catch (e) {
65909 self.emit('error', e)
65910 }
65911 }
65912
65913 response.caseless = caseless(response.headers)
65914
65915 if (response.caseless.has('set-cookie') && (!self._disableCookies)) {
65916 var headerName = response.caseless.has('set-cookie')
65917 if (Array.isArray(response.headers[headerName])) {
65918 response.headers[headerName].forEach(addCookie)
65919 } else {
65920 addCookie(response.headers[headerName])
65921 }
65922 }
65923
65924 if (self._redirect.onResponse(response)) {
65925 return // Ignore the rest of the response
65926 } else {
65927 // Be a good stream and emit end when the response is finished.
65928 // Hack to emit end on close because of a core bug that never fires end
65929 response.on('close', function () {
65930 if (!self._ended) {
65931 self.response.emit('end')
65932 }
65933 })
65934
65935 response.once('end', function () {
65936 self._ended = true
65937 })
65938
65939 var noBody = function (code) {
65940 return (
65941 self.method === 'HEAD' ||
65942 // Informational
65943 (code >= 100 && code < 200) ||
65944 // No Content
65945 code === 204 ||
65946 // Not Modified
65947 code === 304
65948 )
65949 }
65950
65951 var responseContent
65952 if (self.gzip && !noBody(response.statusCode)) {
65953 var contentEncoding = response.headers['content-encoding'] || 'identity'
65954 contentEncoding = contentEncoding.trim().toLowerCase()
65955
65956 // Be more lenient with decoding compressed responses, since (very rarely)
65957 // servers send slightly invalid gzip responses that are still accepted
65958 // by common browsers.
65959 // Always using Z_SYNC_FLUSH is what cURL does.
65960 var zlibOptions = {
65961 flush: zlib.Z_SYNC_FLUSH,
65962 finishFlush: zlib.Z_SYNC_FLUSH
65963 }
65964
65965 if (contentEncoding === 'gzip') {
65966 responseContent = zlib.createGunzip(zlibOptions)
65967 response.pipe(responseContent)
65968 } else if (contentEncoding === 'deflate') {
65969 responseContent = zlib.createInflate(zlibOptions)
65970 response.pipe(responseContent)
65971 } else {
65972 // Since previous versions didn't check for Content-Encoding header,
65973 // ignore any invalid values to preserve backwards-compatibility
65974 if (contentEncoding !== 'identity') {
65975 debug('ignoring unrecognized Content-Encoding ' + contentEncoding)
65976 }
65977 responseContent = response
65978 }
65979 } else {
65980 responseContent = response
65981 }
65982
65983 if (self.encoding) {
65984 if (self.dests.length !== 0) {
65985 console.error('Ignoring encoding parameter as this stream is being piped to another stream which makes the encoding option invalid.')
65986 } else {
65987 responseContent.setEncoding(self.encoding)
65988 }
65989 }
65990
65991 if (self._paused) {
65992 responseContent.pause()
65993 }
65994
65995 self.responseContent = responseContent
65996
65997 self.emit('response', response)
65998
65999 self.dests.forEach(function (dest) {
66000 self.pipeDest(dest)
66001 })
66002
66003 responseContent.on('data', function (chunk) {
66004 if (self.timing && !self.responseStarted) {
66005 self.responseStartTime = (new Date()).getTime()
66006
66007 // NOTE: responseStartTime is deprecated in favor of .timings
66008 response.responseStartTime = self.responseStartTime
66009 }
66010 self._destdata = true
66011 self.emit('data', chunk)
66012 })
66013 responseContent.once('end', function (chunk) {
66014 self.emit('end', chunk)
66015 })
66016 responseContent.on('error', function (error) {
66017 self.emit('error', error)
66018 })
66019 responseContent.on('close', function () { self.emit('close') })
66020
66021 if (self.callback) {
66022 self.readResponseBody(response)
66023 } else { // if no callback
66024 self.on('end', function () {
66025 if (self._aborted) {
66026 debug('aborted', self.uri.href)
66027 return
66028 }
66029 self.emit('complete', response)
66030 })
66031 }
66032 }
66033 debug('finish init function', self.uri.href)
66034}
66035
66036Request.prototype.readResponseBody = function (response) {
66037 var self = this
66038 debug("reading response's body")
66039 var buffers = []
66040 var bufferLength = 0
66041 var strings = []
66042
66043 self.on('data', function (chunk) {
66044 if (!Buffer.isBuffer(chunk)) {
66045 strings.push(chunk)
66046 } else if (chunk.length) {
66047 bufferLength += chunk.length
66048 buffers.push(chunk)
66049 }
66050 })
66051 self.on('end', function () {
66052 debug('end event', self.uri.href)
66053 if (self._aborted) {
66054 debug('aborted', self.uri.href)
66055 // `buffer` is defined in the parent scope and used in a closure it exists for the life of the request.
66056 // This can lead to leaky behavior if the user retains a reference to the request object.
66057 buffers = []
66058 bufferLength = 0
66059 return
66060 }
66061
66062 if (bufferLength) {
66063 debug('has body', self.uri.href, bufferLength)
66064 response.body = Buffer.concat(buffers, bufferLength)
66065 if (self.encoding !== null) {
66066 response.body = response.body.toString(self.encoding)
66067 }
66068 // `buffer` is defined in the parent scope and used in a closure it exists for the life of the Request.
66069 // This can lead to leaky behavior if the user retains a reference to the request object.
66070 buffers = []
66071 bufferLength = 0
66072 } else if (strings.length) {
66073 // The UTF8 BOM [0xEF,0xBB,0xBF] is converted to [0xFE,0xFF] in the JS UTC16/UCS2 representation.
66074 // Strip this value out when the encoding is set to 'utf8', as upstream consumers won't expect it and it breaks JSON.parse().
66075 if (self.encoding === 'utf8' && strings[0].length > 0 && strings[0][0] === '\uFEFF') {
66076 strings[0] = strings[0].substring(1)
66077 }
66078 response.body = strings.join('')
66079 }
66080
66081 if (self._json) {
66082 try {
66083 response.body = JSON.parse(response.body, self._jsonReviver)
66084 } catch (e) {
66085 debug('invalid JSON received', self.uri.href)
66086 }
66087 }
66088 debug('emitting complete', self.uri.href)
66089 if (typeof response.body === 'undefined' && !self._json) {
66090 response.body = self.encoding === null ? Buffer.alloc(0) : ''
66091 }
66092 self.emit('complete', response, response.body)
66093 })
66094}
66095
66096Request.prototype.abort = function () {
66097 var self = this
66098 self._aborted = true
66099
66100 if (self.req) {
66101 self.req.abort()
66102 } else if (self.response) {
66103 self.response.destroy()
66104 }
66105
66106 self.emit('abort')
66107}
66108
66109Request.prototype.pipeDest = function (dest) {
66110 var self = this
66111 var response = self.response
66112 // Called after the response is received
66113 if (dest.headers && !dest.headersSent) {
66114 if (response.caseless.has('content-type')) {
66115 var ctname = response.caseless.has('content-type')
66116 if (dest.setHeader) {
66117 dest.setHeader(ctname, response.headers[ctname])
66118 } else {
66119 dest.headers[ctname] = response.headers[ctname]
66120 }
66121 }
66122
66123 if (response.caseless.has('content-length')) {
66124 var clname = response.caseless.has('content-length')
66125 if (dest.setHeader) {
66126 dest.setHeader(clname, response.headers[clname])
66127 } else {
66128 dest.headers[clname] = response.headers[clname]
66129 }
66130 }
66131 }
66132 if (dest.setHeader && !dest.headersSent) {
66133 for (var i in response.headers) {
66134 // If the response content is being decoded, the Content-Encoding header
66135 // of the response doesn't represent the piped content, so don't pass it.
66136 if (!self.gzip || i !== 'content-encoding') {
66137 dest.setHeader(i, response.headers[i])
66138 }
66139 }
66140 dest.statusCode = response.statusCode
66141 }
66142 if (self.pipefilter) {
66143 self.pipefilter(response, dest)
66144 }
66145}
66146
66147Request.prototype.qs = function (q, clobber) {
66148 var self = this
66149 var base
66150 if (!clobber && self.uri.query) {
66151 base = self._qs.parse(self.uri.query)
66152 } else {
66153 base = {}
66154 }
66155
66156 for (var i in q) {
66157 base[i] = q[i]
66158 }
66159
66160 var qs = self._qs.stringify(base)
66161
66162 if (qs === '') {
66163 return self
66164 }
66165
66166 self.uri = url.parse(self.uri.href.split('?')[0] + '?' + qs)
66167 self.url = self.uri
66168 self.path = self.uri.path
66169
66170 if (self.uri.host === 'unix') {
66171 self.enableUnixSocket()
66172 }
66173
66174 return self
66175}
66176Request.prototype.form = function (form) {
66177 var self = this
66178 if (form) {
66179 if (!/^application\/x-www-form-urlencoded\b/.test(self.getHeader('content-type'))) {
66180 self.setHeader('content-type', 'application/x-www-form-urlencoded')
66181 }
66182 self.body = (typeof form === 'string')
66183 ? self._qs.rfc3986(form.toString('utf8'))
66184 : self._qs.stringify(form).toString('utf8')
66185 return self
66186 }
66187 // create form-data object
66188 self._form = new FormData()
66189 self._form.on('error', function (err) {
66190 err.message = 'form-data: ' + err.message
66191 self.emit('error', err)
66192 self.abort()
66193 })
66194 return self._form
66195}
66196Request.prototype.multipart = function (multipart) {
66197 var self = this
66198
66199 self._multipart.onRequest(multipart)
66200
66201 if (!self._multipart.chunked) {
66202 self.body = self._multipart.body
66203 }
66204
66205 return self
66206}
66207Request.prototype.json = function (val) {
66208 var self = this
66209
66210 if (!self.hasHeader('accept')) {
66211 self.setHeader('accept', 'application/json')
66212 }
66213
66214 if (typeof self.jsonReplacer === 'function') {
66215 self._jsonReplacer = self.jsonReplacer
66216 }
66217
66218 self._json = true
66219 if (typeof val === 'boolean') {
66220 if (self.body !== undefined) {
66221 if (!/^application\/x-www-form-urlencoded\b/.test(self.getHeader('content-type'))) {
66222 self.body = safeStringify(self.body, self._jsonReplacer)
66223 } else {
66224 self.body = self._qs.rfc3986(self.body)
66225 }
66226 if (!self.hasHeader('content-type')) {
66227 self.setHeader('content-type', 'application/json')
66228 }
66229 }
66230 } else {
66231 self.body = safeStringify(val, self._jsonReplacer)
66232 if (!self.hasHeader('content-type')) {
66233 self.setHeader('content-type', 'application/json')
66234 }
66235 }
66236
66237 if (typeof self.jsonReviver === 'function') {
66238 self._jsonReviver = self.jsonReviver
66239 }
66240
66241 return self
66242}
66243Request.prototype.getHeader = function (name, headers) {
66244 var self = this
66245 var result, re, match
66246 if (!headers) {
66247 headers = self.headers
66248 }
66249 Object.keys(headers).forEach(function (key) {
66250 if (key.length !== name.length) {
66251 return
66252 }
66253 re = new RegExp(name, 'i')
66254 match = key.match(re)
66255 if (match) {
66256 result = headers[key]
66257 }
66258 })
66259 return result
66260}
66261Request.prototype.enableUnixSocket = function () {
66262 // Get the socket & request paths from the URL
66263 var unixParts = this.uri.path.split(':')
66264 var host = unixParts[0]
66265 var path = unixParts[1]
66266 // Apply unix properties to request
66267 this.socketPath = host
66268 this.uri.pathname = path
66269 this.uri.path = path
66270 this.uri.host = host
66271 this.uri.hostname = host
66272 this.uri.isUnix = true
66273}
66274
66275Request.prototype.auth = function (user, pass, sendImmediately, bearer) {
66276 var self = this
66277
66278 self._auth.onRequest(user, pass, sendImmediately, bearer)
66279
66280 return self
66281}
66282Request.prototype.aws = function (opts, now) {
66283 var self = this
66284
66285 if (!now) {
66286 self._aws = opts
66287 return self
66288 }
66289
66290 if (opts.sign_version === 4 || opts.sign_version === '4') {
66291 // use aws4
66292 var options = {
66293 host: self.uri.host,
66294 path: self.uri.path,
66295 method: self.method,
66296 headers: self.headers,
66297 body: self.body
66298 }
66299 if (opts.service) {
66300 options.service = opts.service
66301 }
66302 var signRes = aws4.sign(options, {
66303 accessKeyId: opts.key,
66304 secretAccessKey: opts.secret,
66305 sessionToken: opts.session
66306 })
66307 self.setHeader('authorization', signRes.headers.Authorization)
66308 self.setHeader('x-amz-date', signRes.headers['X-Amz-Date'])
66309 if (signRes.headers['X-Amz-Security-Token']) {
66310 self.setHeader('x-amz-security-token', signRes.headers['X-Amz-Security-Token'])
66311 }
66312 } else {
66313 // default: use aws-sign2
66314 var date = new Date()
66315 self.setHeader('date', date.toUTCString())
66316 var auth = {
66317 key: opts.key,
66318 secret: opts.secret,
66319 verb: self.method.toUpperCase(),
66320 date: date,
66321 contentType: self.getHeader('content-type') || '',
66322 md5: self.getHeader('content-md5') || '',
66323 amazonHeaders: aws2.canonicalizeHeaders(self.headers)
66324 }
66325 var path = self.uri.path
66326 if (opts.bucket && path) {
66327 auth.resource = '/' + opts.bucket + path
66328 } else if (opts.bucket && !path) {
66329 auth.resource = '/' + opts.bucket
66330 } else if (!opts.bucket && path) {
66331 auth.resource = path
66332 } else if (!opts.bucket && !path) {
66333 auth.resource = '/'
66334 }
66335 auth.resource = aws2.canonicalizeResource(auth.resource)
66336 self.setHeader('authorization', aws2.authorization(auth))
66337 }
66338
66339 return self
66340}
66341Request.prototype.httpSignature = function (opts) {
66342 var self = this
66343 httpSignature.signRequest({
66344 getHeader: function (header) {
66345 return self.getHeader(header, self.headers)
66346 },
66347 setHeader: function (header, value) {
66348 self.setHeader(header, value)
66349 },
66350 method: self.method,
66351 path: self.path
66352 }, opts)
66353 debug('httpSignature authorization', self.getHeader('authorization'))
66354
66355 return self
66356}
66357Request.prototype.hawk = function (opts) {
66358 var self = this
66359 self.setHeader('Authorization', hawk.header(self.uri, self.method, opts))
66360}
66361Request.prototype.oauth = function (_oauth) {
66362 var self = this
66363
66364 self._oauth.onRequest(_oauth)
66365
66366 return self
66367}
66368
66369Request.prototype.jar = function (jar) {
66370 var self = this
66371 var cookies
66372
66373 if (self._redirect.redirectsFollowed === 0) {
66374 self.originalCookieHeader = self.getHeader('cookie')
66375 }
66376
66377 if (!jar) {
66378 // disable cookies
66379 cookies = false
66380 self._disableCookies = true
66381 } else {
66382 var targetCookieJar = (jar && jar.getCookieString) ? jar : globalCookieJar
66383 var urihref = self.uri.href
66384 // fetch cookie in the Specified host
66385 if (targetCookieJar) {
66386 cookies = targetCookieJar.getCookieString(urihref)
66387 }
66388 }
66389
66390 // if need cookie and cookie is not empty
66391 if (cookies && cookies.length) {
66392 if (self.originalCookieHeader) {
66393 // Don't overwrite existing Cookie header
66394 self.setHeader('cookie', self.originalCookieHeader + '; ' + cookies)
66395 } else {
66396 self.setHeader('cookie', cookies)
66397 }
66398 }
66399 self._jar = jar
66400 return self
66401}
66402
66403// Stream API
66404Request.prototype.pipe = function (dest, opts) {
66405 var self = this
66406
66407 if (self.response) {
66408 if (self._destdata) {
66409 self.emit('error', new Error('You cannot pipe after data has been emitted from the response.'))
66410 } else if (self._ended) {
66411 self.emit('error', new Error('You cannot pipe after the response has been ended.'))
66412 } else {
66413 stream.Stream.prototype.pipe.call(self, dest, opts)
66414 self.pipeDest(dest)
66415 return dest
66416 }
66417 } else {
66418 self.dests.push(dest)
66419 stream.Stream.prototype.pipe.call(self, dest, opts)
66420 return dest
66421 }
66422}
66423Request.prototype.write = function () {
66424 var self = this
66425 if (self._aborted) { return }
66426
66427 if (!self._started) {
66428 self.start()
66429 }
66430 if (self.req) {
66431 return self.req.write.apply(self.req, arguments)
66432 }
66433}
66434Request.prototype.end = function (chunk) {
66435 var self = this
66436 if (self._aborted) { return }
66437
66438 if (chunk) {
66439 self.write(chunk)
66440 }
66441 if (!self._started) {
66442 self.start()
66443 }
66444 if (self.req) {
66445 self.req.end()
66446 }
66447}
66448Request.prototype.pause = function () {
66449 var self = this
66450 if (!self.responseContent) {
66451 self._paused = true
66452 } else {
66453 self.responseContent.pause.apply(self.responseContent, arguments)
66454 }
66455}
66456Request.prototype.resume = function () {
66457 var self = this
66458 if (!self.responseContent) {
66459 self._paused = false
66460 } else {
66461 self.responseContent.resume.apply(self.responseContent, arguments)
66462 }
66463}
66464Request.prototype.destroy = function () {
66465 var self = this
66466 if (!self._ended) {
66467 self.end()
66468 } else if (self.response) {
66469 self.response.destroy()
66470 }
66471}
66472
66473Request.defaultProxyHeaderWhiteList =
66474 Tunnel.defaultProxyHeaderWhiteList.slice()
66475
66476Request.defaultProxyHeaderExclusiveList =
66477 Tunnel.defaultProxyHeaderExclusiveList.slice()
66478
66479// Exports
66480
66481Request.prototype.toJSON = requestToJSON
66482module.exports = Request
66483
66484}).call(this,require('_process'))
66485},{"./lib/auth":300,"./lib/cookies":301,"./lib/getProxyFromURI":302,"./lib/har":303,"./lib/hawk":304,"./lib/helpers":305,"./lib/multipart":306,"./lib/oauth":307,"./lib/querystring":308,"./lib/redirect":309,"./lib/tunnel":310,"_process":265,"aws-sign2":72,"aws4":73,"caseless":116,"extend":161,"forever-agent":166,"form-data":167,"http":362,"http-signature":203,"https":208,"is-typedarray":212,"isstream":214,"mime-types":236,"performance-now":263,"safe-buffer":325,"stream":361,"url":393,"util":397,"zlib":111}],324:[function(require,module,exports){
66486'use strict'
66487var Buffer = require('buffer').Buffer
66488var inherits = require('inherits')
66489var HashBase = require('hash-base')
66490
66491var ARRAY16 = new Array(16)
66492
66493var zl = [
66494 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
66495 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8,
66496 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12,
66497 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2,
66498 4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13
66499]
66500
66501var zr = [
66502 5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12,
66503 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2,
66504 15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13,
66505 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14,
66506 12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11
66507]
66508
66509var sl = [
66510 11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8,
66511 7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12,
66512 11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5,
66513 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12,
66514 9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6
66515]
66516
66517var sr = [
66518 8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6,
66519 9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11,
66520 9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5,
66521 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8,
66522 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11
66523]
66524
66525var hl = [0x00000000, 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xa953fd4e]
66526var hr = [0x50a28be6, 0x5c4dd124, 0x6d703ef3, 0x7a6d76e9, 0x00000000]
66527
66528function RIPEMD160 () {
66529 HashBase.call(this, 64)
66530
66531 // state
66532 this._a = 0x67452301
66533 this._b = 0xefcdab89
66534 this._c = 0x98badcfe
66535 this._d = 0x10325476
66536 this._e = 0xc3d2e1f0
66537}
66538
66539inherits(RIPEMD160, HashBase)
66540
66541RIPEMD160.prototype._update = function () {
66542 var words = ARRAY16
66543 for (var j = 0; j < 16; ++j) words[j] = this._block.readInt32LE(j * 4)
66544
66545 var al = this._a | 0
66546 var bl = this._b | 0
66547 var cl = this._c | 0
66548 var dl = this._d | 0
66549 var el = this._e | 0
66550
66551 var ar = this._a | 0
66552 var br = this._b | 0
66553 var cr = this._c | 0
66554 var dr = this._d | 0
66555 var er = this._e | 0
66556
66557 // computation
66558 for (var i = 0; i < 80; i += 1) {
66559 var tl
66560 var tr
66561 if (i < 16) {
66562 tl = fn1(al, bl, cl, dl, el, words[zl[i]], hl[0], sl[i])
66563 tr = fn5(ar, br, cr, dr, er, words[zr[i]], hr[0], sr[i])
66564 } else if (i < 32) {
66565 tl = fn2(al, bl, cl, dl, el, words[zl[i]], hl[1], sl[i])
66566 tr = fn4(ar, br, cr, dr, er, words[zr[i]], hr[1], sr[i])
66567 } else if (i < 48) {
66568 tl = fn3(al, bl, cl, dl, el, words[zl[i]], hl[2], sl[i])
66569 tr = fn3(ar, br, cr, dr, er, words[zr[i]], hr[2], sr[i])
66570 } else if (i < 64) {
66571 tl = fn4(al, bl, cl, dl, el, words[zl[i]], hl[3], sl[i])
66572 tr = fn2(ar, br, cr, dr, er, words[zr[i]], hr[3], sr[i])
66573 } else { // if (i<80) {
66574 tl = fn5(al, bl, cl, dl, el, words[zl[i]], hl[4], sl[i])
66575 tr = fn1(ar, br, cr, dr, er, words[zr[i]], hr[4], sr[i])
66576 }
66577
66578 al = el
66579 el = dl
66580 dl = rotl(cl, 10)
66581 cl = bl
66582 bl = tl
66583
66584 ar = er
66585 er = dr
66586 dr = rotl(cr, 10)
66587 cr = br
66588 br = tr
66589 }
66590
66591 // update state
66592 var t = (this._b + cl + dr) | 0
66593 this._b = (this._c + dl + er) | 0
66594 this._c = (this._d + el + ar) | 0
66595 this._d = (this._e + al + br) | 0
66596 this._e = (this._a + bl + cr) | 0
66597 this._a = t
66598}
66599
66600RIPEMD160.prototype._digest = function () {
66601 // create padding and handle blocks
66602 this._block[this._blockOffset++] = 0x80
66603 if (this._blockOffset > 56) {
66604 this._block.fill(0, this._blockOffset, 64)
66605 this._update()
66606 this._blockOffset = 0
66607 }
66608
66609 this._block.fill(0, this._blockOffset, 56)
66610 this._block.writeUInt32LE(this._length[0], 56)
66611 this._block.writeUInt32LE(this._length[1], 60)
66612 this._update()
66613
66614 // produce result
66615 var buffer = Buffer.alloc ? Buffer.alloc(20) : new Buffer(20)
66616 buffer.writeInt32LE(this._a, 0)
66617 buffer.writeInt32LE(this._b, 4)
66618 buffer.writeInt32LE(this._c, 8)
66619 buffer.writeInt32LE(this._d, 12)
66620 buffer.writeInt32LE(this._e, 16)
66621 return buffer
66622}
66623
66624function rotl (x, n) {
66625 return (x << n) | (x >>> (32 - n))
66626}
66627
66628function fn1 (a, b, c, d, e, m, k, s) {
66629 return (rotl((a + (b ^ c ^ d) + m + k) | 0, s) + e) | 0
66630}
66631
66632function fn2 (a, b, c, d, e, m, k, s) {
66633 return (rotl((a + ((b & c) | ((~b) & d)) + m + k) | 0, s) + e) | 0
66634}
66635
66636function fn3 (a, b, c, d, e, m, k, s) {
66637 return (rotl((a + ((b | (~c)) ^ d) + m + k) | 0, s) + e) | 0
66638}
66639
66640function fn4 (a, b, c, d, e, m, k, s) {
66641 return (rotl((a + ((b & d) | (c & (~d))) + m + k) | 0, s) + e) | 0
66642}
66643
66644function fn5 (a, b, c, d, e, m, k, s) {
66645 return (rotl((a + (b ^ (c | (~d))) + m + k) | 0, s) + e) | 0
66646}
66647
66648module.exports = RIPEMD160
66649
66650},{"buffer":114,"hash-base":189,"inherits":210}],325:[function(require,module,exports){
66651/* eslint-disable node/no-deprecated-api */
66652var buffer = require('buffer')
66653var Buffer = buffer.Buffer
66654
66655// alternative to using Object.keys for old browsers
66656function copyProps (src, dst) {
66657 for (var key in src) {
66658 dst[key] = src[key]
66659 }
66660}
66661if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) {
66662 module.exports = buffer
66663} else {
66664 // Copy properties from require('buffer')
66665 copyProps(buffer, exports)
66666 exports.Buffer = SafeBuffer
66667}
66668
66669function SafeBuffer (arg, encodingOrOffset, length) {
66670 return Buffer(arg, encodingOrOffset, length)
66671}
66672
66673// Copy static methods from Buffer
66674copyProps(Buffer, SafeBuffer)
66675
66676SafeBuffer.from = function (arg, encodingOrOffset, length) {
66677 if (typeof arg === 'number') {
66678 throw new TypeError('Argument must not be a number')
66679 }
66680 return Buffer(arg, encodingOrOffset, length)
66681}
66682
66683SafeBuffer.alloc = function (size, fill, encoding) {
66684 if (typeof size !== 'number') {
66685 throw new TypeError('Argument must be a number')
66686 }
66687 var buf = Buffer(size)
66688 if (fill !== undefined) {
66689 if (typeof encoding === 'string') {
66690 buf.fill(fill, encoding)
66691 } else {
66692 buf.fill(fill)
66693 }
66694 } else {
66695 buf.fill(0)
66696 }
66697 return buf
66698}
66699
66700SafeBuffer.allocUnsafe = function (size) {
66701 if (typeof size !== 'number') {
66702 throw new TypeError('Argument must be a number')
66703 }
66704 return Buffer(size)
66705}
66706
66707SafeBuffer.allocUnsafeSlow = function (size) {
66708 if (typeof size !== 'number') {
66709 throw new TypeError('Argument must be a number')
66710 }
66711 return buffer.SlowBuffer(size)
66712}
66713
66714},{"buffer":114}],326:[function(require,module,exports){
66715(function (process){
66716/* eslint-disable node/no-deprecated-api */
66717
66718'use strict'
66719
66720var buffer = require('buffer')
66721var Buffer = buffer.Buffer
66722
66723var safer = {}
66724
66725var key
66726
66727for (key in buffer) {
66728 if (!buffer.hasOwnProperty(key)) continue
66729 if (key === 'SlowBuffer' || key === 'Buffer') continue
66730 safer[key] = buffer[key]
66731}
66732
66733var Safer = safer.Buffer = {}
66734for (key in Buffer) {
66735 if (!Buffer.hasOwnProperty(key)) continue
66736 if (key === 'allocUnsafe' || key === 'allocUnsafeSlow') continue
66737 Safer[key] = Buffer[key]
66738}
66739
66740safer.Buffer.prototype = Buffer.prototype
66741
66742if (!Safer.from || Safer.from === Uint8Array.from) {
66743 Safer.from = function (value, encodingOrOffset, length) {
66744 if (typeof value === 'number') {
66745 throw new TypeError('The "value" argument must not be of type number. Received type ' + typeof value)
66746 }
66747 if (value && typeof value.length === 'undefined') {
66748 throw new TypeError('The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type ' + typeof value)
66749 }
66750 return Buffer(value, encodingOrOffset, length)
66751 }
66752}
66753
66754if (!Safer.alloc) {
66755 Safer.alloc = function (size, fill, encoding) {
66756 if (typeof size !== 'number') {
66757 throw new TypeError('The "size" argument must be of type number. Received type ' + typeof size)
66758 }
66759 if (size < 0 || size >= 2 * (1 << 30)) {
66760 throw new RangeError('The value "' + size + '" is invalid for option "size"')
66761 }
66762 var buf = Buffer(size)
66763 if (!fill || fill.length === 0) {
66764 buf.fill(0)
66765 } else if (typeof encoding === 'string') {
66766 buf.fill(fill, encoding)
66767 } else {
66768 buf.fill(fill)
66769 }
66770 return buf
66771 }
66772}
66773
66774if (!safer.kStringMaxLength) {
66775 try {
66776 safer.kStringMaxLength = process.binding('buffer').kStringMaxLength
66777 } catch (e) {
66778 // we can't determine kStringMaxLength in environments where process.binding
66779 // is unsupported, so let's not set it
66780 }
66781}
66782
66783if (!safer.constants) {
66784 safer.constants = {
66785 MAX_LENGTH: safer.kMaxLength
66786 }
66787 if (safer.kStringMaxLength) {
66788 safer.constants.MAX_STRING_LENGTH = safer.kStringMaxLength
66789 }
66790}
66791
66792module.exports = safer
66793
66794}).call(this,require('_process'))
66795},{"_process":265,"buffer":114}],327:[function(require,module,exports){
66796var Buffer = require('safe-buffer').Buffer
66797
66798// prototype class for hash functions
66799function Hash (blockSize, finalSize) {
66800 this._block = Buffer.alloc(blockSize)
66801 this._finalSize = finalSize
66802 this._blockSize = blockSize
66803 this._len = 0
66804}
66805
66806Hash.prototype.update = function (data, enc) {
66807 if (typeof data === 'string') {
66808 enc = enc || 'utf8'
66809 data = Buffer.from(data, enc)
66810 }
66811
66812 var block = this._block
66813 var blockSize = this._blockSize
66814 var length = data.length
66815 var accum = this._len
66816
66817 for (var offset = 0; offset < length;) {
66818 var assigned = accum % blockSize
66819 var remainder = Math.min(length - offset, blockSize - assigned)
66820
66821 for (var i = 0; i < remainder; i++) {
66822 block[assigned + i] = data[offset + i]
66823 }
66824
66825 accum += remainder
66826 offset += remainder
66827
66828 if ((accum % blockSize) === 0) {
66829 this._update(block)
66830 }
66831 }
66832
66833 this._len += length
66834 return this
66835}
66836
66837Hash.prototype.digest = function (enc) {
66838 var rem = this._len % this._blockSize
66839
66840 this._block[rem] = 0x80
66841
66842 // zero (rem + 1) trailing bits, where (rem + 1) is the smallest
66843 // non-negative solution to the equation (length + 1 + (rem + 1)) === finalSize mod blockSize
66844 this._block.fill(0, rem + 1)
66845
66846 if (rem >= this._finalSize) {
66847 this._update(this._block)
66848 this._block.fill(0)
66849 }
66850
66851 var bits = this._len * 8
66852
66853 // uint32
66854 if (bits <= 0xffffffff) {
66855 this._block.writeUInt32BE(bits, this._blockSize - 4)
66856
66857 // uint64
66858 } else {
66859 var lowBits = (bits & 0xffffffff) >>> 0
66860 var highBits = (bits - lowBits) / 0x100000000
66861
66862 this._block.writeUInt32BE(highBits, this._blockSize - 8)
66863 this._block.writeUInt32BE(lowBits, this._blockSize - 4)
66864 }
66865
66866 this._update(this._block)
66867 var hash = this._hash()
66868
66869 return enc ? hash.toString(enc) : hash
66870}
66871
66872Hash.prototype._update = function () {
66873 throw new Error('_update must be implemented by subclass')
66874}
66875
66876module.exports = Hash
66877
66878},{"safe-buffer":325}],328:[function(require,module,exports){
66879var exports = module.exports = function SHA (algorithm) {
66880 algorithm = algorithm.toLowerCase()
66881
66882 var Algorithm = exports[algorithm]
66883 if (!Algorithm) throw new Error(algorithm + ' is not supported (we accept pull requests)')
66884
66885 return new Algorithm()
66886}
66887
66888exports.sha = require('./sha')
66889exports.sha1 = require('./sha1')
66890exports.sha224 = require('./sha224')
66891exports.sha256 = require('./sha256')
66892exports.sha384 = require('./sha384')
66893exports.sha512 = require('./sha512')
66894
66895},{"./sha":329,"./sha1":330,"./sha224":331,"./sha256":332,"./sha384":333,"./sha512":334}],329:[function(require,module,exports){
66896/*
66897 * A JavaScript implementation of the Secure Hash Algorithm, SHA-0, as defined
66898 * in FIPS PUB 180-1
66899 * This source code is derived from sha1.js of the same repository.
66900 * The difference between SHA-0 and SHA-1 is just a bitwise rotate left
66901 * operation was added.
66902 */
66903
66904var inherits = require('inherits')
66905var Hash = require('./hash')
66906var Buffer = require('safe-buffer').Buffer
66907
66908var K = [
66909 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc | 0, 0xca62c1d6 | 0
66910]
66911
66912var W = new Array(80)
66913
66914function Sha () {
66915 this.init()
66916 this._w = W
66917
66918 Hash.call(this, 64, 56)
66919}
66920
66921inherits(Sha, Hash)
66922
66923Sha.prototype.init = function () {
66924 this._a = 0x67452301
66925 this._b = 0xefcdab89
66926 this._c = 0x98badcfe
66927 this._d = 0x10325476
66928 this._e = 0xc3d2e1f0
66929
66930 return this
66931}
66932
66933function rotl5 (num) {
66934 return (num << 5) | (num >>> 27)
66935}
66936
66937function rotl30 (num) {
66938 return (num << 30) | (num >>> 2)
66939}
66940
66941function ft (s, b, c, d) {
66942 if (s === 0) return (b & c) | ((~b) & d)
66943 if (s === 2) return (b & c) | (b & d) | (c & d)
66944 return b ^ c ^ d
66945}
66946
66947Sha.prototype._update = function (M) {
66948 var W = this._w
66949
66950 var a = this._a | 0
66951 var b = this._b | 0
66952 var c = this._c | 0
66953 var d = this._d | 0
66954 var e = this._e | 0
66955
66956 for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4)
66957 for (; i < 80; ++i) W[i] = W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16]
66958
66959 for (var j = 0; j < 80; ++j) {
66960 var s = ~~(j / 20)
66961 var t = (rotl5(a) + ft(s, b, c, d) + e + W[j] + K[s]) | 0
66962
66963 e = d
66964 d = c
66965 c = rotl30(b)
66966 b = a
66967 a = t
66968 }
66969
66970 this._a = (a + this._a) | 0
66971 this._b = (b + this._b) | 0
66972 this._c = (c + this._c) | 0
66973 this._d = (d + this._d) | 0
66974 this._e = (e + this._e) | 0
66975}
66976
66977Sha.prototype._hash = function () {
66978 var H = Buffer.allocUnsafe(20)
66979
66980 H.writeInt32BE(this._a | 0, 0)
66981 H.writeInt32BE(this._b | 0, 4)
66982 H.writeInt32BE(this._c | 0, 8)
66983 H.writeInt32BE(this._d | 0, 12)
66984 H.writeInt32BE(this._e | 0, 16)
66985
66986 return H
66987}
66988
66989module.exports = Sha
66990
66991},{"./hash":327,"inherits":210,"safe-buffer":325}],330:[function(require,module,exports){
66992/*
66993 * A JavaScript implementation of the Secure Hash Algorithm, SHA-1, as defined
66994 * in FIPS PUB 180-1
66995 * Version 2.1a Copyright Paul Johnston 2000 - 2002.
66996 * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
66997 * Distributed under the BSD License
66998 * See http://pajhome.org.uk/crypt/md5 for details.
66999 */
67000
67001var inherits = require('inherits')
67002var Hash = require('./hash')
67003var Buffer = require('safe-buffer').Buffer
67004
67005var K = [
67006 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc | 0, 0xca62c1d6 | 0
67007]
67008
67009var W = new Array(80)
67010
67011function Sha1 () {
67012 this.init()
67013 this._w = W
67014
67015 Hash.call(this, 64, 56)
67016}
67017
67018inherits(Sha1, Hash)
67019
67020Sha1.prototype.init = function () {
67021 this._a = 0x67452301
67022 this._b = 0xefcdab89
67023 this._c = 0x98badcfe
67024 this._d = 0x10325476
67025 this._e = 0xc3d2e1f0
67026
67027 return this
67028}
67029
67030function rotl1 (num) {
67031 return (num << 1) | (num >>> 31)
67032}
67033
67034function rotl5 (num) {
67035 return (num << 5) | (num >>> 27)
67036}
67037
67038function rotl30 (num) {
67039 return (num << 30) | (num >>> 2)
67040}
67041
67042function ft (s, b, c, d) {
67043 if (s === 0) return (b & c) | ((~b) & d)
67044 if (s === 2) return (b & c) | (b & d) | (c & d)
67045 return b ^ c ^ d
67046}
67047
67048Sha1.prototype._update = function (M) {
67049 var W = this._w
67050
67051 var a = this._a | 0
67052 var b = this._b | 0
67053 var c = this._c | 0
67054 var d = this._d | 0
67055 var e = this._e | 0
67056
67057 for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4)
67058 for (; i < 80; ++i) W[i] = rotl1(W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16])
67059
67060 for (var j = 0; j < 80; ++j) {
67061 var s = ~~(j / 20)
67062 var t = (rotl5(a) + ft(s, b, c, d) + e + W[j] + K[s]) | 0
67063
67064 e = d
67065 d = c
67066 c = rotl30(b)
67067 b = a
67068 a = t
67069 }
67070
67071 this._a = (a + this._a) | 0
67072 this._b = (b + this._b) | 0
67073 this._c = (c + this._c) | 0
67074 this._d = (d + this._d) | 0
67075 this._e = (e + this._e) | 0
67076}
67077
67078Sha1.prototype._hash = function () {
67079 var H = Buffer.allocUnsafe(20)
67080
67081 H.writeInt32BE(this._a | 0, 0)
67082 H.writeInt32BE(this._b | 0, 4)
67083 H.writeInt32BE(this._c | 0, 8)
67084 H.writeInt32BE(this._d | 0, 12)
67085 H.writeInt32BE(this._e | 0, 16)
67086
67087 return H
67088}
67089
67090module.exports = Sha1
67091
67092},{"./hash":327,"inherits":210,"safe-buffer":325}],331:[function(require,module,exports){
67093/**
67094 * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined
67095 * in FIPS 180-2
67096 * Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009.
67097 * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
67098 *
67099 */
67100
67101var inherits = require('inherits')
67102var Sha256 = require('./sha256')
67103var Hash = require('./hash')
67104var Buffer = require('safe-buffer').Buffer
67105
67106var W = new Array(64)
67107
67108function Sha224 () {
67109 this.init()
67110
67111 this._w = W // new Array(64)
67112
67113 Hash.call(this, 64, 56)
67114}
67115
67116inherits(Sha224, Sha256)
67117
67118Sha224.prototype.init = function () {
67119 this._a = 0xc1059ed8
67120 this._b = 0x367cd507
67121 this._c = 0x3070dd17
67122 this._d = 0xf70e5939
67123 this._e = 0xffc00b31
67124 this._f = 0x68581511
67125 this._g = 0x64f98fa7
67126 this._h = 0xbefa4fa4
67127
67128 return this
67129}
67130
67131Sha224.prototype._hash = function () {
67132 var H = Buffer.allocUnsafe(28)
67133
67134 H.writeInt32BE(this._a, 0)
67135 H.writeInt32BE(this._b, 4)
67136 H.writeInt32BE(this._c, 8)
67137 H.writeInt32BE(this._d, 12)
67138 H.writeInt32BE(this._e, 16)
67139 H.writeInt32BE(this._f, 20)
67140 H.writeInt32BE(this._g, 24)
67141
67142 return H
67143}
67144
67145module.exports = Sha224
67146
67147},{"./hash":327,"./sha256":332,"inherits":210,"safe-buffer":325}],332:[function(require,module,exports){
67148/**
67149 * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined
67150 * in FIPS 180-2
67151 * Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009.
67152 * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
67153 *
67154 */
67155
67156var inherits = require('inherits')
67157var Hash = require('./hash')
67158var Buffer = require('safe-buffer').Buffer
67159
67160var K = [
67161 0x428A2F98, 0x71374491, 0xB5C0FBCF, 0xE9B5DBA5,
67162 0x3956C25B, 0x59F111F1, 0x923F82A4, 0xAB1C5ED5,
67163 0xD807AA98, 0x12835B01, 0x243185BE, 0x550C7DC3,
67164 0x72BE5D74, 0x80DEB1FE, 0x9BDC06A7, 0xC19BF174,
67165 0xE49B69C1, 0xEFBE4786, 0x0FC19DC6, 0x240CA1CC,
67166 0x2DE92C6F, 0x4A7484AA, 0x5CB0A9DC, 0x76F988DA,
67167 0x983E5152, 0xA831C66D, 0xB00327C8, 0xBF597FC7,
67168 0xC6E00BF3, 0xD5A79147, 0x06CA6351, 0x14292967,
67169 0x27B70A85, 0x2E1B2138, 0x4D2C6DFC, 0x53380D13,
67170 0x650A7354, 0x766A0ABB, 0x81C2C92E, 0x92722C85,
67171 0xA2BFE8A1, 0xA81A664B, 0xC24B8B70, 0xC76C51A3,
67172 0xD192E819, 0xD6990624, 0xF40E3585, 0x106AA070,
67173 0x19A4C116, 0x1E376C08, 0x2748774C, 0x34B0BCB5,
67174 0x391C0CB3, 0x4ED8AA4A, 0x5B9CCA4F, 0x682E6FF3,
67175 0x748F82EE, 0x78A5636F, 0x84C87814, 0x8CC70208,
67176 0x90BEFFFA, 0xA4506CEB, 0xBEF9A3F7, 0xC67178F2
67177]
67178
67179var W = new Array(64)
67180
67181function Sha256 () {
67182 this.init()
67183
67184 this._w = W // new Array(64)
67185
67186 Hash.call(this, 64, 56)
67187}
67188
67189inherits(Sha256, Hash)
67190
67191Sha256.prototype.init = function () {
67192 this._a = 0x6a09e667
67193 this._b = 0xbb67ae85
67194 this._c = 0x3c6ef372
67195 this._d = 0xa54ff53a
67196 this._e = 0x510e527f
67197 this._f = 0x9b05688c
67198 this._g = 0x1f83d9ab
67199 this._h = 0x5be0cd19
67200
67201 return this
67202}
67203
67204function ch (x, y, z) {
67205 return z ^ (x & (y ^ z))
67206}
67207
67208function maj (x, y, z) {
67209 return (x & y) | (z & (x | y))
67210}
67211
67212function sigma0 (x) {
67213 return (x >>> 2 | x << 30) ^ (x >>> 13 | x << 19) ^ (x >>> 22 | x << 10)
67214}
67215
67216function sigma1 (x) {
67217 return (x >>> 6 | x << 26) ^ (x >>> 11 | x << 21) ^ (x >>> 25 | x << 7)
67218}
67219
67220function gamma0 (x) {
67221 return (x >>> 7 | x << 25) ^ (x >>> 18 | x << 14) ^ (x >>> 3)
67222}
67223
67224function gamma1 (x) {
67225 return (x >>> 17 | x << 15) ^ (x >>> 19 | x << 13) ^ (x >>> 10)
67226}
67227
67228Sha256.prototype._update = function (M) {
67229 var W = this._w
67230
67231 var a = this._a | 0
67232 var b = this._b | 0
67233 var c = this._c | 0
67234 var d = this._d | 0
67235 var e = this._e | 0
67236 var f = this._f | 0
67237 var g = this._g | 0
67238 var h = this._h | 0
67239
67240 for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4)
67241 for (; i < 64; ++i) W[i] = (gamma1(W[i - 2]) + W[i - 7] + gamma0(W[i - 15]) + W[i - 16]) | 0
67242
67243 for (var j = 0; j < 64; ++j) {
67244 var T1 = (h + sigma1(e) + ch(e, f, g) + K[j] + W[j]) | 0
67245 var T2 = (sigma0(a) + maj(a, b, c)) | 0
67246
67247 h = g
67248 g = f
67249 f = e
67250 e = (d + T1) | 0
67251 d = c
67252 c = b
67253 b = a
67254 a = (T1 + T2) | 0
67255 }
67256
67257 this._a = (a + this._a) | 0
67258 this._b = (b + this._b) | 0
67259 this._c = (c + this._c) | 0
67260 this._d = (d + this._d) | 0
67261 this._e = (e + this._e) | 0
67262 this._f = (f + this._f) | 0
67263 this._g = (g + this._g) | 0
67264 this._h = (h + this._h) | 0
67265}
67266
67267Sha256.prototype._hash = function () {
67268 var H = Buffer.allocUnsafe(32)
67269
67270 H.writeInt32BE(this._a, 0)
67271 H.writeInt32BE(this._b, 4)
67272 H.writeInt32BE(this._c, 8)
67273 H.writeInt32BE(this._d, 12)
67274 H.writeInt32BE(this._e, 16)
67275 H.writeInt32BE(this._f, 20)
67276 H.writeInt32BE(this._g, 24)
67277 H.writeInt32BE(this._h, 28)
67278
67279 return H
67280}
67281
67282module.exports = Sha256
67283
67284},{"./hash":327,"inherits":210,"safe-buffer":325}],333:[function(require,module,exports){
67285var inherits = require('inherits')
67286var SHA512 = require('./sha512')
67287var Hash = require('./hash')
67288var Buffer = require('safe-buffer').Buffer
67289
67290var W = new Array(160)
67291
67292function Sha384 () {
67293 this.init()
67294 this._w = W
67295
67296 Hash.call(this, 128, 112)
67297}
67298
67299inherits(Sha384, SHA512)
67300
67301Sha384.prototype.init = function () {
67302 this._ah = 0xcbbb9d5d
67303 this._bh = 0x629a292a
67304 this._ch = 0x9159015a
67305 this._dh = 0x152fecd8
67306 this._eh = 0x67332667
67307 this._fh = 0x8eb44a87
67308 this._gh = 0xdb0c2e0d
67309 this._hh = 0x47b5481d
67310
67311 this._al = 0xc1059ed8
67312 this._bl = 0x367cd507
67313 this._cl = 0x3070dd17
67314 this._dl = 0xf70e5939
67315 this._el = 0xffc00b31
67316 this._fl = 0x68581511
67317 this._gl = 0x64f98fa7
67318 this._hl = 0xbefa4fa4
67319
67320 return this
67321}
67322
67323Sha384.prototype._hash = function () {
67324 var H = Buffer.allocUnsafe(48)
67325
67326 function writeInt64BE (h, l, offset) {
67327 H.writeInt32BE(h, offset)
67328 H.writeInt32BE(l, offset + 4)
67329 }
67330
67331 writeInt64BE(this._ah, this._al, 0)
67332 writeInt64BE(this._bh, this._bl, 8)
67333 writeInt64BE(this._ch, this._cl, 16)
67334 writeInt64BE(this._dh, this._dl, 24)
67335 writeInt64BE(this._eh, this._el, 32)
67336 writeInt64BE(this._fh, this._fl, 40)
67337
67338 return H
67339}
67340
67341module.exports = Sha384
67342
67343},{"./hash":327,"./sha512":334,"inherits":210,"safe-buffer":325}],334:[function(require,module,exports){
67344var inherits = require('inherits')
67345var Hash = require('./hash')
67346var Buffer = require('safe-buffer').Buffer
67347
67348var K = [
67349 0x428a2f98, 0xd728ae22, 0x71374491, 0x23ef65cd,
67350 0xb5c0fbcf, 0xec4d3b2f, 0xe9b5dba5, 0x8189dbbc,
67351 0x3956c25b, 0xf348b538, 0x59f111f1, 0xb605d019,
67352 0x923f82a4, 0xaf194f9b, 0xab1c5ed5, 0xda6d8118,
67353 0xd807aa98, 0xa3030242, 0x12835b01, 0x45706fbe,
67354 0x243185be, 0x4ee4b28c, 0x550c7dc3, 0xd5ffb4e2,
67355 0x72be5d74, 0xf27b896f, 0x80deb1fe, 0x3b1696b1,
67356 0x9bdc06a7, 0x25c71235, 0xc19bf174, 0xcf692694,
67357 0xe49b69c1, 0x9ef14ad2, 0xefbe4786, 0x384f25e3,
67358 0x0fc19dc6, 0x8b8cd5b5, 0x240ca1cc, 0x77ac9c65,
67359 0x2de92c6f, 0x592b0275, 0x4a7484aa, 0x6ea6e483,
67360 0x5cb0a9dc, 0xbd41fbd4, 0x76f988da, 0x831153b5,
67361 0x983e5152, 0xee66dfab, 0xa831c66d, 0x2db43210,
67362 0xb00327c8, 0x98fb213f, 0xbf597fc7, 0xbeef0ee4,
67363 0xc6e00bf3, 0x3da88fc2, 0xd5a79147, 0x930aa725,
67364 0x06ca6351, 0xe003826f, 0x14292967, 0x0a0e6e70,
67365 0x27b70a85, 0x46d22ffc, 0x2e1b2138, 0x5c26c926,
67366 0x4d2c6dfc, 0x5ac42aed, 0x53380d13, 0x9d95b3df,
67367 0x650a7354, 0x8baf63de, 0x766a0abb, 0x3c77b2a8,
67368 0x81c2c92e, 0x47edaee6, 0x92722c85, 0x1482353b,
67369 0xa2bfe8a1, 0x4cf10364, 0xa81a664b, 0xbc423001,
67370 0xc24b8b70, 0xd0f89791, 0xc76c51a3, 0x0654be30,
67371 0xd192e819, 0xd6ef5218, 0xd6990624, 0x5565a910,
67372 0xf40e3585, 0x5771202a, 0x106aa070, 0x32bbd1b8,
67373 0x19a4c116, 0xb8d2d0c8, 0x1e376c08, 0x5141ab53,
67374 0x2748774c, 0xdf8eeb99, 0x34b0bcb5, 0xe19b48a8,
67375 0x391c0cb3, 0xc5c95a63, 0x4ed8aa4a, 0xe3418acb,
67376 0x5b9cca4f, 0x7763e373, 0x682e6ff3, 0xd6b2b8a3,
67377 0x748f82ee, 0x5defb2fc, 0x78a5636f, 0x43172f60,
67378 0x84c87814, 0xa1f0ab72, 0x8cc70208, 0x1a6439ec,
67379 0x90befffa, 0x23631e28, 0xa4506ceb, 0xde82bde9,
67380 0xbef9a3f7, 0xb2c67915, 0xc67178f2, 0xe372532b,
67381 0xca273ece, 0xea26619c, 0xd186b8c7, 0x21c0c207,
67382 0xeada7dd6, 0xcde0eb1e, 0xf57d4f7f, 0xee6ed178,
67383 0x06f067aa, 0x72176fba, 0x0a637dc5, 0xa2c898a6,
67384 0x113f9804, 0xbef90dae, 0x1b710b35, 0x131c471b,
67385 0x28db77f5, 0x23047d84, 0x32caab7b, 0x40c72493,
67386 0x3c9ebe0a, 0x15c9bebc, 0x431d67c4, 0x9c100d4c,
67387 0x4cc5d4be, 0xcb3e42b6, 0x597f299c, 0xfc657e2a,
67388 0x5fcb6fab, 0x3ad6faec, 0x6c44198c, 0x4a475817
67389]
67390
67391var W = new Array(160)
67392
67393function Sha512 () {
67394 this.init()
67395 this._w = W
67396
67397 Hash.call(this, 128, 112)
67398}
67399
67400inherits(Sha512, Hash)
67401
67402Sha512.prototype.init = function () {
67403 this._ah = 0x6a09e667
67404 this._bh = 0xbb67ae85
67405 this._ch = 0x3c6ef372
67406 this._dh = 0xa54ff53a
67407 this._eh = 0x510e527f
67408 this._fh = 0x9b05688c
67409 this._gh = 0x1f83d9ab
67410 this._hh = 0x5be0cd19
67411
67412 this._al = 0xf3bcc908
67413 this._bl = 0x84caa73b
67414 this._cl = 0xfe94f82b
67415 this._dl = 0x5f1d36f1
67416 this._el = 0xade682d1
67417 this._fl = 0x2b3e6c1f
67418 this._gl = 0xfb41bd6b
67419 this._hl = 0x137e2179
67420
67421 return this
67422}
67423
67424function Ch (x, y, z) {
67425 return z ^ (x & (y ^ z))
67426}
67427
67428function maj (x, y, z) {
67429 return (x & y) | (z & (x | y))
67430}
67431
67432function sigma0 (x, xl) {
67433 return (x >>> 28 | xl << 4) ^ (xl >>> 2 | x << 30) ^ (xl >>> 7 | x << 25)
67434}
67435
67436function sigma1 (x, xl) {
67437 return (x >>> 14 | xl << 18) ^ (x >>> 18 | xl << 14) ^ (xl >>> 9 | x << 23)
67438}
67439
67440function Gamma0 (x, xl) {
67441 return (x >>> 1 | xl << 31) ^ (x >>> 8 | xl << 24) ^ (x >>> 7)
67442}
67443
67444function Gamma0l (x, xl) {
67445 return (x >>> 1 | xl << 31) ^ (x >>> 8 | xl << 24) ^ (x >>> 7 | xl << 25)
67446}
67447
67448function Gamma1 (x, xl) {
67449 return (x >>> 19 | xl << 13) ^ (xl >>> 29 | x << 3) ^ (x >>> 6)
67450}
67451
67452function Gamma1l (x, xl) {
67453 return (x >>> 19 | xl << 13) ^ (xl >>> 29 | x << 3) ^ (x >>> 6 | xl << 26)
67454}
67455
67456function getCarry (a, b) {
67457 return (a >>> 0) < (b >>> 0) ? 1 : 0
67458}
67459
67460Sha512.prototype._update = function (M) {
67461 var W = this._w
67462
67463 var ah = this._ah | 0
67464 var bh = this._bh | 0
67465 var ch = this._ch | 0
67466 var dh = this._dh | 0
67467 var eh = this._eh | 0
67468 var fh = this._fh | 0
67469 var gh = this._gh | 0
67470 var hh = this._hh | 0
67471
67472 var al = this._al | 0
67473 var bl = this._bl | 0
67474 var cl = this._cl | 0
67475 var dl = this._dl | 0
67476 var el = this._el | 0
67477 var fl = this._fl | 0
67478 var gl = this._gl | 0
67479 var hl = this._hl | 0
67480
67481 for (var i = 0; i < 32; i += 2) {
67482 W[i] = M.readInt32BE(i * 4)
67483 W[i + 1] = M.readInt32BE(i * 4 + 4)
67484 }
67485 for (; i < 160; i += 2) {
67486 var xh = W[i - 15 * 2]
67487 var xl = W[i - 15 * 2 + 1]
67488 var gamma0 = Gamma0(xh, xl)
67489 var gamma0l = Gamma0l(xl, xh)
67490
67491 xh = W[i - 2 * 2]
67492 xl = W[i - 2 * 2 + 1]
67493 var gamma1 = Gamma1(xh, xl)
67494 var gamma1l = Gamma1l(xl, xh)
67495
67496 // W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16]
67497 var Wi7h = W[i - 7 * 2]
67498 var Wi7l = W[i - 7 * 2 + 1]
67499
67500 var Wi16h = W[i - 16 * 2]
67501 var Wi16l = W[i - 16 * 2 + 1]
67502
67503 var Wil = (gamma0l + Wi7l) | 0
67504 var Wih = (gamma0 + Wi7h + getCarry(Wil, gamma0l)) | 0
67505 Wil = (Wil + gamma1l) | 0
67506 Wih = (Wih + gamma1 + getCarry(Wil, gamma1l)) | 0
67507 Wil = (Wil + Wi16l) | 0
67508 Wih = (Wih + Wi16h + getCarry(Wil, Wi16l)) | 0
67509
67510 W[i] = Wih
67511 W[i + 1] = Wil
67512 }
67513
67514 for (var j = 0; j < 160; j += 2) {
67515 Wih = W[j]
67516 Wil = W[j + 1]
67517
67518 var majh = maj(ah, bh, ch)
67519 var majl = maj(al, bl, cl)
67520
67521 var sigma0h = sigma0(ah, al)
67522 var sigma0l = sigma0(al, ah)
67523 var sigma1h = sigma1(eh, el)
67524 var sigma1l = sigma1(el, eh)
67525
67526 // t1 = h + sigma1 + ch + K[j] + W[j]
67527 var Kih = K[j]
67528 var Kil = K[j + 1]
67529
67530 var chh = Ch(eh, fh, gh)
67531 var chl = Ch(el, fl, gl)
67532
67533 var t1l = (hl + sigma1l) | 0
67534 var t1h = (hh + sigma1h + getCarry(t1l, hl)) | 0
67535 t1l = (t1l + chl) | 0
67536 t1h = (t1h + chh + getCarry(t1l, chl)) | 0
67537 t1l = (t1l + Kil) | 0
67538 t1h = (t1h + Kih + getCarry(t1l, Kil)) | 0
67539 t1l = (t1l + Wil) | 0
67540 t1h = (t1h + Wih + getCarry(t1l, Wil)) | 0
67541
67542 // t2 = sigma0 + maj
67543 var t2l = (sigma0l + majl) | 0
67544 var t2h = (sigma0h + majh + getCarry(t2l, sigma0l)) | 0
67545
67546 hh = gh
67547 hl = gl
67548 gh = fh
67549 gl = fl
67550 fh = eh
67551 fl = el
67552 el = (dl + t1l) | 0
67553 eh = (dh + t1h + getCarry(el, dl)) | 0
67554 dh = ch
67555 dl = cl
67556 ch = bh
67557 cl = bl
67558 bh = ah
67559 bl = al
67560 al = (t1l + t2l) | 0
67561 ah = (t1h + t2h + getCarry(al, t1l)) | 0
67562 }
67563
67564 this._al = (this._al + al) | 0
67565 this._bl = (this._bl + bl) | 0
67566 this._cl = (this._cl + cl) | 0
67567 this._dl = (this._dl + dl) | 0
67568 this._el = (this._el + el) | 0
67569 this._fl = (this._fl + fl) | 0
67570 this._gl = (this._gl + gl) | 0
67571 this._hl = (this._hl + hl) | 0
67572
67573 this._ah = (this._ah + ah + getCarry(this._al, al)) | 0
67574 this._bh = (this._bh + bh + getCarry(this._bl, bl)) | 0
67575 this._ch = (this._ch + ch + getCarry(this._cl, cl)) | 0
67576 this._dh = (this._dh + dh + getCarry(this._dl, dl)) | 0
67577 this._eh = (this._eh + eh + getCarry(this._el, el)) | 0
67578 this._fh = (this._fh + fh + getCarry(this._fl, fl)) | 0
67579 this._gh = (this._gh + gh + getCarry(this._gl, gl)) | 0
67580 this._hh = (this._hh + hh + getCarry(this._hl, hl)) | 0
67581}
67582
67583Sha512.prototype._hash = function () {
67584 var H = Buffer.allocUnsafe(64)
67585
67586 function writeInt64BE (h, l, offset) {
67587 H.writeInt32BE(h, offset)
67588 H.writeInt32BE(l, offset + 4)
67589 }
67590
67591 writeInt64BE(this._ah, this._al, 0)
67592 writeInt64BE(this._bh, this._bl, 8)
67593 writeInt64BE(this._ch, this._cl, 16)
67594 writeInt64BE(this._dh, this._dl, 24)
67595 writeInt64BE(this._eh, this._el, 32)
67596 writeInt64BE(this._fh, this._fl, 40)
67597 writeInt64BE(this._gh, this._gl, 48)
67598 writeInt64BE(this._hh, this._hl, 56)
67599
67600 return H
67601}
67602
67603module.exports = Sha512
67604
67605},{"./hash":327,"inherits":210,"safe-buffer":325}],335:[function(require,module,exports){
67606// Copyright 2015 Joyent, Inc.
67607
67608var Buffer = require('safer-buffer').Buffer;
67609
67610var algInfo = {
67611 'dsa': {
67612 parts: ['p', 'q', 'g', 'y'],
67613 sizePart: 'p'
67614 },
67615 'rsa': {
67616 parts: ['e', 'n'],
67617 sizePart: 'n'
67618 },
67619 'ecdsa': {
67620 parts: ['curve', 'Q'],
67621 sizePart: 'Q'
67622 },
67623 'ed25519': {
67624 parts: ['A'],
67625 sizePart: 'A'
67626 }
67627};
67628algInfo['curve25519'] = algInfo['ed25519'];
67629
67630var algPrivInfo = {
67631 'dsa': {
67632 parts: ['p', 'q', 'g', 'y', 'x']
67633 },
67634 'rsa': {
67635 parts: ['n', 'e', 'd', 'iqmp', 'p', 'q']
67636 },
67637 'ecdsa': {
67638 parts: ['curve', 'Q', 'd']
67639 },
67640 'ed25519': {
67641 parts: ['A', 'k']
67642 }
67643};
67644algPrivInfo['curve25519'] = algPrivInfo['ed25519'];
67645
67646var hashAlgs = {
67647 'md5': true,
67648 'sha1': true,
67649 'sha256': true,
67650 'sha384': true,
67651 'sha512': true
67652};
67653
67654/*
67655 * Taken from
67656 * http://csrc.nist.gov/groups/ST/toolkit/documents/dss/NISTReCur.pdf
67657 */
67658var curves = {
67659 'nistp256': {
67660 size: 256,
67661 pkcs8oid: '1.2.840.10045.3.1.7',
67662 p: Buffer.from(('00' +
67663 'ffffffff 00000001 00000000 00000000' +
67664 '00000000 ffffffff ffffffff ffffffff').
67665 replace(/ /g, ''), 'hex'),
67666 a: Buffer.from(('00' +
67667 'FFFFFFFF 00000001 00000000 00000000' +
67668 '00000000 FFFFFFFF FFFFFFFF FFFFFFFC').
67669 replace(/ /g, ''), 'hex'),
67670 b: Buffer.from((
67671 '5ac635d8 aa3a93e7 b3ebbd55 769886bc' +
67672 '651d06b0 cc53b0f6 3bce3c3e 27d2604b').
67673 replace(/ /g, ''), 'hex'),
67674 s: Buffer.from(('00' +
67675 'c49d3608 86e70493 6a6678e1 139d26b7' +
67676 '819f7e90').
67677 replace(/ /g, ''), 'hex'),
67678 n: Buffer.from(('00' +
67679 'ffffffff 00000000 ffffffff ffffffff' +
67680 'bce6faad a7179e84 f3b9cac2 fc632551').
67681 replace(/ /g, ''), 'hex'),
67682 G: Buffer.from(('04' +
67683 '6b17d1f2 e12c4247 f8bce6e5 63a440f2' +
67684 '77037d81 2deb33a0 f4a13945 d898c296' +
67685 '4fe342e2 fe1a7f9b 8ee7eb4a 7c0f9e16' +
67686 '2bce3357 6b315ece cbb64068 37bf51f5').
67687 replace(/ /g, ''), 'hex')
67688 },
67689 'nistp384': {
67690 size: 384,
67691 pkcs8oid: '1.3.132.0.34',
67692 p: Buffer.from(('00' +
67693 'ffffffff ffffffff ffffffff ffffffff' +
67694 'ffffffff ffffffff ffffffff fffffffe' +
67695 'ffffffff 00000000 00000000 ffffffff').
67696 replace(/ /g, ''), 'hex'),
67697 a: Buffer.from(('00' +
67698 'FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFF' +
67699 'FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFE' +
67700 'FFFFFFFF 00000000 00000000 FFFFFFFC').
67701 replace(/ /g, ''), 'hex'),
67702 b: Buffer.from((
67703 'b3312fa7 e23ee7e4 988e056b e3f82d19' +
67704 '181d9c6e fe814112 0314088f 5013875a' +
67705 'c656398d 8a2ed19d 2a85c8ed d3ec2aef').
67706 replace(/ /g, ''), 'hex'),
67707 s: Buffer.from(('00' +
67708 'a335926a a319a27a 1d00896a 6773a482' +
67709 '7acdac73').
67710 replace(/ /g, ''), 'hex'),
67711 n: Buffer.from(('00' +
67712 'ffffffff ffffffff ffffffff ffffffff' +
67713 'ffffffff ffffffff c7634d81 f4372ddf' +
67714 '581a0db2 48b0a77a ecec196a ccc52973').
67715 replace(/ /g, ''), 'hex'),
67716 G: Buffer.from(('04' +
67717 'aa87ca22 be8b0537 8eb1c71e f320ad74' +
67718 '6e1d3b62 8ba79b98 59f741e0 82542a38' +
67719 '5502f25d bf55296c 3a545e38 72760ab7' +
67720 '3617de4a 96262c6f 5d9e98bf 9292dc29' +
67721 'f8f41dbd 289a147c e9da3113 b5f0b8c0' +
67722 '0a60b1ce 1d7e819d 7a431d7c 90ea0e5f').
67723 replace(/ /g, ''), 'hex')
67724 },
67725 'nistp521': {
67726 size: 521,
67727 pkcs8oid: '1.3.132.0.35',
67728 p: Buffer.from((
67729 '01ffffff ffffffff ffffffff ffffffff' +
67730 'ffffffff ffffffff ffffffff ffffffff' +
67731 'ffffffff ffffffff ffffffff ffffffff' +
67732 'ffffffff ffffffff ffffffff ffffffff' +
67733 'ffff').replace(/ /g, ''), 'hex'),
67734 a: Buffer.from(('01FF' +
67735 'FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFF' +
67736 'FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFF' +
67737 'FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFF' +
67738 'FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFC').
67739 replace(/ /g, ''), 'hex'),
67740 b: Buffer.from(('51' +
67741 '953eb961 8e1c9a1f 929a21a0 b68540ee' +
67742 'a2da725b 99b315f3 b8b48991 8ef109e1' +
67743 '56193951 ec7e937b 1652c0bd 3bb1bf07' +
67744 '3573df88 3d2c34f1 ef451fd4 6b503f00').
67745 replace(/ /g, ''), 'hex'),
67746 s: Buffer.from(('00' +
67747 'd09e8800 291cb853 96cc6717 393284aa' +
67748 'a0da64ba').replace(/ /g, ''), 'hex'),
67749 n: Buffer.from(('01ff' +
67750 'ffffffff ffffffff ffffffff ffffffff' +
67751 'ffffffff ffffffff ffffffff fffffffa' +
67752 '51868783 bf2f966b 7fcc0148 f709a5d0' +
67753 '3bb5c9b8 899c47ae bb6fb71e 91386409').
67754 replace(/ /g, ''), 'hex'),
67755 G: Buffer.from(('04' +
67756 '00c6 858e06b7 0404e9cd 9e3ecb66 2395b442' +
67757 '9c648139 053fb521 f828af60 6b4d3dba' +
67758 'a14b5e77 efe75928 fe1dc127 a2ffa8de' +
67759 '3348b3c1 856a429b f97e7e31 c2e5bd66' +
67760 '0118 39296a78 9a3bc004 5c8a5fb4 2c7d1bd9' +
67761 '98f54449 579b4468 17afbd17 273e662c' +
67762 '97ee7299 5ef42640 c550b901 3fad0761' +
67763 '353c7086 a272c240 88be9476 9fd16650').
67764 replace(/ /g, ''), 'hex')
67765 }
67766};
67767
67768module.exports = {
67769 info: algInfo,
67770 privInfo: algPrivInfo,
67771 hashAlgs: hashAlgs,
67772 curves: curves
67773};
67774
67775},{"safer-buffer":326}],336:[function(require,module,exports){
67776// Copyright 2016 Joyent, Inc.
67777
67778module.exports = Certificate;
67779
67780var assert = require('assert-plus');
67781var Buffer = require('safer-buffer').Buffer;
67782var algs = require('./algs');
67783var crypto = require('crypto');
67784var Fingerprint = require('./fingerprint');
67785var Signature = require('./signature');
67786var errs = require('./errors');
67787var util = require('util');
67788var utils = require('./utils');
67789var Key = require('./key');
67790var PrivateKey = require('./private-key');
67791var Identity = require('./identity');
67792
67793var formats = {};
67794formats['openssh'] = require('./formats/openssh-cert');
67795formats['x509'] = require('./formats/x509');
67796formats['pem'] = require('./formats/x509-pem');
67797
67798var CertificateParseError = errs.CertificateParseError;
67799var InvalidAlgorithmError = errs.InvalidAlgorithmError;
67800
67801function Certificate(opts) {
67802 assert.object(opts, 'options');
67803 assert.arrayOfObject(opts.subjects, 'options.subjects');
67804 utils.assertCompatible(opts.subjects[0], Identity, [1, 0],
67805 'options.subjects');
67806 utils.assertCompatible(opts.subjectKey, Key, [1, 0],
67807 'options.subjectKey');
67808 utils.assertCompatible(opts.issuer, Identity, [1, 0], 'options.issuer');
67809 if (opts.issuerKey !== undefined) {
67810 utils.assertCompatible(opts.issuerKey, Key, [1, 0],
67811 'options.issuerKey');
67812 }
67813 assert.object(opts.signatures, 'options.signatures');
67814 assert.buffer(opts.serial, 'options.serial');
67815 assert.date(opts.validFrom, 'options.validFrom');
67816 assert.date(opts.validUntil, 'optons.validUntil');
67817
67818 assert.optionalArrayOfString(opts.purposes, 'options.purposes');
67819
67820 this._hashCache = {};
67821
67822 this.subjects = opts.subjects;
67823 this.issuer = opts.issuer;
67824 this.subjectKey = opts.subjectKey;
67825 this.issuerKey = opts.issuerKey;
67826 this.signatures = opts.signatures;
67827 this.serial = opts.serial;
67828 this.validFrom = opts.validFrom;
67829 this.validUntil = opts.validUntil;
67830 this.purposes = opts.purposes;
67831}
67832
67833Certificate.formats = formats;
67834
67835Certificate.prototype.toBuffer = function (format, options) {
67836 if (format === undefined)
67837 format = 'x509';
67838 assert.string(format, 'format');
67839 assert.object(formats[format], 'formats[format]');
67840 assert.optionalObject(options, 'options');
67841
67842 return (formats[format].write(this, options));
67843};
67844
67845Certificate.prototype.toString = function (format, options) {
67846 if (format === undefined)
67847 format = 'pem';
67848 return (this.toBuffer(format, options).toString());
67849};
67850
67851Certificate.prototype.fingerprint = function (algo) {
67852 if (algo === undefined)
67853 algo = 'sha256';
67854 assert.string(algo, 'algorithm');
67855 var opts = {
67856 type: 'certificate',
67857 hash: this.hash(algo),
67858 algorithm: algo
67859 };
67860 return (new Fingerprint(opts));
67861};
67862
67863Certificate.prototype.hash = function (algo) {
67864 assert.string(algo, 'algorithm');
67865 algo = algo.toLowerCase();
67866 if (algs.hashAlgs[algo] === undefined)
67867 throw (new InvalidAlgorithmError(algo));
67868
67869 if (this._hashCache[algo])
67870 return (this._hashCache[algo]);
67871
67872 var hash = crypto.createHash(algo).
67873 update(this.toBuffer('x509')).digest();
67874 this._hashCache[algo] = hash;
67875 return (hash);
67876};
67877
67878Certificate.prototype.isExpired = function (when) {
67879 if (when === undefined)
67880 when = new Date();
67881 return (!((when.getTime() >= this.validFrom.getTime()) &&
67882 (when.getTime() < this.validUntil.getTime())));
67883};
67884
67885Certificate.prototype.isSignedBy = function (issuerCert) {
67886 utils.assertCompatible(issuerCert, Certificate, [1, 0], 'issuer');
67887
67888 if (!this.issuer.equals(issuerCert.subjects[0]))
67889 return (false);
67890 if (this.issuer.purposes && this.issuer.purposes.length > 0 &&
67891 this.issuer.purposes.indexOf('ca') === -1) {
67892 return (false);
67893 }
67894
67895 return (this.isSignedByKey(issuerCert.subjectKey));
67896};
67897
67898Certificate.prototype.getExtension = function (keyOrOid) {
67899 assert.string(keyOrOid, 'keyOrOid');
67900 var ext = this.getExtensions().filter(function (maybeExt) {
67901 if (maybeExt.format === 'x509')
67902 return (maybeExt.oid === keyOrOid);
67903 if (maybeExt.format === 'openssh')
67904 return (maybeExt.name === keyOrOid);
67905 return (false);
67906 })[0];
67907 return (ext);
67908};
67909
67910Certificate.prototype.getExtensions = function () {
67911 var exts = [];
67912 var x509 = this.signatures.x509;
67913 if (x509 && x509.extras && x509.extras.exts) {
67914 x509.extras.exts.forEach(function (ext) {
67915 ext.format = 'x509';
67916 exts.push(ext);
67917 });
67918 }
67919 var openssh = this.signatures.openssh;
67920 if (openssh && openssh.exts) {
67921 openssh.exts.forEach(function (ext) {
67922 ext.format = 'openssh';
67923 exts.push(ext);
67924 });
67925 }
67926 return (exts);
67927};
67928
67929Certificate.prototype.isSignedByKey = function (issuerKey) {
67930 utils.assertCompatible(issuerKey, Key, [1, 2], 'issuerKey');
67931
67932 if (this.issuerKey !== undefined) {
67933 return (this.issuerKey.
67934 fingerprint('sha512').matches(issuerKey));
67935 }
67936
67937 var fmt = Object.keys(this.signatures)[0];
67938 var valid = formats[fmt].verify(this, issuerKey);
67939 if (valid)
67940 this.issuerKey = issuerKey;
67941 return (valid);
67942};
67943
67944Certificate.prototype.signWith = function (key) {
67945 utils.assertCompatible(key, PrivateKey, [1, 2], 'key');
67946 var fmts = Object.keys(formats);
67947 var didOne = false;
67948 for (var i = 0; i < fmts.length; ++i) {
67949 if (fmts[i] !== 'pem') {
67950 var ret = formats[fmts[i]].sign(this, key);
67951 if (ret === true)
67952 didOne = true;
67953 }
67954 }
67955 if (!didOne) {
67956 throw (new Error('Failed to sign the certificate for any ' +
67957 'available certificate formats'));
67958 }
67959};
67960
67961Certificate.createSelfSigned = function (subjectOrSubjects, key, options) {
67962 var subjects;
67963 if (Array.isArray(subjectOrSubjects))
67964 subjects = subjectOrSubjects;
67965 else
67966 subjects = [subjectOrSubjects];
67967
67968 assert.arrayOfObject(subjects);
67969 subjects.forEach(function (subject) {
67970 utils.assertCompatible(subject, Identity, [1, 0], 'subject');
67971 });
67972
67973 utils.assertCompatible(key, PrivateKey, [1, 2], 'private key');
67974
67975 assert.optionalObject(options, 'options');
67976 if (options === undefined)
67977 options = {};
67978 assert.optionalObject(options.validFrom, 'options.validFrom');
67979 assert.optionalObject(options.validUntil, 'options.validUntil');
67980 var validFrom = options.validFrom;
67981 var validUntil = options.validUntil;
67982 if (validFrom === undefined)
67983 validFrom = new Date();
67984 if (validUntil === undefined) {
67985 assert.optionalNumber(options.lifetime, 'options.lifetime');
67986 var lifetime = options.lifetime;
67987 if (lifetime === undefined)
67988 lifetime = 10*365*24*3600;
67989 validUntil = new Date();
67990 validUntil.setTime(validUntil.getTime() + lifetime*1000);
67991 }
67992 assert.optionalBuffer(options.serial, 'options.serial');
67993 var serial = options.serial;
67994 if (serial === undefined)
67995 serial = Buffer.from('0000000000000001', 'hex');
67996
67997 var purposes = options.purposes;
67998 if (purposes === undefined)
67999 purposes = [];
68000
68001 if (purposes.indexOf('signature') === -1)
68002 purposes.push('signature');
68003
68004 /* Self-signed certs are always CAs. */
68005 if (purposes.indexOf('ca') === -1)
68006 purposes.push('ca');
68007 if (purposes.indexOf('crl') === -1)
68008 purposes.push('crl');
68009
68010 /*
68011 * If we weren't explicitly given any other purposes, do the sensible
68012 * thing and add some basic ones depending on the subject type.
68013 */
68014 if (purposes.length <= 3) {
68015 var hostSubjects = subjects.filter(function (subject) {
68016 return (subject.type === 'host');
68017 });
68018 var userSubjects = subjects.filter(function (subject) {
68019 return (subject.type === 'user');
68020 });
68021 if (hostSubjects.length > 0) {
68022 if (purposes.indexOf('serverAuth') === -1)
68023 purposes.push('serverAuth');
68024 }
68025 if (userSubjects.length > 0) {
68026 if (purposes.indexOf('clientAuth') === -1)
68027 purposes.push('clientAuth');
68028 }
68029 if (userSubjects.length > 0 || hostSubjects.length > 0) {
68030 if (purposes.indexOf('keyAgreement') === -1)
68031 purposes.push('keyAgreement');
68032 if (key.type === 'rsa' &&
68033 purposes.indexOf('encryption') === -1)
68034 purposes.push('encryption');
68035 }
68036 }
68037
68038 var cert = new Certificate({
68039 subjects: subjects,
68040 issuer: subjects[0],
68041 subjectKey: key.toPublic(),
68042 issuerKey: key.toPublic(),
68043 signatures: {},
68044 serial: serial,
68045 validFrom: validFrom,
68046 validUntil: validUntil,
68047 purposes: purposes
68048 });
68049 cert.signWith(key);
68050
68051 return (cert);
68052};
68053
68054Certificate.create =
68055 function (subjectOrSubjects, key, issuer, issuerKey, options) {
68056 var subjects;
68057 if (Array.isArray(subjectOrSubjects))
68058 subjects = subjectOrSubjects;
68059 else
68060 subjects = [subjectOrSubjects];
68061
68062 assert.arrayOfObject(subjects);
68063 subjects.forEach(function (subject) {
68064 utils.assertCompatible(subject, Identity, [1, 0], 'subject');
68065 });
68066
68067 utils.assertCompatible(key, Key, [1, 0], 'key');
68068 if (PrivateKey.isPrivateKey(key))
68069 key = key.toPublic();
68070 utils.assertCompatible(issuer, Identity, [1, 0], 'issuer');
68071 utils.assertCompatible(issuerKey, PrivateKey, [1, 2], 'issuer key');
68072
68073 assert.optionalObject(options, 'options');
68074 if (options === undefined)
68075 options = {};
68076 assert.optionalObject(options.validFrom, 'options.validFrom');
68077 assert.optionalObject(options.validUntil, 'options.validUntil');
68078 var validFrom = options.validFrom;
68079 var validUntil = options.validUntil;
68080 if (validFrom === undefined)
68081 validFrom = new Date();
68082 if (validUntil === undefined) {
68083 assert.optionalNumber(options.lifetime, 'options.lifetime');
68084 var lifetime = options.lifetime;
68085 if (lifetime === undefined)
68086 lifetime = 10*365*24*3600;
68087 validUntil = new Date();
68088 validUntil.setTime(validUntil.getTime() + lifetime*1000);
68089 }
68090 assert.optionalBuffer(options.serial, 'options.serial');
68091 var serial = options.serial;
68092 if (serial === undefined)
68093 serial = Buffer.from('0000000000000001', 'hex');
68094
68095 var purposes = options.purposes;
68096 if (purposes === undefined)
68097 purposes = [];
68098
68099 if (purposes.indexOf('signature') === -1)
68100 purposes.push('signature');
68101
68102 if (options.ca === true) {
68103 if (purposes.indexOf('ca') === -1)
68104 purposes.push('ca');
68105 if (purposes.indexOf('crl') === -1)
68106 purposes.push('crl');
68107 }
68108
68109 var hostSubjects = subjects.filter(function (subject) {
68110 return (subject.type === 'host');
68111 });
68112 var userSubjects = subjects.filter(function (subject) {
68113 return (subject.type === 'user');
68114 });
68115 if (hostSubjects.length > 0) {
68116 if (purposes.indexOf('serverAuth') === -1)
68117 purposes.push('serverAuth');
68118 }
68119 if (userSubjects.length > 0) {
68120 if (purposes.indexOf('clientAuth') === -1)
68121 purposes.push('clientAuth');
68122 }
68123 if (userSubjects.length > 0 || hostSubjects.length > 0) {
68124 if (purposes.indexOf('keyAgreement') === -1)
68125 purposes.push('keyAgreement');
68126 if (key.type === 'rsa' &&
68127 purposes.indexOf('encryption') === -1)
68128 purposes.push('encryption');
68129 }
68130
68131 var cert = new Certificate({
68132 subjects: subjects,
68133 issuer: issuer,
68134 subjectKey: key,
68135 issuerKey: issuerKey.toPublic(),
68136 signatures: {},
68137 serial: serial,
68138 validFrom: validFrom,
68139 validUntil: validUntil,
68140 purposes: purposes
68141 });
68142 cert.signWith(issuerKey);
68143
68144 return (cert);
68145};
68146
68147Certificate.parse = function (data, format, options) {
68148 if (typeof (data) !== 'string')
68149 assert.buffer(data, 'data');
68150 if (format === undefined)
68151 format = 'auto';
68152 assert.string(format, 'format');
68153 if (typeof (options) === 'string')
68154 options = { filename: options };
68155 assert.optionalObject(options, 'options');
68156 if (options === undefined)
68157 options = {};
68158 assert.optionalString(options.filename, 'options.filename');
68159 if (options.filename === undefined)
68160 options.filename = '(unnamed)';
68161
68162 assert.object(formats[format], 'formats[format]');
68163
68164 try {
68165 var k = formats[format].read(data, options);
68166 return (k);
68167 } catch (e) {
68168 throw (new CertificateParseError(options.filename, format, e));
68169 }
68170};
68171
68172Certificate.isCertificate = function (obj, ver) {
68173 return (utils.isCompatible(obj, Certificate, ver));
68174};
68175
68176/*
68177 * API versions for Certificate:
68178 * [1,0] -- initial ver
68179 * [1,1] -- openssh format now unpacks extensions
68180 */
68181Certificate.prototype._sshpkApiVersion = [1, 1];
68182
68183Certificate._oldVersionDetect = function (obj) {
68184 return ([1, 0]);
68185};
68186
68187},{"./algs":335,"./errors":339,"./fingerprint":340,"./formats/openssh-cert":343,"./formats/x509":352,"./formats/x509-pem":351,"./identity":353,"./key":355,"./private-key":356,"./signature":357,"./utils":359,"assert-plus":67,"crypto":126,"safer-buffer":326,"util":397}],337:[function(require,module,exports){
68188// Copyright 2017 Joyent, Inc.
68189
68190module.exports = {
68191 DiffieHellman: DiffieHellman,
68192 generateECDSA: generateECDSA,
68193 generateED25519: generateED25519
68194};
68195
68196var assert = require('assert-plus');
68197var crypto = require('crypto');
68198var Buffer = require('safer-buffer').Buffer;
68199var algs = require('./algs');
68200var utils = require('./utils');
68201var nacl = require('tweetnacl');
68202
68203var Key = require('./key');
68204var PrivateKey = require('./private-key');
68205
68206var CRYPTO_HAVE_ECDH = (crypto.createECDH !== undefined);
68207
68208var ecdh = require('ecc-jsbn');
68209var ec = require('ecc-jsbn/lib/ec');
68210var jsbn = require('jsbn').BigInteger;
68211
68212function DiffieHellman(key) {
68213 utils.assertCompatible(key, Key, [1, 4], 'key');
68214 this._isPriv = PrivateKey.isPrivateKey(key, [1, 3]);
68215 this._algo = key.type;
68216 this._curve = key.curve;
68217 this._key = key;
68218 if (key.type === 'dsa') {
68219 if (!CRYPTO_HAVE_ECDH) {
68220 throw (new Error('Due to bugs in the node 0.10 ' +
68221 'crypto API, node 0.12.x or later is required ' +
68222 'to use DH'));
68223 }
68224 this._dh = crypto.createDiffieHellman(
68225 key.part.p.data, undefined,
68226 key.part.g.data, undefined);
68227 this._p = key.part.p;
68228 this._g = key.part.g;
68229 if (this._isPriv)
68230 this._dh.setPrivateKey(key.part.x.data);
68231 this._dh.setPublicKey(key.part.y.data);
68232
68233 } else if (key.type === 'ecdsa') {
68234 if (!CRYPTO_HAVE_ECDH) {
68235 this._ecParams = new X9ECParameters(this._curve);
68236
68237 if (this._isPriv) {
68238 this._priv = new ECPrivate(
68239 this._ecParams, key.part.d.data);
68240 }
68241 return;
68242 }
68243
68244 var curve = {
68245 'nistp256': 'prime256v1',
68246 'nistp384': 'secp384r1',
68247 'nistp521': 'secp521r1'
68248 }[key.curve];
68249 this._dh = crypto.createECDH(curve);
68250 if (typeof (this._dh) !== 'object' ||
68251 typeof (this._dh.setPrivateKey) !== 'function') {
68252 CRYPTO_HAVE_ECDH = false;
68253 DiffieHellman.call(this, key);
68254 return;
68255 }
68256 if (this._isPriv)
68257 this._dh.setPrivateKey(key.part.d.data);
68258 this._dh.setPublicKey(key.part.Q.data);
68259
68260 } else if (key.type === 'curve25519') {
68261 if (this._isPriv) {
68262 utils.assertCompatible(key, PrivateKey, [1, 5], 'key');
68263 this._priv = key.part.k.data;
68264 }
68265
68266 } else {
68267 throw (new Error('DH not supported for ' + key.type + ' keys'));
68268 }
68269}
68270
68271DiffieHellman.prototype.getPublicKey = function () {
68272 if (this._isPriv)
68273 return (this._key.toPublic());
68274 return (this._key);
68275};
68276
68277DiffieHellman.prototype.getPrivateKey = function () {
68278 if (this._isPriv)
68279 return (this._key);
68280 else
68281 return (undefined);
68282};
68283DiffieHellman.prototype.getKey = DiffieHellman.prototype.getPrivateKey;
68284
68285DiffieHellman.prototype._keyCheck = function (pk, isPub) {
68286 assert.object(pk, 'key');
68287 if (!isPub)
68288 utils.assertCompatible(pk, PrivateKey, [1, 3], 'key');
68289 utils.assertCompatible(pk, Key, [1, 4], 'key');
68290
68291 if (pk.type !== this._algo) {
68292 throw (new Error('A ' + pk.type + ' key cannot be used in ' +
68293 this._algo + ' Diffie-Hellman'));
68294 }
68295
68296 if (pk.curve !== this._curve) {
68297 throw (new Error('A key from the ' + pk.curve + ' curve ' +
68298 'cannot be used with a ' + this._curve +
68299 ' Diffie-Hellman'));
68300 }
68301
68302 if (pk.type === 'dsa') {
68303 assert.deepEqual(pk.part.p, this._p,
68304 'DSA key prime does not match');
68305 assert.deepEqual(pk.part.g, this._g,
68306 'DSA key generator does not match');
68307 }
68308};
68309
68310DiffieHellman.prototype.setKey = function (pk) {
68311 this._keyCheck(pk);
68312
68313 if (pk.type === 'dsa') {
68314 this._dh.setPrivateKey(pk.part.x.data);
68315 this._dh.setPublicKey(pk.part.y.data);
68316
68317 } else if (pk.type === 'ecdsa') {
68318 if (CRYPTO_HAVE_ECDH) {
68319 this._dh.setPrivateKey(pk.part.d.data);
68320 this._dh.setPublicKey(pk.part.Q.data);
68321 } else {
68322 this._priv = new ECPrivate(
68323 this._ecParams, pk.part.d.data);
68324 }
68325
68326 } else if (pk.type === 'curve25519') {
68327 var k = pk.part.k;
68328 if (!pk.part.k)
68329 k = pk.part.r;
68330 this._priv = k.data;
68331 if (this._priv[0] === 0x00)
68332 this._priv = this._priv.slice(1);
68333 this._priv = this._priv.slice(0, 32);
68334 }
68335 this._key = pk;
68336 this._isPriv = true;
68337};
68338DiffieHellman.prototype.setPrivateKey = DiffieHellman.prototype.setKey;
68339
68340DiffieHellman.prototype.computeSecret = function (otherpk) {
68341 this._keyCheck(otherpk, true);
68342 if (!this._isPriv)
68343 throw (new Error('DH exchange has not been initialized with ' +
68344 'a private key yet'));
68345
68346 var pub;
68347 if (this._algo === 'dsa') {
68348 return (this._dh.computeSecret(
68349 otherpk.part.y.data));
68350
68351 } else if (this._algo === 'ecdsa') {
68352 if (CRYPTO_HAVE_ECDH) {
68353 return (this._dh.computeSecret(
68354 otherpk.part.Q.data));
68355 } else {
68356 pub = new ECPublic(
68357 this._ecParams, otherpk.part.Q.data);
68358 return (this._priv.deriveSharedSecret(pub));
68359 }
68360
68361 } else if (this._algo === 'curve25519') {
68362 pub = otherpk.part.A.data;
68363 while (pub[0] === 0x00 && pub.length > 32)
68364 pub = pub.slice(1);
68365 var priv = this._priv;
68366 assert.strictEqual(pub.length, 32);
68367 assert.strictEqual(priv.length, 32);
68368
68369 var secret = nacl.box.before(new Uint8Array(pub),
68370 new Uint8Array(priv));
68371
68372 return (Buffer.from(secret));
68373 }
68374
68375 throw (new Error('Invalid algorithm: ' + this._algo));
68376};
68377
68378DiffieHellman.prototype.generateKey = function () {
68379 var parts = [];
68380 var priv, pub;
68381 if (this._algo === 'dsa') {
68382 this._dh.generateKeys();
68383
68384 parts.push({name: 'p', data: this._p.data});
68385 parts.push({name: 'q', data: this._key.part.q.data});
68386 parts.push({name: 'g', data: this._g.data});
68387 parts.push({name: 'y', data: this._dh.getPublicKey()});
68388 parts.push({name: 'x', data: this._dh.getPrivateKey()});
68389 this._key = new PrivateKey({
68390 type: 'dsa',
68391 parts: parts
68392 });
68393 this._isPriv = true;
68394 return (this._key);
68395
68396 } else if (this._algo === 'ecdsa') {
68397 if (CRYPTO_HAVE_ECDH) {
68398 this._dh.generateKeys();
68399
68400 parts.push({name: 'curve',
68401 data: Buffer.from(this._curve)});
68402 parts.push({name: 'Q', data: this._dh.getPublicKey()});
68403 parts.push({name: 'd', data: this._dh.getPrivateKey()});
68404 this._key = new PrivateKey({
68405 type: 'ecdsa',
68406 curve: this._curve,
68407 parts: parts
68408 });
68409 this._isPriv = true;
68410 return (this._key);
68411
68412 } else {
68413 var n = this._ecParams.getN();
68414 var r = new jsbn(crypto.randomBytes(n.bitLength()));
68415 var n1 = n.subtract(jsbn.ONE);
68416 priv = r.mod(n1).add(jsbn.ONE);
68417 pub = this._ecParams.getG().multiply(priv);
68418
68419 priv = Buffer.from(priv.toByteArray());
68420 pub = Buffer.from(this._ecParams.getCurve().
68421 encodePointHex(pub), 'hex');
68422
68423 this._priv = new ECPrivate(this._ecParams, priv);
68424
68425 parts.push({name: 'curve',
68426 data: Buffer.from(this._curve)});
68427 parts.push({name: 'Q', data: pub});
68428 parts.push({name: 'd', data: priv});
68429
68430 this._key = new PrivateKey({
68431 type: 'ecdsa',
68432 curve: this._curve,
68433 parts: parts
68434 });
68435 this._isPriv = true;
68436 return (this._key);
68437 }
68438
68439 } else if (this._algo === 'curve25519') {
68440 var pair = nacl.box.keyPair();
68441 priv = Buffer.from(pair.secretKey);
68442 pub = Buffer.from(pair.publicKey);
68443 priv = Buffer.concat([priv, pub]);
68444 assert.strictEqual(priv.length, 64);
68445 assert.strictEqual(pub.length, 32);
68446
68447 parts.push({name: 'A', data: pub});
68448 parts.push({name: 'k', data: priv});
68449 this._key = new PrivateKey({
68450 type: 'curve25519',
68451 parts: parts
68452 });
68453 this._isPriv = true;
68454 return (this._key);
68455 }
68456
68457 throw (new Error('Invalid algorithm: ' + this._algo));
68458};
68459DiffieHellman.prototype.generateKeys = DiffieHellman.prototype.generateKey;
68460
68461/* These are helpers for using ecc-jsbn (for node 0.10 compatibility). */
68462
68463function X9ECParameters(name) {
68464 var params = algs.curves[name];
68465 assert.object(params);
68466
68467 var p = new jsbn(params.p);
68468 var a = new jsbn(params.a);
68469 var b = new jsbn(params.b);
68470 var n = new jsbn(params.n);
68471 var h = jsbn.ONE;
68472 var curve = new ec.ECCurveFp(p, a, b);
68473 var G = curve.decodePointHex(params.G.toString('hex'));
68474
68475 this.curve = curve;
68476 this.g = G;
68477 this.n = n;
68478 this.h = h;
68479}
68480X9ECParameters.prototype.getCurve = function () { return (this.curve); };
68481X9ECParameters.prototype.getG = function () { return (this.g); };
68482X9ECParameters.prototype.getN = function () { return (this.n); };
68483X9ECParameters.prototype.getH = function () { return (this.h); };
68484
68485function ECPublic(params, buffer) {
68486 this._params = params;
68487 if (buffer[0] === 0x00)
68488 buffer = buffer.slice(1);
68489 this._pub = params.getCurve().decodePointHex(buffer.toString('hex'));
68490}
68491
68492function ECPrivate(params, buffer) {
68493 this._params = params;
68494 this._priv = new jsbn(utils.mpNormalize(buffer));
68495}
68496ECPrivate.prototype.deriveSharedSecret = function (pubKey) {
68497 assert.ok(pubKey instanceof ECPublic);
68498 var S = pubKey._pub.multiply(this._priv);
68499 return (Buffer.from(S.getX().toBigInteger().toByteArray()));
68500};
68501
68502function generateED25519() {
68503 var pair = nacl.sign.keyPair();
68504 var priv = Buffer.from(pair.secretKey);
68505 var pub = Buffer.from(pair.publicKey);
68506 assert.strictEqual(priv.length, 64);
68507 assert.strictEqual(pub.length, 32);
68508
68509 var parts = [];
68510 parts.push({name: 'A', data: pub});
68511 parts.push({name: 'k', data: priv.slice(0, 32)});
68512 var key = new PrivateKey({
68513 type: 'ed25519',
68514 parts: parts
68515 });
68516 return (key);
68517}
68518
68519/* Generates a new ECDSA private key on a given curve. */
68520function generateECDSA(curve) {
68521 var parts = [];
68522 var key;
68523
68524 if (CRYPTO_HAVE_ECDH) {
68525 /*
68526 * Node crypto doesn't expose key generation directly, but the
68527 * ECDH instances can generate keys. It turns out this just
68528 * calls into the OpenSSL generic key generator, and we can
68529 * read its output happily without doing an actual DH. So we
68530 * use that here.
68531 */
68532 var osCurve = {
68533 'nistp256': 'prime256v1',
68534 'nistp384': 'secp384r1',
68535 'nistp521': 'secp521r1'
68536 }[curve];
68537
68538 var dh = crypto.createECDH(osCurve);
68539 dh.generateKeys();
68540
68541 parts.push({name: 'curve',
68542 data: Buffer.from(curve)});
68543 parts.push({name: 'Q', data: dh.getPublicKey()});
68544 parts.push({name: 'd', data: dh.getPrivateKey()});
68545
68546 key = new PrivateKey({
68547 type: 'ecdsa',
68548 curve: curve,
68549 parts: parts
68550 });
68551 return (key);
68552 } else {
68553
68554 var ecParams = new X9ECParameters(curve);
68555
68556 /* This algorithm taken from FIPS PUB 186-4 (section B.4.1) */
68557 var n = ecParams.getN();
68558 /*
68559 * The crypto.randomBytes() function can only give us whole
68560 * bytes, so taking a nod from X9.62, we round up.
68561 */
68562 var cByteLen = Math.ceil((n.bitLength() + 64) / 8);
68563 var c = new jsbn(crypto.randomBytes(cByteLen));
68564
68565 var n1 = n.subtract(jsbn.ONE);
68566 var priv = c.mod(n1).add(jsbn.ONE);
68567 var pub = ecParams.getG().multiply(priv);
68568
68569 priv = Buffer.from(priv.toByteArray());
68570 pub = Buffer.from(ecParams.getCurve().
68571 encodePointHex(pub), 'hex');
68572
68573 parts.push({name: 'curve', data: Buffer.from(curve)});
68574 parts.push({name: 'Q', data: pub});
68575 parts.push({name: 'd', data: priv});
68576
68577 key = new PrivateKey({
68578 type: 'ecdsa',
68579 curve: curve,
68580 parts: parts
68581 });
68582 return (key);
68583 }
68584}
68585
68586},{"./algs":335,"./key":355,"./private-key":356,"./utils":359,"assert-plus":67,"crypto":126,"ecc-jsbn":139,"ecc-jsbn/lib/ec":140,"jsbn":215,"safer-buffer":326,"tweetnacl":391}],338:[function(require,module,exports){
68587// Copyright 2015 Joyent, Inc.
68588
68589module.exports = {
68590 Verifier: Verifier,
68591 Signer: Signer
68592};
68593
68594var nacl = require('tweetnacl');
68595var stream = require('stream');
68596var util = require('util');
68597var assert = require('assert-plus');
68598var Buffer = require('safer-buffer').Buffer;
68599var Signature = require('./signature');
68600
68601function Verifier(key, hashAlgo) {
68602 if (hashAlgo.toLowerCase() !== 'sha512')
68603 throw (new Error('ED25519 only supports the use of ' +
68604 'SHA-512 hashes'));
68605
68606 this.key = key;
68607 this.chunks = [];
68608
68609 stream.Writable.call(this, {});
68610}
68611util.inherits(Verifier, stream.Writable);
68612
68613Verifier.prototype._write = function (chunk, enc, cb) {
68614 this.chunks.push(chunk);
68615 cb();
68616};
68617
68618Verifier.prototype.update = function (chunk) {
68619 if (typeof (chunk) === 'string')
68620 chunk = Buffer.from(chunk, 'binary');
68621 this.chunks.push(chunk);
68622};
68623
68624Verifier.prototype.verify = function (signature, fmt) {
68625 var sig;
68626 if (Signature.isSignature(signature, [2, 0])) {
68627 if (signature.type !== 'ed25519')
68628 return (false);
68629 sig = signature.toBuffer('raw');
68630
68631 } else if (typeof (signature) === 'string') {
68632 sig = Buffer.from(signature, 'base64');
68633
68634 } else if (Signature.isSignature(signature, [1, 0])) {
68635 throw (new Error('signature was created by too old ' +
68636 'a version of sshpk and cannot be verified'));
68637 }
68638
68639 assert.buffer(sig);
68640 return (nacl.sign.detached.verify(
68641 new Uint8Array(Buffer.concat(this.chunks)),
68642 new Uint8Array(sig),
68643 new Uint8Array(this.key.part.A.data)));
68644};
68645
68646function Signer(key, hashAlgo) {
68647 if (hashAlgo.toLowerCase() !== 'sha512')
68648 throw (new Error('ED25519 only supports the use of ' +
68649 'SHA-512 hashes'));
68650
68651 this.key = key;
68652 this.chunks = [];
68653
68654 stream.Writable.call(this, {});
68655}
68656util.inherits(Signer, stream.Writable);
68657
68658Signer.prototype._write = function (chunk, enc, cb) {
68659 this.chunks.push(chunk);
68660 cb();
68661};
68662
68663Signer.prototype.update = function (chunk) {
68664 if (typeof (chunk) === 'string')
68665 chunk = Buffer.from(chunk, 'binary');
68666 this.chunks.push(chunk);
68667};
68668
68669Signer.prototype.sign = function () {
68670 var sig = nacl.sign.detached(
68671 new Uint8Array(Buffer.concat(this.chunks)),
68672 new Uint8Array(Buffer.concat([
68673 this.key.part.k.data, this.key.part.A.data])));
68674 var sigBuf = Buffer.from(sig);
68675 var sigObj = Signature.parse(sigBuf, 'ed25519', 'raw');
68676 sigObj.hashAlgorithm = 'sha512';
68677 return (sigObj);
68678};
68679
68680},{"./signature":357,"assert-plus":67,"safer-buffer":326,"stream":361,"tweetnacl":391,"util":397}],339:[function(require,module,exports){
68681// Copyright 2015 Joyent, Inc.
68682
68683var assert = require('assert-plus');
68684var util = require('util');
68685
68686function FingerprintFormatError(fp, format) {
68687 if (Error.captureStackTrace)
68688 Error.captureStackTrace(this, FingerprintFormatError);
68689 this.name = 'FingerprintFormatError';
68690 this.fingerprint = fp;
68691 this.format = format;
68692 this.message = 'Fingerprint format is not supported, or is invalid: ';
68693 if (fp !== undefined)
68694 this.message += ' fingerprint = ' + fp;
68695 if (format !== undefined)
68696 this.message += ' format = ' + format;
68697}
68698util.inherits(FingerprintFormatError, Error);
68699
68700function InvalidAlgorithmError(alg) {
68701 if (Error.captureStackTrace)
68702 Error.captureStackTrace(this, InvalidAlgorithmError);
68703 this.name = 'InvalidAlgorithmError';
68704 this.algorithm = alg;
68705 this.message = 'Algorithm "' + alg + '" is not supported';
68706}
68707util.inherits(InvalidAlgorithmError, Error);
68708
68709function KeyParseError(name, format, innerErr) {
68710 if (Error.captureStackTrace)
68711 Error.captureStackTrace(this, KeyParseError);
68712 this.name = 'KeyParseError';
68713 this.format = format;
68714 this.keyName = name;
68715 this.innerErr = innerErr;
68716 this.message = 'Failed to parse ' + name + ' as a valid ' + format +
68717 ' format key: ' + innerErr.message;
68718}
68719util.inherits(KeyParseError, Error);
68720
68721function SignatureParseError(type, format, innerErr) {
68722 if (Error.captureStackTrace)
68723 Error.captureStackTrace(this, SignatureParseError);
68724 this.name = 'SignatureParseError';
68725 this.type = type;
68726 this.format = format;
68727 this.innerErr = innerErr;
68728 this.message = 'Failed to parse the given data as a ' + type +
68729 ' signature in ' + format + ' format: ' + innerErr.message;
68730}
68731util.inherits(SignatureParseError, Error);
68732
68733function CertificateParseError(name, format, innerErr) {
68734 if (Error.captureStackTrace)
68735 Error.captureStackTrace(this, CertificateParseError);
68736 this.name = 'CertificateParseError';
68737 this.format = format;
68738 this.certName = name;
68739 this.innerErr = innerErr;
68740 this.message = 'Failed to parse ' + name + ' as a valid ' + format +
68741 ' format certificate: ' + innerErr.message;
68742}
68743util.inherits(CertificateParseError, Error);
68744
68745function KeyEncryptedError(name, format) {
68746 if (Error.captureStackTrace)
68747 Error.captureStackTrace(this, KeyEncryptedError);
68748 this.name = 'KeyEncryptedError';
68749 this.format = format;
68750 this.keyName = name;
68751 this.message = 'The ' + format + ' format key ' + name + ' is ' +
68752 'encrypted (password-protected), and no passphrase was ' +
68753 'provided in `options`';
68754}
68755util.inherits(KeyEncryptedError, Error);
68756
68757module.exports = {
68758 FingerprintFormatError: FingerprintFormatError,
68759 InvalidAlgorithmError: InvalidAlgorithmError,
68760 KeyParseError: KeyParseError,
68761 SignatureParseError: SignatureParseError,
68762 KeyEncryptedError: KeyEncryptedError,
68763 CertificateParseError: CertificateParseError
68764};
68765
68766},{"assert-plus":67,"util":397}],340:[function(require,module,exports){
68767// Copyright 2018 Joyent, Inc.
68768
68769module.exports = Fingerprint;
68770
68771var assert = require('assert-plus');
68772var Buffer = require('safer-buffer').Buffer;
68773var algs = require('./algs');
68774var crypto = require('crypto');
68775var errs = require('./errors');
68776var Key = require('./key');
68777var PrivateKey = require('./private-key');
68778var Certificate = require('./certificate');
68779var utils = require('./utils');
68780
68781var FingerprintFormatError = errs.FingerprintFormatError;
68782var InvalidAlgorithmError = errs.InvalidAlgorithmError;
68783
68784function Fingerprint(opts) {
68785 assert.object(opts, 'options');
68786 assert.string(opts.type, 'options.type');
68787 assert.buffer(opts.hash, 'options.hash');
68788 assert.string(opts.algorithm, 'options.algorithm');
68789
68790 this.algorithm = opts.algorithm.toLowerCase();
68791 if (algs.hashAlgs[this.algorithm] !== true)
68792 throw (new InvalidAlgorithmError(this.algorithm));
68793
68794 this.hash = opts.hash;
68795 this.type = opts.type;
68796 this.hashType = opts.hashType;
68797}
68798
68799Fingerprint.prototype.toString = function (format) {
68800 if (format === undefined) {
68801 if (this.algorithm === 'md5' || this.hashType === 'spki')
68802 format = 'hex';
68803 else
68804 format = 'base64';
68805 }
68806 assert.string(format);
68807
68808 switch (format) {
68809 case 'hex':
68810 if (this.hashType === 'spki')
68811 return (this.hash.toString('hex'));
68812 return (addColons(this.hash.toString('hex')));
68813 case 'base64':
68814 if (this.hashType === 'spki')
68815 return (this.hash.toString('base64'));
68816 return (sshBase64Format(this.algorithm,
68817 this.hash.toString('base64')));
68818 default:
68819 throw (new FingerprintFormatError(undefined, format));
68820 }
68821};
68822
68823Fingerprint.prototype.matches = function (other) {
68824 assert.object(other, 'key or certificate');
68825 if (this.type === 'key' && this.hashType !== 'ssh') {
68826 utils.assertCompatible(other, Key, [1, 7], 'key with spki');
68827 if (PrivateKey.isPrivateKey(other)) {
68828 utils.assertCompatible(other, PrivateKey, [1, 6],
68829 'privatekey with spki support');
68830 }
68831 } else if (this.type === 'key') {
68832 utils.assertCompatible(other, Key, [1, 0], 'key');
68833 } else {
68834 utils.assertCompatible(other, Certificate, [1, 0],
68835 'certificate');
68836 }
68837
68838 var theirHash = other.hash(this.algorithm, this.hashType);
68839 var theirHash2 = crypto.createHash(this.algorithm).
68840 update(theirHash).digest('base64');
68841
68842 if (this.hash2 === undefined)
68843 this.hash2 = crypto.createHash(this.algorithm).
68844 update(this.hash).digest('base64');
68845
68846 return (this.hash2 === theirHash2);
68847};
68848
68849/*JSSTYLED*/
68850var base64RE = /^[A-Za-z0-9+\/=]+$/;
68851/*JSSTYLED*/
68852var hexRE = /^[a-fA-F0-9]+$/;
68853
68854Fingerprint.parse = function (fp, options) {
68855 assert.string(fp, 'fingerprint');
68856
68857 var alg, hash, enAlgs;
68858 if (Array.isArray(options)) {
68859 enAlgs = options;
68860 options = {};
68861 }
68862 assert.optionalObject(options, 'options');
68863 if (options === undefined)
68864 options = {};
68865 if (options.enAlgs !== undefined)
68866 enAlgs = options.enAlgs;
68867 if (options.algorithms !== undefined)
68868 enAlgs = options.algorithms;
68869 assert.optionalArrayOfString(enAlgs, 'algorithms');
68870
68871 var hashType = 'ssh';
68872 if (options.hashType !== undefined)
68873 hashType = options.hashType;
68874 assert.string(hashType, 'options.hashType');
68875
68876 var parts = fp.split(':');
68877 if (parts.length == 2) {
68878 alg = parts[0].toLowerCase();
68879 if (!base64RE.test(parts[1]))
68880 throw (new FingerprintFormatError(fp));
68881 try {
68882 hash = Buffer.from(parts[1], 'base64');
68883 } catch (e) {
68884 throw (new FingerprintFormatError(fp));
68885 }
68886 } else if (parts.length > 2) {
68887 alg = 'md5';
68888 if (parts[0].toLowerCase() === 'md5')
68889 parts = parts.slice(1);
68890 parts = parts.map(function (p) {
68891 while (p.length < 2)
68892 p = '0' + p;
68893 if (p.length > 2)
68894 throw (new FingerprintFormatError(fp));
68895 return (p);
68896 });
68897 parts = parts.join('');
68898 if (!hexRE.test(parts) || parts.length % 2 !== 0)
68899 throw (new FingerprintFormatError(fp));
68900 try {
68901 hash = Buffer.from(parts, 'hex');
68902 } catch (e) {
68903 throw (new FingerprintFormatError(fp));
68904 }
68905 } else {
68906 if (hexRE.test(fp)) {
68907 hash = Buffer.from(fp, 'hex');
68908 } else if (base64RE.test(fp)) {
68909 hash = Buffer.from(fp, 'base64');
68910 } else {
68911 throw (new FingerprintFormatError(fp));
68912 }
68913
68914 switch (hash.length) {
68915 case 32:
68916 alg = 'sha256';
68917 break;
68918 case 16:
68919 alg = 'md5';
68920 break;
68921 case 20:
68922 alg = 'sha1';
68923 break;
68924 case 64:
68925 alg = 'sha512';
68926 break;
68927 default:
68928 throw (new FingerprintFormatError(fp));
68929 }
68930
68931 /* Plain hex/base64: guess it's probably SPKI unless told. */
68932 if (options.hashType === undefined)
68933 hashType = 'spki';
68934 }
68935
68936 if (alg === undefined)
68937 throw (new FingerprintFormatError(fp));
68938
68939 if (algs.hashAlgs[alg] === undefined)
68940 throw (new InvalidAlgorithmError(alg));
68941
68942 if (enAlgs !== undefined) {
68943 enAlgs = enAlgs.map(function (a) { return a.toLowerCase(); });
68944 if (enAlgs.indexOf(alg) === -1)
68945 throw (new InvalidAlgorithmError(alg));
68946 }
68947
68948 return (new Fingerprint({
68949 algorithm: alg,
68950 hash: hash,
68951 type: options.type || 'key',
68952 hashType: hashType
68953 }));
68954};
68955
68956function addColons(s) {
68957 /*JSSTYLED*/
68958 return (s.replace(/(.{2})(?=.)/g, '$1:'));
68959}
68960
68961function base64Strip(s) {
68962 /*JSSTYLED*/
68963 return (s.replace(/=*$/, ''));
68964}
68965
68966function sshBase64Format(alg, h) {
68967 return (alg.toUpperCase() + ':' + base64Strip(h));
68968}
68969
68970Fingerprint.isFingerprint = function (obj, ver) {
68971 return (utils.isCompatible(obj, Fingerprint, ver));
68972};
68973
68974/*
68975 * API versions for Fingerprint:
68976 * [1,0] -- initial ver
68977 * [1,1] -- first tagged ver
68978 * [1,2] -- hashType and spki support
68979 */
68980Fingerprint.prototype._sshpkApiVersion = [1, 2];
68981
68982Fingerprint._oldVersionDetect = function (obj) {
68983 assert.func(obj.toString);
68984 assert.func(obj.matches);
68985 return ([1, 0]);
68986};
68987
68988},{"./algs":335,"./certificate":336,"./errors":339,"./key":355,"./private-key":356,"./utils":359,"assert-plus":67,"crypto":126,"safer-buffer":326}],341:[function(require,module,exports){
68989// Copyright 2018 Joyent, Inc.
68990
68991module.exports = {
68992 read: read,
68993 write: write
68994};
68995
68996var assert = require('assert-plus');
68997var Buffer = require('safer-buffer').Buffer;
68998var utils = require('../utils');
68999var Key = require('../key');
69000var PrivateKey = require('../private-key');
69001
69002var pem = require('./pem');
69003var ssh = require('./ssh');
69004var rfc4253 = require('./rfc4253');
69005var dnssec = require('./dnssec');
69006var putty = require('./putty');
69007
69008var DNSSEC_PRIVKEY_HEADER_PREFIX = 'Private-key-format: v1';
69009
69010function read(buf, options) {
69011 if (typeof (buf) === 'string') {
69012 if (buf.trim().match(/^[-]+[ ]*BEGIN/))
69013 return (pem.read(buf, options));
69014 if (buf.match(/^\s*ssh-[a-z]/))
69015 return (ssh.read(buf, options));
69016 if (buf.match(/^\s*ecdsa-/))
69017 return (ssh.read(buf, options));
69018 if (buf.match(/^putty-user-key-file-2:/i))
69019 return (putty.read(buf, options));
69020 if (findDNSSECHeader(buf))
69021 return (dnssec.read(buf, options));
69022 buf = Buffer.from(buf, 'binary');
69023 } else {
69024 assert.buffer(buf);
69025 if (findPEMHeader(buf))
69026 return (pem.read(buf, options));
69027 if (findSSHHeader(buf))
69028 return (ssh.read(buf, options));
69029 if (findPuTTYHeader(buf))
69030 return (putty.read(buf, options));
69031 if (findDNSSECHeader(buf))
69032 return (dnssec.read(buf, options));
69033 }
69034 if (buf.readUInt32BE(0) < buf.length)
69035 return (rfc4253.read(buf, options));
69036 throw (new Error('Failed to auto-detect format of key'));
69037}
69038
69039function findPuTTYHeader(buf) {
69040 var offset = 0;
69041 while (offset < buf.length &&
69042 (buf[offset] === 32 || buf[offset] === 10 || buf[offset] === 9))
69043 ++offset;
69044 if (offset + 22 <= buf.length &&
69045 buf.slice(offset, offset + 22).toString('ascii').toLowerCase() ===
69046 'putty-user-key-file-2:')
69047 return (true);
69048 return (false);
69049}
69050
69051function findSSHHeader(buf) {
69052 var offset = 0;
69053 while (offset < buf.length &&
69054 (buf[offset] === 32 || buf[offset] === 10 || buf[offset] === 9))
69055 ++offset;
69056 if (offset + 4 <= buf.length &&
69057 buf.slice(offset, offset + 4).toString('ascii') === 'ssh-')
69058 return (true);
69059 if (offset + 6 <= buf.length &&
69060 buf.slice(offset, offset + 6).toString('ascii') === 'ecdsa-')
69061 return (true);
69062 return (false);
69063}
69064
69065function findPEMHeader(buf) {
69066 var offset = 0;
69067 while (offset < buf.length &&
69068 (buf[offset] === 32 || buf[offset] === 10))
69069 ++offset;
69070 if (buf[offset] !== 45)
69071 return (false);
69072 while (offset < buf.length &&
69073 (buf[offset] === 45))
69074 ++offset;
69075 while (offset < buf.length &&
69076 (buf[offset] === 32))
69077 ++offset;
69078 if (offset + 5 > buf.length ||
69079 buf.slice(offset, offset + 5).toString('ascii') !== 'BEGIN')
69080 return (false);
69081 return (true);
69082}
69083
69084function findDNSSECHeader(buf) {
69085 // private case first
69086 if (buf.length <= DNSSEC_PRIVKEY_HEADER_PREFIX.length)
69087 return (false);
69088 var headerCheck = buf.slice(0, DNSSEC_PRIVKEY_HEADER_PREFIX.length);
69089 if (headerCheck.toString('ascii') === DNSSEC_PRIVKEY_HEADER_PREFIX)
69090 return (true);
69091
69092 // public-key RFC3110 ?
69093 // 'domain.com. IN KEY ...' or 'domain.com. IN DNSKEY ...'
69094 // skip any comment-lines
69095 if (typeof (buf) !== 'string') {
69096 buf = buf.toString('ascii');
69097 }
69098 var lines = buf.split('\n');
69099 var line = 0;
69100 /* JSSTYLED */
69101 while (lines[line].match(/^\;/))
69102 line++;
69103 if (lines[line].toString('ascii').match(/\. IN KEY /))
69104 return (true);
69105 if (lines[line].toString('ascii').match(/\. IN DNSKEY /))
69106 return (true);
69107 return (false);
69108}
69109
69110function write(key, options) {
69111 throw (new Error('"auto" format cannot be used for writing'));
69112}
69113
69114},{"../key":355,"../private-key":356,"../utils":359,"./dnssec":342,"./pem":344,"./putty":347,"./rfc4253":348,"./ssh":350,"assert-plus":67,"safer-buffer":326}],342:[function(require,module,exports){
69115// Copyright 2017 Joyent, Inc.
69116
69117module.exports = {
69118 read: read,
69119 write: write
69120};
69121
69122var assert = require('assert-plus');
69123var Buffer = require('safer-buffer').Buffer;
69124var Key = require('../key');
69125var PrivateKey = require('../private-key');
69126var utils = require('../utils');
69127var SSHBuffer = require('../ssh-buffer');
69128var Dhe = require('../dhe');
69129
69130var supportedAlgos = {
69131 'rsa-sha1' : 5,
69132 'rsa-sha256' : 8,
69133 'rsa-sha512' : 10,
69134 'ecdsa-p256-sha256' : 13,
69135 'ecdsa-p384-sha384' : 14
69136 /*
69137 * ed25519 is hypothetically supported with id 15
69138 * but the common tools available don't appear to be
69139 * capable of generating/using ed25519 keys
69140 */
69141};
69142
69143var supportedAlgosById = {};
69144Object.keys(supportedAlgos).forEach(function (k) {
69145 supportedAlgosById[supportedAlgos[k]] = k.toUpperCase();
69146});
69147
69148function read(buf, options) {
69149 if (typeof (buf) !== 'string') {
69150 assert.buffer(buf, 'buf');
69151 buf = buf.toString('ascii');
69152 }
69153 var lines = buf.split('\n');
69154 if (lines[0].match(/^Private-key-format\: v1/)) {
69155 var algElems = lines[1].split(' ');
69156 var algoNum = parseInt(algElems[1], 10);
69157 var algoName = algElems[2];
69158 if (!supportedAlgosById[algoNum])
69159 throw (new Error('Unsupported algorithm: ' + algoName));
69160 return (readDNSSECPrivateKey(algoNum, lines.slice(2)));
69161 }
69162
69163 // skip any comment-lines
69164 var line = 0;
69165 /* JSSTYLED */
69166 while (lines[line].match(/^\;/))
69167 line++;
69168 // we should now have *one single* line left with our KEY on it.
69169 if ((lines[line].match(/\. IN KEY /) ||
69170 lines[line].match(/\. IN DNSKEY /)) && lines[line+1].length === 0) {
69171 return (readRFC3110(lines[line]));
69172 }
69173 throw (new Error('Cannot parse dnssec key'));
69174}
69175
69176function readRFC3110(keyString) {
69177 var elems = keyString.split(' ');
69178 //unused var flags = parseInt(elems[3], 10);
69179 //unused var protocol = parseInt(elems[4], 10);
69180 var algorithm = parseInt(elems[5], 10);
69181 if (!supportedAlgosById[algorithm])
69182 throw (new Error('Unsupported algorithm: ' + algorithm));
69183 var base64key = elems.slice(6, elems.length).join();
69184 var keyBuffer = Buffer.from(base64key, 'base64');
69185 if (supportedAlgosById[algorithm].match(/^RSA-/)) {
69186 // join the rest of the body into a single base64-blob
69187 var publicExponentLen = keyBuffer.readUInt8(0);
69188 if (publicExponentLen != 3 && publicExponentLen != 1)
69189 throw (new Error('Cannot parse dnssec key: ' +
69190 'unsupported exponent length'));
69191
69192 var publicExponent = keyBuffer.slice(1, publicExponentLen+1);
69193 publicExponent = utils.mpNormalize(publicExponent);
69194 var modulus = keyBuffer.slice(1+publicExponentLen);
69195 modulus = utils.mpNormalize(modulus);
69196 // now, make the key
69197 var rsaKey = {
69198 type: 'rsa',
69199 parts: []
69200 };
69201 rsaKey.parts.push({ name: 'e', data: publicExponent});
69202 rsaKey.parts.push({ name: 'n', data: modulus});
69203 return (new Key(rsaKey));
69204 }
69205 if (supportedAlgosById[algorithm] === 'ECDSA-P384-SHA384' ||
69206 supportedAlgosById[algorithm] === 'ECDSA-P256-SHA256') {
69207 var curve = 'nistp384';
69208 var size = 384;
69209 if (supportedAlgosById[algorithm].match(/^ECDSA-P256-SHA256/)) {
69210 curve = 'nistp256';
69211 size = 256;
69212 }
69213
69214 var ecdsaKey = {
69215 type: 'ecdsa',
69216 curve: curve,
69217 size: size,
69218 parts: [
69219 {name: 'curve', data: Buffer.from(curve) },
69220 {name: 'Q', data: utils.ecNormalize(keyBuffer) }
69221 ]
69222 };
69223 return (new Key(ecdsaKey));
69224 }
69225 throw (new Error('Unsupported algorithm: ' +
69226 supportedAlgosById[algorithm]));
69227}
69228
69229function elementToBuf(e) {
69230 return (Buffer.from(e.split(' ')[1], 'base64'));
69231}
69232
69233function readDNSSECRSAPrivateKey(elements) {
69234 var rsaParams = {};
69235 elements.forEach(function (element) {
69236 if (element.split(' ')[0] === 'Modulus:')
69237 rsaParams['n'] = elementToBuf(element);
69238 else if (element.split(' ')[0] === 'PublicExponent:')
69239 rsaParams['e'] = elementToBuf(element);
69240 else if (element.split(' ')[0] === 'PrivateExponent:')
69241 rsaParams['d'] = elementToBuf(element);
69242 else if (element.split(' ')[0] === 'Prime1:')
69243 rsaParams['p'] = elementToBuf(element);
69244 else if (element.split(' ')[0] === 'Prime2:')
69245 rsaParams['q'] = elementToBuf(element);
69246 else if (element.split(' ')[0] === 'Exponent1:')
69247 rsaParams['dmodp'] = elementToBuf(element);
69248 else if (element.split(' ')[0] === 'Exponent2:')
69249 rsaParams['dmodq'] = elementToBuf(element);
69250 else if (element.split(' ')[0] === 'Coefficient:')
69251 rsaParams['iqmp'] = elementToBuf(element);
69252 });
69253 // now, make the key
69254 var key = {
69255 type: 'rsa',
69256 parts: [
69257 { name: 'e', data: utils.mpNormalize(rsaParams['e'])},
69258 { name: 'n', data: utils.mpNormalize(rsaParams['n'])},
69259 { name: 'd', data: utils.mpNormalize(rsaParams['d'])},
69260 { name: 'p', data: utils.mpNormalize(rsaParams['p'])},
69261 { name: 'q', data: utils.mpNormalize(rsaParams['q'])},
69262 { name: 'dmodp',
69263 data: utils.mpNormalize(rsaParams['dmodp'])},
69264 { name: 'dmodq',
69265 data: utils.mpNormalize(rsaParams['dmodq'])},
69266 { name: 'iqmp',
69267 data: utils.mpNormalize(rsaParams['iqmp'])}
69268 ]
69269 };
69270 return (new PrivateKey(key));
69271}
69272
69273function readDNSSECPrivateKey(alg, elements) {
69274 if (supportedAlgosById[alg].match(/^RSA-/)) {
69275 return (readDNSSECRSAPrivateKey(elements));
69276 }
69277 if (supportedAlgosById[alg] === 'ECDSA-P384-SHA384' ||
69278 supportedAlgosById[alg] === 'ECDSA-P256-SHA256') {
69279 var d = Buffer.from(elements[0].split(' ')[1], 'base64');
69280 var curve = 'nistp384';
69281 var size = 384;
69282 if (supportedAlgosById[alg] === 'ECDSA-P256-SHA256') {
69283 curve = 'nistp256';
69284 size = 256;
69285 }
69286 // DNSSEC generates the public-key on the fly (go calculate it)
69287 var publicKey = utils.publicFromPrivateECDSA(curve, d);
69288 var Q = publicKey.part['Q'].data;
69289 var ecdsaKey = {
69290 type: 'ecdsa',
69291 curve: curve,
69292 size: size,
69293 parts: [
69294 {name: 'curve', data: Buffer.from(curve) },
69295 {name: 'd', data: d },
69296 {name: 'Q', data: Q }
69297 ]
69298 };
69299 return (new PrivateKey(ecdsaKey));
69300 }
69301 throw (new Error('Unsupported algorithm: ' + supportedAlgosById[alg]));
69302}
69303
69304function dnssecTimestamp(date) {
69305 var year = date.getFullYear() + ''; //stringify
69306 var month = (date.getMonth() + 1);
69307 var timestampStr = year + month + date.getUTCDate();
69308 timestampStr += '' + date.getUTCHours() + date.getUTCMinutes();
69309 timestampStr += date.getUTCSeconds();
69310 return (timestampStr);
69311}
69312
69313function rsaAlgFromOptions(opts) {
69314 if (!opts || !opts.hashAlgo || opts.hashAlgo === 'sha1')
69315 return ('5 (RSASHA1)');
69316 else if (opts.hashAlgo === 'sha256')
69317 return ('8 (RSASHA256)');
69318 else if (opts.hashAlgo === 'sha512')
69319 return ('10 (RSASHA512)');
69320 else
69321 throw (new Error('Unknown or unsupported hash: ' +
69322 opts.hashAlgo));
69323}
69324
69325function writeRSA(key, options) {
69326 // if we're missing parts, add them.
69327 if (!key.part.dmodp || !key.part.dmodq) {
69328 utils.addRSAMissing(key);
69329 }
69330
69331 var out = '';
69332 out += 'Private-key-format: v1.3\n';
69333 out += 'Algorithm: ' + rsaAlgFromOptions(options) + '\n';
69334 var n = utils.mpDenormalize(key.part['n'].data);
69335 out += 'Modulus: ' + n.toString('base64') + '\n';
69336 var e = utils.mpDenormalize(key.part['e'].data);
69337 out += 'PublicExponent: ' + e.toString('base64') + '\n';
69338 var d = utils.mpDenormalize(key.part['d'].data);
69339 out += 'PrivateExponent: ' + d.toString('base64') + '\n';
69340 var p = utils.mpDenormalize(key.part['p'].data);
69341 out += 'Prime1: ' + p.toString('base64') + '\n';
69342 var q = utils.mpDenormalize(key.part['q'].data);
69343 out += 'Prime2: ' + q.toString('base64') + '\n';
69344 var dmodp = utils.mpDenormalize(key.part['dmodp'].data);
69345 out += 'Exponent1: ' + dmodp.toString('base64') + '\n';
69346 var dmodq = utils.mpDenormalize(key.part['dmodq'].data);
69347 out += 'Exponent2: ' + dmodq.toString('base64') + '\n';
69348 var iqmp = utils.mpDenormalize(key.part['iqmp'].data);
69349 out += 'Coefficient: ' + iqmp.toString('base64') + '\n';
69350 // Assume that we're valid as-of now
69351 var timestamp = new Date();
69352 out += 'Created: ' + dnssecTimestamp(timestamp) + '\n';
69353 out += 'Publish: ' + dnssecTimestamp(timestamp) + '\n';
69354 out += 'Activate: ' + dnssecTimestamp(timestamp) + '\n';
69355 return (Buffer.from(out, 'ascii'));
69356}
69357
69358function writeECDSA(key, options) {
69359 var out = '';
69360 out += 'Private-key-format: v1.3\n';
69361
69362 if (key.curve === 'nistp256') {
69363 out += 'Algorithm: 13 (ECDSAP256SHA256)\n';
69364 } else if (key.curve === 'nistp384') {
69365 out += 'Algorithm: 14 (ECDSAP384SHA384)\n';
69366 } else {
69367 throw (new Error('Unsupported curve'));
69368 }
69369 var base64Key = key.part['d'].data.toString('base64');
69370 out += 'PrivateKey: ' + base64Key + '\n';
69371
69372 // Assume that we're valid as-of now
69373 var timestamp = new Date();
69374 out += 'Created: ' + dnssecTimestamp(timestamp) + '\n';
69375 out += 'Publish: ' + dnssecTimestamp(timestamp) + '\n';
69376 out += 'Activate: ' + dnssecTimestamp(timestamp) + '\n';
69377
69378 return (Buffer.from(out, 'ascii'));
69379}
69380
69381function write(key, options) {
69382 if (PrivateKey.isPrivateKey(key)) {
69383 if (key.type === 'rsa') {
69384 return (writeRSA(key, options));
69385 } else if (key.type === 'ecdsa') {
69386 return (writeECDSA(key, options));
69387 } else {
69388 throw (new Error('Unsupported algorithm: ' + key.type));
69389 }
69390 } else if (Key.isKey(key)) {
69391 /*
69392 * RFC3110 requires a keyname, and a keytype, which we
69393 * don't really have a mechanism for specifying such
69394 * additional metadata.
69395 */
69396 throw (new Error('Format "dnssec" only supports ' +
69397 'writing private keys'));
69398 } else {
69399 throw (new Error('key is not a Key or PrivateKey'));
69400 }
69401}
69402
69403},{"../dhe":337,"../key":355,"../private-key":356,"../ssh-buffer":358,"../utils":359,"assert-plus":67,"safer-buffer":326}],343:[function(require,module,exports){
69404// Copyright 2017 Joyent, Inc.
69405
69406module.exports = {
69407 read: read,
69408 verify: verify,
69409 sign: sign,
69410 signAsync: signAsync,
69411 write: write,
69412
69413 /* Internal private API */
69414 fromBuffer: fromBuffer,
69415 toBuffer: toBuffer
69416};
69417
69418var assert = require('assert-plus');
69419var SSHBuffer = require('../ssh-buffer');
69420var crypto = require('crypto');
69421var Buffer = require('safer-buffer').Buffer;
69422var algs = require('../algs');
69423var Key = require('../key');
69424var PrivateKey = require('../private-key');
69425var Identity = require('../identity');
69426var rfc4253 = require('./rfc4253');
69427var Signature = require('../signature');
69428var utils = require('../utils');
69429var Certificate = require('../certificate');
69430
69431function verify(cert, key) {
69432 /*
69433 * We always give an issuerKey, so if our verify() is being called then
69434 * there was no signature. Return false.
69435 */
69436 return (false);
69437}
69438
69439var TYPES = {
69440 'user': 1,
69441 'host': 2
69442};
69443Object.keys(TYPES).forEach(function (k) { TYPES[TYPES[k]] = k; });
69444
69445var ECDSA_ALGO = /^ecdsa-sha2-([^@-]+)-cert-v01@openssh.com$/;
69446
69447function read(buf, options) {
69448 if (Buffer.isBuffer(buf))
69449 buf = buf.toString('ascii');
69450 var parts = buf.trim().split(/[ \t\n]+/g);
69451 if (parts.length < 2 || parts.length > 3)
69452 throw (new Error('Not a valid SSH certificate line'));
69453
69454 var algo = parts[0];
69455 var data = parts[1];
69456
69457 data = Buffer.from(data, 'base64');
69458 return (fromBuffer(data, algo));
69459}
69460
69461function fromBuffer(data, algo, partial) {
69462 var sshbuf = new SSHBuffer({ buffer: data });
69463 var innerAlgo = sshbuf.readString();
69464 if (algo !== undefined && innerAlgo !== algo)
69465 throw (new Error('SSH certificate algorithm mismatch'));
69466 if (algo === undefined)
69467 algo = innerAlgo;
69468
69469 var cert = {};
69470 cert.signatures = {};
69471 cert.signatures.openssh = {};
69472
69473 cert.signatures.openssh.nonce = sshbuf.readBuffer();
69474
69475 var key = {};
69476 var parts = (key.parts = []);
69477 key.type = getAlg(algo);
69478
69479 var partCount = algs.info[key.type].parts.length;
69480 while (parts.length < partCount)
69481 parts.push(sshbuf.readPart());
69482 assert.ok(parts.length >= 1, 'key must have at least one part');
69483
69484 var algInfo = algs.info[key.type];
69485 if (key.type === 'ecdsa') {
69486 var res = ECDSA_ALGO.exec(algo);
69487 assert.ok(res !== null);
69488 assert.strictEqual(res[1], parts[0].data.toString());
69489 }
69490
69491 for (var i = 0; i < algInfo.parts.length; ++i) {
69492 parts[i].name = algInfo.parts[i];
69493 if (parts[i].name !== 'curve' &&
69494 algInfo.normalize !== false) {
69495 var p = parts[i];
69496 p.data = utils.mpNormalize(p.data);
69497 }
69498 }
69499
69500 cert.subjectKey = new Key(key);
69501
69502 cert.serial = sshbuf.readInt64();
69503
69504 var type = TYPES[sshbuf.readInt()];
69505 assert.string(type, 'valid cert type');
69506
69507 cert.signatures.openssh.keyId = sshbuf.readString();
69508
69509 var principals = [];
69510 var pbuf = sshbuf.readBuffer();
69511 var psshbuf = new SSHBuffer({ buffer: pbuf });
69512 while (!psshbuf.atEnd())
69513 principals.push(psshbuf.readString());
69514 if (principals.length === 0)
69515 principals = ['*'];
69516
69517 cert.subjects = principals.map(function (pr) {
69518 if (type === 'user')
69519 return (Identity.forUser(pr));
69520 else if (type === 'host')
69521 return (Identity.forHost(pr));
69522 throw (new Error('Unknown identity type ' + type));
69523 });
69524
69525 cert.validFrom = int64ToDate(sshbuf.readInt64());
69526 cert.validUntil = int64ToDate(sshbuf.readInt64());
69527
69528 var exts = [];
69529 var extbuf = new SSHBuffer({ buffer: sshbuf.readBuffer() });
69530 var ext;
69531 while (!extbuf.atEnd()) {
69532 ext = { critical: true };
69533 ext.name = extbuf.readString();
69534 ext.data = extbuf.readBuffer();
69535 exts.push(ext);
69536 }
69537 extbuf = new SSHBuffer({ buffer: sshbuf.readBuffer() });
69538 while (!extbuf.atEnd()) {
69539 ext = { critical: false };
69540 ext.name = extbuf.readString();
69541 ext.data = extbuf.readBuffer();
69542 exts.push(ext);
69543 }
69544 cert.signatures.openssh.exts = exts;
69545
69546 /* reserved */
69547 sshbuf.readBuffer();
69548
69549 var signingKeyBuf = sshbuf.readBuffer();
69550 cert.issuerKey = rfc4253.read(signingKeyBuf);
69551
69552 /*
69553 * OpenSSH certs don't give the identity of the issuer, just their
69554 * public key. So, we use an Identity that matches anything. The
69555 * isSignedBy() function will later tell you if the key matches.
69556 */
69557 cert.issuer = Identity.forHost('**');
69558
69559 var sigBuf = sshbuf.readBuffer();
69560 cert.signatures.openssh.signature =
69561 Signature.parse(sigBuf, cert.issuerKey.type, 'ssh');
69562
69563 if (partial !== undefined) {
69564 partial.remainder = sshbuf.remainder();
69565 partial.consumed = sshbuf._offset;
69566 }
69567
69568 return (new Certificate(cert));
69569}
69570
69571function int64ToDate(buf) {
69572 var i = buf.readUInt32BE(0) * 4294967296;
69573 i += buf.readUInt32BE(4);
69574 var d = new Date();
69575 d.setTime(i * 1000);
69576 d.sourceInt64 = buf;
69577 return (d);
69578}
69579
69580function dateToInt64(date) {
69581 if (date.sourceInt64 !== undefined)
69582 return (date.sourceInt64);
69583 var i = Math.round(date.getTime() / 1000);
69584 var upper = Math.floor(i / 4294967296);
69585 var lower = Math.floor(i % 4294967296);
69586 var buf = Buffer.alloc(8);
69587 buf.writeUInt32BE(upper, 0);
69588 buf.writeUInt32BE(lower, 4);
69589 return (buf);
69590}
69591
69592function sign(cert, key) {
69593 if (cert.signatures.openssh === undefined)
69594 cert.signatures.openssh = {};
69595 try {
69596 var blob = toBuffer(cert, true);
69597 } catch (e) {
69598 delete (cert.signatures.openssh);
69599 return (false);
69600 }
69601 var sig = cert.signatures.openssh;
69602 var hashAlgo = undefined;
69603 if (key.type === 'rsa' || key.type === 'dsa')
69604 hashAlgo = 'sha1';
69605 var signer = key.createSign(hashAlgo);
69606 signer.write(blob);
69607 sig.signature = signer.sign();
69608 return (true);
69609}
69610
69611function signAsync(cert, signer, done) {
69612 if (cert.signatures.openssh === undefined)
69613 cert.signatures.openssh = {};
69614 try {
69615 var blob = toBuffer(cert, true);
69616 } catch (e) {
69617 delete (cert.signatures.openssh);
69618 done(e);
69619 return;
69620 }
69621 var sig = cert.signatures.openssh;
69622
69623 signer(blob, function (err, signature) {
69624 if (err) {
69625 done(err);
69626 return;
69627 }
69628 try {
69629 /*
69630 * This will throw if the signature isn't of a
69631 * type/algo that can be used for SSH.
69632 */
69633 signature.toBuffer('ssh');
69634 } catch (e) {
69635 done(e);
69636 return;
69637 }
69638 sig.signature = signature;
69639 done();
69640 });
69641}
69642
69643function write(cert, options) {
69644 if (options === undefined)
69645 options = {};
69646
69647 var blob = toBuffer(cert);
69648 var out = getCertType(cert.subjectKey) + ' ' + blob.toString('base64');
69649 if (options.comment)
69650 out = out + ' ' + options.comment;
69651 return (out);
69652}
69653
69654
69655function toBuffer(cert, noSig) {
69656 assert.object(cert.signatures.openssh, 'signature for openssh format');
69657 var sig = cert.signatures.openssh;
69658
69659 if (sig.nonce === undefined)
69660 sig.nonce = crypto.randomBytes(16);
69661 var buf = new SSHBuffer({});
69662 buf.writeString(getCertType(cert.subjectKey));
69663 buf.writeBuffer(sig.nonce);
69664
69665 var key = cert.subjectKey;
69666 var algInfo = algs.info[key.type];
69667 algInfo.parts.forEach(function (part) {
69668 buf.writePart(key.part[part]);
69669 });
69670
69671 buf.writeInt64(cert.serial);
69672
69673 var type = cert.subjects[0].type;
69674 assert.notStrictEqual(type, 'unknown');
69675 cert.subjects.forEach(function (id) {
69676 assert.strictEqual(id.type, type);
69677 });
69678 type = TYPES[type];
69679 buf.writeInt(type);
69680
69681 if (sig.keyId === undefined) {
69682 sig.keyId = cert.subjects[0].type + '_' +
69683 (cert.subjects[0].uid || cert.subjects[0].hostname);
69684 }
69685 buf.writeString(sig.keyId);
69686
69687 var sub = new SSHBuffer({});
69688 cert.subjects.forEach(function (id) {
69689 if (type === TYPES.host)
69690 sub.writeString(id.hostname);
69691 else if (type === TYPES.user)
69692 sub.writeString(id.uid);
69693 });
69694 buf.writeBuffer(sub.toBuffer());
69695
69696 buf.writeInt64(dateToInt64(cert.validFrom));
69697 buf.writeInt64(dateToInt64(cert.validUntil));
69698
69699 var exts = sig.exts;
69700 if (exts === undefined)
69701 exts = [];
69702
69703 var extbuf = new SSHBuffer({});
69704 exts.forEach(function (ext) {
69705 if (ext.critical !== true)
69706 return;
69707 extbuf.writeString(ext.name);
69708 extbuf.writeBuffer(ext.data);
69709 });
69710 buf.writeBuffer(extbuf.toBuffer());
69711
69712 extbuf = new SSHBuffer({});
69713 exts.forEach(function (ext) {
69714 if (ext.critical === true)
69715 return;
69716 extbuf.writeString(ext.name);
69717 extbuf.writeBuffer(ext.data);
69718 });
69719 buf.writeBuffer(extbuf.toBuffer());
69720
69721 /* reserved */
69722 buf.writeBuffer(Buffer.alloc(0));
69723
69724 sub = rfc4253.write(cert.issuerKey);
69725 buf.writeBuffer(sub);
69726
69727 if (!noSig)
69728 buf.writeBuffer(sig.signature.toBuffer('ssh'));
69729
69730 return (buf.toBuffer());
69731}
69732
69733function getAlg(certType) {
69734 if (certType === 'ssh-rsa-cert-v01@openssh.com')
69735 return ('rsa');
69736 if (certType === 'ssh-dss-cert-v01@openssh.com')
69737 return ('dsa');
69738 if (certType.match(ECDSA_ALGO))
69739 return ('ecdsa');
69740 if (certType === 'ssh-ed25519-cert-v01@openssh.com')
69741 return ('ed25519');
69742 throw (new Error('Unsupported cert type ' + certType));
69743}
69744
69745function getCertType(key) {
69746 if (key.type === 'rsa')
69747 return ('ssh-rsa-cert-v01@openssh.com');
69748 if (key.type === 'dsa')
69749 return ('ssh-dss-cert-v01@openssh.com');
69750 if (key.type === 'ecdsa')
69751 return ('ecdsa-sha2-' + key.curve + '-cert-v01@openssh.com');
69752 if (key.type === 'ed25519')
69753 return ('ssh-ed25519-cert-v01@openssh.com');
69754 throw (new Error('Unsupported key type ' + key.type));
69755}
69756
69757},{"../algs":335,"../certificate":336,"../identity":353,"../key":355,"../private-key":356,"../signature":357,"../ssh-buffer":358,"../utils":359,"./rfc4253":348,"assert-plus":67,"crypto":126,"safer-buffer":326}],344:[function(require,module,exports){
69758// Copyright 2018 Joyent, Inc.
69759
69760module.exports = {
69761 read: read,
69762 write: write
69763};
69764
69765var assert = require('assert-plus');
69766var asn1 = require('asn1');
69767var crypto = require('crypto');
69768var Buffer = require('safer-buffer').Buffer;
69769var algs = require('../algs');
69770var utils = require('../utils');
69771var Key = require('../key');
69772var PrivateKey = require('../private-key');
69773
69774var pkcs1 = require('./pkcs1');
69775var pkcs8 = require('./pkcs8');
69776var sshpriv = require('./ssh-private');
69777var rfc4253 = require('./rfc4253');
69778
69779var errors = require('../errors');
69780
69781var OID_PBES2 = '1.2.840.113549.1.5.13';
69782var OID_PBKDF2 = '1.2.840.113549.1.5.12';
69783
69784var OID_TO_CIPHER = {
69785 '1.2.840.113549.3.7': '3des-cbc',
69786 '2.16.840.1.101.3.4.1.2': 'aes128-cbc',
69787 '2.16.840.1.101.3.4.1.42': 'aes256-cbc'
69788};
69789var CIPHER_TO_OID = {};
69790Object.keys(OID_TO_CIPHER).forEach(function (k) {
69791 CIPHER_TO_OID[OID_TO_CIPHER[k]] = k;
69792});
69793
69794var OID_TO_HASH = {
69795 '1.2.840.113549.2.7': 'sha1',
69796 '1.2.840.113549.2.9': 'sha256',
69797 '1.2.840.113549.2.11': 'sha512'
69798};
69799var HASH_TO_OID = {};
69800Object.keys(OID_TO_HASH).forEach(function (k) {
69801 HASH_TO_OID[OID_TO_HASH[k]] = k;
69802});
69803
69804/*
69805 * For reading we support both PKCS#1 and PKCS#8. If we find a private key,
69806 * we just take the public component of it and use that.
69807 */
69808function read(buf, options, forceType) {
69809 var input = buf;
69810 if (typeof (buf) !== 'string') {
69811 assert.buffer(buf, 'buf');
69812 buf = buf.toString('ascii');
69813 }
69814
69815 var lines = buf.trim().split(/[\r\n]+/g);
69816
69817 var m;
69818 var si = -1;
69819 while (!m && si < lines.length) {
69820 m = lines[++si].match(/*JSSTYLED*/
69821 /[-]+[ ]*BEGIN ([A-Z0-9][A-Za-z0-9]+ )?(PUBLIC|PRIVATE) KEY[ ]*[-]+/);
69822 }
69823 assert.ok(m, 'invalid PEM header');
69824
69825 var m2;
69826 var ei = lines.length;
69827 while (!m2 && ei > 0) {
69828 m2 = lines[--ei].match(/*JSSTYLED*/
69829 /[-]+[ ]*END ([A-Z0-9][A-Za-z0-9]+ )?(PUBLIC|PRIVATE) KEY[ ]*[-]+/);
69830 }
69831 assert.ok(m2, 'invalid PEM footer');
69832
69833 /* Begin and end banners must match key type */
69834 assert.equal(m[2], m2[2]);
69835 var type = m[2].toLowerCase();
69836
69837 var alg;
69838 if (m[1]) {
69839 /* They also must match algorithms, if given */
69840 assert.equal(m[1], m2[1], 'PEM header and footer mismatch');
69841 alg = m[1].trim();
69842 }
69843
69844 lines = lines.slice(si, ei + 1);
69845
69846 var headers = {};
69847 while (true) {
69848 lines = lines.slice(1);
69849 m = lines[0].match(/*JSSTYLED*/
69850 /^([A-Za-z0-9-]+): (.+)$/);
69851 if (!m)
69852 break;
69853 headers[m[1].toLowerCase()] = m[2];
69854 }
69855
69856 /* Chop off the first and last lines */
69857 lines = lines.slice(0, -1).join('');
69858 buf = Buffer.from(lines, 'base64');
69859
69860 var cipher, key, iv;
69861 if (headers['proc-type']) {
69862 var parts = headers['proc-type'].split(',');
69863 if (parts[0] === '4' && parts[1] === 'ENCRYPTED') {
69864 if (typeof (options.passphrase) === 'string') {
69865 options.passphrase = Buffer.from(
69866 options.passphrase, 'utf-8');
69867 }
69868 if (!Buffer.isBuffer(options.passphrase)) {
69869 throw (new errors.KeyEncryptedError(
69870 options.filename, 'PEM'));
69871 } else {
69872 parts = headers['dek-info'].split(',');
69873 assert.ok(parts.length === 2);
69874 cipher = parts[0].toLowerCase();
69875 iv = Buffer.from(parts[1], 'hex');
69876 key = utils.opensslKeyDeriv(cipher, iv,
69877 options.passphrase, 1).key;
69878 }
69879 }
69880 }
69881
69882 if (alg && alg.toLowerCase() === 'encrypted') {
69883 var eder = new asn1.BerReader(buf);
69884 var pbesEnd;
69885 eder.readSequence();
69886
69887 eder.readSequence();
69888 pbesEnd = eder.offset + eder.length;
69889
69890 var method = eder.readOID();
69891 if (method !== OID_PBES2) {
69892 throw (new Error('Unsupported PEM/PKCS8 encryption ' +
69893 'scheme: ' + method));
69894 }
69895
69896 eder.readSequence(); /* PBES2-params */
69897
69898 eder.readSequence(); /* keyDerivationFunc */
69899 var kdfEnd = eder.offset + eder.length;
69900 var kdfOid = eder.readOID();
69901 if (kdfOid !== OID_PBKDF2)
69902 throw (new Error('Unsupported PBES2 KDF: ' + kdfOid));
69903 eder.readSequence();
69904 var salt = eder.readString(asn1.Ber.OctetString, true);
69905 var iterations = eder.readInt();
69906 var hashAlg = 'sha1';
69907 if (eder.offset < kdfEnd) {
69908 eder.readSequence();
69909 var hashAlgOid = eder.readOID();
69910 hashAlg = OID_TO_HASH[hashAlgOid];
69911 if (hashAlg === undefined) {
69912 throw (new Error('Unsupported PBKDF2 hash: ' +
69913 hashAlgOid));
69914 }
69915 }
69916 eder._offset = kdfEnd;
69917
69918 eder.readSequence(); /* encryptionScheme */
69919 var cipherOid = eder.readOID();
69920 cipher = OID_TO_CIPHER[cipherOid];
69921 if (cipher === undefined) {
69922 throw (new Error('Unsupported PBES2 cipher: ' +
69923 cipherOid));
69924 }
69925 iv = eder.readString(asn1.Ber.OctetString, true);
69926
69927 eder._offset = pbesEnd;
69928 buf = eder.readString(asn1.Ber.OctetString, true);
69929
69930 if (typeof (options.passphrase) === 'string') {
69931 options.passphrase = Buffer.from(
69932 options.passphrase, 'utf-8');
69933 }
69934 if (!Buffer.isBuffer(options.passphrase)) {
69935 throw (new errors.KeyEncryptedError(
69936 options.filename, 'PEM'));
69937 }
69938
69939 var cinfo = utils.opensshCipherInfo(cipher);
69940
69941 cipher = cinfo.opensslName;
69942 key = utils.pbkdf2(hashAlg, salt, iterations, cinfo.keySize,
69943 options.passphrase);
69944 alg = undefined;
69945 }
69946
69947 if (cipher && key && iv) {
69948 var cipherStream = crypto.createDecipheriv(cipher, key, iv);
69949 var chunk, chunks = [];
69950 cipherStream.once('error', function (e) {
69951 if (e.toString().indexOf('bad decrypt') !== -1) {
69952 throw (new Error('Incorrect passphrase ' +
69953 'supplied, could not decrypt key'));
69954 }
69955 throw (e);
69956 });
69957 cipherStream.write(buf);
69958 cipherStream.end();
69959 while ((chunk = cipherStream.read()) !== null)
69960 chunks.push(chunk);
69961 buf = Buffer.concat(chunks);
69962 }
69963
69964 /* The new OpenSSH internal format abuses PEM headers */
69965 if (alg && alg.toLowerCase() === 'openssh')
69966 return (sshpriv.readSSHPrivate(type, buf, options));
69967 if (alg && alg.toLowerCase() === 'ssh2')
69968 return (rfc4253.readType(type, buf, options));
69969
69970 var der = new asn1.BerReader(buf);
69971 der.originalInput = input;
69972
69973 /*
69974 * All of the PEM file types start with a sequence tag, so chop it
69975 * off here
69976 */
69977 der.readSequence();
69978
69979 /* PKCS#1 type keys name an algorithm in the banner explicitly */
69980 if (alg) {
69981 if (forceType)
69982 assert.strictEqual(forceType, 'pkcs1');
69983 return (pkcs1.readPkcs1(alg, type, der));
69984 } else {
69985 if (forceType)
69986 assert.strictEqual(forceType, 'pkcs8');
69987 return (pkcs8.readPkcs8(alg, type, der));
69988 }
69989}
69990
69991function write(key, options, type) {
69992 assert.object(key);
69993
69994 var alg = {
69995 'ecdsa': 'EC',
69996 'rsa': 'RSA',
69997 'dsa': 'DSA',
69998 'ed25519': 'EdDSA'
69999 }[key.type];
70000 var header;
70001
70002 var der = new asn1.BerWriter();
70003
70004 if (PrivateKey.isPrivateKey(key)) {
70005 if (type && type === 'pkcs8') {
70006 header = 'PRIVATE KEY';
70007 pkcs8.writePkcs8(der, key);
70008 } else {
70009 if (type)
70010 assert.strictEqual(type, 'pkcs1');
70011 header = alg + ' PRIVATE KEY';
70012 pkcs1.writePkcs1(der, key);
70013 }
70014
70015 } else if (Key.isKey(key)) {
70016 if (type && type === 'pkcs1') {
70017 header = alg + ' PUBLIC KEY';
70018 pkcs1.writePkcs1(der, key);
70019 } else {
70020 if (type)
70021 assert.strictEqual(type, 'pkcs8');
70022 header = 'PUBLIC KEY';
70023 pkcs8.writePkcs8(der, key);
70024 }
70025
70026 } else {
70027 throw (new Error('key is not a Key or PrivateKey'));
70028 }
70029
70030 var tmp = der.buffer.toString('base64');
70031 var len = tmp.length + (tmp.length / 64) +
70032 18 + 16 + header.length*2 + 10;
70033 var buf = Buffer.alloc(len);
70034 var o = 0;
70035 o += buf.write('-----BEGIN ' + header + '-----\n', o);
70036 for (var i = 0; i < tmp.length; ) {
70037 var limit = i + 64;
70038 if (limit > tmp.length)
70039 limit = tmp.length;
70040 o += buf.write(tmp.slice(i, limit), o);
70041 buf[o++] = 10;
70042 i = limit;
70043 }
70044 o += buf.write('-----END ' + header + '-----\n', o);
70045
70046 return (buf.slice(0, o));
70047}
70048
70049},{"../algs":335,"../errors":339,"../key":355,"../private-key":356,"../utils":359,"./pkcs1":345,"./pkcs8":346,"./rfc4253":348,"./ssh-private":349,"asn1":66,"assert-plus":67,"crypto":126,"safer-buffer":326}],345:[function(require,module,exports){
70050// Copyright 2015 Joyent, Inc.
70051
70052module.exports = {
70053 read: read,
70054 readPkcs1: readPkcs1,
70055 write: write,
70056 writePkcs1: writePkcs1
70057};
70058
70059var assert = require('assert-plus');
70060var asn1 = require('asn1');
70061var Buffer = require('safer-buffer').Buffer;
70062var algs = require('../algs');
70063var utils = require('../utils');
70064
70065var Key = require('../key');
70066var PrivateKey = require('../private-key');
70067var pem = require('./pem');
70068
70069var pkcs8 = require('./pkcs8');
70070var readECDSACurve = pkcs8.readECDSACurve;
70071
70072function read(buf, options) {
70073 return (pem.read(buf, options, 'pkcs1'));
70074}
70075
70076function write(key, options) {
70077 return (pem.write(key, options, 'pkcs1'));
70078}
70079
70080/* Helper to read in a single mpint */
70081function readMPInt(der, nm) {
70082 assert.strictEqual(der.peek(), asn1.Ber.Integer,
70083 nm + ' is not an Integer');
70084 return (utils.mpNormalize(der.readString(asn1.Ber.Integer, true)));
70085}
70086
70087function readPkcs1(alg, type, der) {
70088 switch (alg) {
70089 case 'RSA':
70090 if (type === 'public')
70091 return (readPkcs1RSAPublic(der));
70092 else if (type === 'private')
70093 return (readPkcs1RSAPrivate(der));
70094 throw (new Error('Unknown key type: ' + type));
70095 case 'DSA':
70096 if (type === 'public')
70097 return (readPkcs1DSAPublic(der));
70098 else if (type === 'private')
70099 return (readPkcs1DSAPrivate(der));
70100 throw (new Error('Unknown key type: ' + type));
70101 case 'EC':
70102 case 'ECDSA':
70103 if (type === 'private')
70104 return (readPkcs1ECDSAPrivate(der));
70105 else if (type === 'public')
70106 return (readPkcs1ECDSAPublic(der));
70107 throw (new Error('Unknown key type: ' + type));
70108 case 'EDDSA':
70109 case 'EdDSA':
70110 if (type === 'private')
70111 return (readPkcs1EdDSAPrivate(der));
70112 throw (new Error(type + ' keys not supported with EdDSA'));
70113 default:
70114 throw (new Error('Unknown key algo: ' + alg));
70115 }
70116}
70117
70118function readPkcs1RSAPublic(der) {
70119 // modulus and exponent
70120 var n = readMPInt(der, 'modulus');
70121 var e = readMPInt(der, 'exponent');
70122
70123 // now, make the key
70124 var key = {
70125 type: 'rsa',
70126 parts: [
70127 { name: 'e', data: e },
70128 { name: 'n', data: n }
70129 ]
70130 };
70131
70132 return (new Key(key));
70133}
70134
70135function readPkcs1RSAPrivate(der) {
70136 var version = readMPInt(der, 'version');
70137 assert.strictEqual(version[0], 0);
70138
70139 // modulus then public exponent
70140 var n = readMPInt(der, 'modulus');
70141 var e = readMPInt(der, 'public exponent');
70142 var d = readMPInt(der, 'private exponent');
70143 var p = readMPInt(der, 'prime1');
70144 var q = readMPInt(der, 'prime2');
70145 var dmodp = readMPInt(der, 'exponent1');
70146 var dmodq = readMPInt(der, 'exponent2');
70147 var iqmp = readMPInt(der, 'iqmp');
70148
70149 // now, make the key
70150 var key = {
70151 type: 'rsa',
70152 parts: [
70153 { name: 'n', data: n },
70154 { name: 'e', data: e },
70155 { name: 'd', data: d },
70156 { name: 'iqmp', data: iqmp },
70157 { name: 'p', data: p },
70158 { name: 'q', data: q },
70159 { name: 'dmodp', data: dmodp },
70160 { name: 'dmodq', data: dmodq }
70161 ]
70162 };
70163
70164 return (new PrivateKey(key));
70165}
70166
70167function readPkcs1DSAPrivate(der) {
70168 var version = readMPInt(der, 'version');
70169 assert.strictEqual(version.readUInt8(0), 0);
70170
70171 var p = readMPInt(der, 'p');
70172 var q = readMPInt(der, 'q');
70173 var g = readMPInt(der, 'g');
70174 var y = readMPInt(der, 'y');
70175 var x = readMPInt(der, 'x');
70176
70177 // now, make the key
70178 var key = {
70179 type: 'dsa',
70180 parts: [
70181 { name: 'p', data: p },
70182 { name: 'q', data: q },
70183 { name: 'g', data: g },
70184 { name: 'y', data: y },
70185 { name: 'x', data: x }
70186 ]
70187 };
70188
70189 return (new PrivateKey(key));
70190}
70191
70192function readPkcs1EdDSAPrivate(der) {
70193 var version = readMPInt(der, 'version');
70194 assert.strictEqual(version.readUInt8(0), 1);
70195
70196 // private key
70197 var k = der.readString(asn1.Ber.OctetString, true);
70198
70199 der.readSequence(0xa0);
70200 var oid = der.readOID();
70201 assert.strictEqual(oid, '1.3.101.112', 'the ed25519 curve identifier');
70202
70203 der.readSequence(0xa1);
70204 var A = utils.readBitString(der);
70205
70206 var key = {
70207 type: 'ed25519',
70208 parts: [
70209 { name: 'A', data: utils.zeroPadToLength(A, 32) },
70210 { name: 'k', data: k }
70211 ]
70212 };
70213
70214 return (new PrivateKey(key));
70215}
70216
70217function readPkcs1DSAPublic(der) {
70218 var y = readMPInt(der, 'y');
70219 var p = readMPInt(der, 'p');
70220 var q = readMPInt(der, 'q');
70221 var g = readMPInt(der, 'g');
70222
70223 var key = {
70224 type: 'dsa',
70225 parts: [
70226 { name: 'y', data: y },
70227 { name: 'p', data: p },
70228 { name: 'q', data: q },
70229 { name: 'g', data: g }
70230 ]
70231 };
70232
70233 return (new Key(key));
70234}
70235
70236function readPkcs1ECDSAPublic(der) {
70237 der.readSequence();
70238
70239 var oid = der.readOID();
70240 assert.strictEqual(oid, '1.2.840.10045.2.1', 'must be ecPublicKey');
70241
70242 var curveOid = der.readOID();
70243
70244 var curve;
70245 var curves = Object.keys(algs.curves);
70246 for (var j = 0; j < curves.length; ++j) {
70247 var c = curves[j];
70248 var cd = algs.curves[c];
70249 if (cd.pkcs8oid === curveOid) {
70250 curve = c;
70251 break;
70252 }
70253 }
70254 assert.string(curve, 'a known ECDSA named curve');
70255
70256 var Q = der.readString(asn1.Ber.BitString, true);
70257 Q = utils.ecNormalize(Q);
70258
70259 var key = {
70260 type: 'ecdsa',
70261 parts: [
70262 { name: 'curve', data: Buffer.from(curve) },
70263 { name: 'Q', data: Q }
70264 ]
70265 };
70266
70267 return (new Key(key));
70268}
70269
70270function readPkcs1ECDSAPrivate(der) {
70271 var version = readMPInt(der, 'version');
70272 assert.strictEqual(version.readUInt8(0), 1);
70273
70274 // private key
70275 var d = der.readString(asn1.Ber.OctetString, true);
70276
70277 der.readSequence(0xa0);
70278 var curve = readECDSACurve(der);
70279 assert.string(curve, 'a known elliptic curve');
70280
70281 der.readSequence(0xa1);
70282 var Q = der.readString(asn1.Ber.BitString, true);
70283 Q = utils.ecNormalize(Q);
70284
70285 var key = {
70286 type: 'ecdsa',
70287 parts: [
70288 { name: 'curve', data: Buffer.from(curve) },
70289 { name: 'Q', data: Q },
70290 { name: 'd', data: d }
70291 ]
70292 };
70293
70294 return (new PrivateKey(key));
70295}
70296
70297function writePkcs1(der, key) {
70298 der.startSequence();
70299
70300 switch (key.type) {
70301 case 'rsa':
70302 if (PrivateKey.isPrivateKey(key))
70303 writePkcs1RSAPrivate(der, key);
70304 else
70305 writePkcs1RSAPublic(der, key);
70306 break;
70307 case 'dsa':
70308 if (PrivateKey.isPrivateKey(key))
70309 writePkcs1DSAPrivate(der, key);
70310 else
70311 writePkcs1DSAPublic(der, key);
70312 break;
70313 case 'ecdsa':
70314 if (PrivateKey.isPrivateKey(key))
70315 writePkcs1ECDSAPrivate(der, key);
70316 else
70317 writePkcs1ECDSAPublic(der, key);
70318 break;
70319 case 'ed25519':
70320 if (PrivateKey.isPrivateKey(key))
70321 writePkcs1EdDSAPrivate(der, key);
70322 else
70323 writePkcs1EdDSAPublic(der, key);
70324 break;
70325 default:
70326 throw (new Error('Unknown key algo: ' + key.type));
70327 }
70328
70329 der.endSequence();
70330}
70331
70332function writePkcs1RSAPublic(der, key) {
70333 der.writeBuffer(key.part.n.data, asn1.Ber.Integer);
70334 der.writeBuffer(key.part.e.data, asn1.Ber.Integer);
70335}
70336
70337function writePkcs1RSAPrivate(der, key) {
70338 var ver = Buffer.from([0]);
70339 der.writeBuffer(ver, asn1.Ber.Integer);
70340
70341 der.writeBuffer(key.part.n.data, asn1.Ber.Integer);
70342 der.writeBuffer(key.part.e.data, asn1.Ber.Integer);
70343 der.writeBuffer(key.part.d.data, asn1.Ber.Integer);
70344 der.writeBuffer(key.part.p.data, asn1.Ber.Integer);
70345 der.writeBuffer(key.part.q.data, asn1.Ber.Integer);
70346 if (!key.part.dmodp || !key.part.dmodq)
70347 utils.addRSAMissing(key);
70348 der.writeBuffer(key.part.dmodp.data, asn1.Ber.Integer);
70349 der.writeBuffer(key.part.dmodq.data, asn1.Ber.Integer);
70350 der.writeBuffer(key.part.iqmp.data, asn1.Ber.Integer);
70351}
70352
70353function writePkcs1DSAPrivate(der, key) {
70354 var ver = Buffer.from([0]);
70355 der.writeBuffer(ver, asn1.Ber.Integer);
70356
70357 der.writeBuffer(key.part.p.data, asn1.Ber.Integer);
70358 der.writeBuffer(key.part.q.data, asn1.Ber.Integer);
70359 der.writeBuffer(key.part.g.data, asn1.Ber.Integer);
70360 der.writeBuffer(key.part.y.data, asn1.Ber.Integer);
70361 der.writeBuffer(key.part.x.data, asn1.Ber.Integer);
70362}
70363
70364function writePkcs1DSAPublic(der, key) {
70365 der.writeBuffer(key.part.y.data, asn1.Ber.Integer);
70366 der.writeBuffer(key.part.p.data, asn1.Ber.Integer);
70367 der.writeBuffer(key.part.q.data, asn1.Ber.Integer);
70368 der.writeBuffer(key.part.g.data, asn1.Ber.Integer);
70369}
70370
70371function writePkcs1ECDSAPublic(der, key) {
70372 der.startSequence();
70373
70374 der.writeOID('1.2.840.10045.2.1'); /* ecPublicKey */
70375 var curve = key.part.curve.data.toString();
70376 var curveOid = algs.curves[curve].pkcs8oid;
70377 assert.string(curveOid, 'a known ECDSA named curve');
70378 der.writeOID(curveOid);
70379
70380 der.endSequence();
70381
70382 var Q = utils.ecNormalize(key.part.Q.data, true);
70383 der.writeBuffer(Q, asn1.Ber.BitString);
70384}
70385
70386function writePkcs1ECDSAPrivate(der, key) {
70387 var ver = Buffer.from([1]);
70388 der.writeBuffer(ver, asn1.Ber.Integer);
70389
70390 der.writeBuffer(key.part.d.data, asn1.Ber.OctetString);
70391
70392 der.startSequence(0xa0);
70393 var curve = key.part.curve.data.toString();
70394 var curveOid = algs.curves[curve].pkcs8oid;
70395 assert.string(curveOid, 'a known ECDSA named curve');
70396 der.writeOID(curveOid);
70397 der.endSequence();
70398
70399 der.startSequence(0xa1);
70400 var Q = utils.ecNormalize(key.part.Q.data, true);
70401 der.writeBuffer(Q, asn1.Ber.BitString);
70402 der.endSequence();
70403}
70404
70405function writePkcs1EdDSAPrivate(der, key) {
70406 var ver = Buffer.from([1]);
70407 der.writeBuffer(ver, asn1.Ber.Integer);
70408
70409 der.writeBuffer(key.part.k.data, asn1.Ber.OctetString);
70410
70411 der.startSequence(0xa0);
70412 der.writeOID('1.3.101.112');
70413 der.endSequence();
70414
70415 der.startSequence(0xa1);
70416 utils.writeBitString(der, key.part.A.data);
70417 der.endSequence();
70418}
70419
70420function writePkcs1EdDSAPublic(der, key) {
70421 throw (new Error('Public keys are not supported for EdDSA PKCS#1'));
70422}
70423
70424},{"../algs":335,"../key":355,"../private-key":356,"../utils":359,"./pem":344,"./pkcs8":346,"asn1":66,"assert-plus":67,"safer-buffer":326}],346:[function(require,module,exports){
70425// Copyright 2018 Joyent, Inc.
70426
70427module.exports = {
70428 read: read,
70429 readPkcs8: readPkcs8,
70430 write: write,
70431 writePkcs8: writePkcs8,
70432 pkcs8ToBuffer: pkcs8ToBuffer,
70433
70434 readECDSACurve: readECDSACurve,
70435 writeECDSACurve: writeECDSACurve
70436};
70437
70438var assert = require('assert-plus');
70439var asn1 = require('asn1');
70440var Buffer = require('safer-buffer').Buffer;
70441var algs = require('../algs');
70442var utils = require('../utils');
70443var Key = require('../key');
70444var PrivateKey = require('../private-key');
70445var pem = require('./pem');
70446
70447function read(buf, options) {
70448 return (pem.read(buf, options, 'pkcs8'));
70449}
70450
70451function write(key, options) {
70452 return (pem.write(key, options, 'pkcs8'));
70453}
70454
70455/* Helper to read in a single mpint */
70456function readMPInt(der, nm) {
70457 assert.strictEqual(der.peek(), asn1.Ber.Integer,
70458 nm + ' is not an Integer');
70459 return (utils.mpNormalize(der.readString(asn1.Ber.Integer, true)));
70460}
70461
70462function readPkcs8(alg, type, der) {
70463 /* Private keys in pkcs#8 format have a weird extra int */
70464 if (der.peek() === asn1.Ber.Integer) {
70465 assert.strictEqual(type, 'private',
70466 'unexpected Integer at start of public key');
70467 der.readString(asn1.Ber.Integer, true);
70468 }
70469
70470 der.readSequence();
70471 var next = der.offset + der.length;
70472
70473 var oid = der.readOID();
70474 switch (oid) {
70475 case '1.2.840.113549.1.1.1':
70476 der._offset = next;
70477 if (type === 'public')
70478 return (readPkcs8RSAPublic(der));
70479 else
70480 return (readPkcs8RSAPrivate(der));
70481 case '1.2.840.10040.4.1':
70482 if (type === 'public')
70483 return (readPkcs8DSAPublic(der));
70484 else
70485 return (readPkcs8DSAPrivate(der));
70486 case '1.2.840.10045.2.1':
70487 if (type === 'public')
70488 return (readPkcs8ECDSAPublic(der));
70489 else
70490 return (readPkcs8ECDSAPrivate(der));
70491 case '1.3.101.112':
70492 if (type === 'public') {
70493 return (readPkcs8EdDSAPublic(der));
70494 } else {
70495 return (readPkcs8EdDSAPrivate(der));
70496 }
70497 case '1.3.101.110':
70498 if (type === 'public') {
70499 return (readPkcs8X25519Public(der));
70500 } else {
70501 return (readPkcs8X25519Private(der));
70502 }
70503 default:
70504 throw (new Error('Unknown key type OID ' + oid));
70505 }
70506}
70507
70508function readPkcs8RSAPublic(der) {
70509 // bit string sequence
70510 der.readSequence(asn1.Ber.BitString);
70511 der.readByte();
70512 der.readSequence();
70513
70514 // modulus
70515 var n = readMPInt(der, 'modulus');
70516 var e = readMPInt(der, 'exponent');
70517
70518 // now, make the key
70519 var key = {
70520 type: 'rsa',
70521 source: der.originalInput,
70522 parts: [
70523 { name: 'e', data: e },
70524 { name: 'n', data: n }
70525 ]
70526 };
70527
70528 return (new Key(key));
70529}
70530
70531function readPkcs8RSAPrivate(der) {
70532 der.readSequence(asn1.Ber.OctetString);
70533 der.readSequence();
70534
70535 var ver = readMPInt(der, 'version');
70536 assert.equal(ver[0], 0x0, 'unknown RSA private key version');
70537
70538 // modulus then public exponent
70539 var n = readMPInt(der, 'modulus');
70540 var e = readMPInt(der, 'public exponent');
70541 var d = readMPInt(der, 'private exponent');
70542 var p = readMPInt(der, 'prime1');
70543 var q = readMPInt(der, 'prime2');
70544 var dmodp = readMPInt(der, 'exponent1');
70545 var dmodq = readMPInt(der, 'exponent2');
70546 var iqmp = readMPInt(der, 'iqmp');
70547
70548 // now, make the key
70549 var key = {
70550 type: 'rsa',
70551 parts: [
70552 { name: 'n', data: n },
70553 { name: 'e', data: e },
70554 { name: 'd', data: d },
70555 { name: 'iqmp', data: iqmp },
70556 { name: 'p', data: p },
70557 { name: 'q', data: q },
70558 { name: 'dmodp', data: dmodp },
70559 { name: 'dmodq', data: dmodq }
70560 ]
70561 };
70562
70563 return (new PrivateKey(key));
70564}
70565
70566function readPkcs8DSAPublic(der) {
70567 der.readSequence();
70568
70569 var p = readMPInt(der, 'p');
70570 var q = readMPInt(der, 'q');
70571 var g = readMPInt(der, 'g');
70572
70573 // bit string sequence
70574 der.readSequence(asn1.Ber.BitString);
70575 der.readByte();
70576
70577 var y = readMPInt(der, 'y');
70578
70579 // now, make the key
70580 var key = {
70581 type: 'dsa',
70582 parts: [
70583 { name: 'p', data: p },
70584 { name: 'q', data: q },
70585 { name: 'g', data: g },
70586 { name: 'y', data: y }
70587 ]
70588 };
70589
70590 return (new Key(key));
70591}
70592
70593function readPkcs8DSAPrivate(der) {
70594 der.readSequence();
70595
70596 var p = readMPInt(der, 'p');
70597 var q = readMPInt(der, 'q');
70598 var g = readMPInt(der, 'g');
70599
70600 der.readSequence(asn1.Ber.OctetString);
70601 var x = readMPInt(der, 'x');
70602
70603 /* The pkcs#8 format does not include the public key */
70604 var y = utils.calculateDSAPublic(g, p, x);
70605
70606 var key = {
70607 type: 'dsa',
70608 parts: [
70609 { name: 'p', data: p },
70610 { name: 'q', data: q },
70611 { name: 'g', data: g },
70612 { name: 'y', data: y },
70613 { name: 'x', data: x }
70614 ]
70615 };
70616
70617 return (new PrivateKey(key));
70618}
70619
70620function readECDSACurve(der) {
70621 var curveName, curveNames;
70622 var j, c, cd;
70623
70624 if (der.peek() === asn1.Ber.OID) {
70625 var oid = der.readOID();
70626
70627 curveNames = Object.keys(algs.curves);
70628 for (j = 0; j < curveNames.length; ++j) {
70629 c = curveNames[j];
70630 cd = algs.curves[c];
70631 if (cd.pkcs8oid === oid) {
70632 curveName = c;
70633 break;
70634 }
70635 }
70636
70637 } else {
70638 // ECParameters sequence
70639 der.readSequence();
70640 var version = der.readString(asn1.Ber.Integer, true);
70641 assert.strictEqual(version[0], 1, 'ECDSA key not version 1');
70642
70643 var curve = {};
70644
70645 // FieldID sequence
70646 der.readSequence();
70647 var fieldTypeOid = der.readOID();
70648 assert.strictEqual(fieldTypeOid, '1.2.840.10045.1.1',
70649 'ECDSA key is not from a prime-field');
70650 var p = curve.p = utils.mpNormalize(
70651 der.readString(asn1.Ber.Integer, true));
70652 /*
70653 * p always starts with a 1 bit, so count the zeros to get its
70654 * real size.
70655 */
70656 curve.size = p.length * 8 - utils.countZeros(p);
70657
70658 // Curve sequence
70659 der.readSequence();
70660 curve.a = utils.mpNormalize(
70661 der.readString(asn1.Ber.OctetString, true));
70662 curve.b = utils.mpNormalize(
70663 der.readString(asn1.Ber.OctetString, true));
70664 if (der.peek() === asn1.Ber.BitString)
70665 curve.s = der.readString(asn1.Ber.BitString, true);
70666
70667 // Combined Gx and Gy
70668 curve.G = der.readString(asn1.Ber.OctetString, true);
70669 assert.strictEqual(curve.G[0], 0x4,
70670 'uncompressed G is required');
70671
70672 curve.n = utils.mpNormalize(
70673 der.readString(asn1.Ber.Integer, true));
70674 curve.h = utils.mpNormalize(
70675 der.readString(asn1.Ber.Integer, true));
70676 assert.strictEqual(curve.h[0], 0x1, 'a cofactor=1 curve is ' +
70677 'required');
70678
70679 curveNames = Object.keys(algs.curves);
70680 var ks = Object.keys(curve);
70681 for (j = 0; j < curveNames.length; ++j) {
70682 c = curveNames[j];
70683 cd = algs.curves[c];
70684 var equal = true;
70685 for (var i = 0; i < ks.length; ++i) {
70686 var k = ks[i];
70687 if (cd[k] === undefined)
70688 continue;
70689 if (typeof (cd[k]) === 'object' &&
70690 cd[k].equals !== undefined) {
70691 if (!cd[k].equals(curve[k])) {
70692 equal = false;
70693 break;
70694 }
70695 } else if (Buffer.isBuffer(cd[k])) {
70696 if (cd[k].toString('binary')
70697 !== curve[k].toString('binary')) {
70698 equal = false;
70699 break;
70700 }
70701 } else {
70702 if (cd[k] !== curve[k]) {
70703 equal = false;
70704 break;
70705 }
70706 }
70707 }
70708 if (equal) {
70709 curveName = c;
70710 break;
70711 }
70712 }
70713 }
70714 return (curveName);
70715}
70716
70717function readPkcs8ECDSAPrivate(der) {
70718 var curveName = readECDSACurve(der);
70719 assert.string(curveName, 'a known elliptic curve');
70720
70721 der.readSequence(asn1.Ber.OctetString);
70722 der.readSequence();
70723
70724 var version = readMPInt(der, 'version');
70725 assert.equal(version[0], 1, 'unknown version of ECDSA key');
70726
70727 var d = der.readString(asn1.Ber.OctetString, true);
70728 var Q;
70729
70730 if (der.peek() == 0xa0) {
70731 der.readSequence(0xa0);
70732 der._offset += der.length;
70733 }
70734 if (der.peek() == 0xa1) {
70735 der.readSequence(0xa1);
70736 Q = der.readString(asn1.Ber.BitString, true);
70737 Q = utils.ecNormalize(Q);
70738 }
70739
70740 if (Q === undefined) {
70741 var pub = utils.publicFromPrivateECDSA(curveName, d);
70742 Q = pub.part.Q.data;
70743 }
70744
70745 var key = {
70746 type: 'ecdsa',
70747 parts: [
70748 { name: 'curve', data: Buffer.from(curveName) },
70749 { name: 'Q', data: Q },
70750 { name: 'd', data: d }
70751 ]
70752 };
70753
70754 return (new PrivateKey(key));
70755}
70756
70757function readPkcs8ECDSAPublic(der) {
70758 var curveName = readECDSACurve(der);
70759 assert.string(curveName, 'a known elliptic curve');
70760
70761 var Q = der.readString(asn1.Ber.BitString, true);
70762 Q = utils.ecNormalize(Q);
70763
70764 var key = {
70765 type: 'ecdsa',
70766 parts: [
70767 { name: 'curve', data: Buffer.from(curveName) },
70768 { name: 'Q', data: Q }
70769 ]
70770 };
70771
70772 return (new Key(key));
70773}
70774
70775function readPkcs8EdDSAPublic(der) {
70776 if (der.peek() === 0x00)
70777 der.readByte();
70778
70779 var A = utils.readBitString(der);
70780
70781 var key = {
70782 type: 'ed25519',
70783 parts: [
70784 { name: 'A', data: utils.zeroPadToLength(A, 32) }
70785 ]
70786 };
70787
70788 return (new Key(key));
70789}
70790
70791function readPkcs8X25519Public(der) {
70792 var A = utils.readBitString(der);
70793
70794 var key = {
70795 type: 'curve25519',
70796 parts: [
70797 { name: 'A', data: utils.zeroPadToLength(A, 32) }
70798 ]
70799 };
70800
70801 return (new Key(key));
70802}
70803
70804function readPkcs8EdDSAPrivate(der) {
70805 if (der.peek() === 0x00)
70806 der.readByte();
70807
70808 der.readSequence(asn1.Ber.OctetString);
70809 var k = der.readString(asn1.Ber.OctetString, true);
70810 k = utils.zeroPadToLength(k, 32);
70811
70812 var A;
70813 if (der.peek() === asn1.Ber.BitString) {
70814 A = utils.readBitString(der);
70815 A = utils.zeroPadToLength(A, 32);
70816 } else {
70817 A = utils.calculateED25519Public(k);
70818 }
70819
70820 var key = {
70821 type: 'ed25519',
70822 parts: [
70823 { name: 'A', data: utils.zeroPadToLength(A, 32) },
70824 { name: 'k', data: utils.zeroPadToLength(k, 32) }
70825 ]
70826 };
70827
70828 return (new PrivateKey(key));
70829}
70830
70831function readPkcs8X25519Private(der) {
70832 if (der.peek() === 0x00)
70833 der.readByte();
70834
70835 der.readSequence(asn1.Ber.OctetString);
70836 var k = der.readString(asn1.Ber.OctetString, true);
70837 k = utils.zeroPadToLength(k, 32);
70838
70839 var A = utils.calculateX25519Public(k);
70840
70841 var key = {
70842 type: 'curve25519',
70843 parts: [
70844 { name: 'A', data: utils.zeroPadToLength(A, 32) },
70845 { name: 'k', data: utils.zeroPadToLength(k, 32) }
70846 ]
70847 };
70848
70849 return (new PrivateKey(key));
70850}
70851
70852function pkcs8ToBuffer(key) {
70853 var der = new asn1.BerWriter();
70854 writePkcs8(der, key);
70855 return (der.buffer);
70856}
70857
70858function writePkcs8(der, key) {
70859 der.startSequence();
70860
70861 if (PrivateKey.isPrivateKey(key)) {
70862 var sillyInt = Buffer.from([0]);
70863 der.writeBuffer(sillyInt, asn1.Ber.Integer);
70864 }
70865
70866 der.startSequence();
70867 switch (key.type) {
70868 case 'rsa':
70869 der.writeOID('1.2.840.113549.1.1.1');
70870 if (PrivateKey.isPrivateKey(key))
70871 writePkcs8RSAPrivate(key, der);
70872 else
70873 writePkcs8RSAPublic(key, der);
70874 break;
70875 case 'dsa':
70876 der.writeOID('1.2.840.10040.4.1');
70877 if (PrivateKey.isPrivateKey(key))
70878 writePkcs8DSAPrivate(key, der);
70879 else
70880 writePkcs8DSAPublic(key, der);
70881 break;
70882 case 'ecdsa':
70883 der.writeOID('1.2.840.10045.2.1');
70884 if (PrivateKey.isPrivateKey(key))
70885 writePkcs8ECDSAPrivate(key, der);
70886 else
70887 writePkcs8ECDSAPublic(key, der);
70888 break;
70889 case 'ed25519':
70890 der.writeOID('1.3.101.112');
70891 if (PrivateKey.isPrivateKey(key))
70892 throw (new Error('Ed25519 private keys in pkcs8 ' +
70893 'format are not supported'));
70894 writePkcs8EdDSAPublic(key, der);
70895 break;
70896 default:
70897 throw (new Error('Unsupported key type: ' + key.type));
70898 }
70899
70900 der.endSequence();
70901}
70902
70903function writePkcs8RSAPrivate(key, der) {
70904 der.writeNull();
70905 der.endSequence();
70906
70907 der.startSequence(asn1.Ber.OctetString);
70908 der.startSequence();
70909
70910 var version = Buffer.from([0]);
70911 der.writeBuffer(version, asn1.Ber.Integer);
70912
70913 der.writeBuffer(key.part.n.data, asn1.Ber.Integer);
70914 der.writeBuffer(key.part.e.data, asn1.Ber.Integer);
70915 der.writeBuffer(key.part.d.data, asn1.Ber.Integer);
70916 der.writeBuffer(key.part.p.data, asn1.Ber.Integer);
70917 der.writeBuffer(key.part.q.data, asn1.Ber.Integer);
70918 if (!key.part.dmodp || !key.part.dmodq)
70919 utils.addRSAMissing(key);
70920 der.writeBuffer(key.part.dmodp.data, asn1.Ber.Integer);
70921 der.writeBuffer(key.part.dmodq.data, asn1.Ber.Integer);
70922 der.writeBuffer(key.part.iqmp.data, asn1.Ber.Integer);
70923
70924 der.endSequence();
70925 der.endSequence();
70926}
70927
70928function writePkcs8RSAPublic(key, der) {
70929 der.writeNull();
70930 der.endSequence();
70931
70932 der.startSequence(asn1.Ber.BitString);
70933 der.writeByte(0x00);
70934
70935 der.startSequence();
70936 der.writeBuffer(key.part.n.data, asn1.Ber.Integer);
70937 der.writeBuffer(key.part.e.data, asn1.Ber.Integer);
70938 der.endSequence();
70939
70940 der.endSequence();
70941}
70942
70943function writePkcs8DSAPrivate(key, der) {
70944 der.startSequence();
70945 der.writeBuffer(key.part.p.data, asn1.Ber.Integer);
70946 der.writeBuffer(key.part.q.data, asn1.Ber.Integer);
70947 der.writeBuffer(key.part.g.data, asn1.Ber.Integer);
70948 der.endSequence();
70949
70950 der.endSequence();
70951
70952 der.startSequence(asn1.Ber.OctetString);
70953 der.writeBuffer(key.part.x.data, asn1.Ber.Integer);
70954 der.endSequence();
70955}
70956
70957function writePkcs8DSAPublic(key, der) {
70958 der.startSequence();
70959 der.writeBuffer(key.part.p.data, asn1.Ber.Integer);
70960 der.writeBuffer(key.part.q.data, asn1.Ber.Integer);
70961 der.writeBuffer(key.part.g.data, asn1.Ber.Integer);
70962 der.endSequence();
70963 der.endSequence();
70964
70965 der.startSequence(asn1.Ber.BitString);
70966 der.writeByte(0x00);
70967 der.writeBuffer(key.part.y.data, asn1.Ber.Integer);
70968 der.endSequence();
70969}
70970
70971function writeECDSACurve(key, der) {
70972 var curve = algs.curves[key.curve];
70973 if (curve.pkcs8oid) {
70974 /* This one has a name in pkcs#8, so just write the oid */
70975 der.writeOID(curve.pkcs8oid);
70976
70977 } else {
70978 // ECParameters sequence
70979 der.startSequence();
70980
70981 var version = Buffer.from([1]);
70982 der.writeBuffer(version, asn1.Ber.Integer);
70983
70984 // FieldID sequence
70985 der.startSequence();
70986 der.writeOID('1.2.840.10045.1.1'); // prime-field
70987 der.writeBuffer(curve.p, asn1.Ber.Integer);
70988 der.endSequence();
70989
70990 // Curve sequence
70991 der.startSequence();
70992 var a = curve.p;
70993 if (a[0] === 0x0)
70994 a = a.slice(1);
70995 der.writeBuffer(a, asn1.Ber.OctetString);
70996 der.writeBuffer(curve.b, asn1.Ber.OctetString);
70997 der.writeBuffer(curve.s, asn1.Ber.BitString);
70998 der.endSequence();
70999
71000 der.writeBuffer(curve.G, asn1.Ber.OctetString);
71001 der.writeBuffer(curve.n, asn1.Ber.Integer);
71002 var h = curve.h;
71003 if (!h) {
71004 h = Buffer.from([1]);
71005 }
71006 der.writeBuffer(h, asn1.Ber.Integer);
71007
71008 // ECParameters
71009 der.endSequence();
71010 }
71011}
71012
71013function writePkcs8ECDSAPublic(key, der) {
71014 writeECDSACurve(key, der);
71015 der.endSequence();
71016
71017 var Q = utils.ecNormalize(key.part.Q.data, true);
71018 der.writeBuffer(Q, asn1.Ber.BitString);
71019}
71020
71021function writePkcs8ECDSAPrivate(key, der) {
71022 writeECDSACurve(key, der);
71023 der.endSequence();
71024
71025 der.startSequence(asn1.Ber.OctetString);
71026 der.startSequence();
71027
71028 var version = Buffer.from([1]);
71029 der.writeBuffer(version, asn1.Ber.Integer);
71030
71031 der.writeBuffer(key.part.d.data, asn1.Ber.OctetString);
71032
71033 der.startSequence(0xa1);
71034 var Q = utils.ecNormalize(key.part.Q.data, true);
71035 der.writeBuffer(Q, asn1.Ber.BitString);
71036 der.endSequence();
71037
71038 der.endSequence();
71039 der.endSequence();
71040}
71041
71042function writePkcs8EdDSAPublic(key, der) {
71043 der.endSequence();
71044
71045 utils.writeBitString(der, key.part.A.data);
71046}
71047
71048function writePkcs8EdDSAPrivate(key, der) {
71049 der.endSequence();
71050
71051 var k = utils.mpNormalize(key.part.k.data, true);
71052 der.startSequence(asn1.Ber.OctetString);
71053 der.writeBuffer(k, asn1.Ber.OctetString);
71054 der.endSequence();
71055}
71056
71057},{"../algs":335,"../key":355,"../private-key":356,"../utils":359,"./pem":344,"asn1":66,"assert-plus":67,"safer-buffer":326}],347:[function(require,module,exports){
71058// Copyright 2018 Joyent, Inc.
71059
71060module.exports = {
71061 read: read,
71062 write: write
71063};
71064
71065var assert = require('assert-plus');
71066var Buffer = require('safer-buffer').Buffer;
71067var rfc4253 = require('./rfc4253');
71068var Key = require('../key');
71069
71070var errors = require('../errors');
71071
71072function read(buf, options) {
71073 var lines = buf.toString('ascii').split(/[\r\n]+/);
71074 var found = false;
71075 var parts;
71076 var si = 0;
71077 while (si < lines.length) {
71078 parts = splitHeader(lines[si++]);
71079 if (parts &&
71080 parts[0].toLowerCase() === 'putty-user-key-file-2') {
71081 found = true;
71082 break;
71083 }
71084 }
71085 if (!found) {
71086 throw (new Error('No PuTTY format first line found'));
71087 }
71088 var alg = parts[1];
71089
71090 parts = splitHeader(lines[si++]);
71091 assert.equal(parts[0].toLowerCase(), 'encryption');
71092
71093 parts = splitHeader(lines[si++]);
71094 assert.equal(parts[0].toLowerCase(), 'comment');
71095 var comment = parts[1];
71096
71097 parts = splitHeader(lines[si++]);
71098 assert.equal(parts[0].toLowerCase(), 'public-lines');
71099 var publicLines = parseInt(parts[1], 10);
71100 if (!isFinite(publicLines) || publicLines < 0 ||
71101 publicLines > lines.length) {
71102 throw (new Error('Invalid public-lines count'));
71103 }
71104
71105 var publicBuf = Buffer.from(
71106 lines.slice(si, si + publicLines).join(''), 'base64');
71107 var keyType = rfc4253.algToKeyType(alg);
71108 var key = rfc4253.read(publicBuf);
71109 if (key.type !== keyType) {
71110 throw (new Error('Outer key algorithm mismatch'));
71111 }
71112 key.comment = comment;
71113 return (key);
71114}
71115
71116function splitHeader(line) {
71117 var idx = line.indexOf(':');
71118 if (idx === -1)
71119 return (null);
71120 var header = line.slice(0, idx);
71121 ++idx;
71122 while (line[idx] === ' ')
71123 ++idx;
71124 var rest = line.slice(idx);
71125 return ([header, rest]);
71126}
71127
71128function write(key, options) {
71129 assert.object(key);
71130 if (!Key.isKey(key))
71131 throw (new Error('Must be a public key'));
71132
71133 var alg = rfc4253.keyTypeToAlg(key);
71134 var buf = rfc4253.write(key);
71135 var comment = key.comment || '';
71136
71137 var b64 = buf.toString('base64');
71138 var lines = wrap(b64, 64);
71139
71140 lines.unshift('Public-Lines: ' + lines.length);
71141 lines.unshift('Comment: ' + comment);
71142 lines.unshift('Encryption: none');
71143 lines.unshift('PuTTY-User-Key-File-2: ' + alg);
71144
71145 return (Buffer.from(lines.join('\n') + '\n'));
71146}
71147
71148function wrap(txt, len) {
71149 var lines = [];
71150 var pos = 0;
71151 while (pos < txt.length) {
71152 lines.push(txt.slice(pos, pos + 64));
71153 pos += 64;
71154 }
71155 return (lines);
71156}
71157
71158},{"../errors":339,"../key":355,"./rfc4253":348,"assert-plus":67,"safer-buffer":326}],348:[function(require,module,exports){
71159// Copyright 2015 Joyent, Inc.
71160
71161module.exports = {
71162 read: read.bind(undefined, false, undefined),
71163 readType: read.bind(undefined, false),
71164 write: write,
71165 /* semi-private api, used by sshpk-agent */
71166 readPartial: read.bind(undefined, true),
71167
71168 /* shared with ssh format */
71169 readInternal: read,
71170 keyTypeToAlg: keyTypeToAlg,
71171 algToKeyType: algToKeyType
71172};
71173
71174var assert = require('assert-plus');
71175var Buffer = require('safer-buffer').Buffer;
71176var algs = require('../algs');
71177var utils = require('../utils');
71178var Key = require('../key');
71179var PrivateKey = require('../private-key');
71180var SSHBuffer = require('../ssh-buffer');
71181
71182function algToKeyType(alg) {
71183 assert.string(alg);
71184 if (alg === 'ssh-dss')
71185 return ('dsa');
71186 else if (alg === 'ssh-rsa')
71187 return ('rsa');
71188 else if (alg === 'ssh-ed25519')
71189 return ('ed25519');
71190 else if (alg === 'ssh-curve25519')
71191 return ('curve25519');
71192 else if (alg.match(/^ecdsa-sha2-/))
71193 return ('ecdsa');
71194 else
71195 throw (new Error('Unknown algorithm ' + alg));
71196}
71197
71198function keyTypeToAlg(key) {
71199 assert.object(key);
71200 if (key.type === 'dsa')
71201 return ('ssh-dss');
71202 else if (key.type === 'rsa')
71203 return ('ssh-rsa');
71204 else if (key.type === 'ed25519')
71205 return ('ssh-ed25519');
71206 else if (key.type === 'curve25519')
71207 return ('ssh-curve25519');
71208 else if (key.type === 'ecdsa')
71209 return ('ecdsa-sha2-' + key.part.curve.data.toString());
71210 else
71211 throw (new Error('Unknown key type ' + key.type));
71212}
71213
71214function read(partial, type, buf, options) {
71215 if (typeof (buf) === 'string')
71216 buf = Buffer.from(buf);
71217 assert.buffer(buf, 'buf');
71218
71219 var key = {};
71220
71221 var parts = key.parts = [];
71222 var sshbuf = new SSHBuffer({buffer: buf});
71223
71224 var alg = sshbuf.readString();
71225 assert.ok(!sshbuf.atEnd(), 'key must have at least one part');
71226
71227 key.type = algToKeyType(alg);
71228
71229 var partCount = algs.info[key.type].parts.length;
71230 if (type && type === 'private')
71231 partCount = algs.privInfo[key.type].parts.length;
71232
71233 while (!sshbuf.atEnd() && parts.length < partCount)
71234 parts.push(sshbuf.readPart());
71235 while (!partial && !sshbuf.atEnd())
71236 parts.push(sshbuf.readPart());
71237
71238 assert.ok(parts.length >= 1,
71239 'key must have at least one part');
71240 assert.ok(partial || sshbuf.atEnd(),
71241 'leftover bytes at end of key');
71242
71243 var Constructor = Key;
71244 var algInfo = algs.info[key.type];
71245 if (type === 'private' || algInfo.parts.length !== parts.length) {
71246 algInfo = algs.privInfo[key.type];
71247 Constructor = PrivateKey;
71248 }
71249 assert.strictEqual(algInfo.parts.length, parts.length);
71250
71251 if (key.type === 'ecdsa') {
71252 var res = /^ecdsa-sha2-(.+)$/.exec(alg);
71253 assert.ok(res !== null);
71254 assert.strictEqual(res[1], parts[0].data.toString());
71255 }
71256
71257 var normalized = true;
71258 for (var i = 0; i < algInfo.parts.length; ++i) {
71259 var p = parts[i];
71260 p.name = algInfo.parts[i];
71261 /*
71262 * OpenSSH stores ed25519 "private" keys as seed + public key
71263 * concat'd together (k followed by A). We want to keep them
71264 * separate for other formats that don't do this.
71265 */
71266 if (key.type === 'ed25519' && p.name === 'k')
71267 p.data = p.data.slice(0, 32);
71268
71269 if (p.name !== 'curve' && algInfo.normalize !== false) {
71270 var nd;
71271 if (key.type === 'ed25519') {
71272 nd = utils.zeroPadToLength(p.data, 32);
71273 } else {
71274 nd = utils.mpNormalize(p.data);
71275 }
71276 if (nd.toString('binary') !==
71277 p.data.toString('binary')) {
71278 p.data = nd;
71279 normalized = false;
71280 }
71281 }
71282 }
71283
71284 if (normalized)
71285 key._rfc4253Cache = sshbuf.toBuffer();
71286
71287 if (partial && typeof (partial) === 'object') {
71288 partial.remainder = sshbuf.remainder();
71289 partial.consumed = sshbuf._offset;
71290 }
71291
71292 return (new Constructor(key));
71293}
71294
71295function write(key, options) {
71296 assert.object(key);
71297
71298 var alg = keyTypeToAlg(key);
71299 var i;
71300
71301 var algInfo = algs.info[key.type];
71302 if (PrivateKey.isPrivateKey(key))
71303 algInfo = algs.privInfo[key.type];
71304 var parts = algInfo.parts;
71305
71306 var buf = new SSHBuffer({});
71307
71308 buf.writeString(alg);
71309
71310 for (i = 0; i < parts.length; ++i) {
71311 var data = key.part[parts[i]].data;
71312 if (algInfo.normalize !== false) {
71313 if (key.type === 'ed25519')
71314 data = utils.zeroPadToLength(data, 32);
71315 else
71316 data = utils.mpNormalize(data);
71317 }
71318 if (key.type === 'ed25519' && parts[i] === 'k')
71319 data = Buffer.concat([data, key.part.A.data]);
71320 buf.writeBuffer(data);
71321 }
71322
71323 return (buf.toBuffer());
71324}
71325
71326},{"../algs":335,"../key":355,"../private-key":356,"../ssh-buffer":358,"../utils":359,"assert-plus":67,"safer-buffer":326}],349:[function(require,module,exports){
71327// Copyright 2015 Joyent, Inc.
71328
71329module.exports = {
71330 read: read,
71331 readSSHPrivate: readSSHPrivate,
71332 write: write
71333};
71334
71335var assert = require('assert-plus');
71336var asn1 = require('asn1');
71337var Buffer = require('safer-buffer').Buffer;
71338var algs = require('../algs');
71339var utils = require('../utils');
71340var crypto = require('crypto');
71341
71342var Key = require('../key');
71343var PrivateKey = require('../private-key');
71344var pem = require('./pem');
71345var rfc4253 = require('./rfc4253');
71346var SSHBuffer = require('../ssh-buffer');
71347var errors = require('../errors');
71348
71349var bcrypt;
71350
71351function read(buf, options) {
71352 return (pem.read(buf, options));
71353}
71354
71355var MAGIC = 'openssh-key-v1';
71356
71357function readSSHPrivate(type, buf, options) {
71358 buf = new SSHBuffer({buffer: buf});
71359
71360 var magic = buf.readCString();
71361 assert.strictEqual(magic, MAGIC, 'bad magic string');
71362
71363 var cipher = buf.readString();
71364 var kdf = buf.readString();
71365 var kdfOpts = buf.readBuffer();
71366
71367 var nkeys = buf.readInt();
71368 if (nkeys !== 1) {
71369 throw (new Error('OpenSSH-format key file contains ' +
71370 'multiple keys: this is unsupported.'));
71371 }
71372
71373 var pubKey = buf.readBuffer();
71374
71375 if (type === 'public') {
71376 assert.ok(buf.atEnd(), 'excess bytes left after key');
71377 return (rfc4253.read(pubKey));
71378 }
71379
71380 var privKeyBlob = buf.readBuffer();
71381 assert.ok(buf.atEnd(), 'excess bytes left after key');
71382
71383 var kdfOptsBuf = new SSHBuffer({ buffer: kdfOpts });
71384 switch (kdf) {
71385 case 'none':
71386 if (cipher !== 'none') {
71387 throw (new Error('OpenSSH-format key uses KDF "none" ' +
71388 'but specifies a cipher other than "none"'));
71389 }
71390 break;
71391 case 'bcrypt':
71392 var salt = kdfOptsBuf.readBuffer();
71393 var rounds = kdfOptsBuf.readInt();
71394 var cinf = utils.opensshCipherInfo(cipher);
71395 if (bcrypt === undefined) {
71396 bcrypt = require('bcrypt-pbkdf');
71397 }
71398
71399 if (typeof (options.passphrase) === 'string') {
71400 options.passphrase = Buffer.from(options.passphrase,
71401 'utf-8');
71402 }
71403 if (!Buffer.isBuffer(options.passphrase)) {
71404 throw (new errors.KeyEncryptedError(
71405 options.filename, 'OpenSSH'));
71406 }
71407
71408 var pass = new Uint8Array(options.passphrase);
71409 var salti = new Uint8Array(salt);
71410 /* Use the pbkdf to derive both the key and the IV. */
71411 var out = new Uint8Array(cinf.keySize + cinf.blockSize);
71412 var res = bcrypt.pbkdf(pass, pass.length, salti, salti.length,
71413 out, out.length, rounds);
71414 if (res !== 0) {
71415 throw (new Error('bcrypt_pbkdf function returned ' +
71416 'failure, parameters invalid'));
71417 }
71418 out = Buffer.from(out);
71419 var ckey = out.slice(0, cinf.keySize);
71420 var iv = out.slice(cinf.keySize, cinf.keySize + cinf.blockSize);
71421 var cipherStream = crypto.createDecipheriv(cinf.opensslName,
71422 ckey, iv);
71423 cipherStream.setAutoPadding(false);
71424 var chunk, chunks = [];
71425 cipherStream.once('error', function (e) {
71426 if (e.toString().indexOf('bad decrypt') !== -1) {
71427 throw (new Error('Incorrect passphrase ' +
71428 'supplied, could not decrypt key'));
71429 }
71430 throw (e);
71431 });
71432 cipherStream.write(privKeyBlob);
71433 cipherStream.end();
71434 while ((chunk = cipherStream.read()) !== null)
71435 chunks.push(chunk);
71436 privKeyBlob = Buffer.concat(chunks);
71437 break;
71438 default:
71439 throw (new Error(
71440 'OpenSSH-format key uses unknown KDF "' + kdf + '"'));
71441 }
71442
71443 buf = new SSHBuffer({buffer: privKeyBlob});
71444
71445 var checkInt1 = buf.readInt();
71446 var checkInt2 = buf.readInt();
71447 if (checkInt1 !== checkInt2) {
71448 throw (new Error('Incorrect passphrase supplied, could not ' +
71449 'decrypt key'));
71450 }
71451
71452 var ret = {};
71453 var key = rfc4253.readInternal(ret, 'private', buf.remainder());
71454
71455 buf.skip(ret.consumed);
71456
71457 var comment = buf.readString();
71458 key.comment = comment;
71459
71460 return (key);
71461}
71462
71463function write(key, options) {
71464 var pubKey;
71465 if (PrivateKey.isPrivateKey(key))
71466 pubKey = key.toPublic();
71467 else
71468 pubKey = key;
71469
71470 var cipher = 'none';
71471 var kdf = 'none';
71472 var kdfopts = Buffer.alloc(0);
71473 var cinf = { blockSize: 8 };
71474 var passphrase;
71475 if (options !== undefined) {
71476 passphrase = options.passphrase;
71477 if (typeof (passphrase) === 'string')
71478 passphrase = Buffer.from(passphrase, 'utf-8');
71479 if (passphrase !== undefined) {
71480 assert.buffer(passphrase, 'options.passphrase');
71481 assert.optionalString(options.cipher, 'options.cipher');
71482 cipher = options.cipher;
71483 if (cipher === undefined)
71484 cipher = 'aes128-ctr';
71485 cinf = utils.opensshCipherInfo(cipher);
71486 kdf = 'bcrypt';
71487 }
71488 }
71489
71490 var privBuf;
71491 if (PrivateKey.isPrivateKey(key)) {
71492 privBuf = new SSHBuffer({});
71493 var checkInt = crypto.randomBytes(4).readUInt32BE(0);
71494 privBuf.writeInt(checkInt);
71495 privBuf.writeInt(checkInt);
71496 privBuf.write(key.toBuffer('rfc4253'));
71497 privBuf.writeString(key.comment || '');
71498
71499 var n = 1;
71500 while (privBuf._offset % cinf.blockSize !== 0)
71501 privBuf.writeChar(n++);
71502 privBuf = privBuf.toBuffer();
71503 }
71504
71505 switch (kdf) {
71506 case 'none':
71507 break;
71508 case 'bcrypt':
71509 var salt = crypto.randomBytes(16);
71510 var rounds = 16;
71511 var kdfssh = new SSHBuffer({});
71512 kdfssh.writeBuffer(salt);
71513 kdfssh.writeInt(rounds);
71514 kdfopts = kdfssh.toBuffer();
71515
71516 if (bcrypt === undefined) {
71517 bcrypt = require('bcrypt-pbkdf');
71518 }
71519 var pass = new Uint8Array(passphrase);
71520 var salti = new Uint8Array(salt);
71521 /* Use the pbkdf to derive both the key and the IV. */
71522 var out = new Uint8Array(cinf.keySize + cinf.blockSize);
71523 var res = bcrypt.pbkdf(pass, pass.length, salti, salti.length,
71524 out, out.length, rounds);
71525 if (res !== 0) {
71526 throw (new Error('bcrypt_pbkdf function returned ' +
71527 'failure, parameters invalid'));
71528 }
71529 out = Buffer.from(out);
71530 var ckey = out.slice(0, cinf.keySize);
71531 var iv = out.slice(cinf.keySize, cinf.keySize + cinf.blockSize);
71532
71533 var cipherStream = crypto.createCipheriv(cinf.opensslName,
71534 ckey, iv);
71535 cipherStream.setAutoPadding(false);
71536 var chunk, chunks = [];
71537 cipherStream.once('error', function (e) {
71538 throw (e);
71539 });
71540 cipherStream.write(privBuf);
71541 cipherStream.end();
71542 while ((chunk = cipherStream.read()) !== null)
71543 chunks.push(chunk);
71544 privBuf = Buffer.concat(chunks);
71545 break;
71546 default:
71547 throw (new Error('Unsupported kdf ' + kdf));
71548 }
71549
71550 var buf = new SSHBuffer({});
71551
71552 buf.writeCString(MAGIC);
71553 buf.writeString(cipher); /* cipher */
71554 buf.writeString(kdf); /* kdf */
71555 buf.writeBuffer(kdfopts); /* kdfoptions */
71556
71557 buf.writeInt(1); /* nkeys */
71558 buf.writeBuffer(pubKey.toBuffer('rfc4253'));
71559
71560 if (privBuf)
71561 buf.writeBuffer(privBuf);
71562
71563 buf = buf.toBuffer();
71564
71565 var header;
71566 if (PrivateKey.isPrivateKey(key))
71567 header = 'OPENSSH PRIVATE KEY';
71568 else
71569 header = 'OPENSSH PUBLIC KEY';
71570
71571 var tmp = buf.toString('base64');
71572 var len = tmp.length + (tmp.length / 70) +
71573 18 + 16 + header.length*2 + 10;
71574 buf = Buffer.alloc(len);
71575 var o = 0;
71576 o += buf.write('-----BEGIN ' + header + '-----\n', o);
71577 for (var i = 0; i < tmp.length; ) {
71578 var limit = i + 70;
71579 if (limit > tmp.length)
71580 limit = tmp.length;
71581 o += buf.write(tmp.slice(i, limit), o);
71582 buf[o++] = 10;
71583 i = limit;
71584 }
71585 o += buf.write('-----END ' + header + '-----\n', o);
71586
71587 return (buf.slice(0, o));
71588}
71589
71590},{"../algs":335,"../errors":339,"../key":355,"../private-key":356,"../ssh-buffer":358,"../utils":359,"./pem":344,"./rfc4253":348,"asn1":66,"assert-plus":67,"bcrypt-pbkdf":76,"crypto":126,"safer-buffer":326}],350:[function(require,module,exports){
71591// Copyright 2015 Joyent, Inc.
71592
71593module.exports = {
71594 read: read,
71595 write: write
71596};
71597
71598var assert = require('assert-plus');
71599var Buffer = require('safer-buffer').Buffer;
71600var rfc4253 = require('./rfc4253');
71601var utils = require('../utils');
71602var Key = require('../key');
71603var PrivateKey = require('../private-key');
71604
71605var sshpriv = require('./ssh-private');
71606
71607/*JSSTYLED*/
71608var SSHKEY_RE = /^([a-z0-9-]+)[ \t]+([a-zA-Z0-9+\/]+[=]*)([ \t]+([^ \t][^\n]*[\n]*)?)?$/;
71609/*JSSTYLED*/
71610var SSHKEY_RE2 = /^([a-z0-9-]+)[ \t\n]+([a-zA-Z0-9+\/][a-zA-Z0-9+\/ \t\n=]*)([^a-zA-Z0-9+\/ \t\n=].*)?$/;
71611
71612function read(buf, options) {
71613 if (typeof (buf) !== 'string') {
71614 assert.buffer(buf, 'buf');
71615 buf = buf.toString('ascii');
71616 }
71617
71618 var trimmed = buf.trim().replace(/[\\\r]/g, '');
71619 var m = trimmed.match(SSHKEY_RE);
71620 if (!m)
71621 m = trimmed.match(SSHKEY_RE2);
71622 assert.ok(m, 'key must match regex');
71623
71624 var type = rfc4253.algToKeyType(m[1]);
71625 var kbuf = Buffer.from(m[2], 'base64');
71626
71627 /*
71628 * This is a bit tricky. If we managed to parse the key and locate the
71629 * key comment with the regex, then do a non-partial read and assert
71630 * that we have consumed all bytes. If we couldn't locate the key
71631 * comment, though, there may be whitespace shenanigans going on that
71632 * have conjoined the comment to the rest of the key. We do a partial
71633 * read in this case to try to make the best out of a sorry situation.
71634 */
71635 var key;
71636 var ret = {};
71637 if (m[4]) {
71638 try {
71639 key = rfc4253.read(kbuf);
71640
71641 } catch (e) {
71642 m = trimmed.match(SSHKEY_RE2);
71643 assert.ok(m, 'key must match regex');
71644 kbuf = Buffer.from(m[2], 'base64');
71645 key = rfc4253.readInternal(ret, 'public', kbuf);
71646 }
71647 } else {
71648 key = rfc4253.readInternal(ret, 'public', kbuf);
71649 }
71650
71651 assert.strictEqual(type, key.type);
71652
71653 if (m[4] && m[4].length > 0) {
71654 key.comment = m[4];
71655
71656 } else if (ret.consumed) {
71657 /*
71658 * Now the magic: trying to recover the key comment when it's
71659 * gotten conjoined to the key or otherwise shenanigan'd.
71660 *
71661 * Work out how much base64 we used, then drop all non-base64
71662 * chars from the beginning up to this point in the the string.
71663 * Then offset in this and try to make up for missing = chars.
71664 */
71665 var data = m[2] + (m[3] ? m[3] : '');
71666 var realOffset = Math.ceil(ret.consumed / 3) * 4;
71667 data = data.slice(0, realOffset - 2). /*JSSTYLED*/
71668 replace(/[^a-zA-Z0-9+\/=]/g, '') +
71669 data.slice(realOffset - 2);
71670
71671 var padding = ret.consumed % 3;
71672 if (padding > 0 &&
71673 data.slice(realOffset - 1, realOffset) !== '=')
71674 realOffset--;
71675 while (data.slice(realOffset, realOffset + 1) === '=')
71676 realOffset++;
71677
71678 /* Finally, grab what we think is the comment & clean it up. */
71679 var trailer = data.slice(realOffset);
71680 trailer = trailer.replace(/[\r\n]/g, ' ').
71681 replace(/^\s+/, '');
71682 if (trailer.match(/^[a-zA-Z0-9]/))
71683 key.comment = trailer;
71684 }
71685
71686 return (key);
71687}
71688
71689function write(key, options) {
71690 assert.object(key);
71691 if (!Key.isKey(key))
71692 throw (new Error('Must be a public key'));
71693
71694 var parts = [];
71695 var alg = rfc4253.keyTypeToAlg(key);
71696 parts.push(alg);
71697
71698 var buf = rfc4253.write(key);
71699 parts.push(buf.toString('base64'));
71700
71701 if (key.comment)
71702 parts.push(key.comment);
71703
71704 return (Buffer.from(parts.join(' ')));
71705}
71706
71707},{"../key":355,"../private-key":356,"../utils":359,"./rfc4253":348,"./ssh-private":349,"assert-plus":67,"safer-buffer":326}],351:[function(require,module,exports){
71708// Copyright 2016 Joyent, Inc.
71709
71710var x509 = require('./x509');
71711
71712module.exports = {
71713 read: read,
71714 verify: x509.verify,
71715 sign: x509.sign,
71716 write: write
71717};
71718
71719var assert = require('assert-plus');
71720var asn1 = require('asn1');
71721var Buffer = require('safer-buffer').Buffer;
71722var algs = require('../algs');
71723var utils = require('../utils');
71724var Key = require('../key');
71725var PrivateKey = require('../private-key');
71726var pem = require('./pem');
71727var Identity = require('../identity');
71728var Signature = require('../signature');
71729var Certificate = require('../certificate');
71730
71731function read(buf, options) {
71732 if (typeof (buf) !== 'string') {
71733 assert.buffer(buf, 'buf');
71734 buf = buf.toString('ascii');
71735 }
71736
71737 var lines = buf.trim().split(/[\r\n]+/g);
71738
71739 var m;
71740 var si = -1;
71741 while (!m && si < lines.length) {
71742 m = lines[++si].match(/*JSSTYLED*/
71743 /[-]+[ ]*BEGIN CERTIFICATE[ ]*[-]+/);
71744 }
71745 assert.ok(m, 'invalid PEM header');
71746
71747 var m2;
71748 var ei = lines.length;
71749 while (!m2 && ei > 0) {
71750 m2 = lines[--ei].match(/*JSSTYLED*/
71751 /[-]+[ ]*END CERTIFICATE[ ]*[-]+/);
71752 }
71753 assert.ok(m2, 'invalid PEM footer');
71754
71755 lines = lines.slice(si, ei + 1);
71756
71757 var headers = {};
71758 while (true) {
71759 lines = lines.slice(1);
71760 m = lines[0].match(/*JSSTYLED*/
71761 /^([A-Za-z0-9-]+): (.+)$/);
71762 if (!m)
71763 break;
71764 headers[m[1].toLowerCase()] = m[2];
71765 }
71766
71767 /* Chop off the first and last lines */
71768 lines = lines.slice(0, -1).join('');
71769 buf = Buffer.from(lines, 'base64');
71770
71771 return (x509.read(buf, options));
71772}
71773
71774function write(cert, options) {
71775 var dbuf = x509.write(cert, options);
71776
71777 var header = 'CERTIFICATE';
71778 var tmp = dbuf.toString('base64');
71779 var len = tmp.length + (tmp.length / 64) +
71780 18 + 16 + header.length*2 + 10;
71781 var buf = Buffer.alloc(len);
71782 var o = 0;
71783 o += buf.write('-----BEGIN ' + header + '-----\n', o);
71784 for (var i = 0; i < tmp.length; ) {
71785 var limit = i + 64;
71786 if (limit > tmp.length)
71787 limit = tmp.length;
71788 o += buf.write(tmp.slice(i, limit), o);
71789 buf[o++] = 10;
71790 i = limit;
71791 }
71792 o += buf.write('-----END ' + header + '-----\n', o);
71793
71794 return (buf.slice(0, o));
71795}
71796
71797},{"../algs":335,"../certificate":336,"../identity":353,"../key":355,"../private-key":356,"../signature":357,"../utils":359,"./pem":344,"./x509":352,"asn1":66,"assert-plus":67,"safer-buffer":326}],352:[function(require,module,exports){
71798// Copyright 2017 Joyent, Inc.
71799
71800module.exports = {
71801 read: read,
71802 verify: verify,
71803 sign: sign,
71804 signAsync: signAsync,
71805 write: write
71806};
71807
71808var assert = require('assert-plus');
71809var asn1 = require('asn1');
71810var Buffer = require('safer-buffer').Buffer;
71811var algs = require('../algs');
71812var utils = require('../utils');
71813var Key = require('../key');
71814var PrivateKey = require('../private-key');
71815var pem = require('./pem');
71816var Identity = require('../identity');
71817var Signature = require('../signature');
71818var Certificate = require('../certificate');
71819var pkcs8 = require('./pkcs8');
71820
71821/*
71822 * This file is based on RFC5280 (X.509).
71823 */
71824
71825/* Helper to read in a single mpint */
71826function readMPInt(der, nm) {
71827 assert.strictEqual(der.peek(), asn1.Ber.Integer,
71828 nm + ' is not an Integer');
71829 return (utils.mpNormalize(der.readString(asn1.Ber.Integer, true)));
71830}
71831
71832function verify(cert, key) {
71833 var sig = cert.signatures.x509;
71834 assert.object(sig, 'x509 signature');
71835
71836 var algParts = sig.algo.split('-');
71837 if (algParts[0] !== key.type)
71838 return (false);
71839
71840 var blob = sig.cache;
71841 if (blob === undefined) {
71842 var der = new asn1.BerWriter();
71843 writeTBSCert(cert, der);
71844 blob = der.buffer;
71845 }
71846
71847 var verifier = key.createVerify(algParts[1]);
71848 verifier.write(blob);
71849 return (verifier.verify(sig.signature));
71850}
71851
71852function Local(i) {
71853 return (asn1.Ber.Context | asn1.Ber.Constructor | i);
71854}
71855
71856function Context(i) {
71857 return (asn1.Ber.Context | i);
71858}
71859
71860var SIGN_ALGS = {
71861 'rsa-md5': '1.2.840.113549.1.1.4',
71862 'rsa-sha1': '1.2.840.113549.1.1.5',
71863 'rsa-sha256': '1.2.840.113549.1.1.11',
71864 'rsa-sha384': '1.2.840.113549.1.1.12',
71865 'rsa-sha512': '1.2.840.113549.1.1.13',
71866 'dsa-sha1': '1.2.840.10040.4.3',
71867 'dsa-sha256': '2.16.840.1.101.3.4.3.2',
71868 'ecdsa-sha1': '1.2.840.10045.4.1',
71869 'ecdsa-sha256': '1.2.840.10045.4.3.2',
71870 'ecdsa-sha384': '1.2.840.10045.4.3.3',
71871 'ecdsa-sha512': '1.2.840.10045.4.3.4',
71872 'ed25519-sha512': '1.3.101.112'
71873};
71874Object.keys(SIGN_ALGS).forEach(function (k) {
71875 SIGN_ALGS[SIGN_ALGS[k]] = k;
71876});
71877SIGN_ALGS['1.3.14.3.2.3'] = 'rsa-md5';
71878SIGN_ALGS['1.3.14.3.2.29'] = 'rsa-sha1';
71879
71880var EXTS = {
71881 'issuerKeyId': '2.5.29.35',
71882 'altName': '2.5.29.17',
71883 'basicConstraints': '2.5.29.19',
71884 'keyUsage': '2.5.29.15',
71885 'extKeyUsage': '2.5.29.37'
71886};
71887
71888function read(buf, options) {
71889 if (typeof (buf) === 'string') {
71890 buf = Buffer.from(buf, 'binary');
71891 }
71892 assert.buffer(buf, 'buf');
71893
71894 var der = new asn1.BerReader(buf);
71895
71896 der.readSequence();
71897 if (Math.abs(der.length - der.remain) > 1) {
71898 throw (new Error('DER sequence does not contain whole byte ' +
71899 'stream'));
71900 }
71901
71902 var tbsStart = der.offset;
71903 der.readSequence();
71904 var sigOffset = der.offset + der.length;
71905 var tbsEnd = sigOffset;
71906
71907 if (der.peek() === Local(0)) {
71908 der.readSequence(Local(0));
71909 var version = der.readInt();
71910 assert.ok(version <= 3,
71911 'only x.509 versions up to v3 supported');
71912 }
71913
71914 var cert = {};
71915 cert.signatures = {};
71916 var sig = (cert.signatures.x509 = {});
71917 sig.extras = {};
71918
71919 cert.serial = readMPInt(der, 'serial');
71920
71921 der.readSequence();
71922 var after = der.offset + der.length;
71923 var certAlgOid = der.readOID();
71924 var certAlg = SIGN_ALGS[certAlgOid];
71925 if (certAlg === undefined)
71926 throw (new Error('unknown signature algorithm ' + certAlgOid));
71927
71928 der._offset = after;
71929 cert.issuer = Identity.parseAsn1(der);
71930
71931 der.readSequence();
71932 cert.validFrom = readDate(der);
71933 cert.validUntil = readDate(der);
71934
71935 cert.subjects = [Identity.parseAsn1(der)];
71936
71937 der.readSequence();
71938 after = der.offset + der.length;
71939 cert.subjectKey = pkcs8.readPkcs8(undefined, 'public', der);
71940 der._offset = after;
71941
71942 /* issuerUniqueID */
71943 if (der.peek() === Local(1)) {
71944 der.readSequence(Local(1));
71945 sig.extras.issuerUniqueID =
71946 buf.slice(der.offset, der.offset + der.length);
71947 der._offset += der.length;
71948 }
71949
71950 /* subjectUniqueID */
71951 if (der.peek() === Local(2)) {
71952 der.readSequence(Local(2));
71953 sig.extras.subjectUniqueID =
71954 buf.slice(der.offset, der.offset + der.length);
71955 der._offset += der.length;
71956 }
71957
71958 /* extensions */
71959 if (der.peek() === Local(3)) {
71960 der.readSequence(Local(3));
71961 var extEnd = der.offset + der.length;
71962 der.readSequence();
71963
71964 while (der.offset < extEnd)
71965 readExtension(cert, buf, der);
71966
71967 assert.strictEqual(der.offset, extEnd);
71968 }
71969
71970 assert.strictEqual(der.offset, sigOffset);
71971
71972 der.readSequence();
71973 after = der.offset + der.length;
71974 var sigAlgOid = der.readOID();
71975 var sigAlg = SIGN_ALGS[sigAlgOid];
71976 if (sigAlg === undefined)
71977 throw (new Error('unknown signature algorithm ' + sigAlgOid));
71978 der._offset = after;
71979
71980 var sigData = der.readString(asn1.Ber.BitString, true);
71981 if (sigData[0] === 0)
71982 sigData = sigData.slice(1);
71983 var algParts = sigAlg.split('-');
71984
71985 sig.signature = Signature.parse(sigData, algParts[0], 'asn1');
71986 sig.signature.hashAlgorithm = algParts[1];
71987 sig.algo = sigAlg;
71988 sig.cache = buf.slice(tbsStart, tbsEnd);
71989
71990 return (new Certificate(cert));
71991}
71992
71993function readDate(der) {
71994 if (der.peek() === asn1.Ber.UTCTime) {
71995 return (utcTimeToDate(der.readString(asn1.Ber.UTCTime)));
71996 } else if (der.peek() === asn1.Ber.GeneralizedTime) {
71997 return (gTimeToDate(der.readString(asn1.Ber.GeneralizedTime)));
71998 } else {
71999 throw (new Error('Unsupported date format'));
72000 }
72001}
72002
72003function writeDate(der, date) {
72004 if (date.getUTCFullYear() >= 2050 || date.getUTCFullYear() < 1950) {
72005 der.writeString(dateToGTime(date), asn1.Ber.GeneralizedTime);
72006 } else {
72007 der.writeString(dateToUTCTime(date), asn1.Ber.UTCTime);
72008 }
72009}
72010
72011/* RFC5280, section 4.2.1.6 (GeneralName type) */
72012var ALTNAME = {
72013 OtherName: Local(0),
72014 RFC822Name: Context(1),
72015 DNSName: Context(2),
72016 X400Address: Local(3),
72017 DirectoryName: Local(4),
72018 EDIPartyName: Local(5),
72019 URI: Context(6),
72020 IPAddress: Context(7),
72021 OID: Context(8)
72022};
72023
72024/* RFC5280, section 4.2.1.12 (KeyPurposeId) */
72025var EXTPURPOSE = {
72026 'serverAuth': '1.3.6.1.5.5.7.3.1',
72027 'clientAuth': '1.3.6.1.5.5.7.3.2',
72028 'codeSigning': '1.3.6.1.5.5.7.3.3',
72029
72030 /* See https://github.com/joyent/oid-docs/blob/master/root.md */
72031 'joyentDocker': '1.3.6.1.4.1.38678.1.4.1',
72032 'joyentCmon': '1.3.6.1.4.1.38678.1.4.2'
72033};
72034var EXTPURPOSE_REV = {};
72035Object.keys(EXTPURPOSE).forEach(function (k) {
72036 EXTPURPOSE_REV[EXTPURPOSE[k]] = k;
72037});
72038
72039var KEYUSEBITS = [
72040 'signature', 'identity', 'keyEncryption',
72041 'encryption', 'keyAgreement', 'ca', 'crl'
72042];
72043
72044function readExtension(cert, buf, der) {
72045 der.readSequence();
72046 var after = der.offset + der.length;
72047 var extId = der.readOID();
72048 var id;
72049 var sig = cert.signatures.x509;
72050 if (!sig.extras.exts)
72051 sig.extras.exts = [];
72052
72053 var critical;
72054 if (der.peek() === asn1.Ber.Boolean)
72055 critical = der.readBoolean();
72056
72057 switch (extId) {
72058 case (EXTS.basicConstraints):
72059 der.readSequence(asn1.Ber.OctetString);
72060 der.readSequence();
72061 var bcEnd = der.offset + der.length;
72062 var ca = false;
72063 if (der.peek() === asn1.Ber.Boolean)
72064 ca = der.readBoolean();
72065 if (cert.purposes === undefined)
72066 cert.purposes = [];
72067 if (ca === true)
72068 cert.purposes.push('ca');
72069 var bc = { oid: extId, critical: critical };
72070 if (der.offset < bcEnd && der.peek() === asn1.Ber.Integer)
72071 bc.pathLen = der.readInt();
72072 sig.extras.exts.push(bc);
72073 break;
72074 case (EXTS.extKeyUsage):
72075 der.readSequence(asn1.Ber.OctetString);
72076 der.readSequence();
72077 if (cert.purposes === undefined)
72078 cert.purposes = [];
72079 var ekEnd = der.offset + der.length;
72080 while (der.offset < ekEnd) {
72081 var oid = der.readOID();
72082 cert.purposes.push(EXTPURPOSE_REV[oid] || oid);
72083 }
72084 /*
72085 * This is a bit of a hack: in the case where we have a cert
72086 * that's only allowed to do serverAuth or clientAuth (and not
72087 * the other), we want to make sure all our Subjects are of
72088 * the right type. But we already parsed our Subjects and
72089 * decided if they were hosts or users earlier (since it appears
72090 * first in the cert).
72091 *
72092 * So we go through and mutate them into the right kind here if
72093 * it doesn't match. This might not be hugely beneficial, as it
72094 * seems that single-purpose certs are not often seen in the
72095 * wild.
72096 */
72097 if (cert.purposes.indexOf('serverAuth') !== -1 &&
72098 cert.purposes.indexOf('clientAuth') === -1) {
72099 cert.subjects.forEach(function (ide) {
72100 if (ide.type !== 'host') {
72101 ide.type = 'host';
72102 ide.hostname = ide.uid ||
72103 ide.email ||
72104 ide.components[0].value;
72105 }
72106 });
72107 } else if (cert.purposes.indexOf('clientAuth') !== -1 &&
72108 cert.purposes.indexOf('serverAuth') === -1) {
72109 cert.subjects.forEach(function (ide) {
72110 if (ide.type !== 'user') {
72111 ide.type = 'user';
72112 ide.uid = ide.hostname ||
72113 ide.email ||
72114 ide.components[0].value;
72115 }
72116 });
72117 }
72118 sig.extras.exts.push({ oid: extId, critical: critical });
72119 break;
72120 case (EXTS.keyUsage):
72121 der.readSequence(asn1.Ber.OctetString);
72122 var bits = der.readString(asn1.Ber.BitString, true);
72123 var setBits = readBitField(bits, KEYUSEBITS);
72124 setBits.forEach(function (bit) {
72125 if (cert.purposes === undefined)
72126 cert.purposes = [];
72127 if (cert.purposes.indexOf(bit) === -1)
72128 cert.purposes.push(bit);
72129 });
72130 sig.extras.exts.push({ oid: extId, critical: critical,
72131 bits: bits });
72132 break;
72133 case (EXTS.altName):
72134 der.readSequence(asn1.Ber.OctetString);
72135 der.readSequence();
72136 var aeEnd = der.offset + der.length;
72137 while (der.offset < aeEnd) {
72138 switch (der.peek()) {
72139 case ALTNAME.OtherName:
72140 case ALTNAME.EDIPartyName:
72141 der.readSequence();
72142 der._offset += der.length;
72143 break;
72144 case ALTNAME.OID:
72145 der.readOID(ALTNAME.OID);
72146 break;
72147 case ALTNAME.RFC822Name:
72148 /* RFC822 specifies email addresses */
72149 var email = der.readString(ALTNAME.RFC822Name);
72150 id = Identity.forEmail(email);
72151 if (!cert.subjects[0].equals(id))
72152 cert.subjects.push(id);
72153 break;
72154 case ALTNAME.DirectoryName:
72155 der.readSequence(ALTNAME.DirectoryName);
72156 id = Identity.parseAsn1(der);
72157 if (!cert.subjects[0].equals(id))
72158 cert.subjects.push(id);
72159 break;
72160 case ALTNAME.DNSName:
72161 var host = der.readString(
72162 ALTNAME.DNSName);
72163 id = Identity.forHost(host);
72164 if (!cert.subjects[0].equals(id))
72165 cert.subjects.push(id);
72166 break;
72167 default:
72168 der.readString(der.peek());
72169 break;
72170 }
72171 }
72172 sig.extras.exts.push({ oid: extId, critical: critical });
72173 break;
72174 default:
72175 sig.extras.exts.push({
72176 oid: extId,
72177 critical: critical,
72178 data: der.readString(asn1.Ber.OctetString, true)
72179 });
72180 break;
72181 }
72182
72183 der._offset = after;
72184}
72185
72186var UTCTIME_RE =
72187 /^([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})?Z$/;
72188function utcTimeToDate(t) {
72189 var m = t.match(UTCTIME_RE);
72190 assert.ok(m, 'timestamps must be in UTC');
72191 var d = new Date();
72192
72193 var thisYear = d.getUTCFullYear();
72194 var century = Math.floor(thisYear / 100) * 100;
72195
72196 var year = parseInt(m[1], 10);
72197 if (thisYear % 100 < 50 && year >= 60)
72198 year += (century - 1);
72199 else
72200 year += century;
72201 d.setUTCFullYear(year, parseInt(m[2], 10) - 1, parseInt(m[3], 10));
72202 d.setUTCHours(parseInt(m[4], 10), parseInt(m[5], 10));
72203 if (m[6] && m[6].length > 0)
72204 d.setUTCSeconds(parseInt(m[6], 10));
72205 return (d);
72206}
72207
72208var GTIME_RE =
72209 /^([0-9]{4})([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})?Z$/;
72210function gTimeToDate(t) {
72211 var m = t.match(GTIME_RE);
72212 assert.ok(m);
72213 var d = new Date();
72214
72215 d.setUTCFullYear(parseInt(m[1], 10), parseInt(m[2], 10) - 1,
72216 parseInt(m[3], 10));
72217 d.setUTCHours(parseInt(m[4], 10), parseInt(m[5], 10));
72218 if (m[6] && m[6].length > 0)
72219 d.setUTCSeconds(parseInt(m[6], 10));
72220 return (d);
72221}
72222
72223function zeroPad(n, m) {
72224 if (m === undefined)
72225 m = 2;
72226 var s = '' + n;
72227 while (s.length < m)
72228 s = '0' + s;
72229 return (s);
72230}
72231
72232function dateToUTCTime(d) {
72233 var s = '';
72234 s += zeroPad(d.getUTCFullYear() % 100);
72235 s += zeroPad(d.getUTCMonth() + 1);
72236 s += zeroPad(d.getUTCDate());
72237 s += zeroPad(d.getUTCHours());
72238 s += zeroPad(d.getUTCMinutes());
72239 s += zeroPad(d.getUTCSeconds());
72240 s += 'Z';
72241 return (s);
72242}
72243
72244function dateToGTime(d) {
72245 var s = '';
72246 s += zeroPad(d.getUTCFullYear(), 4);
72247 s += zeroPad(d.getUTCMonth() + 1);
72248 s += zeroPad(d.getUTCDate());
72249 s += zeroPad(d.getUTCHours());
72250 s += zeroPad(d.getUTCMinutes());
72251 s += zeroPad(d.getUTCSeconds());
72252 s += 'Z';
72253 return (s);
72254}
72255
72256function sign(cert, key) {
72257 if (cert.signatures.x509 === undefined)
72258 cert.signatures.x509 = {};
72259 var sig = cert.signatures.x509;
72260
72261 sig.algo = key.type + '-' + key.defaultHashAlgorithm();
72262 if (SIGN_ALGS[sig.algo] === undefined)
72263 return (false);
72264
72265 var der = new asn1.BerWriter();
72266 writeTBSCert(cert, der);
72267 var blob = der.buffer;
72268 sig.cache = blob;
72269
72270 var signer = key.createSign();
72271 signer.write(blob);
72272 cert.signatures.x509.signature = signer.sign();
72273
72274 return (true);
72275}
72276
72277function signAsync(cert, signer, done) {
72278 if (cert.signatures.x509 === undefined)
72279 cert.signatures.x509 = {};
72280 var sig = cert.signatures.x509;
72281
72282 var der = new asn1.BerWriter();
72283 writeTBSCert(cert, der);
72284 var blob = der.buffer;
72285 sig.cache = blob;
72286
72287 signer(blob, function (err, signature) {
72288 if (err) {
72289 done(err);
72290 return;
72291 }
72292 sig.algo = signature.type + '-' + signature.hashAlgorithm;
72293 if (SIGN_ALGS[sig.algo] === undefined) {
72294 done(new Error('Invalid signing algorithm "' +
72295 sig.algo + '"'));
72296 return;
72297 }
72298 sig.signature = signature;
72299 done();
72300 });
72301}
72302
72303function write(cert, options) {
72304 var sig = cert.signatures.x509;
72305 assert.object(sig, 'x509 signature');
72306
72307 var der = new asn1.BerWriter();
72308 der.startSequence();
72309 if (sig.cache) {
72310 der._ensure(sig.cache.length);
72311 sig.cache.copy(der._buf, der._offset);
72312 der._offset += sig.cache.length;
72313 } else {
72314 writeTBSCert(cert, der);
72315 }
72316
72317 der.startSequence();
72318 der.writeOID(SIGN_ALGS[sig.algo]);
72319 if (sig.algo.match(/^rsa-/))
72320 der.writeNull();
72321 der.endSequence();
72322
72323 var sigData = sig.signature.toBuffer('asn1');
72324 var data = Buffer.alloc(sigData.length + 1);
72325 data[0] = 0;
72326 sigData.copy(data, 1);
72327 der.writeBuffer(data, asn1.Ber.BitString);
72328 der.endSequence();
72329
72330 return (der.buffer);
72331}
72332
72333function writeTBSCert(cert, der) {
72334 var sig = cert.signatures.x509;
72335 assert.object(sig, 'x509 signature');
72336
72337 der.startSequence();
72338
72339 der.startSequence(Local(0));
72340 der.writeInt(2);
72341 der.endSequence();
72342
72343 der.writeBuffer(utils.mpNormalize(cert.serial), asn1.Ber.Integer);
72344
72345 der.startSequence();
72346 der.writeOID(SIGN_ALGS[sig.algo]);
72347 if (sig.algo.match(/^rsa-/))
72348 der.writeNull();
72349 der.endSequence();
72350
72351 cert.issuer.toAsn1(der);
72352
72353 der.startSequence();
72354 writeDate(der, cert.validFrom);
72355 writeDate(der, cert.validUntil);
72356 der.endSequence();
72357
72358 var subject = cert.subjects[0];
72359 var altNames = cert.subjects.slice(1);
72360 subject.toAsn1(der);
72361
72362 pkcs8.writePkcs8(der, cert.subjectKey);
72363
72364 if (sig.extras && sig.extras.issuerUniqueID) {
72365 der.writeBuffer(sig.extras.issuerUniqueID, Local(1));
72366 }
72367
72368 if (sig.extras && sig.extras.subjectUniqueID) {
72369 der.writeBuffer(sig.extras.subjectUniqueID, Local(2));
72370 }
72371
72372 if (altNames.length > 0 || subject.type === 'host' ||
72373 (cert.purposes !== undefined && cert.purposes.length > 0) ||
72374 (sig.extras && sig.extras.exts)) {
72375 der.startSequence(Local(3));
72376 der.startSequence();
72377
72378 var exts = [];
72379 if (cert.purposes !== undefined && cert.purposes.length > 0) {
72380 exts.push({
72381 oid: EXTS.basicConstraints,
72382 critical: true
72383 });
72384 exts.push({
72385 oid: EXTS.keyUsage,
72386 critical: true
72387 });
72388 exts.push({
72389 oid: EXTS.extKeyUsage,
72390 critical: true
72391 });
72392 }
72393 exts.push({ oid: EXTS.altName });
72394 if (sig.extras && sig.extras.exts)
72395 exts = sig.extras.exts;
72396
72397 for (var i = 0; i < exts.length; ++i) {
72398 der.startSequence();
72399 der.writeOID(exts[i].oid);
72400
72401 if (exts[i].critical !== undefined)
72402 der.writeBoolean(exts[i].critical);
72403
72404 if (exts[i].oid === EXTS.altName) {
72405 der.startSequence(asn1.Ber.OctetString);
72406 der.startSequence();
72407 if (subject.type === 'host') {
72408 der.writeString(subject.hostname,
72409 Context(2));
72410 }
72411 for (var j = 0; j < altNames.length; ++j) {
72412 if (altNames[j].type === 'host') {
72413 der.writeString(
72414 altNames[j].hostname,
72415 ALTNAME.DNSName);
72416 } else if (altNames[j].type ===
72417 'email') {
72418 der.writeString(
72419 altNames[j].email,
72420 ALTNAME.RFC822Name);
72421 } else {
72422 /*
72423 * Encode anything else as a
72424 * DN style name for now.
72425 */
72426 der.startSequence(
72427 ALTNAME.DirectoryName);
72428 altNames[j].toAsn1(der);
72429 der.endSequence();
72430 }
72431 }
72432 der.endSequence();
72433 der.endSequence();
72434 } else if (exts[i].oid === EXTS.basicConstraints) {
72435 der.startSequence(asn1.Ber.OctetString);
72436 der.startSequence();
72437 var ca = (cert.purposes.indexOf('ca') !== -1);
72438 var pathLen = exts[i].pathLen;
72439 der.writeBoolean(ca);
72440 if (pathLen !== undefined)
72441 der.writeInt(pathLen);
72442 der.endSequence();
72443 der.endSequence();
72444 } else if (exts[i].oid === EXTS.extKeyUsage) {
72445 der.startSequence(asn1.Ber.OctetString);
72446 der.startSequence();
72447 cert.purposes.forEach(function (purpose) {
72448 if (purpose === 'ca')
72449 return;
72450 if (KEYUSEBITS.indexOf(purpose) !== -1)
72451 return;
72452 var oid = purpose;
72453 if (EXTPURPOSE[purpose] !== undefined)
72454 oid = EXTPURPOSE[purpose];
72455 der.writeOID(oid);
72456 });
72457 der.endSequence();
72458 der.endSequence();
72459 } else if (exts[i].oid === EXTS.keyUsage) {
72460 der.startSequence(asn1.Ber.OctetString);
72461 /*
72462 * If we parsed this certificate from a byte
72463 * stream (i.e. we didn't generate it in sshpk)
72464 * then we'll have a ".bits" property on the
72465 * ext with the original raw byte contents.
72466 *
72467 * If we have this, use it here instead of
72468 * regenerating it. This guarantees we output
72469 * the same data we parsed, so signatures still
72470 * validate.
72471 */
72472 if (exts[i].bits !== undefined) {
72473 der.writeBuffer(exts[i].bits,
72474 asn1.Ber.BitString);
72475 } else {
72476 var bits = writeBitField(cert.purposes,
72477 KEYUSEBITS);
72478 der.writeBuffer(bits,
72479 asn1.Ber.BitString);
72480 }
72481 der.endSequence();
72482 } else {
72483 der.writeBuffer(exts[i].data,
72484 asn1.Ber.OctetString);
72485 }
72486
72487 der.endSequence();
72488 }
72489
72490 der.endSequence();
72491 der.endSequence();
72492 }
72493
72494 der.endSequence();
72495}
72496
72497/*
72498 * Reads an ASN.1 BER bitfield out of the Buffer produced by doing
72499 * `BerReader#readString(asn1.Ber.BitString)`. That function gives us the raw
72500 * contents of the BitString tag, which is a count of unused bits followed by
72501 * the bits as a right-padded byte string.
72502 *
72503 * `bits` is the Buffer, `bitIndex` should contain an array of string names
72504 * for the bits in the string, ordered starting with bit #0 in the ASN.1 spec.
72505 *
72506 * Returns an array of Strings, the names of the bits that were set to 1.
72507 */
72508function readBitField(bits, bitIndex) {
72509 var bitLen = 8 * (bits.length - 1) - bits[0];
72510 var setBits = {};
72511 for (var i = 0; i < bitLen; ++i) {
72512 var byteN = 1 + Math.floor(i / 8);
72513 var bit = 7 - (i % 8);
72514 var mask = 1 << bit;
72515 var bitVal = ((bits[byteN] & mask) !== 0);
72516 var name = bitIndex[i];
72517 if (bitVal && typeof (name) === 'string') {
72518 setBits[name] = true;
72519 }
72520 }
72521 return (Object.keys(setBits));
72522}
72523
72524/*
72525 * `setBits` is an array of strings, containing the names for each bit that
72526 * sould be set to 1. `bitIndex` is same as in `readBitField()`.
72527 *
72528 * Returns a Buffer, ready to be written out with `BerWriter#writeString()`.
72529 */
72530function writeBitField(setBits, bitIndex) {
72531 var bitLen = bitIndex.length;
72532 var blen = Math.ceil(bitLen / 8);
72533 var unused = blen * 8 - bitLen;
72534 var bits = Buffer.alloc(1 + blen); // zero-filled
72535 bits[0] = unused;
72536 for (var i = 0; i < bitLen; ++i) {
72537 var byteN = 1 + Math.floor(i / 8);
72538 var bit = 7 - (i % 8);
72539 var mask = 1 << bit;
72540 var name = bitIndex[i];
72541 if (name === undefined)
72542 continue;
72543 var bitVal = (setBits.indexOf(name) !== -1);
72544 if (bitVal) {
72545 bits[byteN] |= mask;
72546 }
72547 }
72548 return (bits);
72549}
72550
72551},{"../algs":335,"../certificate":336,"../identity":353,"../key":355,"../private-key":356,"../signature":357,"../utils":359,"./pem":344,"./pkcs8":346,"asn1":66,"assert-plus":67,"safer-buffer":326}],353:[function(require,module,exports){
72552// Copyright 2017 Joyent, Inc.
72553
72554module.exports = Identity;
72555
72556var assert = require('assert-plus');
72557var algs = require('./algs');
72558var crypto = require('crypto');
72559var Fingerprint = require('./fingerprint');
72560var Signature = require('./signature');
72561var errs = require('./errors');
72562var util = require('util');
72563var utils = require('./utils');
72564var asn1 = require('asn1');
72565var Buffer = require('safer-buffer').Buffer;
72566
72567/*JSSTYLED*/
72568var DNS_NAME_RE = /^([*]|[a-z0-9][a-z0-9\-]{0,62})(?:\.([*]|[a-z0-9][a-z0-9\-]{0,62}))*$/i;
72569
72570var oids = {};
72571oids.cn = '2.5.4.3';
72572oids.o = '2.5.4.10';
72573oids.ou = '2.5.4.11';
72574oids.l = '2.5.4.7';
72575oids.s = '2.5.4.8';
72576oids.c = '2.5.4.6';
72577oids.sn = '2.5.4.4';
72578oids.postalCode = '2.5.4.17';
72579oids.serialNumber = '2.5.4.5';
72580oids.street = '2.5.4.9';
72581oids.x500UniqueIdentifier = '2.5.4.45';
72582oids.role = '2.5.4.72';
72583oids.telephoneNumber = '2.5.4.20';
72584oids.description = '2.5.4.13';
72585oids.dc = '0.9.2342.19200300.100.1.25';
72586oids.uid = '0.9.2342.19200300.100.1.1';
72587oids.mail = '0.9.2342.19200300.100.1.3';
72588oids.title = '2.5.4.12';
72589oids.gn = '2.5.4.42';
72590oids.initials = '2.5.4.43';
72591oids.pseudonym = '2.5.4.65';
72592oids.emailAddress = '1.2.840.113549.1.9.1';
72593
72594var unoids = {};
72595Object.keys(oids).forEach(function (k) {
72596 unoids[oids[k]] = k;
72597});
72598
72599function Identity(opts) {
72600 var self = this;
72601 assert.object(opts, 'options');
72602 assert.arrayOfObject(opts.components, 'options.components');
72603 this.components = opts.components;
72604 this.componentLookup = {};
72605 this.components.forEach(function (c) {
72606 if (c.name && !c.oid)
72607 c.oid = oids[c.name];
72608 if (c.oid && !c.name)
72609 c.name = unoids[c.oid];
72610 if (self.componentLookup[c.name] === undefined)
72611 self.componentLookup[c.name] = [];
72612 self.componentLookup[c.name].push(c);
72613 });
72614 if (this.componentLookup.cn && this.componentLookup.cn.length > 0) {
72615 this.cn = this.componentLookup.cn[0].value;
72616 }
72617 assert.optionalString(opts.type, 'options.type');
72618 if (opts.type === undefined) {
72619 if (this.components.length === 1 &&
72620 this.componentLookup.cn &&
72621 this.componentLookup.cn.length === 1 &&
72622 this.componentLookup.cn[0].value.match(DNS_NAME_RE)) {
72623 this.type = 'host';
72624 this.hostname = this.componentLookup.cn[0].value;
72625
72626 } else if (this.componentLookup.dc &&
72627 this.components.length === this.componentLookup.dc.length) {
72628 this.type = 'host';
72629 this.hostname = this.componentLookup.dc.map(
72630 function (c) {
72631 return (c.value);
72632 }).join('.');
72633
72634 } else if (this.componentLookup.uid &&
72635 this.components.length ===
72636 this.componentLookup.uid.length) {
72637 this.type = 'user';
72638 this.uid = this.componentLookup.uid[0].value;
72639
72640 } else if (this.componentLookup.cn &&
72641 this.componentLookup.cn.length === 1 &&
72642 this.componentLookup.cn[0].value.match(DNS_NAME_RE)) {
72643 this.type = 'host';
72644 this.hostname = this.componentLookup.cn[0].value;
72645
72646 } else if (this.componentLookup.uid &&
72647 this.componentLookup.uid.length === 1) {
72648 this.type = 'user';
72649 this.uid = this.componentLookup.uid[0].value;
72650
72651 } else if (this.componentLookup.mail &&
72652 this.componentLookup.mail.length === 1) {
72653 this.type = 'email';
72654 this.email = this.componentLookup.mail[0].value;
72655
72656 } else if (this.componentLookup.cn &&
72657 this.componentLookup.cn.length === 1) {
72658 this.type = 'user';
72659 this.uid = this.componentLookup.cn[0].value;
72660
72661 } else {
72662 this.type = 'unknown';
72663 }
72664 } else {
72665 this.type = opts.type;
72666 if (this.type === 'host')
72667 this.hostname = opts.hostname;
72668 else if (this.type === 'user')
72669 this.uid = opts.uid;
72670 else if (this.type === 'email')
72671 this.email = opts.email;
72672 else
72673 throw (new Error('Unknown type ' + this.type));
72674 }
72675}
72676
72677Identity.prototype.toString = function () {
72678 return (this.components.map(function (c) {
72679 var n = c.name.toUpperCase();
72680 /*JSSTYLED*/
72681 n = n.replace(/=/g, '\\=');
72682 var v = c.value;
72683 /*JSSTYLED*/
72684 v = v.replace(/,/g, '\\,');
72685 return (n + '=' + v);
72686 }).join(', '));
72687};
72688
72689Identity.prototype.get = function (name, asArray) {
72690 assert.string(name, 'name');
72691 var arr = this.componentLookup[name];
72692 if (arr === undefined || arr.length === 0)
72693 return (undefined);
72694 if (!asArray && arr.length > 1)
72695 throw (new Error('Multiple values for attribute ' + name));
72696 if (!asArray)
72697 return (arr[0].value);
72698 return (arr.map(function (c) {
72699 return (c.value);
72700 }));
72701};
72702
72703Identity.prototype.toArray = function (idx) {
72704 return (this.components.map(function (c) {
72705 return ({
72706 name: c.name,
72707 value: c.value
72708 });
72709 }));
72710};
72711
72712/*
72713 * These are from X.680 -- PrintableString allowed chars are in section 37.4
72714 * table 8. Spec for IA5Strings is "1,6 + SPACE + DEL" where 1 refers to
72715 * ISO IR #001 (standard ASCII control characters) and 6 refers to ISO IR #006
72716 * (the basic ASCII character set).
72717 */
72718/* JSSTYLED */
72719var NOT_PRINTABLE = /[^a-zA-Z0-9 '(),+.\/:=?-]/;
72720/* JSSTYLED */
72721var NOT_IA5 = /[^\x00-\x7f]/;
72722
72723Identity.prototype.toAsn1 = function (der, tag) {
72724 der.startSequence(tag);
72725 this.components.forEach(function (c) {
72726 der.startSequence(asn1.Ber.Constructor | asn1.Ber.Set);
72727 der.startSequence();
72728 der.writeOID(c.oid);
72729 /*
72730 * If we fit in a PrintableString, use that. Otherwise use an
72731 * IA5String or UTF8String.
72732 *
72733 * If this identity was parsed from a DN, use the ASN.1 types
72734 * from the original representation (otherwise this might not
72735 * be a full match for the original in some validators).
72736 */
72737 if (c.asn1type === asn1.Ber.Utf8String ||
72738 c.value.match(NOT_IA5)) {
72739 var v = Buffer.from(c.value, 'utf8');
72740 der.writeBuffer(v, asn1.Ber.Utf8String);
72741
72742 } else if (c.asn1type === asn1.Ber.IA5String ||
72743 c.value.match(NOT_PRINTABLE)) {
72744 der.writeString(c.value, asn1.Ber.IA5String);
72745
72746 } else {
72747 var type = asn1.Ber.PrintableString;
72748 if (c.asn1type !== undefined)
72749 type = c.asn1type;
72750 der.writeString(c.value, type);
72751 }
72752 der.endSequence();
72753 der.endSequence();
72754 });
72755 der.endSequence();
72756};
72757
72758function globMatch(a, b) {
72759 if (a === '**' || b === '**')
72760 return (true);
72761 var aParts = a.split('.');
72762 var bParts = b.split('.');
72763 if (aParts.length !== bParts.length)
72764 return (false);
72765 for (var i = 0; i < aParts.length; ++i) {
72766 if (aParts[i] === '*' || bParts[i] === '*')
72767 continue;
72768 if (aParts[i] !== bParts[i])
72769 return (false);
72770 }
72771 return (true);
72772}
72773
72774Identity.prototype.equals = function (other) {
72775 if (!Identity.isIdentity(other, [1, 0]))
72776 return (false);
72777 if (other.components.length !== this.components.length)
72778 return (false);
72779 for (var i = 0; i < this.components.length; ++i) {
72780 if (this.components[i].oid !== other.components[i].oid)
72781 return (false);
72782 if (!globMatch(this.components[i].value,
72783 other.components[i].value)) {
72784 return (false);
72785 }
72786 }
72787 return (true);
72788};
72789
72790Identity.forHost = function (hostname) {
72791 assert.string(hostname, 'hostname');
72792 return (new Identity({
72793 type: 'host',
72794 hostname: hostname,
72795 components: [ { name: 'cn', value: hostname } ]
72796 }));
72797};
72798
72799Identity.forUser = function (uid) {
72800 assert.string(uid, 'uid');
72801 return (new Identity({
72802 type: 'user',
72803 uid: uid,
72804 components: [ { name: 'uid', value: uid } ]
72805 }));
72806};
72807
72808Identity.forEmail = function (email) {
72809 assert.string(email, 'email');
72810 return (new Identity({
72811 type: 'email',
72812 email: email,
72813 components: [ { name: 'mail', value: email } ]
72814 }));
72815};
72816
72817Identity.parseDN = function (dn) {
72818 assert.string(dn, 'dn');
72819 var parts = [''];
72820 var idx = 0;
72821 var rem = dn;
72822 while (rem.length > 0) {
72823 var m;
72824 /*JSSTYLED*/
72825 if ((m = /^,/.exec(rem)) !== null) {
72826 parts[++idx] = '';
72827 rem = rem.slice(m[0].length);
72828 /*JSSTYLED*/
72829 } else if ((m = /^\\,/.exec(rem)) !== null) {
72830 parts[idx] += ',';
72831 rem = rem.slice(m[0].length);
72832 /*JSSTYLED*/
72833 } else if ((m = /^\\./.exec(rem)) !== null) {
72834 parts[idx] += m[0];
72835 rem = rem.slice(m[0].length);
72836 /*JSSTYLED*/
72837 } else if ((m = /^[^\\,]+/.exec(rem)) !== null) {
72838 parts[idx] += m[0];
72839 rem = rem.slice(m[0].length);
72840 } else {
72841 throw (new Error('Failed to parse DN'));
72842 }
72843 }
72844 var cmps = parts.map(function (c) {
72845 c = c.trim();
72846 var eqPos = c.indexOf('=');
72847 while (eqPos > 0 && c.charAt(eqPos - 1) === '\\')
72848 eqPos = c.indexOf('=', eqPos + 1);
72849 if (eqPos === -1) {
72850 throw (new Error('Failed to parse DN'));
72851 }
72852 /*JSSTYLED*/
72853 var name = c.slice(0, eqPos).toLowerCase().replace(/\\=/g, '=');
72854 var value = c.slice(eqPos + 1);
72855 return ({ name: name, value: value });
72856 });
72857 return (new Identity({ components: cmps }));
72858};
72859
72860Identity.fromArray = function (components) {
72861 assert.arrayOfObject(components, 'components');
72862 components.forEach(function (cmp) {
72863 assert.object(cmp, 'component');
72864 assert.string(cmp.name, 'component.name');
72865 if (!Buffer.isBuffer(cmp.value) &&
72866 !(typeof (cmp.value) === 'string')) {
72867 throw (new Error('Invalid component value'));
72868 }
72869 });
72870 return (new Identity({ components: components }));
72871};
72872
72873Identity.parseAsn1 = function (der, top) {
72874 var components = [];
72875 der.readSequence(top);
72876 var end = der.offset + der.length;
72877 while (der.offset < end) {
72878 der.readSequence(asn1.Ber.Constructor | asn1.Ber.Set);
72879 var after = der.offset + der.length;
72880 der.readSequence();
72881 var oid = der.readOID();
72882 var type = der.peek();
72883 var value;
72884 switch (type) {
72885 case asn1.Ber.PrintableString:
72886 case asn1.Ber.IA5String:
72887 case asn1.Ber.OctetString:
72888 case asn1.Ber.T61String:
72889 value = der.readString(type);
72890 break;
72891 case asn1.Ber.Utf8String:
72892 value = der.readString(type, true);
72893 value = value.toString('utf8');
72894 break;
72895 case asn1.Ber.CharacterString:
72896 case asn1.Ber.BMPString:
72897 value = der.readString(type, true);
72898 value = value.toString('utf16le');
72899 break;
72900 default:
72901 throw (new Error('Unknown asn1 type ' + type));
72902 }
72903 components.push({ oid: oid, asn1type: type, value: value });
72904 der._offset = after;
72905 }
72906 der._offset = end;
72907 return (new Identity({
72908 components: components
72909 }));
72910};
72911
72912Identity.isIdentity = function (obj, ver) {
72913 return (utils.isCompatible(obj, Identity, ver));
72914};
72915
72916/*
72917 * API versions for Identity:
72918 * [1,0] -- initial ver
72919 */
72920Identity.prototype._sshpkApiVersion = [1, 0];
72921
72922Identity._oldVersionDetect = function (obj) {
72923 return ([1, 0]);
72924};
72925
72926},{"./algs":335,"./errors":339,"./fingerprint":340,"./signature":357,"./utils":359,"asn1":66,"assert-plus":67,"crypto":126,"safer-buffer":326,"util":397}],354:[function(require,module,exports){
72927// Copyright 2015 Joyent, Inc.
72928
72929var Key = require('./key');
72930var Fingerprint = require('./fingerprint');
72931var Signature = require('./signature');
72932var PrivateKey = require('./private-key');
72933var Certificate = require('./certificate');
72934var Identity = require('./identity');
72935var errs = require('./errors');
72936
72937module.exports = {
72938 /* top-level classes */
72939 Key: Key,
72940 parseKey: Key.parse,
72941 Fingerprint: Fingerprint,
72942 parseFingerprint: Fingerprint.parse,
72943 Signature: Signature,
72944 parseSignature: Signature.parse,
72945 PrivateKey: PrivateKey,
72946 parsePrivateKey: PrivateKey.parse,
72947 generatePrivateKey: PrivateKey.generate,
72948 Certificate: Certificate,
72949 parseCertificate: Certificate.parse,
72950 createSelfSignedCertificate: Certificate.createSelfSigned,
72951 createCertificate: Certificate.create,
72952 Identity: Identity,
72953 identityFromDN: Identity.parseDN,
72954 identityForHost: Identity.forHost,
72955 identityForUser: Identity.forUser,
72956 identityForEmail: Identity.forEmail,
72957 identityFromArray: Identity.fromArray,
72958
72959 /* errors */
72960 FingerprintFormatError: errs.FingerprintFormatError,
72961 InvalidAlgorithmError: errs.InvalidAlgorithmError,
72962 KeyParseError: errs.KeyParseError,
72963 SignatureParseError: errs.SignatureParseError,
72964 KeyEncryptedError: errs.KeyEncryptedError,
72965 CertificateParseError: errs.CertificateParseError
72966};
72967
72968},{"./certificate":336,"./errors":339,"./fingerprint":340,"./identity":353,"./key":355,"./private-key":356,"./signature":357}],355:[function(require,module,exports){
72969(function (Buffer){
72970// Copyright 2018 Joyent, Inc.
72971
72972module.exports = Key;
72973
72974var assert = require('assert-plus');
72975var algs = require('./algs');
72976var crypto = require('crypto');
72977var Fingerprint = require('./fingerprint');
72978var Signature = require('./signature');
72979var DiffieHellman = require('./dhe').DiffieHellman;
72980var errs = require('./errors');
72981var utils = require('./utils');
72982var PrivateKey = require('./private-key');
72983var edCompat;
72984
72985try {
72986 edCompat = require('./ed-compat');
72987} catch (e) {
72988 /* Just continue through, and bail out if we try to use it. */
72989}
72990
72991var InvalidAlgorithmError = errs.InvalidAlgorithmError;
72992var KeyParseError = errs.KeyParseError;
72993
72994var formats = {};
72995formats['auto'] = require('./formats/auto');
72996formats['pem'] = require('./formats/pem');
72997formats['pkcs1'] = require('./formats/pkcs1');
72998formats['pkcs8'] = require('./formats/pkcs8');
72999formats['rfc4253'] = require('./formats/rfc4253');
73000formats['ssh'] = require('./formats/ssh');
73001formats['ssh-private'] = require('./formats/ssh-private');
73002formats['openssh'] = formats['ssh-private'];
73003formats['dnssec'] = require('./formats/dnssec');
73004formats['putty'] = require('./formats/putty');
73005formats['ppk'] = formats['putty'];
73006
73007function Key(opts) {
73008 assert.object(opts, 'options');
73009 assert.arrayOfObject(opts.parts, 'options.parts');
73010 assert.string(opts.type, 'options.type');
73011 assert.optionalString(opts.comment, 'options.comment');
73012
73013 var algInfo = algs.info[opts.type];
73014 if (typeof (algInfo) !== 'object')
73015 throw (new InvalidAlgorithmError(opts.type));
73016
73017 var partLookup = {};
73018 for (var i = 0; i < opts.parts.length; ++i) {
73019 var part = opts.parts[i];
73020 partLookup[part.name] = part;
73021 }
73022
73023 this.type = opts.type;
73024 this.parts = opts.parts;
73025 this.part = partLookup;
73026 this.comment = undefined;
73027 this.source = opts.source;
73028
73029 /* for speeding up hashing/fingerprint operations */
73030 this._rfc4253Cache = opts._rfc4253Cache;
73031 this._hashCache = {};
73032
73033 var sz;
73034 this.curve = undefined;
73035 if (this.type === 'ecdsa') {
73036 var curve = this.part.curve.data.toString();
73037 this.curve = curve;
73038 sz = algs.curves[curve].size;
73039 } else if (this.type === 'ed25519' || this.type === 'curve25519') {
73040 sz = 256;
73041 this.curve = 'curve25519';
73042 } else {
73043 var szPart = this.part[algInfo.sizePart];
73044 sz = szPart.data.length;
73045 sz = sz * 8 - utils.countZeros(szPart.data);
73046 }
73047 this.size = sz;
73048}
73049
73050Key.formats = formats;
73051
73052Key.prototype.toBuffer = function (format, options) {
73053 if (format === undefined)
73054 format = 'ssh';
73055 assert.string(format, 'format');
73056 assert.object(formats[format], 'formats[format]');
73057 assert.optionalObject(options, 'options');
73058
73059 if (format === 'rfc4253') {
73060 if (this._rfc4253Cache === undefined)
73061 this._rfc4253Cache = formats['rfc4253'].write(this);
73062 return (this._rfc4253Cache);
73063 }
73064
73065 return (formats[format].write(this, options));
73066};
73067
73068Key.prototype.toString = function (format, options) {
73069 return (this.toBuffer(format, options).toString());
73070};
73071
73072Key.prototype.hash = function (algo, type) {
73073 assert.string(algo, 'algorithm');
73074 assert.optionalString(type, 'type');
73075 if (type === undefined)
73076 type = 'ssh';
73077 algo = algo.toLowerCase();
73078 if (algs.hashAlgs[algo] === undefined)
73079 throw (new InvalidAlgorithmError(algo));
73080
73081 var cacheKey = algo + '||' + type;
73082 if (this._hashCache[cacheKey])
73083 return (this._hashCache[cacheKey]);
73084
73085 var buf;
73086 if (type === 'ssh') {
73087 buf = this.toBuffer('rfc4253');
73088 } else if (type === 'spki') {
73089 buf = formats.pkcs8.pkcs8ToBuffer(this);
73090 } else {
73091 throw (new Error('Hash type ' + type + ' not supported'));
73092 }
73093 var hash = crypto.createHash(algo).update(buf).digest();
73094 this._hashCache[cacheKey] = hash;
73095 return (hash);
73096};
73097
73098Key.prototype.fingerprint = function (algo, type) {
73099 if (algo === undefined)
73100 algo = 'sha256';
73101 if (type === undefined)
73102 type = 'ssh';
73103 assert.string(algo, 'algorithm');
73104 assert.string(type, 'type');
73105 var opts = {
73106 type: 'key',
73107 hash: this.hash(algo, type),
73108 algorithm: algo,
73109 hashType: type
73110 };
73111 return (new Fingerprint(opts));
73112};
73113
73114Key.prototype.defaultHashAlgorithm = function () {
73115 var hashAlgo = 'sha1';
73116 if (this.type === 'rsa')
73117 hashAlgo = 'sha256';
73118 if (this.type === 'dsa' && this.size > 1024)
73119 hashAlgo = 'sha256';
73120 if (this.type === 'ed25519')
73121 hashAlgo = 'sha512';
73122 if (this.type === 'ecdsa') {
73123 if (this.size <= 256)
73124 hashAlgo = 'sha256';
73125 else if (this.size <= 384)
73126 hashAlgo = 'sha384';
73127 else
73128 hashAlgo = 'sha512';
73129 }
73130 return (hashAlgo);
73131};
73132
73133Key.prototype.createVerify = function (hashAlgo) {
73134 if (hashAlgo === undefined)
73135 hashAlgo = this.defaultHashAlgorithm();
73136 assert.string(hashAlgo, 'hash algorithm');
73137
73138 /* ED25519 is not supported by OpenSSL, use a javascript impl. */
73139 if (this.type === 'ed25519' && edCompat !== undefined)
73140 return (new edCompat.Verifier(this, hashAlgo));
73141 if (this.type === 'curve25519')
73142 throw (new Error('Curve25519 keys are not suitable for ' +
73143 'signing or verification'));
73144
73145 var v, nm, err;
73146 try {
73147 nm = hashAlgo.toUpperCase();
73148 v = crypto.createVerify(nm);
73149 } catch (e) {
73150 err = e;
73151 }
73152 if (v === undefined || (err instanceof Error &&
73153 err.message.match(/Unknown message digest/))) {
73154 nm = 'RSA-';
73155 nm += hashAlgo.toUpperCase();
73156 v = crypto.createVerify(nm);
73157 }
73158 assert.ok(v, 'failed to create verifier');
73159 var oldVerify = v.verify.bind(v);
73160 var key = this.toBuffer('pkcs8');
73161 var curve = this.curve;
73162 var self = this;
73163 v.verify = function (signature, fmt) {
73164 if (Signature.isSignature(signature, [2, 0])) {
73165 if (signature.type !== self.type)
73166 return (false);
73167 if (signature.hashAlgorithm &&
73168 signature.hashAlgorithm !== hashAlgo)
73169 return (false);
73170 if (signature.curve && self.type === 'ecdsa' &&
73171 signature.curve !== curve)
73172 return (false);
73173 return (oldVerify(key, signature.toBuffer('asn1')));
73174
73175 } else if (typeof (signature) === 'string' ||
73176 Buffer.isBuffer(signature)) {
73177 return (oldVerify(key, signature, fmt));
73178
73179 /*
73180 * Avoid doing this on valid arguments, walking the prototype
73181 * chain can be quite slow.
73182 */
73183 } else if (Signature.isSignature(signature, [1, 0])) {
73184 throw (new Error('signature was created by too old ' +
73185 'a version of sshpk and cannot be verified'));
73186
73187 } else {
73188 throw (new TypeError('signature must be a string, ' +
73189 'Buffer, or Signature object'));
73190 }
73191 };
73192 return (v);
73193};
73194
73195Key.prototype.createDiffieHellman = function () {
73196 if (this.type === 'rsa')
73197 throw (new Error('RSA keys do not support Diffie-Hellman'));
73198
73199 return (new DiffieHellman(this));
73200};
73201Key.prototype.createDH = Key.prototype.createDiffieHellman;
73202
73203Key.parse = function (data, format, options) {
73204 if (typeof (data) !== 'string')
73205 assert.buffer(data, 'data');
73206 if (format === undefined)
73207 format = 'auto';
73208 assert.string(format, 'format');
73209 if (typeof (options) === 'string')
73210 options = { filename: options };
73211 assert.optionalObject(options, 'options');
73212 if (options === undefined)
73213 options = {};
73214 assert.optionalString(options.filename, 'options.filename');
73215 if (options.filename === undefined)
73216 options.filename = '(unnamed)';
73217
73218 assert.object(formats[format], 'formats[format]');
73219
73220 try {
73221 var k = formats[format].read(data, options);
73222 if (k instanceof PrivateKey)
73223 k = k.toPublic();
73224 if (!k.comment)
73225 k.comment = options.filename;
73226 return (k);
73227 } catch (e) {
73228 if (e.name === 'KeyEncryptedError')
73229 throw (e);
73230 throw (new KeyParseError(options.filename, format, e));
73231 }
73232};
73233
73234Key.isKey = function (obj, ver) {
73235 return (utils.isCompatible(obj, Key, ver));
73236};
73237
73238/*
73239 * API versions for Key:
73240 * [1,0] -- initial ver, may take Signature for createVerify or may not
73241 * [1,1] -- added pkcs1, pkcs8 formats
73242 * [1,2] -- added auto, ssh-private, openssh formats
73243 * [1,3] -- added defaultHashAlgorithm
73244 * [1,4] -- added ed support, createDH
73245 * [1,5] -- first explicitly tagged version
73246 * [1,6] -- changed ed25519 part names
73247 * [1,7] -- spki hash types
73248 */
73249Key.prototype._sshpkApiVersion = [1, 7];
73250
73251Key._oldVersionDetect = function (obj) {
73252 assert.func(obj.toBuffer);
73253 assert.func(obj.fingerprint);
73254 if (obj.createDH)
73255 return ([1, 4]);
73256 if (obj.defaultHashAlgorithm)
73257 return ([1, 3]);
73258 if (obj.formats['auto'])
73259 return ([1, 2]);
73260 if (obj.formats['pkcs1'])
73261 return ([1, 1]);
73262 return ([1, 0]);
73263};
73264
73265}).call(this,{"isBuffer":require("../../is-buffer/index.js")})
73266},{"../../is-buffer/index.js":211,"./algs":335,"./dhe":337,"./ed-compat":338,"./errors":339,"./fingerprint":340,"./formats/auto":341,"./formats/dnssec":342,"./formats/pem":344,"./formats/pkcs1":345,"./formats/pkcs8":346,"./formats/putty":347,"./formats/rfc4253":348,"./formats/ssh":350,"./formats/ssh-private":349,"./private-key":356,"./signature":357,"./utils":359,"assert-plus":67,"crypto":126}],356:[function(require,module,exports){
73267// Copyright 2017 Joyent, Inc.
73268
73269module.exports = PrivateKey;
73270
73271var assert = require('assert-plus');
73272var Buffer = require('safer-buffer').Buffer;
73273var algs = require('./algs');
73274var crypto = require('crypto');
73275var Fingerprint = require('./fingerprint');
73276var Signature = require('./signature');
73277var errs = require('./errors');
73278var util = require('util');
73279var utils = require('./utils');
73280var dhe = require('./dhe');
73281var generateECDSA = dhe.generateECDSA;
73282var generateED25519 = dhe.generateED25519;
73283var edCompat = require('./ed-compat');
73284var nacl = require('tweetnacl');
73285
73286var Key = require('./key');
73287
73288var InvalidAlgorithmError = errs.InvalidAlgorithmError;
73289var KeyParseError = errs.KeyParseError;
73290var KeyEncryptedError = errs.KeyEncryptedError;
73291
73292var formats = {};
73293formats['auto'] = require('./formats/auto');
73294formats['pem'] = require('./formats/pem');
73295formats['pkcs1'] = require('./formats/pkcs1');
73296formats['pkcs8'] = require('./formats/pkcs8');
73297formats['rfc4253'] = require('./formats/rfc4253');
73298formats['ssh-private'] = require('./formats/ssh-private');
73299formats['openssh'] = formats['ssh-private'];
73300formats['ssh'] = formats['ssh-private'];
73301formats['dnssec'] = require('./formats/dnssec');
73302
73303function PrivateKey(opts) {
73304 assert.object(opts, 'options');
73305 Key.call(this, opts);
73306
73307 this._pubCache = undefined;
73308}
73309util.inherits(PrivateKey, Key);
73310
73311PrivateKey.formats = formats;
73312
73313PrivateKey.prototype.toBuffer = function (format, options) {
73314 if (format === undefined)
73315 format = 'pkcs1';
73316 assert.string(format, 'format');
73317 assert.object(formats[format], 'formats[format]');
73318 assert.optionalObject(options, 'options');
73319
73320 return (formats[format].write(this, options));
73321};
73322
73323PrivateKey.prototype.hash = function (algo, type) {
73324 return (this.toPublic().hash(algo, type));
73325};
73326
73327PrivateKey.prototype.fingerprint = function (algo, type) {
73328 return (this.toPublic().fingerprint(algo, type));
73329};
73330
73331PrivateKey.prototype.toPublic = function () {
73332 if (this._pubCache)
73333 return (this._pubCache);
73334
73335 var algInfo = algs.info[this.type];
73336 var pubParts = [];
73337 for (var i = 0; i < algInfo.parts.length; ++i) {
73338 var p = algInfo.parts[i];
73339 pubParts.push(this.part[p]);
73340 }
73341
73342 this._pubCache = new Key({
73343 type: this.type,
73344 source: this,
73345 parts: pubParts
73346 });
73347 if (this.comment)
73348 this._pubCache.comment = this.comment;
73349 return (this._pubCache);
73350};
73351
73352PrivateKey.prototype.derive = function (newType) {
73353 assert.string(newType, 'type');
73354 var priv, pub, pair;
73355
73356 if (this.type === 'ed25519' && newType === 'curve25519') {
73357 priv = this.part.k.data;
73358 if (priv[0] === 0x00)
73359 priv = priv.slice(1);
73360
73361 pair = nacl.box.keyPair.fromSecretKey(new Uint8Array(priv));
73362 pub = Buffer.from(pair.publicKey);
73363
73364 return (new PrivateKey({
73365 type: 'curve25519',
73366 parts: [
73367 { name: 'A', data: utils.mpNormalize(pub) },
73368 { name: 'k', data: utils.mpNormalize(priv) }
73369 ]
73370 }));
73371 } else if (this.type === 'curve25519' && newType === 'ed25519') {
73372 priv = this.part.k.data;
73373 if (priv[0] === 0x00)
73374 priv = priv.slice(1);
73375
73376 pair = nacl.sign.keyPair.fromSeed(new Uint8Array(priv));
73377 pub = Buffer.from(pair.publicKey);
73378
73379 return (new PrivateKey({
73380 type: 'ed25519',
73381 parts: [
73382 { name: 'A', data: utils.mpNormalize(pub) },
73383 { name: 'k', data: utils.mpNormalize(priv) }
73384 ]
73385 }));
73386 }
73387 throw (new Error('Key derivation not supported from ' + this.type +
73388 ' to ' + newType));
73389};
73390
73391PrivateKey.prototype.createVerify = function (hashAlgo) {
73392 return (this.toPublic().createVerify(hashAlgo));
73393};
73394
73395PrivateKey.prototype.createSign = function (hashAlgo) {
73396 if (hashAlgo === undefined)
73397 hashAlgo = this.defaultHashAlgorithm();
73398 assert.string(hashAlgo, 'hash algorithm');
73399
73400 /* ED25519 is not supported by OpenSSL, use a javascript impl. */
73401 if (this.type === 'ed25519' && edCompat !== undefined)
73402 return (new edCompat.Signer(this, hashAlgo));
73403 if (this.type === 'curve25519')
73404 throw (new Error('Curve25519 keys are not suitable for ' +
73405 'signing or verification'));
73406
73407 var v, nm, err;
73408 try {
73409 nm = hashAlgo.toUpperCase();
73410 v = crypto.createSign(nm);
73411 } catch (e) {
73412 err = e;
73413 }
73414 if (v === undefined || (err instanceof Error &&
73415 err.message.match(/Unknown message digest/))) {
73416 nm = 'RSA-';
73417 nm += hashAlgo.toUpperCase();
73418 v = crypto.createSign(nm);
73419 }
73420 assert.ok(v, 'failed to create verifier');
73421 var oldSign = v.sign.bind(v);
73422 var key = this.toBuffer('pkcs1');
73423 var type = this.type;
73424 var curve = this.curve;
73425 v.sign = function () {
73426 var sig = oldSign(key);
73427 if (typeof (sig) === 'string')
73428 sig = Buffer.from(sig, 'binary');
73429 sig = Signature.parse(sig, type, 'asn1');
73430 sig.hashAlgorithm = hashAlgo;
73431 sig.curve = curve;
73432 return (sig);
73433 };
73434 return (v);
73435};
73436
73437PrivateKey.parse = function (data, format, options) {
73438 if (typeof (data) !== 'string')
73439 assert.buffer(data, 'data');
73440 if (format === undefined)
73441 format = 'auto';
73442 assert.string(format, 'format');
73443 if (typeof (options) === 'string')
73444 options = { filename: options };
73445 assert.optionalObject(options, 'options');
73446 if (options === undefined)
73447 options = {};
73448 assert.optionalString(options.filename, 'options.filename');
73449 if (options.filename === undefined)
73450 options.filename = '(unnamed)';
73451
73452 assert.object(formats[format], 'formats[format]');
73453
73454 try {
73455 var k = formats[format].read(data, options);
73456 assert.ok(k instanceof PrivateKey, 'key is not a private key');
73457 if (!k.comment)
73458 k.comment = options.filename;
73459 return (k);
73460 } catch (e) {
73461 if (e.name === 'KeyEncryptedError')
73462 throw (e);
73463 throw (new KeyParseError(options.filename, format, e));
73464 }
73465};
73466
73467PrivateKey.isPrivateKey = function (obj, ver) {
73468 return (utils.isCompatible(obj, PrivateKey, ver));
73469};
73470
73471PrivateKey.generate = function (type, options) {
73472 if (options === undefined)
73473 options = {};
73474 assert.object(options, 'options');
73475
73476 switch (type) {
73477 case 'ecdsa':
73478 if (options.curve === undefined)
73479 options.curve = 'nistp256';
73480 assert.string(options.curve, 'options.curve');
73481 return (generateECDSA(options.curve));
73482 case 'ed25519':
73483 return (generateED25519());
73484 default:
73485 throw (new Error('Key generation not supported with key ' +
73486 'type "' + type + '"'));
73487 }
73488};
73489
73490/*
73491 * API versions for PrivateKey:
73492 * [1,0] -- initial ver
73493 * [1,1] -- added auto, pkcs[18], openssh/ssh-private formats
73494 * [1,2] -- added defaultHashAlgorithm
73495 * [1,3] -- added derive, ed, createDH
73496 * [1,4] -- first tagged version
73497 * [1,5] -- changed ed25519 part names and format
73498 * [1,6] -- type arguments for hash() and fingerprint()
73499 */
73500PrivateKey.prototype._sshpkApiVersion = [1, 6];
73501
73502PrivateKey._oldVersionDetect = function (obj) {
73503 assert.func(obj.toPublic);
73504 assert.func(obj.createSign);
73505 if (obj.derive)
73506 return ([1, 3]);
73507 if (obj.defaultHashAlgorithm)
73508 return ([1, 2]);
73509 if (obj.formats['auto'])
73510 return ([1, 1]);
73511 return ([1, 0]);
73512};
73513
73514},{"./algs":335,"./dhe":337,"./ed-compat":338,"./errors":339,"./fingerprint":340,"./formats/auto":341,"./formats/dnssec":342,"./formats/pem":344,"./formats/pkcs1":345,"./formats/pkcs8":346,"./formats/rfc4253":348,"./formats/ssh-private":349,"./key":355,"./signature":357,"./utils":359,"assert-plus":67,"crypto":126,"safer-buffer":326,"tweetnacl":391,"util":397}],357:[function(require,module,exports){
73515// Copyright 2015 Joyent, Inc.
73516
73517module.exports = Signature;
73518
73519var assert = require('assert-plus');
73520var Buffer = require('safer-buffer').Buffer;
73521var algs = require('./algs');
73522var crypto = require('crypto');
73523var errs = require('./errors');
73524var utils = require('./utils');
73525var asn1 = require('asn1');
73526var SSHBuffer = require('./ssh-buffer');
73527
73528var InvalidAlgorithmError = errs.InvalidAlgorithmError;
73529var SignatureParseError = errs.SignatureParseError;
73530
73531function Signature(opts) {
73532 assert.object(opts, 'options');
73533 assert.arrayOfObject(opts.parts, 'options.parts');
73534 assert.string(opts.type, 'options.type');
73535
73536 var partLookup = {};
73537 for (var i = 0; i < opts.parts.length; ++i) {
73538 var part = opts.parts[i];
73539 partLookup[part.name] = part;
73540 }
73541
73542 this.type = opts.type;
73543 this.hashAlgorithm = opts.hashAlgo;
73544 this.curve = opts.curve;
73545 this.parts = opts.parts;
73546 this.part = partLookup;
73547}
73548
73549Signature.prototype.toBuffer = function (format) {
73550 if (format === undefined)
73551 format = 'asn1';
73552 assert.string(format, 'format');
73553
73554 var buf;
73555 var stype = 'ssh-' + this.type;
73556
73557 switch (this.type) {
73558 case 'rsa':
73559 switch (this.hashAlgorithm) {
73560 case 'sha256':
73561 stype = 'rsa-sha2-256';
73562 break;
73563 case 'sha512':
73564 stype = 'rsa-sha2-512';
73565 break;
73566 case 'sha1':
73567 case undefined:
73568 break;
73569 default:
73570 throw (new Error('SSH signature ' +
73571 'format does not support hash ' +
73572 'algorithm ' + this.hashAlgorithm));
73573 }
73574 if (format === 'ssh') {
73575 buf = new SSHBuffer({});
73576 buf.writeString(stype);
73577 buf.writePart(this.part.sig);
73578 return (buf.toBuffer());
73579 } else {
73580 return (this.part.sig.data);
73581 }
73582 break;
73583
73584 case 'ed25519':
73585 if (format === 'ssh') {
73586 buf = new SSHBuffer({});
73587 buf.writeString(stype);
73588 buf.writePart(this.part.sig);
73589 return (buf.toBuffer());
73590 } else {
73591 return (this.part.sig.data);
73592 }
73593 break;
73594
73595 case 'dsa':
73596 case 'ecdsa':
73597 var r, s;
73598 if (format === 'asn1') {
73599 var der = new asn1.BerWriter();
73600 der.startSequence();
73601 r = utils.mpNormalize(this.part.r.data);
73602 s = utils.mpNormalize(this.part.s.data);
73603 der.writeBuffer(r, asn1.Ber.Integer);
73604 der.writeBuffer(s, asn1.Ber.Integer);
73605 der.endSequence();
73606 return (der.buffer);
73607 } else if (format === 'ssh' && this.type === 'dsa') {
73608 buf = new SSHBuffer({});
73609 buf.writeString('ssh-dss');
73610 r = this.part.r.data;
73611 if (r.length > 20 && r[0] === 0x00)
73612 r = r.slice(1);
73613 s = this.part.s.data;
73614 if (s.length > 20 && s[0] === 0x00)
73615 s = s.slice(1);
73616 if ((this.hashAlgorithm &&
73617 this.hashAlgorithm !== 'sha1') ||
73618 r.length + s.length !== 40) {
73619 throw (new Error('OpenSSH only supports ' +
73620 'DSA signatures with SHA1 hash'));
73621 }
73622 buf.writeBuffer(Buffer.concat([r, s]));
73623 return (buf.toBuffer());
73624 } else if (format === 'ssh' && this.type === 'ecdsa') {
73625 var inner = new SSHBuffer({});
73626 r = this.part.r.data;
73627 inner.writeBuffer(r);
73628 inner.writePart(this.part.s);
73629
73630 buf = new SSHBuffer({});
73631 /* XXX: find a more proper way to do this? */
73632 var curve;
73633 if (r[0] === 0x00)
73634 r = r.slice(1);
73635 var sz = r.length * 8;
73636 if (sz === 256)
73637 curve = 'nistp256';
73638 else if (sz === 384)
73639 curve = 'nistp384';
73640 else if (sz === 528)
73641 curve = 'nistp521';
73642 buf.writeString('ecdsa-sha2-' + curve);
73643 buf.writeBuffer(inner.toBuffer());
73644 return (buf.toBuffer());
73645 }
73646 throw (new Error('Invalid signature format'));
73647 default:
73648 throw (new Error('Invalid signature data'));
73649 }
73650};
73651
73652Signature.prototype.toString = function (format) {
73653 assert.optionalString(format, 'format');
73654 return (this.toBuffer(format).toString('base64'));
73655};
73656
73657Signature.parse = function (data, type, format) {
73658 if (typeof (data) === 'string')
73659 data = Buffer.from(data, 'base64');
73660 assert.buffer(data, 'data');
73661 assert.string(format, 'format');
73662 assert.string(type, 'type');
73663
73664 var opts = {};
73665 opts.type = type.toLowerCase();
73666 opts.parts = [];
73667
73668 try {
73669 assert.ok(data.length > 0, 'signature must not be empty');
73670 switch (opts.type) {
73671 case 'rsa':
73672 return (parseOneNum(data, type, format, opts));
73673 case 'ed25519':
73674 return (parseOneNum(data, type, format, opts));
73675
73676 case 'dsa':
73677 case 'ecdsa':
73678 if (format === 'asn1')
73679 return (parseDSAasn1(data, type, format, opts));
73680 else if (opts.type === 'dsa')
73681 return (parseDSA(data, type, format, opts));
73682 else
73683 return (parseECDSA(data, type, format, opts));
73684
73685 default:
73686 throw (new InvalidAlgorithmError(type));
73687 }
73688
73689 } catch (e) {
73690 if (e instanceof InvalidAlgorithmError)
73691 throw (e);
73692 throw (new SignatureParseError(type, format, e));
73693 }
73694};
73695
73696function parseOneNum(data, type, format, opts) {
73697 if (format === 'ssh') {
73698 try {
73699 var buf = new SSHBuffer({buffer: data});
73700 var head = buf.readString();
73701 } catch (e) {
73702 /* fall through */
73703 }
73704 if (buf !== undefined) {
73705 var msg = 'SSH signature does not match expected ' +
73706 'type (expected ' + type + ', got ' + head + ')';
73707 switch (head) {
73708 case 'ssh-rsa':
73709 assert.strictEqual(type, 'rsa', msg);
73710 opts.hashAlgo = 'sha1';
73711 break;
73712 case 'rsa-sha2-256':
73713 assert.strictEqual(type, 'rsa', msg);
73714 opts.hashAlgo = 'sha256';
73715 break;
73716 case 'rsa-sha2-512':
73717 assert.strictEqual(type, 'rsa', msg);
73718 opts.hashAlgo = 'sha512';
73719 break;
73720 case 'ssh-ed25519':
73721 assert.strictEqual(type, 'ed25519', msg);
73722 opts.hashAlgo = 'sha512';
73723 break;
73724 default:
73725 throw (new Error('Unknown SSH signature ' +
73726 'type: ' + head));
73727 }
73728 var sig = buf.readPart();
73729 assert.ok(buf.atEnd(), 'extra trailing bytes');
73730 sig.name = 'sig';
73731 opts.parts.push(sig);
73732 return (new Signature(opts));
73733 }
73734 }
73735 opts.parts.push({name: 'sig', data: data});
73736 return (new Signature(opts));
73737}
73738
73739function parseDSAasn1(data, type, format, opts) {
73740 var der = new asn1.BerReader(data);
73741 der.readSequence();
73742 var r = der.readString(asn1.Ber.Integer, true);
73743 var s = der.readString(asn1.Ber.Integer, true);
73744
73745 opts.parts.push({name: 'r', data: utils.mpNormalize(r)});
73746 opts.parts.push({name: 's', data: utils.mpNormalize(s)});
73747
73748 return (new Signature(opts));
73749}
73750
73751function parseDSA(data, type, format, opts) {
73752 if (data.length != 40) {
73753 var buf = new SSHBuffer({buffer: data});
73754 var d = buf.readBuffer();
73755 if (d.toString('ascii') === 'ssh-dss')
73756 d = buf.readBuffer();
73757 assert.ok(buf.atEnd(), 'extra trailing bytes');
73758 assert.strictEqual(d.length, 40, 'invalid inner length');
73759 data = d;
73760 }
73761 opts.parts.push({name: 'r', data: data.slice(0, 20)});
73762 opts.parts.push({name: 's', data: data.slice(20, 40)});
73763 return (new Signature(opts));
73764}
73765
73766function parseECDSA(data, type, format, opts) {
73767 var buf = new SSHBuffer({buffer: data});
73768
73769 var r, s;
73770 var inner = buf.readBuffer();
73771 var stype = inner.toString('ascii');
73772 if (stype.slice(0, 6) === 'ecdsa-') {
73773 var parts = stype.split('-');
73774 assert.strictEqual(parts[0], 'ecdsa');
73775 assert.strictEqual(parts[1], 'sha2');
73776 opts.curve = parts[2];
73777 switch (opts.curve) {
73778 case 'nistp256':
73779 opts.hashAlgo = 'sha256';
73780 break;
73781 case 'nistp384':
73782 opts.hashAlgo = 'sha384';
73783 break;
73784 case 'nistp521':
73785 opts.hashAlgo = 'sha512';
73786 break;
73787 default:
73788 throw (new Error('Unsupported ECDSA curve: ' +
73789 opts.curve));
73790 }
73791 inner = buf.readBuffer();
73792 assert.ok(buf.atEnd(), 'extra trailing bytes on outer');
73793 buf = new SSHBuffer({buffer: inner});
73794 r = buf.readPart();
73795 } else {
73796 r = {data: inner};
73797 }
73798
73799 s = buf.readPart();
73800 assert.ok(buf.atEnd(), 'extra trailing bytes');
73801
73802 r.name = 'r';
73803 s.name = 's';
73804
73805 opts.parts.push(r);
73806 opts.parts.push(s);
73807 return (new Signature(opts));
73808}
73809
73810Signature.isSignature = function (obj, ver) {
73811 return (utils.isCompatible(obj, Signature, ver));
73812};
73813
73814/*
73815 * API versions for Signature:
73816 * [1,0] -- initial ver
73817 * [2,0] -- support for rsa in full ssh format, compat with sshpk-agent
73818 * hashAlgorithm property
73819 * [2,1] -- first tagged version
73820 */
73821Signature.prototype._sshpkApiVersion = [2, 1];
73822
73823Signature._oldVersionDetect = function (obj) {
73824 assert.func(obj.toBuffer);
73825 if (obj.hasOwnProperty('hashAlgorithm'))
73826 return ([2, 0]);
73827 return ([1, 0]);
73828};
73829
73830},{"./algs":335,"./errors":339,"./ssh-buffer":358,"./utils":359,"asn1":66,"assert-plus":67,"crypto":126,"safer-buffer":326}],358:[function(require,module,exports){
73831// Copyright 2015 Joyent, Inc.
73832
73833module.exports = SSHBuffer;
73834
73835var assert = require('assert-plus');
73836var Buffer = require('safer-buffer').Buffer;
73837
73838function SSHBuffer(opts) {
73839 assert.object(opts, 'options');
73840 if (opts.buffer !== undefined)
73841 assert.buffer(opts.buffer, 'options.buffer');
73842
73843 this._size = opts.buffer ? opts.buffer.length : 1024;
73844 this._buffer = opts.buffer || Buffer.alloc(this._size);
73845 this._offset = 0;
73846}
73847
73848SSHBuffer.prototype.toBuffer = function () {
73849 return (this._buffer.slice(0, this._offset));
73850};
73851
73852SSHBuffer.prototype.atEnd = function () {
73853 return (this._offset >= this._buffer.length);
73854};
73855
73856SSHBuffer.prototype.remainder = function () {
73857 return (this._buffer.slice(this._offset));
73858};
73859
73860SSHBuffer.prototype.skip = function (n) {
73861 this._offset += n;
73862};
73863
73864SSHBuffer.prototype.expand = function () {
73865 this._size *= 2;
73866 var buf = Buffer.alloc(this._size);
73867 this._buffer.copy(buf, 0);
73868 this._buffer = buf;
73869};
73870
73871SSHBuffer.prototype.readPart = function () {
73872 return ({data: this.readBuffer()});
73873};
73874
73875SSHBuffer.prototype.readBuffer = function () {
73876 var len = this._buffer.readUInt32BE(this._offset);
73877 this._offset += 4;
73878 assert.ok(this._offset + len <= this._buffer.length,
73879 'length out of bounds at +0x' + this._offset.toString(16) +
73880 ' (data truncated?)');
73881 var buf = this._buffer.slice(this._offset, this._offset + len);
73882 this._offset += len;
73883 return (buf);
73884};
73885
73886SSHBuffer.prototype.readString = function () {
73887 return (this.readBuffer().toString());
73888};
73889
73890SSHBuffer.prototype.readCString = function () {
73891 var offset = this._offset;
73892 while (offset < this._buffer.length &&
73893 this._buffer[offset] !== 0x00)
73894 offset++;
73895 assert.ok(offset < this._buffer.length, 'c string does not terminate');
73896 var str = this._buffer.slice(this._offset, offset).toString();
73897 this._offset = offset + 1;
73898 return (str);
73899};
73900
73901SSHBuffer.prototype.readInt = function () {
73902 var v = this._buffer.readUInt32BE(this._offset);
73903 this._offset += 4;
73904 return (v);
73905};
73906
73907SSHBuffer.prototype.readInt64 = function () {
73908 assert.ok(this._offset + 8 < this._buffer.length,
73909 'buffer not long enough to read Int64');
73910 var v = this._buffer.slice(this._offset, this._offset + 8);
73911 this._offset += 8;
73912 return (v);
73913};
73914
73915SSHBuffer.prototype.readChar = function () {
73916 var v = this._buffer[this._offset++];
73917 return (v);
73918};
73919
73920SSHBuffer.prototype.writeBuffer = function (buf) {
73921 while (this._offset + 4 + buf.length > this._size)
73922 this.expand();
73923 this._buffer.writeUInt32BE(buf.length, this._offset);
73924 this._offset += 4;
73925 buf.copy(this._buffer, this._offset);
73926 this._offset += buf.length;
73927};
73928
73929SSHBuffer.prototype.writeString = function (str) {
73930 this.writeBuffer(Buffer.from(str, 'utf8'));
73931};
73932
73933SSHBuffer.prototype.writeCString = function (str) {
73934 while (this._offset + 1 + str.length > this._size)
73935 this.expand();
73936 this._buffer.write(str, this._offset);
73937 this._offset += str.length;
73938 this._buffer[this._offset++] = 0;
73939};
73940
73941SSHBuffer.prototype.writeInt = function (v) {
73942 while (this._offset + 4 > this._size)
73943 this.expand();
73944 this._buffer.writeUInt32BE(v, this._offset);
73945 this._offset += 4;
73946};
73947
73948SSHBuffer.prototype.writeInt64 = function (v) {
73949 assert.buffer(v, 'value');
73950 if (v.length > 8) {
73951 var lead = v.slice(0, v.length - 8);
73952 for (var i = 0; i < lead.length; ++i) {
73953 assert.strictEqual(lead[i], 0,
73954 'must fit in 64 bits of precision');
73955 }
73956 v = v.slice(v.length - 8, v.length);
73957 }
73958 while (this._offset + 8 > this._size)
73959 this.expand();
73960 v.copy(this._buffer, this._offset);
73961 this._offset += 8;
73962};
73963
73964SSHBuffer.prototype.writeChar = function (v) {
73965 while (this._offset + 1 > this._size)
73966 this.expand();
73967 this._buffer[this._offset++] = v;
73968};
73969
73970SSHBuffer.prototype.writePart = function (p) {
73971 this.writeBuffer(p.data);
73972};
73973
73974SSHBuffer.prototype.write = function (buf) {
73975 while (this._offset + buf.length > this._size)
73976 this.expand();
73977 buf.copy(this._buffer, this._offset);
73978 this._offset += buf.length;
73979};
73980
73981},{"assert-plus":67,"safer-buffer":326}],359:[function(require,module,exports){
73982// Copyright 2015 Joyent, Inc.
73983
73984module.exports = {
73985 bufferSplit: bufferSplit,
73986 addRSAMissing: addRSAMissing,
73987 calculateDSAPublic: calculateDSAPublic,
73988 calculateED25519Public: calculateED25519Public,
73989 calculateX25519Public: calculateX25519Public,
73990 mpNormalize: mpNormalize,
73991 mpDenormalize: mpDenormalize,
73992 ecNormalize: ecNormalize,
73993 countZeros: countZeros,
73994 assertCompatible: assertCompatible,
73995 isCompatible: isCompatible,
73996 opensslKeyDeriv: opensslKeyDeriv,
73997 opensshCipherInfo: opensshCipherInfo,
73998 publicFromPrivateECDSA: publicFromPrivateECDSA,
73999 zeroPadToLength: zeroPadToLength,
74000 writeBitString: writeBitString,
74001 readBitString: readBitString,
74002 pbkdf2: pbkdf2
74003};
74004
74005var assert = require('assert-plus');
74006var Buffer = require('safer-buffer').Buffer;
74007var PrivateKey = require('./private-key');
74008var Key = require('./key');
74009var crypto = require('crypto');
74010var algs = require('./algs');
74011var asn1 = require('asn1');
74012
74013var ec = require('ecc-jsbn/lib/ec');
74014var jsbn = require('jsbn').BigInteger;
74015var nacl = require('tweetnacl');
74016
74017var MAX_CLASS_DEPTH = 3;
74018
74019function isCompatible(obj, klass, needVer) {
74020 if (obj === null || typeof (obj) !== 'object')
74021 return (false);
74022 if (needVer === undefined)
74023 needVer = klass.prototype._sshpkApiVersion;
74024 if (obj instanceof klass &&
74025 klass.prototype._sshpkApiVersion[0] == needVer[0])
74026 return (true);
74027 var proto = Object.getPrototypeOf(obj);
74028 var depth = 0;
74029 while (proto.constructor.name !== klass.name) {
74030 proto = Object.getPrototypeOf(proto);
74031 if (!proto || ++depth > MAX_CLASS_DEPTH)
74032 return (false);
74033 }
74034 if (proto.constructor.name !== klass.name)
74035 return (false);
74036 var ver = proto._sshpkApiVersion;
74037 if (ver === undefined)
74038 ver = klass._oldVersionDetect(obj);
74039 if (ver[0] != needVer[0] || ver[1] < needVer[1])
74040 return (false);
74041 return (true);
74042}
74043
74044function assertCompatible(obj, klass, needVer, name) {
74045 if (name === undefined)
74046 name = 'object';
74047 assert.ok(obj, name + ' must not be null');
74048 assert.object(obj, name + ' must be an object');
74049 if (needVer === undefined)
74050 needVer = klass.prototype._sshpkApiVersion;
74051 if (obj instanceof klass &&
74052 klass.prototype._sshpkApiVersion[0] == needVer[0])
74053 return;
74054 var proto = Object.getPrototypeOf(obj);
74055 var depth = 0;
74056 while (proto.constructor.name !== klass.name) {
74057 proto = Object.getPrototypeOf(proto);
74058 assert.ok(proto && ++depth <= MAX_CLASS_DEPTH,
74059 name + ' must be a ' + klass.name + ' instance');
74060 }
74061 assert.strictEqual(proto.constructor.name, klass.name,
74062 name + ' must be a ' + klass.name + ' instance');
74063 var ver = proto._sshpkApiVersion;
74064 if (ver === undefined)
74065 ver = klass._oldVersionDetect(obj);
74066 assert.ok(ver[0] == needVer[0] && ver[1] >= needVer[1],
74067 name + ' must be compatible with ' + klass.name + ' klass ' +
74068 'version ' + needVer[0] + '.' + needVer[1]);
74069}
74070
74071var CIPHER_LEN = {
74072 'des-ede3-cbc': { key: 24, iv: 8 },
74073 'aes-128-cbc': { key: 16, iv: 16 },
74074 'aes-256-cbc': { key: 32, iv: 16 }
74075};
74076var PKCS5_SALT_LEN = 8;
74077
74078function opensslKeyDeriv(cipher, salt, passphrase, count) {
74079 assert.buffer(salt, 'salt');
74080 assert.buffer(passphrase, 'passphrase');
74081 assert.number(count, 'iteration count');
74082
74083 var clen = CIPHER_LEN[cipher];
74084 assert.object(clen, 'supported cipher');
74085
74086 salt = salt.slice(0, PKCS5_SALT_LEN);
74087
74088 var D, D_prev, bufs;
74089 var material = Buffer.alloc(0);
74090 while (material.length < clen.key + clen.iv) {
74091 bufs = [];
74092 if (D_prev)
74093 bufs.push(D_prev);
74094 bufs.push(passphrase);
74095 bufs.push(salt);
74096 D = Buffer.concat(bufs);
74097 for (var j = 0; j < count; ++j)
74098 D = crypto.createHash('md5').update(D).digest();
74099 material = Buffer.concat([material, D]);
74100 D_prev = D;
74101 }
74102
74103 return ({
74104 key: material.slice(0, clen.key),
74105 iv: material.slice(clen.key, clen.key + clen.iv)
74106 });
74107}
74108
74109/* See: RFC2898 */
74110function pbkdf2(hashAlg, salt, iterations, size, passphrase) {
74111 var hkey = Buffer.alloc(salt.length + 4);
74112 salt.copy(hkey);
74113
74114 var gen = 0, ts = [];
74115 var i = 1;
74116 while (gen < size) {
74117 var t = T(i++);
74118 gen += t.length;
74119 ts.push(t);
74120 }
74121 return (Buffer.concat(ts).slice(0, size));
74122
74123 function T(I) {
74124 hkey.writeUInt32BE(I, hkey.length - 4);
74125
74126 var hmac = crypto.createHmac(hashAlg, passphrase);
74127 hmac.update(hkey);
74128
74129 var Ti = hmac.digest();
74130 var Uc = Ti;
74131 var c = 1;
74132 while (c++ < iterations) {
74133 hmac = crypto.createHmac(hashAlg, passphrase);
74134 hmac.update(Uc);
74135 Uc = hmac.digest();
74136 for (var x = 0; x < Ti.length; ++x)
74137 Ti[x] ^= Uc[x];
74138 }
74139 return (Ti);
74140 }
74141}
74142
74143/* Count leading zero bits on a buffer */
74144function countZeros(buf) {
74145 var o = 0, obit = 8;
74146 while (o < buf.length) {
74147 var mask = (1 << obit);
74148 if ((buf[o] & mask) === mask)
74149 break;
74150 obit--;
74151 if (obit < 0) {
74152 o++;
74153 obit = 8;
74154 }
74155 }
74156 return (o*8 + (8 - obit) - 1);
74157}
74158
74159function bufferSplit(buf, chr) {
74160 assert.buffer(buf);
74161 assert.string(chr);
74162
74163 var parts = [];
74164 var lastPart = 0;
74165 var matches = 0;
74166 for (var i = 0; i < buf.length; ++i) {
74167 if (buf[i] === chr.charCodeAt(matches))
74168 ++matches;
74169 else if (buf[i] === chr.charCodeAt(0))
74170 matches = 1;
74171 else
74172 matches = 0;
74173
74174 if (matches >= chr.length) {
74175 var newPart = i + 1;
74176 parts.push(buf.slice(lastPart, newPart - matches));
74177 lastPart = newPart;
74178 matches = 0;
74179 }
74180 }
74181 if (lastPart <= buf.length)
74182 parts.push(buf.slice(lastPart, buf.length));
74183
74184 return (parts);
74185}
74186
74187function ecNormalize(buf, addZero) {
74188 assert.buffer(buf);
74189 if (buf[0] === 0x00 && buf[1] === 0x04) {
74190 if (addZero)
74191 return (buf);
74192 return (buf.slice(1));
74193 } else if (buf[0] === 0x04) {
74194 if (!addZero)
74195 return (buf);
74196 } else {
74197 while (buf[0] === 0x00)
74198 buf = buf.slice(1);
74199 if (buf[0] === 0x02 || buf[0] === 0x03)
74200 throw (new Error('Compressed elliptic curve points ' +
74201 'are not supported'));
74202 if (buf[0] !== 0x04)
74203 throw (new Error('Not a valid elliptic curve point'));
74204 if (!addZero)
74205 return (buf);
74206 }
74207 var b = Buffer.alloc(buf.length + 1);
74208 b[0] = 0x0;
74209 buf.copy(b, 1);
74210 return (b);
74211}
74212
74213function readBitString(der, tag) {
74214 if (tag === undefined)
74215 tag = asn1.Ber.BitString;
74216 var buf = der.readString(tag, true);
74217 assert.strictEqual(buf[0], 0x00, 'bit strings with unused bits are ' +
74218 'not supported (0x' + buf[0].toString(16) + ')');
74219 return (buf.slice(1));
74220}
74221
74222function writeBitString(der, buf, tag) {
74223 if (tag === undefined)
74224 tag = asn1.Ber.BitString;
74225 var b = Buffer.alloc(buf.length + 1);
74226 b[0] = 0x00;
74227 buf.copy(b, 1);
74228 der.writeBuffer(b, tag);
74229}
74230
74231function mpNormalize(buf) {
74232 assert.buffer(buf);
74233 while (buf.length > 1 && buf[0] === 0x00 && (buf[1] & 0x80) === 0x00)
74234 buf = buf.slice(1);
74235 if ((buf[0] & 0x80) === 0x80) {
74236 var b = Buffer.alloc(buf.length + 1);
74237 b[0] = 0x00;
74238 buf.copy(b, 1);
74239 buf = b;
74240 }
74241 return (buf);
74242}
74243
74244function mpDenormalize(buf) {
74245 assert.buffer(buf);
74246 while (buf.length > 1 && buf[0] === 0x00)
74247 buf = buf.slice(1);
74248 return (buf);
74249}
74250
74251function zeroPadToLength(buf, len) {
74252 assert.buffer(buf);
74253 assert.number(len);
74254 while (buf.length > len) {
74255 assert.equal(buf[0], 0x00);
74256 buf = buf.slice(1);
74257 }
74258 while (buf.length < len) {
74259 var b = Buffer.alloc(buf.length + 1);
74260 b[0] = 0x00;
74261 buf.copy(b, 1);
74262 buf = b;
74263 }
74264 return (buf);
74265}
74266
74267function bigintToMpBuf(bigint) {
74268 var buf = Buffer.from(bigint.toByteArray());
74269 buf = mpNormalize(buf);
74270 return (buf);
74271}
74272
74273function calculateDSAPublic(g, p, x) {
74274 assert.buffer(g);
74275 assert.buffer(p);
74276 assert.buffer(x);
74277 g = new jsbn(g);
74278 p = new jsbn(p);
74279 x = new jsbn(x);
74280 var y = g.modPow(x, p);
74281 var ybuf = bigintToMpBuf(y);
74282 return (ybuf);
74283}
74284
74285function calculateED25519Public(k) {
74286 assert.buffer(k);
74287
74288 var kp = nacl.sign.keyPair.fromSeed(new Uint8Array(k));
74289 return (Buffer.from(kp.publicKey));
74290}
74291
74292function calculateX25519Public(k) {
74293 assert.buffer(k);
74294
74295 var kp = nacl.box.keyPair.fromSeed(new Uint8Array(k));
74296 return (Buffer.from(kp.publicKey));
74297}
74298
74299function addRSAMissing(key) {
74300 assert.object(key);
74301 assertCompatible(key, PrivateKey, [1, 1]);
74302
74303 var d = new jsbn(key.part.d.data);
74304 var buf;
74305
74306 if (!key.part.dmodp) {
74307 var p = new jsbn(key.part.p.data);
74308 var dmodp = d.mod(p.subtract(1));
74309
74310 buf = bigintToMpBuf(dmodp);
74311 key.part.dmodp = {name: 'dmodp', data: buf};
74312 key.parts.push(key.part.dmodp);
74313 }
74314 if (!key.part.dmodq) {
74315 var q = new jsbn(key.part.q.data);
74316 var dmodq = d.mod(q.subtract(1));
74317
74318 buf = bigintToMpBuf(dmodq);
74319 key.part.dmodq = {name: 'dmodq', data: buf};
74320 key.parts.push(key.part.dmodq);
74321 }
74322}
74323
74324function publicFromPrivateECDSA(curveName, priv) {
74325 assert.string(curveName, 'curveName');
74326 assert.buffer(priv);
74327 var params = algs.curves[curveName];
74328 var p = new jsbn(params.p);
74329 var a = new jsbn(params.a);
74330 var b = new jsbn(params.b);
74331 var curve = new ec.ECCurveFp(p, a, b);
74332 var G = curve.decodePointHex(params.G.toString('hex'));
74333
74334 var d = new jsbn(mpNormalize(priv));
74335 var pub = G.multiply(d);
74336 pub = Buffer.from(curve.encodePointHex(pub), 'hex');
74337
74338 var parts = [];
74339 parts.push({name: 'curve', data: Buffer.from(curveName)});
74340 parts.push({name: 'Q', data: pub});
74341
74342 var key = new Key({type: 'ecdsa', curve: curve, parts: parts});
74343 return (key);
74344}
74345
74346function opensshCipherInfo(cipher) {
74347 var inf = {};
74348 switch (cipher) {
74349 case '3des-cbc':
74350 inf.keySize = 24;
74351 inf.blockSize = 8;
74352 inf.opensslName = 'des-ede3-cbc';
74353 break;
74354 case 'blowfish-cbc':
74355 inf.keySize = 16;
74356 inf.blockSize = 8;
74357 inf.opensslName = 'bf-cbc';
74358 break;
74359 case 'aes128-cbc':
74360 case 'aes128-ctr':
74361 case 'aes128-gcm@openssh.com':
74362 inf.keySize = 16;
74363 inf.blockSize = 16;
74364 inf.opensslName = 'aes-128-' + cipher.slice(7, 10);
74365 break;
74366 case 'aes192-cbc':
74367 case 'aes192-ctr':
74368 case 'aes192-gcm@openssh.com':
74369 inf.keySize = 24;
74370 inf.blockSize = 16;
74371 inf.opensslName = 'aes-192-' + cipher.slice(7, 10);
74372 break;
74373 case 'aes256-cbc':
74374 case 'aes256-ctr':
74375 case 'aes256-gcm@openssh.com':
74376 inf.keySize = 32;
74377 inf.blockSize = 16;
74378 inf.opensslName = 'aes-256-' + cipher.slice(7, 10);
74379 break;
74380 default:
74381 throw (new Error(
74382 'Unsupported openssl cipher "' + cipher + '"'));
74383 }
74384 return (inf);
74385}
74386
74387},{"./algs":335,"./key":355,"./private-key":356,"asn1":66,"assert-plus":67,"crypto":126,"ecc-jsbn/lib/ec":140,"jsbn":215,"safer-buffer":326,"tweetnacl":391}],360:[function(require,module,exports){
74388'use strict';
74389
74390var isNative = /\.node$/;
74391
74392function forEach(obj, callback) {
74393 for ( var key in obj ) {
74394 if (!Object.prototype.hasOwnProperty.call(obj, key)) {
74395 continue;
74396 }
74397 callback(key);
74398 }
74399}
74400
74401function assign(target, source) {
74402 forEach(source, function (key) {
74403 target[key] = source[key];
74404 });
74405 return target;
74406}
74407
74408function clearCache(requireCache) {
74409 forEach(requireCache, function (resolvedPath) {
74410 if (!isNative.test(resolvedPath)) {
74411 delete requireCache[resolvedPath];
74412 }
74413 });
74414}
74415
74416module.exports = function (requireCache, callback, callbackForModulesToKeep, module) {
74417
74418 var originalCache = assign({}, requireCache);
74419 clearCache(requireCache);
74420
74421 if (callbackForModulesToKeep) {
74422
74423 var originalModuleChildren = module.children ? module.children.slice() : false; // Creates a shallow copy of module.children
74424
74425 callbackForModulesToKeep();
74426
74427 // Lists the cache entries made by callbackForModulesToKeep()
74428 var modulesToKeep = [];
74429 forEach(requireCache, function (key) {
74430 modulesToKeep.push(key);
74431 });
74432
74433 // Discards the modules required in callbackForModulesToKeep()
74434 clearCache(requireCache);
74435
74436 if (module.children) { // Only true for node.js
74437 module.children = originalModuleChildren; // Removes last references to modules required in callbackForModulesToKeep() -> No memory leak
74438 }
74439
74440 // Takes the cache entries of the original cache in case the modules where required before
74441 for ( var i = 0; i < modulesToKeep.length; i+=1 ) {
74442 if (originalCache[modulesToKeep[i]]) {
74443 requireCache[modulesToKeep[i]] = originalCache[modulesToKeep[i]];
74444 }
74445 }
74446
74447 }
74448
74449 var freshModule = callback();
74450
74451 var stealthCache = callbackForModulesToKeep ? assign({}, requireCache) : false;
74452
74453 clearCache(requireCache);
74454
74455 if (callbackForModulesToKeep) {
74456 // In case modules to keep were required inside the stealthy require for the first time, copy them to the restored cache
74457 for ( var k = 0; k < modulesToKeep.length; k+=1 ) {
74458 if (stealthCache[modulesToKeep[k]]) {
74459 requireCache[modulesToKeep[k]] = stealthCache[modulesToKeep[k]];
74460 }
74461 }
74462 }
74463
74464 assign(requireCache, originalCache);
74465
74466 return freshModule;
74467
74468};
74469
74470},{}],361:[function(require,module,exports){
74471// Copyright Joyent, Inc. and other Node contributors.
74472//
74473// Permission is hereby granted, free of charge, to any person obtaining a
74474// copy of this software and associated documentation files (the
74475// "Software"), to deal in the Software without restriction, including
74476// without limitation the rights to use, copy, modify, merge, publish,
74477// distribute, sublicense, and/or sell copies of the Software, and to permit
74478// persons to whom the Software is furnished to do so, subject to the
74479// following conditions:
74480//
74481// The above copyright notice and this permission notice shall be included
74482// in all copies or substantial portions of the Software.
74483//
74484// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
74485// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
74486// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
74487// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
74488// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
74489// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
74490// USE OR OTHER DEALINGS IN THE SOFTWARE.
74491
74492module.exports = Stream;
74493
74494var EE = require('events').EventEmitter;
74495var inherits = require('inherits');
74496
74497inherits(Stream, EE);
74498Stream.Readable = require('readable-stream/readable.js');
74499Stream.Writable = require('readable-stream/writable.js');
74500Stream.Duplex = require('readable-stream/duplex.js');
74501Stream.Transform = require('readable-stream/transform.js');
74502Stream.PassThrough = require('readable-stream/passthrough.js');
74503
74504// Backwards-compat with node 0.4.x
74505Stream.Stream = Stream;
74506
74507
74508
74509// old-style streams. Note that the pipe method (the only relevant
74510// part of this class) is overridden in the Readable class.
74511
74512function Stream() {
74513 EE.call(this);
74514}
74515
74516Stream.prototype.pipe = function(dest, options) {
74517 var source = this;
74518
74519 function ondata(chunk) {
74520 if (dest.writable) {
74521 if (false === dest.write(chunk) && source.pause) {
74522 source.pause();
74523 }
74524 }
74525 }
74526
74527 source.on('data', ondata);
74528
74529 function ondrain() {
74530 if (source.readable && source.resume) {
74531 source.resume();
74532 }
74533 }
74534
74535 dest.on('drain', ondrain);
74536
74537 // If the 'end' option is not supplied, dest.end() will be called when
74538 // source gets the 'end' or 'close' events. Only dest.end() once.
74539 if (!dest._isStdio && (!options || options.end !== false)) {
74540 source.on('end', onend);
74541 source.on('close', onclose);
74542 }
74543
74544 var didOnEnd = false;
74545 function onend() {
74546 if (didOnEnd) return;
74547 didOnEnd = true;
74548
74549 dest.end();
74550 }
74551
74552
74553 function onclose() {
74554 if (didOnEnd) return;
74555 didOnEnd = true;
74556
74557 if (typeof dest.destroy === 'function') dest.destroy();
74558 }
74559
74560 // don't leave dangling pipes when there are errors.
74561 function onerror(er) {
74562 cleanup();
74563 if (EE.listenerCount(this, 'error') === 0) {
74564 throw er; // Unhandled stream error in pipe.
74565 }
74566 }
74567
74568 source.on('error', onerror);
74569 dest.on('error', onerror);
74570
74571 // remove all the event listeners that were added.
74572 function cleanup() {
74573 source.removeListener('data', ondata);
74574 dest.removeListener('drain', ondrain);
74575
74576 source.removeListener('end', onend);
74577 source.removeListener('close', onclose);
74578
74579 source.removeListener('error', onerror);
74580 dest.removeListener('error', onerror);
74581
74582 source.removeListener('end', cleanup);
74583 source.removeListener('close', cleanup);
74584
74585 dest.removeListener('close', cleanup);
74586 }
74587
74588 source.on('end', cleanup);
74589 source.on('close', cleanup);
74590
74591 dest.on('close', cleanup);
74592
74593 dest.emit('pipe', source);
74594
74595 // Allow for unix-like usage: A.pipe(B).pipe(C)
74596 return dest;
74597};
74598
74599},{"events":159,"inherits":210,"readable-stream/duplex.js":280,"readable-stream/passthrough.js":290,"readable-stream/readable.js":291,"readable-stream/transform.js":292,"readable-stream/writable.js":293}],362:[function(require,module,exports){
74600(function (global){
74601var ClientRequest = require('./lib/request')
74602var response = require('./lib/response')
74603var extend = require('xtend')
74604var statusCodes = require('builtin-status-codes')
74605var url = require('url')
74606
74607var http = exports
74608
74609http.request = function (opts, cb) {
74610 if (typeof opts === 'string')
74611 opts = url.parse(opts)
74612 else
74613 opts = extend(opts)
74614
74615 // Normally, the page is loaded from http or https, so not specifying a protocol
74616 // will result in a (valid) protocol-relative url. However, this won't work if
74617 // the protocol is something else, like 'file:'
74618 var defaultProtocol = global.location.protocol.search(/^https?:$/) === -1 ? 'http:' : ''
74619
74620 var protocol = opts.protocol || defaultProtocol
74621 var host = opts.hostname || opts.host
74622 var port = opts.port
74623 var path = opts.path || '/'
74624
74625 // Necessary for IPv6 addresses
74626 if (host && host.indexOf(':') !== -1)
74627 host = '[' + host + ']'
74628
74629 // This may be a relative url. The browser should always be able to interpret it correctly.
74630 opts.url = (host ? (protocol + '//' + host) : '') + (port ? ':' + port : '') + path
74631 opts.method = (opts.method || 'GET').toUpperCase()
74632 opts.headers = opts.headers || {}
74633
74634 // Also valid opts.auth, opts.mode
74635
74636 var req = new ClientRequest(opts)
74637 if (cb)
74638 req.on('response', cb)
74639 return req
74640}
74641
74642http.get = function get (opts, cb) {
74643 var req = http.request(opts, cb)
74644 req.end()
74645 return req
74646}
74647
74648http.ClientRequest = ClientRequest
74649http.IncomingMessage = response.IncomingMessage
74650
74651http.Agent = function () {}
74652http.Agent.defaultMaxSockets = 4
74653
74654http.globalAgent = new http.Agent()
74655
74656http.STATUS_CODES = statusCodes
74657
74658http.METHODS = [
74659 'CHECKOUT',
74660 'CONNECT',
74661 'COPY',
74662 'DELETE',
74663 'GET',
74664 'HEAD',
74665 'LOCK',
74666 'M-SEARCH',
74667 'MERGE',
74668 'MKACTIVITY',
74669 'MKCOL',
74670 'MOVE',
74671 'NOTIFY',
74672 'OPTIONS',
74673 'PATCH',
74674 'POST',
74675 'PROPFIND',
74676 'PROPPATCH',
74677 'PURGE',
74678 'PUT',
74679 'REPORT',
74680 'SEARCH',
74681 'SUBSCRIBE',
74682 'TRACE',
74683 'UNLOCK',
74684 'UNSUBSCRIBE'
74685]
74686}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
74687},{"./lib/request":364,"./lib/response":365,"builtin-status-codes":115,"url":393,"xtend":406}],363:[function(require,module,exports){
74688(function (global){
74689exports.fetch = isFunction(global.fetch) && isFunction(global.ReadableStream)
74690
74691exports.writableStream = isFunction(global.WritableStream)
74692
74693exports.abortController = isFunction(global.AbortController)
74694
74695// The xhr request to example.com may violate some restrictive CSP configurations,
74696// so if we're running in a browser that supports `fetch`, avoid calling getXHR()
74697// and assume support for certain features below.
74698var xhr
74699function getXHR () {
74700 // Cache the xhr value
74701 if (xhr !== undefined) return xhr
74702
74703 if (global.XMLHttpRequest) {
74704 xhr = new global.XMLHttpRequest()
74705 // If XDomainRequest is available (ie only, where xhr might not work
74706 // cross domain), use the page location. Otherwise use example.com
74707 // Note: this doesn't actually make an http request.
74708 try {
74709 xhr.open('GET', global.XDomainRequest ? '/' : 'https://example.com')
74710 } catch(e) {
74711 xhr = null
74712 }
74713 } else {
74714 // Service workers don't have XHR
74715 xhr = null
74716 }
74717 return xhr
74718}
74719
74720function checkTypeSupport (type) {
74721 var xhr = getXHR()
74722 if (!xhr) return false
74723 try {
74724 xhr.responseType = type
74725 return xhr.responseType === type
74726 } catch (e) {}
74727 return false
74728}
74729
74730// If fetch is supported, then arraybuffer will be supported too. Skip calling
74731// checkTypeSupport(), since that calls getXHR().
74732exports.arraybuffer = exports.fetch || checkTypeSupport('arraybuffer')
74733
74734// These next two tests unavoidably show warnings in Chrome. Since fetch will always
74735// be used if it's available, just return false for these to avoid the warnings.
74736exports.msstream = !exports.fetch && checkTypeSupport('ms-stream')
74737exports.mozchunkedarraybuffer = !exports.fetch && checkTypeSupport('moz-chunked-arraybuffer')
74738
74739// If fetch is supported, then overrideMimeType will be supported too. Skip calling
74740// getXHR().
74741exports.overrideMimeType = exports.fetch || (getXHR() ? isFunction(getXHR().overrideMimeType) : false)
74742
74743function isFunction (value) {
74744 return typeof value === 'function'
74745}
74746
74747xhr = null // Help gc
74748
74749}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
74750},{}],364:[function(require,module,exports){
74751(function (process,global,Buffer){
74752var capability = require('./capability')
74753var inherits = require('inherits')
74754var response = require('./response')
74755var stream = require('readable-stream')
74756
74757var IncomingMessage = response.IncomingMessage
74758var rStates = response.readyStates
74759
74760function decideMode (preferBinary, useFetch) {
74761 if (capability.fetch && useFetch) {
74762 return 'fetch'
74763 } else if (capability.mozchunkedarraybuffer) {
74764 return 'moz-chunked-arraybuffer'
74765 } else if (capability.msstream) {
74766 return 'ms-stream'
74767 } else if (capability.arraybuffer && preferBinary) {
74768 return 'arraybuffer'
74769 } else {
74770 return 'text'
74771 }
74772}
74773
74774var ClientRequest = module.exports = function (opts) {
74775 var self = this
74776 stream.Writable.call(self)
74777
74778 self._opts = opts
74779 self._body = []
74780 self._headers = {}
74781 if (opts.auth)
74782 self.setHeader('Authorization', 'Basic ' + Buffer.from(opts.auth).toString('base64'))
74783 Object.keys(opts.headers).forEach(function (name) {
74784 self.setHeader(name, opts.headers[name])
74785 })
74786
74787 var preferBinary
74788 var useFetch = true
74789 if (opts.mode === 'disable-fetch' || ('requestTimeout' in opts && !capability.abortController)) {
74790 // If the use of XHR should be preferred. Not typically needed.
74791 useFetch = false
74792 preferBinary = true
74793 } else if (opts.mode === 'prefer-streaming') {
74794 // If streaming is a high priority but binary compatibility and
74795 // the accuracy of the 'content-type' header aren't
74796 preferBinary = false
74797 } else if (opts.mode === 'allow-wrong-content-type') {
74798 // If streaming is more important than preserving the 'content-type' header
74799 preferBinary = !capability.overrideMimeType
74800 } else if (!opts.mode || opts.mode === 'default' || opts.mode === 'prefer-fast') {
74801 // Use binary if text streaming may corrupt data or the content-type header, or for speed
74802 preferBinary = true
74803 } else {
74804 throw new Error('Invalid value for opts.mode')
74805 }
74806 self._mode = decideMode(preferBinary, useFetch)
74807 self._fetchTimer = null
74808
74809 self.on('finish', function () {
74810 self._onFinish()
74811 })
74812}
74813
74814inherits(ClientRequest, stream.Writable)
74815
74816ClientRequest.prototype.setHeader = function (name, value) {
74817 var self = this
74818 var lowerName = name.toLowerCase()
74819 // This check is not necessary, but it prevents warnings from browsers about setting unsafe
74820 // headers. To be honest I'm not entirely sure hiding these warnings is a good thing, but
74821 // http-browserify did it, so I will too.
74822 if (unsafeHeaders.indexOf(lowerName) !== -1)
74823 return
74824
74825 self._headers[lowerName] = {
74826 name: name,
74827 value: value
74828 }
74829}
74830
74831ClientRequest.prototype.getHeader = function (name) {
74832 var header = this._headers[name.toLowerCase()]
74833 if (header)
74834 return header.value
74835 return null
74836}
74837
74838ClientRequest.prototype.removeHeader = function (name) {
74839 var self = this
74840 delete self._headers[name.toLowerCase()]
74841}
74842
74843ClientRequest.prototype._onFinish = function () {
74844 var self = this
74845
74846 if (self._destroyed)
74847 return
74848 var opts = self._opts
74849
74850 var headersObj = self._headers
74851 var body = null
74852 if (opts.method !== 'GET' && opts.method !== 'HEAD') {
74853 body = new Blob(self._body, {
74854 type: (headersObj['content-type'] || {}).value || ''
74855 });
74856 }
74857
74858 // create flattened list of headers
74859 var headersList = []
74860 Object.keys(headersObj).forEach(function (keyName) {
74861 var name = headersObj[keyName].name
74862 var value = headersObj[keyName].value
74863 if (Array.isArray(value)) {
74864 value.forEach(function (v) {
74865 headersList.push([name, v])
74866 })
74867 } else {
74868 headersList.push([name, value])
74869 }
74870 })
74871
74872 if (self._mode === 'fetch') {
74873 var signal = null
74874 var fetchTimer = null
74875 if (capability.abortController) {
74876 var controller = new AbortController()
74877 signal = controller.signal
74878 self._fetchAbortController = controller
74879
74880 if ('requestTimeout' in opts && opts.requestTimeout !== 0) {
74881 self._fetchTimer = global.setTimeout(function () {
74882 self.emit('requestTimeout')
74883 if (self._fetchAbortController)
74884 self._fetchAbortController.abort()
74885 }, opts.requestTimeout)
74886 }
74887 }
74888
74889 global.fetch(self._opts.url, {
74890 method: self._opts.method,
74891 headers: headersList,
74892 body: body || undefined,
74893 mode: 'cors',
74894 credentials: opts.withCredentials ? 'include' : 'same-origin',
74895 signal: signal
74896 }).then(function (response) {
74897 self._fetchResponse = response
74898 self._connect()
74899 }, function (reason) {
74900 global.clearTimeout(self._fetchTimer)
74901 if (!self._destroyed)
74902 self.emit('error', reason)
74903 })
74904 } else {
74905 var xhr = self._xhr = new global.XMLHttpRequest()
74906 try {
74907 xhr.open(self._opts.method, self._opts.url, true)
74908 } catch (err) {
74909 process.nextTick(function () {
74910 self.emit('error', err)
74911 })
74912 return
74913 }
74914
74915 // Can't set responseType on really old browsers
74916 if ('responseType' in xhr)
74917 xhr.responseType = self._mode
74918
74919 if ('withCredentials' in xhr)
74920 xhr.withCredentials = !!opts.withCredentials
74921
74922 if (self._mode === 'text' && 'overrideMimeType' in xhr)
74923 xhr.overrideMimeType('text/plain; charset=x-user-defined')
74924
74925 if ('requestTimeout' in opts) {
74926 xhr.timeout = opts.requestTimeout
74927 xhr.ontimeout = function () {
74928 self.emit('requestTimeout')
74929 }
74930 }
74931
74932 headersList.forEach(function (header) {
74933 xhr.setRequestHeader(header[0], header[1])
74934 })
74935
74936 self._response = null
74937 xhr.onreadystatechange = function () {
74938 switch (xhr.readyState) {
74939 case rStates.LOADING:
74940 case rStates.DONE:
74941 self._onXHRProgress()
74942 break
74943 }
74944 }
74945 // Necessary for streaming in Firefox, since xhr.response is ONLY defined
74946 // in onprogress, not in onreadystatechange with xhr.readyState = 3
74947 if (self._mode === 'moz-chunked-arraybuffer') {
74948 xhr.onprogress = function () {
74949 self._onXHRProgress()
74950 }
74951 }
74952
74953 xhr.onerror = function () {
74954 if (self._destroyed)
74955 return
74956 self.emit('error', new Error('XHR error'))
74957 }
74958
74959 try {
74960 xhr.send(body)
74961 } catch (err) {
74962 process.nextTick(function () {
74963 self.emit('error', err)
74964 })
74965 return
74966 }
74967 }
74968}
74969
74970/**
74971 * Checks if xhr.status is readable and non-zero, indicating no error.
74972 * Even though the spec says it should be available in readyState 3,
74973 * accessing it throws an exception in IE8
74974 */
74975function statusValid (xhr) {
74976 try {
74977 var status = xhr.status
74978 return (status !== null && status !== 0)
74979 } catch (e) {
74980 return false
74981 }
74982}
74983
74984ClientRequest.prototype._onXHRProgress = function () {
74985 var self = this
74986
74987 if (!statusValid(self._xhr) || self._destroyed)
74988 return
74989
74990 if (!self._response)
74991 self._connect()
74992
74993 self._response._onXHRProgress()
74994}
74995
74996ClientRequest.prototype._connect = function () {
74997 var self = this
74998
74999 if (self._destroyed)
75000 return
75001
75002 self._response = new IncomingMessage(self._xhr, self._fetchResponse, self._mode, self._fetchTimer)
75003 self._response.on('error', function(err) {
75004 self.emit('error', err)
75005 })
75006
75007 self.emit('response', self._response)
75008}
75009
75010ClientRequest.prototype._write = function (chunk, encoding, cb) {
75011 var self = this
75012
75013 self._body.push(chunk)
75014 cb()
75015}
75016
75017ClientRequest.prototype.abort = ClientRequest.prototype.destroy = function () {
75018 var self = this
75019 self._destroyed = true
75020 global.clearTimeout(self._fetchTimer)
75021 if (self._response)
75022 self._response._destroyed = true
75023 if (self._xhr)
75024 self._xhr.abort()
75025 else if (self._fetchAbortController)
75026 self._fetchAbortController.abort()
75027}
75028
75029ClientRequest.prototype.end = function (data, encoding, cb) {
75030 var self = this
75031 if (typeof data === 'function') {
75032 cb = data
75033 data = undefined
75034 }
75035
75036 stream.Writable.prototype.end.call(self, data, encoding, cb)
75037}
75038
75039ClientRequest.prototype.flushHeaders = function () {}
75040ClientRequest.prototype.setTimeout = function () {}
75041ClientRequest.prototype.setNoDelay = function () {}
75042ClientRequest.prototype.setSocketKeepAlive = function () {}
75043
75044// Taken from http://www.w3.org/TR/XMLHttpRequest/#the-setrequestheader%28%29-method
75045var unsafeHeaders = [
75046 'accept-charset',
75047 'accept-encoding',
75048 'access-control-request-headers',
75049 'access-control-request-method',
75050 'connection',
75051 'content-length',
75052 'cookie',
75053 'cookie2',
75054 'date',
75055 'dnt',
75056 'expect',
75057 'host',
75058 'keep-alive',
75059 'origin',
75060 'referer',
75061 'te',
75062 'trailer',
75063 'transfer-encoding',
75064 'upgrade',
75065 'via'
75066]
75067
75068}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},require("buffer").Buffer)
75069},{"./capability":363,"./response":365,"_process":265,"buffer":114,"inherits":210,"readable-stream":380}],365:[function(require,module,exports){
75070(function (process,global,Buffer){
75071var capability = require('./capability')
75072var inherits = require('inherits')
75073var stream = require('readable-stream')
75074
75075var rStates = exports.readyStates = {
75076 UNSENT: 0,
75077 OPENED: 1,
75078 HEADERS_RECEIVED: 2,
75079 LOADING: 3,
75080 DONE: 4
75081}
75082
75083var IncomingMessage = exports.IncomingMessage = function (xhr, response, mode, fetchTimer) {
75084 var self = this
75085 stream.Readable.call(self)
75086
75087 self._mode = mode
75088 self.headers = {}
75089 self.rawHeaders = []
75090 self.trailers = {}
75091 self.rawTrailers = []
75092
75093 // Fake the 'close' event, but only once 'end' fires
75094 self.on('end', function () {
75095 // The nextTick is necessary to prevent the 'request' module from causing an infinite loop
75096 process.nextTick(function () {
75097 self.emit('close')
75098 })
75099 })
75100
75101 if (mode === 'fetch') {
75102 self._fetchResponse = response
75103
75104 self.url = response.url
75105 self.statusCode = response.status
75106 self.statusMessage = response.statusText
75107
75108 response.headers.forEach(function (header, key){
75109 self.headers[key.toLowerCase()] = header
75110 self.rawHeaders.push(key, header)
75111 })
75112
75113 if (capability.writableStream) {
75114 var writable = new WritableStream({
75115 write: function (chunk) {
75116 return new Promise(function (resolve, reject) {
75117 if (self._destroyed) {
75118 reject()
75119 } else if(self.push(Buffer.from(chunk))) {
75120 resolve()
75121 } else {
75122 self._resumeFetch = resolve
75123 }
75124 })
75125 },
75126 close: function () {
75127 global.clearTimeout(fetchTimer)
75128 if (!self._destroyed)
75129 self.push(null)
75130 },
75131 abort: function (err) {
75132 if (!self._destroyed)
75133 self.emit('error', err)
75134 }
75135 })
75136
75137 try {
75138 response.body.pipeTo(writable).catch(function (err) {
75139 global.clearTimeout(fetchTimer)
75140 if (!self._destroyed)
75141 self.emit('error', err)
75142 })
75143 return
75144 } catch (e) {} // pipeTo method isn't defined. Can't find a better way to feature test this
75145 }
75146 // fallback for when writableStream or pipeTo aren't available
75147 var reader = response.body.getReader()
75148 function read () {
75149 reader.read().then(function (result) {
75150 if (self._destroyed)
75151 return
75152 if (result.done) {
75153 global.clearTimeout(fetchTimer)
75154 self.push(null)
75155 return
75156 }
75157 self.push(Buffer.from(result.value))
75158 read()
75159 }).catch(function (err) {
75160 global.clearTimeout(fetchTimer)
75161 if (!self._destroyed)
75162 self.emit('error', err)
75163 })
75164 }
75165 read()
75166 } else {
75167 self._xhr = xhr
75168 self._pos = 0
75169
75170 self.url = xhr.responseURL
75171 self.statusCode = xhr.status
75172 self.statusMessage = xhr.statusText
75173 var headers = xhr.getAllResponseHeaders().split(/\r?\n/)
75174 headers.forEach(function (header) {
75175 var matches = header.match(/^([^:]+):\s*(.*)/)
75176 if (matches) {
75177 var key = matches[1].toLowerCase()
75178 if (key === 'set-cookie') {
75179 if (self.headers[key] === undefined) {
75180 self.headers[key] = []
75181 }
75182 self.headers[key].push(matches[2])
75183 } else if (self.headers[key] !== undefined) {
75184 self.headers[key] += ', ' + matches[2]
75185 } else {
75186 self.headers[key] = matches[2]
75187 }
75188 self.rawHeaders.push(matches[1], matches[2])
75189 }
75190 })
75191
75192 self._charset = 'x-user-defined'
75193 if (!capability.overrideMimeType) {
75194 var mimeType = self.rawHeaders['mime-type']
75195 if (mimeType) {
75196 var charsetMatch = mimeType.match(/;\s*charset=([^;])(;|$)/)
75197 if (charsetMatch) {
75198 self._charset = charsetMatch[1].toLowerCase()
75199 }
75200 }
75201 if (!self._charset)
75202 self._charset = 'utf-8' // best guess
75203 }
75204 }
75205}
75206
75207inherits(IncomingMessage, stream.Readable)
75208
75209IncomingMessage.prototype._read = function () {
75210 var self = this
75211
75212 var resolve = self._resumeFetch
75213 if (resolve) {
75214 self._resumeFetch = null
75215 resolve()
75216 }
75217}
75218
75219IncomingMessage.prototype._onXHRProgress = function () {
75220 var self = this
75221
75222 var xhr = self._xhr
75223
75224 var response = null
75225 switch (self._mode) {
75226 case 'text':
75227 response = xhr.responseText
75228 if (response.length > self._pos) {
75229 var newData = response.substr(self._pos)
75230 if (self._charset === 'x-user-defined') {
75231 var buffer = Buffer.alloc(newData.length)
75232 for (var i = 0; i < newData.length; i++)
75233 buffer[i] = newData.charCodeAt(i) & 0xff
75234
75235 self.push(buffer)
75236 } else {
75237 self.push(newData, self._charset)
75238 }
75239 self._pos = response.length
75240 }
75241 break
75242 case 'arraybuffer':
75243 if (xhr.readyState !== rStates.DONE || !xhr.response)
75244 break
75245 response = xhr.response
75246 self.push(Buffer.from(new Uint8Array(response)))
75247 break
75248 case 'moz-chunked-arraybuffer': // take whole
75249 response = xhr.response
75250 if (xhr.readyState !== rStates.LOADING || !response)
75251 break
75252 self.push(Buffer.from(new Uint8Array(response)))
75253 break
75254 case 'ms-stream':
75255 response = xhr.response
75256 if (xhr.readyState !== rStates.LOADING)
75257 break
75258 var reader = new global.MSStreamReader()
75259 reader.onprogress = function () {
75260 if (reader.result.byteLength > self._pos) {
75261 self.push(Buffer.from(new Uint8Array(reader.result.slice(self._pos))))
75262 self._pos = reader.result.byteLength
75263 }
75264 }
75265 reader.onload = function () {
75266 self.push(null)
75267 }
75268 // reader.onerror = ??? // TODO: this
75269 reader.readAsArrayBuffer(response)
75270 break
75271 }
75272
75273 // The ms-stream case handles end separately in reader.onload()
75274 if (self._xhr.readyState === rStates.DONE && self._mode !== 'ms-stream') {
75275 self.push(null)
75276 }
75277}
75278
75279}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},require("buffer").Buffer)
75280},{"./capability":363,"_process":265,"buffer":114,"inherits":210,"readable-stream":380}],366:[function(require,module,exports){
75281'use strict';
75282
75283function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
75284
75285var codes = {};
75286
75287function createErrorType(code, message, Base) {
75288 if (!Base) {
75289 Base = Error;
75290 }
75291
75292 function getMessage(arg1, arg2, arg3) {
75293 if (typeof message === 'string') {
75294 return message;
75295 } else {
75296 return message(arg1, arg2, arg3);
75297 }
75298 }
75299
75300 var NodeError =
75301 /*#__PURE__*/
75302 function (_Base) {
75303 _inheritsLoose(NodeError, _Base);
75304
75305 function NodeError(arg1, arg2, arg3) {
75306 return _Base.call(this, getMessage(arg1, arg2, arg3)) || this;
75307 }
75308
75309 return NodeError;
75310 }(Base);
75311
75312 NodeError.prototype.name = Base.name;
75313 NodeError.prototype.code = code;
75314 codes[code] = NodeError;
75315} // https://github.com/nodejs/node/blob/v10.8.0/lib/internal/errors.js
75316
75317
75318function oneOf(expected, thing) {
75319 if (Array.isArray(expected)) {
75320 var len = expected.length;
75321 expected = expected.map(function (i) {
75322 return String(i);
75323 });
75324
75325 if (len > 2) {
75326 return "one of ".concat(thing, " ").concat(expected.slice(0, len - 1).join(', '), ", or ") + expected[len - 1];
75327 } else if (len === 2) {
75328 return "one of ".concat(thing, " ").concat(expected[0], " or ").concat(expected[1]);
75329 } else {
75330 return "of ".concat(thing, " ").concat(expected[0]);
75331 }
75332 } else {
75333 return "of ".concat(thing, " ").concat(String(expected));
75334 }
75335} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith
75336
75337
75338function startsWith(str, search, pos) {
75339 return str.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search;
75340} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith
75341
75342
75343function endsWith(str, search, this_len) {
75344 if (this_len === undefined || this_len > str.length) {
75345 this_len = str.length;
75346 }
75347
75348 return str.substring(this_len - search.length, this_len) === search;
75349} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes
75350
75351
75352function includes(str, search, start) {
75353 if (typeof start !== 'number') {
75354 start = 0;
75355 }
75356
75357 if (start + search.length > str.length) {
75358 return false;
75359 } else {
75360 return str.indexOf(search, start) !== -1;
75361 }
75362}
75363
75364createErrorType('ERR_INVALID_OPT_VALUE', function (name, value) {
75365 return 'The value "' + value + '" is invalid for option "' + name + '"';
75366}, TypeError);
75367createErrorType('ERR_INVALID_ARG_TYPE', function (name, expected, actual) {
75368 // determiner: 'must be' or 'must not be'
75369 var determiner;
75370
75371 if (typeof expected === 'string' && startsWith(expected, 'not ')) {
75372 determiner = 'must not be';
75373 expected = expected.replace(/^not /, '');
75374 } else {
75375 determiner = 'must be';
75376 }
75377
75378 var msg;
75379
75380 if (endsWith(name, ' argument')) {
75381 // For cases like 'first argument'
75382 msg = "The ".concat(name, " ").concat(determiner, " ").concat(oneOf(expected, 'type'));
75383 } else {
75384 var type = includes(name, '.') ? 'property' : 'argument';
75385 msg = "The \"".concat(name, "\" ").concat(type, " ").concat(determiner, " ").concat(oneOf(expected, 'type'));
75386 }
75387
75388 msg += ". Received type ".concat(typeof actual);
75389 return msg;
75390}, TypeError);
75391createErrorType('ERR_STREAM_PUSH_AFTER_EOF', 'stream.push() after EOF');
75392createErrorType('ERR_METHOD_NOT_IMPLEMENTED', function (name) {
75393 return 'The ' + name + ' method is not implemented';
75394});
75395createErrorType('ERR_STREAM_PREMATURE_CLOSE', 'Premature close');
75396createErrorType('ERR_STREAM_DESTROYED', function (name) {
75397 return 'Cannot call ' + name + ' after a stream was destroyed';
75398});
75399createErrorType('ERR_MULTIPLE_CALLBACK', 'Callback called multiple times');
75400createErrorType('ERR_STREAM_CANNOT_PIPE', 'Cannot pipe, not readable');
75401createErrorType('ERR_STREAM_WRITE_AFTER_END', 'write after end');
75402createErrorType('ERR_STREAM_NULL_VALUES', 'May not write null values to stream', TypeError);
75403createErrorType('ERR_UNKNOWN_ENCODING', function (arg) {
75404 return 'Unknown encoding: ' + arg;
75405}, TypeError);
75406createErrorType('ERR_STREAM_UNSHIFT_AFTER_END_EVENT', 'stream.unshift() after end event');
75407module.exports.codes = codes;
75408
75409},{}],367:[function(require,module,exports){
75410(function (process){
75411'use strict'
75412
75413var experimentalWarnings = new Set();
75414
75415function emitExperimentalWarning(feature) {
75416 if (experimentalWarnings.has(feature)) return;
75417 var msg = feature + ' is an experimental feature. This feature could ' +
75418 'change at any time';
75419 experimentalWarnings.add(feature);
75420 process.emitWarning(msg, 'ExperimentalWarning');
75421}
75422
75423function noop() {}
75424
75425module.exports.emitExperimentalWarning = process.emitWarning
75426 ? emitExperimentalWarning
75427 : noop;
75428
75429}).call(this,require('_process'))
75430},{"_process":265}],368:[function(require,module,exports){
75431(function (process){
75432// Copyright Joyent, Inc. and other Node contributors.
75433//
75434// Permission is hereby granted, free of charge, to any person obtaining a
75435// copy of this software and associated documentation files (the
75436// "Software"), to deal in the Software without restriction, including
75437// without limitation the rights to use, copy, modify, merge, publish,
75438// distribute, sublicense, and/or sell copies of the Software, and to permit
75439// persons to whom the Software is furnished to do so, subject to the
75440// following conditions:
75441//
75442// The above copyright notice and this permission notice shall be included
75443// in all copies or substantial portions of the Software.
75444//
75445// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
75446// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
75447// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
75448// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
75449// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
75450// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
75451// USE OR OTHER DEALINGS IN THE SOFTWARE.
75452// a duplex stream is just a stream that is both readable and writable.
75453// Since JS doesn't have multiple prototypal inheritance, this class
75454// prototypally inherits from Readable, and then parasitically from
75455// Writable.
75456'use strict';
75457/*<replacement>*/
75458
75459var objectKeys = Object.keys || function (obj) {
75460 var keys = [];
75461
75462 for (var key in obj) {
75463 keys.push(key);
75464 }
75465
75466 return keys;
75467};
75468/*</replacement>*/
75469
75470
75471module.exports = Duplex;
75472
75473var Readable = require('./_stream_readable');
75474
75475var Writable = require('./_stream_writable');
75476
75477require('inherits')(Duplex, Readable);
75478
75479{
75480 // Allow the keys array to be GC'ed.
75481 var keys = objectKeys(Writable.prototype);
75482
75483 for (var v = 0; v < keys.length; v++) {
75484 var method = keys[v];
75485 if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method];
75486 }
75487}
75488
75489function Duplex(options) {
75490 if (!(this instanceof Duplex)) return new Duplex(options);
75491 Readable.call(this, options);
75492 Writable.call(this, options);
75493 this.allowHalfOpen = true;
75494
75495 if (options) {
75496 if (options.readable === false) this.readable = false;
75497 if (options.writable === false) this.writable = false;
75498
75499 if (options.allowHalfOpen === false) {
75500 this.allowHalfOpen = false;
75501 this.once('end', onend);
75502 }
75503 }
75504}
75505
75506Object.defineProperty(Duplex.prototype, 'writableHighWaterMark', {
75507 // making it explicit this property is not enumerable
75508 // because otherwise some prototype manipulation in
75509 // userland will fail
75510 enumerable: false,
75511 get: function get() {
75512 return this._writableState.highWaterMark;
75513 }
75514});
75515Object.defineProperty(Duplex.prototype, 'writableBuffer', {
75516 // making it explicit this property is not enumerable
75517 // because otherwise some prototype manipulation in
75518 // userland will fail
75519 enumerable: false,
75520 get: function get() {
75521 return this._writableState && this._writableState.getBuffer();
75522 }
75523});
75524Object.defineProperty(Duplex.prototype, 'writableLength', {
75525 // making it explicit this property is not enumerable
75526 // because otherwise some prototype manipulation in
75527 // userland will fail
75528 enumerable: false,
75529 get: function get() {
75530 return this._writableState.length;
75531 }
75532}); // the no-half-open enforcer
75533
75534function onend() {
75535 // If the writable side ended, then we're ok.
75536 if (this._writableState.ended) return; // no more data can be written.
75537 // But allow more writes to happen in this tick.
75538
75539 process.nextTick(onEndNT, this);
75540}
75541
75542function onEndNT(self) {
75543 self.end();
75544}
75545
75546Object.defineProperty(Duplex.prototype, 'destroyed', {
75547 // making it explicit this property is not enumerable
75548 // because otherwise some prototype manipulation in
75549 // userland will fail
75550 enumerable: false,
75551 get: function get() {
75552 if (this._readableState === undefined || this._writableState === undefined) {
75553 return false;
75554 }
75555
75556 return this._readableState.destroyed && this._writableState.destroyed;
75557 },
75558 set: function set(value) {
75559 // we ignore the value if the stream
75560 // has not been initialized yet
75561 if (this._readableState === undefined || this._writableState === undefined) {
75562 return;
75563 } // backward compatibility, the user is explicitly
75564 // managing destroyed
75565
75566
75567 this._readableState.destroyed = value;
75568 this._writableState.destroyed = value;
75569 }
75570});
75571}).call(this,require('_process'))
75572},{"./_stream_readable":370,"./_stream_writable":372,"_process":265,"inherits":210}],369:[function(require,module,exports){
75573// Copyright Joyent, Inc. and other Node contributors.
75574//
75575// Permission is hereby granted, free of charge, to any person obtaining a
75576// copy of this software and associated documentation files (the
75577// "Software"), to deal in the Software without restriction, including
75578// without limitation the rights to use, copy, modify, merge, publish,
75579// distribute, sublicense, and/or sell copies of the Software, and to permit
75580// persons to whom the Software is furnished to do so, subject to the
75581// following conditions:
75582//
75583// The above copyright notice and this permission notice shall be included
75584// in all copies or substantial portions of the Software.
75585//
75586// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
75587// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
75588// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
75589// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
75590// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
75591// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
75592// USE OR OTHER DEALINGS IN THE SOFTWARE.
75593// a passthrough stream.
75594// basically just the most minimal sort of Transform stream.
75595// Every written chunk gets output as-is.
75596'use strict';
75597
75598module.exports = PassThrough;
75599
75600var Transform = require('./_stream_transform');
75601
75602require('inherits')(PassThrough, Transform);
75603
75604function PassThrough(options) {
75605 if (!(this instanceof PassThrough)) return new PassThrough(options);
75606 Transform.call(this, options);
75607}
75608
75609PassThrough.prototype._transform = function (chunk, encoding, cb) {
75610 cb(null, chunk);
75611};
75612},{"./_stream_transform":371,"inherits":210}],370:[function(require,module,exports){
75613(function (process,global){
75614// Copyright Joyent, Inc. and other Node contributors.
75615//
75616// Permission is hereby granted, free of charge, to any person obtaining a
75617// copy of this software and associated documentation files (the
75618// "Software"), to deal in the Software without restriction, including
75619// without limitation the rights to use, copy, modify, merge, publish,
75620// distribute, sublicense, and/or sell copies of the Software, and to permit
75621// persons to whom the Software is furnished to do so, subject to the
75622// following conditions:
75623//
75624// The above copyright notice and this permission notice shall be included
75625// in all copies or substantial portions of the Software.
75626//
75627// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
75628// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
75629// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
75630// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
75631// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
75632// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
75633// USE OR OTHER DEALINGS IN THE SOFTWARE.
75634'use strict';
75635
75636module.exports = Readable;
75637/*<replacement>*/
75638
75639var Duplex;
75640/*</replacement>*/
75641
75642Readable.ReadableState = ReadableState;
75643/*<replacement>*/
75644
75645var EE = require('events').EventEmitter;
75646
75647var EElistenerCount = function EElistenerCount(emitter, type) {
75648 return emitter.listeners(type).length;
75649};
75650/*</replacement>*/
75651
75652/*<replacement>*/
75653
75654
75655var Stream = require('./internal/streams/stream');
75656/*</replacement>*/
75657
75658
75659var Buffer = require('buffer').Buffer;
75660
75661var OurUint8Array = global.Uint8Array || function () {};
75662
75663function _uint8ArrayToBuffer(chunk) {
75664 return Buffer.from(chunk);
75665}
75666
75667function _isUint8Array(obj) {
75668 return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
75669}
75670/*<replacement>*/
75671
75672
75673var debugUtil = require('util');
75674
75675var debug;
75676
75677if (debugUtil && debugUtil.debuglog) {
75678 debug = debugUtil.debuglog('stream');
75679} else {
75680 debug = function debug() {};
75681}
75682/*</replacement>*/
75683
75684
75685var BufferList = require('./internal/streams/buffer_list');
75686
75687var destroyImpl = require('./internal/streams/destroy');
75688
75689var _require = require('./internal/streams/state'),
75690 getHighWaterMark = _require.getHighWaterMark;
75691
75692var _require$codes = require('../errors').codes,
75693 ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE,
75694 ERR_STREAM_PUSH_AFTER_EOF = _require$codes.ERR_STREAM_PUSH_AFTER_EOF,
75695 ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED,
75696 ERR_STREAM_UNSHIFT_AFTER_END_EVENT = _require$codes.ERR_STREAM_UNSHIFT_AFTER_END_EVENT;
75697
75698var _require2 = require('../experimentalWarning'),
75699 emitExperimentalWarning = _require2.emitExperimentalWarning; // Lazy loaded to improve the startup performance.
75700
75701
75702var StringDecoder;
75703var createReadableStreamAsyncIterator;
75704
75705require('inherits')(Readable, Stream);
75706
75707var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume'];
75708
75709function prependListener(emitter, event, fn) {
75710 // Sadly this is not cacheable as some libraries bundle their own
75711 // event emitter implementation with them.
75712 if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn); // This is a hack to make sure that our error handler is attached before any
75713 // userland ones. NEVER DO THIS. This is here only because this code needs
75714 // to continue to work with older versions of Node.js that do not include
75715 // the prependListener() method. The goal is to eventually remove this hack.
75716
75717 if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (Array.isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]];
75718}
75719
75720function ReadableState(options, stream, isDuplex) {
75721 Duplex = Duplex || require('./_stream_duplex');
75722 options = options || {}; // Duplex streams are both readable and writable, but share
75723 // the same options object.
75724 // However, some cases require setting options to different
75725 // values for the readable and the writable sides of the duplex stream.
75726 // These options can be provided separately as readableXXX and writableXXX.
75727
75728 if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; // object stream flag. Used to make read(n) ignore n and to
75729 // make all the buffer merging and length checks go away
75730
75731 this.objectMode = !!options.objectMode;
75732 if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode; // the point at which it stops calling _read() to fill the buffer
75733 // Note: 0 is a valid value, means "don't call _read preemptively ever"
75734
75735 this.highWaterMark = getHighWaterMark(this, options, 'readableHighWaterMark', isDuplex); // A linked list is used to store data chunks instead of an array because the
75736 // linked list can remove elements from the beginning faster than
75737 // array.shift()
75738
75739 this.buffer = new BufferList();
75740 this.length = 0;
75741 this.pipes = null;
75742 this.pipesCount = 0;
75743 this.flowing = null;
75744 this.ended = false;
75745 this.endEmitted = false;
75746 this.reading = false; // a flag to be able to tell if the event 'readable'/'data' is emitted
75747 // immediately, or on a later tick. We set this to true at first, because
75748 // any actions that shouldn't happen until "later" should generally also
75749 // not happen before the first read call.
75750
75751 this.sync = true; // whenever we return null, then we set a flag to say
75752 // that we're awaiting a 'readable' event emission.
75753
75754 this.needReadable = false;
75755 this.emittedReadable = false;
75756 this.readableListening = false;
75757 this.resumeScheduled = false;
75758 this.paused = true; // Should close be emitted on destroy. Defaults to true.
75759
75760 this.emitClose = options.emitClose !== false; // has it been destroyed
75761
75762 this.destroyed = false; // Crypto is kind of old and crusty. Historically, its default string
75763 // encoding is 'binary' so we have to make this configurable.
75764 // Everything else in the universe uses 'utf8', though.
75765
75766 this.defaultEncoding = options.defaultEncoding || 'utf8'; // the number of writers that are awaiting a drain event in .pipe()s
75767
75768 this.awaitDrain = 0; // if true, a maybeReadMore has been scheduled
75769
75770 this.readingMore = false;
75771 this.decoder = null;
75772 this.encoding = null;
75773
75774 if (options.encoding) {
75775 if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;
75776 this.decoder = new StringDecoder(options.encoding);
75777 this.encoding = options.encoding;
75778 }
75779}
75780
75781function Readable(options) {
75782 Duplex = Duplex || require('./_stream_duplex');
75783 if (!(this instanceof Readable)) return new Readable(options); // Checking for a Stream.Duplex instance is faster here instead of inside
75784 // the ReadableState constructor, at least with V8 6.5
75785
75786 var isDuplex = this instanceof Duplex;
75787 this._readableState = new ReadableState(options, this, isDuplex); // legacy
75788
75789 this.readable = true;
75790
75791 if (options) {
75792 if (typeof options.read === 'function') this._read = options.read;
75793 if (typeof options.destroy === 'function') this._destroy = options.destroy;
75794 }
75795
75796 Stream.call(this);
75797}
75798
75799Object.defineProperty(Readable.prototype, 'destroyed', {
75800 // making it explicit this property is not enumerable
75801 // because otherwise some prototype manipulation in
75802 // userland will fail
75803 enumerable: false,
75804 get: function get() {
75805 if (this._readableState === undefined) {
75806 return false;
75807 }
75808
75809 return this._readableState.destroyed;
75810 },
75811 set: function set(value) {
75812 // we ignore the value if the stream
75813 // has not been initialized yet
75814 if (!this._readableState) {
75815 return;
75816 } // backward compatibility, the user is explicitly
75817 // managing destroyed
75818
75819
75820 this._readableState.destroyed = value;
75821 }
75822});
75823Readable.prototype.destroy = destroyImpl.destroy;
75824Readable.prototype._undestroy = destroyImpl.undestroy;
75825
75826Readable.prototype._destroy = function (err, cb) {
75827 cb(err);
75828}; // Manually shove something into the read() buffer.
75829// This returns true if the highWaterMark has not been hit yet,
75830// similar to how Writable.write() returns true if you should
75831// write() some more.
75832
75833
75834Readable.prototype.push = function (chunk, encoding) {
75835 var state = this._readableState;
75836 var skipChunkCheck;
75837
75838 if (!state.objectMode) {
75839 if (typeof chunk === 'string') {
75840 encoding = encoding || state.defaultEncoding;
75841
75842 if (encoding !== state.encoding) {
75843 chunk = Buffer.from(chunk, encoding);
75844 encoding = '';
75845 }
75846
75847 skipChunkCheck = true;
75848 }
75849 } else {
75850 skipChunkCheck = true;
75851 }
75852
75853 return readableAddChunk(this, chunk, encoding, false, skipChunkCheck);
75854}; // Unshift should *always* be something directly out of read()
75855
75856
75857Readable.prototype.unshift = function (chunk) {
75858 return readableAddChunk(this, chunk, null, true, false);
75859};
75860
75861function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) {
75862 debug('readableAddChunk', chunk);
75863 var state = stream._readableState;
75864
75865 if (chunk === null) {
75866 state.reading = false;
75867 onEofChunk(stream, state);
75868 } else {
75869 var er;
75870 if (!skipChunkCheck) er = chunkInvalid(state, chunk);
75871
75872 if (er) {
75873 stream.emit('error', er);
75874 } else if (state.objectMode || chunk && chunk.length > 0) {
75875 if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) {
75876 chunk = _uint8ArrayToBuffer(chunk);
75877 }
75878
75879 if (addToFront) {
75880 if (state.endEmitted) stream.emit('error', new ERR_STREAM_UNSHIFT_AFTER_END_EVENT());else addChunk(stream, state, chunk, true);
75881 } else if (state.ended) {
75882 stream.emit('error', new ERR_STREAM_PUSH_AFTER_EOF());
75883 } else if (state.destroyed) {
75884 return false;
75885 } else {
75886 state.reading = false;
75887
75888 if (state.decoder && !encoding) {
75889 chunk = state.decoder.write(chunk);
75890 if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state);
75891 } else {
75892 addChunk(stream, state, chunk, false);
75893 }
75894 }
75895 } else if (!addToFront) {
75896 state.reading = false;
75897 maybeReadMore(stream, state);
75898 }
75899 } // We can push more data if we are below the highWaterMark.
75900 // Also, if we have no data yet, we can stand some more bytes.
75901 // This is to work around cases where hwm=0, such as the repl.
75902
75903
75904 return !state.ended && (state.length < state.highWaterMark || state.length === 0);
75905}
75906
75907function addChunk(stream, state, chunk, addToFront) {
75908 if (state.flowing && state.length === 0 && !state.sync) {
75909 state.awaitDrain = 0;
75910 stream.emit('data', chunk);
75911 } else {
75912 // update the buffer info.
75913 state.length += state.objectMode ? 1 : chunk.length;
75914 if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk);
75915 if (state.needReadable) emitReadable(stream);
75916 }
75917
75918 maybeReadMore(stream, state);
75919}
75920
75921function chunkInvalid(state, chunk) {
75922 var er;
75923
75924 if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
75925 er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer', 'Uint8Array'], chunk);
75926 }
75927
75928 return er;
75929}
75930
75931Readable.prototype.isPaused = function () {
75932 return this._readableState.flowing === false;
75933}; // backwards compatibility.
75934
75935
75936Readable.prototype.setEncoding = function (enc) {
75937 if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;
75938 this._readableState.decoder = new StringDecoder(enc); // if setEncoding(null), decoder.encoding equals utf8
75939
75940 this._readableState.encoding = this._readableState.decoder.encoding;
75941 return this;
75942}; // Don't raise the hwm > 8MB
75943
75944
75945var MAX_HWM = 0x800000;
75946
75947function computeNewHighWaterMark(n) {
75948 if (n >= MAX_HWM) {
75949 n = MAX_HWM;
75950 } else {
75951 // Get the next highest power of 2 to prevent increasing hwm excessively in
75952 // tiny amounts
75953 n--;
75954 n |= n >>> 1;
75955 n |= n >>> 2;
75956 n |= n >>> 4;
75957 n |= n >>> 8;
75958 n |= n >>> 16;
75959 n++;
75960 }
75961
75962 return n;
75963} // This function is designed to be inlinable, so please take care when making
75964// changes to the function body.
75965
75966
75967function howMuchToRead(n, state) {
75968 if (n <= 0 || state.length === 0 && state.ended) return 0;
75969 if (state.objectMode) return 1;
75970
75971 if (n !== n) {
75972 // Only flow one buffer at a time
75973 if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length;
75974 } // If we're asking for more than the current hwm, then raise the hwm.
75975
75976
75977 if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n);
75978 if (n <= state.length) return n; // Don't have enough
75979
75980 if (!state.ended) {
75981 state.needReadable = true;
75982 return 0;
75983 }
75984
75985 return state.length;
75986} // you can override either this method, or the async _read(n) below.
75987
75988
75989Readable.prototype.read = function (n) {
75990 debug('read', n);
75991 n = parseInt(n, 10);
75992 var state = this._readableState;
75993 var nOrig = n;
75994 if (n !== 0) state.emittedReadable = false; // if we're doing read(0) to trigger a readable event, but we
75995 // already have a bunch of data in the buffer, then just trigger
75996 // the 'readable' event and move on.
75997
75998 if (n === 0 && state.needReadable && ((state.highWaterMark !== 0 ? state.length >= state.highWaterMark : state.length > 0) || state.ended)) {
75999 debug('read: emitReadable', state.length, state.ended);
76000 if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this);
76001 return null;
76002 }
76003
76004 n = howMuchToRead(n, state); // if we've ended, and we're now clear, then finish it up.
76005
76006 if (n === 0 && state.ended) {
76007 if (state.length === 0) endReadable(this);
76008 return null;
76009 } // All the actual chunk generation logic needs to be
76010 // *below* the call to _read. The reason is that in certain
76011 // synthetic stream cases, such as passthrough streams, _read
76012 // may be a completely synchronous operation which may change
76013 // the state of the read buffer, providing enough data when
76014 // before there was *not* enough.
76015 //
76016 // So, the steps are:
76017 // 1. Figure out what the state of things will be after we do
76018 // a read from the buffer.
76019 //
76020 // 2. If that resulting state will trigger a _read, then call _read.
76021 // Note that this may be asynchronous, or synchronous. Yes, it is
76022 // deeply ugly to write APIs this way, but that still doesn't mean
76023 // that the Readable class should behave improperly, as streams are
76024 // designed to be sync/async agnostic.
76025 // Take note if the _read call is sync or async (ie, if the read call
76026 // has returned yet), so that we know whether or not it's safe to emit
76027 // 'readable' etc.
76028 //
76029 // 3. Actually pull the requested chunks out of the buffer and return.
76030 // if we need a readable event, then we need to do some reading.
76031
76032
76033 var doRead = state.needReadable;
76034 debug('need readable', doRead); // if we currently have less than the highWaterMark, then also read some
76035
76036 if (state.length === 0 || state.length - n < state.highWaterMark) {
76037 doRead = true;
76038 debug('length less than watermark', doRead);
76039 } // however, if we've ended, then there's no point, and if we're already
76040 // reading, then it's unnecessary.
76041
76042
76043 if (state.ended || state.reading) {
76044 doRead = false;
76045 debug('reading or ended', doRead);
76046 } else if (doRead) {
76047 debug('do read');
76048 state.reading = true;
76049 state.sync = true; // if the length is currently zero, then we *need* a readable event.
76050
76051 if (state.length === 0) state.needReadable = true; // call internal read method
76052
76053 this._read(state.highWaterMark);
76054
76055 state.sync = false; // If _read pushed data synchronously, then `reading` will be false,
76056 // and we need to re-evaluate how much data we can return to the user.
76057
76058 if (!state.reading) n = howMuchToRead(nOrig, state);
76059 }
76060
76061 var ret;
76062 if (n > 0) ret = fromList(n, state);else ret = null;
76063
76064 if (ret === null) {
76065 state.needReadable = true;
76066 n = 0;
76067 } else {
76068 state.length -= n;
76069 state.awaitDrain = 0;
76070 }
76071
76072 if (state.length === 0) {
76073 // If we have nothing in the buffer, then we want to know
76074 // as soon as we *do* get something into the buffer.
76075 if (!state.ended) state.needReadable = true; // If we tried to read() past the EOF, then emit end on the next tick.
76076
76077 if (nOrig !== n && state.ended) endReadable(this);
76078 }
76079
76080 if (ret !== null) this.emit('data', ret);
76081 return ret;
76082};
76083
76084function onEofChunk(stream, state) {
76085 if (state.ended) return;
76086
76087 if (state.decoder) {
76088 var chunk = state.decoder.end();
76089
76090 if (chunk && chunk.length) {
76091 state.buffer.push(chunk);
76092 state.length += state.objectMode ? 1 : chunk.length;
76093 }
76094 }
76095
76096 state.ended = true;
76097
76098 if (state.sync) {
76099 // if we are sync, wait until next tick to emit the data.
76100 // Otherwise we risk emitting data in the flow()
76101 // the readable code triggers during a read() call
76102 emitReadable(stream);
76103 } else {
76104 // emit 'readable' now to make sure it gets picked up.
76105 state.needReadable = false;
76106
76107 if (!state.emittedReadable) {
76108 state.emittedReadable = true;
76109 emitReadable_(stream);
76110 }
76111 }
76112} // Don't emit readable right away in sync mode, because this can trigger
76113// another read() call => stack overflow. This way, it might trigger
76114// a nextTick recursion warning, but that's not so bad.
76115
76116
76117function emitReadable(stream) {
76118 var state = stream._readableState;
76119 state.needReadable = false;
76120
76121 if (!state.emittedReadable) {
76122 debug('emitReadable', state.flowing);
76123 state.emittedReadable = true;
76124 process.nextTick(emitReadable_, stream);
76125 }
76126}
76127
76128function emitReadable_(stream) {
76129 var state = stream._readableState;
76130 debug('emitReadable_', state.destroyed, state.length, state.ended);
76131
76132 if (!state.destroyed && (state.length || state.ended)) {
76133 stream.emit('readable');
76134 } // The stream needs another readable event if
76135 // 1. It is not flowing, as the flow mechanism will take
76136 // care of it.
76137 // 2. It is not ended.
76138 // 3. It is below the highWaterMark, so we can schedule
76139 // another readable later.
76140
76141
76142 state.needReadable = !state.flowing && !state.ended && state.length <= state.highWaterMark;
76143 flow(stream);
76144} // at this point, the user has presumably seen the 'readable' event,
76145// and called read() to consume some data. that may have triggered
76146// in turn another _read(n) call, in which case reading = true if
76147// it's in progress.
76148// However, if we're not ended, or reading, and the length < hwm,
76149// then go ahead and try to read some more preemptively.
76150
76151
76152function maybeReadMore(stream, state) {
76153 if (!state.readingMore) {
76154 state.readingMore = true;
76155 process.nextTick(maybeReadMore_, stream, state);
76156 }
76157}
76158
76159function maybeReadMore_(stream, state) {
76160 // Attempt to read more data if we should.
76161 //
76162 // The conditions for reading more data are (one of):
76163 // - Not enough data buffered (state.length < state.highWaterMark). The loop
76164 // is responsible for filling the buffer with enough data if such data
76165 // is available. If highWaterMark is 0 and we are not in the flowing mode
76166 // we should _not_ attempt to buffer any extra data. We'll get more data
76167 // when the stream consumer calls read() instead.
76168 // - No data in the buffer, and the stream is in flowing mode. In this mode
76169 // the loop below is responsible for ensuring read() is called. Failing to
76170 // call read here would abort the flow and there's no other mechanism for
76171 // continuing the flow if the stream consumer has just subscribed to the
76172 // 'data' event.
76173 //
76174 // In addition to the above conditions to keep reading data, the following
76175 // conditions prevent the data from being read:
76176 // - The stream has ended (state.ended).
76177 // - There is already a pending 'read' operation (state.reading). This is a
76178 // case where the the stream has called the implementation defined _read()
76179 // method, but they are processing the call asynchronously and have _not_
76180 // called push() with new data. In this case we skip performing more
76181 // read()s. The execution ends in this method again after the _read() ends
76182 // up calling push() with more data.
76183 while (!state.reading && !state.ended && (state.length < state.highWaterMark || state.flowing && state.length === 0)) {
76184 var len = state.length;
76185 debug('maybeReadMore read 0');
76186 stream.read(0);
76187 if (len === state.length) // didn't get any data, stop spinning.
76188 break;
76189 }
76190
76191 state.readingMore = false;
76192} // abstract method. to be overridden in specific implementation classes.
76193// call cb(er, data) where data is <= n in length.
76194// for virtual (non-string, non-buffer) streams, "length" is somewhat
76195// arbitrary, and perhaps not very meaningful.
76196
76197
76198Readable.prototype._read = function (n) {
76199 this.emit('error', new ERR_METHOD_NOT_IMPLEMENTED('_read()'));
76200};
76201
76202Readable.prototype.pipe = function (dest, pipeOpts) {
76203 var src = this;
76204 var state = this._readableState;
76205
76206 switch (state.pipesCount) {
76207 case 0:
76208 state.pipes = dest;
76209 break;
76210
76211 case 1:
76212 state.pipes = [state.pipes, dest];
76213 break;
76214
76215 default:
76216 state.pipes.push(dest);
76217 break;
76218 }
76219
76220 state.pipesCount += 1;
76221 debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);
76222 var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr;
76223 var endFn = doEnd ? onend : unpipe;
76224 if (state.endEmitted) process.nextTick(endFn);else src.once('end', endFn);
76225 dest.on('unpipe', onunpipe);
76226
76227 function onunpipe(readable, unpipeInfo) {
76228 debug('onunpipe');
76229
76230 if (readable === src) {
76231 if (unpipeInfo && unpipeInfo.hasUnpiped === false) {
76232 unpipeInfo.hasUnpiped = true;
76233 cleanup();
76234 }
76235 }
76236 }
76237
76238 function onend() {
76239 debug('onend');
76240 dest.end();
76241 } // when the dest drains, it reduces the awaitDrain counter
76242 // on the source. This would be more elegant with a .once()
76243 // handler in flow(), but adding and removing repeatedly is
76244 // too slow.
76245
76246
76247 var ondrain = pipeOnDrain(src);
76248 dest.on('drain', ondrain);
76249 var cleanedUp = false;
76250
76251 function cleanup() {
76252 debug('cleanup'); // cleanup event handlers once the pipe is broken
76253
76254 dest.removeListener('close', onclose);
76255 dest.removeListener('finish', onfinish);
76256 dest.removeListener('drain', ondrain);
76257 dest.removeListener('error', onerror);
76258 dest.removeListener('unpipe', onunpipe);
76259 src.removeListener('end', onend);
76260 src.removeListener('end', unpipe);
76261 src.removeListener('data', ondata);
76262 cleanedUp = true; // if the reader is waiting for a drain event from this
76263 // specific writer, then it would cause it to never start
76264 // flowing again.
76265 // So, if this is awaiting a drain, then we just call it now.
76266 // If we don't know, then assume that we are waiting for one.
76267
76268 if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain();
76269 }
76270
76271 src.on('data', ondata);
76272
76273 function ondata(chunk) {
76274 debug('ondata');
76275 var ret = dest.write(chunk);
76276 debug('dest.write', ret);
76277
76278 if (ret === false) {
76279 // If the user unpiped during `dest.write()`, it is possible
76280 // to get stuck in a permanently paused state if that write
76281 // also returned false.
76282 // => Check whether `dest` is still a piping destination.
76283 if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) {
76284 debug('false write response, pause', state.awaitDrain);
76285 state.awaitDrain++;
76286 }
76287
76288 src.pause();
76289 }
76290 } // if the dest has an error, then stop piping into it.
76291 // however, don't suppress the throwing behavior for this.
76292
76293
76294 function onerror(er) {
76295 debug('onerror', er);
76296 unpipe();
76297 dest.removeListener('error', onerror);
76298 if (EElistenerCount(dest, 'error') === 0) dest.emit('error', er);
76299 } // Make sure our error handler is attached before userland ones.
76300
76301
76302 prependListener(dest, 'error', onerror); // Both close and finish should trigger unpipe, but only once.
76303
76304 function onclose() {
76305 dest.removeListener('finish', onfinish);
76306 unpipe();
76307 }
76308
76309 dest.once('close', onclose);
76310
76311 function onfinish() {
76312 debug('onfinish');
76313 dest.removeListener('close', onclose);
76314 unpipe();
76315 }
76316
76317 dest.once('finish', onfinish);
76318
76319 function unpipe() {
76320 debug('unpipe');
76321 src.unpipe(dest);
76322 } // tell the dest that it's being piped to
76323
76324
76325 dest.emit('pipe', src); // start the flow if it hasn't been started already.
76326
76327 if (!state.flowing) {
76328 debug('pipe resume');
76329 src.resume();
76330 }
76331
76332 return dest;
76333};
76334
76335function pipeOnDrain(src) {
76336 return function pipeOnDrainFunctionResult() {
76337 var state = src._readableState;
76338 debug('pipeOnDrain', state.awaitDrain);
76339 if (state.awaitDrain) state.awaitDrain--;
76340
76341 if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) {
76342 state.flowing = true;
76343 flow(src);
76344 }
76345 };
76346}
76347
76348Readable.prototype.unpipe = function (dest) {
76349 var state = this._readableState;
76350 var unpipeInfo = {
76351 hasUnpiped: false
76352 }; // if we're not piping anywhere, then do nothing.
76353
76354 if (state.pipesCount === 0) return this; // just one destination. most common case.
76355
76356 if (state.pipesCount === 1) {
76357 // passed in one, but it's not the right one.
76358 if (dest && dest !== state.pipes) return this;
76359 if (!dest) dest = state.pipes; // got a match.
76360
76361 state.pipes = null;
76362 state.pipesCount = 0;
76363 state.flowing = false;
76364 if (dest) dest.emit('unpipe', this, unpipeInfo);
76365 return this;
76366 } // slow case. multiple pipe destinations.
76367
76368
76369 if (!dest) {
76370 // remove all.
76371 var dests = state.pipes;
76372 var len = state.pipesCount;
76373 state.pipes = null;
76374 state.pipesCount = 0;
76375 state.flowing = false;
76376
76377 for (var i = 0; i < len; i++) {
76378 dests[i].emit('unpipe', this, {
76379 hasUnpiped: false
76380 });
76381 }
76382
76383 return this;
76384 } // try to find the right one.
76385
76386
76387 var index = indexOf(state.pipes, dest);
76388 if (index === -1) return this;
76389 state.pipes.splice(index, 1);
76390 state.pipesCount -= 1;
76391 if (state.pipesCount === 1) state.pipes = state.pipes[0];
76392 dest.emit('unpipe', this, unpipeInfo);
76393 return this;
76394}; // set up data events if they are asked for
76395// Ensure readable listeners eventually get something
76396
76397
76398Readable.prototype.on = function (ev, fn) {
76399 var res = Stream.prototype.on.call(this, ev, fn);
76400 var state = this._readableState;
76401
76402 if (ev === 'data') {
76403 // update readableListening so that resume() may be a no-op
76404 // a few lines down. This is needed to support once('readable').
76405 state.readableListening = this.listenerCount('readable') > 0; // Try start flowing on next tick if stream isn't explicitly paused
76406
76407 if (state.flowing !== false) this.resume();
76408 } else if (ev === 'readable') {
76409 if (!state.endEmitted && !state.readableListening) {
76410 state.readableListening = state.needReadable = true;
76411 state.flowing = false;
76412 state.emittedReadable = false;
76413 debug('on readable', state.length, state.reading);
76414
76415 if (state.length) {
76416 emitReadable(this);
76417 } else if (!state.reading) {
76418 process.nextTick(nReadingNextTick, this);
76419 }
76420 }
76421 }
76422
76423 return res;
76424};
76425
76426Readable.prototype.addListener = Readable.prototype.on;
76427
76428Readable.prototype.removeListener = function (ev, fn) {
76429 var res = Stream.prototype.removeListener.call(this, ev, fn);
76430
76431 if (ev === 'readable') {
76432 // We need to check if there is someone still listening to
76433 // readable and reset the state. However this needs to happen
76434 // after readable has been emitted but before I/O (nextTick) to
76435 // support once('readable', fn) cycles. This means that calling
76436 // resume within the same tick will have no
76437 // effect.
76438 process.nextTick(updateReadableListening, this);
76439 }
76440
76441 return res;
76442};
76443
76444Readable.prototype.removeAllListeners = function (ev) {
76445 var res = Stream.prototype.removeAllListeners.apply(this, arguments);
76446
76447 if (ev === 'readable' || ev === undefined) {
76448 // We need to check if there is someone still listening to
76449 // readable and reset the state. However this needs to happen
76450 // after readable has been emitted but before I/O (nextTick) to
76451 // support once('readable', fn) cycles. This means that calling
76452 // resume within the same tick will have no
76453 // effect.
76454 process.nextTick(updateReadableListening, this);
76455 }
76456
76457 return res;
76458};
76459
76460function updateReadableListening(self) {
76461 var state = self._readableState;
76462 state.readableListening = self.listenerCount('readable') > 0;
76463
76464 if (state.resumeScheduled && !state.paused) {
76465 // flowing needs to be set to true now, otherwise
76466 // the upcoming resume will not flow.
76467 state.flowing = true; // crude way to check if we should resume
76468 } else if (self.listenerCount('data') > 0) {
76469 self.resume();
76470 }
76471}
76472
76473function nReadingNextTick(self) {
76474 debug('readable nexttick read 0');
76475 self.read(0);
76476} // pause() and resume() are remnants of the legacy readable stream API
76477// If the user uses them, then switch into old mode.
76478
76479
76480Readable.prototype.resume = function () {
76481 var state = this._readableState;
76482
76483 if (!state.flowing) {
76484 debug('resume'); // we flow only if there is no one listening
76485 // for readable, but we still have to call
76486 // resume()
76487
76488 state.flowing = !state.readableListening;
76489 resume(this, state);
76490 }
76491
76492 state.paused = false;
76493 return this;
76494};
76495
76496function resume(stream, state) {
76497 if (!state.resumeScheduled) {
76498 state.resumeScheduled = true;
76499 process.nextTick(resume_, stream, state);
76500 }
76501}
76502
76503function resume_(stream, state) {
76504 debug('resume', state.reading);
76505
76506 if (!state.reading) {
76507 stream.read(0);
76508 }
76509
76510 state.resumeScheduled = false;
76511 stream.emit('resume');
76512 flow(stream);
76513 if (state.flowing && !state.reading) stream.read(0);
76514}
76515
76516Readable.prototype.pause = function () {
76517 debug('call pause flowing=%j', this._readableState.flowing);
76518
76519 if (this._readableState.flowing !== false) {
76520 debug('pause');
76521 this._readableState.flowing = false;
76522 this.emit('pause');
76523 }
76524
76525 this._readableState.paused = true;
76526 return this;
76527};
76528
76529function flow(stream) {
76530 var state = stream._readableState;
76531 debug('flow', state.flowing);
76532
76533 while (state.flowing && stream.read() !== null) {
76534 ;
76535 }
76536} // wrap an old-style stream as the async data source.
76537// This is *not* part of the readable stream interface.
76538// It is an ugly unfortunate mess of history.
76539
76540
76541Readable.prototype.wrap = function (stream) {
76542 var _this = this;
76543
76544 var state = this._readableState;
76545 var paused = false;
76546 stream.on('end', function () {
76547 debug('wrapped end');
76548
76549 if (state.decoder && !state.ended) {
76550 var chunk = state.decoder.end();
76551 if (chunk && chunk.length) _this.push(chunk);
76552 }
76553
76554 _this.push(null);
76555 });
76556 stream.on('data', function (chunk) {
76557 debug('wrapped data');
76558 if (state.decoder) chunk = state.decoder.write(chunk); // don't skip over falsy values in objectMode
76559
76560 if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return;
76561
76562 var ret = _this.push(chunk);
76563
76564 if (!ret) {
76565 paused = true;
76566 stream.pause();
76567 }
76568 }); // proxy all the other methods.
76569 // important when wrapping filters and duplexes.
76570
76571 for (var i in stream) {
76572 if (this[i] === undefined && typeof stream[i] === 'function') {
76573 this[i] = function methodWrap(method) {
76574 return function methodWrapReturnFunction() {
76575 return stream[method].apply(stream, arguments);
76576 };
76577 }(i);
76578 }
76579 } // proxy certain important events.
76580
76581
76582 for (var n = 0; n < kProxyEvents.length; n++) {
76583 stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n]));
76584 } // when we try to consume some more bytes, simply unpause the
76585 // underlying stream.
76586
76587
76588 this._read = function (n) {
76589 debug('wrapped _read', n);
76590
76591 if (paused) {
76592 paused = false;
76593 stream.resume();
76594 }
76595 };
76596
76597 return this;
76598};
76599
76600if (typeof Symbol === 'function') {
76601 Readable.prototype[Symbol.asyncIterator] = function () {
76602 emitExperimentalWarning('Readable[Symbol.asyncIterator]');
76603
76604 if (createReadableStreamAsyncIterator === undefined) {
76605 createReadableStreamAsyncIterator = require('./internal/streams/async_iterator');
76606 }
76607
76608 return createReadableStreamAsyncIterator(this);
76609 };
76610}
76611
76612Object.defineProperty(Readable.prototype, 'readableHighWaterMark', {
76613 // making it explicit this property is not enumerable
76614 // because otherwise some prototype manipulation in
76615 // userland will fail
76616 enumerable: false,
76617 get: function get() {
76618 return this._readableState.highWaterMark;
76619 }
76620});
76621Object.defineProperty(Readable.prototype, 'readableBuffer', {
76622 // making it explicit this property is not enumerable
76623 // because otherwise some prototype manipulation in
76624 // userland will fail
76625 enumerable: false,
76626 get: function get() {
76627 return this._readableState && this._readableState.buffer;
76628 }
76629});
76630Object.defineProperty(Readable.prototype, 'readableFlowing', {
76631 // making it explicit this property is not enumerable
76632 // because otherwise some prototype manipulation in
76633 // userland will fail
76634 enumerable: false,
76635 get: function get() {
76636 return this._readableState.flowing;
76637 },
76638 set: function set(state) {
76639 if (this._readableState) {
76640 this._readableState.flowing = state;
76641 }
76642 }
76643}); // exposed for testing purposes only.
76644
76645Readable._fromList = fromList;
76646Object.defineProperty(Readable.prototype, 'readableLength', {
76647 // making it explicit this property is not enumerable
76648 // because otherwise some prototype manipulation in
76649 // userland will fail
76650 enumerable: false,
76651 get: function get() {
76652 return this._readableState.length;
76653 }
76654}); // Pluck off n bytes from an array of buffers.
76655// Length is the combined lengths of all the buffers in the list.
76656// This function is designed to be inlinable, so please take care when making
76657// changes to the function body.
76658
76659function fromList(n, state) {
76660 // nothing buffered
76661 if (state.length === 0) return null;
76662 var ret;
76663 if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) {
76664 // read it all, truncate the list
76665 if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.first();else ret = state.buffer.concat(state.length);
76666 state.buffer.clear();
76667 } else {
76668 // read part of list
76669 ret = state.buffer.consume(n, state.decoder);
76670 }
76671 return ret;
76672}
76673
76674function endReadable(stream) {
76675 var state = stream._readableState;
76676 debug('endReadable', state.endEmitted);
76677
76678 if (!state.endEmitted) {
76679 state.ended = true;
76680 process.nextTick(endReadableNT, state, stream);
76681 }
76682}
76683
76684function endReadableNT(state, stream) {
76685 debug('endReadableNT', state.endEmitted, state.length); // Check that we didn't get one last unshift.
76686
76687 if (!state.endEmitted && state.length === 0) {
76688 state.endEmitted = true;
76689 stream.readable = false;
76690 stream.emit('end');
76691 }
76692}
76693
76694function indexOf(xs, x) {
76695 for (var i = 0, l = xs.length; i < l; i++) {
76696 if (xs[i] === x) return i;
76697 }
76698
76699 return -1;
76700}
76701}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
76702},{"../errors":366,"../experimentalWarning":367,"./_stream_duplex":368,"./internal/streams/async_iterator":373,"./internal/streams/buffer_list":374,"./internal/streams/destroy":375,"./internal/streams/state":378,"./internal/streams/stream":379,"_process":265,"buffer":114,"events":159,"inherits":210,"string_decoder/":381,"util":82}],371:[function(require,module,exports){
76703// Copyright Joyent, Inc. and other Node contributors.
76704//
76705// Permission is hereby granted, free of charge, to any person obtaining a
76706// copy of this software and associated documentation files (the
76707// "Software"), to deal in the Software without restriction, including
76708// without limitation the rights to use, copy, modify, merge, publish,
76709// distribute, sublicense, and/or sell copies of the Software, and to permit
76710// persons to whom the Software is furnished to do so, subject to the
76711// following conditions:
76712//
76713// The above copyright notice and this permission notice shall be included
76714// in all copies or substantial portions of the Software.
76715//
76716// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
76717// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
76718// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
76719// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
76720// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
76721// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
76722// USE OR OTHER DEALINGS IN THE SOFTWARE.
76723// a transform stream is a readable/writable stream where you do
76724// something with the data. Sometimes it's called a "filter",
76725// but that's not a great name for it, since that implies a thing where
76726// some bits pass through, and others are simply ignored. (That would
76727// be a valid example of a transform, of course.)
76728//
76729// While the output is causally related to the input, it's not a
76730// necessarily symmetric or synchronous transformation. For example,
76731// a zlib stream might take multiple plain-text writes(), and then
76732// emit a single compressed chunk some time in the future.
76733//
76734// Here's how this works:
76735//
76736// The Transform stream has all the aspects of the readable and writable
76737// stream classes. When you write(chunk), that calls _write(chunk,cb)
76738// internally, and returns false if there's a lot of pending writes
76739// buffered up. When you call read(), that calls _read(n) until
76740// there's enough pending readable data buffered up.
76741//
76742// In a transform stream, the written data is placed in a buffer. When
76743// _read(n) is called, it transforms the queued up data, calling the
76744// buffered _write cb's as it consumes chunks. If consuming a single
76745// written chunk would result in multiple output chunks, then the first
76746// outputted bit calls the readcb, and subsequent chunks just go into
76747// the read buffer, and will cause it to emit 'readable' if necessary.
76748//
76749// This way, back-pressure is actually determined by the reading side,
76750// since _read has to be called to start processing a new chunk. However,
76751// a pathological inflate type of transform can cause excessive buffering
76752// here. For example, imagine a stream where every byte of input is
76753// interpreted as an integer from 0-255, and then results in that many
76754// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in
76755// 1kb of data being output. In this case, you could write a very small
76756// amount of input, and end up with a very large amount of output. In
76757// such a pathological inflating mechanism, there'd be no way to tell
76758// the system to stop doing the transform. A single 4MB write could
76759// cause the system to run out of memory.
76760//
76761// However, even in such a pathological case, only a single written chunk
76762// would be consumed, and then the rest would wait (un-transformed) until
76763// the results of the previous transformed chunk were consumed.
76764'use strict';
76765
76766module.exports = Transform;
76767
76768var _require$codes = require('../errors').codes,
76769 ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED,
76770 ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK,
76771 ERR_TRANSFORM_ALREADY_TRANSFORMING = _require$codes.ERR_TRANSFORM_ALREADY_TRANSFORMING,
76772 ERR_TRANSFORM_WITH_LENGTH_0 = _require$codes.ERR_TRANSFORM_WITH_LENGTH_0;
76773
76774var Duplex = require('./_stream_duplex');
76775
76776require('inherits')(Transform, Duplex);
76777
76778function afterTransform(er, data) {
76779 var ts = this._transformState;
76780 ts.transforming = false;
76781 var cb = ts.writecb;
76782
76783 if (cb === null) {
76784 return this.emit('error', new ERR_MULTIPLE_CALLBACK());
76785 }
76786
76787 ts.writechunk = null;
76788 ts.writecb = null;
76789 if (data != null) // single equals check for both `null` and `undefined`
76790 this.push(data);
76791 cb(er);
76792 var rs = this._readableState;
76793 rs.reading = false;
76794
76795 if (rs.needReadable || rs.length < rs.highWaterMark) {
76796 this._read(rs.highWaterMark);
76797 }
76798}
76799
76800function Transform(options) {
76801 if (!(this instanceof Transform)) return new Transform(options);
76802 Duplex.call(this, options);
76803 this._transformState = {
76804 afterTransform: afterTransform.bind(this),
76805 needTransform: false,
76806 transforming: false,
76807 writecb: null,
76808 writechunk: null,
76809 writeencoding: null
76810 }; // start out asking for a readable event once data is transformed.
76811
76812 this._readableState.needReadable = true; // we have implemented the _read method, and done the other things
76813 // that Readable wants before the first _read call, so unset the
76814 // sync guard flag.
76815
76816 this._readableState.sync = false;
76817
76818 if (options) {
76819 if (typeof options.transform === 'function') this._transform = options.transform;
76820 if (typeof options.flush === 'function') this._flush = options.flush;
76821 } // When the writable side finishes, then flush out anything remaining.
76822
76823
76824 this.on('prefinish', prefinish);
76825}
76826
76827function prefinish() {
76828 var _this = this;
76829
76830 if (typeof this._flush === 'function' && !this._readableState.destroyed) {
76831 this._flush(function (er, data) {
76832 done(_this, er, data);
76833 });
76834 } else {
76835 done(this, null, null);
76836 }
76837}
76838
76839Transform.prototype.push = function (chunk, encoding) {
76840 this._transformState.needTransform = false;
76841 return Duplex.prototype.push.call(this, chunk, encoding);
76842}; // This is the part where you do stuff!
76843// override this function in implementation classes.
76844// 'chunk' is an input chunk.
76845//
76846// Call `push(newChunk)` to pass along transformed output
76847// to the readable side. You may call 'push' zero or more times.
76848//
76849// Call `cb(err)` when you are done with this chunk. If you pass
76850// an error, then that'll put the hurt on the whole operation. If you
76851// never call cb(), then you'll never get another chunk.
76852
76853
76854Transform.prototype._transform = function (chunk, encoding, cb) {
76855 cb(new ERR_METHOD_NOT_IMPLEMENTED('_transform()'));
76856};
76857
76858Transform.prototype._write = function (chunk, encoding, cb) {
76859 var ts = this._transformState;
76860 ts.writecb = cb;
76861 ts.writechunk = chunk;
76862 ts.writeencoding = encoding;
76863
76864 if (!ts.transforming) {
76865 var rs = this._readableState;
76866 if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark);
76867 }
76868}; // Doesn't matter what the args are here.
76869// _transform does all the work.
76870// That we got here means that the readable side wants more data.
76871
76872
76873Transform.prototype._read = function (n) {
76874 var ts = this._transformState;
76875
76876 if (ts.writechunk !== null && !ts.transforming) {
76877 ts.transforming = true;
76878
76879 this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);
76880 } else {
76881 // mark that we need a transform, so that any data that comes in
76882 // will get processed, now that we've asked for it.
76883 ts.needTransform = true;
76884 }
76885};
76886
76887Transform.prototype._destroy = function (err, cb) {
76888 Duplex.prototype._destroy.call(this, err, function (err2) {
76889 cb(err2);
76890 });
76891};
76892
76893function done(stream, er, data) {
76894 if (er) return stream.emit('error', er);
76895 if (data != null) // single equals check for both `null` and `undefined`
76896 stream.push(data); // TODO(BridgeAR): Write a test for these two error cases
76897 // if there's nothing in the write buffer, then that means
76898 // that nothing more will ever be provided
76899
76900 if (stream._writableState.length) throw new ERR_TRANSFORM_WITH_LENGTH_0();
76901 if (stream._transformState.transforming) throw new ERR_TRANSFORM_ALREADY_TRANSFORMING();
76902 return stream.push(null);
76903}
76904},{"../errors":366,"./_stream_duplex":368,"inherits":210}],372:[function(require,module,exports){
76905(function (process,global){
76906// Copyright Joyent, Inc. and other Node contributors.
76907//
76908// Permission is hereby granted, free of charge, to any person obtaining a
76909// copy of this software and associated documentation files (the
76910// "Software"), to deal in the Software without restriction, including
76911// without limitation the rights to use, copy, modify, merge, publish,
76912// distribute, sublicense, and/or sell copies of the Software, and to permit
76913// persons to whom the Software is furnished to do so, subject to the
76914// following conditions:
76915//
76916// The above copyright notice and this permission notice shall be included
76917// in all copies or substantial portions of the Software.
76918//
76919// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
76920// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
76921// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
76922// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
76923// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
76924// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
76925// USE OR OTHER DEALINGS IN THE SOFTWARE.
76926// A bit simpler than readable streams.
76927// Implement an async ._write(chunk, encoding, cb), and it'll handle all
76928// the drain event emission and buffering.
76929'use strict';
76930
76931module.exports = Writable;
76932/* <replacement> */
76933
76934function WriteReq(chunk, encoding, cb) {
76935 this.chunk = chunk;
76936 this.encoding = encoding;
76937 this.callback = cb;
76938 this.next = null;
76939} // It seems a linked list but it is not
76940// there will be only 2 of these for each stream
76941
76942
76943function CorkedRequest(state) {
76944 var _this = this;
76945
76946 this.next = null;
76947 this.entry = null;
76948
76949 this.finish = function () {
76950 onCorkedFinish(_this, state);
76951 };
76952}
76953/* </replacement> */
76954
76955/*<replacement>*/
76956
76957
76958var Duplex;
76959/*</replacement>*/
76960
76961Writable.WritableState = WritableState;
76962/*<replacement>*/
76963
76964var internalUtil = {
76965 deprecate: require('util-deprecate')
76966};
76967/*</replacement>*/
76968
76969/*<replacement>*/
76970
76971var Stream = require('./internal/streams/stream');
76972/*</replacement>*/
76973
76974
76975var Buffer = require('buffer').Buffer;
76976
76977var OurUint8Array = global.Uint8Array || function () {};
76978
76979function _uint8ArrayToBuffer(chunk) {
76980 return Buffer.from(chunk);
76981}
76982
76983function _isUint8Array(obj) {
76984 return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
76985}
76986
76987var destroyImpl = require('./internal/streams/destroy');
76988
76989var _require = require('./internal/streams/state'),
76990 getHighWaterMark = _require.getHighWaterMark;
76991
76992var _require$codes = require('../errors').codes,
76993 ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE,
76994 ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED,
76995 ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK,
76996 ERR_STREAM_CANNOT_PIPE = _require$codes.ERR_STREAM_CANNOT_PIPE,
76997 ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED,
76998 ERR_STREAM_NULL_VALUES = _require$codes.ERR_STREAM_NULL_VALUES,
76999 ERR_STREAM_WRITE_AFTER_END = _require$codes.ERR_STREAM_WRITE_AFTER_END,
77000 ERR_UNKNOWN_ENCODING = _require$codes.ERR_UNKNOWN_ENCODING;
77001
77002require('inherits')(Writable, Stream);
77003
77004function nop() {}
77005
77006function WritableState(options, stream, isDuplex) {
77007 Duplex = Duplex || require('./_stream_duplex');
77008 options = options || {}; // Duplex streams are both readable and writable, but share
77009 // the same options object.
77010 // However, some cases require setting options to different
77011 // values for the readable and the writable sides of the duplex stream,
77012 // e.g. options.readableObjectMode vs. options.writableObjectMode, etc.
77013
77014 if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; // object stream flag to indicate whether or not this stream
77015 // contains buffers or objects.
77016
77017 this.objectMode = !!options.objectMode;
77018 if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode; // the point at which write() starts returning false
77019 // Note: 0 is a valid value, means that we always return false if
77020 // the entire buffer is not flushed immediately on write()
77021
77022 this.highWaterMark = getHighWaterMark(this, options, 'writableHighWaterMark', isDuplex); // if _final has been called
77023
77024 this.finalCalled = false; // drain event flag.
77025
77026 this.needDrain = false; // at the start of calling end()
77027
77028 this.ending = false; // when end() has been called, and returned
77029
77030 this.ended = false; // when 'finish' is emitted
77031
77032 this.finished = false; // has it been destroyed
77033
77034 this.destroyed = false; // should we decode strings into buffers before passing to _write?
77035 // this is here so that some node-core streams can optimize string
77036 // handling at a lower level.
77037
77038 var noDecode = options.decodeStrings === false;
77039 this.decodeStrings = !noDecode; // Crypto is kind of old and crusty. Historically, its default string
77040 // encoding is 'binary' so we have to make this configurable.
77041 // Everything else in the universe uses 'utf8', though.
77042
77043 this.defaultEncoding = options.defaultEncoding || 'utf8'; // not an actual buffer we keep track of, but a measurement
77044 // of how much we're waiting to get pushed to some underlying
77045 // socket or file.
77046
77047 this.length = 0; // a flag to see when we're in the middle of a write.
77048
77049 this.writing = false; // when true all writes will be buffered until .uncork() call
77050
77051 this.corked = 0; // a flag to be able to tell if the onwrite cb is called immediately,
77052 // or on a later tick. We set this to true at first, because any
77053 // actions that shouldn't happen until "later" should generally also
77054 // not happen before the first write call.
77055
77056 this.sync = true; // a flag to know if we're processing previously buffered items, which
77057 // may call the _write() callback in the same tick, so that we don't
77058 // end up in an overlapped onwrite situation.
77059
77060 this.bufferProcessing = false; // the callback that's passed to _write(chunk,cb)
77061
77062 this.onwrite = function (er) {
77063 onwrite(stream, er);
77064 }; // the callback that the user supplies to write(chunk,encoding,cb)
77065
77066
77067 this.writecb = null; // the amount that is being written when _write is called.
77068
77069 this.writelen = 0;
77070 this.bufferedRequest = null;
77071 this.lastBufferedRequest = null; // number of pending user-supplied write callbacks
77072 // this must be 0 before 'finish' can be emitted
77073
77074 this.pendingcb = 0; // emit prefinish if the only thing we're waiting for is _write cbs
77075 // This is relevant for synchronous Transform streams
77076
77077 this.prefinished = false; // True if the error was already emitted and should not be thrown again
77078
77079 this.errorEmitted = false; // Should close be emitted on destroy. Defaults to true.
77080
77081 this.emitClose = options.emitClose !== false; // count buffered requests
77082
77083 this.bufferedRequestCount = 0; // allocate the first CorkedRequest, there is always
77084 // one allocated and free to use, and we maintain at most two
77085
77086 this.corkedRequestsFree = new CorkedRequest(this);
77087}
77088
77089WritableState.prototype.getBuffer = function getBuffer() {
77090 var current = this.bufferedRequest;
77091 var out = [];
77092
77093 while (current) {
77094 out.push(current);
77095 current = current.next;
77096 }
77097
77098 return out;
77099};
77100
77101(function () {
77102 try {
77103 Object.defineProperty(WritableState.prototype, 'buffer', {
77104 get: internalUtil.deprecate(function writableStateBufferGetter() {
77105 return this.getBuffer();
77106 }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003')
77107 });
77108 } catch (_) {}
77109})(); // Test _writableState for inheritance to account for Duplex streams,
77110// whose prototype chain only points to Readable.
77111
77112
77113var realHasInstance;
77114
77115if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') {
77116 realHasInstance = Function.prototype[Symbol.hasInstance];
77117 Object.defineProperty(Writable, Symbol.hasInstance, {
77118 value: function value(object) {
77119 if (realHasInstance.call(this, object)) return true;
77120 if (this !== Writable) return false;
77121 return object && object._writableState instanceof WritableState;
77122 }
77123 });
77124} else {
77125 realHasInstance = function realHasInstance(object) {
77126 return object instanceof this;
77127 };
77128}
77129
77130function Writable(options) {
77131 Duplex = Duplex || require('./_stream_duplex'); // Writable ctor is applied to Duplexes, too.
77132 // `realHasInstance` is necessary because using plain `instanceof`
77133 // would return false, as no `_writableState` property is attached.
77134 // Trying to use the custom `instanceof` for Writable here will also break the
77135 // Node.js LazyTransform implementation, which has a non-trivial getter for
77136 // `_writableState` that would lead to infinite recursion.
77137 // Checking for a Stream.Duplex instance is faster here instead of inside
77138 // the WritableState constructor, at least with V8 6.5
77139
77140 var isDuplex = this instanceof Duplex;
77141 if (!isDuplex && !realHasInstance.call(Writable, this)) return new Writable(options);
77142 this._writableState = new WritableState(options, this, isDuplex); // legacy.
77143
77144 this.writable = true;
77145
77146 if (options) {
77147 if (typeof options.write === 'function') this._write = options.write;
77148 if (typeof options.writev === 'function') this._writev = options.writev;
77149 if (typeof options.destroy === 'function') this._destroy = options.destroy;
77150 if (typeof options.final === 'function') this._final = options.final;
77151 }
77152
77153 Stream.call(this);
77154} // Otherwise people can pipe Writable streams, which is just wrong.
77155
77156
77157Writable.prototype.pipe = function () {
77158 this.emit('error', new ERR_STREAM_CANNOT_PIPE());
77159};
77160
77161function writeAfterEnd(stream, cb) {
77162 var er = new ERR_STREAM_WRITE_AFTER_END(); // TODO: defer error events consistently everywhere, not just the cb
77163
77164 stream.emit('error', er);
77165 process.nextTick(cb, er);
77166} // Checks that a user-supplied chunk is valid, especially for the particular
77167// mode the stream is in. Currently this means that `null` is never accepted
77168// and undefined/non-string values are only allowed in object mode.
77169
77170
77171function validChunk(stream, state, chunk, cb) {
77172 var er;
77173
77174 if (chunk === null) {
77175 er = new ERR_STREAM_NULL_VALUES();
77176 } else if (typeof chunk !== 'string' && !state.objectMode) {
77177 er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer'], chunk);
77178 }
77179
77180 if (er) {
77181 stream.emit('error', er);
77182 process.nextTick(cb, er);
77183 return false;
77184 }
77185
77186 return true;
77187}
77188
77189Writable.prototype.write = function (chunk, encoding, cb) {
77190 var state = this._writableState;
77191 var ret = false;
77192
77193 var isBuf = !state.objectMode && _isUint8Array(chunk);
77194
77195 if (isBuf && !Buffer.isBuffer(chunk)) {
77196 chunk = _uint8ArrayToBuffer(chunk);
77197 }
77198
77199 if (typeof encoding === 'function') {
77200 cb = encoding;
77201 encoding = null;
77202 }
77203
77204 if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding;
77205 if (typeof cb !== 'function') cb = nop;
77206 if (state.ending) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) {
77207 state.pendingcb++;
77208 ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb);
77209 }
77210 return ret;
77211};
77212
77213Writable.prototype.cork = function () {
77214 this._writableState.corked++;
77215};
77216
77217Writable.prototype.uncork = function () {
77218 var state = this._writableState;
77219
77220 if (state.corked) {
77221 state.corked--;
77222 if (!state.writing && !state.corked && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state);
77223 }
77224};
77225
77226Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) {
77227 // node::ParseEncoding() requires lower case.
77228 if (typeof encoding === 'string') encoding = encoding.toLowerCase();
77229 if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new ERR_UNKNOWN_ENCODING(encoding);
77230 this._writableState.defaultEncoding = encoding;
77231 return this;
77232};
77233
77234Object.defineProperty(Writable.prototype, 'writableBuffer', {
77235 // making it explicit this property is not enumerable
77236 // because otherwise some prototype manipulation in
77237 // userland will fail
77238 enumerable: false,
77239 get: function get() {
77240 return this._writableState && this._writableState.getBuffer();
77241 }
77242});
77243
77244function decodeChunk(state, chunk, encoding) {
77245 if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') {
77246 chunk = Buffer.from(chunk, encoding);
77247 }
77248
77249 return chunk;
77250}
77251
77252Object.defineProperty(Writable.prototype, 'writableHighWaterMark', {
77253 // making it explicit this property is not enumerable
77254 // because otherwise some prototype manipulation in
77255 // userland will fail
77256 enumerable: false,
77257 get: function get() {
77258 return this._writableState.highWaterMark;
77259 }
77260}); // if we're already writing something, then just put this
77261// in the queue, and wait our turn. Otherwise, call _write
77262// If we return false, then we need a drain event, so set that flag.
77263
77264function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) {
77265 if (!isBuf) {
77266 var newChunk = decodeChunk(state, chunk, encoding);
77267
77268 if (chunk !== newChunk) {
77269 isBuf = true;
77270 encoding = 'buffer';
77271 chunk = newChunk;
77272 }
77273 }
77274
77275 var len = state.objectMode ? 1 : chunk.length;
77276 state.length += len;
77277 var ret = state.length < state.highWaterMark; // we must ensure that previous needDrain will not be reset to false.
77278
77279 if (!ret) state.needDrain = true;
77280
77281 if (state.writing || state.corked) {
77282 var last = state.lastBufferedRequest;
77283 state.lastBufferedRequest = {
77284 chunk: chunk,
77285 encoding: encoding,
77286 isBuf: isBuf,
77287 callback: cb,
77288 next: null
77289 };
77290
77291 if (last) {
77292 last.next = state.lastBufferedRequest;
77293 } else {
77294 state.bufferedRequest = state.lastBufferedRequest;
77295 }
77296
77297 state.bufferedRequestCount += 1;
77298 } else {
77299 doWrite(stream, state, false, len, chunk, encoding, cb);
77300 }
77301
77302 return ret;
77303}
77304
77305function doWrite(stream, state, writev, len, chunk, encoding, cb) {
77306 state.writelen = len;
77307 state.writecb = cb;
77308 state.writing = true;
77309 state.sync = true;
77310 if (state.destroyed) state.onwrite(new ERR_STREAM_DESTROYED('write'));else if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite);
77311 state.sync = false;
77312}
77313
77314function onwriteError(stream, state, sync, er, cb) {
77315 --state.pendingcb;
77316
77317 if (sync) {
77318 // defer the callback if we are being called synchronously
77319 // to avoid piling up things on the stack
77320 process.nextTick(cb, er); // this can emit finish, and it will always happen
77321 // after error
77322
77323 process.nextTick(finishMaybe, stream, state);
77324 stream._writableState.errorEmitted = true;
77325 stream.emit('error', er);
77326 } else {
77327 // the caller expect this to happen before if
77328 // it is async
77329 cb(er);
77330 stream._writableState.errorEmitted = true;
77331 stream.emit('error', er); // this can emit finish, but finish must
77332 // always follow error
77333
77334 finishMaybe(stream, state);
77335 }
77336}
77337
77338function onwriteStateUpdate(state) {
77339 state.writing = false;
77340 state.writecb = null;
77341 state.length -= state.writelen;
77342 state.writelen = 0;
77343}
77344
77345function onwrite(stream, er) {
77346 var state = stream._writableState;
77347 var sync = state.sync;
77348 var cb = state.writecb;
77349 if (typeof cb !== 'function') throw new ERR_MULTIPLE_CALLBACK();
77350 onwriteStateUpdate(state);
77351 if (er) onwriteError(stream, state, sync, er, cb);else {
77352 // Check if we're actually ready to finish, but don't emit yet
77353 var finished = needFinish(state) || stream.destroyed;
77354
77355 if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) {
77356 clearBuffer(stream, state);
77357 }
77358
77359 if (sync) {
77360 process.nextTick(afterWrite, stream, state, finished, cb);
77361 } else {
77362 afterWrite(stream, state, finished, cb);
77363 }
77364 }
77365}
77366
77367function afterWrite(stream, state, finished, cb) {
77368 if (!finished) onwriteDrain(stream, state);
77369 state.pendingcb--;
77370 cb();
77371 finishMaybe(stream, state);
77372} // Must force callback to be called on nextTick, so that we don't
77373// emit 'drain' before the write() consumer gets the 'false' return
77374// value, and has a chance to attach a 'drain' listener.
77375
77376
77377function onwriteDrain(stream, state) {
77378 if (state.length === 0 && state.needDrain) {
77379 state.needDrain = false;
77380 stream.emit('drain');
77381 }
77382} // if there's something in the buffer waiting, then process it
77383
77384
77385function clearBuffer(stream, state) {
77386 state.bufferProcessing = true;
77387 var entry = state.bufferedRequest;
77388
77389 if (stream._writev && entry && entry.next) {
77390 // Fast case, write everything using _writev()
77391 var l = state.bufferedRequestCount;
77392 var buffer = new Array(l);
77393 var holder = state.corkedRequestsFree;
77394 holder.entry = entry;
77395 var count = 0;
77396 var allBuffers = true;
77397
77398 while (entry) {
77399 buffer[count] = entry;
77400 if (!entry.isBuf) allBuffers = false;
77401 entry = entry.next;
77402 count += 1;
77403 }
77404
77405 buffer.allBuffers = allBuffers;
77406 doWrite(stream, state, true, state.length, buffer, '', holder.finish); // doWrite is almost always async, defer these to save a bit of time
77407 // as the hot path ends with doWrite
77408
77409 state.pendingcb++;
77410 state.lastBufferedRequest = null;
77411
77412 if (holder.next) {
77413 state.corkedRequestsFree = holder.next;
77414 holder.next = null;
77415 } else {
77416 state.corkedRequestsFree = new CorkedRequest(state);
77417 }
77418
77419 state.bufferedRequestCount = 0;
77420 } else {
77421 // Slow case, write chunks one-by-one
77422 while (entry) {
77423 var chunk = entry.chunk;
77424 var encoding = entry.encoding;
77425 var cb = entry.callback;
77426 var len = state.objectMode ? 1 : chunk.length;
77427 doWrite(stream, state, false, len, chunk, encoding, cb);
77428 entry = entry.next;
77429 state.bufferedRequestCount--; // if we didn't call the onwrite immediately, then
77430 // it means that we need to wait until it does.
77431 // also, that means that the chunk and cb are currently
77432 // being processed, so move the buffer counter past them.
77433
77434 if (state.writing) {
77435 break;
77436 }
77437 }
77438
77439 if (entry === null) state.lastBufferedRequest = null;
77440 }
77441
77442 state.bufferedRequest = entry;
77443 state.bufferProcessing = false;
77444}
77445
77446Writable.prototype._write = function (chunk, encoding, cb) {
77447 cb(new ERR_METHOD_NOT_IMPLEMENTED('_write()'));
77448};
77449
77450Writable.prototype._writev = null;
77451
77452Writable.prototype.end = function (chunk, encoding, cb) {
77453 var state = this._writableState;
77454
77455 if (typeof chunk === 'function') {
77456 cb = chunk;
77457 chunk = null;
77458 encoding = null;
77459 } else if (typeof encoding === 'function') {
77460 cb = encoding;
77461 encoding = null;
77462 }
77463
77464 if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); // .end() fully uncorks
77465
77466 if (state.corked) {
77467 state.corked = 1;
77468 this.uncork();
77469 } // ignore unnecessary end() calls.
77470
77471
77472 if (!state.ending) endWritable(this, state, cb);
77473 return this;
77474};
77475
77476Object.defineProperty(Writable.prototype, 'writableLength', {
77477 // making it explicit this property is not enumerable
77478 // because otherwise some prototype manipulation in
77479 // userland will fail
77480 enumerable: false,
77481 get: function get() {
77482 return this._writableState.length;
77483 }
77484});
77485
77486function needFinish(state) {
77487 return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing;
77488}
77489
77490function callFinal(stream, state) {
77491 stream._final(function (err) {
77492 state.pendingcb--;
77493
77494 if (err) {
77495 stream.emit('error', err);
77496 }
77497
77498 state.prefinished = true;
77499 stream.emit('prefinish');
77500 finishMaybe(stream, state);
77501 });
77502}
77503
77504function prefinish(stream, state) {
77505 if (!state.prefinished && !state.finalCalled) {
77506 if (typeof stream._final === 'function' && !state.destroyed) {
77507 state.pendingcb++;
77508 state.finalCalled = true;
77509 process.nextTick(callFinal, stream, state);
77510 } else {
77511 state.prefinished = true;
77512 stream.emit('prefinish');
77513 }
77514 }
77515}
77516
77517function finishMaybe(stream, state) {
77518 var need = needFinish(state);
77519
77520 if (need) {
77521 prefinish(stream, state);
77522
77523 if (state.pendingcb === 0) {
77524 state.finished = true;
77525 stream.emit('finish');
77526 }
77527 }
77528
77529 return need;
77530}
77531
77532function endWritable(stream, state, cb) {
77533 state.ending = true;
77534 finishMaybe(stream, state);
77535
77536 if (cb) {
77537 if (state.finished) process.nextTick(cb);else stream.once('finish', cb);
77538 }
77539
77540 state.ended = true;
77541 stream.writable = false;
77542}
77543
77544function onCorkedFinish(corkReq, state, err) {
77545 var entry = corkReq.entry;
77546 corkReq.entry = null;
77547
77548 while (entry) {
77549 var cb = entry.callback;
77550 state.pendingcb--;
77551 cb(err);
77552 entry = entry.next;
77553 } // reuse the free corkReq.
77554
77555
77556 state.corkedRequestsFree.next = corkReq;
77557}
77558
77559Object.defineProperty(Writable.prototype, 'destroyed', {
77560 // making it explicit this property is not enumerable
77561 // because otherwise some prototype manipulation in
77562 // userland will fail
77563 enumerable: false,
77564 get: function get() {
77565 if (this._writableState === undefined) {
77566 return false;
77567 }
77568
77569 return this._writableState.destroyed;
77570 },
77571 set: function set(value) {
77572 // we ignore the value if the stream
77573 // has not been initialized yet
77574 if (!this._writableState) {
77575 return;
77576 } // backward compatibility, the user is explicitly
77577 // managing destroyed
77578
77579
77580 this._writableState.destroyed = value;
77581 }
77582});
77583Writable.prototype.destroy = destroyImpl.destroy;
77584Writable.prototype._undestroy = destroyImpl.undestroy;
77585
77586Writable.prototype._destroy = function (err, cb) {
77587 cb(err);
77588};
77589}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
77590},{"../errors":366,"./_stream_duplex":368,"./internal/streams/destroy":375,"./internal/streams/state":378,"./internal/streams/stream":379,"_process":265,"buffer":114,"inherits":210,"util-deprecate":395}],373:[function(require,module,exports){
77591(function (process){
77592'use strict';
77593
77594var _Object$setPrototypeO;
77595
77596function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
77597
77598var finished = require('./end-of-stream');
77599
77600var kLastResolve = Symbol('lastResolve');
77601var kLastReject = Symbol('lastReject');
77602var kError = Symbol('error');
77603var kEnded = Symbol('ended');
77604var kLastPromise = Symbol('lastPromise');
77605var kHandlePromise = Symbol('handlePromise');
77606var kStream = Symbol('stream');
77607
77608function createIterResult(value, done) {
77609 return {
77610 value: value,
77611 done: done
77612 };
77613}
77614
77615function readAndResolve(iter) {
77616 var resolve = iter[kLastResolve];
77617
77618 if (resolve !== null) {
77619 var data = iter[kStream].read(); // we defer if data is null
77620 // we can be expecting either 'end' or
77621 // 'error'
77622
77623 if (data !== null) {
77624 iter[kLastPromise] = null;
77625 iter[kLastResolve] = null;
77626 iter[kLastReject] = null;
77627 resolve(createIterResult(data, false));
77628 }
77629 }
77630}
77631
77632function onReadable(iter) {
77633 // we wait for the next tick, because it might
77634 // emit an error with process.nextTick
77635 process.nextTick(readAndResolve, iter);
77636}
77637
77638function wrapForNext(lastPromise, iter) {
77639 return function (resolve, reject) {
77640 lastPromise.then(function () {
77641 if (iter[kEnded]) {
77642 resolve(createIterResult(undefined, true));
77643 return;
77644 }
77645
77646 iter[kHandlePromise](resolve, reject);
77647 }, reject);
77648 };
77649}
77650
77651var AsyncIteratorPrototype = Object.getPrototypeOf(function () {});
77652var ReadableStreamAsyncIteratorPrototype = Object.setPrototypeOf((_Object$setPrototypeO = {
77653 get stream() {
77654 return this[kStream];
77655 },
77656
77657 next: function next() {
77658 var _this = this;
77659
77660 // if we have detected an error in the meanwhile
77661 // reject straight away
77662 var error = this[kError];
77663
77664 if (error !== null) {
77665 return Promise.reject(error);
77666 }
77667
77668 if (this[kEnded]) {
77669 return Promise.resolve(createIterResult(undefined, true));
77670 }
77671
77672 if (this[kStream].destroyed) {
77673 // We need to defer via nextTick because if .destroy(err) is
77674 // called, the error will be emitted via nextTick, and
77675 // we cannot guarantee that there is no error lingering around
77676 // waiting to be emitted.
77677 return new Promise(function (resolve, reject) {
77678 process.nextTick(function () {
77679 if (_this[kError]) {
77680 reject(_this[kError]);
77681 } else {
77682 resolve(createIterResult(undefined, true));
77683 }
77684 });
77685 });
77686 } // if we have multiple next() calls
77687 // we will wait for the previous Promise to finish
77688 // this logic is optimized to support for await loops,
77689 // where next() is only called once at a time
77690
77691
77692 var lastPromise = this[kLastPromise];
77693 var promise;
77694
77695 if (lastPromise) {
77696 promise = new Promise(wrapForNext(lastPromise, this));
77697 } else {
77698 // fast path needed to support multiple this.push()
77699 // without triggering the next() queue
77700 var data = this[kStream].read();
77701
77702 if (data !== null) {
77703 return Promise.resolve(createIterResult(data, false));
77704 }
77705
77706 promise = new Promise(this[kHandlePromise]);
77707 }
77708
77709 this[kLastPromise] = promise;
77710 return promise;
77711 }
77712}, _defineProperty(_Object$setPrototypeO, Symbol.asyncIterator, function () {
77713 return this;
77714}), _defineProperty(_Object$setPrototypeO, "return", function _return() {
77715 var _this2 = this;
77716
77717 // destroy(err, cb) is a private API
77718 // we can guarantee we have that here, because we control the
77719 // Readable class this is attached to
77720 return new Promise(function (resolve, reject) {
77721 _this2[kStream].destroy(null, function (err) {
77722 if (err) {
77723 reject(err);
77724 return;
77725 }
77726
77727 resolve(createIterResult(undefined, true));
77728 });
77729 });
77730}), _Object$setPrototypeO), AsyncIteratorPrototype);
77731
77732var createReadableStreamAsyncIterator = function createReadableStreamAsyncIterator(stream) {
77733 var _Object$create;
77734
77735 var iterator = Object.create(ReadableStreamAsyncIteratorPrototype, (_Object$create = {}, _defineProperty(_Object$create, kStream, {
77736 value: stream,
77737 writable: true
77738 }), _defineProperty(_Object$create, kLastResolve, {
77739 value: null,
77740 writable: true
77741 }), _defineProperty(_Object$create, kLastReject, {
77742 value: null,
77743 writable: true
77744 }), _defineProperty(_Object$create, kError, {
77745 value: null,
77746 writable: true
77747 }), _defineProperty(_Object$create, kEnded, {
77748 value: stream._readableState.endEmitted,
77749 writable: true
77750 }), _defineProperty(_Object$create, kHandlePromise, {
77751 value: function value(resolve, reject) {
77752 var data = iterator[kStream].read();
77753
77754 if (data) {
77755 iterator[kLastPromise] = null;
77756 iterator[kLastResolve] = null;
77757 iterator[kLastReject] = null;
77758 resolve(createIterResult(data, false));
77759 } else {
77760 iterator[kLastResolve] = resolve;
77761 iterator[kLastReject] = reject;
77762 }
77763 },
77764 writable: true
77765 }), _Object$create));
77766 iterator[kLastPromise] = null;
77767 finished(stream, function (err) {
77768 if (err && err.code !== 'ERR_STREAM_PREMATURE_CLOSE') {
77769 var reject = iterator[kLastReject]; // reject if we are waiting for data in the Promise
77770 // returned by next() and store the error
77771
77772 if (reject !== null) {
77773 iterator[kLastPromise] = null;
77774 iterator[kLastResolve] = null;
77775 iterator[kLastReject] = null;
77776 reject(err);
77777 }
77778
77779 iterator[kError] = err;
77780 return;
77781 }
77782
77783 var resolve = iterator[kLastResolve];
77784
77785 if (resolve !== null) {
77786 iterator[kLastPromise] = null;
77787 iterator[kLastResolve] = null;
77788 iterator[kLastReject] = null;
77789 resolve(createIterResult(undefined, true));
77790 }
77791
77792 iterator[kEnded] = true;
77793 });
77794 stream.on('readable', onReadable.bind(null, iterator));
77795 return iterator;
77796};
77797
77798module.exports = createReadableStreamAsyncIterator;
77799}).call(this,require('_process'))
77800},{"./end-of-stream":376,"_process":265}],374:[function(require,module,exports){
77801'use strict';
77802
77803function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; var ownKeys = Object.keys(source); if (typeof Object.getOwnPropertySymbols === 'function') { ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { return Object.getOwnPropertyDescriptor(source, sym).enumerable; })); } ownKeys.forEach(function (key) { _defineProperty(target, key, source[key]); }); } return target; }
77804
77805function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
77806
77807var _require = require('buffer'),
77808 Buffer = _require.Buffer;
77809
77810var _require2 = require('util'),
77811 inspect = _require2.inspect;
77812
77813var custom = inspect && inspect.custom || 'inspect';
77814
77815function copyBuffer(src, target, offset) {
77816 Buffer.prototype.copy.call(src, target, offset);
77817}
77818
77819module.exports =
77820/*#__PURE__*/
77821function () {
77822 function BufferList() {
77823 this.head = null;
77824 this.tail = null;
77825 this.length = 0;
77826 }
77827
77828 var _proto = BufferList.prototype;
77829
77830 _proto.push = function push(v) {
77831 var entry = {
77832 data: v,
77833 next: null
77834 };
77835 if (this.length > 0) this.tail.next = entry;else this.head = entry;
77836 this.tail = entry;
77837 ++this.length;
77838 };
77839
77840 _proto.unshift = function unshift(v) {
77841 var entry = {
77842 data: v,
77843 next: this.head
77844 };
77845 if (this.length === 0) this.tail = entry;
77846 this.head = entry;
77847 ++this.length;
77848 };
77849
77850 _proto.shift = function shift() {
77851 if (this.length === 0) return;
77852 var ret = this.head.data;
77853 if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next;
77854 --this.length;
77855 return ret;
77856 };
77857
77858 _proto.clear = function clear() {
77859 this.head = this.tail = null;
77860 this.length = 0;
77861 };
77862
77863 _proto.join = function join(s) {
77864 if (this.length === 0) return '';
77865 var p = this.head;
77866 var ret = '' + p.data;
77867
77868 while (p = p.next) {
77869 ret += s + p.data;
77870 }
77871
77872 return ret;
77873 };
77874
77875 _proto.concat = function concat(n) {
77876 if (this.length === 0) return Buffer.alloc(0);
77877 var ret = Buffer.allocUnsafe(n >>> 0);
77878 var p = this.head;
77879 var i = 0;
77880
77881 while (p) {
77882 copyBuffer(p.data, ret, i);
77883 i += p.data.length;
77884 p = p.next;
77885 }
77886
77887 return ret;
77888 } // Consumes a specified amount of bytes or characters from the buffered data.
77889 ;
77890
77891 _proto.consume = function consume(n, hasStrings) {
77892 var ret;
77893
77894 if (n < this.head.data.length) {
77895 // `slice` is the same for buffers and strings.
77896 ret = this.head.data.slice(0, n);
77897 this.head.data = this.head.data.slice(n);
77898 } else if (n === this.head.data.length) {
77899 // First chunk is a perfect match.
77900 ret = this.shift();
77901 } else {
77902 // Result spans more than one buffer.
77903 ret = hasStrings ? this._getString(n) : this._getBuffer(n);
77904 }
77905
77906 return ret;
77907 };
77908
77909 _proto.first = function first() {
77910 return this.head.data;
77911 } // Consumes a specified amount of characters from the buffered data.
77912 ;
77913
77914 _proto._getString = function _getString(n) {
77915 var p = this.head;
77916 var c = 1;
77917 var ret = p.data;
77918 n -= ret.length;
77919
77920 while (p = p.next) {
77921 var str = p.data;
77922 var nb = n > str.length ? str.length : n;
77923 if (nb === str.length) ret += str;else ret += str.slice(0, n);
77924 n -= nb;
77925
77926 if (n === 0) {
77927 if (nb === str.length) {
77928 ++c;
77929 if (p.next) this.head = p.next;else this.head = this.tail = null;
77930 } else {
77931 this.head = p;
77932 p.data = str.slice(nb);
77933 }
77934
77935 break;
77936 }
77937
77938 ++c;
77939 }
77940
77941 this.length -= c;
77942 return ret;
77943 } // Consumes a specified amount of bytes from the buffered data.
77944 ;
77945
77946 _proto._getBuffer = function _getBuffer(n) {
77947 var ret = Buffer.allocUnsafe(n);
77948 var p = this.head;
77949 var c = 1;
77950 p.data.copy(ret);
77951 n -= p.data.length;
77952
77953 while (p = p.next) {
77954 var buf = p.data;
77955 var nb = n > buf.length ? buf.length : n;
77956 buf.copy(ret, ret.length - n, 0, nb);
77957 n -= nb;
77958
77959 if (n === 0) {
77960 if (nb === buf.length) {
77961 ++c;
77962 if (p.next) this.head = p.next;else this.head = this.tail = null;
77963 } else {
77964 this.head = p;
77965 p.data = buf.slice(nb);
77966 }
77967
77968 break;
77969 }
77970
77971 ++c;
77972 }
77973
77974 this.length -= c;
77975 return ret;
77976 } // Make sure the linked list only shows the minimal necessary information.
77977 ;
77978
77979 _proto[custom] = function (_, options) {
77980 return inspect(this, _objectSpread({}, options, {
77981 // Only inspect one level.
77982 depth: 0,
77983 // It should not recurse.
77984 customInspect: false
77985 }));
77986 };
77987
77988 return BufferList;
77989}();
77990},{"buffer":114,"util":82}],375:[function(require,module,exports){
77991(function (process){
77992'use strict'; // undocumented cb() API, needed for core, not for public API
77993
77994function destroy(err, cb) {
77995 var _this = this;
77996
77997 var readableDestroyed = this._readableState && this._readableState.destroyed;
77998 var writableDestroyed = this._writableState && this._writableState.destroyed;
77999
78000 if (readableDestroyed || writableDestroyed) {
78001 if (cb) {
78002 cb(err);
78003 } else if (err && (!this._writableState || !this._writableState.errorEmitted)) {
78004 process.nextTick(emitErrorNT, this, err);
78005 }
78006
78007 return this;
78008 } // we set destroyed to true before firing error callbacks in order
78009 // to make it re-entrance safe in case destroy() is called within callbacks
78010
78011
78012 if (this._readableState) {
78013 this._readableState.destroyed = true;
78014 } // if this is a duplex stream mark the writable part as destroyed as well
78015
78016
78017 if (this._writableState) {
78018 this._writableState.destroyed = true;
78019 }
78020
78021 this._destroy(err || null, function (err) {
78022 if (!cb && err) {
78023 process.nextTick(emitErrorAndCloseNT, _this, err);
78024
78025 if (_this._writableState) {
78026 _this._writableState.errorEmitted = true;
78027 }
78028 } else if (cb) {
78029 process.nextTick(emitCloseNT, _this);
78030 cb(err);
78031 } else {
78032 process.nextTick(emitCloseNT, _this);
78033 }
78034 });
78035
78036 return this;
78037}
78038
78039function emitErrorAndCloseNT(self, err) {
78040 emitErrorNT(self, err);
78041 emitCloseNT(self);
78042}
78043
78044function emitCloseNT(self) {
78045 if (self._writableState && !self._writableState.emitClose) return;
78046 if (self._readableState && !self._readableState.emitClose) return;
78047 self.emit('close');
78048}
78049
78050function undestroy() {
78051 if (this._readableState) {
78052 this._readableState.destroyed = false;
78053 this._readableState.reading = false;
78054 this._readableState.ended = false;
78055 this._readableState.endEmitted = false;
78056 }
78057
78058 if (this._writableState) {
78059 this._writableState.destroyed = false;
78060 this._writableState.ended = false;
78061 this._writableState.ending = false;
78062 this._writableState.finalCalled = false;
78063 this._writableState.prefinished = false;
78064 this._writableState.finished = false;
78065 this._writableState.errorEmitted = false;
78066 }
78067}
78068
78069function emitErrorNT(self, err) {
78070 self.emit('error', err);
78071}
78072
78073module.exports = {
78074 destroy: destroy,
78075 undestroy: undestroy
78076};
78077}).call(this,require('_process'))
78078},{"_process":265}],376:[function(require,module,exports){
78079// Ported from https://github.com/mafintosh/end-of-stream with
78080// permission from the author, Mathias Buus (@mafintosh).
78081'use strict';
78082
78083var ERR_STREAM_PREMATURE_CLOSE = require('../../../errors').codes.ERR_STREAM_PREMATURE_CLOSE;
78084
78085function once(callback) {
78086 var called = false;
78087 return function () {
78088 if (called) return;
78089 called = true;
78090
78091 for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
78092 args[_key] = arguments[_key];
78093 }
78094
78095 callback.apply(this, args);
78096 };
78097}
78098
78099function noop() {}
78100
78101function isRequest(stream) {
78102 return stream.setHeader && typeof stream.abort === 'function';
78103}
78104
78105function eos(stream, opts, callback) {
78106 if (typeof opts === 'function') return eos(stream, null, opts);
78107 if (!opts) opts = {};
78108 callback = once(callback || noop);
78109 var readable = opts.readable || opts.readable !== false && stream.readable;
78110 var writable = opts.writable || opts.writable !== false && stream.writable;
78111
78112 var onlegacyfinish = function onlegacyfinish() {
78113 if (!stream.writable) onfinish();
78114 };
78115
78116 var writableEnded = stream._writableState && stream._writableState.finished;
78117
78118 var onfinish = function onfinish() {
78119 writable = false;
78120 writableEnded = true;
78121 if (!readable) callback.call(stream);
78122 };
78123
78124 var readableEnded = stream._readableState && stream._readableState.endEmitted;
78125
78126 var onend = function onend() {
78127 readable = false;
78128 readableEnded = true;
78129 if (!writable) callback.call(stream);
78130 };
78131
78132 var onerror = function onerror(err) {
78133 callback.call(stream, err);
78134 };
78135
78136 var onclose = function onclose() {
78137 var err;
78138
78139 if (readable && !readableEnded) {
78140 if (!stream._readableState || !stream._readableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE();
78141 return callback.call(stream, err);
78142 }
78143
78144 if (writable && !writableEnded) {
78145 if (!stream._writableState || !stream._writableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE();
78146 return callback.call(stream, err);
78147 }
78148 };
78149
78150 var onrequest = function onrequest() {
78151 stream.req.on('finish', onfinish);
78152 };
78153
78154 if (isRequest(stream)) {
78155 stream.on('complete', onfinish);
78156 stream.on('abort', onclose);
78157 if (stream.req) onrequest();else stream.on('request', onrequest);
78158 } else if (writable && !stream._writableState) {
78159 // legacy streams
78160 stream.on('end', onlegacyfinish);
78161 stream.on('close', onlegacyfinish);
78162 }
78163
78164 stream.on('end', onend);
78165 stream.on('finish', onfinish);
78166 if (opts.error !== false) stream.on('error', onerror);
78167 stream.on('close', onclose);
78168 return function () {
78169 stream.removeListener('complete', onfinish);
78170 stream.removeListener('abort', onclose);
78171 stream.removeListener('request', onrequest);
78172 if (stream.req) stream.req.removeListener('finish', onfinish);
78173 stream.removeListener('end', onlegacyfinish);
78174 stream.removeListener('close', onlegacyfinish);
78175 stream.removeListener('finish', onfinish);
78176 stream.removeListener('end', onend);
78177 stream.removeListener('error', onerror);
78178 stream.removeListener('close', onclose);
78179 };
78180}
78181
78182module.exports = eos;
78183},{"../../../errors":366}],377:[function(require,module,exports){
78184// Ported from https://github.com/mafintosh/pump with
78185// permission from the author, Mathias Buus (@mafintosh).
78186'use strict';
78187
78188var eos;
78189
78190function once(callback) {
78191 var called = false;
78192 return function () {
78193 if (called) return;
78194 called = true;
78195 callback.apply(void 0, arguments);
78196 };
78197}
78198
78199var _require$codes = require('../../../errors').codes,
78200 ERR_MISSING_ARGS = _require$codes.ERR_MISSING_ARGS,
78201 ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED;
78202
78203function noop(err) {
78204 // Rethrow the error if it exists to avoid swallowing it
78205 if (err) throw err;
78206}
78207
78208function isRequest(stream) {
78209 return stream.setHeader && typeof stream.abort === 'function';
78210}
78211
78212function destroyer(stream, reading, writing, callback) {
78213 callback = once(callback);
78214 var closed = false;
78215 stream.on('close', function () {
78216 closed = true;
78217 });
78218 if (eos === undefined) eos = require('./end-of-stream');
78219 eos(stream, {
78220 readable: reading,
78221 writable: writing
78222 }, function (err) {
78223 if (err) return callback(err);
78224 closed = true;
78225 callback();
78226 });
78227 var destroyed = false;
78228 return function (err) {
78229 if (closed) return;
78230 if (destroyed) return;
78231 destroyed = true; // request.destroy just do .end - .abort is what we want
78232
78233 if (isRequest(stream)) return stream.abort();
78234 if (typeof stream.destroy === 'function') return stream.destroy();
78235 callback(err || new ERR_STREAM_DESTROYED('pipe'));
78236 };
78237}
78238
78239function call(fn) {
78240 fn();
78241}
78242
78243function pipe(from, to) {
78244 return from.pipe(to);
78245}
78246
78247function popCallback(streams) {
78248 if (!streams.length) return noop;
78249 if (typeof streams[streams.length - 1] !== 'function') return noop;
78250 return streams.pop();
78251}
78252
78253function pipeline() {
78254 for (var _len = arguments.length, streams = new Array(_len), _key = 0; _key < _len; _key++) {
78255 streams[_key] = arguments[_key];
78256 }
78257
78258 var callback = popCallback(streams);
78259 if (Array.isArray(streams[0])) streams = streams[0];
78260
78261 if (streams.length < 2) {
78262 throw new ERR_MISSING_ARGS('streams');
78263 }
78264
78265 var error;
78266 var destroys = streams.map(function (stream, i) {
78267 var reading = i < streams.length - 1;
78268 var writing = i > 0;
78269 return destroyer(stream, reading, writing, function (err) {
78270 if (!error) error = err;
78271 if (err) destroys.forEach(call);
78272 if (reading) return;
78273 destroys.forEach(call);
78274 callback(error);
78275 });
78276 });
78277 return streams.reduce(pipe);
78278}
78279
78280module.exports = pipeline;
78281},{"../../../errors":366,"./end-of-stream":376}],378:[function(require,module,exports){
78282'use strict';
78283
78284var ERR_INVALID_OPT_VALUE = require('../../../errors').codes.ERR_INVALID_OPT_VALUE;
78285
78286function highWaterMarkFrom(options, isDuplex, duplexKey) {
78287 return options.highWaterMark != null ? options.highWaterMark : isDuplex ? options[duplexKey] : null;
78288}
78289
78290function getHighWaterMark(state, options, duplexKey, isDuplex) {
78291 var hwm = highWaterMarkFrom(options, isDuplex, duplexKey);
78292
78293 if (hwm != null) {
78294 if (!(isFinite(hwm) && Math.floor(hwm) === hwm) || hwm < 0) {
78295 var name = isDuplex ? duplexKey : 'highWaterMark';
78296 throw new ERR_INVALID_OPT_VALUE(name, hwm);
78297 }
78298
78299 return Math.floor(hwm);
78300 } // Default value
78301
78302
78303 return state.objectMode ? 16 : 16 * 1024;
78304}
78305
78306module.exports = {
78307 getHighWaterMark: getHighWaterMark
78308};
78309},{"../../../errors":366}],379:[function(require,module,exports){
78310arguments[4][288][0].apply(exports,arguments)
78311},{"dup":288,"events":159}],380:[function(require,module,exports){
78312exports = module.exports = require('./lib/_stream_readable.js');
78313exports.Stream = exports;
78314exports.Readable = exports;
78315exports.Writable = require('./lib/_stream_writable.js');
78316exports.Duplex = require('./lib/_stream_duplex.js');
78317exports.Transform = require('./lib/_stream_transform.js');
78318exports.PassThrough = require('./lib/_stream_passthrough.js');
78319exports.finished = require('./lib/internal/streams/end-of-stream.js');
78320exports.pipeline = require('./lib/internal/streams/pipeline.js');
78321
78322},{"./lib/_stream_duplex.js":368,"./lib/_stream_passthrough.js":369,"./lib/_stream_readable.js":370,"./lib/_stream_transform.js":371,"./lib/_stream_writable.js":372,"./lib/internal/streams/end-of-stream.js":376,"./lib/internal/streams/pipeline.js":377}],381:[function(require,module,exports){
78323arguments[4][289][0].apply(exports,arguments)
78324},{"dup":289,"safe-buffer":325}],382:[function(require,module,exports){
78325(function (setImmediate,clearImmediate){
78326var nextTick = require('process/browser.js').nextTick;
78327var apply = Function.prototype.apply;
78328var slice = Array.prototype.slice;
78329var immediateIds = {};
78330var nextImmediateId = 0;
78331
78332// DOM APIs, for completeness
78333
78334exports.setTimeout = function() {
78335 return new Timeout(apply.call(setTimeout, window, arguments), clearTimeout);
78336};
78337exports.setInterval = function() {
78338 return new Timeout(apply.call(setInterval, window, arguments), clearInterval);
78339};
78340exports.clearTimeout =
78341exports.clearInterval = function(timeout) { timeout.close(); };
78342
78343function Timeout(id, clearFn) {
78344 this._id = id;
78345 this._clearFn = clearFn;
78346}
78347Timeout.prototype.unref = Timeout.prototype.ref = function() {};
78348Timeout.prototype.close = function() {
78349 this._clearFn.call(window, this._id);
78350};
78351
78352// Does not start the time, just sets up the members needed.
78353exports.enroll = function(item, msecs) {
78354 clearTimeout(item._idleTimeoutId);
78355 item._idleTimeout = msecs;
78356};
78357
78358exports.unenroll = function(item) {
78359 clearTimeout(item._idleTimeoutId);
78360 item._idleTimeout = -1;
78361};
78362
78363exports._unrefActive = exports.active = function(item) {
78364 clearTimeout(item._idleTimeoutId);
78365
78366 var msecs = item._idleTimeout;
78367 if (msecs >= 0) {
78368 item._idleTimeoutId = setTimeout(function onTimeout() {
78369 if (item._onTimeout)
78370 item._onTimeout();
78371 }, msecs);
78372 }
78373};
78374
78375// That's not how node.js implements it but the exposed api is the same.
78376exports.setImmediate = typeof setImmediate === "function" ? setImmediate : function(fn) {
78377 var id = nextImmediateId++;
78378 var args = arguments.length < 2 ? false : slice.call(arguments, 1);
78379
78380 immediateIds[id] = true;
78381
78382 nextTick(function onNextTick() {
78383 if (immediateIds[id]) {
78384 // fn.call() is faster so we optimize for the common use-case
78385 // @see http://jsperf.com/call-apply-segu
78386 if (args) {
78387 fn.apply(null, args);
78388 } else {
78389 fn.call(null);
78390 }
78391 // Prevent ids from leaking
78392 exports.clearImmediate(id);
78393 }
78394 });
78395
78396 return id;
78397};
78398
78399exports.clearImmediate = typeof clearImmediate === "function" ? clearImmediate : function(id) {
78400 delete immediateIds[id];
78401};
78402}).call(this,require("timers").setImmediate,require("timers").clearImmediate)
78403},{"process/browser.js":265,"timers":382}],383:[function(require,module,exports){
78404/*!
78405 * Copyright (c) 2015, Salesforce.com, Inc.
78406 * All rights reserved.
78407 *
78408 * Redistribution and use in source and binary forms, with or without
78409 * modification, are permitted provided that the following conditions are met:
78410 *
78411 * 1. Redistributions of source code must retain the above copyright notice,
78412 * this list of conditions and the following disclaimer.
78413 *
78414 * 2. Redistributions in binary form must reproduce the above copyright notice,
78415 * this list of conditions and the following disclaimer in the documentation
78416 * and/or other materials provided with the distribution.
78417 *
78418 * 3. Neither the name of Salesforce.com nor the names of its contributors may
78419 * be used to endorse or promote products derived from this software without
78420 * specific prior written permission.
78421 *
78422 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
78423 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
78424 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
78425 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
78426 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
78427 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
78428 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
78429 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
78430 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
78431 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
78432 * POSSIBILITY OF SUCH DAMAGE.
78433 */
78434'use strict';
78435var net = require('net');
78436var urlParse = require('url').parse;
78437var util = require('util');
78438var pubsuffix = require('./pubsuffix-psl');
78439var Store = require('./store').Store;
78440var MemoryCookieStore = require('./memstore').MemoryCookieStore;
78441var pathMatch = require('./pathMatch').pathMatch;
78442var VERSION = require('./version');
78443
78444var punycode;
78445try {
78446 punycode = require('punycode');
78447} catch(e) {
78448 console.warn("tough-cookie: can't load punycode; won't use punycode for domain normalization");
78449}
78450
78451// From RFC6265 S4.1.1
78452// note that it excludes \x3B ";"
78453var COOKIE_OCTETS = /^[\x21\x23-\x2B\x2D-\x3A\x3C-\x5B\x5D-\x7E]+$/;
78454
78455var CONTROL_CHARS = /[\x00-\x1F]/;
78456
78457// From Chromium // '\r', '\n' and '\0' should be treated as a terminator in
78458// the "relaxed" mode, see:
78459// https://github.com/ChromiumWebApps/chromium/blob/b3d3b4da8bb94c1b2e061600df106d590fda3620/net/cookies/parsed_cookie.cc#L60
78460var TERMINATORS = ['\n', '\r', '\0'];
78461
78462// RFC6265 S4.1.1 defines path value as 'any CHAR except CTLs or ";"'
78463// Note ';' is \x3B
78464var PATH_VALUE = /[\x20-\x3A\x3C-\x7E]+/;
78465
78466// date-time parsing constants (RFC6265 S5.1.1)
78467
78468var DATE_DELIM = /[\x09\x20-\x2F\x3B-\x40\x5B-\x60\x7B-\x7E]/;
78469
78470var MONTH_TO_NUM = {
78471 jan:0, feb:1, mar:2, apr:3, may:4, jun:5,
78472 jul:6, aug:7, sep:8, oct:9, nov:10, dec:11
78473};
78474var NUM_TO_MONTH = [
78475 'Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'
78476];
78477var NUM_TO_DAY = [
78478 'Sun','Mon','Tue','Wed','Thu','Fri','Sat'
78479];
78480
78481var MAX_TIME = 2147483647000; // 31-bit max
78482var MIN_TIME = 0; // 31-bit min
78483
78484/*
78485 * Parses a Natural number (i.e., non-negative integer) with either the
78486 * <min>*<max>DIGIT ( non-digit *OCTET )
78487 * or
78488 * <min>*<max>DIGIT
78489 * grammar (RFC6265 S5.1.1).
78490 *
78491 * The "trailingOK" boolean controls if the grammar accepts a
78492 * "( non-digit *OCTET )" trailer.
78493 */
78494function parseDigits(token, minDigits, maxDigits, trailingOK) {
78495 var count = 0;
78496 while (count < token.length) {
78497 var c = token.charCodeAt(count);
78498 // "non-digit = %x00-2F / %x3A-FF"
78499 if (c <= 0x2F || c >= 0x3A) {
78500 break;
78501 }
78502 count++;
78503 }
78504
78505 // constrain to a minimum and maximum number of digits.
78506 if (count < minDigits || count > maxDigits) {
78507 return null;
78508 }
78509
78510 if (!trailingOK && count != token.length) {
78511 return null;
78512 }
78513
78514 return parseInt(token.substr(0,count), 10);
78515}
78516
78517function parseTime(token) {
78518 var parts = token.split(':');
78519 var result = [0,0,0];
78520
78521 /* RF6256 S5.1.1:
78522 * time = hms-time ( non-digit *OCTET )
78523 * hms-time = time-field ":" time-field ":" time-field
78524 * time-field = 1*2DIGIT
78525 */
78526
78527 if (parts.length !== 3) {
78528 return null;
78529 }
78530
78531 for (var i = 0; i < 3; i++) {
78532 // "time-field" must be strictly "1*2DIGIT", HOWEVER, "hms-time" can be
78533 // followed by "( non-digit *OCTET )" so therefore the last time-field can
78534 // have a trailer
78535 var trailingOK = (i == 2);
78536 var num = parseDigits(parts[i], 1, 2, trailingOK);
78537 if (num === null) {
78538 return null;
78539 }
78540 result[i] = num;
78541 }
78542
78543 return result;
78544}
78545
78546function parseMonth(token) {
78547 token = String(token).substr(0,3).toLowerCase();
78548 var num = MONTH_TO_NUM[token];
78549 return num >= 0 ? num : null;
78550}
78551
78552/*
78553 * RFC6265 S5.1.1 date parser (see RFC for full grammar)
78554 */
78555function parseDate(str) {
78556 if (!str) {
78557 return;
78558 }
78559
78560 /* RFC6265 S5.1.1:
78561 * 2. Process each date-token sequentially in the order the date-tokens
78562 * appear in the cookie-date
78563 */
78564 var tokens = str.split(DATE_DELIM);
78565 if (!tokens) {
78566 return;
78567 }
78568
78569 var hour = null;
78570 var minute = null;
78571 var second = null;
78572 var dayOfMonth = null;
78573 var month = null;
78574 var year = null;
78575
78576 for (var i=0; i<tokens.length; i++) {
78577 var token = tokens[i].trim();
78578 if (!token.length) {
78579 continue;
78580 }
78581
78582 var result;
78583
78584 /* 2.1. If the found-time flag is not set and the token matches the time
78585 * production, set the found-time flag and set the hour- value,
78586 * minute-value, and second-value to the numbers denoted by the digits in
78587 * the date-token, respectively. Skip the remaining sub-steps and continue
78588 * to the next date-token.
78589 */
78590 if (second === null) {
78591 result = parseTime(token);
78592 if (result) {
78593 hour = result[0];
78594 minute = result[1];
78595 second = result[2];
78596 continue;
78597 }
78598 }
78599
78600 /* 2.2. If the found-day-of-month flag is not set and the date-token matches
78601 * the day-of-month production, set the found-day-of- month flag and set
78602 * the day-of-month-value to the number denoted by the date-token. Skip
78603 * the remaining sub-steps and continue to the next date-token.
78604 */
78605 if (dayOfMonth === null) {
78606 // "day-of-month = 1*2DIGIT ( non-digit *OCTET )"
78607 result = parseDigits(token, 1, 2, true);
78608 if (result !== null) {
78609 dayOfMonth = result;
78610 continue;
78611 }
78612 }
78613
78614 /* 2.3. If the found-month flag is not set and the date-token matches the
78615 * month production, set the found-month flag and set the month-value to
78616 * the month denoted by the date-token. Skip the remaining sub-steps and
78617 * continue to the next date-token.
78618 */
78619 if (month === null) {
78620 result = parseMonth(token);
78621 if (result !== null) {
78622 month = result;
78623 continue;
78624 }
78625 }
78626
78627 /* 2.4. If the found-year flag is not set and the date-token matches the
78628 * year production, set the found-year flag and set the year-value to the
78629 * number denoted by the date-token. Skip the remaining sub-steps and
78630 * continue to the next date-token.
78631 */
78632 if (year === null) {
78633 // "year = 2*4DIGIT ( non-digit *OCTET )"
78634 result = parseDigits(token, 2, 4, true);
78635 if (result !== null) {
78636 year = result;
78637 /* From S5.1.1:
78638 * 3. If the year-value is greater than or equal to 70 and less
78639 * than or equal to 99, increment the year-value by 1900.
78640 * 4. If the year-value is greater than or equal to 0 and less
78641 * than or equal to 69, increment the year-value by 2000.
78642 */
78643 if (year >= 70 && year <= 99) {
78644 year += 1900;
78645 } else if (year >= 0 && year <= 69) {
78646 year += 2000;
78647 }
78648 }
78649 }
78650 }
78651
78652 /* RFC 6265 S5.1.1
78653 * "5. Abort these steps and fail to parse the cookie-date if:
78654 * * at least one of the found-day-of-month, found-month, found-
78655 * year, or found-time flags is not set,
78656 * * the day-of-month-value is less than 1 or greater than 31,
78657 * * the year-value is less than 1601,
78658 * * the hour-value is greater than 23,
78659 * * the minute-value is greater than 59, or
78660 * * the second-value is greater than 59.
78661 * (Note that leap seconds cannot be represented in this syntax.)"
78662 *
78663 * So, in order as above:
78664 */
78665 if (
78666 dayOfMonth === null || month === null || year === null || second === null ||
78667 dayOfMonth < 1 || dayOfMonth > 31 ||
78668 year < 1601 ||
78669 hour > 23 ||
78670 minute > 59 ||
78671 second > 59
78672 ) {
78673 return;
78674 }
78675
78676 return new Date(Date.UTC(year, month, dayOfMonth, hour, minute, second));
78677}
78678
78679function formatDate(date) {
78680 var d = date.getUTCDate(); d = d >= 10 ? d : '0'+d;
78681 var h = date.getUTCHours(); h = h >= 10 ? h : '0'+h;
78682 var m = date.getUTCMinutes(); m = m >= 10 ? m : '0'+m;
78683 var s = date.getUTCSeconds(); s = s >= 10 ? s : '0'+s;
78684 return NUM_TO_DAY[date.getUTCDay()] + ', ' +
78685 d+' '+ NUM_TO_MONTH[date.getUTCMonth()] +' '+ date.getUTCFullYear() +' '+
78686 h+':'+m+':'+s+' GMT';
78687}
78688
78689// S5.1.2 Canonicalized Host Names
78690function canonicalDomain(str) {
78691 if (str == null) {
78692 return null;
78693 }
78694 str = str.trim().replace(/^\./,''); // S4.1.2.3 & S5.2.3: ignore leading .
78695
78696 // convert to IDN if any non-ASCII characters
78697 if (punycode && /[^\u0001-\u007f]/.test(str)) {
78698 str = punycode.toASCII(str);
78699 }
78700
78701 return str.toLowerCase();
78702}
78703
78704// S5.1.3 Domain Matching
78705function domainMatch(str, domStr, canonicalize) {
78706 if (str == null || domStr == null) {
78707 return null;
78708 }
78709 if (canonicalize !== false) {
78710 str = canonicalDomain(str);
78711 domStr = canonicalDomain(domStr);
78712 }
78713
78714 /*
78715 * "The domain string and the string are identical. (Note that both the
78716 * domain string and the string will have been canonicalized to lower case at
78717 * this point)"
78718 */
78719 if (str == domStr) {
78720 return true;
78721 }
78722
78723 /* "All of the following [three] conditions hold:" (order adjusted from the RFC) */
78724
78725 /* "* The string is a host name (i.e., not an IP address)." */
78726 if (net.isIP(str)) {
78727 return false;
78728 }
78729
78730 /* "* The domain string is a suffix of the string" */
78731 var idx = str.indexOf(domStr);
78732 if (idx <= 0) {
78733 return false; // it's a non-match (-1) or prefix (0)
78734 }
78735
78736 // e.g "a.b.c".indexOf("b.c") === 2
78737 // 5 === 3+2
78738 if (str.length !== domStr.length + idx) { // it's not a suffix
78739 return false;
78740 }
78741
78742 /* "* The last character of the string that is not included in the domain
78743 * string is a %x2E (".") character." */
78744 if (str.substr(idx-1,1) !== '.') {
78745 return false;
78746 }
78747
78748 return true;
78749}
78750
78751
78752// RFC6265 S5.1.4 Paths and Path-Match
78753
78754/*
78755 * "The user agent MUST use an algorithm equivalent to the following algorithm
78756 * to compute the default-path of a cookie:"
78757 *
78758 * Assumption: the path (and not query part or absolute uri) is passed in.
78759 */
78760function defaultPath(path) {
78761 // "2. If the uri-path is empty or if the first character of the uri-path is not
78762 // a %x2F ("/") character, output %x2F ("/") and skip the remaining steps.
78763 if (!path || path.substr(0,1) !== "/") {
78764 return "/";
78765 }
78766
78767 // "3. If the uri-path contains no more than one %x2F ("/") character, output
78768 // %x2F ("/") and skip the remaining step."
78769 if (path === "/") {
78770 return path;
78771 }
78772
78773 var rightSlash = path.lastIndexOf("/");
78774 if (rightSlash === 0) {
78775 return "/";
78776 }
78777
78778 // "4. Output the characters of the uri-path from the first character up to,
78779 // but not including, the right-most %x2F ("/")."
78780 return path.slice(0, rightSlash);
78781}
78782
78783function trimTerminator(str) {
78784 for (var t = 0; t < TERMINATORS.length; t++) {
78785 var terminatorIdx = str.indexOf(TERMINATORS[t]);
78786 if (terminatorIdx !== -1) {
78787 str = str.substr(0,terminatorIdx);
78788 }
78789 }
78790
78791 return str;
78792}
78793
78794function parseCookiePair(cookiePair, looseMode) {
78795 cookiePair = trimTerminator(cookiePair);
78796
78797 var firstEq = cookiePair.indexOf('=');
78798 if (looseMode) {
78799 if (firstEq === 0) { // '=' is immediately at start
78800 cookiePair = cookiePair.substr(1);
78801 firstEq = cookiePair.indexOf('='); // might still need to split on '='
78802 }
78803 } else { // non-loose mode
78804 if (firstEq <= 0) { // no '=' or is at start
78805 return; // needs to have non-empty "cookie-name"
78806 }
78807 }
78808
78809 var cookieName, cookieValue;
78810 if (firstEq <= 0) {
78811 cookieName = "";
78812 cookieValue = cookiePair.trim();
78813 } else {
78814 cookieName = cookiePair.substr(0, firstEq).trim();
78815 cookieValue = cookiePair.substr(firstEq+1).trim();
78816 }
78817
78818 if (CONTROL_CHARS.test(cookieName) || CONTROL_CHARS.test(cookieValue)) {
78819 return;
78820 }
78821
78822 var c = new Cookie();
78823 c.key = cookieName;
78824 c.value = cookieValue;
78825 return c;
78826}
78827
78828function parse(str, options) {
78829 if (!options || typeof options !== 'object') {
78830 options = {};
78831 }
78832 str = str.trim();
78833
78834 // We use a regex to parse the "name-value-pair" part of S5.2
78835 var firstSemi = str.indexOf(';'); // S5.2 step 1
78836 var cookiePair = (firstSemi === -1) ? str : str.substr(0, firstSemi);
78837 var c = parseCookiePair(cookiePair, !!options.loose);
78838 if (!c) {
78839 return;
78840 }
78841
78842 if (firstSemi === -1) {
78843 return c;
78844 }
78845
78846 // S5.2.3 "unparsed-attributes consist of the remainder of the set-cookie-string
78847 // (including the %x3B (";") in question)." plus later on in the same section
78848 // "discard the first ";" and trim".
78849 var unparsed = str.slice(firstSemi + 1).trim();
78850
78851 // "If the unparsed-attributes string is empty, skip the rest of these
78852 // steps."
78853 if (unparsed.length === 0) {
78854 return c;
78855 }
78856
78857 /*
78858 * S5.2 says that when looping over the items "[p]rocess the attribute-name
78859 * and attribute-value according to the requirements in the following
78860 * subsections" for every item. Plus, for many of the individual attributes
78861 * in S5.3 it says to use the "attribute-value of the last attribute in the
78862 * cookie-attribute-list". Therefore, in this implementation, we overwrite
78863 * the previous value.
78864 */
78865 var cookie_avs = unparsed.split(';');
78866 while (cookie_avs.length) {
78867 var av = cookie_avs.shift().trim();
78868 if (av.length === 0) { // happens if ";;" appears
78869 continue;
78870 }
78871 var av_sep = av.indexOf('=');
78872 var av_key, av_value;
78873
78874 if (av_sep === -1) {
78875 av_key = av;
78876 av_value = null;
78877 } else {
78878 av_key = av.substr(0,av_sep);
78879 av_value = av.substr(av_sep+1);
78880 }
78881
78882 av_key = av_key.trim().toLowerCase();
78883
78884 if (av_value) {
78885 av_value = av_value.trim();
78886 }
78887
78888 switch(av_key) {
78889 case 'expires': // S5.2.1
78890 if (av_value) {
78891 var exp = parseDate(av_value);
78892 // "If the attribute-value failed to parse as a cookie date, ignore the
78893 // cookie-av."
78894 if (exp) {
78895 // over and underflow not realistically a concern: V8's getTime() seems to
78896 // store something larger than a 32-bit time_t (even with 32-bit node)
78897 c.expires = exp;
78898 }
78899 }
78900 break;
78901
78902 case 'max-age': // S5.2.2
78903 if (av_value) {
78904 // "If the first character of the attribute-value is not a DIGIT or a "-"
78905 // character ...[or]... If the remainder of attribute-value contains a
78906 // non-DIGIT character, ignore the cookie-av."
78907 if (/^-?[0-9]+$/.test(av_value)) {
78908 var delta = parseInt(av_value, 10);
78909 // "If delta-seconds is less than or equal to zero (0), let expiry-time
78910 // be the earliest representable date and time."
78911 c.setMaxAge(delta);
78912 }
78913 }
78914 break;
78915
78916 case 'domain': // S5.2.3
78917 // "If the attribute-value is empty, the behavior is undefined. However,
78918 // the user agent SHOULD ignore the cookie-av entirely."
78919 if (av_value) {
78920 // S5.2.3 "Let cookie-domain be the attribute-value without the leading %x2E
78921 // (".") character."
78922 var domain = av_value.trim().replace(/^\./, '');
78923 if (domain) {
78924 // "Convert the cookie-domain to lower case."
78925 c.domain = domain.toLowerCase();
78926 }
78927 }
78928 break;
78929
78930 case 'path': // S5.2.4
78931 /*
78932 * "If the attribute-value is empty or if the first character of the
78933 * attribute-value is not %x2F ("/"):
78934 * Let cookie-path be the default-path.
78935 * Otherwise:
78936 * Let cookie-path be the attribute-value."
78937 *
78938 * We'll represent the default-path as null since it depends on the
78939 * context of the parsing.
78940 */
78941 c.path = av_value && av_value[0] === "/" ? av_value : null;
78942 break;
78943
78944 case 'secure': // S5.2.5
78945 /*
78946 * "If the attribute-name case-insensitively matches the string "Secure",
78947 * the user agent MUST append an attribute to the cookie-attribute-list
78948 * with an attribute-name of Secure and an empty attribute-value."
78949 */
78950 c.secure = true;
78951 break;
78952
78953 case 'httponly': // S5.2.6 -- effectively the same as 'secure'
78954 c.httpOnly = true;
78955 break;
78956
78957 default:
78958 c.extensions = c.extensions || [];
78959 c.extensions.push(av);
78960 break;
78961 }
78962 }
78963
78964 return c;
78965}
78966
78967// avoid the V8 deoptimization monster!
78968function jsonParse(str) {
78969 var obj;
78970 try {
78971 obj = JSON.parse(str);
78972 } catch (e) {
78973 return e;
78974 }
78975 return obj;
78976}
78977
78978function fromJSON(str) {
78979 if (!str) {
78980 return null;
78981 }
78982
78983 var obj;
78984 if (typeof str === 'string') {
78985 obj = jsonParse(str);
78986 if (obj instanceof Error) {
78987 return null;
78988 }
78989 } else {
78990 // assume it's an Object
78991 obj = str;
78992 }
78993
78994 var c = new Cookie();
78995 for (var i=0; i<Cookie.serializableProperties.length; i++) {
78996 var prop = Cookie.serializableProperties[i];
78997 if (obj[prop] === undefined ||
78998 obj[prop] === Cookie.prototype[prop])
78999 {
79000 continue; // leave as prototype default
79001 }
79002
79003 if (prop === 'expires' ||
79004 prop === 'creation' ||
79005 prop === 'lastAccessed')
79006 {
79007 if (obj[prop] === null) {
79008 c[prop] = null;
79009 } else {
79010 c[prop] = obj[prop] == "Infinity" ?
79011 "Infinity" : new Date(obj[prop]);
79012 }
79013 } else {
79014 c[prop] = obj[prop];
79015 }
79016 }
79017
79018 return c;
79019}
79020
79021/* Section 5.4 part 2:
79022 * "* Cookies with longer paths are listed before cookies with
79023 * shorter paths.
79024 *
79025 * * Among cookies that have equal-length path fields, cookies with
79026 * earlier creation-times are listed before cookies with later
79027 * creation-times."
79028 */
79029
79030function cookieCompare(a,b) {
79031 var cmp = 0;
79032
79033 // descending for length: b CMP a
79034 var aPathLen = a.path ? a.path.length : 0;
79035 var bPathLen = b.path ? b.path.length : 0;
79036 cmp = bPathLen - aPathLen;
79037 if (cmp !== 0) {
79038 return cmp;
79039 }
79040
79041 // ascending for time: a CMP b
79042 var aTime = a.creation ? a.creation.getTime() : MAX_TIME;
79043 var bTime = b.creation ? b.creation.getTime() : MAX_TIME;
79044 cmp = aTime - bTime;
79045 if (cmp !== 0) {
79046 return cmp;
79047 }
79048
79049 // break ties for the same millisecond (precision of JavaScript's clock)
79050 cmp = a.creationIndex - b.creationIndex;
79051
79052 return cmp;
79053}
79054
79055// Gives the permutation of all possible pathMatch()es of a given path. The
79056// array is in longest-to-shortest order. Handy for indexing.
79057function permutePath(path) {
79058 if (path === '/') {
79059 return ['/'];
79060 }
79061 if (path.lastIndexOf('/') === path.length-1) {
79062 path = path.substr(0,path.length-1);
79063 }
79064 var permutations = [path];
79065 while (path.length > 1) {
79066 var lindex = path.lastIndexOf('/');
79067 if (lindex === 0) {
79068 break;
79069 }
79070 path = path.substr(0,lindex);
79071 permutations.push(path);
79072 }
79073 permutations.push('/');
79074 return permutations;
79075}
79076
79077function getCookieContext(url) {
79078 if (url instanceof Object) {
79079 return url;
79080 }
79081 // NOTE: decodeURI will throw on malformed URIs (see GH-32).
79082 // Therefore, we will just skip decoding for such URIs.
79083 try {
79084 url = decodeURI(url);
79085 }
79086 catch(err) {
79087 // Silently swallow error
79088 }
79089
79090 return urlParse(url);
79091}
79092
79093function Cookie(options) {
79094 options = options || {};
79095
79096 Object.keys(options).forEach(function(prop) {
79097 if (Cookie.prototype.hasOwnProperty(prop) &&
79098 Cookie.prototype[prop] !== options[prop] &&
79099 prop.substr(0,1) !== '_')
79100 {
79101 this[prop] = options[prop];
79102 }
79103 }, this);
79104
79105 this.creation = this.creation || new Date();
79106
79107 // used to break creation ties in cookieCompare():
79108 Object.defineProperty(this, 'creationIndex', {
79109 configurable: false,
79110 enumerable: false, // important for assert.deepEqual checks
79111 writable: true,
79112 value: ++Cookie.cookiesCreated
79113 });
79114}
79115
79116Cookie.cookiesCreated = 0; // incremented each time a cookie is created
79117
79118Cookie.parse = parse;
79119Cookie.fromJSON = fromJSON;
79120
79121Cookie.prototype.key = "";
79122Cookie.prototype.value = "";
79123
79124// the order in which the RFC has them:
79125Cookie.prototype.expires = "Infinity"; // coerces to literal Infinity
79126Cookie.prototype.maxAge = null; // takes precedence over expires for TTL
79127Cookie.prototype.domain = null;
79128Cookie.prototype.path = null;
79129Cookie.prototype.secure = false;
79130Cookie.prototype.httpOnly = false;
79131Cookie.prototype.extensions = null;
79132
79133// set by the CookieJar:
79134Cookie.prototype.hostOnly = null; // boolean when set
79135Cookie.prototype.pathIsDefault = null; // boolean when set
79136Cookie.prototype.creation = null; // Date when set; defaulted by Cookie.parse
79137Cookie.prototype.lastAccessed = null; // Date when set
79138Object.defineProperty(Cookie.prototype, 'creationIndex', {
79139 configurable: true,
79140 enumerable: false,
79141 writable: true,
79142 value: 0
79143});
79144
79145Cookie.serializableProperties = Object.keys(Cookie.prototype)
79146 .filter(function(prop) {
79147 return !(
79148 Cookie.prototype[prop] instanceof Function ||
79149 prop === 'creationIndex' ||
79150 prop.substr(0,1) === '_'
79151 );
79152 });
79153
79154Cookie.prototype.inspect = function inspect() {
79155 var now = Date.now();
79156 return 'Cookie="'+this.toString() +
79157 '; hostOnly='+(this.hostOnly != null ? this.hostOnly : '?') +
79158 '; aAge='+(this.lastAccessed ? (now-this.lastAccessed.getTime())+'ms' : '?') +
79159 '; cAge='+(this.creation ? (now-this.creation.getTime())+'ms' : '?') +
79160 '"';
79161};
79162
79163// Use the new custom inspection symbol to add the custom inspect function if
79164// available.
79165if (util.inspect.custom) {
79166 Cookie.prototype[util.inspect.custom] = Cookie.prototype.inspect;
79167}
79168
79169Cookie.prototype.toJSON = function() {
79170 var obj = {};
79171
79172 var props = Cookie.serializableProperties;
79173 for (var i=0; i<props.length; i++) {
79174 var prop = props[i];
79175 if (this[prop] === Cookie.prototype[prop]) {
79176 continue; // leave as prototype default
79177 }
79178
79179 if (prop === 'expires' ||
79180 prop === 'creation' ||
79181 prop === 'lastAccessed')
79182 {
79183 if (this[prop] === null) {
79184 obj[prop] = null;
79185 } else {
79186 obj[prop] = this[prop] == "Infinity" ? // intentionally not ===
79187 "Infinity" : this[prop].toISOString();
79188 }
79189 } else if (prop === 'maxAge') {
79190 if (this[prop] !== null) {
79191 // again, intentionally not ===
79192 obj[prop] = (this[prop] == Infinity || this[prop] == -Infinity) ?
79193 this[prop].toString() : this[prop];
79194 }
79195 } else {
79196 if (this[prop] !== Cookie.prototype[prop]) {
79197 obj[prop] = this[prop];
79198 }
79199 }
79200 }
79201
79202 return obj;
79203};
79204
79205Cookie.prototype.clone = function() {
79206 return fromJSON(this.toJSON());
79207};
79208
79209Cookie.prototype.validate = function validate() {
79210 if (!COOKIE_OCTETS.test(this.value)) {
79211 return false;
79212 }
79213 if (this.expires != Infinity && !(this.expires instanceof Date) && !parseDate(this.expires)) {
79214 return false;
79215 }
79216 if (this.maxAge != null && this.maxAge <= 0) {
79217 return false; // "Max-Age=" non-zero-digit *DIGIT
79218 }
79219 if (this.path != null && !PATH_VALUE.test(this.path)) {
79220 return false;
79221 }
79222
79223 var cdomain = this.cdomain();
79224 if (cdomain) {
79225 if (cdomain.match(/\.$/)) {
79226 return false; // S4.1.2.3 suggests that this is bad. domainMatch() tests confirm this
79227 }
79228 var suffix = pubsuffix.getPublicSuffix(cdomain);
79229 if (suffix == null) { // it's a public suffix
79230 return false;
79231 }
79232 }
79233 return true;
79234};
79235
79236Cookie.prototype.setExpires = function setExpires(exp) {
79237 if (exp instanceof Date) {
79238 this.expires = exp;
79239 } else {
79240 this.expires = parseDate(exp) || "Infinity";
79241 }
79242};
79243
79244Cookie.prototype.setMaxAge = function setMaxAge(age) {
79245 if (age === Infinity || age === -Infinity) {
79246 this.maxAge = age.toString(); // so JSON.stringify() works
79247 } else {
79248 this.maxAge = age;
79249 }
79250};
79251
79252// gives Cookie header format
79253Cookie.prototype.cookieString = function cookieString() {
79254 var val = this.value;
79255 if (val == null) {
79256 val = '';
79257 }
79258 if (this.key === '') {
79259 return val;
79260 }
79261 return this.key+'='+val;
79262};
79263
79264// gives Set-Cookie header format
79265Cookie.prototype.toString = function toString() {
79266 var str = this.cookieString();
79267
79268 if (this.expires != Infinity) {
79269 if (this.expires instanceof Date) {
79270 str += '; Expires='+formatDate(this.expires);
79271 } else {
79272 str += '; Expires='+this.expires;
79273 }
79274 }
79275
79276 if (this.maxAge != null && this.maxAge != Infinity) {
79277 str += '; Max-Age='+this.maxAge;
79278 }
79279
79280 if (this.domain && !this.hostOnly) {
79281 str += '; Domain='+this.domain;
79282 }
79283 if (this.path) {
79284 str += '; Path='+this.path;
79285 }
79286
79287 if (this.secure) {
79288 str += '; Secure';
79289 }
79290 if (this.httpOnly) {
79291 str += '; HttpOnly';
79292 }
79293 if (this.extensions) {
79294 this.extensions.forEach(function(ext) {
79295 str += '; '+ext;
79296 });
79297 }
79298
79299 return str;
79300};
79301
79302// TTL() partially replaces the "expiry-time" parts of S5.3 step 3 (setCookie()
79303// elsewhere)
79304// S5.3 says to give the "latest representable date" for which we use Infinity
79305// For "expired" we use 0
79306Cookie.prototype.TTL = function TTL(now) {
79307 /* RFC6265 S4.1.2.2 If a cookie has both the Max-Age and the Expires
79308 * attribute, the Max-Age attribute has precedence and controls the
79309 * expiration date of the cookie.
79310 * (Concurs with S5.3 step 3)
79311 */
79312 if (this.maxAge != null) {
79313 return this.maxAge<=0 ? 0 : this.maxAge*1000;
79314 }
79315
79316 var expires = this.expires;
79317 if (expires != Infinity) {
79318 if (!(expires instanceof Date)) {
79319 expires = parseDate(expires) || Infinity;
79320 }
79321
79322 if (expires == Infinity) {
79323 return Infinity;
79324 }
79325
79326 return expires.getTime() - (now || Date.now());
79327 }
79328
79329 return Infinity;
79330};
79331
79332// expiryTime() replaces the "expiry-time" parts of S5.3 step 3 (setCookie()
79333// elsewhere)
79334Cookie.prototype.expiryTime = function expiryTime(now) {
79335 if (this.maxAge != null) {
79336 var relativeTo = now || this.creation || new Date();
79337 var age = (this.maxAge <= 0) ? -Infinity : this.maxAge*1000;
79338 return relativeTo.getTime() + age;
79339 }
79340
79341 if (this.expires == Infinity) {
79342 return Infinity;
79343 }
79344 return this.expires.getTime();
79345};
79346
79347// expiryDate() replaces the "expiry-time" parts of S5.3 step 3 (setCookie()
79348// elsewhere), except it returns a Date
79349Cookie.prototype.expiryDate = function expiryDate(now) {
79350 var millisec = this.expiryTime(now);
79351 if (millisec == Infinity) {
79352 return new Date(MAX_TIME);
79353 } else if (millisec == -Infinity) {
79354 return new Date(MIN_TIME);
79355 } else {
79356 return new Date(millisec);
79357 }
79358};
79359
79360// This replaces the "persistent-flag" parts of S5.3 step 3
79361Cookie.prototype.isPersistent = function isPersistent() {
79362 return (this.maxAge != null || this.expires != Infinity);
79363};
79364
79365// Mostly S5.1.2 and S5.2.3:
79366Cookie.prototype.cdomain =
79367Cookie.prototype.canonicalizedDomain = function canonicalizedDomain() {
79368 if (this.domain == null) {
79369 return null;
79370 }
79371 return canonicalDomain(this.domain);
79372};
79373
79374function CookieJar(store, options) {
79375 if (typeof options === "boolean") {
79376 options = {rejectPublicSuffixes: options};
79377 } else if (options == null) {
79378 options = {};
79379 }
79380 if (options.rejectPublicSuffixes != null) {
79381 this.rejectPublicSuffixes = options.rejectPublicSuffixes;
79382 }
79383 if (options.looseMode != null) {
79384 this.enableLooseMode = options.looseMode;
79385 }
79386
79387 if (!store) {
79388 store = new MemoryCookieStore();
79389 }
79390 this.store = store;
79391}
79392CookieJar.prototype.store = null;
79393CookieJar.prototype.rejectPublicSuffixes = true;
79394CookieJar.prototype.enableLooseMode = false;
79395var CAN_BE_SYNC = [];
79396
79397CAN_BE_SYNC.push('setCookie');
79398CookieJar.prototype.setCookie = function(cookie, url, options, cb) {
79399 var err;
79400 var context = getCookieContext(url);
79401 if (options instanceof Function) {
79402 cb = options;
79403 options = {};
79404 }
79405
79406 var host = canonicalDomain(context.hostname);
79407 var loose = this.enableLooseMode;
79408 if (options.loose != null) {
79409 loose = options.loose;
79410 }
79411
79412 // S5.3 step 1
79413 if (!(cookie instanceof Cookie)) {
79414 cookie = Cookie.parse(cookie, { loose: loose });
79415 }
79416 if (!cookie) {
79417 err = new Error("Cookie failed to parse");
79418 return cb(options.ignoreError ? null : err);
79419 }
79420
79421 // S5.3 step 2
79422 var now = options.now || new Date(); // will assign later to save effort in the face of errors
79423
79424 // S5.3 step 3: NOOP; persistent-flag and expiry-time is handled by getCookie()
79425
79426 // S5.3 step 4: NOOP; domain is null by default
79427
79428 // S5.3 step 5: public suffixes
79429 if (this.rejectPublicSuffixes && cookie.domain) {
79430 var suffix = pubsuffix.getPublicSuffix(cookie.cdomain());
79431 if (suffix == null) { // e.g. "com"
79432 err = new Error("Cookie has domain set to a public suffix");
79433 return cb(options.ignoreError ? null : err);
79434 }
79435 }
79436
79437 // S5.3 step 6:
79438 if (cookie.domain) {
79439 if (!domainMatch(host, cookie.cdomain(), false)) {
79440 err = new Error("Cookie not in this host's domain. Cookie:"+cookie.cdomain()+" Request:"+host);
79441 return cb(options.ignoreError ? null : err);
79442 }
79443
79444 if (cookie.hostOnly == null) { // don't reset if already set
79445 cookie.hostOnly = false;
79446 }
79447
79448 } else {
79449 cookie.hostOnly = true;
79450 cookie.domain = host;
79451 }
79452
79453 //S5.2.4 If the attribute-value is empty or if the first character of the
79454 //attribute-value is not %x2F ("/"):
79455 //Let cookie-path be the default-path.
79456 if (!cookie.path || cookie.path[0] !== '/') {
79457 cookie.path = defaultPath(context.pathname);
79458 cookie.pathIsDefault = true;
79459 }
79460
79461 // S5.3 step 8: NOOP; secure attribute
79462 // S5.3 step 9: NOOP; httpOnly attribute
79463
79464 // S5.3 step 10
79465 if (options.http === false && cookie.httpOnly) {
79466 err = new Error("Cookie is HttpOnly and this isn't an HTTP API");
79467 return cb(options.ignoreError ? null : err);
79468 }
79469
79470 var store = this.store;
79471
79472 if (!store.updateCookie) {
79473 store.updateCookie = function(oldCookie, newCookie, cb) {
79474 this.putCookie(newCookie, cb);
79475 };
79476 }
79477
79478 function withCookie(err, oldCookie) {
79479 if (err) {
79480 return cb(err);
79481 }
79482
79483 var next = function(err) {
79484 if (err) {
79485 return cb(err);
79486 } else {
79487 cb(null, cookie);
79488 }
79489 };
79490
79491 if (oldCookie) {
79492 // S5.3 step 11 - "If the cookie store contains a cookie with the same name,
79493 // domain, and path as the newly created cookie:"
79494 if (options.http === false && oldCookie.httpOnly) { // step 11.2
79495 err = new Error("old Cookie is HttpOnly and this isn't an HTTP API");
79496 return cb(options.ignoreError ? null : err);
79497 }
79498 cookie.creation = oldCookie.creation; // step 11.3
79499 cookie.creationIndex = oldCookie.creationIndex; // preserve tie-breaker
79500 cookie.lastAccessed = now;
79501 // Step 11.4 (delete cookie) is implied by just setting the new one:
79502 store.updateCookie(oldCookie, cookie, next); // step 12
79503
79504 } else {
79505 cookie.creation = cookie.lastAccessed = now;
79506 store.putCookie(cookie, next); // step 12
79507 }
79508 }
79509
79510 store.findCookie(cookie.domain, cookie.path, cookie.key, withCookie);
79511};
79512
79513// RFC6365 S5.4
79514CAN_BE_SYNC.push('getCookies');
79515CookieJar.prototype.getCookies = function(url, options, cb) {
79516 var context = getCookieContext(url);
79517 if (options instanceof Function) {
79518 cb = options;
79519 options = {};
79520 }
79521
79522 var host = canonicalDomain(context.hostname);
79523 var path = context.pathname || '/';
79524
79525 var secure = options.secure;
79526 if (secure == null && context.protocol &&
79527 (context.protocol == 'https:' || context.protocol == 'wss:'))
79528 {
79529 secure = true;
79530 }
79531
79532 var http = options.http;
79533 if (http == null) {
79534 http = true;
79535 }
79536
79537 var now = options.now || Date.now();
79538 var expireCheck = options.expire !== false;
79539 var allPaths = !!options.allPaths;
79540 var store = this.store;
79541
79542 function matchingCookie(c) {
79543 // "Either:
79544 // The cookie's host-only-flag is true and the canonicalized
79545 // request-host is identical to the cookie's domain.
79546 // Or:
79547 // The cookie's host-only-flag is false and the canonicalized
79548 // request-host domain-matches the cookie's domain."
79549 if (c.hostOnly) {
79550 if (c.domain != host) {
79551 return false;
79552 }
79553 } else {
79554 if (!domainMatch(host, c.domain, false)) {
79555 return false;
79556 }
79557 }
79558
79559 // "The request-uri's path path-matches the cookie's path."
79560 if (!allPaths && !pathMatch(path, c.path)) {
79561 return false;
79562 }
79563
79564 // "If the cookie's secure-only-flag is true, then the request-uri's
79565 // scheme must denote a "secure" protocol"
79566 if (c.secure && !secure) {
79567 return false;
79568 }
79569
79570 // "If the cookie's http-only-flag is true, then exclude the cookie if the
79571 // cookie-string is being generated for a "non-HTTP" API"
79572 if (c.httpOnly && !http) {
79573 return false;
79574 }
79575
79576 // deferred from S5.3
79577 // non-RFC: allow retention of expired cookies by choice
79578 if (expireCheck && c.expiryTime() <= now) {
79579 store.removeCookie(c.domain, c.path, c.key, function(){}); // result ignored
79580 return false;
79581 }
79582
79583 return true;
79584 }
79585
79586 store.findCookies(host, allPaths ? null : path, function(err,cookies) {
79587 if (err) {
79588 return cb(err);
79589 }
79590
79591 cookies = cookies.filter(matchingCookie);
79592
79593 // sorting of S5.4 part 2
79594 if (options.sort !== false) {
79595 cookies = cookies.sort(cookieCompare);
79596 }
79597
79598 // S5.4 part 3
79599 var now = new Date();
79600 cookies.forEach(function(c) {
79601 c.lastAccessed = now;
79602 });
79603 // TODO persist lastAccessed
79604
79605 cb(null,cookies);
79606 });
79607};
79608
79609CAN_BE_SYNC.push('getCookieString');
79610CookieJar.prototype.getCookieString = function(/*..., cb*/) {
79611 var args = Array.prototype.slice.call(arguments,0);
79612 var cb = args.pop();
79613 var next = function(err,cookies) {
79614 if (err) {
79615 cb(err);
79616 } else {
79617 cb(null, cookies
79618 .sort(cookieCompare)
79619 .map(function(c){
79620 return c.cookieString();
79621 })
79622 .join('; '));
79623 }
79624 };
79625 args.push(next);
79626 this.getCookies.apply(this,args);
79627};
79628
79629CAN_BE_SYNC.push('getSetCookieStrings');
79630CookieJar.prototype.getSetCookieStrings = function(/*..., cb*/) {
79631 var args = Array.prototype.slice.call(arguments,0);
79632 var cb = args.pop();
79633 var next = function(err,cookies) {
79634 if (err) {
79635 cb(err);
79636 } else {
79637 cb(null, cookies.map(function(c){
79638 return c.toString();
79639 }));
79640 }
79641 };
79642 args.push(next);
79643 this.getCookies.apply(this,args);
79644};
79645
79646CAN_BE_SYNC.push('serialize');
79647CookieJar.prototype.serialize = function(cb) {
79648 var type = this.store.constructor.name;
79649 if (type === 'Object') {
79650 type = null;
79651 }
79652
79653 // update README.md "Serialization Format" if you change this, please!
79654 var serialized = {
79655 // The version of tough-cookie that serialized this jar. Generally a good
79656 // practice since future versions can make data import decisions based on
79657 // known past behavior. When/if this matters, use `semver`.
79658 version: 'tough-cookie@'+VERSION,
79659
79660 // add the store type, to make humans happy:
79661 storeType: type,
79662
79663 // CookieJar configuration:
79664 rejectPublicSuffixes: !!this.rejectPublicSuffixes,
79665
79666 // this gets filled from getAllCookies:
79667 cookies: []
79668 };
79669
79670 if (!(this.store.getAllCookies &&
79671 typeof this.store.getAllCookies === 'function'))
79672 {
79673 return cb(new Error('store does not support getAllCookies and cannot be serialized'));
79674 }
79675
79676 this.store.getAllCookies(function(err,cookies) {
79677 if (err) {
79678 return cb(err);
79679 }
79680
79681 serialized.cookies = cookies.map(function(cookie) {
79682 // convert to serialized 'raw' cookies
79683 cookie = (cookie instanceof Cookie) ? cookie.toJSON() : cookie;
79684
79685 // Remove the index so new ones get assigned during deserialization
79686 delete cookie.creationIndex;
79687
79688 return cookie;
79689 });
79690
79691 return cb(null, serialized);
79692 });
79693};
79694
79695// well-known name that JSON.stringify calls
79696CookieJar.prototype.toJSON = function() {
79697 return this.serializeSync();
79698};
79699
79700// use the class method CookieJar.deserialize instead of calling this directly
79701CAN_BE_SYNC.push('_importCookies');
79702CookieJar.prototype._importCookies = function(serialized, cb) {
79703 var jar = this;
79704 var cookies = serialized.cookies;
79705 if (!cookies || !Array.isArray(cookies)) {
79706 return cb(new Error('serialized jar has no cookies array'));
79707 }
79708 cookies = cookies.slice(); // do not modify the original
79709
79710 function putNext(err) {
79711 if (err) {
79712 return cb(err);
79713 }
79714
79715 if (!cookies.length) {
79716 return cb(err, jar);
79717 }
79718
79719 var cookie;
79720 try {
79721 cookie = fromJSON(cookies.shift());
79722 } catch (e) {
79723 return cb(e);
79724 }
79725
79726 if (cookie === null) {
79727 return putNext(null); // skip this cookie
79728 }
79729
79730 jar.store.putCookie(cookie, putNext);
79731 }
79732
79733 putNext();
79734};
79735
79736CookieJar.deserialize = function(strOrObj, store, cb) {
79737 if (arguments.length !== 3) {
79738 // store is optional
79739 cb = store;
79740 store = null;
79741 }
79742
79743 var serialized;
79744 if (typeof strOrObj === 'string') {
79745 serialized = jsonParse(strOrObj);
79746 if (serialized instanceof Error) {
79747 return cb(serialized);
79748 }
79749 } else {
79750 serialized = strOrObj;
79751 }
79752
79753 var jar = new CookieJar(store, serialized.rejectPublicSuffixes);
79754 jar._importCookies(serialized, function(err) {
79755 if (err) {
79756 return cb(err);
79757 }
79758 cb(null, jar);
79759 });
79760};
79761
79762CookieJar.deserializeSync = function(strOrObj, store) {
79763 var serialized = typeof strOrObj === 'string' ?
79764 JSON.parse(strOrObj) : strOrObj;
79765 var jar = new CookieJar(store, serialized.rejectPublicSuffixes);
79766
79767 // catch this mistake early:
79768 if (!jar.store.synchronous) {
79769 throw new Error('CookieJar store is not synchronous; use async API instead.');
79770 }
79771
79772 jar._importCookiesSync(serialized);
79773 return jar;
79774};
79775CookieJar.fromJSON = CookieJar.deserializeSync;
79776
79777CookieJar.prototype.clone = function(newStore, cb) {
79778 if (arguments.length === 1) {
79779 cb = newStore;
79780 newStore = null;
79781 }
79782
79783 this.serialize(function(err,serialized) {
79784 if (err) {
79785 return cb(err);
79786 }
79787 CookieJar.deserialize(serialized, newStore, cb);
79788 });
79789};
79790
79791CAN_BE_SYNC.push('removeAllCookies');
79792CookieJar.prototype.removeAllCookies = function(cb) {
79793 var store = this.store;
79794
79795 // Check that the store implements its own removeAllCookies(). The default
79796 // implementation in Store will immediately call the callback with a "not
79797 // implemented" Error.
79798 if (store.removeAllCookies instanceof Function &&
79799 store.removeAllCookies !== Store.prototype.removeAllCookies)
79800 {
79801 return store.removeAllCookies(cb);
79802 }
79803
79804 store.getAllCookies(function(err, cookies) {
79805 if (err) {
79806 return cb(err);
79807 }
79808
79809 if (cookies.length === 0) {
79810 return cb(null);
79811 }
79812
79813 var completedCount = 0;
79814 var removeErrors = [];
79815
79816 function removeCookieCb(removeErr) {
79817 if (removeErr) {
79818 removeErrors.push(removeErr);
79819 }
79820
79821 completedCount++;
79822
79823 if (completedCount === cookies.length) {
79824 return cb(removeErrors.length ? removeErrors[0] : null);
79825 }
79826 }
79827
79828 cookies.forEach(function(cookie) {
79829 store.removeCookie(cookie.domain, cookie.path, cookie.key, removeCookieCb);
79830 });
79831 });
79832};
79833
79834CookieJar.prototype._cloneSync = syncWrap('clone');
79835CookieJar.prototype.cloneSync = function(newStore) {
79836 if (!newStore.synchronous) {
79837 throw new Error('CookieJar clone destination store is not synchronous; use async API instead.');
79838 }
79839 return this._cloneSync(newStore);
79840};
79841
79842// Use a closure to provide a true imperative API for synchronous stores.
79843function syncWrap(method) {
79844 return function() {
79845 if (!this.store.synchronous) {
79846 throw new Error('CookieJar store is not synchronous; use async API instead.');
79847 }
79848
79849 var args = Array.prototype.slice.call(arguments);
79850 var syncErr, syncResult;
79851 args.push(function syncCb(err, result) {
79852 syncErr = err;
79853 syncResult = result;
79854 });
79855 this[method].apply(this, args);
79856
79857 if (syncErr) {
79858 throw syncErr;
79859 }
79860 return syncResult;
79861 };
79862}
79863
79864// wrap all declared CAN_BE_SYNC methods in the sync wrapper
79865CAN_BE_SYNC.forEach(function(method) {
79866 CookieJar.prototype[method+'Sync'] = syncWrap(method);
79867});
79868
79869exports.version = VERSION;
79870exports.CookieJar = CookieJar;
79871exports.Cookie = Cookie;
79872exports.Store = Store;
79873exports.MemoryCookieStore = MemoryCookieStore;
79874exports.parseDate = parseDate;
79875exports.formatDate = formatDate;
79876exports.parse = parse;
79877exports.fromJSON = fromJSON;
79878exports.domainMatch = domainMatch;
79879exports.defaultPath = defaultPath;
79880exports.pathMatch = pathMatch;
79881exports.getPublicSuffix = pubsuffix.getPublicSuffix;
79882exports.cookieCompare = cookieCompare;
79883exports.permuteDomain = require('./permuteDomain').permuteDomain;
79884exports.permutePath = permutePath;
79885exports.canonicalDomain = canonicalDomain;
79886
79887},{"./memstore":384,"./pathMatch":385,"./permuteDomain":386,"./pubsuffix-psl":387,"./store":388,"./version":389,"net":112,"punycode":274,"url":393,"util":397}],384:[function(require,module,exports){
79888/*!
79889 * Copyright (c) 2015, Salesforce.com, Inc.
79890 * All rights reserved.
79891 *
79892 * Redistribution and use in source and binary forms, with or without
79893 * modification, are permitted provided that the following conditions are met:
79894 *
79895 * 1. Redistributions of source code must retain the above copyright notice,
79896 * this list of conditions and the following disclaimer.
79897 *
79898 * 2. Redistributions in binary form must reproduce the above copyright notice,
79899 * this list of conditions and the following disclaimer in the documentation
79900 * and/or other materials provided with the distribution.
79901 *
79902 * 3. Neither the name of Salesforce.com nor the names of its contributors may
79903 * be used to endorse or promote products derived from this software without
79904 * specific prior written permission.
79905 *
79906 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
79907 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
79908 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
79909 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
79910 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
79911 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
79912 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
79913 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
79914 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
79915 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
79916 * POSSIBILITY OF SUCH DAMAGE.
79917 */
79918'use strict';
79919var Store = require('./store').Store;
79920var permuteDomain = require('./permuteDomain').permuteDomain;
79921var pathMatch = require('./pathMatch').pathMatch;
79922var util = require('util');
79923
79924function MemoryCookieStore() {
79925 Store.call(this);
79926 this.idx = {};
79927}
79928util.inherits(MemoryCookieStore, Store);
79929exports.MemoryCookieStore = MemoryCookieStore;
79930MemoryCookieStore.prototype.idx = null;
79931
79932// Since it's just a struct in RAM, this Store is synchronous
79933MemoryCookieStore.prototype.synchronous = true;
79934
79935// force a default depth:
79936MemoryCookieStore.prototype.inspect = function() {
79937 return "{ idx: "+util.inspect(this.idx, false, 2)+' }';
79938};
79939
79940// Use the new custom inspection symbol to add the custom inspect function if
79941// available.
79942if (util.inspect.custom) {
79943 MemoryCookieStore.prototype[util.inspect.custom] = MemoryCookieStore.prototype.inspect;
79944}
79945
79946MemoryCookieStore.prototype.findCookie = function(domain, path, key, cb) {
79947 if (!this.idx[domain]) {
79948 return cb(null,undefined);
79949 }
79950 if (!this.idx[domain][path]) {
79951 return cb(null,undefined);
79952 }
79953 return cb(null,this.idx[domain][path][key]||null);
79954};
79955
79956MemoryCookieStore.prototype.findCookies = function(domain, path, cb) {
79957 var results = [];
79958 if (!domain) {
79959 return cb(null,[]);
79960 }
79961
79962 var pathMatcher;
79963 if (!path) {
79964 // null means "all paths"
79965 pathMatcher = function matchAll(domainIndex) {
79966 for (var curPath in domainIndex) {
79967 var pathIndex = domainIndex[curPath];
79968 for (var key in pathIndex) {
79969 results.push(pathIndex[key]);
79970 }
79971 }
79972 };
79973
79974 } else {
79975 pathMatcher = function matchRFC(domainIndex) {
79976 //NOTE: we should use path-match algorithm from S5.1.4 here
79977 //(see : https://github.com/ChromiumWebApps/chromium/blob/b3d3b4da8bb94c1b2e061600df106d590fda3620/net/cookies/canonical_cookie.cc#L299)
79978 Object.keys(domainIndex).forEach(function (cookiePath) {
79979 if (pathMatch(path, cookiePath)) {
79980 var pathIndex = domainIndex[cookiePath];
79981
79982 for (var key in pathIndex) {
79983 results.push(pathIndex[key]);
79984 }
79985 }
79986 });
79987 };
79988 }
79989
79990 var domains = permuteDomain(domain) || [domain];
79991 var idx = this.idx;
79992 domains.forEach(function(curDomain) {
79993 var domainIndex = idx[curDomain];
79994 if (!domainIndex) {
79995 return;
79996 }
79997 pathMatcher(domainIndex);
79998 });
79999
80000 cb(null,results);
80001};
80002
80003MemoryCookieStore.prototype.putCookie = function(cookie, cb) {
80004 if (!this.idx[cookie.domain]) {
80005 this.idx[cookie.domain] = {};
80006 }
80007 if (!this.idx[cookie.domain][cookie.path]) {
80008 this.idx[cookie.domain][cookie.path] = {};
80009 }
80010 this.idx[cookie.domain][cookie.path][cookie.key] = cookie;
80011 cb(null);
80012};
80013
80014MemoryCookieStore.prototype.updateCookie = function(oldCookie, newCookie, cb) {
80015 // updateCookie() may avoid updating cookies that are identical. For example,
80016 // lastAccessed may not be important to some stores and an equality
80017 // comparison could exclude that field.
80018 this.putCookie(newCookie,cb);
80019};
80020
80021MemoryCookieStore.prototype.removeCookie = function(domain, path, key, cb) {
80022 if (this.idx[domain] && this.idx[domain][path] && this.idx[domain][path][key]) {
80023 delete this.idx[domain][path][key];
80024 }
80025 cb(null);
80026};
80027
80028MemoryCookieStore.prototype.removeCookies = function(domain, path, cb) {
80029 if (this.idx[domain]) {
80030 if (path) {
80031 delete this.idx[domain][path];
80032 } else {
80033 delete this.idx[domain];
80034 }
80035 }
80036 return cb(null);
80037};
80038
80039MemoryCookieStore.prototype.removeAllCookies = function(cb) {
80040 this.idx = {};
80041 return cb(null);
80042}
80043
80044MemoryCookieStore.prototype.getAllCookies = function(cb) {
80045 var cookies = [];
80046 var idx = this.idx;
80047
80048 var domains = Object.keys(idx);
80049 domains.forEach(function(domain) {
80050 var paths = Object.keys(idx[domain]);
80051 paths.forEach(function(path) {
80052 var keys = Object.keys(idx[domain][path]);
80053 keys.forEach(function(key) {
80054 if (key !== null) {
80055 cookies.push(idx[domain][path][key]);
80056 }
80057 });
80058 });
80059 });
80060
80061 // Sort by creationIndex so deserializing retains the creation order.
80062 // When implementing your own store, this SHOULD retain the order too
80063 cookies.sort(function(a,b) {
80064 return (a.creationIndex||0) - (b.creationIndex||0);
80065 });
80066
80067 cb(null, cookies);
80068};
80069
80070},{"./pathMatch":385,"./permuteDomain":386,"./store":388,"util":397}],385:[function(require,module,exports){
80071arguments[4][318][0].apply(exports,arguments)
80072},{"dup":318}],386:[function(require,module,exports){
80073arguments[4][319][0].apply(exports,arguments)
80074},{"./pubsuffix-psl":387,"dup":319}],387:[function(require,module,exports){
80075arguments[4][320][0].apply(exports,arguments)
80076},{"dup":320,"psl":267}],388:[function(require,module,exports){
80077/*!
80078 * Copyright (c) 2015, Salesforce.com, Inc.
80079 * All rights reserved.
80080 *
80081 * Redistribution and use in source and binary forms, with or without
80082 * modification, are permitted provided that the following conditions are met:
80083 *
80084 * 1. Redistributions of source code must retain the above copyright notice,
80085 * this list of conditions and the following disclaimer.
80086 *
80087 * 2. Redistributions in binary form must reproduce the above copyright notice,
80088 * this list of conditions and the following disclaimer in the documentation
80089 * and/or other materials provided with the distribution.
80090 *
80091 * 3. Neither the name of Salesforce.com nor the names of its contributors may
80092 * be used to endorse or promote products derived from this software without
80093 * specific prior written permission.
80094 *
80095 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
80096 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
80097 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
80098 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
80099 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
80100 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
80101 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
80102 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
80103 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
80104 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
80105 * POSSIBILITY OF SUCH DAMAGE.
80106 */
80107'use strict';
80108/*jshint unused:false */
80109
80110function Store() {
80111}
80112exports.Store = Store;
80113
80114// Stores may be synchronous, but are still required to use a
80115// Continuation-Passing Style API. The CookieJar itself will expose a "*Sync"
80116// API that converts from synchronous-callbacks to imperative style.
80117Store.prototype.synchronous = false;
80118
80119Store.prototype.findCookie = function(domain, path, key, cb) {
80120 throw new Error('findCookie is not implemented');
80121};
80122
80123Store.prototype.findCookies = function(domain, path, cb) {
80124 throw new Error('findCookies is not implemented');
80125};
80126
80127Store.prototype.putCookie = function(cookie, cb) {
80128 throw new Error('putCookie is not implemented');
80129};
80130
80131Store.prototype.updateCookie = function(oldCookie, newCookie, cb) {
80132 // recommended default implementation:
80133 // return this.putCookie(newCookie, cb);
80134 throw new Error('updateCookie is not implemented');
80135};
80136
80137Store.prototype.removeCookie = function(domain, path, key, cb) {
80138 throw new Error('removeCookie is not implemented');
80139};
80140
80141Store.prototype.removeCookies = function(domain, path, cb) {
80142 throw new Error('removeCookies is not implemented');
80143};
80144
80145Store.prototype.removeAllCookies = function(cb) {
80146 throw new Error('removeAllCookies is not implemented');
80147}
80148
80149Store.prototype.getAllCookies = function(cb) {
80150 throw new Error('getAllCookies is not implemented (therefore jar cannot be serialized)');
80151};
80152
80153},{}],389:[function(require,module,exports){
80154// generated by genversion
80155module.exports = '2.5.0'
80156
80157},{}],390:[function(require,module,exports){
80158(function (process){
80159'use strict'
80160
80161var net = require('net')
80162 , tls = require('tls')
80163 , http = require('http')
80164 , https = require('https')
80165 , events = require('events')
80166 , assert = require('assert')
80167 , util = require('util')
80168 , Buffer = require('safe-buffer').Buffer
80169 ;
80170
80171exports.httpOverHttp = httpOverHttp
80172exports.httpsOverHttp = httpsOverHttp
80173exports.httpOverHttps = httpOverHttps
80174exports.httpsOverHttps = httpsOverHttps
80175
80176
80177function httpOverHttp(options) {
80178 var agent = new TunnelingAgent(options)
80179 agent.request = http.request
80180 return agent
80181}
80182
80183function httpsOverHttp(options) {
80184 var agent = new TunnelingAgent(options)
80185 agent.request = http.request
80186 agent.createSocket = createSecureSocket
80187 agent.defaultPort = 443
80188 return agent
80189}
80190
80191function httpOverHttps(options) {
80192 var agent = new TunnelingAgent(options)
80193 agent.request = https.request
80194 return agent
80195}
80196
80197function httpsOverHttps(options) {
80198 var agent = new TunnelingAgent(options)
80199 agent.request = https.request
80200 agent.createSocket = createSecureSocket
80201 agent.defaultPort = 443
80202 return agent
80203}
80204
80205
80206function TunnelingAgent(options) {
80207 var self = this
80208 self.options = options || {}
80209 self.proxyOptions = self.options.proxy || {}
80210 self.maxSockets = self.options.maxSockets || http.Agent.defaultMaxSockets
80211 self.requests = []
80212 self.sockets = []
80213
80214 self.on('free', function onFree(socket, host, port) {
80215 for (var i = 0, len = self.requests.length; i < len; ++i) {
80216 var pending = self.requests[i]
80217 if (pending.host === host && pending.port === port) {
80218 // Detect the request to connect same origin server,
80219 // reuse the connection.
80220 self.requests.splice(i, 1)
80221 pending.request.onSocket(socket)
80222 return
80223 }
80224 }
80225 socket.destroy()
80226 self.removeSocket(socket)
80227 })
80228}
80229util.inherits(TunnelingAgent, events.EventEmitter)
80230
80231TunnelingAgent.prototype.addRequest = function addRequest(req, options) {
80232 var self = this
80233
80234 // Legacy API: addRequest(req, host, port, path)
80235 if (typeof options === 'string') {
80236 options = {
80237 host: options,
80238 port: arguments[2],
80239 path: arguments[3]
80240 };
80241 }
80242
80243 if (self.sockets.length >= this.maxSockets) {
80244 // We are over limit so we'll add it to the queue.
80245 self.requests.push({host: options.host, port: options.port, request: req})
80246 return
80247 }
80248
80249 // If we are under maxSockets create a new one.
80250 self.createConnection({host: options.host, port: options.port, request: req})
80251}
80252
80253TunnelingAgent.prototype.createConnection = function createConnection(pending) {
80254 var self = this
80255
80256 self.createSocket(pending, function(socket) {
80257 socket.on('free', onFree)
80258 socket.on('close', onCloseOrRemove)
80259 socket.on('agentRemove', onCloseOrRemove)
80260 pending.request.onSocket(socket)
80261
80262 function onFree() {
80263 self.emit('free', socket, pending.host, pending.port)
80264 }
80265
80266 function onCloseOrRemove(err) {
80267 self.removeSocket(socket)
80268 socket.removeListener('free', onFree)
80269 socket.removeListener('close', onCloseOrRemove)
80270 socket.removeListener('agentRemove', onCloseOrRemove)
80271 }
80272 })
80273}
80274
80275TunnelingAgent.prototype.createSocket = function createSocket(options, cb) {
80276 var self = this
80277 var placeholder = {}
80278 self.sockets.push(placeholder)
80279
80280 var connectOptions = mergeOptions({}, self.proxyOptions,
80281 { method: 'CONNECT'
80282 , path: options.host + ':' + options.port
80283 , agent: false
80284 }
80285 )
80286 if (connectOptions.proxyAuth) {
80287 connectOptions.headers = connectOptions.headers || {}
80288 connectOptions.headers['Proxy-Authorization'] = 'Basic ' +
80289 Buffer.from(connectOptions.proxyAuth).toString('base64')
80290 }
80291
80292 debug('making CONNECT request')
80293 var connectReq = self.request(connectOptions)
80294 connectReq.useChunkedEncodingByDefault = false // for v0.6
80295 connectReq.once('response', onResponse) // for v0.6
80296 connectReq.once('upgrade', onUpgrade) // for v0.6
80297 connectReq.once('connect', onConnect) // for v0.7 or later
80298 connectReq.once('error', onError)
80299 connectReq.end()
80300
80301 function onResponse(res) {
80302 // Very hacky. This is necessary to avoid http-parser leaks.
80303 res.upgrade = true
80304 }
80305
80306 function onUpgrade(res, socket, head) {
80307 // Hacky.
80308 process.nextTick(function() {
80309 onConnect(res, socket, head)
80310 })
80311 }
80312
80313 function onConnect(res, socket, head) {
80314 connectReq.removeAllListeners()
80315 socket.removeAllListeners()
80316
80317 if (res.statusCode === 200) {
80318 assert.equal(head.length, 0)
80319 debug('tunneling connection has established')
80320 self.sockets[self.sockets.indexOf(placeholder)] = socket
80321 cb(socket)
80322 } else {
80323 debug('tunneling socket could not be established, statusCode=%d', res.statusCode)
80324 var error = new Error('tunneling socket could not be established, ' + 'statusCode=' + res.statusCode)
80325 error.code = 'ECONNRESET'
80326 options.request.emit('error', error)
80327 self.removeSocket(placeholder)
80328 }
80329 }
80330
80331 function onError(cause) {
80332 connectReq.removeAllListeners()
80333
80334 debug('tunneling socket could not be established, cause=%s\n', cause.message, cause.stack)
80335 var error = new Error('tunneling socket could not be established, ' + 'cause=' + cause.message)
80336 error.code = 'ECONNRESET'
80337 options.request.emit('error', error)
80338 self.removeSocket(placeholder)
80339 }
80340}
80341
80342TunnelingAgent.prototype.removeSocket = function removeSocket(socket) {
80343 var pos = this.sockets.indexOf(socket)
80344 if (pos === -1) return
80345
80346 this.sockets.splice(pos, 1)
80347
80348 var pending = this.requests.shift()
80349 if (pending) {
80350 // If we have pending requests and a socket gets closed a new one
80351 // needs to be created to take over in the pool for the one that closed.
80352 this.createConnection(pending)
80353 }
80354}
80355
80356function createSecureSocket(options, cb) {
80357 var self = this
80358 TunnelingAgent.prototype.createSocket.call(self, options, function(socket) {
80359 // 0 is dummy port for v0.6
80360 var secureSocket = tls.connect(0, mergeOptions({}, self.options,
80361 { servername: options.host
80362 , socket: socket
80363 }
80364 ))
80365 self.sockets[self.sockets.indexOf(socket)] = secureSocket
80366 cb(secureSocket)
80367 })
80368}
80369
80370
80371function mergeOptions(target) {
80372 for (var i = 1, len = arguments.length; i < len; ++i) {
80373 var overrides = arguments[i]
80374 if (typeof overrides === 'object') {
80375 var keys = Object.keys(overrides)
80376 for (var j = 0, keyLen = keys.length; j < keyLen; ++j) {
80377 var k = keys[j]
80378 if (overrides[k] !== undefined) {
80379 target[k] = overrides[k]
80380 }
80381 }
80382 }
80383 }
80384 return target
80385}
80386
80387
80388var debug
80389if (process.env.NODE_DEBUG && /\btunnel\b/.test(process.env.NODE_DEBUG)) {
80390 debug = function() {
80391 var args = Array.prototype.slice.call(arguments)
80392 if (typeof args[0] === 'string') {
80393 args[0] = 'TUNNEL: ' + args[0]
80394 } else {
80395 args.unshift('TUNNEL:')
80396 }
80397 console.error.apply(console, args)
80398 }
80399} else {
80400 debug = function() {}
80401}
80402exports.debug = debug // for test
80403
80404}).call(this,require('_process'))
80405},{"_process":265,"assert":68,"events":159,"http":362,"https":208,"net":112,"safe-buffer":325,"tls":112,"util":397}],391:[function(require,module,exports){
80406(function(nacl) {
80407'use strict';
80408
80409// Ported in 2014 by Dmitry Chestnykh and Devi Mandiri.
80410// Public domain.
80411//
80412// Implementation derived from TweetNaCl version 20140427.
80413// See for details: http://tweetnacl.cr.yp.to/
80414
80415var gf = function(init) {
80416 var i, r = new Float64Array(16);
80417 if (init) for (i = 0; i < init.length; i++) r[i] = init[i];
80418 return r;
80419};
80420
80421// Pluggable, initialized in high-level API below.
80422var randombytes = function(/* x, n */) { throw new Error('no PRNG'); };
80423
80424var _0 = new Uint8Array(16);
80425var _9 = new Uint8Array(32); _9[0] = 9;
80426
80427var gf0 = gf(),
80428 gf1 = gf([1]),
80429 _121665 = gf([0xdb41, 1]),
80430 D = gf([0x78a3, 0x1359, 0x4dca, 0x75eb, 0xd8ab, 0x4141, 0x0a4d, 0x0070, 0xe898, 0x7779, 0x4079, 0x8cc7, 0xfe73, 0x2b6f, 0x6cee, 0x5203]),
80431 D2 = gf([0xf159, 0x26b2, 0x9b94, 0xebd6, 0xb156, 0x8283, 0x149a, 0x00e0, 0xd130, 0xeef3, 0x80f2, 0x198e, 0xfce7, 0x56df, 0xd9dc, 0x2406]),
80432 X = gf([0xd51a, 0x8f25, 0x2d60, 0xc956, 0xa7b2, 0x9525, 0xc760, 0x692c, 0xdc5c, 0xfdd6, 0xe231, 0xc0a4, 0x53fe, 0xcd6e, 0x36d3, 0x2169]),
80433 Y = gf([0x6658, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666]),
80434 I = gf([0xa0b0, 0x4a0e, 0x1b27, 0xc4ee, 0xe478, 0xad2f, 0x1806, 0x2f43, 0xd7a7, 0x3dfb, 0x0099, 0x2b4d, 0xdf0b, 0x4fc1, 0x2480, 0x2b83]);
80435
80436function ts64(x, i, h, l) {
80437 x[i] = (h >> 24) & 0xff;
80438 x[i+1] = (h >> 16) & 0xff;
80439 x[i+2] = (h >> 8) & 0xff;
80440 x[i+3] = h & 0xff;
80441 x[i+4] = (l >> 24) & 0xff;
80442 x[i+5] = (l >> 16) & 0xff;
80443 x[i+6] = (l >> 8) & 0xff;
80444 x[i+7] = l & 0xff;
80445}
80446
80447function vn(x, xi, y, yi, n) {
80448 var i,d = 0;
80449 for (i = 0; i < n; i++) d |= x[xi+i]^y[yi+i];
80450 return (1 & ((d - 1) >>> 8)) - 1;
80451}
80452
80453function crypto_verify_16(x, xi, y, yi) {
80454 return vn(x,xi,y,yi,16);
80455}
80456
80457function crypto_verify_32(x, xi, y, yi) {
80458 return vn(x,xi,y,yi,32);
80459}
80460
80461function core_salsa20(o, p, k, c) {
80462 var j0 = c[ 0] & 0xff | (c[ 1] & 0xff)<<8 | (c[ 2] & 0xff)<<16 | (c[ 3] & 0xff)<<24,
80463 j1 = k[ 0] & 0xff | (k[ 1] & 0xff)<<8 | (k[ 2] & 0xff)<<16 | (k[ 3] & 0xff)<<24,
80464 j2 = k[ 4] & 0xff | (k[ 5] & 0xff)<<8 | (k[ 6] & 0xff)<<16 | (k[ 7] & 0xff)<<24,
80465 j3 = k[ 8] & 0xff | (k[ 9] & 0xff)<<8 | (k[10] & 0xff)<<16 | (k[11] & 0xff)<<24,
80466 j4 = k[12] & 0xff | (k[13] & 0xff)<<8 | (k[14] & 0xff)<<16 | (k[15] & 0xff)<<24,
80467 j5 = c[ 4] & 0xff | (c[ 5] & 0xff)<<8 | (c[ 6] & 0xff)<<16 | (c[ 7] & 0xff)<<24,
80468 j6 = p[ 0] & 0xff | (p[ 1] & 0xff)<<8 | (p[ 2] & 0xff)<<16 | (p[ 3] & 0xff)<<24,
80469 j7 = p[ 4] & 0xff | (p[ 5] & 0xff)<<8 | (p[ 6] & 0xff)<<16 | (p[ 7] & 0xff)<<24,
80470 j8 = p[ 8] & 0xff | (p[ 9] & 0xff)<<8 | (p[10] & 0xff)<<16 | (p[11] & 0xff)<<24,
80471 j9 = p[12] & 0xff | (p[13] & 0xff)<<8 | (p[14] & 0xff)<<16 | (p[15] & 0xff)<<24,
80472 j10 = c[ 8] & 0xff | (c[ 9] & 0xff)<<8 | (c[10] & 0xff)<<16 | (c[11] & 0xff)<<24,
80473 j11 = k[16] & 0xff | (k[17] & 0xff)<<8 | (k[18] & 0xff)<<16 | (k[19] & 0xff)<<24,
80474 j12 = k[20] & 0xff | (k[21] & 0xff)<<8 | (k[22] & 0xff)<<16 | (k[23] & 0xff)<<24,
80475 j13 = k[24] & 0xff | (k[25] & 0xff)<<8 | (k[26] & 0xff)<<16 | (k[27] & 0xff)<<24,
80476 j14 = k[28] & 0xff | (k[29] & 0xff)<<8 | (k[30] & 0xff)<<16 | (k[31] & 0xff)<<24,
80477 j15 = c[12] & 0xff | (c[13] & 0xff)<<8 | (c[14] & 0xff)<<16 | (c[15] & 0xff)<<24;
80478
80479 var x0 = j0, x1 = j1, x2 = j2, x3 = j3, x4 = j4, x5 = j5, x6 = j6, x7 = j7,
80480 x8 = j8, x9 = j9, x10 = j10, x11 = j11, x12 = j12, x13 = j13, x14 = j14,
80481 x15 = j15, u;
80482
80483 for (var i = 0; i < 20; i += 2) {
80484 u = x0 + x12 | 0;
80485 x4 ^= u<<7 | u>>>(32-7);
80486 u = x4 + x0 | 0;
80487 x8 ^= u<<9 | u>>>(32-9);
80488 u = x8 + x4 | 0;
80489 x12 ^= u<<13 | u>>>(32-13);
80490 u = x12 + x8 | 0;
80491 x0 ^= u<<18 | u>>>(32-18);
80492
80493 u = x5 + x1 | 0;
80494 x9 ^= u<<7 | u>>>(32-7);
80495 u = x9 + x5 | 0;
80496 x13 ^= u<<9 | u>>>(32-9);
80497 u = x13 + x9 | 0;
80498 x1 ^= u<<13 | u>>>(32-13);
80499 u = x1 + x13 | 0;
80500 x5 ^= u<<18 | u>>>(32-18);
80501
80502 u = x10 + x6 | 0;
80503 x14 ^= u<<7 | u>>>(32-7);
80504 u = x14 + x10 | 0;
80505 x2 ^= u<<9 | u>>>(32-9);
80506 u = x2 + x14 | 0;
80507 x6 ^= u<<13 | u>>>(32-13);
80508 u = x6 + x2 | 0;
80509 x10 ^= u<<18 | u>>>(32-18);
80510
80511 u = x15 + x11 | 0;
80512 x3 ^= u<<7 | u>>>(32-7);
80513 u = x3 + x15 | 0;
80514 x7 ^= u<<9 | u>>>(32-9);
80515 u = x7 + x3 | 0;
80516 x11 ^= u<<13 | u>>>(32-13);
80517 u = x11 + x7 | 0;
80518 x15 ^= u<<18 | u>>>(32-18);
80519
80520 u = x0 + x3 | 0;
80521 x1 ^= u<<7 | u>>>(32-7);
80522 u = x1 + x0 | 0;
80523 x2 ^= u<<9 | u>>>(32-9);
80524 u = x2 + x1 | 0;
80525 x3 ^= u<<13 | u>>>(32-13);
80526 u = x3 + x2 | 0;
80527 x0 ^= u<<18 | u>>>(32-18);
80528
80529 u = x5 + x4 | 0;
80530 x6 ^= u<<7 | u>>>(32-7);
80531 u = x6 + x5 | 0;
80532 x7 ^= u<<9 | u>>>(32-9);
80533 u = x7 + x6 | 0;
80534 x4 ^= u<<13 | u>>>(32-13);
80535 u = x4 + x7 | 0;
80536 x5 ^= u<<18 | u>>>(32-18);
80537
80538 u = x10 + x9 | 0;
80539 x11 ^= u<<7 | u>>>(32-7);
80540 u = x11 + x10 | 0;
80541 x8 ^= u<<9 | u>>>(32-9);
80542 u = x8 + x11 | 0;
80543 x9 ^= u<<13 | u>>>(32-13);
80544 u = x9 + x8 | 0;
80545 x10 ^= u<<18 | u>>>(32-18);
80546
80547 u = x15 + x14 | 0;
80548 x12 ^= u<<7 | u>>>(32-7);
80549 u = x12 + x15 | 0;
80550 x13 ^= u<<9 | u>>>(32-9);
80551 u = x13 + x12 | 0;
80552 x14 ^= u<<13 | u>>>(32-13);
80553 u = x14 + x13 | 0;
80554 x15 ^= u<<18 | u>>>(32-18);
80555 }
80556 x0 = x0 + j0 | 0;
80557 x1 = x1 + j1 | 0;
80558 x2 = x2 + j2 | 0;
80559 x3 = x3 + j3 | 0;
80560 x4 = x4 + j4 | 0;
80561 x5 = x5 + j5 | 0;
80562 x6 = x6 + j6 | 0;
80563 x7 = x7 + j7 | 0;
80564 x8 = x8 + j8 | 0;
80565 x9 = x9 + j9 | 0;
80566 x10 = x10 + j10 | 0;
80567 x11 = x11 + j11 | 0;
80568 x12 = x12 + j12 | 0;
80569 x13 = x13 + j13 | 0;
80570 x14 = x14 + j14 | 0;
80571 x15 = x15 + j15 | 0;
80572
80573 o[ 0] = x0 >>> 0 & 0xff;
80574 o[ 1] = x0 >>> 8 & 0xff;
80575 o[ 2] = x0 >>> 16 & 0xff;
80576 o[ 3] = x0 >>> 24 & 0xff;
80577
80578 o[ 4] = x1 >>> 0 & 0xff;
80579 o[ 5] = x1 >>> 8 & 0xff;
80580 o[ 6] = x1 >>> 16 & 0xff;
80581 o[ 7] = x1 >>> 24 & 0xff;
80582
80583 o[ 8] = x2 >>> 0 & 0xff;
80584 o[ 9] = x2 >>> 8 & 0xff;
80585 o[10] = x2 >>> 16 & 0xff;
80586 o[11] = x2 >>> 24 & 0xff;
80587
80588 o[12] = x3 >>> 0 & 0xff;
80589 o[13] = x3 >>> 8 & 0xff;
80590 o[14] = x3 >>> 16 & 0xff;
80591 o[15] = x3 >>> 24 & 0xff;
80592
80593 o[16] = x4 >>> 0 & 0xff;
80594 o[17] = x4 >>> 8 & 0xff;
80595 o[18] = x4 >>> 16 & 0xff;
80596 o[19] = x4 >>> 24 & 0xff;
80597
80598 o[20] = x5 >>> 0 & 0xff;
80599 o[21] = x5 >>> 8 & 0xff;
80600 o[22] = x5 >>> 16 & 0xff;
80601 o[23] = x5 >>> 24 & 0xff;
80602
80603 o[24] = x6 >>> 0 & 0xff;
80604 o[25] = x6 >>> 8 & 0xff;
80605 o[26] = x6 >>> 16 & 0xff;
80606 o[27] = x6 >>> 24 & 0xff;
80607
80608 o[28] = x7 >>> 0 & 0xff;
80609 o[29] = x7 >>> 8 & 0xff;
80610 o[30] = x7 >>> 16 & 0xff;
80611 o[31] = x7 >>> 24 & 0xff;
80612
80613 o[32] = x8 >>> 0 & 0xff;
80614 o[33] = x8 >>> 8 & 0xff;
80615 o[34] = x8 >>> 16 & 0xff;
80616 o[35] = x8 >>> 24 & 0xff;
80617
80618 o[36] = x9 >>> 0 & 0xff;
80619 o[37] = x9 >>> 8 & 0xff;
80620 o[38] = x9 >>> 16 & 0xff;
80621 o[39] = x9 >>> 24 & 0xff;
80622
80623 o[40] = x10 >>> 0 & 0xff;
80624 o[41] = x10 >>> 8 & 0xff;
80625 o[42] = x10 >>> 16 & 0xff;
80626 o[43] = x10 >>> 24 & 0xff;
80627
80628 o[44] = x11 >>> 0 & 0xff;
80629 o[45] = x11 >>> 8 & 0xff;
80630 o[46] = x11 >>> 16 & 0xff;
80631 o[47] = x11 >>> 24 & 0xff;
80632
80633 o[48] = x12 >>> 0 & 0xff;
80634 o[49] = x12 >>> 8 & 0xff;
80635 o[50] = x12 >>> 16 & 0xff;
80636 o[51] = x12 >>> 24 & 0xff;
80637
80638 o[52] = x13 >>> 0 & 0xff;
80639 o[53] = x13 >>> 8 & 0xff;
80640 o[54] = x13 >>> 16 & 0xff;
80641 o[55] = x13 >>> 24 & 0xff;
80642
80643 o[56] = x14 >>> 0 & 0xff;
80644 o[57] = x14 >>> 8 & 0xff;
80645 o[58] = x14 >>> 16 & 0xff;
80646 o[59] = x14 >>> 24 & 0xff;
80647
80648 o[60] = x15 >>> 0 & 0xff;
80649 o[61] = x15 >>> 8 & 0xff;
80650 o[62] = x15 >>> 16 & 0xff;
80651 o[63] = x15 >>> 24 & 0xff;
80652}
80653
80654function core_hsalsa20(o,p,k,c) {
80655 var j0 = c[ 0] & 0xff | (c[ 1] & 0xff)<<8 | (c[ 2] & 0xff)<<16 | (c[ 3] & 0xff)<<24,
80656 j1 = k[ 0] & 0xff | (k[ 1] & 0xff)<<8 | (k[ 2] & 0xff)<<16 | (k[ 3] & 0xff)<<24,
80657 j2 = k[ 4] & 0xff | (k[ 5] & 0xff)<<8 | (k[ 6] & 0xff)<<16 | (k[ 7] & 0xff)<<24,
80658 j3 = k[ 8] & 0xff | (k[ 9] & 0xff)<<8 | (k[10] & 0xff)<<16 | (k[11] & 0xff)<<24,
80659 j4 = k[12] & 0xff | (k[13] & 0xff)<<8 | (k[14] & 0xff)<<16 | (k[15] & 0xff)<<24,
80660 j5 = c[ 4] & 0xff | (c[ 5] & 0xff)<<8 | (c[ 6] & 0xff)<<16 | (c[ 7] & 0xff)<<24,
80661 j6 = p[ 0] & 0xff | (p[ 1] & 0xff)<<8 | (p[ 2] & 0xff)<<16 | (p[ 3] & 0xff)<<24,
80662 j7 = p[ 4] & 0xff | (p[ 5] & 0xff)<<8 | (p[ 6] & 0xff)<<16 | (p[ 7] & 0xff)<<24,
80663 j8 = p[ 8] & 0xff | (p[ 9] & 0xff)<<8 | (p[10] & 0xff)<<16 | (p[11] & 0xff)<<24,
80664 j9 = p[12] & 0xff | (p[13] & 0xff)<<8 | (p[14] & 0xff)<<16 | (p[15] & 0xff)<<24,
80665 j10 = c[ 8] & 0xff | (c[ 9] & 0xff)<<8 | (c[10] & 0xff)<<16 | (c[11] & 0xff)<<24,
80666 j11 = k[16] & 0xff | (k[17] & 0xff)<<8 | (k[18] & 0xff)<<16 | (k[19] & 0xff)<<24,
80667 j12 = k[20] & 0xff | (k[21] & 0xff)<<8 | (k[22] & 0xff)<<16 | (k[23] & 0xff)<<24,
80668 j13 = k[24] & 0xff | (k[25] & 0xff)<<8 | (k[26] & 0xff)<<16 | (k[27] & 0xff)<<24,
80669 j14 = k[28] & 0xff | (k[29] & 0xff)<<8 | (k[30] & 0xff)<<16 | (k[31] & 0xff)<<24,
80670 j15 = c[12] & 0xff | (c[13] & 0xff)<<8 | (c[14] & 0xff)<<16 | (c[15] & 0xff)<<24;
80671
80672 var x0 = j0, x1 = j1, x2 = j2, x3 = j3, x4 = j4, x5 = j5, x6 = j6, x7 = j7,
80673 x8 = j8, x9 = j9, x10 = j10, x11 = j11, x12 = j12, x13 = j13, x14 = j14,
80674 x15 = j15, u;
80675
80676 for (var i = 0; i < 20; i += 2) {
80677 u = x0 + x12 | 0;
80678 x4 ^= u<<7 | u>>>(32-7);
80679 u = x4 + x0 | 0;
80680 x8 ^= u<<9 | u>>>(32-9);
80681 u = x8 + x4 | 0;
80682 x12 ^= u<<13 | u>>>(32-13);
80683 u = x12 + x8 | 0;
80684 x0 ^= u<<18 | u>>>(32-18);
80685
80686 u = x5 + x1 | 0;
80687 x9 ^= u<<7 | u>>>(32-7);
80688 u = x9 + x5 | 0;
80689 x13 ^= u<<9 | u>>>(32-9);
80690 u = x13 + x9 | 0;
80691 x1 ^= u<<13 | u>>>(32-13);
80692 u = x1 + x13 | 0;
80693 x5 ^= u<<18 | u>>>(32-18);
80694
80695 u = x10 + x6 | 0;
80696 x14 ^= u<<7 | u>>>(32-7);
80697 u = x14 + x10 | 0;
80698 x2 ^= u<<9 | u>>>(32-9);
80699 u = x2 + x14 | 0;
80700 x6 ^= u<<13 | u>>>(32-13);
80701 u = x6 + x2 | 0;
80702 x10 ^= u<<18 | u>>>(32-18);
80703
80704 u = x15 + x11 | 0;
80705 x3 ^= u<<7 | u>>>(32-7);
80706 u = x3 + x15 | 0;
80707 x7 ^= u<<9 | u>>>(32-9);
80708 u = x7 + x3 | 0;
80709 x11 ^= u<<13 | u>>>(32-13);
80710 u = x11 + x7 | 0;
80711 x15 ^= u<<18 | u>>>(32-18);
80712
80713 u = x0 + x3 | 0;
80714 x1 ^= u<<7 | u>>>(32-7);
80715 u = x1 + x0 | 0;
80716 x2 ^= u<<9 | u>>>(32-9);
80717 u = x2 + x1 | 0;
80718 x3 ^= u<<13 | u>>>(32-13);
80719 u = x3 + x2 | 0;
80720 x0 ^= u<<18 | u>>>(32-18);
80721
80722 u = x5 + x4 | 0;
80723 x6 ^= u<<7 | u>>>(32-7);
80724 u = x6 + x5 | 0;
80725 x7 ^= u<<9 | u>>>(32-9);
80726 u = x7 + x6 | 0;
80727 x4 ^= u<<13 | u>>>(32-13);
80728 u = x4 + x7 | 0;
80729 x5 ^= u<<18 | u>>>(32-18);
80730
80731 u = x10 + x9 | 0;
80732 x11 ^= u<<7 | u>>>(32-7);
80733 u = x11 + x10 | 0;
80734 x8 ^= u<<9 | u>>>(32-9);
80735 u = x8 + x11 | 0;
80736 x9 ^= u<<13 | u>>>(32-13);
80737 u = x9 + x8 | 0;
80738 x10 ^= u<<18 | u>>>(32-18);
80739
80740 u = x15 + x14 | 0;
80741 x12 ^= u<<7 | u>>>(32-7);
80742 u = x12 + x15 | 0;
80743 x13 ^= u<<9 | u>>>(32-9);
80744 u = x13 + x12 | 0;
80745 x14 ^= u<<13 | u>>>(32-13);
80746 u = x14 + x13 | 0;
80747 x15 ^= u<<18 | u>>>(32-18);
80748 }
80749
80750 o[ 0] = x0 >>> 0 & 0xff;
80751 o[ 1] = x0 >>> 8 & 0xff;
80752 o[ 2] = x0 >>> 16 & 0xff;
80753 o[ 3] = x0 >>> 24 & 0xff;
80754
80755 o[ 4] = x5 >>> 0 & 0xff;
80756 o[ 5] = x5 >>> 8 & 0xff;
80757 o[ 6] = x5 >>> 16 & 0xff;
80758 o[ 7] = x5 >>> 24 & 0xff;
80759
80760 o[ 8] = x10 >>> 0 & 0xff;
80761 o[ 9] = x10 >>> 8 & 0xff;
80762 o[10] = x10 >>> 16 & 0xff;
80763 o[11] = x10 >>> 24 & 0xff;
80764
80765 o[12] = x15 >>> 0 & 0xff;
80766 o[13] = x15 >>> 8 & 0xff;
80767 o[14] = x15 >>> 16 & 0xff;
80768 o[15] = x15 >>> 24 & 0xff;
80769
80770 o[16] = x6 >>> 0 & 0xff;
80771 o[17] = x6 >>> 8 & 0xff;
80772 o[18] = x6 >>> 16 & 0xff;
80773 o[19] = x6 >>> 24 & 0xff;
80774
80775 o[20] = x7 >>> 0 & 0xff;
80776 o[21] = x7 >>> 8 & 0xff;
80777 o[22] = x7 >>> 16 & 0xff;
80778 o[23] = x7 >>> 24 & 0xff;
80779
80780 o[24] = x8 >>> 0 & 0xff;
80781 o[25] = x8 >>> 8 & 0xff;
80782 o[26] = x8 >>> 16 & 0xff;
80783 o[27] = x8 >>> 24 & 0xff;
80784
80785 o[28] = x9 >>> 0 & 0xff;
80786 o[29] = x9 >>> 8 & 0xff;
80787 o[30] = x9 >>> 16 & 0xff;
80788 o[31] = x9 >>> 24 & 0xff;
80789}
80790
80791function crypto_core_salsa20(out,inp,k,c) {
80792 core_salsa20(out,inp,k,c);
80793}
80794
80795function crypto_core_hsalsa20(out,inp,k,c) {
80796 core_hsalsa20(out,inp,k,c);
80797}
80798
80799var sigma = new Uint8Array([101, 120, 112, 97, 110, 100, 32, 51, 50, 45, 98, 121, 116, 101, 32, 107]);
80800 // "expand 32-byte k"
80801
80802function crypto_stream_salsa20_xor(c,cpos,m,mpos,b,n,k) {
80803 var z = new Uint8Array(16), x = new Uint8Array(64);
80804 var u, i;
80805 for (i = 0; i < 16; i++) z[i] = 0;
80806 for (i = 0; i < 8; i++) z[i] = n[i];
80807 while (b >= 64) {
80808 crypto_core_salsa20(x,z,k,sigma);
80809 for (i = 0; i < 64; i++) c[cpos+i] = m[mpos+i] ^ x[i];
80810 u = 1;
80811 for (i = 8; i < 16; i++) {
80812 u = u + (z[i] & 0xff) | 0;
80813 z[i] = u & 0xff;
80814 u >>>= 8;
80815 }
80816 b -= 64;
80817 cpos += 64;
80818 mpos += 64;
80819 }
80820 if (b > 0) {
80821 crypto_core_salsa20(x,z,k,sigma);
80822 for (i = 0; i < b; i++) c[cpos+i] = m[mpos+i] ^ x[i];
80823 }
80824 return 0;
80825}
80826
80827function crypto_stream_salsa20(c,cpos,b,n,k) {
80828 var z = new Uint8Array(16), x = new Uint8Array(64);
80829 var u, i;
80830 for (i = 0; i < 16; i++) z[i] = 0;
80831 for (i = 0; i < 8; i++) z[i] = n[i];
80832 while (b >= 64) {
80833 crypto_core_salsa20(x,z,k,sigma);
80834 for (i = 0; i < 64; i++) c[cpos+i] = x[i];
80835 u = 1;
80836 for (i = 8; i < 16; i++) {
80837 u = u + (z[i] & 0xff) | 0;
80838 z[i] = u & 0xff;
80839 u >>>= 8;
80840 }
80841 b -= 64;
80842 cpos += 64;
80843 }
80844 if (b > 0) {
80845 crypto_core_salsa20(x,z,k,sigma);
80846 for (i = 0; i < b; i++) c[cpos+i] = x[i];
80847 }
80848 return 0;
80849}
80850
80851function crypto_stream(c,cpos,d,n,k) {
80852 var s = new Uint8Array(32);
80853 crypto_core_hsalsa20(s,n,k,sigma);
80854 var sn = new Uint8Array(8);
80855 for (var i = 0; i < 8; i++) sn[i] = n[i+16];
80856 return crypto_stream_salsa20(c,cpos,d,sn,s);
80857}
80858
80859function crypto_stream_xor(c,cpos,m,mpos,d,n,k) {
80860 var s = new Uint8Array(32);
80861 crypto_core_hsalsa20(s,n,k,sigma);
80862 var sn = new Uint8Array(8);
80863 for (var i = 0; i < 8; i++) sn[i] = n[i+16];
80864 return crypto_stream_salsa20_xor(c,cpos,m,mpos,d,sn,s);
80865}
80866
80867/*
80868* Port of Andrew Moon's Poly1305-donna-16. Public domain.
80869* https://github.com/floodyberry/poly1305-donna
80870*/
80871
80872var poly1305 = function(key) {
80873 this.buffer = new Uint8Array(16);
80874 this.r = new Uint16Array(10);
80875 this.h = new Uint16Array(10);
80876 this.pad = new Uint16Array(8);
80877 this.leftover = 0;
80878 this.fin = 0;
80879
80880 var t0, t1, t2, t3, t4, t5, t6, t7;
80881
80882 t0 = key[ 0] & 0xff | (key[ 1] & 0xff) << 8; this.r[0] = ( t0 ) & 0x1fff;
80883 t1 = key[ 2] & 0xff | (key[ 3] & 0xff) << 8; this.r[1] = ((t0 >>> 13) | (t1 << 3)) & 0x1fff;
80884 t2 = key[ 4] & 0xff | (key[ 5] & 0xff) << 8; this.r[2] = ((t1 >>> 10) | (t2 << 6)) & 0x1f03;
80885 t3 = key[ 6] & 0xff | (key[ 7] & 0xff) << 8; this.r[3] = ((t2 >>> 7) | (t3 << 9)) & 0x1fff;
80886 t4 = key[ 8] & 0xff | (key[ 9] & 0xff) << 8; this.r[4] = ((t3 >>> 4) | (t4 << 12)) & 0x00ff;
80887 this.r[5] = ((t4 >>> 1)) & 0x1ffe;
80888 t5 = key[10] & 0xff | (key[11] & 0xff) << 8; this.r[6] = ((t4 >>> 14) | (t5 << 2)) & 0x1fff;
80889 t6 = key[12] & 0xff | (key[13] & 0xff) << 8; this.r[7] = ((t5 >>> 11) | (t6 << 5)) & 0x1f81;
80890 t7 = key[14] & 0xff | (key[15] & 0xff) << 8; this.r[8] = ((t6 >>> 8) | (t7 << 8)) & 0x1fff;
80891 this.r[9] = ((t7 >>> 5)) & 0x007f;
80892
80893 this.pad[0] = key[16] & 0xff | (key[17] & 0xff) << 8;
80894 this.pad[1] = key[18] & 0xff | (key[19] & 0xff) << 8;
80895 this.pad[2] = key[20] & 0xff | (key[21] & 0xff) << 8;
80896 this.pad[3] = key[22] & 0xff | (key[23] & 0xff) << 8;
80897 this.pad[4] = key[24] & 0xff | (key[25] & 0xff) << 8;
80898 this.pad[5] = key[26] & 0xff | (key[27] & 0xff) << 8;
80899 this.pad[6] = key[28] & 0xff | (key[29] & 0xff) << 8;
80900 this.pad[7] = key[30] & 0xff | (key[31] & 0xff) << 8;
80901};
80902
80903poly1305.prototype.blocks = function(m, mpos, bytes) {
80904 var hibit = this.fin ? 0 : (1 << 11);
80905 var t0, t1, t2, t3, t4, t5, t6, t7, c;
80906 var d0, d1, d2, d3, d4, d5, d6, d7, d8, d9;
80907
80908 var h0 = this.h[0],
80909 h1 = this.h[1],
80910 h2 = this.h[2],
80911 h3 = this.h[3],
80912 h4 = this.h[4],
80913 h5 = this.h[5],
80914 h6 = this.h[6],
80915 h7 = this.h[7],
80916 h8 = this.h[8],
80917 h9 = this.h[9];
80918
80919 var r0 = this.r[0],
80920 r1 = this.r[1],
80921 r2 = this.r[2],
80922 r3 = this.r[3],
80923 r4 = this.r[4],
80924 r5 = this.r[5],
80925 r6 = this.r[6],
80926 r7 = this.r[7],
80927 r8 = this.r[8],
80928 r9 = this.r[9];
80929
80930 while (bytes >= 16) {
80931 t0 = m[mpos+ 0] & 0xff | (m[mpos+ 1] & 0xff) << 8; h0 += ( t0 ) & 0x1fff;
80932 t1 = m[mpos+ 2] & 0xff | (m[mpos+ 3] & 0xff) << 8; h1 += ((t0 >>> 13) | (t1 << 3)) & 0x1fff;
80933 t2 = m[mpos+ 4] & 0xff | (m[mpos+ 5] & 0xff) << 8; h2 += ((t1 >>> 10) | (t2 << 6)) & 0x1fff;
80934 t3 = m[mpos+ 6] & 0xff | (m[mpos+ 7] & 0xff) << 8; h3 += ((t2 >>> 7) | (t3 << 9)) & 0x1fff;
80935 t4 = m[mpos+ 8] & 0xff | (m[mpos+ 9] & 0xff) << 8; h4 += ((t3 >>> 4) | (t4 << 12)) & 0x1fff;
80936 h5 += ((t4 >>> 1)) & 0x1fff;
80937 t5 = m[mpos+10] & 0xff | (m[mpos+11] & 0xff) << 8; h6 += ((t4 >>> 14) | (t5 << 2)) & 0x1fff;
80938 t6 = m[mpos+12] & 0xff | (m[mpos+13] & 0xff) << 8; h7 += ((t5 >>> 11) | (t6 << 5)) & 0x1fff;
80939 t7 = m[mpos+14] & 0xff | (m[mpos+15] & 0xff) << 8; h8 += ((t6 >>> 8) | (t7 << 8)) & 0x1fff;
80940 h9 += ((t7 >>> 5)) | hibit;
80941
80942 c = 0;
80943
80944 d0 = c;
80945 d0 += h0 * r0;
80946 d0 += h1 * (5 * r9);
80947 d0 += h2 * (5 * r8);
80948 d0 += h3 * (5 * r7);
80949 d0 += h4 * (5 * r6);
80950 c = (d0 >>> 13); d0 &= 0x1fff;
80951 d0 += h5 * (5 * r5);
80952 d0 += h6 * (5 * r4);
80953 d0 += h7 * (5 * r3);
80954 d0 += h8 * (5 * r2);
80955 d0 += h9 * (5 * r1);
80956 c += (d0 >>> 13); d0 &= 0x1fff;
80957
80958 d1 = c;
80959 d1 += h0 * r1;
80960 d1 += h1 * r0;
80961 d1 += h2 * (5 * r9);
80962 d1 += h3 * (5 * r8);
80963 d1 += h4 * (5 * r7);
80964 c = (d1 >>> 13); d1 &= 0x1fff;
80965 d1 += h5 * (5 * r6);
80966 d1 += h6 * (5 * r5);
80967 d1 += h7 * (5 * r4);
80968 d1 += h8 * (5 * r3);
80969 d1 += h9 * (5 * r2);
80970 c += (d1 >>> 13); d1 &= 0x1fff;
80971
80972 d2 = c;
80973 d2 += h0 * r2;
80974 d2 += h1 * r1;
80975 d2 += h2 * r0;
80976 d2 += h3 * (5 * r9);
80977 d2 += h4 * (5 * r8);
80978 c = (d2 >>> 13); d2 &= 0x1fff;
80979 d2 += h5 * (5 * r7);
80980 d2 += h6 * (5 * r6);
80981 d2 += h7 * (5 * r5);
80982 d2 += h8 * (5 * r4);
80983 d2 += h9 * (5 * r3);
80984 c += (d2 >>> 13); d2 &= 0x1fff;
80985
80986 d3 = c;
80987 d3 += h0 * r3;
80988 d3 += h1 * r2;
80989 d3 += h2 * r1;
80990 d3 += h3 * r0;
80991 d3 += h4 * (5 * r9);
80992 c = (d3 >>> 13); d3 &= 0x1fff;
80993 d3 += h5 * (5 * r8);
80994 d3 += h6 * (5 * r7);
80995 d3 += h7 * (5 * r6);
80996 d3 += h8 * (5 * r5);
80997 d3 += h9 * (5 * r4);
80998 c += (d3 >>> 13); d3 &= 0x1fff;
80999
81000 d4 = c;
81001 d4 += h0 * r4;
81002 d4 += h1 * r3;
81003 d4 += h2 * r2;
81004 d4 += h3 * r1;
81005 d4 += h4 * r0;
81006 c = (d4 >>> 13); d4 &= 0x1fff;
81007 d4 += h5 * (5 * r9);
81008 d4 += h6 * (5 * r8);
81009 d4 += h7 * (5 * r7);
81010 d4 += h8 * (5 * r6);
81011 d4 += h9 * (5 * r5);
81012 c += (d4 >>> 13); d4 &= 0x1fff;
81013
81014 d5 = c;
81015 d5 += h0 * r5;
81016 d5 += h1 * r4;
81017 d5 += h2 * r3;
81018 d5 += h3 * r2;
81019 d5 += h4 * r1;
81020 c = (d5 >>> 13); d5 &= 0x1fff;
81021 d5 += h5 * r0;
81022 d5 += h6 * (5 * r9);
81023 d5 += h7 * (5 * r8);
81024 d5 += h8 * (5 * r7);
81025 d5 += h9 * (5 * r6);
81026 c += (d5 >>> 13); d5 &= 0x1fff;
81027
81028 d6 = c;
81029 d6 += h0 * r6;
81030 d6 += h1 * r5;
81031 d6 += h2 * r4;
81032 d6 += h3 * r3;
81033 d6 += h4 * r2;
81034 c = (d6 >>> 13); d6 &= 0x1fff;
81035 d6 += h5 * r1;
81036 d6 += h6 * r0;
81037 d6 += h7 * (5 * r9);
81038 d6 += h8 * (5 * r8);
81039 d6 += h9 * (5 * r7);
81040 c += (d6 >>> 13); d6 &= 0x1fff;
81041
81042 d7 = c;
81043 d7 += h0 * r7;
81044 d7 += h1 * r6;
81045 d7 += h2 * r5;
81046 d7 += h3 * r4;
81047 d7 += h4 * r3;
81048 c = (d7 >>> 13); d7 &= 0x1fff;
81049 d7 += h5 * r2;
81050 d7 += h6 * r1;
81051 d7 += h7 * r0;
81052 d7 += h8 * (5 * r9);
81053 d7 += h9 * (5 * r8);
81054 c += (d7 >>> 13); d7 &= 0x1fff;
81055
81056 d8 = c;
81057 d8 += h0 * r8;
81058 d8 += h1 * r7;
81059 d8 += h2 * r6;
81060 d8 += h3 * r5;
81061 d8 += h4 * r4;
81062 c = (d8 >>> 13); d8 &= 0x1fff;
81063 d8 += h5 * r3;
81064 d8 += h6 * r2;
81065 d8 += h7 * r1;
81066 d8 += h8 * r0;
81067 d8 += h9 * (5 * r9);
81068 c += (d8 >>> 13); d8 &= 0x1fff;
81069
81070 d9 = c;
81071 d9 += h0 * r9;
81072 d9 += h1 * r8;
81073 d9 += h2 * r7;
81074 d9 += h3 * r6;
81075 d9 += h4 * r5;
81076 c = (d9 >>> 13); d9 &= 0x1fff;
81077 d9 += h5 * r4;
81078 d9 += h6 * r3;
81079 d9 += h7 * r2;
81080 d9 += h8 * r1;
81081 d9 += h9 * r0;
81082 c += (d9 >>> 13); d9 &= 0x1fff;
81083
81084 c = (((c << 2) + c)) | 0;
81085 c = (c + d0) | 0;
81086 d0 = c & 0x1fff;
81087 c = (c >>> 13);
81088 d1 += c;
81089
81090 h0 = d0;
81091 h1 = d1;
81092 h2 = d2;
81093 h3 = d3;
81094 h4 = d4;
81095 h5 = d5;
81096 h6 = d6;
81097 h7 = d7;
81098 h8 = d8;
81099 h9 = d9;
81100
81101 mpos += 16;
81102 bytes -= 16;
81103 }
81104 this.h[0] = h0;
81105 this.h[1] = h1;
81106 this.h[2] = h2;
81107 this.h[3] = h3;
81108 this.h[4] = h4;
81109 this.h[5] = h5;
81110 this.h[6] = h6;
81111 this.h[7] = h7;
81112 this.h[8] = h8;
81113 this.h[9] = h9;
81114};
81115
81116poly1305.prototype.finish = function(mac, macpos) {
81117 var g = new Uint16Array(10);
81118 var c, mask, f, i;
81119
81120 if (this.leftover) {
81121 i = this.leftover;
81122 this.buffer[i++] = 1;
81123 for (; i < 16; i++) this.buffer[i] = 0;
81124 this.fin = 1;
81125 this.blocks(this.buffer, 0, 16);
81126 }
81127
81128 c = this.h[1] >>> 13;
81129 this.h[1] &= 0x1fff;
81130 for (i = 2; i < 10; i++) {
81131 this.h[i] += c;
81132 c = this.h[i] >>> 13;
81133 this.h[i] &= 0x1fff;
81134 }
81135 this.h[0] += (c * 5);
81136 c = this.h[0] >>> 13;
81137 this.h[0] &= 0x1fff;
81138 this.h[1] += c;
81139 c = this.h[1] >>> 13;
81140 this.h[1] &= 0x1fff;
81141 this.h[2] += c;
81142
81143 g[0] = this.h[0] + 5;
81144 c = g[0] >>> 13;
81145 g[0] &= 0x1fff;
81146 for (i = 1; i < 10; i++) {
81147 g[i] = this.h[i] + c;
81148 c = g[i] >>> 13;
81149 g[i] &= 0x1fff;
81150 }
81151 g[9] -= (1 << 13);
81152
81153 mask = (c ^ 1) - 1;
81154 for (i = 0; i < 10; i++) g[i] &= mask;
81155 mask = ~mask;
81156 for (i = 0; i < 10; i++) this.h[i] = (this.h[i] & mask) | g[i];
81157
81158 this.h[0] = ((this.h[0] ) | (this.h[1] << 13) ) & 0xffff;
81159 this.h[1] = ((this.h[1] >>> 3) | (this.h[2] << 10) ) & 0xffff;
81160 this.h[2] = ((this.h[2] >>> 6) | (this.h[3] << 7) ) & 0xffff;
81161 this.h[3] = ((this.h[3] >>> 9) | (this.h[4] << 4) ) & 0xffff;
81162 this.h[4] = ((this.h[4] >>> 12) | (this.h[5] << 1) | (this.h[6] << 14)) & 0xffff;
81163 this.h[5] = ((this.h[6] >>> 2) | (this.h[7] << 11) ) & 0xffff;
81164 this.h[6] = ((this.h[7] >>> 5) | (this.h[8] << 8) ) & 0xffff;
81165 this.h[7] = ((this.h[8] >>> 8) | (this.h[9] << 5) ) & 0xffff;
81166
81167 f = this.h[0] + this.pad[0];
81168 this.h[0] = f & 0xffff;
81169 for (i = 1; i < 8; i++) {
81170 f = (((this.h[i] + this.pad[i]) | 0) + (f >>> 16)) | 0;
81171 this.h[i] = f & 0xffff;
81172 }
81173
81174 mac[macpos+ 0] = (this.h[0] >>> 0) & 0xff;
81175 mac[macpos+ 1] = (this.h[0] >>> 8) & 0xff;
81176 mac[macpos+ 2] = (this.h[1] >>> 0) & 0xff;
81177 mac[macpos+ 3] = (this.h[1] >>> 8) & 0xff;
81178 mac[macpos+ 4] = (this.h[2] >>> 0) & 0xff;
81179 mac[macpos+ 5] = (this.h[2] >>> 8) & 0xff;
81180 mac[macpos+ 6] = (this.h[3] >>> 0) & 0xff;
81181 mac[macpos+ 7] = (this.h[3] >>> 8) & 0xff;
81182 mac[macpos+ 8] = (this.h[4] >>> 0) & 0xff;
81183 mac[macpos+ 9] = (this.h[4] >>> 8) & 0xff;
81184 mac[macpos+10] = (this.h[5] >>> 0) & 0xff;
81185 mac[macpos+11] = (this.h[5] >>> 8) & 0xff;
81186 mac[macpos+12] = (this.h[6] >>> 0) & 0xff;
81187 mac[macpos+13] = (this.h[6] >>> 8) & 0xff;
81188 mac[macpos+14] = (this.h[7] >>> 0) & 0xff;
81189 mac[macpos+15] = (this.h[7] >>> 8) & 0xff;
81190};
81191
81192poly1305.prototype.update = function(m, mpos, bytes) {
81193 var i, want;
81194
81195 if (this.leftover) {
81196 want = (16 - this.leftover);
81197 if (want > bytes)
81198 want = bytes;
81199 for (i = 0; i < want; i++)
81200 this.buffer[this.leftover + i] = m[mpos+i];
81201 bytes -= want;
81202 mpos += want;
81203 this.leftover += want;
81204 if (this.leftover < 16)
81205 return;
81206 this.blocks(this.buffer, 0, 16);
81207 this.leftover = 0;
81208 }
81209
81210 if (bytes >= 16) {
81211 want = bytes - (bytes % 16);
81212 this.blocks(m, mpos, want);
81213 mpos += want;
81214 bytes -= want;
81215 }
81216
81217 if (bytes) {
81218 for (i = 0; i < bytes; i++)
81219 this.buffer[this.leftover + i] = m[mpos+i];
81220 this.leftover += bytes;
81221 }
81222};
81223
81224function crypto_onetimeauth(out, outpos, m, mpos, n, k) {
81225 var s = new poly1305(k);
81226 s.update(m, mpos, n);
81227 s.finish(out, outpos);
81228 return 0;
81229}
81230
81231function crypto_onetimeauth_verify(h, hpos, m, mpos, n, k) {
81232 var x = new Uint8Array(16);
81233 crypto_onetimeauth(x,0,m,mpos,n,k);
81234 return crypto_verify_16(h,hpos,x,0);
81235}
81236
81237function crypto_secretbox(c,m,d,n,k) {
81238 var i;
81239 if (d < 32) return -1;
81240 crypto_stream_xor(c,0,m,0,d,n,k);
81241 crypto_onetimeauth(c, 16, c, 32, d - 32, c);
81242 for (i = 0; i < 16; i++) c[i] = 0;
81243 return 0;
81244}
81245
81246function crypto_secretbox_open(m,c,d,n,k) {
81247 var i;
81248 var x = new Uint8Array(32);
81249 if (d < 32) return -1;
81250 crypto_stream(x,0,32,n,k);
81251 if (crypto_onetimeauth_verify(c, 16,c, 32,d - 32,x) !== 0) return -1;
81252 crypto_stream_xor(m,0,c,0,d,n,k);
81253 for (i = 0; i < 32; i++) m[i] = 0;
81254 return 0;
81255}
81256
81257function set25519(r, a) {
81258 var i;
81259 for (i = 0; i < 16; i++) r[i] = a[i]|0;
81260}
81261
81262function car25519(o) {
81263 var i, v, c = 1;
81264 for (i = 0; i < 16; i++) {
81265 v = o[i] + c + 65535;
81266 c = Math.floor(v / 65536);
81267 o[i] = v - c * 65536;
81268 }
81269 o[0] += c-1 + 37 * (c-1);
81270}
81271
81272function sel25519(p, q, b) {
81273 var t, c = ~(b-1);
81274 for (var i = 0; i < 16; i++) {
81275 t = c & (p[i] ^ q[i]);
81276 p[i] ^= t;
81277 q[i] ^= t;
81278 }
81279}
81280
81281function pack25519(o, n) {
81282 var i, j, b;
81283 var m = gf(), t = gf();
81284 for (i = 0; i < 16; i++) t[i] = n[i];
81285 car25519(t);
81286 car25519(t);
81287 car25519(t);
81288 for (j = 0; j < 2; j++) {
81289 m[0] = t[0] - 0xffed;
81290 for (i = 1; i < 15; i++) {
81291 m[i] = t[i] - 0xffff - ((m[i-1]>>16) & 1);
81292 m[i-1] &= 0xffff;
81293 }
81294 m[15] = t[15] - 0x7fff - ((m[14]>>16) & 1);
81295 b = (m[15]>>16) & 1;
81296 m[14] &= 0xffff;
81297 sel25519(t, m, 1-b);
81298 }
81299 for (i = 0; i < 16; i++) {
81300 o[2*i] = t[i] & 0xff;
81301 o[2*i+1] = t[i]>>8;
81302 }
81303}
81304
81305function neq25519(a, b) {
81306 var c = new Uint8Array(32), d = new Uint8Array(32);
81307 pack25519(c, a);
81308 pack25519(d, b);
81309 return crypto_verify_32(c, 0, d, 0);
81310}
81311
81312function par25519(a) {
81313 var d = new Uint8Array(32);
81314 pack25519(d, a);
81315 return d[0] & 1;
81316}
81317
81318function unpack25519(o, n) {
81319 var i;
81320 for (i = 0; i < 16; i++) o[i] = n[2*i] + (n[2*i+1] << 8);
81321 o[15] &= 0x7fff;
81322}
81323
81324function A(o, a, b) {
81325 for (var i = 0; i < 16; i++) o[i] = a[i] + b[i];
81326}
81327
81328function Z(o, a, b) {
81329 for (var i = 0; i < 16; i++) o[i] = a[i] - b[i];
81330}
81331
81332function M(o, a, b) {
81333 var v, c,
81334 t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0, t5 = 0, t6 = 0, t7 = 0,
81335 t8 = 0, t9 = 0, t10 = 0, t11 = 0, t12 = 0, t13 = 0, t14 = 0, t15 = 0,
81336 t16 = 0, t17 = 0, t18 = 0, t19 = 0, t20 = 0, t21 = 0, t22 = 0, t23 = 0,
81337 t24 = 0, t25 = 0, t26 = 0, t27 = 0, t28 = 0, t29 = 0, t30 = 0,
81338 b0 = b[0],
81339 b1 = b[1],
81340 b2 = b[2],
81341 b3 = b[3],
81342 b4 = b[4],
81343 b5 = b[5],
81344 b6 = b[6],
81345 b7 = b[7],
81346 b8 = b[8],
81347 b9 = b[9],
81348 b10 = b[10],
81349 b11 = b[11],
81350 b12 = b[12],
81351 b13 = b[13],
81352 b14 = b[14],
81353 b15 = b[15];
81354
81355 v = a[0];
81356 t0 += v * b0;
81357 t1 += v * b1;
81358 t2 += v * b2;
81359 t3 += v * b3;
81360 t4 += v * b4;
81361 t5 += v * b5;
81362 t6 += v * b6;
81363 t7 += v * b7;
81364 t8 += v * b8;
81365 t9 += v * b9;
81366 t10 += v * b10;
81367 t11 += v * b11;
81368 t12 += v * b12;
81369 t13 += v * b13;
81370 t14 += v * b14;
81371 t15 += v * b15;
81372 v = a[1];
81373 t1 += v * b0;
81374 t2 += v * b1;
81375 t3 += v * b2;
81376 t4 += v * b3;
81377 t5 += v * b4;
81378 t6 += v * b5;
81379 t7 += v * b6;
81380 t8 += v * b7;
81381 t9 += v * b8;
81382 t10 += v * b9;
81383 t11 += v * b10;
81384 t12 += v * b11;
81385 t13 += v * b12;
81386 t14 += v * b13;
81387 t15 += v * b14;
81388 t16 += v * b15;
81389 v = a[2];
81390 t2 += v * b0;
81391 t3 += v * b1;
81392 t4 += v * b2;
81393 t5 += v * b3;
81394 t6 += v * b4;
81395 t7 += v * b5;
81396 t8 += v * b6;
81397 t9 += v * b7;
81398 t10 += v * b8;
81399 t11 += v * b9;
81400 t12 += v * b10;
81401 t13 += v * b11;
81402 t14 += v * b12;
81403 t15 += v * b13;
81404 t16 += v * b14;
81405 t17 += v * b15;
81406 v = a[3];
81407 t3 += v * b0;
81408 t4 += v * b1;
81409 t5 += v * b2;
81410 t6 += v * b3;
81411 t7 += v * b4;
81412 t8 += v * b5;
81413 t9 += v * b6;
81414 t10 += v * b7;
81415 t11 += v * b8;
81416 t12 += v * b9;
81417 t13 += v * b10;
81418 t14 += v * b11;
81419 t15 += v * b12;
81420 t16 += v * b13;
81421 t17 += v * b14;
81422 t18 += v * b15;
81423 v = a[4];
81424 t4 += v * b0;
81425 t5 += v * b1;
81426 t6 += v * b2;
81427 t7 += v * b3;
81428 t8 += v * b4;
81429 t9 += v * b5;
81430 t10 += v * b6;
81431 t11 += v * b7;
81432 t12 += v * b8;
81433 t13 += v * b9;
81434 t14 += v * b10;
81435 t15 += v * b11;
81436 t16 += v * b12;
81437 t17 += v * b13;
81438 t18 += v * b14;
81439 t19 += v * b15;
81440 v = a[5];
81441 t5 += v * b0;
81442 t6 += v * b1;
81443 t7 += v * b2;
81444 t8 += v * b3;
81445 t9 += v * b4;
81446 t10 += v * b5;
81447 t11 += v * b6;
81448 t12 += v * b7;
81449 t13 += v * b8;
81450 t14 += v * b9;
81451 t15 += v * b10;
81452 t16 += v * b11;
81453 t17 += v * b12;
81454 t18 += v * b13;
81455 t19 += v * b14;
81456 t20 += v * b15;
81457 v = a[6];
81458 t6 += v * b0;
81459 t7 += v * b1;
81460 t8 += v * b2;
81461 t9 += v * b3;
81462 t10 += v * b4;
81463 t11 += v * b5;
81464 t12 += v * b6;
81465 t13 += v * b7;
81466 t14 += v * b8;
81467 t15 += v * b9;
81468 t16 += v * b10;
81469 t17 += v * b11;
81470 t18 += v * b12;
81471 t19 += v * b13;
81472 t20 += v * b14;
81473 t21 += v * b15;
81474 v = a[7];
81475 t7 += v * b0;
81476 t8 += v * b1;
81477 t9 += v * b2;
81478 t10 += v * b3;
81479 t11 += v * b4;
81480 t12 += v * b5;
81481 t13 += v * b6;
81482 t14 += v * b7;
81483 t15 += v * b8;
81484 t16 += v * b9;
81485 t17 += v * b10;
81486 t18 += v * b11;
81487 t19 += v * b12;
81488 t20 += v * b13;
81489 t21 += v * b14;
81490 t22 += v * b15;
81491 v = a[8];
81492 t8 += v * b0;
81493 t9 += v * b1;
81494 t10 += v * b2;
81495 t11 += v * b3;
81496 t12 += v * b4;
81497 t13 += v * b5;
81498 t14 += v * b6;
81499 t15 += v * b7;
81500 t16 += v * b8;
81501 t17 += v * b9;
81502 t18 += v * b10;
81503 t19 += v * b11;
81504 t20 += v * b12;
81505 t21 += v * b13;
81506 t22 += v * b14;
81507 t23 += v * b15;
81508 v = a[9];
81509 t9 += v * b0;
81510 t10 += v * b1;
81511 t11 += v * b2;
81512 t12 += v * b3;
81513 t13 += v * b4;
81514 t14 += v * b5;
81515 t15 += v * b6;
81516 t16 += v * b7;
81517 t17 += v * b8;
81518 t18 += v * b9;
81519 t19 += v * b10;
81520 t20 += v * b11;
81521 t21 += v * b12;
81522 t22 += v * b13;
81523 t23 += v * b14;
81524 t24 += v * b15;
81525 v = a[10];
81526 t10 += v * b0;
81527 t11 += v * b1;
81528 t12 += v * b2;
81529 t13 += v * b3;
81530 t14 += v * b4;
81531 t15 += v * b5;
81532 t16 += v * b6;
81533 t17 += v * b7;
81534 t18 += v * b8;
81535 t19 += v * b9;
81536 t20 += v * b10;
81537 t21 += v * b11;
81538 t22 += v * b12;
81539 t23 += v * b13;
81540 t24 += v * b14;
81541 t25 += v * b15;
81542 v = a[11];
81543 t11 += v * b0;
81544 t12 += v * b1;
81545 t13 += v * b2;
81546 t14 += v * b3;
81547 t15 += v * b4;
81548 t16 += v * b5;
81549 t17 += v * b6;
81550 t18 += v * b7;
81551 t19 += v * b8;
81552 t20 += v * b9;
81553 t21 += v * b10;
81554 t22 += v * b11;
81555 t23 += v * b12;
81556 t24 += v * b13;
81557 t25 += v * b14;
81558 t26 += v * b15;
81559 v = a[12];
81560 t12 += v * b0;
81561 t13 += v * b1;
81562 t14 += v * b2;
81563 t15 += v * b3;
81564 t16 += v * b4;
81565 t17 += v * b5;
81566 t18 += v * b6;
81567 t19 += v * b7;
81568 t20 += v * b8;
81569 t21 += v * b9;
81570 t22 += v * b10;
81571 t23 += v * b11;
81572 t24 += v * b12;
81573 t25 += v * b13;
81574 t26 += v * b14;
81575 t27 += v * b15;
81576 v = a[13];
81577 t13 += v * b0;
81578 t14 += v * b1;
81579 t15 += v * b2;
81580 t16 += v * b3;
81581 t17 += v * b4;
81582 t18 += v * b5;
81583 t19 += v * b6;
81584 t20 += v * b7;
81585 t21 += v * b8;
81586 t22 += v * b9;
81587 t23 += v * b10;
81588 t24 += v * b11;
81589 t25 += v * b12;
81590 t26 += v * b13;
81591 t27 += v * b14;
81592 t28 += v * b15;
81593 v = a[14];
81594 t14 += v * b0;
81595 t15 += v * b1;
81596 t16 += v * b2;
81597 t17 += v * b3;
81598 t18 += v * b4;
81599 t19 += v * b5;
81600 t20 += v * b6;
81601 t21 += v * b7;
81602 t22 += v * b8;
81603 t23 += v * b9;
81604 t24 += v * b10;
81605 t25 += v * b11;
81606 t26 += v * b12;
81607 t27 += v * b13;
81608 t28 += v * b14;
81609 t29 += v * b15;
81610 v = a[15];
81611 t15 += v * b0;
81612 t16 += v * b1;
81613 t17 += v * b2;
81614 t18 += v * b3;
81615 t19 += v * b4;
81616 t20 += v * b5;
81617 t21 += v * b6;
81618 t22 += v * b7;
81619 t23 += v * b8;
81620 t24 += v * b9;
81621 t25 += v * b10;
81622 t26 += v * b11;
81623 t27 += v * b12;
81624 t28 += v * b13;
81625 t29 += v * b14;
81626 t30 += v * b15;
81627
81628 t0 += 38 * t16;
81629 t1 += 38 * t17;
81630 t2 += 38 * t18;
81631 t3 += 38 * t19;
81632 t4 += 38 * t20;
81633 t5 += 38 * t21;
81634 t6 += 38 * t22;
81635 t7 += 38 * t23;
81636 t8 += 38 * t24;
81637 t9 += 38 * t25;
81638 t10 += 38 * t26;
81639 t11 += 38 * t27;
81640 t12 += 38 * t28;
81641 t13 += 38 * t29;
81642 t14 += 38 * t30;
81643 // t15 left as is
81644
81645 // first car
81646 c = 1;
81647 v = t0 + c + 65535; c = Math.floor(v / 65536); t0 = v - c * 65536;
81648 v = t1 + c + 65535; c = Math.floor(v / 65536); t1 = v - c * 65536;
81649 v = t2 + c + 65535; c = Math.floor(v / 65536); t2 = v - c * 65536;
81650 v = t3 + c + 65535; c = Math.floor(v / 65536); t3 = v - c * 65536;
81651 v = t4 + c + 65535; c = Math.floor(v / 65536); t4 = v - c * 65536;
81652 v = t5 + c + 65535; c = Math.floor(v / 65536); t5 = v - c * 65536;
81653 v = t6 + c + 65535; c = Math.floor(v / 65536); t6 = v - c * 65536;
81654 v = t7 + c + 65535; c = Math.floor(v / 65536); t7 = v - c * 65536;
81655 v = t8 + c + 65535; c = Math.floor(v / 65536); t8 = v - c * 65536;
81656 v = t9 + c + 65535; c = Math.floor(v / 65536); t9 = v - c * 65536;
81657 v = t10 + c + 65535; c = Math.floor(v / 65536); t10 = v - c * 65536;
81658 v = t11 + c + 65535; c = Math.floor(v / 65536); t11 = v - c * 65536;
81659 v = t12 + c + 65535; c = Math.floor(v / 65536); t12 = v - c * 65536;
81660 v = t13 + c + 65535; c = Math.floor(v / 65536); t13 = v - c * 65536;
81661 v = t14 + c + 65535; c = Math.floor(v / 65536); t14 = v - c * 65536;
81662 v = t15 + c + 65535; c = Math.floor(v / 65536); t15 = v - c * 65536;
81663 t0 += c-1 + 37 * (c-1);
81664
81665 // second car
81666 c = 1;
81667 v = t0 + c + 65535; c = Math.floor(v / 65536); t0 = v - c * 65536;
81668 v = t1 + c + 65535; c = Math.floor(v / 65536); t1 = v - c * 65536;
81669 v = t2 + c + 65535; c = Math.floor(v / 65536); t2 = v - c * 65536;
81670 v = t3 + c + 65535; c = Math.floor(v / 65536); t3 = v - c * 65536;
81671 v = t4 + c + 65535; c = Math.floor(v / 65536); t4 = v - c * 65536;
81672 v = t5 + c + 65535; c = Math.floor(v / 65536); t5 = v - c * 65536;
81673 v = t6 + c + 65535; c = Math.floor(v / 65536); t6 = v - c * 65536;
81674 v = t7 + c + 65535; c = Math.floor(v / 65536); t7 = v - c * 65536;
81675 v = t8 + c + 65535; c = Math.floor(v / 65536); t8 = v - c * 65536;
81676 v = t9 + c + 65535; c = Math.floor(v / 65536); t9 = v - c * 65536;
81677 v = t10 + c + 65535; c = Math.floor(v / 65536); t10 = v - c * 65536;
81678 v = t11 + c + 65535; c = Math.floor(v / 65536); t11 = v - c * 65536;
81679 v = t12 + c + 65535; c = Math.floor(v / 65536); t12 = v - c * 65536;
81680 v = t13 + c + 65535; c = Math.floor(v / 65536); t13 = v - c * 65536;
81681 v = t14 + c + 65535; c = Math.floor(v / 65536); t14 = v - c * 65536;
81682 v = t15 + c + 65535; c = Math.floor(v / 65536); t15 = v - c * 65536;
81683 t0 += c-1 + 37 * (c-1);
81684
81685 o[ 0] = t0;
81686 o[ 1] = t1;
81687 o[ 2] = t2;
81688 o[ 3] = t3;
81689 o[ 4] = t4;
81690 o[ 5] = t5;
81691 o[ 6] = t6;
81692 o[ 7] = t7;
81693 o[ 8] = t8;
81694 o[ 9] = t9;
81695 o[10] = t10;
81696 o[11] = t11;
81697 o[12] = t12;
81698 o[13] = t13;
81699 o[14] = t14;
81700 o[15] = t15;
81701}
81702
81703function S(o, a) {
81704 M(o, a, a);
81705}
81706
81707function inv25519(o, i) {
81708 var c = gf();
81709 var a;
81710 for (a = 0; a < 16; a++) c[a] = i[a];
81711 for (a = 253; a >= 0; a--) {
81712 S(c, c);
81713 if(a !== 2 && a !== 4) M(c, c, i);
81714 }
81715 for (a = 0; a < 16; a++) o[a] = c[a];
81716}
81717
81718function pow2523(o, i) {
81719 var c = gf();
81720 var a;
81721 for (a = 0; a < 16; a++) c[a] = i[a];
81722 for (a = 250; a >= 0; a--) {
81723 S(c, c);
81724 if(a !== 1) M(c, c, i);
81725 }
81726 for (a = 0; a < 16; a++) o[a] = c[a];
81727}
81728
81729function crypto_scalarmult(q, n, p) {
81730 var z = new Uint8Array(32);
81731 var x = new Float64Array(80), r, i;
81732 var a = gf(), b = gf(), c = gf(),
81733 d = gf(), e = gf(), f = gf();
81734 for (i = 0; i < 31; i++) z[i] = n[i];
81735 z[31]=(n[31]&127)|64;
81736 z[0]&=248;
81737 unpack25519(x,p);
81738 for (i = 0; i < 16; i++) {
81739 b[i]=x[i];
81740 d[i]=a[i]=c[i]=0;
81741 }
81742 a[0]=d[0]=1;
81743 for (i=254; i>=0; --i) {
81744 r=(z[i>>>3]>>>(i&7))&1;
81745 sel25519(a,b,r);
81746 sel25519(c,d,r);
81747 A(e,a,c);
81748 Z(a,a,c);
81749 A(c,b,d);
81750 Z(b,b,d);
81751 S(d,e);
81752 S(f,a);
81753 M(a,c,a);
81754 M(c,b,e);
81755 A(e,a,c);
81756 Z(a,a,c);
81757 S(b,a);
81758 Z(c,d,f);
81759 M(a,c,_121665);
81760 A(a,a,d);
81761 M(c,c,a);
81762 M(a,d,f);
81763 M(d,b,x);
81764 S(b,e);
81765 sel25519(a,b,r);
81766 sel25519(c,d,r);
81767 }
81768 for (i = 0; i < 16; i++) {
81769 x[i+16]=a[i];
81770 x[i+32]=c[i];
81771 x[i+48]=b[i];
81772 x[i+64]=d[i];
81773 }
81774 var x32 = x.subarray(32);
81775 var x16 = x.subarray(16);
81776 inv25519(x32,x32);
81777 M(x16,x16,x32);
81778 pack25519(q,x16);
81779 return 0;
81780}
81781
81782function crypto_scalarmult_base(q, n) {
81783 return crypto_scalarmult(q, n, _9);
81784}
81785
81786function crypto_box_keypair(y, x) {
81787 randombytes(x, 32);
81788 return crypto_scalarmult_base(y, x);
81789}
81790
81791function crypto_box_beforenm(k, y, x) {
81792 var s = new Uint8Array(32);
81793 crypto_scalarmult(s, x, y);
81794 return crypto_core_hsalsa20(k, _0, s, sigma);
81795}
81796
81797var crypto_box_afternm = crypto_secretbox;
81798var crypto_box_open_afternm = crypto_secretbox_open;
81799
81800function crypto_box(c, m, d, n, y, x) {
81801 var k = new Uint8Array(32);
81802 crypto_box_beforenm(k, y, x);
81803 return crypto_box_afternm(c, m, d, n, k);
81804}
81805
81806function crypto_box_open(m, c, d, n, y, x) {
81807 var k = new Uint8Array(32);
81808 crypto_box_beforenm(k, y, x);
81809 return crypto_box_open_afternm(m, c, d, n, k);
81810}
81811
81812var K = [
81813 0x428a2f98, 0xd728ae22, 0x71374491, 0x23ef65cd,
81814 0xb5c0fbcf, 0xec4d3b2f, 0xe9b5dba5, 0x8189dbbc,
81815 0x3956c25b, 0xf348b538, 0x59f111f1, 0xb605d019,
81816 0x923f82a4, 0xaf194f9b, 0xab1c5ed5, 0xda6d8118,
81817 0xd807aa98, 0xa3030242, 0x12835b01, 0x45706fbe,
81818 0x243185be, 0x4ee4b28c, 0x550c7dc3, 0xd5ffb4e2,
81819 0x72be5d74, 0xf27b896f, 0x80deb1fe, 0x3b1696b1,
81820 0x9bdc06a7, 0x25c71235, 0xc19bf174, 0xcf692694,
81821 0xe49b69c1, 0x9ef14ad2, 0xefbe4786, 0x384f25e3,
81822 0x0fc19dc6, 0x8b8cd5b5, 0x240ca1cc, 0x77ac9c65,
81823 0x2de92c6f, 0x592b0275, 0x4a7484aa, 0x6ea6e483,
81824 0x5cb0a9dc, 0xbd41fbd4, 0x76f988da, 0x831153b5,
81825 0x983e5152, 0xee66dfab, 0xa831c66d, 0x2db43210,
81826 0xb00327c8, 0x98fb213f, 0xbf597fc7, 0xbeef0ee4,
81827 0xc6e00bf3, 0x3da88fc2, 0xd5a79147, 0x930aa725,
81828 0x06ca6351, 0xe003826f, 0x14292967, 0x0a0e6e70,
81829 0x27b70a85, 0x46d22ffc, 0x2e1b2138, 0x5c26c926,
81830 0x4d2c6dfc, 0x5ac42aed, 0x53380d13, 0x9d95b3df,
81831 0x650a7354, 0x8baf63de, 0x766a0abb, 0x3c77b2a8,
81832 0x81c2c92e, 0x47edaee6, 0x92722c85, 0x1482353b,
81833 0xa2bfe8a1, 0x4cf10364, 0xa81a664b, 0xbc423001,
81834 0xc24b8b70, 0xd0f89791, 0xc76c51a3, 0x0654be30,
81835 0xd192e819, 0xd6ef5218, 0xd6990624, 0x5565a910,
81836 0xf40e3585, 0x5771202a, 0x106aa070, 0x32bbd1b8,
81837 0x19a4c116, 0xb8d2d0c8, 0x1e376c08, 0x5141ab53,
81838 0x2748774c, 0xdf8eeb99, 0x34b0bcb5, 0xe19b48a8,
81839 0x391c0cb3, 0xc5c95a63, 0x4ed8aa4a, 0xe3418acb,
81840 0x5b9cca4f, 0x7763e373, 0x682e6ff3, 0xd6b2b8a3,
81841 0x748f82ee, 0x5defb2fc, 0x78a5636f, 0x43172f60,
81842 0x84c87814, 0xa1f0ab72, 0x8cc70208, 0x1a6439ec,
81843 0x90befffa, 0x23631e28, 0xa4506ceb, 0xde82bde9,
81844 0xbef9a3f7, 0xb2c67915, 0xc67178f2, 0xe372532b,
81845 0xca273ece, 0xea26619c, 0xd186b8c7, 0x21c0c207,
81846 0xeada7dd6, 0xcde0eb1e, 0xf57d4f7f, 0xee6ed178,
81847 0x06f067aa, 0x72176fba, 0x0a637dc5, 0xa2c898a6,
81848 0x113f9804, 0xbef90dae, 0x1b710b35, 0x131c471b,
81849 0x28db77f5, 0x23047d84, 0x32caab7b, 0x40c72493,
81850 0x3c9ebe0a, 0x15c9bebc, 0x431d67c4, 0x9c100d4c,
81851 0x4cc5d4be, 0xcb3e42b6, 0x597f299c, 0xfc657e2a,
81852 0x5fcb6fab, 0x3ad6faec, 0x6c44198c, 0x4a475817
81853];
81854
81855function crypto_hashblocks_hl(hh, hl, m, n) {
81856 var wh = new Int32Array(16), wl = new Int32Array(16),
81857 bh0, bh1, bh2, bh3, bh4, bh5, bh6, bh7,
81858 bl0, bl1, bl2, bl3, bl4, bl5, bl6, bl7,
81859 th, tl, i, j, h, l, a, b, c, d;
81860
81861 var ah0 = hh[0],
81862 ah1 = hh[1],
81863 ah2 = hh[2],
81864 ah3 = hh[3],
81865 ah4 = hh[4],
81866 ah5 = hh[5],
81867 ah6 = hh[6],
81868 ah7 = hh[7],
81869
81870 al0 = hl[0],
81871 al1 = hl[1],
81872 al2 = hl[2],
81873 al3 = hl[3],
81874 al4 = hl[4],
81875 al5 = hl[5],
81876 al6 = hl[6],
81877 al7 = hl[7];
81878
81879 var pos = 0;
81880 while (n >= 128) {
81881 for (i = 0; i < 16; i++) {
81882 j = 8 * i + pos;
81883 wh[i] = (m[j+0] << 24) | (m[j+1] << 16) | (m[j+2] << 8) | m[j+3];
81884 wl[i] = (m[j+4] << 24) | (m[j+5] << 16) | (m[j+6] << 8) | m[j+7];
81885 }
81886 for (i = 0; i < 80; i++) {
81887 bh0 = ah0;
81888 bh1 = ah1;
81889 bh2 = ah2;
81890 bh3 = ah3;
81891 bh4 = ah4;
81892 bh5 = ah5;
81893 bh6 = ah6;
81894 bh7 = ah7;
81895
81896 bl0 = al0;
81897 bl1 = al1;
81898 bl2 = al2;
81899 bl3 = al3;
81900 bl4 = al4;
81901 bl5 = al5;
81902 bl6 = al6;
81903 bl7 = al7;
81904
81905 // add
81906 h = ah7;
81907 l = al7;
81908
81909 a = l & 0xffff; b = l >>> 16;
81910 c = h & 0xffff; d = h >>> 16;
81911
81912 // Sigma1
81913 h = ((ah4 >>> 14) | (al4 << (32-14))) ^ ((ah4 >>> 18) | (al4 << (32-18))) ^ ((al4 >>> (41-32)) | (ah4 << (32-(41-32))));
81914 l = ((al4 >>> 14) | (ah4 << (32-14))) ^ ((al4 >>> 18) | (ah4 << (32-18))) ^ ((ah4 >>> (41-32)) | (al4 << (32-(41-32))));
81915
81916 a += l & 0xffff; b += l >>> 16;
81917 c += h & 0xffff; d += h >>> 16;
81918
81919 // Ch
81920 h = (ah4 & ah5) ^ (~ah4 & ah6);
81921 l = (al4 & al5) ^ (~al4 & al6);
81922
81923 a += l & 0xffff; b += l >>> 16;
81924 c += h & 0xffff; d += h >>> 16;
81925
81926 // K
81927 h = K[i*2];
81928 l = K[i*2+1];
81929
81930 a += l & 0xffff; b += l >>> 16;
81931 c += h & 0xffff; d += h >>> 16;
81932
81933 // w
81934 h = wh[i%16];
81935 l = wl[i%16];
81936
81937 a += l & 0xffff; b += l >>> 16;
81938 c += h & 0xffff; d += h >>> 16;
81939
81940 b += a >>> 16;
81941 c += b >>> 16;
81942 d += c >>> 16;
81943
81944 th = c & 0xffff | d << 16;
81945 tl = a & 0xffff | b << 16;
81946
81947 // add
81948 h = th;
81949 l = tl;
81950
81951 a = l & 0xffff; b = l >>> 16;
81952 c = h & 0xffff; d = h >>> 16;
81953
81954 // Sigma0
81955 h = ((ah0 >>> 28) | (al0 << (32-28))) ^ ((al0 >>> (34-32)) | (ah0 << (32-(34-32)))) ^ ((al0 >>> (39-32)) | (ah0 << (32-(39-32))));
81956 l = ((al0 >>> 28) | (ah0 << (32-28))) ^ ((ah0 >>> (34-32)) | (al0 << (32-(34-32)))) ^ ((ah0 >>> (39-32)) | (al0 << (32-(39-32))));
81957
81958 a += l & 0xffff; b += l >>> 16;
81959 c += h & 0xffff; d += h >>> 16;
81960
81961 // Maj
81962 h = (ah0 & ah1) ^ (ah0 & ah2) ^ (ah1 & ah2);
81963 l = (al0 & al1) ^ (al0 & al2) ^ (al1 & al2);
81964
81965 a += l & 0xffff; b += l >>> 16;
81966 c += h & 0xffff; d += h >>> 16;
81967
81968 b += a >>> 16;
81969 c += b >>> 16;
81970 d += c >>> 16;
81971
81972 bh7 = (c & 0xffff) | (d << 16);
81973 bl7 = (a & 0xffff) | (b << 16);
81974
81975 // add
81976 h = bh3;
81977 l = bl3;
81978
81979 a = l & 0xffff; b = l >>> 16;
81980 c = h & 0xffff; d = h >>> 16;
81981
81982 h = th;
81983 l = tl;
81984
81985 a += l & 0xffff; b += l >>> 16;
81986 c += h & 0xffff; d += h >>> 16;
81987
81988 b += a >>> 16;
81989 c += b >>> 16;
81990 d += c >>> 16;
81991
81992 bh3 = (c & 0xffff) | (d << 16);
81993 bl3 = (a & 0xffff) | (b << 16);
81994
81995 ah1 = bh0;
81996 ah2 = bh1;
81997 ah3 = bh2;
81998 ah4 = bh3;
81999 ah5 = bh4;
82000 ah6 = bh5;
82001 ah7 = bh6;
82002 ah0 = bh7;
82003
82004 al1 = bl0;
82005 al2 = bl1;
82006 al3 = bl2;
82007 al4 = bl3;
82008 al5 = bl4;
82009 al6 = bl5;
82010 al7 = bl6;
82011 al0 = bl7;
82012
82013 if (i%16 === 15) {
82014 for (j = 0; j < 16; j++) {
82015 // add
82016 h = wh[j];
82017 l = wl[j];
82018
82019 a = l & 0xffff; b = l >>> 16;
82020 c = h & 0xffff; d = h >>> 16;
82021
82022 h = wh[(j+9)%16];
82023 l = wl[(j+9)%16];
82024
82025 a += l & 0xffff; b += l >>> 16;
82026 c += h & 0xffff; d += h >>> 16;
82027
82028 // sigma0
82029 th = wh[(j+1)%16];
82030 tl = wl[(j+1)%16];
82031 h = ((th >>> 1) | (tl << (32-1))) ^ ((th >>> 8) | (tl << (32-8))) ^ (th >>> 7);
82032 l = ((tl >>> 1) | (th << (32-1))) ^ ((tl >>> 8) | (th << (32-8))) ^ ((tl >>> 7) | (th << (32-7)));
82033
82034 a += l & 0xffff; b += l >>> 16;
82035 c += h & 0xffff; d += h >>> 16;
82036
82037 // sigma1
82038 th = wh[(j+14)%16];
82039 tl = wl[(j+14)%16];
82040 h = ((th >>> 19) | (tl << (32-19))) ^ ((tl >>> (61-32)) | (th << (32-(61-32)))) ^ (th >>> 6);
82041 l = ((tl >>> 19) | (th << (32-19))) ^ ((th >>> (61-32)) | (tl << (32-(61-32)))) ^ ((tl >>> 6) | (th << (32-6)));
82042
82043 a += l & 0xffff; b += l >>> 16;
82044 c += h & 0xffff; d += h >>> 16;
82045
82046 b += a >>> 16;
82047 c += b >>> 16;
82048 d += c >>> 16;
82049
82050 wh[j] = (c & 0xffff) | (d << 16);
82051 wl[j] = (a & 0xffff) | (b << 16);
82052 }
82053 }
82054 }
82055
82056 // add
82057 h = ah0;
82058 l = al0;
82059
82060 a = l & 0xffff; b = l >>> 16;
82061 c = h & 0xffff; d = h >>> 16;
82062
82063 h = hh[0];
82064 l = hl[0];
82065
82066 a += l & 0xffff; b += l >>> 16;
82067 c += h & 0xffff; d += h >>> 16;
82068
82069 b += a >>> 16;
82070 c += b >>> 16;
82071 d += c >>> 16;
82072
82073 hh[0] = ah0 = (c & 0xffff) | (d << 16);
82074 hl[0] = al0 = (a & 0xffff) | (b << 16);
82075
82076 h = ah1;
82077 l = al1;
82078
82079 a = l & 0xffff; b = l >>> 16;
82080 c = h & 0xffff; d = h >>> 16;
82081
82082 h = hh[1];
82083 l = hl[1];
82084
82085 a += l & 0xffff; b += l >>> 16;
82086 c += h & 0xffff; d += h >>> 16;
82087
82088 b += a >>> 16;
82089 c += b >>> 16;
82090 d += c >>> 16;
82091
82092 hh[1] = ah1 = (c & 0xffff) | (d << 16);
82093 hl[1] = al1 = (a & 0xffff) | (b << 16);
82094
82095 h = ah2;
82096 l = al2;
82097
82098 a = l & 0xffff; b = l >>> 16;
82099 c = h & 0xffff; d = h >>> 16;
82100
82101 h = hh[2];
82102 l = hl[2];
82103
82104 a += l & 0xffff; b += l >>> 16;
82105 c += h & 0xffff; d += h >>> 16;
82106
82107 b += a >>> 16;
82108 c += b >>> 16;
82109 d += c >>> 16;
82110
82111 hh[2] = ah2 = (c & 0xffff) | (d << 16);
82112 hl[2] = al2 = (a & 0xffff) | (b << 16);
82113
82114 h = ah3;
82115 l = al3;
82116
82117 a = l & 0xffff; b = l >>> 16;
82118 c = h & 0xffff; d = h >>> 16;
82119
82120 h = hh[3];
82121 l = hl[3];
82122
82123 a += l & 0xffff; b += l >>> 16;
82124 c += h & 0xffff; d += h >>> 16;
82125
82126 b += a >>> 16;
82127 c += b >>> 16;
82128 d += c >>> 16;
82129
82130 hh[3] = ah3 = (c & 0xffff) | (d << 16);
82131 hl[3] = al3 = (a & 0xffff) | (b << 16);
82132
82133 h = ah4;
82134 l = al4;
82135
82136 a = l & 0xffff; b = l >>> 16;
82137 c = h & 0xffff; d = h >>> 16;
82138
82139 h = hh[4];
82140 l = hl[4];
82141
82142 a += l & 0xffff; b += l >>> 16;
82143 c += h & 0xffff; d += h >>> 16;
82144
82145 b += a >>> 16;
82146 c += b >>> 16;
82147 d += c >>> 16;
82148
82149 hh[4] = ah4 = (c & 0xffff) | (d << 16);
82150 hl[4] = al4 = (a & 0xffff) | (b << 16);
82151
82152 h = ah5;
82153 l = al5;
82154
82155 a = l & 0xffff; b = l >>> 16;
82156 c = h & 0xffff; d = h >>> 16;
82157
82158 h = hh[5];
82159 l = hl[5];
82160
82161 a += l & 0xffff; b += l >>> 16;
82162 c += h & 0xffff; d += h >>> 16;
82163
82164 b += a >>> 16;
82165 c += b >>> 16;
82166 d += c >>> 16;
82167
82168 hh[5] = ah5 = (c & 0xffff) | (d << 16);
82169 hl[5] = al5 = (a & 0xffff) | (b << 16);
82170
82171 h = ah6;
82172 l = al6;
82173
82174 a = l & 0xffff; b = l >>> 16;
82175 c = h & 0xffff; d = h >>> 16;
82176
82177 h = hh[6];
82178 l = hl[6];
82179
82180 a += l & 0xffff; b += l >>> 16;
82181 c += h & 0xffff; d += h >>> 16;
82182
82183 b += a >>> 16;
82184 c += b >>> 16;
82185 d += c >>> 16;
82186
82187 hh[6] = ah6 = (c & 0xffff) | (d << 16);
82188 hl[6] = al6 = (a & 0xffff) | (b << 16);
82189
82190 h = ah7;
82191 l = al7;
82192
82193 a = l & 0xffff; b = l >>> 16;
82194 c = h & 0xffff; d = h >>> 16;
82195
82196 h = hh[7];
82197 l = hl[7];
82198
82199 a += l & 0xffff; b += l >>> 16;
82200 c += h & 0xffff; d += h >>> 16;
82201
82202 b += a >>> 16;
82203 c += b >>> 16;
82204 d += c >>> 16;
82205
82206 hh[7] = ah7 = (c & 0xffff) | (d << 16);
82207 hl[7] = al7 = (a & 0xffff) | (b << 16);
82208
82209 pos += 128;
82210 n -= 128;
82211 }
82212
82213 return n;
82214}
82215
82216function crypto_hash(out, m, n) {
82217 var hh = new Int32Array(8),
82218 hl = new Int32Array(8),
82219 x = new Uint8Array(256),
82220 i, b = n;
82221
82222 hh[0] = 0x6a09e667;
82223 hh[1] = 0xbb67ae85;
82224 hh[2] = 0x3c6ef372;
82225 hh[3] = 0xa54ff53a;
82226 hh[4] = 0x510e527f;
82227 hh[5] = 0x9b05688c;
82228 hh[6] = 0x1f83d9ab;
82229 hh[7] = 0x5be0cd19;
82230
82231 hl[0] = 0xf3bcc908;
82232 hl[1] = 0x84caa73b;
82233 hl[2] = 0xfe94f82b;
82234 hl[3] = 0x5f1d36f1;
82235 hl[4] = 0xade682d1;
82236 hl[5] = 0x2b3e6c1f;
82237 hl[6] = 0xfb41bd6b;
82238 hl[7] = 0x137e2179;
82239
82240 crypto_hashblocks_hl(hh, hl, m, n);
82241 n %= 128;
82242
82243 for (i = 0; i < n; i++) x[i] = m[b-n+i];
82244 x[n] = 128;
82245
82246 n = 256-128*(n<112?1:0);
82247 x[n-9] = 0;
82248 ts64(x, n-8, (b / 0x20000000) | 0, b << 3);
82249 crypto_hashblocks_hl(hh, hl, x, n);
82250
82251 for (i = 0; i < 8; i++) ts64(out, 8*i, hh[i], hl[i]);
82252
82253 return 0;
82254}
82255
82256function add(p, q) {
82257 var a = gf(), b = gf(), c = gf(),
82258 d = gf(), e = gf(), f = gf(),
82259 g = gf(), h = gf(), t = gf();
82260
82261 Z(a, p[1], p[0]);
82262 Z(t, q[1], q[0]);
82263 M(a, a, t);
82264 A(b, p[0], p[1]);
82265 A(t, q[0], q[1]);
82266 M(b, b, t);
82267 M(c, p[3], q[3]);
82268 M(c, c, D2);
82269 M(d, p[2], q[2]);
82270 A(d, d, d);
82271 Z(e, b, a);
82272 Z(f, d, c);
82273 A(g, d, c);
82274 A(h, b, a);
82275
82276 M(p[0], e, f);
82277 M(p[1], h, g);
82278 M(p[2], g, f);
82279 M(p[3], e, h);
82280}
82281
82282function cswap(p, q, b) {
82283 var i;
82284 for (i = 0; i < 4; i++) {
82285 sel25519(p[i], q[i], b);
82286 }
82287}
82288
82289function pack(r, p) {
82290 var tx = gf(), ty = gf(), zi = gf();
82291 inv25519(zi, p[2]);
82292 M(tx, p[0], zi);
82293 M(ty, p[1], zi);
82294 pack25519(r, ty);
82295 r[31] ^= par25519(tx) << 7;
82296}
82297
82298function scalarmult(p, q, s) {
82299 var b, i;
82300 set25519(p[0], gf0);
82301 set25519(p[1], gf1);
82302 set25519(p[2], gf1);
82303 set25519(p[3], gf0);
82304 for (i = 255; i >= 0; --i) {
82305 b = (s[(i/8)|0] >> (i&7)) & 1;
82306 cswap(p, q, b);
82307 add(q, p);
82308 add(p, p);
82309 cswap(p, q, b);
82310 }
82311}
82312
82313function scalarbase(p, s) {
82314 var q = [gf(), gf(), gf(), gf()];
82315 set25519(q[0], X);
82316 set25519(q[1], Y);
82317 set25519(q[2], gf1);
82318 M(q[3], X, Y);
82319 scalarmult(p, q, s);
82320}
82321
82322function crypto_sign_keypair(pk, sk, seeded) {
82323 var d = new Uint8Array(64);
82324 var p = [gf(), gf(), gf(), gf()];
82325 var i;
82326
82327 if (!seeded) randombytes(sk, 32);
82328 crypto_hash(d, sk, 32);
82329 d[0] &= 248;
82330 d[31] &= 127;
82331 d[31] |= 64;
82332
82333 scalarbase(p, d);
82334 pack(pk, p);
82335
82336 for (i = 0; i < 32; i++) sk[i+32] = pk[i];
82337 return 0;
82338}
82339
82340var L = new Float64Array([0xed, 0xd3, 0xf5, 0x5c, 0x1a, 0x63, 0x12, 0x58, 0xd6, 0x9c, 0xf7, 0xa2, 0xde, 0xf9, 0xde, 0x14, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x10]);
82341
82342function modL(r, x) {
82343 var carry, i, j, k;
82344 for (i = 63; i >= 32; --i) {
82345 carry = 0;
82346 for (j = i - 32, k = i - 12; j < k; ++j) {
82347 x[j] += carry - 16 * x[i] * L[j - (i - 32)];
82348 carry = (x[j] + 128) >> 8;
82349 x[j] -= carry * 256;
82350 }
82351 x[j] += carry;
82352 x[i] = 0;
82353 }
82354 carry = 0;
82355 for (j = 0; j < 32; j++) {
82356 x[j] += carry - (x[31] >> 4) * L[j];
82357 carry = x[j] >> 8;
82358 x[j] &= 255;
82359 }
82360 for (j = 0; j < 32; j++) x[j] -= carry * L[j];
82361 for (i = 0; i < 32; i++) {
82362 x[i+1] += x[i] >> 8;
82363 r[i] = x[i] & 255;
82364 }
82365}
82366
82367function reduce(r) {
82368 var x = new Float64Array(64), i;
82369 for (i = 0; i < 64; i++) x[i] = r[i];
82370 for (i = 0; i < 64; i++) r[i] = 0;
82371 modL(r, x);
82372}
82373
82374// Note: difference from C - smlen returned, not passed as argument.
82375function crypto_sign(sm, m, n, sk) {
82376 var d = new Uint8Array(64), h = new Uint8Array(64), r = new Uint8Array(64);
82377 var i, j, x = new Float64Array(64);
82378 var p = [gf(), gf(), gf(), gf()];
82379
82380 crypto_hash(d, sk, 32);
82381 d[0] &= 248;
82382 d[31] &= 127;
82383 d[31] |= 64;
82384
82385 var smlen = n + 64;
82386 for (i = 0; i < n; i++) sm[64 + i] = m[i];
82387 for (i = 0; i < 32; i++) sm[32 + i] = d[32 + i];
82388
82389 crypto_hash(r, sm.subarray(32), n+32);
82390 reduce(r);
82391 scalarbase(p, r);
82392 pack(sm, p);
82393
82394 for (i = 32; i < 64; i++) sm[i] = sk[i];
82395 crypto_hash(h, sm, n + 64);
82396 reduce(h);
82397
82398 for (i = 0; i < 64; i++) x[i] = 0;
82399 for (i = 0; i < 32; i++) x[i] = r[i];
82400 for (i = 0; i < 32; i++) {
82401 for (j = 0; j < 32; j++) {
82402 x[i+j] += h[i] * d[j];
82403 }
82404 }
82405
82406 modL(sm.subarray(32), x);
82407 return smlen;
82408}
82409
82410function unpackneg(r, p) {
82411 var t = gf(), chk = gf(), num = gf(),
82412 den = gf(), den2 = gf(), den4 = gf(),
82413 den6 = gf();
82414
82415 set25519(r[2], gf1);
82416 unpack25519(r[1], p);
82417 S(num, r[1]);
82418 M(den, num, D);
82419 Z(num, num, r[2]);
82420 A(den, r[2], den);
82421
82422 S(den2, den);
82423 S(den4, den2);
82424 M(den6, den4, den2);
82425 M(t, den6, num);
82426 M(t, t, den);
82427
82428 pow2523(t, t);
82429 M(t, t, num);
82430 M(t, t, den);
82431 M(t, t, den);
82432 M(r[0], t, den);
82433
82434 S(chk, r[0]);
82435 M(chk, chk, den);
82436 if (neq25519(chk, num)) M(r[0], r[0], I);
82437
82438 S(chk, r[0]);
82439 M(chk, chk, den);
82440 if (neq25519(chk, num)) return -1;
82441
82442 if (par25519(r[0]) === (p[31]>>7)) Z(r[0], gf0, r[0]);
82443
82444 M(r[3], r[0], r[1]);
82445 return 0;
82446}
82447
82448function crypto_sign_open(m, sm, n, pk) {
82449 var i, mlen;
82450 var t = new Uint8Array(32), h = new Uint8Array(64);
82451 var p = [gf(), gf(), gf(), gf()],
82452 q = [gf(), gf(), gf(), gf()];
82453
82454 mlen = -1;
82455 if (n < 64) return -1;
82456
82457 if (unpackneg(q, pk)) return -1;
82458
82459 for (i = 0; i < n; i++) m[i] = sm[i];
82460 for (i = 0; i < 32; i++) m[i+32] = pk[i];
82461 crypto_hash(h, m, n);
82462 reduce(h);
82463 scalarmult(p, q, h);
82464
82465 scalarbase(q, sm.subarray(32));
82466 add(p, q);
82467 pack(t, p);
82468
82469 n -= 64;
82470 if (crypto_verify_32(sm, 0, t, 0)) {
82471 for (i = 0; i < n; i++) m[i] = 0;
82472 return -1;
82473 }
82474
82475 for (i = 0; i < n; i++) m[i] = sm[i + 64];
82476 mlen = n;
82477 return mlen;
82478}
82479
82480var crypto_secretbox_KEYBYTES = 32,
82481 crypto_secretbox_NONCEBYTES = 24,
82482 crypto_secretbox_ZEROBYTES = 32,
82483 crypto_secretbox_BOXZEROBYTES = 16,
82484 crypto_scalarmult_BYTES = 32,
82485 crypto_scalarmult_SCALARBYTES = 32,
82486 crypto_box_PUBLICKEYBYTES = 32,
82487 crypto_box_SECRETKEYBYTES = 32,
82488 crypto_box_BEFORENMBYTES = 32,
82489 crypto_box_NONCEBYTES = crypto_secretbox_NONCEBYTES,
82490 crypto_box_ZEROBYTES = crypto_secretbox_ZEROBYTES,
82491 crypto_box_BOXZEROBYTES = crypto_secretbox_BOXZEROBYTES,
82492 crypto_sign_BYTES = 64,
82493 crypto_sign_PUBLICKEYBYTES = 32,
82494 crypto_sign_SECRETKEYBYTES = 64,
82495 crypto_sign_SEEDBYTES = 32,
82496 crypto_hash_BYTES = 64;
82497
82498nacl.lowlevel = {
82499 crypto_core_hsalsa20: crypto_core_hsalsa20,
82500 crypto_stream_xor: crypto_stream_xor,
82501 crypto_stream: crypto_stream,
82502 crypto_stream_salsa20_xor: crypto_stream_salsa20_xor,
82503 crypto_stream_salsa20: crypto_stream_salsa20,
82504 crypto_onetimeauth: crypto_onetimeauth,
82505 crypto_onetimeauth_verify: crypto_onetimeauth_verify,
82506 crypto_verify_16: crypto_verify_16,
82507 crypto_verify_32: crypto_verify_32,
82508 crypto_secretbox: crypto_secretbox,
82509 crypto_secretbox_open: crypto_secretbox_open,
82510 crypto_scalarmult: crypto_scalarmult,
82511 crypto_scalarmult_base: crypto_scalarmult_base,
82512 crypto_box_beforenm: crypto_box_beforenm,
82513 crypto_box_afternm: crypto_box_afternm,
82514 crypto_box: crypto_box,
82515 crypto_box_open: crypto_box_open,
82516 crypto_box_keypair: crypto_box_keypair,
82517 crypto_hash: crypto_hash,
82518 crypto_sign: crypto_sign,
82519 crypto_sign_keypair: crypto_sign_keypair,
82520 crypto_sign_open: crypto_sign_open,
82521
82522 crypto_secretbox_KEYBYTES: crypto_secretbox_KEYBYTES,
82523 crypto_secretbox_NONCEBYTES: crypto_secretbox_NONCEBYTES,
82524 crypto_secretbox_ZEROBYTES: crypto_secretbox_ZEROBYTES,
82525 crypto_secretbox_BOXZEROBYTES: crypto_secretbox_BOXZEROBYTES,
82526 crypto_scalarmult_BYTES: crypto_scalarmult_BYTES,
82527 crypto_scalarmult_SCALARBYTES: crypto_scalarmult_SCALARBYTES,
82528 crypto_box_PUBLICKEYBYTES: crypto_box_PUBLICKEYBYTES,
82529 crypto_box_SECRETKEYBYTES: crypto_box_SECRETKEYBYTES,
82530 crypto_box_BEFORENMBYTES: crypto_box_BEFORENMBYTES,
82531 crypto_box_NONCEBYTES: crypto_box_NONCEBYTES,
82532 crypto_box_ZEROBYTES: crypto_box_ZEROBYTES,
82533 crypto_box_BOXZEROBYTES: crypto_box_BOXZEROBYTES,
82534 crypto_sign_BYTES: crypto_sign_BYTES,
82535 crypto_sign_PUBLICKEYBYTES: crypto_sign_PUBLICKEYBYTES,
82536 crypto_sign_SECRETKEYBYTES: crypto_sign_SECRETKEYBYTES,
82537 crypto_sign_SEEDBYTES: crypto_sign_SEEDBYTES,
82538 crypto_hash_BYTES: crypto_hash_BYTES
82539};
82540
82541/* High-level API */
82542
82543function checkLengths(k, n) {
82544 if (k.length !== crypto_secretbox_KEYBYTES) throw new Error('bad key size');
82545 if (n.length !== crypto_secretbox_NONCEBYTES) throw new Error('bad nonce size');
82546}
82547
82548function checkBoxLengths(pk, sk) {
82549 if (pk.length !== crypto_box_PUBLICKEYBYTES) throw new Error('bad public key size');
82550 if (sk.length !== crypto_box_SECRETKEYBYTES) throw new Error('bad secret key size');
82551}
82552
82553function checkArrayTypes() {
82554 var t, i;
82555 for (i = 0; i < arguments.length; i++) {
82556 if ((t = Object.prototype.toString.call(arguments[i])) !== '[object Uint8Array]')
82557 throw new TypeError('unexpected type ' + t + ', use Uint8Array');
82558 }
82559}
82560
82561function cleanup(arr) {
82562 for (var i = 0; i < arr.length; i++) arr[i] = 0;
82563}
82564
82565// TODO: Completely remove this in v0.15.
82566if (!nacl.util) {
82567 nacl.util = {};
82568 nacl.util.decodeUTF8 = nacl.util.encodeUTF8 = nacl.util.encodeBase64 = nacl.util.decodeBase64 = function() {
82569 throw new Error('nacl.util moved into separate package: https://github.com/dchest/tweetnacl-util-js');
82570 };
82571}
82572
82573nacl.randomBytes = function(n) {
82574 var b = new Uint8Array(n);
82575 randombytes(b, n);
82576 return b;
82577};
82578
82579nacl.secretbox = function(msg, nonce, key) {
82580 checkArrayTypes(msg, nonce, key);
82581 checkLengths(key, nonce);
82582 var m = new Uint8Array(crypto_secretbox_ZEROBYTES + msg.length);
82583 var c = new Uint8Array(m.length);
82584 for (var i = 0; i < msg.length; i++) m[i+crypto_secretbox_ZEROBYTES] = msg[i];
82585 crypto_secretbox(c, m, m.length, nonce, key);
82586 return c.subarray(crypto_secretbox_BOXZEROBYTES);
82587};
82588
82589nacl.secretbox.open = function(box, nonce, key) {
82590 checkArrayTypes(box, nonce, key);
82591 checkLengths(key, nonce);
82592 var c = new Uint8Array(crypto_secretbox_BOXZEROBYTES + box.length);
82593 var m = new Uint8Array(c.length);
82594 for (var i = 0; i < box.length; i++) c[i+crypto_secretbox_BOXZEROBYTES] = box[i];
82595 if (c.length < 32) return false;
82596 if (crypto_secretbox_open(m, c, c.length, nonce, key) !== 0) return false;
82597 return m.subarray(crypto_secretbox_ZEROBYTES);
82598};
82599
82600nacl.secretbox.keyLength = crypto_secretbox_KEYBYTES;
82601nacl.secretbox.nonceLength = crypto_secretbox_NONCEBYTES;
82602nacl.secretbox.overheadLength = crypto_secretbox_BOXZEROBYTES;
82603
82604nacl.scalarMult = function(n, p) {
82605 checkArrayTypes(n, p);
82606 if (n.length !== crypto_scalarmult_SCALARBYTES) throw new Error('bad n size');
82607 if (p.length !== crypto_scalarmult_BYTES) throw new Error('bad p size');
82608 var q = new Uint8Array(crypto_scalarmult_BYTES);
82609 crypto_scalarmult(q, n, p);
82610 return q;
82611};
82612
82613nacl.scalarMult.base = function(n) {
82614 checkArrayTypes(n);
82615 if (n.length !== crypto_scalarmult_SCALARBYTES) throw new Error('bad n size');
82616 var q = new Uint8Array(crypto_scalarmult_BYTES);
82617 crypto_scalarmult_base(q, n);
82618 return q;
82619};
82620
82621nacl.scalarMult.scalarLength = crypto_scalarmult_SCALARBYTES;
82622nacl.scalarMult.groupElementLength = crypto_scalarmult_BYTES;
82623
82624nacl.box = function(msg, nonce, publicKey, secretKey) {
82625 var k = nacl.box.before(publicKey, secretKey);
82626 return nacl.secretbox(msg, nonce, k);
82627};
82628
82629nacl.box.before = function(publicKey, secretKey) {
82630 checkArrayTypes(publicKey, secretKey);
82631 checkBoxLengths(publicKey, secretKey);
82632 var k = new Uint8Array(crypto_box_BEFORENMBYTES);
82633 crypto_box_beforenm(k, publicKey, secretKey);
82634 return k;
82635};
82636
82637nacl.box.after = nacl.secretbox;
82638
82639nacl.box.open = function(msg, nonce, publicKey, secretKey) {
82640 var k = nacl.box.before(publicKey, secretKey);
82641 return nacl.secretbox.open(msg, nonce, k);
82642};
82643
82644nacl.box.open.after = nacl.secretbox.open;
82645
82646nacl.box.keyPair = function() {
82647 var pk = new Uint8Array(crypto_box_PUBLICKEYBYTES);
82648 var sk = new Uint8Array(crypto_box_SECRETKEYBYTES);
82649 crypto_box_keypair(pk, sk);
82650 return {publicKey: pk, secretKey: sk};
82651};
82652
82653nacl.box.keyPair.fromSecretKey = function(secretKey) {
82654 checkArrayTypes(secretKey);
82655 if (secretKey.length !== crypto_box_SECRETKEYBYTES)
82656 throw new Error('bad secret key size');
82657 var pk = new Uint8Array(crypto_box_PUBLICKEYBYTES);
82658 crypto_scalarmult_base(pk, secretKey);
82659 return {publicKey: pk, secretKey: new Uint8Array(secretKey)};
82660};
82661
82662nacl.box.publicKeyLength = crypto_box_PUBLICKEYBYTES;
82663nacl.box.secretKeyLength = crypto_box_SECRETKEYBYTES;
82664nacl.box.sharedKeyLength = crypto_box_BEFORENMBYTES;
82665nacl.box.nonceLength = crypto_box_NONCEBYTES;
82666nacl.box.overheadLength = nacl.secretbox.overheadLength;
82667
82668nacl.sign = function(msg, secretKey) {
82669 checkArrayTypes(msg, secretKey);
82670 if (secretKey.length !== crypto_sign_SECRETKEYBYTES)
82671 throw new Error('bad secret key size');
82672 var signedMsg = new Uint8Array(crypto_sign_BYTES+msg.length);
82673 crypto_sign(signedMsg, msg, msg.length, secretKey);
82674 return signedMsg;
82675};
82676
82677nacl.sign.open = function(signedMsg, publicKey) {
82678 if (arguments.length !== 2)
82679 throw new Error('nacl.sign.open accepts 2 arguments; did you mean to use nacl.sign.detached.verify?');
82680 checkArrayTypes(signedMsg, publicKey);
82681 if (publicKey.length !== crypto_sign_PUBLICKEYBYTES)
82682 throw new Error('bad public key size');
82683 var tmp = new Uint8Array(signedMsg.length);
82684 var mlen = crypto_sign_open(tmp, signedMsg, signedMsg.length, publicKey);
82685 if (mlen < 0) return null;
82686 var m = new Uint8Array(mlen);
82687 for (var i = 0; i < m.length; i++) m[i] = tmp[i];
82688 return m;
82689};
82690
82691nacl.sign.detached = function(msg, secretKey) {
82692 var signedMsg = nacl.sign(msg, secretKey);
82693 var sig = new Uint8Array(crypto_sign_BYTES);
82694 for (var i = 0; i < sig.length; i++) sig[i] = signedMsg[i];
82695 return sig;
82696};
82697
82698nacl.sign.detached.verify = function(msg, sig, publicKey) {
82699 checkArrayTypes(msg, sig, publicKey);
82700 if (sig.length !== crypto_sign_BYTES)
82701 throw new Error('bad signature size');
82702 if (publicKey.length !== crypto_sign_PUBLICKEYBYTES)
82703 throw new Error('bad public key size');
82704 var sm = new Uint8Array(crypto_sign_BYTES + msg.length);
82705 var m = new Uint8Array(crypto_sign_BYTES + msg.length);
82706 var i;
82707 for (i = 0; i < crypto_sign_BYTES; i++) sm[i] = sig[i];
82708 for (i = 0; i < msg.length; i++) sm[i+crypto_sign_BYTES] = msg[i];
82709 return (crypto_sign_open(m, sm, sm.length, publicKey) >= 0);
82710};
82711
82712nacl.sign.keyPair = function() {
82713 var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES);
82714 var sk = new Uint8Array(crypto_sign_SECRETKEYBYTES);
82715 crypto_sign_keypair(pk, sk);
82716 return {publicKey: pk, secretKey: sk};
82717};
82718
82719nacl.sign.keyPair.fromSecretKey = function(secretKey) {
82720 checkArrayTypes(secretKey);
82721 if (secretKey.length !== crypto_sign_SECRETKEYBYTES)
82722 throw new Error('bad secret key size');
82723 var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES);
82724 for (var i = 0; i < pk.length; i++) pk[i] = secretKey[32+i];
82725 return {publicKey: pk, secretKey: new Uint8Array(secretKey)};
82726};
82727
82728nacl.sign.keyPair.fromSeed = function(seed) {
82729 checkArrayTypes(seed);
82730 if (seed.length !== crypto_sign_SEEDBYTES)
82731 throw new Error('bad seed size');
82732 var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES);
82733 var sk = new Uint8Array(crypto_sign_SECRETKEYBYTES);
82734 for (var i = 0; i < 32; i++) sk[i] = seed[i];
82735 crypto_sign_keypair(pk, sk, true);
82736 return {publicKey: pk, secretKey: sk};
82737};
82738
82739nacl.sign.publicKeyLength = crypto_sign_PUBLICKEYBYTES;
82740nacl.sign.secretKeyLength = crypto_sign_SECRETKEYBYTES;
82741nacl.sign.seedLength = crypto_sign_SEEDBYTES;
82742nacl.sign.signatureLength = crypto_sign_BYTES;
82743
82744nacl.hash = function(msg) {
82745 checkArrayTypes(msg);
82746 var h = new Uint8Array(crypto_hash_BYTES);
82747 crypto_hash(h, msg, msg.length);
82748 return h;
82749};
82750
82751nacl.hash.hashLength = crypto_hash_BYTES;
82752
82753nacl.verify = function(x, y) {
82754 checkArrayTypes(x, y);
82755 // Zero length arguments are considered not equal.
82756 if (x.length === 0 || y.length === 0) return false;
82757 if (x.length !== y.length) return false;
82758 return (vn(x, 0, y, 0, x.length) === 0) ? true : false;
82759};
82760
82761nacl.setPRNG = function(fn) {
82762 randombytes = fn;
82763};
82764
82765(function() {
82766 // Initialize PRNG if environment provides CSPRNG.
82767 // If not, methods calling randombytes will throw.
82768 var crypto = typeof self !== 'undefined' ? (self.crypto || self.msCrypto) : null;
82769 if (crypto && crypto.getRandomValues) {
82770 // Browsers.
82771 var QUOTA = 65536;
82772 nacl.setPRNG(function(x, n) {
82773 var i, v = new Uint8Array(n);
82774 for (i = 0; i < n; i += QUOTA) {
82775 crypto.getRandomValues(v.subarray(i, i + Math.min(n - i, QUOTA)));
82776 }
82777 for (i = 0; i < n; i++) x[i] = v[i];
82778 cleanup(v);
82779 });
82780 } else if (typeof require !== 'undefined') {
82781 // Node.js.
82782 crypto = require('crypto');
82783 if (crypto && crypto.randomBytes) {
82784 nacl.setPRNG(function(x, n) {
82785 var i, v = crypto.randomBytes(n);
82786 for (i = 0; i < n; i++) x[i] = v[i];
82787 cleanup(v);
82788 });
82789 }
82790 }
82791})();
82792
82793})(typeof module !== 'undefined' && module.exports ? module.exports : (self.nacl = self.nacl || {}));
82794
82795},{"crypto":82}],392:[function(require,module,exports){
82796/** @license URI.js v4.2.1 (c) 2011 Gary Court. License: http://github.com/garycourt/uri-js */
82797(function (global, factory) {
82798 typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
82799 typeof define === 'function' && define.amd ? define(['exports'], factory) :
82800 (factory((global.URI = global.URI || {})));
82801}(this, (function (exports) { 'use strict';
82802
82803function merge() {
82804 for (var _len = arguments.length, sets = Array(_len), _key = 0; _key < _len; _key++) {
82805 sets[_key] = arguments[_key];
82806 }
82807
82808 if (sets.length > 1) {
82809 sets[0] = sets[0].slice(0, -1);
82810 var xl = sets.length - 1;
82811 for (var x = 1; x < xl; ++x) {
82812 sets[x] = sets[x].slice(1, -1);
82813 }
82814 sets[xl] = sets[xl].slice(1);
82815 return sets.join('');
82816 } else {
82817 return sets[0];
82818 }
82819}
82820function subexp(str) {
82821 return "(?:" + str + ")";
82822}
82823function typeOf(o) {
82824 return o === undefined ? "undefined" : o === null ? "null" : Object.prototype.toString.call(o).split(" ").pop().split("]").shift().toLowerCase();
82825}
82826function toUpperCase(str) {
82827 return str.toUpperCase();
82828}
82829function toArray(obj) {
82830 return obj !== undefined && obj !== null ? obj instanceof Array ? obj : typeof obj.length !== "number" || obj.split || obj.setInterval || obj.call ? [obj] : Array.prototype.slice.call(obj) : [];
82831}
82832function assign(target, source) {
82833 var obj = target;
82834 if (source) {
82835 for (var key in source) {
82836 obj[key] = source[key];
82837 }
82838 }
82839 return obj;
82840}
82841
82842function buildExps(isIRI) {
82843 var ALPHA$$ = "[A-Za-z]",
82844 CR$ = "[\\x0D]",
82845 DIGIT$$ = "[0-9]",
82846 DQUOTE$$ = "[\\x22]",
82847 HEXDIG$$ = merge(DIGIT$$, "[A-Fa-f]"),
82848 //case-insensitive
82849 LF$$ = "[\\x0A]",
82850 SP$$ = "[\\x20]",
82851 PCT_ENCODED$ = subexp(subexp("%[EFef]" + HEXDIG$$ + "%" + HEXDIG$$ + HEXDIG$$ + "%" + HEXDIG$$ + HEXDIG$$) + "|" + subexp("%[89A-Fa-f]" + HEXDIG$$ + "%" + HEXDIG$$ + HEXDIG$$) + "|" + subexp("%" + HEXDIG$$ + HEXDIG$$)),
82852 //expanded
82853 GEN_DELIMS$$ = "[\\:\\/\\?\\#\\[\\]\\@]",
82854 SUB_DELIMS$$ = "[\\!\\$\\&\\'\\(\\)\\*\\+\\,\\;\\=]",
82855 RESERVED$$ = merge(GEN_DELIMS$$, SUB_DELIMS$$),
82856 UCSCHAR$$ = isIRI ? "[\\xA0-\\u200D\\u2010-\\u2029\\u202F-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]" : "[]",
82857 //subset, excludes bidi control characters
82858 IPRIVATE$$ = isIRI ? "[\\uE000-\\uF8FF]" : "[]",
82859 //subset
82860 UNRESERVED$$ = merge(ALPHA$$, DIGIT$$, "[\\-\\.\\_\\~]", UCSCHAR$$),
82861 SCHEME$ = subexp(ALPHA$$ + merge(ALPHA$$, DIGIT$$, "[\\+\\-\\.]") + "*"),
82862 USERINFO$ = subexp(subexp(PCT_ENCODED$ + "|" + merge(UNRESERVED$$, SUB_DELIMS$$, "[\\:]")) + "*"),
82863 DEC_OCTET$ = subexp(subexp("25[0-5]") + "|" + subexp("2[0-4]" + DIGIT$$) + "|" + subexp("1" + DIGIT$$ + DIGIT$$) + "|" + subexp("[1-9]" + DIGIT$$) + "|" + DIGIT$$),
82864 DEC_OCTET_RELAXED$ = subexp(subexp("25[0-5]") + "|" + subexp("2[0-4]" + DIGIT$$) + "|" + subexp("1" + DIGIT$$ + DIGIT$$) + "|" + subexp("0?[1-9]" + DIGIT$$) + "|0?0?" + DIGIT$$),
82865 //relaxed parsing rules
82866 IPV4ADDRESS$ = subexp(DEC_OCTET_RELAXED$ + "\\." + DEC_OCTET_RELAXED$ + "\\." + DEC_OCTET_RELAXED$ + "\\." + DEC_OCTET_RELAXED$),
82867 H16$ = subexp(HEXDIG$$ + "{1,4}"),
82868 LS32$ = subexp(subexp(H16$ + "\\:" + H16$) + "|" + IPV4ADDRESS$),
82869 IPV6ADDRESS1$ = subexp(subexp(H16$ + "\\:") + "{6}" + LS32$),
82870 // 6( h16 ":" ) ls32
82871 IPV6ADDRESS2$ = subexp("\\:\\:" + subexp(H16$ + "\\:") + "{5}" + LS32$),
82872 // "::" 5( h16 ":" ) ls32
82873 IPV6ADDRESS3$ = subexp(subexp(H16$) + "?\\:\\:" + subexp(H16$ + "\\:") + "{4}" + LS32$),
82874 //[ h16 ] "::" 4( h16 ":" ) ls32
82875 IPV6ADDRESS4$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,1}" + H16$) + "?\\:\\:" + subexp(H16$ + "\\:") + "{3}" + LS32$),
82876 //[ *1( h16 ":" ) h16 ] "::" 3( h16 ":" ) ls32
82877 IPV6ADDRESS5$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,2}" + H16$) + "?\\:\\:" + subexp(H16$ + "\\:") + "{2}" + LS32$),
82878 //[ *2( h16 ":" ) h16 ] "::" 2( h16 ":" ) ls32
82879 IPV6ADDRESS6$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,3}" + H16$) + "?\\:\\:" + H16$ + "\\:" + LS32$),
82880 //[ *3( h16 ":" ) h16 ] "::" h16 ":" ls32
82881 IPV6ADDRESS7$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,4}" + H16$) + "?\\:\\:" + LS32$),
82882 //[ *4( h16 ":" ) h16 ] "::" ls32
82883 IPV6ADDRESS8$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,5}" + H16$) + "?\\:\\:" + H16$),
82884 //[ *5( h16 ":" ) h16 ] "::" h16
82885 IPV6ADDRESS9$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,6}" + H16$) + "?\\:\\:"),
82886 //[ *6( h16 ":" ) h16 ] "::"
82887 IPV6ADDRESS$ = subexp([IPV6ADDRESS1$, IPV6ADDRESS2$, IPV6ADDRESS3$, IPV6ADDRESS4$, IPV6ADDRESS5$, IPV6ADDRESS6$, IPV6ADDRESS7$, IPV6ADDRESS8$, IPV6ADDRESS9$].join("|")),
82888 ZONEID$ = subexp(subexp(UNRESERVED$$ + "|" + PCT_ENCODED$) + "+"),
82889 //RFC 6874
82890 IPV6ADDRZ$ = subexp(IPV6ADDRESS$ + "\\%25" + ZONEID$),
82891 //RFC 6874
82892 IPV6ADDRZ_RELAXED$ = subexp(IPV6ADDRESS$ + subexp("\\%25|\\%(?!" + HEXDIG$$ + "{2})") + ZONEID$),
82893 //RFC 6874, with relaxed parsing rules
82894 IPVFUTURE$ = subexp("[vV]" + HEXDIG$$ + "+\\." + merge(UNRESERVED$$, SUB_DELIMS$$, "[\\:]") + "+"),
82895 IP_LITERAL$ = subexp("\\[" + subexp(IPV6ADDRZ_RELAXED$ + "|" + IPV6ADDRESS$ + "|" + IPVFUTURE$) + "\\]"),
82896 //RFC 6874
82897 REG_NAME$ = subexp(subexp(PCT_ENCODED$ + "|" + merge(UNRESERVED$$, SUB_DELIMS$$)) + "*"),
82898 HOST$ = subexp(IP_LITERAL$ + "|" + IPV4ADDRESS$ + "(?!" + REG_NAME$ + ")" + "|" + REG_NAME$),
82899 PORT$ = subexp(DIGIT$$ + "*"),
82900 AUTHORITY$ = subexp(subexp(USERINFO$ + "@") + "?" + HOST$ + subexp("\\:" + PORT$) + "?"),
82901 PCHAR$ = subexp(PCT_ENCODED$ + "|" + merge(UNRESERVED$$, SUB_DELIMS$$, "[\\:\\@]")),
82902 SEGMENT$ = subexp(PCHAR$ + "*"),
82903 SEGMENT_NZ$ = subexp(PCHAR$ + "+"),
82904 SEGMENT_NZ_NC$ = subexp(subexp(PCT_ENCODED$ + "|" + merge(UNRESERVED$$, SUB_DELIMS$$, "[\\@]")) + "+"),
82905 PATH_ABEMPTY$ = subexp(subexp("\\/" + SEGMENT$) + "*"),
82906 PATH_ABSOLUTE$ = subexp("\\/" + subexp(SEGMENT_NZ$ + PATH_ABEMPTY$) + "?"),
82907 //simplified
82908 PATH_NOSCHEME$ = subexp(SEGMENT_NZ_NC$ + PATH_ABEMPTY$),
82909 //simplified
82910 PATH_ROOTLESS$ = subexp(SEGMENT_NZ$ + PATH_ABEMPTY$),
82911 //simplified
82912 PATH_EMPTY$ = "(?!" + PCHAR$ + ")",
82913 PATH$ = subexp(PATH_ABEMPTY$ + "|" + PATH_ABSOLUTE$ + "|" + PATH_NOSCHEME$ + "|" + PATH_ROOTLESS$ + "|" + PATH_EMPTY$),
82914 QUERY$ = subexp(subexp(PCHAR$ + "|" + merge("[\\/\\?]", IPRIVATE$$)) + "*"),
82915 FRAGMENT$ = subexp(subexp(PCHAR$ + "|[\\/\\?]") + "*"),
82916 HIER_PART$ = subexp(subexp("\\/\\/" + AUTHORITY$ + PATH_ABEMPTY$) + "|" + PATH_ABSOLUTE$ + "|" + PATH_ROOTLESS$ + "|" + PATH_EMPTY$),
82917 URI$ = subexp(SCHEME$ + "\\:" + HIER_PART$ + subexp("\\?" + QUERY$) + "?" + subexp("\\#" + FRAGMENT$) + "?"),
82918 RELATIVE_PART$ = subexp(subexp("\\/\\/" + AUTHORITY$ + PATH_ABEMPTY$) + "|" + PATH_ABSOLUTE$ + "|" + PATH_NOSCHEME$ + "|" + PATH_EMPTY$),
82919 RELATIVE$ = subexp(RELATIVE_PART$ + subexp("\\?" + QUERY$) + "?" + subexp("\\#" + FRAGMENT$) + "?"),
82920 URI_REFERENCE$ = subexp(URI$ + "|" + RELATIVE$),
82921 ABSOLUTE_URI$ = subexp(SCHEME$ + "\\:" + HIER_PART$ + subexp("\\?" + QUERY$) + "?"),
82922 GENERIC_REF$ = "^(" + SCHEME$ + ")\\:" + subexp(subexp("\\/\\/(" + subexp("(" + USERINFO$ + ")@") + "?(" + HOST$ + ")" + subexp("\\:(" + PORT$ + ")") + "?)") + "?(" + PATH_ABEMPTY$ + "|" + PATH_ABSOLUTE$ + "|" + PATH_ROOTLESS$ + "|" + PATH_EMPTY$ + ")") + subexp("\\?(" + QUERY$ + ")") + "?" + subexp("\\#(" + FRAGMENT$ + ")") + "?$",
82923 RELATIVE_REF$ = "^(){0}" + subexp(subexp("\\/\\/(" + subexp("(" + USERINFO$ + ")@") + "?(" + HOST$ + ")" + subexp("\\:(" + PORT$ + ")") + "?)") + "?(" + PATH_ABEMPTY$ + "|" + PATH_ABSOLUTE$ + "|" + PATH_NOSCHEME$ + "|" + PATH_EMPTY$ + ")") + subexp("\\?(" + QUERY$ + ")") + "?" + subexp("\\#(" + FRAGMENT$ + ")") + "?$",
82924 ABSOLUTE_REF$ = "^(" + SCHEME$ + ")\\:" + subexp(subexp("\\/\\/(" + subexp("(" + USERINFO$ + ")@") + "?(" + HOST$ + ")" + subexp("\\:(" + PORT$ + ")") + "?)") + "?(" + PATH_ABEMPTY$ + "|" + PATH_ABSOLUTE$ + "|" + PATH_ROOTLESS$ + "|" + PATH_EMPTY$ + ")") + subexp("\\?(" + QUERY$ + ")") + "?$",
82925 SAMEDOC_REF$ = "^" + subexp("\\#(" + FRAGMENT$ + ")") + "?$",
82926 AUTHORITY_REF$ = "^" + subexp("(" + USERINFO$ + ")@") + "?(" + HOST$ + ")" + subexp("\\:(" + PORT$ + ")") + "?$";
82927 return {
82928 NOT_SCHEME: new RegExp(merge("[^]", ALPHA$$, DIGIT$$, "[\\+\\-\\.]"), "g"),
82929 NOT_USERINFO: new RegExp(merge("[^\\%\\:]", UNRESERVED$$, SUB_DELIMS$$), "g"),
82930 NOT_HOST: new RegExp(merge("[^\\%\\[\\]\\:]", UNRESERVED$$, SUB_DELIMS$$), "g"),
82931 NOT_PATH: new RegExp(merge("[^\\%\\/\\:\\@]", UNRESERVED$$, SUB_DELIMS$$), "g"),
82932 NOT_PATH_NOSCHEME: new RegExp(merge("[^\\%\\/\\@]", UNRESERVED$$, SUB_DELIMS$$), "g"),
82933 NOT_QUERY: new RegExp(merge("[^\\%]", UNRESERVED$$, SUB_DELIMS$$, "[\\:\\@\\/\\?]", IPRIVATE$$), "g"),
82934 NOT_FRAGMENT: new RegExp(merge("[^\\%]", UNRESERVED$$, SUB_DELIMS$$, "[\\:\\@\\/\\?]"), "g"),
82935 ESCAPE: new RegExp(merge("[^]", UNRESERVED$$, SUB_DELIMS$$), "g"),
82936 UNRESERVED: new RegExp(UNRESERVED$$, "g"),
82937 OTHER_CHARS: new RegExp(merge("[^\\%]", UNRESERVED$$, RESERVED$$), "g"),
82938 PCT_ENCODED: new RegExp(PCT_ENCODED$, "g"),
82939 IPV4ADDRESS: new RegExp("^(" + IPV4ADDRESS$ + ")$"),
82940 IPV6ADDRESS: new RegExp("^\\[?(" + IPV6ADDRESS$ + ")" + subexp(subexp("\\%25|\\%(?!" + HEXDIG$$ + "{2})") + "(" + ZONEID$ + ")") + "?\\]?$") //RFC 6874, with relaxed parsing rules
82941 };
82942}
82943var URI_PROTOCOL = buildExps(false);
82944
82945var IRI_PROTOCOL = buildExps(true);
82946
82947var slicedToArray = function () {
82948 function sliceIterator(arr, i) {
82949 var _arr = [];
82950 var _n = true;
82951 var _d = false;
82952 var _e = undefined;
82953
82954 try {
82955 for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {
82956 _arr.push(_s.value);
82957
82958 if (i && _arr.length === i) break;
82959 }
82960 } catch (err) {
82961 _d = true;
82962 _e = err;
82963 } finally {
82964 try {
82965 if (!_n && _i["return"]) _i["return"]();
82966 } finally {
82967 if (_d) throw _e;
82968 }
82969 }
82970
82971 return _arr;
82972 }
82973
82974 return function (arr, i) {
82975 if (Array.isArray(arr)) {
82976 return arr;
82977 } else if (Symbol.iterator in Object(arr)) {
82978 return sliceIterator(arr, i);
82979 } else {
82980 throw new TypeError("Invalid attempt to destructure non-iterable instance");
82981 }
82982 };
82983}();
82984
82985
82986
82987
82988
82989
82990
82991
82992
82993
82994
82995
82996
82997var toConsumableArray = function (arr) {
82998 if (Array.isArray(arr)) {
82999 for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) arr2[i] = arr[i];
83000
83001 return arr2;
83002 } else {
83003 return Array.from(arr);
83004 }
83005};
83006
83007/** Highest positive signed 32-bit float value */
83008
83009var maxInt = 2147483647; // aka. 0x7FFFFFFF or 2^31-1
83010
83011/** Bootstring parameters */
83012var base = 36;
83013var tMin = 1;
83014var tMax = 26;
83015var skew = 38;
83016var damp = 700;
83017var initialBias = 72;
83018var initialN = 128; // 0x80
83019var delimiter = '-'; // '\x2D'
83020
83021/** Regular expressions */
83022var regexPunycode = /^xn--/;
83023var regexNonASCII = /[^\0-\x7E]/; // non-ASCII chars
83024var regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g; // RFC 3490 separators
83025
83026/** Error messages */
83027var errors = {
83028 'overflow': 'Overflow: input needs wider integers to process',
83029 'not-basic': 'Illegal input >= 0x80 (not a basic code point)',
83030 'invalid-input': 'Invalid input'
83031};
83032
83033/** Convenience shortcuts */
83034var baseMinusTMin = base - tMin;
83035var floor = Math.floor;
83036var stringFromCharCode = String.fromCharCode;
83037
83038/*--------------------------------------------------------------------------*/
83039
83040/**
83041 * A generic error utility function.
83042 * @private
83043 * @param {String} type The error type.
83044 * @returns {Error} Throws a `RangeError` with the applicable error message.
83045 */
83046function error$1(type) {
83047 throw new RangeError(errors[type]);
83048}
83049
83050/**
83051 * A generic `Array#map` utility function.
83052 * @private
83053 * @param {Array} array The array to iterate over.
83054 * @param {Function} callback The function that gets called for every array
83055 * item.
83056 * @returns {Array} A new array of values returned by the callback function.
83057 */
83058function map(array, fn) {
83059 var result = [];
83060 var length = array.length;
83061 while (length--) {
83062 result[length] = fn(array[length]);
83063 }
83064 return result;
83065}
83066
83067/**
83068 * A simple `Array#map`-like wrapper to work with domain name strings or email
83069 * addresses.
83070 * @private
83071 * @param {String} domain The domain name or email address.
83072 * @param {Function} callback The function that gets called for every
83073 * character.
83074 * @returns {Array} A new string of characters returned by the callback
83075 * function.
83076 */
83077function mapDomain(string, fn) {
83078 var parts = string.split('@');
83079 var result = '';
83080 if (parts.length > 1) {
83081 // In email addresses, only the domain name should be punycoded. Leave
83082 // the local part (i.e. everything up to `@`) intact.
83083 result = parts[0] + '@';
83084 string = parts[1];
83085 }
83086 // Avoid `split(regex)` for IE8 compatibility. See #17.
83087 string = string.replace(regexSeparators, '\x2E');
83088 var labels = string.split('.');
83089 var encoded = map(labels, fn).join('.');
83090 return result + encoded;
83091}
83092
83093/**
83094 * Creates an array containing the numeric code points of each Unicode
83095 * character in the string. While JavaScript uses UCS-2 internally,
83096 * this function will convert a pair of surrogate halves (each of which
83097 * UCS-2 exposes as separate characters) into a single code point,
83098 * matching UTF-16.
83099 * @see `punycode.ucs2.encode`
83100 * @see <https://mathiasbynens.be/notes/javascript-encoding>
83101 * @memberOf punycode.ucs2
83102 * @name decode
83103 * @param {String} string The Unicode input string (UCS-2).
83104 * @returns {Array} The new array of code points.
83105 */
83106function ucs2decode(string) {
83107 var output = [];
83108 var counter = 0;
83109 var length = string.length;
83110 while (counter < length) {
83111 var value = string.charCodeAt(counter++);
83112 if (value >= 0xD800 && value <= 0xDBFF && counter < length) {
83113 // It's a high surrogate, and there is a next character.
83114 var extra = string.charCodeAt(counter++);
83115 if ((extra & 0xFC00) == 0xDC00) {
83116 // Low surrogate.
83117 output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000);
83118 } else {
83119 // It's an unmatched surrogate; only append this code unit, in case the
83120 // next code unit is the high surrogate of a surrogate pair.
83121 output.push(value);
83122 counter--;
83123 }
83124 } else {
83125 output.push(value);
83126 }
83127 }
83128 return output;
83129}
83130
83131/**
83132 * Creates a string based on an array of numeric code points.
83133 * @see `punycode.ucs2.decode`
83134 * @memberOf punycode.ucs2
83135 * @name encode
83136 * @param {Array} codePoints The array of numeric code points.
83137 * @returns {String} The new Unicode string (UCS-2).
83138 */
83139var ucs2encode = function ucs2encode(array) {
83140 return String.fromCodePoint.apply(String, toConsumableArray(array));
83141};
83142
83143/**
83144 * Converts a basic code point into a digit/integer.
83145 * @see `digitToBasic()`
83146 * @private
83147 * @param {Number} codePoint The basic numeric code point value.
83148 * @returns {Number} The numeric value of a basic code point (for use in
83149 * representing integers) in the range `0` to `base - 1`, or `base` if
83150 * the code point does not represent a value.
83151 */
83152var basicToDigit = function basicToDigit(codePoint) {
83153 if (codePoint - 0x30 < 0x0A) {
83154 return codePoint - 0x16;
83155 }
83156 if (codePoint - 0x41 < 0x1A) {
83157 return codePoint - 0x41;
83158 }
83159 if (codePoint - 0x61 < 0x1A) {
83160 return codePoint - 0x61;
83161 }
83162 return base;
83163};
83164
83165/**
83166 * Converts a digit/integer into a basic code point.
83167 * @see `basicToDigit()`
83168 * @private
83169 * @param {Number} digit The numeric value of a basic code point.
83170 * @returns {Number} The basic code point whose value (when used for
83171 * representing integers) is `digit`, which needs to be in the range
83172 * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is
83173 * used; else, the lowercase form is used. The behavior is undefined
83174 * if `flag` is non-zero and `digit` has no uppercase form.
83175 */
83176var digitToBasic = function digitToBasic(digit, flag) {
83177 // 0..25 map to ASCII a..z or A..Z
83178 // 26..35 map to ASCII 0..9
83179 return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5);
83180};
83181
83182/**
83183 * Bias adaptation function as per section 3.4 of RFC 3492.
83184 * https://tools.ietf.org/html/rfc3492#section-3.4
83185 * @private
83186 */
83187var adapt = function adapt(delta, numPoints, firstTime) {
83188 var k = 0;
83189 delta = firstTime ? floor(delta / damp) : delta >> 1;
83190 delta += floor(delta / numPoints);
83191 for (; /* no initialization */delta > baseMinusTMin * tMax >> 1; k += base) {
83192 delta = floor(delta / baseMinusTMin);
83193 }
83194 return floor(k + (baseMinusTMin + 1) * delta / (delta + skew));
83195};
83196
83197/**
83198 * Converts a Punycode string of ASCII-only symbols to a string of Unicode
83199 * symbols.
83200 * @memberOf punycode
83201 * @param {String} input The Punycode string of ASCII-only symbols.
83202 * @returns {String} The resulting string of Unicode symbols.
83203 */
83204var decode = function decode(input) {
83205 // Don't use UCS-2.
83206 var output = [];
83207 var inputLength = input.length;
83208 var i = 0;
83209 var n = initialN;
83210 var bias = initialBias;
83211
83212 // Handle the basic code points: let `basic` be the number of input code
83213 // points before the last delimiter, or `0` if there is none, then copy
83214 // the first basic code points to the output.
83215
83216 var basic = input.lastIndexOf(delimiter);
83217 if (basic < 0) {
83218 basic = 0;
83219 }
83220
83221 for (var j = 0; j < basic; ++j) {
83222 // if it's not a basic code point
83223 if (input.charCodeAt(j) >= 0x80) {
83224 error$1('not-basic');
83225 }
83226 output.push(input.charCodeAt(j));
83227 }
83228
83229 // Main decoding loop: start just after the last delimiter if any basic code
83230 // points were copied; start at the beginning otherwise.
83231
83232 for (var index = basic > 0 ? basic + 1 : 0; index < inputLength;) /* no final expression */{
83233
83234 // `index` is the index of the next character to be consumed.
83235 // Decode a generalized variable-length integer into `delta`,
83236 // which gets added to `i`. The overflow checking is easier
83237 // if we increase `i` as we go, then subtract off its starting
83238 // value at the end to obtain `delta`.
83239 var oldi = i;
83240 for (var w = 1, k = base;; /* no condition */k += base) {
83241
83242 if (index >= inputLength) {
83243 error$1('invalid-input');
83244 }
83245
83246 var digit = basicToDigit(input.charCodeAt(index++));
83247
83248 if (digit >= base || digit > floor((maxInt - i) / w)) {
83249 error$1('overflow');
83250 }
83251
83252 i += digit * w;
83253 var t = k <= bias ? tMin : k >= bias + tMax ? tMax : k - bias;
83254
83255 if (digit < t) {
83256 break;
83257 }
83258
83259 var baseMinusT = base - t;
83260 if (w > floor(maxInt / baseMinusT)) {
83261 error$1('overflow');
83262 }
83263
83264 w *= baseMinusT;
83265 }
83266
83267 var out = output.length + 1;
83268 bias = adapt(i - oldi, out, oldi == 0);
83269
83270 // `i` was supposed to wrap around from `out` to `0`,
83271 // incrementing `n` each time, so we'll fix that now:
83272 if (floor(i / out) > maxInt - n) {
83273 error$1('overflow');
83274 }
83275
83276 n += floor(i / out);
83277 i %= out;
83278
83279 // Insert `n` at position `i` of the output.
83280 output.splice(i++, 0, n);
83281 }
83282
83283 return String.fromCodePoint.apply(String, output);
83284};
83285
83286/**
83287 * Converts a string of Unicode symbols (e.g. a domain name label) to a
83288 * Punycode string of ASCII-only symbols.
83289 * @memberOf punycode
83290 * @param {String} input The string of Unicode symbols.
83291 * @returns {String} The resulting Punycode string of ASCII-only symbols.
83292 */
83293var encode = function encode(input) {
83294 var output = [];
83295
83296 // Convert the input in UCS-2 to an array of Unicode code points.
83297 input = ucs2decode(input);
83298
83299 // Cache the length.
83300 var inputLength = input.length;
83301
83302 // Initialize the state.
83303 var n = initialN;
83304 var delta = 0;
83305 var bias = initialBias;
83306
83307 // Handle the basic code points.
83308 var _iteratorNormalCompletion = true;
83309 var _didIteratorError = false;
83310 var _iteratorError = undefined;
83311
83312 try {
83313 for (var _iterator = input[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
83314 var _currentValue2 = _step.value;
83315
83316 if (_currentValue2 < 0x80) {
83317 output.push(stringFromCharCode(_currentValue2));
83318 }
83319 }
83320 } catch (err) {
83321 _didIteratorError = true;
83322 _iteratorError = err;
83323 } finally {
83324 try {
83325 if (!_iteratorNormalCompletion && _iterator.return) {
83326 _iterator.return();
83327 }
83328 } finally {
83329 if (_didIteratorError) {
83330 throw _iteratorError;
83331 }
83332 }
83333 }
83334
83335 var basicLength = output.length;
83336 var handledCPCount = basicLength;
83337
83338 // `handledCPCount` is the number of code points that have been handled;
83339 // `basicLength` is the number of basic code points.
83340
83341 // Finish the basic string with a delimiter unless it's empty.
83342 if (basicLength) {
83343 output.push(delimiter);
83344 }
83345
83346 // Main encoding loop:
83347 while (handledCPCount < inputLength) {
83348
83349 // All non-basic code points < n have been handled already. Find the next
83350 // larger one:
83351 var m = maxInt;
83352 var _iteratorNormalCompletion2 = true;
83353 var _didIteratorError2 = false;
83354 var _iteratorError2 = undefined;
83355
83356 try {
83357 for (var _iterator2 = input[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
83358 var currentValue = _step2.value;
83359
83360 if (currentValue >= n && currentValue < m) {
83361 m = currentValue;
83362 }
83363 }
83364
83365 // Increase `delta` enough to advance the decoder's <n,i> state to <m,0>,
83366 // but guard against overflow.
83367 } catch (err) {
83368 _didIteratorError2 = true;
83369 _iteratorError2 = err;
83370 } finally {
83371 try {
83372 if (!_iteratorNormalCompletion2 && _iterator2.return) {
83373 _iterator2.return();
83374 }
83375 } finally {
83376 if (_didIteratorError2) {
83377 throw _iteratorError2;
83378 }
83379 }
83380 }
83381
83382 var handledCPCountPlusOne = handledCPCount + 1;
83383 if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) {
83384 error$1('overflow');
83385 }
83386
83387 delta += (m - n) * handledCPCountPlusOne;
83388 n = m;
83389
83390 var _iteratorNormalCompletion3 = true;
83391 var _didIteratorError3 = false;
83392 var _iteratorError3 = undefined;
83393
83394 try {
83395 for (var _iterator3 = input[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) {
83396 var _currentValue = _step3.value;
83397
83398 if (_currentValue < n && ++delta > maxInt) {
83399 error$1('overflow');
83400 }
83401 if (_currentValue == n) {
83402 // Represent delta as a generalized variable-length integer.
83403 var q = delta;
83404 for (var k = base;; /* no condition */k += base) {
83405 var t = k <= bias ? tMin : k >= bias + tMax ? tMax : k - bias;
83406 if (q < t) {
83407 break;
83408 }
83409 var qMinusT = q - t;
83410 var baseMinusT = base - t;
83411 output.push(stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0)));
83412 q = floor(qMinusT / baseMinusT);
83413 }
83414
83415 output.push(stringFromCharCode(digitToBasic(q, 0)));
83416 bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength);
83417 delta = 0;
83418 ++handledCPCount;
83419 }
83420 }
83421 } catch (err) {
83422 _didIteratorError3 = true;
83423 _iteratorError3 = err;
83424 } finally {
83425 try {
83426 if (!_iteratorNormalCompletion3 && _iterator3.return) {
83427 _iterator3.return();
83428 }
83429 } finally {
83430 if (_didIteratorError3) {
83431 throw _iteratorError3;
83432 }
83433 }
83434 }
83435
83436 ++delta;
83437 ++n;
83438 }
83439 return output.join('');
83440};
83441
83442/**
83443 * Converts a Punycode string representing a domain name or an email address
83444 * to Unicode. Only the Punycoded parts of the input will be converted, i.e.
83445 * it doesn't matter if you call it on a string that has already been
83446 * converted to Unicode.
83447 * @memberOf punycode
83448 * @param {String} input The Punycoded domain name or email address to
83449 * convert to Unicode.
83450 * @returns {String} The Unicode representation of the given Punycode
83451 * string.
83452 */
83453var toUnicode = function toUnicode(input) {
83454 return mapDomain(input, function (string) {
83455 return regexPunycode.test(string) ? decode(string.slice(4).toLowerCase()) : string;
83456 });
83457};
83458
83459/**
83460 * Converts a Unicode string representing a domain name or an email address to
83461 * Punycode. Only the non-ASCII parts of the domain name will be converted,
83462 * i.e. it doesn't matter if you call it with a domain that's already in
83463 * ASCII.
83464 * @memberOf punycode
83465 * @param {String} input The domain name or email address to convert, as a
83466 * Unicode string.
83467 * @returns {String} The Punycode representation of the given domain name or
83468 * email address.
83469 */
83470var toASCII = function toASCII(input) {
83471 return mapDomain(input, function (string) {
83472 return regexNonASCII.test(string) ? 'xn--' + encode(string) : string;
83473 });
83474};
83475
83476/*--------------------------------------------------------------------------*/
83477
83478/** Define the public API */
83479var punycode = {
83480 /**
83481 * A string representing the current Punycode.js version number.
83482 * @memberOf punycode
83483 * @type String
83484 */
83485 'version': '2.1.0',
83486 /**
83487 * An object of methods to convert from JavaScript's internal character
83488 * representation (UCS-2) to Unicode code points, and back.
83489 * @see <https://mathiasbynens.be/notes/javascript-encoding>
83490 * @memberOf punycode
83491 * @type Object
83492 */
83493 'ucs2': {
83494 'decode': ucs2decode,
83495 'encode': ucs2encode
83496 },
83497 'decode': decode,
83498 'encode': encode,
83499 'toASCII': toASCII,
83500 'toUnicode': toUnicode
83501};
83502
83503/**
83504 * URI.js
83505 *
83506 * @fileoverview An RFC 3986 compliant, scheme extendable URI parsing/validating/resolving library for JavaScript.
83507 * @author <a href="mailto:gary.court@gmail.com">Gary Court</a>
83508 * @see http://github.com/garycourt/uri-js
83509 */
83510/**
83511 * Copyright 2011 Gary Court. All rights reserved.
83512 *
83513 * Redistribution and use in source and binary forms, with or without modification, are
83514 * permitted provided that the following conditions are met:
83515 *
83516 * 1. Redistributions of source code must retain the above copyright notice, this list of
83517 * conditions and the following disclaimer.
83518 *
83519 * 2. Redistributions in binary form must reproduce the above copyright notice, this list
83520 * of conditions and the following disclaimer in the documentation and/or other materials
83521 * provided with the distribution.
83522 *
83523 * THIS SOFTWARE IS PROVIDED BY GARY COURT ``AS IS'' AND ANY EXPRESS OR IMPLIED
83524 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
83525 * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GARY COURT OR
83526 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
83527 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
83528 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
83529 * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
83530 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
83531 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
83532 *
83533 * The views and conclusions contained in the software and documentation are those of the
83534 * authors and should not be interpreted as representing official policies, either expressed
83535 * or implied, of Gary Court.
83536 */
83537var SCHEMES = {};
83538function pctEncChar(chr) {
83539 var c = chr.charCodeAt(0);
83540 var e = void 0;
83541 if (c < 16) e = "%0" + c.toString(16).toUpperCase();else if (c < 128) e = "%" + c.toString(16).toUpperCase();else if (c < 2048) e = "%" + (c >> 6 | 192).toString(16).toUpperCase() + "%" + (c & 63 | 128).toString(16).toUpperCase();else e = "%" + (c >> 12 | 224).toString(16).toUpperCase() + "%" + (c >> 6 & 63 | 128).toString(16).toUpperCase() + "%" + (c & 63 | 128).toString(16).toUpperCase();
83542 return e;
83543}
83544function pctDecChars(str) {
83545 var newStr = "";
83546 var i = 0;
83547 var il = str.length;
83548 while (i < il) {
83549 var c = parseInt(str.substr(i + 1, 2), 16);
83550 if (c < 128) {
83551 newStr += String.fromCharCode(c);
83552 i += 3;
83553 } else if (c >= 194 && c < 224) {
83554 if (il - i >= 6) {
83555 var c2 = parseInt(str.substr(i + 4, 2), 16);
83556 newStr += String.fromCharCode((c & 31) << 6 | c2 & 63);
83557 } else {
83558 newStr += str.substr(i, 6);
83559 }
83560 i += 6;
83561 } else if (c >= 224) {
83562 if (il - i >= 9) {
83563 var _c = parseInt(str.substr(i + 4, 2), 16);
83564 var c3 = parseInt(str.substr(i + 7, 2), 16);
83565 newStr += String.fromCharCode((c & 15) << 12 | (_c & 63) << 6 | c3 & 63);
83566 } else {
83567 newStr += str.substr(i, 9);
83568 }
83569 i += 9;
83570 } else {
83571 newStr += str.substr(i, 3);
83572 i += 3;
83573 }
83574 }
83575 return newStr;
83576}
83577function _normalizeComponentEncoding(components, protocol) {
83578 function decodeUnreserved(str) {
83579 var decStr = pctDecChars(str);
83580 return !decStr.match(protocol.UNRESERVED) ? str : decStr;
83581 }
83582 if (components.scheme) components.scheme = String(components.scheme).replace(protocol.PCT_ENCODED, decodeUnreserved).toLowerCase().replace(protocol.NOT_SCHEME, "");
83583 if (components.userinfo !== undefined) components.userinfo = String(components.userinfo).replace(protocol.PCT_ENCODED, decodeUnreserved).replace(protocol.NOT_USERINFO, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase);
83584 if (components.host !== undefined) components.host = String(components.host).replace(protocol.PCT_ENCODED, decodeUnreserved).toLowerCase().replace(protocol.NOT_HOST, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase);
83585 if (components.path !== undefined) components.path = String(components.path).replace(protocol.PCT_ENCODED, decodeUnreserved).replace(components.scheme ? protocol.NOT_PATH : protocol.NOT_PATH_NOSCHEME, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase);
83586 if (components.query !== undefined) components.query = String(components.query).replace(protocol.PCT_ENCODED, decodeUnreserved).replace(protocol.NOT_QUERY, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase);
83587 if (components.fragment !== undefined) components.fragment = String(components.fragment).replace(protocol.PCT_ENCODED, decodeUnreserved).replace(protocol.NOT_FRAGMENT, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase);
83588 return components;
83589}
83590
83591function _stripLeadingZeros(str) {
83592 return str.replace(/^0*(.*)/, "$1") || "0";
83593}
83594function _normalizeIPv4(host, protocol) {
83595 var matches = host.match(protocol.IPV4ADDRESS) || [];
83596
83597 var _matches = slicedToArray(matches, 2),
83598 address = _matches[1];
83599
83600 if (address) {
83601 return address.split(".").map(_stripLeadingZeros).join(".");
83602 } else {
83603 return host;
83604 }
83605}
83606function _normalizeIPv6(host, protocol) {
83607 var matches = host.match(protocol.IPV6ADDRESS) || [];
83608
83609 var _matches2 = slicedToArray(matches, 3),
83610 address = _matches2[1],
83611 zone = _matches2[2];
83612
83613 if (address) {
83614 var _address$toLowerCase$ = address.toLowerCase().split('::').reverse(),
83615 _address$toLowerCase$2 = slicedToArray(_address$toLowerCase$, 2),
83616 last = _address$toLowerCase$2[0],
83617 first = _address$toLowerCase$2[1];
83618
83619 var firstFields = first ? first.split(":").map(_stripLeadingZeros) : [];
83620 var lastFields = last.split(":").map(_stripLeadingZeros);
83621 var isLastFieldIPv4Address = protocol.IPV4ADDRESS.test(lastFields[lastFields.length - 1]);
83622 var fieldCount = isLastFieldIPv4Address ? 7 : 8;
83623 var lastFieldsStart = lastFields.length - fieldCount;
83624 var fields = Array(fieldCount);
83625 for (var x = 0; x < fieldCount; ++x) {
83626 fields[x] = firstFields[x] || lastFields[lastFieldsStart + x] || '';
83627 }
83628 if (isLastFieldIPv4Address) {
83629 fields[fieldCount - 1] = _normalizeIPv4(fields[fieldCount - 1], protocol);
83630 }
83631 var allZeroFields = fields.reduce(function (acc, field, index) {
83632 if (!field || field === "0") {
83633 var lastLongest = acc[acc.length - 1];
83634 if (lastLongest && lastLongest.index + lastLongest.length === index) {
83635 lastLongest.length++;
83636 } else {
83637 acc.push({ index: index, length: 1 });
83638 }
83639 }
83640 return acc;
83641 }, []);
83642 var longestZeroFields = allZeroFields.sort(function (a, b) {
83643 return b.length - a.length;
83644 })[0];
83645 var newHost = void 0;
83646 if (longestZeroFields && longestZeroFields.length > 1) {
83647 var newFirst = fields.slice(0, longestZeroFields.index);
83648 var newLast = fields.slice(longestZeroFields.index + longestZeroFields.length);
83649 newHost = newFirst.join(":") + "::" + newLast.join(":");
83650 } else {
83651 newHost = fields.join(":");
83652 }
83653 if (zone) {
83654 newHost += "%" + zone;
83655 }
83656 return newHost;
83657 } else {
83658 return host;
83659 }
83660}
83661var URI_PARSE = /^(?:([^:\/?#]+):)?(?:\/\/((?:([^\/?#@]*)@)?(\[[^\/?#\]]+\]|[^\/?#:]*)(?:\:(\d*))?))?([^?#]*)(?:\?([^#]*))?(?:#((?:.|\n|\r)*))?/i;
83662var NO_MATCH_IS_UNDEFINED = "".match(/(){0}/)[1] === undefined;
83663function parse(uriString) {
83664 var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
83665
83666 var components = {};
83667 var protocol = options.iri !== false ? IRI_PROTOCOL : URI_PROTOCOL;
83668 if (options.reference === "suffix") uriString = (options.scheme ? options.scheme + ":" : "") + "//" + uriString;
83669 var matches = uriString.match(URI_PARSE);
83670 if (matches) {
83671 if (NO_MATCH_IS_UNDEFINED) {
83672 //store each component
83673 components.scheme = matches[1];
83674 components.userinfo = matches[3];
83675 components.host = matches[4];
83676 components.port = parseInt(matches[5], 10);
83677 components.path = matches[6] || "";
83678 components.query = matches[7];
83679 components.fragment = matches[8];
83680 //fix port number
83681 if (isNaN(components.port)) {
83682 components.port = matches[5];
83683 }
83684 } else {
83685 //IE FIX for improper RegExp matching
83686 //store each component
83687 components.scheme = matches[1] || undefined;
83688 components.userinfo = uriString.indexOf("@") !== -1 ? matches[3] : undefined;
83689 components.host = uriString.indexOf("//") !== -1 ? matches[4] : undefined;
83690 components.port = parseInt(matches[5], 10);
83691 components.path = matches[6] || "";
83692 components.query = uriString.indexOf("?") !== -1 ? matches[7] : undefined;
83693 components.fragment = uriString.indexOf("#") !== -1 ? matches[8] : undefined;
83694 //fix port number
83695 if (isNaN(components.port)) {
83696 components.port = uriString.match(/\/\/(?:.|\n)*\:(?:\/|\?|\#|$)/) ? matches[4] : undefined;
83697 }
83698 }
83699 if (components.host) {
83700 //normalize IP hosts
83701 components.host = _normalizeIPv6(_normalizeIPv4(components.host, protocol), protocol);
83702 }
83703 //determine reference type
83704 if (components.scheme === undefined && components.userinfo === undefined && components.host === undefined && components.port === undefined && !components.path && components.query === undefined) {
83705 components.reference = "same-document";
83706 } else if (components.scheme === undefined) {
83707 components.reference = "relative";
83708 } else if (components.fragment === undefined) {
83709 components.reference = "absolute";
83710 } else {
83711 components.reference = "uri";
83712 }
83713 //check for reference errors
83714 if (options.reference && options.reference !== "suffix" && options.reference !== components.reference) {
83715 components.error = components.error || "URI is not a " + options.reference + " reference.";
83716 }
83717 //find scheme handler
83718 var schemeHandler = SCHEMES[(options.scheme || components.scheme || "").toLowerCase()];
83719 //check if scheme can't handle IRIs
83720 if (!options.unicodeSupport && (!schemeHandler || !schemeHandler.unicodeSupport)) {
83721 //if host component is a domain name
83722 if (components.host && (options.domainHost || schemeHandler && schemeHandler.domainHost)) {
83723 //convert Unicode IDN -> ASCII IDN
83724 try {
83725 components.host = punycode.toASCII(components.host.replace(protocol.PCT_ENCODED, pctDecChars).toLowerCase());
83726 } catch (e) {
83727 components.error = components.error || "Host's domain name can not be converted to ASCII via punycode: " + e;
83728 }
83729 }
83730 //convert IRI -> URI
83731 _normalizeComponentEncoding(components, URI_PROTOCOL);
83732 } else {
83733 //normalize encodings
83734 _normalizeComponentEncoding(components, protocol);
83735 }
83736 //perform scheme specific parsing
83737 if (schemeHandler && schemeHandler.parse) {
83738 schemeHandler.parse(components, options);
83739 }
83740 } else {
83741 components.error = components.error || "URI can not be parsed.";
83742 }
83743 return components;
83744}
83745
83746function _recomposeAuthority(components, options) {
83747 var protocol = options.iri !== false ? IRI_PROTOCOL : URI_PROTOCOL;
83748 var uriTokens = [];
83749 if (components.userinfo !== undefined) {
83750 uriTokens.push(components.userinfo);
83751 uriTokens.push("@");
83752 }
83753 if (components.host !== undefined) {
83754 //normalize IP hosts, add brackets and escape zone separator for IPv6
83755 uriTokens.push(_normalizeIPv6(_normalizeIPv4(String(components.host), protocol), protocol).replace(protocol.IPV6ADDRESS, function (_, $1, $2) {
83756 return "[" + $1 + ($2 ? "%25" + $2 : "") + "]";
83757 }));
83758 }
83759 if (typeof components.port === "number") {
83760 uriTokens.push(":");
83761 uriTokens.push(components.port.toString(10));
83762 }
83763 return uriTokens.length ? uriTokens.join("") : undefined;
83764}
83765
83766var RDS1 = /^\.\.?\//;
83767var RDS2 = /^\/\.(\/|$)/;
83768var RDS3 = /^\/\.\.(\/|$)/;
83769var RDS5 = /^\/?(?:.|\n)*?(?=\/|$)/;
83770function removeDotSegments(input) {
83771 var output = [];
83772 while (input.length) {
83773 if (input.match(RDS1)) {
83774 input = input.replace(RDS1, "");
83775 } else if (input.match(RDS2)) {
83776 input = input.replace(RDS2, "/");
83777 } else if (input.match(RDS3)) {
83778 input = input.replace(RDS3, "/");
83779 output.pop();
83780 } else if (input === "." || input === "..") {
83781 input = "";
83782 } else {
83783 var im = input.match(RDS5);
83784 if (im) {
83785 var s = im[0];
83786 input = input.slice(s.length);
83787 output.push(s);
83788 } else {
83789 throw new Error("Unexpected dot segment condition");
83790 }
83791 }
83792 }
83793 return output.join("");
83794}
83795
83796function serialize(components) {
83797 var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
83798
83799 var protocol = options.iri ? IRI_PROTOCOL : URI_PROTOCOL;
83800 var uriTokens = [];
83801 //find scheme handler
83802 var schemeHandler = SCHEMES[(options.scheme || components.scheme || "").toLowerCase()];
83803 //perform scheme specific serialization
83804 if (schemeHandler && schemeHandler.serialize) schemeHandler.serialize(components, options);
83805 if (components.host) {
83806 //if host component is an IPv6 address
83807 if (protocol.IPV6ADDRESS.test(components.host)) {}
83808 //TODO: normalize IPv6 address as per RFC 5952
83809
83810 //if host component is a domain name
83811 else if (options.domainHost || schemeHandler && schemeHandler.domainHost) {
83812 //convert IDN via punycode
83813 try {
83814 components.host = !options.iri ? punycode.toASCII(components.host.replace(protocol.PCT_ENCODED, pctDecChars).toLowerCase()) : punycode.toUnicode(components.host);
83815 } catch (e) {
83816 components.error = components.error || "Host's domain name can not be converted to " + (!options.iri ? "ASCII" : "Unicode") + " via punycode: " + e;
83817 }
83818 }
83819 }
83820 //normalize encoding
83821 _normalizeComponentEncoding(components, protocol);
83822 if (options.reference !== "suffix" && components.scheme) {
83823 uriTokens.push(components.scheme);
83824 uriTokens.push(":");
83825 }
83826 var authority = _recomposeAuthority(components, options);
83827 if (authority !== undefined) {
83828 if (options.reference !== "suffix") {
83829 uriTokens.push("//");
83830 }
83831 uriTokens.push(authority);
83832 if (components.path && components.path.charAt(0) !== "/") {
83833 uriTokens.push("/");
83834 }
83835 }
83836 if (components.path !== undefined) {
83837 var s = components.path;
83838 if (!options.absolutePath && (!schemeHandler || !schemeHandler.absolutePath)) {
83839 s = removeDotSegments(s);
83840 }
83841 if (authority === undefined) {
83842 s = s.replace(/^\/\//, "/%2F"); //don't allow the path to start with "//"
83843 }
83844 uriTokens.push(s);
83845 }
83846 if (components.query !== undefined) {
83847 uriTokens.push("?");
83848 uriTokens.push(components.query);
83849 }
83850 if (components.fragment !== undefined) {
83851 uriTokens.push("#");
83852 uriTokens.push(components.fragment);
83853 }
83854 return uriTokens.join(""); //merge tokens into a string
83855}
83856
83857function resolveComponents(base, relative) {
83858 var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
83859 var skipNormalization = arguments[3];
83860
83861 var target = {};
83862 if (!skipNormalization) {
83863 base = parse(serialize(base, options), options); //normalize base components
83864 relative = parse(serialize(relative, options), options); //normalize relative components
83865 }
83866 options = options || {};
83867 if (!options.tolerant && relative.scheme) {
83868 target.scheme = relative.scheme;
83869 //target.authority = relative.authority;
83870 target.userinfo = relative.userinfo;
83871 target.host = relative.host;
83872 target.port = relative.port;
83873 target.path = removeDotSegments(relative.path || "");
83874 target.query = relative.query;
83875 } else {
83876 if (relative.userinfo !== undefined || relative.host !== undefined || relative.port !== undefined) {
83877 //target.authority = relative.authority;
83878 target.userinfo = relative.userinfo;
83879 target.host = relative.host;
83880 target.port = relative.port;
83881 target.path = removeDotSegments(relative.path || "");
83882 target.query = relative.query;
83883 } else {
83884 if (!relative.path) {
83885 target.path = base.path;
83886 if (relative.query !== undefined) {
83887 target.query = relative.query;
83888 } else {
83889 target.query = base.query;
83890 }
83891 } else {
83892 if (relative.path.charAt(0) === "/") {
83893 target.path = removeDotSegments(relative.path);
83894 } else {
83895 if ((base.userinfo !== undefined || base.host !== undefined || base.port !== undefined) && !base.path) {
83896 target.path = "/" + relative.path;
83897 } else if (!base.path) {
83898 target.path = relative.path;
83899 } else {
83900 target.path = base.path.slice(0, base.path.lastIndexOf("/") + 1) + relative.path;
83901 }
83902 target.path = removeDotSegments(target.path);
83903 }
83904 target.query = relative.query;
83905 }
83906 //target.authority = base.authority;
83907 target.userinfo = base.userinfo;
83908 target.host = base.host;
83909 target.port = base.port;
83910 }
83911 target.scheme = base.scheme;
83912 }
83913 target.fragment = relative.fragment;
83914 return target;
83915}
83916
83917function resolve(baseURI, relativeURI, options) {
83918 var schemelessOptions = assign({ scheme: 'null' }, options);
83919 return serialize(resolveComponents(parse(baseURI, schemelessOptions), parse(relativeURI, schemelessOptions), schemelessOptions, true), schemelessOptions);
83920}
83921
83922function normalize(uri, options) {
83923 if (typeof uri === "string") {
83924 uri = serialize(parse(uri, options), options);
83925 } else if (typeOf(uri) === "object") {
83926 uri = parse(serialize(uri, options), options);
83927 }
83928 return uri;
83929}
83930
83931function equal(uriA, uriB, options) {
83932 if (typeof uriA === "string") {
83933 uriA = serialize(parse(uriA, options), options);
83934 } else if (typeOf(uriA) === "object") {
83935 uriA = serialize(uriA, options);
83936 }
83937 if (typeof uriB === "string") {
83938 uriB = serialize(parse(uriB, options), options);
83939 } else if (typeOf(uriB) === "object") {
83940 uriB = serialize(uriB, options);
83941 }
83942 return uriA === uriB;
83943}
83944
83945function escapeComponent(str, options) {
83946 return str && str.toString().replace(!options || !options.iri ? URI_PROTOCOL.ESCAPE : IRI_PROTOCOL.ESCAPE, pctEncChar);
83947}
83948
83949function unescapeComponent(str, options) {
83950 return str && str.toString().replace(!options || !options.iri ? URI_PROTOCOL.PCT_ENCODED : IRI_PROTOCOL.PCT_ENCODED, pctDecChars);
83951}
83952
83953var handler = {
83954 scheme: "http",
83955 domainHost: true,
83956 parse: function parse(components, options) {
83957 //report missing host
83958 if (!components.host) {
83959 components.error = components.error || "HTTP URIs must have a host.";
83960 }
83961 return components;
83962 },
83963 serialize: function serialize(components, options) {
83964 //normalize the default port
83965 if (components.port === (String(components.scheme).toLowerCase() !== "https" ? 80 : 443) || components.port === "") {
83966 components.port = undefined;
83967 }
83968 //normalize the empty path
83969 if (!components.path) {
83970 components.path = "/";
83971 }
83972 //NOTE: We do not parse query strings for HTTP URIs
83973 //as WWW Form Url Encoded query strings are part of the HTML4+ spec,
83974 //and not the HTTP spec.
83975 return components;
83976 }
83977};
83978
83979var handler$1 = {
83980 scheme: "https",
83981 domainHost: handler.domainHost,
83982 parse: handler.parse,
83983 serialize: handler.serialize
83984};
83985
83986var O = {};
83987var isIRI = true;
83988//RFC 3986
83989var UNRESERVED$$ = "[A-Za-z0-9\\-\\.\\_\\~" + (isIRI ? "\\xA0-\\u200D\\u2010-\\u2029\\u202F-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF" : "") + "]";
83990var HEXDIG$$ = "[0-9A-Fa-f]"; //case-insensitive
83991var PCT_ENCODED$ = subexp(subexp("%[EFef]" + HEXDIG$$ + "%" + HEXDIG$$ + HEXDIG$$ + "%" + HEXDIG$$ + HEXDIG$$) + "|" + subexp("%[89A-Fa-f]" + HEXDIG$$ + "%" + HEXDIG$$ + HEXDIG$$) + "|" + subexp("%" + HEXDIG$$ + HEXDIG$$)); //expanded
83992//RFC 5322, except these symbols as per RFC 6068: @ : / ? # [ ] & ; =
83993//const ATEXT$$ = "[A-Za-z0-9\\!\\#\\$\\%\\&\\'\\*\\+\\-\\/\\=\\?\\^\\_\\`\\{\\|\\}\\~]";
83994//const WSP$$ = "[\\x20\\x09]";
83995//const OBS_QTEXT$$ = "[\\x01-\\x08\\x0B\\x0C\\x0E-\\x1F\\x7F]"; //(%d1-8 / %d11-12 / %d14-31 / %d127)
83996//const QTEXT$$ = merge("[\\x21\\x23-\\x5B\\x5D-\\x7E]", OBS_QTEXT$$); //%d33 / %d35-91 / %d93-126 / obs-qtext
83997//const VCHAR$$ = "[\\x21-\\x7E]";
83998//const WSP$$ = "[\\x20\\x09]";
83999//const OBS_QP$ = subexp("\\\\" + merge("[\\x00\\x0D\\x0A]", OBS_QTEXT$$)); //%d0 / CR / LF / obs-qtext
84000//const FWS$ = subexp(subexp(WSP$$ + "*" + "\\x0D\\x0A") + "?" + WSP$$ + "+");
84001//const QUOTED_PAIR$ = subexp(subexp("\\\\" + subexp(VCHAR$$ + "|" + WSP$$)) + "|" + OBS_QP$);
84002//const QUOTED_STRING$ = subexp('\\"' + subexp(FWS$ + "?" + QCONTENT$) + "*" + FWS$ + "?" + '\\"');
84003var ATEXT$$ = "[A-Za-z0-9\\!\\$\\%\\'\\*\\+\\-\\^\\_\\`\\{\\|\\}\\~]";
84004var QTEXT$$ = "[\\!\\$\\%\\'\\(\\)\\*\\+\\,\\-\\.0-9\\<\\>A-Z\\x5E-\\x7E]";
84005var VCHAR$$ = merge(QTEXT$$, "[\\\"\\\\]");
84006var SOME_DELIMS$$ = "[\\!\\$\\'\\(\\)\\*\\+\\,\\;\\:\\@]";
84007var UNRESERVED = new RegExp(UNRESERVED$$, "g");
84008var PCT_ENCODED = new RegExp(PCT_ENCODED$, "g");
84009var NOT_LOCAL_PART = new RegExp(merge("[^]", ATEXT$$, "[\\.]", '[\\"]', VCHAR$$), "g");
84010var NOT_HFNAME = new RegExp(merge("[^]", UNRESERVED$$, SOME_DELIMS$$), "g");
84011var NOT_HFVALUE = NOT_HFNAME;
84012function decodeUnreserved(str) {
84013 var decStr = pctDecChars(str);
84014 return !decStr.match(UNRESERVED) ? str : decStr;
84015}
84016var handler$2 = {
84017 scheme: "mailto",
84018 parse: function parse$$1(components, options) {
84019 var mailtoComponents = components;
84020 var to = mailtoComponents.to = mailtoComponents.path ? mailtoComponents.path.split(",") : [];
84021 mailtoComponents.path = undefined;
84022 if (mailtoComponents.query) {
84023 var unknownHeaders = false;
84024 var headers = {};
84025 var hfields = mailtoComponents.query.split("&");
84026 for (var x = 0, xl = hfields.length; x < xl; ++x) {
84027 var hfield = hfields[x].split("=");
84028 switch (hfield[0]) {
84029 case "to":
84030 var toAddrs = hfield[1].split(",");
84031 for (var _x = 0, _xl = toAddrs.length; _x < _xl; ++_x) {
84032 to.push(toAddrs[_x]);
84033 }
84034 break;
84035 case "subject":
84036 mailtoComponents.subject = unescapeComponent(hfield[1], options);
84037 break;
84038 case "body":
84039 mailtoComponents.body = unescapeComponent(hfield[1], options);
84040 break;
84041 default:
84042 unknownHeaders = true;
84043 headers[unescapeComponent(hfield[0], options)] = unescapeComponent(hfield[1], options);
84044 break;
84045 }
84046 }
84047 if (unknownHeaders) mailtoComponents.headers = headers;
84048 }
84049 mailtoComponents.query = undefined;
84050 for (var _x2 = 0, _xl2 = to.length; _x2 < _xl2; ++_x2) {
84051 var addr = to[_x2].split("@");
84052 addr[0] = unescapeComponent(addr[0]);
84053 if (!options.unicodeSupport) {
84054 //convert Unicode IDN -> ASCII IDN
84055 try {
84056 addr[1] = punycode.toASCII(unescapeComponent(addr[1], options).toLowerCase());
84057 } catch (e) {
84058 mailtoComponents.error = mailtoComponents.error || "Email address's domain name can not be converted to ASCII via punycode: " + e;
84059 }
84060 } else {
84061 addr[1] = unescapeComponent(addr[1], options).toLowerCase();
84062 }
84063 to[_x2] = addr.join("@");
84064 }
84065 return mailtoComponents;
84066 },
84067 serialize: function serialize$$1(mailtoComponents, options) {
84068 var components = mailtoComponents;
84069 var to = toArray(mailtoComponents.to);
84070 if (to) {
84071 for (var x = 0, xl = to.length; x < xl; ++x) {
84072 var toAddr = String(to[x]);
84073 var atIdx = toAddr.lastIndexOf("@");
84074 var localPart = toAddr.slice(0, atIdx).replace(PCT_ENCODED, decodeUnreserved).replace(PCT_ENCODED, toUpperCase).replace(NOT_LOCAL_PART, pctEncChar);
84075 var domain = toAddr.slice(atIdx + 1);
84076 //convert IDN via punycode
84077 try {
84078 domain = !options.iri ? punycode.toASCII(unescapeComponent(domain, options).toLowerCase()) : punycode.toUnicode(domain);
84079 } catch (e) {
84080 components.error = components.error || "Email address's domain name can not be converted to " + (!options.iri ? "ASCII" : "Unicode") + " via punycode: " + e;
84081 }
84082 to[x] = localPart + "@" + domain;
84083 }
84084 components.path = to.join(",");
84085 }
84086 var headers = mailtoComponents.headers = mailtoComponents.headers || {};
84087 if (mailtoComponents.subject) headers["subject"] = mailtoComponents.subject;
84088 if (mailtoComponents.body) headers["body"] = mailtoComponents.body;
84089 var fields = [];
84090 for (var name in headers) {
84091 if (headers[name] !== O[name]) {
84092 fields.push(name.replace(PCT_ENCODED, decodeUnreserved).replace(PCT_ENCODED, toUpperCase).replace(NOT_HFNAME, pctEncChar) + "=" + headers[name].replace(PCT_ENCODED, decodeUnreserved).replace(PCT_ENCODED, toUpperCase).replace(NOT_HFVALUE, pctEncChar));
84093 }
84094 }
84095 if (fields.length) {
84096 components.query = fields.join("&");
84097 }
84098 return components;
84099 }
84100};
84101
84102var URN_PARSE = /^([^\:]+)\:(.*)/;
84103//RFC 2141
84104var handler$3 = {
84105 scheme: "urn",
84106 parse: function parse$$1(components, options) {
84107 var matches = components.path && components.path.match(URN_PARSE);
84108 var urnComponents = components;
84109 if (matches) {
84110 var scheme = options.scheme || urnComponents.scheme || "urn";
84111 var nid = matches[1].toLowerCase();
84112 var nss = matches[2];
84113 var urnScheme = scheme + ":" + (options.nid || nid);
84114 var schemeHandler = SCHEMES[urnScheme];
84115 urnComponents.nid = nid;
84116 urnComponents.nss = nss;
84117 urnComponents.path = undefined;
84118 if (schemeHandler) {
84119 urnComponents = schemeHandler.parse(urnComponents, options);
84120 }
84121 } else {
84122 urnComponents.error = urnComponents.error || "URN can not be parsed.";
84123 }
84124 return urnComponents;
84125 },
84126 serialize: function serialize$$1(urnComponents, options) {
84127 var scheme = options.scheme || urnComponents.scheme || "urn";
84128 var nid = urnComponents.nid;
84129 var urnScheme = scheme + ":" + (options.nid || nid);
84130 var schemeHandler = SCHEMES[urnScheme];
84131 if (schemeHandler) {
84132 urnComponents = schemeHandler.serialize(urnComponents, options);
84133 }
84134 var uriComponents = urnComponents;
84135 var nss = urnComponents.nss;
84136 uriComponents.path = (nid || options.nid) + ":" + nss;
84137 return uriComponents;
84138 }
84139};
84140
84141var UUID = /^[0-9A-Fa-f]{8}(?:\-[0-9A-Fa-f]{4}){3}\-[0-9A-Fa-f]{12}$/;
84142//RFC 4122
84143var handler$4 = {
84144 scheme: "urn:uuid",
84145 parse: function parse(urnComponents, options) {
84146 var uuidComponents = urnComponents;
84147 uuidComponents.uuid = uuidComponents.nss;
84148 uuidComponents.nss = undefined;
84149 if (!options.tolerant && (!uuidComponents.uuid || !uuidComponents.uuid.match(UUID))) {
84150 uuidComponents.error = uuidComponents.error || "UUID is not valid.";
84151 }
84152 return uuidComponents;
84153 },
84154 serialize: function serialize(uuidComponents, options) {
84155 var urnComponents = uuidComponents;
84156 //normalize UUID
84157 urnComponents.nss = (uuidComponents.uuid || "").toLowerCase();
84158 return urnComponents;
84159 }
84160};
84161
84162SCHEMES[handler.scheme] = handler;
84163SCHEMES[handler$1.scheme] = handler$1;
84164SCHEMES[handler$2.scheme] = handler$2;
84165SCHEMES[handler$3.scheme] = handler$3;
84166SCHEMES[handler$4.scheme] = handler$4;
84167
84168exports.SCHEMES = SCHEMES;
84169exports.pctEncChar = pctEncChar;
84170exports.pctDecChars = pctDecChars;
84171exports.parse = parse;
84172exports.removeDotSegments = removeDotSegments;
84173exports.serialize = serialize;
84174exports.resolveComponents = resolveComponents;
84175exports.resolve = resolve;
84176exports.normalize = normalize;
84177exports.equal = equal;
84178exports.escapeComponent = escapeComponent;
84179exports.unescapeComponent = unescapeComponent;
84180
84181Object.defineProperty(exports, '__esModule', { value: true });
84182
84183})));
84184
84185
84186},{}],393:[function(require,module,exports){
84187// Copyright Joyent, Inc. and other Node contributors.
84188//
84189// Permission is hereby granted, free of charge, to any person obtaining a
84190// copy of this software and associated documentation files (the
84191// "Software"), to deal in the Software without restriction, including
84192// without limitation the rights to use, copy, modify, merge, publish,
84193// distribute, sublicense, and/or sell copies of the Software, and to permit
84194// persons to whom the Software is furnished to do so, subject to the
84195// following conditions:
84196//
84197// The above copyright notice and this permission notice shall be included
84198// in all copies or substantial portions of the Software.
84199//
84200// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
84201// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
84202// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
84203// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
84204// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
84205// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
84206// USE OR OTHER DEALINGS IN THE SOFTWARE.
84207
84208'use strict';
84209
84210var punycode = require('punycode');
84211var util = require('./util');
84212
84213exports.parse = urlParse;
84214exports.resolve = urlResolve;
84215exports.resolveObject = urlResolveObject;
84216exports.format = urlFormat;
84217
84218exports.Url = Url;
84219
84220function Url() {
84221 this.protocol = null;
84222 this.slashes = null;
84223 this.auth = null;
84224 this.host = null;
84225 this.port = null;
84226 this.hostname = null;
84227 this.hash = null;
84228 this.search = null;
84229 this.query = null;
84230 this.pathname = null;
84231 this.path = null;
84232 this.href = null;
84233}
84234
84235// Reference: RFC 3986, RFC 1808, RFC 2396
84236
84237// define these here so at least they only have to be
84238// compiled once on the first module load.
84239var protocolPattern = /^([a-z0-9.+-]+:)/i,
84240 portPattern = /:[0-9]*$/,
84241
84242 // Special case for a simple path URL
84243 simplePathPattern = /^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/,
84244
84245 // RFC 2396: characters reserved for delimiting URLs.
84246 // We actually just auto-escape these.
84247 delims = ['<', '>', '"', '`', ' ', '\r', '\n', '\t'],
84248
84249 // RFC 2396: characters not allowed for various reasons.
84250 unwise = ['{', '}', '|', '\\', '^', '`'].concat(delims),
84251
84252 // Allowed by RFCs, but cause of XSS attacks. Always escape these.
84253 autoEscape = ['\''].concat(unwise),
84254 // Characters that are never ever allowed in a hostname.
84255 // Note that any invalid chars are also handled, but these
84256 // are the ones that are *expected* to be seen, so we fast-path
84257 // them.
84258 nonHostChars = ['%', '/', '?', ';', '#'].concat(autoEscape),
84259 hostEndingChars = ['/', '?', '#'],
84260 hostnameMaxLen = 255,
84261 hostnamePartPattern = /^[+a-z0-9A-Z_-]{0,63}$/,
84262 hostnamePartStart = /^([+a-z0-9A-Z_-]{0,63})(.*)$/,
84263 // protocols that can allow "unsafe" and "unwise" chars.
84264 unsafeProtocol = {
84265 'javascript': true,
84266 'javascript:': true
84267 },
84268 // protocols that never have a hostname.
84269 hostlessProtocol = {
84270 'javascript': true,
84271 'javascript:': true
84272 },
84273 // protocols that always contain a // bit.
84274 slashedProtocol = {
84275 'http': true,
84276 'https': true,
84277 'ftp': true,
84278 'gopher': true,
84279 'file': true,
84280 'http:': true,
84281 'https:': true,
84282 'ftp:': true,
84283 'gopher:': true,
84284 'file:': true
84285 },
84286 querystring = require('querystring');
84287
84288function urlParse(url, parseQueryString, slashesDenoteHost) {
84289 if (url && util.isObject(url) && url instanceof Url) return url;
84290
84291 var u = new Url;
84292 u.parse(url, parseQueryString, slashesDenoteHost);
84293 return u;
84294}
84295
84296Url.prototype.parse = function(url, parseQueryString, slashesDenoteHost) {
84297 if (!util.isString(url)) {
84298 throw new TypeError("Parameter 'url' must be a string, not " + typeof url);
84299 }
84300
84301 // Copy chrome, IE, opera backslash-handling behavior.
84302 // Back slashes before the query string get converted to forward slashes
84303 // See: https://code.google.com/p/chromium/issues/detail?id=25916
84304 var queryIndex = url.indexOf('?'),
84305 splitter =
84306 (queryIndex !== -1 && queryIndex < url.indexOf('#')) ? '?' : '#',
84307 uSplit = url.split(splitter),
84308 slashRegex = /\\/g;
84309 uSplit[0] = uSplit[0].replace(slashRegex, '/');
84310 url = uSplit.join(splitter);
84311
84312 var rest = url;
84313
84314 // trim before proceeding.
84315 // This is to support parse stuff like " http://foo.com \n"
84316 rest = rest.trim();
84317
84318 if (!slashesDenoteHost && url.split('#').length === 1) {
84319 // Try fast path regexp
84320 var simplePath = simplePathPattern.exec(rest);
84321 if (simplePath) {
84322 this.path = rest;
84323 this.href = rest;
84324 this.pathname = simplePath[1];
84325 if (simplePath[2]) {
84326 this.search = simplePath[2];
84327 if (parseQueryString) {
84328 this.query = querystring.parse(this.search.substr(1));
84329 } else {
84330 this.query = this.search.substr(1);
84331 }
84332 } else if (parseQueryString) {
84333 this.search = '';
84334 this.query = {};
84335 }
84336 return this;
84337 }
84338 }
84339
84340 var proto = protocolPattern.exec(rest);
84341 if (proto) {
84342 proto = proto[0];
84343 var lowerProto = proto.toLowerCase();
84344 this.protocol = lowerProto;
84345 rest = rest.substr(proto.length);
84346 }
84347
84348 // figure out if it's got a host
84349 // user@server is *always* interpreted as a hostname, and url
84350 // resolution will treat //foo/bar as host=foo,path=bar because that's
84351 // how the browser resolves relative URLs.
84352 if (slashesDenoteHost || proto || rest.match(/^\/\/[^@\/]+@[^@\/]+/)) {
84353 var slashes = rest.substr(0, 2) === '//';
84354 if (slashes && !(proto && hostlessProtocol[proto])) {
84355 rest = rest.substr(2);
84356 this.slashes = true;
84357 }
84358 }
84359
84360 if (!hostlessProtocol[proto] &&
84361 (slashes || (proto && !slashedProtocol[proto]))) {
84362
84363 // there's a hostname.
84364 // the first instance of /, ?, ;, or # ends the host.
84365 //
84366 // If there is an @ in the hostname, then non-host chars *are* allowed
84367 // to the left of the last @ sign, unless some host-ending character
84368 // comes *before* the @-sign.
84369 // URLs are obnoxious.
84370 //
84371 // ex:
84372 // http://a@b@c/ => user:a@b host:c
84373 // http://a@b?@c => user:a host:c path:/?@c
84374
84375 // v0.12 TODO(isaacs): This is not quite how Chrome does things.
84376 // Review our test case against browsers more comprehensively.
84377
84378 // find the first instance of any hostEndingChars
84379 var hostEnd = -1;
84380 for (var i = 0; i < hostEndingChars.length; i++) {
84381 var hec = rest.indexOf(hostEndingChars[i]);
84382 if (hec !== -1 && (hostEnd === -1 || hec < hostEnd))
84383 hostEnd = hec;
84384 }
84385
84386 // at this point, either we have an explicit point where the
84387 // auth portion cannot go past, or the last @ char is the decider.
84388 var auth, atSign;
84389 if (hostEnd === -1) {
84390 // atSign can be anywhere.
84391 atSign = rest.lastIndexOf('@');
84392 } else {
84393 // atSign must be in auth portion.
84394 // http://a@b/c@d => host:b auth:a path:/c@d
84395 atSign = rest.lastIndexOf('@', hostEnd);
84396 }
84397
84398 // Now we have a portion which is definitely the auth.
84399 // Pull that off.
84400 if (atSign !== -1) {
84401 auth = rest.slice(0, atSign);
84402 rest = rest.slice(atSign + 1);
84403 this.auth = decodeURIComponent(auth);
84404 }
84405
84406 // the host is the remaining to the left of the first non-host char
84407 hostEnd = -1;
84408 for (var i = 0; i < nonHostChars.length; i++) {
84409 var hec = rest.indexOf(nonHostChars[i]);
84410 if (hec !== -1 && (hostEnd === -1 || hec < hostEnd))
84411 hostEnd = hec;
84412 }
84413 // if we still have not hit it, then the entire thing is a host.
84414 if (hostEnd === -1)
84415 hostEnd = rest.length;
84416
84417 this.host = rest.slice(0, hostEnd);
84418 rest = rest.slice(hostEnd);
84419
84420 // pull out port.
84421 this.parseHost();
84422
84423 // we've indicated that there is a hostname,
84424 // so even if it's empty, it has to be present.
84425 this.hostname = this.hostname || '';
84426
84427 // if hostname begins with [ and ends with ]
84428 // assume that it's an IPv6 address.
84429 var ipv6Hostname = this.hostname[0] === '[' &&
84430 this.hostname[this.hostname.length - 1] === ']';
84431
84432 // validate a little.
84433 if (!ipv6Hostname) {
84434 var hostparts = this.hostname.split(/\./);
84435 for (var i = 0, l = hostparts.length; i < l; i++) {
84436 var part = hostparts[i];
84437 if (!part) continue;
84438 if (!part.match(hostnamePartPattern)) {
84439 var newpart = '';
84440 for (var j = 0, k = part.length; j < k; j++) {
84441 if (part.charCodeAt(j) > 127) {
84442 // we replace non-ASCII char with a temporary placeholder
84443 // we need this to make sure size of hostname is not
84444 // broken by replacing non-ASCII by nothing
84445 newpart += 'x';
84446 } else {
84447 newpart += part[j];
84448 }
84449 }
84450 // we test again with ASCII char only
84451 if (!newpart.match(hostnamePartPattern)) {
84452 var validParts = hostparts.slice(0, i);
84453 var notHost = hostparts.slice(i + 1);
84454 var bit = part.match(hostnamePartStart);
84455 if (bit) {
84456 validParts.push(bit[1]);
84457 notHost.unshift(bit[2]);
84458 }
84459 if (notHost.length) {
84460 rest = '/' + notHost.join('.') + rest;
84461 }
84462 this.hostname = validParts.join('.');
84463 break;
84464 }
84465 }
84466 }
84467 }
84468
84469 if (this.hostname.length > hostnameMaxLen) {
84470 this.hostname = '';
84471 } else {
84472 // hostnames are always lower case.
84473 this.hostname = this.hostname.toLowerCase();
84474 }
84475
84476 if (!ipv6Hostname) {
84477 // IDNA Support: Returns a punycoded representation of "domain".
84478 // It only converts parts of the domain name that
84479 // have non-ASCII characters, i.e. it doesn't matter if
84480 // you call it with a domain that already is ASCII-only.
84481 this.hostname = punycode.toASCII(this.hostname);
84482 }
84483
84484 var p = this.port ? ':' + this.port : '';
84485 var h = this.hostname || '';
84486 this.host = h + p;
84487 this.href += this.host;
84488
84489 // strip [ and ] from the hostname
84490 // the host field still retains them, though
84491 if (ipv6Hostname) {
84492 this.hostname = this.hostname.substr(1, this.hostname.length - 2);
84493 if (rest[0] !== '/') {
84494 rest = '/' + rest;
84495 }
84496 }
84497 }
84498
84499 // now rest is set to the post-host stuff.
84500 // chop off any delim chars.
84501 if (!unsafeProtocol[lowerProto]) {
84502
84503 // First, make 100% sure that any "autoEscape" chars get
84504 // escaped, even if encodeURIComponent doesn't think they
84505 // need to be.
84506 for (var i = 0, l = autoEscape.length; i < l; i++) {
84507 var ae = autoEscape[i];
84508 if (rest.indexOf(ae) === -1)
84509 continue;
84510 var esc = encodeURIComponent(ae);
84511 if (esc === ae) {
84512 esc = escape(ae);
84513 }
84514 rest = rest.split(ae).join(esc);
84515 }
84516 }
84517
84518
84519 // chop off from the tail first.
84520 var hash = rest.indexOf('#');
84521 if (hash !== -1) {
84522 // got a fragment string.
84523 this.hash = rest.substr(hash);
84524 rest = rest.slice(0, hash);
84525 }
84526 var qm = rest.indexOf('?');
84527 if (qm !== -1) {
84528 this.search = rest.substr(qm);
84529 this.query = rest.substr(qm + 1);
84530 if (parseQueryString) {
84531 this.query = querystring.parse(this.query);
84532 }
84533 rest = rest.slice(0, qm);
84534 } else if (parseQueryString) {
84535 // no query string, but parseQueryString still requested
84536 this.search = '';
84537 this.query = {};
84538 }
84539 if (rest) this.pathname = rest;
84540 if (slashedProtocol[lowerProto] &&
84541 this.hostname && !this.pathname) {
84542 this.pathname = '/';
84543 }
84544
84545 //to support http.request
84546 if (this.pathname || this.search) {
84547 var p = this.pathname || '';
84548 var s = this.search || '';
84549 this.path = p + s;
84550 }
84551
84552 // finally, reconstruct the href based on what has been validated.
84553 this.href = this.format();
84554 return this;
84555};
84556
84557// format a parsed object into a url string
84558function urlFormat(obj) {
84559 // ensure it's an object, and not a string url.
84560 // If it's an obj, this is a no-op.
84561 // this way, you can call url_format() on strings
84562 // to clean up potentially wonky urls.
84563 if (util.isString(obj)) obj = urlParse(obj);
84564 if (!(obj instanceof Url)) return Url.prototype.format.call(obj);
84565 return obj.format();
84566}
84567
84568Url.prototype.format = function() {
84569 var auth = this.auth || '';
84570 if (auth) {
84571 auth = encodeURIComponent(auth);
84572 auth = auth.replace(/%3A/i, ':');
84573 auth += '@';
84574 }
84575
84576 var protocol = this.protocol || '',
84577 pathname = this.pathname || '',
84578 hash = this.hash || '',
84579 host = false,
84580 query = '';
84581
84582 if (this.host) {
84583 host = auth + this.host;
84584 } else if (this.hostname) {
84585 host = auth + (this.hostname.indexOf(':') === -1 ?
84586 this.hostname :
84587 '[' + this.hostname + ']');
84588 if (this.port) {
84589 host += ':' + this.port;
84590 }
84591 }
84592
84593 if (this.query &&
84594 util.isObject(this.query) &&
84595 Object.keys(this.query).length) {
84596 query = querystring.stringify(this.query);
84597 }
84598
84599 var search = this.search || (query && ('?' + query)) || '';
84600
84601 if (protocol && protocol.substr(-1) !== ':') protocol += ':';
84602
84603 // only the slashedProtocols get the //. Not mailto:, xmpp:, etc.
84604 // unless they had them to begin with.
84605 if (this.slashes ||
84606 (!protocol || slashedProtocol[protocol]) && host !== false) {
84607 host = '//' + (host || '');
84608 if (pathname && pathname.charAt(0) !== '/') pathname = '/' + pathname;
84609 } else if (!host) {
84610 host = '';
84611 }
84612
84613 if (hash && hash.charAt(0) !== '#') hash = '#' + hash;
84614 if (search && search.charAt(0) !== '?') search = '?' + search;
84615
84616 pathname = pathname.replace(/[?#]/g, function(match) {
84617 return encodeURIComponent(match);
84618 });
84619 search = search.replace('#', '%23');
84620
84621 return protocol + host + pathname + search + hash;
84622};
84623
84624function urlResolve(source, relative) {
84625 return urlParse(source, false, true).resolve(relative);
84626}
84627
84628Url.prototype.resolve = function(relative) {
84629 return this.resolveObject(urlParse(relative, false, true)).format();
84630};
84631
84632function urlResolveObject(source, relative) {
84633 if (!source) return relative;
84634 return urlParse(source, false, true).resolveObject(relative);
84635}
84636
84637Url.prototype.resolveObject = function(relative) {
84638 if (util.isString(relative)) {
84639 var rel = new Url();
84640 rel.parse(relative, false, true);
84641 relative = rel;
84642 }
84643
84644 var result = new Url();
84645 var tkeys = Object.keys(this);
84646 for (var tk = 0; tk < tkeys.length; tk++) {
84647 var tkey = tkeys[tk];
84648 result[tkey] = this[tkey];
84649 }
84650
84651 // hash is always overridden, no matter what.
84652 // even href="" will remove it.
84653 result.hash = relative.hash;
84654
84655 // if the relative url is empty, then there's nothing left to do here.
84656 if (relative.href === '') {
84657 result.href = result.format();
84658 return result;
84659 }
84660
84661 // hrefs like //foo/bar always cut to the protocol.
84662 if (relative.slashes && !relative.protocol) {
84663 // take everything except the protocol from relative
84664 var rkeys = Object.keys(relative);
84665 for (var rk = 0; rk < rkeys.length; rk++) {
84666 var rkey = rkeys[rk];
84667 if (rkey !== 'protocol')
84668 result[rkey] = relative[rkey];
84669 }
84670
84671 //urlParse appends trailing / to urls like http://www.example.com
84672 if (slashedProtocol[result.protocol] &&
84673 result.hostname && !result.pathname) {
84674 result.path = result.pathname = '/';
84675 }
84676
84677 result.href = result.format();
84678 return result;
84679 }
84680
84681 if (relative.protocol && relative.protocol !== result.protocol) {
84682 // if it's a known url protocol, then changing
84683 // the protocol does weird things
84684 // first, if it's not file:, then we MUST have a host,
84685 // and if there was a path
84686 // to begin with, then we MUST have a path.
84687 // if it is file:, then the host is dropped,
84688 // because that's known to be hostless.
84689 // anything else is assumed to be absolute.
84690 if (!slashedProtocol[relative.protocol]) {
84691 var keys = Object.keys(relative);
84692 for (var v = 0; v < keys.length; v++) {
84693 var k = keys[v];
84694 result[k] = relative[k];
84695 }
84696 result.href = result.format();
84697 return result;
84698 }
84699
84700 result.protocol = relative.protocol;
84701 if (!relative.host && !hostlessProtocol[relative.protocol]) {
84702 var relPath = (relative.pathname || '').split('/');
84703 while (relPath.length && !(relative.host = relPath.shift()));
84704 if (!relative.host) relative.host = '';
84705 if (!relative.hostname) relative.hostname = '';
84706 if (relPath[0] !== '') relPath.unshift('');
84707 if (relPath.length < 2) relPath.unshift('');
84708 result.pathname = relPath.join('/');
84709 } else {
84710 result.pathname = relative.pathname;
84711 }
84712 result.search = relative.search;
84713 result.query = relative.query;
84714 result.host = relative.host || '';
84715 result.auth = relative.auth;
84716 result.hostname = relative.hostname || relative.host;
84717 result.port = relative.port;
84718 // to support http.request
84719 if (result.pathname || result.search) {
84720 var p = result.pathname || '';
84721 var s = result.search || '';
84722 result.path = p + s;
84723 }
84724 result.slashes = result.slashes || relative.slashes;
84725 result.href = result.format();
84726 return result;
84727 }
84728
84729 var isSourceAbs = (result.pathname && result.pathname.charAt(0) === '/'),
84730 isRelAbs = (
84731 relative.host ||
84732 relative.pathname && relative.pathname.charAt(0) === '/'
84733 ),
84734 mustEndAbs = (isRelAbs || isSourceAbs ||
84735 (result.host && relative.pathname)),
84736 removeAllDots = mustEndAbs,
84737 srcPath = result.pathname && result.pathname.split('/') || [],
84738 relPath = relative.pathname && relative.pathname.split('/') || [],
84739 psychotic = result.protocol && !slashedProtocol[result.protocol];
84740
84741 // if the url is a non-slashed url, then relative
84742 // links like ../.. should be able
84743 // to crawl up to the hostname, as well. This is strange.
84744 // result.protocol has already been set by now.
84745 // Later on, put the first path part into the host field.
84746 if (psychotic) {
84747 result.hostname = '';
84748 result.port = null;
84749 if (result.host) {
84750 if (srcPath[0] === '') srcPath[0] = result.host;
84751 else srcPath.unshift(result.host);
84752 }
84753 result.host = '';
84754 if (relative.protocol) {
84755 relative.hostname = null;
84756 relative.port = null;
84757 if (relative.host) {
84758 if (relPath[0] === '') relPath[0] = relative.host;
84759 else relPath.unshift(relative.host);
84760 }
84761 relative.host = null;
84762 }
84763 mustEndAbs = mustEndAbs && (relPath[0] === '' || srcPath[0] === '');
84764 }
84765
84766 if (isRelAbs) {
84767 // it's absolute.
84768 result.host = (relative.host || relative.host === '') ?
84769 relative.host : result.host;
84770 result.hostname = (relative.hostname || relative.hostname === '') ?
84771 relative.hostname : result.hostname;
84772 result.search = relative.search;
84773 result.query = relative.query;
84774 srcPath = relPath;
84775 // fall through to the dot-handling below.
84776 } else if (relPath.length) {
84777 // it's relative
84778 // throw away the existing file, and take the new path instead.
84779 if (!srcPath) srcPath = [];
84780 srcPath.pop();
84781 srcPath = srcPath.concat(relPath);
84782 result.search = relative.search;
84783 result.query = relative.query;
84784 } else if (!util.isNullOrUndefined(relative.search)) {
84785 // just pull out the search.
84786 // like href='?foo'.
84787 // Put this after the other two cases because it simplifies the booleans
84788 if (psychotic) {
84789 result.hostname = result.host = srcPath.shift();
84790 //occationaly the auth can get stuck only in host
84791 //this especially happens in cases like
84792 //url.resolveObject('mailto:local1@domain1', 'local2@domain2')
84793 var authInHost = result.host && result.host.indexOf('@') > 0 ?
84794 result.host.split('@') : false;
84795 if (authInHost) {
84796 result.auth = authInHost.shift();
84797 result.host = result.hostname = authInHost.shift();
84798 }
84799 }
84800 result.search = relative.search;
84801 result.query = relative.query;
84802 //to support http.request
84803 if (!util.isNull(result.pathname) || !util.isNull(result.search)) {
84804 result.path = (result.pathname ? result.pathname : '') +
84805 (result.search ? result.search : '');
84806 }
84807 result.href = result.format();
84808 return result;
84809 }
84810
84811 if (!srcPath.length) {
84812 // no path at all. easy.
84813 // we've already handled the other stuff above.
84814 result.pathname = null;
84815 //to support http.request
84816 if (result.search) {
84817 result.path = '/' + result.search;
84818 } else {
84819 result.path = null;
84820 }
84821 result.href = result.format();
84822 return result;
84823 }
84824
84825 // if a url ENDs in . or .., then it must get a trailing slash.
84826 // however, if it ends in anything else non-slashy,
84827 // then it must NOT get a trailing slash.
84828 var last = srcPath.slice(-1)[0];
84829 var hasTrailingSlash = (
84830 (result.host || relative.host || srcPath.length > 1) &&
84831 (last === '.' || last === '..') || last === '');
84832
84833 // strip single dots, resolve double dots to parent dir
84834 // if the path tries to go above the root, `up` ends up > 0
84835 var up = 0;
84836 for (var i = srcPath.length; i >= 0; i--) {
84837 last = srcPath[i];
84838 if (last === '.') {
84839 srcPath.splice(i, 1);
84840 } else if (last === '..') {
84841 srcPath.splice(i, 1);
84842 up++;
84843 } else if (up) {
84844 srcPath.splice(i, 1);
84845 up--;
84846 }
84847 }
84848
84849 // if the path is allowed to go above the root, restore leading ..s
84850 if (!mustEndAbs && !removeAllDots) {
84851 for (; up--; up) {
84852 srcPath.unshift('..');
84853 }
84854 }
84855
84856 if (mustEndAbs && srcPath[0] !== '' &&
84857 (!srcPath[0] || srcPath[0].charAt(0) !== '/')) {
84858 srcPath.unshift('');
84859 }
84860
84861 if (hasTrailingSlash && (srcPath.join('/').substr(-1) !== '/')) {
84862 srcPath.push('');
84863 }
84864
84865 var isAbsolute = srcPath[0] === '' ||
84866 (srcPath[0] && srcPath[0].charAt(0) === '/');
84867
84868 // put the host back
84869 if (psychotic) {
84870 result.hostname = result.host = isAbsolute ? '' :
84871 srcPath.length ? srcPath.shift() : '';
84872 //occationaly the auth can get stuck only in host
84873 //this especially happens in cases like
84874 //url.resolveObject('mailto:local1@domain1', 'local2@domain2')
84875 var authInHost = result.host && result.host.indexOf('@') > 0 ?
84876 result.host.split('@') : false;
84877 if (authInHost) {
84878 result.auth = authInHost.shift();
84879 result.host = result.hostname = authInHost.shift();
84880 }
84881 }
84882
84883 mustEndAbs = mustEndAbs || (result.host && srcPath.length);
84884
84885 if (mustEndAbs && !isAbsolute) {
84886 srcPath.unshift('');
84887 }
84888
84889 if (!srcPath.length) {
84890 result.pathname = null;
84891 result.path = null;
84892 } else {
84893 result.pathname = srcPath.join('/');
84894 }
84895
84896 //to support request.http
84897 if (!util.isNull(result.pathname) || !util.isNull(result.search)) {
84898 result.path = (result.pathname ? result.pathname : '') +
84899 (result.search ? result.search : '');
84900 }
84901 result.auth = relative.auth || result.auth;
84902 result.slashes = result.slashes || relative.slashes;
84903 result.href = result.format();
84904 return result;
84905};
84906
84907Url.prototype.parseHost = function() {
84908 var host = this.host;
84909 var port = portPattern.exec(host);
84910 if (port) {
84911 port = port[0];
84912 if (port !== ':') {
84913 this.port = port.substr(1);
84914 }
84915 host = host.substr(0, host.length - port.length);
84916 }
84917 if (host) this.hostname = host;
84918};
84919
84920},{"./util":394,"punycode":274,"querystring":277}],394:[function(require,module,exports){
84921'use strict';
84922
84923module.exports = {
84924 isString: function(arg) {
84925 return typeof(arg) === 'string';
84926 },
84927 isObject: function(arg) {
84928 return typeof(arg) === 'object' && arg !== null;
84929 },
84930 isNull: function(arg) {
84931 return arg === null;
84932 },
84933 isNullOrUndefined: function(arg) {
84934 return arg == null;
84935 }
84936};
84937
84938},{}],395:[function(require,module,exports){
84939(function (global){
84940
84941/**
84942 * Module exports.
84943 */
84944
84945module.exports = deprecate;
84946
84947/**
84948 * Mark that a method should not be used.
84949 * Returns a modified function which warns once by default.
84950 *
84951 * If `localStorage.noDeprecation = true` is set, then it is a no-op.
84952 *
84953 * If `localStorage.throwDeprecation = true` is set, then deprecated functions
84954 * will throw an Error when invoked.
84955 *
84956 * If `localStorage.traceDeprecation = true` is set, then deprecated functions
84957 * will invoke `console.trace()` instead of `console.error()`.
84958 *
84959 * @param {Function} fn - the function to deprecate
84960 * @param {String} msg - the string to print to the console when `fn` is invoked
84961 * @returns {Function} a new "deprecated" version of `fn`
84962 * @api public
84963 */
84964
84965function deprecate (fn, msg) {
84966 if (config('noDeprecation')) {
84967 return fn;
84968 }
84969
84970 var warned = false;
84971 function deprecated() {
84972 if (!warned) {
84973 if (config('throwDeprecation')) {
84974 throw new Error(msg);
84975 } else if (config('traceDeprecation')) {
84976 console.trace(msg);
84977 } else {
84978 console.warn(msg);
84979 }
84980 warned = true;
84981 }
84982 return fn.apply(this, arguments);
84983 }
84984
84985 return deprecated;
84986}
84987
84988/**
84989 * Checks `localStorage` for boolean values for the given `name`.
84990 *
84991 * @param {String} name
84992 * @returns {Boolean}
84993 * @api private
84994 */
84995
84996function config (name) {
84997 // accessing global.localStorage can trigger a DOMException in sandboxed iframes
84998 try {
84999 if (!global.localStorage) return false;
85000 } catch (_) {
85001 return false;
85002 }
85003 var val = global.localStorage[name];
85004 if (null == val) return false;
85005 return String(val).toLowerCase() === 'true';
85006}
85007
85008}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
85009},{}],396:[function(require,module,exports){
85010arguments[4][70][0].apply(exports,arguments)
85011},{"dup":70}],397:[function(require,module,exports){
85012arguments[4][71][0].apply(exports,arguments)
85013},{"./support/isBuffer":396,"_process":265,"dup":71,"inherits":210}],398:[function(require,module,exports){
85014/**
85015 * Convert array of 16 byte values to UUID string format of the form:
85016 * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
85017 */
85018var byteToHex = [];
85019for (var i = 0; i < 256; ++i) {
85020 byteToHex[i] = (i + 0x100).toString(16).substr(1);
85021}
85022
85023function bytesToUuid(buf, offset) {
85024 var i = offset || 0;
85025 var bth = byteToHex;
85026 // join used to fix memory issue caused by concatenation: https://bugs.chromium.org/p/v8/issues/detail?id=3175#c4
85027 return ([bth[buf[i++]], bth[buf[i++]],
85028 bth[buf[i++]], bth[buf[i++]], '-',
85029 bth[buf[i++]], bth[buf[i++]], '-',
85030 bth[buf[i++]], bth[buf[i++]], '-',
85031 bth[buf[i++]], bth[buf[i++]], '-',
85032 bth[buf[i++]], bth[buf[i++]],
85033 bth[buf[i++]], bth[buf[i++]],
85034 bth[buf[i++]], bth[buf[i++]]]).join('');
85035}
85036
85037module.exports = bytesToUuid;
85038
85039},{}],399:[function(require,module,exports){
85040// Unique ID creation requires a high quality random # generator. In the
85041// browser this is a little complicated due to unknown quality of Math.random()
85042// and inconsistent support for the `crypto` API. We do the best we can via
85043// feature-detection
85044
85045// getRandomValues needs to be invoked in a context where "this" is a Crypto
85046// implementation. Also, find the complete implementation of crypto on IE11.
85047var getRandomValues = (typeof(crypto) != 'undefined' && crypto.getRandomValues && crypto.getRandomValues.bind(crypto)) ||
85048 (typeof(msCrypto) != 'undefined' && typeof window.msCrypto.getRandomValues == 'function' && msCrypto.getRandomValues.bind(msCrypto));
85049
85050if (getRandomValues) {
85051 // WHATWG crypto RNG - http://wiki.whatwg.org/wiki/Crypto
85052 var rnds8 = new Uint8Array(16); // eslint-disable-line no-undef
85053
85054 module.exports = function whatwgRNG() {
85055 getRandomValues(rnds8);
85056 return rnds8;
85057 };
85058} else {
85059 // Math.random()-based (RNG)
85060 //
85061 // If all else fails, use Math.random(). It's fast, but is of unspecified
85062 // quality.
85063 var rnds = new Array(16);
85064
85065 module.exports = function mathRNG() {
85066 for (var i = 0, r; i < 16; i++) {
85067 if ((i & 0x03) === 0) r = Math.random() * 0x100000000;
85068 rnds[i] = r >>> ((i & 0x03) << 3) & 0xff;
85069 }
85070
85071 return rnds;
85072 };
85073}
85074
85075},{}],400:[function(require,module,exports){
85076var rng = require('./lib/rng');
85077var bytesToUuid = require('./lib/bytesToUuid');
85078
85079function v4(options, buf, offset) {
85080 var i = buf && offset || 0;
85081
85082 if (typeof(options) == 'string') {
85083 buf = options === 'binary' ? new Array(16) : null;
85084 options = null;
85085 }
85086 options = options || {};
85087
85088 var rnds = options.random || (options.rng || rng)();
85089
85090 // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`
85091 rnds[6] = (rnds[6] & 0x0f) | 0x40;
85092 rnds[8] = (rnds[8] & 0x3f) | 0x80;
85093
85094 // Copy bytes to buffer, if provided
85095 if (buf) {
85096 for (var ii = 0; ii < 16; ++ii) {
85097 buf[i + ii] = rnds[ii];
85098 }
85099 }
85100
85101 return buf || bytesToUuid(rnds);
85102}
85103
85104module.exports = v4;
85105
85106},{"./lib/bytesToUuid":398,"./lib/rng":399}],401:[function(require,module,exports){
85107/*
85108 * verror.js: richer JavaScript errors
85109 */
85110
85111var mod_assertplus = require('assert-plus');
85112var mod_util = require('util');
85113
85114var mod_extsprintf = require('extsprintf');
85115var mod_isError = require('core-util-is').isError;
85116var sprintf = mod_extsprintf.sprintf;
85117
85118/*
85119 * Public interface
85120 */
85121
85122/* So you can 'var VError = require('verror')' */
85123module.exports = VError;
85124/* For compatibility */
85125VError.VError = VError;
85126/* Other exported classes */
85127VError.SError = SError;
85128VError.WError = WError;
85129VError.MultiError = MultiError;
85130
85131/*
85132 * Common function used to parse constructor arguments for VError, WError, and
85133 * SError. Named arguments to this function:
85134 *
85135 * strict force strict interpretation of sprintf arguments, even
85136 * if the options in "argv" don't say so
85137 *
85138 * argv error's constructor arguments, which are to be
85139 * interpreted as described in README.md. For quick
85140 * reference, "argv" has one of the following forms:
85141 *
85142 * [ sprintf_args... ] (argv[0] is a string)
85143 * [ cause, sprintf_args... ] (argv[0] is an Error)
85144 * [ options, sprintf_args... ] (argv[0] is an object)
85145 *
85146 * This function normalizes these forms, producing an object with the following
85147 * properties:
85148 *
85149 * options equivalent to "options" in third form. This will never
85150 * be a direct reference to what the caller passed in
85151 * (i.e., it may be a shallow copy), so it can be freely
85152 * modified.
85153 *
85154 * shortmessage result of sprintf(sprintf_args), taking options.strict
85155 * into account as described in README.md.
85156 */
85157function parseConstructorArguments(args)
85158{
85159 var argv, options, sprintf_args, shortmessage, k;
85160
85161 mod_assertplus.object(args, 'args');
85162 mod_assertplus.bool(args.strict, 'args.strict');
85163 mod_assertplus.array(args.argv, 'args.argv');
85164 argv = args.argv;
85165
85166 /*
85167 * First, figure out which form of invocation we've been given.
85168 */
85169 if (argv.length === 0) {
85170 options = {};
85171 sprintf_args = [];
85172 } else if (mod_isError(argv[0])) {
85173 options = { 'cause': argv[0] };
85174 sprintf_args = argv.slice(1);
85175 } else if (typeof (argv[0]) === 'object') {
85176 options = {};
85177 for (k in argv[0]) {
85178 options[k] = argv[0][k];
85179 }
85180 sprintf_args = argv.slice(1);
85181 } else {
85182 mod_assertplus.string(argv[0],
85183 'first argument to VError, SError, or WError ' +
85184 'constructor must be a string, object, or Error');
85185 options = {};
85186 sprintf_args = argv;
85187 }
85188
85189 /*
85190 * Now construct the error's message.
85191 *
85192 * extsprintf (which we invoke here with our caller's arguments in order
85193 * to construct this Error's message) is strict in its interpretation of
85194 * values to be processed by the "%s" specifier. The value passed to
85195 * extsprintf must actually be a string or something convertible to a
85196 * String using .toString(). Passing other values (notably "null" and
85197 * "undefined") is considered a programmer error. The assumption is
85198 * that if you actually want to print the string "null" or "undefined",
85199 * then that's easy to do that when you're calling extsprintf; on the
85200 * other hand, if you did NOT want that (i.e., there's actually a bug
85201 * where the program assumes some variable is non-null and tries to
85202 * print it, which might happen when constructing a packet or file in
85203 * some specific format), then it's better to stop immediately than
85204 * produce bogus output.
85205 *
85206 * However, sometimes the bug is only in the code calling VError, and a
85207 * programmer might prefer to have the error message contain "null" or
85208 * "undefined" rather than have the bug in the error path crash the
85209 * program (making the first bug harder to identify). For that reason,
85210 * by default VError converts "null" or "undefined" arguments to their
85211 * string representations and passes those to extsprintf. Programmers
85212 * desiring the strict behavior can use the SError class or pass the
85213 * "strict" option to the VError constructor.
85214 */
85215 mod_assertplus.object(options);
85216 if (!options.strict && !args.strict) {
85217 sprintf_args = sprintf_args.map(function (a) {
85218 return (a === null ? 'null' :
85219 a === undefined ? 'undefined' : a);
85220 });
85221 }
85222
85223 if (sprintf_args.length === 0) {
85224 shortmessage = '';
85225 } else {
85226 shortmessage = sprintf.apply(null, sprintf_args);
85227 }
85228
85229 return ({
85230 'options': options,
85231 'shortmessage': shortmessage
85232 });
85233}
85234
85235/*
85236 * See README.md for reference documentation.
85237 */
85238function VError()
85239{
85240 var args, obj, parsed, cause, ctor, message, k;
85241
85242 args = Array.prototype.slice.call(arguments, 0);
85243
85244 /*
85245 * This is a regrettable pattern, but JavaScript's built-in Error class
85246 * is defined to work this way, so we allow the constructor to be called
85247 * without "new".
85248 */
85249 if (!(this instanceof VError)) {
85250 obj = Object.create(VError.prototype);
85251 VError.apply(obj, arguments);
85252 return (obj);
85253 }
85254
85255 /*
85256 * For convenience and backwards compatibility, we support several
85257 * different calling forms. Normalize them here.
85258 */
85259 parsed = parseConstructorArguments({
85260 'argv': args,
85261 'strict': false
85262 });
85263
85264 /*
85265 * If we've been given a name, apply it now.
85266 */
85267 if (parsed.options.name) {
85268 mod_assertplus.string(parsed.options.name,
85269 'error\'s "name" must be a string');
85270 this.name = parsed.options.name;
85271 }
85272
85273 /*
85274 * For debugging, we keep track of the original short message (attached
85275 * this Error particularly) separately from the complete message (which
85276 * includes the messages of our cause chain).
85277 */
85278 this.jse_shortmsg = parsed.shortmessage;
85279 message = parsed.shortmessage;
85280
85281 /*
85282 * If we've been given a cause, record a reference to it and update our
85283 * message appropriately.
85284 */
85285 cause = parsed.options.cause;
85286 if (cause) {
85287 mod_assertplus.ok(mod_isError(cause), 'cause is not an Error');
85288 this.jse_cause = cause;
85289
85290 if (!parsed.options.skipCauseMessage) {
85291 message += ': ' + cause.message;
85292 }
85293 }
85294
85295 /*
85296 * If we've been given an object with properties, shallow-copy that
85297 * here. We don't want to use a deep copy in case there are non-plain
85298 * objects here, but we don't want to use the original object in case
85299 * the caller modifies it later.
85300 */
85301 this.jse_info = {};
85302 if (parsed.options.info) {
85303 for (k in parsed.options.info) {
85304 this.jse_info[k] = parsed.options.info[k];
85305 }
85306 }
85307
85308 this.message = message;
85309 Error.call(this, message);
85310
85311 if (Error.captureStackTrace) {
85312 ctor = parsed.options.constructorOpt || this.constructor;
85313 Error.captureStackTrace(this, ctor);
85314 }
85315
85316 return (this);
85317}
85318
85319mod_util.inherits(VError, Error);
85320VError.prototype.name = 'VError';
85321
85322VError.prototype.toString = function ve_toString()
85323{
85324 var str = (this.hasOwnProperty('name') && this.name ||
85325 this.constructor.name || this.constructor.prototype.name);
85326 if (this.message)
85327 str += ': ' + this.message;
85328
85329 return (str);
85330};
85331
85332/*
85333 * This method is provided for compatibility. New callers should use
85334 * VError.cause() instead. That method also uses the saner `null` return value
85335 * when there is no cause.
85336 */
85337VError.prototype.cause = function ve_cause()
85338{
85339 var cause = VError.cause(this);
85340 return (cause === null ? undefined : cause);
85341};
85342
85343/*
85344 * Static methods
85345 *
85346 * These class-level methods are provided so that callers can use them on
85347 * instances of Errors that are not VErrors. New interfaces should be provided
85348 * only using static methods to eliminate the class of programming mistake where
85349 * people fail to check whether the Error object has the corresponding methods.
85350 */
85351
85352VError.cause = function (err)
85353{
85354 mod_assertplus.ok(mod_isError(err), 'err must be an Error');
85355 return (mod_isError(err.jse_cause) ? err.jse_cause : null);
85356};
85357
85358VError.info = function (err)
85359{
85360 var rv, cause, k;
85361
85362 mod_assertplus.ok(mod_isError(err), 'err must be an Error');
85363 cause = VError.cause(err);
85364 if (cause !== null) {
85365 rv = VError.info(cause);
85366 } else {
85367 rv = {};
85368 }
85369
85370 if (typeof (err.jse_info) == 'object' && err.jse_info !== null) {
85371 for (k in err.jse_info) {
85372 rv[k] = err.jse_info[k];
85373 }
85374 }
85375
85376 return (rv);
85377};
85378
85379VError.findCauseByName = function (err, name)
85380{
85381 var cause;
85382
85383 mod_assertplus.ok(mod_isError(err), 'err must be an Error');
85384 mod_assertplus.string(name, 'name');
85385 mod_assertplus.ok(name.length > 0, 'name cannot be empty');
85386
85387 for (cause = err; cause !== null; cause = VError.cause(cause)) {
85388 mod_assertplus.ok(mod_isError(cause));
85389 if (cause.name == name) {
85390 return (cause);
85391 }
85392 }
85393
85394 return (null);
85395};
85396
85397VError.hasCauseWithName = function (err, name)
85398{
85399 return (VError.findCauseByName(err, name) !== null);
85400};
85401
85402VError.fullStack = function (err)
85403{
85404 mod_assertplus.ok(mod_isError(err), 'err must be an Error');
85405
85406 var cause = VError.cause(err);
85407
85408 if (cause) {
85409 return (err.stack + '\ncaused by: ' + VError.fullStack(cause));
85410 }
85411
85412 return (err.stack);
85413};
85414
85415VError.errorFromList = function (errors)
85416{
85417 mod_assertplus.arrayOfObject(errors, 'errors');
85418
85419 if (errors.length === 0) {
85420 return (null);
85421 }
85422
85423 errors.forEach(function (e) {
85424 mod_assertplus.ok(mod_isError(e));
85425 });
85426
85427 if (errors.length == 1) {
85428 return (errors[0]);
85429 }
85430
85431 return (new MultiError(errors));
85432};
85433
85434VError.errorForEach = function (err, func)
85435{
85436 mod_assertplus.ok(mod_isError(err), 'err must be an Error');
85437 mod_assertplus.func(func, 'func');
85438
85439 if (err instanceof MultiError) {
85440 err.errors().forEach(function iterError(e) { func(e); });
85441 } else {
85442 func(err);
85443 }
85444};
85445
85446
85447/*
85448 * SError is like VError, but stricter about types. You cannot pass "null" or
85449 * "undefined" as string arguments to the formatter.
85450 */
85451function SError()
85452{
85453 var args, obj, parsed, options;
85454
85455 args = Array.prototype.slice.call(arguments, 0);
85456 if (!(this instanceof SError)) {
85457 obj = Object.create(SError.prototype);
85458 SError.apply(obj, arguments);
85459 return (obj);
85460 }
85461
85462 parsed = parseConstructorArguments({
85463 'argv': args,
85464 'strict': true
85465 });
85466
85467 options = parsed.options;
85468 VError.call(this, options, '%s', parsed.shortmessage);
85469
85470 return (this);
85471}
85472
85473/*
85474 * We don't bother setting SError.prototype.name because once constructed,
85475 * SErrors are just like VErrors.
85476 */
85477mod_util.inherits(SError, VError);
85478
85479
85480/*
85481 * Represents a collection of errors for the purpose of consumers that generally
85482 * only deal with one error. Callers can extract the individual errors
85483 * contained in this object, but may also just treat it as a normal single
85484 * error, in which case a summary message will be printed.
85485 */
85486function MultiError(errors)
85487{
85488 mod_assertplus.array(errors, 'list of errors');
85489 mod_assertplus.ok(errors.length > 0, 'must be at least one error');
85490 this.ase_errors = errors;
85491
85492 VError.call(this, {
85493 'cause': errors[0]
85494 }, 'first of %d error%s', errors.length, errors.length == 1 ? '' : 's');
85495}
85496
85497mod_util.inherits(MultiError, VError);
85498MultiError.prototype.name = 'MultiError';
85499
85500MultiError.prototype.errors = function me_errors()
85501{
85502 return (this.ase_errors.slice(0));
85503};
85504
85505
85506/*
85507 * See README.md for reference details.
85508 */
85509function WError()
85510{
85511 var args, obj, parsed, options;
85512
85513 args = Array.prototype.slice.call(arguments, 0);
85514 if (!(this instanceof WError)) {
85515 obj = Object.create(WError.prototype);
85516 WError.apply(obj, args);
85517 return (obj);
85518 }
85519
85520 parsed = parseConstructorArguments({
85521 'argv': args,
85522 'strict': false
85523 });
85524
85525 options = parsed.options;
85526 options['skipCauseMessage'] = true;
85527 VError.call(this, options, '%s', parsed.shortmessage);
85528
85529 return (this);
85530}
85531
85532mod_util.inherits(WError, VError);
85533WError.prototype.name = 'WError';
85534
85535WError.prototype.toString = function we_toString()
85536{
85537 var str = (this.hasOwnProperty('name') && this.name ||
85538 this.constructor.name || this.constructor.prototype.name);
85539 if (this.message)
85540 str += ': ' + this.message;
85541 if (this.jse_cause && this.jse_cause.message)
85542 str += '; caused by ' + this.jse_cause.toString();
85543
85544 return (str);
85545};
85546
85547/*
85548 * For purely historical reasons, WError's cause() function allows you to set
85549 * the cause.
85550 */
85551WError.prototype.cause = function we_cause(c)
85552{
85553 if (mod_isError(c))
85554 this.jse_cause = c;
85555
85556 return (this.jse_cause);
85557};
85558
85559},{"assert-plus":67,"core-util-is":120,"extsprintf":402,"util":397}],402:[function(require,module,exports){
85560(function (process){
85561/*
85562 * extsprintf.js: extended POSIX-style sprintf
85563 */
85564
85565var mod_assert = require('assert');
85566var mod_util = require('util');
85567
85568/*
85569 * Public interface
85570 */
85571exports.sprintf = jsSprintf;
85572exports.printf = jsPrintf;
85573exports.fprintf = jsFprintf;
85574
85575/*
85576 * Stripped down version of s[n]printf(3c). We make a best effort to throw an
85577 * exception when given a format string we don't understand, rather than
85578 * ignoring it, so that we won't break existing programs if/when we go implement
85579 * the rest of this.
85580 *
85581 * This implementation currently supports specifying
85582 * - field alignment ('-' flag),
85583 * - zero-pad ('0' flag)
85584 * - always show numeric sign ('+' flag),
85585 * - field width
85586 * - conversions for strings, decimal integers, and floats (numbers).
85587 * - argument size specifiers. These are all accepted but ignored, since
85588 * Javascript has no notion of the physical size of an argument.
85589 *
85590 * Everything else is currently unsupported, most notably precision, unsigned
85591 * numbers, non-decimal numbers, and characters.
85592 */
85593function jsSprintf(ofmt)
85594{
85595 var regex = [
85596 '([^%]*)', /* normal text */
85597 '%', /* start of format */
85598 '([\'\\-+ #0]*?)', /* flags (optional) */
85599 '([1-9]\\d*)?', /* width (optional) */
85600 '(\\.([1-9]\\d*))?', /* precision (optional) */
85601 '[lhjztL]*?', /* length mods (ignored) */
85602 '([diouxXfFeEgGaAcCsSp%jr])' /* conversion */
85603 ].join('');
85604
85605 var re = new RegExp(regex);
85606
85607 /* variadic arguments used to fill in conversion specifiers */
85608 var args = Array.prototype.slice.call(arguments, 1);
85609 /* remaining format string */
85610 var fmt = ofmt;
85611
85612 /* components of the current conversion specifier */
85613 var flags, width, precision, conversion;
85614 var left, pad, sign, arg, match;
85615
85616 /* return value */
85617 var ret = '';
85618
85619 /* current variadic argument (1-based) */
85620 var argn = 1;
85621 /* 0-based position in the format string that we've read */
85622 var posn = 0;
85623 /* 1-based position in the format string of the current conversion */
85624 var convposn;
85625 /* current conversion specifier */
85626 var curconv;
85627
85628 mod_assert.equal('string', typeof (fmt),
85629 'first argument must be a format string');
85630
85631 while ((match = re.exec(fmt)) !== null) {
85632 ret += match[1];
85633 fmt = fmt.substring(match[0].length);
85634
85635 /*
85636 * Update flags related to the current conversion specifier's
85637 * position so that we can report clear error messages.
85638 */
85639 curconv = match[0].substring(match[1].length);
85640 convposn = posn + match[1].length + 1;
85641 posn += match[0].length;
85642
85643 flags = match[2] || '';
85644 width = match[3] || 0;
85645 precision = match[4] || '';
85646 conversion = match[6];
85647 left = false;
85648 sign = false;
85649 pad = ' ';
85650
85651 if (conversion == '%') {
85652 ret += '%';
85653 continue;
85654 }
85655
85656 if (args.length === 0) {
85657 throw (jsError(ofmt, convposn, curconv,
85658 'has no matching argument ' +
85659 '(too few arguments passed)'));
85660 }
85661
85662 arg = args.shift();
85663 argn++;
85664
85665 if (flags.match(/[\' #]/)) {
85666 throw (jsError(ofmt, convposn, curconv,
85667 'uses unsupported flags'));
85668 }
85669
85670 if (precision.length > 0) {
85671 throw (jsError(ofmt, convposn, curconv,
85672 'uses non-zero precision (not supported)'));
85673 }
85674
85675 if (flags.match(/-/))
85676 left = true;
85677
85678 if (flags.match(/0/))
85679 pad = '0';
85680
85681 if (flags.match(/\+/))
85682 sign = true;
85683
85684 switch (conversion) {
85685 case 's':
85686 if (arg === undefined || arg === null) {
85687 throw (jsError(ofmt, convposn, curconv,
85688 'attempted to print undefined or null ' +
85689 'as a string (argument ' + argn + ' to ' +
85690 'sprintf)'));
85691 }
85692 ret += doPad(pad, width, left, arg.toString());
85693 break;
85694
85695 case 'd':
85696 arg = Math.floor(arg);
85697 /*jsl:fallthru*/
85698 case 'f':
85699 sign = sign && arg > 0 ? '+' : '';
85700 ret += sign + doPad(pad, width, left,
85701 arg.toString());
85702 break;
85703
85704 case 'x':
85705 ret += doPad(pad, width, left, arg.toString(16));
85706 break;
85707
85708 case 'j': /* non-standard */
85709 if (width === 0)
85710 width = 10;
85711 ret += mod_util.inspect(arg, false, width);
85712 break;
85713
85714 case 'r': /* non-standard */
85715 ret += dumpException(arg);
85716 break;
85717
85718 default:
85719 throw (jsError(ofmt, convposn, curconv,
85720 'is not supported'));
85721 }
85722 }
85723
85724 ret += fmt;
85725 return (ret);
85726}
85727
85728function jsError(fmtstr, convposn, curconv, reason) {
85729 mod_assert.equal(typeof (fmtstr), 'string');
85730 mod_assert.equal(typeof (curconv), 'string');
85731 mod_assert.equal(typeof (convposn), 'number');
85732 mod_assert.equal(typeof (reason), 'string');
85733 return (new Error('format string "' + fmtstr +
85734 '": conversion specifier "' + curconv + '" at character ' +
85735 convposn + ' ' + reason));
85736}
85737
85738function jsPrintf() {
85739 var args = Array.prototype.slice.call(arguments);
85740 args.unshift(process.stdout);
85741 jsFprintf.apply(null, args);
85742}
85743
85744function jsFprintf(stream) {
85745 var args = Array.prototype.slice.call(arguments, 1);
85746 return (stream.write(jsSprintf.apply(this, args)));
85747}
85748
85749function doPad(chr, width, left, str)
85750{
85751 var ret = str;
85752
85753 while (ret.length < width) {
85754 if (left)
85755 ret += chr;
85756 else
85757 ret = chr + ret;
85758 }
85759
85760 return (ret);
85761}
85762
85763/*
85764 * This function dumps long stack traces for exceptions having a cause() method.
85765 * See node-verror for an example.
85766 */
85767function dumpException(ex)
85768{
85769 var ret;
85770
85771 if (!(ex instanceof Error))
85772 throw (new Error(jsSprintf('invalid type for %%r: %j', ex)));
85773
85774 /* Note that V8 prepends "ex.stack" with ex.toString(). */
85775 ret = 'EXCEPTION: ' + ex.constructor.name + ': ' + ex.stack;
85776
85777 if (ex.cause && typeof (ex.cause) === 'function') {
85778 var cex = ex.cause();
85779 if (cex) {
85780 ret += '\nCaused by: ' + dumpException(cex);
85781 }
85782 }
85783
85784 return (ret);
85785}
85786
85787}).call(this,require('_process'))
85788},{"_process":265,"assert":68,"util":397}],403:[function(require,module,exports){
85789var indexOf = function (xs, item) {
85790 if (xs.indexOf) return xs.indexOf(item);
85791 else for (var i = 0; i < xs.length; i++) {
85792 if (xs[i] === item) return i;
85793 }
85794 return -1;
85795};
85796var Object_keys = function (obj) {
85797 if (Object.keys) return Object.keys(obj)
85798 else {
85799 var res = [];
85800 for (var key in obj) res.push(key)
85801 return res;
85802 }
85803};
85804
85805var forEach = function (xs, fn) {
85806 if (xs.forEach) return xs.forEach(fn)
85807 else for (var i = 0; i < xs.length; i++) {
85808 fn(xs[i], i, xs);
85809 }
85810};
85811
85812var defineProp = (function() {
85813 try {
85814 Object.defineProperty({}, '_', {});
85815 return function(obj, name, value) {
85816 Object.defineProperty(obj, name, {
85817 writable: true,
85818 enumerable: false,
85819 configurable: true,
85820 value: value
85821 })
85822 };
85823 } catch(e) {
85824 return function(obj, name, value) {
85825 obj[name] = value;
85826 };
85827 }
85828}());
85829
85830var globals = ['Array', 'Boolean', 'Date', 'Error', 'EvalError', 'Function',
85831'Infinity', 'JSON', 'Math', 'NaN', 'Number', 'Object', 'RangeError',
85832'ReferenceError', 'RegExp', 'String', 'SyntaxError', 'TypeError', 'URIError',
85833'decodeURI', 'decodeURIComponent', 'encodeURI', 'encodeURIComponent', 'escape',
85834'eval', 'isFinite', 'isNaN', 'parseFloat', 'parseInt', 'undefined', 'unescape'];
85835
85836function Context() {}
85837Context.prototype = {};
85838
85839var Script = exports.Script = function NodeScript (code) {
85840 if (!(this instanceof Script)) return new Script(code);
85841 this.code = code;
85842};
85843
85844Script.prototype.runInContext = function (context) {
85845 if (!(context instanceof Context)) {
85846 throw new TypeError("needs a 'context' argument.");
85847 }
85848
85849 var iframe = document.createElement('iframe');
85850 if (!iframe.style) iframe.style = {};
85851 iframe.style.display = 'none';
85852
85853 document.body.appendChild(iframe);
85854
85855 var win = iframe.contentWindow;
85856 var wEval = win.eval, wExecScript = win.execScript;
85857
85858 if (!wEval && wExecScript) {
85859 // win.eval() magically appears when this is called in IE:
85860 wExecScript.call(win, 'null');
85861 wEval = win.eval;
85862 }
85863
85864 forEach(Object_keys(context), function (key) {
85865 win[key] = context[key];
85866 });
85867 forEach(globals, function (key) {
85868 if (context[key]) {
85869 win[key] = context[key];
85870 }
85871 });
85872
85873 var winKeys = Object_keys(win);
85874
85875 var res = wEval.call(win, this.code);
85876
85877 forEach(Object_keys(win), function (key) {
85878 // Avoid copying circular objects like `top` and `window` by only
85879 // updating existing context properties or new properties in the `win`
85880 // that was only introduced after the eval.
85881 if (key in context || indexOf(winKeys, key) === -1) {
85882 context[key] = win[key];
85883 }
85884 });
85885
85886 forEach(globals, function (key) {
85887 if (!(key in context)) {
85888 defineProp(context, key, win[key]);
85889 }
85890 });
85891
85892 document.body.removeChild(iframe);
85893
85894 return res;
85895};
85896
85897Script.prototype.runInThisContext = function () {
85898 return eval(this.code); // maybe...
85899};
85900
85901Script.prototype.runInNewContext = function (context) {
85902 var ctx = Script.createContext(context);
85903 var res = this.runInContext(ctx);
85904
85905 if (context) {
85906 forEach(Object_keys(ctx), function (key) {
85907 context[key] = ctx[key];
85908 });
85909 }
85910
85911 return res;
85912};
85913
85914forEach(Object_keys(Script.prototype), function (name) {
85915 exports[name] = Script[name] = function (code) {
85916 var s = Script(code);
85917 return s[name].apply(s, [].slice.call(arguments, 1));
85918 };
85919});
85920
85921exports.isContext = function (context) {
85922 return context instanceof Context;
85923};
85924
85925exports.createScript = function (code) {
85926 return exports.Script(code);
85927};
85928
85929exports.createContext = Script.createContext = function (context) {
85930 var copy = new Context();
85931 if(typeof context === 'object') {
85932 forEach(Object_keys(context), function (key) {
85933 copy[key] = context[key];
85934 });
85935 }
85936 return copy;
85937};
85938
85939},{}],404:[function(require,module,exports){
85940/*jshint strict:true node:true es5:true onevar:true laxcomma:true laxbreak:true*/
85941(function () {
85942 "use strict";
85943
85944 // "FIFO" isn't easy to convert to camelCase and back reliably
85945 var isFnodeTypes = [
85946 "isFile", "isDirectory", "isSymbolicLink", "isBlockDevice", "isCharacterDevice", "isFIFO", "isSocket"
85947 ],
85948 fnodeTypes = [
85949 "file", "directory", "symbolicLink", "blockDevice", "characterDevice", "FIFO", "socket"
85950 ],
85951 fnodeTypesPlural = [
85952 "files", "directories", "symbolicLinks", "blockDevices", "characterDevices", "FIFOs", "sockets"
85953 ];
85954
85955
85956 //
85957 function createNodeGroups() {
85958 var nodeGroups = {};
85959 fnodeTypesPlural.concat("nodes", "errors").forEach(function (fnodeTypePlural) {
85960 nodeGroups[fnodeTypePlural] = [];
85961 });
85962 return nodeGroups;
85963 }
85964
85965
85966 // Determine each file node's type
85967 //
85968 function sortFnodesByType(stat, fnodes) {
85969 var i, isType;
85970
85971 for (i = 0; i < isFnodeTypes.length; i += 1) {
85972 isType = isFnodeTypes[i];
85973 if (stat[isType]()) {
85974 stat.type = fnodeTypes[i];
85975 fnodes[fnodeTypesPlural[i]].push(stat);
85976 return;
85977 }
85978 }
85979 }
85980
85981
85982 // Get the current number of listeners (which may change)
85983 // Emit events to each listener
85984 // Wait for all listeners to `next()` before continueing
85985 // (in theory this may avoid disk thrashing)
85986 function emitSingleEvents(emitter, path, stats, next, self) {
85987 var num = 1 + emitter.listeners(stats.type).length + emitter.listeners("node").length;
85988
85989 function nextWhenReady(flag) {
85990 if (flag) {
85991 stats.flag = flag;
85992 }
85993 num -= 1;
85994 if (0 === num) { next.call(self); }
85995 }
85996
85997 emitter.emit(stats.type, path, stats, nextWhenReady);
85998 emitter.emit("node", path, stats, nextWhenReady);
85999 nextWhenReady();
86000 }
86001
86002
86003 // Since the risk for disk thrashing among anything
86004 // other than files is relatively low, all types are
86005 // emitted at once, but all must complete before advancing
86006 function emitPluralEvents(emitter, path, nodes, next, self) {
86007 var num = 1;
86008
86009 function nextWhenReady() {
86010 num -= 1;
86011 if (0 === num) { next.call(self); }
86012 }
86013
86014 fnodeTypesPlural.concat(["nodes", "errors"]).forEach(function (fnodeType) {
86015 if (0 === nodes[fnodeType].length) { return; }
86016 num += emitter.listeners(fnodeType).length;
86017 emitter.emit(fnodeType, path, nodes[fnodeType], nextWhenReady);
86018 });
86019 nextWhenReady();
86020 }
86021
86022 module.exports = {
86023 emitNodeType: emitSingleEvents,
86024 emitNodeTypeGroups: emitPluralEvents,
86025 isFnodeTypes: isFnodeTypes,
86026 fnodeTypes: fnodeTypes,
86027 fnodeTypesPlural: fnodeTypesPlural,
86028 sortFnodesByType: sortFnodesByType,
86029 createNodeGroups: createNodeGroups
86030 };
86031}());
86032
86033},{}],405:[function(require,module,exports){
86034// Adapted from work by jorge@jorgechamorro.com on 2010-11-25
86035(function () {
86036 "use strict";
86037
86038 function noop() {}
86039
86040 var fs = require('fs')
86041 , forEachAsync = require('foreachasync').forEachAsync
86042 , EventEmitter = require('events').EventEmitter
86043 , TypeEmitter = require('./node-type-emitter')
86044 , util = require('util')
86045 , path = require('path')
86046 ;
86047
86048 function appendToDirs(stat) {
86049 /*jshint validthis:true*/
86050 if(stat.flag && stat.flag === NO_DESCEND) { return; }
86051 this.push(stat.name);
86052 }
86053
86054 function wFilesHandlerWrapper(items) {
86055 /*jshint validthis:true*/
86056 this._wFilesHandler(noop, items);
86057 }
86058
86059 function Walker(pathname, options, sync) {
86060 EventEmitter.call(this);
86061
86062 var me = this
86063 ;
86064
86065 options = options || {};
86066 me._wStat = options.followLinks && 'stat' || 'lstat';
86067 me._wStatSync = me._wStat + 'Sync';
86068 me._wsync = sync;
86069 me._wq = [];
86070 me._wqueue = [me._wq];
86071 me._wcurpath = undefined;
86072 me._wfilters = options.filters || [];
86073 me._wfirstrun = true;
86074 me._wcurpath = pathname;
86075
86076 if (me._wsync) {
86077 //console.log('_walkSync');
86078 me._wWalk = me._wWalkSync;
86079 } else {
86080 //console.log('_walkASync');
86081 me._wWalk = me._wWalkAsync;
86082 }
86083
86084 options.listeners = options.listeners || {};
86085 Object.keys(options.listeners).forEach(function (event) {
86086 var callbacks = options.listeners[event]
86087 ;
86088
86089 if ('function' === typeof callbacks) {
86090 callbacks = [callbacks];
86091 }
86092
86093 callbacks.forEach(function (callback) {
86094 me.on(event, callback);
86095 });
86096 });
86097
86098 me._wWalk();
86099 }
86100
86101 // Inherits must come before prototype additions
86102 util.inherits(Walker, EventEmitter);
86103
86104 Walker.prototype._wLstatHandler = function (err, stat) {
86105 var me = this
86106 ;
86107
86108 stat = stat || {};
86109 stat.name = me._wcurfile;
86110
86111 if (err) {
86112 stat.error = err;
86113 //me.emit('error', curpath, stat);
86114 // TODO v3.0 (don't noop the next if there are listeners)
86115 me.emit('nodeError', me._wcurpath, stat, noop);
86116 me._wfnodegroups.errors.push(stat);
86117 me._wCurFileCallback();
86118 } else {
86119 TypeEmitter.sortFnodesByType(stat, me._wfnodegroups);
86120 // NOTE: wCurFileCallback doesn't need thisness, so this is okay
86121 TypeEmitter.emitNodeType(me, me._wcurpath, stat, me._wCurFileCallback, me);
86122 }
86123 };
86124 Walker.prototype._wFilesHandler = function (cont, file) {
86125 var statPath
86126 , me = this
86127 ;
86128
86129
86130 me._wcurfile = file;
86131 me._wCurFileCallback = cont;
86132 me.emit('name', me._wcurpath, file, noop);
86133
86134 statPath = me._wcurpath + path.sep + file;
86135
86136 if (!me._wsync) {
86137 // TODO how to remove this anony?
86138 fs[me._wStat](statPath, function (err, stat) {
86139 me._wLstatHandler(err, stat);
86140 });
86141 return;
86142 }
86143
86144 try {
86145 me._wLstatHandler(null, fs[me._wStatSync](statPath));
86146 } catch(e) {
86147 me._wLstatHandler(e);
86148 }
86149 };
86150 Walker.prototype._wOnEmitDone = function () {
86151 var me = this
86152 , dirs = []
86153 ;
86154
86155 me._wfnodegroups.directories.forEach(appendToDirs, dirs);
86156 dirs.forEach(me._wJoinPath, me);
86157 me._wqueue.push(me._wq = dirs);
86158 me._wNext();
86159 };
86160 Walker.prototype._wPostFilesHandler = function () {
86161 var me = this
86162 ;
86163
86164 if (me._wfnodegroups.errors.length) {
86165 // TODO v3.0 (don't noop the next)
86166 // .errors is an array of stats with { name: name, error: error }
86167 me.emit('errors', me._wcurpath, me._wfnodegroups.errors, noop);
86168 }
86169 // XXX emitNodeTypes still needs refactor
86170 TypeEmitter.emitNodeTypeGroups(me, me._wcurpath, me._wfnodegroups, me._wOnEmitDone, me);
86171 };
86172 Walker.prototype._wReadFiles = function () {
86173 var me = this
86174 ;
86175
86176 if (!me._wcurfiles || 0 === me._wcurfiles.length) {
86177 return me._wNext();
86178 }
86179
86180 // TODO could allow user to selectively stat
86181 // and don't stat if there are no stat listeners
86182 me.emit('names', me._wcurpath, me._wcurfiles, noop);
86183
86184 if (me._wsync) {
86185 me._wcurfiles.forEach(wFilesHandlerWrapper, me);
86186 me._wPostFilesHandler();
86187 } else {
86188 forEachAsync(me._wcurfiles, me._wFilesHandler, me).then(me._wPostFilesHandler);
86189 }
86190 };
86191 Walker.prototype._wReaddirHandler = function (err, files) {
86192 var fnodeGroups = TypeEmitter.createNodeGroups()
86193 , me = this
86194 , parent
86195 , child
86196 ;
86197
86198 me._wfnodegroups = fnodeGroups;
86199 me._wcurfiles = files;
86200
86201 // no error, great
86202 if (!err) {
86203 me._wReadFiles();
86204 return;
86205 }
86206
86207 // TODO path.sep
86208 me._wcurpath = me._wcurpath.replace(/\/$/, '');
86209
86210 // error? not first run? => directory error
86211 if (!me._wfirstrun) {
86212 // TODO v3.0 (don't noop the next if there are listeners)
86213 me.emit('directoryError', me._wcurpath, { error: err }, noop);
86214 // TODO v3.0
86215 //me.emit('directoryError', me._wcurpath.replace(/^(.*)\/.*$/, '$1'), { name: me._wcurpath.replace(/^.*\/(.*)/, '$1'), error: err }, noop);
86216 me._wReadFiles();
86217 return;
86218 }
86219
86220 // error? first run? => maybe a file, maybe a true error
86221 me._wfirstrun = false;
86222
86223 // readdir failed (might be a file), try a stat on the parent
86224 parent = me._wcurpath.replace(/^(.*)\/.*$/, '$1');
86225 fs[me._wStat](parent, function (e, stat) {
86226
86227 if (stat) {
86228 // success
86229 // now try stat on this as a child of the parent directory
86230 child = me._wcurpath.replace(/^.*\/(.*)$/, '$1');
86231 me._wcurfiles = [child];
86232 me._wcurpath = parent;
86233 } else {
86234 // TODO v3.0
86235 //me.emit('directoryError', me._wcurpath.replace(/^(.*)\/.*$/, '$1'), { name: me._wcurpath.replace(/^.*\/(.*)/, '$1'), error: err }, noop);
86236 // TODO v3.0 (don't noop the next)
86237 // the original readdir error, not the parent stat error
86238 me.emit('nodeError', me._wcurpath, { error: err }, noop);
86239 }
86240
86241 me._wReadFiles();
86242 });
86243 };
86244 Walker.prototype._wFilter = function () {
86245 var me = this
86246 , exclude
86247 ;
86248
86249 // Stop directories that contain filter keywords
86250 // from continuing through the walk process
86251 exclude = me._wfilters.some(function (filter) {
86252 if (me._wcurpath.match(filter)) {
86253 return true;
86254 }
86255 });
86256
86257 return exclude;
86258 };
86259 Walker.prototype._wWalkSync = function () {
86260 //console.log('walkSync');
86261 var err
86262 , files
86263 , me = this
86264 ;
86265
86266 try {
86267 files = fs.readdirSync(me._wcurpath);
86268 } catch(e) {
86269 err = e;
86270 }
86271
86272 me._wReaddirHandler(err, files);
86273 };
86274 Walker.prototype._wWalkAsync = function () {
86275 //console.log('walkAsync');
86276 var me = this
86277 ;
86278
86279 // TODO how to remove this anony?
86280 fs.readdir(me._wcurpath, function (err, files) {
86281 me._wReaddirHandler(err, files);
86282 });
86283 };
86284 Walker.prototype._wNext = function () {
86285 var me = this
86286 ;
86287
86288 if (me._paused) {
86289 return;
86290 }
86291 if (me._wq.length) {
86292 me._wcurpath = me._wq.pop();
86293 while (me._wq.length && me._wFilter()) {
86294 me._wcurpath = me._wq.pop();
86295 }
86296 if (me._wcurpath && !me._wFilter()) {
86297 me._wWalk();
86298 } else {
86299 me._wNext();
86300 }
86301 return;
86302 }
86303 me._wqueue.length -= 1;
86304 if (me._wqueue.length) {
86305 me._wq = me._wqueue[me._wqueue.length - 1];
86306 return me._wNext();
86307 }
86308
86309 // To not break compatibility
86310 //process.nextTick(function () {
86311 me.emit('end');
86312 //});
86313 };
86314 Walker.prototype._wJoinPath = function (v, i, o) {
86315 var me = this
86316 ;
86317
86318 o[i] = [me._wcurpath, path.sep, v].join('');
86319 };
86320 Walker.prototype.pause = function () {
86321 this._paused = true;
86322 };
86323 Walker.prototype.resume = function () {
86324 this._paused = false;
86325 this._wNext();
86326 };
86327
86328 exports.walk = function (path, opts) {
86329 return new Walker(path, opts, false);
86330 };
86331
86332 exports.walkSync = function (path, opts) {
86333 return new Walker(path, opts, true);
86334 };
86335}());
86336
86337},{"./node-type-emitter":404,"events":159,"foreachasync":165,"fs":112,"path":257,"util":397}],406:[function(require,module,exports){
86338module.exports = extend
86339
86340var hasOwnProperty = Object.prototype.hasOwnProperty;
86341
86342function extend() {
86343 var target = {}
86344
86345 for (var i = 0; i < arguments.length; i++) {
86346 var source = arguments[i]
86347
86348 for (var key in source) {
86349 if (hasOwnProperty.call(source, key)) {
86350 target[key] = source[key]
86351 }
86352 }
86353 }
86354
86355 return target
86356}
86357
86358},{}],407:[function(require,module,exports){
86359module.exports={
86360 "name": "percy-client",
86361 "version": "3.2.2",
86362 "description": "JavaScript API client library for Percy (https://percy.io).",
86363 "main": "dist/main.js",
86364 "scripts": {
86365 "build": "npm run build:compile && npm run build:browserify",
86366 "build:browserify": "browserify --standalone percy-client dist/main.js -o dist/bundle.js",
86367 "build:compile": "babel src --presets babel-preset-es2015 --out-dir dist",
86368 "debug": "mocha debug --require babel-core/register",
86369 "lint": "./node_modules/eslint/bin/eslint.js .",
86370 "lint:fix": "./node_modules/eslint/bin/eslint.js . --fix",
86371 "prepublish": "npm run build",
86372 "tdd": "mocha --require babel-core/register --watch",
86373 "test": "mocha --require babel-core/register"
86374 },
86375 "lint-staged": {
86376 "*.{js,css}": [
86377 "./node_modules/eslint/bin/eslint.js --fix --color",
86378 "git add"
86379 ]
86380 },
86381 "files": [
86382 "dist/"
86383 ],
86384 "repository": {
86385 "type": "git",
86386 "url": "https://github.com/percy/percy-js.git"
86387 },
86388 "author": "Perceptual Inc.",
86389 "license": "MIT",
86390 "bugs": {
86391 "url": "https://github.com/percy/percy-js/issues"
86392 },
86393 "homepage": "https://github.com/percy/percy-js",
86394 "devDependencies": {
86395 "babel-cli": "^6.26.0",
86396 "babel-core": "^6.26.0",
86397 "babel-plugin-transform-object-assign": "^6.22.0",
86398 "babel-preset-es2015": "^6.3.13",
86399 "browserify": "^16.2.3",
86400 "eslint": "^6.0.0",
86401 "eslint-config-prettier": "^6.0.0",
86402 "eslint-plugin-prettier": "^3.0.1",
86403 "husky": "^3.0.1",
86404 "lint-staged": "^9.1.0",
86405 "mocha": "^6.0.0",
86406 "nock": "^10.0.6",
86407 "prettier": "^1.12.1",
86408 "sinon": "^7.2.3"
86409 },
86410 "dependencies": {
86411 "base64-js": "^1.2.3",
86412 "bluebird": "^3.5.1",
86413 "bluebird-retry": "^0.11.0",
86414 "dotenv": "^8.1.0",
86415 "es6-promise-pool": "^2.5.0",
86416 "jssha": "^2.1.0",
86417 "regenerator-runtime": "^0.13.1",
86418 "request": "^2.87.0",
86419 "request-promise": "^4.2.2",
86420 "walk": "^2.3.14"
86421 },
86422 "husky": {
86423 "hooks": {
86424 "pre-commit": "lint-staged"
86425 }
86426 }
86427}
86428
86429},{}]},{},[2])(2)
86430});